ViewVC Help
View File | Revision Log | Show Annotations | View Changeset | Root Listing
root/gclib/gclib/gff.cpp
Revision: 153
Committed: Fri Jan 20 22:35:32 2012 UTC (7 years, 5 months ago) by gpertea
File size: 67755 byte(s)
Log Message:
still working on trans-splicing/fusions in gff

Line User Rev File contents
1 gpertea 2 #include "gff.h"
2    
3     //GffNames* GffReader::names=NULL;
4     GffNames* GffObj::names=NULL;
5     //global set of feature names, attribute names etc.
6     // -- common for all GffObjs in current application!
7    
8 gpertea 16 const uint GFF_MAX_LOCUS = 7000000; //longest known gene in human is ~2.2M, UCSC claims a gene for mouse of ~ 3.1 M
9     const uint GFF_MAX_EXON = 30000; //longest known exon in human is ~11K
10 gpertea 115 const uint GFF_MAX_INTRON= 6000000; //Ensembl shows a >5MB human intron
11 gpertea 16 bool gff_show_warnings = false; //global setting, set by GffReader->showWarnings()
12 gpertea 2 const int gff_fid_mRNA=0;
13 gpertea 16 const int gff_fid_transcript=1;
14     const int gff_fid_exon=2;
15     const int gff_fid_CDS=3; //never really used in GffObj ftype_id or subftype_id
16     const uint gfo_flag_HAS_ERRORS = 0x00000001;
17     const uint gfo_flag_CHILDREN_PROMOTED= 0x00000002;
18     const uint gfo_flag_IS_GENE = 0x00000004;
19     const uint gfo_flag_IS_TRANSCRIPT = 0x00000008;
20 gpertea 153 const uint gfo_flag_HAS_GFF_ID = 0x00000010; //found GFF3 feature line with its own ID
21 gpertea 16 const uint gfo_flag_BY_EXON = 0x00000020; //created by subfeature (exon) directly
22     const uint gfo_flag_DISCARDED = 0x00000100;
23     const uint gfo_flag_LST_KEEP = 0x00000200;
24     const uint gfo_flag_LEVEL_MSK = 0x00FF0000;
25     const byte gfo_flagShift_LEVEL = 16;
26 gpertea 2
27     void gffnames_ref(GffNames* &n) {
28     if (n==NULL) n=new GffNames();
29     n->numrefs++;
30     }
31    
32     void gffnames_unref(GffNames* &n) {
33     if (n==NULL) GError("Error: attempt to remove reference to null GffNames object!\n");
34     n->numrefs--;
35     if (n->numrefs==0) { delete n; n=NULL; }
36     }
37    
38     int gfo_cmpByLoc(const pointer p1, const pointer p2) {
39    
40     GffObj& g1=*((GffObj*)p1);
41     GffObj& g2=*((GffObj*)p2);
42 gpertea 16 if (g1.gseq_id==g2.gseq_id) {
43     if (g1.start!=g2.start)
44     return (int)(g1.start-g2.start);
45     else if (g1.getLevel()!=g2.getLevel())
46     return (int)(g1.getLevel()-g2.getLevel());
47     else
48     if (g1.end!=g2.end)
49     return (int)(g1.end-g2.end);
50     else return strcmp(g1.getID(), g2.getID());
51     }
52     else return (int)(g1.gseq_id-g2.gseq_id);
53 gpertea 2 }
54    
55 gpertea 150 char* GffLine::extractAttr(const char* attr, bool caseStrict, bool enforce_GTF2) {
56 gpertea 16 //parse a key attribute and remove it from the info string
57     //(only works for attributes that have values following them after ' ' or '=')
58     static const char GTF2_ERR[]="Error parsing attribute %s ('\"' required) at GTF line:\n%s\n";
59 gpertea 150 int attrlen=strlen(attr);
60     char cend=attr[attrlen-1];
61     //char* pos = (caseStrict) ? strstr(info, attr) : strifind(info, attr);
62     //must make sure attr is not found in quoted text
63     char* pos=info;
64     char prevch=0;
65     bool in_str=false;
66     bool notfound=true;
67     int (*strcmpfn)(const char*, const char*, int) = caseStrict ? Gstrcmp : Gstricmp;
68     while (notfound && *pos) {
69     char ch=*pos;
70     if (ch=='"') {
71     in_str=!in_str;
72     pos++;
73     prevch=ch;
74     continue;
75     }
76     if (!in_str && (prevch==0 || prevch==' ' || prevch == ';')
77     && strcmpfn(attr, pos, attrlen)==0) {
78     //attr match found
79     //check for word boundary on right
80     char* epos=pos+attrlen;
81     if (cend=='=' || cend==' ' || *epos==0 || *epos==' ') {
82     notfound=false;
83     break;
84     }
85     //not a perfect match, move on
86     pos=epos;
87     prevch=*(pos-1);
88     continue;
89     }
90     //not a match or in_str
91     prevch=ch;
92     pos++;
93     }
94     if (notfound) return NULL;
95     char* vp=pos+attrlen;
96 gpertea 16 while (*vp==' ') vp++;
97     if (*vp==';' || *vp==0)
98 gpertea 150 GError("Error parsing value of GFF attribute \"%s\", line:\n%s\n", attr, dupline);
99 gpertea 16 bool dq_enclosed=false; //value string enclosed by double quotes
100     if (*vp=='"') {
101     dq_enclosed=true;
102     vp++;
103     }
104     if (enforce_GTF2 && !dq_enclosed)
105 gpertea 150 GError(GTF2_ERR,attr, dupline);
106 gpertea 16 char* vend=vp;
107     if (dq_enclosed) {
108     while (*vend!='"' && *vend!=';' && *vend!=0) vend++;
109     }
110     else {
111     while (*vend!=';' && *vend!=0) vend++;
112     }
113     if (enforce_GTF2 && *vend!='"')
114 gpertea 150 GError(GTF2_ERR, attr, dupline);
115 gpertea 16 char *r=Gstrdup(vp, vend-1);
116     //-- now remove this attribute from the info string
117     while (*vend!=0 && (*vend=='"' || *vend==';' || *vend==' ')) vend++;
118     if (*vend==0) vend--;
119     for (char *src=vend, *dest=pos;;src++,dest++) {
120     *dest=*src;
121     if (*src==0) break;
122     }
123     return r;
124     }
125 gpertea 2
126 gpertea 16 static char fnamelc[128];
127    
128 gpertea 2 GffLine::GffLine(GffReader* reader, const char* l) {
129 gpertea 16 llen=strlen(l);
130     GMALLOC(line,llen+1);
131     memcpy(line, l, llen+1);
132     GMALLOC(dupline, llen+1);
133     memcpy(dupline, l, llen+1);
134 gpertea 2 skip=true;
135     gseqname=NULL;
136     track=NULL;
137     ftype=NULL;
138     info=NULL;
139 gpertea 16 _parents=NULL;
140     _parents_len=0;
141     num_parents=0;
142     parents=NULL;
143     is_gff3=false;
144 gpertea 2 is_cds=false;
145 gpertea 16 is_transcript=false;
146 gpertea 2 is_exon=false;
147 gpertea 16 is_gene=false;
148 gpertea 2 exontype=0;
149 gpertea 16 gene_id=NULL;
150     gene_name=NULL;
151 gpertea 2 qstart=0;
152     qend=0;
153     qlen=0;
154     ID=NULL;
155     char* t[9];
156     int i=0;
157     int tidx=1;
158     t[0]=line;
159    
160     while (line[i]!=0) {
161     if (line[i]=='\t') {
162     line[i]=0;
163     t[tidx]=line+i+1;
164     tidx++;
165     if (tidx>8) break;
166     }
167     i++;
168     }
169    
170     if (tidx<8) { // ignore non-GFF lines
171     // GMessage("Warning: error parsing GFF/GTF line:\n%s\n", l);
172     return;
173     }
174     gseqname=t[0];
175     track=t[1];
176     ftype=t[2];
177     info=t[8];
178     char* p=t[3];
179 gpertea 66 if (!parseUInt(p,fstart)) {
180     //FIXME: chromosome_band entries in Flybase
181     GMessage("Warning: invalid start coordinate at line:\n%s\n",l);
182     return;
183     }
184 gpertea 2 p=t[4];
185 gpertea 66 if (!parseUInt(p,fend)) {
186     GMessage("Warning: invalid end coordinate at line:\n%s\n",l);
187     return;
188     }
189 gpertea 144 if (fend<fstart) Gswap(fend,fstart); //make sure fstart>=fend, always
190 gpertea 2 p=t[5];
191     if (p[0]=='.' && p[1]==0) {
192     score=0;
193     }
194     else {
195     if (!parseDouble(p,score))
196     GError("Error parsing feature score from GFF line:\n%s\n",l);
197     }
198     strand=*t[6];
199     if (strand!='+' && strand!='-' && strand!='.')
200     GError("Error parsing strand (%c) from GFF line:\n%s\n",strand,l);
201 gpertea 16 phase=*t[7]; // must be '.', '0', '1' or '2'
202 gpertea 2 ID=NULL;
203     // exon/CDS/mrna filter
204 gpertea 16 strncpy(fnamelc, ftype, 127);
205     fnamelc[127]=0;
206 gpertea 2 strlower(fnamelc); //convert to lower case
207 gpertea 16 bool is_t_data=false;
208 gpertea 2 if (strstr(fnamelc, "utr")!=NULL) {
209     exontype=exgffUTR;
210     is_exon=true;
211 gpertea 16 is_t_data=true;
212 gpertea 2 }
213 gpertea 66 else if (endsWith(fnamelc, "exon")) {
214 gpertea 2 exontype=exgffExon;
215     is_exon=true;
216 gpertea 16 is_t_data=true;
217 gpertea 2 }
218 gpertea 16 else if (strstr(fnamelc, "stop") &&
219     (strstr(fnamelc, "codon") || strstr(fnamelc, "cds"))){
220 gpertea 2 exontype=exgffStop;
221 gpertea 16 is_cds=true; //though some place it outside the last CDS segment
222     is_t_data=true;
223     }
224     else if (strstr(fnamelc, "start") &&
225     ((strstr(fnamelc, "codon")!=NULL) || strstr(fnamelc, "cds")!=NULL)){
226     exontype=exgffStart;
227 gpertea 2 is_cds=true;
228 gpertea 16 is_t_data=true;
229 gpertea 2 }
230     else if (strcmp(fnamelc, "cds")==0) {
231     exontype=exgffCDS;
232     is_cds=true;
233 gpertea 16 is_t_data=true;
234 gpertea 2 }
235 gpertea 16 else if (endsWith(fnamelc, "gene") || startsWith(fnamelc, "gene")) {
236     is_gene=true;
237     is_t_data=true; //because its name will be attached to parented transcripts
238 gpertea 2 }
239 gpertea 16 else if (endsWith(fnamelc,"rna") || endsWith(fnamelc,"transcript")) {
240     is_transcript=true;
241     is_t_data=true;
242     }
243 gpertea 2
244 gpertea 16 if (reader->transcriptsOnly && !is_t_data) {
245     char* id=extractAttr("ID=");
246     if (id==NULL) id=extractAttr("transcript_id");
247     //GMessage("Discarding non-transcript line:\n%s\n",l);
248     if (id!=NULL) {
249     reader->discarded_ids.Add(id, new int(1));
250     GFREE(id);
251     }
252     return; //skip this line, unwanted feature name
253 gpertea 2 }
254 gpertea 150 ID=extractAttr("ID=",true);
255     char* Parent=extractAttr("Parent=",true);
256 gpertea 16 is_gff3=(ID!=NULL || Parent!=NULL);
257     if (is_gff3) {
258     //parse as GFF3
259     if (ID!=NULL) {
260     //has ID attr so it's likely to be a parent feature
261     //look for explicit gene name
262 gpertea 150 gene_name=extractAttr("gene_name=");
263 gpertea 16 if (gene_name==NULL) {
264 gpertea 150 gene_name=extractAttr("geneName=");
265 gpertea 16 if (gene_name==NULL) {
266 gpertea 150 gene_name=extractAttr("gene_sym=");
267 gpertea 16 if (gene_name==NULL) {
268 gpertea 150 gene_name=extractAttr("gene=");
269 gpertea 16 }
270     }
271     }
272 gpertea 150 gene_id=extractAttr("geneID=");
273 gpertea 16 if (gene_id==NULL) {
274 gpertea 150 gene_id=extractAttr("gene_id=");
275 gpertea 16 }
276     if (is_gene) {
277     //special case: keep the Name and ID attributes of the gene feature
278     if (gene_name==NULL)
279     gene_name=extractAttr("Name=");
280     if (gene_id==NULL) //the ID is also gene_id in this case
281     gene_id=Gstrdup(ID);
282     //skip=false;
283     //return;
284     GFREE(Parent); //TMI, we really don't care about gene Parents?
285     } //gene feature
286     }// has GFF3 ID
287     if (Parent!=NULL) {
288     //keep Parent attr
289     //parse multiple parents
290     num_parents=1;
291     p=Parent;
292     int last_delim_pos=-1;
293     while (*p!=';' && *p!=0) {
294     if (*p==',' && *(p+1)!=0 && *(p+1)!=';') {
295     num_parents++;
296     last_delim_pos=(p-Parent);
297     }
298     p++;
299     }
300     _parents_len=p-Parent+1;
301     _parents=Parent;
302     GMALLOC(parents, num_parents*sizeof(char*));
303     parents[0]=_parents;
304     int i=1;
305     if (last_delim_pos>0) {
306     for (p=_parents+1;p<=_parents+last_delim_pos;p++) {
307     if (*p==',') {
308     char* ep=p-1;
309     while (*ep==' ' && ep>_parents) ep--;
310     *(ep+1)=0; //end the string there
311     parents[i]=p+1;
312     i++;
313     }
314     }
315     }
316     } //has Parent field
317     } //GFF3
318     else { // GTF-like expected
319 gpertea 150 Parent=extractAttr("transcript_id",true);
320 gpertea 16 if (Parent!=NULL) { //GTF2 format detected
321     if (is_transcript) {
322     // atypical GTF with a parent transcript line declared
323     ID=Parent;
324     Parent=NULL;
325     }
326     gene_id=extractAttr("gene_id"); // for GTF this is the only attribute accepted as geneID
327 gpertea 150 if (gene_id==NULL)
328     gene_id=extractAttr("geneid");
329 gpertea 16 gene_name=extractAttr("gene_name");
330     if (gene_name==NULL) {
331 gpertea 150
332 gpertea 16 gene_name=extractAttr("gene_sym");
333 gpertea 150 if (gene_name==NULL) {
334 gpertea 16 gene_name=extractAttr("gene");
335 gpertea 150 if (gene_name==NULL)
336     gene_name=extractAttr("genesymbol");
337     }
338 gpertea 16 }
339 gpertea 2 //prepare for parseAttr by adding '=' character instead of spaces for all attributes
340     //after the attribute name
341     p=info;
342     bool noed=true; //not edited after the last delim
343     bool nsp=false; //non-space found after last delim
344     while (*p!=0) {
345 gpertea 16 if (*p==' ') {
346     if (nsp && noed) {
347     *p='=';
348     noed=false;
349     p++;
350     continue;
351     }
352     }
353     else nsp=true; //non-space
354     if (*p==';') { noed=true; nsp=false; }
355     p++;
356     }
357     } //GTF2 detected (no parent line)
358     else {// Parent is NULL, check for jigsaw format or other pre-GTF2 format
359     //char* fexon=strstr(fnamelc, "exon");
360     //if (fexon!=NULL) {
361     if (exontype==exgffExon) {
362 gpertea 2 if (startsWith(track,"jigsaw")) {
363 gpertea 16 is_cds=true;
364     strcpy(track,"jigsaw");
365     p=strchr(info,';');
366     if (p==NULL) { Parent=Gstrdup(info); info=NULL; }
367     else { Parent=Gstrdup(info,p-1);
368     info=p+1;
369     }
370     }
371     } //exon feature?
372     if (Parent==NULL && exontype>=exgffCDS &&
373     (i=strcspn(info,"; \t\n\r"))<=(int)(strlen(info)+1)) {
374     //one word ID ? really desperate attempt to parse it here
375 gpertea 2 Parent=Gstrdup(info,info+i-1);
376 gpertea 16 info=NULL; //discard anything else on the line
377     }
378     }
379     if (Parent!=NULL) { //GTF transcript_id for exon/CDS feature
380     _parents=Parent;
381     GMALLOC(parents,sizeof(char*));
382     num_parents=1;
383     parents[0]=_parents;
384     }
385     } //GTF-like
386 gpertea 2
387 gpertea 16 //parse other potentially useful features
388     if (is_gff3) {
389     if ((p=strstr(info,"Target="))!=NULL) { //has Target attr
390     p+=7;
391     while (*p!=';' && *p!=0 && *p!=' ') p++;
392     if (*p!=' ') {
393     GError("Error parsing target coordinates from GFF line:\n%s\n",l);
394     }
395     if (!parseUInt(p,qstart))
396     GError("Error parsing target start coordinate from GFF line:\n%s\n",l);
397     if (*p!=' ') {
398     GError("Error parsing next target coordinate from GFF line:\n%s\n",l);
399     }
400     p++;
401     if (!parseUInt(p,qend))
402     GError("Error parsing target end coordinate from GFF line:\n%s\n",l);
403 gpertea 2 }
404 gpertea 16 if ((p=strifind(info,"Qreg="))!=NULL) { //has Qreg attr
405     p+=5;
406     if (!parseUInt(p,qstart))
407     GError("Error parsing target start coordinate from GFF line:\n%s\n",l);
408     if (*p!='-') {
409     GError("Error parsing next target coordinate from GFF line:\n%s\n",l);
410     }
411     p++;
412     if (!parseUInt(p,qend))
413     GError("Error parsing target end coordinate from GFF line:\n%s\n",l);
414     if (*p=='|' || *p==':') {
415     p++;
416     if (!parseUInt(p,qlen))
417     GError("Error parsing target length from GFF Qreg|: \n%s\n",l);
418     }
419     }//has Qreg attr
420     if (qlen==0 && (p=strifind(info,"Qlen="))!=NULL) {
421     p+=5;
422     if (!parseUInt(p,qlen))
423     GError("Error parsing target length from GFF Qlen:\n%s\n",l);
424 gpertea 2 }
425 gpertea 16 }//parsing some useful attributes in GFF3 records
426     if (ID==NULL && parents==NULL) {
427     if (reader->gff_warns)
428     GMessage("Warning: could not parse ID or Parent from GFF line:\n%s\n",dupline);
429     return; //skip
430 gpertea 2 }
431     skip=false;
432     }
433    
434 gpertea 55
435     void GffObj::addCDS(uint cd_start, uint cd_end, char phase) {
436     if (cd_start>=this->start) {
437     this->CDstart=cd_start;
438     if (strand=='+') this->CDphase=phase;
439     }
440     else this->CDstart=this->start;
441     if (cd_end<=this->end) {
442     this->CDend=cd_end;
443     if (strand=='-') this->CDphase=phase;
444     }
445     else this->CDend=this->end;
446     isTranscript(true);
447     exon_ftype_id=gff_fid_exon;
448     if (monoFeature()) {
449     if (exons.Count()==0) addExon(this->start, this->end,0,'.',0,0,false,exgffExon);
450     else exons[0]->exontype=exgffExon;
451     }
452     }
453    
454 gpertea 16 int GffObj::addExon(GffReader* reader, GffLine* gl, bool keepAttr, bool noExonAttr) {
455 gpertea 2 //this will make sure we have the right subftype_id!
456 gpertea 55 //int subf_id=-1;
457     if (!isTranscript() && gl->is_cds) {
458 gpertea 50 isTranscript(true);
459     exon_ftype_id=gff_fid_exon;
460     if (exons.Count()==1) exons[0]->exontype=exgffExon;
461     }
462 gpertea 16 if (isTranscript()) {
463     if (exon_ftype_id<0) {//exon_ftype_id=gff_fid_exon;
464     if (gl->exontype>0) exon_ftype_id=gff_fid_exon;
465     else exon_ftype_id=names->feats.addName(gl->ftype);
466     }
467 gpertea 2 //any recognized mRNA segment gets the generic "exon" type (also applies to CDS)
468 gpertea 16 if (gl->exontype==0 && !gl->is_transcript) {
469     //extraneous mRNA feature, discard
470     if (reader->gff_warns)
471     GMessage("Warning: discarding unrecognized transcript subfeature %s of %s\n",
472     gl->ftype, gffID);
473 gpertea 2 return -1;
474 gpertea 16 }
475 gpertea 2 }
476 gpertea 16 else { //non-mRNA parent feature, check this subf type
477 gpertea 55 int subf_id=names->feats.addName(gl->ftype);
478 gpertea 16 if (exon_ftype_id<0 || exons.Count()==0) //never assigned a subfeature type before (e.g. first exon being added)
479     exon_ftype_id=subf_id;
480     else {
481     if (exon_ftype_id!=subf_id) {
482 gpertea 50 //
483 gpertea 16 if (exon_ftype_id==ftype_id && exons.Count()==1 && exons[0]->start==start && exons[0]->end==end) {
484     //the existing exon was just a dummy one created by default, discard it
485     exons.Clear();
486     covlen=0;
487     exon_ftype_id=subf_id; //allow the new subfeature to completely takeover
488     }
489     else { //multiple subfeatures, prefer those with
490     if (reader->gff_warns)
491     GMessage("GFF Warning: multiple subfeatures (%s and %s) found for %s, discarding ",
492     names->feats.getName(subf_id), names->feats.getName(exon_ftype_id),gffID);
493     if (gl->exontype!=0) { //new feature is an exon, discard previously parsed subfeatures
494     if (reader->gff_warns) GMessage("%s.\n", names->feats.getName(exon_ftype_id));
495     exon_ftype_id=subf_id;
496     exons.Clear();
497     covlen=0;
498     }
499     else { //discard new feature
500     if (reader->gff_warns) GMessage("%s.\n", names->feats.getName(subf_id));
501     return -1; //skip this 2nd subfeature type for this parent!
502     }
503     }
504     } //incoming subfeature is of different type
505     } //new subfeature type
506     } //non-mRNA parent
507 gpertea 2 int eidx=addExon(gl->fstart, gl->fend, gl->score, gl->phase,
508     gl->qstart,gl->qend, gl->is_cds, gl->exontype);
509 gpertea 16 if (eidx<0) return eidx; //this should never happen
510     if (keepAttr) {
511     if (noExonAttr) {
512     if (attrs==NULL) //place the parsed attributes directly at transcript level
513     parseAttrs(attrs, gl->info);
514     }
515     else { //need all exon-level attributes
516     parseAttrs(exons[eidx]->attrs, gl->info, true);
517     }
518 gpertea 2 }
519     return eidx;
520     }
521    
522    
523     int GffObj::addExon(uint segstart, uint segend, double sc, char fr, int qs, int qe, bool iscds, char exontype) {
524     if (exons.Count()==0) {
525     if (iscds) isCDS=true; //for now, assume CDS only if first "exon" given is a CDS
526 gpertea 16 if (exon_ftype_id<0) {
527     exon_ftype_id = isTranscript() ? gff_fid_exon : ftype_id;
528 gpertea 2 }
529     }
530 gpertea 16 //special treatment of start/stop codon features, they might be broken/split between exons
531     //and in that case some providers will still give the wrong end coordinate as start+2 (e.g. UCSC)
532     //so we should not trust the end coordinate for such features
533     if (exontype==exgffStart || exontype==exgffStop) {
534     if (strand=='-') segstart=segend;
535     else segend=segstart;
536     if (exontype==exgffStart) {
537     if (CDstart==0 || segstart<CDstart) CDstart=segstart;
538     }
539     else {
540     if (segstart>CDend) CDend=segstart;
541     }
542     }
543     else if (iscds) { //update CDS anchors:
544 gpertea 2 if (CDstart==0 || segstart<CDstart) {
545     CDstart=segstart;
546     if (exontype==exgffCDS && strand=='+') CDphase=fr;
547     }
548     if (segend>CDend) {
549     if (exontype==exgffCDS && strand=='-') CDphase=fr;
550     CDend=segend;
551     }
552     }
553 gpertea 16 else { // not a CDS/start/stop
554 gpertea 2 isCDS=false;
555     }
556     if (qs || qe) {
557 gpertea 144 if (qs>qe) Gswap(qs,qe);
558 gpertea 2 if (qs==0) qs=1;
559 gpertea 16 }
560 gpertea 2 int ovlen=0;
561 gpertea 16 if (exontype>0) { //check for overlaps between exon-type segments
562     int oi=exonOverlapIdx(segstart, segend, &ovlen);
563     if (oi>=0) { //overlap existing segment
564     if (ovlen==0) {
565     //adjacent segments will be merged
566     //e.g. CDS to (UTR|exon)
567     if ((exons[oi]->exontype>=exgffUTR && exontype==exgffCDS) ||
568     (exons[oi]->exontype==exgffCDS && exontype>=exgffUTR)) {
569     expandExon(oi, segstart, segend, exgffCDSUTR, sc, fr, qs, qe);
570     return oi;
571     }
572     //CDS adjacent to stop_codon: UCSC does (did?) this
573     if ((exons[oi]->exontype==exgffStop && exontype==exgffCDS) ||
574     (exons[oi]->exontype==exgffCDS && exontype==exgffStop)) {
575     expandExon(oi, segstart, segend, exgffCDS, sc, fr, qs, qe);
576     return oi;
577     }
578     }
579     //only allow this for CDS within exon, stop_codon within (CDS|UTR|exon),
580     // start_codon within (CDS|exon)
581     if (exons[oi]->exontype>exontype &&
582     exons[oi]->start<=segstart && exons[oi]->end>=segend &&
583     !(exons[oi]->exontype==exgffUTR && exontype==exgffCDS)) {
584     //larger segment given first, now the smaller included one is redundant
585     return oi; //only used to store attributes from current GffLine
586     }
587     if (exontype>exons[oi]->exontype &&
588     segstart<=exons[oi]->start && segend>=exons[oi]->end &&
589     !(exontype==exgffUTR && exons[oi]->exontype==exgffCDS)) {
590     //smaller segment given first, so we have to enlarge it
591     expandExon(oi, segstart, segend, exontype, sc, fr, qs, qe);
592     //this should also check for overlapping next exon (oi+1) ?
593     return oi;
594     }
595     //there is also the special case of "ribosomal slippage exception" (programmed frameshift)
596     //where two CDS segments may actually overlap for 1 or 2 bases, but there should be only one encompassing exon
597     //if (ovlen>2 || exons[oi]->exontype!=exgffCDS || exontype!=exgffCDS) {
598     // had to relax this because of some weird UCSC annotations with exons partially overlapping the CDS segments
599     /*
600     if (ovlen>2 && exons[oi]->exontype!=exgffUTR && exontype!=exgffUTR) {
601     if (gff_show_warnings)
602     GMessage("GFF Warning: discarding overlapping feature segment (%d-%d) (vs %d-%d (%s)) for GFF ID %s on %s\n",
603     segstart, segend, exons[oi]->start, exons[oi]->end, getSubfName(), gffID, getGSeqName());
604     hasErrors(true);
605     return -1; //segment NOT added
606     }
607     */
608 gpertea 2
609 gpertea 16 if ((ovlen>2 || ovlen==0) || exons[oi]->exontype!=exgffCDS || exontype!=exgffCDS) {
610     if (gff_show_warnings)
611     GMessage("GFF Warning: merging overlapping/adjacent feature segment (%d-%d) into (%d-%d) (%s) for GFF ID %s on %s\n",
612     segstart, segend, exons[oi]->start, exons[oi]->end, getSubfName(), gffID, getGSeqName());
613     expandExon(oi, segstart, segend, exontype, sc, fr, qs, qe);
614     return oi;
615     }
616     // else add the segment if the overlap is small and between two CDS segments
617     //TODO: we might want to add an attribute here with the slippage coordinate and size?
618     covlen-=ovlen;
619     }//overlap or adjacent to existing segment
620     } //check for overlap
621 gpertea 2 // --- no overlap, or accepted micro-overlap (ribosomal slippage)
622     // create & add the new segment
623 gpertea 51 /*
624     if (start>0 && exontype==exgffCDS && exons.Count()==0) {
625     //adding a CDS directly as the first subfeature of a declared parent
626     segstart=start;
627     segend=end;
628     }
629     */
630 gpertea 2 GffExon* enew=new GffExon(segstart, segend, sc, fr, qs, qe, exontype);
631     int eidx=exons.Add(enew);
632     if (eidx<0) {
633 gpertea 16 //this would actually be acceptable if the object is a "Gene" and "exons" are in fact isoforms
634     if (gff_show_warnings)
635     GMessage("GFF Warning: failed adding segment %d-%d for %s (discarded)!\n",
636 gpertea 2 segstart, segend, gffID);
637 gpertea 16 delete enew;
638     hasErrors(true);
639 gpertea 2 return -1;
640     }
641     covlen+=(int)(exons[eidx]->end-exons[eidx]->start)+1;
642 gpertea 55 //adjust parent feature coordinates to contain this exon
643     if (start==0 || start>exons.First()->start) {
644 gpertea 51 start=exons.First()->start;
645     }
646 gpertea 55 if (end<exons.Last()->end) end=exons.Last()->end;
647    
648 gpertea 2 if (uptr!=NULL) { //collect stats about the underlying genomic sequence
649     GSeqStat* gsd=(GSeqStat*)uptr;
650     if (start<gsd->mincoord) gsd->mincoord=start;
651     if (end>gsd->maxcoord) gsd->maxcoord=end;
652 gpertea 16 if (this->len()>gsd->maxfeat_len) {
653     gsd->maxfeat_len=this->len();
654     gsd->maxfeat=this;
655     }
656 gpertea 2 }
657     return eidx;
658     }
659    
660 gpertea 16 void GffObj::expandExon(int oi, uint segstart, uint segend, char exontype, double sc, char fr, int qs, int qe) {
661     //oi is the index of the *first* overlapping segment found that must be enlarged
662     covlen-=exons[oi]->len();
663     if (segstart<exons[oi]->start)
664     exons[oi]->start=segstart;
665     if (qs && qs<exons[oi]->qstart) exons[oi]->qstart=qs;
666     if (segend>exons[oi]->end)
667     exons[oi]->end=segend;
668     if (qe && qe>exons[oi]->qend) exons[oi]->qend=qe;
669     //warning: score cannot be properly adjusted! e.g. if it's a p-value it's just going to get worse
670     if (sc!=0) exons[oi]->score=sc;
671     covlen+=exons[oi]->len();
672     //if (exons[oi]->exontype< exontype) -- always true
673     exons[oi]->exontype = exontype;
674     if (exontype==exgffCDS) exons[oi]->phase=fr;
675     //we must check if any more exons are also overlapping this
676     int ni=oi+1; //next exon index after oi
677     while (ni<exons.Count() && segend>=exons[ni]->start) { // next segment overlaps new enlarged segment
678     //only allow this if next segment is fully included, and a subordinate
679     if (exons[ni]->exontype<exontype && exons[ni]->end<=segend) {
680     /* I guess we have to relax this due to stupid UCSC hg18 files having a start_codon sticking out
681     chr1 hg18_knownGene start_codon 69806911 69806913 0.000000 + .
682     chr1 hg18_knownGene CDS 69806911 69806912 0.000000 + 0
683     chr1 hg18_knownGene exon 69805456 69806912 0.000000 + .
684     */
685     if (exons[ni]->qstart<exons[oi]->qstart) exons[oi]->qstart=exons[ni]->qstart;
686     if (exons[ni]->qend>exons[oi]->qend) exons[oi]->qend=exons[ni]->qend;
687     exons.Delete(ni);
688     }
689     else {
690     if (gff_show_warnings) GMessage("GFF Warning: overlapping existing exon(%d-%d) while expanding to %d-%d for GFF ID %s\n",
691     exons[ni]->start, exons[ni]->end, segstart, segend, gffID);
692     //hasErrors(true);
693     break;
694     }
695     }
696     // -- make sure any other related boundaries are updated:
697     start=exons.First()->start;
698     end=exons.Last()->end;
699     if (uptr!=NULL) { //collect stats about the underlying genomic sequence
700     GSeqStat* gsd=(GSeqStat*)uptr;
701     if (start<gsd->mincoord) gsd->mincoord=start;
702     if (end>gsd->maxcoord) gsd->maxcoord=end;
703     if (this->len()>gsd->maxfeat_len) {
704     gsd->maxfeat_len=this->len();
705     gsd->maxfeat=this;
706     }
707     }
708     }
709    
710 gpertea 2 void GffObj::removeExon(int idx) {
711     /*
712     if (idx==0 && segs[0].start==gstart)
713     gstart=segs[1].start;
714     if (idx==segcount && segs[segcount].end==gend)
715     gend=segs[segcount-1].end;
716     */
717     if (idx<0 || idx>=exons.Count()) return;
718     int segstart=exons[idx]->start;
719     int segend=exons[idx]->end;
720     exons.Delete(idx);
721     covlen -= (int)(segend-segstart)+1;
722     start=exons.First()->start;
723     end=exons.Last()->end;
724     if (isCDS) { CDstart=start; CDend=end; }
725     }
726    
727 gpertea 16 void GffObj::removeExon(GffExon* p) {
728     for (int idx=0;idx<exons.Count();idx++) {
729     if (exons[idx]==p) {
730     int segstart=exons[idx]->start;
731     int segend=exons[idx]->end;
732     exons.Delete(idx);
733     covlen -= (int)(segend-segstart)+1;
734     start=exons.First()->start;
735     end=exons.Last()->end;
736     if (isCDS) { CDstart=start; CDend=end; }
737     return;
738     }
739     }
740     }
741    
742    
743    
744 gpertea 2 GffObj::GffObj(GffReader *gfrd, GffLine* gffline, bool keepAttr, bool noExonAttr):
745 gpertea 16 GSeg(0,0), exons(true,true,false), children(1,false) {
746     xstart=0;
747     xend=0;
748     xstatus=0;
749     partial=false;
750     isCDS=false;
751     uptr=NULL;
752     ulink=NULL;
753     parent=NULL;
754     udata=0;
755     flags=0;
756     CDstart=0;
757     CDend=0;
758     CDphase=0;
759     geneID=NULL;
760     gene_name=NULL;
761     attrs=NULL;
762     gffID=NULL;
763     track_id=-1;
764     gseq_id=-1;
765     ftype_id=-1;
766     exon_ftype_id=-1;
767     strand='.';
768     if (gfrd==NULL)
769 gpertea 2 GError("Cannot use this GffObj constructor with a NULL GffReader!\n");
770 gpertea 16 gffnames_ref(names);
771     if (gfrd->names==NULL) gfrd->names=names;
772     //qlen=0;qstart=0;qend=0;
773     gscore=0;
774     uscore=0;
775     covlen=0;
776     qcov=0;
777     start=gffline->fstart;
778     end=gffline->fend;
779     gseq_id=names->gseqs.addName(gffline->gseqname);
780     track_id=names->tracks.addName(gffline->track);
781     strand=gffline->strand;
782     qlen=gffline->qlen;
783     qstart=gffline->qstart;
784     qend=gffline->qend;
785     //setup flags from gffline
786     isCDS=gffline->is_cds; //for now
787     isGene(gffline->is_gene);
788     isTranscript(gffline->is_transcript || gffline->exontype!=0);
789 gpertea 153 //fromGff3(gffline->is_gff3);
790 gpertea 16
791     if (gffline->parents!=NULL) {
792     //GTF style -- create a GffObj directly by subfeature
793     //(also possible orphan GFF3 exon line, or an exon given before its parent (chado))
794     if (gffline->exontype!=0) { //recognized exon-like feature
795     ftype_id=gff_fid_transcript; //so this is some sort of transcript
796     exon_ftype_id=gff_fid_exon; //subfeatures MUST be exons
797     }
798     else {//unrecognized subfeatures
799     //make this GffObj of the same feature type
800     ftype_id=names->feats.addName(gffline->ftype);
801     }
802 gpertea 153 if (gffline->ID==NULL) { //typical GTF2 without "transcript" line
803 gpertea 16 gffID=Gstrdup(gffline->parents[0]);
804     this->createdByExon(true);
805     //this is likely the first exon/segment of the feature
806     addExon(gfrd, gffline, keepAttr, noExonAttr);
807 gpertea 2 }
808 gpertea 153 else { //a parented feature with an ID -- probably an orphan or premature GFF3 subfeature line
809 gpertea 16 if (gffline->is_gff3 && gffline->exontype!=0) {
810     //premature exon given before its parent transcript
811     //create the transcript entry here
812     gffID=Gstrdup(gffline->parents[0]);
813     this->createdByExon(true);
814     //this is the first exon/segment of the transcript
815     addExon(gfrd, gffline, keepAttr, noExonAttr);
816     }
817     else { //unrecognized non-exon feature ? use the ID instead
818     gffID=Gstrdup(gffline->ID);
819     if (keepAttr) this->parseAttrs(attrs, gffline->info);
820     }
821 gpertea 2 }
822 gpertea 16 } //subfeature given directly
823     else { //gffline->parents==NULL
824     //create a parent feature in its own right
825 gpertea 2 gscore=gffline->score;
826     if (gffline->ID==NULL || gffline->ID[0]==0)
827 gpertea 16 GError("Error: no ID found for GFF record start\n");
828 gpertea 153 this->hasGffID(true);
829 gpertea 16 gffID=Gstrdup(gffline->ID); //there must be an ID here
830     //if (gffline->is_transcript) ftype_id=gff_fid_mRNA;
831     //else
832     ftype_id=names->feats.addName(gffline->ftype);
833     if (gffline->is_transcript)
834     exon_ftype_id=gff_fid_exon;
835    
836     if (keepAttr) this->parseAttrs(attrs, gffline->info);
837     }//no parent
838    
839     if (gffline->gene_name!=NULL) {
840     gene_name=Gstrdup(gffline->gene_name);
841     }
842     if (gffline->gene_id!=NULL) {
843     geneID=Gstrdup(gffline->gene_id);
844     }
845    
846     GSeqStat* gsd=gfrd->gseqstats.AddIfNew(new GSeqStat(gseq_id,names->gseqs.lastNameUsed()),true);
847     uptr=gsd;
848     if (start<gsd->mincoord) gsd->mincoord=start;
849     if (end>gsd->maxcoord) gsd->maxcoord=end;
850     if (this->len()>gsd->maxfeat_len) {
851     gsd->maxfeat_len=this->len();
852     gsd->maxfeat=this;
853 gpertea 2 }
854     }
855    
856     GffLine* GffReader::nextGffLine() {
857     if (gffline!=NULL) return gffline; //caller should free gffline after processing
858     while (gffline==NULL) {
859     int llen=0;
860     buflen=GFF_LINELEN-1;
861     char* l=fgetline(linebuf, buflen, fh, &fpos, &llen);
862     if (l==NULL) {
863     return NULL; //end of file
864     }
865     int ns=0; //first nonspace position
866     while (l[ns]!=0 && isspace(l[ns])) ns++;
867     if (l[ns]=='#' || llen<10) continue;
868     gffline=new GffLine(this, l);
869     if (gffline->skip) {
870     delete gffline;
871     gffline=NULL;
872 gpertea 16 continue;
873 gpertea 2 }
874 gpertea 16 if (gffline->ID==NULL && gffline->parents==NULL) { //it must have an ID
875     //this might not be needed, already checked in the GffLine constructor
876     if (gff_warns)
877     GMessage("Warning: malformed GFF line, no parent or record Id (kipping\n");
878     delete gffline;
879     gffline=NULL;
880     //continue;
881     }
882 gpertea 2 }
883     return gffline;
884     }
885    
886 gpertea 151
887 gpertea 2 char* GffReader::gfoBuildId(const char* id, const char* ctg) {
888     //caller must free the returned pointer
889     char* buf=NULL;
890     int idlen=strlen(id);
891     GMALLOC(buf, idlen+strlen(ctg)+2);
892     strcpy(buf, id);
893     buf[idlen]='~';
894     strcpy(buf+idlen+1, ctg);
895     return buf;
896     }
897 gpertea 151 /*
898 gpertea 2 void GffReader::gfoRemove(const char* id, const char* ctg) {
899     char* buf=gfoBuildId(id,ctg);
900     phash.Remove(buf);
901     GFREE(buf);
902     }
903 gpertea 151 */
904 gpertea 16 //Warning: if gflst gets altered, idx becomes obsolete
905 gpertea 151 GfoHolder* GffReader::gfoAdd(GffObj* gfo, int idx) {
906     GVec<GfoHolder>* glst=new GVec<GfoHolder>(1);
907     GfoHolder gh(gfo,idx);
908     int i=glst->Add(gh);
909     phash.Add(gfo->gffID, glst);
910     return &(glst->Get(i));
911 gpertea 2 }
912 gpertea 16
913 gpertea 151 GfoHolder* GffReader::gfoAdd(GVec<GfoHolder>& glst, GffObj* gfo, int idx) {
914     GfoHolder gh(gfo,idx);
915     int i=glst.Add(gh);
916     return &(glst[i]);
917 gpertea 2 }
918    
919 gpertea 151 GfoHolder* GffReader::gfoFind(const char* id, const char* ctg, char strand, uint start, GVec<GfoHolder>** glst) {
920     GVec<GfoHolder>* gl=phash.Find(id);
921     GfoHolder* gh=NULL;
922     if (gl) {
923     for (int i=0;i<gl->Count();i++) {
924     GfoHolder& gfo = gl->Get(i);
925     if (ctg!=NULL && strcmp(ctg,gfo.gffobj->getGSeqName())!=0)
926     continue;
927     if (strand && strand != gfo.gffobj->strand)
928     continue;
929     if (start>0 && abs((int)start-(int)gfo.gffobj->start)>GFF_MAX_LOCUS)
930     continue;
931     //must be the same transcript, according to given comparison criteria
932     gh=&gfo;
933     break;
934     }
935     }
936     if (glst) *glst=gl;
937     return gh;
938     }
939    
940 gpertea 16 GfoHolder* GffReader::replaceGffRec(GffLine* gffline, bool keepAttr, bool noExonAttr, int replaceidx) {
941     GffObj* newgfo=new GffObj(this, gffline, keepAttr, noExonAttr);
942     GfoHolder* r=NULL;
943     if (replaceidx>=0) {
944     gflst.Put(replaceidx,newgfo);
945 gpertea 151 r=gfoAdd(newgfo, replaceidx);
946 gpertea 16 }
947     else {
948     int gfoidx=gflst.Add(newgfo);
949 gpertea 151 r=gfoAdd(newgfo, gfoidx);
950 gpertea 16 }
951 gpertea 153 /*
952 gpertea 16 if (gff_warns) {
953     int* pcount=tids.Find(newgfo->gffID);
954     if (pcount!=NULL) {
955 gpertea 151 if (gff_warns) GMessage("Warning: duplicate GFF ID: %s\n", newgfo->gffID);
956 gpertea 16 (*pcount)++;
957     }
958     else {
959     tids.Add(newgfo->gffID,new int(1));
960     }
961     }
962 gpertea 153 */
963 gpertea 16 return r;
964     }
965 gpertea 2
966 gpertea 16 GfoHolder* GffReader::updateParent(GfoHolder* newgfh, GffObj* parent) {
967     //assert(parent);
968     //assert(newgfo);
969     parent->children.Add(newgfh->gffobj);
970     if (newgfh->gffobj->parent==NULL) newgfh->gffobj->parent=parent;
971     newgfh->gffobj->setLevel(parent->getLevel()+1);
972     if (parent->isGene()) {
973     if (parent->gene_name!=NULL && newgfh->gffobj->gene_name==NULL)
974     newgfh->gffobj->gene_name=Gstrdup(parent->gene_name);
975     if (parent->geneID!=NULL && newgfh->gffobj->geneID==NULL)
976     newgfh->gffobj->geneID=Gstrdup(parent->geneID);
977     }
978    
979     return newgfh;
980 gpertea 2 }
981    
982 gpertea 16 GfoHolder* GffReader::newGffRec(GffLine* gffline, bool keepAttr, bool noExonAttr,
983 gpertea 151 GffObj* parent, GffExon* pexon, GVec<GfoHolder>* glst) {
984 gpertea 16 GffObj* newgfo=new GffObj(this, gffline, keepAttr, noExonAttr);
985     GfoHolder* r=NULL;
986     int gfoidx=gflst.Add(newgfo);
987 gpertea 151 r=(glst) ? gfoAdd(*glst, newgfo, gfoidx) :gfoAdd(newgfo, gfoidx);
988 gpertea 16 if (parent!=NULL) {
989     updateParent(r, parent);
990     if (pexon!=NULL) parent->removeExon(pexon);
991     }
992 gpertea 153 /*
993 gpertea 16 if (gff_warns) {
994     int* pcount=tids.Find(newgfo->gffID);
995     if (pcount!=NULL) {
996     if (gff_warns) GMessage("Warning: duplicate GFF ID: %s\n", newgfo->gffID);
997     (*pcount)++;
998     }
999     else {
1000     tids.Add(newgfo->gffID,new int(1));
1001     }
1002     }
1003 gpertea 153 */
1004 gpertea 16 return r;
1005     }
1006 gpertea 2
1007 gpertea 16 GfoHolder* GffReader::updateGffRec(GfoHolder* prevgfo, GffLine* gffline,
1008     bool keepAttr) {
1009     if (prevgfo==NULL) return NULL;
1010 gpertea 153 //prevgfo->gffobj->createdByExon(false);
1011 gpertea 16 prevgfo->gffobj->ftype_id=prevgfo->gffobj->names->feats.addName(gffline->ftype);
1012     prevgfo->gffobj->start=gffline->fstart;
1013     prevgfo->gffobj->end=gffline->fend;
1014     prevgfo->gffobj->isGene(gffline->is_gene);
1015     prevgfo->gffobj->isTranscript(gffline->is_transcript || gffline->exontype!=0);
1016 gpertea 153 prevgfo->gffobj->hasGffID(gffline->ID!=NULL);
1017 gpertea 16 if (keepAttr) {
1018     if (prevgfo->gffobj->attrs!=NULL) prevgfo->gffobj->attrs->Clear();
1019     prevgfo->gffobj->parseAttrs(prevgfo->gffobj->attrs, gffline->info);
1020     }
1021     return prevgfo;
1022     }
1023    
1024    
1025     bool GffReader::addExonFeature(GfoHolder* prevgfo, GffLine* gffline, GHash<CNonExon>& pex, bool noExonAttr) {
1026     bool r=true;
1027     if (gffline->strand!=prevgfo->gffobj->strand) {
1028 gpertea 115 //TODO: add support for trans-splicing and even inter-chromosomal fusions
1029     if (prevgfo->gffobj->strand=='.') {
1030     prevgfo->gffobj->strand=gffline->strand;
1031     }
1032     else {
1033     GMessage("GFF Error at %s (%c): exon %d-%d (%c) found on different strand; discarded.\n",
1034     prevgfo->gffobj->gffID, prevgfo->gffobj->strand,
1035     gffline->fstart, gffline->fend, gffline->strand, prevgfo->gffobj->getGSeqName());
1036     //r=false;
1037     return true; //FIXME: split trans-spliced mRNAs by strand
1038     }
1039     }
1040 gpertea 16 int gdist=(gffline->fstart>prevgfo->gffobj->end) ? gffline->fstart-prevgfo->gffobj->end :
1041     ((gffline->fend<prevgfo->gffobj->start)? prevgfo->gffobj->start-gffline->fend :
1042     0 );
1043     if (gdist>(int)GFF_MAX_LOCUS) { //too far apart, most likely this is a duplicate ID
1044     GMessage("Error: duplicate GFF ID '%s' (or exons too far apart)!\n",prevgfo->gffobj->gffID);
1045     //validation_errors = true;
1046     r=false;
1047     if (!gff_warns) exit(1);
1048     }
1049     int eidx=prevgfo->gffobj->addExon(this, gffline, !noExonAttr, noExonAttr);
1050     if (eidx>=0 && gffline->ID!=NULL && gffline->exontype==0)
1051     subfPoolAdd(pex, prevgfo);
1052     return r;
1053     }
1054    
1055     CNonExon* GffReader::subfPoolCheck(GffLine* gffline, GHash<CNonExon>& pex, char*& subp_name) {
1056     CNonExon* subp=NULL;
1057     subp_name=NULL;
1058     for (int i=0;i<gffline->num_parents;i++) {
1059     if (transcriptsOnly && discarded_ids.Find(gffline->parents[i])!=NULL)
1060     continue;
1061     subp_name=gfoBuildId(gffline->parents[i], gffline->gseqname); //e.g. mRNA name
1062     subp=pex.Find(subp_name);
1063     if (subp!=NULL)
1064     return subp;
1065     GFREE(subp_name);
1066     }
1067     return NULL;
1068     }
1069    
1070     void GffReader::subfPoolAdd(GHash<CNonExon>& pex, GfoHolder* newgfo) {
1071     //this might become a parent feature later
1072     if (newgfo->gffobj->exons.Count()>0) {
1073     char* xbuf=gfoBuildId(gffline->ID, gffline->gseqname);
1074     pex.Add(xbuf, new CNonExon(newgfo->idx, newgfo->gffobj,
1075     newgfo->gffobj->exons[0], gffline));
1076     GFREE(xbuf);
1077     }
1078     }
1079    
1080     GfoHolder* GffReader::promoteFeature(CNonExon* subp, char*& subp_name, GHash<CNonExon>& pex,
1081     bool keepAttr, bool noExonAttr) {
1082     GffObj* prevp=subp->parent; //grandparent of gffline (e.g. gene)
1083     if (prevp!=gflst[subp->idx])
1084     GError("Error promoting subfeature %s, gflst index mismatch?!\n", subp->gffline->ID);
1085     subp->gffline->discardParent();
1086     GfoHolder* gfoh=newGffRec(subp->gffline, keepAttr, noExonAttr, prevp, subp->exon);
1087     pex.Remove(subp_name); //no longer a potential parent, moved it to phash already
1088     prevp->promotedChildren(true);
1089     return gfoh; //returns the holder of newly promoted feature
1090     }
1091    
1092     //have to parse the whole file because exons can be scattered all over
1093 gpertea 153 //trans-splicing and fusions are only accepted in proper GFF3 format, with a single parent feature ID entry
1094 gpertea 2 void GffReader::readAll(bool keepAttr, bool mergeCloseExons, bool noExonAttr) {
1095 gpertea 16 bool validation_errors = false;
1096     //loc_debug=false;
1097     GHash<CNonExon> pex; //keep track of any "exon"-like features that have an ID
1098     //and thus could become promoted to parent features
1099 gpertea 2 while (nextGffLine()!=NULL) {
1100 gpertea 16 //seen this gff ID before?
1101     GfoHolder* prevseen=NULL;
1102 gpertea 152 if (gffline->ID && gffline->exontype==0) //GFF3 parent-like feature (mRNA, gene, etc.)
1103 gpertea 153 //look for same ID on the same chromosome
1104 gpertea 16 prevseen=gfoFind(gffline->ID, gffline->gseqname);
1105     if (prevseen!=NULL) {
1106 gpertea 153 //found same ID/chromosome combo
1107     if (prevseen->gffobj->createdByExon() &&
1108     prevseen->gffobj->start>=gffline->fstart && prevseen->gffobj->end<=gffline->fend) {
1109     //an exon of this ID was given before
1110     //this line has the main attributes for this ID
1111 gpertea 16 updateGffRec(prevseen, gffline, keepAttr);
1112     }
1113     else {
1114     GMessage("Error: duplicate GFF ID '%s' encountered!\n",gffline->ID);
1115     validation_errors = true;
1116     if (gff_warns) {
1117     delete gffline; gffline=NULL; continue;
1118     }
1119     else exit(1);
1120     }
1121 gpertea 2 }
1122 gpertea 16 if (gffline->parents==NULL) {//start GFF3-like record with no parent (mRNA, gene)
1123     if (!prevseen) newGffRec(gffline, keepAttr, noExonAttr);
1124 gpertea 2 }
1125 gpertea 151 else { //--- it's a parented feature (exon/CDS, but might still be a mRNA)
1126 gpertea 16 bool found_parent=false;
1127     GfoHolder* newgfo=prevseen;
1128 gpertea 151 GVec<GfoHolder>* newgflst=NULL;
1129 gpertea 16 for (int i=0;i<gffline->num_parents;i++) {
1130     if (transcriptsOnly && discarded_ids.Find(gffline->parents[i])!=NULL)
1131     continue; //skipping discarded parent feature
1132 gpertea 151 GfoHolder* parentgfo=gfoFind(gffline->parents[i], gffline->gseqname, gffline->strand, gffline->fstart, &newgflst);
1133 gpertea 16 if (parentgfo!=NULL) { //parent GffObj parsed earlier
1134     found_parent=true;
1135     if (parentgfo->gffobj->isGene() && gffline->is_transcript
1136     && gffline->exontype==0) {
1137     //not an exon, but a transcript parented by a gene
1138     if (newgfo) {
1139     updateParent(newgfo, parentgfo->gffobj);
1140     }
1141     else {
1142     newgfo=newGffRec(gffline, keepAttr, noExonAttr, parentgfo->gffobj);
1143     }
1144     }
1145     else { //potential exon subfeature
1146     if (!addExonFeature(parentgfo, gffline, pex, noExonAttr))
1147     validation_errors=true;
1148     }
1149 gpertea 2 }
1150 gpertea 16 } //for each parsed parent Id
1151     if (!found_parent) { //new GTF-like record starting here with a subfeature directly
1152     //or it could be some chado GFF3 barf with exons declared BEFORE their parent :(
1153     //check if this feature isn't parented by a previously stored "exon" subfeature
1154     char* subp_name=NULL;
1155     CNonExon* subp=subfPoolCheck(gffline, pex, subp_name);
1156     if (subp!=NULL) { //found a subfeature that is the parent of this gffline
1157     //promote that subfeature to a full GffObj
1158     GfoHolder* gfoh=promoteFeature(subp, subp_name, pex, keepAttr, noExonAttr);
1159     //add current gffline as an exon of the newly promoted subfeature
1160     if (!addExonFeature(gfoh, gffline, pex, noExonAttr))
1161     validation_errors=true;
1162     }
1163     else { //no parent seen before, create one directly with this exon
1164     //loc_debug=true;
1165 gpertea 151 GfoHolder* newgfo=prevseen ? prevseen : newGffRec(gffline, keepAttr, noExonAttr, NULL, NULL, newgflst);
1166 gpertea 16 if (gffline->ID!=NULL && gffline->exontype==0)
1167     subfPoolAdd(pex, newgfo);
1168     //even those with errors will be added here!
1169     }
1170     GFREE(subp_name);
1171     } //no previous parent found
1172     } //parented feature
1173     //--
1174     delete gffline;
1175     gffline=NULL;
1176     }//while gff lines
1177     gflst.finalize(this, mergeCloseExons, keepAttr, noExonAttr); //force sorting by locus if so constructed
1178 gpertea 2 // all gff records are now loaded in GList gflst
1179     // so we can free the hash
1180     phash.Clear();
1181 gpertea 153 //tids.Clear();
1182 gpertea 16 if (validation_errors) {
1183     exit(1);
1184     }
1185 gpertea 2 }
1186    
1187 gpertea 16 GffObj* GffObj::finalize(GffReader* gfr, bool mergeCloseExons, bool keepAttrs, bool noExonAttr) {
1188     //merge
1189     //always merge adjacent or overlapping segments
1190     //but if mergeCloseExons then merge even when distance is up to 5 bases
1191 gpertea 2 udata=0;
1192     uptr=NULL;
1193 gpertea 16 if (gfr->transcriptsOnly && !(isTranscript() || (isGene() && children.Count()==0))) {
1194     isDiscarded(true);
1195     }
1196     if (ftype_id==gff_fid_transcript && CDstart>0) {
1197     ftype_id=gff_fid_mRNA;
1198     //exon_ftype_id=gff_fid_exon;
1199     }
1200     //if (ftype_id==gff_fid_mRNA || exon_ftype_id==gff_fid_exon || mergeCloseExons) {
1201     if (isTranscript() || exon_ftype_id==gff_fid_exon || mergeCloseExons) {
1202 gpertea 2 int mindist=mergeCloseExons ? 5:1;
1203     for (int i=0;i<exons.Count()-1;i++) {
1204     int ni=i+1;
1205     uint mend=exons[i]->end;
1206     while (ni<exons.Count()) {
1207     int dist=(int)(exons[ni]->start-mend);
1208 gpertea 16 if (dist>mindist) break; //no merging with next segment
1209     if (gfr!=NULL && gfr->gff_warns && dist!=0 && (exons[ni]->exontype!=exgffUTR && exons[i]->exontype!=exgffUTR)) {
1210     GMessage("GFF warning: merging adjacent/overlapping segments of %s on %s (%d-%d, %d-%d)\n",
1211     gffID, getGSeqName(), exons[i]->start, exons[i]->end,exons[ni]->start, exons[ni]->end);
1212     }
1213 gpertea 2 mend=exons[ni]->end;
1214 gpertea 16 covlen-=exons[i]->len();
1215 gpertea 2 exons[i]->end=mend;
1216 gpertea 16 covlen+=exons[i]->len();
1217     covlen-=exons[ni]->len();
1218 gpertea 2 if (exons[ni]->attrs!=NULL && (exons[i]->attrs==NULL ||
1219     exons[i]->attrs->Count()<exons[ni]->attrs->Count())) {
1220     //use the other exon attributes, if more
1221     delete(exons[i]->attrs);
1222     exons[i]->attrs=exons[ni]->attrs;
1223     exons[ni]->attrs=NULL;
1224     }
1225     exons.Delete(ni);
1226     } //check for merge with next exon
1227     } //for each exon
1228     }
1229 gpertea 16 //attribute reduction for GTF records
1230 gpertea 153 if (keepAttrs && !noExonAttr && !hasGffID()
1231 gpertea 16 && exons.Count()>0 && exons[0]->attrs!=NULL) {
1232     bool attrs_discarded=false;
1233     for (int a=0;a<exons[0]->attrs->Count();a++) {
1234     int attr_name_id=exons[0]->attrs->Get(a)->attr_id;
1235     char* attr_name=names->attrs.getName(attr_name_id);
1236     char* attr_val =exons[0]->attrs->Get(a)->attr_val;
1237     bool sameExonAttr=true;
1238     for (int i=1;i<exons.Count();i++) {
1239     char* ov=exons[i]->getAttr(attr_name_id);
1240     if (ov==NULL || (strcmp(ov,attr_val)!=0)) {
1241     sameExonAttr=false;
1242     break;
1243     }
1244     }
1245     if (sameExonAttr) {
1246     //delete this attribute from exons level
1247     attrs_discarded=true;
1248     this->addAttr(attr_name, attr_val);
1249     for (int i=1;i<exons.Count();i++) {
1250     removeExonAttr(*(exons[i]), attr_name_id);
1251     }
1252     exons[0]->attrs->freeItem(a);
1253     }
1254     }
1255     if (attrs_discarded) exons[0]->attrs->Pack();
1256     }
1257 gpertea 2 return this;
1258     }
1259    
1260 gpertea 16 void GffObj::parseAttrs(GffAttrs*& atrlist, char* info, bool isExon) {
1261 gpertea 2 if (names==NULL)
1262     GError(ERR_NULL_GFNAMES, "parseAttrs()");
1263     if (atrlist==NULL)
1264     atrlist=new GffAttrs();
1265     char* endinfo=info+strlen(info);
1266     char* start=info;
1267     char* pch=start;
1268     while (start<endinfo) {
1269     //skip spaces
1270     while (*start==' ' && start<endinfo) start++;
1271     pch=strchr(start, ';');
1272     if (pch==NULL) pch=endinfo;
1273     else {
1274     *pch='\0';
1275     pch++;
1276     }
1277     char* ech=strchr(start,'=');
1278     if (ech!=NULL) { // attr=value format found
1279     *ech='\0';
1280 gpertea 16 //if (noExonAttr && (strcmp(start, "exon_number")==0 || strcmp(start, "exon")==0)) { start=pch; continue; }
1281     if (strcmp(start, "exon_number")==0 || strcmp(start, "exon")==0 ||
1282     strcmp(start, "exon_id")==0)
1283     { start=pch; continue; }
1284 gpertea 2 ech++;
1285     while (*ech==' ' && ech<endinfo) ech++;//skip extra spaces after the '='
1286 gpertea 16 //atrlist->Add(new GffAttr(names->attrs.addName(start),ech));
1287     //make sure we don't add the same attribute more than once
1288     if (isExon && (strcmp(start, "protein_id")==0)) {
1289     //Ensembl special case
1290     this->addAttr(start, ech);
1291     start=pch;
1292     continue;
1293     }
1294     atrlist->add_or_update(names, start, ech);
1295 gpertea 2 }
1296     /*
1297     else { //not an attr=value format
1298     atrlist->Add(new GffAttr(names->attrs.addName(start),"1"));
1299     }
1300     */
1301     start=pch;
1302     }
1303     if (atrlist->Count()==0) { delete atrlist; atrlist=NULL; }
1304     }
1305    
1306 gpertea 16 void GffObj::addAttr(const char* attrname, const char* attrvalue) {
1307 gpertea 2 if (this->attrs==NULL)
1308     this->attrs=new GffAttrs();
1309 gpertea 16 //this->attrs->Add(new GffAttr(names->attrs.addName(attrname),attrvalue));
1310     this->attrs->add_or_update(names, attrname, attrvalue);
1311 gpertea 2 }
1312    
1313 gpertea 16
1314     void GffObj::setFeatureName(const char* feature) {
1315     //change the feature name/type for a transcript
1316     int fid=names->feats.addName(feature);
1317     if (monoFeature() && exons.Count()>0)
1318     this->exon_ftype_id=fid;
1319     this->ftype_id=fid;
1320     }
1321    
1322     void GffObj::setRefName(const char* newname) {
1323     //change the feature name/type for a transcript
1324     int rid=names->gseqs.addName(newname);
1325     this->gseq_id=rid;
1326     }
1327    
1328    
1329    
1330     int GffObj::removeAttr(const char* attrname, const char* attrval) {
1331     if (this->attrs==NULL || attrname==NULL || attrname[0]==0) return 0;
1332     int aid=this->names->attrs.getId(attrname);
1333     if (aid<0) return 0;
1334     int delcount=0; //could be more than one ?
1335     for (int i=0;i<this->attrs->Count();i++) {
1336     if (aid==this->attrs->Get(i)->attr_id) {
1337     if (attrval==NULL ||
1338     strcmp(attrval, this->attrs->Get(i)->attr_val)==0) {
1339     delcount++;
1340     this->attrs->freeItem(i);
1341     }
1342     }
1343     }
1344     if (delcount>0) this->attrs->Pack();
1345     return delcount;
1346     }
1347    
1348     int GffObj::removeAttr(int aid, const char* attrval) {
1349     if (this->attrs==NULL || aid<0) return 0;
1350     int delcount=0; //could be more than one ?
1351     for (int i=0;i<this->attrs->Count();i++) {
1352     if (aid==this->attrs->Get(i)->attr_id) {
1353     if (attrval==NULL ||
1354     strcmp(attrval, this->attrs->Get(i)->attr_val)==0) {
1355     delcount++;
1356     this->attrs->freeItem(i);
1357     }
1358     }
1359     }
1360     if (delcount>0) this->attrs->Pack();
1361     return delcount;
1362     }
1363    
1364    
1365     int GffObj::removeExonAttr(GffExon& exon, const char* attrname, const char* attrval) {
1366     if (exon.attrs==NULL || attrname==NULL || attrname[0]==0) return 0;
1367     int aid=this->names->attrs.getId(attrname);
1368     if (aid<0) return 0;
1369     int delcount=0; //could be more than one
1370     for (int i=0;i<exon.attrs->Count();i++) {
1371     if (aid==exon.attrs->Get(i)->attr_id) {
1372     if (attrval==NULL ||
1373     strcmp(attrval, exon.attrs->Get(i)->attr_val)==0) {
1374     delcount++;
1375     exon.attrs->freeItem(i);
1376     }
1377     }
1378     }
1379     if (delcount>0) exon.attrs->Pack();
1380     return delcount;
1381     }
1382    
1383     int GffObj::removeExonAttr(GffExon& exon, int aid, const char* attrval) {
1384     if (exon.attrs==NULL || aid<0) return 0;
1385     int delcount=0; //could be more than one
1386     for (int i=0;i<exon.attrs->Count();i++) {
1387     if (aid==exon.attrs->Get(i)->attr_id) {
1388     if (attrval==NULL ||
1389     strcmp(attrval, exon.attrs->Get(i)->attr_val)==0) {
1390     delcount++;
1391     exon.attrs->freeItem(i);
1392     }
1393     }
1394     }
1395     if (delcount>0) exon.attrs->Pack();
1396     return delcount;
1397     }
1398    
1399    
1400 gpertea 2 void GffObj::getCDS_ends(uint& cds_start, uint& cds_end) {
1401     cds_start=0;
1402     cds_end=0;
1403     if (CDstart==0 || CDend==0) return; //no CDS info
1404     int cdsadj=0;
1405     if (CDphase=='1' || CDphase=='2') {
1406     cdsadj=CDphase-'0';
1407     }
1408     cds_start=CDstart;
1409     cds_end=CDend;
1410     if (strand=='-') cds_end-=cdsadj;
1411     else cds_start+=cdsadj;
1412     }
1413    
1414     void GffObj::mRNA_CDS_coords(uint& cds_mstart, uint& cds_mend) {
1415     //sets cds_start and cds_end to the CDS start,end coordinates on the spliced mRNA transcript
1416     cds_mstart=0;
1417     cds_mend=0;
1418     if (CDstart==0 || CDend==0) return; //no CDS info
1419     //restore normal coordinates, just in case
1420     unxcoord();
1421     int cdsadj=0;
1422     if (CDphase=='1' || CDphase=='2') {
1423     cdsadj=CDphase-'0';
1424     }
1425     /*
1426     uint seqstart=CDstart;
1427     uint seqend=CDend;
1428     */
1429     uint seqstart=exons.First()->start;
1430     uint seqend=exons.Last()->end;
1431     int s=0; //resulting nucleotide counter
1432     if (strand=='-') {
1433     for (int x=exons.Count()-1;x>=0;x--) {
1434     uint sgstart=exons[x]->start;
1435     uint sgend=exons[x]->end;
1436     if (seqend<sgstart || seqstart>sgend) continue;
1437     if (seqstart>=sgstart && seqstart<=sgend)
1438     sgstart=seqstart; //seqstart within this segment
1439     if (seqend>=sgstart && seqend<=sgend)
1440     sgend=seqend; //seqend within this segment
1441     s+=(int)(sgend-sgstart)+1;
1442     if (CDstart>=sgstart && CDstart<=sgend) {
1443     //CDstart in this segment
1444     //and we are getting the whole transcript
1445     cds_mend=s-(int)(CDstart-sgstart);
1446     }
1447     if (CDend>=sgstart && CDend<=sgend) {
1448     //CDstart in this segment
1449     //and we are getting the whole transcript
1450     cds_mstart=s-(int)(CDend-cdsadj-sgstart);
1451     }
1452     } //for each exon
1453     } // - strand
1454     else { // + strand
1455     for (int x=0;x<exons.Count();x++) {
1456     uint sgstart=exons[x]->start;
1457     uint sgend=exons[x]->end;
1458     if (seqend<sgstart || seqstart>sgend) continue;
1459     if (seqstart>=sgstart && seqstart<=sgend)
1460     sgstart=seqstart; //seqstart within this segment
1461     if (seqend>=sgstart && seqend<=sgend)
1462     sgend=seqend; //seqend within this segment
1463     s+=(int)(sgend-sgstart)+1;
1464     /* for (uint i=sgstart;i<=sgend;i++) {
1465     spliced[s]=gsubseq[i-gstart];
1466     s++;
1467     }//for each nt
1468     */
1469     if (CDstart>=sgstart && CDstart<=sgend) {
1470     //CDstart in this segment
1471     cds_mstart=s-(int)(sgend-CDstart-cdsadj);
1472     }
1473     if (CDend>=sgstart && CDend<=sgend) {
1474     //CDend in this segment
1475     cds_mend=s-(int)(sgend-CDend);
1476     }
1477     } //for each exon
1478     } // + strand
1479     //spliced[s]=0;
1480     //if (rlen!=NULL) *rlen=s;
1481     //return spliced;
1482     }
1483    
1484 gpertea 16 char* GffObj::getUnspliced(GFaSeqGet* faseq, int* rlen, GList<GSeg>* seglst)
1485     {
1486     if (faseq==NULL) { GMessage("Warning: getUnspliced(NULL,.. ) called!\n");
1487     return NULL;
1488     }
1489     //restore normal coordinates:
1490     unxcoord();
1491     if (exons.Count()==0) return NULL;
1492     int fspan=end-start+1;
1493     const char* gsubseq=faseq->subseq(start, fspan);
1494     if (gsubseq==NULL) {
1495     GError("Error getting subseq for %s (%d..%d)!\n", gffID, start, end);
1496     }
1497     char* unspliced=NULL;
1498    
1499     int seqstart=exons.First()->start;
1500     int seqend=exons.Last()->end;
1501    
1502     int unsplicedlen = 0;
1503    
1504     unsplicedlen += seqend - seqstart + 1;
1505    
1506     GMALLOC(unspliced, unsplicedlen+1); //allocate more here
1507     //uint seqstart, seqend;
1508    
1509     int s = 0; //resulting nucleotide counter
1510     if (strand=='-')
1511     {
1512     if (seglst!=NULL)
1513     seglst->Add(new GSeg(s+1,s+1+seqend-seqstart));
1514     for (int i=seqend;i>=seqstart;i--)
1515     {
1516     unspliced[s] = ntComplement(gsubseq[i-start]);
1517     s++;
1518     }//for each nt
1519     } // - strand
1520     else
1521     { // + strand
1522     if (seglst!=NULL)
1523     seglst->Add(new GSeg(s+1,s+1+seqend-seqstart));
1524     for (int i=seqstart;i<=seqend;i++)
1525     {
1526     unspliced[s]=gsubseq[i-start];
1527     s++;
1528     }//for each nt
1529     } // + strand
1530     //assert(s <= unsplicedlen);
1531     unspliced[s]=0;
1532     if (rlen!=NULL) *rlen=s;
1533     return unspliced;
1534     }
1535    
1536 gpertea 2 char* GffObj::getSpliced(GFaSeqGet* faseq, bool CDSonly, int* rlen, uint* cds_start, uint* cds_end,
1537     GList<GSeg>* seglst) {
1538     if (CDSonly && CDstart==0) return NULL;
1539     if (faseq==NULL) { GMessage("Warning: getSpliced(NULL,.. ) called!\n");
1540     return NULL;
1541     }
1542     //restore normal coordinates:
1543     unxcoord();
1544     if (exons.Count()==0) return NULL;
1545     int fspan=end-start+1;
1546     const char* gsubseq=faseq->subseq(start, fspan);
1547     if (gsubseq==NULL) {
1548     GError("Error getting subseq for %s (%d..%d)!\n", gffID, start, end);
1549     }
1550 gpertea 16 if (fspan<(int)(end-start+1)) { //special case: stop coordinate was extended past the gseq length, must adjust
1551     int endadj=end-start+1-fspan;
1552     uint prevend=end;
1553     end-=endadj;
1554     if (CDend>end) CDend=end;
1555     if (exons.Last()->end>end) {
1556     exons.Last()->end=end; //this could get us into trouble if exon start is also > end
1557     if (exons.Last()->start>exons.Last()->end) {
1558     GError("GffObj::getSpliced() error: improper genomic coordinate %d on %s for %s\n",
1559     prevend,getGSeqName(), getID());
1560     }
1561     covlen-=endadj;
1562     }
1563     }
1564 gpertea 2 char* spliced=NULL;
1565     GMALLOC(spliced, covlen+1); //allocate more here
1566     uint seqstart, seqend;
1567     int cdsadj=0;
1568     if (CDphase=='1' || CDphase=='2') {
1569     cdsadj=CDphase-'0';
1570     }
1571     if (CDSonly) {
1572     seqstart=CDstart;
1573     seqend=CDend;
1574     if (strand=='-') seqend-=cdsadj;
1575     else seqstart+=cdsadj;
1576     }
1577     else {
1578     seqstart=exons.First()->start;
1579     seqend=exons.Last()->end;
1580     }
1581     int s=0; //resulting nucleotide counter
1582     if (strand=='-') {
1583     for (int x=exons.Count()-1;x>=0;x--) {
1584     uint sgstart=exons[x]->start;
1585     uint sgend=exons[x]->end;
1586     if (seqend<sgstart || seqstart>sgend) continue;
1587     if (seqstart>=sgstart && seqstart<=sgend)
1588     sgstart=seqstart; //seqstart within this segment
1589     if (seqend>=sgstart && seqend<=sgend)
1590     sgend=seqend; //seqend within this segment
1591     if (seglst!=NULL)
1592     seglst->Add(new GSeg(s+1,s+1+sgend-sgstart));
1593     for (uint i=sgend;i>=sgstart;i--) {
1594     spliced[s] = ntComplement(gsubseq[i-start]);
1595     s++;
1596     }//for each nt
1597    
1598     if (!CDSonly && cds_start!=NULL && CDstart>0) {
1599     if (CDstart>=sgstart && CDstart<=sgend) {
1600     //CDstart in this segment
1601     //and we are getting the whole transcript
1602     *cds_end=s-(CDstart-sgstart);
1603     }
1604     if (CDend>=sgstart && CDend<=sgend) {
1605     //CDstart in this segment
1606     //and we are getting the whole transcript
1607     *cds_start=s-(CDend-cdsadj-sgstart);
1608     }
1609     }//update local CDS coordinates
1610     } //for each exon
1611     } // - strand
1612     else { // + strand
1613     for (int x=0;x<exons.Count();x++) {
1614     uint sgstart=exons[x]->start;
1615     uint sgend=exons[x]->end;
1616     if (seqend<sgstart || seqstart>sgend) continue;
1617     if (seqstart>=sgstart && seqstart<=sgend)
1618     sgstart=seqstart; //seqstart within this segment
1619     if (seqend>=sgstart && seqend<=sgend)
1620     sgend=seqend; //seqend within this segment
1621     if (seglst!=NULL)
1622     seglst->Add(new GSeg(s+1,s+1+sgend-sgstart));
1623     for (uint i=sgstart;i<=sgend;i++) {
1624     spliced[s]=gsubseq[i-start];
1625     s++;
1626     }//for each nt
1627     if (!CDSonly && cds_start!=NULL && CDstart>0) {
1628     if (CDstart>=sgstart && CDstart<=sgend) {
1629     //CDstart in this segment
1630     //and we are getting the whole transcript
1631     *cds_start=s-(sgend-CDstart-cdsadj);
1632     }
1633     if (CDend>=sgstart && CDend<=sgend) {
1634     //CDstart in this segment
1635     //and we are getting the whole transcript
1636     *cds_end=s-(sgend-CDend);
1637     }
1638     }//update local CDS coordinates
1639     } //for each exon
1640     } // + strand
1641     spliced[s]=0;
1642     if (rlen!=NULL) *rlen=s;
1643     return spliced;
1644     }
1645    
1646     char* GffObj::getSplicedTr(GFaSeqGet* faseq, bool CDSonly, int* rlen) {
1647     if (CDSonly && CDstart==0) return NULL;
1648     //restore normal coordinates:
1649     unxcoord();
1650     if (exons.Count()==0) return NULL;
1651     int fspan=end-start+1;
1652     const char* gsubseq=faseq->subseq(start, fspan);
1653     if (gsubseq==NULL) {
1654     GError("Error getting subseq for %s (%d..%d)!\n", gffID, start, end);
1655     }
1656    
1657     char* translation=NULL;
1658     GMALLOC(translation, (int)(covlen/3)+1);
1659     uint seqstart, seqend;
1660     int cdsadj=0;
1661     if (CDphase=='1' || CDphase=='2') {
1662     cdsadj=CDphase-'0';
1663     }
1664     if (CDSonly) {
1665     seqstart=CDstart;
1666     seqend=CDend;
1667     if (strand=='-') seqend-=cdsadj;
1668     else seqstart+=cdsadj;
1669     }
1670     else {
1671     seqstart=exons.First()->start;
1672     seqend=exons.Last()->end;
1673     }
1674     Codon codon;
1675     int nt=0; //codon nucleotide counter (0..2)
1676     int aa=0; //aminoacid count
1677     if (strand=='-') {
1678     for (int x=exons.Count()-1;x>=0;x--) {
1679     uint sgstart=exons[x]->start;
1680     uint sgend=exons[x]->end;
1681     if (seqend<sgstart || seqstart>sgend) continue;
1682     if (seqstart>=sgstart && seqstart<=sgend)
1683     sgstart=seqstart; //seqstart within this segment
1684     if (seqend>=sgstart && seqend<=sgend) {
1685     sgend=seqend; //seqend within this segment
1686     }
1687     for (uint i=sgend;i>=sgstart;i--) {
1688     codon.nuc[nt]=ntComplement(gsubseq[i-start]);
1689     nt++;
1690     if (nt==3) {
1691     nt=0;
1692     translation[aa]=codon.translate();
1693     aa++;
1694     }
1695     }//for each nt
1696     } //for each exon
1697     } // - strand
1698     else { // + strand
1699     for (int x=0;x<exons.Count();x++) {
1700     uint sgstart=exons[x]->start;
1701     uint sgend=exons[x]->end;
1702     if (seqend<sgstart || seqstart>sgend) continue;
1703     if (seqstart>=sgstart && seqstart<=sgend)
1704     sgstart=seqstart; //seqstart within this segment
1705     if (seqend>=sgstart && seqend<=sgend)
1706     sgend=seqend; //seqend within this segment
1707     for (uint i=sgstart;i<=sgend;i++) {
1708     codon.nuc[nt]=gsubseq[i-start];
1709     nt++;
1710     if (nt==3) {
1711     nt=0;
1712     translation[aa]=codon.translate();
1713     aa++;
1714     }
1715     }//for each nt
1716     } //for each exon
1717     } // + strand
1718     translation[aa]=0;
1719     if (rlen!=NULL) *rlen=aa;
1720     return translation;
1721     }
1722    
1723     void GffObj::printSummary(FILE* fout) {
1724     if (fout==NULL) fout=stdout;
1725     fprintf(fout, "%s\t%c\t%d\t%d\t%4.2f\t%4.1f\n", gffID,
1726     strand, start, end, gscore, (float)qcov/10.0);
1727     }
1728    
1729 gpertea 16 void GffObj::printGxfLine(FILE* fout, const char* tlabel, const char* gseqname, bool iscds,
1730 gpertea 2 uint segstart, uint segend, int exidx, char phase, bool gff3) {
1731     static char scorestr[14];
1732     strcpy(scorestr,".");
1733     GffAttrs* xattrs=NULL;
1734     if (exidx>=0) {
1735     if (exons[exidx]->score) sprintf(scorestr,"%.2f", exons[exidx]->score);
1736     xattrs=exons[exidx]->attrs;
1737     }
1738     if (phase==0 || !iscds) phase='.';
1739     const char* ftype=iscds ? "CDS" : getSubfName();
1740     if (gff3) {
1741     fprintf(fout,
1742     "%s\t%s\t%s\t%d\t%d\t%s\t%c\t%c\tParent=%s",
1743     gseqname, tlabel, ftype, segstart, segend, scorestr, strand,
1744     phase, gffID);
1745     if (xattrs!=NULL) {
1746     for (int i=0;i<xattrs->Count();i++)
1747     fprintf(fout, ";%s=%s",names->attrs.getName(xattrs->Get(i)->attr_id),
1748     xattrs->Get(i)->attr_val);
1749     }
1750     fprintf(fout, "\n");
1751     } //GFF
1752 gpertea 16 else {//for GTF -- we print only transcripts
1753     //if (isValidTranscript())
1754     fprintf(fout, "%s\t%s\t%s\t%d\t%d\t%s\t%c\t%c\ttranscript_id \"%s\";",
1755     gseqname, tlabel, ftype, segstart, segend, scorestr, strand, phase, gffID);
1756     //char* geneid=(geneID!=NULL)? geneID : gffID;
1757     if (geneID)
1758     fprintf(fout," gene_id \"%s\";",geneID);
1759     if (gene_name!=NULL) {
1760     //fprintf(fout, " gene_name ");
1761     //if (gene_name[0]=='"') fprintf (fout, "%s;",gene_name);
1762     // else fprintf(fout, "\"%s\";",gene_name);
1763     fprintf(fout," gene_name \"%s\";",gene_name);
1764     }
1765 gpertea 2 if (xattrs!=NULL) {
1766 gpertea 16 for (int i=0;i<xattrs->Count();i++) {
1767     if (xattrs->Get(i)->attr_val==NULL) continue;
1768     const char* attrname=names->attrs.getName(xattrs->Get(i)->attr_id);
1769     fprintf(fout, " %s ",attrname);
1770     if (xattrs->Get(i)->attr_val[0]=='"')
1771     fprintf(fout, "%s;",xattrs->Get(i)->attr_val);
1772     else fprintf(fout, "\"%s\";",xattrs->Get(i)->attr_val);
1773     }
1774 gpertea 2 }
1775 gpertea 16 //for GTF, also append the GffObj attributes to each exon line
1776     if ((xattrs=this->attrs)!=NULL) {
1777     for (int i=0;i<xattrs->Count();i++) {
1778     if (xattrs->Get(i)->attr_val==NULL) continue;
1779     const char* attrname=names->attrs.getName(xattrs->Get(i)->attr_id);
1780     fprintf(fout, " %s ",attrname);
1781     if (xattrs->Get(i)->attr_val[0]=='"')
1782     fprintf(fout, "%s;",xattrs->Get(i)->attr_val);
1783     else fprintf(fout, "\"%s\";",xattrs->Get(i)->attr_val);
1784     }
1785     }
1786 gpertea 2 fprintf(fout, "\n");
1787     }//GTF
1788     }
1789    
1790 gpertea 16 void GffObj::printGxf(FILE* fout, GffPrintMode gffp,
1791     const char* tlabel, const char* gfparent) {
1792 gpertea 2 static char tmpstr[255];
1793     if (tlabel==NULL) {
1794     tlabel=track_id>=0 ? names->tracks.Get(track_id)->name :
1795     (char*)"gffobj" ;
1796     }
1797     unxcoord();
1798 gpertea 16 //if (exons.Count()==0) return;
1799     const char* gseqname=names->gseqs.Get(gseq_id)->name;
1800 gpertea 2 bool gff3 = (gffp>=pgffAny);
1801     bool showCDS = (gffp==pgtfAny || gffp==pgtfCDS || gffp==pgffCDS || gffp==pgffAny || gffp==pgffBoth);
1802     bool showExon = (gffp<=pgtfExon || gffp==pgffAny || gffp==pgffExon || gffp==pgffBoth);
1803     if (gff3) {
1804     //print GFF3 mRNA line:
1805     if (gscore>0.0) sprintf(tmpstr,"%.2f", gscore);
1806     else strcpy(tmpstr,".");
1807     uint pstart, pend;
1808     if (gffp==pgffCDS) {
1809     pstart=CDstart;
1810     pend=CDend;
1811     }
1812     else { pstart=start;pend=end; }
1813 gpertea 16 //const char* ftype=isTranscript() ? "mRNA" : getFeatureName();
1814     const char* ftype=getFeatureName();
1815 gpertea 2 fprintf(fout,
1816     "%s\t%s\t%s\t%d\t%d\t%s\t%c\t.\tID=%s",
1817     gseqname, tlabel, ftype, pstart, pend, tmpstr, strand, gffID);
1818 gpertea 16 if (CDstart>0 && !showCDS && !isCDS) fprintf(fout,";CDS=%d-%d",CDstart,CDend);
1819     if (gfparent!=NULL) {
1820     //parent override
1821     fprintf(fout, ";Parent=%s",gfparent);
1822     }
1823     else {
1824     if (parent!=NULL && !parent->isDiscarded())
1825     fprintf(fout, ";Parent=%s",parent->getID());
1826     }
1827     if (geneID!=NULL)
1828     fprintf(fout, ";geneID=%s",geneID);
1829     if (gene_name!=NULL)
1830     fprintf(fout, ";gene_name=%s",gene_name);
1831 gpertea 2 if (attrs!=NULL) {
1832     for (int i=0;i<attrs->Count();i++) {
1833 gpertea 16 const char* attrname=names->attrs.getName(attrs->Get(i)->attr_id);
1834     fprintf(fout,";%s=%s", attrname,
1835 gpertea 2 attrs->Get(i)->attr_val);
1836     }
1837     }
1838     fprintf(fout,"\n");
1839     }// gff3 mRNA line
1840     if (showExon) {
1841     //print exons
1842 gpertea 16 if (isCDS && exons.Count()>0 &&
1843     ((strand=='-' && exons.Last()->phase<'0') || (strand=='+' && exons.Last()->phase<'0')))
1844     updateExonPhase();
1845    
1846     for (int i=0;i<exons.Count();i++) {
1847     printGxfLine(fout, tlabel, gseqname, isCDS, exons[i]->start, exons[i]->end, i, exons[i]->phase, gff3);
1848     }
1849     }//printing exons
1850 gpertea 2 if (showCDS && !isCDS && CDstart>0) {
1851     GArray<GffCDSeg> cds(true,true);
1852     getCDSegs(cds);
1853     for (int i=0;i<cds.Count();i++) {
1854     printGxfLine(fout, tlabel, gseqname, true, cds[i].start, cds[i].end, -1, cds[i].phase, gff3);
1855     }
1856     } //showCDS
1857     }
1858    
1859 gpertea 16 void GffObj::updateExonPhase() {
1860     if (!isCDS) return;
1861     int cdsacc=0;
1862     if (CDphase=='1' || CDphase=='2') {
1863     cdsacc+= 3-(CDphase-'0');
1864     }
1865     if (strand=='-') { //reverse strand
1866     for (int i=exons.Count()-1;i>=0;i--) {
1867     exons[i]->phase='0'+ (3-cdsacc%3)%3;
1868     cdsacc+=exons[i]->end-exons[i]->start+1;
1869     }
1870     }
1871     else { //forward strand
1872     for (int i=0;i<exons.Count();i++) {
1873     exons[i]->phase='0'+ (3-cdsacc%3)%3;
1874     cdsacc+=exons[i]->end-exons[i]->start+1;
1875     }
1876     }
1877     }
1878 gpertea 2
1879 gpertea 16
1880 gpertea 2 void GffObj::getCDSegs(GArray<GffCDSeg>& cds) {
1881     GffCDSeg cdseg;
1882     int cdsacc=0;
1883     if (CDphase=='1' || CDphase=='2') {
1884     cdsacc+= 3-(CDphase-'0');
1885     }
1886     if (strand=='-') {
1887     for (int x=exons.Count()-1;x>=0;x--) {
1888     uint sgstart=exons[x]->start;
1889     uint sgend=exons[x]->end;
1890     if (CDend<sgstart || CDstart>sgend) continue;
1891     if (CDstart>=sgstart && CDstart<=sgend)
1892     sgstart=CDstart; //cdstart within this segment
1893     if (CDend>=sgstart && CDend<=sgend)
1894     sgend=CDend; //cdend within this segment
1895     cdseg.start=sgstart;
1896     cdseg.end=sgend;
1897     cdseg.exonidx=x;
1898     //cdseg.phase='0'+(cdsacc>0 ? (3-cdsacc%3)%3 : 0);
1899     cdseg.phase='0'+ (3-cdsacc%3)%3;
1900     cdsacc+=sgend-sgstart+1;
1901     cds.Add(cdseg);
1902     } //for each exon
1903     } // - strand
1904     else { // + strand
1905     for (int x=0;x<exons.Count();x++) {
1906     uint sgstart=exons[x]->start;
1907     uint sgend=exons[x]->end;
1908     if (CDend<sgstart || CDstart>sgend) continue;
1909     if (CDstart>=sgstart && CDstart<=sgend)
1910     sgstart=CDstart; //seqstart within this segment
1911     if (CDend>=sgstart && CDend<=sgend)
1912     sgend=CDend; //seqend within this segment
1913     cdseg.start=sgstart;
1914     cdseg.end=sgend;
1915     cdseg.exonidx=x;
1916     //cdseg.phase='0'+(cdsacc>0 ? (3-cdsacc%3)%3 : 0);
1917     cdseg.phase='0' + (3-cdsacc%3)%3 ;
1918     cdsacc+=sgend-sgstart+1;
1919     cds.Add(cdseg);
1920     } //for each exon
1921     } // + strand
1922     }