forked from gpertea/gclib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgff.cpp
More file actions
2549 lines (2450 loc) · 84 KB
/
gff.cpp
File metadata and controls
2549 lines (2450 loc) · 84 KB
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
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; // "exon" feature
const uint gfo_flag_HAS_ERRORS = 0x00000001;
const uint gfo_flag_CHILDREN_PROMOTED= 0x00000002;
const uint gfo_flag_IS_GENE = 0x00000004;
const uint gfo_flag_IS_TRANSCRIPT = 0x00000008;
const uint gfo_flag_HAS_GFF_ID = 0x00000010; //found transcript feature line (GFF3 or GTF)
const uint gfo_flag_BY_EXON = 0x00000020; //created by subfeature (exon) directly
const uint gfo_flag_DISCARDED = 0x00000100;
const uint gfo_flag_LST_KEEP = 0x00000200;
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 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 !
}
char* GffLine::extractAttr(const char* attr, bool caseStrict, bool enforce_GTF2, int* rlen) {
//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) at GTF 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=info;
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)
GError("Error parsing value of GFF attribute \"%s\", line:\n%s\n", attr, dupline);
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, dupline);
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, dupline);
char *r=Gstrdup(vp, vend-1);
if (rlen) *rlen = vend-vp;
//-- now remove this attribute from the info string
while (*vend!=0 && (*vend=='"' || *vend==';' || *vend==' ')) vend++;
if (*vend==0) vend--;
for (char *src=vend, *dest=pos;;src++,dest++) {
*dest=*src;
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), extra(NULL), 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++;
if (tidx>13) { extra=t[13]; 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];
//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 (!parseInt(blen[i], exonlen) || exonlen<=0) {
GMessage("Warning: invalid BED block size %s at line:\n%s\n",blen[i], l);
return;
}
int exonstart;
if (!parseInt(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);
}
skip=false;
}
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), strand(0), flags(0), exontype(0), phase(0),
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=1; //reset only if it reaches 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
// GMessage("Warning: error parsing GFF/GTF line:\n%s\n", l);
return;
}
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) Gswap(fend,fstart); //make sure fstart<=fend, always
p=t[5];
if (p[0]=='.' && p[1]==0) {
score=0;
}
else {
if (!parseDouble(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
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") &&
(strstr(fnamelc, "codon") || strstr(fnamelc, "cds"))){
exontype=exgffStop;
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=exgffStart;
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") || 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 a parent feature here
(e.g. protein with 2 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.
*/
char *gtf_tid=NULL;
char *gtf_gid=NULL;
if (reader->is_gff3 || reader->gff_type==0) {
ID=extractAttr("ID=",true);
Parent=extractAttr("Parent=",true);
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) {
gtf_gid=extractAttr("gene_id", true, true);
if (gtf_gid==NULL) 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=extractAttr("gene_name=");
if (gene_name==NULL) {
gene_name=extractAttr("geneName=");
if (gene_name==NULL) {
gene_name=extractAttr("gene_sym=");
if (gene_name==NULL) {
gene_name=extractAttr("gene=");
}
}
}
gene_id=extractAttr("geneID=");
if (gene_id==NULL) {
gene_id=extractAttr("gene_id=");
}
if (is_gene) { //WARNING: this might be mislabeled (e.g. TAIR: "mRNA_TE_gene")
//special case: keep the Name and ID attributes of the gene feature
if (gene_name==NULL)
gene_name=extractAttr("Name=");
if (gene_id==NULL) //the ID is also gene_id in this case
gene_id=Gstrdup(ID);
//skip=false;
//return;
//-- we don't care about gene parents.. unless it's a mislabeled "gene" feature
//GFREE(Parent);
} //gene feature (probably)
}// 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
//parse other potentially useful GFF3 attributes
if ((p=strstr(info,"Target="))!=NULL) { //has Target attr
p+=7;
while (*p!=';' && *p!=0 && *p!=' ') p++;
if (*p!=' ') {
GError("Error parsing target coordinates from GFF line:\n%s\n",l);
}
if (!parseUInt(p,qstart))
GError("Error parsing target start coordinate from GFF line:\n%s\n",l);
if (*p!=' ') {
GError("Error parsing next target coordinate from GFF line:\n%s\n",l);
}
p++;
if (!parseUInt(p,qend))
GError("Error parsing target end coordinate from GFF line:\n%s\n",l);
}
if ((p=strifind(info,"Qreg="))!=NULL) { //has Qreg attr
p+=5;
if (!parseUInt(p,qstart))
GError("Error parsing target start coordinate from GFF line:\n%s\n",l);
if (*p!='-') {
GError("Error parsing next target coordinate from GFF line:\n%s\n",l);
}
p++;
if (!parseUInt(p,qend))
GError("Error parsing target end coordinate from GFF line:\n%s\n",l);
if (*p=='|' || *p==':') {
p++;
if (!parseUInt(p,qlen))
GError("Error parsing target length from GFF Qreg|: \n%s\n",l);
}
}//has Qreg attr
if (qlen==0 && (p=strifind(info,"Qlen="))!=NULL) {
p+=5;
if (!parseUInt(p,qlen))
GError("Error parsing target length from GFF Qlen:\n%s\n",l);
}
} //GFF3
else { // GTF syntax
if (reader->transcriptsOnly && !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 this
gene_id = (gtf_gid!=NULL) ? gtf_gid : extractAttr("gene_id", true, true);
if (ID==NULL) {
// no transcript_id -- this is not a valid GTF2 format, but Ensembl
//is 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
}
}
// 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;
}
gene_id = (gtf_gid!=NULL) ? gtf_gid : extractAttr("gene_id", true, true);
if (gene_id!=NULL)
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);
gene_id = (gtf_gid!=NULL) ? gtf_gid : extractAttr("gene_id", true, true); // for GTF this is the only attribute accepted as geneID
//old pre-GTF2 formats like Jigsaw's (legacy)
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
gene_name=extractAttr("gene_name");
if (gene_name==NULL) {
gene_name=extractAttr("gene_sym");
if (gene_name==NULL) {
gene_name=extractAttr("gene");
if (gene_name==NULL)
gene_name=extractAttr("genesymbol");
}
}
//prepare GTF for 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 (reader->gff_warns)
GMessage("Warning: could not parse ID or Parent from GFF line:\n%s\n",dupline);
return; //skip
}
skipLine=0;
}
void GffObj::addCDS(uint cd_start, uint cd_end, char phase) {
if (cd_start>=this->start) {
this->CDstart=cd_start;
if (strand=='+') this->CDphase=phase;
}
else this->CDstart=this->start;
if (cd_end<=this->end) {
this->CDend=cd_end;
if (strand=='-') this->CDphase=phase;
}
else this->CDend=this->end;
isTranscript(true);
exon_ftype_id=gff_fid_exon;
if (monoFeature()) {
if (exons.Count()==0) addExon(this->start, this->end,0,'.',0,0,false,exgffExon);
else exons[0]->exontype=exgffExon;
}
}
int GffObj::addExon(GffReader* reader, GffLine* gl, bool keepAttr, bool noExonAttr) {
//this will make sure we have the right subftype_id!
//int subf_id=-1;
if (!isTranscript() && gl->exontype>0) {
isTranscript(true);
exon_ftype_id=gff_fid_exon;
if (exons.Count()==1) exons[0]->exontype=exgffExon;
}
if (isTranscript()) {
if (exon_ftype_id<0) {//exon_ftype_id=gff_fid_exon;
if (gl->exontype>0) exon_ftype_id=gff_fid_exon;
else exon_ftype_id=names->feats.addName(gl->ftype);
}
//any recognized mRNA segment gets the generic "exon" type (also applies to CDS)
if (gl->exontype==0 && !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 (exon_ftype_id<0 || exons.Count()==0) //never assigned a subfeature type before (e.g. first exon being added)
exon_ftype_id=subf_id;
else {
if (exon_ftype_id!=subf_id) {
//
if (exon_ftype_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;
exon_ftype_id=subf_id; //allow the new subfeature to completely takeover
}
else { //multiple subfeatures, prefer those with
if (reader->gff_warns)
GMessage("GFF Warning: multiple subfeatures (%s and %s) found for %s, discarding ",
names->feats.getName(subf_id), names->feats.getName(exon_ftype_id),gffID);
if (gl->exontype!=0) { //new feature is an exon, discard previously parsed subfeatures
if (reader->gff_warns) GMessage("%s.\n", names->feats.getName(exon_ftype_id));
exon_ftype_id=subf_id;
exons.Clear();
covlen=0;
}
else { //discard new feature
if (reader->gff_warns) GMessage("%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=addExon(gl->fstart, gl->fend, gl->score, gl->phase,
gl->qstart,gl->qend, gl->is_cds, gl->exontype);
if (eidx<0) return eidx; //this should never happen
if (keepAttr) {
if (noExonAttr) {
if (attrs==NULL) //place the parsed attributes directly at transcript level
parseAttrs(attrs, gl->info);
}
else { //need all exon-level attributes
parseAttrs(exons[eidx]->attrs, gl->info, true);
}
}
return eidx;
}
int GffObj::addExon(uint segstart, uint segend, double sc, char fr, int qs, int qe, bool iscds, char exontype) {
if (segstart>segend) { Gswap(segstart, segend); }
if (exons.Count()==0) {
if (iscds) isCDS=true; //for now, assume CDS only if first "exon" given is a CDS
if (exon_ftype_id<0) {
exon_ftype_id = (isTranscript() || isGene()) ? gff_fid_exon : ftype_id;
}
}
//special treatment of start/stop codon features, they might be broken/split between exons (?)
//we consider these as part of the CDS
if (exontype==exgffStart || exontype==exgffStop) {
iscds=true;
//if (CDend==0 || segend>CDend) CDend=segend;
//if (CDstart==0 || segstart<CDstart) CDstart=segstart;
}
if (iscds) { //update CDS anchors:
if (CDstart==0 || segstart<CDstart) {
CDstart=segstart;
if (exontype==exgffCDS && strand=='+') CDphase=fr;
}
if (CDend==0 || segend>CDend) {
CDend=segend;
if (exontype==exgffCDS && strand=='-') CDphase=fr;
}
}
else { // not a CDS/start/stop
isCDS=false; //not a CDS-only feature
}
//if (exontype==exgffStart || exontype==exgffStop) exontype=exgffCDS;
if (qs || qe) {
if (qs>qe) Gswap(qs,qe);
if (qs==0) qs=1;
}
int ovlen=0;
if (exontype>0) { //check for overlaps between exon-type segments
int oi=-1;
while ((oi=exonOverlapIdx(segstart, segend, &ovlen, oi+1))>=0) {
//ovlen==0 for adjacent segment
if (exons[oi]->exontype>0) {
if (exons[oi]->start<=segstart && exons[oi]->end>=segend) {
//existing feature includes this segment
return oi;
}
else {
expandExon(oi, segstart, segend, exgffExon, sc, fr, qs, qe);
return oi;
}
}
}
/*
if (oi>=0) { //overlap existing segment (exon)
if (ovlen==0) {
//adjacent exon-type segments will be merged
//e.g. CDS to (UTR|exon|stop_codon)
if ((exons[oi]->exontype>=exgffUTR && exontype==exgffCDS) ||
(exons[oi]->exontype==exgffCDS && exontype>=exgffUTR)) {
expandExon(oi, segstart, segend, exgffCDSUTR, sc, fr, qs, qe);
return oi;
}
//CDS adjacent to stop_codon: UCSC does (did?) this
if ((exons[oi]->exontype==exgffStop && exontype==exgffCDS) ||
(exons[oi]->exontype==exgffCDS && exontype==exgffStop)) {
expandExon(oi, segstart, segend, exgffCDS, sc, fr, qs, qe);
return oi;
}
}
//segment inclusion: only allow this for CDS within exon, stop_codon within (CDS|UTR|exon),
// start_codon within (CDS|exon)
if (exons[oi]->start<=segstart && exons[oi]->end>=segend) {
//larger segment given first, now the smaller included one is redundant
if (exons[oi]->exontype>exontype &&
!(exons[oi]->exontype==exgffUTR && exontype==exgffCDS)) {
return oi; //only used to store attributes from current GffLine
}
else {
//if (gff_show_warnings && (exons[oi]->start<segstart || exons[oi]->end>segend)) {
// GMessage("GFF Warning: unusual segment inclusion: %s(%d-%d) within %s(%d-%d) (ID=%s)\n",
// strExonType(exontype), segstart, segend, strExonType(exons[oi]->exontype),
// exons[oi]->start, exons[oi]->end, this->gffID);
//}
return oi;
}
}
if (exontype>exons[oi]->exontype &&
segstart<=exons[oi]->start && segend>=exons[oi]->end &&
!(exontype==exgffUTR && exons[oi]->exontype==exgffCDS)) {
//smaller segment given first, so we have to enlarge it
expandExon(oi, segstart, segend, exontype, sc, fr, qs, qe);
//this should also check for overlapping next exon (oi+1) ?
return oi;
}
//there is also the special case of "ribosomal slippage exception" (programmed frameshift)
//where two CDS segments may actually overlap for 1 or 2 bases, but there should be only one encompassing exon
//if (ovlen>2 || exons[oi]->exontype!=exgffCDS || exontype!=exgffCDS) {
// had to relax this because of some weird UCSC annotations with exons partially overlapping the CDS segments
if ((ovlen>2 || ovlen==0) || exons[oi]->exontype!=exgffCDS || exontype!=exgffCDS) {
//if (gff_show_warnings)
// GMessage("GFF Warning: merging overlapping/adjacent feature segment %s (%d-%d) with %s (%d-%d) for GFF ID %s on %s\n",
// strExonType(exontype), segstart, segend, strExonType(exons[oi]->exontype), exons[oi]->start, exons[oi]->end, gffID, getGSeqName());
expandExon(oi, segstart, segend, exontype, sc, fr, qs, qe);
return oi;
}
// else add the segment if the overlap is small and between two CDS segments
//TODO: we might want to add an attribute here with the slippage coordinate and size?
covlen-=ovlen;
}//overlap or adjacent to existing segment
*/
} //exon type, check for overlap with existing exons
// create & add the new segment
/*
if (start>0 && exontype==exgffCDS && exons.Count()==0) {
//adding a CDS directly as the first subfeature of a declared parent
segstart=start;
segend=end;
}
*/
GffExon* enew=new GffExon(segstart, segend, sc, fr, qs, qe, exontype);
int eidx=exons.Add(enew);
if (eidx<0) {
//this would actually be acceptable if the object is a "Gene" and "exons" are in fact isoforms
if (gff_show_warnings)
GMessage("GFF Warning: failed adding segment %d-%d for %s (discarded)!\n",
segstart, segend, gffID);
delete enew;
hasErrors(true);
return -1;
}
covlen+=(int)(exons[eidx]->end-exons[eidx]->start)+1;
//adjust parent feature coordinates to contain this exon
if (start==0 || start>exons.First()->start) {
start=exons.First()->start;
}
if (end<exons.Last()->end) end=exons.Last()->end;
return eidx;
}
void GffObj::expandExon(int oi, uint segstart, uint segend, char exontype, double sc, char fr, int qs, int qe) {
//oi is the index of the *first* overlapping segment found that must be enlarged
covlen-=exons[oi]->len();
if (segstart<exons[oi]->start)
exons[oi]->start=segstart;
if (qs && qs<exons[oi]->qstart) exons[oi]->qstart=qs;
if (segend>exons[oi]->end)
exons[oi]->end=segend;
if (qe && qe>exons[oi]->qend) exons[oi]->qend=qe;
//warning: score cannot be properly adjusted! e.g. if it's a p-value it's just going to get worse
if (sc!=0) exons[oi]->score=sc;
//covlen+=exons[oi]->len();
//if (exons[oi]->exontype< exontype) -- always true
exons[oi]->exontype = exontype;
if (exontype==exgffCDS) exons[oi]->phase=fr;
//we must check if any more exons are also overlapping this
int ni=oi+1; //next exon index after oi
while (ni<exons.Count() && exons[ni]->start<=segend+1) { // next segment overlaps OR adjacent to newly enlarged segment
//if (exons[ni]->exontype<exontype && exons[ni]->end<=segend) {
if (exons[ni]->exontype>0) {
if (exons[ni]->start<exons[oi]->start) exons[oi]->start=exons[ni]->start;
if (exons[ni]->end>exons[oi]->end) exons[oi]->end=exons[ni]->end;
if (exons[ni]->qstart<exons[oi]->qstart) exons[oi]->qstart=exons[ni]->qstart;
if (exons[ni]->qend>exons[oi]->qend) exons[oi]->qend=exons[ni]->qend;
exons.Delete(ni);
} else ++ni;
/*else {
if (gff_show_warnings) GMessage("GFF Warning: overlapping existing exon(%d-%d) while expanding to %d-%d for GFF ID %s\n",
exons[ni]->start, exons[ni]->end, segstart, segend, gffID);
//hasErrors(true);
break;
}*/
} //until no more overlapping/adjacent segments found
// -- make sure any other related boundaries are updated:
start=exons.First()->start;
end=exons.Last()->end;
//recalculate covlen
covlen=0;
for (int i=0;i<exons.Count();++i) covlen+=exons[i]->len();
/*
if (uptr!=NULL) { //collect stats about the underlying genomic sequence
GSeqStat* gsd=(GSeqStat*)uptr;
if (start<gsd->mincoord) gsd->mincoord=start;
if (end>gsd->maxcoord) gsd->maxcoord=end;
if (this->len()>gsd->maxfeat_len) {
gsd->maxfeat_len=this->len();
gsd->maxfeat=this;
}
}
*/
}
void GffObj::removeExon(int idx) {
/*
if (idx==0 && segs[0].start==gstart)
gstart=segs[1].start;
if (idx==segcount && segs[segcount].end==gend)
gend=segs[segcount-1].end;
*/
if (idx<0 || idx>=exons.Count()) return;
int segstart=exons[idx]->start;
int segend=exons[idx]->end;
exons.Delete(idx);
covlen -= (int)(segend-segstart)+1;
start=exons.First()->start;
end=exons.Last()->end;
if (isCDS) { CDstart=start; CDend=end; }
}
void GffObj::removeExon(GffExon* p) {
for (int idx=0;idx<exons.Count();idx++) {
if (exons[idx]==p) {
int segstart=exons[idx]->start;
int segend=exons[idx]->end;
exons.Delete(idx);
covlen -= (int)(segend-segstart)+1;
if (exons.Count() > 0) {
start=exons.First()->start;
end=exons.Last()->end;
if (isCDS) { CDstart=start; CDend=end; }
}
return;
}
}
}
GffObj::GffObj(GffReader *gfrd, BEDLine* bedline):GSeg(0,0), exons(true,true,false) {
xstart=0;
xend=0;
xstatus=0;
partial=false;
isCDS=false;
uptr=NULL;
ulink=NULL;
parent=NULL;
udata=0;
flags=0;
CDstart=0;
CDend=0;
CDphase=0;
geneID=NULL;
gene_name=NULL;
attrs=NULL;
gffID=NULL;
track_id=-1;
gseq_id=-1;
//ftype_id=-1;
exon_ftype_id=-1;
strand='.';
if (gfrd == NULL || bedline == NULL)
GError("Error: cannot use this GffObj constructor with NULL GffReader/BEDLine!\n");
gffnames_ref(names);
//qlen=0;qstart=0;qend=0;
gscore=0;
uscore=0;
covlen=0;
qcov=0;
ftype_id=gff_fid_transcript;
exon_ftype_id=gff_fid_exon;
start=bedline->fstart;
end=bedline->fend;
gseq_id=names->gseqs.addName(bedline->gseqname);
track_id=names->tracks.addName("BED");
strand=bedline->strand;
qlen=0;
qstart=0;
qend=0;
//setup flags from gffline
isCDS=false;
isGene(false);
isTranscript(true);
gffID=Gstrdup(bedline->ID);
for (int i=0;i<bedline->exons.Count();++i) {
this->addExon(bedline->exons[i].start,bedline->exons[i].end);
}
}
GffObj::GffObj(GffReader *gfrd, GffLine* gffline, bool keepAttr, bool noExonAttr):
GSeg(0,0), exons(true,true,false), children(1,false) {
xstart=0;
xend=0;
xstatus=0;
partial=false;
isCDS=false;
uptr=NULL;
ulink=NULL;
parent=NULL;
udata=0;
flags=0;
CDstart=0;
CDend=0;
CDphase=0;
geneID=NULL;
gene_name=NULL;
attrs=NULL;
gffID=NULL;
track_id=-1;
gseq_id=-1;
//ftype_id=-1;
exon_ftype_id=-1;
strand='.';
if (gfrd == NULL || gffline == NULL)
GError("Cannot use this GffObj constructor with NULL GffReader/GffLine!\n");
gffnames_ref(names);
//qlen=0;qstart=0;qend=0;
gscore=0;
uscore=0;
covlen=0;
qcov=0;
ftype_id=gffline->ftype_id;
start=gffline->fstart;
end=gffline->fend;
gseq_id=names->gseqs.addName(gffline->gseqname);
track_id=names->tracks.addName(gffline->track);
strand=gffline->strand;
qlen=gffline->qlen;
qstart=gffline->qstart;
qend=gffline->qend;
//setup flags from gffline
isCDS=gffline->is_cds; //for now
isGene(gffline->is_gene);
isTranscript(gffline->is_transcript || gffline->exontype!=0);
//fromGff3(gffline->is_gff3);
if (gffline->parents!=NULL && !gffline->is_transcript) {
//GTF style -- create a GffObj directly by subfeature