Debian Codegraph @

bcftools/vcfcnv.c

raw symbols SCIP
1 /* The MIT License
2
3 Copyright (c) 2014-2022 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 /*
28 Known issues:
29 - The --AF-file option behaves like --targets-file, sites not listed in the AFs
30 are skipped.
31 */
32
33 #include <stdio.h>
34 #include <unistd.h>
35 #include <assert.h>
36 #include <getopt.h>
37 #include <math.h>
38 #include <inttypes.h>
39 #include <htslib/vcf.h>
40 #include <htslib/synced_bcf_reader.h>
41 #include <htslib/kstring.h>
42 #include <htslib/kfunc.h>
43 #include <htslib/khash_str2int.h>
44 #include <htslib/hts_defs.h>
45 #include "bcftools.h"
46 #include "HMM.h"
47 #include "rbuf.h"
48
49 #define DBG0 0
50
51 #define N_STATES 4
52 #define CN0 0
53 #define CN1 1
54 #define CN2 2
55 #define CN3 3
56
57 typedef struct
58 {
59 float mean, dev2, norm;
60 }
61 gauss_param_t;
62
63 typedef struct
64 {
65 char *name;
66 int idx; // VCF sample index
67 float *lrr,*baf, baf_dev2, baf_dev2_dflt, lrr_dev2;
68 float cell_frac, cell_frac_dflt;
69 gauss_param_t gauss_param[18];
70 double pobs[N_STATES];
71 FILE *dat_fh, *cn_fh, *summary_fh;
72 char *dat_fname, *cn_fname, *summary_fname;
73 }
74 sample_t;
75
76 typedef struct _args_t
77 {
78 bcf_srs_t *files;
79 bcf_hdr_t *hdr;
80 int prev_rid, ntot, nused;
81 sample_t query_sample, control_sample;
82
83 int nstates; // number of states: N_STATES for one sample, N_STATES^2 for two samples
84 double lrr_bias, baf_bias; // LRR/BAF weights
85 double same_prob, ij_prob; // prior of both samples being the same and the transition probability P(i|j)
86 double err_prob; // constant probability of erroneous measurement
87 float *nonref_afs, nonref_af, nonref_af_dflt, fRR, fRA, fAA, *tmpf;
88 unsigned long int nRR, nRA, nAA;
89 int mtmpf;
90
91 double *tprob, *tprob_arr; // array of transition matrices, precalculated up to ntprob_arr positions
92 double *iprobs; // states' initial probabilities
93 int ntprob_arr;
94
95 hmm_t *hmm;
96 double *eprob; // emission probs [nstates*nsites,msites]
97 uint32_t *sites; // positions [nsites,msites]
98 int nsites, msites;
99
100 double baum_welch_th, optimize_frac;
101 float plot_th;
102 FILE *summary_fh;
103 char **argv, *regions_list, *summary_fname, *output_dir;
104 char *targets_list, *af_fname;
105 int argc, verbose, lrr_smooth_win;
106 }
107 args_t;
108
109 FILE *open_file(char **fname, const char *mode, const char *fmt, ...) HTS_FORMAT(HTS_PRINTF_FMT, 3, 4);
110
111 static inline void hmm2cn_state(int nstates, int i, int *a, int *b)
112 {
113 *a = i / N_STATES;
114 *b = i - (*a)*N_STATES;
115 }
116 static double *init_tprob_matrix(int ndim, double ij_prob, double same_prob)
117 {
118 int i,j;
119 double *mat = (double*) malloc(sizeof(double)*ndim*ndim);
120
121 assert( ndim==N_STATES || ndim==N_STATES*N_STATES);
122
123 if ( ndim==N_STATES ) // one sample
124 {
125 double pii = 1 - ij_prob*(N_STATES-1);
126 if ( pii < ij_prob ) error("Error: -x set a bit too high, P(x|x) < P(x|y): %e vs %e\n", pii,ij_prob);
127 for (j=0; j<ndim; j++)
128 {
129 double sum = 0;
130 for (i=0; i<ndim; i++)
131 {
132 // transition from j-th to i-th state
133 if ( i==j )
134 MAT(mat,ndim,i,j) = pii;
135 else
136 MAT(mat,ndim,i,j) = ij_prob;
137
138 sum += MAT(mat,ndim,i,j);
139 }
140 assert( fabs(sum - 1.0)<1e-15 );
141 }
142 }
143 else // two samples
144 {
145 // interpret ij_prob differently, as ii_prob in fact, so that for two
146 // samples the behaviour is somewhat closer to single sample calling
147 // with s=0.
148 double pii = 1 - ij_prob*(N_STATES-1);
149 ij_prob = (1 - pii) / (ndim - 1);
150 for (j=0; j<ndim; j++)
151 {
152 int ja,jb;
153 hmm2cn_state(ndim, j, &ja, &jb);
154
155 double sum = 0;
156 for (i=0; i<ndim; i++)
157 {
158 int ia,ib;
159 hmm2cn_state(ndim, i, &ia, &ib);
160
161 // transition from (ja,jb)-th to (ia,ib)-th state
162 double pa = ja==ia ? pii : ij_prob;
163 double pb = jb==ib ? pii : ij_prob;
164
165 if ( ia==ib && ja==jb )
166 MAT(mat,ndim,i,j) = pa*pb - pa*pb*same_prob + sqrt(pa*pb)*same_prob;
167 else if ( ia==ib )
168 MAT(mat,ndim,i,j) = pa*pb;
169 else
170 MAT(mat,ndim,i,j) = pa*pb*(1-same_prob);
171
172 sum += MAT(mat,ndim,i,j);
173 }
174 for (i=0; i<ndim; i++) MAT(mat,ndim,i,j) /= sum;
175 }
176 }
177 return mat;
178 }
179
180 static double *init_iprobs(int ndim, double same_prob)
181 {
182 int i;
183 double *probs = (double*) malloc(sizeof(double)*ndim);
184
185 assert( ndim==N_STATES || ndim==N_STATES*N_STATES);
186
187 if ( ndim==N_STATES )
188 {
189 // one sample: prior on CN2
190 for (i=0; i<ndim; i++)
191 probs[i] = i==CN2 ? 0.5 : 0.5/3;
192 }
193 else
194 {
195 // two samples
196 double norm = 0;
197 for (i=0; i<ndim; i++)
198 {
199 int ia,ib;
200 hmm2cn_state(ndim, i, &ia, &ib);
201
202 double pa = ia==CN2 ? 0.5 : 0.5/3;
203 double pb = ib==CN2 ? 0.5 : 0.5/3;
204
205 probs[i] = pa*pb;
206 if ( ia!=ib ) probs[i] *= 1-same_prob;
207
208 norm += probs[i];
209 }
210 for (i=0; i<ndim; i++) probs[i] /= norm;
211 }
212 return probs;
213 }
214
215 static void init_sample_files(sample_t *smpl, char *dir)
216 {
217 smpl->dat_fh = open_file(&smpl->dat_fname,"w","%s/dat.%s.tab",dir,smpl->name);
218 if ( !smpl->dat_fh ) error("Error opening file: %s/dat.%s.tab\n",dir,smpl->name);
219
220 smpl->cn_fh = open_file(&smpl->cn_fname,"w","%s/cn.%s.tab",dir,smpl->name);
221 if ( !smpl->cn_fh ) error("Error opening file: %s/cn.%s.tab\n",dir,smpl->name);
222
223 smpl->summary_fh = open_file(&smpl->summary_fname,"w","%s/summary.%s.tab",dir,smpl->name);
224 if ( !smpl->summary_fh ) error("Error opening file: %s/summary.%s.tab\n",dir,smpl->name);
225
226 fprintf(smpl->dat_fh,"# [1]Chromosome\t[2]Position\t[3]BAF\t[4]LRR\n");
227 fprintf(smpl->cn_fh,"# [1]Chromosome\t[2]Position\t[3]CN\t[4]P(CN0)\t[5]P(CN1)\t[6]P(CN2)\t[7]P(CN3)\n");
228 fprintf(smpl->summary_fh,"# RG, Regions [2]Chromosome\t[3]Start\t[4]End\t[5]Copy Number state\t[6]Quality\t[7]nSites\t[8]nHETs\n");
229 }
230 static void close_sample_files(sample_t *smpl)
231 {
232 if ( fclose(smpl->dat_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,smpl->dat_fname);
233 if ( fclose(smpl->cn_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,smpl->cn_fname);
234 if ( fclose(smpl->summary_fh)!=0 ) error("[%s] Error: close failed .. %s\n", __func__,smpl->summary_fname);
235 }
236
237 static double norm_cdf(double mean, double dev);
238 static void init_data(args_t *args)
239 {
240 args->prev_rid = -1;
241 args->hdr = args->files->readers[0].header;
242
243 if ( !args->query_sample.name )
244 {
245 if ( bcf_hdr_nsamples(args->hdr)>1 ) error("Multi-sample VCF, missing the -s option\n");
246 args->query_sample.name = strdup(args->hdr->samples[0]);
247 }
248 else
249 if ( bcf_hdr_id2int(args->hdr,BCF_DT_SAMPLE,args->query_sample.name)<0 ) error("The sample \"%s\" not found\n", args->query_sample.name);
250 if ( !args->files->readers[0].file->is_bin )
251 {
252 int ret;
253 kstring_t tmp = {0,0,0};
254 if ( args->control_sample.name )
255 {
256 ksprintf(&tmp, "%s,%s", args->query_sample.name,args->control_sample.name);
257 ret = bcf_hdr_set_samples(args->hdr, tmp.s, 0);
258 }
259 else
260 {
261 ret = bcf_hdr_set_samples(args->hdr, args->query_sample.name, 0);
262 tmp.s = args->query_sample.name;
263 }
264 if ( ret<0 ) error("Error parsing the list of samples: %s\n", tmp.s);
265 else if ( ret>0 ) error("The sample not found in the VCF: %s\n", ret==1 ? args->query_sample.name : args->control_sample.name);
266
267 if ( args->control_sample.name ) free(tmp.s);
268 }
269 args->query_sample.idx = bcf_hdr_id2int(args->hdr,BCF_DT_SAMPLE,args->query_sample.name);
270 args->control_sample.idx = args->control_sample.name ? bcf_hdr_id2int(args->hdr,BCF_DT_SAMPLE,args->control_sample.name) : -1;
271 args->nstates = args->control_sample.name ? N_STATES*N_STATES : N_STATES;
272 args->tprob = init_tprob_matrix(args->nstates, args->ij_prob, args->same_prob);
273 args->iprobs = init_iprobs(args->nstates, args->same_prob);
274 args->hmm = hmm_init(args->nstates, args->tprob, 10000);
275 hmm_init_states(args->hmm, args->iprobs);
276
277 args->summary_fh = stdout;
278 init_sample_files(&args->query_sample, args->output_dir);
279 if ( args->control_sample.name )
280 {
281 init_sample_files(&args->control_sample, args->output_dir);
282 args->summary_fh = open_file(&args->summary_fname,"w","%s/summary.tab",args->output_dir);
283 }
284 else
285 args->summary_fh = NULL; // one sample only, no two-file summary
286
287
288 int i;
289 FILE *fh = args->summary_fh ? args->summary_fh : args->query_sample.summary_fh;
290
291 fprintf(fh, "# This file was produced by: bcftools cnv(%s+htslib-%s)\n", bcftools_version(),hts_version());
292 fprintf(fh, "# The command line was:\tbcftools %s", args->argv[0]);
293 for (i=1; i<args->argc; i++) fprintf(fh, " %s",args->argv[i]);
294 if ( args->control_sample.name )
295 fprintf(fh, "\n#\n"
296 "# RG, Regions\t[2]Chromosome\t[3]Start\t[4]End\t[5]Copy number:%s\t[6]Copy number:%s\t[7]Quality"
297 "\t[8]nSites in (5)\t[9]nHETs in (5)\t[10]nSites in (6)\t[11]nHETs in(6)\n",
298 args->query_sample.name,args->control_sample.name
299 );
300 else
301 fprintf(fh, "\n#\n"
302 "# RG, Regions\t[2]Chromosome\t[3]Start\t[4]End\t[5]Copy number:%s\t[6]Quality\t[7]nSites\t[8]nHETs\n",
303 args->query_sample.name
304 );
305 if ( args->optimize_frac )
306 {
307 fprintf(args->query_sample.summary_fh, "# CF, cell fraction estimate\t[2]Chromosome\t[3]Start\t[4]End\t[5]Cell fraction\t[6]BAF deviation\n");
308 if ( args->control_sample.name )
309 {
310 fprintf(args->control_sample.summary_fh, "# CF, cell fraction estimate\t[2]Chromosome\t[3]Start\t[4]End\t[5]Cell fraction\t[6]BAF deviation\n");
311 fprintf(args->summary_fh, "# CF, cell fraction estimate\t[2]Chromosome\t[3]Start\t[4]End\t"
312 "[5]Cell fraction:%s\t[6]Cell fraction:%s\t[7]BAF deviation:%s\t[8]BAF deviation:%s\n",
313 args->query_sample.name,args->control_sample.name,
314 args->query_sample.name,args->control_sample.name
315 );
316 }
317 }
318 }
319
320 char *msprintf(const char *fmt, ...);
321 static void py_plot_cnv(char *script, float th)
322 {
323 if ( th>100 ) return; // create no plots
324
325 char *cmd = msprintf("python %s -p %f", script, th);
326 int ret = system(cmd);
327 if ( ret) fprintf(stderr, "The command returned non-zero status %d: %s\n", ret, cmd);
328 free(cmd);
329 }
330
331 static void plot_sample(args_t *args, sample_t *smpl)
332 {
333 char *fname;
334 FILE *fp = open_file(&fname,"w","%s/plot.%s.py",args->output_dir,smpl->name);
335 fprintf(fp,
336 "import matplotlib as mpl\n"
337 "mpl.use('Agg')\n"
338 "import matplotlib.pyplot as plt\n"
339 "import csv\n"
340 "import numpy as np\n"
341 "csv.register_dialect('tab', delimiter='\\t', quoting=csv.QUOTE_NONE)\n"
342 "\n"
343 "dat = {}\n"
344 "with open('%s', 'r') as f:\n"
345 " reader = csv.reader(f, 'tab')\n"
346 " for row in reader:\n"
347 " chr = row[0]\n"
348 " if chr[0]=='#': continue\n"
349 " if chr not in dat: dat[chr] = []\n"
350 " dat[chr].append([int(row[1]), float(row[2]), float(row[3])])\n"
351 "\n"
352 "cnv = {}\n"
353 "with open('%s', 'r') as f:\n"
354 " reader = csv.reader(f, 'tab')\n"
355 " for row in reader:\n"
356 " chr = row[0]\n"
357 " if chr[0]=='#': continue\n"
358 " if chr not in cnv: cnv[chr] = []\n"
359 " row[2] = int(row[2]) + 0.5\n"
360 " row[1] = int(row[1])\n"
361 " cnv[chr].append(row[1:])\n"
362 "\n"
363 "for chr in dat:\n"
364 " fig,(ax1, ax2, ax3) = plt.subplots(3,1,figsize=(10,8),sharex=True)\n"
365 " ax1.plot([x[0] for x in dat[chr]],[x[2] for x in dat[chr]], '.', ms=3)\n"
366 " ax2.plot([x[0] for x in dat[chr]],[x[1] for x in dat[chr]], '.', ms=3)\n"
367 " cn_dat = cnv[chr]\n"
368 " xgrid = [float(x[0]) for x in cn_dat]\n"
369 " ygrid = np.linspace(0,5,6)\n"
370 " xgrid, ygrid = np.meshgrid(xgrid, ygrid)\n"
371 " heat = np.zeros_like(xgrid)\n"
372 " for x in range(len(heat[0])-1):\n"
373 " heat[0][x] = cn_dat[x][2]\n"
374 " heat[1][x] = cn_dat[x][3]\n"
375 " heat[2][x] = cn_dat[x][4]\n"
376 " heat[3][x] = cn_dat[x][5]\n"
377 " mesh = ax3.pcolormesh(xgrid, ygrid, heat, cmap='bwr_r', shading='auto', alpha=0)\n"
378 " mesh.set_clim(vmin=-1,vmax=1)\n"
379 " ax3.plot([x[0] for x in cn_dat],[x[1] for x in cn_dat],'.-',ms=3,color='black')\n"
380 " fig.suptitle('%s (chr '+chr+')')\n"
381 " ax1.set_title('Log-R intensities Ratio',fontsize=10)\n"
382 " ax2.set_title('B-Allele Frequency',fontsize=10)\n"
383 " ax3.set_title('Copy Number Variation',fontsize=10)\n"
384 " ax1.set_ylabel('LRR')\n"
385 " ax2.set_ylabel('BAF')\n"
386 " ax3.set_ylabel('CN')\n"
387 " ax3.set_xlabel('Coordinate (chrom '+chr+')',fontsize=10)\n"
388 " ax3.set_ylim(-0.1,4.1)\n"
389 " ax3.set_yticks([0.5,1.5,2.5,3.5])\n"
390 " ax3.set_yticklabels(['CN0','CN1','CN2','CN3'])\n"
391 " plt.subplots_adjust(left=0.08,right=0.95,bottom=0.08,top=0.92)\n"
392 " plt.savefig('%s/plot.%s.chr'+chr+'.png')\n"
393 " plt.close()\n"
394 "\n",
395 smpl->dat_fname,smpl->cn_fname,smpl->name,args->output_dir,smpl->name
396 );
397 fclose(fp);
398
399 py_plot_cnv(fname, args->plot_th);
400 free(fname);
401 }
402
403 static void create_plots(args_t *args)
404 {
405 close_sample_files(&args->query_sample);
406 if ( args->control_sample.name ) close_sample_files(&args->control_sample);
407 if ( args->summary_fh ) fclose(args->summary_fh);
408
409 if ( !args->control_sample.name )
410 {
411 plot_sample(args, &args->query_sample);
412 return;
413 }
414
415 char *fname;
416 FILE *fp = open_file(&fname,"w","%s/plot.%s.%s.py",args->output_dir,args->control_sample.name,args->query_sample.name);
417 fprintf(fp,
418 "import matplotlib as mpl\n"
419 "mpl.use('Agg')\n"
420 "import matplotlib.pyplot as plt\n"
421 "import csv,argparse\n"
422 "import numpy as np\n"
423 "csv.register_dialect('tab', delimiter='\\t', quoting=csv.QUOTE_NONE)\n"
424 "\n"
425 "control_sample = '%s'\n"
426 "query_sample = '%s'\n"
427 "\n"
428 "parser = argparse.ArgumentParser()\n"
429 "parser.add_argument('-p', '--plot-threshold', type=float)\n"
430 "parser.add_argument('-c', '--chromosome')\n"
431 "args = parser.parse_args()\n"
432 "if args.plot_threshold==None: args.plot_threshold = 0\n"
433 "\n"
434 "def chroms_to_plot(th):\n"
435 " dat = {}\n"
436 " with open('%s/summary.tab', 'r') as f:\n"
437 " reader = csv.reader(f, 'tab')\n"
438 " for row in reader:\n"
439 " if row[0]!='RG': continue\n"
440 " chr = row[1]\n"
441 " start = row[2]\n"
442 " end = row[3]\n"
443 " qual = float(row[6])\n"
444 " if row[4]==row[5] and args.plot_threshold!=0: continue\n"
445 " if chr not in dat: dat[chr] = 0.0\n"
446 " if qual > dat[chr]: dat[chr] = qual\n"
447 " out = {}\n"
448 " for chr in dat:\n"
449 " if (chr not in dat) or dat[chr]<th: continue\n"
450 " out[chr] = 1\n"
451 " return out\n"
452 "if args.chromosome!=None:\n"
453 " plot_chroms = { args.chromosome:1 }\n"
454 "else:\n"
455 " plot_chroms = chroms_to_plot(args.plot_threshold)\n"
456 "\n"
457 "def read_dat(file,dat,plot_chr):\n"
458 " with open(file, 'r') as f:\n"
459 " reader = csv.reader(f, 'tab')\n"
460 " for row in reader:\n"
461 " chr = row[0]\n"
462 " if chr != plot_chr: continue\n"
463 " dat.append([int(row[1]), float(row[2]), float(row[3])])\n"
464 "def read_cnv(file,cnv,plot_chr):\n"
465 " with open(file, 'r') as f:\n"
466 " reader = csv.reader(f, 'tab')\n"
467 " for row in reader:\n"
468 " chr = row[0]\n"
469 " if chr != plot_chr: continue\n"
470 " row[2] = int(row[2]) + 0.5\n"
471 " row[1] = int(row[1])\n"
472 " cnv.append(row[1:])\n"
473 "def find_diffs(a,b):\n"
474 " out = []\n"
475 " diff = []\n"
476 " for i in range(len(a)):\n"
477 " if a[i][1]!=b[i][1]:\n"
478 " if i>0: diff.append([b[i-1][0],b[i-1][1],a[i-1][1]])\n"
479 " diff.append([b[i][0],b[i][1],a[i][1]])\n"
480 " elif len(diff):\n"
481 " diff.append([b[i][0],b[i][1],a[i][1]])\n"
482 " out.append(diff)\n"
483 " diff = []\n"
484 " if len(diff): out.append(diff)\n"
485 " return out\n"
486 "\n"
487 "for chr in sorted(plot_chroms.keys()):\n"
488 " control_dat = []\n"
489 " control_cnv = []\n"
490 " query_dat = []\n"
491 " query_cnv = []\n"
492 " read_dat('%s',control_dat,chr)\n"
493 " read_dat('%s',query_dat,chr)\n"
494 " read_cnv('%s',control_cnv,chr)\n"
495 " read_cnv('%s',query_cnv,chr)\n"
496 "\n"
497 " fig,(ax1,ax2,ax3,ax4,ax5,ax6) = plt.subplots(6,1,figsize=(10,8),sharex=True)\n"
498 " ax1.plot([x[0] for x in control_dat],[x[2] for x in control_dat], '.', ms=3,color='red')\n"
499 " ax2.plot([x[0] for x in control_dat],[x[1] for x in control_dat], '.', ms=3,color='red')\n"
500 " cn_dat = control_cnv\n"
501 " xgrid = [float(x[0]) for x in cn_dat]\n"
502 " ygrid = np.linspace(0,5,6)\n"
503 " xgrid, ygrid = np.meshgrid(xgrid, ygrid)\n"
504 " heat = np.zeros_like(xgrid)\n"
505 " for x in range(len(heat[0])-1):\n"
506 " heat[0][x] = cn_dat[x][2]\n"
507 " heat[1][x] = cn_dat[x][3]\n"
508 " heat[2][x] = cn_dat[x][4]\n"
509 " heat[3][x] = cn_dat[x][5]\n"
510 " mesh = ax3.pcolormesh(xgrid, ygrid, heat, cmap='bwr', shading='auto', alpha=0)\n"
511 " mesh.set_clim(vmin=-1,vmax=1)\n"
512 " ax3.plot([x[0] for x in cn_dat],[x[1] for x in cn_dat],'-',ms=3,color='black',lw=1.7)\n"
513 "\n"
514 " ax6.plot([x[0] for x in query_dat],[x[2] for x in query_dat], '.', ms=3)\n"
515 " ax5.plot([x[0] for x in query_dat],[x[1] for x in query_dat], '.', ms=3)\n"
516 " cn_dat = query_cnv\n"
517 " xgrid = [float(x[0]) for x in cn_dat]\n"
518 " ygrid = np.linspace(0,5,6)\n"
519 " xgrid, ygrid = np.meshgrid(xgrid, ygrid)\n"
520 " heat = np.zeros_like(xgrid)\n"
521 " for x in range(len(heat[0])-1):\n"
522 " heat[0][x] = cn_dat[x][2]\n"
523 " heat[1][x] = cn_dat[x][3]\n"
524 " heat[2][x] = cn_dat[x][4]\n"
525 " heat[3][x] = cn_dat[x][5]\n"
526 " mesh = ax4.pcolormesh(xgrid, ygrid, heat, cmap='bwr_r')\n"
527 " mesh.set_clim(vmin=-1,vmax=1)\n"
528 " ax4.plot([x[0] for x in cn_dat],[x[1] for x in cn_dat],'-',ms=3,color='black',lw=1.7)\n"
529 " ax3.annotate(control_sample, xy=(0.02,0.1), xycoords='axes fraction', color='red',fontsize=12, va='bottom',ha='left')\n"
530 " ax4.annotate(query_sample, xy=(0.02,0.9), xycoords='axes fraction', color='blue',fontsize=12, va='top',ha='left')\n"
531 "\n"
532 " diffs = find_diffs(control_cnv,query_cnv)\n"
533 " for diff in diffs:\n"
534 " ax3.plot([x[0] for x in diff],[x[1] for x in diff],'-',ms=3,color='blue',lw=1.7)\n"
535 " ax4.plot([x[0] for x in diff],[x[2] for x in diff],'-',ms=3,color='red',lw=1.7)\n"
536 "\n"
537 " fig.suptitle('chr '+chr+', '+control_sample+' vs '+query_sample)\n"
538 " ax1.tick_params(axis='both', labelsize=8)\n"
539 " ax2.tick_params(axis='both', labelsize=8)\n"
540 " ax3.tick_params(axis='both', labelsize=8)\n"
541 " ax4.tick_params(axis='both', labelsize=8)\n"
542 " ax5.tick_params(axis='both', labelsize=8)\n"
543 " ax6.tick_params(axis='both', labelsize=8)\n"
544 " ax6.set_xlabel('Coordinate (chrom '+chr+')',fontsize=8)\n"
545 " ax1.set_ylabel('LRR')\n"
546 " ax2.set_ylabel('BAF')\n"
547 " ax3.set_ylabel('CN')\n"
548 " ax6.set_ylabel('LRR')\n"
549 " ax5.set_ylabel('BAF')\n"
550 " ax4.set_ylabel('CN')\n"
551 " ax3.set_ylim(-0.1,4.1)\n"
552 " ax3.set_yticks([0.5,1.5,2.5,3.5])\n"
553 " ax3.set_yticklabels(['CN0','CN1','CN2','CN3'])\n"
554 " ax4.set_ylim(-0.1,4.1)\n"
555 " ax4.set_yticks([0.5,1.5,2.5,3.5])\n"
556 " ax4.set_yticklabels(['CN0','CN1','CN2','CN3'])\n"
557 " plt.subplots_adjust(left=0.08,right=0.95,bottom=0.08,top=0.92,hspace=0)\n"
558 " plt.savefig('%s/plot.%s.%s.chr'+chr+'.png')\n"
559 " plt.close()\n"
560 "\n",
561 args->control_sample.name,args->query_sample.name,
562 args->output_dir,
563 args->control_sample.dat_fname,args->query_sample.dat_fname,
564 args->control_sample.cn_fname,args->query_sample.cn_fname,
565 args->output_dir,args->control_sample.name,args->query_sample.name
566 );
567 fclose(fp);
568
569 py_plot_cnv(fname,args->plot_th);
570 free(fname);
571 }
572
573 static void destroy_data(args_t *args)
574 {
575 bcf_sr_destroy(args->files);
576 hmm_destroy(args->hmm);
577 free(args->tmpf);
578 free(args->sites);
579 free(args->eprob);
580 free(args->tprob);
581 free(args->iprobs);
582 free(args->summary_fname);
583 free(args->nonref_afs);
584 free(args->query_sample.baf);
585 free(args->query_sample.lrr);
586 free(args->control_sample.baf);
587 free(args->control_sample.lrr);
588 free(args->query_sample.name);
589 free(args->query_sample.dat_fname);
590 free(args->query_sample.cn_fname);
591 free(args->query_sample.summary_fname);
592 free(args->control_sample.dat_fname);
593 free(args->control_sample.cn_fname);
594 free(args->control_sample.summary_fname);
595 }
596
597 static inline char copy_number_state(args_t *args, int istate, int ismpl)
598 {
599 char code[] = "01234";
600 if ( !args->control_sample.name ) return code[istate];
601 int idx = ismpl ? istate - (istate/N_STATES)*N_STATES : istate/N_STATES;
602 return code[idx];
603 }
604
605 static double avg_ii_prob(int n, double *mat)
606 {
607 int i;
608 double avg = 0;
609 for (i=0; i<n; i++) avg += MAT(mat,n,i,i);
610 return avg/n;
611 }
612
613 #define GAUSS_CN1_PK_R(smpl) (&((smpl)->gauss_param[0]))
614 #define GAUSS_CN1_PK_A(smpl) (&((smpl)->gauss_param[1]))
615 #define GAUSS_CN2_PK_RR(smpl) (&((smpl)->gauss_param[2]))
616 #define GAUSS_CN2_PK_RA(smpl) (&((smpl)->gauss_param[3]))
617 #define GAUSS_CN2_PK_AA(smpl) (&((smpl)->gauss_param[4]))
618 #define GAUSS_CN3_PK_RRR(smpl) (&((smpl)->gauss_param[5]))
619 #define GAUSS_CN3_PK_RRA(smpl) (&((smpl)->gauss_param[6]))
620 #define GAUSS_CN3_PK_RAA(smpl) (&((smpl)->gauss_param[7]))
621 #define GAUSS_CN3_PK_AAA(smpl) (&((smpl)->gauss_param[8]))
622
623 static inline double norm_prob(double baf, gauss_param_t *param)
624 {
625 return exp(-(baf-param->mean)*(baf-param->mean)*0.5/param->dev2) / param->norm / sqrt(2*M_PI*param->dev2);
626 }
627
628 static int set_observed_prob(args_t *args, sample_t *smpl, int isite)
629 {
630 float baf = smpl->baf[isite];
631 float lrr = args->lrr_bias>0 ? smpl->lrr[isite] : 0;
632
633 float fRR = args->fRR;
634 float fRA = args->fRA;
635 float fAA = args->fAA;
636
637 if ( baf<0 )
638 {
639 // no call: either some technical issue or the call could not be made because it is CN0
640 int i;
641 smpl->pobs[CN0] = 0.5;
642 for (i=1; i<N_STATES; i++) smpl->pobs[i] = (1.0-smpl->pobs[CN0])/(N_STATES-1);
643 return 0;
644 }
645
646 double cn1_baf =
647 norm_prob(baf,GAUSS_CN1_PK_R(smpl)) * (fRR + fRA*0.5) +
648 norm_prob(baf,GAUSS_CN1_PK_A(smpl)) * (fAA + fRA*0.5) ;
649 double cn2_baf =
650 norm_prob(baf,GAUSS_CN2_PK_RR(smpl)) * fRR +
651 norm_prob(baf,GAUSS_CN2_PK_RA(smpl)) * fRA +
652 norm_prob(baf,GAUSS_CN2_PK_AA(smpl)) * fAA;
653 double cn3_baf =
654 norm_prob(baf,GAUSS_CN3_PK_RRR(smpl)) * fRR +
655 norm_prob(baf,GAUSS_CN3_PK_RRA(smpl)) * fRA*0.5 +
656 norm_prob(baf,GAUSS_CN3_PK_RAA(smpl)) * fRA*0.5 +
657 norm_prob(baf,GAUSS_CN3_PK_AAA(smpl)) * fAA;
658
659 double norm = cn1_baf + cn2_baf + cn3_baf;
660 cn1_baf /= norm;
661 cn2_baf /= norm;
662 cn3_baf /= norm;
663
664 #if DBG0
665 if ( args->verbose ) fprintf(stderr,"%f\t%f %f %f\n", baf,cn1_baf,cn2_baf,cn3_baf);
666 #endif
667
668 double cn1_lrr = exp(-(lrr + 0.45)*(lrr + 0.45)/smpl->lrr_dev2);
669 double cn2_lrr = exp(-(lrr - 0.00)*(lrr - 0.00)/smpl->lrr_dev2);
670 double cn3_lrr = exp(-(lrr - 0.30)*(lrr - 0.30)/smpl->lrr_dev2);
671
672 smpl->pobs[CN0] = 0;
673 smpl->pobs[CN1] = args->err_prob + (1 - args->baf_bias + args->baf_bias*cn1_baf)*(1 - args->lrr_bias + args->lrr_bias*cn1_lrr);
674 smpl->pobs[CN2] = args->err_prob + (1 - args->baf_bias + args->baf_bias*cn2_baf)*(1 - args->lrr_bias + args->lrr_bias*cn2_lrr);
675 smpl->pobs[CN3] = args->err_prob + (1 - args->baf_bias + args->baf_bias*cn3_baf)*(1 - args->lrr_bias + args->lrr_bias*cn3_lrr);
676
677 return 0;
678 }
679
680 static void set_emission_prob(args_t *args, int isite)
681 {
682 double *eprob = &args->eprob[args->nstates*isite];
683 int i;
684 for (i=0; i<N_STATES; i++)
685 eprob[i] = args->query_sample.pobs[i];
686 }
687
688 static void set_emission_prob2(args_t *args, int isite)
689 {
690 double *eprob = &args->eprob[args->nstates*isite];
691 int i, j;
692 for (i=0; i<N_STATES; i++)
693 {
694 for (j=0; j<N_STATES; j++)
695 {
696 eprob[i*N_STATES+j] = args->query_sample.pobs[i]*args->control_sample.pobs[j];
697 }
698 }
699 }
700
701 static void set_gauss_params(args_t *args, sample_t *smpl);
702 static double norm_cdf(double mean, double dev)
703 {
704 double bot = 0, top = 1;
705 top = 1 - 0.5*erfc((top-mean)/(dev*sqrt(2)));
706 bot = 1 - 0.5*erfc((bot-mean)/(dev*sqrt(2)));
707 return top-bot;
708 }
709
710 static void set_emission_probs(args_t *args)
711 {
712 if ( !args->af_fname )
713 {
714 args->fRR = 0.76;
715 args->fRA = 0.14;
716 args->fAA = 0.098;
717 }
718
719 set_gauss_params(args, &args->query_sample);
720 if ( args->control_sample.name ) set_gauss_params(args, &args->control_sample);
721
722 #if DBG0
723 args->verbose = 1;
724 args->query_sample.baf[0] = 0; set_observed_prob(args,&args->query_sample,0);
725 args->query_sample.baf[0] = 1/3.; set_observed_prob(args,&args->query_sample,0);
726 args->query_sample.baf[0] = 1/2.; set_observed_prob(args,&args->query_sample,0);
727 args->query_sample.baf[0] = 2/3.; set_observed_prob(args,&args->query_sample,0);
728 args->query_sample.baf[0] = 1; set_observed_prob(args,&args->query_sample,0);
729 args->verbose = 0;
730 #endif
731
732 int i;
733 for (i=0; i<args->nsites; i++)
734 {
735 if ( args->af_fname )
736 {
737 args->fRR = (1-args->nonref_afs[i])*(1-args->nonref_afs[i]);
738 args->fRA = 2*args->nonref_afs[i]*(1-args->nonref_afs[i]);
739 args->fAA = args->nonref_afs[i]*args->nonref_afs[i];
740 }
741 set_observed_prob(args,&args->query_sample,i);
742 if ( args->control_sample.name )
743 {
744 set_observed_prob(args,&args->control_sample,i);
745 set_emission_prob2(args,i);
746 }
747 else
748 set_emission_prob(args,i);
749 }
750 }
751
752 static void smooth_data(float *dat, int ndat, int win)
753 {
754 if ( win<=1 ) return;
755
756 int i,j, k1 = win/2, k2 = win-k1;
757 rbuf_t rbuf;
758 rbuf_init(&rbuf,win);
759 float sum = 0, *buf = (float*)malloc(sizeof(float)*win);
760 for (i=0; i<k2; i++)
761 {
762 sum += dat[i];
763 int j = rbuf_append(&rbuf);
764 buf[j] = dat[i];
765 }
766 for (i=0; i<ndat; i++)
767 {
768 dat[i] = sum/rbuf.n;
769 if ( i>=k1 )
770 {
771 j = rbuf_shift(&rbuf);
772 sum -= buf[j];
773 }
774 if ( i+k2<ndat )
775 {
776 sum += dat[i+k2];
777 j = rbuf_append(&rbuf);
778 buf[j] = dat[i+k2];
779 }
780 }
781 free(buf);
782 }
783
784 static void set_gauss_params(args_t *args, sample_t *smpl)
785 {
786 int i;
787 for (i=0; i<18; i++) smpl->gauss_param[i].dev2 = smpl->baf_dev2;
788
789 double dev = sqrt(smpl->baf_dev2);
790
791 GAUSS_CN1_PK_R(smpl)->mean = 0;
792 GAUSS_CN1_PK_A(smpl)->mean = 1;
793 GAUSS_CN1_PK_R(smpl)->norm = norm_cdf(GAUSS_CN1_PK_R(smpl)->mean,dev);
794 GAUSS_CN1_PK_A(smpl)->norm = norm_cdf(GAUSS_CN1_PK_A(smpl)->mean,dev);
795
796 GAUSS_CN2_PK_RR(smpl)->mean = 0;
797 GAUSS_CN2_PK_RA(smpl)->mean = 0.5;
798 GAUSS_CN2_PK_AA(smpl)->mean = 1;
799 GAUSS_CN2_PK_RR(smpl)->norm = norm_cdf(GAUSS_CN2_PK_RR(smpl)->mean,dev);
800 GAUSS_CN2_PK_RA(smpl)->norm = norm_cdf(GAUSS_CN2_PK_RA(smpl)->mean,dev);
801 GAUSS_CN2_PK_AA(smpl)->norm = norm_cdf(GAUSS_CN2_PK_AA(smpl)->mean,dev);
802
803 GAUSS_CN3_PK_RRR(smpl)->mean = 0;
804 GAUSS_CN3_PK_RRA(smpl)->mean = 1.0/(2+smpl->cell_frac);
805 GAUSS_CN3_PK_RAA(smpl)->mean = (1.0+smpl->cell_frac)/(2+smpl->cell_frac);
806 GAUSS_CN3_PK_AAA(smpl)->mean = 1;
807 GAUSS_CN3_PK_RRR(smpl)->norm = norm_cdf(GAUSS_CN3_PK_RRR(smpl)->mean,dev);
808 GAUSS_CN3_PK_RRA(smpl)->norm = norm_cdf(GAUSS_CN3_PK_RRA(smpl)->mean,dev);
809 GAUSS_CN3_PK_RAA(smpl)->norm = norm_cdf(GAUSS_CN3_PK_RAA(smpl)->mean,dev);
810 GAUSS_CN3_PK_AAA(smpl)->norm = norm_cdf(GAUSS_CN3_PK_AAA(smpl)->mean,dev);
811 }
812
813 static int update_sample_args(args_t *args, sample_t *smpl, int ismpl)
814 {
815 hmm_t *hmm = args->hmm;
816 double *fwd = hmm_get_fwd_bwd_prob(hmm);
817 int nstates = hmm_get_nstates(hmm);
818
819 // estimate the BAF mean and deviation for CN3
820 double mean_cn3 = 0, norm_cn3 = 0;
821 double baf_dev2 = 0, baf_AA_dev2 = 0, norm_baf_AA_dev2 = 0;
822
823 // experimental: smooth CN3 probs to bias toward bigger events, this lowers
824 // the FP rate when the data is noisy
825 hts_expand(float,args->nsites,args->mtmpf,args->tmpf);
826 int i, j, k = 0;
827 for (i=0; i<args->nsites; i++)
828 {
829 float baf = smpl->baf[i];
830 if ( baf>4/5.) continue; // skip AA genotypes
831 if ( baf>0.5 ) baf = 1 - baf; // the bands should be symmetric
832 if ( baf<1/5.) continue; // skip RR genotypes
833
834 double prob_cn3 = 0, *probs = fwd + i*nstates;
835 if ( !args->control_sample.name )
836 {
837 prob_cn3 = probs[CN3];
838 }
839 else if ( ismpl==0 )
840 {
841 // query sample: CN3 probability must be recovered from all states of the control sample
842 for (j=0; j<N_STATES; j++) prob_cn3 += probs[CN3*N_STATES+j];
843 }
844 else
845 {
846 // same as above but for control sample
847 for (j=0; j<N_STATES; j++) prob_cn3 += probs[CN3+j*N_STATES];
848 }
849 args->tmpf[k++] = prob_cn3;
850 }
851 smooth_data(args->tmpf, k, 50);
852 k = 0;
853 for (i=0; i<args->nsites; i++)
854 {
855 float baf = smpl->baf[i];
856 if ( baf>4/5.) { baf_AA_dev2 += (1.0-baf)*(1.0-baf); norm_baf_AA_dev2++; continue; } // skip AA genotypes
857 if ( baf>0.5 ) baf = 1 - baf; // the bands should be symmetric
858 if ( baf<1/5.) continue; // skip RR genotypes
859
860 double prob_cn3 = args->tmpf[k++];
861 mean_cn3 += prob_cn3 * baf;
862 norm_cn3 += prob_cn3;
863 }
864 if ( !norm_cn3 )
865 {
866 smpl->cell_frac = 1.0;
867 return 1;
868 }
869 mean_cn3 /= norm_cn3;
870 k = 0;
871 for (i=0; i<args->nsites; i++)
872 {
873 float baf = smpl->baf[i];
874 if ( baf>0.5 ) baf = 1 - baf; // the bands should be symmetric
875 if ( baf<1/5.) continue; // skip RR,AA genotypes
876
877 double prob_cn3 = args->tmpf[k++];
878 baf_dev2 += prob_cn3 * (baf - mean_cn3)*(baf - mean_cn3);
879 }
880
881 /*
882 A noisy CN2 band is hard to distinguish from two CN3 bands which are
883 close to each other. Set a threshold on the minimum separation based
884 on the BAF deviation at p=0.95
885 */
886 baf_dev2 /= norm_cn3;
887 baf_AA_dev2 /= norm_baf_AA_dev2;
888 if ( baf_dev2 < baf_AA_dev2 ) baf_dev2 = baf_AA_dev2;
889 double max_mean_cn3 = 0.5 - sqrt(baf_dev2)*1.644854; // R: qnorm(0.95)=1.644854
890 //fprintf(stderr,"dev=%f AA_dev=%f max_mean_cn3=%f mean_cn3=%f\n", baf_dev2,baf_AA_dev2,max_mean_cn3,mean_cn3);
891 assert( max_mean_cn3>0 );
892
893 double new_frac = 1./mean_cn3 - 2;
894 if ( mean_cn3 > max_mean_cn3 || new_frac < args->optimize_frac )
895 {
896 // out of bounds, beyond our detection limits. Give up and say it converged
897 smpl->cell_frac = 1.0;
898 return 1;
899 }
900 if ( new_frac>1 ) new_frac = 1;
901 int converged = fabs(new_frac - smpl->cell_frac) < 1e-1 ? 1 : 0;
902
903 // Update dev2, but stay within safe limits
904 if ( baf_dev2 > 3*smpl->baf_dev2_dflt ) baf_dev2 = 3*smpl->baf_dev2_dflt;
905 else if ( baf_dev2 < 0.5*smpl->baf_dev2_dflt ) baf_dev2 = 0.5*smpl->baf_dev2_dflt;
906
907 smpl->cell_frac = new_frac;
908 smpl->baf_dev2 = baf_dev2;
909
910 return converged;
911 }
912
913 // Update parameters which depend on the estimated fraction of aberrant cells
914 // in CN3. Returns 0 if the current estimate did not need to be updated or 1
915 // if there was a change.
916 static int update_args(args_t *args)
917 {
918 int converged = update_sample_args(args, &args->query_sample, 0);
919 if ( args->control_sample.name )
920 {
921 converged += update_sample_args(args, &args->control_sample, 1);
922 return converged==2 ? 0 : 1;
923 }
924 return converged ? 0 : 1;
925 }
926
927 // for an approximate estimate of the number of het genotypes in a region
928 #define BAF_LIKELY_HET(val) (val)>0.25 && (val)<0.75
929
930 static void cnv_flush_viterbi(args_t *args)
931 {
932 if ( !args->nsites ) return;
933
934 // Set HMM transition matrix for the new chromsome again. This is for case
935 // Baum-Welch was used, which is experimental, largerly unsupported and not
936 // done by default.
937 hmm_t *hmm = args->hmm;
938 hmm_set_tprob(args->hmm, args->tprob, 10000);
939
940 // Smooth LRR values to reduce noise
941 if ( args->lrr_bias > 0 )
942 {
943 smooth_data(args->query_sample.lrr,args->nsites, args->lrr_smooth_win);
944 if ( args->control_sample.name ) smooth_data(args->control_sample.lrr,args->nsites, args->lrr_smooth_win);
945 }
946
947 // Set the BAF peak likelihoods, such as P(RRR|CN3), taking account the
948 // estimated fraction of aberrant cells in the mixture. With the new chromosome,
949 // reset the fraction to the default value.
950 args->query_sample.cell_frac = args->query_sample.cell_frac_dflt;
951 args->control_sample.cell_frac = args->control_sample.cell_frac_dflt;
952 args->query_sample.baf_dev2 = args->query_sample.baf_dev2_dflt;
953 args->control_sample.baf_dev2 = args->control_sample.baf_dev2_dflt;
954 set_gauss_params(args, &args->query_sample);
955 if ( args->control_sample.name ) set_gauss_params(args, &args->control_sample);
956
957 if ( args->optimize_frac )
958 {
959 int niter = 0;
960 fprintf(stderr,"Attempting to estimate the fraction of aberrant cells (chr %s):\n", bcf_hdr_id2name(args->hdr,args->prev_rid));
961 do
962 {
963 fprintf(stderr,"\t.. %f %f", args->query_sample.cell_frac,args->query_sample.baf_dev2);
964 if ( args->control_sample.name )
965 fprintf(stderr,"\t.. %f %f", args->control_sample.cell_frac,args->control_sample.baf_dev2);
966 fprintf(stderr,"\n");
967 set_emission_probs(args);
968 hmm_run_fwd_bwd(hmm, args->nsites, args->eprob, args->sites);
969 }
970 while ( update_args(args) && ++niter<20 );
971 if ( niter>=20 )
972 {
973 // no convergence
974 args->query_sample.cell_frac = args->query_sample.cell_frac_dflt;
975 args->control_sample.cell_frac = args->control_sample.cell_frac_dflt;
976 args->query_sample.baf_dev2 = args->query_sample.baf_dev2_dflt;
977 args->control_sample.baf_dev2 = args->control_sample.baf_dev2_dflt;
978 set_gauss_params(args, &args->query_sample);
979 if ( args->control_sample.name ) set_gauss_params(args, &args->control_sample);
980 }
981
982 fprintf(stderr,"\t.. %f %f", args->query_sample.cell_frac,args->query_sample.baf_dev2);
983 if ( args->control_sample.name )
984 fprintf(stderr,"\t.. %f %f", args->control_sample.cell_frac,args->control_sample.baf_dev2);
985 fprintf(stderr,"\n");
986
987 fprintf(args->query_sample.summary_fh,"CF\t%s\t%d\t%d\t%.2f\t%f\n",
988 bcf_hdr_id2name(args->hdr,args->prev_rid),args->sites[0]+1,args->sites[args->nsites-1]+1,
989 args->query_sample.cell_frac,sqrt(args->query_sample.baf_dev2));
990 if ( args->control_sample.name )
991 {
992 fprintf(args->control_sample.summary_fh,"CF\t%s\t%d\t%d\t%.2f\t%f\n",
993 bcf_hdr_id2name(args->hdr,args->prev_rid),args->sites[0]+1,args->sites[args->nsites-1]+1,
994 args->control_sample.cell_frac,sqrt(args->control_sample.baf_dev2));
995 fprintf(args->summary_fh,"CF\t%s\t%d\t%d\t%.2f\t%.2f\t%f\t%f\n",
996 bcf_hdr_id2name(args->hdr,args->prev_rid),args->sites[0]+1,args->sites[args->nsites-1]+1,
997 args->query_sample.cell_frac, args->control_sample.cell_frac,
998 sqrt(args->query_sample.baf_dev2), sqrt(args->control_sample.baf_dev2));
999 }
1000 }
1001 set_emission_probs(args);
1002
1003 while ( args->baum_welch_th!=0 )
1004 {
1005 int nstates = hmm_get_nstates(hmm);
1006 double ori_ii = avg_ii_prob(nstates,hmm_get_tprob(hmm));
1007 hmm_run_baum_welch(hmm, args->nsites, args->eprob, args->sites);
1008 double new_ii = avg_ii_prob(nstates,hmm_get_tprob(hmm));
1009 fprintf(stderr,"%e\t%e\t%e\n", ori_ii,new_ii,new_ii-ori_ii);
1010 double *tprob = init_tprob_matrix(nstates, 1-new_ii, args->same_prob);
1011 hmm_set_tprob(args->hmm, tprob, 10000);
1012 double *tprob_arr = hmm_get_tprob(hmm);
1013 free(tprob);
1014 if ( fabs(new_ii - ori_ii) < args->baum_welch_th )
1015 {
1016 int i,j;
1017 for (i=0; i<nstates; i++)
1018 {
1019 for (j=0; j<nstates; j++)
1020 {
1021 printf(" %.15f", MAT(tprob_arr,nstates,j,i));
1022 }
1023 printf("\n");
1024 }
1025 break;
1026 }
1027 }
1028 hmm_run_viterbi(hmm, args->nsites, args->eprob, args->sites);
1029 hmm_run_fwd_bwd(hmm, args->nsites, args->eprob, args->sites);
1030
1031
1032 // Output the results
1033 uint8_t *vpath = hmm_get_viterbi_path(hmm);
1034 double qual = 0, *fwd = hmm_get_fwd_bwd_prob(hmm);
1035 int i,j, isite, start_cn = vpath[0], start_pos = args->sites[0], istart_pos = 0;
1036 int ctrl_ntot = 0, smpl_ntot = 0, ctrl_nhet = 0, smpl_nhet = 0;
1037 for (isite=0; isite<args->nsites; isite++)
1038 {
1039 int state = vpath[args->nstates*isite];
1040 double *pval = fwd + isite*args->nstates;
1041
1042 qual += pval[start_cn];
1043
1044 // output CN and fwd-bwd likelihood for each site
1045 if ( args->query_sample.cn_fh )
1046 {
1047 fprintf(args->query_sample.cn_fh, "%s\t%d\t%c", bcf_hdr_id2name(args->hdr,args->prev_rid), args->sites[isite]+1, copy_number_state(args,state,0));
1048 if ( !args->control_sample.cn_fh )
1049 for (i=0; i<args->nstates; i++) fprintf(args->query_sample.cn_fh, "\t%f", pval[i]);
1050 else
1051 for (i=0; i<N_STATES; i++)
1052 {
1053 double sum = 0;
1054 for (j=0; j<N_STATES; j++) sum += pval[i*N_STATES+j];
1055 fprintf(args->query_sample.cn_fh, "\t%f", sum);
1056 }
1057 fprintf(args->query_sample.cn_fh, "\n");
1058 if ( args->query_sample.baf[isite]>=0 ) // if non-missing
1059 {
1060 if ( BAF_LIKELY_HET(args->query_sample.baf[isite]) ) smpl_nhet++;
1061 smpl_ntot++;
1062 }
1063 }
1064 if ( args->control_sample.cn_fh )
1065 {
1066 fprintf(args->control_sample.cn_fh, "%s\t%d\t%c", bcf_hdr_id2name(args->hdr,args->prev_rid), args->sites[isite]+1, copy_number_state(args,state,1));
1067 for (i=0; i<N_STATES; i++)
1068 {
1069 double sum = 0;
1070 for (j=0; j<N_STATES; j++) sum += pval[i+N_STATES*j];
1071 fprintf(args->control_sample.cn_fh, "\t%f", sum);
1072 }
1073 fprintf(args->control_sample.cn_fh, "\n");
1074 if ( args->control_sample.baf[isite]>=0 ) // if non-missing
1075 {
1076 if ( BAF_LIKELY_HET(args->control_sample.baf[isite]) ) ctrl_nhet++;
1077 ctrl_ntot++;
1078 }
1079 }
1080
1081 if ( start_cn != state )
1082 {
1083 char start_cn_query = copy_number_state(args,start_cn,0);
1084 qual = phred_score(1 - qual/(isite - istart_pos));
1085 fprintf(args->query_sample.summary_fh,"RG\t%s\t%d\t%d\t%c\t%.1f\t%d\t%d\n",
1086 bcf_hdr_id2name(args->hdr,args->prev_rid), start_pos+1, args->sites[isite],start_cn_query,qual,smpl_ntot,smpl_nhet);
1087
1088 if ( args->control_sample.name )
1089 {
1090 // regions 0-based, half-open
1091 char start_cn_ctrl = copy_number_state(args,start_cn,1);
1092 fprintf(args->control_sample.summary_fh,"RG\t%s\t%d\t%d\t%c\t%.1f\t%d\t%d\n",
1093 bcf_hdr_id2name(args->hdr,args->prev_rid), start_pos+1, args->sites[isite],start_cn_ctrl,qual,ctrl_ntot,ctrl_nhet);
1094 fprintf(args->summary_fh,"RG\t%s\t%d\t%d\t%c\t%c\t%.1f\t%d\t%d\t%d\t%d\n",
1095 bcf_hdr_id2name(args->hdr,args->prev_rid), start_pos+1, args->sites[isite],start_cn_query,start_cn_ctrl,qual,smpl_ntot,smpl_nhet,ctrl_ntot,ctrl_nhet);
1096 }
1097
1098 istart_pos = isite;
1099 start_pos = args->sites[isite];
1100 start_cn = state;
1101 qual = 0;
1102 smpl_ntot = smpl_nhet = ctrl_ntot = ctrl_nhet = 0;
1103 }
1104 }
1105 qual = phred_score(1 - qual/(isite - istart_pos));
1106 char start_cn_query = copy_number_state(args,start_cn,0);
1107 fprintf(args->query_sample.summary_fh,"RG\t%s\t%d\t%d\t%c\t%.1f\t%d\t%d\n",
1108 bcf_hdr_id2name(args->hdr,args->prev_rid), start_pos+1, args->sites[isite-1]+1,start_cn_query,qual,smpl_ntot,smpl_nhet);
1109 if ( args->control_sample.name )
1110 {
1111 char start_cn_ctrl = copy_number_state(args,start_cn,1);
1112 fprintf(args->control_sample.summary_fh,"RG\t%s\t%d\t%d\t%c\t%.1f\t%d\t%d\n",
1113 bcf_hdr_id2name(args->hdr,args->prev_rid), start_pos+1, args->sites[isite-1]+1,start_cn_ctrl,qual,ctrl_ntot,ctrl_nhet);
1114 fprintf(args->summary_fh,"RG\t%s\t%d\t%d\t%c\t%c\t%.1f\t%d\t%d\t%d\t%d\n",
1115 bcf_hdr_id2name(args->hdr,args->prev_rid), start_pos+1, args->sites[isite-1]+1,start_cn_query,start_cn_ctrl,qual,smpl_ntot,smpl_nhet,ctrl_ntot,ctrl_nhet);
1116 }
1117 }
1118
1119 static int parse_lrr_baf(sample_t *smpl, bcf_fmt_t *baf_fmt, bcf_fmt_t *lrr_fmt, float *baf, float *lrr)
1120 {
1121 *baf = ((float*)(baf_fmt->p + baf_fmt->size*smpl->idx))[0];
1122 if ( bcf_float_is_missing(*baf) || isnan(*baf) ) *baf = -0.1; // arbitrary negative value == missing value
1123
1124 if ( lrr_fmt )
1125 {
1126 *lrr = ((float*)(lrr_fmt->p + lrr_fmt->size*smpl->idx))[0];
1127 if ( bcf_float_is_missing(*lrr) || isnan(*lrr) ) { *lrr = 0; *baf = -0.1; }
1128 }
1129 else
1130 *lrr = 0;
1131
1132 return *baf<0 ? 0 : 1;
1133 }
1134
1135 static void cnv_next_line(args_t *args, bcf1_t *line)
1136 {
1137 if ( !line )
1138 {
1139 // Done, flush viterbi
1140 cnv_flush_viterbi(args);
1141 return;
1142 }
1143
1144 if ( line->rid!=args->prev_rid )
1145 {
1146 // New chromosome
1147 cnv_flush_viterbi(args);
1148 args->prev_rid = line->rid;
1149 args->nsites = 0;
1150 args->nRR = args->nAA = args->nRA = 0;
1151 }
1152
1153 // Process line
1154 args->ntot++;
1155
1156 bcf_fmt_t *baf_fmt, *lrr_fmt = NULL;
1157 if ( !(baf_fmt = bcf_get_fmt(args->hdr, line, "BAF")) ) return;
1158 if ( args->lrr_bias>0 && !(lrr_fmt = bcf_get_fmt(args->hdr, line, "LRR")) ) return;
1159
1160 float baf1,lrr1,baf2,lrr2;
1161 int ret = 0;
1162 ret += parse_lrr_baf(&args->query_sample, baf_fmt,lrr_fmt,&baf1,&lrr1);
1163 ret += parse_lrr_baf(&args->control_sample,baf_fmt,lrr_fmt,&baf2,&lrr2);
1164 if ( !ret ) return;
1165
1166 // Realloc buffers needed to store observed data and used by viterbi and fwd-bwd
1167 args->nsites++;
1168 int m = args->msites;
1169 hts_expand(uint32_t,args->nsites,args->msites,args->sites);
1170 if ( args->msites!=m )
1171 {
1172 args->eprob = (double*) realloc(args->eprob,sizeof(double)*args->msites*args->nstates);
1173 if ( args->control_sample.name )
1174 {
1175 args->control_sample.lrr = (float*) realloc(args->control_sample.lrr,sizeof(float)*args->msites);
1176 args->control_sample.baf = (float*) realloc(args->control_sample.baf,sizeof(float)*args->msites);
1177 }
1178 args->query_sample.lrr = (float*) realloc(args->query_sample.lrr,sizeof(float)*args->msites);
1179 args->query_sample.baf = (float*) realloc(args->query_sample.baf,sizeof(float)*args->msites);
1180 if ( args->af_fname )
1181 args->nonref_afs = (float*) realloc(args->nonref_afs,sizeof(float)*args->msites);
1182 }
1183 args->sites[args->nsites-1] = line->pos;
1184 args->query_sample.lrr[args->nsites-1] = lrr1;
1185 args->query_sample.baf[args->nsites-1] = baf1;
1186 if ( args->af_fname )
1187 {
1188 double alt_freq;
1189 args->nonref_afs[args->nsites-1] = read_AF(args->files->targets,line,&alt_freq)<0 ? args->nonref_af_dflt : alt_freq;
1190 }
1191 if ( args->control_sample.name )
1192 {
1193 args->control_sample.lrr[args->nsites-1] = lrr2;
1194 args->control_sample.baf[args->nsites-1] = baf2;
1195 if ( baf2>=0 ) // skip missing values
1196 fprintf(args->control_sample.dat_fh,"%s\t%"PRId64"\t%.3f\t%.3f\n",bcf_hdr_id2name(args->hdr,args->prev_rid), (int64_t) line->pos+1,baf2,lrr2);
1197 }
1198 if ( baf1>=0 ) // skip missing values
1199 fprintf(args->query_sample.dat_fh,"%s\t%"PRId64"\t%.3f\t%.3f\n",bcf_hdr_id2name(args->hdr,args->prev_rid), (int64_t) line->pos+1,baf1,lrr1);
1200
1201 if ( baf1>=0 )
1202 {
1203 if ( baf1<1/5. ) args->nRR++;
1204 else if ( baf1>4/5. ) args->nAA++;
1205 else args->nRA++;
1206 }
1207 args->nused++;
1208 }
1209
1210 static void usage(args_t *args)
1211 {
1212 fprintf(stderr, "\n");
1213 fprintf(stderr, "About: Copy number variation caller, requires Illumina's B-allele frequency (BAF) and Log R\n");
1214 fprintf(stderr, " Ratio intensity (LRR). The HMM considers the following copy number states: CN 2\n");
1215 fprintf(stderr, " (normal), 1 (single-copy loss), 0 (complete loss), 3 (single-copy gain)\n");
1216 fprintf(stderr, "Usage: bcftools cnv [OPTIONS] FILE.vcf\n");
1217 fprintf(stderr, "General Options:\n");
1218 fprintf(stderr, " -c, --control-sample STRING Optional control sample name to highlight differences\n");
1219 fprintf(stderr, " -f, --AF-file FILE Read allele frequencies from file (CHR\\tPOS\\tREF,ALT\\tAF)\n");
1220 fprintf(stderr, " -o, --output-dir PATH \n");
1221 fprintf(stderr, " -p, --plot-threshold FLOAT Plot aberrant chromosomes with quality at least FLOAT\n");
1222 fprintf(stderr, " -r, --regions REGION Restrict to comma-separated list of regions\n");
1223 fprintf(stderr, " -R, --regions-file FILE Restrict to regions listed in a file\n");
1224 fprintf(stderr, " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n");
1225 fprintf(stderr, " -s, --query-sample STRING Query samply name\n");
1226 fprintf(stderr, " -t, --targets REGION Similar to -r but streams rather than index-jumps\n");
1227 fprintf(stderr, " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n");
1228 fprintf(stderr, " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n");
1229 fprintf(stderr, "HMM Options:\n");
1230 fprintf(stderr, " -a, --aberrant FLOAT[,FLOAT] Fraction of aberrant cells in query and control [1.0,1.0]\n");
1231 fprintf(stderr, " -b, --BAF-weight FLOAT Relative contribution from BAF [1]\n");
1232 fprintf(stderr, " -d, --BAF-dev FLOAT[,FLOAT] Expected BAF deviation in query and control [0.04,0.04]\n"); // experimental
1233 fprintf(stderr, " -e, --err-prob FLOAT Uniform error probability [1e-4]\n");
1234 fprintf(stderr, " -k, --LRR-dev FLOAT[,FLOAT] Expected LRR deviation [0.2,0.2]\n"); // experimental
1235 fprintf(stderr, " -l, --LRR-weight FLOAT Relative contribution from LRR [0.2]\n");
1236 fprintf(stderr, " -L, --LRR-smooth-win INT Window of LRR moving average smoothing [10]\n");
1237 fprintf(stderr, " -O, --optimize FLOAT Estimate fraction of aberrant cells down to FLOAT [1.0]\n");
1238 fprintf(stderr, " -P, --same-prob FLOA> Prior probability of -s/-c being the same [0.5]\n");
1239 fprintf(stderr, " -x, --xy-prob FLOAT P(x|y) transition probability [1e-9]\n");
1240 fprintf(stderr, "\n");
1241 exit(1);
1242 }
1243
1244 int main_vcfcnv(int argc, char *argv[])
1245 {
1246 int c;
1247 args_t *args = (args_t*) calloc(1,sizeof(args_t));
1248 args->argc = argc; args->argv = argv;
1249 args->files = bcf_sr_init();
1250 args->plot_th = 1e9; // by default plot none
1251 args->nonref_af_dflt = 0.1;
1252 args->lrr_smooth_win = 10;
1253
1254 args->query_sample.cell_frac_dflt = 1;
1255 args->control_sample.cell_frac_dflt = 1;
1256
1257 // How much FORMAT/LRR and FORMAT/BAF matter
1258 args->lrr_bias = 0.2;
1259 args->baf_bias = 1.0;
1260 args->err_prob = 1e-4;
1261
1262 // Transition probability to a different state and the prior of both samples being the same
1263 args->ij_prob = 1e-9;
1264 args->same_prob = 0.5;
1265
1266 // Squared std dev of BAF and LRR values (gaussian noise), estimated from real data (hets, one sample, one chr)
1267 args->query_sample.baf_dev2_dflt = args->control_sample.baf_dev2_dflt = 0.04*0.04; // illumina: 0.03
1268 args->query_sample.lrr_dev2 = args->control_sample.lrr_dev2 = 0.2*0.2; //0.20*0.20; // illumina: 0.18
1269
1270 int regions_is_file = 0, targets_is_file = 0;
1271 int regions_overlap = 1;
1272 int targets_overlap = 0;
1273
1274 static struct option loptions[] =
1275 {
1276 {"BAF-dev",1,0,'d'},
1277 {"LRR-dev",1,0,'k'},
1278 {"LRR-smooth-win",1,0,'L'},
1279 {"AF-file",1,0,'f'},
1280 {"baum-welch",1,0,'W'}, // hidden
1281 {"optimize",1,0,'O'},
1282 {"aberrant",1,0,'a'},
1283 {"err-prob",1,0,'e'},
1284 {"BAF-weight",1,0,'b'},
1285 {"LRR-weight",1,0,'l'},
1286 {"same-prob",1,0,'P'},
1287 {"xy-prob",1,0,'x'},
1288 {"query-sample",1,0,'s'},
1289 {"control-sample",1,0,'c'},
1290 {"targets",1,0,'t'},
1291 {"targets-file",1,0,'T'},
1292 {"targets-overlap",required_argument,NULL,4},
1293 {"regions",1,0,'r'},
1294 {"regions-file",1,0,'R'},
1295 {"regions-overlap",required_argument,NULL,3},
1296 {"plot-threshold",1,0,'p'},
1297 {"output-dir",1,0,'o'},
1298 {0,0,0,0}
1299 };
1300 char *tmp = NULL;
1301 while ((c = getopt_long(argc, argv, "h?r:R:t:T:s:o:p:l:T:c:b:P:x:e:O:W::f:a:L:d:k:",loptions,NULL)) >= 0) {
1302 switch (c) {
1303 case 'L':
1304 args->lrr_smooth_win = strtol(optarg,&tmp,10);
1305 if ( *tmp ) error("Could not parse: --LRR-smooth-win %s\n", optarg);
1306 break;
1307 case 'f': args->af_fname = optarg; break;
1308 case 'O':
1309 args->optimize_frac = strtod(optarg,&tmp);
1310 if ( *tmp ) error("Could not parse: -O %s\n", optarg);
1311 break;
1312 case 'd':
1313 args->query_sample.baf_dev2_dflt = strtod(optarg,&tmp);
1314 if ( *tmp )
1315 {
1316 if ( *tmp!=',') error("Could not parse: -d %s\n", optarg);
1317 args->control_sample.baf_dev2_dflt = strtod(tmp+1,&tmp);
1318 if ( *tmp ) error("Could not parse: -d %s\n", optarg);
1319 }
1320 else
1321 args->control_sample.baf_dev2_dflt = args->query_sample.baf_dev2_dflt;
1322 args->query_sample.baf_dev2_dflt *= args->query_sample.baf_dev2_dflt;
1323 args->control_sample.baf_dev2_dflt *= args->control_sample.baf_dev2_dflt;
1324 break;
1325 case 'k':
1326 args->query_sample.lrr_dev2 = strtod(optarg,&tmp);
1327 if ( *tmp )
1328 {
1329 if ( *tmp!=',') error("Could not parse: -k %s\n", optarg);
1330 args->control_sample.lrr_dev2 = strtod(tmp+1,&tmp);
1331 if ( *tmp ) error("Could not parse: -d %s\n", optarg);
1332 }
1333 else
1334 args->control_sample.lrr_dev2 = args->query_sample.lrr_dev2;
1335 args->query_sample.lrr_dev2 *= args->query_sample.lrr_dev2;
1336 args->control_sample.lrr_dev2 *= args->control_sample.lrr_dev2;
1337 break;
1338 case 'a':
1339 args->query_sample.cell_frac_dflt = strtod(optarg,&tmp);
1340 if ( *tmp )
1341 {
1342 if ( *tmp!=',') error("Could not parse: -a %s\n", optarg);
1343 args->control_sample.cell_frac_dflt = strtod(tmp+1,&tmp);
1344 if ( *tmp ) error("Could not parse: -a %s\n", optarg);
1345 }
1346 break;
1347 case 'W':
1348 args->baum_welch_th = strtod(optarg,&tmp);
1349 if ( *tmp ) error("Could not parse: -W %s\n", optarg);
1350 break;
1351 case 'e':
1352 args->err_prob = strtod(optarg,&tmp);
1353 if ( *tmp ) error("Could not parse: -e %s\n", optarg);
1354 break;
1355 case 'b':
1356 args->baf_bias = strtod(optarg,&tmp);
1357 if ( *tmp ) error("Could not parse: -b %s\n", optarg);
1358 break;
1359 case 'x':
1360 args->ij_prob = strtod(optarg,&tmp);
1361 if ( *tmp ) error("Could not parse: -x %s\n", optarg);
1362 break;
1363 case 'P':
1364 args->same_prob = strtod(optarg,&tmp);
1365 if ( *tmp ) error("Could not parse: -P %s\n", optarg);
1366 break;
1367 case 'l':
1368 args->lrr_bias = strtod(optarg,&tmp);
1369 if ( *tmp ) error("Could not parse: -l %s\n", optarg);
1370 break;
1371 case 'p':
1372 args->plot_th = strtod(optarg,&tmp);
1373 if ( *tmp ) error("Could not parse: -p %s\n", optarg);
1374 break;
1375 case 'o': args->output_dir = optarg; break;
1376 case 's': args->query_sample.name = strdup(optarg); break;
1377 case 'c': args->control_sample.name = optarg; break;
1378 case 't': args->targets_list = optarg; break;
1379 case 'T': args->targets_list = optarg; targets_is_file = 1; break;
1380 case 'r': args->regions_list = optarg; break;
1381 case 'R': args->regions_list = optarg; regions_is_file = 1; break;
1382 case 3 :
1383 regions_overlap = parse_overlap_option(optarg);
1384 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
1385 break;
1386 case 4 :
1387 targets_overlap = parse_overlap_option(optarg);
1388 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
1389 break;
1390 case 'h':
1391 case '?': usage(args); break;
1392 default: error("Unknown argument: %s\n", optarg);
1393 }
1394 }
1395
1396 char *fname = NULL;
1397 if ( optind>=argc )
1398 {
1399 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-";
1400 }
1401 else fname = argv[optind];
1402 if ( !fname ) usage(args);
1403
1404 if ( !args->output_dir ) error("Expected -o option\n");
1405 if ( args->regions_list )
1406 {
1407 bcf_sr_set_opt(args->files,BCF_SR_REGIONS_OVERLAP,regions_overlap);
1408 if ( bcf_sr_set_regions(args->files, args->regions_list, regions_is_file)<0 )
1409 error("Failed to read the regions: %s\n", args->regions_list);
1410 }
1411 if ( args->targets_list )
1412 {
1413 bcf_sr_set_opt(args->files,BCF_SR_TARGETS_OVERLAP,targets_overlap);
1414 if ( bcf_sr_set_targets(args->files, args->targets_list, targets_is_file, 0)<0 )
1415 error("Failed to read the targets: %s\n", args->targets_list);
1416 }
1417 if ( args->af_fname )
1418 {
1419 if ( bcf_sr_set_targets(args->files, args->af_fname, 1, 3)<0 )
1420 error("Failed to read the targets: %s\n", args->af_fname);
1421 }
1422 if ( !bcf_sr_add_reader(args->files, fname) )
1423 error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->files->errnum));
1424
1425 init_data(args);
1426 while ( bcf_sr_next_line(args->files) )
1427 {
1428 bcf1_t *line = bcf_sr_get_line(args->files,0);
1429 cnv_next_line(args, line);
1430 }
1431 cnv_next_line(args, NULL);
1432 create_plots(args);
1433 fprintf(stderr,"Number of lines: total/processed: %d/%d\n", args->ntot,args->nused);
1434 destroy_data(args);
1435 free(args);
1436 return 0;
1437 }
1438
1439