forked from samtools/bcftools
-
Notifications
You must be signed in to change notification settings - Fork 2
/
csq.c
4395 lines (4051 loc) · 174 KB
/
csq.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* The MIT License
Copyright (c) 2016-2021 Genome Research Ltd.
Author: Petr Danecek <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/*
Things that would be nice to have
- dynamic N_REF_PAD
- for stop-lost events (also in frameshifts) report the number of truncated aa's
- memory could be greatly reduced by indexing gff (but it is quite compact already)
- deletions that go beyond transcript boundaries are not checked at sequence level
- alloc tscript->ref in hap_finalize, introduce fa_off_beg:16,fa_off_end:16
- see test/csq/ENST00000573314/insertion-overlap.vcf #1476288882
Read about transcript types here
http://vega.sanger.ac.uk/info/about/gene_and_transcript_types.html
http://www.ensembl.org/info/genome/variation/predicted_data.html
http://www.gencodegenes.org/gencode_biotypes.html
List of supported biotypes
antisense
IG_C_gene
IG_D_gene
IG_J_gene
IG_LV_gene
IG_V_gene
lincRNA
macro_lncRNA
miRNA
misc_RNA
Mt_rRNA
Mt_tRNA
polymorphic_pseudogene
processed_transcript
protein_coding
ribozyme
rRNA
sRNA
scRNA
scaRNA
sense_intronic
sense_overlapping
snRNA
snoRNA
TR_C_gene
TR_D_gene
TR_J_gene
TR_V_gene
The gff parsing logic
We collect features such by combining gff lines A,B,C as follows:
A .. gene line with a supported biotype
A.ID=~/^gene:/
B .. transcript line referencing A with supported biotype
B.ID=~/^transcript:/ && B.Parent=~/^gene:A.ID/
C .. corresponding CDS, exon, and UTR lines:
C[3] in {"CDS","exon","three_prime_UTR","five_prime_UTR"} && C.Parent=~/^transcript:B.ID/
For coding biotypes ("protein_coding" or "polymorphic_pseudogene") the
complete chain link C -> B -> A is required. For the rest, link B -> A suffices.
The supported consequence types, sorted by impact:
splice_acceptor_variant .. end region of an intron changed (2bp at the 3' end of an intron)
splice_donor_variant .. start region of an intron changed (2bp at the 5' end of an intron)
stop_gained .. DNA sequence variant resulting in a stop codon
frameshift_variant .. number of inserted/deleted bases not a multiple of three, disrupted translational frame
stop_lost .. elongated transcript, stop codon changed
start_lost .. the first codon changed
inframe_altering .. combination of indels leading to unchanged reading frame and length
inframe_insertion .. inserted coding sequence, unchanged reading frame
inframe_deletion .. deleted coding sequence, unchanged reading frame
missense_variant .. amino acid (aa) change, unchanged length
splice_region_variant .. change within 1-3 bases of the exon or 3-8 bases of the intron
synonymous_variant .. DNA sequence variant resulting in no amino acid change
stop_retained_variant .. different stop codon
start_retained_variant .. start codon retained by indel realignment
non_coding_variant .. variant in non-coding sequence, such as RNA gene
5_prime_UTR_variant
3_prime_UTR_variant
intron_variant .. reported only if none of the above
intergenic_variant .. reported only if none of the above
The annotation algorithm.
The algorithm checks if the variant falls in a region of a supported type. The
search is performed in the following order, until a match is found:
1. idx_cds(gf_cds_t) - lookup CDS by position, create haplotypes, call consequences
2. idx_utr(gf_utr_t) - check UTR hits
3. idx_exon(gf_exon_t) - check for splice variants
4. idx_tscript(tscript_t) - check for intronic variants, RNAs, etc.
These regidx indexes are created by parsing a gff3 file as follows:
1. create the array "ftr" of all UTR, CDS, exons. This will be
processed later and pruned based on transcript types we want to keep.
In the same go, create the hash "id2tr" of transcripts to keep
(based on biotype) which maps from transcript_id to a transcript. At
the same time also build the hash "gid2gene" which maps from gene_id to
gf_gene_t pointer.
2. build "idx_cds", "idx_tscript", "idx_utr" and "idx_exon" indexes.
Use only features from "ftr" which are present in "id2tr".
3. clean data that won't be needed anymore: ftr, id2tr, gid2gene.
Data structures.
idx_cds, idx_utr, idx_exon, idx_tscript:
as described above, regidx structures for fast lookup of exons/transcripts
overlapping a region, the payload is a pointer to tscript.cds
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <getopt.h>
#include <math.h>
#include <inttypes.h>
#include <htslib/hts.h>
#include <htslib/vcf.h>
#include <htslib/synced_bcf_reader.h>
#include <htslib/khash.h>
#include <htslib/khash_str2int.h>
#include <htslib/kseq.h>
#include <htslib/faidx.h>
#include <errno.h>
#include <unistd.h>
#include <ctype.h>
#include "bcftools.h"
#include "filter.h"
#include "regidx.h"
#include "kheap.h"
#include "smpl_ilist.h"
#include "rbuf.h"
#ifndef __FUNCTION__
# define __FUNCTION__ __func__
#endif
// Logic of the filters: include or exclude sites which match the filters?
#define FLT_INCLUDE 1
#define FLT_EXCLUDE 2
// Definition of splice_region, splice_acceptor and splice_donor
#define N_SPLICE_DONOR 2
#define N_SPLICE_REGION_EXON 3
#define N_SPLICE_REGION_INTRON 8
#define N_REF_PAD 10 // number of bases to avoid boundary effects
#define STRAND_REV 0
#define STRAND_FWD 1
#define TRIM_NONE 0
#define TRIM_5PRIME 1
#define TRIM_3PRIME 2
// How to treat phased/unphased genotypes
#define PHASE_REQUIRE 0 // --phase r
#define PHASE_MERGE 1 // --phase m
#define PHASE_AS_IS 2 // --phase a
#define PHASE_SKIP 3 // --phase s
#define PHASE_NON_REF 4 // --phase R
#define PHASE_DROP_GT 5 // --samples -
// Node types in the haplotype tree
#define HAP_CDS 0
#define HAP_ROOT 1
#define HAP_SSS 2 // start/stop/splice
#define CSQ_PRINTED_UPSTREAM (1<<0)
#define CSQ_SYNONYMOUS_VARIANT (1<<1)
#define CSQ_MISSENSE_VARIANT (1<<2)
#define CSQ_STOP_LOST (1<<3)
#define CSQ_STOP_GAINED (1<<4)
#define CSQ_INFRAME_DELETION (1<<5)
#define CSQ_INFRAME_INSERTION (1<<6)
#define CSQ_FRAMESHIFT_VARIANT (1<<7)
#define CSQ_SPLICE_ACCEPTOR (1<<8)
#define CSQ_SPLICE_DONOR (1<<9)
#define CSQ_START_LOST (1<<10)
#define CSQ_SPLICE_REGION (1<<11)
#define CSQ_STOP_RETAINED (1<<12)
#define CSQ_UTR5 (1<<13)
#define CSQ_UTR3 (1<<14)
#define CSQ_NON_CODING (1<<15)
#define CSQ_INTRON (1<<16)
//#define CSQ_INTERGENIC (1<<17)
#define CSQ_INFRAME_ALTERING (1<<18)
#define CSQ_UPSTREAM_STOP (1<<19) // adds * in front of the csq string
#define CSQ_INCOMPLETE_CDS (1<<20) // to remove START/STOP in incomplete CDS, see ENSG00000173376/synon.vcf
#define CSQ_CODING_SEQUENCE (1<<21) // cannot tell exactly what it is, but it does affect the coding sequence
#define CSQ_ELONGATION (1<<22) // symbolic insertion
#define CSQ_START_RETAINED (1<<23)
// Haplotype-aware consequences, printed in one vcf record only, the rest has a reference @12345
#define CSQ_COMPOUND (CSQ_SYNONYMOUS_VARIANT|CSQ_MISSENSE_VARIANT|CSQ_STOP_LOST|CSQ_STOP_GAINED| \
CSQ_INFRAME_DELETION|CSQ_INFRAME_INSERTION|CSQ_FRAMESHIFT_VARIANT| \
CSQ_START_LOST|CSQ_STOP_RETAINED|CSQ_INFRAME_ALTERING|CSQ_INCOMPLETE_CDS| \
CSQ_UPSTREAM_STOP|CSQ_START_RETAINED)
#define CSQ_START_STOP (CSQ_STOP_LOST|CSQ_STOP_GAINED|CSQ_STOP_RETAINED|CSQ_START_LOST|CSQ_START_RETAINED)
#define CSQ_PRN_STRAND(csq) ((csq)&CSQ_COMPOUND && !((csq)&(CSQ_SPLICE_ACCEPTOR|CSQ_SPLICE_DONOR|CSQ_SPLICE_REGION)))
#define CSQ_PRN_TSCRIPT (~(CSQ_INTRON|CSQ_NON_CODING))
#define CSQ_PRN_BIOTYPE CSQ_NON_CODING
// see kput_vcsq()
const char *csq_strings[] =
{
NULL,
"synonymous",
"missense",
"stop_lost",
"stop_gained",
"inframe_deletion",
"inframe_insertion",
"frameshift",
"splice_acceptor",
"splice_donor",
"start_lost",
"splice_region",
"stop_retained",
"5_prime_utr",
"3_prime_utr",
"non_coding",
"intron",
"intergenic",
"inframe_altering",
NULL,
NULL,
"coding_sequence",
"feature_elongation",
"start_retained"
};
// GFF line types
#define GFF_TSCRIPT_LINE 1
#define GFF_GENE_LINE 2
/*
Genomic features, for fast lookup by position to overlapping features
*/
#define GF_coding_bit 6
#define GF_is_coding(x) ((x) & (1<<GF_coding_bit))
#define GF_MT_rRNA 1 // non-coding: 1, 2, ...
#define GF_MT_tRNA 2
#define GF_lincRNA 3
#define GF_miRNA 4
#define GF_MISC_RNA 5
#define GF_rRNA 6
#define GF_snRNA 7
#define GF_snoRNA 8
#define GF_PROCESSED_TRANSCRIPT 9
#define GF_ANTISENSE 10
#define GF_macro_lncRNA 11
#define GF_ribozyme 12
#define GF_sRNA 13
#define GF_scRNA 14
#define GF_scaRNA 15
#define GF_SENSE_INTRONIC 16
#define GF_SENSE_OVERLAPPING 17
#define GF_PSEUDOGENE 18
#define GF_PROCESSED_PSEUDOGENE 19
#define GF_ARTIFACT 20
#define GF_IG_PSEUDOGENE 21
#define GF_IG_C_PSEUDOGENE 22
#define GF_IG_J_PSEUDOGENE 23
#define GF_IG_V_PSEUDOGENE 24
#define GF_TR_V_PSEUDOGENE 25
#define GF_TR_J_PSEUDOGENE 26
#define GF_MT_tRNA_PSEUDOGENE 27
#define GF_misc_RNA_PSEUDOGENE 28
#define GF_miRNA_PSEUDOGENE 29
#define GF_RIBOZYME 30
#define GF_RETAINED_INTRON 31
#define GF_RETROTRANSPOSED 32
#define GF_tRNA_PSEUDOGENE 33
#define GF_TRANSCRIBED_PROCESSED_PSEUDOGENE 34
#define GF_TRANSCRIBED_UNPROCESSED_PSEUDOGENE 35
#define GF_TRANSCRIBED_UNITARY_PSEUDOGENE 36
#define GF_TRANSLATED_UNPROCESSED_PSEUDOGENE 37
#define GF_TRANSLATED_PROCESSED_PSEUDOGENE 38
#define GF_KNOWN_NCRNA 39
#define GF_UNITARY_PSEUDOGENE 40
#define GF_UNPROCESSED_PSEUDOGENE 41
#define GF_LRG_GENE 42
#define GF_3PRIME_OVERLAPPING_ncRNA 43
#define GF_DISRUPTED_DOMAIN 44
#define GF_vaultRNA 45
#define GF_BIDIRECTIONAL_PROMOTER_lncRNA 46
#define GF_AMBIGUOUS_ORF 47
#define GF_PROTEIN_CODING (1|(1<<GF_coding_bit)) // coding: 65, 66, ...
#define GF_POLYMORPHIC_PSEUDOGENE (2|(1<<GF_coding_bit))
#define GF_IG_C (3|(1<<GF_coding_bit))
#define GF_IG_D (4|(1<<GF_coding_bit))
#define GF_IG_J (5|(1<<GF_coding_bit))
#define GF_IG_LV (6|(1<<GF_coding_bit))
#define GF_IG_V (7|(1<<GF_coding_bit))
#define GF_TR_C (8|(1<<GF_coding_bit))
#define GF_TR_D (9|(1<<GF_coding_bit))
#define GF_TR_J (10|(1<<GF_coding_bit))
#define GF_TR_V (11|(1<<GF_coding_bit))
#define GF_NMD (12|(1<<GF_coding_bit))
#define GF_NON_STOP_DECAY (13|(1<<GF_coding_bit))
#define GF_CDS ((1<<(GF_coding_bit+1))+1) // special types: 129, 130, ...
#define GF_EXON ((1<<(GF_coding_bit+1))+2)
#define GF_UTR3 ((1<<(GF_coding_bit+1))+3)
#define GF_UTR5 ((1<<(GF_coding_bit+1))+4)
// GF_MAX = (1<<30)-1, see hap_node_t
#define CDS_PHASE_UNKN 3
typedef struct _tscript_t tscript_t;
typedef struct
{
tscript_t *tr; // transcript
uint32_t beg; // the start coordinate of the CDS (on the reference strand, 0-based)
uint32_t pos; // 0-based index of the first exon base within the transcript (only to
// update hap_node_t.sbeg in hap_init, could be calculated on the fly)
uint32_t len; // exon length
uint32_t icds:30, // exon index within the transcript
phase:2; // offset of the CDS: 0,1,2 or 3 for unknown
}
gf_cds_t;
typedef struct
{
char *name; // human readable name, e.g. ORF45
uint32_t iseq;
}
gf_gene_t;
typedef struct
{
uint32_t beg,end;
tscript_t *tr;
}
gf_exon_t;
typedef enum { prime3, prime5 } utr_t;
typedef struct
{
utr_t which;
uint32_t beg,end;
tscript_t *tr;
}
gf_utr_t;
/*
Structures related to VCF output:
vcsq_t
information required to assemble consequence lines such as "inframe_deletion|XYZ|ENST01|+|5TY>5I|121ACG>A+124TA>T"
vrec_t
single VCF record and csq tied to this record. (Haplotype can have multiple
consequences in several VCF records. Each record can have multiple consequences
from multiple haplotypes.)
csq_t
a top-level consequence tied to a haplotype
vbuf_t
pos2vbuf
VCF records with the same position clustered together for a fast lookup via pos2vbuf
*/
typedef struct _vbuf_t vbuf_t;
typedef struct _vcsq_t vcsq_t;
struct _vcsq_t
{
uint32_t strand:1,
type:31; // one of CSQ_* types
uint32_t trid;
uint32_t vcf_ial;
uint32_t biotype; // one of GF_* types
char *gene; // gene name
bcf1_t *ref; // if type&CSQ_PRINTED_UPSTREAM, ref consequence "@1234"
kstring_t vstr; // variant string, eg 5TY>5I|121ACG>A+124TA>T
};
typedef struct
{
bcf1_t *line;
uint32_t *fmt_bm; // bitmask of sample consequences with first/second haplotype interleaved
uint32_t nfmt:4, // the bitmask size (the number of integers per sample)
nvcsq:28, mvcsq;
vcsq_t *vcsq; // there can be multiple consequences for a single VCF record
}
vrec_t;
typedef struct
{
uint32_t pos;
vrec_t *vrec; // vcf line that this csq is tied to; needed when printing haplotypes (hap_stage_vcf)
int idx; // 0-based index of the csq at the VCF line, for FMT/BCSQ
vcsq_t type;
}
csq_t;
struct _vbuf_t
{
vrec_t **vrec; // buffer of VCF lines with the same position
int n, m;
uint32_t keep_until; // the maximum transcript end position
};
KHASH_MAP_INIT_INT(pos2vbuf, vbuf_t*)
/*
Structures related to haplotype-aware consequences in coding regions
hap_node_t
node of a haplotype tree. Each transcript has one tree
tscript_t
despite its general name, it is intended for coding transcripts only
hap_t
hstack_t
for traversal of the haplotype tree and braking combined
consequences into independent parts
*/
typedef struct _hap_node_t hap_node_t;
struct _hap_node_t
{
char *seq; // cds segment [parent_node,this_node)
char *var; // variant "ref>alt"
uint32_t type:2, // HAP_ROOT or HAP_CDS
csq:30; // this node's consequence
int dlen; // alt minus ref length: <0 del, >0 ins, 0 substitution
uint32_t rbeg; // variant's VCF position (0-based, inclusive)
int32_t rlen; // variant's rlen; alen=rlen+dlen; fake for non CDS types
uint32_t sbeg; // variant's position on the spliced reference transcript (0-based, inclusive, N_REF_PAD not included)
uint32_t icds; // which exon does this node's variant overlaps
hap_node_t **child, *prev; // children haplotypes and previous coding node
int nchild, mchild;
bcf1_t *cur_rec, *rec; // current VCF record and node's VCF record
int vcf_ial; // which VCF allele generated this node
uint32_t nend; // number of haplotypes ending in this node
int *cur_child, mcur_child; // mapping from the allele to the currently active child
csq_t *csq_list; // list of haplotype's consequences, broken by position (each corresponds to a VCF record)
int ncsq_list, mcsq_list;
};
struct _tscript_t
{
uint32_t id; // transcript id
uint32_t beg,end; // transcript's beg and end coordinate (ref strand, 0-based, inclusive)
uint32_t strand:1, // STRAND_REV or STRAND_FWD
ncds:31, // number of exons
mcds;
gf_cds_t **cds; // ordered list of exons
char *ref; // reference sequence, padded with N_REF_PAD bases on both ends
char *sref; // spliced reference sequence, padded with N_REF_PAD bases on both ends
hap_node_t *root; // root of the haplotype tree
hap_node_t **hap; // pointer to haplotype leaves, two for each sample
int nhap, nsref; // number of haplotypes and length of sref, including 2*N_REF_PAD
uint32_t trim:2, // complete, 5' or 3' trimmed, see TRIM_* types
type:30; // one of GF_* types
gf_gene_t *gene;
};
static inline int cmp_tscript(tscript_t **a, tscript_t **b)
{
return ( (*a)->end < (*b)->end ) ? 1 : 0;
}
KHEAP_INIT(trhp, tscript_t*, cmp_tscript)
typedef khp_trhp_t tr_heap_t;
typedef struct
{
hap_node_t *node; // current node
int ichild; // current child in the active node
int dlen; // total dlen, from the root to the active node
size_t slen; // total sequence length, from the root to the active node
}
hstack_t;
typedef struct
{
int mstack;
hstack_t *stack;
tscript_t *tr; // tr->ref: spliced transcript on ref strand
kstring_t sseq; // spliced haplotype sequence on ref strand
kstring_t tseq; // the variable part of translated haplotype transcript, coding strand
kstring_t tref; // the variable part of translated reference transcript, coding strand
uint32_t sbeg; // stack's sbeg, for cases first node's type is HAP_SSS
int upstream_stop;
}
hap_t;
/*
Helper structures, only for initialization
ftr_t
temporary list of all exons, CDS, UTRs
*/
KHASH_MAP_INIT_INT(int2tscript, tscript_t*)
KHASH_MAP_INIT_INT(int2gene, gf_gene_t*)
typedef struct
{
int type; // GF_CDS, GF_EXON, GF_5UTR, GF_3UTR
uint32_t beg;
uint32_t end;
uint32_t trid;
uint32_t strand:1; // STRAND_REV,STRAND_FWD
uint32_t phase:2; // 0, 1, 2, or 3 for unknown
uint32_t iseq:29;
}
ftr_t;
/*
Mapping from GFF ID string (such as ENST00000450305 or Zm00001d027230_P001)
to integer id. To keep the memory requirements low, the original version
relied on IDs in the form of a string prefix and a numerical id. However,
it turns out that this assumption is not valid for some ensembl GFFs, see
for example Zea_mays.AGPv4.36.gff3.gz
*/
typedef struct
{
void *str2id; // khash_str2int
int nstr, mstr;
char **str; // numeric id to string
}
id_tbl_t;
typedef struct
{
// all exons, CDS, UTRs
ftr_t *ftr;
int nftr, mftr;
// mapping from gene id to gf_gene_t
kh_int2gene_t *gid2gene;
// mapping from transcript id to tscript, for quick CDS anchoring
kh_int2tscript_t *id2tr;
// sequences
void *seq2int; // str2int hash
char **seq;
int nseq, mseq;
// ignored biotypes
void *ignored_biotypes;
id_tbl_t gene_ids; // temporary table for mapping between gene id (eg. Zm00001d027245) and a numeric idx
}
aux_t;
typedef struct _args_t
{
// the main regidx lookups, from chr:beg-end to overlapping features and
// index iterator
regidx_t *idx_cds, *idx_utr, *idx_exon, *idx_tscript;
regitr_t *itr;
// temporary structures, deleted after initializtion
aux_t init;
// text tab-delimited output (out) or vcf/bcf output (out_fh)
FILE *out;
htsFile *out_fh;
// vcf
bcf_srs_t *sr;
bcf_hdr_t *hdr;
int hdr_nsmpl; // actual number of samples in the vcf, for bcf_update_format_values()
// include or exclude sites which match the filters
filter_t *filter;
char *filter_str;
int filter_logic; // FLT_INCLUDE or FLT_EXCLUDE
// samples to process
int sample_is_file;
char *sample_list;
smpl_ilist_t *smpl;
char *outdir, **argv, *fa_fname, *gff_fname, *output_fname;
char *bcsq_tag;
int argc, output_type, clevel;
int phase, verbosity, local_csq, record_cmd_line;
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)
int ncsq2_small_warned;
int brief_predictions;
int rid; // current chromosome
tr_heap_t *active_tr; // heap of active transcripts for quick flushing
hap_t *hap; // transcript haplotype recursion
vbuf_t **vcf_buf; // buffered VCF lines to annotate with CSQ and flush
rbuf_t vcf_rbuf; // round buffer indexes to vcf_buf
kh_pos2vbuf_t *pos2vbuf; // fast lookup of buffered lines by position
tscript_t **rm_tr; // buffer of transcripts to clean
int nrm_tr, mrm_tr;
csq_t *csq_buf; // pool of csq not managed by hap_node_t, i.e. non-CDS csqs
int ncsq_buf, mcsq_buf;
id_tbl_t tscript_ids; // mapping between transcript id (eg. Zm00001d027245_T001) and a numeric idx
int force; // force run under various conditions. Currently only to skip out-of-phase transcripts
int n_threads; // extra compression/decompression threads
faidx_t *fai;
kstring_t str, str2;
int32_t *gt_arr, mgt_arr;
}
args_t;
// AAA, AAC, ...
const char *gencode = "KNKNTTTTRSRSIIMIQHQHPPPPRRRRLLLLEDEDAAAAGGGGVVVV*Y*YSSSS*CWCLFLF";
const uint8_t nt4[] =
{
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
4,0,4,1, 4,4,4,2, 4,4,4,4, 4,4,4,4,
4,4,4,4, 3,4,4,4, 4,4,4,4, 4,4,4,4,
4,0,4,1, 4,4,4,2, 4,4,4,4, 4,4,4,4,
4,4,4,4, 3
};
const uint8_t cnt4[] =
{
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
4,4,4,4, 4,4,4,4, 4,4,4,4, 4,4,4,4,
4,3,4,2, 4,4,4,1, 4,4,4,4, 4,4,4,4,
4,4,4,4, 0,4,4,4, 4,4,4,4, 4,4,4,4,
4,3,4,2, 4,4,4,1, 4,4,4,4, 4,4,4,4,
4,4,4,4, 0
};
#define dna2aa(x) gencode[ nt4[(uint8_t)(x)[0]]<<4 | nt4[(uint8_t)(x)[1]]<<2 | nt4[(uint8_t)(x)[2]] ]
#define cdna2aa(x) gencode[ cnt4[(uint8_t)(x)[2]]<<4 | cnt4[(uint8_t)(x)[1]]<<2 | cnt4[(uint8_t)(x)[0]] ]
static const char *gf_strings_noncoding[] =
{
"MT_rRNA", "MT_tRNA", "lincRNA", "miRNA", "misc_RNA", "rRNA", "snRNA", "snoRNA", "processed_transcript",
"antisense", "macro_lncRNA", "ribozyme", "sRNA", "scRNA", "scaRNA", "sense_intronic", "sense_overlapping",
"pseudogene", "processed_pseudogene", "artifact", "IG_pseudogene", "IG_C_pseudogene", "IG_J_pseudogene",
"IG_V_pseudogene", "TR_V_pseudogene", "TR_J_pseudogene", "MT_tRNA_pseudogene", "misc_RNA_pseudogene",
"miRNA_pseudogene", "ribozyme", "retained_intron", "retrotransposed", "Trna_pseudogene", "transcribed_processed_pseudogene",
"transcribed_unprocessed_pseudogene", "transcribed_unitary_pseudogene", "translated_unprocessed_pseudogene",
"translated_processed_pseudogene", "known_ncRNA", "unitary_pseudogene", "unprocessed_pseudogene",
"LRG_gene", "3_prime_overlapping_ncRNA", "disrupted_domain", "vaultRNA", "bidirectional_promoter_lncRNA", "ambiguous_orf"
};
static const char *gf_strings_coding[] = { "protein_coding", "polymorphic_pseudogene", "IG_C", "IG_D", "IG_J", "IG_LV", "IG_V", "TR_C", "TR_D", "TR_J", "TR_V", "NMD", "non_stop_decay"};
static const char *gf_strings_special[] = { "CDS", "exon", "3_prime_UTR", "5_prime_UTR" };
const char *gf_type2gff_string(int type)
{
if ( !GF_is_coding(type) )
{
if ( type < (1<<GF_coding_bit) ) return gf_strings_noncoding[type-1];
type &= (1<<(GF_coding_bit+1)) - 1;
return gf_strings_special[type - 1];
}
type &= (1<<GF_coding_bit) - 1;
return gf_strings_coding[type - 1];
}
/*
gff parsing functions
*/
static inline int feature_set_seq(args_t *args, char *chr_beg, char *chr_end)
{
aux_t *aux = &args->init;
char c = chr_end[1];
chr_end[1] = 0;
int iseq;
if ( khash_str2int_get(aux->seq2int, chr_beg, &iseq)!=0 )
{
// check for possible mismatch in chromosome naming convention such as chrX vs X
char *new_chr = NULL;
if ( faidx_has_seq(args->fai,chr_beg) )
new_chr = strdup(chr_beg); // valid chr name, the same in gff and faidx
else
{
int len = strlen(chr_beg);
if ( !strncmp("chr",chr_beg,3) && len>3 )
new_chr = strdup(chr_beg+3); // gff has the prefix, faidx does not
else
{
new_chr = malloc(len+4); // gff does not have the prefix, faidx has
memcpy(new_chr,"chr",3);
memcpy(new_chr+3,chr_beg,len);
new_chr[len+3] = 0;
}
if ( !faidx_has_seq(args->fai,new_chr) ) // modification did not help, this sequence is not in fai
{
static int unkwn_chr_warned = 0;
if ( !unkwn_chr_warned && args->verbosity>0 )
fprintf(stderr,"Warning: GFF chromosome \"%s\" not part of the reference genome\n",chr_beg);
unkwn_chr_warned = 1;
free(new_chr);
new_chr = strdup(chr_beg); // use the original sequence name
}
}
if ( khash_str2int_get(aux->seq2int, new_chr, &iseq)!=0 )
{
hts_expand(char*, aux->nseq+1, aux->mseq, aux->seq);
aux->seq[aux->nseq] = new_chr;
iseq = khash_str2int_inc(aux->seq2int, aux->seq[aux->nseq]);
aux->nseq++;
assert( aux->nseq < 1<<29 ); // see gf_gene_t.iseq and ftr_t.iseq
}
else
free(new_chr);
}
chr_end[1] = c;
return iseq;
}
static inline char *gff_skip(const char *line, char *ss)
{
while ( *ss && *ss!='\t' ) ss++;
if ( !*ss ) error("[%s:%d %s] Could not parse the line: %s\n",__FILE__,__LINE__,__FUNCTION__,line);
return ss+1;
}
static inline void gff_parse_chr(const char *line, char **chr_beg, char **chr_end)
{
char *se = (char*) line;
while ( *se && *se!='\t' ) se++;
if ( !*se ) error("[%s:%d %s] Could not parse the line: %s\n",__FILE__,__LINE__,__FUNCTION__,line);
*chr_beg = (char*) line;
*chr_end = se-1;
}
static inline char *gff_parse_beg_end(const char *line, char *ss, uint32_t *beg, uint32_t *end)
{
char *se = ss;
*beg = strtol(ss, &se, 10) - 1;
if ( ss==se ) error("[%s:%d %s] Could not parse the line:\n\t%s\n\t%s\n",__FILE__,__LINE__,__FUNCTION__,line,ss);
ss = se+1;
*end = strtol(ss, &se, 10) - 1;
if ( ss==se ) error("[%s:%d %s] Could not parse the line: %s\n",__FILE__,__LINE__,__FUNCTION__,line);
return se+1;
}
static void gff_id_init(id_tbl_t *tbl)
{
memset(tbl, 0, sizeof(*tbl));
tbl->str2id = khash_str2int_init();
}
static void gff_id_destroy(id_tbl_t *tbl)
{
khash_str2int_destroy_free(tbl->str2id);
free(tbl->str);
}
static inline uint32_t gff_id_parse(id_tbl_t *tbl, const char *line, const char *needle, char *ss)
{
ss = strstr(ss,needle); // e.g. "ID=transcript:"
if ( !ss ) error("[%s:%d %s] Could not parse the line, \"%s\" not present: %s\n",__FILE__,__LINE__,__FUNCTION__,needle,line);
ss += strlen(needle);
char *se = ss;
while ( *se && *se!=';' && !isspace(*se) ) se++;
char tmp = *se;
*se = 0;
int id;
if ( khash_str2int_get(tbl->str2id, ss, &id) < 0 )
{
id = tbl->nstr++;
hts_expand(char*, tbl->nstr, tbl->mstr, tbl->str);
tbl->str[id] = strdup(ss);
khash_str2int_set(tbl->str2id, tbl->str[id], id);
}
*se = tmp;
return id;
}
static inline int gff_parse_type(char *line)
{
line = strstr(line,"ID=");
if ( !line ) return -1;
line += 3;
if ( !strncmp(line,"transcript:",11) ) return GFF_TSCRIPT_LINE;
else if ( !strncmp(line,"gene:",5) ) return GFF_GENE_LINE;
return -1;
}
static inline int gff_parse_biotype(char *_line)
{
char *line = strstr(_line,"biotype=");
if ( !line ) return -1;
line += 8;
switch (*line)
{
case 'p':
if ( !strncmp(line,"protein_coding",14) ) return GF_PROTEIN_CODING;
else if ( !strncmp(line,"pseudogene",10) ) return GF_PSEUDOGENE;
else if ( !strncmp(line,"processed_transcript",20) ) return GF_PROCESSED_TRANSCRIPT;
else if ( !strncmp(line,"processed_pseudogene",20) ) return GF_PROCESSED_PSEUDOGENE;
else if ( !strncmp(line,"polymorphic_pseudogene",22) ) return GF_POLYMORPHIC_PSEUDOGENE;
break;
case 'a':
if ( !strncmp(line,"artifact",8) ) return GF_ARTIFACT;
else if ( !strncmp(line,"antisense",9) ) return GF_ANTISENSE;
else if ( !strncmp(line,"ambiguous_orf",13) ) return GF_AMBIGUOUS_ORF;
break;
case 'I':
if ( !strncmp(line,"IG_C_gene",9) ) return GF_IG_C;
else if ( !strncmp(line,"IG_D_gene",9) ) return GF_IG_D;
else if ( !strncmp(line,"IG_J_gene",9) ) return GF_IG_J;
else if ( !strncmp(line,"IG_LV_gene",10) ) return GF_IG_LV;
else if ( !strncmp(line,"IG_V_gene",9) ) return GF_IG_V;
else if ( !strncmp(line,"IG_pseudogene",13) ) return GF_IG_PSEUDOGENE;
else if ( !strncmp(line,"IG_C_pseudogene",15) ) return GF_IG_C_PSEUDOGENE;
else if ( !strncmp(line,"IG_J_pseudogene",15) ) return GF_IG_J_PSEUDOGENE;
else if ( !strncmp(line,"IG_V_pseudogene",15) ) return GF_IG_V_PSEUDOGENE;
break;
case 'T':
if ( !strncmp(line,"TR_C_gene",9) ) return GF_TR_C;
else if ( !strncmp(line,"TR_D_gene",9) ) return GF_TR_D;
else if ( !strncmp(line,"TR_J_gene",9) ) return GF_TR_J;
else if ( !strncmp(line,"TR_V_gene",9) ) return GF_TR_V;
else if ( !strncmp(line,"TR_V_pseudogene",15) ) return GF_TR_V_PSEUDOGENE;
else if ( !strncmp(line,"TR_J_pseudogene",15) ) return GF_TR_J_PSEUDOGENE;
break;
case 'M':
if ( !strncmp(line,"Mt_tRNA_pseudogene",18) ) return GF_MT_tRNA_PSEUDOGENE;
else if ( !strncmp(line,"Mt_tRNA",7) ) return GF_MT_tRNA;
else if ( !strncmp(line,"Mt_rRNA",7) ) return GF_MT_tRNA;
break;
case 'l':
if ( !strncmp(line,"lincRNA",7) ) return GF_lincRNA;
break;
case 'm':
if ( !strncmp(line,"macro_lncRNA",12) ) return GF_macro_lncRNA;
else if ( !strncmp(line,"misc_RNA_pseudogene",19) ) return GF_misc_RNA_PSEUDOGENE;
else if ( !strncmp(line,"miRNA_pseudogene",16) ) return GF_miRNA_PSEUDOGENE;
else if ( !strncmp(line,"miRNA",5) ) return GF_miRNA;
else if ( !strncmp(line,"misc_RNA",8) ) return GF_MISC_RNA;
break;
case 'r':
if ( !strncmp(line,"rRNA",4) ) return GF_rRNA;
else if ( !strncmp(line,"ribozyme",8) ) return GF_RIBOZYME;
else if ( !strncmp(line,"retained_intron",15) ) return GF_RETAINED_INTRON;
else if ( !strncmp(line,"retrotransposed",15) ) return GF_RETROTRANSPOSED;
break;
case 's':
if ( !strncmp(line,"snRNA",5) ) return GF_snRNA;
else if ( !strncmp(line,"sRNA",4) ) return GF_sRNA;
else if ( !strncmp(line,"scRNA",5) ) return GF_scRNA;
else if ( !strncmp(line,"scaRNA",6) ) return GF_scaRNA;
else if ( !strncmp(line,"snoRNA",6) ) return GF_snoRNA;
else if ( !strncmp(line,"sense_intronic",14) ) return GF_SENSE_INTRONIC;
else if ( !strncmp(line,"sense_overlapping",17) ) return GF_SENSE_OVERLAPPING;
break;
case 't':
if ( !strncmp(line,"tRNA_pseudogene",15) ) return GF_tRNA_PSEUDOGENE;
else if ( !strncmp(line,"transcribed_processed_pseudogene",32) ) return GF_TRANSCRIBED_PROCESSED_PSEUDOGENE;
else if ( !strncmp(line,"transcribed_unprocessed_pseudogene",34) ) return GF_TRANSCRIBED_UNPROCESSED_PSEUDOGENE;
else if ( !strncmp(line,"transcribed_unitary_pseudogene",30) ) return GF_TRANSCRIBED_UNITARY_PSEUDOGENE;
else if ( !strncmp(line,"translated_unprocessed_pseudogene",33) ) return GF_TRANSLATED_UNPROCESSED_PSEUDOGENE;
else if ( !strncmp(line,"translated_processed_pseudogene",31) ) return GF_TRANSLATED_PROCESSED_PSEUDOGENE;
break;
case 'n':
if ( !strncmp(line,"nonsense_mediated_decay",23) ) return GF_NMD;
else if ( !strncmp(line,"non_stop_decay",14) ) return GF_NON_STOP_DECAY;
break;
case 'k':
if ( !strncmp(line,"known_ncrna",11) ) return GF_KNOWN_NCRNA;
break;
case 'u':
if ( !strncmp(line,"unitary_pseudogene",18) ) return GF_UNITARY_PSEUDOGENE;
else if ( !strncmp(line,"unprocessed_pseudogene",22) ) return GF_UNPROCESSED_PSEUDOGENE;
break;
case 'L':
if ( !strncmp(line,"LRG_gene",8) ) return GF_LRG_GENE;
break;
case '3':
if ( !strncmp(line,"3prime_overlapping_ncRNA",24) ) return GF_3PRIME_OVERLAPPING_ncRNA;
break;
case 'd':
if ( !strncmp(line,"disrupted_domain",16) ) return GF_DISRUPTED_DOMAIN;
break;
case 'v':
if ( !strncmp(line,"vaultRNA",8) ) return GF_vaultRNA;
break;
case 'b':
if ( !strncmp(line,"bidirectional_promoter_lncRNA",29) ) return GF_BIDIRECTIONAL_PROMOTER_lncRNA;
break;
}
return 0;
}
static inline int gff_ignored_biotype(args_t *args, char *ss)
{
ss = strstr(ss,"biotype=");
if ( !ss ) return 0;
ss += 8;
char *se = ss, tmp;
while ( *se && *se!=';' ) se++;
tmp = *se;
*se = 0;
char *key = ss;
int n = 0;
if ( khash_str2int_get(args->init.ignored_biotypes, ss, &n)!=0 ) key = strdup(ss);
khash_str2int_set(args->init.ignored_biotypes, key, n+1);
*se = tmp;
return 1;
}
gf_gene_t *gene_init(aux_t *aux, uint32_t gene_id)
{
khint_t k = kh_get(int2gene, aux->gid2gene, (int)gene_id);
gf_gene_t *gene = (k == kh_end(aux->gid2gene)) ? NULL : kh_val(aux->gid2gene, k);
if ( !gene )
{
gene = (gf_gene_t*) calloc(1,sizeof(gf_gene_t));
int ret;
k = kh_put(int2gene, aux->gid2gene, (int)gene_id, &ret);
kh_val(aux->gid2gene,k) = gene;
}
return gene;
}
void gff_parse_transcript(args_t *args, const char *line, char *ss, ftr_t *ftr)
{
aux_t *aux = &args->init;
int biotype = gff_parse_biotype(ss);
if ( biotype <= 0 )
{
if ( !gff_ignored_biotype(args, ss) && args->verbosity > 0 ) fprintf(stderr,"ignored transcript: %s\n",line);
return;
}
// create a mapping from transcript_id to gene_id
uint32_t trid = gff_id_parse(&args->tscript_ids, line, "ID=transcript:", ss);
uint32_t gene_id = gff_id_parse(&args->init.gene_ids, line, "Parent=gene:", ss);
tscript_t *tr = (tscript_t*) calloc(1,sizeof(tscript_t));
tr->id = trid;
tr->strand = ftr->strand;
tr->gene = gene_init(aux, gene_id);
tr->type = biotype;
tr->beg = ftr->beg;
tr->end = ftr->end;
khint_t k;
int ret;
k = kh_put(int2tscript, aux->id2tr, (int)trid, &ret);
kh_val(aux->id2tr,k) = tr;
}
void gff_parse_gene(args_t *args, const char *line, char *ss, char *chr_beg, char *chr_end, ftr_t *ftr)
{
int biotype = gff_parse_biotype(ss);
if ( biotype <= 0 )
{
if ( !gff_ignored_biotype(args, ss) && args->verbosity > 0 ) fprintf(stderr,"ignored gene: %s\n",line);
return;
}
aux_t *aux = &args->init;
// substring search for "ID=gene:ENSG00000437963"
uint32_t gene_id = gff_id_parse(&aux->gene_ids, line, "ID=gene:", ss);
gf_gene_t *gene = gene_init(aux, gene_id);
assert( !gene->name ); // the gene_id should be unique
gene->iseq = feature_set_seq(args, chr_beg,chr_end);
// substring search for "Name=OR4F5"
ss = strstr(chr_end+2,"Name=");
if ( ss )
{
ss += 5;
char *se = ss;
while ( *se && *se!=';' && !isspace(*se) ) se++;
gene->name = (char*) malloc(se-ss+1);
memcpy(gene->name,ss,se-ss);
gene->name[se-ss] = 0;
}
else
gene->name = strdup(aux->gene_ids.str[gene_id]); // Name=<GeneName> field is not present, use the gene ID instead
}
int gff_parse(args_t *args, char *line, ftr_t *ftr)
{
// - skip empty lines and commented lines
// - columns
// 1. chr
// 2. <skip>
// 3. CDS, transcript, gene, ...
// 4-5. beg,end
// 6. <skip>
// 7. strand
// 8. phase
// 9. Parent=transcript:ENST(\d+);ID=... etc
char *ss = line;