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