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