1 | from ..constants import BAD_FITNESS |
---|
2 | |
---|
3 | |
---|
4 | class Individual: |
---|
5 | only_positive_fitness = True # Note: when using diversification techniques (e.g. niching), setting this to 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). |
---|
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 |
---|
31 | if self.only_positive_fitness: |
---|
32 | if fitness < 0: |
---|
33 | fitness = 0 |
---|
34 | self.fitness = self.rawfitness = fitness |
---|
35 | |
---|
36 | def __str__(self): |
---|
37 | try: |
---|
38 | return "%g\t%g\t'%s'" % (self.rawfitness, self.fitness, self.genotype) |
---|
39 | except: |
---|
40 | return "%g\t'%s'" % (self.rawfitness, self.genotype) |
---|
41 | |
---|
42 | def __gt__(self, other): |
---|
43 | return self.rawfitness > other.rawfitness |
---|