from springbots.springbot import store_xml from springbots.evolvespringbot import random_springbot import optparse if __name__ == "__main__": # Parses command line parser = optparse.OptionParser(description="Generate a random Springbots XML genome population") parser.add_option("-p", "--population", dest="population", default=1, help="Number of random springbots to create", metavar="NUMBER") parser.add_option("-n", "--nodes", dest="nodes_num", default=10, help="Number of nodes", metavar="NUMBER") parser.add_option("-s", "--springs", dest="springs_num", default=30, help="Number of springs", metavar="NUMBER") parser.add_option("-r", "--noderadius", dest="node_radius", default=100, help="Max distance to create new nodes", metavar="NUMBER") (options, args) = parser.parse_args() # Parses integer values options.population = int(options.population) options.springs_num = int(options.springs_num) options.nodes_num = int(options.nodes_num) options.node_radius = int(options.node_radius) # Creates a population of random springbots with the chosen parameters and # writes it to XML output store_xml(\ [random_springbot(options.nodes_num, options.springs_num, options.node_radius) \ for x in xrange(options.population)])
"--nodes", dest="nodes_num", default=10, help="Number of nodes", metavar="NUMBER") parser.add_option("-s", "--springs", dest="springs_num", default=30, help="Number of springs", metavar="NUMBER") parser.add_option("-r", "--noderadius", dest="node_radius", default=100, help="Max distance to create new nodes", metavar="NUMBER") (options, args) = parser.parse_args() # Parses integer values options.population = int(options.population) options.springs_num = int(options.springs_num) options.nodes_num = int(options.nodes_num) options.node_radius = int(options.node_radius) # Creates a population of random springbots with the chosen parameters and # writes it to XML output store_xml(\ [random_springbot(options.nodes_num, options.springs_num, options.node_radius) \ for x in range(options.population)])
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...")
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...")
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..."