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