Debian Codegraph @

GFF-class.h

raw
1 /* BaitFisher (version 1.2.7) a program for designing DNA target enrichment baits
2 * Copyright 2013-2016 by Christoph Mayer
3 *
4 * This source file is part of the BaitFisher-package.
5 *
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with BaitFisher. If not, see <http://www.gnu.org/licenses/>.
18 *
19 *
20 * For any enquiries send an Email to Christoph Mayer
21 * [email protected]
22 *
23 * When publishing work that is based on the results please cite:
24 * Mayer et al. 2016: BaitFisher: A software package for multi-species target DNA enrichment probe design
25 *
26 */
27 #ifndef GFF_RECORD_H
28 #define GFF_RECORD_H
29
30 #include "easystring.h"
31 #include <vector>
32 #include "range_functions.h"
33 #include "cstdio" // for FILE
34 #include "CSequence_Mol2_1.h"
35
36 //***********************************************************************************
37 // In the long run, we intend to follow the conventions specified in: http://www.bioperl.org/wiki/GFF3
38 // In particular the handling of special characters does not conform to this standard yet.
39
40 // Convention: fstart and fend are the direct gff field entries 4 and 5. Minimum value is 1. The end value is the last position in the feature.
41 // This convention is not identical to the convention in CgenomeFeature class, where all values are 0 based.
42 // In this class the philisoph is to be as close as possible to the value in the file.
43 // Example: First three bases of seq.: 1,3
44 //
45 // Convention has been checked.
46 //***********************************************************************************
47
48 using namespace std;
49
50 static const easystring empty_easy_string;
51
52 // Forward declaration of friend functions of the classes in this file. This avoids the friend-injection problem:
53 class GFF_record;
54 bool position_lessThan_GFF_record(GFF_record &, GFF_record &);
55 bool position_lessThan_GFF_record_pointer(GFF_record *, GFF_record *);
56
57
58 class GFF_record {
59
60 private:
61 easystring parse_error;
62
63 easystring seqname; // gff field 1
64 easystring source; // gff field 2
65 easystring feature; // gff field 3
66 unsigned fstart; // gff field 4
67 unsigned fend; // gff field 5 // According to the gff file conventions this is an inclusive end.
68 easystring score; // gff field 6
69 char strand; // gff field 7
70 char phase; // gff field 8
71 std::vector<easystring> att_names;
72 std::vector<easystring> att_names_lower_case;
73 std::vector<easystring> att_values;
74
75
76 public:
77 GFF_record (const std::string &str)
78 {
79 parse_string(str);
80 }
81
82 GFF_record (const easystring &str)
83 {
84 parse_string(str);
85 }
86
87 GFF_record (easystring &p_seqname,
88 easystring &p_source,
89 easystring &p_feature,
90 unsigned p_fstart,
91 unsigned p_fend,
92 easystring &p_score,
93 char p_strand,
94 char p_phase,
95 easystring &p_att
96 ):
97 seqname(p_seqname), source(p_source), feature(p_feature), fstart(p_fstart),
98 fend(p_fend), score(p_score), strand(p_strand), phase(p_phase)
99 {
100 parse_attributes(p_att);
101 }
102
103
104 unsigned good() const
105 {
106 return parse_error.empty();
107 }
108
109 std::string getErrorReason() const
110 {
111 return parse_error;
112 }
113
114
115 private:
116
117 bool parse_attributes(const easystring &tmp_att)
118 {
119 int i, att_num;
120 std::vector<std::easystring> sv;
121
122 att_num = split_respect(sv, tmp_att, ";");
123
124 // std::cerr << "+++ Number of attributes found: " << att_num << std::endl;
125
126 easystring key;
127 easystring val;
128 std::size_t index;
129 // unsigned num_quotes1, num_quotes2;
130
131 for (i=0; i<att_num; ++i)
132 {
133 sv[i].removeSpacesFront();
134 sv[i].removeSpacesBack();
135
136 index = sv[i].find_first_of(" =");
137 if (index == std::string::npos)
138 {
139 parse_error = "Unrecognized attribute: \"" + sv[i] + "\"";
140 return false;
141 }
142 key = easystring(sv[i].begin(), sv[i].begin()+index);
143 // cerr << "new key: " << key << endl;
144 while (index < sv[i].size() &&
145 (sv[i][index] == ' ' || sv[i][index] == '=') )
146 ++index;
147 if (index == sv[i].size() )
148 {
149 parse_error = "Unrecognized attribute: \"" + sv[i] + "\"";
150 return false;
151 }
152 val = easystring(sv[i].begin()+index, sv[i].end() );
153 // cerr << "new val: " << val << endl;
154
155 // Drop the following checks since quotes can occur as singletons:
156 // Example: "3' UTR"
157 /* // More error checks concerning val could be useful */
158 /* num_quotes1 = val.countChar('\"'); */
159 /* num_quotes2 = val.countChar('\''); */
160
161 /* if (num_quotes1 % 2 != 0 || num_quotes2 % 2 != 0) */
162 /* { */
163 /* parse_error = "unmatched quotes on in attribute field. Attribute: " + key; */
164 /* return false; */
165 /* } */
166 att_names.push_back(key);
167 key.ToLower();
168 att_names_lower_case.push_back(key);
169 att_values.push_back(val);
170 }
171 return true;
172 }
173
174 bool parse_string(const easystring &str)
175 {
176 std::vector<std::easystring> sv;
177 easystring tmp_att;
178 int i, split_num;
179
180 // We use split_strict since successive tabs are not allowed
181 split_num = split_strict(sv, str, "\t");
182
183 if (split_num != 9)
184 {
185 parse_error = "wrong number of tab deliminated fields";
186 return false;
187 }
188
189 for (i=0; i<9; ++i)
190 {
191 sv[i].removeSpacesFront();
192 sv[i].removeSpacesBack();
193
194 if ( sv[i].empty() )
195 {
196 parse_error = "on the tab deliminated line the field with position" + easystring(char(i+49)) + " is empty";
197 return false;
198 }
199 }
200
201 seqname = sv[0];
202 source = sv[1];
203 feature = sv[2];
204 fstart = sv[3].ToUnsigned();
205 fend = sv[4].ToUnsigned();
206 score = sv[5];
207 strand = sv[6][0]; // Result must be checked.
208 phase = sv[7][0]; // Result must be checked.
209 tmp_att = sv[8];
210
211 if (fstart > fend)
212 {
213 parse_error = "start > end";
214 return false;
215 }
216
217 if (strchr("+-?.0",strand) == NULL)
218 {
219 parse_error = easystring("wrong strand symbol \"") + strand + "\". Must be one of \"+-?.0\"";
220 return false;
221 }
222
223 if (strchr("012+-.", phase) == NULL)
224 {
225 parse_error = easystring("wrong phase symbol \"") + phase + "\". Must be one of \"012+-.\"";
226 return false;
227 }
228
229 return parse_attributes(tmp_att);
230 }
231
232 public:
233
234 easystring getSeqid () { return seqname; }
235 easystring getSource () { return source; }
236 easystring getFeature () { return feature; }
237 unsigned getStart () { return fstart; }
238 unsigned getEnd () { return fend; }
239
240 unsigned getStartIndex () { return fstart-1; } // Lowest index is 0
241 unsigned getEndIndex () { return fend; } // Is index after last index that lies in the feature.
242 // This is equal to the last position in feature. fend has lowest value 1.
243 // Example: Start codon at beginning of sequence: gff positions 1,3. Sequence indices: 0,3
244
245 easystring getScoreAsString() { return score; }
246
247 /* std::pair<bool, double> getScore() */
248 /* { */
249 /* if (score.size() == 1 && score[0] == '.') */
250 /* return make_pair(false, 0); */
251 /* else */
252 /* return make_pair(true, score.ToDouble()); */
253 /* } */
254
255 char getStrand () { return strand; }
256 char getPhase () { return phase; }
257
258 unsigned length() { return fend-fstart; }
259
260 const vector<easystring>& getAttributeNames()
261 {
262 return att_names;
263 }
264
265 const vector<easystring>& getAttributeNamesLowerCase()
266 {
267 return att_names_lower_case;
268 }
269
270 int getIndexOfAttribute(const easystring &s, bool lower_case_comparison = false)
271 {
272 int i = 0, n = att_names.size();
273
274 if (!lower_case_comparison)
275 while (i < n && att_names[i] != s)
276 {
277 ++i;
278 }
279 else
280 while (i < n && att_names_lower_case[i] != s)
281 {
282 ++i;
283 }
284
285 if (i==n)
286 return -1;
287 else
288 return i;
289 }
290
291
292 unsigned countValuesOfAttribute(const easystring &s, bool lower_case_comparison = false)
293 {
294 int i = getIndexOfAttribute(s, lower_case_comparison);
295
296 if (i == -1)
297 return 0;
298 else
299 return att_values[i].countChar(',')+1;
300 }
301
302 unsigned countValuesOfAttribute(unsigned i)
303 {
304 if (i >= att_names.size())
305 return 0;
306 else
307 return att_values[i].countChar(',')+1;
308 }
309
310 const easystring &getValueOfAttribute(const easystring &s, bool lower_case_comparison = false)
311 {
312 int i = getIndexOfAttribute(s, lower_case_comparison);
313
314 if (i == -1)
315 return empty_easy_string;
316 else
317 return att_values[i];
318 }
319
320 const easystring &getValueOfAttribute(unsigned i)
321 {
322 if (i >= att_names.size())
323 return empty_easy_string;
324 else
325 return att_values[i];
326 }
327
328 bool isFeature(const easystring &str)
329 {
330 return (str == feature);
331 }
332
333
334 void print(ostream &os, int flag=0)
335 {
336 unsigned i;
337
338 if ( !good() )
339 {
340 os << "Invalid gff recored." << endl;
341 os << "Reason: " << parse_error << endl;
342 return;
343 }
344 if (flag == 0) // gff output format
345 {
346 os << seqname << "\t"
347 << source << "\t"
348 << feature << "\t"
349 << fstart << "\t"
350 << fend << "\t"
351 << score << "\t"
352 << strand << "\t"
353 << phase << "\t";
354
355 for (i=0; i < att_names.size()-1; ++i)
356 {
357 os << att_names[i] << "=" << getValueOfAttribute(att_names[i]) << "; ";
358 }
359 os << att_names[i] << "=" << getValueOfAttribute(att_names[i]);
360 }
361 else if (flag == 1) // long multiline format
362 {
363 os << "seqname: " << seqname << endl
364 << "source: " << source << endl
365 << "feature: " << feature << endl
366 << "start: " << fstart << endl
367 << "end: " << fend << endl
368 << "score: " << score << endl
369 << "strand: " << strand << endl
370 << "phase: " << phase << endl;
371
372
373 for (i=0; i < att_names.size(); ++i)
374 {
375 os << "attribute: (" << att_names[i]
376 << ") number of values: " << countValuesOfAttribute(att_names[i])
377 << ", value: " << getValueOfAttribute(att_names[i]) << endl;
378 }
379 }
380 }
381
382 /* bool is_in_range(unsigned a, unsigned e) */
383 /* { */
384 /* return is_r2_Subrange_of_r1(a, e, fstart, fend); */
385 /* } */
386
387 /* unsigned overlap_with_range(unsigned a, unsigned e) */
388 /* { */
389 /* return overlap(a, e, fstart, fend); */
390 /* } */
391
392 /* void union_with_range(unsigned a, unsigned e, unsigned &c1, unsigned &c2) */
393 /* { */
394 /* range_union(a, e, fstart, fend, c1, c2); */
395 /* } */
396
397 /* void intersection_with_range(unsigned a, unsigned e, unsigned &c1, unsigned &c2) */
398 /* { */
399 /* range_intersection(a, e, fstart, fend, c1, c2); */
400 /* } */
401
402 bool print_sequence(FILE *of, easystring format, CSequence_Mol &seq, int char_per_line,
403 bool ref_comp_if_neg_direction = true )
404 {
405 // the name of the sequence we print:
406 easystring seq_name;
407 string strand_desc;
408 unsigned i;
409
410 if (seq.getName() != seqname)
411 return false;
412
413 // %I seqID
414 // %S source
415 // %F feature
416 // %b begin
417 // %e end
418 // %s score
419 // %d strand (Direction) short
420 // %D strand (Direction) long
421 // %p phase
422 // %A attribute 0
423
424 if ( format.empty() )
425 {
426 format = "%I#%S#%F#%b-%e#%p#%A%D";
427 }
428
429 unsigned N = format.size();
430
431 for (i=0; i < N; ++i)
432 {
433 if (format[i] == '\\' )
434 {
435 ++i;
436 if (i == N)
437 break;
438 seq_name += format[i];
439 }
440 else if (format[i] == '%')
441 {
442 ++i;
443 if (i == N)
444 break;
445 switch(format[i])
446 {
447 case 'I': seq_name += seqname; break;
448 case 'S': seq_name += source; break;
449 case 'F': seq_name += feature; break;
450 case 'b': seq_name += easystring(fstart); break;
451 case 'e': seq_name += easystring(fend); break;
452 case 's': seq_name += score; break;
453 case 'd': seq_name += strand; break;
454 case 'D':
455 if ( strand == '+') {
456 strand_desc = "on+strand_is+strand";
457 }
458 else if ( strand == '-' ) {
459 if (ref_comp_if_neg_direction) {
460 seq_name += "on-strand_is-strand";
461 }
462 else {
463 seq_name += "on-strand_is+strand";
464 }
465 }
466 else {
467 seq_name += "not-stranded";
468 }
469 break;
470
471 case 'p': seq_name += easystring( phase ); break;
472 case 'A': seq_name += getValueOfAttribute(0); break;
473 default: seq_name += easystring(format[i]); break;
474 }
475 }
476 else
477 seq_name += easystring(format[i]);
478 }
479
480 /* seq_name = */
481 /* seqname + */
482 /* string("|") + */
483 /* source + */
484 /* string("|") + */
485 /* feature + */
486 /* string("|") + */
487 /* easystring( fstart ) + */
488 /* string(":") + */
489 /* easystring( fend ) + */
490 /* string("|") + */
491 /* score + */
492 /* string("|") + */
493 /* easystring( strand ) + */
494 /* string("|") + */
495 /* easystring( phase ) + */
496 /* string("|") + */
497 /* getValueOfAttribute(0) + */
498 /* string("|") + */
499 /* strand_desc; */
500
501 bool revComp = ref_comp_if_neg_direction && strand == '-';
502
503 // fend is position at which feature ends.
504 // The following write function expects 0 based indizes,
505 // Example: print first three bases, pass 0 and 3 in both cases, we have 1 and 3
506
507 if (revComp)
508 seq.writeSequence_revComp(of, fstart-1, fend, seq_name.c_str(), char_per_line);
509 else
510 seq.writeSequence(of, fstart-1, fend, seq_name.c_str(), char_per_line);
511 return true;
512 }
513
514
515 // friend functions:
516
517 friend unsigned overlap(GFF_record &a, GFF_record &b)
518 {
519 if (a.seqname != b.seqname)
520 return 0;
521 return overlap(a.fstart, a.fend, b.fstart, b.fend);
522 }
523
524 friend unsigned overlap_in_same_direction(GFF_record &a, GFF_record &b)
525 {
526 if (a.strand != b.strand)
527 return 0;
528
529 if (a.seqname != b.seqname)
530 return 0;
531
532 return overlap(a.fstart, a.fend, b.fstart, b.fend);
533 }
534
535 friend bool position_lessThan_GFF_record(GFF_record &a, GFF_record &b)
536 {
537 if (a.seqname != b.seqname)
538 return a.seqname < b.seqname;
539
540 if (a.fstart < b.fstart)
541 return true;
542
543 if (a.fstart > b.fstart)
544 return false;
545
546 // We have a.fstart == b.fstart now!!!
547 if ( equalRange(a, b) )
548 {
549 if ( a.feature == "exon" )
550 return true;
551 else
552 return false;
553 }
554
555 if ( b.fend < a.fend )
556 return true;
557 else
558 return false;
559 }
560
561 friend bool position_lessThan_GFF_record_pointer(GFF_record *a, GFF_record *b)
562 {
563 if (a->seqname != b->seqname)
564 return a->seqname < b->seqname;
565
566 if (a->fstart < b->fstart)
567 return true;
568
569 if (a->fstart > b->fstart)
570 return false;
571
572 // We have a.fstart == b.fstart now!!!
573 if ( equalRange(*a, *b) )
574 {
575 if ( a->feature == "exon" )
576 return true;
577 else
578 return false;
579 }
580
581 if ( b->fend < a->fend )
582 return true;
583 else
584 return false;
585 }
586
587
588
589 friend bool operator==(GFF_record &a, GFF_record &b)
590 {
591 if (a.fstart != b.fstart || a.fend != b.fend)
592 return false;
593 if (a.feature != b.feature)
594 return false;
595 if (a.seqname != b.seqname)
596 return false;
597 if (a.source != b.source)
598 return false;
599
600 if (a.score != b.score)
601 return false;
602 if (a.strand != b.strand)
603 return false;
604 if (a.phase != b.phase)
605 return false;
606
607 if (a.att_names != b.att_names)
608 return false;
609 if (a.att_values != b.att_values)
610 return false;
611
612 return true;
613 }
614
615 friend bool equalRange(GFF_record &a, GFF_record &b)
616 {
617 return equalRange(a.fstart, a.fend, b.fstart, b.fend);
618 }
619
620 friend bool isSubfeature_Arg2_of_Arg1(GFF_record &a, GFF_record &b)
621 {
622 return is_r2_Subrange_of_r1(a.fstart, a.fend, b.fstart, b.fend);
623 }
624
625
626
627
628 };
629
630
631
632
633 #endif