save motifs with the analysis
[mussa.git] / alg / mussa.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 //                        ----------------------------------------
12 //                          ---------- mussa_class.cc -----------
13 //                        ----------------------------------------
14
15 #include <boost/filesystem/path.hpp>
16 #include <boost/filesystem/operations.hpp>
17 #include <boost/filesystem/fstream.hpp>
18 namespace fs = boost::filesystem;
19
20 #include <boost/spirit/core.hpp>
21 #include <boost/spirit/actor/push_back_actor.hpp>
22 #include <boost/spirit/iterator/file_iterator.hpp>
23 #include <boost/spirit/utility/chset.hpp>
24 namespace spirit = boost::spirit;
25
26 #include <iostream>
27 #include <sstream>
28
29 #include "mussa_exceptions.hpp"
30 #include "alg/mussa.hpp"
31 #include "alg/flp.hpp"
32
33 using namespace std;
34
35
36 Mussa::Mussa()
37   : color_mapper(new AnnotationColors)
38 {
39   clear();
40   connect(&the_paths, SIGNAL(progress(const std::string&, int, int)), 
41           this, SIGNAL(progress(const std::string&, int, int)));
42 }
43
44 Mussa::Mussa(const Mussa& m)
45   : analysis_name(m.analysis_name),
46     window(m.window),
47     threshold(m.threshold),
48     soft_thres(m.soft_thres),
49     ana_mode(m.ana_mode),
50     win_append(m.win_append),
51     thres_append(m.thres_append),
52     motif_sequences(m.motif_sequences),
53     color_mapper(m.color_mapper),
54     analysis_path(m.analysis_path),
55     dirty(m.dirty)
56 {
57   connect(&the_paths, SIGNAL(progress(const std::string&, int, int)), 
58           this, SIGNAL(progress(const std::string&, int, int)));
59 }
60
61 boost::filesystem::path Mussa::get_analysis_path() const
62 {
63   return analysis_path;
64 }
65
66 void Mussa::set_analysis_path(boost::filesystem::path pathname)
67 {
68   analysis_path = pathname;
69 }
70
71 // set all parameters to null state
72 void
73 Mussa::clear()
74 {
75   analysis_name = "";
76   ana_mode = TransitiveNway;
77   window = 0;
78   threshold = 0;
79   soft_thres = 0;
80   win_append = false;
81   thres_append = false;
82   motif_sequences.clear();
83   if(color_mapper) color_mapper->clear();
84   the_seqs.clear();
85   the_paths.clear();
86   analysis_path = fs::path();
87   dirty = false;
88 }
89
90 bool Mussa::is_dirty() const
91 {
92   return dirty;
93 }
94
95 bool Mussa::empty() const
96 {
97   return the_seqs.empty();
98 }
99
100
101 // these 5 simple methods manually set the parameters for doing an analysis
102 // used so that the gui can take input from user and setup the analysis
103 // note - still need a set_append(bool, bool) method...
104 void
105 Mussa::set_name(string a_name)
106 {
107   analysis_name = a_name;
108   dirty = true;
109 }
110
111 string Mussa::get_name() const
112 {
113   return analysis_name;
114 }
115
116 string Mussa::get_title() const
117 {
118   fs::path analysis_path = get_analysis_path();
119   if (not analysis_path.empty()) {
120     return analysis_path.native_file_string();
121   } else if (get_name().size() > 0) {
122     return get_name();
123   } else {
124     return std::string("Unnamed");
125   }
126 }
127
128 int 
129 Mussa::size() const
130 {
131   if (the_seqs.size() > 0)
132     return the_seqs.size();
133   else
134     return 0;
135 }
136
137 void
138 Mussa::set_window(int a_window)
139 {
140   window = a_window;
141   dirty = true;
142 }
143
144 int Mussa::get_window() const
145 {
146   return window;
147 }
148
149 void
150 Mussa::set_threshold(int a_threshold)
151 {
152   threshold = a_threshold;
153   dirty = true;
154   if (a_threshold > soft_thres) {
155     soft_thres = a_threshold;
156   }
157 }
158
159 int Mussa::get_threshold() const
160 {
161   return threshold;
162 }
163
164 void
165 Mussa::set_soft_threshold(int new_threshold)
166 {
167   if (new_threshold < threshold) {
168     soft_thres = threshold;
169   } else if (new_threshold > window) {
170     soft_thres = window; 
171   } else {
172     soft_thres = new_threshold;
173   }
174 }
175
176 int Mussa::get_soft_threshold() const
177 {
178   return soft_thres;
179 }
180
181 void
182 Mussa::set_analysis_mode(enum analysis_modes new_ana_mode)
183 {
184   ana_mode = new_ana_mode;
185   dirty = true;
186 }
187
188 enum Mussa::analysis_modes Mussa::get_analysis_mode() const
189 {
190   return ana_mode;
191 }
192
193 string Mussa::get_analysis_mode_name() const
194 {
195   switch (ana_mode)
196   {
197   case TransitiveNway:
198     return string("Transitive");
199     break;
200   case RadialNway:
201     return string("Radial");
202     break;
203   case EntropyNway:
204     return string("Entropy");
205     break;
206   case RecursiveNway:
207     return string("[deprecated] Recursive");
208     break;
209   default:
210     throw runtime_error("invalid analysis mode type");
211     break;
212   }
213 }
214
215 const NwayPaths& Mussa::paths() const
216 {
217   return the_paths;
218 }
219
220 //template <class IteratorT>
221 //void Mussa::createLocalAlignment(IteratorT begin, IteratorT end)
222 void Mussa::createLocalAlignment(std::list<ConservedPath>::iterator begin, 
223                                  std::list<ConservedPath>::iterator end, 
224                                  std::list<ConservedPath::path_type>& result,
225                                  std::list<std::vector<bool> >& reversed)
226 {
227   const vector_sequence_type& raw_seq = the_seqs;
228   ConservedPath::path_type aligned_path;
229   size_t i2, i3;
230   int x_start, x_end;
231   int window_length, win_i;
232   int rc_1 = 0; 
233   int rc_2 = 0;
234   vector<bool> rc_list;
235   bool full_match;
236   vector<bool> matched;
237   int align_counter;
238
239   align_counter = 0;
240   for(std::list<ConservedPath>::iterator pathz_i=begin; pathz_i != end; ++pathz_i)
241   {
242     ConservedPath& a_path = *pathz_i;
243     window_length = a_path.window_size;
244     // determine which parts of the path are RC relative to first species
245     rc_list = a_path.reverseComplimented();
246     
247     // loop over each bp in the conserved region for all sequences
248     for(win_i = 0; win_i < window_length; win_i++)
249     {
250       aligned_path.clear();
251       // determine which exact base pairs match between the sequences
252       full_match = true;
253       for(i2 = 0; i2 < a_path.size()-1; i2++)
254       {
255         // assume not rc as most likely, adjust below
256         rc_1 = 0;
257         rc_2 = 0;
258         // no matter the case, any RC node needs adjustments
259         if (a_path[i2] < 0)
260           rc_1 = window_length-1;
261         if (a_path[i2+1] < 0)
262           rc_2 = window_length-1;        
263          
264         x_start = (abs(a_path[i2]-rc_1+win_i));
265         x_end =   (abs(a_path[i2+1]-rc_2+win_i));
266         
267         boost::shared_ptr<Sequence> cur(raw_seq[i2]) ;
268         boost::shared_ptr<Sequence> next(raw_seq[i2+1]);
269         // RC case handling
270         // ugh, and xor...only want rc coloring if just one of the nodes is rc
271         // if both nodes are rc, then they are 'normal' relative to each other
272         if((rc_list[i2] || rc_list[i2+1] )&&!(rc_list[i2] && rc_list[i2+1]))
273         { //the hideous rc matching logic - not complex, but annoying
274           if(!(( ((*cur)[x_start]=='A')&&((*next)[x_end]=='T')) ||
275                 (((*cur)[x_start]=='T')&&((*next)[x_end]=='A')) ||
276                 (((*cur)[x_start]=='G')&&((*next)[x_end]=='C')) ||
277                 (((*cur)[x_start]=='C')&&((*next)[x_end]=='G'))) ) 
278           {
279             full_match = false;
280           } else {
281             aligned_path.push_back(x_start);
282           }
283         }
284         else
285         { // forward match
286           if (!( ((*cur)[x_start] == (*next)[x_end]) &&
287                 ((*cur)[x_start] != 'N') && ((*next)[x_end] != 'N') ) ) {
288             full_match = false;
289           } else {
290             aligned_path.push_back(x_start);
291           }
292         }
293       }
294       // grab the last part of our path, assuming we matched
295       if (full_match)
296         aligned_path.push_back(x_end);
297
298       if (aligned_path.size() == a_path.size()) {
299         result.push_back(aligned_path);
300         reversed.push_back(rc_list);
301       }
302     }
303     align_counter++;
304   }
305 }
306
307
308 void Mussa::append_sequence(const Sequence& a_seq)
309 {
310   boost::shared_ptr<Sequence> seq_copy(new Sequence(a_seq));
311   the_seqs.push_back(seq_copy);
312   dirty = true;
313 }
314
315 void Mussa::append_sequence(boost::shared_ptr<Sequence> a_seq)
316 {
317   the_seqs.push_back(a_seq);
318   dirty = true;
319 }
320
321
322 const vector<boost::shared_ptr<Sequence> >& 
323 Mussa::sequences() const
324 {
325   return the_seqs;
326 }
327
328 void Mussa::load_sequence(fs::path seq_file, fs::path annot_file, 
329                           int fasta_index, int sub_seq_start, int sub_seq_end,
330                           std::string *name)
331 {
332   boost::shared_ptr<Sequence> aseq(new Sequence);
333   aseq->load_fasta(seq_file, fasta_index, sub_seq_start, sub_seq_end);
334   if ( not annot_file.empty() ) {
335     aseq->load_annot(annot_file, sub_seq_start, sub_seq_end);
336   }
337   if (name != 0 and name->size() > 0 ) {
338     aseq->set_species(*name);
339   }
340   the_seqs.push_back(aseq);
341   dirty = true;
342 }
343
344 void
345 Mussa::load_mupa_file(fs::path para_file_path)
346 {
347   fs::ifstream para_file;
348   string file_data_line;
349   string param, value; 
350   fs::path annot_file;
351   int split_index, fasta_index;
352   int sub_seq_start, sub_seq_end;
353   bool seq_params, did_seq;
354   string err_msg;
355   bool parsing_path;
356   string::size_type new_index, dir_index;
357
358   // initialize values
359   clear();
360
361   // if file was opened, read the parameter values
362   if (not fs::exists(para_file_path))
363   {
364     throw mussa_load_error("Config File: " + para_file_path.string() + " not found");
365   } else if (fs::is_directory(para_file_path)) {
366     throw mussa_load_error("Config File: " + para_file_path.string() + " is a directory.");
367   } else if (fs::is_empty(para_file_path)) {
368     throw mussa_load_error("Config File: " + para_file_path.string() + " is empty");
369   } else  {
370     para_file.open(para_file_path, ios::in);
371
372     // what directory is the mupa file in?
373     fs::path file_path_base = para_file_path.branch_path();
374
375     // setup loop by getting file's first line
376     getline(para_file,file_data_line);
377     split_index = file_data_line.find(" ");
378     param = file_data_line.substr(0,split_index);
379     value = file_data_line.substr(split_index+1);
380     
381     while (para_file)
382     {
383       did_seq = false;
384       if (param == "ANA_NAME")
385         analysis_name = value;
386       else if (param == "APPEND_WIN")
387         win_append = true;
388       else if (param == "APPEND_THRES")
389         thres_append = true;
390       else if (param == "SEQUENCE_NUM")
391         ; // ignore sequence_num now
392       else if (param == "WINDOW")
393         window = atoi(value.c_str());
394       else if (param == "THRESHOLD")
395         threshold = atoi(value.c_str());
396       else if (param == "SEQUENCE")
397       {
398         fs::path seq_file = file_path_base / value;
399         //cout << "seq_file_name " << seq_files.back() << endl;
400         fasta_index = 1;
401         annot_file = "";
402         sub_seq_start = 0;
403         sub_seq_end = 0;
404         seq_params = true;
405
406         while (para_file && seq_params)
407         {
408           getline(para_file,file_data_line);
409           split_index = file_data_line.find(" ");
410           param = file_data_line.substr(0,split_index);
411           value = file_data_line.substr(split_index+1);
412
413           if (param == "FASTA_INDEX")
414             fasta_index = atoi(value.c_str());
415           else if (param == "ANNOTATION")
416             annot_file = file_path_base / value;
417           else if (param == "SEQ_START")
418             sub_seq_start = atoi(value.c_str());
419           else if (param == "SEQ_END")
420           {
421             sub_seq_end = atoi(value.c_str());
422           }
423           //ignore empty lines or that start with '#'
424           else if ((param == "") || (param == "#")) {}
425           else seq_params = false;
426         }
427         load_sequence(seq_file, annot_file, fasta_index, sub_seq_start, 
428                       sub_seq_end);
429         did_seq = true;
430       }
431       //ignore empty lines or that start with '#'
432       else if ((param == "") || (param == "#")) {}
433       else
434       {
435         clog << "Illegal/misplaced mussa parameter in file\n";
436         clog << param << "\n";
437       }
438
439       if (!did_seq)
440       {
441         getline(para_file,file_data_line);
442         split_index = file_data_line.find(" ");
443         param = file_data_line.substr(0,split_index);
444         value = file_data_line.substr(split_index+1);
445         did_seq = false;
446       }
447     }
448
449     para_file.close();
450
451     soft_thres = threshold;
452     //cout << "nway mupa: analysis_name = " << analysis_name 
453     //     << " window = " << window 
454     //     << " threshold = " << threshold << endl;
455   }
456   // no file was loaded, signal error
457   dirty = true;
458 }
459
460
461 void
462 Mussa::analyze()
463 {
464   if (the_seqs.size() < 2) {
465     throw mussa_analysis_error("you need to have at least 2 sequences to "
466                                "do an analysis.");
467   }
468   //cout << "nway ana: seq_num = " << the_seqs.size() << endl;
469
470   seqcomp();
471   the_paths.setup(window, threshold);
472   nway();
473 }
474
475 void
476 Mussa::seqcomp()
477 {
478   vector<int> seq_lens;
479   vector<FLPs> empty_FLP_vector;
480   FLPs dummy_comp;
481   string save_file_string;
482
483   empty_FLP_vector.clear();
484   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
485   {
486     all_comps.push_back(empty_FLP_vector); 
487     for(vector<Sequence>::size_type i2 = 0; i2 < the_seqs.size(); i2++)
488       all_comps[i].push_back(dummy_comp);
489   }
490   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
491     seq_lens.push_back(the_seqs[i]->size());
492   }
493   int seqcomps_done = 0;
494   int seqcomps_todo = (the_seqs.size() * (the_seqs.size()-1)) / 2;
495   emit progress("seqcomp", seqcomps_done, seqcomps_todo);
496
497   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
498     for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
499     {
500       //cout << "seqcomping: " << i << " v. " << i2 << endl;
501       all_comps[i][i2].setup(window, threshold);
502       all_comps[i][i2].seqcomp(*the_seqs[i], *the_seqs[i2], false);
503       all_comps[i][i2].seqcomp(*the_seqs[i], the_seqs[i2]->rev_comp(),true);
504       ++seqcomps_done;
505       emit progress("seqcomp", seqcomps_done, seqcomps_todo);
506     }
507 }
508
509 void
510 Mussa::nway()
511 {
512
513   the_paths.set_soft_threshold(soft_thres);
514
515   if (ana_mode == TransitiveNway) {
516     the_paths.trans_path_search(all_comps);
517   }
518   else if (ana_mode == RadialNway) {
519     the_paths.radiate_path_search(all_comps);
520   }
521   else if (ana_mode == EntropyNway)
522   {
523     vector<Sequence> some_Seqs;
524     //unlike other methods, entropy needs to look at the sequence at this stage
525     some_Seqs.clear();
526     for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
527     {
528       some_Seqs.push_back(*the_seqs[i]);
529     }
530
531     the_paths.setup_ent(ent_thres, some_Seqs); // ent analysis extra setup
532     the_paths.entropy_path_search(all_comps);
533   }
534
535   // old recursive transitive analysis function
536   else if (ana_mode == RecursiveNway)
537     the_paths.find_paths_r(all_comps);
538
539   the_paths.simple_refine();
540 }
541
542 void
543 Mussa::save(fs::path save_path)
544 {
545   fs::path flp_filepath;
546   fs::fstream save_file;
547   ostringstream append_info;
548   int dir_create_status;
549
550   if (save_path.empty()) {
551     if (not analysis_path.empty()) {
552       save_path = analysis_path;
553     } else if (not analysis_name.empty()) {
554       std::string save_name = analysis_name;
555        // gotta do bit with adding win & thres if to be appended
556        if (win_append) {
557         append_info.str("");
558         append_info <<  "_w" << window;
559         save_name += append_info.str();
560       }
561
562       if (thres_append) {
563         append_info.str("");
564         append_info <<  "_t" << threshold;
565         save_name += append_info.str();
566       }
567       save_path = save_name;
568     } else {
569       throw mussa_save_error("Need filename or analysis name to save");
570     }
571   }
572
573   if (not fs::exists(save_path)) {
574     fs::create_directory(save_path);
575   }
576   // save sequence and annots to a special mussa file
577   save_file.open(save_path / (save_path.leaf()+".museq"), ios::out);
578   save_file << "<Mussa_Sequence>" << endl;
579
580   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
581   {
582     the_seqs[i]->save(save_file);
583   }
584
585   save_file << "</Mussa_Sequence>" << endl;
586   save_file.close();
587
588   // if we have any motifs, save them.
589   if (motif_sequences.size()) {
590     save_motifs(save_path/(save_path.leaf()+".mtl"));
591   }
592
593   // save nway paths to its mussa save file
594   the_paths.save(save_path / (save_path.leaf()+ ".muway"));
595
596   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++) {
597     for(vector<Sequence>::size_type i2 = i+1; i2 < the_seqs.size(); i2++)
598     {
599       append_info.str("");
600       append_info <<  "_sp_" << i << "v" << i2;
601       all_comps[i][i2].save(save_path/(save_path.leaf()+append_info.str()+".flp"));
602     }
603   }
604
605   dirty = false;
606   analysis_path = save_path;
607 }
608
609 void
610 Mussa::save_muway(fs::path save_path)
611 {
612   the_paths.save(save_path);
613 }
614
615 void
616 Mussa::load(fs::path ana_file)
617 {
618   int i, i2;
619   fs::path file_path_base;
620   fs::path a_file_path; 
621   fs::path ana_path(ana_file);
622   bool parsing_path;
623   string err_msg;
624   ostringstream append_info;
625   vector<FLPs> empty_FLP_vector;
626   FLPs dummy_comp;
627
628   analysis_path = ana_file;
629   analysis_name = ana_path.leaf();
630   file_path_base =  ana_path.branch_path() / analysis_name;
631   a_file_path = file_path_base / (analysis_name + ".muway");
632   the_paths.load(a_file_path);
633   // perhaps this could be more elegent, but at least this'll let
634   // us know what our threshold and window sizes were when we load a muway
635   window = the_paths.get_window();
636   threshold = the_paths.get_threshold();
637   soft_thres = threshold;
638
639   int seq_num = the_paths.sequence_count();
640
641   a_file_path = file_path_base / (analysis_name + ".museq");
642
643   // this is a bit of a hack due to C++ not acting like it should with files
644   for (i = 1; i <= seq_num; i++)
645   {
646     boost::shared_ptr<Sequence> tmp_seq(new Sequence);
647     tmp_seq->load_museq(a_file_path, i);
648     the_seqs.push_back(tmp_seq);
649   }
650   
651   fs::path motif_file = file_path_base / (analysis_name + ".mtl");
652   if (fs::exists(motif_file)) {
653     load_motifs(motif_file);
654   }
655   empty_FLP_vector.clear();
656   for(i = 0; i < seq_num; i++)
657   {
658     all_comps.push_back(empty_FLP_vector); 
659     for(i2 = 0; i2 < seq_num; i2++)
660       all_comps[i].push_back(dummy_comp);
661   }
662   
663   for(i = 0; i < seq_num; i++)
664   {
665     for(i2 = i+1; i2 < seq_num; i2++)
666     {
667       append_info.str("");
668       append_info << analysis_name <<  "_sp_" << i << "v" << i2 << ".flp";
669       //clog << append_info.str() << endl;
670       a_file_path = file_path_base / append_info.str();
671       //clog << "path " << a_file_path.string() << endl;
672       all_comps[i][i2].load(a_file_path);
673       //clog << "real size = " << all_comps[i][i2].size() << endl;
674     }
675   }
676 }
677
678
679 void
680 Mussa::save_old()
681 {
682   fs::fstream save_file;
683
684   save_file.open(analysis_name, ios::out);
685
686   for(vector<Sequence>::size_type i = 0; i < the_seqs.size(); i++)
687     save_file << *(the_seqs[i]) << endl;
688
689   save_file << window << endl;
690   save_file.close();
691   //note more complex eventually since analysis_name may need to have
692   //window size, threshold and other stuff to modify it...
693   the_paths.save_old(analysis_name);
694 }
695
696
697 void
698 Mussa::load_old(char * load_file_path, int s_num)
699 {
700   fstream save_file;
701   string file_data_line; 
702   int i, space_split_i, comma_split_i;
703   vector<int> loaded_path;
704   string node_pair, node;
705   Sequence a_seq;
706
707   int seq_num = s_num;
708   the_paths.setup(0, 0);
709   save_file.open(load_file_path, ios::in);
710
711   // currently loads old mussa format
712
713   // get sequences
714   for(i = 0; i < seq_num; i++)
715   {
716     getline(save_file, file_data_line);
717     boost::shared_ptr<Sequence> a_seq(new Sequence(file_data_line));
718     the_seqs.push_back(a_seq);
719   }
720
721   // get window size
722   getline(save_file, file_data_line);
723   window = atoi(file_data_line.c_str());
724   // get paths
725
726   while (!save_file.eof())
727   {
728     loaded_path.clear();
729     getline(save_file, file_data_line);
730     if (file_data_line != "")
731     for(i = 0; i < seq_num; i++)
732     {
733       space_split_i = file_data_line.find(" ");
734       node_pair = file_data_line.substr(0,space_split_i);
735       //cout << "np= " << node_pair;
736       comma_split_i = node_pair.find(",");
737       node = node_pair.substr(comma_split_i+1);
738       //cout << "n= " << node << " ";
739       loaded_path.push_back(atoi (node.c_str()));
740       file_data_line = file_data_line.substr(space_split_i+1);
741     }
742     //cout << endl;
743     // FIXME: do we have any information about what the threshold should be?
744     the_paths.add_path(0, loaded_path);
745   }
746   save_file.close();
747
748   //the_paths.save("tmp.save");
749 }
750
751 void Mussa::add_motif(const Sequence& motif, const Color& color)
752 {
753   motif_sequences.insert(motif);
754   color_mapper->appendInstanceColor("motif", motif.get_sequence(), color);
755 }
756
757 void Mussa::set_motifs(const vector<Sequence>& motifs, 
758                        const vector<Color>& colors)
759 {
760   if (motifs.size() != colors.size()) {
761     throw mussa_error("motif and color vectors must be the same size");
762   }
763
764   motif_sequences.clear();
765   for(size_t i = 0; i != motifs.size(); ++i)
766   {
767     add_motif(motifs[i], colors[i]);
768   }
769   update_sequences_motifs();
770 }
771
772 // Helper functor to append created motifs to our Mussa analysis
773 struct push_back_motif {
774   Mussa::motif_set& motifs;
775   boost::shared_ptr<AnnotationColors> color_mapper;
776   std::string& seq_string;
777   std::string& name;
778   float& red;
779   float& green;
780   float& blue;
781   float& alpha;
782   int& parsed;
783
784   push_back_motif(Mussa::motif_set& motifs_,
785                   boost::shared_ptr<AnnotationColors> color_mapper_,
786                   std::string& seq_, 
787                   std::string& name_,
788                   float &red_, float &green_, float &blue_, float &alpha_,
789                   int &parsed_)
790     : motifs(motifs_),
791       color_mapper(color_mapper_),
792       seq_string(seq_),
793       name(name_),
794       red(red_),
795       green(green_),
796       blue(blue_),
797       alpha(alpha_),
798       parsed(parsed_)
799   {
800   }
801
802   void operator()(std::string::const_iterator, 
803                   std::string::const_iterator) const 
804   {
805     Sequence seq(seq_string, Sequence::nucleic_alphabet);
806     // shouldn't we have a better field than "fasta header" and speices?
807     seq.set_fasta_header(name);
808     // we need to clear the name in case the next motif doesn't have one.
809     name.clear();
810     // be nice if glsequence was a subclass of sequence so we could
811     // just attach colors directly to the motif.
812     Color c(red, green, blue, alpha);
813     color_mapper->appendInstanceColor("motif", seq.c_str(), c);
814     alpha = 1.0;
815     motifs.insert(seq);
816     ++parsed;
817   };
818 };
819
820 void Mussa::load_motifs(fs::path filename)
821 {
822   fs::ifstream f;
823   f.open(filename, ifstream::in);
824   load_motifs(f);
825 }
826
827 // I mostly split the ifstream out so I can use a stringstream to test it.
828 void Mussa::load_motifs(std::istream &in)
829 {
830   std::string data;
831   const char *alphabet = Alphabet::nucleic_alphabet.c_str();
832   string seq;
833   string name;
834   float red = 1.0;
835   float green = 0.0;
836   float blue = 0.0;
837   float alpha = 1.0;
838   int parsed = 1;
839
840   // slurp our data into a string
841   std::streamsize bytes_read = 1;
842   while (in.good() and bytes_read) {
843     const std::streamsize bufsiz=512;
844     char buf[bufsiz];
845     bytes_read = in.readsome(buf, bufsiz);
846     data.append(buf, buf+bytes_read);
847   }
848   // parse our string
849   bool ok = spirit::parse(data.begin(), data.end(),
850      *(
851        ( 
852         (
853          (+spirit::chset<>(alphabet))[spirit::assign_a(seq)] >> 
854          +spirit::space_p
855         ) >>
856         !(
857           (
858             // names can either be letter followed by non-space characters
859             (spirit::alpha_p >> *spirit::graph_p)[spirit::assign_a(name)]
860             |
861             // or a quoted string
862             (
863              spirit::ch_p('"') >> 
864                (+(~spirit::ch_p('"')))[spirit::assign_a(name)] >>
865              spirit::ch_p('"')
866             )
867           ) >> +spirit::space_p
868         ) >>
869         spirit::real_p[spirit::assign_a(red)] >> +spirit::space_p >>
870         spirit::real_p[spirit::assign_a(green)] >> +spirit::space_p >>
871         spirit::real_p[spirit::assign_a(blue)] >> +spirit::space_p >>
872         !(spirit::real_p[spirit::assign_a(alpha)] >> +spirit::space_p)
873        )[push_back_motif(motif_sequences, color_mapper, seq, name, red, green, blue, alpha, parsed)]
874      )).full;
875   if (not ok) {
876     stringstream msg;
877     msg << "Error parsing motif #" << parsed;
878     // erase our potentially broken motif list
879     motif_sequences.clear();
880     throw motif_load_error(msg.str());
881   }
882   update_sequences_motifs();
883 }
884
885 void Mussa::save_motifs(fs::path filename)
886 {
887   fs::ofstream out_stream;
888   out_stream.open(filename, ofstream::out);
889   save_motifs(out_stream);
890 }
891
892 void Mussa::save_motifs(std::ostream& out)
893 {
894   for(motif_set::iterator motif_i = motif_sequences.begin();
895       motif_i != motif_sequences.end();
896       ++motif_i)
897   {
898     out << motif_i->get_sequence() << " ";
899     if (motif_i->get_name().size() > 0) {
900       out << "\"" << motif_i->get_name() << "\" ";
901     }
902     out << color_mapper->lookup("motif", motif_i->get_sequence());
903     out << std::endl;
904   }
905 }
906
907 void Mussa::update_sequences_motifs()
908 {
909   // once we've loaded all the motifs from the file, 
910   // lets attach them to the sequences
911   for(vector<boost::shared_ptr<Sequence> >::iterator seq_i = the_seqs.begin();
912       seq_i != the_seqs.end();
913       ++seq_i)
914   {
915     // clear out old motifs
916     (*seq_i)->clear_motifs();
917     // for all the motifs in our set, attach them to the current sequence
918     for(set<Sequence>::iterator motif_i = motif_sequences.begin();
919         motif_i != motif_sequences.end();
920         ++motif_i)
921     {
922       (*seq_i)->add_motif(*motif_i);
923     }
924   }
925 }
926
927 const set<Sequence>& Mussa::motifs() const
928 {
929   return motif_sequences;
930 }
931
932 boost::shared_ptr<AnnotationColors> Mussa::colorMapper()
933 {
934   return color_mapper;
935 }