Completed
Push — 0.7.dev ( 20409b...5de18e )
by
unknown
02:36
created

ga_math.get_clusters_representation()   A

Complexity

Conditions 4

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

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