def __init__(self, parameters): ''' Constructor of the Class ImageLearning ''' GA.__init__(self, parameters) self.rectangles = 32 self.bit = 8 self.alleles = 7 * self.bit self.population = [] self.image = np.asarray(Image.open(parameters['path_to_image'])) self.pixel_x = len(self.image[0]) self.pixel_y = len(self.image)
def main(): # Tuning based on user k_coloring = 4 nodes = 10 # Graph Generator graph = GraphGenerator(nodes) graph.printAJ() # Algorithms # Simple Backtracking print("SIMPLE BACKTRACKING") bt = Backtracking(graph, k_coloring) bt.backtracking() bt.print() # Backtracking with arc consistency print( "=========================================================================" ) print("BACKTRACKING WITH ARC CONSISTENCY") ac = ArcConsistency(graph, k_coloring) ac.backtracking() ac.print() # Backtracking with forward checking print( "=========================================================================" ) print("BACKTRACKING WITH FORWARD CHECKING") fc = ForwardChecking(graph, k_coloring) fc.backtracking() fc.print() # Local Search Genetic Algorithm print( "=========================================================================" ) print("GENETIC ALGORITHM") ga = GA(graph, k_coloring) ga.train() # Local Search Simulated Annealing print( "=========================================================================" ) print("SIMULATED ANNEALING") sa = SimulatedAnnealing(graph, k_coloring) sa.simulate()
def main(): f = open('weights', 'w') weights = GA.Run() resetPos() weightsJSON = json.dumps(weights.tolist()) f.write(weightsJSON) emitter.send(weightsJSON) print "Best Weights: ", print weights
def start_evolution(self): import pprint self.params = { 'graph': self.graph, 'start_idx': int(self.start_airport.text()), 'end_idx': int(self.destination_airport.text()), 'max_flights': int(self.max_flights.text()), 'cost_weight': int(self.cost_weight.text()), 'time_weight': int(self.time_weight.text()), 'pop_size': int(self.pop_size.text()), 'generations': int(self.generation.text()), 'mutation_rate': float(self.mutation_rate.text()), 'tournament_size': int(self.tournament_size.text()), 'elitism': bool(self.elitism.currentText()), 'dest_min': int(self.dest_min.text()), 'dest_max': int(self.dest_max.text()), } # pprint.pprint(params) self.output_of_algorithm = sys.__stdout__ GA.run_with_params(self.params) self.newwindow()
def start_evolution(self): import pprint self.params = { 'graph' : self.graph, 'start_idx' : int(self.start_airport.text()), 'end_idx' : int(self.destination_airport.text()), 'max_flights' : int(self.max_flights.text()), 'cost_weight' : int(self.cost_weight.text()), 'time_weight' : int(self.time_weight.text()), 'pop_size' : int(self.pop_size.text()), 'generations' : int(self.generation.text()), 'mutation_rate' : float(self.mutation_rate.text()), 'tournament_size' : int(self.tournament_size.text()), 'elitism' : bool(self.elitism.currentText()), 'dest_min' : int(self.dest_min.text()), 'dest_max' : int(self.dest_max.text()), } # pprint.pprint(params) self.output_of_algorithm = sys.__stdout__ GA.run_with_params(self.params) self.newwindow()
def main(): inputFileName = "medium_02_tsp.txt" outputFileName = "medium_02_tsp_computed.txt" # inputFileName = "hard_02_tsp_plain_coord.txt" # outputFileName = "hard_02_tsp_plain_coord_computed.txt" repo = FileRepository(inputFileName, outputFileName) repo.readFromFile() # repo.readFromFilePlainCoord() # initialise GA parameters gaParam = {'popSize': 100, 'noGen': 1000, 'function': fitness} ga = GA(gaParam, repo) ga.initialisation() ga.evaluation() bestChromo = ga.bestChromosome() for g in range(gaParam['noGen']): ga.oneGenerationElitism() bestChromo = ga.bestChromosome() print('Best solution in generation ' + str(g) + ' is: ' + str(bestChromo)) repo.writeToFile(str(bestChromo))
def main(): outFile, instance, method, v, t, m, l, p, o = parseInput() if method == "ga": ga = GA(instance, m, l, p, o, v) ga.evolve_CrossoverAndMutation() statistics = ga.getStatistics() solution = ga else: ip = IP(instance, t, v) ip.solveModel() statistics = ip.getStatistics() solution = ip if outFile != '': saveSolution(outFile, statistics, solution) printSolution(solution, statistics)
class GUI: def __init__(self): self.ga = GA(N = config.generationSize) self.root = tk.Tk() self.closingFlag = False def run(self): self.createWindow() def createWindow(self): self.fig = self.ga.showGAVisuals(0) self.canvas = FigureCanvasTkAgg(self.fig, master=self.root) self.dataLabel = tk.Label(self.root, text="Data", bg="black",fg="#585858",font=("Helvetica", 10),anchor=tk.W) tk.Grid.columnconfigure(self.root, 0, weight=1) tk.Grid.rowconfigure(self.root, 0, weight=1) tk.Grid.rowconfigure(self.root, 1, weight=0) self.plt_canvas = self.canvas.get_tk_widget().grid(row=0, sticky=tk.N+tk.S+tk.E+tk.W) self.plot_data = self.dataLabel.grid(row=1, sticky=tk.N+tk.S+tk.E+tk.W) self.root.overrideredirect(True) self.root.overrideredirect(False) self.root.attributes("-fullscreen", True) self.root.after(100, self.runSimulation) self.root.bind('<Escape>', self.quit) self.root.mainloop() def runSimulation(self): self.currentGenerationNumber = 0 self.simulationQueue = queue.Queue() self.signalQueue = queue.Queue() self.simulationThread = ThreadedTask(self.simulationQueue,self.ga,self.signalQueue) self.simulationThread.start() self.root.after(100, self.process_queue) def process_queue(self): try: msg = self.simulationQueue.get() # Show result of the task if needed newGen = False if type(msg) == dict: self.completedSimulations = msg["Completed Simulations"] self.generationSize = msg["Generation Size"] self.newGenerationNumber = msg["Generation Number"] self.newGenBool = msg['New Generation bool'] if self.newGenBool: print('New Generation started') newGen = True self.currentGenerationNumber +=1 self.updateFigure() self.signalQueue.put('Ready') self.root.after(100, self.process_queue) self.updateLabel() else: print(msg) except queue.Empty: self.root.after(100, self.process_queue) def updateLabel(self): info = "Generation Progress: {0}/{1}".format(self.completedSimulations,self.generationSize) if self.closingFlag: info = info + '\t\t\t' + 'CLOSING...' self.dataLabel.config(text=info) def updateFigure(self): self.fig = self.ga.showGAVisuals(self.currentGenerationNumber) self.canvas = FigureCanvasTkAgg(self.fig, master=self.root) self.plt_canvas = self.canvas.get_tk_widget().grid(row=0, sticky=tk.N+tk.S+tk.E+tk.W) self.signalQueue.put('Ready') def quit(self,event): self.closingFlag = True print('key press detected') self.signalQueue.put('Stop') print('Put stop signal in queue') self.simulationThread.join() print("Simulation Thread joined main") sys.exit() def refreshWindow(self): self.root.destroy() self.root = tk.Tk() self.createWindow()
def __init__(self): self.ga = GA(N = config.generationSize) self.root = tk.Tk() self.closingFlag = False
carte.ajouterVille(ville17) ville18 = Ville(4.047255, 48.370925, 'Troyes') carte.ajouterVille(ville18) ville19 = Ville(0.103163, 49.532415, 'Le Havre') carte.ajouterVille(ville19) ville20 = Ville(-1.495348, 49.667704, 'Cherbourg') carte.ajouterVille(ville20) ville21 = Ville(-4.494615, 48.447500, 'Brest') carte.ajouterVille(ville21) ville22 = Ville(-0.457140, 46.373545, 'Niort') carte.ajouterVille(ville22) pop = Population(carte, 50, True) print("Distance initiale : " + str(pop.getFittest().getDistance())) ga = GA(carte) pop = ga.evoluerPopulation(pop) for i in range(0, 200): pop = ga.evoluerPopulation(pop) print("Distance finale : " + str(pop.getFittest().getDistance())) meilleurePopulation = pop.getFittest() lons = [] lats = [] noms = [] for ville in meilleurePopulation.circuit: lons.append(ville.lon) lats.append(ville.lat) noms.append(ville.nom)
return "x = " + str(self.x) + "y = " + str(self.y) def getFitness(self): return self.fitness def crossbreed(self, partner): l = random() xo = (self.x + partner.x * l) / (1 + l) yo = (self.y + partner.y * l) / (1 + l) return (Tacka(xo, yo), Tacka(partner.x - xo, partner.y - yo)) def printInfo(self): print(self) def mutate(self, currentIter, allIter): if random() > 0.5: self.x + random() self.y + random() else: self.x - random() self.y - random() if __name__ == "__main__": points = [] for i in range(10): points.append(Tacka(randint(-100, 100), randint(-100, 100))) t = GA(points, 100) print(t.x, t.y)
def runSimulation(): ga = GA(N=1) ga.run()
return fitness def main(): f = open('weights', 'w') weights = GA.Run() resetPos() weightsJSON = json.dumps(weights.tolist()) f.write(weightsJSON) emitter.send(weightsJSON) print "Best Weights: ", print weights #while sup.step(timestep) != -1: #pass GA = GA(Genotype(weightNum), fitnessFun) sup = Supervisor() timestep = int(sup.getBasicTimeStep()) emitter = sup.getEmitter("emitter") robot = sup.getFromDef("Robot") rpostion = robot.getField("translation") start_pos = rpostion.getSFVec3f() rrotation = robot.getField("rotation") start_rot = rrotation.getSFRotation() main()