# source:framspy/evolalg/mutation_cross/frams_cross_or_mutate.py@1113

Last change on this file since 1113 was 1113, checked in by Maciej Komosinski, 2 years ago

Added a framework for evolutionary algorithms cooperating with FramsticksLib?.py

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