def mousePressEvent(self, event): global selected_spring, focus_spring, selected_springbot global CORES # A principio libera qualquer spring e springbot selected_spring = None # verifica se selecionou algum node ou spring if self.focus_node: if mainwindow.edit_mode and event.button() == QtCore.Qt.MidButton: self.focus_node.parent.remove(self.focus_node) # Deleta todos nodes nao conectados for node in self.focus_node.parent.unconnected(): self.focus_node.parent.remove(node) # Verifica se matou springbot if len(self.focus_node.parent.nodes) == 0: mainwindow.springbots.remove(self.focus_node.parent) if self.focus_node.parent is selected_springbot: selected_springbot = random.choice( mainwindow.springbots ) if mainwindow.springbots else None self.focus_node = None else: self.selected_node = self.focus_node selected_springbot = self.focus_node.parent elif focus_spring: if mainwindow.edit_mode and event.button() == QtCore.Qt.MidButton: focus_spring.parent.remove(focus_spring) # Deleta todos nodes nao conectados for node in focus_spring.parent.unconnected(): focus_spring.parent.remove(node) focus_spring = None else: selected_spring = focus_spring selected_springbot = focus_spring.parent elif mainwindow.edit_mode and event.button() == QtCore.Qt.RightButton: # cria nodo(novo springbot) newspringbot = EvolveSpringbot(name=latimname(5)) newspringbot.cor = random.choice(CORES) self.selected_node = self.focus_node = Node(pos=(event.x(), event.y())) newspringbot.add(self.focus_node) mainwindow.springbots.append(newspringbot) selected_springbot = newspringbot self.creating = (self.selected_node and event.button() == QtCore.Qt.RightButton) self.mouse_pos = (event.x(), event.y())
def mousePressEvent (self, event): global selected_spring, focus_spring, selected_springbot global CORES # A principio libera qualquer spring e springbot selected_spring = None # verifica se selecionou algum node ou spring if self.focus_node: if mainwindow.edit_mode and event.button() == QtCore.Qt.MidButton: self.focus_node.parent.remove(self.focus_node) # Deleta todos nodes nao conectados for node in self.focus_node.parent.unconnected(): self.focus_node.parent.remove(node) # Verifica se matou springbot if len(self.focus_node.parent.nodes) == 0: mainwindow.springbots.remove(self.focus_node.parent) if self.focus_node.parent is selected_springbot: selected_springbot = random.choice(mainwindow.springbots) if mainwindow.springbots else None self.focus_node = None else: self.selected_node = self.focus_node selected_springbot = self.focus_node.parent elif focus_spring: if mainwindow.edit_mode and event.button() == QtCore.Qt.MidButton: focus_spring.parent.remove(focus_spring) # Deleta todos nodes nao conectados for node in focus_spring.parent.unconnected(): focus_spring.parent.remove(node) focus_spring = None else: selected_spring = focus_spring selected_springbot = focus_spring.parent elif mainwindow.edit_mode and event.button() == QtCore.Qt.RightButton: # cria nodo(novo springbot) newspringbot = EvolveSpringbot(name = latimname(5)) newspringbot.cor = random.choice(CORES) self.selected_node = self.focus_node = Node(pos=(event.x(), event.y())) newspringbot.add(self.focus_node) mainwindow.springbots.append(newspringbot) selected_springbot = newspringbot self.creating = (self.selected_node and event.button() == QtCore.Qt.RightButton) self.mouse_pos = (event.x(), event.y())
help="Fitness function used to evolve, default is walk", metavar="FITNESS", ) (options, args) = parser.parse_args() if not HAS_PYGAME: options.graphics = False # Load fitness function fitness = fitness.__dict__[options.fitness] options.save_freq = int(options.save_freq) options.limit = int(options.limit) options.start_at = int(options.start_at) options.prefix = options.prefix if options.prefix is not None else lower(latimname(3)) if options.verbose: print "# %s experiment." % options.prefix if len(args) == 0: readfile = sys.stdin else: readfile = args[0] # Reads the initial population init_population = load_xml(readfile) # If graphics is enabled, starts pygame if options.graphics: pygame.init() pygame.display.set_mode(
def serial_evolve( population, fitness=fitness.walk, save_freq=100, limit=-1, verbose=False, graphics=False, discard_fraction=0.4, random_insert=0.1, best=False, start_iteration=1, prefix="", ): """ Given the initial population 'population', executes a genetic algorithm to evolve them for best fitness. Saves the population each 'save_freq' interval(ordered by fitness) """ # Test if parameters are correct if discard_fraction < 0 or random_insert < 0: raise ValueError("discard_fraction and random_insert must both range from 0 to 1") elif discard_fraction + random_insert > 1: raise ValueError("the sum of discard_fraction and random_insert must not be greater than 1") iter = start_iteration # Initial iteration # Calculate amount of discarded and random population discarded = int(len(population) / 2 * discard_fraction) randoms = int(len(population) / 2 * random_insert) if verbose: print "# Initiating simulation with a population of %d specimens." % (len(population)) print "# Evolving for %s:" % (fitness.__name__) print "# At each iteration %d will be discarded, %d of the remaining will" % (discarded, discarded - randoms), print " be selected cloned and mutated and %d random springbots will be inserted" % (randoms) # Transforms population into evolvespringbots population = [EvolveSpringbot(springbot) for springbot in population] try: while population and iter != limit: if verbose: print "Iteration %d:" % (iter) z = 1 fitness_sum = 0 bloodline_len_sum = 0 # Tests fitness for each springbot for specimen in population: specimen["fitness"] = fitness(specimen, WIDTH, HEIGHT, graphics) if verbose: print '\t%d/%d: "%s"(%d) %.3f' % ( z, len(population), specimen["name"], specimen.generations(), specimen["fitness"], ) z += 1 bloodline_len_sum += specimen.generations() fitness_sum += specimen["fitness"] if verbose: print "Bloodline lenght average: %.4f" % (bloodline_len_sum / float(len(population))) print "Fitness average: %.4f" % (fitness_sum / float(len(population))) # Now Order population by its fitness population.sort(cmp=lambda A, B: cmp(A["fitness"], B["fitness"]), reverse=True) # Discards some of the worse half for specimen in sample(population[len(population) / 2 :], discarded + randoms): population.remove(specimen) # Clones and mutates some of the remaining for specimen in sample(population, discarded): child = EvolveSpringbot(specimen).mutate() child.addBloodline(specimen) names = child["name"].split() # Gives a child's name if len(names) == 1: child["name"] = names[0] + " " + latimname(2) elif len(names) == 2: child["name"] = names[0] + " " + names[1] + " " + latimname(2) elif len(names) == 3: child["name"] = names[0] + " " + names[2] + " " + latimname(2) # Incorporate children into the population population.append(child) # Incorporate randoms population += [EvolveSpringbot(random=True) for x in xrange(randoms)] # Test if it is time to save population if iter % save_freq == 0: # Saves the current population filename = "%s-%s-p%d-i%d.xml" % (prefix, fitness.__name__, len(population), iter) store_xml(population, filename) if verbose: print "# iteration %d saved into %s" % (iter, filename) # Saves best if asked if best: filename = "%s-%s-p%d-best.xml" % (prefix, fitness.__name__, len(population)) store_xml(population[:1], filename) if verbose: print "# Best of iteration %d saved into %s" % (iter, filename) # Increments iteration iter += 1 except KeyboardInterrupt: pass # Order population by its fitness population.sort(reverse=True) # Now, saves the current population and quit filename = "%s-%s-p%d-i%d.xml" % (prefix, fitness.__name__, len(population), iter) store_xml(population, filename) if verbose: print print "# iteration %d saved into %s" % (iter, filename) print "# terminating..."
def serial_evolve(population, fitness=fitness.walk, save_freq=100, limit=-1, verbose=False, graphics=False, discard_fraction=0.4, random_insert=0.1, best=False, start_iteration = 1, prefix=''): """ Given the initial population 'population', executes a genetic algorithm to evolve them for best fitness. Saves the population each 'save_freq' interval(ordered by fitness) """ # Test if parameters are correct if discard_fraction < 0 or random_insert < 0: raise ValueError("discard_fraction and random_insert must both range from 0 to 1") elif discard_fraction + random_insert > 1: raise ValueError("the sum of discard_fraction and random_insert must not be greater than 1") iter = start_iteration # Initial iteration # Calculate amount of discarded and random population discarded = int(len(population)/2 * discard_fraction) randoms = int(len(population)/2 * random_insert) if verbose: print("# Initiating simulation with a population of %d specimens." % (len(population))) print("# Evolving for %s:" % (fitness.__name__)) print("# At each iteration %d will be discarded, %d of the remaining will" % (discarded, discarded-randoms), end=' ') print(" be selected cloned and mutated and %d random springbots will be inserted" % (randoms)) # Transforms population into evolvespringbots population = [EvolveSpringbot(springbot) for springbot in population] try: while population and iter != limit: if verbose: print("Iteration %d:" % (iter)) z = 1 fitness_sum = 0 bloodline_len_sum = 0 # Tests fitness for each springbot for specimen in population: specimen['fitness'] = fitness(specimen, WIDTH, HEIGHT, graphics) if verbose: print("\t%d/%d: \"%s\"(%d) %.3f" % \ (z, len(population), specimen['name'], specimen.generations(), specimen['fitness'])) z += 1 bloodline_len_sum += specimen.generations() fitness_sum += specimen['fitness'] if verbose: print("Bloodline lenght average: %.4f" % (bloodline_len_sum/float(len(population)))) print("Fitness average: %.4f" % (fitness_sum/float(len(population)))) # Now Order population by its fitness population.sort( cmp=lambda A,B: cmp(A['fitness'], B['fitness']), reverse=True) # Discards some of the worse half for specimen in sample(population[len(population)//2:], discarded + randoms): population.remove(specimen) # Clones and mutates some of the remaining for specimen in sample(population, discarded): child = EvolveSpringbot(specimen).mutate() child.addBloodline(specimen) names = child['name'].split() # Gives a child's name if len(names) == 1: child['name'] = names[0] + " " + latimname(2) elif len(names) == 2: child['name'] = names[0] + " " + names[1] + " " + latimname(2) elif len(names) == 3: child['name'] = names[0] + " " + names[2] + " " + latimname(2) # Incorporate children into the population population.append(child) # Incorporate randoms population += [EvolveSpringbot(random=True) for x in range(randoms)] # Test if it is time to save population if iter % save_freq == 0: # Saves the current population filename = "%s-%s-p%d-i%d.xml" % (prefix, fitness.__name__, len(population), iter) store_xml(population, filename) if verbose: print("# iteration %d saved into %s" % (iter, filename)) # Saves best if asked if best: filename = "%s-%s-p%d-best.xml" % (prefix, fitness.__name__, len(population)) store_xml(population[:1], filename) if verbose: print("# Best of iteration %d saved into %s" % (iter, filename)) # Increments iteration iter += 1 except KeyboardInterrupt: pass # Order population by its fitness population.sort( cmp=lambda A,B: cmp(A['fitness'], B['fitness']), reverse=True) # Now, saves the current population and quit filename = "%s-%s-p%d-i%d.xml" % (prefix, fitness.__name__, len(population), iter) store_xml(population, filename) if verbose: print() print("# iteration %d saved into %s" % (iter, filename)) print("# terminating...")
help="Append a prefix to population file names saved, default is a random name", metavar="PREFIX") parser.add_option("-f", "--fitness", dest="fitness", default="walk", help="Fitness function used to evolve, default is walk", metavar="FITNESS") (options, args) = parser.parse_args() if not HAS_PYGAME: options.graphics = False # Load fitness function fitness = fitness.__dict__[options.fitness] options.save_freq = int(options.save_freq) options.limit = int(options.limit) options.start_at = int(options.start_at) options.prefix = options.prefix if options.prefix is not None else latimname(3).lower() if options.verbose: print("# %s experiment." % options.prefix) if len(args) == 0: readfile = sys.stdin else: readfile = args[0] # Reads the initial population init_population = load_xml(readfile) # If graphics is enabled, starts pygame if options.graphics: pygame.init() pygame.display.set_mode((WIDTH,HEIGHT), pygame.FULLSCREEN | pygame.DOUBLEBUF | pygame.HWSURFACE if options.fullscreen else pygame.DOUBLEBUF)
def network_evolve(save_freq=100, limit=-1, verbose=False, discard_fraction=0.4, random_insert=0.1, best=False, start_iteration=1, prefix=''): """ Given the initial population 'population', executes a genetic algorithm to evolve them for best fitness. Saves the population each 'save_freq' interval(ordered by fitness) """ global population, servers, fitness_function # Test if parameters are correct if discard_fraction < 0 or random_insert < 0: raise ValueError( "discard_fraction and random_insert must both range from 0 to 1") elif discard_fraction + random_insert > 1: raise ValueError( "the sum of discard_fraction and random_insert must not be greater than 1" ) iteration = start_iteration # Initial iteration # Calculate amount of discarded and random population discarded = int(len(population) / 2 * discard_fraction) randoms = int(len(population) / 2 * random_insert) if verbose: print("# Initiating simulation with a population of %d specimens..." % (len(population))) print("# Evolving for %s:" % (fitness_function)) print( "# At each iteration %d will be discarded, %d of the remaining will" % (discarded, discarded - randoms), end=' ') print( " be selected cloned and mutated and %d random springbots will be inserted" % (randoms)) # Turn all population into NetworkEvolveSpringbot population = [ NetworkEvolveSpringbot(springbot) for springbot in population ] threads = [] try: while population and iteration != limit: # (Re)load servers from file load_servers() if verbose: print("Iteration %d:" % (iteration)) fitness_sum = 0 bloodline_len_sum = 0 # Create threads threads = [FitnessThread(i) for i in range(len(population))] # Start all threads for thread in threads: thread.start() # Join(waits) all threads for thread in threads: thread.join() if verbose: specimen = population[thread.index] print("\t%d/%d: \"%s\"(%d) %.3f" % \ (thread.index+1, len(population), specimen['name'], specimen.generations(), specimen['fitness'])) bloodline_len_sum += specimen.generations() fitness_sum += specimen['fitness'] if verbose: print("Bloodline lenght average: %.4f" % (bloodline_len_sum / float(len(population)))) print("Fitness average: %.4f" % (fitness_sum / float(len(population)))) # Now Order population by its fitness population.sort(cmp=lambda A, B: cmp(A['fitness'], B['fitness']), reverse=True) # Discards some of the worse half for specimen in sample(population[len(population) // 2:], discarded + randoms): population.remove(specimen) # Clones and mutates some of the remaining half for specimen in sample(population, discarded): child = NetworkEvolveSpringbot(specimen).mutate() child.addBloodline(specimen) names = child['name'].split() # Gives a child's name if len(names) == 1: child['name'] = names[0] + " " + latimname(2) elif len(names) == 2: child['name'] = " ".join( [names[0], names[1], latimname(2)]) elif len(names) == 3: child['name'] = " ".join( [names[0], names[2], latimname(2)]) # Incorporate children into the population population.append(child) # Incorporate randoms population += [ NetworkEvolveSpringbot(random=True) for x in range(randoms) ] # Test if it is time to save population if iteration % save_freq == 0: # Saves the current population filename = "%s-%s-p%d-i%d.xml" % (prefix, fitness_function, len(population), iteration) store_xml(population, filename) if verbose: print("# iteration %d saved into %s" % (iteration, filename)) # Saves best if asked if best: filename = "%s-%s-p%d-best.xml" % (prefix, fitness_function, len(population)) store_xml(population[:1], filename) if verbose: print("# Best of iteration %d saved into %s" % (iteration, filename)) # Increments iteration iteration += 1 except KeyboardInterrupt: pass if verbose: print("# waiting for threads...") # Join(waits) all threads for thread in threads: thread.join() # Order population by its fitness population.sort(reverse=True) # Now, saves the current population and quit filename = "%s-%s-p%d-i%d.xml" % (prefix, fitness_function, len(population), iteration) store_xml(population, filename) if verbose: print() print("# iteration %d saved into %s" % (iteration, filename)) print("# terminating...")
default=None, help= "Append a prefix to population file names saved, default is a random name", metavar="PREFIX") (options, args) = parser.parse_args() # Read command line parameters serverslist = options.serverslist fitness_function = options.fitness options.save_freq = int(options.save_freq) options.limit = int(options.limit) options.start_at = int(options.start_at) options.prefix = options.prefix if options.prefix is not None else lower( latimname(3)) if options.verbose: print("# %s experiment." % options.prefix) if len(args) == 0: readfile = sys.stdin else: readfile = args[0] # Reads the initial population population = load_xml(readfile) # Starts the simulation network_evolve(save_freq=options.save_freq, limit=options.limit, verbose=options.verbose, best=options.best,
def network_evolve(save_freq=100, limit=-1, verbose=False, discard_fraction=0.4, random_insert=0.1, best=False, start_iteration = 1, prefix=''): """ Given the initial population 'population', executes a genetic algorithm to evolve them for best fitness. Saves the population each 'save_freq' interval(ordered by fitness) """ global population, servers, fitness_function # Test if parameters are correct if discard_fraction < 0 or random_insert < 0: raise ValueError("discard_fraction and random_insert must both range from 0 to 1") elif discard_fraction + random_insert > 1: raise ValueError("the sum of discard_fraction and random_insert must not be greater than 1") iteration = start_iteration # Initial iteration # Calculate amount of discarded and random population discarded = int(len(population)/2 * discard_fraction) randoms = int(len(population)/2 * random_insert) if verbose: print "# Initiating simulation with a population of %d specimens..." % (len(population)) print "# Evolving for %s:" % (fitness_function) print "# At each iteration %d will be discarded, %d of the remaining will" % ( discarded, discarded-randoms), print " be selected cloned and mutated and %d random springbots will be inserted" % ( randoms) # Turn all population into NetworkEvolveSpringbot population = [NetworkEvolveSpringbot(springbot) for springbot in population] threads = [] try: while population and iteration != limit: # (Re)load servers from file load_servers() if verbose: print "Iteration %d:" % (iteration) fitness_sum = 0 bloodline_len_sum = 0 # Create threads threads = [FitnessThread(i) for i in xrange(len(population))] # Start all threads for thread in threads: thread.start() # Join(waits) all threads for thread in threads: thread.join() if verbose: specimen = population[thread.index] print "\t%d/%d: \"%s\"(%d) %.3f" % \ (thread.index+1, len(population), specimen['name'], specimen.generations(), specimen['fitness']) bloodline_len_sum +=specimen.generations() fitness_sum += specimen['fitness'] if verbose: print "Bloodline lenght average: %.4f" % (bloodline_len_sum/float(len(population))) print "Fitness average: %.4f" % (fitness_sum/float(len(population))) # Now Order population by its fitness population.sort( cmp=lambda A,B: cmp(A['fitness'], B['fitness']), reverse=True) # Discards some of the worse half for specimen in sample(population[len(population)/2:], discarded + randoms): population.remove(specimen) # Clones and mutates some of the remaining half for specimen in sample(population, discarded): child = NetworkEvolveSpringbot(specimen).mutate() child.addBloodline(specimen) names = child['name'].split() # Gives a child's name if len(names) == 1: child['name'] = names[0] + " " + latimname(2) elif len(names) == 2: child['name'] = " ".join([names[0], names[1], latimname(2)]) elif len(names) == 3: child['name'] = " ".join([names[0], names[2], latimname(2)]) # Incorporate children into the population population.append(child) # Incorporate randoms population += [NetworkEvolveSpringbot(random=True) for x in xrange(randoms)] # Test if it is time to save population if iteration % save_freq == 0: # Saves the current population filename = "%s-%s-p%d-i%d.xml" % (prefix, fitness_function, len(population), iteration) store_xml(population, filename) if verbose: print "# iteration %d saved into %s" % (iteration, filename) # Saves best if asked if best: filename = "%s-%s-p%d-best.xml" % (prefix, fitness_function, len(population)) store_xml(population[:1], filename) if verbose: print "# Best of iteration %d saved into %s" % (iteration, filename) # Increments iteration iteration += 1 except KeyboardInterrupt: pass if verbose: print "# waiting for threads..." # Join(waits) all threads for thread in threads: thread.join() # Order population by its fitness population.sort(reverse=True) # Now, saves the current population and quit filename = "%s-%s-p%d-i%d.xml" % (prefix, fitness_function, len(population), iteration) store_xml(population, filename) if verbose: print print "# iteration %d saved into %s" % (iteration, filename) print "# terminating..."