Completed
Push — 0.7.dev ( bfeadc...20409b )
by Andrei
01:28
created

ga_math.get_uniform()   B

Complexity

Conditions 4

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
dl 0
loc 26
rs 8.5806
c 0
b 0
f 0
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 ga_math:
6
    """
7
    """
8
9
    @staticmethod
10
    def get_centres(chromosomes, data, count_clusters):
11
        """ """
12
13
        centres = ga_math.calc_centers(chromosomes, data, count_clusters)
14
15
        return centres
16
17
    @staticmethod
18
    def calc_centers(chromosomes, data, count_clusters):
19
        """ """
20
21
        # Initialize center
22
        centers = np.zeros(shape=(len(chromosomes), count_clusters, len(data[0])))
23
24
        for _idx_chromosome in range(len(chromosomes)):
25
26
            # Get count data in clusters
27
            count_data_in_cluster = np.zeros(count_clusters)
28
29
            # Next data point
30
            for _idx in range(len(chromosomes[_idx_chromosome])):
31
32
                cluster_num = chromosomes[_idx_chromosome][_idx]
33
34
                centers[_idx_chromosome][cluster_num] += data[_idx]
35
                count_data_in_cluster[cluster_num] += 1
36
37
            for _idx_cluster in range(count_clusters):
38
                if count_data_in_cluster[_idx_cluster] != 0:
39
                    centers[_idx_chromosome][_idx_cluster] /= count_data_in_cluster[_idx_cluster]
40
41
        return centers
42
43
    @staticmethod
44
    def calc_probability_vector(fitness):
45
        """  """
46
47
        if len(fitness) == 0:
48
            raise AttributeError("Has no any fitness functions.")
49
50
        # Get 1/fitness function
51
        inv_fitness = np.zeros(len(fitness))
52
53
        #
54
        for _idx in range(len(inv_fitness)):
55
56
            if fitness[_idx] != 0.0:
57
                inv_fitness[_idx] = 1.0 / fitness[_idx]
58
            else:
59
                inv_fitness[_idx] = 0.0
60
61
        # Initialize vector
62
        prob = np.zeros(len(fitness))
63
64
        # Initialize first element
65
        prob[0] = inv_fitness[0]
66
67
        # Accumulate values in probability vector
68
        for _idx in range(1, len(inv_fitness)):
69
            prob[_idx] = prob[_idx - 1] + inv_fitness[_idx]
70
71
        # Normalize
72
        prob /= prob[-1]
73
74
        ga_math.set_last_value_to_one(prob)
75
76
        return prob
77
78
    @staticmethod
79
    def set_last_value_to_one(probabilities):
80
        """!
81
        @brief Update the last same probabilities to one.
82
        @details All values of probability list equals to the last element are set to 1.
83
        """
84
85
        # Start from the last elem
86
        back_idx = - 1
87
88
        # All values equal to the last elem should be set to 1
89
        last_val = probabilities[back_idx]
90
91
        # for all elements or if a elem not equal to the last elem
92
        for _ in range(-1, -len(probabilities) - 1):
93
            if probabilities[back_idx] == last_val:
94
                probabilities[back_idx] = 1
95
            else:
96
                break
97
98
    @staticmethod
99
    def get_uniform(probabilities):
100
        """!
101
        @brief Returns index in probabilities.
102
103
        @param[in] probabilities (list): List with segments in increasing sequence with val in [0, 1],
104
                   for example, [0 0.1 0.2 0.3 1.0].
105
        """
106
107
        # Initialize return value
108
        res_idx = None
109
110
        # Get random num in range [0, 1)
111
        random_num = np.random.rand()
112
113
        # Find segment with  val1 < random_num < val2
114
        for _idx in range(len(probabilities)):
115
            if random_num < probabilities[_idx]:
116
                res_idx = _idx
117
                break
118
119
        if res_idx is None:
120
            print('Probabilities : ', probabilities)
121
            raise AttributeError("'probabilities' should contain 1 as the end of last segment(s)")
122
123
        return res_idx
124
125