gradient_free_optimizers.optimizers.pop_opt.genetic_algorithm   A
last analyzed

Complexity

Total Complexity 14

Size/Duplication

Total Lines 119
Duplicated Lines 47.9 %

Importance

Changes 0
Metric Value
wmc 14
eloc 88
dl 57
loc 119
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A GeneticAlgorithmOptimizer.evaluate() 0 3 1
A GeneticAlgorithmOptimizer.fittest_parents() 0 14 2
A GeneticAlgorithmOptimizer.__init__() 35 35 1
A GeneticAlgorithmOptimizer.iterate() 22 22 4
A GeneticAlgorithmOptimizer._constraint_loop() 0 5 3
A GeneticAlgorithmOptimizer.init_pos() 0 5 1
A GeneticAlgorithmOptimizer._crossover() 0 9 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
# Author: Simon Blanke
2
# Email: [email protected]
3
# License: MIT License
4
5
import random
6
import numpy as np
7
8
from ._evolutionary_algorithm import EvolutionaryAlgorithmOptimizer
9
from ._individual import Individual
10
11
12
class GeneticAlgorithmOptimizer(EvolutionaryAlgorithmOptimizer):
13
    name = "Genetic Algorithm"
14
    _name_ = "genetic_algorithm"
15
    __name__ = "GeneticAlgorithmOptimizer"
16
17
    optimizer_type = "population"
18
    computationally_expensive = False
19
20 View Code Duplication
    def __init__(
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
21
        self,
22
        search_space,
23
        initialize={"grid": 4, "random": 2, "vertices": 4},
24
        constraints=[],
25
        random_state=None,
26
        rand_rest_p=0,
27
        nth_process=None,
28
        population=10,
29
        offspring=10,
30
        crossover="discrete-recombination",
31
        n_parents=2,
32
        mutation_rate=0.5,
33
        crossover_rate=0.5,
34
    ):
35
        super().__init__(
36
            search_space=search_space,
37
            initialize=initialize,
38
            constraints=constraints,
39
            random_state=random_state,
40
            rand_rest_p=rand_rest_p,
41
            nth_process=nth_process,
42
        )
43
44
        self.population = population
45
        self.offspring = offspring
46
        self.crossover = crossover
47
        self.n_parents = n_parents
48
        self.mutation_rate = mutation_rate
49
        self.crossover_rate = crossover_rate
50
51
        self.individuals = self._create_population(Individual)
52
        self.optimizers = self.individuals
53
54
        self.offspring_l = []
55
56
    def fittest_parents(self):
57
        fittest_parents_f = 0.5
58
59
        self.sort_pop_best_score()
60
61
        n_fittest = int(len(self.pop_sorted) * fittest_parents_f)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable len does not seem to be defined.
Loading history...
62
63
        best_l = self.pop_sorted[:n_fittest]
64
        worst_l = self.pop_sorted[n_fittest:]
65
66
        if 0.01 >= random.random():
67
            best_l[random.randint(0, len(best_l) - 1)] = random.choice(worst_l)
68
69
        return best_l
70
71
    def _crossover(self):
72
        fittest_parents = self.fittest_parents()
73
        selected_parents = random.sample(fittest_parents, self.n_parents)
74
75
        for _ in range(self.offspring):
76
            parent_pos_l = [parent.pos_new for parent in selected_parents]
77
            offspring = self.discrete_recombination(parent_pos_l)
78
            offspring = self._constraint_loop(offspring)
79
            self.offspring_l.append(offspring)
80
81
    def _constraint_loop(self, position):
82
        while True:
83
            if self.conv.not_in_constraint(position):
84
                return position
85
            position = self.p_current.move_climb(position, epsilon_mod=0.3)
86
87
    @EvolutionaryAlgorithmOptimizer.track_new_pos
88
    def init_pos(self):
89
        nth_pop = self.nth_trial % len(self.individuals)
90
        self.p_current = self.individuals[nth_pop]
91
        return self.p_current.init_pos()
92
93 View Code Duplication
    @EvolutionaryAlgorithmOptimizer.track_new_pos
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
94
    def iterate(self):
95
        n_ind = len(self.individuals)
96
97
        if n_ind == 1:
98
            self.p_current = self.individuals[0]
99
            return self.p_current.iterate()
100
101
        self.sort_pop_best_score()
102
        rnd_int = random.randint(0, len(self.pop_sorted) - 1)
103
        self.p_current = self.pop_sorted[rnd_int]
104
105
        total_rate = self.mutation_rate + self.crossover_rate
106
        rand = np.random.uniform(low=0, high=total_rate)
107
108
        if rand <= self.mutation_rate:
109
            return self.p_current.iterate()
110
        else:
111
            if not self.offspring_l:
112
                self._crossover()
113
            self.p_current.pos_new = self.offspring_l.pop(0)
114
            return self.p_current.pos_new
115
116
    @EvolutionaryAlgorithmOptimizer.track_new_score
117
    def evaluate(self, score_new):
118
        self.p_current.evaluate(score_new)
119