source: framspy/evolalg/dissimilarity/archive.py @ 1182

Last change on this file since 1182 was 1182, checked in by Maciej Komosinski, 5 weeks ago

More concise code and less redundancy in dissimilarity classes, added support for archive of genotypes, added hard limit on the number of genotype chars

File size: 1.4 KB
Line 
1import copy
2from typing import Union
3
4from evolalg.base.step import Step
5from evolalg.dissimilarity.dissimilarity import Dissimilarity
6from evolalg.dissimilarity.frams_dissimilarity import FramsDissimilarity
7from evolalg.statistics.halloffame_custom import HallOfFameCustom
8
9# TODO not fully tested. Verify if works OK, in particular test adding new individuals.
10class 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
Note: See TracBrowser for help on using the repository browser.