Debian Codegraph @

easel/esl_cluster.c

raw symbols SCIP
1 /* Generalized single linkage clustering.
2 *
3 * Contents:
4 * 1. Single linkage clustering, generalized
5 * 2. Unit tests
6 * 3. Test driver
7 * 4. Example
8 */
9 #include <esl_config.h>
10
11 #include <stdlib.h>
12
13 #include "easel.h"
14 #include "esl_cluster.h"
15
16
17 /*****************************************************************
18 * 1. Single linkage clustering, generalized
19 *****************************************************************/
20
21 /* Function: esl_cluster_SingleLinkage()
22 * Synopsis: Generalized single linkage clustering.
23 * Incept: SRE, Mon Jan 7 08:35:10 2008 [Janelia]
24 *
25 * Purpose: Given a set of vertices, cluster them by single-linkage
26 * clustering.
27 *
28 * The data describing each vertex is provided in an array
29 * starting at <base>, consisting of <n> vertices. Each
30 * vertex can be of any type (structure, scalar, pointer)
31 * so long as each vertex element is of fixed size <n>
32 * bytes.
33 *
34 * A pointer to the clustering function is provided in
35 * <(*linkfunc)()>, and a pointer to any necessary
36 * parameters for that function (for example, any
37 * thresholds) is provided in <param>.
38 *
39 * The <int (*linkfunc)()> must be written by the
40 * caller. It takes arguments <(void *v1, void *v2, void
41 * *param, int *ret_link)>: pointers to two vertices to
42 * test for linkage and a pointer to any necessary
43 * parameters, and it passes the answer <TRUE> (1) or
44 * <FALSE> (0) back in <*ret_link>. The <(*linkfunc)()>
45 * returns <eslOK> (0) on success, and a nonzero error code
46 * on failure (see <easel.h> for a list of Easel's error
47 * codes).
48 *
49 * The caller provides an allocated <workspace> with space
50 * for at least <2n> integers. (Allocation in the caller
51 * allows the caller to reuse memory and save
52 * allocation/free cycles, if it has many rounds of
53 * clustering to do.)
54 *
55 * The caller also provides allocated space in
56 * <assignments> for <n> integers which, upon successful
57 * return, contains assignments of the <0..n-1> vertices to
58 * <0..C-1> clusters. That is, if <assignments[42] = 1>,
59 * that means vertex 42 is assigned to cluster 1. The
60 * total number of clusters is returned in <ret_C>.
61 *
62 * The algorithm runs in $O(N)$ memory; importantly, it
63 * does not require a $O(N^2)$ adjacency matrix. Worst case
64 * time complexity is $O(N^2)$ (multiplied by any
65 * additional complexity in the <(*linkfunc()> itself), but
66 * the worst case (no links at all; <C=n> clusters) should
67 * be unusual. More typically, time scales as about $N \log
68 * N$. Best case is $N$, for a completely connected graph
69 * in which all vertices group into one cluster. (More
70 * precisely, best case complexity arises when vertex 0 is
71 * connected to all other <n-1> vertices.)
72 *
73 * Notes: I don't know if this algorithm is published. I
74 * haven't seen it in graph theory books, but that might
75 * be because it's so obvious that nobody's bothered.
76 *
77 * In brief, we're going to do a breadth-first search of the
78 * graph, and we're going to calculate links on the fly
79 * rather than precalculating them into a standard adjacency
80 * matrix.
81 *
82 * While working, we keep two stacks of maximum length N:
83 * a : list of vertices that are still unconnected.
84 * b : list of vertices that we've connected to
85 * in our current breadth level, but we haven't
86 * yet tested for other connections to a.
87 * The current length (number of elements in) a and b are
88 * kept in na, nb.
89 *
90 * We store our results in an array of length N:
91 * c : assigns each vertex to a component. for example
92 * c[4] = 1 means that vertex 4 is in component 1.
93 * nc is the number of components. Components
94 * are numbered from 0 to nc-1. We return c and nc
95 * to our caller.
96 *
97 * The algorithm is:
98 *
99 * Initialisation:
100 * a <-- all the vertices
101 * na <-- N
102 * b <-- empty set
103 * nb <-- 0
104 * nc <-- 0
105 *
106 * Then:
107 * while (a is not empty)
108 * pop a vertex off a, push onto b
109 * while (b is not empty)
110 * pop vertex v off b
111 * assign c[v] = nc
112 * for each vertex w in a:
113 * compare v,w. If w is linked to v, remove w
114 * from a, push onto b.
115 * nc++
116 * q.e.d.
117 *
118 * Args: base - pointer to array of n fixed-size vertices to be clustered.
119 * n - number of vertices
120 * size - size of each vertex element
121 * linkfunc - pointer to caller's function for defining linked pairs
122 * param - pointer to any data that needs to be provided to <(*linkfunc)>
123 * workspace - caller provides at least 2n*sizeof(int) of workspace
124 * assignments - RETURN: assignments to clusters (caller provides n*sizeof(int) space)
125 * ret_C - RETURN: number of clusters
126 *
127 * Returns: <eslOK> on success; <assignments[0..n-1]> contains cluster assigments
128 * <0..C-1> for each vertex, and <*ret_C> contains the number of clusters
129 * <C>
130 *
131 * Throws: status codes from the caller's <(*linkfunc)> on failure; in this case,
132 * the contents of <*assignments> is undefined, and <*ret_C> is 0.
133 */
134 int
135 esl_cluster_SingleLinkage(const void *base, size_t n, size_t size,
136 int (*linkfunc)(const void *, const void *, const void *, int *), const void *param,
137 int *workspace, int *assignments, int *ret_C)
138 {
139 int na, *a = NULL; /* stack of available vertices (still unconnected) */
140 int nb, *b = NULL; /* stack of connected but unextended vertices */
141 int nc, *c = NULL; /* array of results: # clusters, assignments to clusters */
142 int v,w; /* indices of vertices */
143 int i; /* counter over the available list */
144 int do_link;
145 int status;
146
147 a = workspace;
148 b = workspace + n;
149 c = assignments;
150
151 for (v = 0; v < n; v++) a[v] = n-v-1; /* initialize by pushing all vertices onto available list (backwards) */
152 na = n;
153 nb = 0;
154 nc = 0;
155
156 while (na > 0) /* while vertices remain unexamined or unclustered: */
157 {
158 v = a[na-1]; na--; /* pop a vertex off a, */
159 b[nb] = v; nb++; /* and push it onto b */
160
161 while (nb > 0) /* while vertices remain unextended: */
162 {
163 v = b[nb-1]; nb--; /* pop vertex off b */
164 c[v] = nc; /* assign it to cluster nc */
165 for (i = na-1; i >= 0; i--) /* backwards, because of deletion/swapping we do*/
166 {
167 if ((status = (*linkfunc)( (char *) base + v*size, (char *) base + a[i]*size, param, &do_link)) != eslOK) goto ERROR;
168 if (do_link)
169 {
170 w = a[i]; a[i] = a[na-1]; na--; /* delete w from a */
171 b[nb] = w; nb++; /* and push it onto b */
172 }
173 }
174 }
175 nc++;
176 }
177
178 *ret_C = nc;
179 return eslOK;
180
181 ERROR:
182 *ret_C = 0;
183 return status;
184 }
185 /*------------------ end, single linkage clustering -------------*/
186
187
188
189
190
191
192 /*****************************************************************
193 * 2. Unit tests
194 *****************************************************************/
195 #ifdef eslCLUSTER_TESTDRIVE
196 #include <math.h>
197
198 static int
199 test_linkage_definition(const void *v1, const void *v2, const void *param, int *ret_link)
200 {
201 double a = *((double *) v1); /* you have to cast a void ptr before you can dereference it */
202 double b = *((double *) v2);
203 double threshold = *((double *) param);
204
205 *ret_link = ((fabs(a-b) <= threshold) ? TRUE : FALSE);
206 return eslOK;
207 }
208
209 static void
210 utest_singlelinkage(double *testdata, int n, double threshold, int *correct_assignment, int correct_C)
211 {
212 int *workspace;
213 int *assignment;
214 int C;
215 int v;
216
217 if ((workspace = malloc(sizeof(int) * n * 2)) == NULL) esl_fatal("allocation failed");
218 if ((assignment = malloc(sizeof(int) * n)) == NULL) esl_fatal("allocation failed");
219
220 if (esl_cluster_SingleLinkage(testdata, n, sizeof(double),
221 test_linkage_definition, &threshold,
222 workspace, assignment, &C) != eslOK) esl_fatal("single linkage clustering failed");
223
224 if (C != correct_C) esl_fatal("expected %d clusters, but got %d\n", correct_C, C);
225 for (v = 0; v < n; v++)
226 if (correct_assignment[v] != assignment[v])
227 esl_fatal("expected vertex %d to be in cluster %d, but it's in %d\n", v, correct_assignment[v], assignment[v]);
228
229 free(workspace);
230 free(assignment);
231 }
232 #endif /* eslCLUSTER_TESTDRIVE */
233
234
235
236
237 /*****************************************************************
238 * 3. Test driver
239 *****************************************************************/
240 #ifdef eslCLUSTER_TESTDRIVE
241 /* gcc -g -Wall -o test -I. -L. -DeslCLUSTER_TESTDRIVE esl_cluster.c -leasel -lm
242 */
243 #include <esl_config.h>
244
245 #include <stdio.h>
246 #include <math.h>
247
248 #include "easel.h"
249 #include "esl_getopts.h"
250 #include "esl_cluster.h"
251
252 static ESL_OPTIONS options[] = {
253 /* name type default env range toggles reqs incomp help docgroup*/
254 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
255 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
256 };
257 static char usage[] = "[-options]";
258 static char banner[] = "test driver for cluster module";
259
260 int
261 main(int argc, char **argv)
262 {
263 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
264 double vertex[] = { 1.0, 2.0, 4.0, 5.0, 7.0, 8.0 };
265 int na1 = 3, a1[] = { 0, 0, 1, 1, 2, 2 }; /* correct answer when threshold = 1.5 */
266 int na2 = 6, a2[] = { 0, 1, 2, 3, 4, 5 }; /* correct answer when threshold < 1.0 */
267 int na3 = 1, a3[] = { 0, 0, 0, 0, 0, 0 }; /* correct answer when threshold > 2.0 */
268 int n = sizeof(vertex) / sizeof(double);
269
270 utest_singlelinkage(vertex, n, 1.5, a1, na1);
271 utest_singlelinkage(vertex, n, 0.5, a2, na2);
272 utest_singlelinkage(vertex, n, 2.5, a3, na3);
273
274 esl_getopts_Destroy(go);
275 return 0;
276 }
277 #endif /* eslCLUSTER_TESTDRIVE*/
278
279
280
281
282
283 /*****************************************************************
284 * 4. Example
285 *****************************************************************/
286 #ifdef eslCLUSTER_EXAMPLE
287 /*::cexcerpt::cluster_example::begin::*/
288 /* gcc -g -Wall -o example -I. -L. -DeslCLUSTER_EXAMPLE esl_cluster.c easel.c -lm */
289 #include <esl_config.h>
290
291 #include <stdio.h>
292 #include <stdlib.h>
293 #include <math.h>
294
295 #include "easel.h"
296 #include "esl_cluster.h"
297
298 static int
299 my_linkage_definition(const void *v1, const void *v2, const void *param, int *ret_link)
300 {
301 double a = *((double *) v1); /* you have to cast a void ptr before you can dereference it */
302 double b = *((double *) v2);
303 double threshold = *((double *) param);
304
305 *ret_link = ((fabs(a-b) <= threshold) ? TRUE : FALSE);
306 return eslOK;
307 }
308
309 int
310 main(int argc, char **argv)
311 {
312 double vertex[] = { 1.0, 2.0, 4.0, 5.0, 7.0, 8.0 };
313 int n = sizeof(vertex) / sizeof(double);
314 double threshold = 1.5;
315 int *workspace;
316 int *assignment;
317 int C;
318 int v;
319
320 workspace = malloc(sizeof(int) * n * 2);
321 assignment = malloc(sizeof(int) * n);
322
323 esl_cluster_SingleLinkage(vertex, n, sizeof(double),
324 my_linkage_definition, &threshold,
325 workspace, assignment, &C);
326
327 printf("There are %d clusters.\n", C);
328 for (v = 0; v < n; v++) printf("vertex %d is in cluster %d\n", v, assignment[v]);
329
330 free(workspace);
331 free(assignment);
332 return 0;
333 }
334 /*::cexcerpt::cluster_example::end::*/
335 #endif /*eslCLUSTER_EXAMPLE*/
336
337
338
339