Question
This code is in Python, itis part of a TSP problem is for checking that in order to pick two cities for proposing a new
This code is in Python, itis part of a TSP problem is for checking that in order to pick two cities for proposing a new move (improvement with simulated annealing) it is better to use move1 instead of move2 because the first gives couples from a uniform distribution while the second does not.
I don't understand what the function destructure (in bold) does. Please explain it to me.
import numpy as np import matplotlib.pyplot as plt
def move1(n): while True: i = np.random.randint(n) j = np.random.randint(n) if i > j: i, j = j, i break return i,j
def move2(n, sample_size=10**2): for i in range(sample_size): i = np.random.randint(n-1) j = np.random.randint(i+1, n) return i,j
def destructure(moves): mi = [x[0] for x in moves] mj = [x[1] for x in moves] return mi, mj
def test_moves(n=10, sample_size=10**2): t1 = [move1(n) for k in range(sample_size)] t2 = [move2(n) for k in range(sample_size)]
t1i, t1j = destructure(t1) t2i, t2j = destructure(t2) # plot the i's plt.clf() # note: clf() is better than cla() since we're using subplots # at the end (see below). plt.title("historgram of the i values") plt.hist(t1i, bins=n-1, histtype='step', label='move1') plt.hist(t2i, bins=n-1, histtype='step', label='move2') plt.legend(loc='upper right') plt.pause(2) # # plot the j's # plt.clf() # plt.title("historgram of the j values") # plt.hist(t1j, bins=n-1, histtype='step', label='move1') # plt.hist(t2j, bins=n-1, histtype='step', label='move2') # plt.legend(loc='upper left') # plt.pause(2) # # # 2-d plots, first move1 then move2 # plt.clf() # plt.title("move1 histogram") # plt.hist2d(t1i, t1j, bins=(n-1, n-1)) # plt.pause(2) # plt.title("move2 histogram") # plt.hist2d(t2i, t2j, bins=(n-1, n-1)) # plt.pause(2) # same as above, both plots at once plt.clf() plt.subplot(211) plt.title("move1 vs move 2 histogram") plt.hist2d(t1i, t1j, bins=(n-1, n-1)) plt.subplot(212) plt.hist2d(t2i, t2j, bins=(n-1, n-1)) plt.pause(2)
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started