]> git.donarmstrong.com Git - mothur.git/blob - mergegroupscommand.cpp
Merge remote-tracking branch 'mothur/master'
[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", "sharedGroup", "none",false,false); parameters.push_back(pshared);
17                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "sharedGroup", "none",false,false); parameters.push_back(pgroup);
18                 CommandParameter pdesign("design", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pdesign);
19                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
20                 CommandParameter pgroups("groups", "String", "", "", "", "", "",false,false); parameters.push_back(pgroups);
21                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
22                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
23                 
24                 vector<string> myArray;
25                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
26                 return myArray;
27         }
28         catch(exception& e) {
29                 m->errorOut(e, "MergeGroupsCommand", "setParameters");
30                 exit(1);
31         }
32 }
33 //**********************************************************************************************************************
34 string MergeGroupsCommand::getHelpString(){     
35         try {
36                 string helpString = "";
37                 helpString += "The merge.groups command reads a shared or group file and a design file and merges the groups that are in the same grouping in the design file.\n";
38                 helpString += "The merge.groups command outputs a .shared file. \n";
39                 helpString += "The merge.groups command parameters are shared, group, groups, label and design.  The design parameter is required.\n";
40                 helpString += "The design parameter allows you to assign your groups to sets. It is required. \n";
41                 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";
42                 helpString += "The groups parameter allows you to specify which of the groups in your shared or group file you would like included. The group names are separated by dashes.\n";
43                 helpString += "The label parameter allows you to select what distance levels you would like, and are also separated by dashes.\n";
44                 helpString += "The merge.groups command should be in the following format: merge.groups(design=yourDesignFile, shared=yourSharedFile).\n";
45                 helpString += "Example merge.groups(design=temp.design, groups=A-B-C, shared=temp.shared).\n";
46                 helpString += "The default value for groups is all the groups in your sharedfile, and all labels in your inputfile will be used.\n";
47                 helpString += "Note: No spaces between parameter labels (i.e. groups), '=' and parameters (i.e.yourGroups).\n";
48                 return helpString;
49         }
50         catch(exception& e) {
51                 m->errorOut(e, "MergeGroupsCommand", "getHelpString");
52                 exit(1);
53         }
54 }
55 //**********************************************************************************************************************
56 string MergeGroupsCommand::getOutputFileNameTag(string type, string inputName=""){      
57         try {
58         string outputFileName = "";
59                 map<string, vector<string> >::iterator it;
60         
61         //is this a type this command creates
62         it = outputTypes.find(type);
63         if (it == outputTypes.end()) {  m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
64         else {
65             if (type == "shared")        {   outputFileName = "merge" +  m->getExtension(inputName);       }
66             else if (type == "group")    {   outputFileName =   "merge" +  m->getExtension(inputName);     }
67             else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true;  }
68         }
69         return outputFileName;
70         }
71         catch(exception& e) {
72                 m->errorOut(e, "MergeGroupsCommand", "getOutputFileNameTag");
73                 exit(1);
74         }
75 }
76 //**********************************************************************************************************************
77 MergeGroupsCommand::MergeGroupsCommand(){       
78         try {
79                 abort = true; calledHelp = true; 
80                 setParameters();
81                 vector<string> tempOutNames;
82                 outputTypes["shared"] = tempOutNames;
83                 outputTypes["group"] = tempOutNames;
84         }
85         catch(exception& e) {
86                 m->errorOut(e, "MergeGroupsCommand", "MetaStatsCommand");
87                 exit(1);
88         }
89 }
90 //**********************************************************************************************************************
91
92 MergeGroupsCommand::MergeGroupsCommand(string option) {
93         try {
94                 abort = false; calledHelp = false;   
95                 allLines = 1;
96                 
97                 //allow user to run help
98                 if(option == "help") { help(); abort = true; calledHelp = true; }
99                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
100                 
101                 else {
102                         vector<string> myArray = setParameters();
103                         
104                         OptionParser parser(option);
105                         map<string,string> parameters = parser.getParameters();
106                         
107                         ValidParameters validParameter;
108                         
109                         //check to make sure all parameters are valid for command
110                         map<string,string>::iterator it;
111                         for (it = parameters.begin(); it != parameters.end(); it++) { 
112                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
113                         }
114                         
115                         //initialize outputTypes
116                         vector<string> tempOutNames;
117                         outputTypes["shared"] = tempOutNames;
118                         outputTypes["group"] = tempOutNames;
119                         
120                         //if the user changes the output directory command factory will send this info to us in the output parameter 
121                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
122                         
123                         //if the user changes the input directory command factory will send this info to us in the output parameter 
124                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
125                         if (inputDir == "not found"){   inputDir = "";          }
126                         else {
127                                 string path;
128                                 it = parameters.find("design");
129                                 //user has given a template file
130                                 if(it != parameters.end()){ 
131                                         path = m->hasPath(it->second);
132                                         //if the user has not given a path then, add inputdir. else leave path alone.
133                                         if (path == "") {       parameters["design"] = inputDir + it->second;           }
134                                 }
135                                 
136                                 it = parameters.find("shared");
137                                 //user has given a template file
138                                 if(it != parameters.end()){ 
139                                         path = m->hasPath(it->second);
140                                         //if the user has not given a path then, add inputdir. else leave path alone.
141                                         if (path == "") {       parameters["shared"] = inputDir + it->second;           }
142                                 }
143                                 
144                                 it = parameters.find("group");
145                                 //user has given a template file
146                                 if(it != parameters.end()){ 
147                                         path = m->hasPath(it->second);
148                                         //if the user has not given a path then, add inputdir. else leave path alone.
149                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
150                                 }
151                                 
152                         }
153                         
154                         //check for required parameters
155                         designfile = validParameter.validFile(parameters, "design", true);
156                         if (designfile == "not open") { abort = true; }
157                         else if (designfile == "not found") {                           
158                                 //if there is a current shared file, use it
159                                 designfile = m->getDesignFile(); 
160                                 if (designfile != "") { m->mothurOut("Using " + designfile + " as input file for the design parameter."); m->mothurOutEndLine(); }
161                                 else {  m->mothurOut("You have no current designfile and the design parameter is required."); m->mothurOutEndLine(); abort = true; }
162                         }else { m->setDesignFile(designfile); } 
163                         
164                         sharedfile = validParameter.validFile(parameters, "shared", true);
165                         if (sharedfile == "not open") { abort = true; sharedfile = ""; }
166                         else if (sharedfile == "not found") {  sharedfile = ""; }
167                         else { m->setSharedFile(sharedfile); }  
168                         
169                         groupfile = validParameter.validFile(parameters, "group", true);
170                         if (groupfile == "not open") { abort = true; groupfile = ""; }
171                         else if (groupfile == "not found") {  groupfile = ""; }
172                         else { m->setGroupFile(groupfile); }    
173                         
174                         //check for optional parameter and set defaults
175                         // ...at some point should added some additional type checking...
176                         label = validParameter.validFile(parameters, "label", false);                   
177                         if (label == "not found") { label = ""; }
178                         else { 
179                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
180                                 else { allLines = 1;  }
181                         }
182                         
183                         groups = validParameter.validFile(parameters, "groups", false);                 
184                         if (groups == "not found") { groups = "all";  }
185                         m->splitAtDash(groups, Groups);
186                         m->setGroups(Groups);
187                         
188                         if ((sharedfile == "") && (groupfile == "")) { 
189                                 //give priority to group, then shared
190                                 groupfile = m->getGroupFile(); 
191                                 if (groupfile != "") {  m->mothurOut("Using " + groupfile + " as input file for the group parameter."); m->mothurOutEndLine(); }
192                                 else { 
193                                         sharedfile = m->getSharedFile(); 
194                                         if (sharedfile != "") { m->mothurOut("Using " + sharedfile + " as input file for the shared parameter."); m->mothurOutEndLine(); }
195                                         else { 
196                                                 m->mothurOut("You have no current groupfile or sharedfile and one is required."); m->mothurOutEndLine(); abort = true;
197                                         }
198                                 }
199                         }
200                 }
201                 
202         }
203         catch(exception& e) {
204                 m->errorOut(e, "MergeGroupsCommand", "MergeGroupsCommand");
205                 exit(1);
206         }
207 }
208 //**********************************************************************************************************************
209
210 int MergeGroupsCommand::execute(){
211         try {
212                 
213                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
214         
215                 designMap = new GroupMap(designfile);
216                 designMap->readDesignMap();
217                 
218                 if (groupfile != "") { processGroupFile(designMap); }
219                 if (sharedfile != "") { processSharedFile(designMap); }
220
221                 //reset groups parameter
222                 m->clearGroups();  
223                 delete designMap;
224                 
225                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]); } return 0;}
226                 
227                 
228                 //set shared file as new current sharedfile
229                 string current = "";
230                 itTypes = outputTypes.find("shared");
231                 if (itTypes != outputTypes.end()) {
232                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSharedFile(current); }
233                 }
234                 
235                 itTypes = outputTypes.find("group");
236                 if (itTypes != outputTypes.end()) {
237                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
238                 }
239                 
240                 m->mothurOutEndLine();
241                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
242                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
243                 m->mothurOutEndLine();
244                 
245                 return 0;
246         }
247         catch(exception& e) {
248                 m->errorOut(e, "MergeGroupsCommand", "execute");
249                 exit(1);
250         }
251 }
252 //**********************************************************************************************************************
253
254 int MergeGroupsCommand::process(vector<SharedRAbundVector*>& thisLookUp, ofstream& out){
255         try {
256                 
257                 map<string, SharedRAbundVector> merged;
258                 map<string, SharedRAbundVector>::iterator it;
259                 
260                 for (int i = 0; i < thisLookUp.size(); i++) {
261                         
262                         if (m->control_pressed) { return 0; }
263                         
264                         //what grouping does this group belong to
265                         string grouping = designMap->getGroup(thisLookUp[i]->getGroup());
266                         if (grouping == "not found") { m->mothurOut("[ERROR]: " + thisLookUp[i]->getGroup() + " is not in your design file. Ignoring!"); m->mothurOutEndLine(); grouping = "NOTFOUND"; }
267                         
268                         else {
269                                 //do we already have a member of this grouping?
270                                 it = merged.find(grouping);
271                                 
272                                 if (it == merged.end()) { //nope, so create it
273                                         merged[grouping] = *thisLookUp[i];
274                                         merged[grouping].setGroup(grouping);
275                                 }else { //yes, merge it
276                                         
277                                         for (int j = 0; j < thisLookUp[i]->getNumBins(); j++) {
278                                                 int abund = (it->second).getAbundance(j);
279                                                 abund += thisLookUp[i]->getAbundance(j);
280                                                 
281                                                 (it->second).set(j, abund, grouping);
282                                         }
283                                 }
284                         }
285                 }
286                 
287                 //print new file
288                 for (it = merged.begin(); it != merged.end(); it++) {
289                         out << (it->second).getLabel() << '\t' << it->first << '\t';
290                         (it->second).print(out);
291                 }
292                 
293                 return 0;
294                 
295         }
296         catch(exception& e) {
297                 m->errorOut(e, "MergeGroupsCommand", "process");
298                 exit(1);
299         }
300 }
301 //**********************************************************************************************************************
302
303 int MergeGroupsCommand::processSharedFile(GroupMap*& designMap){
304         try {
305                 
306                 string thisOutputDir = outputDir;
307                 if (outputDir == "") {  thisOutputDir += m->hasPath(sharedfile);  }
308                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(sharedfile)) + getOutputFileNameTag("shared", sharedfile);
309         outputTypes["shared"].push_back(outputFileName); outputNames.push_back(outputFileName);
310                 
311                 ofstream out;
312                 m->openOutputFile(outputFileName, out);
313                 
314                 InputData input(sharedfile, "sharedfile");
315                 lookup = input.getSharedRAbundVectors();
316                 string lastLabel = lookup[0]->getLabel();
317                 
318                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
319                 set<string> processedLabels;
320                 set<string> userLabels = labels;
321                 
322                 //as long as you are not at the end of the file or done wih the lines you want
323                 while((lookup[0] != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
324                         
325                         if (m->control_pressed) {  out.close(); for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  } m->clearGroups();  delete designMap;  for (int i = 0; i < outputNames.size(); i++) {    m->mothurRemove(outputNames[i]); } return 0; }
326                         
327                         if(allLines == 1 || labels.count(lookup[0]->getLabel()) == 1){                  
328                                 
329                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
330                                 
331                                 if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
332                                 process(lookup, out);
333                                 
334                                 processedLabels.insert(lookup[0]->getLabel());
335                                 userLabels.erase(lookup[0]->getLabel());
336                         }
337                         
338                         if ((m->anyLabelsToProcess(lookup[0]->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
339                                 string saveLabel = lookup[0]->getLabel();
340                                 
341                                 for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }  
342                                 lookup = input.getSharedRAbundVectors(lastLabel);
343                                 m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
344                                 
345                                 if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
346                                 process(lookup, out);
347                                 
348                                 processedLabels.insert(lookup[0]->getLabel());
349                                 userLabels.erase(lookup[0]->getLabel());
350                                 
351                                 //restore real lastlabel to save below
352                                 lookup[0]->setLabel(saveLabel);
353                         }
354                         
355                         lastLabel = lookup[0]->getLabel();
356                         //prevent memory leak
357                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i]; lookup[i] = NULL; }
358                         
359                         if (m->control_pressed) {  out.close(); m->clearGroups();   delete designMap;  for (int i = 0; i < outputNames.size(); i++) {   m->mothurRemove(outputNames[i]); } return 0; }
360                         
361                         //get next line to process
362                         lookup = input.getSharedRAbundVectors();                                
363                 }
364                 
365                 if (m->control_pressed) { out.close(); m->clearGroups();  delete designMap;  for (int i = 0; i < outputNames.size(); i++) {     m->mothurRemove(outputNames[i]); }  return 0; }
366                 
367                 //output error messages about any remaining user labels
368                 set<string>::iterator it;
369                 bool needToRun = false;
370                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
371                         m->mothurOut("Your file does not include the label " + *it); 
372                         if (processedLabels.count(lastLabel) != 1) {
373                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
374                                 needToRun = true;
375                         }else {
376                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
377                         }
378                 }
379                 
380                 //run last label if you need to
381                 if (needToRun == true)  {
382                         for (int i = 0; i < lookup.size(); i++) { if (lookup[i] != NULL) { delete lookup[i]; } }  
383                         lookup = input.getSharedRAbundVectors(lastLabel);
384                         
385                         m->mothurOut(lookup[0]->getLabel()); m->mothurOutEndLine();
386                         
387                         if (!m->printedHeaders) { lookup[0]->printHeaders(out); }
388                         process(lookup, out);
389                         
390                         for (int i = 0; i < lookup.size(); i++) {  delete lookup[i];  }
391                 }
392                 
393                 out.close();
394                 
395                                 
396                 return 0;
397                 
398         }
399         catch(exception& e) {
400                 m->errorOut(e, "MergeGroupsCommand", "processSharedFile");
401                 exit(1);
402         }
403 }
404 //**********************************************************************************************************************
405
406 int MergeGroupsCommand::processGroupFile(GroupMap*& designMap){
407         try {
408                 
409                 string thisOutputDir = outputDir;
410                 if (outputDir == "") {  thisOutputDir += m->hasPath(groupfile);  }
411                 string outputFileName = thisOutputDir + m->getRootName(m->getSimpleName(groupfile)) + getOutputFileNameTag("group", groupfile);
412                 outputTypes["group"].push_back(outputFileName); outputNames.push_back(outputFileName);
413                 
414                 ofstream out;
415                 m->openOutputFile(outputFileName, out);
416                 
417                 //read groupfile
418                 GroupMap groupMap(groupfile);
419                 groupMap.readMap();
420                 
421                 //fill Groups - checks for "all" and for any typo groups
422                 SharedUtil* util = new SharedUtil();
423                 vector<string> nameGroups = groupMap.getNamesOfGroups();
424                 util->setGroups(Groups, nameGroups);
425                 delete util;
426                 
427                 vector<string> namesOfSeqs = groupMap.getNamesSeqs();
428                 bool error = false;
429                 
430                 for (int i = 0; i < namesOfSeqs.size(); i++) {
431                         
432                         if (m->control_pressed) { break; }
433                         
434                         string thisGroup = groupMap.getGroup(namesOfSeqs[i]);
435                         
436                         //are you in a group the user wants
437                         if (m->inUsersGroups(thisGroup, Groups)) {
438                                 string thisGrouping = designMap->getGroup(thisGroup);
439                                 
440                                 if (thisGrouping == "not found") { m->mothurOut("[ERROR]: " + namesOfSeqs[i] + " is from group " + thisGroup + " which is not in your design file, please correct."); m->mothurOutEndLine();  error = true; }
441                                 else {
442                                         out << namesOfSeqs[i] << '\t' << thisGrouping << endl;
443                                 }
444                         }
445                 }
446                 
447                 if (error) { m->control_pressed = true; }
448
449                 out.close();
450                 
451                 return 0;
452                 
453         }
454         catch(exception& e) {
455                 m->errorOut(e, "MergeGroupsCommand", "processGroupFile");
456                 exit(1);
457         }
458 }
459 //**********************************************************************************************************************
460
461
462