Debian Codegraph @

bcftools/vcfcnv.c.pysam.c

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