1 | from abc import ABC |
---|
2 | |
---|
3 | import numpy as np |
---|
4 | |
---|
5 | from evolalg.base.frams_step import FramsStep |
---|
6 | from evolalg.dissimilarity.dissimilarity import Dissimilarity |
---|
7 | |
---|
8 | |
---|
9 | class FramsDissimilarity(FramsStep): |
---|
10 | |
---|
11 | def __init__(self, frams_lib, reduction="mean", output_field="dissim", *args, **kwargs): |
---|
12 | super(FramsDissimilarity, self).__init__(frams_lib, *args, **kwargs) |
---|
13 | |
---|
14 | self.output_field = output_field |
---|
15 | self.fn_reduce = None |
---|
16 | if reduction == "mean": |
---|
17 | self.fn_reduce = np.mean |
---|
18 | elif reduction == "max": |
---|
19 | self.fn_reduce = np.max |
---|
20 | elif reduction == "min": |
---|
21 | self.fn_reduce = np.min |
---|
22 | elif reduction == "sum": |
---|
23 | self.fn_reduce = np.sum |
---|
24 | elif reduction == "none" or reduction is None: |
---|
25 | self.fn_reduce = None |
---|
26 | else: |
---|
27 | raise ValueError("Unknown reduction type. Supported: mean, max, min, sum, none") |
---|
28 | |
---|
29 | def reduce(self, dissim_matrix): |
---|
30 | if self.fn_reduce is None: |
---|
31 | return dissim_matrix |
---|
32 | return self.fn_reduce(dissim_matrix, axis=1) |
---|
33 | |
---|
34 | def call(self, population): |
---|
35 | super(FramsDissimilarity, self).call(population) |
---|
36 | if len(population) == 0: |
---|
37 | return [] |
---|
38 | dissim_matrix = self.frams.dissimilarity([_.genotype for _ in population]) |
---|
39 | dissim = self.reduce(dissim_matrix) |
---|
40 | for d,ind in zip(dissim, population): |
---|
41 | setattr(ind, self.output_field, d) |
---|
42 | return population |
---|