Debian Codegraph @

easel/esl_msacluster.c

raw symbols SCIP
1 /* Clustering sequences in an MSA by % identity.
2 *
3 * Table of contents:
4 * 1. Single linkage clustering an MSA by %id
5 * 2. Internal functions, interface to the clustering API
6 * 3. Some internal functions needed for regression tests
7 * 4. Unit tests
8 * 5. Test driver
9 * 6. Example
10 *
11 * (Wondering why isn't this just part of the cluster or MSA modules?
12 * esl_cluster itself is a core module, dependent only on easel. MSA
13 * clustering involves at least the distance, cluster, and msa
14 * modules. We're better off separating its functionality away into a
15 * more highly derived module.)
16 */
17 #include <esl_config.h>
18
19 #include "easel.h"
20 #include "esl_alphabet.h"
21 #include "esl_cluster.h"
22 #include "esl_distance.h"
23 #include "esl_msa.h"
24
25 #include "esl_msacluster.h"
26
27 /* These functions are going to get defined in an internal regression
28 * testing section further below:
29 */
30 #if defined(eslMSACLUSTER_REGRESSION) || defined(eslMSAWEIGHT_REGRESSION)
31 #include <ctype.h>
32 static double squid_distance(char *s1, char *s2);
33 static double squid_xdistance(ESL_ALPHABET *a, ESL_DSQ *x1, ESL_DSQ *x2);
34 #endif
35
36 /* These functions will define linkage between a pair of text or
37 * digital aseq's:
38 */
39 static int msacluster_clinkage(const void *v1, const void *v2, const void *p, int *ret_link);
40 static int msacluster_xlinkage(const void *v1, const void *v2, const void *p, int *ret_link);
41
42 /* In digital mode, we'll need to pass the clustering routine two parameters -
43 * %id threshold and alphabet ptr - so make a structure that bundles them.
44 */
45 struct msa_param_s {
46 double maxid;
47 ESL_ALPHABET *abc;
48 };
49
50
51 /*****************************************************************
52 * 1. Single linkage clustering an MSA by %id
53 *****************************************************************/
54
55 /* Function: esl_msacluster_SingleLinkage()
56 * Synopsis: Single linkage clustering by percent identity.
57 * Incept: SRE, Sun Nov 5 10:11:45 2006 [Janelia]
58 *
59 * Purpose: Perform single link clustering of the sequences in
60 * multiple alignment <msa>. Any pair of sequences with
61 * percent identity $\geq$ <maxid> are linked (using
62 * the definition from the \eslmod{distance} module).
63 *
64 * The resulting clustering is optionally returned in one
65 * or more of <opt_c>, <opt_nin>, and <opt_nc>. The
66 * <opt_c[0..nseq-1]> array assigns a cluster index
67 * <(0..nc-1)> to each sequence. For example, <c[4] = 1>
68 * means that sequence 4 is assigned to cluster 1. The
69 * <opt_nin[0..nc-1]> array is the number of sequences
70 * in each cluster. <opt_nc> is the number of clusters.
71 *
72 * Importantly, this algorithm runs in $O(N)$ memory, and
73 * produces one discrete clustering. Compare to
74 * <esl_tree_SingleLinkage()>, which requires an $O(N^2)$
75 * adjacency matrix, and produces a hierarchical clustering
76 * tree.
77 *
78 * The algorithm is worst case $O(LN^2)$ time, for $N$
79 * sequences of length $L$. However, the worst case is no
80 * links at all, and this is unusual. More typically, time
81 * scales as about $LN \log N$. The best case scales as
82 * $LN$, when there is just one cluster in a completely
83 * connected graph.
84 *
85 * Args: msa - multiple alignment to cluster
86 * maxid - pairwise identity threshold: cluster if $\geq$ <maxid>
87 * opt_c - optRETURN: cluster assignments for each sequence, [0..nseq-1]
88 * opt_nin - optRETURN: number of seqs in each cluster, [0..nc-1]
89 * opt_nc - optRETURN: number of clusters
90 *
91 * Returns: <eslOK> on success; the <opt_c[0..nseq-1]> array contains
92 * cluster indices <0..nc-1> assigned to each sequence; the
93 * <opt_nin[0..nc-1]> array contains the number of seqs in
94 * each cluster; and <opt_nc> contains the number of
95 * clusters. The <opt_c> array and <opt_nin> arrays will be
96 * allocated here, if non-<NULL>, and must be free'd by the
97 * caller. The input <msa> is unmodified.
98 *
99 * The caller may pass <NULL> for either <opt_c> or
100 * <opt_nc> if it is only interested in one of the two
101 * results.
102 *
103 * Throws: <eslEMEM> on allocation failure, and <eslEINVAL> if a pairwise
104 * comparison is invalid (which means the MSA is corrupted, so it
105 * shouldn't happen). In either case, <opt_c> and <opt_nin> are set to <NULL>
106 * and <opt_nc> is set to 0, and the <msa> is unmodified.
107 */
108 int
109 esl_msacluster_SingleLinkage(const ESL_MSA *msa, double maxid,
110 int **opt_c, int **opt_nin, int *opt_nc)
111
112 {
113 int status;
114 int *workspace = NULL;
115 int *assignment = NULL;
116 int *nin = NULL;
117 int nc;
118 int i;
119 struct msa_param_s param;
120 int free_assignment = 0;
121 int allocated_assignment = 0;
122 /* Allocations */
123 ESL_ALLOC(workspace, sizeof(int) * msa->nseq * 2);
124 if(opt_c != NULL && *opt_c !=NULL){ // opt_c exists, and already has memory allocated
125 assignment = *opt_c;
126 }
127 else{ // need to allocate space for assignment
128 ESL_ALLOC(assignment, sizeof(int) * msa->nseq);
129 allocated_assignment = 1;
130 if(opt_c != NULL){ // opt_c exists, but had no memory allocated
131 *opt_c = assignment;
132 }
133 else{ // opt_c doesn't exist, so need to clean up assignment memory
134 free_assignment = 1;
135 }
136 }
137
138
139 /* call to SLC API: */
140 if (! (msa->flags & eslMSA_DIGITAL))
141 status = esl_cluster_SingleLinkage((void *) msa->aseq, (size_t) msa->nseq, sizeof(char *),
142 msacluster_clinkage, (void *) &maxid,
143 workspace, assignment, &nc);
144 else {
145 param.maxid = maxid;
146 param.abc = msa->abc;
147 status = esl_cluster_SingleLinkage((void *) msa->ax, (size_t) msa->nseq, sizeof(ESL_DSQ *),
148 msacluster_xlinkage, (void *) &param,
149 workspace, assignment, &nc);
150 }
151 if (status != eslOK) goto ERROR;
152
153
154 if (opt_nin != NULL)
155 {
156 if(*opt_nin == NULL){ // Need to allocate backing storage
157 ESL_ALLOC(nin, sizeof(int) * nc);
158 *opt_nin = nin;
159 }
160 else{ //use the storage that's already there
161 nin = *opt_nin;
162 }
163 for (i = 0; i < nc; i++) nin[i] = 0;
164 for (i = 0; i < msa->nseq; i++)
165 nin[assignment[i]]++;
166
167 }
168
169 /* cleanup and return */
170 free(workspace);
171 if(free_assignment){
172 free(assignment);
173 }
174 if (opt_nc != NULL) *opt_nc = nc;
175 return eslOK;
176
177 ERROR:
178 if (workspace != NULL) free(workspace);
179 if (allocated_assignment) free(assignment);
180 if (nin != NULL) free(nin);
181 if (opt_c != NULL) *opt_c = NULL;
182 if (opt_nc != NULL) *opt_nc = 0;
183 return status;
184 }
185
186
187
188
189
190 /*****************************************************************
191 * 2. Internal functions, interface to the clustering API
192 *****************************************************************/
193
194 /* Definition of %id linkage in text-mode aligned seqs (>= maxid): */
195 static int
196 msacluster_clinkage(const void *v1, const void *v2, const void *p, int *ret_link)
197 {
198 char *as1 = *(char **) v1;
199 char *as2 = *(char **) v2;
200 double maxid = *(double *) p;
201 double pid;
202 int status = eslOK;
203
204 #if defined(eslMSACLUSTER_REGRESSION) || defined(eslMSAWEIGHT_REGRESSION)
205 pid = 1. - squid_distance(as1, as2);
206 #else
207 if ((status = esl_dst_CPairId(as1, as2, &pid, NULL, NULL)) != eslOK) return status;
208 #endif
209
210 *ret_link = (pid >= maxid ? TRUE : FALSE);
211 return status;
212 }
213
214 /* Definition of % id linkage in digital aligned seqs (>= maxid) */
215 static int
216 msacluster_xlinkage(const void *v1, const void *v2, const void *p, int *ret_link)
217 {
218 ESL_DSQ *ax1 = *(ESL_DSQ **) v1;
219 ESL_DSQ *ax2 = *(ESL_DSQ **) v2;
220 struct msa_param_s *param = (struct msa_param_s *) p;
221 double pid;
222 int status = eslOK;
223
224 #if defined(eslMSACLUSTER_REGRESSION) || defined(eslMSAWEIGHT_REGRESSION)
225 pid = 1. - squid_xdistance(param->abc, ax1, ax2);
226 #else
227 if ( (status = esl_dst_XPairId(param->abc, ax1, ax2, &pid, NULL, NULL)) != eslOK) return status;
228 #endif
229
230 *ret_link = (pid >= param->maxid ? TRUE : FALSE);
231 return status;
232 }
233
234
235 /*****************************************************************
236 * 3. Some internal functions needed for regression tests
237 *****************************************************************/
238
239 /* When regression testing against squid, we have to replace
240 * Easel's distance calculations with a simpler, (even) less robust
241 * calculation that squid did.
242 */
243 #if defined(eslMSACLUSTER_REGRESSION) || defined(eslMSAWEIGHT_REGRESSION)
244 static double
245 squid_distance(char *s1, char *s2)
246 {
247 int diff = 0;
248 int valid = 0;
249
250 for (; *s1 != '\0'; s1++, s2++)
251 {
252 if (!isalpha(*s1) || !isalpha(*s2)) continue;
253 if (*s1 != *s2) diff++;
254 valid++;
255 }
256 return (valid > 0 ? ((double) diff / (double) valid) : 0.0);
257 }
258 static double
259 squid_xdistance(ESL_ALPHABET *a, ESL_DSQ *x1, ESL_DSQ *x2)
260 {
261 int diff = 0;
262 int valid = 0;
263
264 for (; *x1 != eslDSQ_SENTINEL; x1++, x2++)
265 {
266 if (esl_abc_XIsGap(a, *x1) || esl_abc_XIsGap(a, *x2)) continue;
267 if (*x1 != *x2) diff++;
268 valid++;
269 }
270 return (valid > 0 ? ((double) diff / (double) valid) : 0.0);
271 }
272 #endif /* eslMSACLUSTER_REGRESSION || eslMSAWEIGHT_REGRESSION */
273
274
275 /*****************************************************************
276 * 4. Unit tests
277 *****************************************************************/
278 #ifdef eslMSACLUSTER_TESTDRIVE
279 #include "esl_getopts.h"
280
281 static void
282 utest_SingleLinkage(ESL_GETOPTS *go, const ESL_MSA *msa, double maxid, int expected_nc, int last_assignment)
283 {
284 char *msg = "utest_SingleLinkage() failed";
285 int *assignment = NULL;
286 int *nin = NULL;
287 int nc;
288
289 if (esl_msacluster_SingleLinkage(msa, maxid, &assignment, &nin, &nc) != eslOK) esl_fatal(msg);
290 if (nc != expected_nc) esl_fatal(msg);
291 if (assignment[msa->nseq-1] != last_assignment) esl_fatal(msg);
292 free(assignment);
293 free(nin);
294 }
295 #endif /*eslMSACLUSTER_TESTDRIVE*/
296
297 /*****************************************************************
298 * 5. Test driver
299 *****************************************************************/
300 #ifdef eslMSACLUSTER_TESTDRIVE
301 /* gcc -g -Wall -o msacluster_utest -I. -L. -DeslMSACLUSTER_TESTDRIVE esl_msacluster.c -leasel -lm
302 */
303 #include <esl_config.h>
304
305 #include <stdio.h>
306 #include <math.h>
307
308 #include "easel.h"
309 #include "esl_alphabet.h"
310 #include "esl_getopts.h"
311 #include "esl_msa.h"
312 #include "esl_msacluster.h"
313 #include "esl_msafile.h"
314
315 static ESL_OPTIONS options[] = {
316 /* name type default env range toggles reqs incomp help docgroup*/
317 { "-h", eslARG_NONE, FALSE, NULL, NULL, NULL, NULL, NULL, "show brief help on version and usage", 0 },
318 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
319 };
320 static char usage[] = "[-options]";
321 static char banner[] = "test driver for msacluster module";
322
323 int
324 main(int argc, char **argv)
325 {
326 ESL_GETOPTS *go = esl_getopts_CreateDefaultApp(options, 0, argc, argv, banner, usage);
327 ESL_ALPHABET *abc = esl_alphabet_Create(eslAMINO);
328 char *msg = "esl_msacluster_utest failed";
329 int status;
330 ESL_MSA *msa = esl_msa_CreateFromString("\
331 # STOCKHOLM 1.0\n\
332 \n\
333 seq0 AAAAAAAAAA\n\
334 seq1 AAAAAAAAAA\n\
335 seq2 AAAAAAAAAC\n\
336 seq3 AAAAAAAADD\n\
337 seq4 AAAAAAAEEE\n\
338 seq5 AAAAAAFFFF\n\
339 seq6 AAAAAGGGGG\n\
340 seq7 AAAAHHHHHH\n\
341 seq8 AAAIIIIIII\n\
342 seq9 AAKKKKKKKK\n\
343 seq10 ALLLLLLLLL\n\
344 seq11 MMMMMMMMMM\n\
345 //", eslMSAFILE_STOCKHOLM);
346
347
348 utest_SingleLinkage(go, msa, 1.0, 11, 10); /* at 100% id, only seq0/seq1 cluster */
349 utest_SingleLinkage(go, msa, 0.5, 6, 5); /* at 50% id, seq0-seq6 cluster */
350 utest_SingleLinkage(go, msa, 0.0, 1, 0); /* at 0% id, everything clusters */
351
352 /* Do the same tests, but now with a digital MSA */
353 esl_msa_Digitize(abc, msa, NULL);
354 utest_SingleLinkage(go, msa, 1.0, 11, 10); /* at 100% id, only seq0/seq1 cluster */
355 utest_SingleLinkage(go, msa, 0.5, 6, 5); /* at 50% id, seq0-seq6 cluster */
356 utest_SingleLinkage(go, msa, 0.0, 1, 0); /* at 0% id, everything clusters */
357
358
359 // test handling of the three possible cases for the assignment input/output
360 int *nin = NULL;
361 int nc;
362 // Passing NULL as assignment should cause allocate + free within
363 //msacluster_SingleLinkage
364 if (esl_msacluster_SingleLinkage(msa, 0.5, NULL, &nin, &nc) != eslOK) esl_fatal(msg);
365
366 int *assignment = NULL;
367
368 // Passing an assignment variable with no backing storage should cause //
369 // msacluster_SingleLinkage to allocate
370 if (esl_msacluster_SingleLinkage(msa, 0.5, &assignment, &nin, &nc) != eslOK) esl_fatal(msg);
371
372 if(assignment == NULL) esl_fatal(msg);
373 free(assignment);
374
375 ESL_ALLOC(assignment, 12*sizeof(int));
376 int *assignment2 = assignment;
377
378 // Passing an assignment variable with backing storage should cause //
379 // msacluster_SingleLinkage to use the allocated storage
380 if (esl_msacluster_SingleLinkage(msa, 0.5, &assignment, &nin, &nc) != eslOK) esl_fatal(msg);
381
382 if(assignment != assignment2) esl_fatal(msg);
383 free(assignment);
384
385
386 free(nin);
387
388 esl_msa_Destroy(msa);
389 esl_alphabet_Destroy(abc);
390 esl_getopts_Destroy(go);
391 return 0;
392
393 ERROR:
394 return eslFAIL;
395 }
396 #endif /* eslMSACLUSTER_TESTDRIVE*/
397
398
399
400
401 /*****************************************************************
402 * 6. Example
403 *****************************************************************/
404
405 #ifdef eslMSACLUSTER_EXAMPLE
406 /*::cexcerpt::msacluster_example::begin::*/
407 /*
408 gcc -g -Wall -o msacluster_example -I. -L. -DeslMSACLUSTER_EXAMPLE esl_msacluster.c -leasel -lm
409 ./msacluster_example <MSA file>
410 */
411 #include <stdio.h>
412 #include "easel.h"
413 #include "esl_msa.h"
414 #include "esl_msacluster.h"
415 #include "esl_msafile.h"
416
417 int
418 main(int argc, char **argv)
419 {
420 char *filename = argv[1];
421 int fmt = eslMSAFILE_UNKNOWN;
422 ESL_ALPHABET *abc = NULL;
423 ESL_MSAFILE *afp = NULL;
424 ESL_MSA *msa = NULL;
425 double maxid = 0.62; /* cluster at 62% identity: the BLOSUM62 rule */
426 int *assignment = NULL;
427 int *nin = NULL;
428 int nclusters;
429 int c, i;
430 int status;
431
432 /* Open; guess alphabet; set to digital mode */
433 if ((status = esl_msafile_Open(&abc, filename, NULL, fmt, NULL, &afp)) != eslOK)
434 esl_msafile_OpenFailure(afp, status);
435
436 /* read one alignment */
437 if ((status = esl_msafile_Read(afp, &msa)) != eslOK)
438 esl_msafile_ReadFailure(afp, status);
439
440 /* do the clustering */
441 esl_msacluster_SingleLinkage(msa, maxid, &assignment, &nin, &nclusters);
442
443 printf("%d clusters at threshold of %f fractional identity\n", nclusters, maxid);
444 for (c = 0; c < nclusters; c++) {
445 printf("cluster %d:\n", c);
446 for (i = 0; i < msa->nseq; i++) if (assignment[i] == c) printf(" %s\n", msa->sqname[i]);
447 printf("(%d sequences)\n\n", nin[c]);
448 }
449
450 esl_msa_Destroy(msa);
451 esl_msafile_Close(afp);
452 free(assignment);
453 free(nin);
454 return 0;
455 }
456 /*::cexcerpt::msacluster_example::end::*/
457 #endif /*eslMSACLUSTER_EXAMPLE*/
458 /*------------------------ end of example -----------------------*/