Debian Codegraph @

bcftools/csq.c.pysam.c

raw symbols SCIP
1 #include "bcftools.pysam.h"
2
3 /* The MIT License
4
5 Copyright (c) 2016-2024 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 Things that would be nice to have
30 - dynamic N_REF_PAD
31 - for stop-lost events (also in frameshifts) report the number of truncated aa's
32 - memory could be greatly reduced by indexing gff (but it is quite compact already)
33 - deletions that go beyond transcript boundaries are not checked at sequence level
34 - alloc tscript->ref in hap_finalize, introduce fa_off_beg:16,fa_off_end:16
35 - see test/csq/ENST00000573314/insertion-overlap.vcf #1476288882
36
37 Read about transcript types here
38 http://vega.sanger.ac.uk/info/about/gene_and_transcript_types.html
39 https://www.ensembl.org/info/genome/variation/prediction/predicted_data.html
40 https://www.gencodegenes.org/pages/biotypes.html
41
42 List of supported biotypes
43 antisense
44 IG_C_gene
45 IG_D_gene
46 IG_J_gene
47 IG_LV_gene
48 IG_V_gene
49 lincRNA
50 lncRNA .. generic term for 3prime_overlapping_ncRNA, antisense, bidirectional_promoter_lncRNA, lincRNA, macro_lncRNA, non_coding, processed_transcript, sense_intronic, sense_overlapping
51 macro_lncRNA
52 miRNA
53 misc_RNA
54 Mt_rRNA
55 Mt_tRNA
56 polymorphic_pseudogene
57 processed_transcript
58 protein_coding, mRNA
59 ribozyme
60 rRNA
61 sRNA
62 scRNA
63 scaRNA
64 sense_intronic
65 sense_overlapping
66 snRNA
67 snoRNA
68 TR_C_gene
69 TR_D_gene
70 TR_J_gene
71 TR_V_gene
72
73 The gff parsing logic
74 We collect features such by combining gff lines A,B,C as follows:
75 A .. gene line with a supported biotype
76 A.ID=~/^gene:/
77
78 B .. transcript line referencing A with supported biotype
79 B.ID=~/^transcript:/ && B.Parent=~/^gene:A.ID/
80
81 C .. corresponding CDS, exon, and UTR lines:
82 C[3] in {"CDS","exon","three_prime_UTR","five_prime_UTR"} && C.Parent=~/^transcript:B.ID/
83
84 For coding biotypes ("protein_coding" or "polymorphic_pseudogene") the
85 complete chain link C -> B -> A is required. For the rest, link B -> A suffices.
86
87
88 The supported consequence types, sorted by impact:
89 splice_acceptor_variant .. end region of an intron changed (2bp at the 3' end of an intron)
90 splice_donor_variant .. start region of an intron changed (2bp at the 5' end of an intron)
91 stop_gained .. DNA sequence variant resulting in a stop codon
92 frameshift_variant .. number of inserted/deleted bases not a multiple of three, disrupted translational frame
93 stop_lost .. elongated transcript, stop codon changed
94 start_lost .. the first codon changed
95 inframe_altering .. combination of indels leading to unchanged reading frame and length
96 inframe_insertion .. inserted coding sequence, unchanged reading frame
97 inframe_deletion .. deleted coding sequence, unchanged reading frame
98 missense_variant .. amino acid (aa) change, unchanged length
99 splice_region_variant .. change within 1-3 bases of the exon or 3-8 bases of the intron
100 synonymous_variant .. DNA sequence variant resulting in no amino acid change
101 stop_retained_variant .. different stop codon
102 start_retained_variant .. start codon retained by indel realignment
103 non_coding_variant .. variant in non-coding sequence, such as RNA gene
104 5_prime_UTR_variant
105 3_prime_UTR_variant
106 intron_variant .. reported only if none of the above
107 intergenic_variant .. reported only if none of the above
108
109
110 The annotation algorithm.
111 The algorithm checks if the variant falls in a region of a supported type. The
112 search is performed in the following order, until a match is found:
113 1. idx_cds(gf_cds_t) - lookup CDS by position, create haplotypes, call consequences
114 2. idx_utr(gf_utr_t) - check UTR hits
115 3. idx_exon(gf_exon_t) - check for splice variants
116 4. idx_tscript(tscript_t) - check for intronic variants, RNAs, etc.
117
118 These regidx indexes are created by parsing a gff3 file as follows:
119 1. create the array "ftr" of all UTR, CDS, exons. This will be
120 processed later and pruned based on transcript types we want to keep.
121 In the same go, create the hash "id2tr" of transcripts to keep
122 (based on biotype) which maps from transcript_id to a transcript. At
123 the same time also build the hash "gid2gene" which maps from gene_id to
124 gf_gene_t pointer.
125
126 2. build "idx_cds", "idx_tscript", "idx_utr" and "idx_exon" indexes.
127 Use only features from "ftr" which are present in "id2tr".
128
129 3. clean data that won't be needed anymore: ftr, id2tr, gid2gene.
130
131 Data structures.
132 idx_cds, idx_utr, idx_exon, idx_tscript:
133 as described above, regidx structures for fast lookup of exons/transcripts
134 overlapping a region, the payload is a pointer to tscript.cds
135 */
136
137 #include <stdio.h>
138 #include <stdlib.h>
139 #include <assert.h>
140 #include <getopt.h>
141 #include <math.h>
142 #include <inttypes.h>
143 #include <htslib/hts.h>
144 #include <htslib/vcf.h>
145 #include <htslib/synced_bcf_reader.h>
146 #include <htslib/khash.h>
147 #include <htslib/khash_str2int.h>
148 #include <htslib/kseq.h>
149 #include <htslib/faidx.h>
150 #include <htslib/bgzf.h>
151 #include <errno.h>
152 #include <unistd.h>
153 #include <ctype.h>
154 #include <strings.h>
155 #include "bcftools.h"
156 #include "filter.h"
157 #include "regidx.h"
158 #include "kheap.h"
159 #include "smpl_ilist.h"
160 #include "rbuf.h"
161 #include "gff.h"
162
163 #ifndef __FUNCTION__
164 # define __FUNCTION__ __func__
165 #endif
166
167 // Logic of the filters: include or exclude sites which match the filters?
168 #define FLT_INCLUDE 1
169 #define FLT_EXCLUDE 2
170
171 #define N_REF_PAD 10 // number of bases to avoid boundary effects
172
173 // How to treat phased/unphased genotypes
174 #define PHASE_REQUIRE 0 // --phase r
175 #define PHASE_MERGE 1 // --phase m
176 #define PHASE_AS_IS 2 // --phase a
177 #define PHASE_SKIP 3 // --phase s
178 #define PHASE_NON_REF 4 // --phase R
179 #define PHASE_DROP_GT 5 // --samples -
180
181 // Node types in the haplotype tree
182 #define HAP_CDS 0
183 #define HAP_ROOT 1
184 #define HAP_SSS 2 // start/stop/splice
185
186 #define CSQ_PRINTED_UPSTREAM (1<<0)
187 #define CSQ_SYNONYMOUS_VARIANT (1<<1)
188 #define CSQ_MISSENSE_VARIANT (1<<2)
189 #define CSQ_STOP_LOST (1<<3)
190 #define CSQ_STOP_GAINED (1<<4)
191 #define CSQ_INFRAME_DELETION (1<<5)
192 #define CSQ_INFRAME_INSERTION (1<<6)
193 #define CSQ_FRAMESHIFT_VARIANT (1<<7)
194 #define CSQ_SPLICE_ACCEPTOR (1<<8)
195 #define CSQ_SPLICE_DONOR (1<<9)
196 #define CSQ_START_LOST (1<<10)
197 #define CSQ_SPLICE_REGION (1<<11)
198 #define CSQ_STOP_RETAINED (1<<12)
199 #define CSQ_UTR5 (1<<13)
200 #define CSQ_UTR3 (1<<14)
201 #define CSQ_NON_CODING (1<<15)
202 #define CSQ_INTRON (1<<16)
203 //#define CSQ_INTERGENIC (1<<17)
204 #define CSQ_INFRAME_ALTERING (1<<18)
205 #define CSQ_UPSTREAM_STOP (1<<19) // adds * in front of the csq string
206 #define CSQ_INCOMPLETE_CDS (1<<20) // to remove START/STOP in incomplete CDS, see ENSG00000173376/synon.vcf
207 #define CSQ_CODING_SEQUENCE (1<<21) // cannot tell exactly what it is, but it does affect the coding sequence
208 #define CSQ_ELONGATION (1<<22) // symbolic insertion
209 #define CSQ_START_RETAINED (1<<23)
210
211 // Haplotype-aware consequences, printed in one vcf record only, the rest has a reference @12345
212 #define CSQ_COMPOUND (CSQ_SYNONYMOUS_VARIANT|CSQ_MISSENSE_VARIANT|CSQ_STOP_LOST|CSQ_STOP_GAINED| \
213 CSQ_INFRAME_DELETION|CSQ_INFRAME_INSERTION|CSQ_FRAMESHIFT_VARIANT| \
214 CSQ_START_LOST|CSQ_STOP_RETAINED|CSQ_INFRAME_ALTERING|CSQ_INCOMPLETE_CDS| \
215 CSQ_UPSTREAM_STOP|CSQ_START_RETAINED)
216 #define CSQ_START_STOP (CSQ_STOP_LOST|CSQ_STOP_GAINED|CSQ_STOP_RETAINED|CSQ_START_LOST|CSQ_START_RETAINED)
217
218 #define CSQ_PRN_STRAND(csq) ((csq)&CSQ_COMPOUND && !((csq)&(CSQ_SPLICE_ACCEPTOR|CSQ_SPLICE_DONOR|CSQ_SPLICE_REGION)))
219 #define CSQ_PRN_TSCRIPT (~(CSQ_INTRON|CSQ_NON_CODING))
220 #define CSQ_PRN_NMD (~(CSQ_INTRON|CSQ_NON_CODING))
221 #define CSQ_PRN_BIOTYPE CSQ_NON_CODING
222
223 // see kput_vcsq()
224 const char *csq_strings[] =
225 {
226 NULL,
227 "synonymous",
228 "missense",
229 "stop_lost",
230 "stop_gained",
231 "inframe_deletion",
232 "inframe_insertion",
233 "frameshift",
234 "splice_acceptor",
235 "splice_donor",
236 "start_lost",
237 "splice_region",
238 "stop_retained",
239 "5_prime_utr",
240 "3_prime_utr",
241 "non_coding",
242 "intron",
243 "intergenic",
244 "inframe_altering",
245 NULL,
246 NULL,
247 "coding_sequence",
248 "feature_elongation",
249 "start_retained"
250 };
251
252 /*
253 Structures related to VCF output:
254
255 vcsq_t
256 information required to assemble consequence lines such as "inframe_deletion|XYZ|ENST01|+|5TY>5I|121ACG>A+124TA>T"
257
258 vrec_t
259 single VCF record and csq tied to this record. (Haplotype can have multiple
260 consequences in several VCF records. Each record can have multiple consequences
261 from multiple haplotypes.)
262
263 csq_t
264 a top-level consequence tied to a haplotype
265
266 vbuf_t
267 pos2vbuf
268 VCF records with the same position clustered together for a fast lookup via pos2vbuf
269 */
270 typedef struct _vbuf_t vbuf_t;
271 typedef struct _vcsq_t vcsq_t;
272 struct _vcsq_t
273 {
274 uint32_t strand:1,
275 type:31; // one of CSQ_* types
276 uint32_t trid;
277 uint32_t vcf_ial;
278 uint32_t biotype; // one of GF_* types
279 char *gene; // gene name
280 bcf1_t *ref; // if type&CSQ_PRINTED_UPSTREAM, ref consequence "@1234"
281 kstring_t vstr; // variant string, eg 5TY>5I|121ACG>A+124TA>T
282 };
283 typedef struct
284 {
285 bcf1_t *line;
286 uint32_t *fmt_bm; // bitmask of sample consequences with first/second haplotype interleaved
287 uint32_t nfmt:4, // the bitmask size (the number of integers per sample)
288 nvcsq:28, mvcsq;
289 vcsq_t *vcsq; // there can be multiple consequences for a single VCF record
290 }
291 vrec_t;
292 typedef struct
293 {
294 uint32_t pos;
295 vrec_t *vrec; // vcf line that this csq is tied to; needed when printing haplotypes (hap_stage_vcf)
296 int idx; // 0-based index of the csq at the VCF line, for FMT/BCSQ
297 vcsq_t type;
298 }
299 csq_t;
300 struct _vbuf_t
301 {
302 vrec_t **vrec; // buffer of VCF lines with the same position
303 int n, m;
304 uint32_t keep_until; // the maximum transcript end position
305 };
306 KHASH_MAP_INIT_INT(pos2vbuf, vbuf_t*)
307
308
309 /*
310 Structures related to haplotype-aware consequences in coding regions
311
312 hap_node_t
313 node of a haplotype tree. Each transcript has one tree
314
315 tscript_t
316 despite its general name, it is intended for coding transcripts only
317
318 hap_t
319 hstack_t
320 for traversal of the haplotype tree and braking combined
321 consequences into independent parts
322 */
323 typedef struct _hap_node_t hap_node_t;
324 struct _hap_node_t
325 {
326 char *seq; // cds segment [parent_node,this_node)
327 char *var; // variant "ref>alt"
328 uint32_t type:2, // HAP_ROOT or HAP_CDS
329 csq:30; // this node's consequence
330 int dlen; // alt minus ref length: <0 del, >0 ins, 0 substitution
331 uint32_t rbeg; // variant's VCF position (0-based, inclusive)
332 int32_t rlen; // variant's rlen; alen=rlen+dlen; fake for non CDS types
333 uint32_t sbeg; // variant's position on the spliced reference transcript (0-based, inclusive, N_REF_PAD not included)
334 uint32_t icds; // which exon does this node's variant overlaps
335 hap_node_t **child, *prev; // children haplotypes and previous coding node
336 int nchild, mchild;
337 bcf1_t *cur_rec, *rec; // current VCF record and node's VCF record
338 int vcf_ial; // which VCF allele generated this node
339 uint32_t nend; // number of haplotypes ending in this node
340 int *cur_child, mcur_child; // mapping from the allele to the currently active child
341 csq_t *csq_list; // list of haplotype's consequences, broken by position (each corresponds to a VCF record)
342 int ncsq_list, mcsq_list;
343 };
344 #define TSCRIPT_AUX(x) ((tscript_t*)(x)->aux)
345 typedef struct
346 {
347 char *ref; // reference sequence, padded with N_REF_PAD bases on both ends
348 char *sref; // spliced reference sequence, padded with N_REF_PAD bases on both ends
349 hap_node_t *root; // root of the haplotype tree
350 hap_node_t **hap; // pointer to haplotype leaves, two for each sample
351 int nhap, nsref; // number of haplotypes and length of sref, including 2*N_REF_PAD
352 }
353 tscript_t;
354 static inline int cmp_tscript(gf_tscript_t **a, gf_tscript_t **b)
355 {
356 return ( (*a)->end < (*b)->end ) ? 1 : 0;
357 }
358 KHEAP_INIT(trhp, gf_tscript_t*, cmp_tscript)
359 typedef khp_trhp_t tr_heap_t;
360 typedef struct
361 {
362 hap_node_t *node; // current node
363 int ichild; // current child in the active node
364 int dlen; // total dlen, from the root to the active node
365 size_t slen; // total sequence length, from the root to the active node
366 }
367 hstack_t;
368 typedef struct
369 {
370 int mstack;
371 hstack_t *stack;
372 gf_tscript_t *tr; // tr->ref: spliced transcript on ref strand
373 kstring_t sseq; // spliced haplotype sequence on ref strand
374 kstring_t tseq; // the variable part of translated haplotype transcript, coding strand
375 kstring_t tref; // the variable part of translated reference transcript, coding strand
376 uint32_t sbeg; // stack's sbeg, for cases first node's type is HAP_SSS
377 int upstream_stop;
378 }
379 hap_t;
380
381 typedef struct _args_t
382 {
383 // the main regidx lookups, from chr:beg-end to overlapping features and
384 // index iterator
385 gff_t *gff;
386 regidx_t *idx_cds, *idx_utr, *idx_exon, *idx_tscript;
387 regitr_t *itr;
388
389 // text tab-delimited output (out) or vcf/bcf output (out_fh)
390 FILE *out;
391 htsFile *out_fh;
392 char *index_fn;
393 int write_index;
394 char *dump_gff;
395
396 // vcf
397 bcf_srs_t *sr;
398 bcf_hdr_t *hdr;
399 int hdr_nsmpl; // actual number of samples in the vcf, for bcf_update_format_values()
400
401 // include or exclude sites which match the filters
402 filter_t *filter;
403 char *filter_str;
404 int filter_logic; // FLT_INCLUDE or FLT_EXCLUDE
405
406 // samples to process
407 int sample_is_file;
408 char *sample_list;
409 smpl_ilist_t *smpl;
410
411 char *outdir, **argv, *fa_fname, *gff_fname, *output_fname;
412 char *bcsq_tag;
413 int argc, output_type, clevel;
414 int phase, verbosity, local_csq, record_cmd_line;
415 int ncsq2_max, nfmt_bcsq; // maximum number of csq per site that can be accessed from FORMAT/BCSQ (*2 and 1 bit skipped to avoid BCF missing values)
416 int ncsq2_small_warned;
417 int brief_predictions;
418 int unify_chr_names;
419 char *chr_name;
420 int mchr_name;
421 struct {
422 int unknown_chr,unknown_tscript_biotype,unknown_strand,unknown_phase,duplicate_id;
423 int unknown_cds_phase,incomplete_cds,wrong_phase,overlapping_cds;
424 } warned;
425
426 int rid; // current chromosome
427 tr_heap_t *active_tr; // heap of active transcripts for quick flushing
428 hap_t *hap; // transcript haplotype recursion
429 vbuf_t **vcf_buf; // buffered VCF lines to annotate with CSQ and flush
430 rbuf_t vcf_rbuf; // round buffer indexes to vcf_buf
431 kh_pos2vbuf_t *pos2vbuf; // fast lookup of buffered lines by position
432 gf_tscript_t **rm_tr; // buffer of transcripts to clean
433 int nrm_tr, mrm_tr;
434 csq_t *csq_buf; // pool of csq not managed by hap_node_t, i.e. non-CDS csqs
435 int ncsq_buf, mcsq_buf;
436 int force; // force run under various conditions. Currently only to skip out-of-phase transcripts
437 int n_threads; // extra compression/decompression threads
438
439 faidx_t *fai;
440 kstring_t str, str2;
441 int32_t *gt_arr, mgt_arr;
442 }
443 args_t;
444
445 // AAA, AAC, ...
446 const char *gencode = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF";
447 const uint8_t nt4[] =
448 {
449 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
450 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
451 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
452 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
453 4,0,4,1, 4,4,4,2, 4,4,4,4, 4,4,4,4,
454 4,4,4,4, 3,4,4,4, 4,4,4,4, 4,4,4,4,
455 4,0,4,1, 4,4,4,2, 4,4,4,4, 4,4,4,4,
456 4,4,4,4, 3
457 };
458 const uint8_t cnt4[] =
459 {
460 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
461 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
462 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
463 4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
464 4,3,4,2, 4,4,4,1, 4,4,4,4, 4,4,4,4,
465 4,4,4,4, 0,4,4,4, 4,4,4,4, 4,4,4,4,
466 4,3,4,2, 4,4,4,1, 4,4,4,4, 4,4,4,4,
467 4,4,4,4, 0
468 };
469 #define dna2aa(x) gencode[ nt4[(uint8_t)(x)[0]]<<4 | nt4[(uint8_t)(x)[1]]<<2 | nt4[(uint8_t)(x)[2]] ]
470 #define cdna2aa(x) gencode[ cnt4[(uint8_t)(x)[2]]<<4 | cnt4[(uint8_t)(x)[1]]<<2 | cnt4[(uint8_t)(x)[0]] ]
471
472 static inline int ncsq2_to_nfmt(int ncsq2)
473 {
474 return 1 + (ncsq2 - 1) / 30;
475 }
476 static inline void icsq2_to_bit(int icsq2, int *ival, int *ibit)
477 {
478 *ival = icsq2 / 30;
479 *ibit = icsq2 % 30;
480 }
481
482 void init_data(args_t *args)
483 {
484 args->nfmt_bcsq = ncsq2_to_nfmt(args->ncsq2_max);
485
486 args->fai = fai_load(args->fa_fname);
487 if ( !args->fai ) error("Failed to load the fai index: %s\n", args->fa_fname);
488
489 args->gff = gff_init(args->gff_fname);
490 gff_set(args->gff,verbosity,args->verbosity);
491 gff_set(args->gff,strip_chr_names,args->unify_chr_names);
492 gff_set(args->gff,force_out_of_phase,args->force);
493 gff_set(args->gff,dump_fname,args->dump_gff);
494 gff_parse(args->gff);
495 args->idx_cds = gff_get(args->gff,idx_cds);
496 args->idx_utr = gff_get(args->gff,idx_utr);
497 args->idx_exon = gff_get(args->gff,idx_exon);
498 args->idx_tscript = gff_get(args->gff,idx_tscript);
499 args->itr = regitr_init(NULL);
500
501 args->rid = -1;
502
503 if ( args->filter_str )
504 args->filter = filter_init(args->hdr, args->filter_str);
505
506 args->pos2vbuf = kh_init(pos2vbuf);
507 args->active_tr = khp_init(trhp);
508 args->hap = (hap_t*) calloc(1,sizeof(hap_t));
509
510 // init samples
511 if ( !bcf_hdr_nsamples(args->hdr) ) args->phase = PHASE_DROP_GT;
512 if ( args->sample_list && !strcmp("-",args->sample_list) )
513 {
514 // ignore all samples
515 if ( args->output_type==FT_TAB_TEXT )
516 {
517 // significant speedup for plain VCFs
518 if (bcf_hdr_set_samples(args->hdr,NULL,0) < 0)
519 error_errno("[%s] Couldn't build sample filter", __func__);
520 }
521 args->phase = PHASE_DROP_GT;
522 }
523 else
524 args->smpl = smpl_ilist_init(args->hdr, args->sample_list, args->sample_is_file, SMPL_STRICT);
525 args->hdr_nsmpl = args->phase==PHASE_DROP_GT ? 0 : bcf_hdr_nsamples(args->hdr);
526
527 if ( args->output_type==FT_TAB_TEXT )
528 {
529 args->out = args->output_fname ? fopen(args->output_fname,"w") : bcftools_stdout;
530 if ( !args->out ) error("Failed to write to %s: %s\n", !strcmp("-",args->output_fname)?"standard output":args->output_fname,strerror(errno));
531
532 fprintf(args->out,"# This file was produced by: bcftools +csq(%s+htslib-%s)\n", bcftools_version(),hts_version());
533 fprintf(args->out,"# The command line was:\tbcftools +%s", args->argv[0]);
534 int i;
535 for (i=1; i<args->argc; i++)
536 fprintf(args->out," %s",args->argv[i]);
537 fprintf(args->out,"\n");
538 fprintf(args->out,"# LOG\t[2]Message\n");
539 fprintf(args->out,"# CSQ"); i = 1;
540 fprintf(args->out,"\t[%d]Sample", ++i);
541 fprintf(args->out,"\t[%d]Haplotype", ++i);
542 fprintf(args->out,"\t[%d]Chromosome", ++i);
543 fprintf(args->out,"\t[%d]Position", ++i);
544 fprintf(args->out,"\t[%d]Consequence", ++i);
545 fprintf(args->out,"\n");
546 }
547 else
548 {
549 char wmode[8];
550 set_wmode(wmode,args->output_type,args->output_fname,args->clevel);
551 args->out_fh = hts_open(args->output_fname ? args->output_fname : "-", wmode);
552 if ( args->out_fh == NULL ) error("[%s] Error: cannot write to %s: %s\n", __func__,args->output_fname? args->output_fname : "standard output", strerror(errno));
553 if ( args->n_threads > 0)
554 hts_set_opt(args->out_fh, HTS_OPT_THREAD_POOL, args->sr->p);
555 if ( args->record_cmd_line ) bcf_hdr_append_version(args->hdr,args->argc,args->argv,"bcftools/csq");
556 bcf_hdr_printf(args->hdr,"##INFO=<ID=%s,Number=.,Type=String,Description=\"%s consequence annotation from BCFtools/csq, see http://samtools.github.io/bcftools/howtos/csq-calling.html for details. Format: Consequence|gene|transcript|biotype|strand|amino_acid_change|dna_change\">",args->bcsq_tag, args->local_csq ? "Local" : "Haplotype-aware");
557 if ( args->hdr_nsmpl )
558 bcf_hdr_printf(args->hdr,"##FORMAT=<ID=%s,Number=.,Type=Integer,Description=\"Bitmask of indexes to INFO/BCSQ, with interleaved first/second haplotype. Use \\\"bcftools query -f'[%%CHROM\\t%%POS\\t%%SAMPLE\\t%%TBCSQ\\n]'\\\" to translate.\">",args->bcsq_tag);
559 if ( bcf_hdr_write(args->out_fh, args->hdr)!=0 ) error("[%s] Error: cannot write the header to %s\n", __func__,args->output_fname?args->output_fname:"standard output");
560 if ( init_index2(args->out_fh,args->hdr,args->output_fname,
561 &args->index_fn, args->write_index) < 0 )
562 error("Error: failed to initialise index for %s\n",args->output_fname);
563 }
564 if ( args->verbosity > 0 ) fprintf(bcftools_stderr,"Calling...\n");
565 }
566
567 void destroy_data(args_t *args)
568 {
569 if ( args->ncsq2_small_warned )
570 fprintf(bcftools_stderr,
571 "Note: Some samples had too many consequences to be represented in %d bytes. If you need to record them all,\n"
572 " the limit can be increased by running with `--ncsq %d`.\n",ncsq2_to_nfmt(args->ncsq2_max)/8,1+args->ncsq2_small_warned/2);
573
574 regitr_destroy(args->itr);
575 gff_destroy(args->gff);
576
577 if ( args->filter )
578 filter_destroy(args->filter);
579
580 khp_destroy(trhp,args->active_tr);
581 kh_destroy(pos2vbuf,args->pos2vbuf);
582 if ( args->smpl ) smpl_ilist_destroy(args->smpl);
583 int i,j,ret;
584 if ( args->out_fh )
585 {
586 if ( args->write_index )
587 {
588 if ( bcf_idx_save(args->out_fh)<0 )
589 {
590 if ( hts_close(args->out_fh)!=0 ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
591 error("Error: cannot write to index %s\n", args->index_fn);
592 }
593 free(args->index_fn);
594 }
595 ret = hts_close(args->out_fh);
596 }
597 else
598 ret = fclose(args->out);
599 if ( ret ) error("Error: close failed .. %s\n", args->output_fname?args->output_fname:"bcftools_stdout");
600 for (i=0; i<args->vcf_rbuf.m; i++)
601 {
602 vbuf_t *vbuf = args->vcf_buf[i];
603 if ( !vbuf ) continue;
604 for (j=0; j<vbuf->m; j++)
605 {
606 if ( !vbuf->vrec[j] ) continue;
607 if ( vbuf->vrec[j]->line ) bcf_destroy(vbuf->vrec[j]->line);
608 free(vbuf->vrec[j]->fmt_bm);
609 free(vbuf->vrec[j]->vcsq);
610 free(vbuf->vrec[j]);
611 }
612 free(vbuf->vrec);
613 free(vbuf);
614 }
615 free(args->vcf_buf);
616 free(args->rm_tr);
617 free(args->csq_buf);
618 free(args->hap->stack);
619 free(args->hap->sseq.s);
620 free(args->hap->tseq.s);
621 free(args->hap->tref.s);
622 free(args->hap);
623 fai_destroy(args->fai);
624 free(args->gt_arr);
625 free(args->str.s);
626 free(args->str2.s);
627 free(args->chr_name);
628 }
629
630 /*
631 The splice_* functions are for consequences around splice sites: start,stop,splice_*
632 */
633 #define SPLICE_VAR_REF 0 // ref: ACGT>ACGT, csq not applicable, skip completely
634 #define SPLICE_OUTSIDE 1 // splice acceptor or similar; csq set and is done, does not overlap the region
635 #define SPLICE_INSIDE 2 // overlaps coding region; csq can be set but coding prediction is needed
636 #define SPLICE_OVERLAP 3 // indel overlaps region boundary, csq set but could not determine csq
637 typedef struct
638 {
639 gf_tscript_t *tr;
640 struct {
641 int32_t pos, rlen, alen, ial;
642 char *ref, *alt;
643 bcf1_t *rec;
644 } vcf;
645 uint16_t check_acceptor:1, // check distance from exon start (fwd) or end (rev)
646 check_start:1, // this is the first coding exon (relative to transcript orientation), check first (fwd) or last (rev) codon
647 check_stop:1, // this is the last coding exon (relative to transcript orientation), check last (fwd) or first (rev) codon
648 check_donor:1, // as with check_acceptor
649 check_region_beg:1, // do/don't check for splices at this end, eg. in the first or last exon
650 check_region_end:1, //
651 check_utr:1, // check splice sites (acceptor/donor/region_*) only if not in utr
652 set_refalt:1; // set kref,kalt, if set, check also for synonymous events
653 uint32_t csq;
654 int tbeg, tend; // number of trimmed bases from beg and end of ref,alt allele
655 uint32_t ref_beg, // ref coordinates with spurious bases removed, ACC>AC can become AC>A or CC>C, whichever gives
656 ref_end; // a more conservative csq (the first and last base in kref.s)
657 kstring_t kref, kalt; // trimmed alleles, set only with SPLICE_OLAP
658 }
659 splice_t;
660 void splice_init(splice_t *splice, bcf1_t *rec)
661 {
662 memset(splice,0,sizeof(*splice));
663 splice->vcf.rec = rec;
664 splice->vcf.pos = rec->pos;
665 splice->vcf.rlen = rec->rlen;
666 splice->vcf.ref = rec->d.allele[0];
667 splice->csq = 0;
668 }
669 static inline void splice_build_hap(splice_t *splice, uint32_t beg, int len)
670 {
671 // len>0 .. beg is the first base, del filled from right
672 // len<0 .. beg is the last base, del filled from left
673
674 int rlen, alen, rbeg, abeg; // first base to include (ref coordinates)
675 if ( len<0 )
676 {
677 rlen = alen = -len;
678 rbeg = beg - rlen + 1;
679 int dlen = splice->vcf.alen - splice->vcf.rlen;
680 if ( dlen<0 && beg < splice->ref_end ) // incomplete del, beg is in the middle
681 dlen += splice->ref_end - beg;
682 abeg = rbeg + dlen;
683 }
684 else
685 {
686 rbeg = abeg = beg;
687 rlen = alen = len;
688 // check for incomplete del as above??
689 }
690
691 #define XDBG 0
692 #if XDBG
693 fprintf(bcftools_stderr,"build_hap: rbeg=%d + %d abeg=%d \n",rbeg,rlen,abeg);
694 #endif
695 splice->kref.l = 0;
696 splice->kalt.l = 0;
697
698 // add the part before vcf.ref, in the vcf.ref and after vcf.ref
699 int roff; // how many vcf.ref bases already used
700 if ( rbeg < splice->vcf.pos )
701 {
702 assert( splice->tr->beg <= rbeg ); // this can be extended thanks to N_REF_PAD
703 kputsn(TSCRIPT_AUX(splice->tr)->ref + N_REF_PAD + rbeg - splice->tr->beg, splice->vcf.pos - rbeg, &splice->kref);
704 roff = 0;
705 }
706 else
707 roff = rbeg - splice->vcf.pos;
708 #if XDBG
709 fprintf(bcftools_stderr,"r1: %s roff=%d\n",splice->kref.s,roff);
710 #endif
711
712 if ( roff < splice->vcf.rlen && splice->kref.l < rlen )
713 {
714 int len = splice->vcf.rlen - roff; // len still available in vcf.ref
715 if ( len > rlen - splice->kref.l ) len = rlen - splice->kref.l; // how much of ref allele is still needed
716 kputsn(splice->vcf.ref + roff, len, &splice->kref);
717 }
718 #if XDBG
719 fprintf(bcftools_stderr,"r2: %s\n",splice->kref.s);
720 #endif
721
722 uint32_t end = splice->vcf.pos + splice->vcf.rlen; // position just after the ref allele
723 if ( splice->kref.l < rlen )
724 {
725 if ( end + rlen - splice->kref.l - 1 > splice->tr->end ) // trim, the requested sequence is too long (could be extended, see N_REF_PAD)
726 rlen -= end + rlen - splice->kref.l - 1 - splice->tr->end;
727 if ( splice->kref.l < rlen )
728 kputsn(TSCRIPT_AUX(splice->tr)->ref + N_REF_PAD + end - splice->tr->beg, rlen - splice->kref.l, &splice->kref);
729 }
730 #if XDBG
731 fprintf(bcftools_stderr,"r3: %s\n",splice->kref.s);
732 #endif
733
734
735 int aoff;
736 if ( abeg < splice->vcf.pos )
737 {
738 assert( splice->tr->beg <= abeg );
739 kputsn(TSCRIPT_AUX(splice->tr)->ref + N_REF_PAD + abeg - splice->tr->beg, splice->vcf.pos - abeg, &splice->kalt);
740 aoff = 0;
741 }
742 else
743 aoff = abeg - splice->vcf.pos;
744 #if XDBG
745 fprintf(bcftools_stderr,"a1: %s aoff=%d\n",splice->kalt.s,aoff);
746 #endif
747
748 if ( aoff < splice->vcf.alen && splice->kalt.l < alen )
749 {
750 int len = splice->vcf.alen - aoff; // len still available in vcf.alt
751 if ( len > alen - splice->kalt.l ) len = alen - splice->kalt.l; // how much of alt allele is still needed
752 kputsn(splice->vcf.alt + aoff, len, &splice->kalt);
753 aoff -= len;
754 }
755 if ( aoff < 0 ) aoff = 0;
756 else aoff--;
757 #if XDBG
758 fprintf(bcftools_stderr,"a2: %s aoff=%d\n",splice->kalt.s,aoff);
759 #endif
760
761 end = splice->vcf.pos + splice->vcf.rlen; // position just after the ref allele
762 if ( splice->kalt.l < alen )
763 {
764 if ( end + alen + aoff - splice->kalt.l - 1 > splice->tr->end ) // trim, the requested sequence is too long
765 alen -= end + alen + aoff - splice->kalt.l - 1 - splice->tr->end;
766 if ( alen > 0 && alen > splice->kalt.l )
767 kputsn(TSCRIPT_AUX(splice->tr)->ref + aoff + N_REF_PAD + end - splice->tr->beg, alen - splice->kalt.l, &splice->kalt);
768 }
769 #if XDBG
770 fprintf(bcftools_stderr,"a3: %s\n",splice->kalt.s);
771 fprintf(bcftools_stderr," [%s]\n [%s]\n\n",splice->kref.s,splice->kalt.s);
772 #endif
773 }
774 void csq_stage(args_t *args, csq_t *csq, bcf1_t *rec);
775 static inline int csq_stage_utr(args_t *args, regitr_t *itr, bcf1_t *rec, uint32_t trid, uint32_t type, int ial)
776 {
777 while ( regitr_overlap(itr) )
778 {
779 gf_utr_t *utr = regitr_payload(itr, gf_utr_t*);
780 gf_tscript_t *tr = utr->tr;
781 if ( tr->id != trid ) continue;
782 csq_t csq;
783 memset(&csq, 0, sizeof(csq_t));
784 csq.pos = rec->pos;
785 csq.type.type = (utr->which==prime5 ? CSQ_UTR5 : CSQ_UTR3) | type;
786 csq.type.biotype = tr->type;
787 csq.type.strand = tr->strand;
788 csq.type.trid = tr->id;
789 csq.type.vcf_ial = ial;
790 csq.type.gene = tr->gene->name;
791 csq_stage(args, &csq, rec);
792 return csq.type.type;
793 }
794 return 0;
795 }
796 static inline void csq_stage_splice(args_t *args, bcf1_t *rec, gf_tscript_t *tr, uint32_t type, int ial)
797 {
798 #if XDBG
799 fprintf(bcftools_stderr,"csq_stage_splice %d: type=%d\n",(int)rec->pos+1,type);
800 #endif
801 if ( !type ) return;
802 csq_t csq;
803 memset(&csq, 0, sizeof(csq_t));
804 csq.pos = rec->pos;
805 csq.type.type = type;
806 csq.type.biotype = tr->type;
807 csq.type.strand = tr->strand;
808 csq.type.trid = tr->id;
809 csq.type.vcf_ial = ial;
810 csq.type.gene = tr->gene->name;
811 csq_stage(args, &csq, rec);
812 }
813 static inline const char *drop_chr_prefix(args_t *args, const char *chr)
814 {
815 if ( !args->unify_chr_names ) return chr;
816 if ( !strncasecmp("chr",chr,3) ) return chr+3;
817 return chr;
818 }
819 static inline const char *add_chr_prefix(args_t *args, const char *chr)
820 {
821 if ( !args->unify_chr_names ) return chr;
822 int len = strlen(chr);
823 hts_expand(char,len+4,args->mchr_name,args->chr_name);
824 memcpy(args->chr_name,"chr",3);
825 memcpy(args->chr_name+3,chr,len+1);
826 return args->chr_name;
827 }
828 static inline int splice_csq_ins(args_t *args, splice_t *splice, uint32_t ex_beg, uint32_t ex_end)
829 {
830 // coordinates that matter for consequences, eg AC>ACG trimmed to C>CG, 1bp
831 // before and after the inserted bases
832 if ( splice->tbeg || splice->vcf.ref[0]!=splice->vcf.alt[0] )
833 {
834 splice->ref_beg = splice->vcf.pos + splice->tbeg - 1;
835 splice->ref_end = splice->vcf.pos + splice->vcf.rlen - splice->tend;
836 }
837 else
838 {
839 if ( splice->tend ) splice->tend--;
840 splice->ref_beg = splice->vcf.pos;
841 splice->ref_end = splice->vcf.pos + splice->vcf.rlen - splice->tend;
842 }
843 #if XDBG
844 fprintf(bcftools_stderr,"ins: %s>%s .. ex=%d,%d beg,end=%d,%d tbeg,tend=%d,%d check_utr=%d start,stop,beg,end=%d,%d,%d,%d\n", splice->vcf.ref,splice->vcf.alt,ex_beg,ex_end,splice->ref_beg,splice->ref_end,splice->tbeg,splice->tend,splice->check_utr,splice->check_start,splice->check_stop,splice->check_region_beg,splice->check_region_end);
845 #endif
846
847 int ret;
848 if ( splice->ref_beg >= ex_end ) // fully outside, beyond the exon
849 {
850 if ( splice->check_utr )
851 {
852 regitr_t *itr = regitr_init(NULL);
853 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,splice->vcf.rec));
854 if ( regidx_overlap(args->idx_utr,chr,splice->ref_beg+1,splice->ref_beg+1, itr) ) // adjacent utr
855 {
856 ret = csq_stage_utr(args, itr, splice->vcf.rec, splice->tr->id, splice->csq, splice->vcf.ial);
857 if ( ret!=0 )
858 {
859 regitr_destroy(itr);
860 return SPLICE_OUTSIDE; // overlaps utr
861 }
862 }
863 regitr_destroy(itr);
864 }
865 if ( !splice->check_region_end ) return SPLICE_OUTSIDE;
866 char *ref = NULL, *alt = NULL;
867 if ( splice->set_refalt ) // seq identity is checked only when tr->ref is available
868 {
869 splice_build_hap(splice, ex_end+1, N_SPLICE_REGION_INTRON);
870 ref = splice->kref.s, alt = splice->kalt.s;
871 }
872 if ( splice->ref_beg < ex_end + N_SPLICE_REGION_INTRON && splice->ref_end > ex_end + N_SPLICE_DONOR )
873 {
874 splice->csq |= CSQ_SPLICE_REGION;
875 if ( ref && !strncmp(ref,alt,N_SPLICE_REGION_INTRON) ) splice->csq |= CSQ_SYNONYMOUS_VARIANT;
876 }
877 if ( splice->ref_beg < ex_end + N_SPLICE_DONOR )
878 {
879 if ( splice->check_donor && splice->tr->strand==STRAND_FWD ) splice->csq |= CSQ_SPLICE_DONOR;
880 if ( splice->check_acceptor && splice->tr->strand==STRAND_REV ) splice->csq |= CSQ_SPLICE_ACCEPTOR;
881 if ( ref && !strncmp(ref,alt,N_SPLICE_DONOR) ) splice->csq |= CSQ_SYNONYMOUS_VARIANT;
882 }
883 csq_stage_splice(args, splice->vcf.rec, splice->tr, splice->csq, splice->vcf.ial);
884 return SPLICE_OUTSIDE;
885 }
886 if ( splice->ref_end < ex_beg || (splice->ref_end == ex_beg && !splice->check_region_beg) ) // fully outside, before the exon
887 {
888 if ( splice->check_utr )
889 {
890 regitr_t *itr = regitr_init(NULL);
891 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,splice->vcf.rec));
892 if ( regidx_overlap(args->idx_utr,chr,splice->ref_end-1,splice->ref_end-1, itr) ) // adjacent utr
893 {
894 ret = csq_stage_utr(args, itr, splice->vcf.rec, splice->tr->id, splice->csq, splice->vcf.ial);
895 if ( ret!=0 )
896 {
897 regitr_destroy(itr);
898 return SPLICE_OUTSIDE; // overlaps utr
899 }
900 }
901 regitr_destroy(itr);
902 }
903 if ( !splice->check_region_beg ) return SPLICE_OUTSIDE;
904 char *ref = NULL, *alt = NULL;
905 if ( splice->set_refalt ) // seq identity is checked only when tr->ref is available
906 {
907 splice_build_hap(splice, ex_beg - N_SPLICE_REGION_INTRON, N_SPLICE_REGION_INTRON);
908 ref = splice->kref.s, alt = splice->kalt.s;
909 }
910 if ( splice->ref_end > ex_beg - N_SPLICE_REGION_INTRON && splice->ref_beg < ex_beg - N_SPLICE_DONOR )
911 {
912 splice->csq |= CSQ_SPLICE_REGION;
913 if ( ref && !strncmp(ref,alt,N_SPLICE_REGION_INTRON) ) splice->csq |= CSQ_SYNONYMOUS_VARIANT;
914 }
915 if ( splice->ref_end > ex_beg - N_SPLICE_DONOR )
916 {
917 if ( splice->check_donor && splice->tr->strand==STRAND_REV ) splice->csq |= CSQ_SPLICE_DONOR;
918 if ( splice->check_acceptor && splice->tr->strand==STRAND_FWD ) splice->csq |= CSQ_SPLICE_ACCEPTOR;
919 if ( ref && !strncmp(ref+N_SPLICE_REGION_INTRON-N_SPLICE_DONOR,alt+N_SPLICE_REGION_INTRON-N_SPLICE_DONOR,N_SPLICE_DONOR) ) splice->csq |= CSQ_SYNONYMOUS_VARIANT;
920 }
921 csq_stage_splice(args, splice->vcf.rec, splice->tr, splice->csq, splice->vcf.ial);
922 return SPLICE_OUTSIDE;
923 }
924 // overlaps the exon or inside the exon
925 // possible todo: find better alignment for frameshifting variants?
926 if ( splice->ref_beg <= ex_beg + 2 ) // in the first 3bp
927 {
928 if ( splice->check_region_beg ) splice->csq |= CSQ_SPLICE_REGION;
929 if ( splice->tr->strand==STRAND_FWD ) { if ( splice->check_start ) splice->csq |= CSQ_START_LOST; }
930 else { if ( splice->check_stop ) splice->csq |= CSQ_STOP_LOST; }
931 }
932 if ( splice->ref_end > ex_end - 2 )
933 {
934 if ( splice->check_region_end ) splice->csq |= CSQ_SPLICE_REGION;
935 if ( splice->tr->strand==STRAND_REV ) { if ( splice->check_start ) splice->csq |= CSQ_START_LOST; }
936 else { if ( splice->check_stop ) splice->csq |= CSQ_STOP_LOST; }
937 }
938 if ( splice->set_refalt )
939 {
940 // Make sure the variant will not end up left aligned to avoid overlapping vcf records
941 // splice_build_hap(splice, splice->ref_beg, splice->vcf.alen - splice->tend - splice->tbeg + 1);
942 // splice->vcf.rlen -= splice->tbeg + splice->tend - 1;
943 // if ( splice->kref.l > splice->vcf.rlen ) { splice->kref.l = splice->vcf.rlen; splice->kref.s[splice->kref.l] = 0; }
944 if ( splice->ref_beg < splice->vcf.pos ) // this must have been caused by too much trimming from right
945 {
946 int dlen = splice->vcf.pos - splice->ref_beg;
947 assert( dlen==1 );
948 splice->tbeg += dlen;
949 if ( splice->tbeg + splice->tend == splice->vcf.rlen ) splice->tend -= dlen;
950 splice->ref_beg = splice->vcf.pos;
951 }
952 if ( splice->ref_end==ex_beg ) splice->tend--; // prevent zero-length ref allele
953 splice_build_hap(splice, splice->ref_beg, splice->vcf.alen - splice->tend - splice->tbeg + 1);
954 splice->vcf.rlen -= splice->tbeg + splice->tend - 1;
955 if ( splice->kref.l > splice->vcf.rlen ) { splice->kref.l = splice->vcf.rlen; splice->kref.s[splice->kref.l] = 0; }
956 }
957 csq_stage_splice(args, splice->vcf.rec, splice->tr, splice->csq, splice->vcf.ial);
958 return SPLICE_INSIDE;
959 }
960
961 int shifted_del_synonymous(args_t *args, splice_t *splice, uint32_t ex_beg, uint32_t ex_end)
962 {
963 static int small_ref_padding_warned = 0;
964 gf_tscript_t *tr = splice->tr;
965
966 // We know the VCF record overlaps the exon, but does it overlap the start codon?
967 if ( tr->strand==STRAND_REV && splice->vcf.pos + splice->vcf.rlen + 2 <= ex_end ) return 0;
968 if ( tr->strand==STRAND_FWD && splice->vcf.pos >= ex_beg + 3 ) return 0;
969
970 #if XDBG
971 fprintf(bcftools_stderr,"shifted_del_synonymous: %d-%d %s\n",ex_beg,ex_end, tr->strand==STRAND_FWD?"fwd":(tr->strand==STRAND_REV?"rev":"unk"));
972 fprintf(bcftools_stderr," %d .. %s > %s\n",splice->vcf.pos+1,splice->vcf.ref,splice->vcf.alt);
973 #endif
974
975 // is there enough ref sequence for the extension? All coordinates are 0-based
976 int ref_len = strlen(splice->vcf.ref);
977 int alt_len = strlen(splice->vcf.alt);
978 assert( ref_len > alt_len );
979 int ndel = ref_len - alt_len;
980
981 if ( tr->strand==STRAND_REV )
982 {
983 int32_t vcf_ref_end = splice->vcf.pos + ref_len - 1; // end pos of the VCF REF allele
984 int32_t tr_ref_end = splice->tr->end + N_REF_PAD; // the end pos of accessible cached ref seq
985 if ( vcf_ref_end + ndel > tr_ref_end )
986 {
987 if ( !small_ref_padding_warned )
988 {
989 fprintf(bcftools_stderr,"Warning: Could not verify synonymous start/stop at %s:%d due to small N_REF_PAD. (Improve me?)\n",bcf_seqname(args->hdr,splice->vcf.rec),splice->vcf.pos+1);
990 small_ref_padding_warned = 1;
991 }
992 return 0;
993 }
994
995 char *ptr_vcf = splice->vcf.ref + alt_len; // the first deleted base in the VCF REF allele
996 char *ptr_ref = TSCRIPT_AUX(splice->tr)->ref + N_REF_PAD + (vcf_ref_end + 1 - splice->tr->beg); // the first ref base after the ndel bases deleted
997 #if XDBG
998 fprintf(bcftools_stderr,"vcf: %s\nref: %s\n",ptr_vcf,ptr_ref);
999 #endif
1000 int i = 0;
1001 while ( ptr_vcf[i] && ptr_vcf[i]==ptr_ref[i] ) i++;
1002 if ( ptr_vcf[i] ) return 0; // the deleted sequence cannot be replaced
1003 }
1004 else if ( tr->strand==STRAND_FWD )
1005 {
1006 // STRAND_FWD
1007 int32_t vcf_block_beg = splice->vcf.pos + ref_len - 2*ndel; // the position of the first base of the ref block that could potentially replace the deletion
1008 if ( vcf_block_beg < 0 ) return 0;
1009
1010 #if XDBG
1011 fprintf(bcftools_stderr,"vcf_block_beg: %d\n",vcf_block_beg+1);
1012 #endif
1013
1014 if ( N_REF_PAD + vcf_block_beg < ex_beg )
1015 {
1016 if ( !small_ref_padding_warned )
1017 {
1018 fprintf(bcftools_stderr,"Warning: Could not verify synonymous start/stop at %s:%d due to small N_REF_PAD. (Improve me?)\n",bcf_seqname(args->hdr,splice->vcf.rec),splice->vcf.pos+1);
1019 small_ref_padding_warned = 1;
1020 }
1021 return 0;
1022 }
1023
1024 char *ptr_vcf = splice->vcf.ref + alt_len; // the first deleted base in the VCF REF allele
1025 char *ptr_ref = TSCRIPT_AUX(splice->tr)->ref + N_REF_PAD + vcf_block_beg - splice->tr->beg; // the replacement ref block
1026 #if XDBG
1027 fprintf(bcftools_stderr,"vcf: %s\nref: %s\n",ptr_vcf,ptr_ref);
1028 #endif
1029
1030 int i = 0;
1031 while ( ptr_vcf[i] && ptr_vcf[i]==ptr_ref[i] ) i++;
1032 if ( ptr_vcf[i] ) return 0; // the deleted sequence cannot be replaced
1033 }
1034
1035 return 1;
1036 }
1037
1038 static inline int splice_csq_del(args_t *args, splice_t *splice, uint32_t ex_beg, uint32_t ex_end)
1039 {
1040 if ( splice->check_start )
1041 {
1042 // check for synonymous start
1043 // test/csq/ENST00000375992/incorrect-synon-del-not-start-lost.txt
1044 // test/csq/ENST00000368801.2/start-lost.txt
1045 // test/csq/ENST00000318249.2/synonymous-start-lost.txt
1046 int is_synonymous = shifted_del_synonymous(args, splice, ex_beg, ex_end);
1047 if ( is_synonymous )
1048 {
1049 splice->csq |= CSQ_START_RETAINED;
1050 return SPLICE_OVERLAP;
1051 }
1052 }
1053
1054 // coordinates that matter for consequences, eg AC>ACG trimmed to C>CG
1055 splice->ref_beg = splice->vcf.pos + splice->tbeg - 1; // 1b before the deleted base
1056 splice->ref_end = splice->vcf.pos + splice->vcf.rlen - splice->tend - 1; // the last deleted base
1057
1058 #if XDBG
1059 fprintf(bcftools_stderr,"splice_csq_del: %s>%s .. ex=%d,%d beg,end=%d,%d tbeg,tend=%d,%d check_utr=%d start,stop,beg,end=%d,%d,%d,%d\n", splice->vcf.ref,splice->vcf.alt,ex_beg,ex_end,splice->ref_beg,splice->ref_end,splice->tbeg,splice->tend,splice->check_utr,splice->check_start,splice->check_stop,splice->check_region_beg,splice->check_region_end);
1060 #endif
1061
1062 if ( splice->ref_beg + 1 < ex_beg ) // the part before the exon; ref_beg is off by -1
1063 {
1064 if ( splice->check_region_beg )
1065 {
1066 int csq = 0;
1067 if ( splice->check_utr )
1068 {
1069 regitr_t *itr = regitr_init(NULL);
1070 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,splice->vcf.rec));
1071 if ( regidx_overlap(args->idx_utr,chr,splice->ref_beg,ex_beg-1, itr) ) // adjacent utr
1072 csq = csq_stage_utr(args, itr, splice->vcf.rec, splice->tr->id, splice->csq, splice->vcf.ial);
1073 regitr_destroy(itr);
1074 }
1075 if ( !csq )
1076 {
1077 char *ref = NULL, *alt = NULL;
1078 if ( splice->set_refalt ) // seq identity is checked only when tr->ref is available
1079 {
1080 // filling from the left does not work for ENST00000341065/frame3.vcf
1081 // CAG.GTGGCCAG CAG.GTGGCCAG
1082 // CA-.--GGCCAG vs CAG.---GCCAG
1083 // splice_build_hap(splice, ex_beg-1, -N_SPLICE_REGION_INTRON);
1084 //
1085 // filling from the right:
1086 splice_build_hap(splice, ex_beg - N_SPLICE_REGION_INTRON, N_SPLICE_REGION_INTRON);
1087 ref = splice->kref.s, alt = splice->kalt.s;
1088 }
1089 if ( splice->ref_end >= ex_beg - N_SPLICE_REGION_INTRON && splice->ref_beg < ex_beg - N_SPLICE_DONOR )
1090 {
1091 splice->csq |= CSQ_SPLICE_REGION;
1092 if ( ref && alt && !strncmp(ref,alt,N_SPLICE_REGION_INTRON) ) splice->csq |= CSQ_SYNONYMOUS_VARIANT;
1093 }
1094 if ( splice->ref_end >= ex_beg - N_SPLICE_DONOR )
1095 {
1096 if ( splice->check_donor && splice->tr->strand==STRAND_REV ) splice->csq |= CSQ_SPLICE_DONOR;
1097 if ( splice->check_acceptor && splice->tr->strand==STRAND_FWD ) splice->csq |= CSQ_SPLICE_ACCEPTOR;
1098 if ( ref && alt && !strncmp(ref+N_SPLICE_REGION_INTRON-N_SPLICE_DONOR,alt+N_SPLICE_REGION_INTRON-N_SPLICE_DONOR,N_SPLICE_DONOR) ) splice->csq |= CSQ_SYNONYMOUS_VARIANT;
1099 }
1100 }
1101 }
1102 if ( splice->ref_end >= ex_beg )
1103 {
1104 splice->tbeg = splice->ref_beg - splice->vcf.pos + 1;
1105 splice->ref_beg = ex_beg - 1;
1106 if ( splice->tbeg + splice->tend == splice->vcf.alen )
1107 {
1108 // the deletion overlaps ex_beg and cannot be easily realigned to the right
1109 if ( !splice->tend )
1110 {
1111 splice->csq |= CSQ_CODING_SEQUENCE;
1112 return SPLICE_OVERLAP;
1113 }
1114 splice->tend--;
1115 }
1116 }
1117 }
1118 if ( ex_end < splice->ref_end ) // the part after the exon
1119 {
1120 if ( splice->check_region_end )
1121 {
1122 int csq = 0;
1123 if ( splice->check_utr )
1124 {
1125 regitr_t *itr = regitr_init(NULL);
1126 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,splice->vcf.rec));
1127 if ( regidx_overlap(args->idx_utr,chr,ex_end+1,splice->ref_end, itr) ) // adjacent utr
1128 csq = csq_stage_utr(args, itr, splice->vcf.rec, splice->tr->id, splice->csq, splice->vcf.ial);
1129 regitr_destroy(itr);
1130 }
1131 if ( !csq )
1132 {
1133 char *ref = NULL, *alt = NULL;
1134 if ( splice->set_refalt ) // seq identity is checked only when tr->ref is available
1135 {
1136 splice_build_hap(splice, ex_end+1, N_SPLICE_REGION_INTRON); // ref,alt positioned at the first intron base
1137 ref = splice->kref.s, alt = splice->kalt.s;
1138 }
1139 if ( splice->ref_beg < ex_end + N_SPLICE_REGION_INTRON && splice->ref_end > ex_end + N_SPLICE_DONOR )
1140 {
1141 splice->csq |= CSQ_SPLICE_REGION;
1142 if ( ref && alt && !strncmp(ref,alt,N_SPLICE_REGION_INTRON) ) splice->csq |= CSQ_SYNONYMOUS_VARIANT;
1143 }
1144 if ( splice->ref_beg < ex_end + N_SPLICE_DONOR )
1145 {
1146 if ( splice->check_donor && splice->tr->strand==STRAND_FWD ) splice->csq |= CSQ_SPLICE_DONOR;
1147 if ( splice->check_acceptor && splice->tr->strand==STRAND_REV ) splice->csq |= CSQ_SPLICE_ACCEPTOR;
1148 if ( ref && alt && !strncmp(ref+N_SPLICE_REGION_INTRON-N_SPLICE_DONOR,alt+N_SPLICE_REGION_INTRON-N_SPLICE_DONOR,N_SPLICE_DONOR) ) splice->csq |= CSQ_SYNONYMOUS_VARIANT;
1149 }
1150 }
1151 }
1152 if ( splice->ref_beg < ex_end )
1153 {
1154 splice->tend = splice->vcf.rlen - (splice->ref_end - splice->vcf.pos + 1);
1155 splice->ref_end = ex_end;
1156 }
1157 }
1158 if ( splice->ref_end < ex_beg || splice->ref_beg >= ex_end )
1159 {
1160 csq_stage_splice(args, splice->vcf.rec, splice->tr, splice->csq, splice->vcf.ial);
1161 return SPLICE_OUTSIDE;
1162 }
1163 if ( splice->ref_beg < ex_beg + 2 ) // ref_beg is off by -1
1164 {
1165 if ( splice->check_region_beg ) splice->csq |= CSQ_SPLICE_REGION;
1166 if ( splice->tr->strand==STRAND_FWD ) { if ( splice->check_start ) splice->csq |= CSQ_START_LOST; }
1167 else { if ( splice->check_stop ) splice->csq |= CSQ_STOP_LOST; }
1168 }
1169 if ( splice->ref_end > ex_end - 3 )
1170 {
1171 if ( splice->check_region_end ) splice->csq |= CSQ_SPLICE_REGION;
1172 if ( splice->tr->strand==STRAND_REV ) { if ( splice->check_start ) splice->csq |= CSQ_START_LOST; }
1173 else { if ( splice->check_stop ) splice->csq |= CSQ_STOP_LOST; }
1174 }
1175 if ( splice->set_refalt )
1176 {
1177 if ( splice->tbeg>0 ) splice->tbeg--; //why is this?
1178 if ( splice->vcf.rlen > splice->tbeg + splice->tend && splice->vcf.alen > splice->tbeg + splice->tend )
1179 {
1180 splice->vcf.rlen -= splice->tbeg + splice->tend;
1181 splice->vcf.alen -= splice->tbeg + splice->tend;
1182 }
1183 splice->kref.l = 0; kputsn(splice->vcf.ref + splice->tbeg, splice->vcf.rlen, &splice->kref);
1184 splice->kalt.l = 0; kputsn(splice->vcf.alt + splice->tbeg, splice->vcf.alen, &splice->kalt);
1185 if ( (splice->ref_beg+1 < ex_beg && splice->ref_end >= ex_beg) || (splice->ref_beg+1 < ex_end && splice->ref_end >= ex_end) ) // ouch, ugly ENST00000409523/long-overlapping-del.vcf
1186 {
1187 int ref_beg = splice->ref_beg + splice->kalt.l - 1; // 0 for AAA>A, 1 for AAA>AC
1188 if ( ref_beg < splice->ref_end )
1189 splice->csq |= (splice->ref_end - ref_beg)%3 ? CSQ_FRAMESHIFT_VARIANT : CSQ_INFRAME_DELETION;
1190 return SPLICE_OVERLAP;
1191 }
1192 }
1193 csq_stage_splice(args, splice->vcf.rec, splice->tr, splice->csq, splice->vcf.ial);
1194 return SPLICE_INSIDE;
1195 }
1196
1197 static inline int splice_csq_mnp(args_t *args, splice_t *splice, uint32_t ex_beg, uint32_t ex_end)
1198 {
1199 // not a real variant, can be ignored: eg ACGT>ACGT
1200 if ( splice->tbeg + splice->tend == splice->vcf.rlen ) return SPLICE_VAR_REF;
1201
1202 splice->ref_beg = splice->vcf.pos + splice->tbeg;
1203 splice->ref_end = splice->vcf.pos + splice->vcf.rlen - splice->tend - 1;
1204
1205 #if XDBG
1206 fprintf(bcftools_stderr,"mnp: %s>%s .. ex=%d,%d beg,end=%d,%d tbeg,tend=%d,%d check_utr=%d start,stop,beg,end=%d,%d,%d,%d\n", splice->vcf.ref,splice->vcf.alt,ex_beg,ex_end,splice->ref_beg,splice->ref_end,splice->tbeg,splice->tend,splice->check_utr,splice->check_start,splice->check_stop,splice->check_region_beg,splice->check_region_end);
1207 #endif
1208
1209 if ( splice->ref_beg < ex_beg ) // the part before the exon
1210 {
1211 if ( splice->check_region_beg )
1212 {
1213 int csq = 0;
1214 if ( splice->check_utr )
1215 {
1216 regitr_t *itr = regitr_init(NULL);
1217 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,splice->vcf.rec));
1218 if ( regidx_overlap(args->idx_utr,chr,splice->ref_beg,ex_beg-1, itr) ) // adjacent utr
1219 csq = csq_stage_utr(args, itr, splice->vcf.rec, splice->tr->id, splice->csq, splice->vcf.ial);
1220 regitr_destroy(itr);
1221 }
1222 if ( !csq )
1223 {
1224 if ( splice->ref_end >= ex_beg - N_SPLICE_REGION_INTRON && splice->ref_beg < ex_beg - N_SPLICE_DONOR )
1225 splice->csq |= CSQ_SPLICE_REGION;
1226 if ( splice->ref_end >= ex_beg - N_SPLICE_DONOR )
1227 {
1228 if ( splice->check_donor && splice->tr->strand==STRAND_REV ) splice->csq |= CSQ_SPLICE_DONOR;
1229 if ( splice->check_acceptor && splice->tr->strand==STRAND_FWD ) splice->csq |= CSQ_SPLICE_ACCEPTOR;
1230 }
1231 }
1232 }
1233 if ( splice->ref_end >= ex_beg )
1234 {
1235 splice->tbeg = splice->ref_beg - splice->vcf.pos;
1236 splice->ref_beg = ex_beg;
1237 }
1238 }
1239 if ( ex_end < splice->ref_end ) // the part after the exon
1240 {
1241 if ( splice->check_region_end )
1242 {
1243 int csq = 0;
1244 if ( splice->check_utr )
1245 {
1246 regitr_t *itr = regitr_init(NULL);
1247 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,splice->vcf.rec));
1248 if ( regidx_overlap(args->idx_utr,chr,ex_end+1,splice->ref_end, itr) ) // adjacent utr
1249 csq = csq_stage_utr(args, itr, splice->vcf.rec, splice->tr->id, splice->csq, splice->vcf.ial);
1250 regitr_destroy(itr);
1251 }
1252 if ( !csq )
1253 {
1254 if ( splice->ref_beg <= ex_end + N_SPLICE_REGION_INTRON && splice->ref_end > ex_end + N_SPLICE_DONOR )
1255 splice->csq |= CSQ_SPLICE_REGION;
1256 if ( splice->ref_beg <= ex_end + N_SPLICE_DONOR )
1257 {
1258 if ( splice->check_donor && splice->tr->strand==STRAND_FWD ) splice->csq |= CSQ_SPLICE_DONOR;
1259 if ( splice->check_acceptor && splice->tr->strand==STRAND_REV ) splice->csq |= CSQ_SPLICE_ACCEPTOR;
1260 }
1261 }
1262 }
1263 if ( splice->ref_beg <= ex_end )
1264 {
1265 splice->tend = splice->vcf.rlen - (splice->ref_end - splice->vcf.pos + 1);
1266 splice->ref_end = ex_end;
1267 }
1268 }
1269 if ( splice->ref_end < ex_beg || splice->ref_beg > ex_end )
1270 {
1271 csq_stage_splice(args, splice->vcf.rec, splice->tr, splice->csq, splice->vcf.ial);
1272 return SPLICE_OUTSIDE;
1273 }
1274
1275 if ( splice->ref_beg < ex_beg + 3 )
1276 {
1277 if ( splice->check_region_beg ) splice->csq |= CSQ_SPLICE_REGION;
1278 if ( splice->tr->strand==STRAND_FWD ) { if ( splice->check_start ) splice->csq |= CSQ_START_LOST; }
1279 else if ( splice->tr->strand==STRAND_REV ) { if ( splice->check_stop ) splice->csq |= CSQ_STOP_LOST; }
1280 }
1281 if ( splice->ref_end > ex_end - 3 )
1282 {
1283 if ( splice->check_region_end ) splice->csq |= CSQ_SPLICE_REGION;
1284 if ( splice->tr->strand==STRAND_REV ) { if ( splice->check_start ) splice->csq |= CSQ_START_LOST; }
1285 else if ( splice->tr->strand==STRAND_FWD ) { if ( splice->check_stop ) splice->csq |= CSQ_STOP_LOST; }
1286 }
1287 if ( splice->set_refalt )
1288 {
1289 splice->vcf.rlen -= splice->tbeg + splice->tend;
1290 splice->kref.l = 0; kputsn(splice->vcf.ref + splice->tbeg, splice->vcf.rlen, &splice->kref);
1291 splice->kalt.l = 0; kputsn(splice->vcf.alt + splice->tbeg, splice->vcf.rlen, &splice->kalt);
1292 }
1293 csq_stage_splice(args, splice->vcf.rec, splice->tr, splice->csq, splice->vcf.ial);
1294 return SPLICE_INSIDE;
1295 }
1296 static inline int splice_csq(args_t *args, splice_t *splice, uint32_t ex_beg, uint32_t ex_end)
1297 {
1298 splice->vcf.alen = strlen(splice->vcf.alt);
1299
1300 int rlen1 = splice->vcf.rlen - 1, alen1 = splice->vcf.alen - 1, i = 0;
1301 splice->tbeg = 0, splice->tend = 0;
1302
1303 // trim from the right, then from the left
1304 while ( i<=rlen1 && i<=alen1 )
1305 {
1306 if ( splice->vcf.ref[rlen1-i] != splice->vcf.alt[alen1-i] ) break;
1307 i++;
1308 }
1309 splice->tend = i;
1310 rlen1 -= i, alen1 -= i, i = 0;
1311 while ( i<=rlen1 && i<=alen1 )
1312 {
1313 if ( splice->vcf.ref[i] != splice->vcf.alt[i] ) break;
1314 i++;
1315 }
1316 splice->tbeg = i;
1317
1318 // The mnp, ins and del code was split into near-identical functions for clarity and debugging;
1319 // possible todo: generalize once stable
1320 if ( splice->vcf.rlen==splice->vcf.alen ) return splice_csq_mnp(args, splice, ex_beg, ex_end);
1321 if ( splice->vcf.rlen < splice->vcf.alen ) return splice_csq_ins(args, splice, ex_beg, ex_end);
1322 if ( splice->vcf.rlen > splice->vcf.alen ) return splice_csq_del(args, splice, ex_beg, ex_end);
1323
1324 return 0;
1325 }
1326
1327
1328 // return value: 0 added, 1 overlapping variant, 2 silent discard (intronic,alt=ref)
1329 int hap_init(args_t *args, hap_node_t *parent, hap_node_t *child, gf_cds_t *cds, bcf1_t *rec, int ial)
1330 {
1331 int i;
1332 kstring_t str = {0,0,0};
1333 gf_tscript_t *tr = cds->tr;
1334 child->icds = cds->icds; // index of cds in the tscript's list of exons
1335 child->vcf_ial = ial;
1336
1337 splice_t splice;
1338 splice_init(&splice, rec);
1339 splice.tr = tr;
1340 splice.vcf.ial = ial;
1341 splice.vcf.alt = rec->d.allele[ial];
1342 splice.check_acceptor = splice.check_donor = splice.set_refalt = splice.check_utr = 1;
1343 if ( !(tr->trim & TRIM_5PRIME) )
1344 {
1345 if ( tr->strand==STRAND_FWD ) { if ( child->icds==0 ) splice.check_start = 1; }
1346 else if ( tr->strand==STRAND_REV ) { if ( child->icds==tr->ncds-1 ) splice.check_start = 1; }
1347 }
1348 if ( !(tr->trim & TRIM_3PRIME) )
1349 {
1350 if ( tr->strand==STRAND_FWD ) { if ( child->icds==tr->ncds-1 ) splice.check_stop = 1; }
1351 else if ( tr->strand==STRAND_REV ) { if ( child->icds==0 ) splice.check_stop = 1; }
1352 }
1353 if ( splice.check_start ) // do not check starts in incomplete CDS, defined as not starting with M
1354 {
1355 if ( tr->strand==STRAND_FWD ) { if ( dna2aa(TSCRIPT_AUX(tr)->ref+N_REF_PAD+cds->beg-tr->beg) != 'M' ) splice.check_start = 0; }
1356 else if ( tr->strand==STRAND_REV ) { if ( cdna2aa(TSCRIPT_AUX(tr)->ref+N_REF_PAD+cds->beg-tr->beg+cds->len-3) != 'M' ) splice.check_start = 0; }
1357 }
1358 if ( child->icds!=0 ) splice.check_region_beg = 1;
1359 if ( child->icds!=tr->ncds-1 ) splice.check_region_end = 1;
1360
1361 #if XDBG
1362 fprintf(bcftools_stderr,"\nhap_init: %d [%s][%s] check start:%d,stop:%d\n",splice.vcf.pos+1,splice.vcf.ref,splice.vcf.alt,splice.check_start,splice.check_stop);
1363 #endif
1364 int ret = splice_csq(args, &splice, cds->beg, cds->beg + cds->len - 1);
1365 #if XDBG
1366 fprintf(bcftools_stderr,"cds splice_csq: %d [%s][%s] .. beg,end=%d %d, ret=%d, csq=%d\n\n",splice.vcf.pos+1,splice.kref.s,splice.kalt.s,splice.ref_beg+1,splice.ref_end+1,ret,splice.csq);
1367 #endif
1368
1369 if ( ret==SPLICE_VAR_REF ) return 2; // not a variant, eg REF=CA ALT=CA
1370 if ( ret==SPLICE_OUTSIDE || ret==SPLICE_OVERLAP || splice.csq==CSQ_START_LOST ) // not a coding csq
1371 {
1372 free(splice.kref.s);
1373 free(splice.kalt.s);
1374
1375 if ( !splice.csq ) return 2; // fully intronic, no csq
1376
1377 // splice_region/acceptor/donor
1378 child->seq = NULL;
1379 child->sbeg = 0;
1380 child->rbeg = rec->pos;
1381 child->rlen = 0;
1382 child->dlen = 0;
1383 kputs(rec->d.allele[0],&str);
1384 kputc('>',&str);
1385 kputs(rec->d.allele[ial],&str);
1386 child->var = str.s;
1387 child->type = HAP_SSS;
1388 child->csq = splice.csq;
1389 child->rec = rec;
1390 return 0;
1391 }
1392 if ( splice.csq & CSQ_SYNONYMOUS_VARIANT ) splice.csq &= ~CSQ_SYNONYMOUS_VARIANT; // synonymous&splice,frame could become synonymous&frame,splice
1393
1394 int dbeg = 0;
1395 if ( splice.ref_beg < cds->beg )
1396 {
1397 // The vcf record overlaps the exon boundary, but the variant itself
1398 // should fit inside since we are here. This will need more work.
1399 // #1475227917
1400 dbeg = cds->beg - splice.ref_beg;
1401 splice.kref.l -= dbeg;
1402 splice.ref_beg = cds->beg;
1403 assert( dbeg <= splice.kalt.l );
1404 }
1405
1406 assert( parent->type!=HAP_SSS );
1407 if ( parent->type==HAP_CDS )
1408 {
1409 i = parent->icds;
1410 if ( i!=cds->icds )
1411 {
1412 // the variant is on a new exon, finish up the previous
1413 int len = tr->cds[i]->len - parent->rbeg - parent->rlen + tr->cds[i]->beg;
1414 if ( len > 0 )
1415 kputsn_(TSCRIPT_AUX(tr)->ref + N_REF_PAD + parent->rbeg + parent->rlen - tr->beg, len, &str);
1416 }
1417
1418 // append any skipped non-variant exons
1419 while ( ++i < cds->icds )
1420 kputsn_(TSCRIPT_AUX(tr)->ref + N_REF_PAD + tr->cds[i]->beg - tr->beg, tr->cds[i]->len, &str);
1421
1422 if ( parent->icds==child->icds )
1423 {
1424 int len = splice.ref_beg - parent->rbeg - parent->rlen;
1425 if ( len < 0 ) // overlapping variants
1426 {
1427 free(str.s);
1428 free(splice.kref.s);
1429 free(splice.kalt.s);
1430 return 1;
1431 }
1432 kputsn_(TSCRIPT_AUX(tr)->ref + N_REF_PAD + parent->rbeg + parent->rlen - tr->beg, len, &str);
1433 }
1434 else
1435 kputsn_(TSCRIPT_AUX(tr)->ref + N_REF_PAD + cds->beg - tr->beg, splice.ref_beg - cds->beg, &str);
1436 }
1437 kputs(splice.kalt.s + dbeg, &str);
1438
1439 child->seq = str.s;
1440 child->sbeg = cds->pos + (splice.ref_beg - cds->beg);
1441 child->rbeg = splice.ref_beg;
1442 child->rlen = splice.kref.l;
1443 child->type = HAP_CDS;
1444 child->prev = parent;
1445 child->rec = rec;
1446 child->csq = splice.csq;
1447
1448 // set vlen and the "ref>alt" string
1449 {
1450 int rlen = strlen(rec->d.allele[0]);
1451 int alen = strlen(rec->d.allele[ial]);
1452 child->dlen = alen - rlen;
1453 child->var = (char*) malloc(rlen+alen+2);
1454 memcpy(child->var,rec->d.allele[0],rlen);
1455 child->var[rlen] = '>';
1456 memcpy(child->var+rlen+1,rec->d.allele[ial],alen);
1457 child->var[rlen+alen+1] = 0;
1458 }
1459
1460 // yuck, the whole CDS is modified/deleted, not ready for this, todo.
1461 if ( child->rbeg + child->rlen > cds->beg + cds->len )
1462 {
1463 child->type = HAP_SSS;
1464 if ( !child->csq ) child->csq |= CSQ_CODING_SEQUENCE; // hack, specifically for ENST00000390520/deletion-overlap.vcf
1465 }
1466
1467
1468 free(splice.kref.s);
1469 free(splice.kalt.s);
1470 return 0;
1471 }
1472 void hap_destroy(hap_node_t *hap)
1473 {
1474 int i;
1475 for (i=0; i<hap->nchild; i++)
1476 if ( hap->child[i] ) hap_destroy(hap->child[i]);
1477 for (i=0; i<hap->mcsq_list; i++) free(hap->csq_list[i].type.vstr.s);
1478 free(hap->csq_list);
1479 free(hap->child);
1480 free(hap->cur_child);
1481 free(hap->seq);
1482 free(hap->var);
1483 free(hap);
1484 }
1485
1486
1487 /*
1488 ref: spliced reference and its length (ref.l)
1489 seq: part of the spliced query transcript on the reference strand to translate, its
1490 length (seq.l) and the total length of the complete transcript (seq.m)
1491 sbeg: seq offset within the spliced query transcript
1492 rbeg: seq offset within ref, 0-based
1493 rend: last base of seq within ref, plus one. If seq does not contain indels, it is rend=rbeg+seq->l
1494 strand: coding strand - 0:rev, 1:fwd
1495 tseq: translated sequence (aa)
1496 fill: frameshift, fill until the end (strand=fwd) or from the start (strand=rev)
1497 */
1498 void cds_translate(kstring_t *_ref, kstring_t *_seq, uint32_t sbeg, uint32_t rbeg, uint32_t rend, int strand, kstring_t *tseq, int fill)
1499 {
1500 #if XDBG
1501 fprintf(bcftools_stderr,"\ntranslate: %d %d %d fill=%d seq.l=%d\n",sbeg,rbeg,rend,fill,(int)_seq->l);
1502 #endif
1503 char tmp[3], *codon, *end;
1504 int i, len, npad;
1505
1506 kstring_t ref = *_ref;
1507 kstring_t seq = *_seq;
1508
1509 tseq->l = 0;
1510 if ( !seq.l )
1511 {
1512 kputc('?', tseq);
1513 return;
1514 }
1515
1516 #define DBG 0
1517 #if DBG
1518 fprintf(bcftools_stderr,"translate: sbeg,rbeg,rend=%d %d %d fill=%d seq.l=%d\n",sbeg,rbeg,rend,fill,(int)_seq->l);
1519 fprintf(bcftools_stderr," ref: l=%d %s\n", (int)ref.l,ref.s);
1520 fprintf(bcftools_stderr," seq: l=%d m=%d ", (int)seq.l,(int)seq.m);
1521 for (i=0; i<seq.l; i++) fprintf(bcftools_stderr,"%c",seq.s[i]); fprintf(bcftools_stderr,"\n");
1522 fprintf(bcftools_stderr," sbeg,rbeg,rend: %d,%d,%d\n", sbeg,rbeg,rend);
1523 fprintf(bcftools_stderr," strand,fill: %d,%d\n", strand,fill);
1524 #endif
1525
1526 if ( strand==STRAND_FWD )
1527 {
1528 // left padding
1529 npad = sbeg % 3;
1530 #if DBG>1
1531 fprintf(bcftools_stderr," npad: %d\n",npad);
1532 #endif
1533 assert( npad<=rbeg );
1534
1535 for (i=0; i<npad; i++)
1536 tmp[i] = ref.s[rbeg+i-npad+N_REF_PAD];
1537 for (; i<3 && i-npad<seq.l; i++)
1538 tmp[i] = seq.s[i-npad];
1539 len = seq.l - i + npad; // the remaining length of padded sseq
1540 #if DBG>1
1541 fprintf(bcftools_stderr,"\t i=%d\n", i);
1542 #endif
1543 if ( i==3 )
1544 {
1545 kputc_(dna2aa(tmp), tseq);
1546 #if DBG>1
1547 fprintf(bcftools_stderr,"[1]%c%c%c\n",tmp[0],tmp[1],tmp[2]);
1548 #endif
1549 codon = seq.s + 3 - npad; // next codon
1550 end = codon + len - 1 - (len % 3); // last position of a valid codon
1551 while ( codon < end )
1552 {
1553 kputc_(dna2aa(codon), tseq);
1554 #if DBG>1
1555 fprintf(bcftools_stderr,"[2]%c%c%c\n",codon[0],codon[1],codon[2]);
1556 #endif
1557 codon += 3;
1558 }
1559 end = seq.s + seq.l - 1;
1560 for (i=0; codon+i<=end; i++) tmp[i] = codon[i];
1561 }
1562
1563 // right padding
1564 codon = ref.s + rend + N_REF_PAD;
1565 if ( i>0 )
1566 {
1567 #if DBG>1
1568 if(i==1)fprintf(bcftools_stderr,"[3]%c\n",tmp[0]);
1569 if(i==2)fprintf(bcftools_stderr,"[3]%c%c\n",tmp[0],tmp[1]);
1570 #endif
1571 for (; i<3; i++)
1572 {
1573 tmp[i] = *codon;
1574 codon++;
1575 }
1576 kputc_(dna2aa(tmp), tseq);
1577 #if DBG>1
1578 fprintf(bcftools_stderr,"[4]%c%c%c\n",tmp[0],tmp[1],tmp[2]);
1579 #endif
1580 }
1581 if ( fill!=0 )
1582 {
1583 end = ref.s + ref.l - N_REF_PAD;
1584 while ( codon+3 <= end )
1585 {
1586 kputc_(dna2aa(codon), tseq);
1587 #if DBG>1
1588 fprintf(bcftools_stderr,"[5]%c%c%c\t%c\n",codon[0],codon[1],codon[2],dna2aa(codon));
1589 #endif
1590 codon += 3;
1591 }
1592 }
1593 }
1594 else if ( strand==STRAND_REV )
1595 {
1596 // right padding - number of bases to take from ref
1597 npad = (seq.m - (sbeg + seq.l)) % 3;
1598 #if DBG>1
1599 fprintf(bcftools_stderr," npad: %d\n",npad);
1600 #endif
1601 if ( !(npad>=0 && sbeg+seq.l+npad<=seq.m) ) fprintf(bcftools_stderr,"sbeg=%d seq.l=%d seq.m=%d npad=%d\n",sbeg,(int)seq.l,(int)seq.m,npad);
1602 assert( npad>=0 && sbeg+seq.l+npad<=seq.m ); // todo: first codon on the rev strand
1603
1604 if ( npad==2 )
1605 {
1606 tmp[1] = ref.s[rend+N_REF_PAD];
1607 tmp[2] = ref.s[rend+N_REF_PAD+1];
1608 i = 0;
1609 }
1610 else if ( npad==1 )
1611 {
1612 tmp[2] = ref.s[rend+N_REF_PAD];
1613 i = 1;
1614 }
1615 else
1616 i = 2;
1617
1618 end = seq.s + seq.l;
1619 for (; i>=0 && end>seq.s; i--) tmp[i] = *(--end);
1620 #if DBG>1
1621 fprintf(bcftools_stderr,"\t i=%d\n", i);
1622 if(i==1)fprintf(bcftools_stderr,"[0] %c\n",tmp[2]);
1623 if(i==0)fprintf(bcftools_stderr,"[0] %c%c\n",tmp[1],tmp[2]);
1624 #endif
1625 if ( i==-1 )
1626 {
1627 #if DBG>1
1628 fprintf(bcftools_stderr,"[1]%c%c%c\t%c\n",tmp[0],tmp[1],tmp[2], cdna2aa(tmp));
1629 #endif
1630 kputc_(cdna2aa(tmp), tseq);
1631 codon = end - 3;
1632 while ( codon >= seq.s )
1633 {
1634 kputc_(cdna2aa(codon), tseq);
1635 #if DBG>1
1636 fprintf(bcftools_stderr,"[2]%c%c%c\t%c\n",codon[0],codon[1],codon[2], cdna2aa(codon));
1637 #endif
1638 codon -= 3;
1639 }
1640 if ( seq.s-codon==2 )
1641 {
1642 tmp[2] = seq.s[0];
1643 i = 1;
1644 }
1645 else if ( seq.s-codon==1 )
1646 {
1647 tmp[1] = seq.s[0];
1648 tmp[2] = seq.s[1];
1649 i = 0;
1650 }
1651 else
1652 i = -1;
1653 #if DBG>1
1654 if(i==1)fprintf(bcftools_stderr,"[3] %c\n",tmp[2]);
1655 if(i==0)fprintf(bcftools_stderr,"[3] %c%c\n",tmp[1],tmp[2]);
1656 #endif
1657 }
1658 // left padding
1659 end = ref.s + N_REF_PAD + rbeg;
1660 if ( i>=0 )
1661 {
1662 for (; i>=0 && end>=ref.s; i--) tmp[i] = *(--end);
1663 kputc_(cdna2aa(tmp), tseq);
1664 #if DBG>1
1665 fprintf(bcftools_stderr,"[4]%c%c%c\t%c\n",tmp[0],tmp[1],tmp[2],cdna2aa(tmp));
1666 #endif
1667 }
1668 if ( fill!=0 )
1669 {
1670 codon = end - 3;
1671 while ( codon >= ref.s + N_REF_PAD )
1672 {
1673 kputc_(cdna2aa(codon), tseq);
1674 #if DBG>1
1675 fprintf(bcftools_stderr,"[5]%c%c%c\t%c\n",codon[0],codon[1],codon[2],cdna2aa(codon));
1676 #endif
1677 codon -= 3;
1678 }
1679 }
1680 }
1681 else error("Should not happen: %d\n", strand);
1682 kputc_(0,tseq); tseq->l--;
1683 #if DBG
1684 fprintf(bcftools_stderr," tseq: %s\n", tseq->s);
1685 #endif
1686 }
1687
1688 void tscript_splice_ref(gf_tscript_t *tr)
1689 {
1690 int i, len = 0;
1691 for (i=0; i<tr->ncds; i++)
1692 len += tr->cds[i]->len;
1693
1694 TSCRIPT_AUX(tr)->nsref = len + 2*N_REF_PAD;
1695 TSCRIPT_AUX(tr)->sref = (char*) malloc(len + 1 + 2*N_REF_PAD);
1696 len = 0;
1697
1698 memcpy(TSCRIPT_AUX(tr)->sref, TSCRIPT_AUX(tr)->ref + tr->cds[0]->beg - tr->beg, N_REF_PAD);
1699 len += N_REF_PAD;
1700
1701 for (i=0; i<tr->ncds; i++)
1702 {
1703 memcpy(TSCRIPT_AUX(tr)->sref + len, TSCRIPT_AUX(tr)->ref + N_REF_PAD + tr->cds[i]->beg - tr->beg, tr->cds[i]->len);
1704 len += tr->cds[i]->len;
1705 }
1706 memcpy(TSCRIPT_AUX(tr)->sref + len, TSCRIPT_AUX(tr)->ref + N_REF_PAD + tr->cds[tr->ncds-1]->beg - tr->beg, N_REF_PAD);
1707 len += N_REF_PAD;
1708
1709 TSCRIPT_AUX(tr)->sref[len] = 0;
1710 }
1711
1712 // returns: 0 if consequence was added, 1 if it already exists or could not be added
1713 int csq_push(args_t *args, csq_t *csq, bcf1_t *rec)
1714 {
1715 #if XDBG
1716 fprintf(bcftools_stderr,"csq_push: %d .. %d\n",(int)rec->pos+1,csq->type.type);
1717 #endif
1718 khint_t k = kh_get(pos2vbuf, args->pos2vbuf, (int)csq->pos);
1719 vbuf_t *vbuf = (k == kh_end(args->pos2vbuf)) ? NULL : kh_val(args->pos2vbuf, k);
1720 if ( !vbuf ) error("This should not happen. %s:%d %s\n",bcf_seqname(args->hdr,rec),csq->pos+1,csq->type.vstr.s);
1721
1722 int i;
1723 for (i=0; i<vbuf->n; i++)
1724 if ( vbuf->vrec[i]->line==rec ) break;
1725 if ( i==vbuf->n ) error("This should not happen.. %s:%d %s\n", bcf_seqname(args->hdr,rec),csq->pos+1,csq->type.vstr.s);
1726 vrec_t *vrec = vbuf->vrec[i];
1727
1728 // if the variant overlaps donor/acceptor and also splice region, report only donor/acceptor
1729 if ( csq->type.type & CSQ_SPLICE_REGION && csq->type.type & (CSQ_SPLICE_DONOR|CSQ_SPLICE_ACCEPTOR) )
1730 csq->type.type &= ~CSQ_SPLICE_REGION;
1731
1732 if ( csq->type.type & CSQ_PRINTED_UPSTREAM )
1733 {
1734 for (i=0; i<vrec->nvcsq; i++)
1735 {
1736 // Same as below, to avoid records like
1737 // 3630 .. @3632,stop_lost|AL627309.1|ENST00000423372|protein_coding|-
1738 // 3632 .. stop_lost|AL627309.1|ENST00000423372|protein_coding|-|260*>260G|3630T>A+3632A>C
1739 if ( csq->type.type&CSQ_START_STOP && vrec->vcsq[i].type&CSQ_START_STOP )
1740 {
1741 vrec->vcsq[i] = csq->type;
1742 goto exit_duplicate;
1743 }
1744 if ( !(vrec->vcsq[i].type & CSQ_PRINTED_UPSTREAM) ) continue;
1745 if ( csq->type.ref != vrec->vcsq[i].ref ) continue;
1746 goto exit_duplicate;
1747 }
1748 }
1749 else if ( csq->type.type & CSQ_COMPOUND )
1750 {
1751 for (i=0; i<vrec->nvcsq; i++)
1752 {
1753 if ( csq->type.trid != vrec->vcsq[i].trid && (csq->type.type|vrec->vcsq[i].type)&CSQ_PRN_TSCRIPT ) continue;
1754 if ( csq->type.biotype != vrec->vcsq[i].biotype ) continue;
1755 if ( csq->type.gene != vrec->vcsq[i].gene ) continue;
1756 if ( csq->type.vcf_ial != vrec->vcsq[i].vcf_ial ) continue;
1757 if ( (csq->type.type&CSQ_UPSTREAM_STOP)^(vrec->vcsq[i].type&CSQ_UPSTREAM_STOP) ) continue; // both must or mustn't have upstream_stop
1758 if ( csq->type.vstr.s || vrec->vcsq[i].vstr.s )
1759 {
1760 // This is a bit hacky, but we want a simpler and more predictable output. The splice_csq() function
1761 // can trigger stop/start events based on indel overlap, then another stop/start event can be triggered
1762 // from add_csq() or test_cds_local() based on sequence comparison, and on output we could find two
1763 // consequences:
1764 // stop_lost|AL627309.1|ENST00000423372|protein_coding|-
1765 // stop_lost&inframe_insertion|AL627309.1|ENST00000423372|protein_coding|-|260*>260CL|3630T>TAAA
1766 if ( !csq->type.vstr.s || !vrec->vcsq[i].vstr.s )
1767 {
1768 if ( csq->type.type&CSQ_START_STOP && vrec->vcsq[i].type&CSQ_START_STOP )
1769 {
1770 vrec->vcsq[i].type |= csq->type.type;
1771
1772 // remove stop_lost&synonymous if stop_retained set
1773 if ( vrec->vcsq[i].type&CSQ_STOP_RETAINED )
1774 vrec->vcsq[i].type &= ~(CSQ_STOP_LOST|CSQ_SYNONYMOUS_VARIANT);
1775
1776 if ( !vrec->vcsq[i].vstr.s ) vrec->vcsq[i].vstr = csq->type.vstr;
1777 goto exit_duplicate;
1778 }
1779 continue;
1780 }
1781 if ( strcmp(csq->type.vstr.s,vrec->vcsq[i].vstr.s) ) continue;
1782 }
1783 vrec->vcsq[i].type |= csq->type.type;
1784 goto exit_duplicate;
1785 }
1786 }
1787 else
1788 {
1789 for (i=0; i<vrec->nvcsq; i++)
1790 {
1791 if ( csq->type.trid != vrec->vcsq[i].trid && (csq->type.type|vrec->vcsq[i].type)&CSQ_PRN_TSCRIPT) continue;
1792 if ( csq->type.biotype != vrec->vcsq[i].biotype ) continue;
1793 if ( !(vrec->vcsq[i].type & CSQ_COMPOUND) )
1794 {
1795 vrec->vcsq[i].type |= csq->type.type;
1796 goto exit_duplicate;
1797 }
1798 if ( vrec->vcsq[i].type==(vrec->vcsq[i].type|csq->type.type) ) goto exit_duplicate;
1799 }
1800 }
1801 // no such csq yet in this vcf record
1802 csq->vrec = vrec;
1803 csq->idx = vrec->nvcsq++;
1804 hts_expand0(vcsq_t, vrec->nvcsq, vrec->mvcsq, vrec->vcsq);
1805 vrec->vcsq[i] = csq->type;
1806 return 0;
1807
1808 exit_duplicate:
1809 csq->vrec = vrec;
1810 csq->idx = i;
1811 return 1;
1812 }
1813
1814 // soff .. position of the variant within the trimmed query transcript
1815 // sbeg .. position of the variant within the query transcript
1816 // rbeg .. position on the reference transcript (if there are no indels, then rbeg=send)
1817 // rpos .. VCF position
1818 #define node2soff(i) (hap->stack[i].slen - (hap->stack[i].node->rlen + hap->stack[i].node->dlen))
1819 #define node2sbeg(i) (hap->sbeg + node2soff(i))
1820 #define node2send(i) (hap->sbeg + hap->stack[i].slen)
1821 #define node2rbeg(i) (hap->stack[i].node->sbeg)
1822 #define node2rend(i) (hap->stack[i].node->sbeg + hap->stack[i].node->rlen)
1823 #define node2rpos(i) (hap->stack[i].node->rec->pos)
1824
1825 void kput_vcsq(args_t *args, vcsq_t *csq, kstring_t *str)
1826 {
1827 // Remove start/stop from incomplete CDS, but only if there is another
1828 // consequence as something must be reported
1829 if ( csq->type & CSQ_INCOMPLETE_CDS && (csq->type & ~(CSQ_START_STOP|CSQ_INCOMPLETE_CDS|CSQ_UPSTREAM_STOP)) ) csq->type &= ~(CSQ_START_STOP|CSQ_INCOMPLETE_CDS);
1830
1831 // Remove missense from start/stops
1832 if ( csq->type & CSQ_START_STOP && csq->type & CSQ_MISSENSE_VARIANT ) csq->type &= ~CSQ_MISSENSE_VARIANT;
1833
1834 if ( csq->type & CSQ_PRINTED_UPSTREAM && csq->ref )
1835 {
1836 kputc_('@',str);
1837 kputw(csq->ref->pos+1, str);
1838 return;
1839 }
1840 if ( csq->type & CSQ_UPSTREAM_STOP )
1841 kputc_('*',str);
1842
1843 int has_csq = 0, i, n = sizeof(csq_strings)/sizeof(char*);
1844 for (i=1; i<n; i++)
1845 if ( csq_strings[i] && csq->type&(1<<i) ) { has_csq = 1; kputs(csq_strings[i],str); break; }
1846 i++;
1847 for (; i<n; i++)
1848 if ( csq_strings[i] && csq->type&(1<<i) ) { has_csq = 1; kputc_('&',str); kputs(csq_strings[i],str); }
1849
1850 if ( (csq->biotype==GF_NMD) && (csq->type & CSQ_PRN_NMD) )
1851 {
1852 if ( has_csq ) kputc_('&',str); // just in case, this should always be true
1853 kputs("NMD_transcript",str);
1854 }
1855
1856 kputc_('|', str);
1857 if ( csq->gene ) kputs(csq->gene , str);
1858
1859 kputc_('|', str);
1860 // if ( csq->type & CSQ_PRN_TSCRIPT ) kputs(args->tscript_ids.str[csq->trid], str);
1861 if ( csq->type & CSQ_PRN_TSCRIPT ) kputs(gff_id2string(args->gff,transcript,csq->trid), str);
1862
1863 kputc_('|', str);
1864 kputs(gf_type2gff_string(csq->biotype), str);
1865
1866 if ( CSQ_PRN_STRAND(csq->type) || csq->vstr.l )
1867 kputs(csq->strand==STRAND_FWD ? "|+" : (csq->strand==STRAND_REV ? "|-" : "|."), str);
1868
1869 if ( csq->vstr.l )
1870 kputs(csq->vstr.s, str);
1871 }
1872
1873 void kprint_aa_prediction(args_t *args, int beg, kstring_t *aa, kstring_t *str)
1874 {
1875 if ( !args->brief_predictions || (int)aa->l - args->brief_predictions < 3 )
1876 kputs(aa->s, str);
1877 else
1878 {
1879 int i, len = aa->l;
1880 if ( aa->s[len-1]=='*' ) len--;
1881 for (i=0; i<len && i<args->brief_predictions; i++) kputc(aa->s[i], str);
1882 kputs("..", str);
1883 kputw(beg+len, str);
1884 }
1885 }
1886
1887 void hap_add_csq(args_t *args, hap_t *hap, hap_node_t *node, int tlen, int ibeg, int iend, int dlen, int indel)
1888 {
1889 int i;
1890 gf_tscript_t *tr = hap->tr;
1891 assert( tr->strand==STRAND_FWD || tr->strand==STRAND_REV );
1892 int ref_node = tr->strand==STRAND_FWD ? ibeg : iend;
1893 int icsq = node->ncsq_list++;
1894 hts_expand0(csq_t,node->ncsq_list,node->mcsq_list,node->csq_list);
1895 csq_t *csq = &node->csq_list[icsq];
1896 csq->pos = hap->stack[ref_node].node->rec->pos;
1897 csq->type.trid = tr->id;
1898 csq->type.vcf_ial = node->vcf_ial;
1899 csq->type.gene = tr->gene->name;
1900 csq->type.strand = tr->strand;
1901 csq->type.biotype = tr->type;
1902
1903 // only now we see the translated sequence and can determine if the stop/start changes are real
1904 int rm_csq = 0;
1905 csq->type.type = 0;
1906 for (i=ibeg; i<=iend; i++)
1907 csq->type.type |= hap->stack[i].node->csq & CSQ_COMPOUND;
1908 if ( dlen==0 && indel ) csq->type.type |= CSQ_INFRAME_ALTERING;
1909
1910 int has_upstream_stop = hap->upstream_stop;
1911 if ( hap->stack[ibeg].node->type != HAP_SSS )
1912 {
1913 // check for truncating stops
1914 for (i=0; i<hap->tref.l; i++)
1915 if ( hap->tref.s[i]=='*' ) break;
1916 if ( i!=hap->tref.l )
1917 {
1918 hap->tref.l = i+1;
1919 hap->tref.s[i+1] = 0;
1920 }
1921 for (i=0; i<hap->tseq.l; i++)
1922 if ( hap->tseq.s[i]=='*' ) break;
1923 if ( i!=hap->tseq.l )
1924 {
1925 hap->tseq.l = i+1;
1926 hap->tseq.s[i+1] = 0;
1927 hap->upstream_stop = 1;
1928 }
1929 if ( csq->type.type & CSQ_STOP_LOST )
1930 {
1931 if ( hap->tref.s[hap->tref.l-1]=='*' && hap->tref.s[hap->tref.l-1] == hap->tseq.s[hap->tseq.l-1] )
1932 {
1933 rm_csq |= CSQ_STOP_LOST;
1934 csq->type.type |= CSQ_STOP_RETAINED;
1935 }
1936 else if ( hap->tref.s[hap->tref.l-1]!='*' )
1937 {
1938 // This is CDS 3' incomplete ENSG00000173376/synon.vcf, can also be missense
1939 // We observe in real data a change to a stop, ENST00000528237/retained-stop-incomplete-cds.vcf
1940 if ( hap->tseq.s[hap->tseq.l-1] == '*' )
1941 {
1942 rm_csq |= CSQ_STOP_GAINED;
1943 csq->type.type |= CSQ_STOP_RETAINED;
1944 }
1945 else
1946 csq->type.type |= CSQ_INCOMPLETE_CDS;
1947 }
1948 }
1949 if ( csq->type.type & CSQ_START_LOST && hap->tref.s[0]!='M' )
1950 {
1951 rm_csq |= CSQ_START_LOST;
1952 csq->type.type &= ~CSQ_START_LOST;
1953 }
1954 if ( dlen!=0 )
1955 {
1956 if ( dlen%3 )
1957 csq->type.type |= CSQ_FRAMESHIFT_VARIANT;
1958 else if ( dlen<0 )
1959 csq->type.type |= CSQ_INFRAME_DELETION;
1960 else
1961 csq->type.type |= CSQ_INFRAME_INSERTION;
1962 if ( hap->tref.s[hap->tref.l-1]!='*' && hap->tseq.s[hap->tseq.l-1]=='*' )
1963 csq->type.type |= CSQ_STOP_GAINED;
1964 }
1965 else
1966 {
1967 int aa_change = 0;
1968 for (i=0; i<hap->tref.l; i++)
1969 {
1970 if ( hap->tref.s[i] == hap->tseq.s[i] ) continue;
1971 aa_change = 1;
1972 if ( hap->tref.s[i] == '*' )
1973 csq->type.type |= CSQ_STOP_LOST;
1974 else if ( hap->tseq.s[i] == '*' )
1975 csq->type.type |= CSQ_STOP_GAINED;
1976 else
1977 csq->type.type |= CSQ_MISSENSE_VARIANT;
1978 }
1979 if ( !aa_change )
1980 csq->type.type |= CSQ_SYNONYMOUS_VARIANT;
1981 }
1982 }
1983 // Check if compound inframe variants are real inframes, or if the stop codon occurs before the frameshift can be restored
1984 if ( ibeg!=iend && (csq->type.type & (CSQ_INFRAME_DELETION|CSQ_INFRAME_INSERTION|CSQ_INFRAME_ALTERING)) && hap->tseq.s[hap->tseq.l-1]=='*' )
1985 {
1986 rm_csq |= CSQ_INFRAME_DELETION | CSQ_INFRAME_INSERTION | CSQ_INFRAME_ALTERING;
1987 csq->type.type |= CSQ_FRAMESHIFT_VARIANT | CSQ_STOP_GAINED;
1988 }
1989 if ( has_upstream_stop ) csq->type.type |= CSQ_UPSTREAM_STOP;
1990 csq->type.type &= ~rm_csq;
1991
1992 if ( hap->stack[ibeg].node->type == HAP_SSS )
1993 {
1994 node->csq_list[icsq].type.type |= hap->stack[ibeg].node->csq & ~rm_csq;
1995 node->csq_list[icsq].type.ref = hap->stack[ibeg].node->rec;
1996 node->csq_list[icsq].type.biotype = tr->type;
1997 csq_push(args, node->csq_list+icsq, hap->stack[ibeg].node->rec);
1998 return;
1999 }
2000
2001 kstring_t str = node->csq_list[icsq].type.vstr;
2002 str.l = 0;
2003
2004 // create the aa variant string
2005 int aa_rbeg = tr->strand==STRAND_FWD ? node2rbeg(ibeg)/3+1 : (TSCRIPT_AUX(hap->tr)->nsref - 2*N_REF_PAD - node2rend(iend))/3+1;
2006 int aa_sbeg = tr->strand==STRAND_FWD ? node2sbeg(ibeg)/3+1 : (tlen - node2send(iend))/3+1;
2007 kputc_('|', &str);
2008 kputw(aa_rbeg, &str);
2009 kprint_aa_prediction(args,aa_rbeg,&hap->tref,&str);
2010 if ( !(csq->type.type & CSQ_SYNONYMOUS_VARIANT) )
2011 {
2012 kputc_('>', &str);
2013 kputw(aa_sbeg, &str);
2014 kprint_aa_prediction(args,aa_sbeg,&hap->tseq,&str);
2015 }
2016 kputc_('|', &str);
2017
2018 // create the dna variant string and, in case of combined variants,
2019 // insert silent CSQ_PRINTED_UPSTREAM variants
2020 for (i=ibeg; i<=iend; i++)
2021 {
2022 if ( i>ibeg ) kputc_('+', &str);
2023 kputw(node2rpos(i)+1, &str);
2024 kputs(hap->stack[i].node->var, &str);
2025 }
2026 node->csq_list[icsq].type.vstr = str;
2027 csq_push(args, node->csq_list+icsq, hap->stack[ref_node].node->rec);
2028
2029 for (i=ibeg; i<=iend; i++)
2030 {
2031 // csq are printed at one position only for combined variants, the rest is
2032 // silent and references the first
2033 if ( hap->stack[i].node->csq & ~CSQ_COMPOUND )
2034 {
2035 node->ncsq_list++;
2036 hts_expand0(csq_t,node->ncsq_list,node->mcsq_list,node->csq_list);
2037 csq_t *tmp_csq = &node->csq_list[node->ncsq_list - 1];
2038 tmp_csq->pos = hap->stack[i].node->rec->pos;
2039 tmp_csq->type.trid = tr->id;
2040 //??tmp_csq->type.vcf_ial = node->vcf_ial; .. this should not be needed for non-compound variants
2041 tmp_csq->type.gene = tr->gene->name;
2042 tmp_csq->type.strand = tr->strand;
2043 tmp_csq->type.type = hap->stack[i].node->csq & ~CSQ_COMPOUND & ~rm_csq;
2044 tmp_csq->type.biotype = tr->type;
2045 tmp_csq->type.vstr.l = 0;
2046 kputs(str.s,&tmp_csq->type.vstr);
2047 csq_push(args, tmp_csq, hap->stack[i].node->rec);
2048 }
2049 if ( i!=ref_node && (node->csq_list[icsq].type.type & CSQ_COMPOUND || !(hap->stack[i].node->csq & ~CSQ_COMPOUND)) )
2050 {
2051 node->ncsq_list++;
2052 hts_expand0(csq_t,node->ncsq_list,node->mcsq_list,node->csq_list);
2053 csq_t *tmp_csq = &node->csq_list[node->ncsq_list - 1];
2054 tmp_csq->pos = hap->stack[i].node->rec->pos;
2055 tmp_csq->type.trid = tr->id;
2056 //??tmp_csq->type.vcf_ial = node->vcf_ial; .. this should not be needed for non-compound variants
2057 tmp_csq->type.gene = tr->gene->name;
2058 tmp_csq->type.strand = tr->strand;
2059 tmp_csq->type.type = CSQ_PRINTED_UPSTREAM | hap->stack[i].node->csq;
2060 tmp_csq->type.biotype = tr->type;
2061 tmp_csq->type.ref = hap->stack[ref_node].node->rec;
2062 tmp_csq->type.vstr.l = 0;
2063 csq_push(args, tmp_csq, hap->stack[i].node->rec);
2064 }
2065 }
2066 }
2067
2068
2069 void hap_finalize(args_t *args, hap_t *hap)
2070 {
2071 gf_tscript_t *tr = hap->tr;
2072 if ( !TSCRIPT_AUX(tr)->sref )
2073 tscript_splice_ref(tr);
2074
2075 kstring_t sref;
2076 sref.s = TSCRIPT_AUX(tr)->sref;
2077 sref.l = TSCRIPT_AUX(tr)->nsref;
2078 sref.m = sref.l;
2079
2080 int istack = 0;
2081 hts_expand(hstack_t,1,hap->mstack,hap->stack);
2082
2083 hap->sseq.l = 0;
2084 hap->tseq.l = 0;
2085 hap->stack[0].node = TSCRIPT_AUX(tr)->root;
2086 hap->stack[0].ichild = -1;
2087 hap->stack[0].slen = 0;
2088 hap->stack[0].dlen = 0;
2089
2090 while ( istack>=0 )
2091 {
2092 hstack_t *stack = &hap->stack[istack];
2093 hap_node_t *node = hap->stack[istack].node;
2094 while ( ++hap->stack[istack].ichild < node->nchild )
2095 {
2096 if ( node->child[stack->ichild] ) break;
2097 }
2098 if ( stack->ichild == node->nchild ) { istack--; continue; }
2099
2100 node = node->child[stack->ichild];
2101
2102 istack++;
2103 hts_expand(hstack_t,istack+1,hap->mstack,hap->stack);
2104 stack = &hap->stack[istack-1];
2105
2106 hap->stack[istack].node = node;
2107 hap->stack[istack].ichild = -1;
2108
2109 hap->sseq.l = stack->slen;
2110 if ( node->type==HAP_CDS ) kputs(node->seq, &hap->sseq);
2111 hap->stack[istack].slen = hap->sseq.l;
2112 hap->stack[istack].dlen = hap->stack[istack-1].dlen + node->dlen;
2113
2114 if ( !node->nend ) continue; // not a leaf node
2115
2116 // The spliced sequence has been built for the current haplotype and stored
2117 // in hap->sseq. Now we break it and output as independent parts
2118
2119 kstring_t sseq;
2120 sseq.m = sref.m - 2*N_REF_PAD + hap->stack[istack].dlen; // total length of the spliced query transcript
2121 hap->upstream_stop = 0;
2122
2123 int i = 1, dlen = 0, ibeg, indel = 0;
2124 hap->sbeg = hap->stack[i].node->sbeg;
2125 assert( hap->stack[istack].node->type != HAP_SSS );
2126 if ( tr->strand==STRAND_FWD )
2127 {
2128 i = 0, ibeg = -1;
2129 while ( ++i <= istack )
2130 {
2131 assert( hap->stack[i].node->type != HAP_SSS );
2132
2133 dlen += hap->stack[i].node->dlen;
2134 if ( hap->stack[i].node->dlen ) indel = 1;
2135
2136 // This condition extends compound variants.
2137 if ( i<istack )
2138 {
2139 if ( dlen%3 ) // frameshift
2140 {
2141 if ( ibeg==-1 ) ibeg = i;
2142 continue;
2143 }
2144 // the last base of the current variant vs the first base of the next
2145 // variant: are they in the same codon? (forward strand)
2146 int icur = node2sbeg(i);
2147 int inext = node2sbeg(i+1);
2148 if ( hap->stack[i].node->dlen > 0 ) icur += hap->stack[i].node->dlen;
2149 else if ( hap->stack[i].node->dlen < 0 ) icur++;
2150 if ( icur/3 == inext/3 ) // in the same codon, can't be flushed yet
2151 {
2152 if ( ibeg==-1 ) ibeg = i;
2153 continue;
2154 }
2155 }
2156 if ( ibeg<0 ) ibeg = i;
2157
2158 int ioff = node2soff(ibeg);
2159 int icur = node2sbeg(ibeg);
2160 int rbeg = node2rbeg(ibeg);
2161 int rend = node2rend(i);
2162 int fill = dlen%3;
2163
2164 // alt
2165 if ( hap->sseq.l )
2166 {
2167 sseq.l = hap->stack[i].slen - ioff;
2168 sseq.s = hap->sseq.s + ioff;
2169 }
2170 else // splice site overlap, see #1475227917
2171 sseq.l = fill = 0;
2172 cds_translate(&sref, &sseq, icur,rbeg,rend, tr->strand, &hap->tseq, fill);
2173
2174 // ref
2175 sseq.l = node2rend(i) - rbeg;
2176 sseq.s = sref.s + N_REF_PAD + rbeg;
2177 sseq.m = sref.m - 2*N_REF_PAD;
2178 cds_translate(&sref, &sseq, rbeg,rbeg,rend, tr->strand, &hap->tref, fill);
2179 sseq.m = sref.m - 2*N_REF_PAD + hap->stack[istack].dlen;
2180
2181 hap_add_csq(args,hap,node,0, ibeg,i,dlen,indel);
2182 ibeg = -1;
2183 dlen = 0;
2184 indel = 0;
2185 }
2186 }
2187 else if ( tr->strand==STRAND_REV )
2188 {
2189 i = istack + 1, ibeg = -1;
2190 while ( --i > 0 )
2191 {
2192 assert ( hap->stack[i].node->type != HAP_SSS );
2193 dlen += hap->stack[i].node->dlen;
2194 if ( hap->stack[i].node->dlen ) indel = 1;
2195 if ( i>1 )
2196 {
2197 if ( dlen%3 )
2198 {
2199 if ( ibeg==-1 ) ibeg = i;
2200 continue;
2201 }
2202 // the last base of the current variant vs the first base of the next
2203 // variant: are they in the same codon? (reverse strand)
2204 int icur = sseq.m - 1 - node2sbeg(i);
2205 int inext = sseq.m - 1 - node2sbeg(i-1);
2206 if ( hap->stack[i].node->dlen > 0 ) icur += hap->stack[i].node->dlen - 1;
2207 else if ( hap->stack[i].node->dlen < 0 ) icur -= hap->stack[i].node->dlen;
2208 if ( hap->stack[i-1].node->dlen > 0 ) inext -= hap->stack[i-1].node->dlen;
2209 if ( icur/3 == inext/3 )
2210 {
2211 if ( ibeg==-1 ) ibeg = i;
2212 continue;
2213 }
2214 }
2215 if ( ibeg<0 ) ibeg = i;
2216 int ioff = node2soff(i);
2217 int icur = node2sbeg(i);
2218 int rbeg = node2rbeg(i);
2219 int rend = node2rend(ibeg);
2220 int fill = dlen%3;
2221
2222 // alt
2223 if ( hap->sseq.l )
2224 {
2225 sseq.l = hap->stack[ibeg].slen - ioff;
2226 sseq.s = hap->sseq.s + ioff;
2227 }
2228 else // splice site overlap, see #1475227917
2229 sseq.l = fill = 0;
2230 cds_translate(&sref, &sseq, icur,rbeg,rend, tr->strand, &hap->tseq, fill);
2231
2232 // ref
2233 sseq.l = node2rend(ibeg) - rbeg;
2234 sseq.s = sref.s + N_REF_PAD + rbeg;
2235 sseq.m = sref.m - 2*N_REF_PAD;
2236 cds_translate(&sref, &sseq, rbeg,rbeg,rend, tr->strand, &hap->tref, fill);
2237 sseq.m = sref.m - 2*N_REF_PAD + hap->stack[istack].dlen;
2238
2239 hap_add_csq(args,hap,node,sseq.m, i,ibeg,dlen,indel);
2240 ibeg = -1;
2241 dlen = 0;
2242 indel = 0;
2243 }
2244 }
2245 }
2246 }
2247
2248 static inline void csq_print_text(args_t *args, csq_t *csq, int ismpl, int ihap)
2249 {
2250 if ( csq->type.type & CSQ_PRINTED_UPSTREAM ) return;
2251
2252 char *smpl = ismpl >= 0 ? args->hdr->samples[ismpl] : "-";
2253 const char *chr = bcf_hdr_id2name(args->hdr,args->rid);
2254
2255 fprintf(args->out,"CSQ\t%s\t", smpl);
2256 if ( ihap>0 )
2257 fprintf(args->out,"%d", ihap);
2258 else
2259 fprintf(args->out,"-");
2260
2261 args->str.l = 0;
2262 kput_vcsq(args, &csq->type, &args->str);
2263 fprintf(args->out,"\t%s\t%d\t%s\n",chr,csq->pos+1,args->str.s);
2264 }
2265 static inline void hap_print_text(args_t *args, gf_tscript_t *tr, int ismpl, int ihap, hap_node_t *node)
2266 {
2267 if ( !node || !node->ncsq_list ) return;
2268
2269 char *smpl = ismpl >= 0 ? args->hdr->samples[ismpl] : "-";
2270 const char *chr = bcf_hdr_id2name(args->hdr,args->rid);
2271
2272 int i;
2273 for (i=0; i<node->ncsq_list; i++)
2274 {
2275 csq_t *csq = node->csq_list + i;
2276 if ( csq->type.type & CSQ_PRINTED_UPSTREAM ) continue;
2277 assert( csq->type.vstr.l );
2278
2279 fprintf(args->out,"CSQ\t%s\t", smpl);
2280 if ( ihap>0 )
2281 fprintf(args->out,"%d", ihap);
2282 else
2283 fprintf(args->out,"-");
2284
2285 args->str.l = 0;
2286 kput_vcsq(args, &csq->type, &args->str);
2287 fprintf(args->out,"\t%s\t%d\t%s\n",chr,csq->pos+1,args->str.s);
2288 }
2289 }
2290
2291 static inline void hap_stage_vcf(args_t *args, gf_tscript_t *tr, int ismpl, int ihap, hap_node_t *node)
2292 {
2293 if ( !node || !node->ncsq_list || ismpl<0 ) return;
2294
2295 int i;
2296 for (i=0; i<node->ncsq_list; i++)
2297 {
2298 csq_t *csq = node->csq_list + i;
2299 vrec_t *vrec = csq->vrec;
2300 int icsq2 = 2*csq->idx + ihap;
2301 if ( icsq2 >= args->ncsq2_max ) // more than ncsq2_max consequences, so can't fit it in FMT
2302 {
2303 if ( args->verbosity && (!args->ncsq2_small_warned || args->verbosity > 1) )
2304 {
2305 fprintf(bcftools_stderr,
2306 "Warning: Too many consequences for sample %s at %s:%"PRId64", keeping the first %d and skipping the rest.\n",
2307 args->hdr->samples[ismpl],bcf_hdr_id2name(args->hdr,args->rid),(int64_t) vrec->line->pos+1,csq->idx);
2308 if ( !args->ncsq2_small_warned )
2309 fprintf(bcftools_stderr," The limit can be increased by setting the --ncsq parameter. This warning is printed only once.\n");
2310 }
2311 if ( args->ncsq2_small_warned < icsq2 ) args->ncsq2_small_warned = icsq2;
2312 break;
2313 }
2314 int ival, ibit;
2315 icsq2_to_bit(icsq2, &ival,&ibit);
2316 if ( vrec->nfmt < 1 + ival ) vrec->nfmt = 1 + ival;
2317 vrec->fmt_bm[ismpl*args->nfmt_bcsq + ival] |= 1 << ibit;
2318 }
2319 }
2320
2321 void hap_flush(args_t *args, uint32_t pos)
2322 {
2323 int i,j;
2324 tr_heap_t *heap = args->active_tr;
2325 while ( heap->ndat && heap->dat[0]->end<=pos )
2326 {
2327 gf_tscript_t *tr = heap->dat[0];
2328 khp_delete(trhp, heap);
2329 args->hap->tr = tr;
2330 if ( TSCRIPT_AUX(tr)->root && TSCRIPT_AUX(tr)->root->nchild ) // normal, non-localized calling
2331 {
2332 hap_finalize(args, args->hap);
2333
2334 if ( args->output_type==FT_TAB_TEXT ) // plain text output, not a vcf
2335 {
2336 if ( args->phase==PHASE_DROP_GT )
2337 hap_print_text(args, tr, -1,0, TSCRIPT_AUX(tr)->hap[0]);
2338 else
2339 {
2340 for (i=0; i<args->smpl->n; i++)
2341 {
2342 for (j=0; j<2; j++)
2343 hap_print_text(args, tr, args->smpl->idx[i],j+1, TSCRIPT_AUX(tr)->hap[i*2+j]);
2344 }
2345 }
2346 }
2347 else if ( args->phase!=PHASE_DROP_GT )
2348 {
2349 for (i=0; i<args->smpl->n; i++)
2350 {
2351 for (j=0; j<2; j++)
2352 hap_stage_vcf(args, tr, args->smpl->idx[i],j, TSCRIPT_AUX(tr)->hap[i*2+j]);
2353 }
2354 }
2355 }
2356
2357 // mark the transcript for deletion. Cannot delete it immediately because
2358 // by-position VCF output will need them when flushed by vcf_buf_push
2359 args->nrm_tr++;
2360 hts_expand(gf_tscript_t*,args->nrm_tr,args->mrm_tr,args->rm_tr);
2361 args->rm_tr[args->nrm_tr-1] = tr;
2362 }
2363 }
2364
2365 #define SWAP(type_t, a, b) { type_t t = a; a = b; b = t; }
2366
2367 vbuf_t *vbuf_push(args_t *args, bcf1_t **rec_ptr)
2368 {
2369 int i;
2370
2371 assert(rec_ptr);
2372 bcf1_t *rec = *rec_ptr;
2373
2374 // check for duplicate records
2375 i = args->vcf_rbuf.n ? rbuf_last(&args->vcf_rbuf) : -1;
2376 if ( i<0 || args->vcf_buf[i]->vrec[0]->line->pos!=rec->pos )
2377 {
2378 // vcf record with a new pos
2379 rbuf_expand0(&args->vcf_rbuf, vbuf_t*, args->vcf_rbuf.n+1, args->vcf_buf);
2380 i = rbuf_append(&args->vcf_rbuf);
2381 if ( !args->vcf_buf[i] ) args->vcf_buf[i] = (vbuf_t*) calloc(1,sizeof(vbuf_t));
2382 args->vcf_buf[i]->n = 0;
2383 args->vcf_buf[i]->keep_until = 0;
2384 }
2385 vbuf_t *vbuf = args->vcf_buf[i];
2386 vbuf->n++;
2387 hts_expand0(vrec_t*, vbuf->n, vbuf->m, vbuf->vrec);
2388 if ( !vbuf->vrec[vbuf->n - 1] )
2389 vbuf->vrec[vbuf->n - 1] = (vrec_t*) calloc(1,sizeof(vrec_t));
2390
2391 vrec_t *vrec = vbuf->vrec[vbuf->n - 1];
2392 if ( args->phase!=PHASE_DROP_GT && args->smpl->n )
2393 {
2394 if ( !vrec->fmt_bm ) vrec->fmt_bm = (uint32_t*) calloc(args->hdr_nsmpl,sizeof(*vrec->fmt_bm) * args->nfmt_bcsq);
2395 else memset(vrec->fmt_bm,0,args->hdr_nsmpl*sizeof(*vrec->fmt_bm) * args->nfmt_bcsq);
2396 }
2397 if ( !vrec->line ) vrec->line = bcf_init1();
2398 SWAP(bcf1_t*, (*rec_ptr), vrec->line);
2399
2400 int ret;
2401 khint_t k = kh_put(pos2vbuf, args->pos2vbuf, (int)rec->pos, &ret);
2402 kh_val(args->pos2vbuf,k) = vbuf;
2403
2404 return vbuf;
2405 }
2406
2407 void vbuf_flush(args_t *args, uint32_t pos)
2408 {
2409 int i,j;
2410 while ( args->vcf_rbuf.n )
2411 {
2412 vbuf_t *vbuf;
2413 if ( !args->local_csq && args->active_tr->ndat )
2414 {
2415 // check if the first active transcript starts beyond the first buffered VCF record,
2416 // cannot output buffered VCF lines (args.vbuf) until the active transcripts are gone
2417 vbuf = args->vcf_buf[ args->vcf_rbuf.f ];
2418 if ( vbuf->keep_until > pos ) break;
2419 assert( vbuf->n );
2420 }
2421
2422 i = rbuf_shift(&args->vcf_rbuf);
2423 assert( i>=0 );
2424 vbuf = args->vcf_buf[i];
2425 int pos = vbuf->n ? vbuf->vrec[0]->line->pos : -1;
2426 for (i=0; i<vbuf->n; i++)
2427 {
2428 vrec_t *vrec = vbuf->vrec[i];
2429 if ( !args->out_fh ) // not a VCF output
2430 {
2431 vrec->nvcsq = 0;
2432 continue;
2433 }
2434 if ( !vrec->nvcsq )
2435 {
2436 if ( bcf_write(args->out_fh, args->hdr, vrec->line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname?args->output_fname:"standard output");
2437 int save_pos = vrec->line->pos;
2438 bcf_empty(vrec->line);
2439 vrec->line->pos = save_pos; // this is necessary for compound variants
2440 continue;
2441 }
2442
2443 args->str.l = 0;
2444 kput_vcsq(args, &vrec->vcsq[0], &args->str);
2445 for (j=1; j<vrec->nvcsq; j++)
2446 {
2447 kputc_(',', &args->str);
2448 kput_vcsq(args, &vrec->vcsq[j], &args->str);
2449 }
2450 bcf_update_info_string(args->hdr, vrec->line, args->bcsq_tag, args->str.s);
2451 if ( args->hdr_nsmpl )
2452 {
2453 if ( vrec->nfmt < args->nfmt_bcsq )
2454 for (j=1; j<args->hdr_nsmpl; j++)
2455 memmove(&vrec->fmt_bm[j*vrec->nfmt], &vrec->fmt_bm[j*args->nfmt_bcsq], vrec->nfmt*sizeof(*vrec->fmt_bm));
2456 bcf_update_format_int32(args->hdr, vrec->line, args->bcsq_tag, vrec->fmt_bm, args->hdr_nsmpl*vrec->nfmt);
2457 }
2458 vrec->nvcsq = 0;
2459 if ( bcf_write(args->out_fh, args->hdr, vrec->line)!=0 ) error("[%s] Error: cannot write to %s\n", __func__,args->output_fname?args->output_fname:"standard output");
2460 int save_pos = vrec->line->pos;
2461 bcf_empty(vrec->line);
2462 vrec->line->pos = save_pos;
2463 }
2464 if ( pos!=-1 )
2465 {
2466 khint_t k = kh_get(pos2vbuf, args->pos2vbuf, pos);
2467 if ( k != kh_end(args->pos2vbuf) ) kh_del(pos2vbuf, args->pos2vbuf, k);
2468 }
2469 vbuf->n = 0;
2470 }
2471 if ( args->active_tr->ndat ) return;
2472
2473 for (i=0; i<args->nrm_tr; i++)
2474 {
2475 gf_tscript_t *tr = args->rm_tr[i];
2476 tscript_t *aux = TSCRIPT_AUX(tr);
2477 if ( aux->root ) hap_destroy(aux->root);
2478 aux->root = NULL;
2479 free(aux->hap);
2480 free(aux->ref);
2481 free(aux->sref);
2482 free(aux);
2483 tr->aux = NULL;
2484 }
2485 args->nrm_tr = 0;
2486 args->ncsq_buf = 0;
2487 }
2488
2489 void tscript_init_ref(args_t *args, gf_tscript_t *tr, const char *chr)
2490 {
2491 int i, len;
2492 int pad_beg = tr->beg >= N_REF_PAD ? N_REF_PAD : tr->beg;
2493
2494 const char *tmp_chr = chr;
2495 if ( !faidx_has_seq(args->fai,tmp_chr) )
2496 {
2497 tmp_chr = drop_chr_prefix(args,chr);
2498 if ( !faidx_has_seq(args->fai,tmp_chr) ) tmp_chr = add_chr_prefix(args,chr);
2499 }
2500 TSCRIPT_AUX(tr)->ref = faidx_fetch_seq(args->fai, tmp_chr, tr->beg - pad_beg, tr->end + N_REF_PAD, &len);
2501 if ( !TSCRIPT_AUX(tr)->ref )
2502 error("faidx_fetch_seq failed %s:%d-%d\n", chr,tr->beg+1,tr->end+1);
2503
2504 int pad_end = len - (tr->end - tr->beg + 1 + pad_beg);
2505 if ( pad_beg + pad_end != 2*N_REF_PAD )
2506 {
2507 char *ref = (char*) malloc(tr->end - tr->beg + 1 + 2*N_REF_PAD + 1);
2508 for (i=0; i < N_REF_PAD - pad_beg; i++) ref[i] = 'N';
2509 memcpy(ref+i, TSCRIPT_AUX(tr)->ref, len);
2510 len += i;
2511 for (i=0; i < N_REF_PAD - pad_end; i++) ref[i+len] = 'N';
2512 ref[i+len] = 0;
2513 free(TSCRIPT_AUX(tr)->ref);
2514 TSCRIPT_AUX(tr)->ref = ref;
2515 }
2516 }
2517
2518 static void sanity_check_ref(args_t *args, gf_tscript_t *tr, bcf1_t *rec)
2519 {
2520 int vbeg = 0;
2521 int rbeg = rec->pos - tr->beg + N_REF_PAD;
2522 if ( rbeg < 0 ) { vbeg += abs(rbeg); rbeg = 0; }
2523 char *ref = TSCRIPT_AUX(tr)->ref + rbeg;
2524 char *vcf = rec->d.allele[0] + vbeg;
2525 assert( vcf - rec->d.allele[0] < strlen(rec->d.allele[0]) && ref - TSCRIPT_AUX(tr)->ref < tr->end - tr->beg + 2*N_REF_PAD );
2526 int i = 0;
2527 while ( ref[i] && vcf[i] )
2528 {
2529 if ( ref[i]!=vcf[i] && toupper(ref[i])!=toupper(vcf[i]) )
2530 error("Error: the fasta reference does not match the VCF REF allele at %s:%"PRId64" .. fasta=%c vcf=%c\n",
2531 bcf_seqname(args->hdr,rec),(int64_t) rec->pos+vbeg+1,ref[i],vcf[i]);
2532 i++;
2533 }
2534 }
2535
2536 int test_cds_local(args_t *args, bcf1_t *rec)
2537 {
2538 int i,j, ret = 0;
2539 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,rec));
2540 // note that the off-by-one extension of rlen is deliberate to account for insertions
2541 if ( !regidx_overlap(args->idx_cds,chr,rec->pos,rec->pos+rec->rlen, args->itr) ) return 0;
2542
2543 // structures to fake the normal test_cds machinery
2544 hap_node_t root, node;
2545 root.type = HAP_ROOT;
2546 kstring_t *tref = &args->hap->tref, *tseq = &args->hap->tseq;
2547
2548 while ( regitr_overlap(args->itr) )
2549 {
2550 gf_cds_t *cds = regitr_payload(args->itr,gf_cds_t*);
2551 gf_tscript_t *tr = cds->tr;
2552 if ( !GF_is_coding(tr->type) ) continue;
2553 ret = 1;
2554
2555 if ( !TSCRIPT_AUX(tr) )
2556 {
2557 tr->aux = calloc(sizeof(tscript_t),1);
2558 tscript_init_ref(args, tr, chr);
2559 tscript_splice_ref(tr);
2560 khp_insert(trhp, args->active_tr, &tr); // only to clean the reference afterwards
2561 }
2562
2563 sanity_check_ref(args, tr, rec);
2564
2565 kstring_t sref;
2566 sref.s = TSCRIPT_AUX(tr)->sref;
2567 sref.l = TSCRIPT_AUX(tr)->nsref;
2568 sref.m = sref.l;
2569
2570 for (i=1; i<rec->n_allele; i++)
2571 {
2572 if ( rec->d.allele[i][0]=='<' || rec->d.allele[i][0]=='*' ) { continue; }
2573 if ( hap_init(args, &root, &node, cds, rec, i)!=0 ) continue;
2574
2575 csq_t csq;
2576 memset(&csq, 0, sizeof(csq_t));
2577 csq.pos = rec->pos;
2578 csq.type.biotype = tr->type;
2579 csq.type.strand = tr->strand;
2580 csq.type.trid = tr->id;
2581 csq.type.vcf_ial = i;
2582 csq.type.gene = tr->gene->name;
2583
2584 int csq_type = node.csq;
2585
2586 // code repetition: it would be nice to reuse the code from hap_add_csq, needs refactoring though
2587 if ( node.type == HAP_SSS )
2588 {
2589 csq.type.type = csq_type;
2590 csq_stage(args, &csq, rec);
2591 }
2592 else
2593 {
2594 kstring_t sseq;
2595 sseq.m = sref.m - 2*N_REF_PAD + node.dlen;
2596 sseq.s = node.seq;
2597 int alen = sseq.l = strlen(sseq.s);
2598 int fill = node.dlen%3 && alen ? 1 : 0; // see #1475227917
2599 cds_translate(&sref, &sseq, node.sbeg,node.sbeg,node.sbeg+node.rlen, tr->strand, tseq, fill);
2600
2601 sseq.m = sref.m - 2*N_REF_PAD;
2602 sseq.s = sref.s + N_REF_PAD + node.sbeg;
2603 sseq.l = node.rlen;
2604 cds_translate(&sref, &sseq, node.sbeg,node.sbeg,node.sbeg+node.rlen, tr->strand, tref, fill);
2605
2606 // check for truncating stops
2607 for (j=0; j<tref->l; j++)
2608 if ( tref->s[j]=='*' ) break;
2609 if ( j!=tref->l )
2610 {
2611 tref->l = j+1;
2612 tref->s[j+1] = 0;
2613 }
2614 for (j=0; j<tseq->l; j++)
2615 if ( tseq->s[j]=='*' ) break;
2616 if ( j!=tseq->l )
2617 {
2618 tseq->l = j+1;
2619 tseq->s[j+1] = 0;
2620 }
2621 if ( csq_type & CSQ_STOP_LOST )
2622 {
2623 if ( tref->s[tref->l-1]=='*' && tref->s[tref->l-1] == tseq->s[tseq->l-1] )
2624 {
2625 csq_type &= ~CSQ_STOP_LOST;
2626 csq_type |= CSQ_STOP_RETAINED;
2627 }
2628 else if (tref->s[tref->l-1]!='*' )
2629 {
2630 // This is CDS 3' incomplete ENSG00000173376/synon.vcf, can also be missense
2631 // We observe in real data a change to a stop, ENST00000528237/retained-stop-incomplete-cds.vcf
2632 if ( tseq->s[tseq->l-1] == '*' )
2633 {
2634 csq_type &= ~CSQ_STOP_GAINED;
2635 csq_type |= CSQ_STOP_RETAINED;
2636 }
2637 else
2638 csq_type |= CSQ_INCOMPLETE_CDS;
2639 }
2640 }
2641 if ( csq_type & CSQ_START_LOST && tref->s[0]!='M' )
2642 csq_type &= ~CSQ_START_LOST;
2643 if ( node.dlen!=0 )
2644 {
2645 if ( node.dlen%3 )
2646 csq_type |= CSQ_FRAMESHIFT_VARIANT;
2647 else if ( node.dlen<0 )
2648 csq_type |= CSQ_INFRAME_DELETION;
2649 else
2650 csq_type |= CSQ_INFRAME_INSERTION;
2651 if ( tref->s[tref->l-1]!='*' && tseq->s[tseq->l-1]=='*' )
2652 csq_type |= CSQ_STOP_GAINED;
2653 }
2654 else
2655 {
2656 int aa_change = 0;
2657 for (j=0; j<tref->l; j++)
2658 {
2659 if ( tref->s[j] == tseq->s[j] ) continue;
2660 aa_change = 1;
2661 if ( tref->s[j] == '*' )
2662 csq_type |= CSQ_STOP_LOST;
2663 else if ( tseq->s[j] == '*' )
2664 csq_type |= CSQ_STOP_GAINED;
2665 else
2666 csq_type |= CSQ_MISSENSE_VARIANT;
2667 }
2668 if ( !aa_change )
2669 csq_type |= CSQ_SYNONYMOUS_VARIANT;
2670 }
2671 if ( csq_type & CSQ_COMPOUND )
2672 {
2673 // create the aa variant string
2674 kstring_t str = {0,0,0};
2675 int aa_rbeg = tr->strand==STRAND_FWD ? node.sbeg/3+1 : (TSCRIPT_AUX(tr)->nsref - 2*N_REF_PAD - node.sbeg - node.rlen)/3+1;
2676 int aa_sbeg = tr->strand==STRAND_FWD ? node.sbeg/3+1 : (TSCRIPT_AUX(tr)->nsref - 2*N_REF_PAD + node.dlen - node.sbeg - alen)/3+1;
2677 kputc_('|', &str);
2678 kputw(aa_rbeg, &str);
2679 kprint_aa_prediction(args,aa_rbeg,tref,&str);
2680 if ( !(csq_type & CSQ_SYNONYMOUS_VARIANT) )
2681 {
2682 kputc_('>', &str);
2683 kputw(aa_sbeg, &str);
2684 kprint_aa_prediction(args,aa_sbeg,tseq,&str);
2685 }
2686 kputc_('|', &str);
2687 kputw(rec->pos+1, &str);
2688 kputs(node.var, &str);
2689 csq.type.vstr = str;
2690 csq.type.type = csq_type & CSQ_COMPOUND;
2691 csq_stage(args, &csq, rec);
2692
2693 // all this only to clean vstr when vrec is flushed
2694 if ( !TSCRIPT_AUX(tr)->root )
2695 TSCRIPT_AUX(tr)->root = (hap_node_t*) calloc(1,sizeof(hap_node_t));
2696 TSCRIPT_AUX(tr)->root->ncsq_list++;
2697 hts_expand0(csq_t,TSCRIPT_AUX(tr)->root->ncsq_list,TSCRIPT_AUX(tr)->root->mcsq_list,TSCRIPT_AUX(tr)->root->csq_list);
2698 csq_t *rm_csq = TSCRIPT_AUX(tr)->root->csq_list + TSCRIPT_AUX(tr)->root->ncsq_list - 1;
2699 rm_csq->type.vstr = str;
2700 }
2701 if ( csq_type & ~CSQ_COMPOUND )
2702 {
2703 csq.type.type = csq_type & ~CSQ_COMPOUND;
2704 csq.type.vstr.l = 0;
2705 csq_stage(args, &csq, rec);
2706 }
2707 }
2708 free(node.seq);
2709 free(node.var);
2710 }
2711 }
2712 return ret;
2713 }
2714
2715 int test_cds(args_t *args, bcf1_t *rec, vbuf_t *vbuf)
2716 {
2717 static int overlaps_warned = 0, multiploid_warned = 0;
2718
2719 int i, ret = 0, hap_ret;
2720 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,rec));
2721 // note that the off-by-one extension of rlen is deliberate to account for insertions
2722 if ( !regidx_overlap(args->idx_cds,chr,rec->pos,rec->pos+rec->rlen, args->itr) ) return 0;
2723 while ( regitr_overlap(args->itr) )
2724 {
2725 gf_cds_t *cds = regitr_payload(args->itr,gf_cds_t*);
2726 gf_tscript_t *tr = cds->tr;
2727 if ( !GF_is_coding(tr->type) ) continue;
2728 if ( vbuf->keep_until < tr->end ) vbuf->keep_until = tr->end;
2729 ret = 1;
2730 if ( !TSCRIPT_AUX(tr) )
2731 {
2732 // initialize the transcript and its haplotype tree, fetch the reference sequence
2733 tr->aux = calloc(sizeof(tscript_t),1);
2734 tscript_init_ref(args, tr, chr);
2735
2736 TSCRIPT_AUX(tr)->root = (hap_node_t*) calloc(1,sizeof(hap_node_t));
2737 TSCRIPT_AUX(tr)->nhap = args->phase==PHASE_DROP_GT ? 1 : 2*args->smpl->n; // maximum ploidy = diploid
2738 TSCRIPT_AUX(tr)->hap = (hap_node_t**) malloc(TSCRIPT_AUX(tr)->nhap*sizeof(hap_node_t*));
2739 for (i=0; i<TSCRIPT_AUX(tr)->nhap; i++) TSCRIPT_AUX(tr)->hap[i] = NULL;
2740 TSCRIPT_AUX(tr)->root->nend = TSCRIPT_AUX(tr)->nhap;
2741 TSCRIPT_AUX(tr)->root->type = HAP_ROOT;
2742
2743 khp_insert(trhp, args->active_tr, &tr);
2744 }
2745
2746 sanity_check_ref(args, tr, rec);
2747
2748 if ( args->phase==PHASE_DROP_GT )
2749 {
2750 if ( rec->d.allele[1][0]=='<' || rec->d.allele[1][0]=='*' ) { continue; }
2751 hap_node_t *parent = TSCRIPT_AUX(tr)->hap[0] ? TSCRIPT_AUX(tr)->hap[0] : TSCRIPT_AUX(tr)->root;
2752 hap_node_t *child = (hap_node_t*)calloc(1,sizeof(hap_node_t));
2753 hap_ret = hap_init(args, parent, child, cds, rec, 1);
2754 if ( hap_ret!=0 )
2755 {
2756 // overlapping or intron variant, cannot apply
2757 if ( hap_ret==1 )
2758 {
2759 if ( args->verbosity && (!overlaps_warned || args->verbosity > 1) )
2760 {
2761 fprintf(bcftools_stderr,
2762 "Warning: Skipping overlapping variants at %s:%"PRId64"\t%s>%s.\n",
2763 chr,(int64_t) rec->pos+1,rec->d.allele[0],rec->d.allele[1]);
2764 if ( !overlaps_warned )
2765 fprintf(bcftools_stderr," This message is printed only once, the verbosity can be increased with `--verbose 2`\n");
2766 overlaps_warned = 1;
2767 }
2768 if ( args->out )
2769 fprintf(args->out,"LOG\tWarning: Skipping overlapping variants at %s:%"PRId64"\t%s>%s\n", chr,(int64_t) rec->pos+1,rec->d.allele[0],rec->d.allele[1]);
2770 }
2771 else ret = 1; // prevent reporting as intron in test_tscript
2772 hap_destroy(child);
2773 continue;
2774 }
2775 if ( child->type==HAP_SSS )
2776 {
2777 csq_t csq;
2778 memset(&csq, 0, sizeof(csq_t));
2779 csq.pos = rec->pos;
2780 csq.type.biotype = tr->type;
2781 csq.type.strand = tr->strand;
2782 csq.type.trid = tr->id;
2783 csq.type.vcf_ial = 1;
2784 csq.type.gene = tr->gene->name;
2785 csq.type.type = child->csq;
2786 csq_stage(args, &csq, rec);
2787 hap_destroy(child);
2788 ret = 1;
2789 continue;
2790 }
2791 parent->nend--;
2792 parent->nchild = 1;
2793 parent->mchild = 1;
2794 parent->child = (hap_node_t**) malloc(sizeof(hap_node_t*));
2795 parent->child[0] = child;
2796 TSCRIPT_AUX(tr)->hap[0] = child;
2797 TSCRIPT_AUX(tr)->hap[0]->nend = 1;
2798 continue;
2799 }
2800
2801 // apply the VCF variants and extend the haplotype tree
2802 int j, ismpl, ihap, ngts = bcf_get_genotypes(args->hdr, rec, &args->gt_arr, &args->mgt_arr);
2803 ngts /= bcf_hdr_nsamples(args->hdr);
2804 if ( ngts!=1 && ngts!=2 )
2805 {
2806 if ( args->verbosity && (!multiploid_warned || args->verbosity > 1) )
2807 {
2808 fprintf(bcftools_stderr,
2809 "Warning: Skipping site with non-diploid/non-haploid genotypes at %s:%"PRId64"\t%s>%s.\n",
2810 chr,(int64_t) rec->pos+1,rec->d.allele[0],rec->d.allele[1]);
2811 if ( !multiploid_warned )
2812 fprintf(bcftools_stderr," This message is printed only once, the verbosity can be increased with `--verbose 2`\n");
2813 multiploid_warned = 1;
2814 }
2815 if ( args->out )
2816 fprintf(args->out,"LOG\tWarning: Skipping site with non-diploid/non-haploid genotypes at %s:%"PRId64"\t%s>%s\n", chr,(int64_t) rec->pos+1,rec->d.allele[0],rec->d.allele[1]);
2817 continue;
2818 }
2819 for (ismpl=0; ismpl<args->smpl->n; ismpl++)
2820 {
2821 int32_t *gt = args->gt_arr + args->smpl->idx[ismpl]*ngts;
2822 if ( gt[0]==bcf_gt_missing ) continue;
2823
2824 if ( ngts>1 && gt[1]!=bcf_gt_missing && gt[1]!=bcf_int32_vector_end && bcf_gt_allele(gt[0])!=bcf_gt_allele(gt[1]) )
2825 {
2826 if ( args->phase==PHASE_MERGE )
2827 {
2828 if ( !bcf_gt_allele(gt[0]) ) gt[0] = gt[1];
2829 }
2830 if ( !bcf_gt_is_phased(gt[0]) && !bcf_gt_is_phased(gt[1]) )
2831 {
2832 if ( args->phase==PHASE_REQUIRE )
2833 error("Unphased heterozygous genotype at %s:%"PRId64", sample %s. See the --phase option.\n", chr,(int64_t) rec->pos+1,args->hdr->samples[args->smpl->idx[ismpl]]);
2834 if ( args->phase==PHASE_SKIP )
2835 continue;
2836 if ( args->phase==PHASE_NON_REF )
2837 {
2838 if ( !bcf_gt_allele(gt[0]) ) gt[0] = gt[1];
2839 else if ( !bcf_gt_allele(gt[1]) ) gt[1] = gt[0];
2840 }
2841 }
2842 }
2843
2844 for (ihap=0; ihap<ngts; ihap++)
2845 {
2846 if ( gt[ihap]==bcf_gt_missing || gt[ihap]==bcf_int32_vector_end ) continue;
2847
2848 i = 2*ismpl + ihap;
2849
2850 int ial = bcf_gt_allele(gt[ihap]);
2851 if ( !ial ) continue;
2852 assert( ial < rec->n_allele );
2853 if ( rec->d.allele[ial][0]=='<' || rec->d.allele[ial][0]=='*' ) { continue; }
2854
2855 hap_node_t *parent = TSCRIPT_AUX(tr)->hap[i] ? TSCRIPT_AUX(tr)->hap[i] : TSCRIPT_AUX(tr)->root;
2856 if ( parent->cur_rec==rec && parent->cur_child[ial]>=0 )
2857 {
2858 // this haplotype has been seen in another sample
2859 TSCRIPT_AUX(tr)->hap[i] = parent->child[ parent->cur_child[ial] ];
2860 TSCRIPT_AUX(tr)->hap[i]->nend++;
2861 parent->nend--;
2862 continue;
2863 }
2864
2865 hap_node_t *child = (hap_node_t*)calloc(1,sizeof(hap_node_t));
2866 hap_ret = hap_init(args, parent, child, cds, rec, ial);
2867 if ( hap_ret!=0 )
2868 {
2869 // overlapping or intron variant, cannot apply
2870 if ( hap_ret==1 )
2871 {
2872 if ( args->verbosity && (!overlaps_warned || args->verbosity > 1) )
2873 {
2874 fprintf(bcftools_stderr,
2875 "Warning: Skipping overlapping variants at %s:%"PRId64", sample %s\t%s>%s.\n",
2876 chr,(int64_t) rec->pos+1,args->hdr->samples[args->smpl->idx[ismpl]],rec->d.allele[0],rec->d.allele[ial]);
2877 if ( !overlaps_warned )
2878 fprintf(bcftools_stderr," This message is printed only once, the verbosity can be increased with `--verbose 2`\n");
2879 overlaps_warned = 1;
2880 }
2881 if ( args->out )
2882 fprintf(args->out,"LOG\tWarning: Skipping overlapping variants at %s:%"PRId64", sample %s\t%s>%s\n",
2883 chr,(int64_t) rec->pos+1,args->hdr->samples[args->smpl->idx[ismpl]],rec->d.allele[0],rec->d.allele[ial]);
2884 }
2885 hap_destroy(child);
2886 continue;
2887 }
2888 if ( child->type==HAP_SSS )
2889 {
2890 csq_t csq;
2891 memset(&csq, 0, sizeof(csq_t));
2892 csq.pos = rec->pos;
2893 csq.type.biotype = tr->type;
2894 csq.type.strand = tr->strand;
2895 csq.type.trid = tr->id;
2896 csq.type.vcf_ial = ial;
2897 csq.type.gene = tr->gene->name;
2898 csq.type.type = child->csq;
2899 csq_stage(args, &csq, rec);
2900 hap_destroy(child);
2901 continue;
2902 }
2903 if ( parent->cur_rec!=rec )
2904 {
2905 hts_expand(int,rec->n_allele,parent->mcur_child,parent->cur_child);
2906 for (j=0; j<rec->n_allele; j++) parent->cur_child[j] = -1;
2907 parent->cur_rec = rec;
2908 }
2909
2910 j = parent->nchild++;
2911 hts_expand0(hap_node_t*,parent->nchild,parent->mchild,parent->child);
2912 parent->cur_child[ial] = j;
2913 parent->child[j] = child;
2914 TSCRIPT_AUX(tr)->hap[i] = child;
2915 TSCRIPT_AUX(tr)->hap[i]->nend++;
2916 parent->nend--;
2917 }
2918 }
2919 }
2920 return ret;
2921 }
2922
2923 void csq_stage(args_t *args, csq_t *csq, bcf1_t *rec)
2924 {
2925 // known issues: tab output leads to unsorted output. This is because
2926 // coding haplotypes are printed in one go and buffering is not used
2927 // with tab output. VCF output is OK though.
2928 if ( csq_push(args, csq, rec)!=0 && args->phase==PHASE_DROP_GT ) return; // the consequence already exists
2929
2930 int i,j,ngt = 0;
2931 if ( args->phase!=PHASE_DROP_GT )
2932 {
2933 ngt = bcf_get_genotypes(args->hdr, rec, &args->gt_arr, &args->mgt_arr);
2934 if ( ngt>0 ) ngt /= bcf_hdr_nsamples(args->hdr);
2935 }
2936 if ( ngt<=0 )
2937 {
2938 if ( args->output_type==FT_TAB_TEXT )
2939 csq_print_text(args, csq, -1,0);
2940 return;
2941 }
2942 assert( ngt<=2 );
2943
2944 if ( args->output_type==FT_TAB_TEXT )
2945 {
2946 for (i=0; i<args->smpl->n; i++)
2947 {
2948 int32_t *gt = args->gt_arr + args->smpl->idx[i]*ngt;
2949 for (j=0; j<ngt; j++)
2950 {
2951 if ( gt[j]==bcf_gt_missing || gt[j]==bcf_int32_vector_end ) continue;
2952 int ial = bcf_gt_allele(gt[j]);
2953 if ( !ial || ial!=csq->type.vcf_ial ) continue;
2954 csq_print_text(args, csq, args->smpl->idx[i],j+1);
2955 }
2956 }
2957 return;
2958 }
2959
2960 vrec_t *vrec = csq->vrec;
2961 for (i=0; i<args->smpl->n; i++)
2962 {
2963 int32_t *gt = args->gt_arr + args->smpl->idx[i]*ngt;
2964 for (j=0; j<ngt; j++)
2965 {
2966 if ( gt[j]==bcf_gt_missing || gt[j]==bcf_int32_vector_end ) continue;
2967 int ial = bcf_gt_allele(gt[j]);
2968 if ( !ial || ial!=csq->type.vcf_ial ) continue;
2969
2970 int icsq2 = 2*csq->idx + j;
2971 if ( icsq2 >= args->ncsq2_max ) // more than ncsq_max consequences, so can't fit it in FMT
2972 {
2973 int ismpl = args->smpl->idx[i];
2974 if ( args->verbosity && (!args->ncsq2_small_warned || args->verbosity > 1) )
2975 {
2976 fprintf(bcftools_stderr,
2977 "Warning: Too many consequences for sample %s at %s:%"PRId64", keeping the first %d and skipping the rest.\n",
2978 args->hdr->samples[ismpl],bcf_hdr_id2name(args->hdr,args->rid),(int64_t) vrec->line->pos+1,icsq2+1);
2979 if ( !args->ncsq2_small_warned )
2980 fprintf(bcftools_stderr," The limit can be increased by setting the --ncsq parameter. This warning is printed only once.\n");
2981 args->ncsq2_small_warned = 1;
2982 }
2983 if ( args->ncsq2_small_warned < icsq2 ) args->ncsq2_small_warned = icsq2;
2984 break;
2985 }
2986 int ival, ibit;
2987 icsq2_to_bit(icsq2, &ival,&ibit);
2988 if ( vrec->nfmt < 1 + ival ) vrec->nfmt = 1 + ival;
2989 vrec->fmt_bm[i*args->nfmt_bcsq + ival] |= 1 << ibit;
2990 }
2991 }
2992 }
2993 int test_utr(args_t *args, bcf1_t *rec)
2994 {
2995 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,rec));
2996 // note that the off-by-one extension of rlen is deliberate to account for insertions
2997 if ( !regidx_overlap(args->idx_utr,chr,rec->pos,rec->pos+rec->rlen, args->itr) ) return 0;
2998
2999 splice_t splice;
3000 splice_init(&splice, rec);
3001
3002 int i, ret = 0;
3003 while ( regitr_overlap(args->itr) )
3004 {
3005 gf_utr_t *utr = regitr_payload(args->itr, gf_utr_t*);
3006 gf_tscript_t *tr = splice.tr = utr->tr;
3007 for (i=1; i<rec->n_allele; i++)
3008 {
3009 if ( rec->d.allele[i][0]=='<' || rec->d.allele[i][0]=='*' ) { continue; }
3010 splice.vcf.alt = rec->d.allele[i];
3011 splice.csq = 0;
3012 int splice_ret = splice_csq(args, &splice, utr->beg, utr->end);
3013 if ( splice_ret!=SPLICE_INSIDE && splice_ret!=SPLICE_OVERLAP ) continue;
3014 csq_t csq;
3015 memset(&csq, 0, sizeof(csq_t));
3016 csq.pos = rec->pos;
3017 csq.type.type = utr->which==prime5 ? CSQ_UTR5 : CSQ_UTR3;
3018 csq.type.biotype = tr->type;
3019 csq.type.strand = tr->strand;
3020 csq.type.trid = tr->id;
3021 csq.type.vcf_ial = i;
3022 csq.type.gene = tr->gene->name;
3023 csq_stage(args, &csq, rec);
3024 ret = 1;
3025 }
3026 }
3027 assert(!splice.kref.s);
3028 assert(!splice.kalt.s);
3029 return ret;
3030 }
3031 int test_splice(args_t *args, bcf1_t *rec)
3032 {
3033 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,rec));
3034 if ( !regidx_overlap(args->idx_exon,chr,rec->pos,rec->pos + rec->rlen, args->itr) ) return 0;
3035
3036 splice_t splice;
3037 splice_init(&splice, rec);
3038 splice.check_acceptor = splice.check_donor = 1;
3039
3040 int i, ret = 0;
3041 while ( regitr_overlap(args->itr) )
3042 {
3043 gf_exon_t *exon = regitr_payload(args->itr, gf_exon_t*);
3044 splice.tr = exon->tr;
3045 if ( !splice.tr->ncds ) continue; // not a coding transcript, no interest in splice sites
3046
3047 splice.check_region_beg = splice.tr->beg==exon->beg ? 0 : 1;
3048 splice.check_region_end = splice.tr->end==exon->end ? 0 : 1;
3049
3050 for (i=1; i<rec->n_allele; i++)
3051 {
3052 if ( rec->d.allele[1][0]=='<' || rec->d.allele[1][0]=='*' ) { continue; }
3053 splice.vcf.alt = rec->d.allele[i];
3054 splice.csq = 0;
3055 splice_csq(args, &splice, exon->beg, exon->end);
3056 if ( splice.csq ) ret = 1;
3057 }
3058 }
3059 free(splice.kref.s);
3060 free(splice.kalt.s);
3061 return ret;
3062 }
3063 int test_tscript(args_t *args, bcf1_t *rec)
3064 {
3065 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,rec));
3066 if ( !regidx_overlap(args->idx_tscript,chr,rec->pos,rec->pos+rec->rlen, args->itr) ) return 0;
3067
3068 splice_t splice;
3069 splice_init(&splice, rec);
3070
3071 int i, ret = 0;
3072 while ( regitr_overlap(args->itr) )
3073 {
3074 gf_tscript_t *tr = splice.tr = regitr_payload(args->itr, gf_tscript_t*);
3075 for (i=1; i<rec->n_allele; i++)
3076 {
3077 if ( rec->d.allele[i][0]=='<' || rec->d.allele[i][0]=='*' ) { continue; }
3078 splice.vcf.alt = rec->d.allele[i];
3079 splice.csq = 0;
3080 int splice_ret = splice_csq(args, &splice, tr->beg, tr->end);
3081 if ( splice_ret!=SPLICE_INSIDE && splice_ret!=SPLICE_OVERLAP ) continue; // SPLICE_OUTSIDE or SPLICE_REF
3082 csq_t csq;
3083 memset(&csq, 0, sizeof(csq_t));
3084 csq.pos = rec->pos;
3085 csq.type.type = GF_is_coding(tr->type) ? CSQ_INTRON : CSQ_NON_CODING;
3086 csq.type.biotype = tr->type;
3087 csq.type.strand = tr->strand;
3088 csq.type.trid = tr->id;
3089 csq.type.gene = tr->gene->name;
3090 csq_stage(args, &csq, rec);
3091 ret = 1;
3092 }
3093 }
3094 assert(!splice.kref.s);
3095 assert(!splice.kalt.s);
3096 return ret;
3097 }
3098
3099 void test_symbolic_alt(args_t *args, bcf1_t *rec)
3100 {
3101 static int warned = 0;
3102 if ( args->verbosity && (!warned && args->verbosity > 0) )
3103 {
3104 fprintf(bcftools_stderr,"Warning: The support for symbolic ALT insertions is experimental.\n");
3105 warned = 1;
3106 }
3107
3108 const char *chr = drop_chr_prefix(args, bcf_seqname(args->hdr,rec));
3109
3110 // only insertions atm
3111 int beg = rec->pos + 1;
3112 int end = beg;
3113 int csq_class = CSQ_ELONGATION;
3114
3115 int hit = 0;
3116 if ( regidx_overlap(args->idx_cds,chr,beg,end, args->itr) )
3117 {
3118 while ( regitr_overlap(args->itr) )
3119 {
3120 csq_t csq;
3121 memset(&csq, 0, sizeof(csq_t));
3122 gf_cds_t *cds = regitr_payload(args->itr,gf_cds_t*);
3123 gf_tscript_t *tr = cds->tr;
3124 csq.type.type = (GF_is_coding(tr->type) ? CSQ_CODING_SEQUENCE : CSQ_NON_CODING) | csq_class;
3125 csq.pos = rec->pos;
3126 csq.type.biotype = tr->type;
3127 csq.type.strand = tr->strand;
3128 csq.type.trid = tr->id;
3129 csq.type.gene = tr->gene->name;
3130 csq_stage(args, &csq, rec);
3131 hit = 1;
3132 }
3133 }
3134 if ( regidx_overlap(args->idx_utr,chr,beg,end, args->itr) )
3135 {
3136 while ( regitr_overlap(args->itr) )
3137 {
3138 csq_t csq;
3139 memset(&csq, 0, sizeof(csq_t));
3140 gf_utr_t *utr = regitr_payload(args->itr, gf_utr_t*);
3141 gf_tscript_t *tr = utr->tr;
3142 csq.type.type = (utr->which==prime5 ? CSQ_UTR5 : CSQ_UTR3) | csq_class;
3143 csq.pos = rec->pos;
3144 csq.type.biotype = tr->type;
3145 csq.type.strand = tr->strand;
3146 csq.type.trid = tr->id;
3147 csq.type.gene = tr->gene->name;
3148 csq_stage(args, &csq, rec);
3149 hit = 1;
3150 }
3151 }
3152 if ( regidx_overlap(args->idx_exon,chr,beg,end, args->itr) )
3153 {
3154 splice_t splice;
3155 splice_init(&splice, rec);
3156 splice.check_acceptor = splice.check_donor = 1;
3157
3158 while ( regitr_overlap(args->itr) )
3159 {
3160 gf_exon_t *exon = regitr_payload(args->itr, gf_exon_t*);
3161 splice.tr = exon->tr;
3162 if ( !splice.tr->ncds ) continue; // not a coding transcript, no interest in splice sites
3163 splice.check_region_beg = splice.tr->beg==exon->beg ? 0 : 1;
3164 splice.check_region_end = splice.tr->end==exon->end ? 0 : 1;
3165 splice.vcf.alt = rec->d.allele[1];
3166 splice.csq = csq_class;
3167 splice_csq(args, &splice, exon->beg, exon->end);
3168 if ( splice.csq ) hit = 1;
3169 }
3170 }
3171 if ( !hit && regidx_overlap(args->idx_tscript,chr,beg,end, args->itr) )
3172 {
3173 splice_t splice;
3174 splice_init(&splice, rec);
3175
3176 while ( regitr_overlap(args->itr) )
3177 {
3178 csq_t csq;
3179 memset(&csq, 0, sizeof(csq_t));
3180 gf_tscript_t *tr = splice.tr = regitr_payload(args->itr, gf_tscript_t*);
3181 splice.vcf.alt = rec->d.allele[1];
3182 splice.csq = csq_class;
3183 int splice_ret = splice_csq(args, &splice, tr->beg, tr->end);
3184 if ( splice_ret!=SPLICE_INSIDE && splice_ret!=SPLICE_OVERLAP ) continue; // SPLICE_OUTSIDE or SPLICE_REF
3185 csq.type.type = (GF_is_coding(tr->type) ? CSQ_INTRON : CSQ_NON_CODING) | csq_class;
3186 csq.pos = rec->pos;
3187 csq.type.biotype = tr->type;
3188 csq.type.strand = tr->strand;
3189 csq.type.trid = tr->id;
3190 csq.type.gene = tr->gene->name;
3191 csq_stage(args, &csq, rec);
3192 }
3193 }
3194 }
3195
3196 void debug_print_buffers(args_t *args, int pos)
3197 {
3198 int i,j;
3199 fprintf(bcftools_stderr,"debug_print_buffers at %d\n", pos);
3200 fprintf(bcftools_stderr,"vbufs:\n");
3201 for (i=0; i<args->vcf_rbuf.n; i++)
3202 {
3203 int k = rbuf_kth(&args->vcf_rbuf, i);
3204 vbuf_t *vbuf = args->vcf_buf[k];
3205
3206 fprintf(bcftools_stderr,"\tvbuf %d:\n", i);
3207 for (j=0; j<vbuf->n; j++)
3208 {
3209 vrec_t *vrec = vbuf->vrec[j];
3210 fprintf(bcftools_stderr,"\t\t%"PRId64" .. nvcsq=%d\n", (int64_t) vrec->line->pos+1, vrec->nvcsq);
3211 }
3212 }
3213 fprintf(bcftools_stderr,"pos2vbuf:");
3214 khint_t k;
3215 for (k = 0; k < kh_end(args->pos2vbuf); ++k)
3216 if (kh_exist(args->pos2vbuf, k)) fprintf(bcftools_stderr," %d",1+(int)kh_key(args->pos2vbuf, k));
3217 fprintf(bcftools_stderr,"\n");
3218 fprintf(bcftools_stderr,"active_tr: %d\n", args->active_tr->ndat);
3219 }
3220
3221 static void process(args_t *args, bcf1_t **rec_ptr)
3222 {
3223 if ( !rec_ptr )
3224 {
3225 hap_flush(args, REGIDX_MAX);
3226 vbuf_flush(args, REGIDX_MAX);
3227 return;
3228 }
3229
3230 bcf1_t *rec = *rec_ptr;
3231 static int32_t prev_rid = -1, prev_pos = -1;
3232 if ( prev_rid!=rec->rid )
3233 {
3234 prev_rid = rec->rid;
3235 prev_pos = rec->pos;
3236
3237 // Common error is to use different naming conventions in the fasta and the VCF (e.g. X vs chrX).
3238 // Perform a simple sanity check (that does not catch much), the chromosome must be present in the
3239 // reference file
3240 if ( !faidx_has_seq(args->fai,bcf_seqname(args->hdr,rec)) )
3241 {
3242 if ( !faidx_has_seq(args->fai,drop_chr_prefix(args,bcf_seqname(args->hdr,rec))) && !faidx_has_seq(args->fai,add_chr_prefix(args,bcf_seqname(args->hdr,rec))) )
3243 error("Error: the chromosome \"%s\" is not present in %s\n",bcf_seqname(args->hdr,rec),args->fa_fname);
3244 }
3245 }
3246 if ( prev_pos > rec->pos )
3247 error("Error: The file is not sorted, %s:%d comes before %s:%"PRId64"\n",bcf_seqname(args->hdr,rec),prev_pos+1,bcf_seqname(args->hdr,rec),(int64_t) rec->pos+1);
3248
3249 int call_csq = 1;
3250 if ( rec->n_allele < 2 ) call_csq = 0; // no alternate allele
3251 else if ( rec->n_allele==2 && (rec->d.allele[1][0]=='*' || rec->d.allele[1][1]=='*') ) call_csq = 0; // gVCF, not an alt allele
3252 else if ( rec->d.allele[1][0]=='<' )
3253 {
3254 if ( strncmp("<INS",rec->d.allele[1], 4) ) call_csq = 0; // only <INS[:.*]> is supported at the moment
3255 }
3256 if ( call_csq && args->filter )
3257 {
3258 call_csq = filter_test(args->filter, rec, NULL);
3259 if ( args->filter_logic==FLT_EXCLUDE ) call_csq = call_csq ? 0 : 1;
3260 }
3261 if ( !call_csq )
3262 {
3263 if ( !args->out_fh ) return; // not a VCF output
3264 vbuf_push(args, rec_ptr);
3265 hap_flush(args, rec->pos-1);
3266 vbuf_flush(args, rec->pos-1);
3267 return;
3268 }
3269
3270 if ( args->rid != rec->rid )
3271 {
3272 hap_flush(args, REGIDX_MAX);
3273 vbuf_flush(args, REGIDX_MAX);
3274 }
3275 args->rid = rec->rid;
3276 vbuf_t *vbuf = vbuf_push(args, rec_ptr);
3277
3278 if ( rec->d.allele[1][0]!='<' )
3279 {
3280 int hit = args->local_csq ? test_cds_local(args, rec) : test_cds(args, rec, vbuf);
3281 hit += test_utr(args, rec);
3282 hit += test_splice(args, rec);
3283 if ( !hit ) test_tscript(args, rec);
3284 }
3285 else
3286 test_symbolic_alt(args, rec);
3287
3288 if ( rec->pos > 0 )
3289 {
3290 hap_flush(args, rec->pos-1);
3291 vbuf_flush(args, rec->pos-1);
3292 }
3293
3294 return;
3295 }
3296
3297 static const char *usage(void)
3298 {
3299 return
3300 "\n"
3301 "About: Haplotype-aware consequence caller.\n"
3302 "Usage: bcftools csq [OPTIONS] in.vcf\n"
3303 "\n"
3304 "Required options:\n"
3305 " -f, --fasta-ref FILE Reference file in fasta format\n"
3306 " -g, --gff-annot FILE GFF3 annotation file\n"
3307 "\n"
3308 "CSQ options:\n"
3309 " -B, --trim-protein-seq INT Abbreviate protein-changing predictions to max INT aminoacids\n"
3310 " -c, --custom-tag STRING Use this tag instead of the default BCSQ\n"
3311 " -l, --local-csq Localized predictions, consider only one VCF record at a time\n"
3312 " -n, --ncsq INT Maximum number of per-haplotype consequences to consider for each site [15]\n"
3313 " -p, --phase a|m|r|R|s How to handle unphased heterozygous genotypes: [r]\n"
3314 " a: take GTs as is, create haplotypes regardless of phase (0/1 -> 0|1)\n"
3315 " m: merge *all* GTs into a single haplotype (0/1 -> 1, 1/2 -> 1)\n"
3316 " r: require phased GTs, throw an error on unphased het GTs\n"
3317 " R: create non-reference haplotypes if possible (0/1 -> 1|1, 1/2 -> 1|2)\n"
3318 " s: skip unphased hets\n"
3319 "GFF options:\n"
3320 " --dump-gff FILE.gz Dump the parsed GFF file (for debugging purposes)\n"
3321 " --force Run even if some sanity checks fail\n"
3322 " --unify-chr-names 1|0 Automatically unify chromosome naming (e.g. chrX vs X) in GFF, fasta, and VCF [1]\n"
3323 "General options:\n"
3324 " -e, --exclude EXPR Exclude sites for which the expression is true\n"
3325 " -i, --include EXPR Select sites for which the expression is true\n"
3326 " --no-version Do not append version and command line to the header\n"
3327 " -o, --output FILE Write output to a file [standard output]\n"
3328 " -O, --output-type b|u|z|v|t[0-9] b: compressed BCF, u: uncompressed BCF, z: compressed VCF\n"
3329 " v: uncompressed VCF, t: plain tab-delimited text output, 0-9: compression level [v]\n"
3330 " -r, --regions REGION Restrict to comma-separated list of regions\n"
3331 " -R, --regions-file FILE Restrict to regions listed in a file\n"
3332 " --regions-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [1]\n"
3333 " -s, --samples -|LIST Samples to include or \"-\" to apply all variants and ignore samples\n"
3334 " -S, --samples-file FILE Samples to include\n"
3335 " -t, --targets REGION Similar to -r but streams rather than index-jumps\n"
3336 " -T, --targets-file FILE Similar to -R but streams rather than index-jumps\n"
3337 " --targets-overlap 0|1|2 Include if POS in the region (0), record overlaps (1), variant overlaps (2) [0]\n"
3338 " --threads INT Use multithreading with <int> worker threads [0]\n"
3339 " -v, --verbose INT Verbosity level 0-2 [1]\n"
3340 " -W, --write-index[=FMT] Automatically index the output files [off]\n"
3341 "\n"
3342 "Example:\n"
3343 " bcftools csq -f hs37d5.fa -g Homo_sapiens.GRCh37.87.gff3.gz in.vcf\n"
3344 "\n"
3345 " # GFF3 annotation files can be downloaded from Ensembl. e.g. for human:\n"
3346 " http://ftp.ensembl.org/pub/current_gff3/homo_sapiens/\n"
3347 " http://ftp.ensembl.org/pub/grch37/current/gff3/homo_sapiens/\n"
3348 "\n";
3349 }
3350
3351 int main_csq(int argc, char *argv[])
3352 {
3353 args_t *args = (args_t*) calloc(1,sizeof(args_t));
3354 args->argc = argc; args->argv = argv;
3355 args->output_type = FT_VCF;
3356 args->bcsq_tag = "BCSQ";
3357 args->ncsq2_max = 2*(16-1); // 1 bit is reserved for BCF missing values
3358 args->verbosity = 1;
3359 args->record_cmd_line = 1;
3360 args->clevel = -1;
3361 args->unify_chr_names = 1;
3362
3363 static struct option loptions[] =
3364 {
3365 {"force",0,0,1},
3366 {"threads",required_argument,NULL,2},
3367 {"help",0,0,'h'},
3368 {"ncsq",1,0,'n'},
3369 {"brief-predictions",no_argument,0,'b'},
3370 {"trim-protein-seq",required_argument,0,'B'},
3371 {"custom-tag",1,0,'c'},
3372 {"local-csq",0,0,'l'},
3373 {"gff-annot",1,0,'g'},
3374 {"fasta-ref",1,0,'f'},
3375 {"include",1,0,'i'},
3376 {"exclude",1,0,'e'},
3377 {"output",1,0,'o'},
3378 {"output-type",1,NULL,'O'},
3379 {"phase",1,0,'p'},
3380 {"quiet",0,0,'q'},
3381 {"verbose",1,0,'v'},
3382 {"regions",1,0,'r'},
3383 {"regions-file",1,0,'R'},
3384 {"regions-overlap",required_argument,NULL,4},
3385 {"samples",1,0,'s'},
3386 {"samples-file",1,0,'S'},
3387 {"targets",1,0,'t'},
3388 {"targets-file",1,0,'T'},
3389 {"targets-overlap",required_argument,NULL,5},
3390 {"no-version",no_argument,NULL,3},
3391 {"write-index",optional_argument,NULL,'W'},
3392 {"dump-gff",required_argument,NULL,7},
3393 {"unify-chr-names",required_argument,NULL,8},
3394 {0,0,0,0}
3395 };
3396 int c, targets_is_file = 0, regions_is_file = 0;
3397 int regions_overlap = 1;
3398 int targets_overlap = 0;
3399 char *targets_list = NULL, *regions_list = NULL, *tmp;
3400 while ((c = getopt_long(argc, argv, "?hr:R:t:T:i:e:f:o:O:g:s:S:p:qc:ln:bB:v:W::",loptions,NULL)) >= 0)
3401 {
3402 switch (c)
3403 {
3404 case 1 : args->force = 1; break;
3405 case 2 :
3406 args->n_threads = strtol(optarg,&tmp,10);
3407 if ( *tmp ) error("Could not parse argument: --threads %s\n", optarg);
3408 break;
3409 case 3 : args->record_cmd_line = 0; break;
3410 case 'b':
3411 args->brief_predictions = 1;
3412 fprintf(bcftools_stderr,"Warning: The -b option will be removed in future versions. Please use -B 1 instead.\n");
3413 break;
3414 case 'B':
3415 args->brief_predictions = strtol(optarg,&tmp,10);
3416 if ( *tmp || args->brief_predictions<1 ) error("Could not parse argument: --trim-protein-seq %s\n", optarg);
3417 break;
3418 case 'l': args->local_csq = 1; break;
3419 case 'c': args->bcsq_tag = optarg; break;
3420 case 'q': error("Error: the -q option has been deprecated, use -v, --verbose instead.\n"); break;
3421 case 'v':
3422 args->verbosity = atoi(optarg);
3423 if ( args->verbosity<0 || args->verbosity>2 ) error("Error: expected integer 0-2 with -v, --verbose\n");
3424 break;
3425 case 'p':
3426 switch (optarg[0])
3427 {
3428 case 'a': args->phase = PHASE_AS_IS; break;
3429 case 'm': args->phase = PHASE_MERGE; break;
3430 case 'r': args->phase = PHASE_REQUIRE; break;
3431 case 'R': args->phase = PHASE_NON_REF; break;
3432 case 's': args->phase = PHASE_SKIP; break;
3433 default: error("The -p code \"%s\" not recognised\n", optarg);
3434 }
3435 break;
3436 case 'f': args->fa_fname = optarg; break;
3437 case 'g': args->gff_fname = optarg; break;
3438 case 'n':
3439 args->ncsq2_max = 2 * atoi(optarg);
3440 if ( args->ncsq2_max <= 0 ) error("Expected positive integer with -n, got %s\n", optarg);
3441 break;
3442 case 'o': args->output_fname = optarg; break;
3443 case 'O':
3444 switch (optarg[0]) {
3445 case 't': args->output_type = FT_TAB_TEXT; break;
3446 case 'b': args->output_type = FT_BCF_GZ; break;
3447 case 'u': args->output_type = FT_BCF; break;
3448 case 'z': args->output_type = FT_VCF_GZ; break;
3449 case 'v': args->output_type = FT_VCF; break;
3450 default:
3451 {
3452 args->clevel = strtol(optarg,&tmp,10);
3453 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("The output type \"%s\" not recognised\n", optarg);
3454 }
3455 }
3456 if ( optarg[1] )
3457 {
3458 args->clevel = strtol(optarg+1,&tmp,10);
3459 if ( *tmp || args->clevel<0 || args->clevel>9 ) error("Could not parse argument: --output-type %s\n", optarg+1);
3460 }
3461 break;
3462 case 'e':
3463 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
3464 args->filter_str = optarg; args->filter_logic |= FLT_EXCLUDE; break;
3465 case 'i':
3466 if ( args->filter_str ) error("Error: only one -i or -e expression can be given, and they cannot be combined\n");
3467 args->filter_str = optarg; args->filter_logic |= FLT_INCLUDE; break;
3468 case 'r': regions_list = optarg; break;
3469 case 'R': regions_list = optarg; regions_is_file = 1; break;
3470 case 's': args->sample_list = optarg; break;
3471 case 'S': args->sample_list = optarg; args->sample_is_file = 1; break;
3472 case 't': targets_list = optarg; break;
3473 case 'T': targets_list = optarg; targets_is_file = 1; break;
3474 case 4 :
3475 regions_overlap = parse_overlap_option(optarg);
3476 if ( regions_overlap < 0 ) error("Could not parse: --regions-overlap %s\n",optarg);
3477 break;
3478 case 5 :
3479 targets_overlap = parse_overlap_option(optarg);
3480 if ( targets_overlap < 0 ) error("Could not parse: --targets-overlap %s\n",optarg);
3481 break;
3482 case 'W':
3483 if (!(args->write_index = write_index_parse(optarg)))
3484 error("Unsupported index format '%s'\n", optarg);
3485 break;
3486 case 7 : args->dump_gff = optarg; break;
3487 case 8 :
3488 if ( !strcmp(optarg,"0") ) args->unify_chr_names = 0;
3489 else if ( !strcmp(optarg,"1") ) args->unify_chr_names = 1;
3490 else error("Could not parse: --unify-chr-names %s\n",optarg);
3491 break;
3492 case 'h':
3493 case '?': error("%s",usage());
3494 default: error("The option not recognised: %s\n\n", optarg); break;
3495 }
3496 }
3497 char *fname = NULL;
3498 if ( optind==argc )
3499 {
3500 if ( !isatty(fileno((FILE *)stdin)) ) fname = "-"; // reading from stdin
3501 else error("%s", usage());
3502 }
3503 else fname = argv[optind];
3504 if ( argc - optind>1 ) error("%s", usage());
3505 if ( !args->fa_fname ) error("Missing the --fasta-ref option\n");
3506 if ( !args->gff_fname ) error("Missing the --gff option\n");
3507 args->sr = bcf_sr_init();
3508 if ( targets_list )
3509 {
3510 bcf_sr_set_opt(args->sr,BCF_SR_TARGETS_OVERLAP,targets_overlap);
3511 if ( bcf_sr_set_targets(args->sr, targets_list, targets_is_file, 0)<0 )
3512 error("Failed to read the targets: %s\n", targets_list);
3513 }
3514 if ( regions_list )
3515 {
3516 bcf_sr_set_opt(args->sr,BCF_SR_REGIONS_OVERLAP,regions_overlap);
3517 if ( bcf_sr_set_regions(args->sr, regions_list, regions_is_file)<0 )
3518 error("Failed to read the regions: %s\n", regions_list);
3519 }
3520 if ( bcf_sr_set_threads(args->sr, args->n_threads)<0 ) error("Failed to create %d extra threads\n", args->n_threads);
3521 if ( !bcf_sr_add_reader(args->sr, fname) )
3522 error("Failed to read from %s: %s\n", !strcmp("-",fname)?"standard input":fname,bcf_sr_strerror(args->sr->errnum));
3523 args->hdr = bcf_sr_get_header(args->sr,0);
3524
3525 init_data(args);
3526 while ( bcf_sr_next_line(args->sr) )
3527 {
3528 process(args, &args->sr->readers[0].buffer[0]);
3529 }
3530 process(args,NULL);
3531
3532 destroy_data(args);
3533 bcf_sr_destroy(args->sr);
3534 free(args);
3535 return 0;
3536 }
3537