source: framspy/evolalg/examples/standard.py @ 1128

Last change on this file since 1128 was 1128, checked in by Maciej Komosinski, 3 years ago

Introduced the number of generations as a command-line parameter; refactored; fixed a typo

File size: 4.1 KB
Line 
1import argparse
2import os
3import sys
4import numpy as np
5
6#TODO add new example: steadystate.py (analogous to standard.py)
7#TODO extend both standard.py and steadystate.py to support >1 criteria (using DEAP's selNSGA2() and selSPEA2())
8#TODO add comments to all examples in this directory
9#TODO add to standard.py and steadystate.py evaluating each genotype in HOF N (configurable, default 10) times when the evolution ends
10#TODO protect all examples against invalid genotypes (fill population until all genotypes are conrrectly evaluated). And maybe remove invalid.py if it overlaps with (is a subset of) other examples
11
12from FramsticksLib import FramsticksLib
13from evolalg.base.lambda_step import LambdaStep
14from evolalg.dissimilarity.frams_dissimilarity import FramsDissimilarity
15from evolalg.experiment import Experiment
16from evolalg.fitness.fitness_step import FitnessStep
17from evolalg.mutation_cross.frams_cross_and_mutate import FramsCrossAndMutate
18from evolalg.population.frams_population import FramsPopulation
19from evolalg.selection.tournament import TournamentSelection
20from evolalg.statistics.halloffame_stats import HallOfFameStatistics
21from evolalg.statistics.statistics_deap import StatisticsDeap
22from evolalg.base.union_step import UnionStep
23
24
25def ensureDir(string):
26    if os.path.isdir(string):
27        return string
28    else:
29        raise NotADirectoryError(string)
30
31
32def parseArguments():
33    parser = argparse.ArgumentParser(
34        description='Run this program with "python -u %s" if you want to disable buffering of its output.' % sys.argv[
35            0])
36    parser.add_argument('-path', type=ensureDir, required=True, help='Path to Framsticks without trailing slash.')
37    parser.add_argument('-opt', required=True,
38                        help='optimization criteria : vertpos, velocity, distance, vertvel, lifespan, numjoints, numparts, numneurons, numconnections. Single or multiple criteria.')
39    parser.add_argument('-lib', required=False, help="Filename of .so or .dll with framsticks library")
40    parser.add_argument('-genformat', required=False, default="1",
41                        help='Genetic format for the demo run, for example 4, 9, or B. If not given, f1 is assumed.')
42
43    parser.add_argument("-popsize", type=int, default=50, help="Size of population, default 50.")
44    parser.add_argument('-generations', type=int, default=5, help="Number of generations, default 5.")
45    return parser.parse_args()
46
47
48def extract_fitness(ind):
49    return ind.fitness
50
51
52def print_population_count(pop):
53    print("Current:", len(pop))
54    return pop  # Each step must return a population
55
56
57def main():
58    parsed_args = parseArguments()
59    frams = FramsticksLib(parsed_args.path, parsed_args.lib,
60                          "eval-allcriteria.sim")
61
62    hall_of_fame = HallOfFameStatistics(100, "fitness")
63    statistics_union = UnionStep([
64        hall_of_fame,
65        StatisticsDeap([
66            ("avg", np.mean),
67            ("stddev", np.std),
68            ("min", np.min),
69            ("max", np.max),
70            ("count", len)
71        ], extract_fitness)
72    ])
73
74    fitness = FitnessStep(frams, fields={parsed_args.opt: "fitness", }, fields_defaults={})
75
76    init_stages = [FramsPopulation(frams, parsed_args.genformat, 50),
77                   fitness,
78                   statistics_union]
79
80    selection = TournamentSelection(5, copy=True, fit_attr="fitness")
81
82    new_generation_steps = [
83        FramsCrossAndMutate(frams, cross_prob=0.2, mutate_prob=0.9),
84        fitness,
85    ]
86
87    generation_modifications = [
88        statistics_union
89    ]
90
91    experiment = Experiment(init_population=init_stages,
92                            selection=selection,
93                            new_generation_steps=new_generation_steps,
94                            generation_modification=generation_modifications,
95                            end_steps=[],
96                            population_size=parsed_args.popsize
97                            )
98    experiment.init()
99    experiment.run(parsed_args.generations)
100    for ind in hall_of_fame.halloffame:
101        print("%g\t%s" % (ind.fitness, ind.genotype))
102
103
104if __name__ == '__main__':
105    main()
Note: See TracBrowser for help on using the repository browser.