finish dialog box to setup an analysis
[mussa.git] / alg / sequence.cpp
1 //  This file is part of the Mussa source distribution.
2 //  http://mussa.caltech.edu/
3 //  Contact author: Tristan  De Buysscher, tristan@caltech.edu
4
5 // This program and all associated source code files are Copyright (C) 2005
6 // the California Institute of Technology, Pasadena, CA, 91125 USA.  It is
7 // under the GNU Public License; please see the included LICENSE.txt
8 // file for more information, or contact Tristan directly.
9
10
11 //  This file is part of the Mussa source distribution.
12 //  http://mussa.caltech.edu/
13 //  Contact author: Tristan  De Buysscher, tristan@caltech.edu
14
15 // This program and all associated source code files are Copyright (C) 2005
16 // the California Institute of Technology, Pasadena, CA, 91125 USA.  It is
17 // under the GNU Public License; please see the included LICENSE.txt
18 // file for more information, or contact Tristan directly.
19
20
21 //                        ----------------------------------------
22 //                           ---------- sequence.cc -----------
23 //                        ----------------------------------------
24
25 #include "alg/sequence.hpp"
26 #include "mussa_exceptions.hpp"
27
28 #include <string>
29 #include <iostream>
30
31 using namespace std;
32
33 annot::annot() 
34  : start(0),
35    end(0),
36    type(""),
37    name("")
38 {
39 }
40
41 annot::annot(int start, int end, std::string type, std::string name)
42  : start(start),
43    end(end),
44    type(type),
45    name(name)
46 {
47 }
48
49 motif::motif(int start, std::string motif)
50  : annot(start, start+motif.size(), "motif", motif),
51    sequence(motif)
52 {
53 }
54   
55 Sequence::Sequence()
56   : sequence(""),
57     header(""),
58     species("")
59 {
60   annots.clear();
61   motif_list.clear();
62 }
63
64 Sequence::Sequence(string seq)
65 {
66   set_filtered_sequence(seq);
67 }
68
69 Sequence &Sequence::operator=(const Sequence& s)
70 {
71   if (this != &s) {
72     sequence = s.sequence;
73     header = s.header;
74     species = s.species;
75     annots = s.annots;
76   }
77   return *this;
78 }
79
80 Sequence &Sequence::operator=(const std::string& s)
81 {
82   set_filtered_sequence(s);
83   return *this;
84 }
85
86 char Sequence::operator[](int index) const
87 {
88   return sequence[index];
89 }
90
91 ostream& operator<<(ostream& out, const Sequence& seq)
92 {
93   out << "Sequence(" << seq.get_seq() << ")";
94   return out;
95 }
96
97 //! load a fasta file into a sequence
98 /*! 
99  * \param file_path the location of the fasta file in the filesystem
100  * \param seq_num which sequence in the file to load
101  * \param start_index starting position in the fasta sequence, 0 for beginning
102  * \param end_index ending position in the fasta sequence, 0 for end
103  * \return error message, empty string if no error. (gag!)
104  */
105 void
106 Sequence::load_fasta(string file_path, int seq_num, 
107                      int start_index, int end_index)
108 {
109   fstream data_file;
110   string file_data_line;
111   int header_counter = 0;
112   bool read_seq = true;
113   string rev_comp;
114   string sequence_raw;
115   string seq_tmp;             // holds sequence during basic filtering
116
117   data_file.open(file_path.c_str(), ios::in);
118
119   if (seq_num == 0) {
120     throw mussa_load_error("fasta sequence number is 1 based (can't be 0)");
121   }
122   if (!data_file)
123   {    
124     throw mussa_load_error("Sequence File: " + file_path + " not found"); 
125   }
126   // if file opened okay, read it
127   else
128   {
129     // search for the header of the fasta sequence we want
130     while ( (!data_file.eof()) && (header_counter < seq_num) )
131     {
132       getline(data_file,file_data_line);
133       if (file_data_line.substr(0,1) == ">")
134         header_counter++;
135     }
136
137     header = file_data_line.substr(1);
138
139     sequence_raw = "";
140
141     while ( !data_file.eof() && read_seq )
142     {
143       getline(data_file,file_data_line);
144       if (file_data_line.substr(0,1) == ">")
145         read_seq = false;
146       else sequence_raw += file_data_line;
147     }
148
149     data_file.close();
150
151     // Lastly, if subselection of the sequence was specified we keep cut out
152     // and only keep that part
153     // end_index = 0 means no end was specified, so cut to the end 
154     if (end_index == 0)
155       end_index = sequence_raw.size();
156
157     // sequence filtering for upcasing agctn and convert non AGCTN to N
158     set_filtered_sequence(sequence_raw, start_index, end_index-start_index);
159   }
160 }
161
162 void Sequence::set_filtered_sequence(const string &old_seq, 
163                                      string::size_type start, 
164                                      string::size_type count)
165 {
166   char conversionTable[257];
167
168   if ( count == 0)
169     count = old_seq.size() - start;
170   sequence.clear();
171   sequence.reserve(count);
172
173   // Make a conversion table
174
175   // everything we don't specify below will become 'N'
176   for(int table_i=0; table_i < 256; table_i++)
177   {
178     conversionTable[table_i] = 'N';
179   }
180   // add end of string character for printing out table for testing purposes
181   conversionTable[256] = '\0';
182
183   // we want these to map to themselves - ie not to change
184   conversionTable[(int)'A'] = 'A';
185   conversionTable[(int)'T'] = 'T';
186   conversionTable[(int)'G'] = 'G';
187   conversionTable[(int)'C'] = 'C';
188   // this is to upcase
189   conversionTable[(int)'a'] = 'A';
190   conversionTable[(int)'t'] = 'T';
191   conversionTable[(int)'g'] = 'G';
192   conversionTable[(int)'c'] = 'C';
193
194   // finally, the actual conversion loop
195   for(string::size_type seq_index = 0; seq_index < count; seq_index++)
196   {
197     sequence += conversionTable[ (int)old_seq[seq_index+start]];
198   }
199 }
200
201   // this doesn't work properly under gcc 3.x ... it can't recognize toupper
202   //transform(sequence.begin(), sequence.end(), sequence.begin(), toupper);
203
204
205 void
206 Sequence::load_annot(string file_path, int start_index, int end_index)
207 {
208   fstream data_file;
209   string file_data_line;
210   annot an_annot;
211   string::size_type space_split_i;
212   string annot_value;
213   list<annot>::iterator list_i;
214   string err_msg;
215
216
217   annots.clear();
218   data_file.open(file_path.c_str(), ios::in);
219
220   if (!data_file)
221   {
222     throw mussa_load_error("Sequence File: " + file_path + " not found");
223   }
224   // if file opened okay, read it
225   else
226   {
227     getline(data_file,file_data_line);
228     species = file_data_line;
229
230     // end_index = 0 means no end was specified, so cut to the end 
231     if (end_index == 0)
232       end_index = sequence.length();
233
234     //cout << "START: " << start_index << " END: " << end_index << endl;
235
236     while ( !data_file.eof() )
237     {
238       getline(data_file,file_data_line);
239       if (file_data_line != "")
240       {
241         // need to get 4 values...almost same code 4 times...
242         // get annot start index
243         space_split_i = file_data_line.find(" ");
244         annot_value = file_data_line.substr(0,space_split_i);
245         an_annot.start = atoi (annot_value.c_str());
246         file_data_line = file_data_line.substr(space_split_i+1);
247         // get annot end index
248         space_split_i = file_data_line.find(" ");
249         annot_value = file_data_line.substr(0,space_split_i);
250         an_annot.end = atoi (annot_value.c_str());
251         file_data_line = file_data_line.substr(space_split_i+1);
252
253         //cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
254               //     << endl;
255
256         // get annot name
257         space_split_i = file_data_line.find(" ");
258         if (space_split_i == string::npos)  // no entries for name & type
259         {
260           cout << "seq, annots - no name or type\n";
261           an_annot.name = "";
262           an_annot.type = "";
263         }
264         else
265         {
266           annot_value = file_data_line.substr(0,space_split_i);
267           an_annot.name = annot_value;
268           file_data_line = file_data_line.substr(space_split_i+1);
269           // get annot type
270           space_split_i = file_data_line.find(" ");
271           if (space_split_i == string::npos)  // no entry for type
272             an_annot.type = "";
273           else
274           {
275             annot_value = file_data_line.substr(0,space_split_i);
276             an_annot.type = annot_value;
277           }
278         }
279
280
281         // add annot to list if it falls within the range of sequence specified
282         if ((start_index <= an_annot.start) && (end_index >= an_annot.end)) 
283         {
284           an_annot.start -= start_index;
285           an_annot.end -= start_index;
286           annots.push_back(an_annot);
287         }
288         else
289           cout << "FAILED!!!!!!\n";
290       }
291     }
292
293     data_file.close();
294     /*
295     // debugging check
296     for(list_i = annots.begin(); list_i != annots.end(); ++list_i)
297     {
298       cout << (*list_i).start << "," << (*list_i).end << "\t";
299       cout << (*list_i).name << "\t" << (*list_i).type << endl;
300     }
301     */
302   }
303 }
304
305 bool Sequence::empty() const
306 {
307   return (size() == 0);
308 }
309
310 const std::list<annot>& Sequence::annotations() const
311 {
312   return annots;
313 }
314
315 string::size_type Sequence::length() const
316 {
317   return size();
318 }
319
320 string::size_type Sequence::size() const
321 {
322   return sequence.size();
323 }
324
325 Sequence::iterator Sequence::begin()
326 {
327   return sequence.begin();
328 }
329
330 Sequence::const_iterator Sequence::begin() const
331 {
332   return sequence.begin();
333 }
334
335 Sequence::iterator Sequence::end()
336 {
337   return sequence.end();
338 }
339
340 Sequence::const_iterator Sequence::end() const
341 {
342   return sequence.end();
343 }
344
345
346 const string&
347 Sequence::get_seq() const
348 {
349   return sequence;
350 }
351
352
353 string
354 Sequence::subseq(int start, int end) const
355 {
356   return sequence.substr(start, end);
357 }
358
359
360 const char *
361 Sequence::c_seq() const
362 {
363   return sequence.c_str();
364 }
365
366 string
367 Sequence::rev_comp() const
368 {
369   string rev_comp;
370   char conversionTable[257];
371   int seq_i, table_i, len;
372
373   len = sequence.length();
374   rev_comp.reserve(len);
375   // make a conversion table
376   // init all parts of conversion table to '~' character
377   // '~' I doubt will ever appear in a sequence file (jeez, I hope)
378   // and may the fleas of 1000 camels infest the genitals of any biologist (and
379   // seven generations of their progeny) who decides to make it mean
380   // something special!!!
381   // PS - double the curse for any smartass non-biologist who tries it as well
382   for(table_i=0; table_i < 256; table_i++)
383   {
384     conversionTable[table_i] = '~';
385   }
386   // add end of string character for printing out table for testing purposes
387   conversionTable[256] = '\0';
388
389   // add in the characters for the bases we want to convert
390   conversionTable[(int)'A'] = 'T';
391   conversionTable[(int)'T'] = 'A';
392   conversionTable[(int)'G'] = 'C';
393   conversionTable[(int)'C'] = 'G';
394   conversionTable[(int)'N'] = 'N';
395
396   // finally, the actual conversion loop
397   for(seq_i = len - 1; seq_i >= 0; seq_i--)
398   {
399     table_i = (int) sequence[seq_i];
400     rev_comp += conversionTable[table_i];
401   }
402
403   return rev_comp;
404 }
405
406
407 const string&
408 Sequence::get_header() const
409 {
410   return header;
411 }
412 /*
413 //FIXME: i don't think this code is callable
414 string 
415 Sequence::sp_name() const
416 {
417   return species;
418 }
419 */
420
421 void
422 Sequence::set_seq(const string& a_seq)
423 {
424   set_filtered_sequence(a_seq);
425 }
426
427
428 /*
429 string 
430 Sequence::species()
431 {
432   return species;
433 }
434 */
435
436 void
437 Sequence::clear()
438 {
439   sequence = "";
440   header = "";
441   species = "";
442   annots.clear();
443 }
444
445 void
446 Sequence::save(fstream &save_file)
447                //string save_file_path)
448 {
449   //fstream save_file;
450   list<annot>::iterator annots_i;
451
452   // not sure why, or if i'm doing something wrong, but can't seem to pass
453   // file pointers down to this method from the mussa control class
454   // so each call to save a sequence appends to the file started by mussa_class
455   //save_file.open(save_file_path.c_str(), ios::app);
456
457   save_file << "<Sequence>" << endl;
458   save_file << sequence << endl;
459   save_file << "</Sequence>" << endl;
460
461   save_file << "<Annotations>" << endl;
462   save_file << species << endl;
463   for (annots_i = annots.begin(); annots_i != annots.end(); ++annots_i)
464   {
465     save_file << annots_i->start << " " << annots_i->end << " " ;
466     save_file << annots_i->name << " " << annots_i->type << endl;
467   }
468   save_file << "</Annotations>" << endl;
469   //save_file.close();
470 }
471
472 void
473 Sequence::load_museq(string load_file_path, int seq_num)
474 {
475   fstream load_file;
476   string file_data_line;
477   int seq_counter;
478   annot an_annot;
479   string::size_type space_split_i;
480   string annot_value;
481
482   annots.clear();
483   load_file.open(load_file_path.c_str(), ios::in);
484
485   seq_counter = 0;
486   // search for the seq_num-th sequence 
487   while ( (!load_file.eof()) && (seq_counter < seq_num) )
488   {
489     getline(load_file,file_data_line);
490     if (file_data_line == "<Sequence>")
491       seq_counter++;
492   }
493   getline(load_file, file_data_line);
494   sequence = file_data_line;
495   getline(load_file, file_data_line);
496   getline(load_file, file_data_line);
497   if (file_data_line == "<Annotations>")
498   {
499     getline(load_file, file_data_line);
500     species = file_data_line;
501     while ( (!load_file.eof())  && (file_data_line != "</Annotations>") )
502     {
503       getline(load_file,file_data_line);
504       if ((file_data_line != "") && (file_data_line != "</Annotations>"))  
505       {
506         // need to get 4 values...almost same code 4 times...
507         // get annot start index
508         space_split_i = file_data_line.find(" ");
509         annot_value = file_data_line.substr(0,space_split_i);
510         an_annot.start = atoi (annot_value.c_str());
511         file_data_line = file_data_line.substr(space_split_i+1);
512         // get annot end index
513         space_split_i = file_data_line.find(" ");
514         annot_value = file_data_line.substr(0,space_split_i);
515         an_annot.end = atoi (annot_value.c_str());
516
517         if (space_split_i == string::npos)  // no entry for type or name
518         {
519           cout << "seq, annots - no type or name\n";
520           an_annot.type = "";
521           an_annot.name = "";
522         }
523         else   // else get annot type
524         {
525           file_data_line = file_data_line.substr(space_split_i+1);
526           space_split_i = file_data_line.find(" ");
527           annot_value = file_data_line.substr(0,space_split_i);
528           an_annot.type = annot_value;
529           if (space_split_i == string::npos)  // no entry for name
530           {
531             cout << "seq, annots - no name\n";
532             an_annot.name = "";
533           }
534           else          // get annot name
535           {
536             file_data_line = file_data_line.substr(space_split_i+1);
537             space_split_i = file_data_line.find(" ");
538             annot_value = file_data_line.substr(0,space_split_i);
539             an_annot.type = annot_value;
540           }
541         }
542         annots.push_back(an_annot);  // don't forget to actually add the annot
543       }
544       //cout << "seq, annots: " << an_annot.start << ", " << an_annot.end
545       //     << "-->" << an_annot.type << "::" << an_annot.name << endl;
546     }
547   }
548   load_file.close();
549 }
550
551
552 string
553 Sequence::rc_motif(string a_motif)
554 {
555   string rev_comp;
556   char conversionTable[257];
557   int seq_i, table_i, len;
558
559   len = a_motif.length();
560   rev_comp.reserve(len);
561
562   for(table_i=0; table_i < 256; table_i++)
563   {
564     conversionTable[table_i] = '~';
565   }
566   // add end of string character for printing out table for testing purposes
567   conversionTable[256] = '\0';
568
569   // add in the characters for the bases we want to convert (IUPAC)
570   conversionTable[(int)'A'] = 'T';
571   conversionTable[(int)'T'] = 'A';
572   conversionTable[(int)'G'] = 'C';
573   conversionTable[(int)'C'] = 'G';
574   conversionTable[(int)'N'] = 'N';
575   conversionTable[(int)'M'] = 'K';
576   conversionTable[(int)'R'] = 'Y';
577   conversionTable[(int)'W'] = 'W';
578   conversionTable[(int)'S'] = 'S';
579   conversionTable[(int)'Y'] = 'R';
580   conversionTable[(int)'K'] = 'M';
581   conversionTable[(int)'V'] = 'B';
582   conversionTable[(int)'H'] = 'D';
583   conversionTable[(int)'D'] = 'H';
584   conversionTable[(int)'B'] = 'V';
585
586   // finally, the actual conversion loop
587   for(seq_i = len - 1; seq_i >= 0; seq_i--)
588   {
589     //cout << "** i = " << seq_i << " bp = " << 
590     table_i = (int) a_motif[seq_i];
591     rev_comp += conversionTable[table_i];
592   }
593
594   //cout << "seq: " << a_motif << endl;
595   //cout << "rc:  " << rev_comp << endl;
596
597   return rev_comp;
598 }
599
600 string
601 Sequence::motif_normalize(string a_motif)
602 {
603   string valid_motif;
604   int seq_i, len;
605
606   len = a_motif.length();
607   valid_motif.reserve(len);
608
609   // this just upcases IUPAC symbols.  Eventually should return an error if non IUPAC is present.
610   // current nonIUPAC symbols are omitted, which is not reported atm
611   for(seq_i = 0; seq_i < len; seq_i++)
612   {
613     if ((a_motif[seq_i] == 'a') || (a_motif[seq_i] == 'A'))
614       valid_motif += 'A';
615     else if ((a_motif[seq_i] == 't') || (a_motif[seq_i] == 'T'))
616       valid_motif += 'T';
617     else if ((a_motif[seq_i] == 'g') || (a_motif[seq_i] == 'G'))
618       valid_motif += 'G';
619     else if ((a_motif[seq_i] == 'c') || (a_motif[seq_i] == 'C'))
620       valid_motif += 'C';
621     else if ((a_motif[seq_i] == 'n') || (a_motif[seq_i] == 'N'))
622       valid_motif += 'N';
623     else if ((a_motif[seq_i] == 'm') || (a_motif[seq_i] == 'M'))
624       valid_motif += 'M';
625     else if ((a_motif[seq_i] == 'r') || (a_motif[seq_i] == 'R'))
626       valid_motif += 'R';
627     else if ((a_motif[seq_i] == 'w') || (a_motif[seq_i] == 'W'))
628       valid_motif += 'W';
629     else if ((a_motif[seq_i] == 's') || (a_motif[seq_i] == 'S'))
630       valid_motif += 'S';
631     else if ((a_motif[seq_i] == 'y') || (a_motif[seq_i] == 'Y'))
632       valid_motif += 'Y';
633     else if ((a_motif[seq_i] == 'k') || (a_motif[seq_i] == 'K'))
634       valid_motif += 'G';
635     else if ((a_motif[seq_i] == 'v') || (a_motif[seq_i] == 'V'))
636       valid_motif += 'V';
637     else if ((a_motif[seq_i] == 'h') || (a_motif[seq_i] == 'H'))
638       valid_motif += 'H';
639     else if ((a_motif[seq_i] == 'd') || (a_motif[seq_i] == 'D'))
640       valid_motif += 'D';
641     else if ((a_motif[seq_i] == 'b') || (a_motif[seq_i] == 'B'))
642       valid_motif += 'B';
643     else {
644       string msg = "Letter ";
645       msg += a_motif[seq_i];
646       msg += " is not a valid IUPAC symbol";
647       throw motif_normalize_error(msg);
648     }
649   }
650   //cout << "valid_motif is: " << valid_motif << endl;
651   return valid_motif;
652 }
653
654 void Sequence::add_motif(string a_motif)
655 {
656   vector<int> motif_starts = find_motif(a_motif);
657
658   for(vector<int>::iterator motif_start_i = motif_starts.begin();
659       motif_start_i != motif_starts.end();
660       ++motif_start_i)
661   {
662     motif_list.push_back(motif(*motif_start_i, a_motif));
663   }
664 }
665
666 void Sequence::clear_motifs()
667 {
668   motif_list.clear();
669 }
670
671 const list<motif>& Sequence::motifs() const
672 {
673   return motif_list;
674 }
675
676 vector<int>
677 Sequence::find_motif(string a_motif)
678 {
679   vector<int> motif_match_starts;
680   string a_motif_rc;
681
682   motif_match_starts.clear();
683
684   //cout << "motif is: " << a_motif << endl;
685   a_motif = motif_normalize(a_motif);
686   //cout << "motif is: " << a_motif << endl;
687
688   if (a_motif != "")
689   {
690     //cout << "Sequence: none blank motif\n";
691     motif_scan(a_motif, &motif_match_starts);
692
693     a_motif_rc = rc_motif(a_motif);
694     // make sure not to do search again if it is a palindrome
695     if (a_motif_rc != a_motif)
696       motif_scan(a_motif_rc, &motif_match_starts);
697   }
698   return motif_match_starts;
699 }
700
701 void
702 Sequence::motif_scan(string a_motif, vector<int> * motif_match_starts)
703 {
704   char * seq_c;
705   string::size_type seq_i;
706   int motif_i, motif_len;
707
708   // faster to loop thru the sequence as a old c string (ie char array)
709   seq_c = (char*)sequence.c_str();
710   //cout << "Sequence: motif, seq len = " << sequence.length() << endl; 
711   motif_len = a_motif.length();
712
713   //cout << "motif_length: " << motif_len << endl;
714   //cout << "RAAARRRRR\n";
715
716   motif_i = 0;
717
718   //cout << "motif: " << a_motif << endl;
719
720   //cout << "Sequence: motif, length= " << length << endl;
721   seq_i = 0;
722   while (seq_i < sequence.length())
723   {
724     //cout << seq_c[seq_i];
725     //cout << seq_c[seq_i] << "?" << a_motif[motif_i] << ":" << motif_i << " ";
726     // this is pretty much a straight translation of Nora's python code
727     // to match iupac letter codes
728     if (a_motif[motif_i] =='N')
729       motif_i++;
730     else if (a_motif[motif_i] == seq_c[seq_i])
731       motif_i++;
732     else if ((a_motif[motif_i] =='M') && 
733              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C')))
734       motif_i++;
735     else if ((a_motif[motif_i] =='R') && 
736              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G')))
737       motif_i++;
738     else if ((a_motif[motif_i] =='W') && 
739              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='T')))
740       motif_i++;
741     else if ((a_motif[motif_i] =='S') && 
742              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G')))
743       motif_i++;
744     else if ((a_motif[motif_i] =='Y') && 
745              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='T')))
746       motif_i++;
747     else if ((a_motif[motif_i] =='K') && 
748              ((seq_c[seq_i]=='G') || (seq_c[seq_i]=='T')))
749       motif_i++;
750     else if ((a_motif[motif_i] =='V') && 
751              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
752               (seq_c[seq_i]=='G')))
753       motif_i++;
754     else if ((a_motif[seq_i] =='H') && 
755              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='C') ||
756               (seq_c[seq_i]=='T')))
757       motif_i++;
758     else if ((a_motif[motif_i] =='D') &&
759              ((seq_c[seq_i]=='A') || (seq_c[seq_i]=='G') ||
760               (seq_c[seq_i]=='T')))
761       motif_i++;
762     else if ((a_motif[motif_i] =='B') &&
763              ((seq_c[seq_i]=='C') || (seq_c[seq_i]=='G') ||
764               (seq_c[seq_i]=='T')))
765       motif_i++;
766
767     else
768     {
769       seq_i -= motif_i;
770       motif_i = 0;
771     }
772
773     // end Nora stuff, now we see if a match is found this pass
774     if (motif_i == motif_len)
775     {
776       //cout << "!!";
777       annot new_motif;
778       motif_match_starts->push_back(seq_i - motif_len + 1);
779       motif_i = 0;
780     }
781
782     seq_i++;
783   }
784   //cout << endl;
785 }
786