]> git.donarmstrong.com Git - mothur.git/blob - getrelabundcommand.cpp
Merge remote-tracking branch 'mothur/master'
[mothur.git] / getrelabundcommand.cpp
1 /*
2  *  getrelabundcommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 6/21/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "getrelabundcommand.h"
11
12 //**********************************************************************************************************************
13 vector<string> GetRelAbundCommand::setParameters(){     
14         try {
15                 CommandParameter pshared("shared", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pshared);
16                 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
17                 CommandParameter pscale("scale", "Multiple", "totalgroup-totalotu-averagegroup-averageotu", "totalgroup", "", "", "",false,false); parameters.push_back(pscale);
18                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
19                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
20                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
21                 
22                 vector<string> myArray;
23                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
24                 return myArray;
25         }
26         catch(exception& e) {
27                 m->errorOut(e, "GetRelAbundCommand", "setParameters");
28                 exit(1);
29         }
30 }
31 //**********************************************************************************************************************
32 string GetRelAbundCommand::getHelpString(){     
33         try {
34                 string helpString = "";
35                 helpString += "The get.relabund command parameters are shared, groups, scale and label.  shared is required, unless you have a valid current file.\n";
36                 helpString += "The groups parameter allows you to specify which of the groups in your groupfile you would like included. The group names are separated by dashes.\n";
37                 helpString += "The label parameter allows you to select what distance levels you would like, and are also separated by dashes.\n";
38                 helpString += "The scale parameter allows you to select what scale you would like to use. Choices are totalgroup, totalotu, averagegroup, averageotu, default is totalgroup.\n";
39                 helpString += "The get.relabund command should be in the following format: get.relabund(groups=yourGroups, label=yourLabels).\n";
40                 helpString += "Example get.relabund(groups=A-B-C, scale=averagegroup).\n";
41                 helpString += "The default value for groups is all the groups in your groupfile, and all labels in your inputfile will be used.\n";
42                 helpString += "The get.relabund command outputs a .relabund file.\n";
43                 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
44                 return helpString;
45         }
46         catch(exception& e) {
47                 m->errorOut(e, "GetRelAbundCommand", "getHelpString");
48                 exit(1);
49         }
50 }
51 //**********************************************************************************************************************
52 string GetRelAbundCommand::getOutputFileNameTag(string type, string inputName=""){      
53         try {
54         string outputFileName = "";
55                 map<string, vector<string> >::iterator it;
56         
57         //is this a type this command creates
58         it = outputTypes.find(type);
59         if (it == outputTypes.end()) {  m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
60         else {
61             if (type == "relabund")         {   outputFileName = "relabund" ;  }
62             else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true;  }
63         }
64         return outputFileName;
65         }
66         catch(exception& e) {
67                 m->errorOut(e, "GetRelAbundCommand", "getOutputFileNameTag");
68                 exit(1);
69         }
70 }
71 //**********************************************************************************************************************
72 GetRelAbundCommand::GetRelAbundCommand(){       
73         try {
74                 abort = true; calledHelp = true; 
75                 setParameters();
76                 vector<string> tempOutNames;
77                 outputTypes["relabund"] = tempOutNames;
78         }
79         catch(exception& e) {
80                 m->errorOut(e, "GetRelAbundCommand", "GetRelAbundCommand");
81                 exit(1);
82         }
83 }
84 //**********************************************************************************************************************
85 GetRelAbundCommand::GetRelAbundCommand(string option) {
86         try {
87                 abort = false; calledHelp = false;   
88                 allLines = 1;
89                                 
90                 //allow user to run help
91                 if(option == "help") { help(); abort = true; calledHelp = true; }
92                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
93                 
94                 else {
95                         vector<string> myArray = setParameters();
96                         
97                         OptionParser parser(option);
98                         map<string,string> parameters = parser.getParameters();
99                         map<string,string>::iterator it;
100                         
101                         ValidParameters validParameter;
102                         
103                         //check to make sure all parameters are valid for command
104                         for (it = parameters.begin(); it != parameters.end(); it++) { 
105                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
106                         }
107                         
108                         //initialize outputTypes
109                         vector<string> tempOutNames;
110                         outputTypes["relabund"] = tempOutNames;
111                         
112                         //if the user changes the input directory command factory will send this info to us in the output parameter 
113                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
114                         if (inputDir == "not found"){   inputDir = "";          }
115                         else {
116                                 string path;
117                                 it = parameters.find("shared");
118                                 //user has given a template file
119                                 if(it != parameters.end()){ 
120                                         path = m->hasPath(it->second);
121                                         //if the user has not given a path then, add inputdir. else leave path alone.
122                                         if (path == "") {       parameters["shared"] = inputDir + it->second;           }
123                                 }
124                         }
125                 
126                         //get shared file
127                         sharedfile = validParameter.validFile(parameters, "shared", true);
128                         if (sharedfile == "not open") { sharedfile = ""; abort = true; }        
129                         else if (sharedfile == "not found") { 
130                                 //if there is a current shared file, use it
131                                 sharedfile = m->getSharedFile(); 
132                                 if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
133                                 else {  m->mothurOut("You have no current sharedfile and the shared parameter is required."); m->mothurOutEndLine(); abort = true; }
134                         }else { m->setSharedFile(sharedfile); }
135                         
136                         
137                         //if the user changes the output directory command factory will send this info to us in the output parameter 
138                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = m->hasPath(sharedfile);             }
139
140                         //check for optional parameter and set defaults
141                         // ...at some point should added some additional type checking...
142                         label = validParameter.validFile(parameters, "label", false);                   
143                         if (label == "not found") { label = ""; }
144                         else { 
145                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
146                                 else { allLines = 1;  }
147                         }
148                         
149                         groups = validParameter.validFile(parameters, "groups", false);                 
150                         if (groups == "not found") { groups = ""; pickedGroups = false; }
151                         else { 
152                                 pickedGroups = true;
153                                 m->splitAtDash(groups, Groups);
154                                 m->setGroups(Groups);
155                         }
156                         
157                         scale = validParameter.validFile(parameters, "scale", false);                           if (scale == "not found") { scale = "totalgroup"; }
158                         
159                         if ((scale != "totalgroup") && (scale != "totalotu") && (scale != "averagegroup") && (scale != "averageotu")) {
160                                 m->mothurOut(scale + " is not a valid scaling option for the get.relabund command. Choices are totalgroup, totalotu, averagegroup, averageotu."); m->mothurOutEndLine(); abort = true; 
161                         }
162                 }
163
164         }
165         catch(exception& e) {
166                 m->errorOut(e, "GetRelAbundCommand", "GetRelAbundCommand");
167                 exit(1);
168         }
169 }
170 //**********************************************************************************************************************
171
172 int GetRelAbundCommand::execute(){
173         try {
174         
175                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
176                 
177                 string outputFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + getOutputFileNameTag("relabund");
178                 ofstream out;
179                 m->openOutputFile(outputFileName, out);
180                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
181                 
182                 input = new InputData(sharedfile, "sharedfile");
183                 lookup = input->getSharedRAbundVectors();
184                 string lastLabel = lookup[0]->getLabel();
185                 
186                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
187                 set<string> processedLabels;
188                 set<string> userLabels = labels;
189
190                 //as long as you are not at the end of the file or done wih the lines you want
191                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
192                         
193                         if (m->control_pressed) {  outputTypes.clear();  for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } m->clearGroups(); delete input;  out.close(); m->mothurRemove(outputFileName); return 0; }
194         
195                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
196
197                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
198                                 if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
199                                 getRelAbundance(lookup, out);
200                                 
201                                 processedLabels.insert(lookup[0]->getLabel());
202                                 userLabels.erase(lookup[0]->getLabel());
203                         }
204                         
205                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
206                                 string saveLabel = lookup[0]->getLabel();
207                         
208                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }  
209                                 lookup = input->getSharedRAbundVectors(lastLabel);
210                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
211                                 if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
212                                 getRelAbundance(lookup, out);
213                                 
214                                 processedLabels.insert(lookup[0]->getLabel());
215                                 userLabels.erase(lookup[0]->getLabel());
216                                 
217                                 //restore real lastlabel to save below
218                                 lookup[0]->setLabel(saveLabel);
219                         }
220                         
221                         lastLabel = lookup[0]->getLabel();
222                         //prevent memory leak
223                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i]; lookup[i] = NULL; }
224                         
225                         if (m->control_pressed) {  outputTypes.clear();  m->clearGroups(); delete input;  out.close(); m->mothurRemove(outputFileName); return 0; }
226
227                         //get next line to process
228                         lookup = input->getSharedRAbundVectors();                               
229                 }
230                 
231                 if (m->control_pressed) { outputTypes.clear(); m->clearGroups(); delete input;  out.close(); m->mothurRemove(outputFileName);  return 0; }
232
233                 //output error messages about any remaining user labels
234                 set<string>::iterator it;
235                 bool needToRun = false;
236                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
237                         m->mothurOut("Your file does not include the label " + *it); 
238                         if (processedLabels.count(lastLabel) != 1) {
239                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
240                                 needToRun = true;
241                         }else {
242                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
243                         }
244                 }
245         
246                 //run last label if you need to
247                 if (needToRun == true)  {
248                         for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }  
249                         lookup = input->getSharedRAbundVectors(lastLabel);
250                         
251                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
252                         if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
253                         getRelAbundance(lookup, out);
254                         
255                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }
256                 }
257         
258                 //reset groups parameter
259                 m->clearGroups();  
260                 delete input; 
261                 out.close();
262                 
263                 if (m->control_pressed) { outputTypes.clear(); m->mothurRemove(outputFileName); return 0;}
264                 
265                 m->mothurOutEndLine();
266                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
267                 m->mothurOut(outputFileName); m->mothurOutEndLine(); outputNames.push_back(outputFileName); outputTypes["relabund"].push_back(outputFileName);
268                 m->mothurOutEndLine();
269                 
270                 //set relabund file as new current relabundfile
271                 string current = "";
272                 itTypes = outputTypes.find("relabund");
273                 if (itTypes != outputTypes.end()) {
274                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRelAbundFile(current); }
275                 }
276                 
277                 return 0;
278         }
279         catch(exception& e) {
280                 m->errorOut(e, "GetRelAbundCommand", "execute");
281                 exit(1);
282         }
283 }
284 //**********************************************************************************************************************
285
286 int GetRelAbundCommand::getRelAbundance(vector<SharedRAbundVector*>& thisLookUp, ofstream& out){
287         try {
288                 
289                  for (int i = 0; i < thisLookUp.size(); i++) {
290                         out << thisLookUp[i]->getLabel() << '\t' << thisLookUp[i]->getGroup() << '\t' << thisLookUp[i]->getNumBins() << '\t';
291                         
292                         for (int j = 0; j < thisLookUp[i]->getNumBins(); j++) {
293                         
294                                 if (m->control_pressed) { return 0; }
295                         
296                                 int abund = thisLookUp[i]->getAbundance(j);
297                                 
298                                 float relabund = 0.0;
299                                 
300                                 if (scale == "totalgroup") { 
301                                         relabund = abund / (float) thisLookUp[i]->getNumSeqs();
302                                 }else if (scale == "totalotu") {
303                                         //calc the total in this otu
304                                         int totalOtu = 0;
305                                         for (int l = 0; l < thisLookUp.size(); l++) {  totalOtu += thisLookUp[l]->getAbundance(j); }
306                                         relabund = abund / (float) totalOtu;
307                                 }else if (scale == "averagegroup") {
308                                         relabund = abund / (float) (thisLookUp[i]->getNumSeqs() / (float) thisLookUp[i]->getNumBins());
309                                 }else if (scale == "averageotu") {
310                                         //calc the total in this otu
311                                         int totalOtu = 0;
312                                         for (int l = 0; l < thisLookUp.size(); l++) {  totalOtu += thisLookUp[l]->getAbundance(j); }
313                                         float averageOtu = totalOtu / (float) thisLookUp.size();
314                                         
315                                         relabund = abund / (float) averageOtu;
316                                 }else{ m->mothurOut(scale + " is not a valid scaling option."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
317                                 
318                                 out << relabund << '\t';
319                         }
320                         out << endl;
321                  }
322         
323                  return 0;
324         }
325         catch(exception& e) {
326                 m->errorOut(e, "GetRelAbundCommand", "getRelAbundance");
327                 exit(1);
328         }
329 }
330 //**********************************************************************************************************************
331
332