]> git.donarmstrong.com Git - mothur.git/blob - otuhierarchycommand.cpp
rewrote metastats command in c++, added mothurRemove function to handle ~ error....
[mothur.git] / otuhierarchycommand.cpp
1 /*
2  *  otuhierarchycommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 1/19/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "otuhierarchycommand.h"
11
12 //**********************************************************************************************************************
13 vector<string> OtuHierarchyCommand::setParameters(){    
14         try {
15                 CommandParameter poutput("output", "Multiple", "name-number", "name", "", "", "",false,false); parameters.push_back(poutput);
16                 CommandParameter plist("list", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(plist);
17                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
18                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
19                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
20                 
21                 vector<string> myArray;
22                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
23                 return myArray;
24         }
25         catch(exception& e) {
26                 m->errorOut(e, "OtuHierarchyCommand", "setParameters");
27                 exit(1);
28         }
29 }
30 //**********************************************************************************************************************
31 string OtuHierarchyCommand::getHelpString(){    
32         try {
33                 string helpString = "";
34                 helpString += "The otu.hierarchy command is used to see how otus relate at two distances. \n";
35                 helpString += "The otu.hierarchy command parameters are list, label and output.  list and label parameters are required. \n";
36                 helpString += "The output parameter allows you to output the names of the sequence in the OTUs or the OTU numbers. Options are name and number, default is name. \n";
37                 helpString += "The otu.hierarchy command should be in the following format: \n";
38                 helpString += "otu.hierarchy(list=yourListFile, label=yourLabels).\n";
39                 helpString += "Example otu.hierarchy(list=amazon.fn.list, label=0.01-0.03).\n";
40                 helpString += "The otu.hierarchy command outputs a .otu.hierarchy file which is described on the wiki.\n";
41                 helpString += "Note: No spaces between parameter labels (i.e. list), '=' and parameters (i.e.yourListFile).\n";
42                 return helpString;
43         }
44         catch(exception& e) {
45                 m->errorOut(e, "OtuHierarchyCommand", "getHelpString");
46                 exit(1);
47         }
48 }
49
50 //**********************************************************************************************************************
51 OtuHierarchyCommand::OtuHierarchyCommand(){     
52         try {
53                 abort = true; calledHelp = true; 
54                 setParameters();
55                 vector<string> tempOutNames;
56                 outputTypes["otuheirarchy"] = tempOutNames;
57         }
58         catch(exception& e) {
59                 m->errorOut(e, "OtuHierarchyCommand", "OtuHierarchyCommand");
60                 exit(1);
61         }
62 }
63 //**********************************************************************************************************************
64 OtuHierarchyCommand::OtuHierarchyCommand(string option) {
65         try {
66                 abort = false; calledHelp = false;   
67                 
68                 //allow user to run help
69                 if(option == "help") {  help(); abort = true; calledHelp = true; }
70                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
71                 
72                 else {
73                         vector<string> myArray = setParameters();
74                         
75                         OptionParser parser(option);
76                         map<string,string> parameters = parser.getParameters();
77                         
78                         ValidParameters validParameter;
79                         map<string,string>::iterator it;
80                 
81                         //check to make sure all parameters are valid for command
82                         for (it = parameters.begin(); it != parameters.end(); it++) { 
83                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
84                         }
85                         
86                         //initialize outputTypes
87                         vector<string> tempOutNames;
88                         outputTypes["otuheirarchy"] = tempOutNames;
89                         
90                         //if the user changes the input directory command factory will send this info to us in the output parameter 
91                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
92                         if (inputDir == "not found"){   inputDir = "";          }
93                         else {
94                                 string path;
95                                 it = parameters.find("list");
96                                 //user has given a template file
97                                 if(it != parameters.end()){ 
98                                         path = m->hasPath(it->second);
99                                         //if the user has not given a path then, add inputdir. else leave path alone.
100                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
101                                 }
102                         }
103
104                         listFile = validParameter.validFile(parameters, "list", true);
105                         if (listFile == "not found") { 
106                                 listFile = m->getListFile(); 
107                                 if (listFile != "") {  m->mothurOut("Using " + listFile + " as input file for the list parameter."); m->mothurOutEndLine(); }
108                                 else { 
109                                         m->mothurOut("No valid current list file. You must provide a list file."); m->mothurOutEndLine(); 
110                                         abort = true;
111                                 }
112                         }else if (listFile == "not open") { abort = true; }     
113                         else { m->setListFile(listFile); }
114                         
115                         //if the user changes the output directory command factory will send this info to us in the output parameter 
116                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
117                                 outputDir = ""; 
118                                 outputDir += m->hasPath(listFile); //if user entered a file with a path then preserve it        
119                         }
120                         
121                         //check for optional parameter and set defaults
122                         // ...at some point should added some additional type checking...
123                         label = validParameter.validFile(parameters, "label", false);                   
124                         if (label == "not found") { m->mothurOut("label is a required parameter for the otu.hierarchy command."); m->mothurOutEndLine(); abort = true; }
125                         else { 
126                                 m->splitAtDash(label, labels);
127                                 if (labels.size() != 2) { m->mothurOut("You must provide 2 labels."); m->mothurOutEndLine(); abort = true; }
128                         }       
129                         
130                         output = validParameter.validFile(parameters, "output", false);                 if (output == "not found") { output = "name"; }
131                         
132                         if ((output != "name") && (output != "number")) { m->mothurOut("output options are name and number. I will use name."); m->mothurOutEndLine(); output = "name"; }
133                 }
134                 
135         }
136         catch(exception& e) {
137                 m->errorOut(e, "OtuHierarchyCommand", "OtuHierarchyCommand");
138                 exit(1);
139         }                       
140 }
141 //**********************************************************************************************************************
142
143 int OtuHierarchyCommand::execute(){
144         try {
145                 
146                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
147                 
148                 //get listvectors that correspond to labels requested, (or use smart distancing to get closest listvector)
149                 vector<ListVector> lists = getListVectors();
150                 
151                 if (m->control_pressed) { outputTypes.clear(); return 0; }
152                 
153                 //determine which is little and which is big, putting little first
154                 if (lists.size() == 2) {
155                         //if big is first swap them
156                         if (lists[0].getNumBins() < lists[1].getNumBins()) {
157                                 reverse(lists.begin(), lists.end());
158                         }
159                 }else{
160                         m->mothurOut("error getting listvectors, unable to read 2 different vectors, check your label inputs."); m->mothurOutEndLine(); return 0;
161                 }
162                 
163                 //map sequences to bin number in the "little" otu
164                 map<string, int> littleBins; 
165                 for (int i = 0; i < lists[0].getNumBins(); i++) {
166                 
167                         if (m->control_pressed) {  return 0; }
168                         
169                         string names = lists[0].get(i); 
170                         
171                         //parse bin
172                         while (names.find_first_of(',') != -1) { 
173                                 string name = names.substr(0,names.find_first_of(','));
174                                 names = names.substr(names.find_first_of(',')+1, names.length());
175                                 littleBins[name] = i;  
176                         }
177                         
178                         //get last name
179                         littleBins[names] = i;
180                 }
181                 
182                 ofstream out;
183                 string outputFileName = outputDir + m->getRootName(m->getSimpleName(listFile)) + lists[0].getLabel() + "-" + lists[1].getLabel() + ".otu.hierarchy";
184                 m->openOutputFile(outputFileName, out);
185                 
186                 //go through each bin in "big" otu and output the bins in "little" otu which created it
187                 for (int i = 0; i < lists[1].getNumBins(); i++) {
188                 
189                         if (m->control_pressed) { outputTypes.clear(); out.close(); m->mothurRemove(outputFileName); return 0; }
190                         
191                         string names = lists[1].get(i);
192                         
193                         //output column 1
194                         if (output == "name")   {   out << names << '\t';       }
195                         else                                    {       out << i << '\t';               }
196                         
197                         map<int, int> bins; //bin numbers in little that are in this bin in big
198                         map<int, int>::iterator it;
199                         
200                         //parse bin
201                         while (names.find_first_of(',') != -1) { 
202                                 string name = names.substr(0,names.find_first_of(','));
203                                 names = names.substr(names.find_first_of(',')+1, names.length());
204                                 bins[littleBins[name]] = littleBins[name];  
205                         }
206                         
207                         //get last name
208                         bins[littleBins[names]] = littleBins[names]; 
209                         
210                         string col2 = "";
211                         for (it = bins.begin(); it != bins.end(); it++) {
212                                 if (output == "name")   {   col2 += lists[0].get(it->first) + "\t";     }
213                                 else                                    {       col2 += toString(it->first) + "\t";             }
214                         }
215                         
216                         //output column 2
217                         out << col2 << endl;
218                 }
219                 
220                 out.close();
221                 
222                 if (m->control_pressed) { outputTypes.clear(); m->mothurRemove(outputFileName); return 0; }
223                 
224                 m->mothurOutEndLine();
225                 m->mothurOut("Output File Name: "); m->mothurOutEndLine();
226                 m->mothurOut(outputFileName); m->mothurOutEndLine();    outputNames.push_back(outputFileName); outputTypes["otuheirarchy"].push_back(outputFileName); 
227                 m->mothurOutEndLine();
228                 
229                 return 0;
230         }
231         catch(exception& e) {
232                 m->errorOut(e, "OtuHierarchyCommand", "execute");
233                 exit(1);
234         }
235 }
236
237 //**********************************************************************************************************************
238 //returns a vector of listVectors where "little" vector is first
239 vector<ListVector> OtuHierarchyCommand::getListVectors() {
240         try {
241                 
242                 int pos; //to use in smart distancing, position of last read in file
243                 int lastPos;
244                 vector<ListVector> lists;
245                 
246                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
247                 set<string> processedLabels;
248                 set<string> userLabels = labels;
249
250                 //open file
251                 ifstream in;
252                 m->openInputFile(listFile, in);
253                 
254                 //get first list vector in file
255                 ListVector* list = NULL;
256                 string lastLabel = "";
257                 if (!in.eof())  {
258                         pos = in.tellg();
259                         lastPos = pos;
260                         list = new ListVector(in);  
261                         m->gobble(in);
262                         lastLabel = list->getLabel();
263                 }
264                 
265                 while ((list != NULL) && (userLabels.size() != 0)) {
266                 
267                         if (m->control_pressed) {  in.close(); delete list;  return lists; }
268                         
269                         //is this a listvector that we want?
270                         if(labels.count(list->getLabel()) == 1){
271                                 
272                                 //make copy of listvector
273                                 ListVector temp(*list);
274                                 lists.push_back(temp);
275                         
276                                 processedLabels.insert(list->getLabel());
277                                 userLabels.erase(list->getLabel());
278                         }
279                 
280                         //you have a label the user want that is smaller than this label and the last label has not already been processed 
281                         if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
282                                 string saveLabel = list->getLabel();
283                                 int savePos = in.tellg();
284                                 
285                                 //get smart distance line
286                                 delete list;
287                                 in.seekg(lastPos);
288                                 if (!in.eof())  {       
289                                         list = new ListVector(in);  
290                                 }else { list = NULL; }
291                                 
292                                 //make copy of listvector
293                                 ListVector temp(*list);
294                                 lists.push_back(temp);
295                                         
296                                 processedLabels.insert(list->getLabel());
297                                 userLabels.erase(list->getLabel());                                     
298                                                                                 
299                                 //restore real lastlabel to save below
300                                 list->setLabel(saveLabel);
301                                 in.seekg(savePos);
302                         }
303                         
304                         lastLabel = list->getLabel();
305                         lastPos = pos;
306                         
307                         //get next line
308                         delete list;
309                         if (!in.eof())  {       
310                                 pos = in.tellg();
311                                 list = new ListVector(in);  
312                                 m->gobble(in);
313                         }else { list = NULL; }
314                 }
315                 
316                 if (m->control_pressed) { in.close();  return lists; }                          
317                 
318                 //output error messages about any remaining user labels
319                 set<string>::iterator it;
320                 bool needToRun = false;
321                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
322                         m->mothurOut("Your file does not include the label " + *it); 
323                         if (processedLabels.count(lastLabel) != 1) {
324                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
325                                 needToRun = true;
326                         }else {
327                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
328                         }
329                 }
330                 
331                 if (m->control_pressed) {  in.close(); return lists; }
332                 
333                 //run last label if you need to
334                 if (needToRun == true)  {
335                         if (list != NULL) {     delete list;    }
336                         
337                         in.seekg(lastPos);
338                         if (!in.eof())  {       
339                                 list = new ListVector(in); 
340                                 
341                                 //make copy of listvector
342                                 ListVector temp(*list);
343                                 lists.push_back(temp);
344                                 
345                                 delete list;
346                         }
347                 }
348                 
349                 in.close();
350                 return lists;
351         }
352         catch(exception& e) {
353                 m->errorOut(e, "OtuHierarchyCommand", "getListVectors");
354                 exit(1);
355         }
356 }
357
358 //**********************************************************************************************************************
359
360
361
362
363