Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Your task: You are asked to write a function that applies Simulated Annealing to a Traveling Salesman Problem. That is, your function will run simulated

Your task: You are asked to write a function that applies Simulated Annealing to a Traveling Salesman Problem. That is, your function will run simulated annealing as discussed in class and report best solution (i.e. best route). You can use ”generate sol” and ”calculate objective” 1 functions written in class (these functions are already copied into the template). Your function will accept 6 parameters:

Function Parameters:

coords: A two-dimensional numpy array that includes the x and y coordinates for the cities. Each row corresponds to a city. Name of the cities will be given according to their row number in this parameter. You can assume that this input is always in two dimensions and non-empty. Example input shape:

array ([[6,19],

[14,10],

[7,6],

[18,10],

[10,3],

[7,2],

[1,11],

[5,1],

[0,11],

[11,16]])

num iter: Number of iterations for simulated annealing. For example, in class we run our greedy code with 1000 iterations hard coded. In your function, this is controlled by a parameter. You can assume that this input is integer (i.e. no type checking necessary)

best obj: An optional boolean parameter indicating whether or not the objective value needs to be returned. By default it is set to False. If set true, both best route and best objective should be returned as a tuple.

initial temp: An optional parameter to set the initial temperature (energy level). Default value is 100.

cooling rate: An optional parameter for the cooling rate (energy level). Default value is 0.99.

random seed: Seed that is going to fed to numpy’s random module. You don’t need to do anything about this parameter. Template includes all necessary code snippets that deals with this parameter. Please use only numpy’s random module in applying randomization.

Output: Your function should return a numpy array containing the best route. Each city should be represented by their row index, just like we did in class. No need to repeat the first element to close the loop. An example solution looks like:

Array ([1,5,4,8,0,7,6,3,2,9])

If best obj parameter is set to true, your function should also return the best objective value.

Example inputs and expected outputs:

import assignment3 as tpl

import numpy as np

N = 10

np . random . seed ( 4 2 )

coords = np . random . randint ( 0 , 2 0 , (N, 2 ) )

route= tpl . tsp_simulated_annealing( coords )

print ( route )

#Expected output : [ 2 , 1 , 3 , 9 , 0 , 6 , 8 , 7 , 5 , 4 ] <= Note that this i s a numpy array

route = tpl . tsp_ simulatedannealing ( coords , best_obj=True )

print ( route )

#Expected output : ( array ( [ 2 , 1 , 3 , 9 , 0 , 6 , 8 , 7 , 5 , 4 ] ) , 58 .36806144477974)

route = tpl.tsp.simulatedannealing(coords , initialtemp = 500 , coolingrate = 0.8 , best-obj=True )

print ( r o u t e )

#Expected output : ( array ( [ 9 , 3 , 1 , 4 , 5 , 7 , 2 , 6 , 8 , 0 ] ) , 56 .706514221146065)

TERMİNATE
"""
import numpy as np

def getName():
#TODO: Add your full name instead of Lionel Messi
return "Lionel Messi"

def getStudentID():
#TODO: Replace X's with your student ID. It should stay as a string and should have exactly 9 digits in it.
return "012345678"

def generate_sol(current_sol,num_cities):
current_sol_copy = current_sol.copy()
idx1 ,idx2 = np.random.choice(num_cities, 2)
current_sol_copy[idx2] , current_sol_copy[idx1] = current_sol_copy[idx1] , current_sol_copy[idx2]
return current_sol_copy

def calculate_objective(coord, solution):
a1 = coord[solution,:]
altered_sol = np.append(solution[1:] , solution[0])
a2 = coord[altered_sol,:]
return np.sum(np.sqrt(np.sum((a1-a2)**2, axis=1)))

def tsp_simulated_annealing(coords, num_iter = 1000, best_obj=False, initial_temp = 100, cooling_rate = 0.99, random_seed = 42):
np.random.seed(random_seed) # please do not change this line and do not assign a seed again.

#TODO 1: Infer number of cities from the coords
N =

#Initial starting solution. Please do not change
x_old = np.random.permutation(N)

#TODO 2: Implement reminder of simulated annealing logic
return

TEST

""
# To test your code:
# 1. put this test file and your your python code in the same directory
# 2. replace assignment1 in the import statement with the name of your code file


import unittest
import numpy as np
import assignment3 as asm #replace assignment1 with the name of your .py file if you change the name

class TestAssignment(unittest.TestCase):
coords = np.array([[ 6, 19],
[14 ,10],
[ 7, 6],
[18, 10],
[10, 3],
[ 7, 2],
[ 1, 11],
[ 5, 1],
[ 0, 11],
[11, 16]])
output1 = [2, 1, 3, 9, 0, 6, 8, 7, 5, 4]
output2 = [9, 3, 1, 4, 5, 7, 2, 6, 8, 0]
obj1 = 58.36806144477974
obj2 = 56.706514221146065

def test_get_name(self):
name = asm.getName()
self.assertNotEqual(name, "Lionel Messi", "Please enter your name correctly in getName function")

def test_student_ID(self):
studentID = asm.getStudentID()
self.assertNotEqual(studentID, "XXXXXXXXX", "Please enter your student ID correctly in getStudentID function")
self.assertEqual(len(studentID), 9, "Make sure your student ID is 9 digits!")

def test_output_type(self):
result = asm.tsp_simulated_annealing(self.coords)
self.assertIsInstance(result, np.ndarray, "The output must be numpy array if best_obj =False")

result = asm.tsp_simulated_annealing(self.coords, best_obj=True)
self.assertIsInstance(result, tuple, "The output must be tuple if best_obj =True")


def test_correct_result(self):
result = asm.tsp_simulated_annealing(self.coords, best_obj=True)
print("Your output: ", result)
print("Expected output: ", (self.output1, self.obj1))

self.assertListEqual(result[0].tolist(), self.output1, "Generated path does not match the expected.")

self.assertAlmostEqual(self.obj1, result[1], "Objective Values do not match")


result2 = asm.tsp_simulated_annealing(self.coords, initial_temp = 500, cooling_rate = 0.8, best_obj=True)
print("Your output: ", result2)
print("Expected output: ", (self.output2, self.obj2))

self.assertListEqual(result2[0].tolist(), self.output2, "Generated path does not match the expected.")

self.assertAlmostEqual(self.obj2, result2[1], "Objective Values do not match")

if _name_ == '_main_':
unittest.main()

CAN YOU PLEASE DO THIS IN PYTHON

Step by Step Solution

3.47 Rating (177 Votes )

There are 3 Steps involved in it

Step: 1

Input initial temperature T0 minimum temperature T... blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Introduction to Operations Research

Authors: Frederick S. Hillier, Gerald J. Lieberman

10th edition

978-0072535105, 72535105, 978-1259162985

More Books

Students also viewed these Accounting questions

Question

1. Critically discuss treatment approaches for violent offenders.

Answered: 1 week ago