Debian Codegraph @

bcftools/hclust.c

raw symbols SCIP
1 /* The MIT License
2
3 Copyright (c) 2016 Genome Research Ltd.
4
5 Author: Petr Danecek <[email protected]>
6
7 Permission is hereby granted, free of charge, to any person obtaining a copy
8 of this software and associated documentation files (the "Software"), to deal
9 in the Software without restriction, including without limitation the rights
10 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 copies of the Software, and to permit persons to whom the Software is
12 furnished to do so, subject to the following conditions:
13
14 The above copyright notice and this permission notice shall be included in
15 all copies or substantial portions of the Software.
16
17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 THE SOFTWARE.
24
25 */
26
27 #include <htslib/hts.h>
28 #include <htslib/kstring.h>
29 #include <stdlib.h>
30 #include <assert.h>
31 #include "bcftools.h"
32 #include "hclust.h"
33
34 typedef struct _node_t
35 {
36 struct _node_t *akid, *bkid, *next, *prev, *parent;
37 int id, idx; // id: unique node id; idx: current index to pdist
38 float value; // max pairwise dist of elements within the node
39 }
40 node_t;
41
42 struct _hclust_t
43 {
44 int ndat, nclust; // ndat: number of elements (pdist matrix size); nclust: current number of clusters
45 float *pdist; // pairwise cluster distances, diagonal matrix accessed via the PDIST macro
46 node_t *first, *last; // clusters are maintained in a double-linked list
47 node_t **rmme; // convenience array to remove all allocated nodes at the end
48 int nrmme;
49 kstring_t str; // (for debugging) pointer to str.s is returned by create_dot()
50 char **dbg; // (for debugging) created by create_list() via set_threshold() and returned by explain()
51 int ndbg, mdbg;
52 };
53
54 node_t *append_node(hclust_t *clust, int idx)
55 {
56 node_t *node = (node_t*) calloc(1,sizeof(node_t));
57
58 clust->nclust++;
59 node->id = clust->nrmme;
60 node->idx = idx;
61 if ( !clust->first )
62 {
63 clust->first = node;
64 clust->last = node;
65 }
66 else
67 {
68 node->prev = clust->last;
69 clust->last->next = node;
70 clust->last = node;
71 }
72
73 if ( clust->nrmme >= clust->ndat*2 ) error("hclust fixme: %d vs %d\n",clust->nrmme,clust->ndat);
74 clust->rmme[clust->nrmme++] = node;
75
76 return node;
77 }
78 void remove_node(hclust_t *clust, node_t *node)
79 {
80 if ( node==clust->first ) clust->first = node->next;
81 if ( node==clust->last ) clust->last = node->prev;
82 if ( node->next ) node->next->prev = node->prev;
83 if ( node->prev ) node->prev->next = node->next;
84 clust->nclust--;
85 }
86
87 #if DEBUG
88 void hclust_debug(hclust_t *clust)
89 {
90 int i;
91 fprintf(stderr,"nrmme=%d nclust=%d\n", clust->nrmme,clust->nclust);
92 for (i=0; i<clust->nrmme; i++)
93 {
94 node_t *node = clust->rmme[i];
95 int akid = node->akid ? node->akid->id : -1;
96 int bkid = node->bkid ? node->bkid->id : -1;
97 int akidx = node->akid ? node->akid->idx : -1;
98 int bkidx = node->bkid ? node->bkid->idx : -1;
99 fprintf(stderr,"\t%d\t%d\t%f\t%d %d\t%d %d\n",node->id,node->idx,node->value,akid,bkid,akidx,bkidx);
100 }
101
102 int j;
103 for (i=1; i<clust->ndat; i++)
104 {
105 int active = 0;
106 node_t *node = clust->first;
107 while (node)
108 {
109 if ( node->idx==i ) { active=1; break; }
110 node = node->next;
111 }
112 fprintf(stderr,"%2d%c ",i,active?'*':' ');
113 for (j=0; j<i; j++)
114 {
115 if ( PDIST(clust->pdist,i,j)==9 )
116 fprintf(stderr," ----- ");
117 else
118 fprintf(stderr," %f", PDIST(clust->pdist,i,j));
119 }
120 fprintf(stderr,"\n");
121 }
122 for (j=0; j<clust->ndat-1; j++) fprintf(stderr," %6d ",j); fprintf(stderr,"\n");
123 }
124 #endif
125
126 hclust_t *hclust_init(int n, float *pdist)
127 {
128 hclust_t *clust = (hclust_t*) calloc(1,sizeof(hclust_t));
129 clust->ndat = n;
130 clust->pdist = pdist;
131 clust->rmme = (node_t**) calloc(n*2,sizeof(node_t*));
132
133 // init clusters
134 int i;
135 for (i=0; i<clust->ndat; i++) append_node(clust,i);
136
137 // build the tree
138 while ( clust->nclust>1 )
139 {
140 // find two clusters with minimum distance
141 float min_value = HUGE_VAL;
142 node_t *iclust = clust->first->next;
143 node_t *min_iclust = NULL, *min_jclust = NULL;
144 while ( iclust )
145 {
146 node_t *jclust = clust->first;
147 while ( jclust!=iclust )
148 {
149 float value = PDIST(clust->pdist,iclust->idx,jclust->idx);
150 if ( value < min_value )
151 {
152 min_value = value;
153 min_iclust = iclust;
154 min_jclust = jclust;
155 }
156 jclust = jclust->next;
157 }
158 iclust = iclust->next;
159 }
160 assert( min_iclust && min_jclust ); // pdist contains inf or nan, fix the caller
161 remove_node(clust,min_iclust);
162 remove_node(clust,min_jclust);
163
164 // update the pairwise distances. We keep the matrix and as we are moving up the
165 // tree, we use fewer columns/rows as the number of clusters decreases: we reuse
166 // i-th and leave j-th unused. Inter-cluster distance is defined as maximum distance
167 // between pairwise distances of elements within the cluster.
168 iclust = clust->first;
169 while ( iclust )
170 {
171 if ( PDIST(clust->pdist,iclust->idx,min_iclust->idx) < PDIST(clust->pdist,iclust->idx,min_jclust->idx) )
172 PDIST(clust->pdist,iclust->idx,min_iclust->idx) = PDIST(clust->pdist,iclust->idx,min_jclust->idx);
173 iclust = iclust->next;
174 }
175
176 node_t *node = append_node(clust,min_iclust->idx);
177 node->akid = min_iclust;
178 node->bkid = min_jclust;
179 node->value = min_value;
180 node->akid->parent = node;
181 node->bkid->parent = node;
182 }
183
184 return clust;
185 }
186 void hclust_destroy(hclust_t *clust)
187 {
188 int i;
189 for (i=0; i<clust->nrmme; i++) free(clust->rmme[i]);
190 free(clust->rmme);
191 free(clust->dbg);
192 free(clust->str.s);
193 free(clust);
194 }
195
196 char *hclust_create_dot(hclust_t *clust, char **labels, float th)
197 {
198 clust->str.l = 0;
199 ksprintf(&clust->str,"digraph myGraph {");
200
201 int i;
202 for (i=0; i<clust->nrmme; i++)
203 {
204 node_t *node = clust->rmme[i];
205 if ( node->value )
206 ksprintf(&clust->str,"\"%d\" [label=\"%f\"];", node->id,node->value);
207 else
208 ksprintf(&clust->str,"\"%d\" [label=\"%s\"];", node->id,labels[node->idx]);
209 }
210 for (i=0; i<clust->nrmme; i++)
211 {
212 node_t *node = clust->rmme[i];
213 if ( node->akid )
214 {
215 if ( node->value >= th && node->akid && node->akid->value < th )
216 ksprintf(&clust->str,"\"%d\" -> \"%d\" [color=\"#D43F3A\" penwidth=3];", node->id,node->akid->id);
217 else
218 ksprintf(&clust->str,"\"%d\" -> \"%d\";", node->id,node->akid->id);
219 }
220
221 if ( node->bkid )
222 {
223 if ( node->value >= th && node->bkid && node->bkid->value < th )
224 ksprintf(&clust->str,"\"%d\" -> \"%d\" [color=\"#D43F3A\" penwidth=3];", node->id,node->bkid->id);
225 else
226 ksprintf(&clust->str,"\"%d\" -> \"%d\";", node->id,node->bkid->id);
227 }
228 }
229 ksprintf(&clust->str,"};");
230 return clust->str.s;
231 }
232 char **hclust_explain(hclust_t *clust, int *nlines)
233 {
234 clust->ndbg = 0;
235 char *beg = clust->str.s;
236 while ( *beg )
237 {
238 char *end = beg;
239 while ( *end && *end!='\n' ) end++;
240 clust->ndbg++;
241 hts_expand(char*,clust->ndbg,clust->mdbg,clust->dbg);
242 clust->dbg[clust->ndbg-1] = beg;
243 if ( !*end ) break;
244 *end = 0;
245 beg = end + 1;
246 }
247
248 *nlines = clust->ndbg;
249 return clust->dbg;
250 }
251
252 cluster_t *append_cluster(node_t *node, cluster_t *cluster, int *nclust, node_t **stack)
253 {
254 (*nclust)++;
255 cluster = (cluster_t*) realloc(cluster,sizeof(cluster_t)*(*nclust));
256 cluster_t *clust = &cluster[*nclust-1];
257 clust->nmemb = 0;
258 clust->memb = NULL;
259 clust->dist = node->value;
260
261 int nstack = 1;
262 stack[0] = node;
263
264 while ( nstack )
265 {
266 node_t *node = stack[--nstack];
267 node_t *akid = node->akid;
268 node_t *bkid = node->bkid;
269 if ( node->akid )
270 {
271 stack[nstack++] = akid;
272 stack[nstack++] = bkid;
273 }
274 else
275 {
276 clust->nmemb++;
277 clust->memb = (int*) realloc(clust->memb,sizeof(int)*clust->nmemb);
278 clust->memb[clust->nmemb-1] = node->id;
279 }
280 }
281 return cluster;
282 }
283
284 int cmp_nodes(const void *a, const void *b)
285 {
286 const node_t *an = *((const node_t**) a);
287 const node_t *bn = *((const node_t**) b);
288 if ( an->value < bn->value ) return -1;
289 if ( an->value > bn->value ) return 1;
290 return 0;
291 }
292
293 float calc_dev(node_t **dat, int n)
294 {
295 float avg = 0, dev = 0;
296 int i;
297 for (i=0; i<n; i++) avg += dat[i]->value;
298 avg /= n;
299 for (i=0; i<n; i++) dev += (dat[i]->value - avg)*(dat[i]->value - avg);
300 return sqrt(dev/n);
301 }
302
303 /*
304 Heuristics to determine clustering cutoff: sort nodes by distance and
305 split into two groups by minimizing the standard deviation.
306 This works best when two elements from a single different sample are
307 included in the mix.
308 - min_inter_dist .. smaller values are always considered identical
309 - max_intra_dist .. larger values are always considered different
310 */
311 float hclust_set_threshold(hclust_t *clust, float min_inter_dist, float max_intra_dist)
312 {
313 node_t **dat = clust->rmme + clust->ndat;
314 int i, ndat = clust->nrmme - clust->ndat;
315
316 qsort(dat, ndat, sizeof(dat), cmp_nodes);
317
318 clust->str.l = 0;
319 float th, min_dev = HUGE_VAL;
320 int imin = -1;
321 for (i=0; i<ndat; i++)
322 {
323 float dev = 0;
324 if ( i>0 ) dev += calc_dev(dat,i);
325 if ( i+1<ndat ) dev += calc_dev(dat+i,ndat-i);
326 th = dat[i]->value;
327 ksprintf(&clust->str,"DEV\t%f\t%f\n",th,dev);
328 if ( min_dev > dev && th >= min_inter_dist ) { min_dev = dev; imin = i; }
329 }
330 if ( max_intra_dist > 0 )
331 th = max_intra_dist; // use fixed cutoff, the above was only for debugging output
332 else
333 {
334 // dynamic cutoff
335 max_intra_dist = fabs(max_intra_dist);
336 th = imin==-1 ? max_intra_dist : dat[imin]->value;
337 if ( th > max_intra_dist ) th = max_intra_dist;
338 }
339 ksprintf(&clust->str,"TH\t%f\n", th);
340 ksprintf(&clust->str,"MAX_DIST\t%f\n", dat[ndat-1]->value);
341 ksprintf(&clust->str,"MIN_INTER\t%f\n", min_inter_dist);
342 ksprintf(&clust->str,"MAX_INTRA\t%f\n", max_intra_dist);
343 return th;
344 }
345
346 cluster_t *hclust_create_list(hclust_t *clust, float min_inter_dist, float *max_intra_dist, int *nclust)
347 {
348 float cutoff = *max_intra_dist = hclust_set_threshold(clust, min_inter_dist, *max_intra_dist);
349
350 node_t **stack = (node_t**) malloc(sizeof(node_t*)*clust->ndat);
351 node_t **tmp = (node_t**) malloc(sizeof(node_t*)*clust->ndat);
352 stack[0] = clust->first;
353 int nstack = 1;
354
355 cluster_t *cluster = NULL;
356 int ncluster = 0;
357
358 if ( stack[0]->value < cutoff )
359 {
360 // all values are within the limits - create a single cluster
361 cluster = append_cluster(stack[0], cluster, &ncluster, tmp);
362 nstack = 0;
363 }
364
365 while ( nstack )
366 {
367 node_t *node = stack[--nstack];
368 node_t *akid = node->akid;
369 node_t *bkid = node->bkid;
370 if ( !akid )
371 {
372 cluster = append_cluster(node, cluster, &ncluster, tmp);
373 continue;
374 }
375
376 if ( node->value >= cutoff && akid->value < cutoff )
377 cluster = append_cluster(akid, cluster, &ncluster, tmp);
378 else
379 stack[nstack++] = akid;
380
381 if ( node->value >= cutoff && bkid->value < cutoff )
382 cluster = append_cluster(bkid, cluster, &ncluster, tmp);
383 else
384 stack[nstack++] = bkid;
385 }
386
387 free(tmp);
388 free(stack);
389
390 *nclust = ncluster;
391 return cluster;
392 }
393
394 void hclust_destroy_list(cluster_t *clust, int nclust)
395 {
396 int i;
397 for (i=0; i<nclust; i++) free(clust[i].memb);
398 free(clust);
399 }
400
401