Ignore:
Timestamp:
08/31/22 00:05:43 (5 weeks ago)
Author:
Maciej Komosinski
Message:

More concise code and less redundancy in dissimilarity classes, added support for archive of genotypes, added hard limit on the number of genotype chars

File:
1 edited

Legend:

Unmodified
Added
Removed
  • framspy/evolalg/examples/niching_novelty.py

    r1149 r1182  
    1111from evolalg.base.lambda_step import LambdaStep
    1212from evolalg.base.step import Step
     13from evolalg.dissimilarity.archive import ArchiveDissimilarity
    1314from evolalg.dissimilarity.frams_dissimilarity import FramsDissimilarity
    1415from evolalg.dissimilarity.levenshtein import LevenshteinDissimilarity
     
    5657        description='Run this program with "python -u %s" if you want to disable buffering of its output.' % sys.argv[
    5758            0])
    58     parser.add_argument('-path', type=ensureDir, required=True, help='Path to the Framsticks library without trailing slash.')
     59    parser.add_argument('-path', type=ensureDir, required=True,
     60                        help='Path to the Framsticks library without trailing slash.')
    5961    parser.add_argument('-opt', required=True,
    6062                        help='optimization criteria: vertpos, velocity, distance, vertvel, lifespan, numjoints, numparts, numneurons, numconnections (or other as long as it is provided by the .sim file and its .expdef). For multiple criteria optimization, see multicriteria.py.')
     
    6365    parser.add_argument('-genformat', required=False, default="1",
    6466                        help='Genetic format for the demo run, for example 4, 9, or B. If not given, f1 is assumed.')
    65     parser.add_argument('-sim', required=False, default="eval-allcriteria.sim", help="Name of the .sim file with all parameter values. If you want to provide more files, separate them with a semicolon ';'.")
     67    parser.add_argument('-sim', required=False, default="eval-allcriteria.sim",
     68                        help="Name of the .sim file with all parameter values. If you want to provide more files, separate them with a semicolon ';'.")
    6669    parser.add_argument('-fit', required=False, default=Fitness.raw, type=Fitness,
    6770                        help=' Fitness criteria, default: raw', choices=list(Fitness))
    6871    parser.add_argument('-dissim', required=False, type=Dissim, default=Dissim.frams,
    6972                        help='Dissimilarity measure, default: frams', choices=list(Dissim))
    70     parser.add_argument('-knn', type=int, help="'k' value for knn-based fitness criteria (knn-niching and knn-novelty).")
     73    parser.add_argument('-knn', type=int,
     74                        help="'k' value for knn-based fitness criteria (knn-niching and knn-novelty).")
    7175    parser.add_argument('-popsize', type=int, default=50, help="Population size, default: 50.")
    7276    parser.add_argument('-generations', type=int, default=5, help="Number of generations, default: 5.")
     
    7781    parser.add_argument('-max_numneurons', type=int, default=None, help="Maximum number of Neurons. Default: no limit")
    7882    parser.add_argument('-max_numconnections', type=int, default=None, help="Maximum number of Neural connections. Default: no limit")
    79 
     83    parser.add_argument('-max_numgenochars', type=int, default=10000, help="Maximum number of characters in genotype, to disable this option set it to -1. Default: 10 000")
    8084    parser.add_argument('-hof_size', type=int, default=10, help="Number of genotypes in Hall of Fame. Default: 10.")
    81     parser.add_argument('-hof_evaluations', type=int, default=20, help="Number of final evaluations of each genotype in Hall of Fame to obtain reliable (averaged) fitness. Default: 20.")
     85    parser.add_argument('-hof_evaluations', type=int, default=20,
     86                        help="Number of final evaluations of each genotype in Hall of Fame to obtain reliable (averaged) fitness. Default: 20.")
    8287    parser.add_argument('-checkpoint_path', required=False, default=None, help="Path to the checkpoint file")
    8388    parser.add_argument('-checkpoint_interval', required=False, type=int, default=100, help="Checkpoint interval")
    8489    parser.add_argument('-debug', dest='debug', action='store_true', help="Prints names of steps as they are executed")
     90    parser.add_argument('-archive_size', type=int, default=0, help="Size of the archive size for dissimilarity calculation")
    8591    parser.set_defaults(debug=False)
    8692    return parser.parse_args()
     
    131137        return individual.numconnections > self.max_number
    132138
     139class NumCharsHigher(Remove):
     140    def __init__(self, max_number):
     141        super(NumCharsHigher, self).__init__()
     142        self.max_number = max_number
     143
     144    def remove(self, individual):
     145        return len(individual.genotype) > self.max_number
    133146
    134147class ReplaceWithHallOfFame(Step):
     
    136149        super(ReplaceWithHallOfFame, self).__init__(*args, **kwargs)
    137150        self.hof = hof
     151
    138152    def call(self, population, *args, **kwargs):
    139153        super(ReplaceWithHallOfFame, self).call(population)
     
    166180    parsed_args = parseArguments()
    167181    frams_lib = FramsticksLib(parsed_args.path, parsed_args.lib,
    168                           parsed_args.sim.split(";"))
     182                              parsed_args.sim.split(";"))
    169183    # Steps for generating first population
    170184    init_stages = [
     
    187201
    188202    fitness_raw = FitnessStep(frams_lib, fields={parsed_args.opt: "fitness_raw",
    189                                              "numparts": "numparts",
    190                                              "numjoints": "numjoints",
    191                                              "numneurons": "numneurons",
    192                                              "numconnections": "numconnections"},
     203                                                 "numparts": "numparts",
     204                                                 "numjoints": "numjoints",
     205                                                 "numneurons": "numneurons",
     206                                                 "numconnections": "numconnections"},
    193207                              fields_defaults={parsed_args.opt: None, "numparts": float("inf"),
    194208                                               "numjoints": float("inf"), "numneurons": float("inf"),
    195209                                               "numconnections": float("inf")},
    196210                              evaluation_count=1)
    197 
    198211
    199212    fitness_end = FitnessStep(frams_lib, fields={parsed_args.opt: "fitness_raw"},
     
    213226    if parsed_args.max_numconnections is not None:
    214227        remove.append(NumConnectionsHigher(parsed_args.max_numconnections))
     228    if parsed_args.max_numgenochars is not -1:
     229        remove.append(NumCharsHigher(parsed_args.max_numgenochars))
    215230
    216231    remove_step = UnionStep(remove)
     
    245260        generation_modifications.append(raw)
    246261
    247     if parsed_args.fit == Fitness.niching: # TODO reduce redundancy in the four cases below: dictionary?
     262    if parsed_args.fit == Fitness.niching:  # TODO reduce redundancy in the four cases below: dictionary?
     263
    248264        niching = UnionStep([
    249             dissim,
     265            ArchiveDissimilarity(parsed_args.archive_size, dissim),
    250266            LambdaStep(func_niching)
    251267        ])
     
    255271    if parsed_args.fit == Fitness.novelty:
    256272        novelty = UnionStep([
    257             dissim,
     273            ArchiveDissimilarity(parsed_args.archive_size, dissim),
    258274            LambdaStep(func_novelty)
    259275        ])
    260276        init_stages.append(novelty)
    261277        generation_modifications.append(novelty)
    262    
     278
    263279    if parsed_args.fit == Fitness.knn_niching:
    264280        knn_niching = UnionStep([
    265             dissim,
     281            ArchiveDissimilarity(parsed_args.archive_size, dissim),
    266282            LambdaStep(func_knn_niching)
    267283        ])
    268284        init_stages.append(knn_niching)
    269285        generation_modifications.append(knn_niching)
    270    
     286
    271287    if parsed_args.fit == Fitness.knn_novelty:
    272288        knn_novelty = UnionStep([
    273             dissim,
     289            ArchiveDissimilarity(parsed_args.archive_size, dissim),
    274290            LambdaStep(func_knn_novelty)
    275291        ])
     
    302318        fitness_end,
    303319        PopulationSave("halloffame.gen", provider=hall_of_fame.halloffame, fields={"genotype": "genotype",
    304                                                                                   "fitness": "fitness_raw"})]
     320                                                                                   "fitness": "fitness_raw"})]
    305321    # ...but custom fields can be added, e.g. "custom": "recording"
    306322
    307323    # -------------------------------------------------
    308324
    309 
    310 
    311325    # Experiment creation
    312 
    313326
    314327    experiment = Experiment(init_population=init_stages,
     
    354367
    355368
    356 
    357369if __name__ == '__main__':
    358 
    359370    main()
Note: See TracChangeset for help on using the changeset viewer.