1 | import copy |
---|

2 | from typing import Union |
---|

3 | |
---|

4 | from evolalg_steps.base.step import Step |
---|

5 | from evolalg_steps.dissimilarity.dissimilarity import Dissimilarity |
---|

6 | from evolalg_steps.dissimilarity.frams_dissimilarity import FramsDissimilarity |
---|

7 | from evolalg_steps.statistics.halloffame_custom import HallOfFameCustom |
---|

8 | |
---|

9 | # TODO not fully tested. Verify if works OK, in particular test adding new individuals. |
---|

10 | class ArchiveDissimilarity(Step): |
---|

11 | |
---|

12 | def __init__(self, archive_size, dissim: Union[Dissimilarity, FramsDissimilarity], order="max", field="dissim"): |
---|

13 | self.name= "archive" |
---|

14 | self.archive_size = archive_size |
---|

15 | self.archive = [] |
---|

16 | self.dissim = dissim |
---|

17 | self.order = order |
---|

18 | self.field = field |
---|

19 | if self.order not in ["min", "max"]: |
---|

20 | raise ValueError("Order must be min or max") |
---|

21 | |
---|

22 | if self.archive_size < 0: |
---|

23 | raise ValueError(f"Archive size must be integer greater than or equal to 0. Got {self.archive_size}") |
---|

24 | |
---|

25 | def call(self, population): |
---|

26 | super(ArchiveDissimilarity, self).call(population) |
---|

27 | population_archive = population + self.archive |
---|

28 | population_archive = self.dissim(population_archive) |
---|

29 | |
---|

30 | population = population_archive[:len(population)] |
---|

31 | order = 1 |
---|

32 | if self.order == "max": |
---|

33 | order *= -1 |
---|

34 | sorted_archive = sorted(population_archive, key=lambda x: getattr(x, self.field) * order) |
---|

35 | self.archive = copy.deepcopy(sorted_archive[:self.archive_size]) |
---|

36 | return population |
---|