Completed
Push — master ( 9cffad...7a46cc )
by Andrei
01:25
created

dbscan.__neighbor_indexes()   B

Complexity

Conditions 7

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
dl 0
loc 18
rs 7.3333
c 0
b 0
f 0
1
"""!
2
3
@brief Cluster analysis algorithm: DBSCAN.
4
@details Implementation based on article:
5
         - M.Ester, H.Kriegel, J.Sander, X.Xiaowei. A density-based algorithm for discovering clusters in large spatial databases with noise. 1996.
6
7
@authors Andrei Novikov ([email protected])
8
@date 2014-2018
9
@copyright GNU Public License
10
11
@cond GNU_PUBLIC_LICENSE
12
    PyClustering is free software: you can redistribute it and/or modify
13
    it under the terms of the GNU General Public License as published by
14
    the Free Software Foundation, either version 3 of the License, or
15
    (at your option) any later version.
16
    
17
    PyClustering is distributed in the hope that it will be useful,
18
    but WITHOUT ANY WARRANTY; without even the implied warranty of
19
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
    GNU General Public License for more details.
21
    
22
    You should have received a copy of the GNU General Public License
23
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
24
@endcond
25
26
"""
27
28
29
from enum import IntEnum;
30
31
from pyclustering.container.kdtree import kdtree;
32
33
from pyclustering.cluster.encoder import type_encoding;
34
35
from pyclustering.core.wrapper import ccore_library;
36
37
from pyclustering.utils import get_argument;
38
39
import pyclustering.core.dbscan_wrapper as wrapper;
40
41
42
43
class dbscan_data_type(IntEnum):
44
    """!
45
    @brief Enumeration of DBSCAN input data types that is used for processing: points, adjacency matrix.
46
47
    """
48
49
    ## Input data is represented by points that are contained by array like container, for example, by list.
50
    POINTS = 0;
51
52
    ## Input data is represented by distance matrix between points.
53
    DISTANCE_MATRIX = 1;
54
55
56
class dbscan:
57
    """!
58
    @brief Class represents clustering algorithm DBSCAN.
59
    @details This DBSCAN algorithm is KD-tree optimized.
60
             
61
             CCORE option can be used to use the pyclustering core - C/C++ shared library for processing that significantly increases performance.
62
    
63
    Example:
64
    @code
65
        # sample for cluster analysis (represented by list)
66
        sample = read_sample(path_to_sample);
67
        
68
        # create object that uses CCORE for processing
69
        dbscan_instance = dbscan(sample, 0.5, 3, True);
70
        
71
        # cluster analysis
72
        dbscan_instance.process();
73
        
74
        # obtain results of clustering
75
        clusters = dbscan_instance.get_clusters();
76
        noise = dbscan_instance.get_noise();
77
    @endcode
78
    
79
    """
80
    
81
    def __init__(self, data, eps, neighbors, ccore = True, **kwargs):
82
        """!
83
        @brief Constructor of clustering algorithm DBSCAN.
84
        
85
        @param[in] data (list): Input data that is presented as list of points (objects), each point should be represented by list or tuple.
86
        @param[in] eps (double): Connectivity radius between points, points may be connected if distance between them less then the radius.
87
        @param[in] neighbors (uint): minimum number of shared neighbors that is required for establish links between points.
88
        @param[in] ccore (bool): if True than DLL CCORE (C++ solution) will be used for solving the problem.
89
        @param[in] **kwargs: Arbitrary keyword arguments (available arguments: 'data_type').
90
91
        Keyword Args:
92
            data_type (dbscan_data_type): Data type of input sample 'data' that is processed by the algorithm (simple sequence of points or distance matrix).
93
        
94
        """
95
        
96
        self.__pointer_data = data;
97
        self.__kdtree = None;
98
        self.__eps = eps;
99
        self.__sqrt_eps = eps * eps;
100
        self.__neighbors = neighbors;
101
        
102
        self.__visited = [False] * len(self.__pointer_data);
103
        self.__belong = [False] * len(self.__pointer_data);
104
105
        self.__data_type = get_argument('data_type', dbscan_data_type.POINTS, **kwargs);
106
107
        self.__clusters = [];
108
        self.__noise = [];
109
        
110
        self.__ccore = ccore;
111
        if (self.__ccore):
112
            self.__ccore = ccore_library.workable();
113
114
115
    def process(self):
116
        """!
117
        @brief Performs cluster analysis in line with rules of DBSCAN algorithm.
118
        
119
        @see get_clusters()
120
        @see get_noise()
121
        
122
        """
123
        
124
        if self.__ccore is True:
125
            (self.__clusters, self.__noise) = wrapper.dbscan(self.__pointer_data, self.__eps, self.__neighbors, self.__data_type);
126
            
127
        else:
128
            if self.__data_type == dbscan_data_type.POINTS:
129
                self.__kdtree = kdtree(self.__pointer_data, range(len(self.__pointer_data)));
130
131
            for i in range(0, len(self.__pointer_data)):
132
                if self.__visited[i] is False:
133
                     
134
                    cluster = self.__expand_cluster(i);
135
                    if cluster is not None:
136
                        self.__clusters.append(cluster);
137
                    else:
138
                        self.__noise.append(i);
139
                        self.__belong[i] = True;
140
141
142
    def get_clusters(self):
143
        """!
144
        @brief Returns allocated clusters.
145
        
146
        @remark Allocated clusters can be returned only after data processing (use method process()). Otherwise empty list is returned.
147
        
148
        @return (list) List of allocated clusters, each cluster contains indexes of objects in list of data.
149
        
150
        @see process()
151
        @see get_noise()
152
        
153
        """
154
        
155
        return self.__clusters;
156
157
158
    def get_noise(self):
159
        """!
160
        @brief Returns allocated noise.
161
        
162
        @remark Allocated noise can be returned only after data processing (use method process() before). Otherwise empty list is returned.
163
        
164
        @return (list) List of indexes that are marked as a noise.
165
        
166
        @see process()
167
        @see get_clusters()
168
        
169
        """
170
171
        return self.__noise;
172
173
174
    def get_cluster_encoding(self):
175
        """!
176
        @brief Returns clustering result representation type that indicate how clusters are encoded.
177
        
178
        @return (type_encoding) Clustering result representation.
179
        
180
        @see get_clusters()
181
        
182
        """
183
        
184
        return type_encoding.CLUSTER_INDEX_LIST_SEPARATION;
185
186
187
    def __expand_cluster(self, index_point):
188
        """!
189
        @brief Expands cluster from specified point in the input data space.
190
        
191
        @param[in] index_point (list): Index of a point from the data.
192
193
        @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.
194
        
195
        """
196
        
197
        cluster = None;
198
        self.__visited[index_point] = True;
199
        neighbors = self.__neighbor_indexes(index_point);
200
         
201
        if len(neighbors) >= self.__neighbors:
202
            cluster = [ index_point ];
203
             
204
            self.__belong[index_point] = True;
205
             
206
            for i in neighbors:
207
                if self.__visited[i] is False:
208
                    self.__visited[i] = True;
209
                    next_neighbors = self.__neighbor_indexes(i);
210
                     
211
                    if len(next_neighbors) >= self.__neighbors:
212
                        # if some node has less then minimal number of neighbors than we shouldn't look at them
213
                        # because maybe it's a noise.
214
                        neighbors += [k for k in next_neighbors if ( (k in neighbors) == False)];
215
                 
216
                if self.__belong[i] is False:
217
                    cluster.append(i);
218
                    self.__belong[i] = True;
219
             
220
        return cluster;
221
222
    def __neighbor_indexes(self, index_point):
223
        """!
224
        @brief Return list of indexes of neighbors of specified point for the data.
225
        
226
        @param[in] index_point (list): An index of a point for which potential neighbors should be returned in line with connectivity radius.
227
        
228
        @return (list) Return list of indexes of neighbors in line the connectivity radius.
229
        
230
        """
231
232
        if self.__data_type == dbscan_data_type.POINTS:
233
            kdnodes = self.__kdtree.find_nearest_dist_nodes(self.__pointer_data[index_point], self.__eps);
234
            return [node_tuple[1].payload for node_tuple in kdnodes if node_tuple[1].payload != index_point];
235
236
        else:
237
            distances = self.__pointer_data[index_point];
238
            return [ index_neighbor for index_neighbor in range(len(distances))
239
                     if ( (distances[index_neighbor] <= self.__eps) and (index_neighbor != index_point) ) ];
240