source: framspy/evolalg/examples/invalid.py @ 1126

Last change on this file since 1126 was 1113, checked in by Maciej Komosinski, 4 years ago

Added a framework for evolutionary algorithms cooperating with FramsticksLib?.py

File size: 4.3 KB
Line 
1import random
2
3import argparse
4import os
5import sys
6import numpy as np
7
8from evolalg.base.lambda_step import LambdaStep
9from evolalg.experiment import Experiment
10from evolalg.fitness.fitness_step import FitnessStep
11from evolalg.mutation_cross.frams_cross_and_mutate import FramsCrossAndMutate
12from evolalg.population.frams_population import FramsPopulation
13from evolalg.repair.multistep import MultistepRepair
14from evolalg.repair.remove.field import FieldRemove
15from evolalg.selection.tournament import TournamentSelection
16from evolalg.statistics.halloffame_stats import HallOfFameStatistics
17from evolalg.statistics.statistics_deap import StatisticsDeap
18from evolalg.base.union_step import UnionStep
19from evolalg.utils.population_save import PopulationSave
20from evolalg.utils.stable_generation import StableGeneration
21from FramsticksLib import FramsticksLib
22
23
24def ensureDir(string):
25    if os.path.isdir(string):
26        return string
27    else:
28        raise NotADirectoryError(string)
29
30
31def parseArguments():
32    parser = argparse.ArgumentParser(
33        description='Run this program with "python -u %s" if you want to disable buffering of its output.' % sys.argv[
34            0])
35    parser.add_argument('-path', type=ensureDir, required=True, help='Path to Framsticks without trailing slash.')
36    # parser.add_argument('-opt', required=True,
37    #                     help='optimization criteria : vertpos, velocity, distance, vertvel, lifespan, numjoints, numparts, numneurons, numconnections. Single or multiple criteria.')
38    parser.add_argument('-lib', required=False, help="Filename of .so or .dll with framsticks library")
39    parser.add_argument('-genformat', required=False, default="1",
40                        help='Genetic format for the demo run, for example 4, 9, or B. If not given, f1 is assumed.')
41
42    parser.add_argument("-popsize", type=int, default=50, help="Size of population, default 50.")
43    return parser.parse_args()
44
45
46def extract_fitness(ind):
47    return ind.fitness
48
49
50def print_population_count(pop):
51    print("Current:",len(pop))
52    return pop # Each step must return a population
53
54
55def random_remove(pop):
56    return [_ for _ in pop if random.randint(0, 1) == 0]
57
58
59def main():
60    parsed_args = parseArguments()
61    frams_lib = FramsticksLib(parsed_args.path, parsed_args.lib, "eval-movement.sim")
62
63    hall_of_fame = HallOfFameStatistics(100, "fitness")
64    statistics_union = UnionStep([
65        hall_of_fame,
66        StatisticsDeap([
67            ("avg", np.mean),
68            ("stddev", np.std),
69            ("min", np.min),
70            ("max", np.max),
71            ("count", len)
72        ], extract_fitness)
73    ])
74
75    fitness_remove = UnionStep([
76        FitnessStep(frams_lib, fields={"velocity": "fitness", "data->recording": "recording"},
77                    fields_defaults={"velocity": None, "data->recording": None}),
78        FieldRemove("recording", None),
79        print_population_count,  # Stages can be also any Callable
80    ])
81
82    selection = TournamentSelection(5, copy=True)
83    new_generation_steps = [
84        FramsCrossAndMutate(frams_lib, cross_prob=0.2, mutate_prob=0.9),
85        fitness_remove
86    ]
87
88    generation_modifications = [
89        statistics_union  # Or niching, novelty
90    ]
91
92    init_stages = [FramsPopulation(frams_lib, parsed_args.genformat, parsed_args.popsize),
93                   fitness_remove,  # It is possible to create smaller population
94                   statistics_union]
95
96    end_steps = [PopulationSave("halloffame.gen", provider=hall_of_fame.haloffame, fields={"genotype": "genotype",
97                                                                                           "fitness": "fitness",
98                                                                                           "custom": "recording"})]
99
100    experiment = Experiment(init_population=init_stages,
101                            selection=selection,
102                            new_generation_steps=new_generation_steps,
103                            generation_modification=generation_modifications,
104                            end_steps=end_steps,
105                            population_size=parsed_args.popsize
106                            )
107    experiment.init()
108    experiment.run(3)
109    for ind in hall_of_fame.haloffame:
110        print("%g\t%s" % (ind.fitness, ind.genotype))
111
112
113if __name__ == '__main__':
114    main()
Note: See TracBrowser for help on using the repository browser.