def tabou(self, a): tabou = [] ltabou = [] s = self.glouton1() i = 0 while i != 100: i = i + 1 neighbors, fct = self.generateNeighborsTabou( s.getInstance(), ltabou) if (len(fct) == 0): break index = fct.index(max(fct)) newSol = neighbors[index] tabou.append(Solution(newSol, fct[index])) ltabou.append(newSol) if len(ltabou) == a: lst = [tabou[j].getValeur() for j in range(a)] index = lst.index(max(lst)) x = tabou[index] tabou = [] ltabou = [] tabou.append(x) ltabou.append(x.getInstance()) s = Solution(newSol, fct[index]) lst = [tabou[j].getValeur() for j in range(len(tabou))] index = lst.index(max(lst)) return tabou[index]
def optimizedTabou(self,start,size): tabou = [] ltabou = [] s = self.glouton1(start) i = 0 while i != 100: i = i + 1 neighbors,fct = self.generateNeighborsTabou(s.getChemin(),ltabou) index = fct.index(min(fct)) newSol = neighbors[index] tabou.append(Solution(newSol,fct[index])) ltabou.append(newSol) if len(ltabou) == size: lst = [tabou[j].getFct() for j in range(len(tabou))] index = lst.index(min(lst)) x = tabou[index] y = tabou[index].getChemin() tabou = [] ltabou = [] tabou.append(x) ltabou.append(y) s = Solution(newSol,fct[index]) lst = [tabou[j].getFct() for j in range(len(tabou))] index = lst.index(min(lst)) return tabou[index]
def buildSolution(self, branchInfo): # 验证 编译 锁 lock_file = self.__checkLock() if lock_file == '': logger.error('另一个打包脚本正在运行...') return {'success': False, 'error': '另一个打包脚本正在运行...'} logger.info(branchInfo.programName + '/' + branchInfo.branchTag + '编译开始') logger.info("Name: %s" % branchInfo.programName) logger.info("Tag: %s" % branchInfo.branchTag) working_dir = getLocalDir(branchInfo.programName) + '/' + branchInfo.branchTag if branchInfo.programName == 'updater': try: sol = Solution.Solution(working_dir, 'Updater.sln', False, 'Release') sol.buildSolution(True, ['tlupdater']) os.remove(lock_file) if sol.status() == 3: # error return {'success': False, 'error': 'build error %s/%s' % (branchInfo.programName, branchInfo.branchTag)} elif sol.status() == 2: # finished return {'success': True, 'error': 'build successfully %s/%s' % (branchInfo.programName, branchInfo.branchTag)} except Exception as e: os.remove(lock_file) return {'success':False, 'error': e.message} elif branchInfo.programName == 'daemon': try: sol = Solution.Solution(working_dir, 'daemon.sln', False, "Deploy_Release") sol.buildSolution(True, ['daemon']) os.remove(lock_file) if sol.status() == 3: # error return {'success': False, 'error': 'build error %s/%s' % (branchInfo.programName, branchInfo.branchTag)} except Exception as e: os.remove(lock_file) return {'success':False, 'error': e.message} elif branchInfo.programName == 'quoter': try: sol = Solution.Solution(working_dir, 'quoter.sln', False, "Deploy_Release") sol.buildSolution(True, ['XtQuoter']) os.remove(lock_file) if sol.status() == 3: # error return {'success': False, 'error': 'build error %s/%s' % (branchInfo.programName, branchInfo.branchTag)} except Exception as e: os.remove(lock_file) return {'success':False, 'error': e.message} elif branchInfo.programName == 'XtTradeClient': try: sol = Solution.Solution(working_dir, 'XtTradeClient.full.sln', False, "Deploy_Release") sol.buildSolution(True, ['XtTradeClient']) os.remove(lock_file) if sol.status() == 3: # error return {'success': False, 'error': 'build error %s/%s' % (branchInfo.programName, branchInfo.branchTag)} except Exception as e: os.remove(lock_file) return {'success':False, 'error': e.message} logger.info(branchInfo.programName + '/' + branchInfo.branchTag + '编译完成') return {'success': True, 'error': 'build successfully %s/%s' % (branchInfo.programName, branchInfo.branchTag)}
def cleanSolution(self, branchInfo): # 验证 编译 锁 lock_file = self.__checkLock() if lock_file == '': logger.error('另一个打包脚本正在运行...') return {'success': False, 'error': '另一个打包脚本正在运行...'} sln_file = '' root_path = getLocalDir(branchInfo.programName) + '/' + branchInfo.branchTag if branchInfo.programName == 'updater': sln_file = 'Updater.sln' elif branchInfo.programName == 'daemon': sln_file = 'daemon.sln' elif branchInfo.programName == 'quoter': sln_file = 'quoter.sln' elif branchInfo.programName == 'XtTradeClient': sln_file = 'XtTradeClient.full.sln' if sln_file == '': if branchInfo.programName != '': logger.error('program \"', branchInfo.programName, '\" does not exists') os.remove(lock_file) return {'success': False, 'error': 'program \"' + branchInfo.programName + '\" does not exists'} else: os.remove(lock_file) return {'success': False, 'error': 'program name is not set'} logger.info('%s/%s clean start' % (branchInfo.programName, branchInfo.branchTag)) try: if branchInfo.programName == 'updater': try: sol = Solution.Solution(root_path, sln_file, True, "Release") os.remove(lock_file) if sol.status() == 3: # error return {'success': False, 'error': 'clean error %s/%s' % (branchInfo.programName, branchInfo.branchTag)} except Exception as e: os.remove(lock_file) return {'success': False, 'error': e.message} else: try: sol = Solution.Solution(root_path, sln_file, True, self.build_configuration) os.remove(lock_file) if sol.status() == 3: # error return {'success': False, 'error': 'clean error %s' % (branchInfo.programName, branchInfo.branchTag)} except Exception as e: os.remove(lock_file) return {'success': False, 'error': e.message} logger.info('%s/%s clean end' % (branchInfo.programName, branchInfo.branchTag)) return {'success': True, 'error': 'Clean %s succeeds' % sln_file} except Exception as e: os.remove(lock_file) logger.error('%s/%s: %s' %(branchInfo.programName, branchInfo.branchTag, e.message)) return {'success': False, 'error': 'clean %s fails' % sln_file}
def Vk(self,s,k): if k == 0: x0 = self.two_opt(s.getChemin()) # print("2-opt") return Solution(x0,self.fonctionObjectif(x0)) if k == 1: x1 = self.three_opt(s.getChemin()) # print("3-opt") return Solution(x1,self.fonctionObjectif(x1)) if k == 2: x2 = self.four_opt(s.getChemin()) # print("4-opt") return Solution(x2,self.fonctionObjectif(x2))
def mutation(self,ind,fct,typeOfMutation): n = len(ind) if typeOfMutation == "descente": return self.descenteVPop(Solution(ind,fct)) if typeOfMutation == "inversion": l = self.two_opt(ind) return Solution(l,self.fonctionObjectif(l)) if typeOfMutation == "permutation": i = random.randint(0, n-2) j = random.randint(i+1, n-1) lst = ind.copy() lst[i],lst[j] = lst[j],lst[i] return Solution(lst,self.fonctionObjectif(lst))
def tabou(self,start): tabou = [] #Solution ltabou = [] #chemin s = self.glouton1(start) i = 0 while i != 100: i = i + 1 neighbors,fct = self.generateNeighborsTabou(s.getChemin(),ltabou) index = fct.index(min(fct)) newSol = neighbors[index] tabou.append(Solution(newSol,fct[index])) ltabou.append(newSol) s = Solution(newSol,fct[index]) lst = [tabou[j].getFct() for j in range(len(tabou))] index = lst.index(min(lst)) return tabou[index]
def recuit(self,start): T0 = 10 Tmin = 1e-2 kmax = 1e4 T = T0 k = 0 s = self.glouton1(start).getChemin() # calcul de l'énergie initiale du système (la distance initiale à minimiser) Ec = self.fonctionObjectif(s) N = len(s) while T > Tmin: # choix de deux villes différentes au hasard i = random.randint(1,N-1) j = random.randint(1,N -1) if i == j: continue # création de la fluctuation et mesure de l'énergie s = self.fluctuation(s,i,j) Ef = self.fonctionObjectif(s) Ec, s = self.metropolis(s,T,Ef,Ec,i,j) # application de la loi de refroidissement k += 1 T = T0*np.exp(-k/kmax) return Solution(s,self.fonctionObjectif(s))
def mutation(self, ind, fct, typeOfMutation): n = len(ind) if typeOfMutation == "descente": return self.descenteVNS(Solution(ind, fct)) if typeOfMutation == "permutation": i = random.randint(0, n - 2) j = random.randint(i + 1, n - 1) lst = ind.copy() lst[i], lst[j] = lst[j], lst[i] while self.poids(lst) > self.capacite: i = random.randint(0, n - 2) j = random.randint(i + 1, n - 1) lst = ind.copy() lst[i], lst[j] = lst[j], lst[i] return Solution(lst, self.fctObj(lst))
def test_case1(self): testclass = Solution.Solution() spec = Solution.TreeNode(5) spec.left = Solution.TreeNode(2) spec.right = Solution.TreeNode(-3) #testclass.findFrequentTreeSum(spec) self.assertEqual(testclass.findFrequentTreeSum(spec), [2, -3, 4])
def runIteration(self): if self.current_temperature > 1.0: # Create a new solution depending on the current solution, # i.e. a neighbour neighbour = Solution( self.objective_function, 1, # Minimisation self.getRandomNeighbour(self.current_solution)) # Get its energy (cost function) self.getEnergy(neighbour) # Accept the neighbour or not depending on the acceptance probability if self.acceptanceProbability( neighbour.getObjective()) > self.system_random.uniform( 0, 1): self.current_solution = copy.deepcopy(neighbour) # The neighbour is better thant the current element if self.best_solution.getObjective( ) > self.current_solution.getObjective(): self.best_solution = copy.deepcopy(self.current_solution) # Log the current states self.logCurrentState() # Cool the system self.current_temperature = self.cooling_schedule()
def setSolution(self, end, iterations, branchingSum, expandedNodes, visited, time_elapsed): itr = self.end path = [] c = 0 while True: if itr: path.append(itr) itr = itr.getFather() else: path.reverse() if(len(path) == 1 and end == path[0]): path.pop() cost = 0 for j in range(0, len(path)-1): for i in range(0, len(self.graph[path[j]])): if self.graph[path[j]][i][0] == path[j + 1]: cost = cost + self.graph[path[j]][i][1] if iterations == 0: branchFactor = 0 else: branchFactor = branchingSum/iterations self.solution = Solution(path, cost, expandedNodes, branchFactor, len(visited), time_elapsed, iterations) break return self.solution
def main(): root = TreeNode(1) root.left = TreeNode(2) root.left.left = TreeNode(3) root.left.right = TreeNode(4) root.right = TreeNode(5) root.right.right = TreeNode(6) solution = Solution() solution.flatten(root) printFlattenTree(root) print '----' root2 = TreeNode(1) solution.flatten(root2) printFlattenTree(root2) print '----' root3 = TreeNode(1) root3.right = TreeNode(2) root3.right.left = TreeNode(3) root3.right.right = TreeNode(4) root3.right.right.right = TreeNode(5) solution.flatten(root3) printFlattenTree(root3) print '----' solution.flatten(None) printFlattenTree(None)
def main(): with open('testcase.txt', "r") as f: lines = f.readlines() i = 0 passall = True while i < len(lines) : line = lines[i] nums = stringToIntegerList(line) if (nums == "null") : nums = None #print nums line = lines[i+1] #print line expected = int(line.replace("\n","")) ret = Solution.Solution().singleNumber(nums) #print expected #print ret if (expected != ret) : if (nums is None) : strnums = 'null' else: strnums = integerListToString(nums) print "[Fail]" + strnums + ";" + str(ret) + ";" + str(expected) passall = False break i = i + 2 #print out if passall == True : print "[Success]Your solution passed all " + str(len(lines)/2) + " test cases!"
def Create_Solution(App, Row, Col, Unrolling_Vec, Blocking_Vec, IO_Buffers, DFG_Lat): Possible_Solution = Solution() Possible_Solution.Loop_Vec = Get_Loop_Vec(App) Possible_Solution.SCGRA_Row = Row Possible_Solution.SCGRA_Col = Col Possible_Solution.SCGRA_Size = Row * Col Possible_Solution.Loop_Unrolling_Vec = copy.copy(Unrolling_Vec) Possible_Solution.DFG_Lat = DFG_Lat Possible_Solution.In_Buffer = IO_Buffers[0] Possible_Solution.Out_Buffer = IO_Buffers[1] Possible_Solution.In_Addr_Buffer = IO_Buffers[2] Possible_Solution.Out_Addr_Buffer = IO_Buffers[3] Possible_Solution.Inst_Mem = Get_Min_Inst_Mem(DFG_Lat) Possible_Solution.Loop_Blocking_Vec = copy.copy(Blocking_Vec) Possible_Solution.Update_HW_Cost() DFG_Num = Get_SB_Num(Unrolling_Vec, Blocking_Vec) Block_Num = Get_SB_Num(Blocking_Vec, Get_Loop_Vec(App)) Loop_Transfer_Vec = Get_Loop_Transfer_Vec(App, Unrolling_Vec, Blocking_Vec) Possible_Solution.Update_Lat(DFG_Num, Block_Num, Loop_Transfer_Vec) Possible_Solution.Update_Power() Possible_Solution.Update_EDP() Solution_Str = Possible_Solution.Get_Syllabus() return Possible_Solution
def __init__(self): self.design = Solution.Solution() self.design.convert_design_to_string() self.design.save_current_design_as_input() self.design.evaluate_design() self.candidate_design = copy.deepcopy(self.design)
def geneticAlgorithm(self,mutationType): p0 = self.generatePopulation() p = p0 t = 0 while t != 50: crossOverList = self.selectAnyType(p[0], p[1], "crossOver") b = len(crossOverList[0]) childs = [] for i in range(0,len(crossOverList[0])-1,2): childs.append(self.crossOver(crossOverList[0][i], crossOverList[0][i+1])[0]) childs.append(self.crossOver(crossOverList[0][i], crossOverList[0][i+1])[1]) mutationList = self.selectAnyType(p[0], p[1], "mutation") a = len(mutationList[0]) # print("before adding mut " + str(p[0])) for i in range(a): mutated = self.mutation(mutationList[0][i], mutationList[1][i], mutationType) p[0].append(mutated.getChemin()) p[1].append(mutated.getFct()) for i in range(b): p[0].append(childs[i]) p[1].append(self.fonctionObjectif(childs[i])) p = self.selectAnyType(p[0], p[1]) t += 1 index = p[1].index(min(p[1])) return Solution(p[0][index], p[1][index])
def greedy(self,r): for i in range(len(C)): l = Solution([Population.CO[i]]) l.seed_greedy(0,r) self.pop.append(l) self.pop.sort(key = lambda l : l.dis) self.rm_dup()
def Vk(self, s, k): if k == 0: x0 = self.hamming1(s.getInstance()) while self.poids(x0) > self.capacite: x0 = self.hamming1(s.getInstance()) return Solution(x0, self.fctObj(x0)) if k == 1: x1 = self.hamming2(s.getInstance()) while self.poids(x1) > self.capacite: x1 = self.hamming1(s.getInstance()) return Solution(x1, self.fctObj(x1)) if k == 2: x2 = self.hamming3(s.getInstance()) while self.poids(x2) > self.capacite: x2 = self.hamming1(s.getInstance()) return Solution(x2, self.fctObj(x2))
def mazeMaker(dim, p): finalPath = [] arr = [['0' for i in range(dim)] for j in range(dim)] arr[0][0] = "s" arr[dim-1][dim-1] = "g" count = 0 for row in arr: for i, ele in enumerate(row): if ele != "s" and ele != "g" and int(ele) == 0: if random.randrange(0, 100, 1)/100 < p: row[i] = "x" count += 1 sol = Solution(arr, (0, 0), "strat1", fireStartLoc) algoResult = sol.dfs() backtrack_info = algoResult[0] if backtrack_info != {}: finalPath = sol.create_solution(backtrack_info, (0, 0)) if finalPath == []: arr = mazeMaker(dim, p) writeGame(arr, GAMEFILE) writeGame(arr, CLEANFILE) writeGame(arr, FIREFILE) return arr
def rk4(theta0, omega0, step=0.1, stop=10, start=0, name="runge_kutta"): def omega_prime(theta): """ :return: derivative of omega with respect to time at some point theta """ return -(g / l) * theta def theta_prime(omega): """ :return: derivative of theta with respect to time at some point omega """ return omega t = np.arange(start, stop, step) n = int((stop - start)/step) omega = np.zeros(n) theta = np.zeros(n) omega[0], theta[0] = omega0, theta0 for i in range(n-1): # calculate next omega o1 = omega_prime(theta[i]) o2 = omega_prime(theta[i] + o1 * step / 2) o3 = omega_prime(theta[i] + o2 * step / 2) o4 = omega_prime(theta[i] + o3 * step) omega[i + 1] = omega[i] + (step/6)*(o1 + 2*o2 + 2*o3 + o4) # calculate next theta t1 = theta_prime(omega[i]) t2 = theta_prime(omega[i] + t1 * step / 2) t3 = theta_prime(omega[i] + t2 * step / 2) t4 = theta_prime(omega[i] + t3 * step) theta[i + 1] = theta[i] + (step/6)*(t1 + 2 * t2 + 2 * t3 + t4) # calculate energy e = 0.5*m*l*l*(omega**2 + (g/l)*theta**2) return Solution(t, theta, omega, e, name=name)
def tournament_selection_greedy(self, population, improvement_rate): parent_population = copy.deepcopy(population) offspring_population = [] for p in range(len(population)): parents = [] for i in range(Parameters.tournament_size): temp_population = [] for j in range(Parameters.tournament_size): temp_population.append(r.choice(parent_population)) #sort solutions by fitness temp_population.sort(key=lambda x: x.fitness, reverse=False) parents.append({ 'job_permutation': temp_population[0].job_permutation.copy(), 'fe_allocation': temp_population[0].fe_allocation.copy() }) #perform crossover if (r.random() < Parameters.crossover_prob): if (Parameters.crossover_type == 1): child = Crossover.one_point_crossover(parents) elif (Parameters.crossover_type == 2): child = Crossover.pmx_crossover(parents) else: print("Invalid Crossover Type") break else: if (r.random() < 0.5): child = copy.deepcopy(parents[0]) else: child = copy.deepcopy(parents[1]) child = self.Mutation.controlled_mutation_job_permutation_swap( child.copy()) #child = self.Mutation.controlled_mutation_job_permutation_insert(child.copy()) child = self.Mutation.controlled_mutation_fe_allocation( child.copy()) #estimate solution solution = Solution() solution.set_ind(child['job_permutation'].copy(), child['fe_allocation'].copy()) solution.set_lifecyles( self.init.estimate_lifecycles(child['job_permutation'].copy(), child['fe_allocation'].copy(), self.job_batch)) solution.set_capacities( self.init.get_capacities(child['fe_allocation'].copy())) solution.set_fe_schedule( self.init.get_schedules_per_fe(child['fe_allocation'].copy())) solution.set_fitness_with_improvement(self.respecitive_job_day, self.init, improvement_rate) offspring_population.append(solution) offspring_population.sort(key=lambda x: x.fitness, reverse=False) return offspring_population
def test_90(self): solution = Solution.Solution() up2 = [1, 3, 1, 2, 2] mid2 = [2, 3, 2, 3, 2] down2 = [2, 3, 2, 3, 3] col2 = [3, 1, 0, 1, 0] res2 = solution.getMaxScore(5, up2, mid2, down2, col2, 2) self.assertEqual(res2, 90)
def test_90(self): solution = Solution.Solution() up3 = [2, 3, 1, 2, 1] mid3 = [3, 1, 2, 2, 3] down3 = [3, 1, 3, 1, 3] col3 = [1, 4, 4, 3, 1] res3 = solution.getMaxScore(5, up3, mid3, down3, col3, 2) self.assertEqual(res3, 90)
def test_case1(self): # Arrange testclass = Solution.Solution() spec = '(add 1 2)' # Act & Assert self.assertEqual(testclass.evaluate(spec), 3)
def test_81(self): solution = Solution.Solution() up4 = [2, 5, 4, 5, 1] mid4 = [1, 3, 4, 3, 4] down4 = [5, 4, 2, 1, 2] col4 = [0, 3, 3, 0, 2] res4 = solution.getMaxScore(5, up4, mid4, down4, col4, 2) self.assertEqual(res4, 81)
def test_CaseI(self): T = [3, 5, 4, 7, 2, 1] myTree = Solution.Solution() root = None for i in T: data = i root = myTree.insert(root, data) self.assertEqual(myTree.levelOrderForTest(root), "3 2 5 1 4 7 ")
def test_169(self): solution = Solution.Solution() up1 = [1, 2, 1, 2, 2] mid1 = [2, 2, 1, 2, 2] down1 = [2, 2, 1, 1, 2] col1 = [0, 0, 2, 0, 4] res1 = solution.getMaxScore(5, up1, mid1, down1, col1, 2) self.assertEqual(res1, 169)
def test_694(self): solution = Solution.Solution() up1 = [2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2, 2, 2, 1, 2, 1, 2, 1, 2] mid1 = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 1] down1 = [2, 1, 1, 2, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1, 2] col1 = [1, 4, 4, 2, 3, 1, 4, 2, 3, 1, 0, 1, 0, 1, 4, 1, 2, 0, 3, 1] res1 = solution.getMaxScore(20, up1, mid1, down1, col1, 1) self.assertEqual(res1, 694)
def main(): root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(2) root.left.right = TreeNode(3) root.right.right = TreeNode(3) s = Solution() print s.isSymmetric(root)