Completed
Push — master ( fc11b6...19c9a3 )
by Andrei
02:02
created

network.__create_connection()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
"""!
2
3
@brief Neural and oscillatory network module. Consists of models of bio-inspired networks.
4
5
@authors Andrei Novikov ([email protected])
6
@date 2014-2017
7
@copyright GNU Public License
8
9
@cond GNU_PUBLIC_LICENSE
10
    PyClustering is free software: you can redistribute it and/or modify
11
    it under the terms of the GNU General Public License as published by
12
    the Free Software Foundation, either version 3 of the License, or
13
    (at your option) any later version.
14
    
15
    PyClustering is distributed in the hope that it will be useful,
16
    but WITHOUT ANY WARRANTY; without even the implied warranty of
17
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
    GNU General Public License for more details.
19
    
20
    You should have received a copy of the GNU General Public License
21
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
@endcond
23
24
"""
25
26
import math;
27
28
from enum import IntEnum;
29
30
class initial_type(IntEnum):
31
    """!
32
    @brief Enumerator of types of oscillator output initialization.
33
    
34
    """
35
    
36
    ## Output of oscillators are random in line with gaussian distribution.
37
    RANDOM_GAUSSIAN = 0;
38
    
39
    ## Output of oscillators are equidistant from each other (uniformly distributed, not randomly).
40
    EQUIPARTITION = 1;
41
42
43
class solve_type(IntEnum):
44
    """!
45
    @brief Enumerator of solver types that are used for network simulation.
46
    
47
    """
48
    
49
    ## Forward Euler first-order method.
50
    FAST = 0;                   # Usual calculation: x(k + 1) = x(k) + f(x(k)).
51
    
52
    ## Classic fourth-order Runge-Kutta method (fixed step).
53
    RK4 = 1;
54
    
55
    ## Runge-Kutta-Fehlberg method with order 4 and 5 (float step)."
56
    RKF45 = 2;
57
58
59
class conn_type(IntEnum):
60
    """!
61
    @brief Enumerator of connection types between oscillators.
62
    
63
    """
64
    
65
    ## No connection between oscillators.
66
    NONE = 0;
67
    
68
    ## All oscillators have connection with each other.
69
    ALL_TO_ALL = 1;
70
    
71
    ## Connections between oscillators represent grid where one oscillator can be connected with four neighbor oscillators: right, upper, left, lower.
72
    GRID_FOUR = 2;
73
    
74
    ## Connections between oscillators represent grid where one oscillator can be connected with eight neighbor oscillators: right, right-upper, upper, upper-left, left, left-lower, lower, lower-right.
75
    GRID_EIGHT = 3;
76
    
77
    ## Connections between oscillators represent bidirectional list.
78
    LIST_BIDIR = 4; 
79
    
80
    ## Connections are defined by user or by network during simulation.
81
    DYNAMIC = 5;
82
83
84
class conn_represent(IntEnum):
85
    """!
86
    @brief Enumerator of internal network connection representation between oscillators.
87
    
88
    """
89
    
90
    ## Each oscillator has list of his neighbors.
91
    LIST = 0;
92
    
93
    ## Connections are represented my matrix connection NxN, where N is number of oscillators.
94
    MATRIX = 1;    
95
96
97
class network:
98
    """!
99
    @brief Common network description that consists of information about oscillators and connection between them.
100
    
101
    """
102
    
103
    _num_osc = 0;
104
    
105
    __osc_conn = None;
106
    __conn_represent = None;
107
    __conn_type = None;
108
    
109
    __height = 0;
110
    __width = 0;
111
    
112
    
113
    @property
114
    def height(self):
115
        """!
116
        @brief Height of the network grid (that is defined by amout of oscillators in each column), this value is zero in case of non-grid structure.
117
        
118
        @note This property returns valid value only for network with grid structure.
119
        
120
        """
121
        return self.__height;
122
    
123
124
    @property
125
    def width(self):
126
        """!
127
        @brief Width of the network grid, this value is zero in case of non-grid structure.
128
        
129
        @note This property returns valid value only for network with grid structure.
130
        
131
        """
132
        return self.__width;
133
134
135
    @property
136
    def structure(self):
137
        """!
138
        @brief Type of network structure that is used for connecting oscillators.
139
        
140
        """        
141
        return self.__conn_type;
142
   
143
   
144
    def __init__(self, num_osc, type_conn = conn_type.ALL_TO_ALL, conn_represent = conn_represent.MATRIX, height = None, width = None):
145
        """!
146
        @brief Constructor of the network.
147
        
148
        @param[in] num_osc (uint): Number of oscillators in the network that defines size of the network.
149
        @param[in] type_conn (conn_type): Type of connections that are used in the network between oscillators.
150
        @param[in] conn_represent (conn_represent): Type of representation of connections.
151
        @param[in] height (uint): Number of oscillators in column of the network, this argument is used 
152
                    only for network with grid structure (GRID_FOUR, GRID_EIGHT), for other types this argument is ignored.
153
        @param[in] width (uint): Number of oscillotors in row of the network, this argument is used only 
154
                    for network with grid structure (GRID_FOUR, GRID_EIGHT), for other types this argument is ignored.
155
        
156
        """
157
        
158
        self._num_osc = num_osc;
159
        self.__conn_represent = conn_represent;
160
        self.__conn_type = type_conn;
161
        
162
        if ( (type_conn == conn_type.GRID_EIGHT) or (type_conn == conn_type.GRID_FOUR) ):
163
            if ( (height is not None) and (width is not None) ):
164
                self.__height = height;
165
                self.__width = width;
166
            else:
167
                side_size = self._num_osc ** (0.5);
168
                if (side_size - math.floor(side_size) > 0):
169
                    raise NameError('Invalid number of oscillators in the network in case of grid structure');
170
                
171
                self.__height = int(side_size);
172
                self.__width = self.__height;
173
        
174
            if (self.__height * self.__width != self._num_osc):
175
                raise NameError('Width (' + str(self.__width) + ') x Height (' + str(self.__height) + ') must be equal to Size (' + str(self._num_osc) + ') in case of grid structure');
176
        
177
        self._create_structure(type_conn);
178
    
179
    
180
    def __len__(self):
181
        """!
182
        @brief Returns size of the network that is defined by amount of oscillators.
183
        
184
        """
185
        return self._num_osc;
186
187
188
    def __create_connection(self, index1, index2):
189
        if (self.__conn_represent == conn_represent.MATRIX):
190
            self.__osc_conn[index1][index2] = True;
191
        else:
192
            self.__osc_conn[index1].append(index2);
193
194
195
    def __create_all_to_all_connections(self):
196
        """!
197
        @brief Creates connections between all oscillators.
198
        
199
        """
200
        
201
        if (self.__conn_represent == conn_represent.MATRIX):
202
            for index in range(0, self._num_osc, 1):
203
                self.__osc_conn.append([True] * self._num_osc);
204
                self.__osc_conn[index][index] = False;
205
        
206
        elif (self.__conn_represent == conn_represent.LIST):
207
            for index in range(0, self._num_osc, 1):
208
                self.__osc_conn.append([neigh for neigh in range(0, self._num_osc, 1) if index != neigh]); 
209
210
211
    def __create_grid_four_connections(self):
212
        """!
213
        @brief Creates network with connections that make up four grid structure.
214
        @details Each oscillator may be connected with four neighbors in line with 'grid' structure: right, upper, left, lower.
215
        
216
        """
217
        
218
        side_size = self.__width;
219
        if (self.__conn_represent == conn_represent.MATRIX):
220
            self.__osc_conn = [[0] * self._num_osc for index in range(0, self._num_osc, 1)];
221
        elif (self.__conn_represent == conn_represent.LIST):
222
            self.__osc_conn = [[] for index in range(0, self._num_osc, 1)];
223
        else:
224
            raise NameError("Unknown type of representation of connections");
225
        
226
        for index in range(0, self._num_osc, 1):
227
            upper_index = index - side_size;
228
            lower_index = index + side_size;
229
            left_index = index - 1;
230
            right_index = index + 1;
231
            
232
            node_row_index = math.ceil(index / side_size);
233
            if (upper_index >= 0):
234
                self.__create_connection(index, upper_index);
235
            
236
            if (lower_index < self._num_osc):
237
                self.__create_connection(index, lower_index);
238
            
239
            if ( (left_index >= 0) and (math.ceil(left_index / side_size) == node_row_index) ):
240
                self.__create_connection(index, left_index);
241
            
242
            if ( (right_index < self._num_osc) and (math.ceil(right_index / side_size) == node_row_index) ):
243
                self.__create_connection(index, right_index);
244
    
245
    
246
    def __create_grid_eight_connections(self):
247
        """!
248
        @brief Creates network with connections that make up eight grid structure.
249
        @details Each oscillator may be connected with eight neighbors in line with grid structure: right, right-upper, upper, upper-left, left, left-lower, lower, lower-right.
250
        
251
        """
252
        
253
        self.__create_grid_four_connections();     # create connection with right, upper, left, lower.
254
        side_size = self.__width;
255
        
256
        for index in range(0, self._num_osc, 1):
257
            upper_left_index = index - side_size - 1;
258
            upper_right_index = index - side_size + 1;
259
            
260
            lower_left_index = index + side_size - 1;
261
            lower_right_index = index + side_size + 1;
262
            
263
            node_row_index = math.floor(index / side_size);
264
            upper_row_index = node_row_index - 1;
265
            lower_row_index = node_row_index + 1;
266
            
267
            if ( (upper_left_index >= 0) and (math.floor(upper_left_index / side_size) == upper_row_index) ):
268
                self.__create_connection(index, upper_left_index);
269
            
270
            if ( (upper_right_index >= 0) and (math.floor(upper_right_index / side_size) == upper_row_index) ):
271
                self.__create_connection(index, upper_right_index);
272
                
273
            if ( (lower_left_index < self._num_osc) and (math.floor(lower_left_index / side_size) == lower_row_index) ):
274
                self.__create_connection(index, lower_left_index);
275
                
276
            if ( (lower_right_index < self._num_osc) and (math.floor(lower_right_index / side_size) == lower_row_index) ):
277
                self.__create_connection(index, lower_right_index);
278
    
279
    
280
    def __create_list_bidir_connections(self):
281
        """!
282
        @brief Creates network as bidirectional list.
283
        @details Each oscillator may be conneted with two neighbors in line with classical list structure: right, left.
284
        
285
        """
286
        
287
        if (self.__conn_represent == conn_represent.MATRIX):
288
            for index in range(0, self._num_osc, 1):
289
                self.__osc_conn.append([0] * self._num_osc);
290
                self.__osc_conn[index][index] = False;
291
                if (index > 0):
292
                    self.__osc_conn[index][index - 1] = True;
293
                    
294
                if (index < (self._num_osc - 1)):
295
                    self.__osc_conn[index][index + 1] = True;
296
        
297
        elif (self.__conn_represent == conn_represent.LIST):
298
            for index in range(self._num_osc):
299
                self.__osc_conn.append([]);
300
                if (index > 0):
301
                    self.__osc_conn[index].append(index - 1);
302
                
303
                if (index < (self._num_osc - 1)):
304
                    self.__osc_conn[index].append(index + 1);
305
    
306
    
307
    def __create_none_connections(self):
308
        """!
309
        @brief Creates network without connections.
310
        
311
        """
312
        if (self.__conn_represent == conn_represent.MATRIX):
313
            for _ in range(0, self._num_osc, 1):
314
                self.__osc_conn.append([False] * self._num_osc);   
315
        elif (self.__conn_represent == conn_represent.LIST):
316
            self.__osc_conn = [[] for _ in range(0, self._num_osc, 1)];
317
318
    
319
    def __create_dynamic_connection(self):
320
        """!
321
        @brief Prepare storage for dynamic connections.
322
        
323
        """   
324
        if (self.__conn_represent == conn_represent.MATRIX):
325
            for _ in range(0, self._num_osc, 1):
326
                self.__osc_conn.append([False] * self._num_osc);   
327
        elif (self.__conn_represent == conn_represent.LIST):
328
            self.__osc_conn = [[] for _ in range(0, self._num_osc, 1)];
329
        
330
    
331
    def _create_structure(self, type_conn = conn_type.ALL_TO_ALL):
332
        """!
333
        @brief Creates connection in line with representation of matrix connections [NunOsc x NumOsc].
334
        
335
        @param[in] type_conn (conn_type): Connection type (all-to-all, bidirectional list, grid structure, etc.) that is used by the network.
336
        
337
        """
338
        
339
        self.__osc_conn = list();
340
        
341
        if (type_conn == conn_type.NONE):
342
            self.__create_none_connections();
343
        
344
        elif (type_conn == conn_type.ALL_TO_ALL):
345
            self.__create_all_to_all_connections();
346
        
347
        elif (type_conn == conn_type.GRID_FOUR):
348
            self.__create_grid_four_connections();
349
            
350
        elif (type_conn == conn_type.GRID_EIGHT):
351
            self.__create_grid_eight_connections();
352
            
353
        elif (type_conn == conn_type.LIST_BIDIR):
354
            self.__create_list_bidir_connections();
355
        
356
        elif (type_conn == conn_type.DYNAMIC):
357
            self.__create_dynamic_connection();
358
        
359
        else:
360
            raise NameError('The unknown type of connections');
361
         
362
         
363
    def has_connection(self, i, j):
364
        """!
365
        @brief Returns True if there is connection between i and j oscillators and False - if connection doesn't exist.
366
        
367
        @param[in] i (uint): index of an oscillator in the network.
368
        @param[in] j (uint): index of an oscillator in the network.
369
        
370
        """
371
        if (self.__conn_represent == conn_represent.MATRIX):
372
            return (self.__osc_conn[i][j]);
373
        
374
        elif (self.__conn_represent == conn_represent.LIST):
375
            for neigh_index in range(0, len(self.__osc_conn[i]), 1):
376
                if (self.__osc_conn[i][neigh_index] == j):
377
                    return True;
378
            return False;
379
        
380
        else:
381
            raise NameError("Unknown type of representation of coupling");
382
    
383
    
384
    def set_connection(self, i, j):
385
        """!
386
        @brief Couples two specified oscillators in the network with dynamic connections.
387
        
388
        @param[in] i (uint): index of an oscillator that should be coupled with oscillator 'j' in the network.
389
        @param[in] j (uint): index of an oscillator that should be coupled with oscillator 'i' in the network.
390
        
391
        @note This method can be used only in case of DYNAMIC connections, otherwise it throws expection.
392
        
393
        """
394
        
395
        if (self.structure != conn_type.DYNAMIC):
396
            raise NameError("Connection between oscillators can be changed only in case of dynamic type.");
397
        
398
        if (self.__conn_represent == conn_represent.MATRIX):
399
            self.__osc_conn[i][j] = True;
400
            self.__osc_conn[j][i] = True;
401
        else:
402
            self.__osc_conn[i].append(j);
403
            self.__osc_conn[j].append(i); 
404
    
405
    
406
    def get_neighbors(self, index):
407
        """!
408
        @brief Finds neighbors of the oscillator with specified index.
409
        
410
        @param[in] index (uint): index of oscillator for which neighbors should be found in the network.
411
        
412
        @return (list) Indexes of neighbors of the specified oscillator.
413
        
414
        """
415
        
416
        if (self.__conn_represent == conn_represent.LIST):
417
            return self.__osc_conn[index];      # connections are represented by list.
418
        elif (self.__conn_represent == conn_represent.MATRIX):
419
            return [neigh_index for neigh_index in range(self._num_osc) if self.__osc_conn[index][neigh_index] == True];
420
        else:
421
            raise NameError("Unknown type of representation of connections");
422