Last change
on this file since 1235 was
1190,
checked in by Maciej Komosinski, 2 years ago
|
Added the "evolalg" module for evolutionary optimization
|
File size:
1.5 KB
|
Line | |
---|
1 | from ..constants import BAD_FITNESS |
---|
2 | |
---|
3 | |
---|
4 | class Individual: |
---|
5 | only_positive_fitness = True |
---|
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 |
---|
Note: See
TracBrowser
for help on using the repository browser.