1 | from typing import Dict, List |
---|
2 | |
---|
3 | from evolalg.base.frams_step import FramsStep |
---|
4 | from evolalg.base.individual import Individual |
---|
5 | import frams |
---|
6 | |
---|
7 | |
---|
8 | class FitnessStep(FramsStep): |
---|
9 | def __init__(self, frams_lib, fields: Dict, fields_defaults: Dict, commands: List[str] = None, |
---|
10 | vectorized: bool = True, evaluation_count=None): |
---|
11 | |
---|
12 | super().__init__(frams_lib, commands) |
---|
13 | self.fields = fields |
---|
14 | self.fields_defaults = fields_defaults |
---|
15 | self.vectorized = vectorized |
---|
16 | self.evaluation_count = evaluation_count |
---|
17 | self.evaluation_count_original = None # to be able to restore to original value after it is changed |
---|
18 | |
---|
19 | def pre(self): |
---|
20 | if self.evaluation_count is not None: |
---|
21 | self.evaluation_count_original = frams.ExpProperties.evalcount._value() # store original value and restore it in post() |
---|
22 | frams.ExpProperties.evalcount = self.evaluation_count |
---|
23 | |
---|
24 | def post(self): |
---|
25 | if self.evaluation_count is not None: |
---|
26 | frams.ExpProperties.evalcount = self.evaluation_count_original |
---|
27 | self.evaluation_count_original = None |
---|
28 | |
---|
29 | def call(self, population: List[Individual]): |
---|
30 | if self.vectorized: |
---|
31 | data = self.frams.evaluate([_.genotype for _ in population]) |
---|
32 | else: |
---|
33 | data = [self.frams.evaluate([_.genotype]) for _ in population] |
---|
34 | |
---|
35 | for ind, d in zip(population, data): |
---|
36 | for k, v in self.fields.items(): |
---|
37 | try: |
---|
38 | setattr(ind, v, d["evaluations"][""][k]) |
---|
39 | except: |
---|
40 | setattr(ind, v, self.fields_defaults[k]) |
---|
41 | return population |
---|