Debian Codegraph @

bcftools/hclust.c.pysam.c

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