Search is not available for this dataset
text stringlengths 75 104k |
|---|
def __process_by_ccore(self):
"""!
@brief Performs processing using C++ implementation.
"""
if isinstance(self.__initializer, kmeans_plusplus_initializer):
initializer = wrapper.elbow_center_initializer.KMEANS_PLUS_PLUS
else:
initializer = wrapper.elbow_center_initializer.RANDOM
result = wrapper.elbow(self.__data, self.__kmin, self.__kmax, initializer)
self.__kvalue = result[0]
self.__wce = result[1] |
def __process_by_python(self):
"""!
@brief Performs processing using python implementation.
"""
for amount in range(self.__kmin, self.__kmax):
centers = self.__initializer(self.__data, amount).initialize()
instance = kmeans(self.__data, centers, ccore=True)
instance.process()
self.__wce.append(instance.get_total_wce())
self.__calculate_elbows()
self.__find_optimal_kvalue() |
def __calculate_elbows(self):
"""!
@brief Calculates potential elbows.
@details Elbow is calculated as a distance from each point (x, y) to segment from kmin-point (x0, y0) to kmax-point (x1, y1).
"""
x0, y0 = 0.0, self.__wce[0]
x1, y1 = float(len(self.__wce)), self.__wce[-1]
for index_elbow in range(1, len(self.__wce) - 1):
x, y = float(index_elbow), self.__wce[index_elbow]
segment = abs((y0 - y1) * x + (x1 - x0) * y + (x0 * y1 - x1 * y0))
norm = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)
distance = segment / norm
self.__elbows.append(distance) |
def __find_optimal_kvalue(self):
"""!
@brief Finds elbow and returns corresponding K-value.
"""
optimal_elbow_value = max(self.__elbows)
self.__kvalue = self.__elbows.index(optimal_elbow_value) + 1 + self.__kmin |
def show_ordering_diagram(analyser, amount_clusters = None):
"""!
@brief Display cluster-ordering (reachability-plot) diagram.
@param[in] analyser (ordering_analyser): cluster-ordering analyser whose ordering diagram should be displayed.
@param[in] amount_clusters (uint): if it is not 'None' then it displays connectivity radius line that can used for allocation of specified amount of clusters
and colorize diagram by corresponding cluster colors.
Example demonstrates general abilities of 'ordering_visualizer' class:
@code
# Display cluster-ordering diagram with connectivity radius is used for allocation of three clusters.
ordering_visualizer.show_ordering_diagram(analyser, 3);
# Display cluster-ordering diagram without radius.
ordering_visualizer.show_ordering_diagram(analyser);
@endcode
"""
ordering = analyser.cluster_ordering
axis = plt.subplot(111)
if amount_clusters is not None:
radius, borders = analyser.calculate_connvectivity_radius(amount_clusters)
# divide into cluster groups to visualize by colors
left_index_border = 0
current_index_border = 0
for index_border in range(len(borders)):
right_index_border = borders[index_border]
axis.bar(range(left_index_border, right_index_border), ordering[left_index_border:right_index_border], width = 1.0, color = color_list.TITLES[index_border])
left_index_border = right_index_border
current_index_border = index_border
axis.bar(range(left_index_border, len(ordering)), ordering[left_index_border:len(ordering)], width = 1.0, color = color_list.TITLES[current_index_border + 1])
plt.xlim([0, len(ordering)])
plt.axhline(y = radius, linewidth = 2, color = 'black')
plt.text(0, radius + radius * 0.03, " Radius: " + str(round(radius, 4)) + ";\n Clusters: " + str(amount_clusters), color = 'b', fontsize = 10)
else:
axis.bar(range(0, len(ordering)), ordering[0:len(ordering)], width = 1.0, color = 'black')
plt.xlim([0, len(ordering)])
plt.show() |
def calculate_connvectivity_radius(self, amount_clusters, maximum_iterations = 100):
"""!
@brief Calculates connectivity radius of allocation specified amount of clusters using ordering diagram and marks borders of clusters using indexes of values of ordering diagram.
@details Parameter 'maximum_iterations' is used to protect from hanging when it is impossible to allocate specified number of clusters.
@param[in] amount_clusters (uint): amount of clusters that should be allocated by calculated connectivity radius.
@param[in] maximum_iterations (uint): maximum number of iteration for searching connectivity radius to allocated specified amount of clusters (by default it is restricted by 100 iterations).
@return (double, list) Value of connectivity radius and borders of clusters like (radius, borders), radius may be 'None' as well as borders may be '[]'
if connectivity radius hasn't been found for the specified amount of iterations.
"""
maximum_distance = max(self.__ordering)
upper_distance = maximum_distance
lower_distance = 0.0
result = None
amount, borders = self.extract_cluster_amount(maximum_distance)
if amount <= amount_clusters:
for _ in range(maximum_iterations):
radius = (lower_distance + upper_distance) / 2.0
amount, borders = self.extract_cluster_amount(radius)
if amount == amount_clusters:
result = radius
break
elif amount == 0:
break
elif amount > amount_clusters:
lower_distance = radius
elif amount < amount_clusters:
upper_distance = radius
return result, borders |
def extract_cluster_amount(self, radius):
"""!
@brief Obtains amount of clustering that can be allocated by using specified radius for ordering diagram and borders between them.
@details When growth of reachability-distances is detected than it is considered as a start point of cluster,
than pick is detected and after that recession is observed until new growth (that means end of the
current cluster and start of a new one) or end of diagram.
@param[in] radius (double): connectivity radius that is used for cluster allocation.
@return (unit, list) Amount of clusters that can be allocated by the connectivity radius on ordering diagram and borders between them using indexes
from ordering diagram (amount_clusters, border_clusters).
"""
amount_clusters = 1
cluster_start = False
cluster_pick = False
total_similarity = True
previous_cluster_distance = None
previous_distance = None
cluster_borders = []
for index_ordering in range(len(self.__ordering)):
distance = self.__ordering[index_ordering]
if distance >= radius:
if cluster_start is False:
cluster_start = True
amount_clusters += 1
if index_ordering != 0:
cluster_borders.append(index_ordering)
else:
if (distance < previous_cluster_distance) and (cluster_pick is False):
cluster_pick = True
elif (distance > previous_cluster_distance) and (cluster_pick is True):
cluster_pick = False
amount_clusters += 1
if index_ordering != 0:
cluster_borders.append(index_ordering)
previous_cluster_distance = distance
else:
cluster_start = False
cluster_pick = False
if (previous_distance is not None) and (distance != previous_distance):
total_similarity = False
previous_distance = distance
if (total_similarity is True) and (previous_distance > radius):
amount_clusters = 0
return amount_clusters, cluster_borders |
def __process_by_ccore(self):
"""!
@brief Performs cluster analysis using CCORE (C/C++ part of pyclustering library).
"""
(self.__clusters, self.__noise, self.__ordering, self.__eps,
objects_indexes, objects_core_distances, objects_reachability_distances) = \
wrapper.optics(self.__sample_pointer, self.__eps, self.__minpts, self.__amount_clusters, self.__data_type)
self.__optics_objects = []
for i in range(len(objects_indexes)):
if objects_core_distances[i] < 0.0:
objects_core_distances[i] = None
if objects_reachability_distances[i] < 0.0:
objects_reachability_distances[i] = None
optics_object = optics_descriptor(objects_indexes[i], objects_core_distances[i], objects_reachability_distances[i])
optics_object.processed = True
self.__optics_objects.append(optics_object) |
def __process_by_python(self):
"""!
@brief Performs cluster analysis using python code.
"""
if self.__data_type == 'points':
self.__kdtree = kdtree(self.__sample_pointer, range(len(self.__sample_pointer)))
self.__allocate_clusters()
if (self.__amount_clusters is not None) and (self.__amount_clusters != len(self.get_clusters())):
analyser = ordering_analyser(self.get_ordering())
radius, _ = analyser.calculate_connvectivity_radius(self.__amount_clusters)
if radius is not None:
self.__eps = radius
self.__allocate_clusters() |
def __initialize(self, sample):
"""!
@brief Initializes internal states and resets clustering results in line with input sample.
"""
self.__processed = [False] * len(sample)
self.__optics_objects = [optics_descriptor(i) for i in range(len(sample))] # List of OPTICS objects that corresponds to objects from input sample.
self.__ordered_database = [] # List of OPTICS objects in traverse order.
self.__clusters = None # Result of clustering (list of clusters where each cluster contains indexes of objects from input data).
self.__noise = None |
def __allocate_clusters(self):
"""!
@brief Performs cluster allocation and builds ordering diagram that is based on reachability-distances.
"""
self.__initialize(self.__sample_pointer)
for optic_object in self.__optics_objects:
if optic_object.processed is False:
self.__expand_cluster_order(optic_object)
self.__extract_clusters() |
def get_ordering(self):
"""!
@brief Returns clustering ordering information about the input data set.
@details Clustering ordering of data-set contains the information about the internal clustering structure in line with connectivity radius.
@return (ordering_analyser) Analyser of clustering ordering.
@see process()
@see get_clusters()
@see get_noise()
@see get_radius()
@see get_optics_objects()
"""
if self.__ordering is None:
self.__ordering = []
for cluster in self.__clusters:
for index_object in cluster:
optics_object = self.__optics_objects[index_object]
if optics_object.reachability_distance is not None:
self.__ordering.append(optics_object.reachability_distance)
return self.__ordering |
def __create_neighbor_searcher(self, data_type):
"""!
@brief Returns neighbor searcher in line with data type.
@param[in] data_type (string): Data type (points or distance matrix).
"""
if data_type == 'points':
return self.__neighbor_indexes_points
elif data_type == 'distance_matrix':
return self.__neighbor_indexes_distance_matrix
else:
raise TypeError("Unknown type of data is specified '%s'" % data_type) |
def __expand_cluster_order(self, optics_object):
"""!
@brief Expand cluster order from not processed optic-object that corresponds to object from input data.
Traverse procedure is performed until objects are reachable from core-objects in line with connectivity radius.
Order database is updated during expanding.
@param[in] optics_object (optics_descriptor): Object that hasn't been processed.
"""
optics_object.processed = True
neighbors_descriptor = self.__neighbor_searcher(optics_object)
optics_object.reachability_distance = None
self.__ordered_database.append(optics_object)
# Check core distance
if len(neighbors_descriptor) >= self.__minpts:
neighbors_descriptor.sort(key = lambda obj: obj[1])
optics_object.core_distance = neighbors_descriptor[self.__minpts - 1][1]
# Continue processing
order_seed = list()
self.__update_order_seed(optics_object, neighbors_descriptor, order_seed)
while len(order_seed) > 0:
optic_descriptor = order_seed[0]
order_seed.remove(optic_descriptor)
neighbors_descriptor = self.__neighbor_searcher(optic_descriptor)
optic_descriptor.processed = True
self.__ordered_database.append(optic_descriptor)
if len(neighbors_descriptor) >= self.__minpts:
neighbors_descriptor.sort(key = lambda obj: obj[1])
optic_descriptor.core_distance = neighbors_descriptor[self.__minpts - 1][1]
self.__update_order_seed(optic_descriptor, neighbors_descriptor, order_seed)
else:
optic_descriptor.core_distance = None
else:
optics_object.core_distance = None |
def __extract_clusters(self):
"""!
@brief Extract clusters and noise from order database.
"""
self.__clusters = []
self.__noise = []
current_cluster = self.__noise
for optics_object in self.__ordered_database:
if (optics_object.reachability_distance is None) or (optics_object.reachability_distance > self.__eps):
if (optics_object.core_distance is not None) and (optics_object.core_distance <= self.__eps):
self.__clusters.append([ optics_object.index_object ])
current_cluster = self.__clusters[-1]
else:
self.__noise.append(optics_object.index_object)
else:
current_cluster.append(optics_object.index_object) |
def __update_order_seed(self, optic_descriptor, neighbors_descriptors, order_seed):
"""!
@brief Update sorted list of reachable objects (from core-object) that should be processed using neighbors of core-object.
@param[in] optic_descriptor (optics_descriptor): Core-object whose neighbors should be analysed.
@param[in] neighbors_descriptors (list): List of neighbors of core-object.
@param[in|out] order_seed (list): List of sorted object in line with reachable distance.
"""
for neighbor_descriptor in neighbors_descriptors:
index_neighbor = neighbor_descriptor[0]
current_reachable_distance = neighbor_descriptor[1]
if self.__optics_objects[index_neighbor].processed is not True:
reachable_distance = max(current_reachable_distance, optic_descriptor.core_distance)
if self.__optics_objects[index_neighbor].reachability_distance is None:
self.__optics_objects[index_neighbor].reachability_distance = reachable_distance
# insert element in queue O(n) - worst case.
index_insertion = len(order_seed)
for index_seed in range(0, len(order_seed)):
if reachable_distance < order_seed[index_seed].reachability_distance:
index_insertion = index_seed
break
order_seed.insert(index_insertion, self.__optics_objects[index_neighbor])
else:
if reachable_distance < self.__optics_objects[index_neighbor].reachability_distance:
self.__optics_objects[index_neighbor].reachability_distance = reachable_distance
order_seed.sort(key = lambda obj: obj.reachability_distance) |
def __neighbor_indexes_points(self, optic_object):
"""!
@brief Return neighbors of the specified object in case of sequence of points.
@param[in] optic_object (optics_descriptor): Object for which neighbors should be returned in line with connectivity radius.
@return (list) List of indexes of neighbors in line the connectivity radius.
"""
kdnodes = self.__kdtree.find_nearest_dist_nodes(self.__sample_pointer[optic_object.index_object], self.__eps)
return [[node_tuple[1].payload, math.sqrt(node_tuple[0])] for node_tuple in kdnodes if
node_tuple[1].payload != optic_object.index_object] |
def __neighbor_indexes_distance_matrix(self, optic_object):
"""!
@brief Return neighbors of the specified object in case of distance matrix.
@param[in] optic_object (optics_descriptor): Object for which neighbors should be returned in line with connectivity radius.
@return (list) List of indexes of neighbors in line the connectivity radius.
"""
distances = self.__sample_pointer[optic_object.index_object]
return [[index_neighbor, distances[index_neighbor]] for index_neighbor in range(len(distances))
if ((distances[index_neighbor] <= self.__eps) and (index_neighbor != optic_object.index_object))] |
def process(self):
"""!
@brief Performs cluster analysis in line with rules of BIRCH algorithm.
@remark Results of clustering can be obtained using corresponding gets methods.
@see get_clusters()
"""
self.__insert_data();
self.__extract_features();
# in line with specification modify hierarchical algorithm should be used for further clustering
current_number_clusters = len(self.__features);
while (current_number_clusters > self.__number_clusters):
indexes = self.__find_nearest_cluster_features();
self.__features[indexes[0]] += self.__features[indexes[1]];
self.__features.pop(indexes[1]);
current_number_clusters = len(self.__features);
# decode data
self.__decode_data(); |
def __extract_features(self):
"""!
@brief Extracts features from CF-tree cluster.
"""
self.__features = [];
if (len(self.__tree.leafes) == 1):
# parameters are too general, copy all entries
for entry in self.__tree.leafes[0].entries:
self.__features.append(entry);
else:
# copy all leaf clustering features
for node in self.__tree.leafes:
self.__features.append(node.feature); |
def __decode_data(self):
"""!
@brief Decodes data from CF-tree features.
"""
self.__clusters = [ [] for _ in range(self.__number_clusters) ];
self.__noise = [];
for index_point in range(0, len(self.__pointer_data)):
(_, cluster_index) = self.__get_nearest_feature(self.__pointer_data[index_point], self.__features);
self.__clusters[cluster_index].append(index_point); |
def __insert_data(self):
"""!
@brief Inserts input data to the tree.
@remark If number of maximum number of entries is exceeded than diameter is increased and tree is rebuilt.
"""
for index_point in range(0, len(self.__pointer_data)):
point = self.__pointer_data[index_point];
self.__tree.insert_cluster( [ point ] );
if (self.__tree.amount_entries > self.__entry_size_limit):
self.__tree = self.__rebuild_tree(index_point); |
def __rebuild_tree(self, index_point):
"""!
@brief Rebuilt tree in case of maxumum number of entries is exceeded.
@param[in] index_point (uint): Index of point that is used as end point of re-building.
@return (cftree) Rebuilt tree with encoded points till specified point from input data space.
"""
rebuild_result = False;
increased_diameter = self.__tree.threshold * self.__diameter_multiplier;
tree = None;
while(rebuild_result is False):
# increase diameter and rebuild tree
if (increased_diameter == 0.0):
increased_diameter = 1.0;
# build tree with update parameters
tree = cftree(self.__tree.branch_factor, self.__tree.max_entries, increased_diameter, self.__tree.type_measurement);
for index_point in range(0, index_point + 1):
point = self.__pointer_data[index_point];
tree.insert_cluster([point]);
if (tree.amount_entries > self.__entry_size_limit):
increased_diameter *= self.__diameter_multiplier;
continue;
# Re-build is successful.
rebuild_result = True;
return tree; |
def __find_nearest_cluster_features(self):
"""!
@brief Find pair of nearest CF entries.
@return (list) List of two nearest enties that are represented by list [index_point1, index_point2].
"""
minimum_distance = float("Inf");
index1 = 0;
index2 = 0;
for index_candidate1 in range(0, len(self.__features)):
feature1 = self.__features[index_candidate1];
for index_candidate2 in range(index_candidate1 + 1, len(self.__features)):
feature2 = self.__features[index_candidate2];
distance = feature1.get_distance(feature2, self.__measurement_type);
if (distance < minimum_distance):
minimum_distance = distance;
index1 = index_candidate1;
index2 = index_candidate2;
return [index1, index2]; |
def __get_nearest_feature(self, point, feature_collection):
"""!
@brief Find nearest entry for specified point.
@param[in] point (list): Pointer to point from input dataset.
@param[in] feature_collection (list): Feature collection that is used for obtaining nearest feature for the specified point.
@return (double, uint) Tuple of distance to nearest entry to the specified point and index of that entry.
"""
minimum_distance = float("Inf");
index_nearest_feature = -1;
for index_entry in range(0, len(feature_collection)):
point_entry = cfentry(1, linear_sum([ point ]), square_sum([ point ]));
distance = feature_collection[index_entry].get_distance(point_entry, self.__measurement_type);
if (distance < minimum_distance):
minimum_distance = distance;
index_nearest_feature = index_entry;
return (minimum_distance, index_nearest_feature); |
def __read_answer_from_line(self, index_point, line):
"""!
@brief Read information about point from the specific line and place it to cluster or noise in line with that
information.
@param[in] index_point (uint): Index point that should be placed to cluster or noise.
@param[in] line (string): Line where information about point should be read.
"""
if line[0] == 'n':
self.__noise.append(index_point)
else:
index_cluster = int(line)
if index_cluster >= len(self.__clusters):
self.__clusters.append([index_point])
else:
self.__clusters[index_cluster].append(index_point) |
def __read_answer(self):
"""!
@brief Read information about proper clusters and noises from the file.
"""
if self.__clusters is not None:
return
file = open(self.__answer_path, 'r')
self.__clusters, self.__noise = [], []
index_point = 0
for line in file:
self.__read_answer_from_line(index_point, line)
index_point += 1
file.close() |
def append_cluster(self, cluster, data = None, marker = '.', markersize = None, color = None):
"""!
@brief Appends cluster for visualization.
@param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself.
@param[in] data (list): If defines that each element of cluster is considered as a index of object from the data.
@param[in] marker (string): Marker that is used for displaying objects from cluster on the canvas.
@param[in] markersize (uint): Size of marker.
@param[in] color (string): Color of marker.
@return Returns index of cluster descriptor on the canvas.
"""
if len(cluster) == 0:
raise ValueError("Empty cluster is provided.")
markersize = markersize or 5
if color is None:
index_color = len(self.__clusters) % len(color_list.TITLES)
color = color_list.TITLES[index_color]
cluster_descriptor = canvas_cluster_descr(cluster, data, marker, markersize, color)
self.__clusters.append(cluster_descriptor) |
def append_clusters(self, clusters, data=None, marker='.', markersize=None):
"""!
@brief Appends list of cluster for visualization.
@param[in] clusters (list): List of clusters where each cluster may consist of indexes of objects from the data or object itself.
@param[in] data (list): If defines that each element of cluster is considered as a index of object from the data.
@param[in] marker (string): Marker that is used for displaying objects from clusters on the canvas.
@param[in] markersize (uint): Size of marker.
"""
for cluster in clusters:
self.append_cluster(cluster, data, marker, markersize) |
def show(self, pair_filter=None, **kwargs):
"""!
@brief Shows clusters (visualize) in multi-dimensional space.
@param[in] pair_filter (list): List of coordinate pairs that should be displayed. This argument is used as a filter.
@param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'visible_axis' 'visible_labels', 'visible_grid', 'row_size').
<b>Keyword Args:</b><br>
- visible_axis (bool): Defines visibility of axes on each canvas, if True - axes are visible.
By default axis of each canvas are not displayed.
- visible_labels (bool): Defines visibility of labels on each canvas, if True - labels is displayed.
By default labels of each canvas are displayed.
- visible_grid (bool): Defines visibility of grid on each canvas, if True - grid is displayed.
By default grid of each canvas is displayed.
- max_row_size (uint): Maximum number of canvases on one row.
"""
if not len(self.__clusters) > 0:
raise ValueError("There is no non-empty clusters for visualization.")
cluster_data = self.__clusters[0].data or self.__clusters[0].cluster
dimension = len(cluster_data[0])
acceptable_pairs = pair_filter or []
pairs = []
amount_axis = 1
axis_storage = []
if dimension > 1:
pairs = self.__create_pairs(dimension, acceptable_pairs)
amount_axis = len(pairs)
self.__figure = plt.figure()
self.__grid_spec = self.__create_grid_spec(amount_axis, kwargs.get('max_row_size', 4))
for index in range(amount_axis):
ax = self.__create_canvas(dimension, pairs, index, **kwargs)
axis_storage.append(ax)
for cluster_descr in self.__clusters:
self.__draw_canvas_cluster(axis_storage, cluster_descr, pairs)
plt.show() |
def __create_grid_spec(self, amount_axis, max_row_size):
"""!
@brief Create grid specification for figure to place canvases.
@param[in] amount_axis (uint): Amount of canvases that should be organized by the created grid specification.
@param[in] max_row_size (max_row_size): Maximum number of canvases on one row.
@return (gridspec.GridSpec) Grid specification to place canvases on figure.
"""
row_size = amount_axis
if row_size > max_row_size:
row_size = max_row_size
col_size = math.ceil(amount_axis / row_size)
return gridspec.GridSpec(col_size, row_size) |
def __create_pairs(self, dimension, acceptable_pairs):
"""!
@brief Create coordinate pairs that should be displayed.
@param[in] dimension (uint): Data-space dimension.
@param[in] acceptable_pairs (list): List of coordinate pairs that should be displayed.
@return (list) List of coordinate pairs that should be displayed.
"""
if len(acceptable_pairs) > 0:
return acceptable_pairs
return list(itertools.combinations(range(dimension), 2)) |
def __create_canvas(self, dimension, pairs, position, **kwargs):
"""!
@brief Create new canvas with user defined parameters to display cluster or chunk of cluster on it.
@param[in] dimension (uint): Data-space dimension.
@param[in] pairs (list): Pair of coordinates that will be displayed on the canvas. If empty than label will not
be displayed on the canvas.
@param[in] position (uint): Index position of canvas on a grid.
@param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'visible_axis' 'visible_labels', 'visible_grid').
<b>Keyword Args:</b><br>
- visible_axis (bool): Defines visibility of axes on each canvas, if True - axes are visible.
By default axis are not displayed.
- visible_labels (bool): Defines visibility of labels on each canvas, if True - labels is displayed.
By default labels are displayed.
- visible_grid (bool): Defines visibility of grid on each canvas, if True - grid is displayed.
By default grid is displayed.
@return (matplotlib.Axis) Canvas to display cluster of chuck of cluster.
"""
visible_grid = kwargs.get('visible_grid', True)
visible_labels = kwargs.get('visible_labels', True)
visible_axis = kwargs.get('visible_axis', False)
ax = self.__figure.add_subplot(self.__grid_spec[position])
if dimension > 1:
if visible_labels:
ax.set_xlabel("x%d" % pairs[position][0])
ax.set_ylabel("x%d" % pairs[position][1])
else:
ax.set_ylim(-0.5, 0.5)
ax.set_yticklabels([])
if visible_grid:
ax.grid(True)
if not visible_axis:
ax.set_yticklabels([])
ax.set_xticklabels([])
return ax |
def __draw_canvas_cluster(self, axis_storage, cluster_descr, pairs):
"""!
@brief Draw clusters.
@param[in] axis_storage (list): List of matplotlib axis where cluster dimensional chunks are displayed.
@param[in] cluster_descr (canvas_cluster_descr): Canvas cluster descriptor that should be displayed.
@param[in] pairs (list): List of coordinates that should be displayed.
"""
for index_axis in range(len(axis_storage)):
for item in cluster_descr.cluster:
if len(pairs) > 0:
self.__draw_cluster_item_multi_dimension(axis_storage[index_axis], pairs[index_axis], item, cluster_descr)
else:
self.__draw_cluster_item_one_dimension(axis_storage[index_axis], item, cluster_descr) |
def __draw_cluster_item_multi_dimension(self, ax, pair, item, cluster_descr):
"""!
@brief Draw cluster chunk defined by pair coordinates in data space with dimension greater than 1.
@param[in] ax (axis): Matplotlib axis that is used to display chunk of cluster point.
@param[in] pair (list): Coordinate of the point that should be displayed.
@param[in] item (list): Data point or index of data point.
@param[in] cluster_descr (canvas_cluster_descr): Cluster description whose point is visualized.
"""
index_dimension1 = pair[0]
index_dimension2 = pair[1]
if cluster_descr.data is None:
ax.plot(item[index_dimension1], item[index_dimension2],
color=cluster_descr.color, marker=cluster_descr.marker, markersize=cluster_descr.markersize)
else:
ax.plot(cluster_descr.data[item][index_dimension1], cluster_descr.data[item][index_dimension2],
color=cluster_descr.color, marker=cluster_descr.marker, markersize=cluster_descr.markersize) |
def __draw_cluster_item_one_dimension(self, ax, item, cluster_descr):
"""!
@brief Draw cluster point in one dimensional data space..
@param[in] ax (axis): Matplotlib axis that is used to display chunk of cluster point.
@param[in] item (list): Data point or index of data point.
@param[in] cluster_descr (canvas_cluster_descr): Cluster description whose point is visualized.
"""
if cluster_descr.data is None:
ax.plot(item[0], 0.0,
color=cluster_descr.color, marker=cluster_descr.marker, markersize=cluster_descr.markersize)
else:
ax.plot(cluster_descr.data[item][0], 0.0,
color=cluster_descr.color, marker=cluster_descr.marker, markersize=cluster_descr.markersize) |
def append_cluster(self, cluster, data=None, canvas=0, marker='.', markersize=None, color=None):
"""!
@brief Appends cluster to canvas for drawing.
@param[in] cluster (list): cluster that may consist of indexes of objects from the data or object itself.
@param[in] data (list): If defines that each element of cluster is considered as a index of object from the data.
@param[in] canvas (uint): Number of canvas that should be used for displaying cluster.
@param[in] marker (string): Marker that is used for displaying objects from cluster on the canvas.
@param[in] markersize (uint): Size of marker.
@param[in] color (string): Color of marker.
@return Returns index of cluster descriptor on the canvas.
"""
if len(cluster) == 0:
return
if canvas > self.__number_canvases or canvas < 0:
raise ValueError("Canvas index '%d' is out of range [0; %d]." % self.__number_canvases or canvas)
if color is None:
index_color = len(self.__canvas_clusters[canvas]) % len(color_list.TITLES)
color = color_list.TITLES[index_color]
added_canvas_descriptor = canvas_cluster_descr(cluster, data, marker, markersize, color)
self.__canvas_clusters[canvas].append( added_canvas_descriptor )
if data is None:
dimension = len(cluster[0])
if self.__canvas_dimensions[canvas] is None:
self.__canvas_dimensions[canvas] = dimension
elif self.__canvas_dimensions[canvas] != dimension:
raise ValueError("Only clusters with the same dimension of objects can be displayed on canvas.")
else:
dimension = len(data[0])
if self.__canvas_dimensions[canvas] is None:
self.__canvas_dimensions[canvas] = dimension
elif self.__canvas_dimensions[canvas] != dimension:
raise ValueError("Only clusters with the same dimension of objects can be displayed on canvas.")
if (dimension < 1) or (dimension > 3):
raise ValueError("Only objects with size dimension 1 (1D plot), 2 (2D plot) or 3 (3D plot) "
"can be displayed. For multi-dimensional data use 'cluster_visualizer_multidim'.")
if markersize is None:
if (dimension == 1) or (dimension == 2):
added_canvas_descriptor.markersize = self.__default_2d_marker_size
elif dimension == 3:
added_canvas_descriptor.markersize = self.__default_3d_marker_size
return len(self.__canvas_clusters[canvas]) - 1 |
def append_cluster_attribute(self, index_canvas, index_cluster, data, marker = None, markersize = None):
"""!
@brief Append cluster attribure for cluster on specific canvas.
@details Attribute it is data that is visualized for specific cluster using its color, marker and markersize if last two is not specified.
@param[in] index_canvas (uint): Index canvas where cluster is located.
@param[in] index_cluster (uint): Index cluster whose attribute should be added.
@param[in] data (list): List of points (data) that represents attribute.
@param[in] marker (string): Marker that is used for displaying objects from cluster on the canvas.
@param[in] markersize (uint): Size of marker.
"""
cluster_descr = self.__canvas_clusters[index_canvas][index_cluster]
attribute_marker = marker
if attribute_marker is None:
attribute_marker = cluster_descr.marker
attribure_markersize = markersize
if attribure_markersize is None:
attribure_markersize = cluster_descr.markersize
attribute_color = cluster_descr.color
added_attribute_cluster_descriptor = canvas_cluster_descr(data, None, attribute_marker, attribure_markersize, attribute_color)
self.__canvas_clusters[index_canvas][index_cluster].attributes.append(added_attribute_cluster_descriptor) |
def set_canvas_title(self, text, canvas = 0):
"""!
@brief Set title for specified canvas.
@param[in] text (string): Title for canvas.
@param[in] canvas (uint): Index of canvas where title should be displayed.
"""
if canvas > self.__number_canvases:
raise NameError('Canvas does ' + canvas + ' not exists.')
self.__canvas_titles[canvas] = text |
def show(self, figure=None, invisible_axis=True, visible_grid=True, display=True, shift=None):
"""!
@brief Shows clusters (visualize).
@param[in] figure (fig): Defines requirement to use specified figure, if None - new figure is created for drawing clusters.
@param[in] invisible_axis (bool): Defines visibility of axes on each canvas, if True - axes are invisible.
@param[in] visible_grid (bool): Defines visibility of grid on each canvas, if True - grid is displayed.
@param[in] display (bool): Defines requirement to display clusters on a stage, if True - clusters are displayed,
if False - plt.show() should be called by user."
@param[in] shift (uint): Force canvas shift value - defines canvas index from which custers should be visualized.
@return (fig) Figure where clusters are shown.
"""
canvas_shift = shift
if canvas_shift is None:
if figure is not None:
canvas_shift = len(figure.get_axes())
else:
canvas_shift = 0
if figure is not None:
cluster_figure = figure
else:
cluster_figure = plt.figure()
maximum_cols = self.__size_row
maximum_rows = math.ceil( (self.__number_canvases + canvas_shift) / maximum_cols)
grid_spec = gridspec.GridSpec(maximum_rows, maximum_cols)
for index_canvas in range(len(self.__canvas_clusters)):
canvas_data = self.__canvas_clusters[index_canvas]
if len(canvas_data) == 0:
continue
dimension = self.__canvas_dimensions[index_canvas]
#ax = axes[real_index];
if (dimension == 1) or (dimension == 2):
ax = cluster_figure.add_subplot(grid_spec[index_canvas + canvas_shift])
else:
ax = cluster_figure.add_subplot(grid_spec[index_canvas + canvas_shift], projection='3d')
if len(canvas_data) == 0:
plt.setp(ax, visible=False)
for cluster_descr in canvas_data:
self.__draw_canvas_cluster(ax, dimension, cluster_descr)
for attribute_descr in cluster_descr.attributes:
self.__draw_canvas_cluster(ax, dimension, attribute_descr)
if invisible_axis is True:
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
if (dimension == 3):
ax.zaxis.set_ticklabels([])
if self.__canvas_titles[index_canvas] is not None:
ax.set_title(self.__canvas_titles[index_canvas])
ax.grid(visible_grid)
if display is True:
plt.show()
return cluster_figure |
def __draw_canvas_cluster(self, ax, dimension, cluster_descr):
"""!
@brief Draw canvas cluster descriptor.
@param[in] ax (Axis): Axis of the canvas where canvas cluster descriptor should be displayed.
@param[in] dimension (uint): Canvas dimension.
@param[in] cluster_descr (canvas_cluster_descr): Canvas cluster descriptor that should be displayed.
@return (fig) Figure where clusters are shown.
"""
cluster = cluster_descr.cluster
data = cluster_descr.data
marker = cluster_descr.marker
markersize = cluster_descr.markersize
color = cluster_descr.color
for item in cluster:
if dimension == 1:
if data is None:
ax.plot(item[0], 0.0, color = color, marker = marker, markersize = markersize)
else:
ax.plot(data[item][0], 0.0, color = color, marker = marker, markersize = markersize)
elif dimension == 2:
if data is None:
ax.plot(item[0], item[1], color = color, marker = marker, markersize = markersize)
else:
ax.plot(data[item][0], data[item][1], color = color, marker = marker, markersize = markersize)
elif dimension == 3:
if data is None:
ax.scatter(item[0], item[1], item[2], c = color, marker = marker, s = markersize)
else:
ax.scatter(data[item][0], data[item][1], data[item][2], c = color, marker = marker, s = markersize) |
def gaussian(data, mean, covariance):
"""!
@brief Calculates gaussian for dataset using specified mean (mathematical expectation) and variance or covariance in case
multi-dimensional data.
@param[in] data (list): Data that is used for gaussian calculation.
@param[in] mean (float|numpy.array): Mathematical expectation used for calculation.
@param[in] covariance (float|numpy.array): Variance or covariance matrix for calculation.
@return (list) Value of gaussian function for each point in dataset.
"""
dimension = float(len(data[0]))
if dimension != 1.0:
inv_variance = numpy.linalg.pinv(covariance)
else:
inv_variance = 1.0 / covariance
divider = (pi * 2.0) ** (dimension / 2.0) * numpy.sqrt(numpy.linalg.norm(covariance))
if divider != 0.0:
right_const = 1.0 / divider
else:
right_const = float('inf')
result = []
for point in data:
mean_delta = point - mean
point_gaussian = right_const * numpy.exp( -0.5 * mean_delta.dot(inv_variance).dot(numpy.transpose(mean_delta)) )
result.append(point_gaussian)
return result |
def initialize(self, init_type = ema_init_type.KMEANS_INITIALIZATION):
"""!
@brief Calculates initial parameters for EM algorithm: means and covariances using
specified strategy.
@param[in] init_type (ema_init_type): Strategy for initialization.
@return (float|list, float|numpy.array) Initial means and variance (covariance matrix in case multi-dimensional data).
"""
if init_type == ema_init_type.KMEANS_INITIALIZATION:
return self.__initialize_kmeans()
elif init_type == ema_init_type.RANDOM_INITIALIZATION:
return self.__initialize_random()
raise NameError("Unknown type of EM algorithm initialization is specified.") |
def __calculate_initial_clusters(self, centers):
"""!
@brief Calculate Euclidean distance to each point from the each cluster.
@brief Nearest points are captured by according clusters and as a result clusters are updated.
@return (list) updated clusters as list of clusters. Each cluster contains indexes of objects from data.
"""
clusters = [[] for _ in range(len(centers))]
for index_point in range(len(self.__sample)):
index_optim, dist_optim = -1, 0.0
for index in range(len(centers)):
dist = euclidean_distance_square(self.__sample[index_point], centers[index])
if (dist < dist_optim) or (index is 0):
index_optim, dist_optim = index, dist
clusters[index_optim].append(index_point)
return clusters |
def notify(self, means, covariances, clusters):
"""!
@brief This method is used by the algorithm to notify observer about changes where the algorithm
should provide new values: means, covariances and allocated clusters.
@param[in] means (list): Mean of each cluster on currect step.
@param[in] covariances (list): Covariances of each cluster on current step.
@param[in] clusters (list): Allocated cluster on current step.
"""
self.__means_evolution.append(means)
self.__covariances_evolution.append(covariances)
self.__clusters_evolution.append(clusters) |
def show_clusters(clusters, sample, covariances, means, figure = None, display = True):
"""!
@brief Draws clusters and in case of two-dimensional dataset draws their ellipses.
@param[in] clusters (list): Clusters that were allocated by the algorithm.
@param[in] sample (list): Dataset that were used for clustering.
@param[in] covariances (list): Covariances of the clusters.
@param[in] means (list): Means of the clusters.
@param[in] figure (figure): If 'None' then new is figure is creater, otherwise specified figure is used
for visualization.
@param[in] display (bool): If 'True' then figure will be shown by the method, otherwise it should be
shown manually using matplotlib function 'plt.show()'.
@return (figure) Figure where clusters were drawn.
"""
visualizer = cluster_visualizer()
visualizer.append_clusters(clusters, sample)
if figure is None:
figure = visualizer.show(display = False)
else:
visualizer.show(figure = figure, display = False)
if len(sample[0]) == 2:
ema_visualizer.__draw_ellipses(figure, visualizer, clusters, covariances, means)
if display is True:
plt.show()
return figure |
def animate_cluster_allocation(data, observer, animation_velocity = 75, movie_fps = 1, save_movie = None):
"""!
@brief Animates clustering process that is performed by EM algorithm.
@param[in] data (list): Dataset that is used for clustering.
@param[in] observer (ema_observer): EM observer that was used for collection information about clustering process.
@param[in] animation_velocity (uint): Interval between frames in milliseconds (for run-time animation only).
@param[in] movie_fps (uint): Defines frames per second (for rendering movie only).
@param[in] save_movie (string): If it is specified then animation will be stored to file that is specified in this parameter.
"""
figure = plt.figure()
def init_frame():
return frame_generation(0)
def frame_generation(index_iteration):
figure.clf()
figure.suptitle("EM algorithm (iteration: " + str(index_iteration) +")", fontsize = 18, fontweight = 'bold')
clusters = observer.get_evolution_clusters()[index_iteration]
covariances = observer.get_evolution_covariances()[index_iteration]
means = observer.get_evolution_means()[index_iteration]
ema_visualizer.show_clusters(clusters, data, covariances, means, figure, False)
figure.subplots_adjust(top = 0.85)
return [ figure.gca() ]
iterations = len(observer)
cluster_animation = animation.FuncAnimation(figure, frame_generation, iterations, interval = animation_velocity, init_func = init_frame, repeat_delay = 5000)
if save_movie is not None:
cluster_animation.save(save_movie, writer = 'ffmpeg', fps = movie_fps, bitrate = 1500)
else:
plt.show() |
def process(self):
"""!
@brief Run clustering process of the algorithm.
@details This method should be called before call 'get_clusters()'.
"""
previous_likelihood = -200000
current_likelihood = -100000
current_iteration = 0
while(self.__stop is False) and (abs(previous_likelihood - current_likelihood) > self.__tolerance) and (current_iteration < self.__iterations):
self.__expectation_step()
self.__maximization_step()
current_iteration += 1
self.__extract_clusters()
self.__notify()
previous_likelihood = current_likelihood
current_likelihood = self.__log_likelihood()
self.__stop = self.__get_stop_condition()
self.__normalize_probabilities() |
def euclidean_distance_numpy(object1, object2):
"""!
@brief Calculate Euclidean 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) Euclidean distance between two objects.
"""
return numpy.sum(numpy.sqrt(numpy.square(object1 - object2)), axis=1).T |
def euclidean_distance_square(point1, point2):
"""!
@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
"""
distance = 0.0
for i in range(len(point1)):
distance += (point1[i] - point2[i]) ** 2.0
return distance |
def euclidean_distance_square_numpy(object1, object2):
"""!
@brief Calculate square Euclidean 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) Square Euclidean distance between two objects.
"""
return numpy.sum(numpy.square(object1 - object2), axis=1).T |
def manhattan_distance(point1, point2):
"""!
@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
"""
distance = 0.0
dimension = len(point1)
for i in range(dimension):
distance += abs(point1[i] - point2[i])
return distance |
def manhattan_distance_numpy(object1, object2):
"""!
@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.
"""
return numpy.sum(numpy.absolute(object1 - object2), axis=1).T |
def chebyshev_distance(point1, point2):
"""!
@brief Calculate Chebyshev distance between between two vectors.
\f[
dist(a, b) = \max_{}i\left (\left | a_{i} - b_{i} \right |\right );
\f]
@param[in] point1 (array_like): The first vector.
@param[in] point2 (array_like): The second vector.
@return (double) Chebyshev distance between two vectors.
@see euclidean_distance_square, euclidean_distance, minkowski_distance
"""
distance = 0.0
dimension = len(point1)
for i in range(dimension):
distance = max(distance, abs(point1[i] - point2[i]))
return distance |
def chebyshev_distance_numpy(object1, object2):
"""!
@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.
"""
return numpy.max(numpy.absolute(object1 - object2), axis=1).T |
def minkowski_distance(point1, point2, degree=2):
"""!
@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 = 0.0
for i in range(len(point1)):
distance += (point1[i] - point2[i]) ** degree
return distance ** (1.0 / degree) |
def minkowski_distance_numpy(object1, object2, degree=2):
"""!
@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.
"""
return numpy.sum(numpy.power(numpy.power(object1 - object2, degree), 1/degree), axis=1).T |
def canberra_distance_numpy(object1, object2):
"""!
@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='ignore', invalid='ignore'):
result = numpy.divide(numpy.abs(object1 - object2), numpy.abs(object1) + numpy.abs(object2))
if len(result.shape) > 1:
return numpy.sum(numpy.nan_to_num(result), axis=1).T
else:
return numpy.sum(numpy.nan_to_num(result)) |
def chi_square_distance(point1, point2):
"""!
@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.
"""
distance = 0.0
for i in range(len(point1)):
divider = abs(point1[i]) + abs(point2[i])
if divider == 0.0:
continue
distance += ((point1[i] - point2[i]) ** 2.0) / divider
return distance |
def enable_numpy_usage(self):
"""!
@brief Start numpy for distance calculation.
@details Useful in case matrices to increase performance. No effect in case of type_metric.USER_DEFINED type.
"""
self.__numpy = True
if self.__type != type_metric.USER_DEFINED:
self.__calculator = self.__create_distance_calculator() |
def __create_distance_calculator_basic(self):
"""!
@brief Creates distance metric calculator that does not use numpy.
@return (callable) Callable object of distance metric calculator.
"""
if self.__type == type_metric.EUCLIDEAN:
return euclidean_distance
elif self.__type == type_metric.EUCLIDEAN_SQUARE:
return euclidean_distance_square
elif self.__type == type_metric.MANHATTAN:
return manhattan_distance
elif self.__type == type_metric.CHEBYSHEV:
return chebyshev_distance
elif self.__type == type_metric.MINKOWSKI:
return lambda point1, point2: minkowski_distance(point1, point2, self.__args.get('degree', 2))
elif self.__type == type_metric.CANBERRA:
return canberra_distance
elif self.__type == type_metric.CHI_SQUARE:
return chi_square_distance
elif self.__type == type_metric.USER_DEFINED:
return self.__func
else:
raise ValueError("Unknown type of metric: '%d'", self.__type) |
def __create_distance_calculator_numpy(self):
"""!
@brief Creates distance metric calculator that uses numpy.
@return (callable) Callable object of distance metric calculator.
"""
if self.__type == type_metric.EUCLIDEAN:
return euclidean_distance_numpy
elif self.__type == type_metric.EUCLIDEAN_SQUARE:
return euclidean_distance_square_numpy
elif self.__type == type_metric.MANHATTAN:
return manhattan_distance_numpy
elif self.__type == type_metric.CHEBYSHEV:
return chebyshev_distance_numpy
elif self.__type == type_metric.MINKOWSKI:
return lambda object1, object2: minkowski_distance_numpy(object1, object2, self.__args.get('degree', 2))
elif self.__type == type_metric.CANBERRA:
return canberra_distance_numpy
elif self.__type == type_metric.CHI_SQUARE:
return chi_square_distance_numpy
elif self.__type == type_metric.USER_DEFINED:
return self.__func
else:
raise ValueError("Unknown type of metric: '%d'", self.__type) |
def extract_number_oscillations(self, index, amplitude_threshold):
"""!
@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.
"""
return pyclustering.utils.extract_number_oscillations(self.__amplitude, index, amplitude_threshold); |
def show_output_dynamic(fsync_output_dynamic):
"""!
@brief Shows output dynamic (output of each oscillator) during simulation.
@param[in] fsync_output_dynamic (fsync_dynamic): Output dynamic of the fSync network.
@see show_output_dynamics
"""
pyclustering.utils.draw_dynamics(fsync_output_dynamic.time, fsync_output_dynamic.output, x_title = "t", y_title = "amplitude"); |
def simulate(self, steps, time, collect_dynamic = False):
"""!
@brief Performs static simulation of oscillatory network.
@param[in] steps (uint): Number simulation steps.
@param[in] time (double): Time of 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' is True, than return dynamic for the whole simulation time,
otherwise returns only last values (last step of simulation) of output dynamic.
@see simulate()
@see simulate_dynamic()
"""
dynamic_amplitude, dynamic_time = ([], []) if collect_dynamic is False else ([self.__amplitude], [0]);
step = time / steps;
int_step = step / 10.0;
for t in numpy.arange(step, time + step, step):
self.__amplitude = self.__calculate(t, step, int_step);
if collect_dynamic is True:
dynamic_amplitude.append([ numpy.real(amplitude)[0] for amplitude in self.__amplitude ]);
dynamic_time.append(t);
if collect_dynamic is False:
dynamic_amplitude.append([ numpy.real(amplitude)[0] for amplitude in self.__amplitude ]);
dynamic_time.append(time);
output_sync_dynamic = fsync_dynamic(dynamic_amplitude, dynamic_time);
return output_sync_dynamic; |
def __calculate(self, t, step, int_step):
"""!
@brief Calculates new amplitudes for oscillators in the network in line with current step.
@param[in] t (double): 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 (phases) for oscillators.
"""
next_amplitudes = [0.0] * self._num_osc;
for index in range (0, self._num_osc, 1):
z = numpy.array(self.__amplitude[index], dtype = numpy.complex128, ndmin = 1);
result = odeint(self.__calculate_amplitude, z.view(numpy.float64), numpy.arange(t - step, t, int_step), (index , ));
next_amplitudes[index] = (result[len(result) - 1]).view(numpy.complex128);
return next_amplitudes; |
def __oscillator_property(self, index):
"""!
@brief Calculate Landau-Stuart oscillator constant property that is based on frequency and radius.
@param[in] index (uint): Oscillator index whose property is calculated.
@return (double) Oscillator property.
"""
return numpy.array(1j * self.__frequency[index] + self.__radius[index]**2, dtype = numpy.complex128, ndmin = 1); |
def __landau_stuart(self, amplitude, index):
"""!
@brief Calculate Landau-Stuart state.
@param[in] amplitude (double): Current amplitude of oscillator.
@param[in] index (uint): Oscillator index whose state is calculated.
@return (double) Landau-Stuart state.
"""
return (self.__properties[index] - numpy.absolute(amplitude) ** 2) * amplitude; |
def __synchronization_mechanism(self, amplitude, index):
"""!
@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.
"""
sync_influence = 0.0;
for k in range(self._num_osc):
if self.has_connection(index, k) is True:
amplitude_neighbor = numpy.array(self.__amplitude[k], dtype = numpy.complex128, ndmin = 1);
sync_influence += amplitude_neighbor - amplitude;
return sync_influence * self.__coupling_strength / self._num_osc; |
def __calculate_amplitude(self, amplitude, t, argv):
"""!
@brief Returns new amplitude value for particular oscillator that is defined by index that is in 'argv' argument.
@details The method is used for differential calculation.
@param[in] amplitude (double): Current amplitude of oscillator.
@param[in] t (double): Current time of simulation.
@param[in] argv (uint): Index of the current oscillator.
@return (double) New amplitude of the oscillator.
"""
z = amplitude.view(numpy.complex);
dzdt = self.__landau_stuart(z, argv) + self.__synchronization_mechanism(z, argv);
return dzdt.view(numpy.float64); |
def small_mind_image_recognition():
"""!
@brief Trains network using letters 'M', 'I', 'N', 'D' and recognize each of them with and without noise.
"""
images = [];
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_M;
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_I;
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_N;
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_D;
template_recognition_image(images, 100, 10, 0.2); |
def small_abc_image_recognition():
"""!
@brief Trains network using letters 'A', 'B', 'C', and recognize each of them with and without noise.
"""
images = [];
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_A;
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_B;
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_C;
template_recognition_image(images, 250, 25); |
def small_ftk_image_recognition():
"""!
@brief Trains network using letters 'F', 'T', 'K' and recognize each of them with and without noise.
"""
images = [];
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_F;
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_T;
images += IMAGE_SYMBOL_SAMPLES.LIST_IMAGES_SYMBOL_K;
template_recognition_image(images, 100, 10, 0.2); |
def get_clusters_representation(chromosome, count_clusters=None):
""" Convert chromosome to cluster representation:
chromosome : [0, 1, 1, 0, 2, 3, 3]
clusters: [[0, 3], [1, 2], [4], [5, 6]]
"""
if count_clusters is None:
count_clusters = ga_math.calc_count_centers(chromosome)
# Initialize empty clusters
clusters = [[] for _ in range(count_clusters)]
# Fill clusters with index of data
for _idx_data in range(len(chromosome)):
clusters[chromosome[_idx_data]].append(_idx_data)
return clusters |
def get_centres(chromosomes, data, count_clusters):
"""!
"""
centres = ga_math.calc_centers(chromosomes, data, count_clusters)
return centres |
def calc_centers(chromosomes, data, count_clusters=None):
"""!
"""
if count_clusters is None:
count_clusters = ga_math.calc_count_centers(chromosomes[0])
# Initialize center
centers = np.zeros(shape=(len(chromosomes), count_clusters, len(data[0])))
for _idx_chromosome in range(len(chromosomes)):
# Get count data in clusters
count_data_in_cluster = np.zeros(count_clusters)
# Next data point
for _idx in range(len(chromosomes[_idx_chromosome])):
cluster_num = chromosomes[_idx_chromosome][_idx]
centers[_idx_chromosome][cluster_num] += data[_idx]
count_data_in_cluster[cluster_num] += 1
for _idx_cluster in range(count_clusters):
if count_data_in_cluster[_idx_cluster] != 0:
centers[_idx_chromosome][_idx_cluster] /= count_data_in_cluster[_idx_cluster]
return centers |
def calc_probability_vector(fitness):
"""!
"""
if len(fitness) == 0:
raise AttributeError("Has no any fitness functions.")
# Get 1/fitness function
inv_fitness = np.zeros(len(fitness))
#
for _idx in range(len(inv_fitness)):
if fitness[_idx] != 0.0:
inv_fitness[_idx] = 1.0 / fitness[_idx]
else:
inv_fitness[_idx] = 0.0
# Initialize vector
prob = np.zeros(len(fitness))
# Initialize first element
prob[0] = inv_fitness[0]
# Accumulate values in probability vector
for _idx in range(1, len(inv_fitness)):
prob[_idx] = prob[_idx - 1] + inv_fitness[_idx]
# Normalize
prob /= prob[-1]
ga_math.set_last_value_to_one(prob)
return prob |
def set_last_value_to_one(probabilities):
"""!
@brief Update the last same probabilities to one.
@details All values of probability list equals to the last element are set to 1.
"""
# Start from the last elem
back_idx = - 1
# All values equal to the last elem should be set to 1
last_val = probabilities[back_idx]
# for all elements or if a elem not equal to the last elem
for _ in range(-1, -len(probabilities) - 1):
if probabilities[back_idx] == last_val:
probabilities[back_idx] = 1
else:
break |
def get_uniform(probabilities):
"""!
@brief Returns index in probabilities.
@param[in] probabilities (list): List with segments in increasing sequence with val in [0, 1],
for example, [0 0.1 0.2 0.3 1.0].
"""
# Initialize return value
res_idx = None
# Get random num in range [0, 1)
random_num = np.random.rand()
# Find segment with val1 < random_num < val2
for _idx in range(len(probabilities)):
if random_num < probabilities[_idx]:
res_idx = _idx
break
if res_idx is None:
print('Probabilities : ', probabilities)
raise AttributeError("'probabilities' should contain 1 as the end of last segment(s)")
return res_idx |
def cluster_sample1():
"Start with wrong number of clusters."
start_centers = [[3.7, 5.5]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE1, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE1, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def cluster_sample2():
"Start with wrong number of clusters."
start_centers = [[3.5, 4.8], [2.6, 2.5]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE2, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE2, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def cluster_sample3():
"Start with wrong number of clusters."
start_centers = [[0.2, 0.1], [4.0, 1.0]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE3, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE3, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def cluster_sample5():
"Start with wrong number of clusters."
start_centers = [[0.0, 1.0], [0.0, 0.0]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE5, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_SIMPLE5, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def cluster_elongate():
"Not so applicable for this sample"
start_centers = [[1.0, 4.5], [3.1, 2.7]]
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_ELONGATE, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, SIMPLE_SAMPLES.SAMPLE_ELONGATE, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def cluster_lsun():
"Not so applicable for this sample"
start_centers = [[1.0, 3.5], [2.0, 0.5], [3.0, 3.0]]
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_LSUN, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_LSUN, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def cluster_target():
"Not so applicable for this sample"
start_centers = [[0.2, 0.2], [0.0, -2.0], [3.0, -3.0], [3.0, 3.0], [-3.0, 3.0], [-3.0, -3.0]]
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_TARGET, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_TARGET, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def cluster_two_diamonds():
"Start with wrong number of clusters."
start_centers = [[0.8, 0.2]]
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_TWO_DIAMONDS, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_TWO_DIAMONDS, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def cluster_hepta():
"Start with wrong number of clusters."
start_centers = [[0.0, 0.0, 0.0], [3.0, 0.0, 0.0], [-2.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, -3.0, 0.0], [0.0, 0.0, 2.5]]
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_HEPTA, criterion = splitting_type.BAYESIAN_INFORMATION_CRITERION)
template_clustering(start_centers, FCPS_SAMPLES.SAMPLE_HEPTA, criterion = splitting_type.MINIMUM_NOISELESS_DESCRIPTION_LENGTH) |
def process(self):
"""!
@brief Performs cluster analysis by competition between neurons of SOM.
@remark Results of clustering can be obtained using corresponding get methods.
@see get_clusters()
"""
self.__network = som(1, self.__amount_clusters, type_conn.grid_four, None, self.__ccore);
self.__network.train(self.__data_pointer, self.__epouch, True); |
def process(self, order = 0.998, solution = solve_type.FAST, collect_dynamic = False):
"""!
@brief Performs clustering of input data set in line with input parameters.
@param[in] order (double): Level of local synchronization between oscillator that defines end of synchronization process, range [0..1].
@param[in] solution (solve_type) Type of solving differential equation.
@param[in] collect_dynamic (bool): If True - returns whole history of process synchronization otherwise - only final state (when process of clustering is over).
@return (tuple) Returns dynamic of the network as tuple of lists on each iteration (time, oscillator_phases) that depends on collect_dynamic parameter.
@see get_clusters()
"""
if (self.__ccore_network_pointer is not None):
analyser = wrapper.hsyncnet_process(self.__ccore_network_pointer, order, solution, collect_dynamic);
return syncnet_analyser(None, None, analyser);
number_neighbors = self.__initial_neighbors;
current_number_clusters = float('inf');
dyn_phase = [];
dyn_time = [];
radius = average_neighbor_distance(self._osc_loc, number_neighbors);
increase_step = int(len(self._osc_loc) * self.__increase_persent);
if (increase_step < 1):
increase_step = 1;
analyser = None;
while(current_number_clusters > self._number_clusters):
self._create_connections(radius);
analyser = self.simulate_dynamic(order, solution, collect_dynamic);
if (collect_dynamic == True):
if (len(dyn_phase) == 0):
self.__store_dynamic(dyn_phase, dyn_time, analyser, True);
self.__store_dynamic(dyn_phase, dyn_time, analyser, False);
clusters = analyser.allocate_sync_ensembles(0.05);
# Get current number of allocated clusters
current_number_clusters = len(clusters);
# Increase number of neighbors that should be used
number_neighbors += increase_step;
# Update connectivity radius and check if average function can be used anymore
radius = self.__calculate_radius(number_neighbors, radius);
if (collect_dynamic != True):
self.__store_dynamic(dyn_phase, dyn_time, analyser, False);
return syncnet_analyser(dyn_phase, dyn_time, None); |
def __calculate_radius(self, number_neighbors, radius):
"""!
@brief Calculate new connectivity radius.
@param[in] number_neighbors (uint): Average amount of neighbors that should be connected by new radius.
@param[in] radius (double): Current connectivity radius.
@return New connectivity radius.
"""
if (number_neighbors >= len(self._osc_loc)):
return radius * self.__increase_persent + radius;
return average_neighbor_distance(self._osc_loc, number_neighbors); |
def __store_dynamic(self, dyn_phase, dyn_time, analyser, begin_state):
"""!
@brief Store specified state of Sync network to hSync.
@param[in] dyn_phase (list): Output dynamic of hSync where state should be stored.
@param[in] dyn_time (list): Time points that correspond to output dynamic where new time point should be stored.
@param[in] analyser (syncnet_analyser): Sync analyser where Sync states are stored.
@param[in] begin_state (bool): If True the first state of Sync network is stored, otherwise the last state is stored.
"""
if (begin_state is True):
dyn_time.append(0);
dyn_phase.append(analyser.output[0]);
else:
dyn_phase.append(analyser.output[len(analyser.output) - 1]);
dyn_time.append(len(dyn_time)); |
def set_encoding(self, encoding):
"""!
@brief Change clusters encoding to specified type (index list, object list, labeling).
@param[in] encoding (type_encoding): New type of clusters representation.
"""
if(encoding == self.__type_representation):
return;
if (self.__type_representation == type_encoding.CLUSTER_INDEX_LABELING):
if (encoding == type_encoding.CLUSTER_INDEX_LIST_SEPARATION):
self.__clusters = self.__convert_label_to_index();
else:
self.__clusters = self.__convert_label_to_object();
elif (self.__type_representation == type_encoding.CLUSTER_INDEX_LIST_SEPARATION):
if (encoding == type_encoding.CLUSTER_INDEX_LABELING):
self.__clusters = self.__convert_index_to_label();
else:
self.__clusters = self.__convert_index_to_object();
else:
if (encoding == type_encoding.CLUSTER_INDEX_LABELING):
self.__clusters = self.__convert_object_to_label();
else:
self.__clusters = self.__convert_object_to_index();
self.__type_representation = encoding; |
def process(self):
"""!
@brief Performs cluster analysis in line with rules of DBSCAN algorithm.
@see get_clusters()
@see get_noise()
"""
if self.__ccore is True:
(self.__clusters, self.__noise) = wrapper.dbscan(self.__pointer_data, self.__eps, self.__neighbors, self.__data_type)
else:
if self.__data_type == 'points':
self.__kdtree = kdtree(self.__pointer_data, range(len(self.__pointer_data)))
for i in range(0, len(self.__pointer_data)):
if self.__visited[i] is False:
cluster = self.__expand_cluster(i)
if cluster is not None:
self.__clusters.append(cluster)
for i in range(0, len(self.__pointer_data)):
if self.__belong[i] is False:
self.__noise.append(i) |
def __expand_cluster(self, index_point):
"""!
@brief Expands cluster from specified point in the input data space.
@param[in] index_point (list): Index of a point from the data.
@return (list) Return tuple of list of indexes that belong to the same cluster and list of points that are marked as noise: (cluster, noise), or None if nothing has been expanded.
"""
cluster = None
self.__visited[index_point] = True
neighbors = self.__neighbor_searcher(index_point)
if len(neighbors) >= self.__neighbors:
cluster = [index_point]
self.__belong[index_point] = True
for i in neighbors:
if self.__visited[i] is False:
self.__visited[i] = True
next_neighbors = self.__neighbor_searcher(i)
if len(next_neighbors) >= self.__neighbors:
neighbors += [k for k in next_neighbors if ( (k in neighbors) == False) and k != index_point]
if self.__belong[i] is False:
cluster.append(i)
self.__belong[i] = True
return cluster |
def __neighbor_indexes_points(self, index_point):
"""!
@brief Return neighbors of the specified object in case of sequence of points.
@param[in] index_point (uint): Index point whose neighbors are should be found.
@return (list) List of indexes of neighbors in line the connectivity radius.
"""
kdnodes = self.__kdtree.find_nearest_dist_nodes(self.__pointer_data[index_point], self.__eps)
return [node_tuple[1].payload for node_tuple in kdnodes if node_tuple[1].payload != index_point] |
def __neighbor_indexes_distance_matrix(self, index_point):
"""!
@brief Return neighbors of the specified object in case of distance matrix.
@param[in] index_point (uint): Index point whose neighbors are should be found.
@return (list) List of indexes of neighbors in line the connectivity radius.
"""
distances = self.__pointer_data[index_point]
return [index_neighbor for index_neighbor in range(len(distances))
if ((distances[index_neighbor] <= self.__eps) and (index_neighbor != index_point))] |
def generate(self):
"""!
@brief Generates data in line with generator parameters.
"""
data_points = []
for index_cluster in range(self.__amount_clusters):
for _ in range(self.__cluster_sizes[index_cluster]):
point = self.__generate_point(index_cluster)
data_points.append(point)
return data_points |
def __generate_point(self, index_cluster):
"""!
@brief Generates point in line with parameters of specified cluster.
@param[in] index_cluster (uint): Index of cluster whose parameters are used for point generation.
@return (list) New generated point in line with normal distribution and cluster parameters.
"""
return [ random.gauss(self.__cluster_centers[index_cluster][index_dimension],
self.__cluster_width[index_cluster] / 2.0)
for index_dimension in range(self.__dimension) ] |
def __generate_cluster_centers(self, width):
"""!
@brief Generates centers (means in statistical term) for clusters.
@param[in] width (list): Width of generated clusters.
@return (list) Generated centers in line with normal distribution.
"""
centers = []
default_offset = max(width) * 4.0
for i in range(self.__amount_clusters):
center = [ random.gauss(i * default_offset, width[i] / 2.0) for _ in range(self.__dimension) ]
centers.append(center)
return centers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.