Completed
Push — 0.7.dev ( f0d749...68d2d8 )
by
unknown
01:03
created

GAMath.calc_probability_vector()   B

Complexity

Conditions 5

Size

Total Lines 34

Duplication

Lines 34
Ratio 100 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
c 1
b 0
f 0
dl 34
loc 34
rs 8.0894
1
2
import numpy as np
0 ignored issues
show
Configuration introduced by
The import numpy could not be resolved.

This can be caused by one of the following:

1. Missing Dependencies

This error could indicate a configuration issue of Pylint. Make sure that your libraries are available by adding the necessary commands.

# .scrutinizer.yml
before_commands:
    - sudo pip install abc # Python2
    - sudo pip3 install abc # Python3
Tip: We are currently not using virtualenv to run pylint, when installing your modules make sure to use the command for the correct version.

2. Missing __init__.py files

This error could also result from missing __init__.py files in your module folders. Make sure that you place one file in each sub-folder.

Loading history...
3
4
5
class GAMath:
6
    """
7
    """
8
9
    @staticmethod
10
    def get_centres(chromosomes, data, count_clusters):
11
        """ """
12
13
        # Initialize centres
14
        centres = np.zeros((len(chromosomes), count_clusters, len(data[0])))
15
16
        # Calc centers for next chromosome
17
        for _idx in range(len(chromosomes)):
18
            centres[_idx] = GAMath.calc_centers_for_chromosome(chromosomes[_idx], data, count_clusters)
19
20
        return centres
21
22
    @staticmethod
23
    def calc_centers_for_chromosome(chromosome, data, count_clusters):
24
        """ """
25
26
        # Initialize centers
27
        centers = np.zeros((count_clusters, len(data[0])))
28
29
        # Next cluster
30
        for _idx_cluster in range(count_clusters):
31
            centers[_idx_cluster] = GAMath.calc_center(chromosome, data, _idx_cluster)
32
33
        return centers
34
35
    @staticmethod
36
    def calc_center(chromosome, data, cluster_num):
37
        """ """
38
39
        # Initialize center
40
        center = np.zeros(len(data[0]))
41
42
        # Get count data in clusters
43
        count_data_in_cluster = 0
44
45
        # Next data point
46
        for _idx in range(len(chromosome)):
47
48
            # If data associated with current cluster
49
            if chromosome[_idx] == cluster_num:
50
                center += data[_idx]
51
                count_data_in_cluster += 1
52
53
        # If has no data in cluster
54
        if count_data_in_cluster == 0:
55
            return center
56
57
        # Normalize center
58
        center /= count_data_in_cluster
59
60
        return center
61
62 View Code Duplication
    @staticmethod
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
63
    def calc_probability_vector(fitness):
64
        """  """
65
66
        if len(fitness) == 0:
67
            raise AttributeError("Has no any fitness functions.")
68
69
        # Get 1/fitness function
70
        inv_fitness = np.zeros(len(fitness))
71
72
        #
73
        for _idx in range(len(inv_fitness)):
74
75
            if fitness[_idx] != 0.0:
76
                inv_fitness[_idx] = 1.0 / fitness[_idx]
77
            else:
78
                inv_fitness[_idx] = 0.0
79
80
        # Initialize vector
81
        prob = np.zeros(len(fitness))
82
83
        # Initialize first element
84
        prob[0] = inv_fitness[0]
85
86
        # Accumulate values in probability vector
87
        for _idx in range(1, len(inv_fitness)):
88
            prob[_idx] = prob[_idx - 1] + inv_fitness[_idx]
89
90
        # Normalize
91
        prob /= prob[-1]
92
93
        GAMath.set_last_value_to_one(prob)
94
95
        return prob
96
97
    @staticmethod
98
    def set_last_value_to_one(probabilities):
99
        """!
100
        @brief Update the last same probabilities to one.
101
        @details All values of probability list equals to the last element are set to 1.
102
        """
103
104
        # Start from the last elem
105
        back_idx = - 1
106
107
        # All values equal to the last elem should be set to 1
108
        last_val = probabilities[back_idx]
109
110
        # for all elements or if a elem not equal to the last elem
111
        for _idx in range(-1, -len(probabilities) - 1):
0 ignored issues
show
Unused Code introduced by
The variable _idx seems to be unused.
Loading history...
112
            if probabilities[back_idx] == last_val:
113
                probabilities[back_idx] = 1
114
            else:
115
                break
116
117
    @staticmethod
118
    def get_uniform(probabilities):
119
        """!
120
        @brief Returns index in probabilities.
121
122
        @param[in] probabilities (list): List with segments in increasing sequence with val in [0, 1],
123
                   for example, [0 0.1 0.2 0.3 1.0].
124
        """
125
126
        # Initialize return value
127
        res_idx = None
128
129
        # Get random num in range [0, 1)
130
        random_num = np.random.rand()
131
132
        # Find segment with  val1 < random_num < val2
133
        for _idx in range(len(probabilities)):
134
            if random_num < probabilities[_idx]:
135
                res_idx = _idx
136
                break
137
138
        if res_idx is None:
139
            print('Probabilities : ', probabilities)
140
            raise AttributeError("'probabilities' should contain 1 as the end of last segment(s)")
141
142
        return res_idx
143
144