1 | from evolalg.base.frams_step import FramsStep |
---|
2 | from evolalg.mutation_cross.frams_cross import FramsCross |
---|
3 | from evolalg.mutation_cross.frams_mutation import FramsMutation |
---|
4 | import random |
---|
5 | |
---|
6 | |
---|
7 | class FramsCrossOrMutate(FramsStep): |
---|
8 | def __init__(self, frams_lib, commands, cross_prob, mutate_prob, mutate_commands=None, cross_commands=None, *args, |
---|
9 | **kwargs): |
---|
10 | super().__init__(frams_lib, commands, *args, **kwargs) |
---|
11 | |
---|
12 | self.cross_prob = cross_prob |
---|
13 | self.mutate_prob = mutate_prob |
---|
14 | |
---|
15 | self.frams_mutate = FramsMutation(frams_lib, mutate_commands, 1) |
---|
16 | self.frams_cross = FramsCross(frams_lib, cross_commands, 1) |
---|
17 | |
---|
18 | def call(self, population): |
---|
19 | super(FramsCrossOrMutate, self).call(population) |
---|
20 | mutate_idx = [] |
---|
21 | cross_idx = [] |
---|
22 | for i in range(len(population)): |
---|
23 | rng = random.random() |
---|
24 | if rng < self.cross_prob: |
---|
25 | cross_idx.append(i) |
---|
26 | elif rng < self.cross_prob + self.mutate_prob: |
---|
27 | mutate_idx.append(i) |
---|
28 | |
---|
29 | mutate_ind = [population[_] for _ in mutate_idx] |
---|
30 | cross_ind = [population[_] for _ in cross_idx] |
---|
31 | |
---|
32 | if len(mutate_ind) > 0: |
---|
33 | self.frams_mutate(mutate_ind) |
---|
34 | if len(cross_idx) > 0: |
---|
35 | self.frams_cross(cross_idx) |
---|
36 | |
---|
37 | for i, ind in zip(mutate_idx, mutate_ind): |
---|
38 | population[i] = ind |
---|
39 | |
---|
40 | for i, ind in zip(cross_idx, cross_ind): |
---|
41 | population[i] = ind |
---|
42 | |
---|
43 | return population |
---|