-
Notifications
You must be signed in to change notification settings - Fork 13
/
gff.cpp
3715 lines (3597 loc) · 122 KB
/
gff.cpp
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
#include "gff.h"
GffNames* GffObj::names=NULL;
//global set of feature names, attribute names etc.
// -- common for all GffObjs in current application!
const uint GFF_MAX_LOCUS = 7000000; //longest known gene in human is ~2.2M, UCSC claims a gene for mouse of ~ 3.1 M
const uint GFF_MAX_EXON = 30000; //longest known exon in human is ~11K
const uint GFF_MAX_INTRON= 6000000; //Ensembl shows a >5MB mouse intron
const int GFF_MIN_INTRON = 4; //for mergeCloseExons option
//bool gff_show_warnings = false; //global setting, set by GffReader->showWarnings()
int gff_fid_mRNA=0; //mRNA (has CDS)
int gff_fid_transcript=1; // generic "transcript" feature
int gff_fid_exon=2; // generic "exon"-like feature (exon,CDS,UTR,start/stop codon)
int gff_fid_CDS=3; // CDS feature (CDS, start/stop codon)
const char* exonTypes[]={ "None", "StartCodon", "StopCodon",
"CDS", "UTR", "CDS+UTR", "exon" };
const GffScore GFFSCORE_NONE;
//const uint gfo_flag_LEVEL_MSK = 0x00FF0000;
//const byte gfo_flagShift_LEVEL = 16;
void gffnames_ref(GffNames* &n) {
if (n==NULL) n=new GffNames();
n->numrefs++;
}
void gffnames_unref(GffNames* &n) {
if (n==NULL) GError("Error: attempt to remove reference to null GffNames object!\n");
n->numrefs--;
if (n->numrefs==0) { delete n; n=NULL; }
}
const byte CLASSCODE_OVL_RANK = 14; //rank value just above 'o' class code
//rank value < this means exon overlap
const byte CLASSCODE_J_RANK = 6; // all junctional based overlaps
byte classcode_rank(char c) {
switch (c) {
case '=': return 0; // intron chain match or full exon chain match if strict matching is enabled
case '~': return 1; // intron chain match when strict matching is enabled
case ':': return 2; // intron chain match with no CDS match when cds matching is enabled
case '_': return 3; // intron chain match with no CDS match when strict matching and cds matching is enabled
case 'c': return 4; // containment, perfect partial match (transfrag contained in reference)
case 'k': return 4; // reverse containment (reference contained in transfrag)
case 'm': return 6; // full span overlap with all reference introns either matching or retained
case 'n': return 6; // partial overlap transfrag with at least one intron retention
case 'j': return 6; // multi-exon transfrag overlap with at least one junction match OR intron overlap!
case 'e': return 12; // single exon transfrag partially overlapping an intron of reference (possible pre-mRNA fragment)
case 'o': return 12; // other generic exon overlap
//**** >14 => no exon overlaps (not on the same strand) from here on *****
case 's': return 16; //"shadow" - an intron overlaps with a ref intron on the opposite strand (wrong strand mapping?)
case 'x': return 18; // generic overlap on opposite strand (usually wrong strand mapping)
case 'i': return 20; // intra-intron (transfrag fully contained within a reference intron)
case 'y': return 30; // no exon overlap: ref exons fall within transfrag introns! (reverse of i)
case 'p': return 90; // polymerase run
case 'r': return 92; // repeats
case 'u': return 94; // intergenic
case 0 : return 100;
default: return 96;
}
}
const char* strExonType(char xtype) {
static const char* extbl[7]={"None", "start_codon", "stop_codon", "CDS", "UTR", "CDS_UTR", "exon"};
if (xtype>0 && xtype<7)
return extbl[(int)xtype];
else return "NULL";
}
int gfo_cmpByLoc(const pointer p1, const pointer p2) {
GffObj& g1=*((GffObj*)p1);
GffObj& g2=*((GffObj*)p2);
if (g1.gseq_id==g2.gseq_id) {
if (g1.start!=g2.start)
return (int)(g1.start-g2.start);
else if (g1.getLevel()!=g2.getLevel())
return (int)(g1.getLevel()-g2.getLevel());
else
if (g1.end!=g2.end)
return (int)(g1.end-g2.end);
else return strcmp(g1.getID(), g2.getID());
}
else //return (int)(g1.gseq_id-g2.gseq_id); // input order !
return strcmp(g1.getGSeqName(), g2.getGSeqName()); //lexicographic !
}
//comparator for ordering by reference sequence (chromosome) index
int gfo_cmpRefByID(const pointer p1, const pointer p2) {
GffObj& g1=*((GffObj*)p1);
GffObj& g2=*((GffObj*)p2);
if (g1.gseq_id==g2.gseq_id) {
if (g1.start!=g2.start)
return (int)(g1.start-g2.start);
else if (g1.getLevel()!=g2.getLevel())
return (int)(g1.getLevel()-g2.getLevel());
else
if (g1.end!=g2.end)
return (int)(g1.end-g2.end);
else return strcmp(g1.getID(), g2.getID());
}
else return (g1.gseq_id-g2.gseq_id); // sort refs by their id# order
}
char* GffLine::extractGFFAttr(char* & infostr, const char* oline, const char* attr, bool caseStrict,
bool enforce_GTF2, int* rlen, bool deleteAttr) {
//parse a key attribute and remove it from the info string
//(only works for attributes that have values following them after ' ' or '=')
static const char GTF2_ERR[]="Error parsing attribute %s ('\"' required for GTF) at line:\n%s\n";
int attrlen=strlen(attr);
char cend=attr[attrlen-1];
//char* pos = (caseStrict) ? strstr(info, attr) : strifind(info, attr);
//must make sure attr is not found in quoted text
char* pos=infostr;
char prevch=0;
bool in_str=false;
bool notfound=true;
int (*strcmpfn)(const char*, const char*, int) = caseStrict ? Gstrcmp : Gstricmp;
while (notfound && *pos) {
char ch=*pos;
if (ch=='"') {
in_str=!in_str;
pos++;
prevch=ch;
continue;
}
if (!in_str && (prevch==0 || prevch==' ' || prevch == ';')
&& strcmpfn(attr, pos, attrlen)==0) {
//attr match found
//check for word boundary on right
char* epos=pos+attrlen;
if (cend=='=' || cend==' ' || *epos==0 || *epos==' ') {
notfound=false;
break;
}
//not a perfect match, move on
pos=epos;
prevch=*(pos-1);
continue;
}
//not a match or in_str
prevch=ch;
pos++;
}
if (notfound) return NULL;
char* vp=pos+attrlen;
while (*vp==' ') vp++;
if (*vp==';' || *vp==0) {
GMessage("Warning: cannot parse value of GFF attribute \"%s\" at line:\n%s\n", attr, oline);
return NULL;
}
bool dq_enclosed=false; //value string enclosed by double quotes
if (*vp=='"') {
dq_enclosed=true;
vp++;
}
if (enforce_GTF2 && !dq_enclosed)
GError(GTF2_ERR, attr, oline);
char* vend=vp;
if (dq_enclosed) {
while (*vend!='"' && *vend!=';' && *vend!=0) vend++;
}
else {
while (*vend!=';' && *vend!=0) vend++;
}
if (enforce_GTF2 && *vend!='"')
GError(GTF2_ERR, attr, oline);
char *r=Gstrdup(vp, vend-1);
if (rlen) *rlen = vend-vp;
if (deleteAttr) {//-- remove this attribute from infostr
while (*vend!=0 && (*vend=='"' || *vend==';' || *vend==' ')) vend++;
if (*vend==0) vend--;
for (char *src=vend, *dest=pos;;src++,dest++) {
*dest=*src; //shift the rest of infostr (copy over)
if (*src==0) break;
}
}
return r;
}
BEDLine::BEDLine(GffReader* reader, const char* l): skip(true), dupline(NULL), line(NULL), llen(0),
gseqname(NULL), fstart(0), fend(0), strand(0), ID(NULL), info(NULL),
cds_start(0), cds_end(0), cds_phase(0), exons(1) {
if (reader==NULL || l==NULL) return;
llen=strlen(l);
GMALLOC(line,llen+1);
memcpy(line, l, llen+1);
GMALLOC(dupline, llen+1);
memcpy(dupline, l, llen+1);
char* t[14];
int i=0;
int tidx=1;
t[0]=line;
if (startsWith(line, "browser ") || startsWith(line, "track "))
return;
while (line[i]!=0) {
if (line[i]=='\t') {
line[i]=0;
t[tidx]=line+i+1;
tidx++;
//our custom BED-13+ format, with GFF3 attributes in 13th column
if (tidx>12) { info=t[12]; break; }
}
i++;
}
/* if (tidx<6) { // require BED-6+ lines
GMessage("Warning: 6+ BED columns expected, instead found:\n%s\n", l);
return;
}
*/
gseqname=t[0];
char* p=t[1];
if (!parseUInt(p,fstart)) {
GMessage("Warning: invalid BED start coordinate at line:\n%s\n",l);
return;
}
++fstart; //BED start is 0 based
p=t[2];
if (!parseUInt(p,fend)) {
GMessage("Warning: invalid BED end coordinate at line:\n%s\n",l);
return;
}
if (fend<fstart) Gswap(fend,fstart); //make sure fstart<=fend, always
if (tidx>5) {
strand=*t[5];
if (strand!='-' && strand !='.' && strand !='+') {
GMessage("Warning: unrecognized BED strand at line:\n%s\n",l);
return;
}
}
else strand='.';
//if (tidx>12) ID=t[12];
// else ID=t[3];
ID=t[3];
//now parse the exons, if any
if (tidx>11) {
int numexons=0;
p=t[9];
if (!parseInt(p, numexons) || numexons<=0) {
GMessage("Warning: invalid BED block count at line:\n%s\n",l);
return;
}
char** blen;
char** bstart;
GMALLOC(blen, numexons * sizeof(char*));
GMALLOC(bstart, numexons * sizeof(char*));
i=0;
int b=1;
blen[0]=t[10];
while (t[10][i]!=0 && b<=numexons) {
if (t[10][i]==',') {
t[10][i]=0;
if (b<numexons)
blen[b]=t[10]+i+1;
b++;
}
i++;
}
b=1;i=0;
bstart[0]=t[11];
while (t[11][i]!=0 && b<=numexons) {
if (t[11][i]==',') {
t[11][i]=0;
if (b<numexons)
bstart[b]=t[11]+i+1;
b++;
}
i++;
}
GSeg ex;
for (i=0;i<numexons;++i) {
int exonlen;
if (!strToInt(blen[i], exonlen) || exonlen<=0) {
GMessage("Warning: invalid BED block size %s at line:\n%s\n",blen[i], l);
return;
}
int exonstart;
if (!strToInt(bstart[i], exonstart) || exonstart<0) {
GMessage("Warning: invalid BED block start %s at line:\n%s\n",bstart[i], l);
return;
}
if (i==0 && exonstart!=0) {
GMessage("Warning: first BED block start is %d>0 at line:\n%s\n",exonstart, l);
return;
}
exonstart+=fstart;
uint exonend=exonstart+exonlen-1;
if ((uint)exonstart>fend || exonend>fend) {
GMessage("Warning: BED exon %d-%d is outside record boundary at line:\n%s\n",exonstart,exonend, l);
return;
}
ex.start=exonstart;ex.end=exonend;
exons.Add(ex);
}
GFREE(blen);
GFREE(bstart);
}
else { //take it as single-exon transcript
GSeg v(fstart, fend);
exons.Add(v);
}
if (info!=NULL) {
char* cdstr=GffLine::extractGFFAttr(info, dupline, "CDS=");
if (cdstr) {
char* p=strchr(cdstr, ':');
if (p!=NULL) {
*p='\0'; ++p;
}
if (strToUInt(cdstr, cds_start) && cds_start>=fstart-1) {
++cds_start;
if (!strToUInt(p, cds_end) || cds_end>fend) {
GMessage("Warning: invalid CDS (%d-%d) discarded for line:\n%s\n",
cds_start, cds_end, dupline);
cds_start=0;
cds_end=0; //invalid CDS coordinates
}
}
char* cdstr_phase=NULL;
if (cds_start>0 && (cdstr_phase=GffLine::extractGFFAttr(info, dupline, "CDSphase="))!=NULL) {
cds_phase=cdstr_phase[0];
GFREE(cdstr_phase);
}
GFREE(cdstr);
}
}
if (cds_start==0 && cds_end==0 && tidx>7) {
//check if columns 7,8 can be reasonably assumed to be CDS start-end coordinates
if (strToUInt(t[6], cds_start) && strToUInt(t[7], cds_end) && cds_end>cds_start) {
if (cds_start>=fstart-1 && cds_end<=fend)
cds_start++;
else { cds_start=0; cds_end=0; }
}
}
skip=false;
}
bool GffLine::parseSegmentList(GVec<GSeg>& segs, char* str) {
bool segs_valid=false;
char* p=strchr(str, '-');
if (p!=NULL && p>str) {
GDynArray<char*> ss;
strsplit(str, ss, ',');
GSeg seg;
segs_valid=true;
for (uint i=0;i<ss.Count();++i) {
char* p=strchr(ss[i], '-');
if (p==NULL) {
segs_valid=false;
break;
}
*p='\0'; ++p;
int xstart=0, xend=0;
if (!strToInt(ss[i], xstart) || xstart<(int)fstart || xstart>(int)fend){
segs_valid=false;
break;
}
if (!strToInt(p, xend) || xend<(int)fstart || xend>(int)fend) {
segs_valid=false;
break;
}
if (xstart>xend) { seg.start=(uint)xend;seg.end=(uint)xstart; }
else { seg.start=(uint)xstart;seg.end=(uint)xend; }
segs.Add(seg);
} //parse all CDS segments
if (segs_valid) {
if (segs.Count()>1) segs.Sort();
} else
segs.Clear();
}
return segs_valid;
}
void GffLine::ensembl_GFF_ID_process(char*& id) {
char* n=NULL;
if (startsWith(id, "gene:")) {
n=Gstrdup(id+5);
GFREE(id);
id=n;
}
else if (startsWith(id, "transcript:")) {
n=Gstrdup(id+11);
GFREE(id);
id=n;
}
}
void GffLine::ensembl_GTF_ID_process(char*& id, const char* ver_attr) {
char* v=NULL;
v=extractAttr(ver_attr);
if (v!=NULL) {
char* n=Gstrdup(id, strlen(v)+1);
strcat(n,".");strcat(n,v);
GFREE(v);
GFREE(id);
id=n;
}
}
GffLine::GffLine(GffReader* reader, const char* l): _parents(NULL), _parents_len(0),
dupline(NULL), line(NULL), llen(0), gseqname(NULL), track(NULL),
ftype(NULL), ftype_id(-1), info(NULL), fstart(0), fend(0), //qstart(0), qend(0), qlen(0),
score(0), score_decimals(-1), strand(0), flags(0), exontype(exgffNone), phase(0), cds_start(0), cds_end(0),
exons(), cdss(), gene_name(NULL), gene_id(NULL), parents(NULL), num_parents(0), ID(NULL) {
llen=strlen(l);
GMALLOC(line,llen+1);
memcpy(line, l, llen+1);
GMALLOC(dupline, llen+1);
memcpy(dupline, l, llen+1);
skipLine=true; //clear only if we make it to the end of this function
char* t[9];
int i=0;
int tidx=1;
t[0]=line;
char fnamelc[128];
while (line[i]!=0) {
if (line[i]=='\t') {
line[i]=0;
t[tidx]=line+i+1;
tidx++;
//if (tidx>8) break;
}
i++;
}
if (tidx<8) { // ignore non-GFF lines
return;
}
if (tidx>9) {
GMessage("Warning: unexpected tab character in last column, line truncated:\n\%s\n",l);
}
gffWarnings=reader->gff_warns;
gseqname=t[0];
track=t[1];
ftype=t[2];
info=t[8];
char* p=t[3];
if (!parseUInt(p,fstart)) {
//chromosome_band entries in Flybase
GMessage("Warning: invalid start coordinate at line:\n%s\n",l);
return;
}
p=t[4];
if (!parseUInt(p,fend)) {
GMessage("Warning: invalid end coordinate at line:\n%s\n",l);
return;
}
if (fend<fstart) {
GMessage("Error: invalid feature coordinates (end<start!) at line:\n%s\n",l);
Gswap(fend,fstart); //make sure fstart<=fend, always
//return;
}
p=t[5];
if (p[0]=='.' && p[1]==0) {
score=0;
score_decimals=-1;
}
else {
score_decimals=0;
//count decimals
char* pd=strchr(p,'.');
if (pd) {
++pd;
char* pde=pd;
while ((*pde)!=0) ++pde;
score_decimals=pde-pd;
}
if (!parseFloat(p, score))
GError("Error parsing feature score from GFF line:\n%s\n",l);
}
strand=*t[6];
if (strand!='+' && strand!='-' && strand!='.')
GError("Error parsing strand (%c) from GFF line:\n%s\n",strand,l);
phase=*t[7]; // must be '.', '0', '1' or '2'
// exon/CDS/mrna filter
strncpy(fnamelc, ftype, 127);
fnamelc[127]=0;
strlower(fnamelc); //convert to lower case
if (endsWith(fnamelc, "match")) {
//TODO: do not discard generic cDNA_match/protein_match features, convert them internally
// (when a hit chain has multiple _match features with the same ID, e.g. multiple HSPs with the same subject)
// and set GffObj::flag_DISCONTINUOUS
return;
}
bool is_t_data=false;
bool someRNA=false;
if (strstr(fnamelc, "utr")!=NULL) {
exontype=exgffUTR;
is_exon=true;
is_t_data=true;
}
else if (endsWith(fnamelc, "exon")) {
exontype=exgffExon;
is_exon=true;
is_t_data=true;
}
else if (strstr(fnamelc, "stop")!=NULL &&
(strstr(fnamelc, "codon")!=NULL || strstr(fnamelc, "cds")!=NULL) &&
strstr(fnamelc, "redefined")==NULL && strstr(fnamelc, "selenocysteine")==NULL) {
exontype=exgffStopCodon;
is_exon=true;
is_cds=true; //though some place it outside the last CDS segment
is_t_data=true;
}
else if (strstr(fnamelc, "start") &&
((strstr(fnamelc, "codon")!=NULL) || strstr(fnamelc, "cds")!=NULL)){
exontype=exgffStartCodon;
is_exon=true;
is_cds=true;
is_t_data=true;
}
else if (strcmp(fnamelc, "cds")==0) {
exontype=exgffCDS;
is_exon=true;
is_cds=true;
is_t_data=true;
}
else if (startsWith(fnamelc, "intron") || endsWith(fnamelc, "intron")) {
exontype=exgffIntron;
}
else if ((someRNA=endsWith(fnamelc,"rna")) || endsWith(fnamelc,"transcript")) { // || startsWith(fnamelc+1, "rna")) {
is_transcript=true;
is_t_data=true;
if (someRNA) ftype_id=GffObj::names->feats.addName(ftype);
}
else if (endsWith(fnamelc, "_gene_segment")) {
is_transcript=true;
is_t_data=true;
is_gene_segment=true;
}
else if (endsWith(fnamelc, "gene") || startsWith(fnamelc, "gene")) {
is_gene=true;
is_t_data=true; //because its name will be attached to parented transcripts
}
char* Parent=NULL;
/*
Rejecting non-transcript lines early if only transcripts are requested ?!
It would be faster to do this here but there are GFF cases when we reject an
unusual parent feature here (e.g. protein with CDS children) and then
their exon/CDS children show up and get assigned to an implicit parent mRNA
The solution is to still load this parent as GffObj for now and BAN it later
so its children get dismissed/discarded as well.
*/
if (reader->ignoreLocus) {
if (strcmp(ftype, "locus")==0) return;
if (is_transcript || is_gene) {
char* locus=NULL;
if (reader->is_gff3 || reader->gff_type==0)
locus=extractAttr("locus=");
else locus=extractAttr("locus");
if (locus!=NULL) { GFREE(locus); }
}
}
char *gtf_tid=NULL;
char *gtf_gid=NULL;
if (reader->is_gff3 || reader->gff_type==0) {
ID=extractAttr("ID=",true);
if (ID!=NULL && reader->procEnsemblID()) {
ensembl_GFF_ID_process(ID);
}
Parent=extractAttr("Parent=",true);
if (Parent!=NULL && reader->procEnsemblID()) {
ensembl_GFF_ID_process(Parent);
}
if (reader->gff_type==0) {
if (ID!=NULL || Parent!=NULL) reader->is_gff3=true;
else { //check if it looks like a GTF
gtf_tid=extractAttr("transcript_id", true, true);
if (gtf_tid!=NULL) {
if (reader->procEnsemblID())
ensembl_GTF_ID_process(gtf_tid, "transcript_version");
}
else { //NULL gtf_tid, try gene_id
gtf_gid=extractAttr("gene_id", true, true);
if (gtf_gid!=NULL) {
if (reader->procEnsemblID())
ensembl_GTF_ID_process(gtf_gid, "gene_version");
}
else return; //cannot determine file type yet
}
reader->is_gtf=true;
}
}
}
if (reader->is_gff3) {
//parse as GFF3
//if (ID==NULL && Parent==NULL) return; //silently ignore unidentified/unlinked features
if (ID!=NULL) {
//has ID attr so it's likely to be a parent feature
//look for explicit gene name
gene_name=getAttrValue("gene_name=");
if (gene_name==NULL) {
gene_name=getAttrValue("geneName=");
if (gene_name==NULL) {
gene_name=getAttrValue("gene_sym=");
if (gene_name==NULL) {
gene_name=getAttrValue("gene=");
}
}
}
gene_id=getAttrValue("geneID=");
if (gene_id==NULL) {
gene_id=getAttrValue("gene_id=");
}
//--parse exons for TLF
char* segstr=extractAttr("exons=");
bool exons_valid=false;
if (segstr) {
exons_valid=parseSegmentList(exons, segstr);
char* exoncountstr=extractAttr("exonCount=");
if (exoncountstr) {
int exoncount=0;
if (!strToInt(exoncountstr, exoncount) || exoncount!=(int)exons.Count())
GMessage("Warning: exonCount attribute value doesn't match the exons attribute!\n");
GFREE(exoncountstr);
}
GFREE(segstr);
}
if (exons_valid) {
bool validCDS=false;
segstr=extractAttr("CDS=");
if (segstr) {
char* p=strchr(segstr, ':');
if (p!=NULL) { // CDS=start:end format
*p='\0'; ++p;
validCDS=true;
if (validCDS && strToUInt(segstr, cds_start) && cds_start>=fstart) {
if (!strToUInt(p, cds_end) || cds_end>fend) {
validCDS=false;
}
}
if (!validCDS || (int)cds_start<=0 || (int)cds_end<=0) {
GMessage("Warning: invalid CDS (%d-%d) discarded for line:\n%s\n",
cds_start, cds_end, dupline);
cds_start=0;
cds_end=0;
}
} //CDS=start:end format
else { //CDS = list of start-end segments, just like the exons
validCDS=parseSegmentList(cdss, segstr);
if (validCDS && cdss.Count()>0) {
if (cds_start==0) cds_start=cdss.First().start;
if (cds_end==0) cds_end=cdss.Last().end;
}
}
GFREE(segstr);
}
if (validCDS) {
char* cds_phase=NULL;
if ((cds_phase=extractAttr("CDSphase="))!=NULL) {
phase=cds_phase[0];
GFREE(cds_phase);
}
} //CDS found
}//has valid exons
}// has GFF3 ID
if (Parent!=NULL) {
//keep Parent attr
//parse multiple parents
num_parents=1;
p=Parent;
int last_delim_pos=-1;
while (*p!=';' && *p!=0) {
if (*p==',' && *(p+1)!=0 && *(p+1)!=';') {
num_parents++;
last_delim_pos=(p-Parent);
}
p++;
}
_parents_len=p-Parent+1;
_parents=Parent;
GMALLOC(parents, num_parents*sizeof(char*));
parents[0]=_parents;
int i=1;
if (last_delim_pos>0) {
for (p=_parents+1;p<=_parents+last_delim_pos;p++) {
if (*p==',') {
char* ep=p-1;
while (*ep==' ' && ep>_parents) ep--;
*(ep+1)=0; //end the string there
parents[i]=p+1;
i++;
}
}
}
} //has Parent field
//special case for gene_id: for genes, this is the ID
if (gene_id==NULL) {
if (is_gene) {
if (ID!=NULL) gene_id=Gstrdup(ID);
} else if (is_transcript) {
if (Parent!=NULL) gene_id=Gstrdup(Parent);
}
}
} //GFF3
else { // ----------------- GTF syntax ------------------
if (reader->transcripts_Only && !is_t_data) {
return; //alwasys skip unrecognized non-transcript features in GTF
}
if (is_gene) {
reader->gtf_gene=true;
ID = (gtf_tid!=NULL) ? gtf_tid : extractAttr("transcript_id", true, true);
//Ensemble GTF might lack transcript_id !
if (ID!=NULL) {
if (gtf_tid==NULL && reader->procEnsemblID())
ensembl_GTF_ID_process(ID, "transcript_version");
}
gene_id = (gtf_gid!=NULL) ? gtf_gid : extractAttr("gene_id", true, true);
if (gene_id!=NULL && gtf_gid==NULL && reader->procEnsemblID())
ensembl_GTF_ID_process(gene_id, "gene_version");
if (ID==NULL) {
//no transcript_id -- this should not be valid GTF2 format, but Ensembl (Gencode?)
//has being known to add "gene" features with only gene_id in their GTF
if (gene_id!=NULL) { //likely a gene feature line (Ensembl!)
ID=Gstrdup(gene_id); //take over as ID (for defective GTF lacking transcript_id)
}
}
// else if (strcmp(gene_id, ID)==0) //GENCODE v20 gene feature ?
}
else if (is_transcript) {
ID = (gtf_tid!=NULL) ? gtf_tid : extractAttr("transcript_id", true, true);
//gene_id=extractAttr("gene_id"); // for GTF this is the only attribute accepted as geneID
if (ID==NULL) {
//something is wrong here, cannot parse the GTF ID
GMessage("Warning: invalid GTF record, transcript_id not found:\n%s\n", l);
return;
} else if (gtf_tid==NULL && reader->procEnsemblID())
ensembl_GTF_ID_process(ID, "transcript_version");
gene_id = (gtf_gid!=NULL) ? gtf_gid : extractAttr("gene_id", true, true);
if (gene_id!=NULL) {
if (gtf_gid==NULL && reader->procEnsemblID())
ensembl_GTF_ID_process(gene_id, "gene_version");
Parent=Gstrdup(gene_id);
}
reader->gtf_transcript=true;
is_gtf_transcript=1;
} else { //must be an exon type ?
Parent = (gtf_tid!=NULL) ? gtf_tid : extractAttr("transcript_id", true, true);
if (Parent!=NULL && gtf_tid==NULL && reader->procEnsemblID())
ensembl_GTF_ID_process(Parent, "transcript_version");
gene_id = (gtf_gid!=NULL) ? gtf_gid : extractAttr("gene_id", true, true); // for GTF this is the only attribute accepted as geneID
if (gene_id!=NULL && gtf_gid==NULL && reader->procEnsemblID())
ensembl_GTF_ID_process(gene_id, "gene_version");
//old pre-GTF2 formats like Jigsaw's (legacy support)
if (Parent==NULL && exontype==exgffExon) {
if (startsWith(track,"jigsaw")) {
is_cds=true;
strcpy(track,"jigsaw");
p=strchr(info,';');
if (p==NULL) { Parent=Gstrdup(info); info=NULL; }
else { Parent=Gstrdup(info,p-1);
info=p+1;
}
}
}
if (Parent==NULL) {
//something is wrong here couldn't parse the transcript ID for this feature
GMessage("Warning: invalid GTF record, transcript_id not found:\n%s\n", l);
return;
}
}
//more GTF attribute parsing
if (is_gene && gene_id==NULL && ID!=NULL)
gene_id=Gstrdup(ID);
gene_name=getAttrValue("gene_name");
if (gene_name==NULL) {
gene_name=getAttrValue("gene_sym");
if (gene_name==NULL) {
gene_name=getAttrValue("gene");
if (gene_name==NULL)
gene_name=getAttrValue("genesymbol");
}
}
//*** IMPORTANT: prepare GTF for easy parseAttr by adding '=' character after the attribute name
// for ALL attributes
p=info;
bool noed=true; //not edited after the last delim
bool nsp=false; //non-space found after last delim
while (*p!=0) {
if (*p==' ') {
if (nsp && noed) {
*p='=';
noed=false;
p++;
continue;
}
}
else nsp=true; //non-space
if (*p==';') { noed=true; nsp=false; }
p++;
}
//-- GTF prepare parents[] if Parent found
if (Parent!=NULL) { //GTF transcript_id found as a parent
_parents=Parent;
num_parents=1;
_parents_len=strlen(Parent)+1;
GMALLOC(parents, sizeof(char*));
parents[0]=_parents;
}
} //GTF
if (ID==NULL && parents==NULL) {
if (gffWarnings)
GMessage("Warning: discarding unrecognized feature (no ID or Parent):\n%s\n",dupline);
return; //skip
}
skipLine=false;
}
//FIXME - this should only be used AFTER finalize() was called, and must have cdss=NULL of course
void GffObj::setCDS(uint cd_start, uint cd_end, char phase) {
if (cd_start<this->start) {
GMessage("Warning: setCDS() called for %s with an out of bounds CDS start %d!\n",
gffID, cd_start);
return;
}
if (cd_end>this->end) {
GMessage("Warning: setCDS() called for %s with an out of bounds CDS end %d!\n",
gffID, cd_end);
return;
}
this->CDstart=cd_start;
this->CDend=cd_end;
this->CDphase=phase;
isTranscript(true);
subftype_id=gff_fid_exon;
if (monoFeature()) {
if (exons.Count()==0) addExon(this->start, this->end, exgffExon);
else exons[0]->exontype=exgffExon;
}
}
void GffObj::setCDS(GffObj* t) {
//copy the cdss as well
uint cd_start=t->CDstart;
uint cd_end=t->CDend;
uint phase=t->CDphase;
if (cd_start<this->start) {
GMessage("Warning: setCDS() called for %s with an out of bounds CDS start %d!\n",
gffID, cd_start);
return;
}
if (cd_end>this->end) {
GMessage("Warning: setCDS() called for %s with an out of bounds CDS end %d!\n",
gffID, cd_end);
return;
}
this->CDstart=cd_start;
this->CDend=cd_end;
this->CDphase=phase;
isTranscript(true);
subftype_id=gff_fid_exon;
if (monoFeature()) {
if (exons.Count()==0) addExon(this->start, this->end, exgffExon);
else exons[0]->exontype=exgffExon;
}
if (t->cdss!=NULL) {
if (this->cdss!=NULL) delete cdss;
cdss=new GList<GffExon>(true, true, false);
for (int i=0;i<t->cdss->Count();i++) {
cdss->Add(new GffExon(*(t->cdss->Get(i))));
}
}
}
int GffObj::readExon(GffReader& reader, GffLine& gl) {
// -- this should only be called before ::finalize()!
//should make sure to get the right subftype_id!
if (!isTranscript() && gl.exontype>exgffNone) {
//subfeature recognized as exon-like, so this should be considered a transcript!
isTranscript(true);
}
if (isTranscript()) {
if (subftype_id<0) {//exon_ftype_id=gff_fid_exon;
if (gl.exontype>exgffNone) subftype_id=gff_fid_exon;
else subftype_id=names->feats.addName(gl.ftype);
}
//any recognized exon-like segment gets the generic "exon" type (also applies to CDS)
if (gl.exontype==exgffNone && !gl.is_transcript) {
//extraneous mRNA feature, discard
if (reader.gff_warns)
GMessage("Warning: discarding unrecognized transcript subfeature '%s' of %s\n",
gl.ftype, gffID);
return -1;
}
}
else { //non-mRNA parent feature, check this subf type
int subf_id=names->feats.addName(gl.ftype);
if (subftype_id<0 || exons.Count()==0) //never assigned a subfeature type before (e.g. first exon being added)
subftype_id=subf_id;
else {
if (subftype_id!=subf_id) {
if (subftype_id==ftype_id && exons.Count()==1 && exons[0]->start==start && exons[0]->end==end) {
//the existing exon was just a dummy one created by default, discard it?
exons.Clear();
covlen=0;
subftype_id=subf_id; //allow the new subfeature to completely takeover
}
else { //multiple subfeatures, prefer those exon-like
if (reader.gff_warns)
GMessage("Warning: multiple subfeatures (%s and %s) found for %s, discarding ",
names->feats.getName(subf_id), names->feats.getName(subftype_id),gffID);
if (gl.exontype>exgffNone) { //new feature is an exon, discard previously parsed subfeatures
if (reader.gff_warns) GMessage("%s.\n", names->feats.getName(subftype_id));
subftype_id=subf_id;
exons.Clear();
covlen=0;
}
else { //discard new feature
if (reader.gff_warns) GMessage("Warning: skipping subfeature %s.\n", names->feats.getName(subf_id));
return -1; //skip this 2nd subfeature type for this parent!
}
}
} //incoming subfeature is of different type
} //new subfeature type
} //non-mRNA parent
int eidx=-1;
GList<GffExon>* segs=NULL; //either cds or &exons
if (gl.is_cds) {
if (cdss==NULL)
cdss=new GList<GffExon>(true, true, false);
segs=cdss;
} else {
segs=&exons;
}
eidx=addExon(*segs, gl);
if (eidx<0) {
GMessage("Warning: addExon() failed for GFF line:\n%s\n",gl.dupline);
return eidx; //this should never happen!
}
if (reader.keep_Attrs) {
if (reader.noExonAttrs) {
parseAttrs(attrs, gl.info, true);
}
else { //need all exon-level attributes
parseAttrs((*segs)[eidx]->attrs, gl.info, true, gl.is_cds);
}
}
return eidx;
}
int GffObj::addExon(GList<GffExon>& segs, GffLine& gl, int8_t exontype_override) {
int ex_type=(exontype_override!=exgffNone) ? exontype_override : gl.exontype;
GffScore exon_score(gl.score, gl.score_decimals);
int eidx=addExon(gl.fstart, gl.fend, ex_type, gl.phase, exon_score, &segs);
if (&segs==cdss && isGene() && gl.ID!=NULL && eidx>=0) {
//special NCBI cases where CDS can be treated as discontiguous features, grouped by their ID
//-- used for genes with X_gene_segment features
//char* cds_id=Gstrdup(gl.ID);
//segs[eidx]->uptr=cds_id;
segs[eidx]->uptr=gl.ID;
gl.ID=NULL;
}
return eidx;
}
int GffObj::exonOverlapIdx(GList<GffExon>& segs, uint s, uint e, int* ovlen, int start_idx) {
//return the exons' index for the overlapping OR ADJACENT exon
//ovlen, if given, will return the overlap length
//if (s>e) Gswap(s,e);
for (int i=start_idx;i<segs.Count();i++) {
if (segs[i]->start>e+1) break;
if (s-1>segs[i]->end) continue;
//-- overlap/adjacent if we are here:
if (ovlen!=NULL) {
int ovlend= (segs[i]->end>e) ? e : segs[i]->end;
*ovlen= ovlend - ((s>segs[i]->start)? s : segs[i]->start)+1;
}
return i;
} //for each exon
*ovlen=0;
return -1;
}
void GffObj::transferCDS(GffExon* cds) {
//direct adding of a cds to the cdss pointer, without checking
if (cdss==NULL) cdss=new GList<GffExon>(true, true, false);
cdss->Add(cds); //now the caller must forget this exon!
if (CDstart==0 || CDstart>cds->start) CDstart=cds->start;
}
int GffObj::addExon(uint segstart, uint segend, int8_t exontype, char phase, GffScore exon_score, GList<GffExon>* segs) {
if (segstart>segend) { Gswap(segstart, segend); }
if (segs==NULL) segs=&exons;
if (exontype!=exgffNone) { //check for overlaps between exon/CDS-type segments
//addExonSegment(gl.fstart, gl.fend, gl.score, gl.phase, gl.is_cds, exontype_override);
int ovlen=0;
int oi=-1;
while ((oi=exonOverlapIdx(*segs, segstart, segend, &ovlen, oi+1))>=0) {
//note: ovlen==0 for adjacent segments
if ((*segs)[oi]->exontype>exgffNone &&
(*segs)[oi]->start<=segstart && (*segs)[oi]->end>=segend) {
//existing feature contains this segment, so we do NOT need to add it
//-- unless its the annoying NCBI exception: gene with multiple alternate
// _gene_segment CDS features!
if (!(this->isGene() && exontype==exgffCDS &&
(*segs)[oi]->exontype==exgffCDS ))