def __synchronization_mechanism(self, amplitude, index):

sync_influence = <NUM_LIT:0.0>;<EOL>for k in range(self._num_osc):<EOL><INDENT>if self.has_connection(index, k) is True:<EOL><INDENT>amplitude_neighbor = numpy.array(self.__amplitude[k], dtype = numpy.complex128, ndmin = <NUM_LIT:1>);<EOL>sync_influence += amplitude_neighbor - amplitude;<EOL><DEDENT><DEDENT>return sync_influence * self.__coupling_strength / self._num_osc<EOL>

!
        @brief Calculate synchronization part using Kuramoto synchronization mechanism.

        @param[in] amplitude (double): Current amplitude of oscillator.
        @param[in] index (uint): Oscillator index whose synchronization influence is calculated.

        @return (double) Synchronization influence for the specified oscillator.


self.__amplitude = amplitude;<EOL>self.__time = time<EOL>

!
        @brief Constructor of Sync dynamic in frequency domain.

        @param[in] amplitude (list): Dynamic of oscillators on each step of simulation.
        @param[in] time (list): Simulation time where each time-point corresponds to amplitude-point.


return self.__amplitude<EOL>

!
        @brief (list) Returns output dynamic of the Sync network (amplitudes of each oscillator in the network) during simulation.


def extract_number_oscillations(self, index, amplitude_threshold):

return pyclustering.utils.extract_number_oscillations(self.__amplitude, index, amplitude_threshold)<EOL>

!
        @brief Extracts number of oscillations of specified oscillator.

        @param[in] index (uint): Index of oscillator whose dynamic is considered.
        @param[in] amplitude_threshold (double): Amplitude threshold when oscillation is taken into account, for example,
                    when oscillator amplitude is greater than threshold then oscillation is incremented.

        @return (uint) Number of oscillations of specified oscillator.


def _neuron_states(self, inputs, t, argv):

xi = inputs[<NUM_LIT:0>];<EOL>index = argv;<EOL>impact = self._weight[index][index] * self._outputs[index];<EOL>for i in range(<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>):<EOL><INDENT>if (self.has_connection(i, index)):<EOL><INDENT>impact += self._weight[index][i] * self._outputs[i];<EOL><DEDENT><DEDENT>x = -xi + impact;<EOL>if (xi > <NUM_LIT:1>): self._outputs_buffer[index] = <NUM_LIT:1>; <EOL>if (xi < -<NUM_LIT:1>): self._outputs_buffer[index] = -<NUM_LIT:1>;<EOL>return x<EOL>

!
        @brief Returns new value of the neuron (oscillator).

        @param[in] inputs (list): Initial values (current) of the neuron - excitatory.
        @param[in] t (double): Current time of simulation.
        @param[in] argv (tuple): Extra arguments that are not used for integration - index of the neuron.

        @return (double) New value of the neuron.


return self._states<EOL>

!
        @brief Return current states of neurons.

        @return (list) States of neurons.


self._outputs = [val for val in values];<EOL>self._outputs_buffer = [val for val in values]<EOL>

!
        @brief Sets outputs of neurons.


return len(self._dynamic)<EOL>

!
        @brief (uint) Returns number of simulation steps that are stored in dynamic.


self._states = [val for val in values]<EOL>

!
        @brief Set current states of neurons.


def _calculate_states(self, solution, t, step, int_step):

next_states = [<NUM_LIT:0>] * self._num_osc;<EOL>for index in range (<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>):            <EOL><INDENT>result = odeint(self._neuron_states, self._states[index], numpy.arange(t - step, t, int_step), (index , ));<EOL>next_states[index] = result[len(result) - <NUM_LIT:1>][<NUM_LIT:0>];<EOL><DEDENT>self._outputs = [val for val in self._outputs_buffer];<EOL>return next_states<EOL>

!
        @brief Calculates new states for neurons using differential calculus. Returns new states for neurons.

        @param[in] solution (solve_type): Type solver of the differential equation.
        @param[in] t (double): Current time of simulation.
        @param[in] step (double): Step of solution at the end of which states of oscillators should be calculated.
        @param[in] int_step (double): Step differentiation that is used for solving differential equation.

        @return (list) New states for neurons.


@staticmethod<EOL><INDENT>def show_pattern(syncpr_output_dynamic, image_height, image_width):<DEDENT>

number_pictures = len(syncpr_output_dynamic);<EOL>iteration_math_step = <NUM_LIT:1.0>;<EOL>if (number_pictures > <NUM_LIT:50>):<EOL><INDENT>iteration_math_step = number_pictures / <NUM_LIT>;<EOL>number_pictures = <NUM_LIT:50>;<EOL><DEDENT>number_cols = int(numpy.ceil(number_pictures ** <NUM_LIT:0.5>));<EOL>number_rows = int(numpy.ceil(number_pictures / number_cols));<EOL>real_index = <NUM_LIT:0>, <NUM_LIT:0>;<EOL>double_indexer = True;<EOL>if ( (number_cols == <NUM_LIT:1>) or (number_rows == <NUM_LIT:1>) ):<EOL><INDENT>real_index = <NUM_LIT:0>;<EOL>double_indexer = False;<EOL><DEDENT>(_, axarr) = plt.subplots(number_rows, number_cols);<EOL>if (number_pictures > <NUM_LIT:1>):<EOL><INDENT>plt.setp([ax for ax in axarr], visible = False);<EOL><DEDENT>iteration_display = <NUM_LIT:0.0>;<EOL>for iteration in range(len(syncpr_output_dynamic)):<EOL><INDENT>if (iteration >= iteration_display):<EOL><INDENT>iteration_display += iteration_math_step;<EOL>ax_handle = axarr;<EOL>if (number_pictures > <NUM_LIT:1>):<EOL><INDENT>ax_handle = axarr[real_index];<EOL><DEDENT>syncpr_visualizer.__show_pattern(ax_handle, syncpr_output_dynamic, image_height, image_width, iteration);<EOL>if (double_indexer is True):<EOL><INDENT>real_index = real_index[<NUM_LIT:0>], real_index[<NUM_LIT:1>] + <NUM_LIT:1>;<EOL>if (real_index[<NUM_LIT:1>] >= number_cols):<EOL><INDENT>real_index = real_index[<NUM_LIT:0>] + <NUM_LIT:1>, <NUM_LIT:0>; <EOL><DEDENT><DEDENT>else:<EOL><INDENT>real_index += <NUM_LIT:1>;<EOL><DEDENT><DEDENT><DEDENT>plt.show()<EOL>

!
        @brief Displays evolution of phase oscillators as set of patterns where the last one means final result of recognition.

        @param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr network.
        @param[in] image_height (uint): Height of the pattern (image_height * image_width should be equal to number of oscillators).
        @param[in] image_width (uint): Width of the pattern.


<EOL>for pattern in samples:<EOL><INDENT>self.__validate_pattern(pattern);<EOL><DEDENT>if (self._ccore_network_pointer is not None):<EOL><INDENT>return wrapper.syncpr_train(self._ccore_network_pointer, samples);<EOL><DEDENT>length = len(self);<EOL>number_samples = len(samples);<EOL>for i in range(length):<EOL><INDENT>for j in range(i + <NUM_LIT:1>, len(self), <NUM_LIT:1>):<EOL><INDENT>for p in range(number_samples):<EOL><INDENT>value1 = samples[p][i];<EOL>value2 = samples[p][j];<EOL>self._coupling[i][j] += value1 * value2;<EOL><DEDENT>self._coupling[i][j] /= length;<EOL>self._coupling[j][i] = self._coupling[i][j];<EOL><DEDENT><DEDENT>

!
        @brief Trains syncpr network using Hebbian rule for adjusting strength of connections between oscillators during training.

        @param[in] samples (list): list of patterns where each pattern is represented by list of features that are equal to [-1; 1].


@staticmethod<EOL><INDENT>def animate_pattern_recognition(syncpr_output_dynamic, image_height, image_width, animation_velocity = <NUM_LIT>, title = None, save_movie = None):<DEDENT>

figure = plt.figure();<EOL>def init_frame():<EOL><INDENT>return frame_generation(<NUM_LIT:0>);<EOL><DEDENT>def frame_generation(index_dynamic):<EOL><INDENT>figure.clf();<EOL>if (title is not None):<EOL><INDENT>figure.suptitle(title, fontsize = <NUM_LIT>, fontweight = '<STR_LIT>')<EOL><DEDENT>ax1 = figure.add_subplot(<NUM_LIT>, projection='<STR_LIT>');<EOL>ax2 = figure.add_subplot(<NUM_LIT>);<EOL>dynamic = syncpr_output_dynamic.output[index_dynamic];<EOL>artist1, = ax1.plot(dynamic, [<NUM_LIT:1.0>] * len(dynamic), marker = '<STR_LIT:o>', color = '<STR_LIT>', ls = '<STR_LIT>');<EOL>artist2 = syncpr_visualizer.__show_pattern(ax2, syncpr_output_dynamic, image_height, image_width, index_dynamic);<EOL>return [ artist1, artist2 ];<EOL><DEDENT>cluster_animation = animation.FuncAnimation(figure, frame_generation, len(syncpr_output_dynamic), interval = animation_velocity, init_func = init_frame, repeat_delay = <NUM_LIT>);<EOL>if (save_movie is not None):<EOL><INDENT>plt.rcParams['<STR_LIT>'] = '<STR_LIT>';<EOL>ffmpeg_writer = animation.FFMpegWriter();<EOL>cluster_animation.save(save_movie, writer = ffmpeg_writer, fps = <NUM_LIT:15>);<EOL>

!
        @brief Shows animation of pattern recognition process that has been preformed by the oscillatory network.

        @param[in] syncpr_output_dynamic (syncpr_dynamic): Output dynamic of a syncpr network.
        @param[in] image_height (uint): Height of the pattern (image_height * image_width should be equal to number of oscillators).
        @param[in] image_width (uint): Width of the pattern.
        @param[in] animation_velocity (uint): Interval between frames in milliseconds.
        @param[in] title (string): Title of the animation that is displayed on a figure if it is specified.
        @param[in] save_movie (string): If it is specified then animation will be stored to file that is specified in this parameter.


def simulate_dynamic(self, pattern, order = <NUM_LIT>, solution = solve_type.RK4, collect_dynamic = False, step = <NUM_LIT:0.1>, int_step = <NUM_LIT>, threshold_changes = <NUM_LIT>):

self.__validate_pattern(pattern);<EOL>if (self._ccore_network_pointer is not None):<EOL><INDENT>ccore_instance_dynamic = wrapper.syncpr_simulate_dynamic(self._ccore_network_pointer, pattern, order, solution, collect_dynamic, step);<EOL>return syncpr_dynamic(None, None, ccore_instance_dynamic);<EOL><DEDENT>for i in range(<NUM_LIT:0>, len(pattern), <NUM_LIT:1>):<EOL><INDENT>if (pattern[i] > <NUM_LIT:0.0>):<EOL><INDENT>self._phases[i] = <NUM_LIT:0.0>;<EOL><DEDENT>else:<EOL><INDENT>self._phases[i] = math.pi / <NUM_LIT>;<EOL><DEDENT><DEDENT>time_counter = <NUM_LIT:0>;<EOL>previous_order = <NUM_LIT:0>;<EOL>current_order = self.__calculate_memory_order(pattern);<EOL>dyn_phase = [];<EOL>dyn_time = [];<EOL>if (collect_dynamic == True):<EOL><INDENT>dyn_phase.append(self._phases);<EOL>dyn_time.append(<NUM_LIT:0>);<EOL><DEDENT>while (current_order < order):<EOL><INDENT>self._phases = self._calculate_phases(solution, time_counter, step, int_step);<EOL>time_counter += step;<EOL>if (collect_dynamic == True):<EOL><INDENT>dyn_phase.append(self._phases);<EOL>dyn_time.append(time_counter);<EOL><DEDENT>previous_order = current_order;<EOL>current_order = self.__calculate_memory_order(pattern);<EOL>if (abs(current_order - previous_order) < threshold_changes):<EOL><INDENT>break;<EOL><DEDENT><DEDENT>if (collect_dynamic != True):<EOL><INDENT>dyn_phase.append(self._phases);<EOL>dyn_time.append(time_counter);<EOL><DEDENT>output_sync_dynamic = syncpr_dynamic(dyn_phase, dyn_time, None);<EOL>return output_sync_dynamic<EOL>

!
        @brief Performs dynamic simulation of the network until stop condition is not reached.
        @details In other words network performs pattern recognition during simulation.
                 Stop condition is defined by input argument 'order' that represents memory order, but
                 process of simulation can be stopped if convergance rate is low whose threshold is defined
                 by the argument 'threshold_changes'.

        @param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1].
        @param[in] order (double): Order of process synchronization, distributed 0..1.
        @param[in] solution (solve_type): Type of solution.
        @param[in] collect_dynamic (bool): If True - returns whole dynamic of oscillatory network, otherwise returns only last values of dynamics.
        @param[in] step (double): Time step of one iteration of simulation.
        @param[in] int_step (double): Integration step, should be less than step.
        @param[in] threshold_changes (double): Additional stop condition that helps prevent infinite simulation, defines limit of changes of oscillators between current and previous steps.

        @return (list) Dynamic of oscillatory network. If argument 'collect_dynamic' = True, than return dynamic for the whole simulation time,
                otherwise returns only last values (last step of simulation) of dynamic.

        @see simulate()
        @see simulate_static()


if (len(pattern) != len(self)):<EOL><INDENT>raise NameError('<STR_LIT>' + len(pattern) + '<STR_LIT>');<EOL><DEDENT>for feature in pattern:<EOL><INDENT>if ( (feature != -<NUM_LIT:1.0>) and (feature != <NUM_LIT:1.0>) ):<EOL><INDENT>raise NameError('<STR_LIT>' + feature + '<STR_LIT>');<EOL><DEDENT><DEDENT>

!
        @brief Validates pattern.
        @details Throws exception if length of pattern is not equal to size of the network or if it consists feature with value that are not equal to [-1; 1].

        @param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1].


def simulate(self, steps, time, pattern, solution = solve_type.RK4, collect_dynamic = True):

return self.simulate_static(steps, time, pattern, solution, collect_dynamic)<EOL>

!
        @brief Performs static simulation of syncpr oscillatory network.
        @details In other words network performs pattern recognition during simulation.

        @param[in] steps (uint): Number steps of simulations during simulation.
        @param[in] time (double): Time of simulation.
        @param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1].
        @param[in] solution (solve_type): Type of solver that should be used for simulation.
        @param[in] collect_dynamic (bool): If True - returns whole dynamic of oscillatory network, otherwise returns only last values of dynamics.

        @return (list) Dynamic of oscillatory network. If argument 'collect_dynamic' = True, than return dynamic for the whole simulation time,
                otherwise returns only last values (last step of simulation) of dynamic.

        @see simulate_dynamic()
        @see simulate_static()


if (self._ccore_network_pointer is not None):<EOL><INDENT>return wrapper.syncpr_get_size(self._ccore_network_pointer);<EOL><DEDENT>else:<EOL><INDENT>return self._num_osc;<EOL><DEDENT>

!
        @brief Returns size of the network.


for i in range(len(stimulus)):<EOL><INDENT>for j in range(i + <NUM_LIT:1>, len(stimulus)):<EOL><INDENT>weight = self.__calculate_weight(stimulus[i], stimulus[j])<EOL>self.__weights[i][j] = weight<EOL>self.__weights[j][i] = weight<EOL>self.__weights_summary[i] += weight<EOL>self.__weights_summary[j] += weight<EOL><DEDENT><DEDENT>

!
        @brief Create weight all-to-all structure between neurons in line with stimulus.

        @param[in] stimulus (list): External stimulus for the chaotic neural network.


rcParams['<STR_LIT>'] = ['<STR_LIT>']<EOL>rcParams['<STR_LIT>'] = <NUM_LIT:12><EOL>fig = plt.figure()<EOL>axes = None<EOL>if dimension == <NUM_LIT:2>:<EOL><INDENT>axes = fig.add_subplot(<NUM_LIT>)<EOL><DEDENT>elif dimension == <NUM_LIT:3>:<EOL><INDENT>axes = fig.gca(projection='<STR_LIT>')<EOL><DEDENT>surface_font = FontProperties()<EOL>surface_font.set_name('<STR_LIT>')<EOL>surface_font.set_size('<STR_LIT>')<EOL>return (fig, axes)<EOL>

!
        @brief Prepares surface for showing network structure in line with specified dimension.

        @param[in] dimension (uint): Dimension of processed data (external stimulus).

        @return (tuple) Description of surface for drawing network structure.


observation_matrix = numpy.array(cnn_output_dynamic.allocate_observation_matrix())<EOL>plt.imshow(observation_matrix.T, cmap = plt.get_cmap('<STR_LIT>'), interpolation='<STR_LIT:None>', vmin = <NUM_LIT:0.0>, vmax = <NUM_LIT:1.0>)<EOL>plt.show()<EOL>

!
        @brief Shows observation matrix as black/white blocks.
        @details This type of visualization is convenient for observing allocated clusters.

        @param[in] cnn_output_dynamic (cnn_dynamic): Output dynamic of the chaotic neural network.

        @see show_output_dynamic
        @see show_dynamic_matrix


self.__average_distance = average_neighbor_distance(stimulus, self.__amount_neighbors)<EOL>self.__weights = [ [ <NUM_LIT:0.0> for _ in range(len(stimulus)) ] for _ in range(len(stimulus)) ]<EOL>self.__weights_summary = [ <NUM_LIT:0.0> for _ in range(self.__num_osc) ]<EOL>if self.__conn_type == type_conn.ALL_TO_ALL:<EOL><INDENT>self.__create_weights_all_to_all(stimulus)<EOL><DEDENT>elif self.__conn_type == type_conn.TRIANGULATION_DELAUNAY:<EOL><INDENT>self.__create_weights_delaunay_triangulation(stimulus)<EOL><DEDENT>

!
        @brief Create weights between neurons in line with stimulus.

        @param[in] stimulus (list): External stimulus for the chaotic neural network.


self.__create_weights(stimulus)<EOL>self.__location = stimulus<EOL>dynamic = cnn_dynamic([], [])<EOL>dynamic.output.append(self.__output)<EOL>dynamic.time.append(<NUM_LIT:0>)<EOL>for step in range(<NUM_LIT:1>, steps, <NUM_LIT:1>):<EOL><INDENT>self.__output = self.__calculate_states()<EOL>dynamic.output.append(self.__output)<EOL>dynamic.time.append(step)<EOL><DEDENT>return dynamic<EOL>

!
        @brief Simulates chaotic neural network with extrnal stimulus during specified steps.
        @details Stimulus are considered as a coordinates of neurons and in line with that weights
                 are initialized.

        @param[in] steps (uint): Amount of steps for simulation.
        @param[in] stimulus (list): Stimulus that are used for simulation.

        @return (cnn_dynamic) Output dynamic of the chaotic neural network.


output = [ <NUM_LIT:0.0> for _ in range(self.__num_osc) ]<EOL>for i in range(self.__num_osc):<EOL><INDENT>output[i] = self.__neuron_evolution(i)<EOL><DEDENT>return output<EOL>

!
        @brief Calculates new state of each neuron.
        @detail There is no any assignment.

        @return (list) Returns new states (output).


return self.__num_osc<EOL>

!
        @brief Returns size of the chaotic neural network that is defined by amount of neurons.


index = <NUM_LIT:0><EOL>minimum = euclidean_distance_square(self._weights[<NUM_LIT:0>], x)<EOL>for i in range(<NUM_LIT:1>, self._size, <NUM_LIT:1>):<EOL><INDENT>candidate = euclidean_distance_square(self._weights[i], x)<EOL>if candidate < minimum:<EOL><INDENT>index = i<EOL>minimum = candidate<EOL><DEDENT><DEDENT>return index<EOL>

!
        @brief Calculates neuron winner (distance, neuron index).

        @param[in] x (list): Input pattern from the input data set, for example it can be coordinates of point.

        @return (uint) Returns index of neuron that is winner.


return self._size<EOL>

!
        @brief Returns size of the network that defines by amount of neuron in it.

        @return (uint) Size of self-organized map (amount of neurons).


<EOL>self.init_type = type_init.uniform_grid<EOL>self.init_radius = None<EOL>self.init_learn_rate = <NUM_LIT:0.1><EOL>self.adaptation_threshold = <NUM_LIT><EOL>

!
        @brief Constructor container of SOM parameters.


def __initialize_distances(self, size, location):

sqrt_distances = [ [ [] for i in range(size) ] for j in range(size) ]<EOL>for i in range(size):<EOL><INDENT>for j in range(i, size, <NUM_LIT:1>):<EOL><INDENT>dist = euclidean_distance_square(location[i], location[j])<EOL>sqrt_distances[i][j] = dist<EOL>sqrt_distances[j][i] = dist<EOL><DEDENT><DEDENT>return sqrt_distances<EOL>

!
        @brief Initialize distance matrix in SOM grid.

        @param[in] size (uint): Amount of neurons in the network.
        @param[in] location (list): List of coordinates of each neuron in the network.

        @return (list) Distance matrix between neurons in the network.


if som_state['<STR_LIT>'] is True and ccore_library.workable():<EOL><INDENT>self.__upload_dump_to_ccore(som_state['<STR_LIT:state>'])<EOL><DEDENT>else:<EOL><INDENT>self.__upload_dump_to_python(som_state['<STR_LIT:state>'])<EOL><DEDENT>

@brief Set state of SOM network that can be used to load network.


def get_density_matrix(self, surface_divider = <NUM_LIT>):

if self.__ccore_som_pointer is not None:<EOL><INDENT>self._weights = wrapper.som_get_weights(self.__ccore_som_pointer)<EOL><DEDENT>density_matrix = [[<NUM_LIT:0>] * self._cols for i in range(self._rows)]<EOL>dimension = len(self._weights[<NUM_LIT:0>])<EOL>dim_max = [ float('<STR_LIT>') ] * dimension<EOL>dim_min = [ float('<STR_LIT>') ] * dimension<EOL>for weight in self._weights:<EOL><INDENT>for index_dim in range(dimension):<EOL><INDENT>if weight[index_dim] > dim_max[index_dim]:<EOL><INDENT>dim_max[index_dim] = weight[index_dim]<EOL><DEDENT>if weight[index_dim] < dim_min[index_dim]:<EOL><INDENT>dim_min[index_dim] = weight[index_dim]<EOL><DEDENT><DEDENT><DEDENT>radius = [<NUM_LIT:0.0>] * len(self._weights[<NUM_LIT:0>])<EOL>for index_dim in range(dimension):<EOL><INDENT>radius[index_dim] = ( dim_max[index_dim] - dim_min[index_dim] ) / surface_divider<EOL><DEDENT>for point in self._data:<EOL><INDENT>for index_neuron in range(len(self)):<EOL><INDENT>point_covered = True<EOL>for index_dim in range(dimension):<EOL><INDENT>if abs(point[index_dim] - self._weights[index_neuron][index_dim]) > radius[index_dim]:<EOL><INDENT>point_covered = False<EOL>break<EOL><DEDENT><DEDENT>row = int(math.floor(index_neuron / self._cols))<EOL>col = index_neuron - row * self._cols<EOL>if point_covered is True:<EOL><INDENT>density_matrix[row][col] += <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT>return density_matrix<EOL>

!
        @brief Calculates density matrix (P-Matrix).

        @param[in] surface_divider (double): Divider in each dimension that affect radius for density measurement.

        @return (list) Density matrix (P-Matrix).

        @see get_distance_matrix()


if self.__ccore_som_pointer is not None:<EOL><INDENT>self._award = wrapper.som_get_awards(self.__ccore_som_pointer)<EOL><DEDENT>(fig, ax) = plt.subplots()<EOL>winner_matrix = [[<NUM_LIT:0>] * self._cols for i in range(self._rows)]<EOL>for i in range(self._rows):<EOL><INDENT>for j in range(self._cols):<EOL><INDENT>neuron_index = i * self._cols + j<EOL>winner_matrix[i][j] = self._award[neuron_index]<EOL>ax.text(i, j, str(winner_matrix[i][j]), va='<STR_LIT>', ha='<STR_LIT>')<EOL><DEDENT><DEDENT>ax.imshow(winner_matrix, cmap = plt.get_cmap('<STR_LIT>'), interpolation='<STR_LIT:none>')<EOL>ax.grid(True)<EOL>plt.title("<STR_LIT>")<EOL>plt.show()<EOL>

!
        @brief Show winner matrix where each element corresponds to neuron and value represents
               amount of won objects from input dataspace at the last training iteration.

        @see show_distance_matrix()


def show_network(self, awards = False, belongs = False, coupling = True, dataset = True, marker_type = '<STR_LIT:o>'):

if self.__ccore_som_pointer is not None:<EOL><INDENT>self._size = wrapper.som_get_size(self.__ccore_som_pointer)<EOL>self._weights = wrapper.som_get_weights(self.__ccore_som_pointer)<EOL>self._neighbors = wrapper.som_get_neighbors(self.__ccore_som_pointer)<EOL>self._award = wrapper.som_get_awards(self.__ccore_som_pointer)<EOL><DEDENT>dimension = len(self._weights[<NUM_LIT:0>])<EOL>fig = plt.figure()<EOL>if (dimension == <NUM_LIT:1>) or (dimension == <NUM_LIT:2>):<EOL><INDENT>axes = fig.add_subplot(<NUM_LIT>)<EOL><DEDENT>elif dimension == <NUM_LIT:3>:<EOL><INDENT>axes = fig.gca(projection='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>raise NotImplementedError('<STR_LIT>')<EOL><DEDENT>if (self._data is not None) and (dataset is True):<EOL><INDENT>for x in self._data:<EOL><INDENT>if dimension == <NUM_LIT:1>:<EOL><INDENT>axes.plot(x[<NUM_LIT:0>], <NUM_LIT:0.0>, '<STR_LIT>', ms = <NUM_LIT:30>)<EOL><DEDENT>elif dimension == <NUM_LIT:2>:<EOL><INDENT>axes.plot(x[<NUM_LIT:0>], x[<NUM_LIT:1>], '<STR_LIT>')<EOL><DEDENT>elif dimension == <NUM_LIT:3>:<EOL><INDENT>axes.scatter(x[<NUM_LIT:0>], x[<NUM_LIT:1>], x[<NUM_LIT:2>], c = '<STR_LIT:b>', marker = '<STR_LIT:.>')<EOL><DEDENT><DEDENT><DEDENT>for index in range(self._size):<EOL><INDENT>color = '<STR_LIT:g>'<EOL>if self._award[index] == <NUM_LIT:0>:<EOL><INDENT>color = '<STR_LIT:y>'<EOL><DEDENT>if dimension == <NUM_LIT:1>:<EOL><INDENT>axes.plot(self._weights[index][<NUM_LIT:0>], <NUM_LIT:0.0>, color + marker_type)<EOL>if awards:<EOL><INDENT>location = '<STR_LIT>'.format(self._award[index])<EOL>axes.text(self._weights[index][<NUM_LIT:0>], <NUM_LIT:0.0>, location, color='<STR_LIT>', fontsize = <NUM_LIT:10>)<EOL><DEDENT>if belongs and self._data is not None:<EOL><INDENT>location = '<STR_LIT>'.format(index)<EOL>axes.text(self._weights[index][<NUM_LIT:0>], <NUM_LIT:0.0>, location, color='<STR_LIT>', fontsize = <NUM_LIT:12>)<EOL>for k in range(len(self._capture_objects[index])):<EOL><INDENT>point = self._data[self._capture_objects[index][k]]<EOL>axes.text(point[<NUM_LIT:0>], <NUM_LIT:0.0>, location, color='<STR_LIT>', fontsize = <NUM_LIT:10>)<EOL><DEDENT><DEDENT><DEDENT>if dimension == <NUM_LIT:2>:<EOL><INDENT>axes.plot(self._weights[index][<NUM_LIT:0>], self._weights[index][<NUM_LIT:1>], color + marker_type)<EOL>if awards:<EOL><INDENT>location = '<STR_LIT>'.format(self._award[index])<EOL>axes.text(self._weights[index][<NUM_LIT:0>], self._weights[index][<NUM_LIT:1>], location, color='<STR_LIT>', fontsize=<NUM_LIT:10>)<EOL><DEDENT>if belongs and self._data is not None:<EOL><INDENT>location = '<STR_LIT>'.format(index)<EOL>axes.text(self._weights[index][<NUM_LIT:0>], self._weights[index][<NUM_LIT:1>], location, color='<STR_LIT>', fontsize=<NUM_LIT:12>)<EOL>for k in range(len(self._capture_objects[index])):<EOL><INDENT>point = self._data[self._capture_objects[index][k]]<EOL>axes.text(point[<NUM_LIT:0>], point[<NUM_LIT:1>], location, color='<STR_LIT>', fontsize=<NUM_LIT:10>)<EOL><DEDENT><DEDENT>if (self._conn_type != type_conn.func_neighbor) and (coupling != False):<EOL><INDENT>for neighbor in self._neighbors[index]:<EOL><INDENT>if neighbor > index:<EOL><INDENT>axes.plot([self._weights[index][<NUM_LIT:0>], self._weights[neighbor][<NUM_LIT:0>]],<EOL>[self._weights[index][<NUM_LIT:1>], self._weights[neighbor][<NUM_LIT:1>]],<EOL>'<STR_LIT:g>', linewidth=<NUM_LIT:0.5>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif dimension == <NUM_LIT:3>:<EOL><INDENT>axes.scatter(self._weights[index][<NUM_LIT:0>], self._weights[index][<NUM_LIT:1>], self._weights[index][<NUM_LIT:2>], c=color, marker=marker_type)<EOL>if (self._conn_type != type_conn.func_neighbor) and (coupling != False):<EOL><INDENT>for neighbor in self._neighbors[index]:<EOL><INDENT>if neighbor > index:<EOL><INDENT>axes.plot([self._weights[index][<NUM_LIT:0>], self._weights[neighbor][<NUM_LIT:0>]],<EOL>[self._weights[index][<NUM_LIT:1>], self._weights[neighbor][<NUM_LIT:1>]],<EOL>[self._weights[index][<NUM_LIT:2>], self._weights[neighbor][<NUM_LIT:2>]],<EOL>'<STR_LIT>', linewidth=<NUM_LIT:0.5>)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>plt.title("<STR_LIT>")<EOL>plt.grid()<EOL>plt.show()<EOL>

!
        @brief Shows neurons in the dimension of data.

        @param[in] awards (bool): If True - displays how many objects won each neuron.
        @param[in] belongs (bool): If True - marks each won object by according index of neuron-winner (only when dataset is displayed too).
        @param[in] coupling (bool): If True - displays connections between neurons (except case when function neighbor is used).
        @param[in] dataset (bool): If True - displays inputs data set.
        @param[in] marker_type (string): Defines marker that is used for dispaying neurons in the network.


dim_info = dimension_info(self._data)<EOL>step_x = dim_info.get_center()[<NUM_LIT:0>]<EOL>if self._rows > <NUM_LIT:1>: step_x = dim_info.get_width()[<NUM_LIT:0>] / (self._rows - <NUM_LIT:1>);<EOL>step_y = <NUM_LIT:0.0><EOL>if dim_info.get_dimensions() > <NUM_LIT:1>:<EOL><INDENT>step_y = dim_info.get_center()[<NUM_LIT:1>]<EOL>if self._cols > <NUM_LIT:1>: step_y = dim_info.get_width()[<NUM_LIT:1>] / (self._cols - <NUM_LIT:1>);<EOL><DEDENT>random.seed()<EOL>if init_type == type_init.uniform_grid:<EOL><INDENT>self._weights = [ [ [] for i in range(dim_info.get_dimensions()) ] for j in range(self._size)]<EOL>for i in range(self._size):<EOL><INDENT>location = self._location[i]<EOL>for dim in range(dim_info.get_dimensions()):<EOL><INDENT>if dim == <NUM_LIT:0>:<EOL><INDENT>if self._rows > <NUM_LIT:1>:<EOL><INDENT>self._weights[i][dim] = dim_info.get_minimum_coordinate()[dim] + step_x * location[dim]<EOL><DEDENT>else:<EOL><INDENT>self._weights[i][dim] = dim_info.get_center()[dim]<EOL><DEDENT><DEDENT>elif dim == <NUM_LIT:1>:<EOL><INDENT>if self._cols > <NUM_LIT:1>:<EOL><INDENT>self._weights[i][dim] = dim_info.get_minimum_coordinate()[dim] + step_y * location[dim]<EOL><DEDENT>else:<EOL><INDENT>self._weights[i][dim] = dim_info.get_center()[dim]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._weights[i][dim] = dim_info.get_center()[dim]<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif init_type == type_init.random_surface:<EOL><INDENT>self._weights = [[random.uniform(dim_info.get_minimum_coordinate()[i], dim_info.get_maximum_coordinate()[i]) for i in range(dim_info.get_dimensions())] for _ in range(self._size)]<EOL><DEDENT>elif init_type == type_init.random_centroid:<EOL><INDENT>self._weights = [[(random.random() + dim_info.get_center()[i])  for i in range(dim_info.get_dimensions())] for _ in range(self._size)]<EOL><DEDENT>else:<EOL><INDENT>self._weights = [[random.random() for i in range(dim_info.get_dimensions())] for _ in range(self._size)]<EOL><DEDENT>

!
        @brief Creates initial weights for neurons in line with the specified initialization.

        @param[in] init_type (type_init): Type of initialization of initial neuron weights (random, random in center of the input data, random distributed in data, ditributed in line with uniform grid).


if self.__ccore_som_pointer is not None:<EOL><INDENT>return wrapper.som_simulate(self.__ccore_som_pointer, input_pattern)<EOL><DEDENT>return self._competition(input_pattern)<EOL>

!
        @brief Processes input pattern (no learining) and returns index of neuron-winner.
               Using index of neuron winner catched object can be obtained using property capture_objects.

        @param[in] input_pattern (list): Input pattern.

        @return (uint) Returns index of neuron-winner.

        @see capture_objects


if self.__ccore_som_pointer is not None:<EOL><INDENT>self.__download_dump_from_ccore()<EOL>return self.__get_dump_from_python(True)<EOL><DEDENT>return self.__get_dump_from_python(False)<EOL>

@brief Returns state of SOM network that can be used to store network.


def __initialize_locations(self, rows, cols):

location = list()<EOL>for i in range(rows):<EOL><INDENT>for j in range(cols):<EOL><INDENT>location.append([float(i), float(j)])<EOL><DEDENT><DEDENT>return location<EOL>

!
        @brief Initialize locations (coordinates in SOM grid) of each neurons in the map.

        @param[in] rows (uint): Number of neurons in the column (number of rows).
        @param[in] cols (uint): Number of neurons in the row (number of columns).

        @return (list) List of coordinates of each neuron in map.


images = [];<EOL>images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_A;<EOL>images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_B;<EOL>images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_C;<EOL>template_recognition_image(images, <NUM_LIT>, <NUM_LIT>)<EOL>

!
    @brief Trains network using letters 'A', 'B', 'C', and recognize each of them with and without noise.


template_dynamic(<NUM_LIT:2>, -<NUM_LIT:4>, <NUM_LIT:1>, [<NUM_LIT:1>, <NUM_LIT:0>], [<NUM_LIT:1>, <NUM_LIT:1>])<EOL>

Comment: Different initial state - state of sync. will be reached.


template_dynamic(<NUM_LIT:5>, -<NUM_LIT:4>, <NUM_LIT:1>, [<NUM_LIT:1>, <NUM_LIT:0.5>, <NUM_LIT:0>, -<NUM_LIT:0.5>, -<NUM_LIT:1>], [<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>]);<EOL>template_dynamic(<NUM_LIT:5>, -<NUM_LIT:4>, <NUM_LIT:1>, [<NUM_LIT:1>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>], [-<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>, -<NUM_LIT:1>])<EOL>

Note: Oscillations are dead in this case (sync. should be in ideal case)


"<STR_LIT>"<EOL>parameters = legion_parameters();<EOL>parameters.Wt = <NUM_LIT>;<EOL>parameters.fi = <NUM_LIT>;<EOL>parameters.ENABLE_POTENTIONAL = False;<EOL>template_dynamic_legion(<NUM_LIT:15>, <NUM_LIT:1000>, <NUM_LIT:1000>, conn_type = conn_type.LIST_BIDIR, <EOL>stimulus = [<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>], <EOL>params = parameters, <EOL>separate_repr = [ [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>], [<NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:5>, <NUM_LIT:9>, <NUM_LIT:10>], [<NUM_LIT:6>, <NUM_LIT:7>, <NUM_LIT:8>], [<NUM_LIT:11>, <NUM_LIT:12>, <NUM_LIT>, <NUM_LIT>] ])<EOL>

Good example of three synchronous ensembels


parameters = legion_parameters();<EOL>parameters.teta_x = -<NUM_LIT>;<EOL>template_dynamic_legion(<NUM_LIT:16>, <NUM_LIT>, <NUM_LIT>, conn_type = conn_type.GRID_FOUR, params = parameters, stimulus = [<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <EOL><NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>])<EOL>

Not accurate false due to spikes are observed


"<STR_LIT>"<EOL>parameters = legion_parameters();<EOL>parameters.Wt = <NUM_LIT>;<EOL>parameters.fi = <NUM_LIT>;<EOL>template_dynamic_legion(<NUM_LIT:15>, <NUM_LIT:1000>, <NUM_LIT:1000>, conn_type = conn_type.LIST_BIDIR, stimulus = [<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>], params = parameters, separate_repr = [ [<NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:2>], [<NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT:5>, <NUM_LIT:9>, <NUM_LIT:10>], [<NUM_LIT:6>, <NUM_LIT:7>, <NUM_LIT:8>], [<NUM_LIT:11>, <NUM_LIT:12>, <NUM_LIT>, <NUM_LIT>] ])<EOL>


params = pcnn_parameters();<EOL>template_dynamic_pcnn(<NUM_LIT:9>, <NUM_LIT:100>, [<NUM_LIT:1.0>] * <NUM_LIT:9>, params, conn_type.GRID_FOUR)<EOL>


"<STR_LIT>"<EOL>params = pcnn_parameters();<EOL>params.AF = <NUM_LIT:0.1>;<EOL>params.AL = <NUM_LIT:0.0>;<EOL>params.AT = <NUM_LIT>;<EOL>params.VF = <NUM_LIT:1.0>;<EOL>params.VL = <NUM_LIT:1.0>;<EOL>params.VT = <NUM_LIT>;<EOL>params.M = <NUM_LIT:0.0>;<EOL>template_dynamic_pcnn(<NUM_LIT>, <NUM_LIT:100>, [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>], params, conn_type.GRID_FOUR, False)<EOL>


template_dynamic_pcnn(<NUM_LIT:9>, <NUM_LIT:100>, [<NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <EOL><NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>], None, conn_type.GRID_FOUR)<EOL>


params = pcnn_parameters();<EOL>params.AF = <NUM_LIT:0.1>;<EOL>params.AL = <NUM_LIT:0.1>;<EOL>params.AT = <NUM_LIT>;<EOL>params.VF = <NUM_LIT:1.0>;<EOL>params.VL = <NUM_LIT:1.0>;<EOL>params.VT = <NUM_LIT>;<EOL>params.W = <NUM_LIT:1.0>;<EOL>params.M = <NUM_LIT:1.0>;<EOL>template_dynamic_pcnn(<NUM_LIT:100>, <NUM_LIT:50>,  [<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:1>, <NUM_LIT:0>,<EOL><NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>], params, conn_type.GRID_EIGHT, False)<EOL>

Allocate several clusters: the first contains borders (indexes of oscillators) and the second objects (indexes of oscillators)


template_segmentation_image(IMAGE_SIMPLE_SAMPLES.IMAGE_SIMPLE_BUILDING, None, <NUM_LIT>, None, True, False, True)<EOL>


return self.__width<EOL>

!
        @brief Width of the network grid, this value is zero in case of non-grid structure.

        @note This property returns valid value only for network with grid structure.


if (self.structure != conn_type.DYNAMIC):<EOL><INDENT>raise NameError("<STR_LIT>");<EOL><DEDENT>if (self._conn_represent == conn_represent.MATRIX):<EOL><INDENT>self._osc_conn[i][j] = True;<EOL>self._osc_conn[j][i] = True;<EOL><DEDENT>else:<EOL><INDENT>self._osc_conn[i].append(j);<EOL>self._osc_conn[j].append(i);<EOL><DEDENT>

!
        @brief Couples two specified oscillators in the network with dynamic connections.

        @param[in] i (uint): index of an oscillator that should be coupled with oscillator 'j' in the network.
        @param[in] j (uint): index of an oscillator that should be coupled with oscillator 'i' in the network.

        @note This method can be used only in case of DYNAMIC connections, otherwise it throws expection.


if (self._conn_represent == conn_represent.MATRIX):<EOL><INDENT>for index in range(<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>):<EOL><INDENT>self._osc_conn.append([True] * self._num_osc);<EOL>self._osc_conn[index][index] = False;<EOL><DEDENT><DEDENT>elif (self._conn_represent == conn_represent.LIST):<EOL><INDENT>for index in range(<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>):<EOL><INDENT>self._osc_conn.append([neigh for neigh in range(<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>) if index != neigh]);<EOL><DEDENT><DEDENT>

!
        @brief Creates connections between all oscillators.


side_size = self.__width;<EOL>if (self._conn_represent == conn_represent.MATRIX):<EOL><INDENT>self._osc_conn = [[<NUM_LIT:0>] * self._num_osc for index in range(<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>)];<EOL><DEDENT>elif (self._conn_represent == conn_represent.LIST):<EOL><INDENT>self._osc_conn = [[] for index in range(<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>)];<EOL><DEDENT>else:<EOL><INDENT>raise NameError("<STR_LIT>");<EOL><DEDENT>for index in range(<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>):<EOL><INDENT>upper_index = index - side_size;<EOL>lower_index = index + side_size;<EOL>left_index = index - <NUM_LIT:1>;<EOL>right_index = index + <NUM_LIT:1>;<EOL>node_row_index = math.ceil(index / side_size);<EOL>if (upper_index >= <NUM_LIT:0>):<EOL><INDENT>self.__create_connection(index, upper_index);<EOL><DEDENT>if (lower_index < self._num_osc):<EOL><INDENT>self.__create_connection(index, lower_index);<EOL><DEDENT>if ( (left_index >= <NUM_LIT:0>) and (math.ceil(left_index / side_size) == node_row_index) ):<EOL><INDENT>self.__create_connection(index, left_index);<EOL><DEDENT>if ( (right_index < self._num_osc) and (math.ceil(right_index / side_size) == node_row_index) ):<EOL><INDENT>self.__create_connection(index, right_index);<EOL><DEDENT><DEDENT>

!
        @brief Creates network with connections that make up four grid structure.
        @details Each oscillator may be connected with four neighbors in line with 'grid' structure: right, upper, left, lower.


def __init__(self, output, inhibitor, time, ccore = None):

self.__output = output;<EOL>self.__inhibitor = inhibitor;<EOL>self._time = time;<EOL>self.__ccore_legion_dynamic_pointer = ccore<EOL>

!
        @brief Constructor of legion dynamic.

        @param[in] output (list): Output dynamic of the network represented by excitatory values of oscillators.
        @param[in] inhibitor (list): Output dynamic of the global inhibitor of the network.
        @param[in] time (list): Simulation time.
        @param[in] ccore (POINTER): Pointer to CCORE legion_dynamic. If it is specified then others arguments can be omitted.


if (self.__ccore_legion_pointer is not None):<EOL><INDENT>wrapper.legion_destroy(self.__ccore_legion_pointer);<EOL>self.__ccore_legion_pointer = None;<EOL><DEDENT>

!
        @brief Default destructor of LEGION.


if (self.__ccore_legion_dynamic_pointer is not None):<EOL><INDENT>return wrapper.legion_dynamic_get_output(self.__ccore_legion_dynamic_pointer);<EOL><DEDENT>return self.__output<EOL>

!
        @brief Returns output dynamic of the network.


if (self.__ccore_legion_dynamic_pointer is not None):<EOL><INDENT>return wrapper.legion_dynamic_get_time(self.__ccore_legion_dynamic_pointer);<EOL><DEDENT>return list(range(len(self)))<EOL>

!
        @brief Returns simulation time.


def _global_inhibitor_state(self, z, t, argv):

sigma = <NUM_LIT:0.0>;<EOL>for x in self._excitatory:<EOL><INDENT>if (x > self._params.teta_zx):<EOL><INDENT>sigma = <NUM_LIT:1.0>;<EOL>break;<EOL><DEDENT><DEDENT>return self._params.fi * (sigma - z)<EOL>

!
        @brief Returns new value of global inhibitory

        @param[in] z (dobule): Current value of inhibitory.
        @param[in] t (double): Current time of simulation.
        @param[in] argv (tuple): It's not used, can be ignored.

        @return (double) New value if global inhibitory (not assign).


if (self._stimulus is None):<EOL><INDENT>raise NameError("<STR_LIT>");<EOL><DEDENT>self._dynamic_coupling = [ [<NUM_LIT:0>] * self._num_osc for i in range(self._num_osc)];<EOL>for i in range(self._num_osc):<EOL><INDENT>neighbors = self.get_neighbors(i);<EOL>if ( (len(neighbors) > <NUM_LIT:0>) and (self._stimulus[i] > <NUM_LIT:0>) ):<EOL><INDENT>number_stimulated_neighbors = <NUM_LIT:0.0>;<EOL>for j in neighbors:<EOL><INDENT>if (self._stimulus[j] > <NUM_LIT:0>):<EOL><INDENT>number_stimulated_neighbors += <NUM_LIT:1.0>;<EOL><DEDENT><DEDENT>if (number_stimulated_neighbors > <NUM_LIT:0>):<EOL><INDENT>dynamic_weight = self._params.Wt / number_stimulated_neighbors;<EOL>for j in neighbors:<EOL><INDENT>self._dynamic_coupling[i][j] = dynamic_weight;<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

!
        @brief Create dynamic connection in line with input stimulus.


<EOL>self.eps         = <NUM_LIT>;<EOL>self.alpha       = <NUM_LIT>;<EOL>self.gamma       = <NUM_LIT>;<EOL>self.betta       = <NUM_LIT:0.1>;<EOL>self.lamda       = <NUM_LIT:0.1>;<EOL>self.teta        = <NUM_LIT>;<EOL>self.teta_x      = -<NUM_LIT>;<EOL>self.teta_p      = <NUM_LIT>;<EOL>self.teta_xz     = <NUM_LIT:0.1>;<EOL>self.teta_zx     = <NUM_LIT:0.1>;<EOL>self.T           = <NUM_LIT>;<EOL>self.mu          = <NUM_LIT>;<EOL>self.Wz          = <NUM_LIT>;<EOL>self.Wt          = <NUM_LIT>;<EOL>self.fi          = <NUM_LIT>;<EOL>self.ro          = <NUM_LIT>;<EOL>self.I           = <NUM_LIT>;<EOL>self.ENABLE_POTENTIONAL = True<EOL>

!
        @brief    Default constructor of parameters for LEGION (local excitatory global inhibitory oscillatory network).
        @details  Constructor initializes parameters by default non-zero values that can be
                  used for simple simulation.


if (self.__ccore_legion_pointer is not None):<EOL><INDENT>return wrapper.legion_get_size(self.__ccore_legion_pointer);<EOL><DEDENT>return self._num_osc<EOL>

!
        @brief (uint) Returns size of LEGION.


if (self.__ccore_legion_dynamic_pointer is not None):<EOL><INDENT>return wrapper.legion_dynamic_get_inhibitory_output(self.__ccore_legion_dynamic_pointer);<EOL><DEDENT>return self.__inhibitor<EOL>

!
        @brief Returns output dynamic of the global inhibitor of the network.


def _legion_state(self, inputs, t, argv):

index = argv;<EOL>x = inputs[<NUM_LIT:0>];  <EOL>y = inputs[<NUM_LIT:1>];  <EOL>p = inputs[<NUM_LIT:2>];  <EOL>potential_influence = heaviside(p + math.exp(-self._params.alpha * t) - self._params.teta);<EOL>dx = <NUM_LIT> * x - x ** <NUM_LIT> + <NUM_LIT> - y + self._stimulus[index] * potential_influence + self._coupling_term[index] + self._noise[index];<EOL>dy = self._params.eps * (self._params.gamma * (<NUM_LIT:1.0> + math.tanh(x / self._params.betta)) - y);<EOL>neighbors = self.get_neighbors(index);<EOL>potential = <NUM_LIT:0.0>;<EOL>for index_neighbor in neighbors:<EOL><INDENT>potential += self._params.T * heaviside(self._excitatory[index_neighbor] - self._params.teta_x);<EOL><DEDENT>dp = self._params.lamda * (<NUM_LIT:1.0> - p) * heaviside(potential - self._params.teta_p) - self._params.mu * p;<EOL>return [dx, dy, dp]<EOL>

!
        @brief Returns new values of excitatory and inhibitory parts of oscillator and potential of oscillator.

        @param[in] inputs (list): Initial values (current) of oscillator [excitatory, inhibitory, potential].
        @param[in] t (double): Current time of simulation.
        @param[in] argv (uint): Extra arguments that are not used for integration - index of oscillator.

        @return (list) New values of excitatoty and inhibitory part of oscillator and new value of potential (not assign).


next_excitatory = [<NUM_LIT:0.0>] * self._num_osc;<EOL>next_inhibitory = [<NUM_LIT:0.0>] * self._num_osc;<EOL>next_potential = [];<EOL>if (self._params.ENABLE_POTENTIONAL is True):<EOL><INDENT>next_potential = [<NUM_LIT:0.0>] * self._num_osc;<EOL><DEDENT>for index in range (<NUM_LIT:0>, self._num_osc, <NUM_LIT:1>):<EOL><INDENT>if (self._params.ENABLE_POTENTIONAL is True):<EOL><INDENT>result = odeint(self._legion_state, [self._excitatory[index], self._inhibitory[index], self._potential[index]], numpy.arange(t - step, t, int_step), (index , ));<EOL>[ next_excitatory[index], next_inhibitory[index], next_potential[index] ] = result[len(result) - <NUM_LIT:1>][<NUM_LIT:0>:<NUM_LIT:3>];<EOL><DEDENT>else:<EOL><INDENT>result = odeint(self._legion_state_simplify, [self._excitatory[index], self._inhibitory[index] ], numpy.arange(t - step, t, int_step), (index , ));<EOL>[ next_excitatory[index], next_inhibitory[index] ] = result[len(result) - <NUM_LIT:1>][<NUM_LIT:0>:<NUM_LIT:2>];<EOL><DEDENT>neighbors = self.get_neighbors(index);<EOL>coupling = <NUM_LIT:0><EOL>for index_neighbor in neighbors:<EOL><INDENT>coupling += self._dynamic_coupling[index][index_neighbor] * heaviside(self._excitatory[index_neighbor] - self._params.teta_x);<EOL><DEDENT>self._buffer_coupling_term[index] = coupling - self._params.Wz * heaviside(self._global_inhibitor - self._params.teta_xz);<EOL><DEDENT>result = odeint(self._global_inhibitor_state, self._global_inhibitor, numpy.arange(t - step, t, int_step), (None, ));<EOL>self._global_inhibitor = result[len(result) - <NUM_LIT:1>][<NUM_LIT:0>];<EOL>self._noise = [random.random() * self._params.ro for i in range(self._num_osc)];<EOL>self._coupling_term = self._buffer_coupling_term[:];<EOL>self._inhibitory = next_inhibitory[:];<EOL>self._excitatory = next_excitatory[:];<EOL>if (self._params.ENABLE_POTENTIONAL is True):<EOL><INDENT>self._potential = next_potential[:];<EOL><DEDENT>

!
        @brief Calculates new state of each oscillator in the network.

        @param[in] solution (solve_type): Type solver of the differential equation.
        @param[in] t (double): Current time of simulation.
        @param[in] step (double): Step of solution at the end of which states of oscillators should be calculated.
        @param[in] int_step (double): Step differentiation that is used for solving differential equation.


def __analyse_colors(self, image_data, collect_dynamic):

network = syncnet(image_data, self.__color_radius, initial_phases = initial_type.RANDOM_GAUSSIAN, ccore = self.__ccore);<EOL>analyser = network.process(self.__order_color, solve_type.FAST, collect_dynamic);<EOL>return analyser<EOL>

!
        @brief Performs color segmentation by the first layer.

        @param[in] image_data (array_like): Image sample as a array-like structure.
        @param[in] collect_dynamic (bool): If 'True' then whole dynamic of the first layer of the network is collected.

        @return (syncnet_analyser) Analyser of color segmentation results of the first layer.


sync_visualizer.show_output_dynamic(analyser.get_first_layer_analyser())<EOL>

!
        @brief Shows output dynamic of the first layer.

        @param[in] analyser (syncsegm_analyser): Analyser of output dynamic of the 'syncsegm' oscillatory network.


def __init__(self, color_analyser, object_segment_analysers = None):

self.__color_analyser = color_analyser;<EOL>self.__object_segment_analysers = object_segment_analysers<EOL>

!
        @brief Constructor of the analyser.

        @param[in] color_analyser (list): Analyser of coloring segmentation results of the first layer.
        @param[in] object_segment_analysers (list): Analysers of objects on image segments - results of the second layer.


return self.__color_analyser<EOL>

!
        @brief Returns analyser of coloring segmentation of the first layer.


def extract_number_oscillations(osc_dyn, index = <NUM_LIT:0>, amplitude_threshold = <NUM_LIT:1.0>):

number_oscillations = <NUM_LIT:0>;<EOL>waiting_differential = False;<EOL>threshold_passed = False;<EOL>high_level_trigger = True if (osc_dyn[<NUM_LIT:0>][index] > amplitude_threshold) else False;<EOL>for values in osc_dyn:<EOL><INDENT>if ( (values[index] >= amplitude_threshold) and (high_level_trigger is False) ):<EOL><INDENT>high_level_trigger = True;<EOL>threshold_passed = True;<EOL><DEDENT>elif ( (values[index] < amplitude_threshold) and (high_level_trigger is True) ):<EOL><INDENT>high_level_trigger = False;<EOL>threshold_passed = True;<EOL><DEDENT>if (threshold_passed is True):<EOL><INDENT>threshold_passed = False;<EOL>if (waiting_differential is True and high_level_trigger is False):<EOL><INDENT>number_oscillations += <NUM_LIT:1>;<EOL>waiting_differential = False;<EOL><DEDENT>else:<EOL><INDENT>waiting_differential = True;<EOL><DEDENT><DEDENT><DEDENT>return number_oscillations<EOL>

!
    @brief Extracts number of oscillations of specified oscillator.

    @param[in] osc_dyn (list): Dynamic of oscillators.
    @param[in] index (uint): Index of oscillator in dynamic.
    @param[in] amplitude_threshold (double): Amplitude threshold when oscillation is taken into account, for example,
                when oscillator amplitude is greater than threshold then oscillation is incremented.

    @return (uint) Number of oscillations of specified oscillator.


def set_ax_param(ax, x_title = None, y_title = None, x_lim = None, y_lim = None, x_labels = True, y_labels = True, grid = True):

from matplotlib.font_manager import FontProperties;<EOL>from matplotlib import rcParams;<EOL>if (_platform == "<STR_LIT>") or (_platform == "<STR_LIT>"):<EOL><INDENT>rcParams['<STR_LIT>'] = ['<STR_LIT>'];<EOL><DEDENT>else:<EOL><INDENT>rcParams['<STR_LIT>'] = ['<STR_LIT>'];<EOL><DEDENT>rcParams['<STR_LIT>'] = <NUM_LIT:12>;<EOL>surface_font = FontProperties();<EOL>if (_platform == "<STR_LIT>") or (_platform == "<STR_LIT>"):<EOL><INDENT>surface_font.set_name('<STR_LIT>');<EOL><DEDENT>else:<EOL><INDENT>surface_font.set_name('<STR_LIT>');<EOL><DEDENT>surface_font.set_size('<STR_LIT>');<EOL>if (y_title is not None): ax.set_ylabel(y_title, fontproperties = surface_font);<EOL>if (x_title is not None): ax.set_xlabel(x_title, fontproperties = surface_font);<EOL>if (x_lim is not None): ax.set_xlim(x_lim[<NUM_LIT:0>], x_lim[<NUM_LIT:1>]);<EOL>if (y_lim is not None): ax.set_ylim(y_lim[<NUM_LIT:0>], y_lim[<NUM_LIT:1>]);<EOL>if (x_labels is False): ax.xaxis.set_ticklabels([]);<EOL>if (y_labels is False): ax.yaxis.set_ticklabels([]);<EOL>ax.grid(grid)<EOL>

!
    @brief Sets parameters for matplotlib ax.

    @param[in] ax (Axes): Axes for which parameters should applied.
    @param[in] x_title (string): Title for Y.
    @param[in] y_title (string): Title for X.
    @param[in] x_lim (double): X limit.
    @param[in] y_lim (double): Y limit.
    @param[in] x_labels (bool): If True - shows X labels.
    @param[in] y_labels (bool): If True - shows Y labels.
    @param[in] grid (bool): If True - shows grid.


def draw_dynamics_set(dynamics, xtitle = None, ytitle = None, xlim = None, ylim = None, xlabels = False, ylabels = False):

<EOL>number_dynamics = len(dynamics);<EOL>if (number_dynamics == <NUM_LIT:1>):<EOL><INDENT>draw_dynamics(dynamics[<NUM_LIT:0>][<NUM_LIT:0>], dynamics[<NUM_LIT:0>][<NUM_LIT:1>], xtitle, ytitle, xlim, ylim, xlabels, ylabels);<EOL>return;<EOL><DEDENT>number_cols = int(numpy.ceil(number_dynamics ** <NUM_LIT:0.5>));<EOL>number_rows = int(numpy.ceil(number_dynamics / number_cols));<EOL>real_index = <NUM_LIT:0>, <NUM_LIT:0>;<EOL>double_indexer = True;<EOL>if ( (number_cols == <NUM_LIT:1>) or (number_rows == <NUM_LIT:1>) ):<EOL><INDENT>real_index = <NUM_LIT:0>;<EOL>double_indexer = False;<EOL><DEDENT>(_, axarr) = plt.subplots(number_rows, number_cols);<EOL>for dynamic in dynamics:<EOL><INDENT>axarr[real_index] = draw_dynamics(dynamic[<NUM_LIT:0>], dynamic[<NUM_LIT:1>], xtitle, ytitle, xlim, ylim, xlabels, ylabels, axes = axarr[real_index]);<EOL>if (double_indexer is True):<EOL><INDENT>real_index = real_index[<NUM_LIT:0>], real_index[<NUM_LIT:1>] + <NUM_LIT:1>;<EOL>if (real_index[<NUM_LIT:1>] >= number_cols):<EOL><INDENT>real_index = real_index[<NUM_LIT:0>] + <NUM_LIT:1>, <NUM_LIT:0>; <EOL><DEDENT><DEDENT>else:<EOL><INDENT>real_index += <NUM_LIT:1>;<EOL><DEDENT><DEDENT>plt.show()<EOL>

!
    @brief Draw lists of dynamics of neurons (oscillators) in the network.

    @param[in] dynamics (list): List of network outputs that are represented by values of output of oscillators (used by y axis).
    @param[in] xtitle (string): Title for Y.
    @param[in] ytitle (string): Title for X.
    @param[in] xlim (double): X limit.
    @param[in] ylim (double): Y limit.
    @param[in] xlabels (bool): If True - shows X labels.
    @param[in] ylabels (bool): If True - shows Y labels.


image_gray_array = [<NUM_LIT:0.0>] * len(image_rgb_array);<EOL>for index in range(<NUM_LIT:0>, len(image_rgb_array), <NUM_LIT:1>):<EOL><INDENT>image_gray_array[index] = float(image_rgb_array[index][<NUM_LIT:0>]) * <NUM_LIT> + float(image_rgb_array[index][<NUM_LIT:1>]) * <NUM_LIT> + float(image_rgb_array[index][<NUM_LIT:2>]) * <NUM_LIT>;<EOL><DEDENT>return image_gray_array<EOL>

!
    @brief Returns image as 1-dimension (gray colored) matrix, where one element of list describes pixel.
    @details Luma coding is used for transformation and that is calculated directly from gamma-compressed primary intensities as a weighted sum:

    \f[Y = 0.2989R + 0.587G + 0.114B\f]

    @param[in] image_rgb_array (list): Image represented by RGB list.

    @return (list) Image as gray colored matrix, where one element of list describes pixel.

    @code
        colored_image = read_image(file_name);
        gray_image = rgb2gray(colored_image);
    @endcode

    @see read_image()


if (value > <NUM_LIT:0.0>): <EOL><INDENT>return <NUM_LIT:1.0>;<EOL><DEDENT>return <NUM_LIT:0.0><EOL>

!
    @brief Calculates Heaviside function that represents step function.
    @details If input value is greater than 0 then returns 1, otherwise returns 0.

    @param[in] value (double): Argument of Heaviside function.

    @return (double) Value of Heaviside function.


return [a[i] + b[i] for i in range(len(a))]<EOL>

!
    @brief Addition of two lists.
    @details Each element from list 'a' is added to element from list 'b' accordingly.

    @param[in] a (list): List of elements that supports mathematic addition..
    @param[in] b (list): List of elements that supports mathematic addition..

    @return (list) Results of addtion of two lists.


def average_intra_cluster_distance(cluster1, cluster2, data=None):

distance = <NUM_LIT:0.0><EOL>for i in range(len(cluster1) + len(cluster2)):<EOL><INDENT>for j in range(len(cluster1) + len(cluster2)):<EOL><INDENT>if data is None:<EOL><INDENT>if i < len(cluster1):<EOL><INDENT>first_point = cluster1[i]<EOL><DEDENT>else:<EOL><INDENT>first_point = cluster2[i - len(cluster1)]<EOL><DEDENT>if j < len(cluster1):<EOL><INDENT>second_point = cluster1[j]<EOL><DEDENT>else:<EOL><INDENT>second_point = cluster2[j - len(cluster1)]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if i < len(cluster1):<EOL><INDENT>first_point = data[cluster1[i]]<EOL><DEDENT>else:<EOL><INDENT>first_point = data[cluster2[i - len(cluster1)]]<EOL><DEDENT>if j < len(cluster1):<EOL><INDENT>second_point = data[cluster1[j]]<EOL><DEDENT>else:<EOL><INDENT>second_point = data[cluster2[j - len(cluster1)]]<EOL><DEDENT><DEDENT>distance += euclidean_distance_square(first_point, second_point)<EOL><DEDENT><DEDENT>distance /= float((len(cluster1) + len(cluster2)) * (len(cluster1) + len(cluster2) - <NUM_LIT:1.0>))<EOL>return distance ** <NUM_LIT:0.5><EOL>

!
    @brief Calculates average intra-cluster distance between two clusters.
    @details Clusters can be represented by list of coordinates (in this case data shouldn't be specified),
             or by list of indexes of points from the data (represented by list of points), in this case
             data should be specified.

    @param[in] cluster1 (list): The first cluster.
    @param[in] cluster2 (list): The second cluster.
    @param[in] data (list): If specified than elements of clusters will be used as indexes,
               otherwise elements of cluster will be considered as points.

    @return (double) Average intra-cluster distance between two clusters.


width, height = image.size;<EOL>width_start = width;<EOL>width_end = <NUM_LIT:0>;<EOL>height_start = height;<EOL>height_end = <NUM_LIT:0>;<EOL>row, col = <NUM_LIT:0>, <NUM_LIT:0>;<EOL>for pixel in image.getdata():<EOL><INDENT>value = float(pixel[<NUM_LIT:0>]) * <NUM_LIT> + float(pixel[<NUM_LIT:1>]) * <NUM_LIT> + float(pixel[<NUM_LIT:2>]) * <NUM_LIT>;<EOL>if (value < <NUM_LIT>):<EOL><INDENT>if (width_end < col): <EOL><INDENT>width_end = col;<EOL><DEDENT>if (height_end < row):<EOL><INDENT>height_end = row;<EOL><DEDENT>if (width_start > col):<EOL><INDENT>width_start = col;<EOL><DEDENT>if (height_start > row):<EOL><INDENT>height_start = row;<EOL><DEDENT><DEDENT>col += <NUM_LIT:1>;<EOL>if (col >= width):<EOL><INDENT>col = <NUM_LIT:0>;<EOL>row += <NUM_LIT:1>;<EOL><DEDENT><DEDENT>return (width_start, height_start, width_end + <NUM_LIT:1>, height_end + <NUM_LIT:1>)<EOL>

!
    @brief Returns coordinates of gray image content on the input image.

    @param[in] image (Image): PIL Image instance that is processed.

    @return (tuple) Returns coordinates of gray image content as (width_start, height_start, width_end, height_end).


with Image.open(filename) as image_source:<EOL><INDENT>data = [list(pixel) for pixel in image_source.getdata()]<EOL>return data<EOL><DEDENT>

!
    @brief Returns image as N-dimension (depends on the input image) matrix, where one element of list describes pixel.

    @param[in] filename (string): Path to image.

    @return (list) Pixels where each pixel described by list of RGB-values.


def draw_image_mask_segments(source, clusters, hide_axes = True):

if (len(clusters) == <NUM_LIT:0>):<EOL><INDENT>print("<STR_LIT>")<EOL>return;<EOL><DEDENT>image_source = Image.open(source);<EOL>image_size = image_source.size;<EOL>number_clusters = len(clusters) + <NUM_LIT:1>; <EOL>number_cols = int(numpy.ceil(number_clusters ** <NUM_LIT:0.5>));<EOL>number_rows = int(numpy.ceil(number_clusters / number_cols));<EOL>real_index = <NUM_LIT:0>, <NUM_LIT:0>;<EOL>double_indexer = True;<EOL>if ( (number_cols == <NUM_LIT:1>) or (number_rows == <NUM_LIT:1>) ):<EOL><INDENT>real_index = <NUM_LIT:0>;<EOL>double_indexer = False;<EOL><DEDENT>(fig, axarr) = plt.subplots(number_rows, number_cols);<EOL>plt.setp([ax for ax in axarr], visible = False);<EOL>axarr[real_index].imshow(image_source, interpolation = '<STR_LIT:none>');<EOL>plt.setp(axarr[real_index], visible = True);<EOL>if (hide_axes is True):<EOL><INDENT>axarr[real_index].xaxis.set_ticklabels([]);<EOL>axarr[real_index].yaxis.set_ticklabels([]);<EOL>axarr[real_index].xaxis.set_ticks_position('<STR_LIT:none>');<EOL>axarr[real_index].yaxis.set_ticks_position('<STR_LIT:none>');<EOL><DEDENT>if (double_indexer is True):<EOL><INDENT>real_index = <NUM_LIT:0>, <NUM_LIT:1>;<EOL><DEDENT>else:<EOL><INDENT>real_index += <NUM_LIT:1>;<EOL><DEDENT>for cluster in clusters:<EOL><INDENT>stage_cluster = [(<NUM_LIT:255>, <NUM_LIT:255>, <NUM_LIT:255>)] * (image_size[<NUM_LIT:0>] * image_size[<NUM_LIT:1>]);<EOL>for index in cluster:<EOL><INDENT>stage_cluster[index] = (<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>);<EOL><DEDENT>stage = array(stage_cluster, numpy.uint8);<EOL>stage = numpy.reshape(stage, (image_size[<NUM_LIT:1>], image_size[<NUM_LIT:0>]) + ((<NUM_LIT:3>),)); <EOL>image_cluster = Image.fromarray(stage, '<STR_LIT>');<EOL>axarr[real_index].imshow(image_cluster, interpolation = '<STR_LIT:none>');<EOL>plt.setp(axarr[real_index], visible = True);<EOL>if (hide_axes is True):<EOL><INDENT>axarr[real_index].xaxis.set_ticklabels([]);<EOL>axarr[real_index].yaxis.set_ticklabels([]);<EOL>axarr[real_index].xaxis.set_ticks_position('<STR_LIT:none>');<EOL>axarr[real_index].yaxis.set_ticks_position('<STR_LIT:none>');<EOL><DEDENT>if (double_indexer is True):<EOL><INDENT>real_index = real_index[<NUM_LIT:0>], real_index[<NUM_LIT:1>] + <NUM_LIT:1>;<EOL>if (real_index[<NUM_LIT:1>] >= number_cols):<EOL><INDENT>real_index = real_index[<NUM_LIT:0>] + <NUM_LIT:1>, <NUM_LIT:0>; <EOL><DEDENT><DEDENT>else:<EOL><INDENT>real_index += <NUM_LIT:1>;<EOL><DEDENT><DEDENT>plt.show()<EOL>

!
    @brief Shows image segments using black masks.
    @details Each black mask of allocated segment is presented on separate plot.
             The first image is initial and others are black masks of segments.

    @param[in] source (string): Path to image.
    @param[in] clusters (list): List of clusters (allocated segments of image) where each cluster
                                consists of indexes of pixel from source image.
    @param[in] hide_axes (bool): If True then axes will not be displayed.


file = open(filename, '<STR_LIT:r>')<EOL>sample = [[float(val) for val in line.split()] for line in file if len(line.strip()) > <NUM_LIT:0>]<EOL>file.close()<EOL>return sample<EOL>

!
    @brief Returns data sample from simple text file.
    @details This function should be used for text file with following format:
    @code
    point_1_coord_1 point_1_coord_2 ... point_1_coord_n
    point_2_coord_1 point_2_coord_2 ... point_2_coord_n
    ... ...
    @endcode

    @param[in] filename (string): Path to file with data.

    @return (list) Points where each point represented by list of coordinates.


if ( ((type(a) == float) and (type(b) == float)) or ((type(a) == int) and (type(b) == int)) ):<EOL><INDENT>return abs(a - b);<EOL><DEDENT>distance = <NUM_LIT:0.0>;<EOL>dimension = len(a);<EOL>for i in range(<NUM_LIT:0>, dimension):<EOL><INDENT>distance += abs(a[i] - b[i]);<EOL><DEDENT>return distance<EOL>

!
    @brief Calculate Manhattan distance between vector a and b.

    @param[in] a (list): The first cluster.
    @param[in] b (list): The second cluster.

    @return (double) Manhattan distance between two vectors.


def average_inter_cluster_distance(cluster1, cluster2, data = None):

distance = <NUM_LIT:0.0>;<EOL>if (data is None):<EOL><INDENT>for i in range(len(cluster1)):<EOL><INDENT>for j in range(len(cluster2)):<EOL><INDENT>distance += euclidean_distance_square(cluster1[i], cluster2[j]);<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>for i in range(len(cluster1)):<EOL><INDENT>for j in range(len(cluster2)):<EOL><INDENT>distance += euclidean_distance_square(data[ cluster1[i]], data[ cluster2[j]]);<EOL><DEDENT><DEDENT><DEDENT>distance /= float(len(cluster1) * len(cluster2));<EOL>return distance ** <NUM_LIT:0.5><EOL>

!
    @brief Calculates average inter-cluster distance between two clusters.
    @details Clusters can be represented by list of coordinates (in this case data shouldn't be specified),
             or by list of indexes of points from the data (represented by list of points), in this case
             data should be specified.

    @param[in] cluster1 (list): The first cluster where each element can represent index from the data or object itself.
    @param[in] cluster2 (list): The second cluster where each element can represent index from the data or object itself.
    @param[in] data (list): If specified than elements of clusters will be used as indexes,
               otherwise elements of cluster will be considered as points.

    @return (double) Average inter-cluster distance between two clusters.


wsize, hsize = image_source.size;<EOL>(ws, hs, we, he) = gray_pattern_borders(image_source);<EOL>image_source = image_source.crop((ws, hs, we, he));<EOL>image_source = image_source.resize((wsize, hsize), Image.ANTIALIAS);<EOL>data = [pixel for pixel in image_source.getdata()];<EOL>image_pattern = rgb2gray(data);<EOL>return (image_pattern, image_source)<EOL>

!
    @brief Returns stretched content as 1-dimension (gray colored) matrix with size of input image.

    @param[in] image_source (Image): PIL Image instance.

    @return (list, Image) Stretched image as gray colored matrix and source image.


return [a[i] * b for i in range(len(a))]<EOL>

!
    @brief Multiplication between list and number.
    @details Each element from list 'a' is multiplied by number 'b'.

    @param[in] a (list): List of elements that supports mathematic division.
    @param[in] b (double): Number that supports mathematic division.

    @return (list) Result of division between list and number.


def medoid(data, indexes=None, **kwargs):

index_median = None<EOL>distance = float('<STR_LIT>')<EOL>metric = kwargs.get('<STR_LIT>', type_metric.EUCLIDEAN_SQUARE)<EOL>data_type = kwargs.get('<STR_LIT>', '<STR_LIT>')<EOL>if data_type == '<STR_LIT>':<EOL><INDENT>calculator = lambda index1, index2: metric(data[index1], data[index2])<EOL><DEDENT>elif data_type == '<STR_LIT>':<EOL><INDENT>if isinstance(data, numpy.matrix):<EOL><INDENT>calculator = lambda index1, index2: data.item(index1, index2)<EOL><DEDENT>else:<EOL><INDENT>calculator = lambda index1, index2: data[index1][index2]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise TypeError("<STR_LIT>" % data_type)<EOL><DEDENT>if indexes is None:<EOL><INDENT>range_points = range(len(data))<EOL><DEDENT>else:<EOL><INDENT>range_points = indexes<EOL><DEDENT>for index_candidate in range_points:<EOL><INDENT>distance_candidate = <NUM_LIT:0.0><EOL>for index in range_points:<EOL><INDENT>distance_candidate += calculator(index_candidate, index)<EOL><DEDENT>if distance_candidate < distance:<EOL><INDENT>distance = distance_candidate<EOL>index_median = index_candidate<EOL><DEDENT><DEDENT>return index_median<EOL>

!
    @brief Calculate medoid for input points using Euclidean distance.

    @param[in] data (list): Set of points for that median should be calculated.
    @param[in] indexes (list): Indexes of input set of points that will be taken into account during median calculation.
    @param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'metric', 'data_type').

    Keyword Args:

        - metric (distance_metric): Metric that is used for distance calculation between two points.
        - data_type (string): Data type of input sample 'data' (available values: 'points', 'distance_matrix').

    @return (uint) index of point in input set that corresponds to median.


if num_neigh > len(points) - <NUM_LIT:1>:<EOL><INDENT>raise NameError('<STR_LIT>');<EOL><DEDENT>dist_matrix = [ [ <NUM_LIT:0.0> for i in range(len(points)) ] for j in range(len(points)) ];<EOL>for i in range(<NUM_LIT:0>, len(points), <NUM_LIT:1>):<EOL><INDENT>for j in range(i + <NUM_LIT:1>, len(points), <NUM_LIT:1>):<EOL><INDENT>distance = euclidean_distance(points[i], points[j]);<EOL>dist_matrix[i][j] = distance;<EOL>dist_matrix[j][i] = distance;<EOL><DEDENT>dist_matrix[i] = sorted(dist_matrix[i]);<EOL><DEDENT>total_distance = <NUM_LIT:0>;<EOL>for i in range(<NUM_LIT:0>, len(points), <NUM_LIT:1>):<EOL><INDENT>for j in range(<NUM_LIT:0>, num_neigh, <NUM_LIT:1>):<EOL><INDENT>total_distance += dist_matrix[i][j + <NUM_LIT:1>];<EOL><DEDENT><DEDENT>return ( total_distance / (num_neigh * len(points)) )<EOL>

!
    @brief Returns average distance for establish links between specified number of nearest neighbors.

    @param[in] points (list): Input data, list of points where each point represented by list.
    @param[in] num_neigh (uint): Number of neighbors that should be used for distance calculation.

    @return (double) Average distance for establish links between 'num_neigh' in data set 'points'.


def calculate_ellipse_description(covariance, scale = <NUM_LIT>):

eigh_values, eigh_vectors = numpy.linalg.eigh(covariance)<EOL>order = eigh_values.argsort()[::-<NUM_LIT:1>]<EOL>values, vectors = eigh_values[order], eigh_vectors[order]<EOL>angle = numpy.degrees(numpy.arctan2(*vectors[:,<NUM_LIT:0>][::-<NUM_LIT:1>]))<EOL>if <NUM_LIT:0.0> in values:<EOL><INDENT>return <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0><EOL><DEDENT>width, height = <NUM_LIT> * scale * numpy.sqrt(values)<EOL>return angle, width, height<EOL>

!
    @brief Calculates description of ellipse using covariance matrix.

    @param[in] covariance (numpy.array): Covariance matrix for which ellipse area should be calculated.
    @param[in] scale (float): Scale of the ellipse.

    @return (float, float, float) Return ellipse description: angle, width, height.


return [a[i] + b for i in range(len(a))]<EOL>

!
    @brief Addition between list and number.
    @details Each element from list 'a' is added to number 'b'.

    @param[in] a (list): List of elements that supports mathematic addition.
    @param[in] b (double): Value that supports mathematic addition.

    @return (list) Result of addtion of two lists.


return numpy.sum(numpy.absolute(object1 - object2), axis=<NUM_LIT:1>).T<EOL>

!
    @brief Calculate Manhattan distance between two objects using numpy.

    @param[in] object1 (array_like): The first array_like object.
    @param[in] object2 (array_like): The second array_like object.

    @return (double) Manhattan distance between two objects.


def minkowski_distance_numpy(object1, object2, degree=<NUM_LIT:2>):

return numpy.sum(numpy.power(numpy.power(object1 - object2, degree), <NUM_LIT:1>/degree), axis=<NUM_LIT:1>).T<EOL>

!
    @brief Calculate Minkowski distance between objects using numpy.

    @param[in] object1 (array_like): The first array_like object.
    @param[in] object2 (array_like): The second array_like object.
    @param[in] degree (numeric): Degree of that is used for Minkowski distance.

    @return (double) Minkowski distance between two object.


if self.__type == type_metric.EUCLIDEAN:<EOL><INDENT>return euclidean_distance_numpy<EOL><DEDENT>elif self.__type == type_metric.EUCLIDEAN_SQUARE:<EOL><INDENT>return euclidean_distance_square_numpy<EOL><DEDENT>elif self.__type == type_metric.MANHATTAN:<EOL><INDENT>return manhattan_distance_numpy<EOL><DEDENT>elif self.__type == type_metric.CHEBYSHEV:<EOL><INDENT>return chebyshev_distance_numpy<EOL><DEDENT>elif self.__type == type_metric.MINKOWSKI:<EOL><INDENT>return lambda object1, object2: minkowski_distance_numpy(object1, object2, self.__args.get('<STR_LIT>', <NUM_LIT:2>))<EOL><DEDENT>elif self.__type == type_metric.CANBERRA:<EOL><INDENT>return canberra_distance_numpy<EOL><DEDENT>elif self.__type == type_metric.CHI_SQUARE:<EOL><INDENT>return chi_square_distance_numpy<EOL><DEDENT>elif self.__type == type_metric.USER_DEFINED:<EOL><INDENT>return self.__func<EOL><DEDENT>else:<EOL><INDENT>raise ValueError("<STR_LIT>", self.__type)<EOL><DEDENT>

!
        @brief Creates distance metric calculator that uses numpy.

        @return (callable) Callable object of distance metric calculator.


distance = <NUM_LIT:0.0><EOL>dimension = len(point1)<EOL>for i in range(dimension):<EOL><INDENT>distance += abs(point1[i] - point2[i])<EOL><DEDENT>return distance<EOL>

!
    @brief Calculate Manhattan distance between between two vectors.

    \f[
    dist(a, b) = \sum_{i=0}^{N}\left | a_{i} - b_{i} \right |;
    \f]

    @param[in] point1 (array_like): The first vector.
    @param[in] point2 (array_like): The second vector.

    @return (double) Manhattan distance between two vectors.

    @see euclidean_distance_square, euclidean_distance, chebyshev_distance


return self.__func<EOL>

!
        @brief Return user-defined function for calculation distance metric.

        @return (callable): User-defined distance metric function.


with numpy.errstate(divide='<STR_LIT:ignore>', invalid='<STR_LIT:ignore>'):<EOL><INDENT>result = numpy.divide(numpy.abs(object1 - object2), numpy.abs(object1) + numpy.abs(object2))<EOL><DEDENT>if len(result.shape) > <NUM_LIT:1>:<EOL><INDENT>return numpy.sum(numpy.nan_to_num(result), axis=<NUM_LIT:1>).T<EOL><DEDENT>else:<EOL><INDENT>return numpy.sum(numpy.nan_to_num(result))<EOL><DEDENT>

!
    @brief Calculate Canberra distance between two objects using numpy.

    @param[in] object1 (array_like): The first vector.
    @param[in] object2 (array_like): The second vector.

    @return (float) Canberra distance between two objects.


with numpy.errstate(divide='<STR_LIT:ignore>', invalid='<STR_LIT:ignore>'):<EOL><INDENT>result = numpy.divide(numpy.power(object1 - object2, <NUM_LIT:2>), numpy.abs(object1) + numpy.abs(object2))<EOL><DEDENT>if len(result.shape) > <NUM_LIT:1>:<EOL><INDENT>return numpy.sum(numpy.nan_to_num(result), axis=<NUM_LIT:1>).T<EOL><DEDENT>else:<EOL><INDENT>return numpy.sum(numpy.nan_to_num(result))<EOL><DEDENT>

!
    @brief Calculate Chi square distance between two vectors using numpy.

    @param[in] object1 (array_like): The first vector.
    @param[in] object2 (array_like): The second vector.

    @return (float) Chi square distance between two objects.


distance = <NUM_LIT:0.0><EOL>for i in range(len(point1)):<EOL><INDENT>distance += (point1[i] - point2[i]) ** <NUM_LIT><EOL><DEDENT>return distance<EOL>

!
    @brief Calculate square Euclidean distance between two vectors.

    \f[
    dist(a, b) = \sum_{i=0}^{N}(a_{i} - b_{i})^{2};
    \f]

    @param[in] point1 (array_like): The first vector.
    @param[in] point2 (array_like): The second vector.

    @return (double) Square Euclidean distance between two vectors.

    @see euclidean_distance, manhattan_distance, chebyshev_distance


return numpy.max(numpy.absolute(object1 - object2), axis=<NUM_LIT:1>).T<EOL>

!
    @brief Calculate Chebyshev distance between two objects using numpy.

    @param[in] object1 (array_like): The first array_like object.
    @param[in] object2 (array_like): The second array_like object.

    @return (double) Chebyshev distance between two objects.


if self.__numpy is True:<EOL><INDENT>return self.__create_distance_calculator_numpy()<EOL><DEDENT>return self.__create_distance_calculator_basic()<EOL>

!
        @brief Creates distance metric calculator.

        @return (callable) Callable object of distance metric calculator.


def __init__(self, metric_type, **kwargs):

self.__type = metric_type<EOL>self.__args = kwargs<EOL>self.__func = self.__args.get('<STR_LIT>', None)<EOL>self.__numpy = self.__args.get('<STR_LIT>', False)<EOL>self.__calculator = self.__create_distance_calculator()<EOL>

!
        @brief Creates distance metric instance for calculation distance between two points.

        @param[in] metric_type (type_metric):
        @param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'numpy_usage' 'func' and corresponding additional argument for
                    for specific metric types).

        Keyword Args:

            - func (callable): Callable object with two arguments (point #1 and point #2) or (object #1 and object #2) in case of numpy usage.
                                This argument is used only if metric is 'type_metric.USER_DEFINED'.
            - degree (numeric): Only for 'type_metric.MINKOWSKI' - degree of Minkowski equation.
            - numpy_usage (bool): If True then numpy is used for calculation (by default is False).


distance = euclidean_distance_square(point1, point2)<EOL>return distance ** <NUM_LIT:0.5><EOL>

!
    @brief Calculate Euclidean distance between two vectors.
    @details The Euclidean between vectors (points) a and b is calculated by following formula:

    \f[
    dist(a, b) = \sqrt{ \sum_{i=0}^{N}(a_{i} - b_{i})^{2} };
    \f]

    Where N is a length of each vector.

    @param[in] point1 (array_like): The first vector.
    @param[in] point2 (array_like): The second vector.

    @return (double) Euclidean distance between two vectors.

    @see euclidean_distance_square, manhattan_distance, chebyshev_distance


self.__numpy = True<EOL>if self.__type != type_metric.USER_DEFINED:<EOL><INDENT>self.__calculator = self.__create_distance_calculator()<EOL><DEDENT>

!
        @brief Start numpy for distance calculation.
        @details Useful in case matrices to increase performance. No effect in case of type_metric.USER_DEFINED type.


def minkowski_distance(point1, point2, degree=<NUM_LIT:2>):

distance = <NUM_LIT:0.0><EOL>for i in range(len(point1)):<EOL><INDENT>distance += (point1[i] - point2[i]) ** degree<EOL><DEDENT>return distance ** (<NUM_LIT:1.0> / degree)<EOL>

!
    @brief Calculate Minkowski distance between two vectors.

    \f[
    dist(a, b) = \sqrt[p]{ \sum_{i=0}^{N}\left(a_{i} - b_{i}\right)^{p} };
    \f]

    @param[in] point1 (array_like): The first vector.
    @param[in] point2 (array_like): The second vector.
    @param[in] degree (numeric): Degree of that is used for Minkowski distance.

    @return (double) Minkowski distance between two vectors.

    @see euclidean_distance


distance = <NUM_LIT:0.0><EOL>for i in range(len(point1)):<EOL><INDENT>divider = abs(point1[i]) + abs(point2[i])<EOL>if divider == <NUM_LIT:0.0>:<EOL><INDENT>continue<EOL><DEDENT>distance += ((point1[i] - point2[i]) ** <NUM_LIT>) / divider<EOL><DEDENT>return distance<EOL>

!
    @brief Calculate Chi square distance between two vectors.

    \f[
    dist(a, b) = \sum_{i=0}^{N}\frac{\left ( a_{i} - b_{i} \right )^{2}}{\left | a_{i} \right | + \left | b_{i} \right |};
    \f]

    @param[in] point1 (array_like): The first vector.
    @param[in] point2 (array_like): The second vector.

    @return (float) Chi square distance between two objects.


def draw_graph(graph_instance, map_coloring = None):

if (graph_instance.space_description is None):<EOL><INDENT>raise NameError("<STR_LIT>");<EOL><DEDENT>if (map_coloring is not None):<EOL><INDENT>if (len(graph_instance) != len(map_coloring)):<EOL><INDENT>raise NameError("<STR_LIT>");<EOL><DEDENT><DEDENT>fig = plt.figure();<EOL>axes = fig.add_subplot(<NUM_LIT>);<EOL>available_colors = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', '<STR_LIT>'];<EOL>if (map_coloring is not None):<EOL><INDENT>if (len(map_coloring) > len(available_colors)):<EOL><INDENT>raise NameError('<STR_LIT>');<EOL><DEDENT><DEDENT>x_maximum = -float('<STR_LIT>');<EOL>x_minimum = float('<STR_LIT>');<EOL>y_maximum = -float('<STR_LIT>');<EOL>y_minimum = float('<STR_LIT>');<EOL>for i in range(<NUM_LIT:0>, len(graph_instance.space_description), <NUM_LIT:1>):<EOL><INDENT>if (graph_instance.type_graph_descr == type_graph_descr.GRAPH_MATRIX_DESCR):<EOL><INDENT>for j in range(i, len(graph_instance.space_description), <NUM_LIT:1>):    <EOL><INDENT>if (graph_instance.data[i][j] == <NUM_LIT:1>):<EOL><INDENT>axes.plot([graph_instance.space_description[i][<NUM_LIT:0>], graph_instance.space_description[j][<NUM_LIT:0>]], [graph_instance.space_description[i][<NUM_LIT:1>], graph_instance.space_description[j][<NUM_LIT:1>]], '<STR_LIT>', linewidth = <NUM_LIT>);<EOL><DEDENT><DEDENT><DEDENT>elif (graph_instance.type_graph_descr == type_graph_descr.GRAPH_VECTOR_DESCR):<EOL><INDENT>for j in graph_instance.data[i]:<EOL><INDENT>if (i > j):     <EOL><INDENT>axes.plot([graph_instance.space_description[i][<NUM_LIT:0>], graph_instance.space_description[j][<NUM_LIT:0>]], [graph_instance.space_description[i][<NUM_LIT:1>], graph_instance.space_description[j][<NUM_LIT:1>]], '<STR_LIT>', linewidth = <NUM_LIT>);   <EOL><DEDENT><DEDENT><DEDENT>color_node = '<STR_LIT:b>';<EOL>if (map_coloring is not None):<EOL><INDENT>color_node = colors.hex2color(available_colors[map_coloring[i]]);<EOL><DEDENT>axes.plot(graph_instance.space_description[i][<NUM_LIT:0>], graph_instance.space_description[i][<NUM_LIT:1>], color = color_node, marker = '<STR_LIT:o>', markersize = <NUM_LIT:20>);<EOL>if (x_maximum < graph_instance.space_description[i][<NUM_LIT:0>]): x_maximum = graph_instance.space_description[i][<NUM_LIT:0>];<EOL>if (x_minimum > graph_instance.space_description[i][<NUM_LIT:0>]): x_minimum = graph_instance.space_description[i][<NUM_LIT:0>];  <EOL>if (y_maximum < graph_instance.space_description[i][<NUM_LIT:1>]): y_maximum = graph_instance.space_description[i][<NUM_LIT:1>]; <EOL>if (y_minimum > graph_instance.space_description[i][<NUM_LIT:1>]): y_minimum = graph_instance.space_description[i][<NUM_LIT:1>];<EOL><DEDENT>plt.xlim(x_minimum - <NUM_LIT:0.5>, x_maximum + <NUM_LIT:0.5>);<EOL>plt.ylim(y_minimum - <NUM_LIT:0.5>, y_maximum + <NUM_LIT:0.5>);<EOL>plt.show()<EOL>

!
    @brief Draw graph.

    @param[in] graph_instance (graph): Graph that should be drawn.
    @param[in] map_coloring (list): List of color indexes for each vertex. Size of this list should be equal to size of graph (number of vertices).
                                    If it's not specified (None) than graph without coloring will be dwarn.

    @warning Graph can be represented if there is space representation for it.


file = open(filename, '<STR_LIT:r>');<EOL>comments = "<STR_LIT>";<EOL>space_descr = [];<EOL>data = [];<EOL>data_type = None;<EOL>map_data_repr = dict();   <EOL>for line in file:<EOL><INDENT>if (line[<NUM_LIT:0>] == '<STR_LIT:c>' or line[<NUM_LIT:0>] == '<STR_LIT:p>'): <EOL><INDENT>comments += line[<NUM_LIT:1>:]; <EOL><DEDENT>elif (line[<NUM_LIT:0>] == '<STR_LIT:r>'): <EOL><INDENT>node_coordinates = [float(val) for val in line[<NUM_LIT:1>:].split()];<EOL>if (len(node_coordinates) != <NUM_LIT:2>):<EOL><INDENT>raise NameError('<STR_LIT>');<EOL><DEDENT>space_descr.append( [float(val) for val in line[<NUM_LIT:1>:].split()] );<EOL><DEDENT>elif (line[<NUM_LIT:0>] == '<STR_LIT:m>'):<EOL><INDENT>if ( (data_type is not None) and (data_type != '<STR_LIT:m>') ):<EOL><INDENT>raise NameError('<STR_LIT>');<EOL><DEDENT>data_type = '<STR_LIT:m>';<EOL>data.append( [float(val) for val in line[<NUM_LIT:1>:].split()] );<EOL><DEDENT>elif (line[<NUM_LIT:0>] == '<STR_LIT:v>'):<EOL><INDENT>if ( (data_type is not None) and (data_type != '<STR_LIT:v>') ):<EOL><INDENT>raise NameError('<STR_LIT>');<EOL><DEDENT>data_type = '<STR_LIT:v>';<EOL>data.append( [float(val) for val in line[<NUM_LIT:1>:].split()] );<EOL><DEDENT>elif (line[<NUM_LIT:0>] == '<STR_LIT:e>'):<EOL><INDENT>if ( (data_type is not None) and (data_type != '<STR_LIT:e>') ):<EOL><INDENT>raise NameError('<STR_LIT>');<EOL><DEDENT>data_type = '<STR_LIT:e>';<EOL>vertices = [int(val) for val in line[<NUM_LIT:1>:].split()];<EOL>if (vertices[<NUM_LIT:0>] not in map_data_repr):<EOL><INDENT>map_data_repr[ vertices[<NUM_LIT:0>] ] = [ vertices[<NUM_LIT:1>] ];<EOL><DEDENT>else:<EOL><INDENT>map_data_repr[ vertices[<NUM_LIT:0>] ].append(vertices[<NUM_LIT:1>])<EOL><DEDENT>if (vertices[<NUM_LIT:1>] not in map_data_repr):<EOL><INDENT>map_data_repr[ vertices[<NUM_LIT:1>] ] = [ vertices[<NUM_LIT:0>] ];<EOL><DEDENT>else:<EOL><INDENT>map_data_repr[ vertices[<NUM_LIT:1>] ].append(vertices[<NUM_LIT:0>]);<EOL><DEDENT><DEDENT>elif (len(line.strip()) == <NUM_LIT:0>): continue;<EOL>else: <EOL><INDENT>print(line);<EOL>raise NameError('<STR_LIT>');<EOL><DEDENT><DEDENT>if (data_type == '<STR_LIT:e>'):<EOL><INDENT>for index in range(len(map_data_repr)):<EOL><INDENT>data.append([<NUM_LIT:0>] * len(map_data_repr));<EOL>for index_neighbour in map_data_repr[index + <NUM_LIT:1>]:<EOL><INDENT>data[index][index_neighbour - <NUM_LIT:1>] = <NUM_LIT:1>;<EOL><DEDENT><DEDENT><DEDENT>file.close();<EOL>graph_descr = None;<EOL>if (data_type == '<STR_LIT:m>'): graph_descr = type_graph_descr.GRAPH_MATRIX_DESCR;<EOL>elif (data_type == '<STR_LIT:v>'): graph_descr = type_graph_descr.GRAPH_VECTOR_DESCR;<EOL>elif (data_type == '<STR_LIT:e>'): graph_descr = type_graph_descr.GRAPH_MATRIX_DESCR;<EOL>else:<EOL><INDENT>raise NameError('<STR_LIT>');<EOL><DEDENT>if (space_descr != []):<EOL><INDENT>if (len(data) != len(space_descr)):<EOL><INDENT>raise NameError("<STR_LIT>");<EOL><DEDENT><DEDENT>return graph(data, graph_descr, space_descr, comments)<EOL>

!
    @brief Read graph from file in GRPR format.

    @param[in] filename (string): Path to file with graph in GRPR format.

    @return (graph) Graph that is read from file.


return len(self.__data)<EOL>

!
        @return (uint) Size of graph defined by number of vertices.


if (self.__space_descr == [] or self.__space_descr is None):<EOL><INDENT>return None;<EOL><DEDENT>return self.__space_descr<EOL>

!
        @return (list) Space description.


return color.TITLES[sequential_index % len(color.TITLES)]<EOL>

!
        @brief Returns color using round robin to avoid out of range exception.

        @param[in] sequential_index (uint): Index that should be converted to valid color index.

        @return (uint) Color from list color.TITLES.


for row in range(<NUM_LIT:0>, len(graph_matrix)):<EOL><INDENT>for column in range (<NUM_LIT:0>, len(graph_matrix[row])):<EOL><INDENT>if (graph_matrix[row][column] > <NUM_LIT:0>):<EOL><INDENT>self.set_connection(row, column);<EOL><DEDENT><DEDENT><DEDENT>

!
        @brief Creates connection in the network in line with graph.

        @param[in] graph_matrix (list): Matrix representation of the graph.


def allocate_color_clusters(self, tolerance = <NUM_LIT:0.1>):

return self.allocate_sync_ensembles(tolerance)<EOL>

!
        @brief Allocates clusters, when one cluster defines only one color.

        @param[in] tolerance (double): Defines maximum deviation between phases.

        @return (list) Clusters [vertices with color 1], [vertices with color 2], ..., [vertices with color n].


def allocate_map_coloring(self, tolerance = <NUM_LIT:0.1>):

clusters = self.allocate_color_clusters(tolerance);<EOL>number_oscillators = len(self._dynamic[<NUM_LIT:0>]);<EOL>coloring_map = [<NUM_LIT:0>] * number_oscillators;<EOL>for color_index in range(len(clusters)):<EOL><INDENT>for node_index in clusters[color_index]:<EOL><INDENT>coloring_map[node_index] = color_index;<EOL><DEDENT><DEDENT>return coloring_map<EOL>

!
        @brief Allocates coloring map for graph that has been processed.

        @param[in] tolerance (double): Defines maximum deviation between phases.

        @return (list) Colors for each node (index of node in graph), for example [color1, color2, color2, ...].


def _phase_kuramoto(self, teta, t, argv):

index = argv;<EOL>phase = <NUM_LIT:0>;<EOL>for k in range(<NUM_LIT:0>, self._num_osc):<EOL><INDENT>if (self.has_connection(index, k) == True):<EOL><INDENT>phase += self._negative_weight * math.sin(self._phases[k] - teta);<EOL><DEDENT>else:<EOL><INDENT>phase += self._positive_weight * math.sin(self._phases[k] - teta);<EOL><DEDENT><DEDENT>return ( phase / self._reduction )<EOL>

!
        @brief Returns result of phase calculation for oscillator in the network.

        @param[in] teta (double): Value of phase of the oscillator with index argv in the network.
        @param[in] t (double): Unused, can be ignored.
        @param[in] argv (uint): Index of the oscillator in the network.

        @return (double) New value of phase for oscillator with index argv.


def __init__(self, phase, time, pointer_sync_analyser):

super().__init__(phase, time, pointer_sync_analyser)<EOL>

!
        @brief Constructor of the analyser.

        @param[in] phase (list): Output dynamic of the oscillatory network, where one iteration consists of all phases of oscillators.
        @param[in] time (list): Simulation time.
        @param[in] pointer_sync_analyser (POINTER): Pointer to CCORE analyser, if specified then other arguments can be omitted.


def process(self, steps, time, collect_dynamic=True):

output_dynamic = super().simulate(steps, time, collect_dynamic=collect_dynamic)<EOL>return hysteresis_analyser(output_dynamic.output, output_dynamic.time)<EOL>

!
        @brief Peforms graph coloring analysis using simulation of the oscillatory network.

        @param[in] steps (uint): Number steps of simulations during simulation.
        @param[in] time (double): Time of simulation.
        @param[in] collect_dynamic (bool): Specified requirement to collect whole dynamic of the network.

        @return (hysteresis_analyser) Returns analyser of results of clustering.


def __init__(self, graph_matrix, alpha, eps):

number_oscillators = len(graph_matrix)<EOL>super().__init__(number_oscillators)<EOL>self._states = [<NUM_LIT:0>] * self._num_osc<EOL>for i in range(<NUM_LIT:0>, self._num_osc):<EOL><INDENT>self._states[i] = <NUM_LIT:1> - (<NUM_LIT:2> / self._num_osc) * i<EOL><DEDENT>self._outputs = [-<NUM_LIT:1>] * self._num_osc<EOL>self._outputs_buffer = [-<NUM_LIT:1>] * self._num_osc<EOL>self._time_contant = <NUM_LIT:1><EOL>self._weight = []<EOL>for row in range(<NUM_LIT:0>, self._num_osc):<EOL><INDENT>self._weight.append([<NUM_LIT:0>] * self._num_osc)<EOL>for col in range(<NUM_LIT:0>, self._num_osc):<EOL><INDENT>if (row != col):<EOL><INDENT>self._weight[row][col] = -alpha * (graph_matrix[row][col]) / sum(graph_matrix[row])<EOL><DEDENT>else:<EOL><INDENT>self._weight[row][col] = -alpha - eps<EOL><DEDENT><DEDENT><DEDENT>

!
        @brief Constructor of hysteresis oscillatory network for graph coloring.

        @param[in] graph_matrix (list): Matrix representation of a graph.
        @param[in] alpha (double): Positive constant (affect weight between two oscillators w[i][j]).
        @param[in] eps (double): Positive constant (affect feedback to itself (i = j) of each oscillator w[i][j] = -alpha - eps).


super().__init__(amplitudes, time)<EOL>

!
        @brief Constructor of the analyser.

        @param[in] amplitudes (list): Output dynamic of the hysteresis oscillatory network, where one iteration consists of all amplitudes of oscillators.
        @param[in] time (list): Simulation time (timestamps of simulation steps) when amplitudes are stored.


def allocate_map_coloring(self, tolerance, threshold_steps = <NUM_LIT:10>):

clusters = self.allocate_clusters(tolerance, threshold_steps)<EOL>coloring_map = [<NUM_LIT:0>] * len(self._dynamic[<NUM_LIT:0>])<EOL>for color_index in range(len(clusters)):<EOL><INDENT>for node_index in clusters[color_index]:<EOL><INDENT>coloring_map[node_index] = color_index<EOL><DEDENT><DEDENT>return coloring_map<EOL>

!
        @brief Returns list of color indexes that are assigned to each object from input data space accordingly.

        @param[in] tolerance (double): Tolerance level that define maximal difference between outputs of oscillators in one synchronous ensemble.
        @param[in] threshold_steps (uint): Number of steps from the end of simulation that should be analysed for ensemble allocation.
                    If amount of simulation steps has been less than threshold steps than amount of steps will be reduced to amount
                    of simulation steps.

        @remark Results can be obtained only after network simulation (graph processing by the network).

        @return (list) Color indexes that are assigned to each object from input data space accordingly.

        @see allocate_clusters()


template_graph_coloring(GRAPH_SIMPLE_SAMPLES.GRAPH_FIVE_POINTED_FRAME_STAR, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:30>)<EOL>


template_graph_coloring(GRAPH_SIMPLE_SAMPLES.GRAPH_FULL1, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:20>, tolerance = <NUM_LIT>)<EOL>

Bad result - two vertices colored by the same color


template_graph_coloring(GRAPH_SIMPLE_SAMPLES.GRAPH_ONE_LINE, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:20>)<EOL>


template_graph_coloring(GRAPH_SIMPLE_SAMPLES.GRAPH_ONE_CROSSROAD, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:20>)<EOL>


template_graph_coloring(GRAPH_SIMPLE_SAMPLES.GRAPH_TWO_CROSSROADS, <NUM_LIT>, <NUM_LIT>, <NUM_LIT>, <NUM_LIT:20>)<EOL>


def __get_amount_color(self, node_indexes, color_number):

color_counter = <NUM_LIT:0>;  <EOL>for index in node_indexes:<EOL><INDENT>if (self.__coloring[index] == color_number):<EOL><INDENT>color_counter += <NUM_LIT:1>;<EOL><DEDENT><DEDENT>return color_counter<EOL>

!
        @brief Countes how many nodes has color 'color_number'.

        @param[in] node_indexes (list): Indexes of graph nodes for checking.
        @param[in] color_number (uint): Number of color that is searched in nodes.

        @return (uint) Number found nodes with the specified color 'color_number'.


color_counter = <NUM_LIT:1>;<EOL>degrees = list();<EOL>saturation_degrees = [<NUM_LIT:0>] * len(self.__data_pointer);<EOL>self.__coloring = [<NUM_LIT:0>] * len(self.__data_pointer);<EOL>uncolored_vertices = set(range(len(self.__data_pointer)));<EOL>index_maximum_degree = <NUM_LIT:0>;<EOL>maximum_degree = <NUM_LIT:0>;<EOL>for index_node in range(len(self.__data_pointer)):<EOL><INDENT>degrees.append( ( sum(self.__data_pointer[index_node]), index_node ) );<EOL>if (degrees[index_node][<NUM_LIT:0>] > maximum_degree):<EOL><INDENT>(maximum_degree, node_index) = degrees[index_node];<EOL>index_maximum_degree = index_node;<EOL><DEDENT><DEDENT>neighbors = self.__get_neighbors(index_maximum_degree);<EOL>for index_neighbor in neighbors:<EOL><INDENT>saturation_degrees[index_neighbor] += <NUM_LIT:1>;<EOL><DEDENT>self.__coloring[index_maximum_degree] = color_counter;<EOL>uncolored_vertices.remove(index_maximum_degree);<EOL>while(len(uncolored_vertices) > <NUM_LIT:0>):<EOL><INDENT>maximum_satur_degree = -<NUM_LIT:1>;<EOL>for index in uncolored_vertices:<EOL><INDENT>if (saturation_degrees[index] > maximum_satur_degree):<EOL><INDENT>maximum_satur_degree = saturation_degrees[index];<EOL><DEDENT><DEDENT>indexes_maximum_satur_degree = [index for index in uncolored_vertices if saturation_degrees[index] == maximum_satur_degree];           <EOL>coloring_index = indexes_maximum_satur_degree[<NUM_LIT:0>];<EOL>if (len(indexes_maximum_satur_degree) > <NUM_LIT:1>): <EOL><INDENT>maximum_degree = -<NUM_LIT:1>;<EOL>for index in indexes_maximum_satur_degree:<EOL><INDENT>(degree, node_index) = degrees[index];<EOL>if (degree > maximum_degree):<EOL><INDENT>coloring_index = node_index;<EOL>maximum_degree = degree;<EOL><DEDENT><DEDENT><DEDENT>node_index_neighbors = self.__get_neighbors(coloring_index);<EOL>for number_color in range(<NUM_LIT:1>, color_counter + <NUM_LIT:1>, <NUM_LIT:1>):<EOL><INDENT>if (self.__get_amount_color(node_index_neighbors, number_color) == <NUM_LIT:0>):<EOL><INDENT>self.__coloring[coloring_index] = number_color;<EOL>break;<EOL><DEDENT><DEDENT>if (self.__coloring[coloring_index] == <NUM_LIT:0>):<EOL><INDENT>color_counter += <NUM_LIT:1>;     <EOL>self.__coloring[coloring_index] = color_counter;<EOL><DEDENT>uncolored_vertices.remove(coloring_index);<EOL>for index_neighbor in node_index_neighbors:<EOL><INDENT>subneighbors = self.__get_neighbors(index_neighbor);<EOL>if (self.__get_amount_color(subneighbors, self.__coloring[coloring_index]) == <NUM_LIT:1>):<EOL><INDENT>saturation_degrees[index_neighbor] += <NUM_LIT:1>;<EOL><DEDENT><DEDENT><DEDENT>

!
        @brief Perform graph coloring using DSATUR algorithm.

        @see get_colors()


if (self.__radius is not None):<EOL><INDENT>return self.__radius;<EOL><DEDENT>centroid = self.get_centroid();<EOL>radius_part_1 = self.square_sum;<EOL>radius_part_2 = <NUM_LIT:0.0>;<EOL>radius_part_3 = <NUM_LIT:0.0>;<EOL>if (type(centroid) == list):<EOL><INDENT>radius_part_2 = <NUM_LIT> * sum(list_math_multiplication(self.linear_sum, centroid));<EOL>radius_part_3 = self.number_points * sum(list_math_multiplication(centroid, centroid));<EOL><DEDENT>else:<EOL><INDENT>radius_part_2 = <NUM_LIT> * self.linear_sum * centroid;<EOL>radius_part_3 = self.number_points * centroid * centroid;<EOL><DEDENT>self.__radius = ( (<NUM_LIT:1.0> / self.number_points) * (radius_part_1 - radius_part_2 + radius_part_3) ) ** <NUM_LIT:0.5>;<EOL>return self.__radius<EOL>

!
        @brief Calculates radius of cluster that is represented by the entry.
        @details It's calculated once when it's requested after the last changes.

        @return (double) Radius of cluster that is represented by the entry.


def __init__(self, feature, parent, entries, payload):

super().__init__(feature, parent, payload);<EOL>self.type = cfnode_type.CFNODE_LEAF;<EOL>self.__entries = entries<EOL>

!
        @brief Create CF Leaf node.

        @param[in] feature (cfentry): Clustering feature of the created node.
        @param[in] parent (non_leaf_node): Parent of the created node.
        @param[in] entries (list): List of entries of the node.
        @param[in] payload (*): Data that is stored by the node.


nearest_node1 = None;<EOL>nearest_node2 = None;<EOL>nearest_distance = float("<STR_LIT>");<EOL>for i in range(<NUM_LIT:0>, len(self.successors)):<EOL><INDENT>candidate1 = self.successors[i];<EOL>for j in range(i + <NUM_LIT:1>, len(self.successors)):<EOL><INDENT>candidate2 = self.successors[j];<EOL>candidate_distance = candidate1.get_distance(candidate2, type_measurement);<EOL>if (candidate_distance < nearest_distance):<EOL><INDENT>nearest_distance = candidate_distance;<EOL>nearest_node1 = candidate1;<EOL>nearest_node2 = candidate2;<EOL><DEDENT><DEDENT><DEDENT>return [nearest_node1, nearest_node2]<EOL>

!
        @brief Find pair of nearest successors of the node in line with measurement type.

        @param[in] type_measurement (measurement_type): Measurement type that is used for obtaining nearest successors.

        @return (list) Pair of nearest successors represented by list.


self.feature += node.feature;<EOL>for child in node.successors:<EOL><INDENT>child.parent = self;<EOL>self.successors.append(child);<EOL><DEDENT>

!
        @brief Merge non-leaf node to the current.

        @param[in] node (non_leaf_node): Non-leaf node that should be merged with current.


linear_part_first = list_math_addition(self.linear_sum, entry.linear_sum);<EOL>linear_part_second = linear_part_first;<EOL>linear_part_distance = sum(list_math_multiplication(linear_part_first, linear_part_second));<EOL>general_part_distance = <NUM_LIT> * (self.number_points + entry.number_points) * (self.square_sum + entry.square_sum) - <NUM_LIT> * linear_part_distance;<EOL>return (general_part_distance / ( (self.number_points + entry.number_points) * (self.number_points + entry.number_points - <NUM_LIT:1.0>) )) ** <NUM_LIT:0.5><EOL>

!
        @brief Calculates average intra cluster distance between current and specified clusters.

        @param[in] entry (cfentry): Clustering feature to which distance should be obtained.

        @return (double) Average intra cluster distance.