Question
Please explain the code below and write its pseudocode. Thank you import random, sys, math import numpy as np def Rand_Nodes(size): return random.randint(1, size-1) def
Please explain the code below and write its pseudocode. Thank you
import random, sys, math
import numpy as np
def Rand_Nodes(size):
return random.randint(1, size-1)
def Is_New(Gene, node):
for c in Gene:
if c == node:
return False
return True
def Find_Fitness(Gene, nodes): #find lowest value of the objective function
fitness = 0
for i in range(0, len(Gene)-1):
if nodes[Gene[i]][Gene[i+1]] == 0:
return sys.maxsize
else:
fitness += nodes[Gene[i]][Gene[i+1]]
return fitness
def Create_Gene(size):
Gene = [0]
for i in range(size-1):
while True:
new_node = Rand_Nodes(size)
if Is_New(Gene, new_node):
Gene += [new_node]
break
Gene += [0]
return Gene
def Give_2_rand_number(size):
while True:
change1 = Rand_Nodes(size)
change2 = Rand_Nodes(size)
if change1 != change2:
break
if change1 > change2:
temp = change1
change1 = change2
change2 = temp
return change1, change2
def neighbor(Gene):
change1, change2 = Give_2_rand_number(len(Gene)-1)
for i in range((change2 - change1 + 1)//2):
temp = Gene[change1+i]
Gene[change1+i] = Gene[change2-i]
Gene[change2-i] = temp
return Gene
def Energy(Gene, nodes):
return Find_Fitness(Gene, nodes)
def Probability(En, E, T):
if En < E:
return 1
else:
return math.exp(((-1)*(abs(E-En)/T)))
def SA(iteration, nodes):
n = len(nodes)
s = Create_Gene(n)
for i in range(iteration):
temperature = iteration/(i+1)
s_new = neighbor(s[:])
if Probability(Energy(s_new, nodes), Energy(s, nodes), temperature) > random.uniform(0,1):
s = s_new
print(Energy(s, nodes))
print(s)
nodes = []
File_data = np.loadtxt("gr17_d.txt", dtype=int)
#print(File_data) - testing if it actually reads the text file
for each in File_data:
nodes.append(each)
iteration = 10000
SA(iteration, nodes)
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