コード例 #1
0
    def __init__(self, message_target):
        ''' initializes all the wetlands. '''

        self.message_target = message_target
        self.wetlands = {}

        print 'initializing SAMOS'

        for hostname in CLIENT_FITNESS_LABELS:
            storage = hostname + '.pkl'
            print 'loading wetlands', hostname, 'from', storage
            if os.path.exists(storage):
                with open(storage, 'r') as infile:
                    wetland = pickle.load(infile)
            else:
                # creates a new wetlands if we are starting from scratch
                # sets the mutation_rate and pop_max
                wetland = genetics.Population(CLIENT_FITNESS_LABELS[hostname], mutation_rate=0.02, pop_max=50)
                with open(storage, 'w') as outfile:
                    pickle.dump(wetland, outfile)

            self.wetlands[hostname] = wetland
            env_state = wetland.get_current_state()
            self.message_target.add_to_queue("local/env_state/response", (hostname, env_state))
            self.message_target.add_to_queue("local/speech/response", (hostname, wetland.generations + 1, wetland.current_dna + 1, wetland.get_current_fitness()))
            print('current fitness', wetland.get_current_fitness())
コード例 #2
0
    def test_shortest_route(self):
        # define 10 routes each with the same x and y - shortest route would be the sequence of those routes by name
        genes = []
        route_length = 10
        for i in range(0, route_length):
            genes.append(city.City(str(i), i, i))
        pop_size = 100
        routes = []

        for i in range(0, pop_size):
            routes.append(rt.Route(random.sample(genes, len(genes))))
            
        population = gen.Population(routes, pop_size, pop_size // 2)
        fastest_route = population.survival_of_the_fittest(30)

        shortest_distance  = math.sqrt((route_length-1)**2 * 2) * 2 # (pythagoras to x,y = 10,10)

        self.assertAlmostEqual(fastest_route.get_distance(), shortest_distance)
コード例 #3
0
    def test_new_generation(self):
        city01 = city.City('01', 0, 2)
        city02 = city.City('02', 4, 5)
        city03 = city.City('03', 4, 2)
        city04 = city.City('04', 7, 3)
        city05 = city.City('05', 1, 6)
        city06 = city.City('06', 3, 2)
        city07 = city.City('07', 10, 8)
        genes = [city01, city02, city03, city04, city05, city06, city07]
        pop_size = 8
        routes = []

        for i in range(0, pop_size):
            routes.append(rt.Route(random.sample(genes, len(genes))))
            
        population = gen.Population(routes, pop_size)
        new_generation = population.breed()
        self.assertEqual(pop_size, len(new_generation))
コード例 #4
0
    def test_mating_pool(self):
        city01 = city.City('01', 0, 2)
        city02 = city.City('02', 4, 5)
        city03 = city.City('03', 4, 2)
        city04 = city.City('04', 7, 3)
        city05 = city.City('05', 1, 6)
        city06 = city.City('06', 3, 2)
        city07 = city.City('07', 10, 8)
        genes = [city01, city02, city03, city04, city05, city06, city07]
        pop_size = 8
        elite_size = 3
        routes = []

        for i in range(0, pop_size):
            routes.append(rt.Route(random.sample(genes, len(genes))))
            
        population = gen.Population(routes, pop_size, elite_size)
        mating_pool = population.create_mating_pool()
        self.assertEqual(len(mating_pool), elite_size)
コード例 #5
0
    parser.add_argument('--mutate',
                        action='store_true',
                        help='More mutations.')
    parser.add_argument('--checkpoint',
                        type=str,
                        default='checkpoint',
                        help='What name to save the results by.')
    parser.add_argument('--default_parameters',
                        action='store_true',
                        help='Evaluate just the default parameters.')
    args = parser.parse_args()

    MNIST_Experiment.train_time = args.time

    if args.default_parameters:
        default = MNIST_Experiment()
        print(default)
        print()
        print('Evaluate returned', default.evaluate())
        print(default.machine.statistics())
    else:
        population = genetics.Population(args.checkpoint, args.population)
        genetics.evolutionary_algorithm(
            MNIST_Experiment,
            population,
            mutation_probability=0.50 if args.mutate else 0.25,
            mutation_percent=0.50 if args.mutate else 0.25,
            num_processes=args.processes,
            profile=True,
        )
コード例 #6
0
        1,  # 1 = rest of list
        5,  # -1 crosspoint random
        2,  # kids to create
        "GetMates",  # TournamentGet
        0.9,  # select from top 90%
        3,  # select 3
        1  # return 1 of the selected
    ]
]

_totalGeneration = 0
_count = 0
for count in xrange(1):
    print "==== Gens:", genetics.Gen.mycount

    world = genetics.Population(10)  #population
    world.defineEvolution(tSettings)
    world.generateRandomPopulation()
    #world.calcFitness("0123456789")
    #print world.fitness(True)

    for i in range(100):  #generations
        world.calcFitness("0123456789")
        print world.fitness(True)
        if world.solved:
            break
        world.sort("fitness")
        #print world
        world.generateNewGeneration(fromCopy=False)
        world.mutate(world.nextGeneration, 0.15)
        world.setPopulationToNext()
コード例 #7
0
ファイル: eye_sp.py プロジェクト: rhyolight/HTM_experiments
    parser.add_argument('-p', '--population', type=int, default=100)
    parser.add_argument('-n', '--processes', type=int, default=6)
    parser.add_argument('--profile', action='store_true')
    args = parser.parse_args()

    RecognitionExperiment.image_cycles = args.images
    RecognitionExperiment.time_per_image = args.time

    if args.default_parameters or args.best_parameters:
        RecognitionExperiment.debug = True

        if args.default_parameters:
            indv = RecognitionExperiment()
            print("Default Parameters")
        elif args.best_parameters:
            indv = genetics.Population(args.file, 1)[0]
            print("Best of population")

        print(indv)
        print("Evaluate returned", indv.evaluate())
    else:
        population = genetics.Population(args.file, args.population)
        genetics.evolutionary_algorithm(
            RecognitionExperiment,
            population,
            mutation_probability=0.50,
            mutation_percent=0.50,
            num_processes=args.processes,
            profile=args.profile,
        )
コード例 #8
0
parser.add_argument('population_size', type=int)
parser.add_argument('--clone', type=str, default=None)
parser.add_argument('--clear_fitness', action='store_true')
parser.add_argument('--individuals', action='store_true')
parser.add_argument('--mean', action='store_true')
parser.add_argument(
    '--max_children',
    type=int,
    default=genetics.ExperimentMain.ArgumentParser().get_default(
        'max_children'))
args = parser.parse_args()

module = os.path.splitext(os.path.basename(args.program_name))[0]
exec('from ' + module + ' import *')
sys.argv[0] = args.program_name
pop = genetics.Population(args.population_name, args.population_size,
                          args.max_children)

if not len(pop):
    print("Population does not exist.")
    exit(0)

if args.individuals:
    for index, indv in reversed(tuple(enumerate(pop))):
        print("Rank %d" % (index + 1))
        print(indv)
        print()

if args.mean:
    mean = type(pop[0]).average(pop)
    print("Average of population")
    print(mean)
コード例 #9
0
ファイル: tsm.py プロジェクト: SamVanhoutte/python-musings
city07 = city.City('07', 10, 8, 3)
city08 = city.City('08', -6, 3, 8)
genes = [city01, city02, city03, city04, city05, city06, city07, city08]

# Generating cities in one straight line
genes = []
route_length = 25
for i in range(0, route_length):
    genes.append(city.City(str(i), i, i))
print ('The shortest possible distance is ',  math.sqrt((route_length-1)**2 * 2) * 2)

routes = []
for i in range(0, pop_size):
    routes.append(rt.Route(random.sample(genes, len(genes))))
    
population = gen.Population(routes, pop_size, pop_size // 3)

distances = [population.get_fittest_indivual().get_distance()]
for _ in range(0, generation_count):
    population.breed()
    # add shortest distance in route
    fastest = population.get_fittest_indivual()
    distances.append(fastest.get_distance())
    fastest.render()

plt.plot(range(0, generation_count + 1), distances)
plt.title('Distance of the path for every generation')
plt.ylabel('Distance')
plt.ylabel('Generation')
# plt.axis([0, generation_count + 1, 0, 300])
plt.show()
コード例 #10
0
import genetics
import argparse
import sys

parser = argparse.ArgumentParser()
parser.add_argument('program_name', type=str)
parser.add_argument('population_name', type=str)
parser.add_argument('population_size', type=int)
parser.add_argument('--clone', type=str, default=None)
parser.add_argument('--clear_fitness', action='store_true')
parser.add_argument('--individuals', action='store_true')
parser.add_argument('--mean', action='store_true')
args = parser.parse_args()

sys.argv[0] = args.program_name
pop = genetics.Population(args.population_name, args.population_size)

if not len(pop):
    print("Population does not exist.")
    exit(0)

if args.individuals:
    for index, indv in reversed(tuple(enumerate(pop))):
        print("Rank %d" % (index + 1))
        print(indv)
        print()

if args.mean:
    mean = type(pop[0]).average(pop)
    print("Average of population")
    print(mean)