-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathgff_utils.cpp
1640 lines (1566 loc) · 52.8 KB
/
gff_utils.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_utils.h"
GHash<GeneInfo*> gene_ids;
bool verbose=false; //same with GffReader::showWarnings and GffLoader::beVserbose
bool debugMode=false;
bool ensembl_convert=false; //-L, assist in converting Ensembl GTF to GFF3
FILE* ffasta=NULL;
FILE* f_in=NULL;
FILE* f_out=NULL;
FILE* f_w=NULL; //writing fasta with spliced exons (transcripts)
FILE* f_u=NULL;
int wPadding = 0; //padding for -w option
FILE* f_x=NULL; //writing fasta with spliced CDS
FILE* f_y=NULL; //wrting fasta with translated CDS
FILE* f_j=NULL; //wrting junctions (intron coordinates)
int maxintron=999000000;
ID_Flt_Type IDflt=idFlt_None;
bool TFilters=false;
bool wCDSonly=false;
bool wNConly=false;
int minLen=0; //minimum transcript length
bool validCDSonly=false; // translation with no in-frame STOP
bool bothStrands=false; //for single-exon mRNA validation, check the other strand too
bool altPhases=false; //if original phase fails translation validation,
//try the other 2 phases until one makes it
bool addCDSattrs=false;
bool add_hasCDS=false;
//bool streamIn=false; // --stream option
bool adjustStop=false; //automatic adjust the CDS stop coordinate
bool covInfo=false; // --cov-info : only report genome coverage
GStr tableFormat; //list of "attributes" to print in tab delimited format
bool spliceCheck=false; //only known splice-sites
bool decodeChars=false; //decode url-encoded chars in attrs (-D)
bool StarStop=false; //use * instead of . for stop codon translation
bool fullCDSonly=false; // starts with START, ends with STOP codon
bool multiExon=false;
bool writeExonSegs=false;
char* tracklabel=NULL;
/*
char* rfltGSeq=NULL;
char rfltStrand=0;
uint rfltStart=0;
uint rfltEnd=MAX_UINT;*/
GRangeParser* fltRange=NULL;
GRangeParser* fltJunction=NULL;
bool rfltWithin=false; //check for full containment within given range
bool addDescr=false;
bool wfaNoCDS=false;
bool fmtGFF3=true; //default output: GFF3
//other formats only make sense in transcriptOnly mode
bool fmtGTF=false;
bool fmtBED=false;
bool fmtTLF=false;
bool fmtTable=false;
GffPrintMode exonPrinting=pgffAny;
GFastaDb gfasta;
GHash<SeqInfo*> seqinfo;
GVec<CTableField> tableCols;
GHash<RefTran*> reftbl;
GStrSet<> fltIDs;
GStrSet<> attrList;
GHash<int> isoCounter; //counts the valid isoforms
void printFasta(FILE* f, GStr* defline, const char* seq, int seqlen, bool useStar) {
//if seqlen is provided >0, seq does not have to be 0-terminated
if (seq==NULL) return;
int len=(seqlen>0)?seqlen:strlen(seq);
if (len<=0) return;
if (defline!=NULL)
fprintf(f, ">%s\n",defline->chars());
int ilen=0;
for (int i=0; i < len; i++, ilen++) {
if (ilen == 70) {
fputc('\n', f);
ilen = 0;
}
if (useStar && seq[i]=='.')
putc('*', f);
else putc(seq[i], f);
} //for
fputc('\n', f);
}
int qsearch_gloci(uint x, GList<GffLocus>& loci) {
//binary search
//do the simplest tests first:
if (loci[0]->start>x) return 0;
if (loci.Last()->start<x) return -1;
uint istart=0;
int i=0;
int idx=-1;
int maxh=loci.Count()-1;
int l=0;
int h = maxh;
while (l <= h) {
i = (l+h)>>1;
istart=loci[i]->start;
if (istart < x) l = i + 1;
else {
if (istart == x) { //found matching coordinate here
idx=i;
while (idx<=maxh && loci[idx]->start==x) {
idx++;
}
return (idx>maxh) ? -1 : idx;
}
h = i - 1;
}
} //while
idx = l;
while (idx<=maxh && loci[idx]->start<=x) {
idx++;
}
return (idx>maxh) ? -1 : idx;
}
int qsearch_rnas(uint x, GList<GffObj>& rnas) {
//binary search
//do the simplest tests first:
if (rnas[0]->start>x) return 0;
if (rnas.Last()->start<x) return -1;
uint istart=0;
int i=0;
int idx=-1;
int maxh=rnas.Count()-1;
int l=0;
int h = maxh;
while (l <= h) {
i = (l+h)>>1;
istart=rnas[i]->start;
if (istart < x) l = i + 1;
else {
if (istart == x) { //found matching coordinate here
idx=i;
while (idx<=maxh && rnas[idx]->start==x) {
idx++;
}
return (idx>maxh) ? -1 : idx;
}
h = i - 1;
}
} //while
idx = l;
while (idx<=maxh && rnas[idx]->start<=x) {
idx++;
}
return (idx>maxh) ? -1 : idx;
}
int cmpRedundant(GffObj& a, GffObj& b) {
if (a.exons.Count()==b.exons.Count()) {
if (a.covlen==b.covlen) {
return strcmp(a.getID(), b.getID());
}
else return (a.covlen>b.covlen)? 1 : -1;
}
else return (a.exons.Count()>b.exons.Count())? 1: -1;
}
bool tMatch(GffObj& a, GffObj& b) {
//strict intron chain match, or single-exon perfect match
int imax=a.exons.Count()-1;
int jmax=b.exons.Count()-1;
int ovlen=0;
if (imax!=jmax) return false; //different number of introns
if (imax==0) { //single-exon mRNAs
//if (equnspl) {
//fuzz match for single-exon transfrags:
// it's a match if they overlap at least 80% of max len
ovlen=a.exons[0]->overlapLen(b.exons[0]);
int maxlen=GMAX(a.covlen,b.covlen);
return (ovlen>=maxlen*0.8);
/*}
else {
//only exact match
ovlen=a.covlen;
return (a.exons[0]->start==b.exons[0]->start &&
a.exons[0]->end==b.exons[0]->end);
}*/
}
//check intron overlaps
ovlen=a.exons[0]->end-(GMAX(a.start,b.start))+1;
ovlen+=(GMIN(a.end,b.end))-a.exons.Last()->start;
for (int i=1;i<=imax;i++) {
if (i<imax) ovlen+=a.exons[i]->len();
if ((a.exons[i-1]->end!=b.exons[i-1]->end) ||
(a.exons[i]->start!=b.exons[i]->start)) {
return false; //intron mismatch
}
}
return true;
}
char* getSeqDescr(char* seqid) {
static char charbuf[128];
if (seqinfo.Count()==0) return NULL;
char* suf=rstrchr(seqid, '.');
if (suf!=NULL) *suf=0;
SeqInfo* seqd=seqinfo.Find(seqid);
if (suf!=NULL) *suf='.';
if (seqd!=NULL) {
GStr s(seqd->descr);
//cleanup some Uniref gunk
if (s[0]=='[') {
int r=s.index(']');
if (r>=0 && r<8 && isdigit(s[1]))
s.remove(0,r+1);
}
if (s.length()>80) {
int r=s.index(';');
if (r>5) s.cut(r);
}
if (s.length()>127) {
s.cut(127);
int r=s.rindex(' ');
if (r>0) s.cut(r);
}
strcpy(charbuf, s.chars());
return charbuf;
}
else return NULL;
}
char* getSeqName(char* seqid) {
static char charbuf[128];
char* suf=rstrchr(seqid, '.');
if (suf!=NULL) *suf=0;
strcpy(charbuf, seqid);
if (suf!=NULL) *suf='.';
return charbuf;
}
int adjust_stopcodon(GffObj& gffrec, int adj, GList<GSeg>* seglst) {
//adj>0, extend CDS to include a potential stop codon
//when CDS is expanded, the terminal exon might have to be adjusted too
int realadj=0;
if (gffrec.strand=='-') {
if ((int)gffrec.CDstart>adj) {
gffrec.CDstart-=adj;
realadj=adj;
if (gffrec.exons.First()->start>gffrec.CDstart) {
gffrec.covlen+=gffrec.exons.First()->start - gffrec.CDstart;
gffrec.exons.First()->start=gffrec.CDstart;
gffrec.start=gffrec.CDstart;
}
}
}
else { // forward strand
//expand beyond
realadj=adj;
gffrec.CDend+=adj;
if (adj<0) {//restore
if (gffrec.exons.Last()->end==gffrec.CDend-adj) {
gffrec.exons.Last()->end+=adj;
gffrec.end=gffrec.exons.Last()->end;
gffrec.covlen+=adj;
}
}
else if (gffrec.exons.Last()->end<gffrec.CDend) {
gffrec.covlen+=gffrec.CDend-gffrec.exons.Last()->end;
gffrec.exons.Last()->end=gffrec.CDend;
gffrec.end=gffrec.CDend;
}
}
if (seglst!=NULL) seglst->Last()->end+=realadj;
return realadj;
}
void printTableData(FILE* f, GffObj& g, bool inFasta) {
//using attribute list in tableCols
const int DBUF_LEN=1024; //there should not be attribute values larger than 1K!
char dbuf[DBUF_LEN];
char* av=NULL;
for(int i=0;i<tableCols.Count();i++) {
if (i>0 || inFasta) {
if (!inFasta || tableCols[i].type!=ctfGFF_ID)
fprintf(f,"\t");
}
switch(tableCols[i].type) {
case ctfGFF_Attr:
av=g.getAttr(tableCols[i].name.chars());
if (av) {
if (decodeChars) {
GffObj::decodeHexChars(dbuf, av, DBUF_LEN-1);
fprintf(f,"%s", dbuf);
} else fprintf(f,"%s",av);
} else fprintf(f,".");
break;
case ctfGFF_chr:
fprintf(f,"%s",g.getGSeqName());
break;
case ctfGFF_track:
fprintf(f,"%s",g.getTrackName());
break;
case ctfGFF_ID:
if (!inFasta)
fprintf(f,"%s",g.getID());
break;
case ctfGFF_geneID:
fprintf(f,"%s",g.getGeneID()!=NULL ? g.getGeneID() : ".");
break;
case ctfGFF_geneName:
fprintf(f,"%s",g.getGeneName()!=NULL ? g.getGeneName() : ".");
break;
case ctfGFF_Parent:
fprintf(f,"%s",g.parent!=NULL ? g.parent->getID() : ".");
break;
case ctfGFF_feature:
fprintf(f,"%s",g.getFeatureName());
break;
case ctfGFF_start:
fprintf(f,"%d",g.start);
break;
case ctfGFF_end:
fprintf(f,"%d",g.end);
break;
case ctfGFF_strand:
fprintf(f,"%c",g.strand);
break;
case ctfGFF_numexons:
fprintf(f,"%d",g.exons.Count());
break;
case ctfGFF_exons:
if (g.exons.Count()>0) {
for (int x=0;x<g.exons.Count();x++) {
if (x>0) fprintf(f,",");
fprintf(f,"%d-%d",g.exons[x]->start, g.exons[x]->end);
}
} else fprintf(f,".");
break;
case ctfGFF_introns:
if (g.exons.Count()>1) {
for (int i=0;i<g.exons.Count()-1;i++) {
if (i>0) fprintf(f,",");
fprintf(f,"%d-%d",g.exons[i]->end+1, g.exons[i+1]->start-1);
}
} else fprintf(f,".");
break;
case ctfGFF_cds:
if (g.hasCDS()) {
GVec<GffExon> cds;
g.getCDSegs(cds);
for (int x=0;x<cds.Count();x++) {
if (x>0) fprintf(f,",");
fprintf(f,"%d-%d",cds[x].start, cds[x].end);
}
}
else fprintf(f,".");
break;
case ctfGFF_covlen:
fprintf(f, "%d", g.covlen);
break;
case ctfGFF_cdslen:
if (g.hasCDS()) {
GVec<GffExon> cds;
g.getCDSegs(cds);
int clen=0;
for (int x=0;x<cds.Count();x++)
clen+=cds[x].end-cds[x].start+1;
fprintf(f, "%d", clen);
}
else fprintf(f, "0");
break;
} //switch
}
fprintf(f,"\n");
}
bool GffLoader::validateGffRec(GffObj* gffrec) {
if (!checkFilters(gffrec)) {
if (gffrec->isTranscript()) {
TFilters=true;
if (gffrec->parent!=NULL && keepGenes) {
GPVec<GffObj>& pchildren=gffrec->parent->children;
for (int c=0;c<pchildren.Count();c++) {
if (pchildren[c]==gffrec) {
pchildren.Delete(c);
break;
}
}
}
return false;
}
if (gffrec->isGene() && keepGenes) return true;
return false;
} //transcript rejected
return true;
}
bool GffLoader::checkFilters(GffObj* gffrec) {
if (reftbl.Count()>0) { //check if we need to reject by ref seq filter
GStr refname(gffrec->getRefName());
RefTran* rt=reftbl.Find(refname.chars());
if (rt==NULL && refname.length()>2 && refname[-2]=='.' && isdigit(refname[-1])) {
//try removing the version suffix
refname.cut(-2);
//GMessage("[DEBUG] Trying ref name '%s'...\n", refname.chars());
rt=reftbl.Find(refname.chars());
}
if (rt) {
gffrec->setRefName(rt->new_name);
}
/* //no, do not discard non-matching entries, let them pass through!
else {
if (verbose)
GMessage("Info: %s discarded due to reference %s not being mapped\n",
gffrec->getID(), refname.chars());
return false; //discard, ref seq not in the given translation table
}*/
}
if (transcriptsOnly && gffrec->isDiscarded()) {
//discard generic "locus" features with no other detailed subfeatures
//GMessage("Warning: discarding %s GFF generic gene/locus container %s\n",gffrec->getID());
return false;
}
if (IDflt) {
if (fltIDs.hasKey(gffrec->getID())) {
if (IDflt==idFlt_Exclude) return false;
}
else if (IDflt==idFlt_Only) return false;
}
if (minLen>0 && gffrec->covlen<minLen) {
if (verbose)
GMessage("Info: %s discarded due to minimum length threshold %d\n",
gffrec->getID(), minLen);
return false;
}
if (fltRange!=NULL) { //filter by gseqName
if (fltRange->refName!=NULL && strcmp(gffrec->getGSeqName(),fltRange->refName)!=0) {
return false;
}
if (fltRange->strand>0 && gffrec->strand!=fltRange->strand) {
return false;
}
//check coordinates
if (fltRange->start || fltRange->end<UINT_MAX) {
if (rfltWithin) {
if (gffrec->start<fltRange->start || gffrec->end>fltRange->end) {
return false; //not within query range
}
}
else {
if (gffrec->start>fltRange->end || gffrec->end<fltRange->start) {
return false;
}
}
}
}
if (this->attrsFilter) { //mostly relevant for transcripts and gene records
//remove attributes that are not in attrList
gffrec->removeAttrs(attrList);
}
if (gffrec->isTranscript()) { // && TFilters) ?
//these filters only apply to transcripts
if (multiExon && gffrec->exons.Count()<=1) {
return false;
}
if (wCDSonly && gffrec->CDstart==0) {
return false;
}
if (wNConly && gffrec->hasCDS()) return false;
if (fltJunction!=NULL) {
if (gffrec->exons.Count()<=1) return false;
if (fltJunction->refName!=NULL && strcmp(gffrec->getGSeqName(),fltJunction->refName)!=0) {
return false;
}
if (fltJunction->strand && gffrec->strand!=fltJunction->strand) {
return false;
}
//check coordinates
uint jstart=fltJunction->start;
uint jend=fltJunction->end;
if (jstart==0) jstart=jend;
if (jend==0) jend=jstart;
if (gffrec->start>=jstart || gffrec->end<=jend) {
return false;
}
bool noJMatch=true;
for (int i=0;i<gffrec->exons.Count()-1;++i) {
if (fltJunction->start && fltJunction->end) {
if (gffrec->exons[i]->end+1==fltJunction->start &&
gffrec->exons[i+1]->start-1==fltJunction->end)
{ noJMatch=false; break; }
} else if (fltJunction->start) { //end match not required
if (gffrec->exons[i]->end+1==fltJunction->start)
{ noJMatch=false; break; }
} else { //only end match required:
if (gffrec->exons[i+1]->start-1==fltJunction->end)
{ noJMatch=false; break; }
}
}
if (noJMatch) return false;
}
return process_transcript(gfasta, *gffrec);
} //transcript filters check
return true;
}
bool GffLoader::process_transcript(GFastaDb& gfasta, GffObj& gffrec) {
if (!gffrec.isTranscript()) return false; //shouldn't call this function unless it's a transcript
//returns true if the transcript passed the filter
char* gname=gffrec.getGeneName();
if (gname==NULL) gname=gffrec.getGeneID();
if (ensembl_convert && startsWith(gffrec.getID(), "ENS")) {
const char* biotype=gffrec.getAttr("gene_biotype");
if (biotype) {
gffrec.addAttr("type", biotype);
gffrec.removeAttr("gene_biotype");
}
else { //old Ensembl files lacking gene_biotype
gffrec.addAttr("type", gffrec.getTrackName());
}
//bool is_gene=false;
bool is_pseudo=false;
if (strcmp(biotype, "protein_coding")==0 || gffrec.hasCDS())
gffrec.setFeatureName("mRNA");
else {
if (strcmp(biotype, "processed_transcript")==0)
gffrec.setFeatureName("proc_RNA");
else {
//is_gene=endsWith(biotype, "gene");
is_pseudo=strifind(biotype, "pseudo");
if (is_pseudo) {
gffrec.setFeatureName("pseudo_RNA");
}
else if (endsWith(biotype, "RNA")) {
gffrec.setFeatureName(biotype);
} else gffrec.setFeatureName("misc_RNA");
}
}
}
if (gname && strcmp(gname, gffrec.getID())!=0) {
int* isonum=isoCounter.Find(gname);
if (isonum==NULL) {
//isonum=new int(1);
isoCounter.Add(gname,1);
}
else (*isonum)++;
//defline.appendfmt(" gene=%s", gname);
}
int seqlen=0;
const char* tlabel=tracklabel;
if (tlabel==NULL) tlabel=gffrec.getTrackName();
//defline.appendfmt(" track:%s",tlabel);
char* cdsnt = NULL;
char* cdsaa = NULL;
int aalen=0;
for (int i=1;i<gffrec.exons.Count();i++) {
int ilen=gffrec.exons[i]->start-gffrec.exons[i-1]->end-1;
if (verbose && ilen>4000000)
GMessage("Warning: very large intron (%d) for transcript %s\n",
ilen, gffrec.getID());
if (ilen>maxintron) {
return false;
}
}
GMapSegments seglst(gffrec.strand);
GFaSeqGet* faseq=NULL;
if (f_x!=NULL || f_y!=NULL || f_w!=NULL || f_u!=NULL || spliceCheck || validCDSonly || addCDSattrs) {
faseq=fastaSeqGet(gfasta, gffrec.getGSeqName());
if (faseq==NULL)
GError("Error: no genomic sequence available (check -g option!).\n");
}
if (spliceCheck && gffrec.exons.Count()>1) {
//check introns for splice site consensi ( GT-AG, GC-AG or AT-AC )
int glen=gffrec.end-gffrec.start+1;
const char* gseq=faseq->subseq(gffrec.start, glen);
if (gseq==NULL) {
GMessage("Error at GFF ID %s : could not retrieve subsequence %s:%d-%d !\n",
gffrec.getID(), gffrec.getRefName(), gffrec.start, gffrec.end);
return false;
}
bool revcompl=(gffrec.strand=='-');
bool ssValid=true;
for (int e=1;e<gffrec.exons.Count();e++) {
const char* intron=gseq+gffrec.exons[e-1]->end+1-gffrec.start;
int intronlen=gffrec.exons[e]->start-gffrec.exons[e-1]->end-1;
GSpliceSite acceptorSite(intron,intronlen,true, revcompl);
GSpliceSite donorSite(intron,intronlen, false, revcompl);
//GMessage("%c intron %d-%d : %s .. %s\n",
// gffrec.strand, istart, iend, donorSite.nt, acceptorSite.nt);
if (acceptorSite=="AG") { // GT-AG or GC-AG
if (!donorSite.canonicalDonor()) {
ssValid=false;break;
}
}
else if (acceptorSite=="AC") { //AT-AC also accepted
if (donorSite!="AT") { ssValid=false; break; }
}
else { ssValid=false; break; }
}
if (!ssValid) {
if (verbose)
GMessage("Unrecognized splice sites found for '%s'\n",gffrec.getID());
return false; //don't print this one!
}
}
bool trprint=true;
bool inframeStop=false;
//int stopCodonAdjust=0;
int mCDphase=0;
bool fullCDS=false;
bool endStop=false;
bool stopAdjusted=false;
if (add_hasCDS && gffrec.hasCDS()) gffrec.addAttr("hasCDS", "true");
if (gffrec.CDphase=='1' || gffrec.CDphase=='2')
mCDphase = gffrec.CDphase-'0';
//CDS partialness only added when -y -x -V options are given
if (gffrec.hasCDS() && (f_y!=NULL || f_x!=NULL || validCDSonly || addCDSattrs)) {
int strandNum=0;
int phaseNum=0;
CDS_CHECK:
uint cds_olen=0;
inframeStop=false;
cdsnt=gffrec.getSpliced(faseq, true, &seqlen, NULL, &cds_olen, &seglst, adjustStop);
//if adjustStop, seqlen has the CDS+3'UTR length, but cds_olen still has the original CDS length
if (cdsnt!=NULL && cdsnt[0]!='\0') { //has CDS
cdsaa=translateDNA(cdsnt, aalen, seqlen);
char* p=strchr(cdsaa,'.');
int cds_aalen=aalen;
if (adjustStop)
cds_aalen=cds_olen/3; //originally stated CDS length
endStop=false;
if (p!=NULL) { //stop codon found
if (p-cdsaa==cds_aalen-1) { //stop found as the stated last CDS codon
*p='\0';//remove it
endStop=true;
if (adjustStop) {
seqlen=cds_aalen*3;
aalen=cds_aalen;
}
cds_aalen--;
aalen--;
//no need to adjust stop codon
}
else {//stop found in a different position than the last codon
if (p-cdsaa<cds_aalen-1 && !adjustStop) {
inframeStop=true;
}
if (adjustStop) {
*p='\0';
cds_aalen=p-cdsaa+1; //adjusted CDS length
seqlen=cds_aalen*3;
aalen=cds_aalen;
uint gc=seglst.gmap(seqlen);
if (gffrec.strand=='-') gffrec.CDstart=gc;
else gffrec.CDend=gc;
endStop=true;
stopAdjusted=true;
}
}
}//stop codon found
//if (trprint==false) { //failed CDS validity check
if (inframeStop) {
//in-frame stop codon found
if (altPhases && phaseNum<3) {
phaseNum++; //try a different phase
gffrec.CDphase = '0'+((mCDphase+phaseNum)%3);
GFREE(cdsaa);
goto CDS_CHECK;
}
if (gffrec.exons.Count()==1 && bothStrands) {
strandNum++;
phaseNum=0;
if (strandNum<2) {
GFREE(cdsaa);
gffrec.strand = (gffrec.strand=='-') ? '+':'-';
goto CDS_CHECK; //repeat the CDS check for a different frame
}
}
if (verbose) GMessage("Warning: In-frame STOP found for '%s'\n",gffrec.getID());
if (addCDSattrs) gffrec.addAttr("InFrameStop", "true");
} //has in-frame STOP
if (stopAdjusted) {
if (addCDSattrs) gffrec.addAttr("CDStopAdjusted", "true");
inframeStop=false; //pretend it's OK now that we've adjusted it
}
if (!inframeStop) {
bool hasStart=(cdsaa[0]=='M'); //for the regular eukaryotic translation table
fullCDS=(endStop && hasStart);
if (!fullCDS) {
const char* partialness=NULL;
if (hasStart) partialness="3";
else {
partialness = endStop ? "5" : "5_3";
}
if (addCDSattrs) gffrec.addAttr("partialness", partialness);
}
}
if (trprint && ((fullCDSonly && !fullCDS) || (validCDSonly && inframeStop)) )
trprint=false;
//} // Valid CDS only requested?
} //has CDS
} //translation or codon check was requested
if (!trprint) {
GFREE(cdsnt);
GFREE(cdsaa);
//if (adjstop!=NULL) delete adjstop;
return false;
}
/*
if (validCDSonly) {
int stopCodonAdjust=adjstop->restore();
if (stopCodonAdjust!=0 && !endStop) {
//restore stop codon location
//adjust_stopcodon(gffrec, -stopCodonAdjust, &seglst);
if (seglst.Count()>0) seglst.Last()->end-=stopCodonAdjust;
if (cdsnt!=NULL && seqlen>0) {
seqlen-=stopCodonAdjust;
cdsnt[seqlen]=0;
}
if (cdsaa!=NULL) aalen--;
}
}
if (adjstop!=NULL) delete adjstop;
*/
if (cdsnt!=NULL) { // && !inframeStop) {
GStr defline(gffrec.getID(), 94);
if (writeExonSegs) {
defline.append(" loc:");
defline.append(gffrec.getGSeqName());
defline.appendfmt("(%c)",gffrec.strand);
//warning: not CDS coordinates are written here, but the exon ones
defline+=(int)gffrec.start;
defline+=(char)'-';
defline+=(int)gffrec.end;
// -- here these are CDS substring coordinates on the spliced sequence:
defline.append(" segs:");
for (int i=0;i<seglst.Count();i++) {
if (i>0) defline.append(",");
defline+=(int)seglst[i].start;
defline.append("-");
defline+=(int)seglst[i].end;
}
}
if (f_y!=NULL) { //CDS translation fasta output requested
if (cdsaa==NULL) { //translate now if not done before
cdsaa=translateDNA(cdsnt, aalen, seqlen);
}
if (aalen>0) {
if (cdsaa[aalen-1]=='.' || cdsaa[aalen-1]=='\0') --aalen; //avoid printing the stop codon
fprintf(f_y, ">%s", defline.chars());
if (fmtTable) printTableData(f_y, gffrec, true);
else {
if (gffrec.attrs!=NULL && gffrec.attrs->Count()>0) fprintf(f_y," ");
gffrec.printAttrs(f_y, ";", false, decodeChars, false);
fprintf(f_y, "\n");
}
printFasta(f_y, NULL, cdsaa, aalen, StarStop);
}
}
if (f_x!=NULL) { //CDS only
fprintf(f_x, ">%s", defline.chars());
if (fmtTable) printTableData(f_x, gffrec, true);
else {
if (gffrec.attrs!=NULL && gffrec.attrs->Count()>0) fprintf(f_x," ");
gffrec.printAttrs(f_x, ";", false, decodeChars, false);
fprintf(f_x, "\n");
}
printFasta(f_x, NULL, cdsnt, seqlen);
}
GFREE(cdsnt);
GFREE(cdsaa);
} //writing CDS or its translation
if (f_w!=NULL) { //write spliced exons
uint cds_start=0;
uint cds_end=0;
seglst.Clear();
int padLeft=0;
int padRight=0;
if (wPadding>0) {
padLeft= (gffrec.start>(uint)wPadding) ? wPadding : gffrec.start - 1;
int ediff=faseq->getseqlen()-gffrec.end;
padRight=(wPadding>ediff) ? ediff : wPadding;
gffrec.addPadding(padLeft, padRight);
}
char* exont=gffrec.getSpliced(faseq, false, &seqlen, &cds_start, &cds_end, &seglst);
//restore exons to normal (remove padding)
if (wPadding>0)
gffrec.removePadding(padLeft, padRight);
GStr defline(gffrec.getID());
if (exont!=NULL) {
if (!wfaNoCDS && gffrec.CDstart>0) {
defline.appendfmt(" CDS=%d-%d", cds_start, cds_end);
}
if (writeExonSegs) {
defline.append(" loc:");
defline.append(gffrec.getGSeqName());
defline+=(char)'|';
defline+=(int)gffrec.start;
defline+=(char)'-';
defline+=(int)gffrec.end;
defline+=(char)'|';
defline+=(char)gffrec.strand;
defline.append(" exons:");
for (int i=0;i<gffrec.exons.Count();i++) {
if (i>0) defline.append(",");
defline+=(int)gffrec.exons[i]->start;
defline.append("-");
defline+=(int)gffrec.exons[i]->end;
}
if (wPadding>0) {
defline.append(" padding:");
defline.append(padLeft);
defline+=(char)'|';
defline.append(padRight);
}
defline.append(" segs:");
for (int i=0;i<seglst.Count();i++) {
if (i>0) defline.append(",");
defline+=(int)seglst[i].start;
defline.append("-");
defline+=(int)seglst[i].end;
}
}
fprintf(f_w, ">%s", defline.chars());
if (fmtTable) printTableData(f_w, gffrec, true);
else {
if (gffrec.attrs!=NULL && gffrec.attrs->Count()>0) fprintf(f_w," ");
gffrec.printAttrs(f_w, ";", false, decodeChars, false);
fprintf(f_w, "\n");
}
printFasta(f_w, NULL, exont, seqlen);
GFREE(exont);
}
} //writing f_w (spliced exons)
if (f_u!=NULL) { //write unspliced transcript sequence
int padLeft=0;
int padRight=0;
if (wPadding>0) {
padLeft= (gffrec.start>(uint)wPadding) ? wPadding : gffrec.start - 1;
int ediff=faseq->getseqlen()-gffrec.end;
padRight=(wPadding>ediff) ? ediff : wPadding;
}
//char* exont=gffrec.getSpliced(faseq, false, &seqlen, &cds_start, &cds_end, &seglst);
int fspan=gffrec.end-gffrec.start+1+padLeft+padRight;
int fstart=gffrec.start-padLeft;
const char* tseq=faseq->subseq(fstart, fspan); //non-zero-terminated
//fspan will be updated with whatever was read
if (tseq==NULL) {
GError("Error getting transcripts seq for %s (%d : %d)!\n", gffrec.getID(), fstart, fspan);
}
GStr defline(gffrec.getID());
if (tseq!=NULL && fspan>0) {
fprintf(f_u, ">%s", defline.chars());
if (fmtTable) printTableData(f_u, gffrec, true);
else {
if (gffrec.attrs!=NULL && gffrec.attrs->Count()>0) fprintf(f_u," ");
gffrec.printAttrs(f_u, ";", false, decodeChars, false);
fprintf(f_u, "\n");
}
printFasta(f_u, NULL, tseq, fspan);
}
} //writing f_u (unspliced sequence)
return true;
}
GTData::GTData(GffObj* t, GenomicSeqData* gd):rna(t),gdata(gd), locus(NULL), replaced_by(NULL), geneinfo(NULL) {
if (rna!=NULL) {
//geneinfo=(GeneInfo*)rna->uptr; //take over geneinfo, if there
rna->uptr=this;
}
if (gdata!=NULL)
gdata->tdata.Add(this);
}
bool GffLoader::unsplContained(GffObj& ti, GffObj& tj) {
//returns true only if ti (which MUST be single-exon) is "almost" contained in any of tj's exons
//but it does not cross any intron-exon boundary of tj
int imax=ti.exons.Count()-1;
int jmax=tj.exons.Count()-1;
if (imax>0) GError("Error: bad unsplContained() call, 1st parameter must be single-exon transcript!\n");
if (ncSpan) {
int maxIntronOvl=dOvlSET ? 25 : 0;
//int minovl = dOvlSET ? 5 : (int)(0.8 * ti.len()); //minimum overlap to declare "redundancy"
for (int j=0;j<=jmax;j++) {
bool exonOverlap=false;
if (dOvlSET) {
exonOverlap= (tj.exons[j]->overlapLen(ti.start-1, ti.end+1) > 0);
} else {
exonOverlap=(ti.overlapLen(tj.exons[j])>=0.8 * ti.len());
}
if (exonOverlap) {
//must not overlap the introns
if ((j>0 && ti.start+maxIntronOvl<tj.exons[j]->start)
|| (j<jmax && ti.end>tj.exons[j]->end+maxIntronOvl))
return false;
return true;
}
} //for each exon
} else { // not fuzzSpan, strict containment required
for (int j=0;j<=jmax;j++) {
if (ti.end<=tj.exons[j]->end && ti.start>=tj.exons[j]->start)
return true;
}
}
return false;
}
GffObj* GffLoader::redundantTranscripts(GffObj& ti, GffObj& tj) {
// matchAllIntrons==true: transcripts are considered "redundant" only if
// they have the exact same number of introns and same splice sites (or none)
// (single-exon transcripts should be also fully contained to be considered matching)
// matchAllIntrons==false: an intron chain could be a subset of a "container" chain,
// as long as no intron-exon boundaries are violated;
// also, if --cset was given, a single-exon transcript will be collapsed
// if it's contained in one of the exons of the another transcript
// fuzzSpan==false: the genomic span of one transcript MUST BE contained in or equal with the genomic
// span of the other
//
// fuzzSpan==true: then genomic spans of transcripts are no longer required to be fully contained
// (i.e. they may extend each-other in opposite directions)
//if redundancy is detected, the "bigger" transcript is returned (otherwise NULL is returned)
int adj=dOvlSET ? 1 : 0;
if (ti.start>tj.end+adj || tj.start>ti.end+adj ||
(tj.strand!='.' && ti.strand!='.' && tj.strand!=ti.strand)) return NULL; //no span overlap
int imax=ti.exons.Count()-1;
int jmax=tj.exons.Count()-1;
GffObj* bigger=NULL;
GffObj* smaller=NULL;
if (matchAllIntrons) { //full intron chain match expected, or full containment for SET
if (imax!=jmax) return NULL; //must have the same number of exons!
if (ti.covlen>tj.covlen) {
bigger=&ti;
if (!ncSpan && (ti.start>tj.start || ti.end<tj.end))
return NULL; //no containment
}
else { //ti.covlen<=tj.covlen
bigger=&tj;
if (!ncSpan && (tj.start>ti.start || tj.end<ti.end))
return NULL; //no containment
}
//check that all introns really match
for (int i=0;i<imax;i++) {
if (ti.exons[i]->end!=tj.exons[i]->end ||
ti.exons[i+1]->start!=tj.exons[i+1]->start) return NULL;
}
return bigger;
}
//--- matchAllIntrons==false: intron-chain containment is also considered redundancy
int minlen=0;
if (ti.covlen>tj.covlen) {
if (tj.exons.Count()>ti.exons.Count()) {
//exon count override
bigger=&tj;
smaller=&ti;
} else {
bigger=&ti;
smaller=&tj;
}
//maxlen=ti.covlen;
minlen=tj.covlen;
} else { //tj has more bases covered
if (ti.exons.Count()>tj.exons.Count()) {
//exon count override
bigger=&ti;
smaller=&tj;
} else {
bigger=&tj;
smaller=&ti;
}
//maxlen=tj.covlen;
minlen=ti.covlen;
}
if (imax==0 && jmax==0) {
//single-exon transcripts: if fuzzSpan, at least 80% of the shortest one must be overlapped by the other
if (ncSpan) {
if (dOvlSET) {
return (ti.exons[0]->overlapLen(tj.exons[0]->start-1, tj.exons[0]->end+1)>0) ? bigger : NULL;
} else {