source: framspy/evolalg/structures/individual.py @ 1320

Last change on this file since 1320 was 1289, checked in by Maciej Komosinski, 11 months ago

fitness_set_negative_to_zero boolean (a.k.a. "only positive fitness", needed for novelty and niching diversity control) becomes a command-line flag instead of a hardcoded value

File size: 2.0 KB
RevLine 
[1190]1from ..constants import BAD_FITNESS
2
3
4class Individual:
[1289]5    fitness_set_negative_to_zero = False # "static" field. Note: when using diversification techniques (e.g. niching or novelty), leaving this as False and allowing negative fitness values requires verifying/improving diversification formulas. Dividing fitness by similarity (or multiplying by diversity) may have undesired consequences when fitness can be both positive and negative (e.g. low similarity may make positive fitness values higher and negative fitness values lower, while the intention would be to improve fitness for low similarity).
[1190]6
7    def __init__(self):
8        self.genotype = None
9        # used for stats. This is raw fitness value, None = not evaluated or invalid genotype
10        self.rawfitness: float = None
11        # used in selection and can be modified e.g. by diversity or niching techniques
12        self.fitness: float = None
13
14    def copyFrom(self, individual):  # "copying constructor"
15        self.genotype = individual.genotype
16        self.rawfitness = individual.rawfitness
17        self.fitness = individual.fitness
18        return self
19
20    def copy(self):
21        new_copy = Individual()
22        new_copy.genotype = self.genotype
23        new_copy.rawfitness = self.rawfitness
24        new_copy.fitness = self.fitness
25        return new_copy
26
27    def set_and_evaluate(self, genotype, evaluate):
28        self.genotype = genotype
29        fitness = evaluate(genotype)
30        if fitness is not BAD_FITNESS:  # BAD_FITNESS indicates that the genotype was not valid or some other problem occurred during evaluation
[1289]31            if Individual.fitness_set_negative_to_zero and fitness < 0:
32                fitness = 0
[1190]33        self.fitness = self.rawfitness = fitness
34
35    def __str__(self):
36        try:
37            return "%g\t%g\t'%s'" % (self.rawfitness, self.fitness, self.genotype)
38        except:
39            return "%g\t'%s'" % (self.rawfitness, self.genotype)
40
41    def __gt__(self, other):
42        return self.rawfitness > other.rawfitness
Note: See TracBrowser for help on using the repository browser.