def dijk_2_idx(self, rs, column, floor, input, output, idx): io = input + output if idx == 0: a1, b1, c1, d1, e1 = self.dijk_ssr1r2(rs, column, floor, output) a2, b2, c2, d2, e2 = self.dijk_ssr2r1(rs, column, floor, output) if c1 <= c2: io = [io[0], io[1], io[2], io[3]] sol = solution.solution(d1, io, e1) cycletime = c1 else: io = [io[0], io[1], io[3], io[2]] sol = solution.solution(d2, io, e2) cycletime = c2 elif idx == 1: a3, b3, c3, d3, e3 = self.dijk_sr1sr2(rs, column, floor, output) a4, b4, c4, d4, e4 = self.dijk_sr2sr1(rs, column, floor, output) if c3 <= c4: io = [io[0], io[2], io[1], io[3]] sol = solution.solution(d3, io, e3) cycletime = c3 else: io = [io[0], io[3], io[1], io[2]] sol = solution.solution(d4, io, e4) cycletime = c4 return sol, cycletime
def dijk_2(self, rs, column, floor, input, output): # concatenate 4 solutions // input/output example : [51,1] = 1 cycle outputs a1, b1, c1, d1, e1 = self.dijk_ssr1r2(rs, column, floor, output) a2, b2, c2, d2, e2 = self.dijk_ssr2r1(rs, column, floor, output) a3, b3, c3, d3, e3 = self.dijk_sr1sr2(rs, column, floor, output) a4, b4, c4, d4, e4 = self.dijk_sr2sr1(rs, column, floor, output) io = input + output if min(c1, c2, c3, c4) == c1: io = [io[0], io[1], io[2], io[3]] sol = solution.solution(d1, io, e1) cycletime = c1 return sol, cycletime elif min(c1, c2, c3, c4) == c2: io = [io[0], io[1], io[3], io[2]] sol = solution.solution(d2, io, e2) cycletime = c2 return sol, cycletime elif min(c1, c2, c3, c4) == c3: io = [io[0], io[2], io[1], io[3]] sol = solution.solution(d3, io, e3) cycletime = c3 return sol, cycletime elif min(c1, c2, c3, c4) == c4: io = [io[0], io[3], io[1], io[2]] sol = solution.solution(d4, io, e4) cycletime = c4 return sol, cycletime
def evaluate(self,sets): """ This function evaluates the node and returns the resulting set\ """ if self.settings.curOp>=self.settings.maxOp: return[] rDown = None if self.down[0]: rDown = self.down[0].evaluate(sets) else: raise "Node addSet has no right child" self.settings.curOp+=self.num ret = [] if not rDown: return [] for i in xrange(self.num): x = solution.solution(self.settings) for j in xrange(len(x.bits)): x.bits[j] = random.choice(rDown).bits[j] ret.append(x) return ret
def diagonal(pop,n): """ This is an implementation of diagonal recombination """ if not pop: return [] childs = [solution.solution(p.settings) for p in pop] pnts = [random.randint(1,pop[0].settings.solSet['length']-1) for i in xrange(n)] pnts.sort() pnts.append(pop[0].settings.solSet['length']) for c in childs: last = 0 nex = pnts[0] for i in xrange(1,len(pnts)+1): if i!=len(pnts): c.bits[last:nex] = pop[i%len(pop)].bits[last:nex] last = nex nex = pnts[i] else: c.bits[last:] = pop[i%len(pop)].bits[last:] d = pop[0] pop = pop[1:] pop.append(d) return childs
def timeAgent(boardSize, mutationRate, populationSize): start = time.time() #run the agent until the correct answer is found while 1: answer = agent.geneticAlgorithmAgent(boardSize, mutationRate, populationSize, True) if solution(answer) == 0: finish = time.time() return finish - start
def BAT(objf, lb, ub, dim, N, Max_iteration, k, points, metric): n = N # Population size #lb=-50 #ub=50 N_gen = Max_iteration # Number of generations A = 0.5 # Loudness (constant or decreasing) r = 0.5 # Pulse rate (constant or decreasing) Qmin = 0 # Frequency minimum Qmax = 2 # Frequency maximum d = dim # Number of dimensions # Initializing arrays Q = numpy.zeros(n) # Frequency v = numpy.zeros((n, d)) # Velocities Convergence_curve = [] # Initialize the population/solutions Sol = numpy.random.rand(n, d) * (ub - lb) + lb labelsPred = numpy.zeros((n, len(points))) Fitness = numpy.zeros(n) S = numpy.zeros((n, d)) S = numpy.copy(Sol) # initialize solution for the final results s = solution() print("BAT is optimizing \"" + objf.__name__ + "\"") # Initialize timer for the experiment timerStart = time.time() s.startTime = time.strftime("%Y-%m-%d-%H-%M-%S") #Evaluate initial random solutions for i in range(0, n): startpts = numpy.reshape(Sol[i, :], (k, (int)(dim / k))) if objf.__name__ == 'SSE' or objf.__name__ == 'SC' or objf.__name__ == 'DI': fitnessValue, labelsPredValues = objf(startpts, points, k, metric) else: fitnessValue, labelsPredValues = objf(startpts, points, k) Fitness[i] = fitnessValue labelsPred[i, :] = labelsPredValues # Find the initial best solution fmin = min(Fitness) I = numpy.argmin(Fitness) best = Sol[I, :] bestLabelsPred = labelsPred[I, :] # Main loop for t in range(0, N_gen): # Loop over all bats(solutions) for i in range(0, n): Q[i] = Qmin + (Qmin - Qmax) * random.random() v[i, :] = v[i, :] + (Sol[i, :] - best) * Q[i] S[i, :] = Sol[i, :] + v[i, :] # Check boundaries Sol = numpy.clip(Sol, lb, ub) # Pulse rate if random.random() > r: S[i, :] = best + 0.001 * numpy.random.randn(d) # Evaluate new solutions startpts = numpy.reshape(S[i, :], (k, (int)(dim / k))) if objf.__name__ == 'SSE' or objf.__name__ == 'SC' or objf.__name__ == 'DI': fitnessValue, labelsPredValues = objf(startpts, points, k, metric) else: fitnessValue, labelsPredValues = objf(startpts, points, k) Fnew = fitnessValue LabelsPrednew = labelsPredValues # Update if the solution improves if ((Fnew != numpy.inf) and (Fnew <= Fitness[i]) and (random.random() < A)): Sol[i, :] = numpy.copy(S[i, :]) Fitness[i] = Fnew labelsPred[i, :] = LabelsPrednew # Update the current best solution if Fnew != numpy.inf and Fnew <= fmin: best = numpy.copy(S[i, :]) fmin = Fnew bestLabelsPred = LabelsPrednew #update convergence curve Convergence_curve.append(fmin) if (t % 1 == 0): print([ 'At iteration ' + str(t) + ' the best fitness is ' + str(fmin) ]) timerEnd = time.time() s.endTime = time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime = timerEnd - timerStart s.convergence = Convergence_curve s.optimizer = "BAT" s.objfname = objf.__name__ s.labelsPred = numpy.array(bestLabelsPred, dtype=numpy.int64) s.bestIndividual = best return s
def geneticAlgorithmAgent(boardSize, mutationRate, populationSize, silent=False): #generate the population of state nodes import random generation = list() for i in range(populationSize): newState = array.array('i') for x in range(boardSize): newState.append(random.randint(0, boardSize-1)) generation.append(newState) iteration = 1 totalFitness = 01 newTotalFitness = 01 n = 0 #max fitness is n(n-1)/2 (comment is diff from code for efficiency) maxFitness = (boardSize*(boardSize-1)) #termination percentage is 1 - 1/(maxFitness) * 2 terminationPercentage = 1.0 - 1.0/maxFitness #print desired fitness for solution if not silent: print 'Score of {0} required for solution'.format(maxFitness/2) #enter genetic algorithm until less than 5% fitness improvement is seen while 1: newTotalFitness = totalFitness #score generation scoredGeneration, totalFitness = score(generation, populationSize) #if score is not better than the termination percentage, try for 5 times if float(newTotalFitness)/totalFitness > terminationPercentage: n += 1 if n >= 5: return sorted(scoredGeneration, reverse=True)[0][-1] # else: # n = 0 #output iteration, most fit individual and their score if not silent: print 'Iteration: {0}\tMost Fit Individual: {1}\tScore: {2}'.format( iteration, arrToString(scoredGeneration[-1][1]), scoredGeneration[-1][0]) #apply percentages of selection to fitness of each state temp = list() for state in scoredGeneration: temp.append((float(state[0])/totalFitness, state[1])) scoredGeneration = temp #sum up the percentages in each state #set each percentage in such a way, that the most fit (in position 0) is at 1.0 for i in range(len(scoredGeneration) - 2, -1, -1): scoredGeneration[i] = (scoredGeneration[i+1][0] + scoredGeneration[i][0], scoredGeneration[i][1]) #choose double the population size since the state to child ratio is 2:1 generation = list() for i in range(2*populationSize): selection = random.random() #when the random number is less than the current percentage, it is in that range for state in range(len(scoredGeneration)): if selection >= scoredGeneration[state][0]: generation.append(scoredGeneration[state][1]) break #create the children children = list() for i in range(0, len(generation) - 1, 2): x = reproduce(generation[i], generation[i+1]) children.append(x) #mutate the children for child in children: child = mutate(child, mutationRate) #check to see if a solution was found for child in children: if solution(child) == 0: return child #combine children with the parents for a total generation generation = list() for child in children: generation.append(child) for parent in scoredGeneration: generation.append(parent[1]) iteration += 1
def FFA(objf,lb,ub,dim,n,MaxGeneration): #General parameters #n=50 #number of fireflies #dim=30 #dim #lb=-50 #ub=50 #MaxGeneration=500 #FFA parameters alpha=0.5 # Randomness 0--1 (highly random) betamin=0.20 # minimum value of beta gamma=1 # Absorption coefficient zn=numpy.ones(n) zn.fill(float("inf")) #ns(i,:)=Lb+(Ub-Lb).*rand(1,d); ns=numpy.random.uniform(0,1,(n,dim)) *(ub-lb)+lb Lightn=numpy.ones(n) Lightn.fill(float("inf")) #[ns,Lightn]=init_ffa(n,d,Lb,Ub,u0) convergence=[] s=solution() print("CS is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") # Main loop for k in range (0,MaxGeneration): # start iterations #% This line of reducing alpha is optional alpha=alpha_new(alpha,MaxGeneration); #% Evaluate new solutions (for all n fireflies) for i in range(0,n): zn[i]=objf(ns[i,:]) Lightn[i]=zn[i] # Ranking fireflies by their light intensity/objectives Lightn=numpy.sort(zn) Index=numpy.argsort(zn) ns=ns[Index,:] #Find the current best nso=ns Lighto=Lightn nbest=ns[0,:] Lightbest=Lightn[0] #% For output only fbest=Lightbest; #% Move all fireflies to the better locations # [ns]=ffa_move(n,d,ns,Lightn,nso,Lighto,nbest,... # Lightbest,alpha,betamin,gamma,Lb,Ub); scale=numpy.ones(dim)*abs(ub-lb) for i in range (0,n): # The attractiveness parameter beta=exp(-gamma*r) for j in range(0,n): r=numpy.sqrt(numpy.sum((ns[i,:]-ns[j,:])**2)); #r=1 # Update moves if Lightn[i]>Lighto[j]: # Brighter and more attractive beta0=1 beta=(beta0-betamin)*math.exp(-gamma*r**2)+betamin tmpf=alpha*(numpy.random.rand(dim)-0.5)*scale ns[i,:]=ns[i,:]*(1-beta)+nso[j,:]*beta+tmpf #ns=numpy.clip(ns, lb, ub) convergence.append(fbest) IterationNumber=k BestQuality=fbest if (k%1==0): print(['At iteration '+ str(k)+ ' the best fitness is '+ str(BestQuality)]) # ####################### End main loop timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=convergence s.optimizer="FFA" s.objfname=objf.__name__ return s
def test_case_1(self): result = solution.solution('aabcbcbc') self.assertEqual(result, 3)
def test_case_1(self): result = solution.solution(4) self.assertEqual(result, 5)
import solution tests = [{ "in": ["1.11", "2.0.0", "1.2", "2", "0.1", "1.2.1", "1.1.1", "2.0"], "out": ["0.1", "1.1.1", "1.2", "1.2.1", "1.11", "2", "2.0", "2.0.0"] }, { "in": ["1.1.2", "1.0", "1.3.3", "1.0.12", "1.0.2"], "out": ["1.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"] }] for test in tests: print(test["in"]) print(solution.solution(test["in"])) print(test["out"] == solution.solution(test["in"]))
def main_test(): solution()
def GWO(objf,lb,ub,dim,SearchAgents_no,Max_iter): #Max_iter=1000 #lb=-100 #ub=100 #dim=30 #SearchAgents_no=5 # initialize alpha, beta, and delta_pos Alpha_pos=numpy.zeros(dim) Alpha_score=float("inf") Beta_pos=numpy.zeros(dim) Beta_score=float("inf") Delta_pos=numpy.zeros(dim) Delta_score=float("inf") #Initialize the positions of search agents Positions=numpy.random.uniform(0,1,(SearchAgents_no,dim)) *(ub-lb)+lb Convergence_curve=numpy.zeros(Max_iter) s=solution() # Loop counter print("GWO is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") # Main loop for l in range(0,Max_iter): for i in range(0,SearchAgents_no): # Return back the search agents that go beyond the boundaries of the search space Positions[i,:]=numpy.clip(Positions[i,:], lb, ub) # Calculate objective function for each search agent fitness=objf(Positions[i,:]) # Update Alpha, Beta, and Delta if fitness<Alpha_score : Alpha_score=fitness; # Update alpha Alpha_pos=Positions[i,:] if (fitness>Alpha_score and fitness<Beta_score ): Beta_score=fitness # Update beta Beta_pos=Positions[i,:] if (fitness>Alpha_score and fitness>Beta_score and fitness<Delta_score): Delta_score=fitness # Update delta Delta_pos=Positions[i,:] a=2-l*((2)/Max_iter); # a decreases linearly fron 2 to 0 # Update the Position of search agents including omegas for i in range(0,SearchAgents_no): for j in range (0,dim): r1=random.random() # r1 is a random number in [0,1] r2=random.random() # r2 is a random number in [0,1] A1=2*a*r1-a; # Equation (3.3) C1=2*r2; # Equation (3.4) D_alpha=abs(C1*Alpha_pos[j]-Positions[i,j]); # Equation (3.5)-part 1 X1=Alpha_pos[j]-A1*D_alpha; # Equation (3.6)-part 1 r1=random.random() r2=random.random() A2=2*a*r1-a; # Equation (3.3) C2=2*r2; # Equation (3.4) D_beta=abs(C2*Beta_pos[j]-Positions[i,j]); # Equation (3.5)-part 2 X2=Beta_pos[j]-A2*D_beta; # Equation (3.6)-part 2 r1=random.random() r2=random.random() A3=2*a*r1-a; # Equation (3.3) C3=2*r2; # Equation (3.4) D_delta=abs(C3*Delta_pos[j]-Positions[i,j]); # Equation (3.5)-part 3 X3=Delta_pos[j]-A3*D_delta; # Equation (3.5)-part 3 Positions[i,j]=(X1+X2+X3)/3 # Equation (3.7) Convergence_curve[l]=Alpha_score; if (l%1==0): print(['At iteration '+ str(l)+ ' the best fitness is '+ str(Alpha_score)]); timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=Convergence_curve s.optimizer="GWO" s.objfname=objf.__name__ return s
def evaluate(self,sets): """ This function evaluates the node and returns the resulting set\ """ return [solution.solution(self.settings)]
def MFO(objf,lb,ub,dim,N,Max_iteration): #Max_iteration=1000 #lb=-100 #ub=100 #dim=30 N=50 # Number of search agents #Initialize the positions of moths Moth_pos=numpy.random.uniform(0,1,(N,dim)) *(ub-lb)+lb Moth_fitness=numpy.full(N,float("inf")) #Moth_fitness=numpy.fell(float("inf")) Convergence_curve=numpy.zeros(Max_iteration) sorted_population=numpy.copy(Moth_pos) fitness_sorted=numpy.zeros(N) ##################### best_flames=numpy.copy(Moth_pos) best_flame_fitness=numpy.zeros(N) #################### double_population=numpy.zeros((2*N,dim)) double_fitness=numpy.zeros(2*N) double_sorted_population=numpy.zeros((2*N,dim)) double_fitness_sorted=numpy.zeros(2*N) ######################### previous_population=numpy.zeros((N,dim)); previous_fitness=numpy.zeros(N) s=solution() print("MFO is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") Iteration=1; # Main loop while (Iteration<Max_iteration+1): # Number of flames Eq. (3.14) in the paper Flame_no=round(N-Iteration*((N-1)/Max_iteration)); for i in range(0,N): # Check if moths go out of the search spaceand bring it back Moth_pos[i,:]=numpy.clip(Moth_pos[i,:], lb, ub) # evaluate moths Moth_fitness[i]=objf(Moth_pos[i,:]) if Iteration==1: # Sort the first population of moths fitness_sorted=numpy.sort(Moth_fitness) I=numpy.argsort(Moth_fitness) sorted_population=Moth_pos[I,:] #Update the flames best_flames=sorted_population; best_flame_fitness=fitness_sorted; else: # # # Sort the moths double_population=numpy.concatenate((previous_population,best_flames),axis=0) double_fitness=numpy.concatenate((previous_fitness, best_flame_fitness),axis=0); # double_fitness_sorted =numpy.sort(double_fitness); I2 =numpy.argsort(double_fitness); # # for newindex in range(0,2*N): double_sorted_population[newindex,:]=numpy.array(double_population[I2[newindex],:]) fitness_sorted=double_fitness_sorted[0:N] sorted_population=double_sorted_population[0:N,:] # # # Update the flames best_flames=sorted_population; best_flame_fitness=fitness_sorted; # # # Update the position best flame obtained so far Best_flame_score=fitness_sorted[0] Best_flame_pos=sorted_population[0,:] # previous_population=Moth_pos; previous_fitness=Moth_fitness; # # a linearly dicreases from -1 to -2 to calculate t in Eq. (3.12) a=-1+Iteration*((-1)/Max_iteration); # Loop counter for i in range(0,N): # for j in range(0,dim): if (i<=Flame_no): #Update the position of the moth with respect to its corresponsing flame # # D in Eq. (3.13) distance_to_flame=abs(sorted_population[i,j]-Moth_pos[i,j]) b=1 t=(a-1)*random.random()+1; # # % Eq. (3.12) Moth_pos[i,j]=distance_to_flame*math.exp(b*t)*math.cos(t*2*math.pi)+sorted_population[i,j] # end # if i>Flame_no: # Upaate the position of the moth with respct to one flame # # % Eq. (3.13) distance_to_flame=abs(sorted_population[i,j]-Moth_pos[i,j]); b=1; t=(a-1)*random.random()+1; # # % Eq. (3.12) Moth_pos[i,j]=distance_to_flame*math.exp(b*t)*math.cos(t*2*math.pi)+sorted_population[Flame_no,j] #Display best fitness along the iteration if (Iteration%1==0): print(['At iteration '+ str(Iteration)+ ' the best fitness is '+ str(Best_flame_score)]); Iteration=Iteration+1; timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=Convergence_curve s.optimizer="MFO" s.objfname=objf.__name__ return s
def test_solution(): input1 = [5, 6, 4, 3, 6, 2, 3] input2 = [2, 3, 5, 2, 4] print("test reverse: {},{} => {}".format(input1, input2, 4)) assert solution(input1, input2) == 4
def test_medium(): input1 = [ 4149, 5665, 691, 7393, 826, 894, 2458, 620, 2526, 5950, 6944, 3527, 8595, 973, 7886, 6361, 3911, 3757, 7603, 7025, 9389, 1105, 8446, 6189, 5614, 6812, 4946, 7391, 277, 2777, 3887, 446, 1487, 9936, 9271, 3764, 9062, 7763, 3930, 1768, 6385, 781, 110, 2694, 6012, 4581, 6092, 9954, 1071, 9146, 5467, 9409, 7050, 6375, 6635, 83, 3031, 3232, 429, 244, 8935, 8314, 6032, 4361, 7807, 2444, 1883, 5144, 8922, 2210, 4269, 4103, 3560, 2086, 7991, 5024, 1706, 3284, 8031, 3638, 218, 3330, 5428, 2708, 5849, 8999, 7280, 8894, 4474, 6960, 1153, 3764, 1916, 5555, 9349, 2558, 2524, 7449, 1136, 6516, 260, 2361, 9249, 6635, 9986, 9872, 860, 2895, 5578, 906, 3085, 4112, 722, 3740, 5898, 8681, 8437, 4137, 9890, 7016, 5099, 1106, 8201, 9639, 6636, 8172, 4523, 7345, 4890, 656, 3568, 1079, 8038, 7928, 8211, 8302, 6314, 942, 2783, 9208, 2276, 4553, 11, 4524, 4617, 685, 3025, 5426, 4338, 902, 6192, 1639, 4103, 1620, 4564, 2342, 6357, 564, 894, 6582, 6871, 8884, 1422, 939, 633, 4102, 1193, 9477, 9968, 2387, 9391, 3003, 4990, 8753, 9882, 958, 8974, 3994, 76, 3532, 5450, 2850, 3541, 8420, 7414, 2443, 5962, 4892, 3693, 9921, 1540, 2700, 324, 7328, 7151, 2727, 6330, 9548, 6384, ] input2 = [ 8039, 9942, 3680, 1353, 1716, 5514, 792, 8834, 8992, 1635, 9104, 5423, 2547, 6582, 7908, 5799, 4125, 2250, 4326, 1233, 1076, 4507, 7907, 3817, 2288, 762, 7909, 2105, 7774, 3862, 6574, 8279, 4097, 5367, 2759, 5290, 9221, 4805, 4824, 2100, 8086, 6479, 8909, 6163, 4972, 4976, 7875, 6619, 5941, 8159, 1924, 7018, 4395, 2587, 2847, 7582, 3356, 870, 5979, 5258, 1503, 9630, 3618, 299, 1780, 6554, 7374, 7892, 4416, 5935, 7862, 9735, 4882, 5278, 7734, 9118, 9388, 7738, 8086, 8357, 6375, 7990, 6754, 3525, 4199, 7973, 5829, 3711, 8121, 2157, 3646, 3738, 6124, 8957, 4609, 9876, 2610, 2961, 6504, 6343, 5982, 1317, 5007, 2593, 8061, 9979, 7886, 2710, 5850, 9139, 492, 3403, 9832, 6054, 3401, 3711, 9219, 2425, 5464, 776, 8365, 4843, 3198, 7440, 2832, 8024, 8615, 2658, 1095, 5720, 9280, 7674, 8272, 1013, 3235, 2724, 7428, 2009, 6992, 9741, 7688, 9784, 995, 5602, 5494, 9657, 4325, 8650, 5623, 7007, 2532, 8660, 6507, 4580, 8585, 3036, 3657, 8729, 1288, 4309, 3400, 7477, 8224, 3558, 8799, 8198, 7485, 3474, 2677, 3107, 6238, 4357, 7489, 2411, 6685, 952, 3877, 2293, 6742, 7050, 7535, 322, 7775, 6698, 5866, 7939, 9079, 1692, 8404, 6270, 9685, 4469, 6294, 9884, 766, 2629, 4647, 7233, 8096, ] print("test medium: {},{} => {}".format(input1, input2, 0)) assert solution(input1, input2) == 0
def evaluate(self): """ This function evaluates the bbsa by running it a user specified number of times. The average number of evaluations and the average best fitness found are stored for use in calculating the fitness. """ self.logs = {key:[] for key in self.sets['pers'].keys()} self.logs['last'] = [] self.sets['last'] = [solution.solution(self.settings)for i in xrange(self.initPop)] for d in self.sets['last']: d.evaluate() self.settings.curOp = 0 self.settings.curEvals = 0 for i in xrange(self.maxIterations): gMax = -1.0 temp = self.root.evaluate(self.sets) if temp: self.sets['last'] = temp for key in self.logs: if key is 'last': continue s = 0.0 m = 0.0 for x in self.sets['pers'][key]: s+=x.fitness if m<x.fitness: m = x.fitness if len(self.sets['pers'][key])>0: s/=len(self.sets['pers'][key]) if self.sets['pers'][key]: self.logs[key].append((i,self.settings.curEvals,m,s)) if m>gMax: gMax = m s = 0.0 m = 0.0 for x in self.sets['last']: s+=x.fitness if m<x.fitness: m = x.fitness if len(self.sets['last'])>0: s/=len(self.sets['last']) if self.sets['last']: if m>gMax: gMax = m self.logs['last'].append((i,int(self.settings.curEvals),m,s,self.settings.curOp)) if i>self.converge and gMax==0: break if self.settings.curEvals>=self.settings.maxEvals: break if self.settings.curOp>=self.settings.maxOp: break gMax = -1 for key in self.logs: if key is 'last': continue s = 0.0 m = 0.0 for x in self.sets['pers'][key]: s+=x.fitness if m<x.fitness: m = x.fitness if len(self.sets['pers'][key])>0: s/=len(self.sets['pers'][key]) self.logs[key].append((i,self.settings.curEvals,m,s)) if m>gMax: gMax = m s = 0.0 m = 0.0 it = 0 k = 0 for x in self.sets['last']: x.evaluate() s+=x.fitness if m<x.fitness: m = x.fitness it = k k+=1 if len(self.sets['last'])>0: s/=len(self.sets['last']) if m>gMax: gMax = m self.logs['last'].append((i,int(self.settings.curEvals),m,s,self.settings.curOp)) self.settings.curEvals = 0 return self.settings.curOp
def test_case_1(self): result = solution.solution('pPoooyY') self.assertEqual(result, True)
rs = test.get_problem(1).rack.status column = test.get_problem(1).rack.column floor = test.get_problem(1).rack.floor end = time.time() print end - start make = ActionGenerator() # for a in range(floor): # print (floor - a - 1), make.change_to_two_dimension1(rs, column, floor)[floor - a - 1], ' ', \ # make.change_to_two_dimension2(rs, column, floor)[floor - 1 - a] start = time.time() ts = action.action() sol = ts.dijk(rs, column, floor, [18, 24], [23, 25])[0] end = time.time() print end - start temp = solution.solution(sol.loc, sol.type, sol.oper) print column, floor, sol.type, sol.oper print sol.loc print start = time.time() print make.generating_idx(rs, column, floor, sol, 1, 1).loc end = time.time() print end - start # result = make.full_random_action(rs, column, floor, sol) # result = make.action_fixed_action(rs, column, floor, sol, 11) # result = make.oper_fixed_random_action(rs, column, floor, sol, 0) # print result.loc
def test_case_1(self): result = solution.solution([-1, 3, -1, 5]) self.assertEqual(result, 7)
def CS(objf,lb,ub,dim,n,N_IterTotal): #lb=-1 #ub=1 #n=50 #N_IterTotal=1000 #dim=30 # Discovery rate of alien eggs/solutions pa=0.25 nd=dim # Lb=[lb]*nd # Ub=[ub]*nd convergence=[] # RInitialize nests randomely nest=numpy.random.rand(n,dim)*(ub-lb)+lb new_nest=numpy.zeros((n,dim)) new_nest=numpy.copy(nest) bestnest=[0]*dim; fitness=numpy.zeros(n) fitness.fill(float("inf")) s=solution() print("CS is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") fmin,bestnest,nest,fitness =get_best_nest(nest,new_nest,fitness,n,dim,objf) convergence = []; # Main loop counter for iter in range (0,N_IterTotal): # Generate new solutions (but keep the current best) new_nest=get_cuckoos(nest,bestnest,lb,ub,n,dim) # Evaluate new solutions and find best fnew,best,nest,fitness=get_best_nest(nest,new_nest,fitness,n,dim,objf) new_nest=empty_nests(new_nest,pa,n,dim) ; # Evaluate new solutions and find best fnew,best,nest,fitness=get_best_nest(nest,new_nest,fitness,n,dim,objf) if fnew<fmin: fmin=fnew bestnest=best if (iter%10==0): print(['At iteration '+ str(iter)+ ' the best fitness is '+ str(fmin)]); convergence.append(fmin) timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=convergence s.optimizer="CS" s.objfname=objf.__name__ return s
netmaj = [4, 16] #on définit les produit prod1 = product('produit1', [3, 5, 3, 16, 0], 16, 2, 0, 0, 1) prod2 = product('produit2', [3, 5, 3, 21, 0], 21, 3, 0, 0, 1) prod3 = product('produit3', [3, 5, 3, 22, 22], 22, 2, 0, 0, 1) prod4 = product('produit4', [3, 5, 3, 0, 15], 15, 1, 0, 0, 1) prod5 = product('produit5', [3, 5, 3, 0, 24], 24, 46, 0, 0, 23) prod6 = product('produit1', [3, 5, 3, 16, 0], 16, 46, 0, 0, 46) prod = [prod1, prod2, prod3, prod4, prod5, prod6] jssp = instance(mfab, lin, netmin, netmaj, prod) jssp.process_input() sol_const = construct_sol(jssp) sol_const.greedy() sol = solution(jssp, sol_const.X, sol_const.Y, sol_const.U) sol.decode() print("Y =", sol.Y) print("U =", sol.U) print("X =", sol.X) print("FT =", sol.FT) print("CT = ", sol.CT) print("Cmax =", sol.Cmax) sol_fin = tabu_serach(sol, 10, 100) gantt_chart(sol_fin, "Juillet") """ neighbor = move(sol) sol_nei = neighbor[0] movement = neighbor[1] print("mouvement", movement)
import solution class reward(object): ySpeed = 2.5 zSpeed = 0.6666667 def get_maxtime(self, columnNum, floorNum, shuttleNum): return (shuttleNum * 2 + 1) * self.get_time([0,0,0], [0, columnNum-1, floorNum-1]) def get_cycletime(self, solution): cycletime = 0.0 for i in range(len(solution.loc)): if i == 0: cycletime += self.get_time([0,0,0], solution.loc[i]) else: cycletime += self.get_time(solution.loc[i], solution.loc[i-1]) cycletime += self.get_time([0,0,0], solution.loc[len(solution.loc)-1]) return cycletime def get_time(self, start, end): return max(abs((float(start[1]) - float(end[1])) / self.ySpeed), abs((float(start[2]) - float(end[2])) / self.zSpeed)) if __name__ == '__main__': test = reward() sol = solution.solution([[0,1,0],[0,2,0]], [1,2], ['S','R']) print test.get_cycletime(sol) print test.get_maxtime(2, 3, 2)
def BAT(objf,lb,ub,dim,N,Max_iteration): n=N; # Population size #lb=-50 #ub=50 if not isinstance(lb, list): lb = [lb] * dim if not isinstance(ub, list): ub = [ub] * dim N_gen=Max_iteration # Number of generations A=0.5; # Loudness (constant or decreasing) r=0.5; # Pulse rate (constant or decreasing) Qmin=0 # Frequency minimum Qmax=2 # Frequency maximum d=dim # Number of dimensions # Initializing arrays Q=numpy.zeros(n) # Frequency v=numpy.zeros((n,d)) # Velocities Convergence_curve=[]; # Initialize the population/solutions Sol = numpy.zeros((n,d)) for i in range(dim): Sol[:, i] = numpy.random.rand(n) * (ub[i]-lb[i])+lb[i] S=numpy.zeros((n,d)) S=numpy.copy(Sol) Fitness=numpy.zeros(n) # initialize solution for the final results s=solution() print("BAT is optimizing \""+objf.__name__+"\"") # Initialize timer for the experiment timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") #Evaluate initial random solutions for i in range(0,n): Fitness[i]=objf(Sol[i,:]) # Find the initial best solution fmin = min(Fitness) I=numpy.argmin(fmin) best=Sol[I,:] # Main loop for t in range (0,N_gen): # Loop over all bats(solutions) for i in range (0,n): Q[i]=Qmin+(Qmin-Qmax)*random.random() v[i,:]=v[i,:]+(Sol[i,:]-best)*Q[i] S[i,:]=Sol[i,:]+v[i,:] # Check boundaries for j in range(d): Sol[i,j] = numpy.clip(Sol[i,j], lb[j], ub[j]) # Pulse rate if random.random()>r: S[i,:]=best+0.001*numpy.random.randn(d) # Evaluate new solutions Fnew=objf(S[i,:]) # Update if the solution improves if ((Fnew<=Fitness[i]) and (random.random()<A) ): Sol[i,:]=numpy.copy(S[i,:]) Fitness[i]=Fnew; # Update the current best solution if Fnew<=fmin: best=numpy.copy(S[i,:]) fmin=Fnew #update convergence curve Convergence_curve.append(fmin) if (t%1==0): print(['At iteration '+ str(t)+ ' the best fitness is '+ str(fmin)]) timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=Convergence_curve s.optimizer="BAT" s.objfname=objf.__name__ return s
def GA(objf,lb,ub,dim,popSize,iters): """ This is the main method which implements GA Parameters ---------- objf : function The objective function selected lb: int lower bound limit ub: int Upper bound limit dim: int The dimension of the indivisual popSize: int Number of chrmosomes in a population iters: int Number of iterations / generations of GA Returns ------- obj s: The solution obtained from running the algorithm """ cp = 1 #crossover Probability mp = 0.01 #Mutation Probability keep = 2; # elitism parameter: how many of the best individuals to keep from one generation to the next s=solution() bestIndividual=numpy.zeros(dim) scores=numpy.random.uniform(0.0, 1.0, popSize) bestScore=float("inf") ga=numpy.random.uniform(0,1,(popSize,dim)) *(ub-lb)+lb convergence_curve=numpy.zeros(iters) print("GA is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") for l in range(iters): #crossover ga = crossoverPopulaton(ga, scores, popSize, cp, keep) #mutation mutatePopulaton(ga, popSize, mp, keep, lb, ub) ga = clearDups(ga, lb, ub) scores = calculateCost(objf, ga, popSize, lb, ub) bestScore = min(scores) #Sort from best to worst ga, scores = sortPopulation(ga, scores) convergence_curve[l]=bestScore if (l%1==0): print(['At iteration '+ str(l+1)+ ' the best fitness is '+ str(bestScore)]); timerEnd=time.time() s.bestIndividual = bestIndividual s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=convergence_curve s.optimizer="GA" s.objfname=objf.__name__ return s
def PSO(objf,lb,ub,dim,PopSize,iters): # PSO parameters # dim=30 # iters=200 Vmax=6 # PopSize=50 #population size wMax=0.9 wMin=0.2 c1=2 c2=2 # lb=-10 # ub=10 # s=solution() ######################## Initializations vel=numpy.zeros((PopSize,dim)) pBestScore=numpy.zeros(PopSize) pBestScore.fill(float("inf")) pBest=numpy.zeros((PopSize,dim)) gBest=numpy.zeros(dim) gBestScore=float("inf") pos=numpy.random.uniform(0,1,(PopSize,dim)) *(ub-lb)+lb convergence_curve=numpy.zeros(iters) ############################################ print("PSO is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") for l in range(0,iters): for i in range(0,PopSize): #pos[i,:]=checkBounds(pos[i,:],lb,ub) pos[i,:]=numpy.clip(pos[i,:], lb, ub) #Calculate objective function for each particle fitness=objf(pos[i,:]) if(pBestScore[i]>fitness): pBestScore[i]=fitness pBest[i,:]=pos[i,:] if(gBestScore>fitness): gBestScore=fitness gBest=pos[i,:] #Update the W of PSO w=wMax-l*((wMax-wMin)/iters); for i in range(0,PopSize): for j in range (0,dim): r1=random.random() r2=random.random() vel[i,j]=w*vel[i,j]+c1*r1*(pBest[i,j]-pos[i,j])+c2*r2*(gBest[j]-pos[i,j]) if(vel[i,j]>Vmax): vel[i,j]=Vmax if(vel[i,j]<-Vmax): vel[i,j]=-Vmax pos[i,j]=pos[i,j]+vel[i,j] convergence_curve[l]=gBestScore if (l%1==0): print(['At iteration '+ str(l+1)+ ' the best fitness is '+ str(gBestScore)]); timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=convergence_curve s.optimizer="PSO" s.objfname=objf.__name__ return s
def SSA(objf,lb,ub,dim,N,Max_iteration): #Max_iteration=1000 #lb=-100 #ub=100 #dim=30 N=50 # Number of search agents if not isinstance(lb, list): lb = [lb] * dim if not isinstance(ub, list): ub = [ub] * dim Convergence_curve=numpy.zeros(Max_iteration) #Initialize the positions of salps SalpPositions = numpy.zeros((N, dim)) for i in range(dim): SalpPositions[:, i] = numpy.random.uniform(0, 1, N) * (ub[i] - lb[i]) + lb[i] SalpFitness=numpy.full(N,float("inf")) FoodPosition=numpy.zeros(dim) FoodFitness=float("inf") #Moth_fitness=numpy.fell(float("inf")) s=solution() print("SSA is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") for i in range(0,N): # evaluate moths SalpFitness[i]=objf(SalpPositions[i,:]) sorted_salps_fitness=numpy.sort(SalpFitness) I=numpy.argsort(SalpFitness) Sorted_salps=numpy.copy(SalpPositions[I,:]) FoodPosition=numpy.copy(Sorted_salps[0,:]) FoodFitness=sorted_salps_fitness[0] Iteration=1; # Main loop while (Iteration<Max_iteration): # Number of flames Eq. (3.14) in the paper #Flame_no=round(N-Iteration*((N-1)/Max_iteration)); c1 = 2*math.exp(-(4*Iteration/Max_iteration)**2); # Eq. (3.2) in the paper for i in range(0,N): SalpPositions= numpy.transpose(SalpPositions); if i<N/2: for j in range(0,dim): c2=random.random() c3=random.random() #Eq. (3.1) in the paper if c3<0.5: SalpPositions[j,i]=FoodPosition[j]+c1*((ub[j]-lb[j])*c2+lb[j]); else: SalpPositions[j,i]=FoodPosition[j]-c1*((ub[j]-lb[j])*c2+lb[j]); #################### elif i>=N/2 and i<N+1: point1=SalpPositions[:,i-1]; point2=SalpPositions[:,i]; SalpPositions[:,i]=(point2+point1)/2; # Eq. (3.4) in the paper SalpPositions= numpy.transpose(SalpPositions); for i in range(0,N): # Check if salps go out of the search spaceand bring it back for j in range(dim): SalpPositions[i,j]=numpy.clip(SalpPositions[i,j], lb[j], ub[j]) SalpFitness[i]=objf(SalpPositions[i,:]); if SalpFitness[i]<FoodFitness: FoodPosition=numpy.copy(SalpPositions[i,:]) FoodFitness=SalpFitness[i] #Display best fitness along the iteration if (Iteration%1==0): print(['At iteration '+ str(Iteration)+ ' the best fitness is '+ str(FoodFitness)]); Convergence_curve[Iteration]=FoodFitness Iteration=Iteration+1; timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=Convergence_curve s.optimizer="SSA" s.objfname=objf.__name__ return s
def test_solution(): input1 = [] print("test1: {} => {}".format(input1, [])) assert solution(input1) == []
def test_case_1(self): result = solution.solution(['I 16', 'D 1']) self.assertEqual(result, [0, 0])
def test_solution_reverse(): input1 = [10, 8, 5, 4, 3, 1] input2 = [1, 3, 4, 5, 8, 10] print("test reverse: {},{} => {}".format(input1, input2, len(input1))) assert solution(input1, input2) == len(input1)
def test_case_2(self): result = solution.solution(['I 7', 'I 5', 'I -5', 'D -1']) self.assertEqual(result, [7, 5])
#!/usr/bin/python2 # -*- coding: utf-8 -*- from solution import solution solution() print "Check 1: passed - No syntax errors" f = open("chessboard.txt", "w") f.write("_________________\n") for i in range(8): f.write(". . . . . . . . .\n") f.write("-----------------\n") f.close() solution() f = open("chessboard.txt", "r") lineno = 0 errors = 0 for line in f: corrent_line = "" if lineno == 0: corrent_line = "_________________\n" elif lineno == 9: corrent_line = "-----------------\n" elif lineno % 2 == 0: corrent_line = ". .X. .X. .X. .X.\n" elif lineno % 2 == 1: corrent_line = ".X. .X. .X. .X. .\n" if line == corrent_line: print "Line number ", lineno, "is ok."
def WOA3(objf, lb, ub, dim, SearchAgents_no, Max_iter): #dim=30 #SearchAgents_no=50 #lb=-100 #ub=100 #Max_iter=500 if not isinstance(lb, list): lb = [lb] * dim if not isinstance(ub, list): ub = [ub] * dim # initialize position vector and score for the leader Leader_pos = numpy.zeros(dim) Leader_score = float("inf") #change this to -inf for maximization problems #Initialize the positions of search agents Positions = numpy.zeros((SearchAgents_no, dim)) for i in range(dim): Positions[:, i] = numpy.random.uniform( 0, 1, SearchAgents_no) * (ub[i] - lb[i]) + lb[i] #Initialize convergence convergence_curve = numpy.zeros(Max_iter) ############################ s = solution() print("WOA3 is optimizing \"" + objf.__name__ + "\"") timerStart = time.time() s.startTime = time.strftime("%Y-%m-%d-%H-%M-%S") ############################ t = 0 # Loop counter # Main loop while t < Max_iter: for i in range(0, SearchAgents_no): # Return back the search agents that go beyond the boundaries of the search space #Positions[i,:]=checkBounds(Positions[i,:],lb,ub) for j in range(dim): Positions[i, j] = numpy.clip(Positions[i, j], lb[j], ub[j]) # Calculate objective function for each search agent fitness = objf(Positions[i, :]) # Update the leader if fitness < Leader_score: # Change this to > for maximization problem Leader_score = fitness # Update alpha Leader_pos = Positions[i, :].copy( ) # copy current whale position into the leader position a = 2 - t * ((2) / Max_iter) # a decreases linearly fron 2 to 0 in Eq. (2.3) # a2 linearly decreases from -1 to -2 to calculate t in Eq. (3.12) a2 = -1 + t * ((-1) / Max_iter) w_final = 0.9 w_initial = 0.2 w = w_initial - (w_initial - w_final) * ( t / Max_iter ) # introduced by Shi and Eberhart[12] who introduce a Linear Decreasing Inertia Weight(LDIW) strategy in 1998 # Update the Position of search agents for i in range(0, SearchAgents_no): r1 = random.random() # r1 is a random number in [0,1] r2 = random.random() # r2 is a random number in [0,1] A = 2 * a * r1 - a # Eq. (2.3) in the paper C = 2 * r2 # Eq. (2.4) in the paper b = 1 # parameters in Eq. (2.5) l = (a2 - 1) * random.random() + 1 # parameters in Eq. (2.5) p = random.random() # p in Eq. (2.6) for j in range(0, dim): rand_leader_index = math.floor(SearchAgents_no * random.random()) X_rand = Positions[rand_leader_index, :] D_X_rand = abs(C * X_rand[j] - Positions[i, j]) Positions[i, j] = X_rand[j] - A * D_X_rand if p < 0.5: D_Leader = abs(C * Leader_pos[j] - Positions[i, j]) Positions[i, j] = w * Leader_pos[j] - A * D_Leader else: distance2Leader = abs(Leader_pos[j] - Positions[i, j]) # Eq. (2.5) Positions[i, j] = distance2Leader * math.exp( b * l) * math.cos(l * 2 * math.pi) + Leader_pos[j] * w convergence_curve[t] = Leader_score if (t % 1 == 0): print([ 'At iteration ' + str(t) + ' the best fitness is ' + str(Leader_score) ]) t = t + 1 timerEnd = time.time() s.endTime = time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime = timerEnd - timerStart s.convergence = convergence_curve s.optimizer = "WOA3" s.objfname = objf.__name__ s.best = Leader_score s.bestIndividual = Leader_pos s.std = numpy.std(convergence_curve) s.mean = numpy.average(convergence_curve) return s
from random import randint from solution import solution a = randint(0, 100) filename = "test.file.txt" f = open(filename, "w") for i in range(a): f.write("garbage\n") f.close() a1 = a * len("garbage\n") a2 = a * len("garbage") i = solution(filename) print "Check 1: passed - No syntax errors" if i != None: print "Check 2: passed - Η συνάρτηση επιστρέφει κάτι." else: print "Check 2: FAILED - Η συνάρτηση δεν επιστρέφει τίποτα." if isinstance(i, int): print "Check 3: passed - Η συνάρτηση επιστρέφει έναν ακέραιο." else: print "Check 3: FAILED - Η συνάρτηση δεν επιστρέφει ακέραιο." if i == a1 or i == a2: print "Check 4: passed - Το νούμερο των χαρακτήρων είναι σωστό" if i == a2:
def GA(objf, lb, ub, dim, PopSize, iters): """ This is the main method which implements GA Parameters ---------- objf : function The objective function selected lb: int lower bound limit ub: int Upper bound limit PopSize: int Number of chrmosomes in a population iters: int Number of iterations / generations of GA Returns ------- N/A """ cp = 0.8 #crossover Probability mp = 0.001 #Mutation Probability s = solution() bestIndividual = numpy.zeros(dim) scores = numpy.zeros(PopSize) bestScore = float("inf") ga = numpy.random.uniform(0, 1, (PopSize, dim)) * (ub - lb) + lb convergence_curve = numpy.zeros(iters) print("GA is optimizing \"" + objf.__name__ + "\"") timerStart = time.time() s.startTime = time.strftime("%Y-%m-%d-%H-%M-%S") for l in range(iters): #Loop through chromosomes in population for i in range(0, PopSize): # Return back the search agents that go beyond the boundaries of the search space ga[i, :] = numpy.clip(ga[i, :], lb, ub) # Calculate objective function for each search agent fitness = objf(ga[i, :]) scores[i] = fitness if (bestScore > fitness): bestScore = fitness bestIndividual = numpy.copy(ga[i, :]) #Apply evolutionary operators to chromosomes ga = runOperators(ga, scores, bestIndividual, bestScore, cp, mp, PopSize, lb, ub) convergence_curve[l] = bestScore if (l % 1 == 0): print([ 'At iteration ' + str(l + 1) + ' the best fitness is ' + str(bestScore) ]) timerEnd = time.time() s.bestIndividual = bestIndividual s.endTime = time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime = timerEnd - timerStart s.convergence = convergence_curve s.optimizer = "GA" s.objfname = objf.__name__ return s
def test_case_2(self): result = solution.solution('Pyy') self.assertEqual(result, False)
def test_case_1(self): result = solution.solution(5) self.assertEqual(result, [ '00000', '00001', '00010', '00100', '00101', '01000', '01001', '01010', '10000', '10001', '10010', '10100', '10101' ])
def test_case_3(self): result = solution.solution([2, 4, -2, -3, 8]) self.assertEqual(result, 9)
def MVO(objf, lb, ub, dim, N, Max_time): "parameters" #dim=30 #lb=-100 #ub=100 WEP_Max = 1 WEP_Min = 0.2 #Max_time=1000 #N=50 Universes = numpy.random.uniform(0, 1, (N, dim)) * (ub - lb) + lb Sorted_universes = numpy.copy(Universes) convergence = numpy.zeros(Max_time) Best_universe = [0] * dim Best_universe_Inflation_rate = float("inf") s = solution() Time = 1 ############################################ print("MVO is optimizing \"" + objf.__name__ + "\"") timerStart = time.time() s.startTime = time.strftime("%Y-%m-%d-%H-%M-%S") while (Time < Max_time + 1): "Eq. (3.3) in the paper" WEP = WEP_Min + Time * ((WEP_Max - WEP_Min) / Max_time) TDR = 1 - (math.pow(Time, 1 / 6) / math.pow(Max_time, 1 / 6)) Inflation_rates = [0] * len(Universes) for i in range(0, N): Universes[i, :] = numpy.clip(Universes[i, :], lb, ub) Inflation_rates[i] = objf(Universes[i, :]) if Inflation_rates[i] < Best_universe_Inflation_rate: Best_universe_Inflation_rate = Inflation_rates[i] Best_universe = numpy.array(Universes[i, :]) sorted_Inflation_rates = numpy.sort(Inflation_rates) sorted_indexes = numpy.argsort(Inflation_rates) for newindex in range(0, N): Sorted_universes[newindex, :] = numpy.array( Universes[sorted_indexes[newindex], :]) normalized_sorted_Inflation_rates = numpy.copy( normr(sorted_Inflation_rates)) Universes[0, :] = numpy.array(Sorted_universes[0, :]) for i in range(1, N): Back_hole_index = i for j in range(0, dim): r1 = random.random() if r1 < normalized_sorted_Inflation_rates[i]: White_hole_index = RouletteWheelSelection( -sorted_Inflation_rates) if White_hole_index == -1: White_hole_index = 0 White_hole_index = 0 Universes[Back_hole_index, j] = Sorted_universes[White_hole_index, j] r2 = random.random() if r2 < WEP: r3 = random.random() if r3 < 0.5: Universes[i, j] = Best_universe[j] + TDR * ( (ub - lb) * random.random() + lb ) #random.uniform(0,1)+lb); if r3 > 0.5: Universes[i, j] = Best_universe[j] - TDR * ( (ub - lb) * random.random() + lb ) #random.uniform(0,1)+lb); convergence[Time - 1] = Best_universe_Inflation_rate if (Time % 1 == 0): print([ 'At iteration ' + str(Time) + ' the best fitness is ' + str(Best_universe_Inflation_rate) ]) Time = Time + 1 timerEnd = time.time() s.endTime = time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime = timerEnd - timerStart s.convergence = convergence s.optimizer = "MVO" s.objfname = objf.__name__ return s
def test_case_2(self): result = solution.solution([-5, -3, -1]) self.assertEqual(result, -1)
def test_case_4(self): result = solution.solution("abcabcabcabcdededededede") self.assertEqual(result, 14)
def test_case_2(self): result = solution.solution(3) self.assertEqual(result, 3)
def test_case_1(self): result = solution.solution("aabbaccc") self.assertEqual(result, 7)
def test_case_3(self): result = solution.solution('abbbcedd') self.assertEqual(result, 4)
def test_case_2(self): result = solution.solution("ababcdcdababcdcd") self.assertEqual(result, 9)
def test_case_2(self): result = solution.solution('aaaaaaaa') self.assertEqual(result, 1)
def GA(objf,lb,ub,dim,popSize,iters, k, points, metric): """ This is the main method which implements GA Parameters ---------- objf : function The objective function selected lb: list lower bound limit list ub: list Upper bound limit list dim: int The dimension of the indivisual popSize: int Number of chrmosomes in a population iters: int Number of iterations / generations of GA Returns ------- obj s: The solution obtained from running the algorithm """ cp = 1 #crossover Probability mp = 0.01 #Mutation Probability keep = 2; # elitism parameter: how many of the best individuals to keep from one generation to the next s=solution() bestIndividual=numpy.zeros(dim) bestScore=float("inf") bestLabelsPred=numpy.full(len(points), numpy.inf) ga = numpy.random.uniform(0,1,(popSize,dim)) *(ub-lb)+lb scores=numpy.full(popSize,float("inf")) for i in range(dim): ga[:, i]=numpy.random.uniform(0,1,popSize) * (ub - lb) + lb convergence_curve=numpy.zeros(iters) print("GA is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") for l in range(iters): #crossover ga = crossoverPopulaton(ga, scores, popSize, cp, keep) #mutation mutatePopulaton(ga, popSize, mp, keep, lb, ub) ga = clearDups(ga, lb, ub) scores, bestLabelsPred, bestIndividual = calculateCost(objf, ga, dim, popSize, lb, ub, k, points, metric) bestScore = min(scores) #Sort from best to worst ga, scores = sortPopulation(ga, scores) convergence_curve[l]=bestScore if (l%1==0): print(['At iteration '+ str(l+1)+ ' the best fitness is '+ str(bestScore)]); bestLabelsPred = numpy.asarray(bestLabelsPred) timerEnd=time.time() s.bestIndividual = bestIndividual s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=convergence_curve s.optimizer="GA" s.labelsPred = numpy.array(bestLabelsPred, dtype=numpy.int64) s.objfname=objf.__name__ return s
mu = 100 k = 8 pop = [] i = 0 nodes = 35 m = 4 n = 6 top = topFront.topFront() while i<mu: x = solution.solution(nodes,m, n) x.evaluate() pop.append(x) i+=1 top.push(x) pop.sort() maxEvals = 50000 cur = mu children = 40 rate = .001 sk = 10
def test_case_1(self): result = solution.solution(8, 12) self.assertEqual(result, 80)
def WOA(objf,lb,ub,dim,SearchAgents_no,Max_iter): #dim=30 #SearchAgents_no=50 #lb=-100 #ub=100 #Max_iter=500 # initialize position vector and score for the leader Leader_pos=numpy.zeros(dim) Leader_score=float("inf") #change this to -inf for maximization problems #Initialize the positions of search agents Positions=numpy.random.uniform(0,1,(SearchAgents_no,dim)) *(ub-lb)+lb #Initialize convergence convergence_curve=numpy.zeros(Max_iter) ############################ s=solution() print("MFO is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") ############################ t=0 # Loop counter # Main loop while t<Max_iter: for i in range(0,SearchAgents_no): # Return back the search agents that go beyond the boundaries of the search space #Positions[i,:]=checkBounds(Positions[i,:],lb,ub) Positions[i,:]=numpy.clip(Positions[i,:], lb, ub) # Calculate objective function for each search agent fitness=objf(Positions[i,:]) # Update the leader if fitness<Leader_score: # Change this to > for maximization problem Leader_score=fitness; # Update alpha Leader_pos=Positions[i,:] a=2-t*((2)/Max_iter); # a decreases linearly fron 2 to 0 in Eq. (2.3) # a2 linearly dicreases from -1 to -2 to calculate t in Eq. (3.12) a2=-1+t*((-1)/Max_iter); # Update the Position of search agents for i in range(0,SearchAgents_no): r1=random.random() # r1 is a random number in [0,1] r2=random.random() # r2 is a random number in [0,1] A=2*a*r1-a # Eq. (2.3) in the paper C=2*r2 # Eq. (2.4) in the paper b=1; # parameters in Eq. (2.5) l=(a2-1)*random.random()+1 # parameters in Eq. (2.5) p = random.random() # p in Eq. (2.6) for j in range(0,dim): if p<0.5: if abs(A)>=1: rand_leader_index = math.floor(SearchAgents_no*random.random()); X_rand = Positions[rand_leader_index, :] D_X_rand=abs(C*X_rand[j]-Positions[i,j]) Positions[i,j]=X_rand[j]-A*D_X_rand elif abs(A)<1: D_Leader=abs(C*Leader_pos[j]-Positions[i,j]) Positions[i,j]=Leader_pos[j]-A*D_Leader elif p>=0.5: distance2Leader=abs(Leader_pos[j]-Positions[i,j]) # Eq. (2.5) Positions[i,j]=distance2Leader*math.exp(b*l)*math.cos(l*2*math.pi)+Leader_pos[j] convergence_curve[t]=Leader_score if (t%1==0): print(['At iteration '+ str(t)+ ' the best fitness is '+ str(Leader_score)]); t=t+1 timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=convergence_curve s.optimizer="WOA" s.objfname=objf.__name__ return s
from solution import solution assert solution([2, 0, 2, 2, 0]) == '8' assert solution([-2, -3, 4, -5]) == '60' assert solution([2, -3, 1, 0, -5]) == '30' assert solution([-1]) == '-1' assert solution([-1, 0]) == '0'
def MVO(objf,lb,ub,dim,N,Max_time): "parameters" #dim=30 #lb=-100 #ub=100 WEP_Max=1; WEP_Min=0.2 #Max_time=1000 #N=50 Universes=numpy.random.uniform(0,1,(N,dim)) *(ub-lb)+lb Sorted_universes=numpy.copy(Universes) convergence=numpy.zeros(Max_time) Best_universe=[0]*dim; Best_universe_Inflation_rate= float("inf") s=solution() Time=1; ############################################ print("MVO is optimizing \""+objf.__name__+"\"") timerStart=time.time() s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S") while (Time<Max_time+1): "Eq. (3.3) in the paper" WEP=WEP_Min+Time*((WEP_Max-WEP_Min)/Max_time) TDR=1-(math.pow(Time,1/6)/math.pow(Max_time,1/6)) Inflation_rates=[0]*len(Universes) for i in range(0,N): Universes[i,:]=numpy.clip(Universes[i,:], lb, ub) Inflation_rates[i]=objf(Universes[i,:]); if Inflation_rates[i]<Best_universe_Inflation_rate : Best_universe_Inflation_rate=Inflation_rates[i] Best_universe=numpy.array(Universes[i,:]) sorted_Inflation_rates = numpy.sort(Inflation_rates) sorted_indexes = numpy.argsort(Inflation_rates) for newindex in range(0,N): Sorted_universes[newindex,:]=numpy.array(Universes[sorted_indexes[newindex],:]) normalized_sorted_Inflation_rates=numpy.copy(normr(sorted_Inflation_rates)) Universes[0,:]= numpy.array(Sorted_universes[0,:]) for i in range(1,N): Back_hole_index=i for j in range(0,dim): r1=random.random() if r1<normalized_sorted_Inflation_rates[i]: White_hole_index=RouletteWheelSelection(-sorted_Inflation_rates); if White_hole_index==-1: White_hole_index=0; White_hole_index=0; Universes[Back_hole_index,j]=Sorted_universes[White_hole_index,j]; r2=random.random() if r2<WEP: r3=random.random() if r3<0.5: Universes[i,j]=Best_universe[j]+TDR*((ub-lb)*random.random()+lb) #random.uniform(0,1)+lb); if r3>0.5: Universes[i,j]=Best_universe[j]-TDR*((ub-lb)*random.random()+lb) #random.uniform(0,1)+lb); convergence[Time-1]=Best_universe_Inflation_rate if (Time%1==0): print(['At iteration '+ str(Time)+ ' the best fitness is '+ str(Best_universe_Inflation_rate)]); Time=Time+1 timerEnd=time.time() s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S") s.executionTime=timerEnd-timerStart s.convergence=convergence s.optimizer="MVO" s.objfname=objf.__name__ return s
def test_solution(): assert solution('world') == 'dlrow' assert solution('hello') == 'olleh' assert solution('') == '' assert solution('h') == 'h'
import geneticAlgorithmAgent as agent from printBoard import printBoard import solution as s import sys import time x = None silent = False try: if sys.argv[1]: silent = True except: pass size = 6 mut = .008 gen = 100 print '\n\nTesting for n={0}, mutRate={1}, gen={2}\n\n'.format(size,mut,gen) start = time.time() while 1: x = agent.geneticAlgorithmAgent(size, mut, gen ,silent) if s.solution(x) == 0: break finish = time.time() print agent.arrToString(x) printBoard(x) print 'took:', finish-start
def shortest_path(self, rs, column, floor, input, output): rack = rs size_h = column size_v = floor s1 = input[0] s2 = input[1] r1 = output[0] r2 = output[1] item = [s1, r1, s2, r2] io = ['S', 'R', 'S', 'R'] path = ['first', 'second', 'third', 'fourth'] # s1 - r1 lot1 = [] for a, item1 in enumerate(rack): if item1 == -1: loca1 = self.loca_calculate(a, size_h, size_v) lot1.append(loca1) if lot1 == []: print 'no empty space 1' else: lot2 = [] for b, item3 in enumerate(rack): if item3 == r1: loca3 = self.loca_calculate(b, size_h, size_v) lot2.append(loca3) if lot2 == []: print 'no target item 1' else: distance = 100000 lot1.sort() lot2.sort() for c in range(len(lot1)): for d in range(len(lot2)): new_distance = self.get_time([0, 0, 0], lot1[c]) + self.get_time(lot1[c], lot2[d]) if distance > new_distance: path[0] = lot1[c] path[1] = lot2[d] distance = new_distance # s2 path[2] = lot2[d] # r2 lot3 = [] for e, item4 in enumerate(rack): if item4 == r2: loca4 = self.loca_calculate(e, size_h, size_v) lot3.append(loca4) if lot3 == []: print 'no target item 2' else: distance = 100000 lot3.sort() for f in range(len(lot3)): new_distance = self.get_time([0, 0, 0], lot3[f]) + self.get_time(lot3[f], path[2]) if distance > new_distance and path[2] != lot3[f]: path[3] = lot3[f] distance = new_distance sol = solution.solution(path, item, io) cycletime = self.get_cycletime(sol) return sol, cycletime
def nsga(params,setup,log=False): mu = params['mu']['value'] #100 k = params['childK']['value'] #8 pop = [] i = 0 nodes = setup['nodes'] #13 m = setup['m'] # 3 n = setup['n'] # 5 alt = params['altMutate']['value'] #0.002 s = solution.solution(nodes,m,n) si = solution.solution(nodes,m,n) for i in xrange(2,m): s.g.makeTuran(i) s.evaluate() pop.append(s) for i in xrange(2,n): si.g.makeInvTuran(i) si.evaluate() pop.append(si) print "Pre:" while i<mu: x = solution.solution(nodes,m, n) x.evaluate() pop.append(x) i+=1 pop.sort() print "Here" maxEvals = setup['evals'] #50000 cur = mu children = params['lambda']['value'] rate = params['rate']['value'] sk = params['survK']['value'] fronts = pareto.pareto(pop) while cur<maxEvals: childs = [] for i in xrange(children): if random.random()<alt: x= None if random.choice([True,False]): x = fronts.tournSelect(k).invert() else: x = fronts.tournSelect(k).altMutate() x.evaluate() childs.append(x) continue x = fronts.tournSelect(k).mate(fronts.tournSelect(k)) x.mutate(rate) x.evaluate() childs.append(x) cur += children survive = [] pop = fronts.getPop() pop.extend(childs) fronts = pareto.pareto(pop) fronts.keepMu(mu) s = 0.0 q = [1 for e in xrange((nodes*nodes-1)/2)] found = False c = 0 for i in fronts.fronts[0]: q = [a and b for a,b in zip(q,i.g.adj)] s+= i.fitness if log: print c, i.fitness,i.mFit,i.nFit,i.distance if i.fitness==0.0: i.report() found = True c+=1 if log: print print x =sorted(fronts.fronts[0],key = lambda x:x.fitness)[0] if log: print cur, x.nFit,x.mFit,x.fitness print "Reg:",zip(x.g.sets.keys(),[len(x.g.sets[key]) for key in x.g.sets]) print "Inv:",zip(x.g.invSets.keys(),[len(x.g.invSets[key]) for key in x.g.invSets]) if found: break return sorted(fronts.fronts[0],key = lambda x:x.fitness)[0].fitness
def test_null(self): self.assertFalse(solution({}))
def test_check_days(self): self.assertFalse(solution({'2020-01-01': 6}))
def nearest_neighbor_s1s2r1r2(self, rs, column, floor, input, output): rack = rs size_h = column size_v = floor s1 = input[0] s2 = input[1] r1 = output[0] r2 = output[1] item = [s1, s2, r1, r2] io = ['S', 'S', 'R', 'R'] path = ['first', 'second', 'third', 'fourth'] # s1 lot = [] for a, item1 in enumerate(rack): if item1 == -1: loca1 = self.loca_calculate(a, size_h, size_v) lot.append(loca1) if lot == []: print 'no empty space' else: distance = 10000 lot.sort() for b in range(len(lot)): new_distance = self.get_time([0, 0, 0], lot[b]) if distance > new_distance: path[0] = lot[b] distance = new_distance # s2 lot = [] for c, item2 in enumerate(rack): if item2 == -1: loca2 = self.loca_calculate(c, size_h, size_v) lot.append(loca2) if lot == []: print 'no empty space' else: distance = 10000 lot.sort() for d in range(len(lot)): new_distance = self.get_time(path[0], lot[d]) if distance > new_distance and path[0] != lot[d]: path[1] = lot[d] distance = new_distance # r1 lot = [] for e, item3 in enumerate(rack): if item3 == r1: loca3 = self.loca_calculate(e, size_h, size_v) lot.append(loca3) if lot == []: print 'no target item' else: distance = 10000 lot.sort() for f in range(len(lot)): new_distance = self.get_time(path[1], lot[f]) if distance > new_distance: path[2] = lot[f] distance = new_distance # r2 lot = [] for g, item4 in enumerate(rack): if item4 == r2: loca4 = self.loca_calculate(g, size_h, size_v) lot.append(loca4) if lot == []: print 'no target item' else: distance = 10000 lot.sort() for h in range(len(lot)): new_distance = self.get_time(path[2], lot[h]) if distance > new_distance and path[2] != lot[h]: path[3] = lot[h] distance = new_distance sol = solution.solution(path, item, io) cycletime = self.get_cycletime(sol) # print path, item, io, cycletime return sol, cycletime