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

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

Introduced tournament size as a command-line parameter

File size: 4.2 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="Population size, default 50.")
44    parser.add_argument('-generations', type=int, default=5, help="Number of generations, default 5.")
45    parser.add_argument('-tournament', type=int, default=5, help="Tournament size, default 5.")
46    return parser.parse_args()
47
48
49def extract_fitness(ind):
50    return ind.fitness
51
52
53def print_population_count(pop):
54    print("Current:", len(pop))
55    return pop  # Each step must return a population
56
57
58def main():
59    parsed_args = parseArguments()
60    frams = FramsticksLib(parsed_args.path, parsed_args.lib,
61                          "eval-allcriteria.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 = FitnessStep(frams, fields={parsed_args.opt: "fitness", }, fields_defaults={})
76
77    init_stages = [FramsPopulation(frams, parsed_args.genformat, 50),
78                   fitness,
79                   statistics_union]
80
81    selection = TournamentSelection(parsed_args.tournament, copy=True, fit_attr="fitness")
82
83    new_generation_steps = [
84        FramsCrossAndMutate(frams, cross_prob=0.2, mutate_prob=0.9),
85        fitness,
86    ]
87
88    generation_modifications = [
89        statistics_union
90    ]
91
92    experiment = Experiment(init_population=init_stages,
93                            selection=selection,
94                            new_generation_steps=new_generation_steps,
95                            generation_modification=generation_modifications,
96                            end_steps=[],
97                            population_size=parsed_args.popsize
98                            )
99    experiment.init()
100    experiment.run(parsed_args.generations)
101    for ind in hall_of_fame.halloffame:
102        print("%g\t%s" % (ind.fitness, ind.genotype))
103
104
105if __name__ == '__main__':
106    main()
Note: See TracBrowser for help on using the repository browser.