]> git.donarmstrong.com Git - mothur.git/blob - heatmapsimcommand.cpp
working on current change
[mothur.git] / heatmapsimcommand.cpp
1 /*
2  *  heatmapsimcommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 6/8/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "heatmapsimcommand.h"
11 #include "sharedjabund.h"
12 #include "sharedsorabund.h"
13 #include "sharedjclass.h"
14 #include "sharedsorclass.h"
15 #include "sharedjest.h"
16 #include "sharedsorest.h"
17 #include "sharedthetayc.h"
18 #include "sharedthetan.h"
19 #include "sharedmorisitahorn.h"
20 #include "sharedbraycurtis.h"
21
22
23 //**********************************************************************************************************************
24 vector<string> HeatMapSimCommand::setParameters(){      
25         try {
26                 CommandParameter pshared("shared", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "none",false,false); parameters.push_back(pshared);        
27                 CommandParameter pphylip("phylip", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "none",false,false); parameters.push_back(pphylip);
28                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "ColumnName",false,false); parameters.push_back(pname);
29                 CommandParameter pcolumn("column", "InputTypes", "", "", "PhylipColumnShared", "PhylipColumnShared", "ColumnName",false,false); parameters.push_back(pcolumn);          
30                 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
31                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
32                 CommandParameter pcalc("calc", "Multiple", "jabund-sorabund-jclass-sorclass-jest-sorest-thetayc-thetan-morisitahorn-braycurtis", "jest-thetayc", "", "", "",true,false); parameters.push_back(pcalc);
33                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
34                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
35                 
36                 vector<string> myArray;
37                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
38                 return myArray;
39         }
40         catch(exception& e) {
41                 m->errorOut(e, "HeatMapSimCommand", "setParameters");
42                 exit(1);
43         }
44 }
45 //**********************************************************************************************************************
46 string HeatMapSimCommand::getHelpString(){      
47         try {
48                 string helpString = "";
49                 ValidCalculators validCalculator;
50                 helpString += "The heatmap.sim command parameters are shared, phylip, column, name, groups, calc and label.  shared or phylip or column and name are required unless valid current files exist.\n";
51                 helpString += "There are two ways to use the heatmap.sim command. The first is with the read.otu command. \n";
52                 helpString += "With the read.otu command you may use the groups, label and calc parameters. \n";
53                 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included in your heatmap.\n";
54                 helpString += "The group names are separated by dashes. The label parameter allows you to select what distance levels you would like a heatmap created for, and is also separated by dashes.\n";
55                 helpString += "The heatmap.sim command should be in the following format: heatmap.sim(groups=yourGroups, calc=yourCalc, label=yourLabels).\n";
56                 helpString += "Example heatmap.sim(groups=A-B-C, calc=jabund).\n";
57                 helpString += "The default value for groups is all the groups in your groupfile, and all labels in your inputfile will be used.\n";
58                 helpString +=  validCalculator.printCalc("heat");
59                 helpString += "The default value for calc is jclass-thetayc.\n";
60                 helpString += "The heatmap.sim command outputs a .svg file for each calculator you choose at each label you specify.\n";
61                 helpString += "The second way to use the heatmap.sim command is with a distance file representing the distance bewteen your groups. \n";
62                 helpString += "Using the command this way, the phylip or column parameter are required, and only one may be used.  If you use a column file the name filename is required. \n";
63                 helpString += "The heatmap.sim command should be in the following format: heatmap.sim(phylip=yourDistanceFile).\n";
64                 helpString += "Example heatmap.sim(phylip=amazonGroups.dist).\n";
65                 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
66                 return helpString;
67         }
68         catch(exception& e) {
69                 m->errorOut(e, "HeatMapSimCommand", "getHelpString");
70                 exit(1);
71         }
72 }
73 //**********************************************************************************************************************
74 HeatMapSimCommand::HeatMapSimCommand(){ 
75         try {
76                 abort = true; calledHelp = true; 
77                 setParameters();
78                 vector<string> tempOutNames;
79                 outputTypes["svg"] = tempOutNames;
80         }
81         catch(exception& e) {
82                 m->errorOut(e, "HeatMapSimCommand", "HeatMapSimCommand");
83                 exit(1);
84         }
85 }
86 //**********************************************************************************************************************
87
88 HeatMapSimCommand::HeatMapSimCommand(string option)  {
89         try {
90                 abort = false; calledHelp = false;   
91                 allLines = 1;
92                         
93                 //allow user to run help
94                 if(option == "help") {  help(); abort = true; calledHelp = true; }
95                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
96                 
97                 else {
98                         vector<string> myArray = setParameters();
99                         
100                         OptionParser parser(option);
101                         map<string,string> parameters = parser.getParameters();
102                         
103                         ValidParameters validParameter;
104                         map<string,string>::iterator it;
105                         
106                         //check to make sure all parameters are valid for command
107                         for (it = parameters.begin(); it != parameters.end(); it++) { 
108                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
109                         }
110                         
111                         //initialize outputTypes
112                         vector<string> tempOutNames;
113                         outputTypes["svg"] = tempOutNames;
114                         
115                         format = "";
116                         //if the user changes the output directory command factory will send this info to us in the output parameter 
117                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
118                         
119                         //if the user changes the input directory command factory will send this info to us in the output parameter 
120                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
121                         if (inputDir == "not found"){   inputDir = "";          }
122                         else {
123                                 string path;
124                                 it = parameters.find("phylip");
125                                 //user has given a template file
126                                 if(it != parameters.end()){ 
127                                         path = m->hasPath(it->second);
128                                         //if the user has not given a path then, add inputdir. else leave path alone.
129                                         if (path == "") {       parameters["phylip"] = inputDir + it->second;           }
130                                 }
131                                 
132                                 it = parameters.find("column");
133                                 //user has given a template file
134                                 if(it != parameters.end()){ 
135                                         path = m->hasPath(it->second);
136                                         //if the user has not given a path then, add inputdir. else leave path alone.
137                                         if (path == "") {       parameters["column"] = inputDir + it->second;           }
138                                 }
139                                 
140                                 it = parameters.find("name");
141                                 //user has given a template file
142                                 if(it != parameters.end()){ 
143                                         path = m->hasPath(it->second);
144                                         //if the user has not given a path then, add inputdir. else leave path alone.
145                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
146                                 }
147                                 
148                                 it = parameters.find("shared");
149                                 //user has given a template file
150                                 if(it != parameters.end()){ 
151                                         path = m->hasPath(it->second);
152                                         //if the user has not given a path then, add inputdir. else leave path alone.
153                                         if (path == "") {       parameters["shared"] = inputDir + it->second;           }
154                                 }
155                         }
156
157                         //required parameters
158                         phylipfile = validParameter.validFile(parameters, "phylip", true);
159                         if (phylipfile == "not open") { abort = true; }
160                         else if (phylipfile == "not found") { phylipfile = ""; }        
161                         else {  format = "phylip";      inputfile = phylipfile; m-> setPhylipFile(phylipfile); if (outputDir == "") { outputDir += m->hasPath(phylipfile); }  }
162                         
163                         columnfile = validParameter.validFile(parameters, "column", true);
164                         if (columnfile == "not open") { abort = true; } 
165                         else if (columnfile == "not found") { columnfile = ""; }
166                         else {  format = "column";      inputfile = columnfile; m->setColumnFile(columnfile); if (outputDir == "") { outputDir += m->hasPath(columnfile); } }
167                         
168                         sharedfile = validParameter.validFile(parameters, "shared", true);
169                         if (sharedfile == "not open") { abort = true; } 
170                         else if (sharedfile == "not found") { sharedfile = ""; }
171                         else {  format = "shared";      inputfile = sharedfile; m->setSharedFile(sharedfile); if (outputDir == "") { outputDir += m->hasPath(sharedfile); } }
172                         
173                         namefile = validParameter.validFile(parameters, "name", true);
174                         if (namefile == "not open") { abort = true; }   
175                         else if (namefile == "not found") { namefile = ""; }
176                         else { m->setNameFile(namefile); }
177                         
178                         
179                         //error checking on files                       
180                         if ((sharedfile == "") && ((phylipfile == "") && (columnfile == "")))   { 
181                                 sharedfile = m->getSharedFile(); 
182                                 if (sharedfile != "") { format = "shared"; inputfile = sharedfile; m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
183                                 else { 
184                                         //is there are current file available for either of these?
185                                         //give priority to column, then phylip
186                                         columnfile = m->getColumnFile(); 
187                                         if (columnfile != "") {  format = "column"; inputfile = columnfile; m->mothurOut("Using " + columnfile + " as input file for the column parameter."); m->mothurOutEndLine(); }
188                                         else { 
189                                                 phylipfile = m->getPhylipFile(); 
190                                                 if (phylipfile != "") { format = "phylip";  inputfile = phylipfile; m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
191                                                 else { 
192                                                         m->mothurOut("No valid current files. You must provide a shared or phylip or column file."); m->mothurOutEndLine(); 
193                                                         abort = true;
194                                                 }
195                                         }
196                                 }
197                         }
198                         else if ((phylipfile != "") && (columnfile != "")) { m->mothurOut("When running the heatmap.sim command with a distance file you may not use both the column and the phylip parameters."); m->mothurOutEndLine(); abort = true; }
199                         
200                         if (columnfile != "") {
201                                 if (namefile == "") { 
202                                         namefile = m->getNameFile(); 
203                                         if (namefile != "") {  m->mothurOut("Using " + namefile + " as input file for the name parameter."); m->mothurOutEndLine(); }
204                                         else { 
205                                                 m->mothurOut("You need to provide a namefile if you are going to use the column format."); m->mothurOutEndLine(); 
206                                                 abort = true; 
207                                         }       
208                                 }
209                         }
210                         
211                         //check for optional parameter and set defaults
212                         // ...at some point should added some additional type checking...
213                                                         
214                         label = validParameter.validFile(parameters, "label", false);                   
215                         if (label == "not found") { label = ""; }
216                         else { 
217                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
218                                 else { allLines = 1;  }
219                         }
220                                 
221                         calc = validParameter.validFile(parameters, "calc", false);                     
222                         if (calc == "not found") { calc = "jest-thetayc";  }
223                         else { 
224                                 if (calc == "default")  {  calc = "jest-thetayc";  }
225                         }
226                         m->splitAtDash(calc, Estimators);
227                         if (m->inUsersGroups("citation", Estimators)) { 
228                                 ValidCalculators validCalc; validCalc.printCitations(Estimators); 
229                                 //remove citation from list of calcs
230                                 for (int i = 0; i < Estimators.size(); i++) { if (Estimators[i] == "citation") {  Estimators.erase(Estimators.begin()+i); break; } }
231                         }
232                                 
233                         groups = validParameter.validFile(parameters, "groups", false);                 
234                         if (groups == "not found") { groups = ""; }
235                         else { 
236                                 m->splitAtDash(groups, Groups);
237                                 m->Groups = Groups;
238                         }
239                         
240                         
241                         if (abort == false) {
242                                 ValidCalculators validCalculator;
243                         
244                                 int i;
245                                 for (i=0; i<Estimators.size(); i++) {
246                                         if (validCalculator.isValidCalculator("heat", Estimators[i]) == true) { 
247                                                 if (Estimators[i] == "jabund") {        
248                                                         heatCalculators.push_back(new JAbund());
249                                                 }else if (Estimators[i] == "sorabund") { 
250                                                         heatCalculators.push_back(new SorAbund());
251                                                 }else if (Estimators[i] == "jclass") { 
252                                                         heatCalculators.push_back(new Jclass());
253                                                 }else if (Estimators[i] == "sorclass") { 
254                                                         heatCalculators.push_back(new SorClass());
255                                                 }else if (Estimators[i] == "jest") { 
256                                                         heatCalculators.push_back(new Jest());
257                                                 }else if (Estimators[i] == "sorest") { 
258                                                         heatCalculators.push_back(new SorEst());
259                                                 }else if (Estimators[i] == "thetayc") { 
260                                                         heatCalculators.push_back(new ThetaYC());
261                                                 }else if (Estimators[i] == "thetan") { 
262                                                         heatCalculators.push_back(new ThetaN());
263                                                 }else if (Estimators[i] == "morisitahorn") { 
264                                                         heatCalculators.push_back(new MorHorn());
265                                                 }else if (Estimators[i] == "braycurtis") { 
266                                                         heatCalculators.push_back(new BrayCurtis());
267                                                 }
268                                         }
269                                 }
270                                 
271                         }
272                 }
273
274                                 
275
276         }
277         catch(exception& e) {
278                 m->errorOut(e, "HeatMapSimCommand", "HeatMapSimCommand");
279                 exit(1);
280         }
281 }
282 //**********************************************************************************************************************
283
284 int HeatMapSimCommand::execute(){
285         try {
286         
287                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
288                 
289                 heatmap = new HeatMapSim(outputDir, inputfile);
290                 
291                 if (format == "shared") {
292                         runCommandShared();
293                 }else{  runCommandDist();       }
294                 
295                 delete heatmap;
296                 
297                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        remove(outputNames[i].c_str());  } outputTypes.clear(); return 0; }
298                 
299                 m->mothurOutEndLine();
300                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
301                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
302                 m->mothurOutEndLine();
303                 
304                 return 0;
305         }
306         catch(exception& e) {
307                 m->errorOut(e, "HeatMapSimCommand", "execute");
308                 exit(1);
309         }
310 }
311
312 //**********************************************************************************************************************
313 int HeatMapSimCommand::runCommandShared() {
314         try {
315                 //if the users entered no valid calculators don't execute command
316                 if (heatCalculators.size() == 0) { m->mothurOut("No valid calculators."); m->mothurOutEndLine(); return 0; }
317                 
318                 input = new InputData(sharedfile, "sharedfile");
319                 lookup = input->getSharedRAbundVectors();
320                 string lastLabel = lookup[0]->getLabel();
321                         
322                 if (lookup.size() < 2) { m->mothurOut("You have not provided enough valid groups.  I cannot run the command."); m->mothurOutEndLine(); return 0;}
323                                 
324                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
325                 set<string> processedLabels;
326                 set<string> userLabels = labels;
327                 
328                 if (m->control_pressed) {  delete input;  for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }  m->Groups.clear(); return 0; }
329                 
330                 //as long as you are not at the end of the file or done wih the lines you want
331                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
332                         
333                         if (m->control_pressed) { delete input;  for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } m->Groups.clear(); return 0; }
334
335                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
336         
337                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
338                                 vector<string> outfilenames = heatmap->getPic(lookup, heatCalculators);
339                                 for(int i = 0; i < outfilenames.size(); i++) { outputNames.push_back(outfilenames[i]);  outputTypes["svg"].push_back(outfilenames[i]); }
340                                         
341                                 processedLabels.insert(lookup[0]->getLabel());
342                                 userLabels.erase(lookup[0]->getLabel());
343                         }
344                                 
345                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
346                                 string saveLabel = lookup[0]->getLabel();
347                         
348                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
349                                 lookup = input->getSharedRAbundVectors(lastLabel);                              
350
351                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
352                                 vector<string> outfilenames = heatmap->getPic(lookup, heatCalculators);
353                                 for(int i = 0; i < outfilenames.size(); i++) { outputNames.push_back(outfilenames[i]); outputTypes["svg"].push_back(outfilenames[i]);  }
354                                         
355                                 processedLabels.insert(lookup[0]->getLabel());
356                                 userLabels.erase(lookup[0]->getLabel());
357                                 
358                                 //restore real lastlabel to save below
359                                 lookup[0]->setLabel(saveLabel);
360                         }
361                                 
362                         //prevent memory leak
363                          
364                         lastLabel = lookup[0]->getLabel();                      
365
366                         //get next line to process
367                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
368                         lookup = input->getSharedRAbundVectors();
369
370                 }
371                 
372                         
373                 if (m->control_pressed) {  delete input;  m->Groups.clear();  return 0; }
374
375                 //output error messages about any remaining user labels
376                 set<string>::iterator it;
377                 bool needToRun = false;
378                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
379                         m->mothurOut("Your file does not include the label " + *it); 
380                         if (processedLabels.count(lastLabel) != 1) {
381                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
382                                 needToRun = true;
383                         }else {
384                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
385                         }
386                 }
387                 
388                 if (m->control_pressed) {  delete input;  m->Groups.clear(); return 0; }
389                 
390                 //run last label if you need to
391                 if (needToRun == true)  {
392                         for (int i = 0; i < lookup.size(); i++) {  if (lookup[i] != NULL) { delete lookup[i]; } } 
393                         lookup = input->getSharedRAbundVectors(lastLabel);                              
394
395                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
396                         vector<string> outfilenames = heatmap->getPic(lookup, heatCalculators);
397                         for(int i = 0; i < outfilenames.size(); i++) { outputNames.push_back(outfilenames[i]); outputTypes["svg"].push_back(outfilenames[i]);  }
398                         
399                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } 
400                 }
401                 
402                 if (m->control_pressed) {  delete input;  m->Groups.clear(); return 0; }
403                         
404                 //reset groups parameter
405                 m->Groups.clear();  
406                         
407                 delete input;  
408         
409                 return 0;
410         }
411         catch(exception& e) {
412                 m->errorOut(e, "HeatMapSimCommand", "runCommandShared");
413                 exit(1);
414         }
415 }
416 //**********************************************************************************************************************
417 int HeatMapSimCommand::runCommandDist() {
418         try {
419         
420                 vector< vector<double> > matrix;
421                 vector<string> names;
422                 ifstream in;
423                 
424                 //read distance file and create distance vector and names vector
425                 if (format == "phylip") {
426                         //read phylip file
427                         m->openInputFile(phylipfile, in);
428                         
429                         string name;
430                         int numSeqs;
431                         in >> numSeqs >> name; 
432                         
433                         //save name
434                         names.push_back(name);
435                 
436                         //resize the matrix and fill with zeros
437                         matrix.resize(numSeqs); 
438                         for(int i = 0; i < numSeqs; i++) {
439                                 matrix[i].resize(numSeqs, 0.0);
440                         }
441                                         
442                         //determine if matrix is square or lower triangle
443                         //if it is square read the distances for the first sequence
444                         char d;
445                         bool square;
446                         while((d=in.get()) != EOF){
447                                 
448                                 //is d a number meaning its square
449                                 if(isalnum(d)){ 
450                                         square = true;
451                                         in.putback(d);
452                                         
453                                         for(int i=0;i<numSeqs;i++){
454                                                 in >> matrix[0][i];
455                                         }
456                                         break;
457                                 }
458                                 
459                                 //is d a line return meaning its lower triangle
460                                 if(d == '\n'){
461                                         square = false;
462                                         break;
463                                 }
464                         }
465                         
466                         //read rest of matrix
467                         if (square == true) { 
468                                 for(int i=1;i<numSeqs;i++){
469                                         in >> name;             
470                                         names.push_back(name);
471                                         
472                                         if (m->control_pressed) { return 0; }
473                                         
474                                         for(int j=0;j<numSeqs;j++) { in >> matrix[i][j];  }
475                                         m->gobble(in);
476                                 }
477                         }else { 
478                                 double dist;
479                                 for(int i=1;i<numSeqs;i++){
480                                         in >> name;     
481                                         names.push_back(name);  
482                                         
483                                         if (m->control_pressed) { return 0; }
484                                         
485                                         for(int j=0;j<i;j++){
486                                                 in >> dist;
487                                                 matrix[i][j] = dist;  matrix[j][i] = dist;
488                                         }
489                                         m->gobble(in);
490                                 }
491                         }
492                         in.close();
493                 }else {
494                         //read names file
495                         NameAssignment* nameMap = new NameAssignment(namefile);
496                         nameMap->readMap();
497                         
498                         //put names in order in vector
499                         for (int i = 0; i < nameMap->size(); i++) {
500                                 names.push_back(nameMap->get(i));
501                         }
502                         
503                         //resize matrix
504                         matrix.resize(nameMap->size());
505                         for (int i = 0; i < nameMap->size(); i++) {
506                                 matrix[i].resize(nameMap->size(), 0.0);
507                         }
508                         
509                         //read column file
510                         string first, second;
511                         double dist;
512                         m->openInputFile(columnfile, in);
513                         
514                         while (!in.eof()) {
515                                 in >> first >> second >> dist; m->gobble(in);
516                                 
517                                 if (m->control_pressed) { return 0; }
518                                 
519                                 map<string, int>::iterator itA = nameMap->find(first);
520                                 map<string, int>::iterator itB = nameMap->find(second);
521                                 
522                                 if(itA == nameMap->end()){  m->mothurOut("AAError: Sequence '" + first + "' was not found in the names file, please correct\n"); exit(1);  }
523                                 if(itB == nameMap->end()){  m->mothurOut("ABError: Sequence '" + second + "' was not found in the names file, please correct\n"); exit(1);  }
524                                 
525                                 //save distance
526                                 matrix[itA->second][itB->second] = dist;
527                                 matrix[itB->second][itA->second] = dist;
528                         }
529                         in.close();
530                         
531                         delete nameMap;
532                 }
533                 
534                 
535                 string outputFileName = heatmap->getPic(matrix, names);
536                 outputNames.push_back(outputFileName); //vector<vector<double>>, vector<string>
537                 outputTypes["svg"].push_back(outputFileName);
538                 
539                 return 0;
540         }
541         catch(exception& e) {
542                 m->errorOut(e, "HeatMapSimCommand", "runCommandDist");
543                 exit(1);
544         }
545 }
546 //**********************************************************************************************************************
547
548
549
550
551
552