]> git.donarmstrong.com Git - mothur.git/blob - getsharedotucommand.cpp
fixed unifrac bug with multiple processors if numComps was less than processors....
[mothur.git] / getsharedotucommand.cpp
1 /*
2  *  getsharedotucommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 9/22/09.
6  *  Copyright 2009 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "getsharedotucommand.h"
11
12
13 //**********************************************************************************************************************
14 vector<string> GetSharedOTUCommand::getValidParameters(){       
15         try {
16                 string Array[] =  {"label","unique","shared","fasta","list","group","output","outputdir","inputdir"};
17                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
18                 return myArray;
19         }
20         catch(exception& e) {
21                 m->errorOut(e, "GetSharedOTUCommand", "getValidParameters");
22                 exit(1);
23         }
24 }
25 //**********************************************************************************************************************
26 GetSharedOTUCommand::GetSharedOTUCommand(){     
27         try {
28                 abort = true; calledHelp = true; 
29                 vector<string> tempOutNames;
30                 outputTypes["fasta"] = tempOutNames;
31                 outputTypes["accnos"] = tempOutNames;
32                 outputTypes["sharedseqs"] = tempOutNames;
33         }
34         catch(exception& e) {
35                 m->errorOut(e, "GetSharedOTUCommand", "GetSharedOTUCommand");
36                 exit(1);
37         }
38 }
39 //**********************************************************************************************************************
40 vector<string> GetSharedOTUCommand::getRequiredParameters(){    
41         try {
42                 string Array[] =  {"list","group"};
43                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
44                 return myArray;
45         }
46         catch(exception& e) {
47                 m->errorOut(e, "GetSharedOTUCommand", "getRequiredParameters");
48                 exit(1);
49         }
50 }
51 //**********************************************************************************************************************
52 vector<string> GetSharedOTUCommand::getRequiredFiles(){ 
53         try {
54                 vector<string> myArray;
55                 return myArray;
56         }
57         catch(exception& e) {
58                 m->errorOut(e, "GetSharedOTUCommand", "getRequiredFiles");
59                 exit(1);
60         }
61 }
62 //**********************************************************************************************************************
63 GetSharedOTUCommand::GetSharedOTUCommand(string option)  {
64         try {
65         
66                 globaldata = GlobalData::getInstance();
67                 abort = false; calledHelp = false;   
68                 unique = true;
69                 allLines = 1;
70                 labels.clear();
71                 
72                 //allow user to run help
73                 if(option == "help") { help(); abort = true; calledHelp = true; }
74                 
75                 else {
76                         //valid paramters for this command
77                         string Array[] =  {"label","unique","shared","fasta","list","group","output","outputdir","inputdir"};
78                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
79                         
80                         OptionParser parser(option);
81                         map<string,string> parameters = parser.getParameters();
82                         
83                         ValidParameters validParameter;
84                         map<string,string>::iterator it;
85                         
86                         //check to make sure all parameters are valid for command
87                         for (it = parameters.begin(); it != parameters.end(); it++) { 
88                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
89                         }
90                         
91                         //initialize outputTypes
92                         vector<string> tempOutNames;
93                         outputTypes["fasta"] = tempOutNames;
94                         outputTypes["accnos"] = tempOutNames;
95                         outputTypes["sharedseqs"] = tempOutNames;
96                         
97                         //if the user changes the output directory command factory will send this info to us in the output parameter 
98                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
99                         
100                         //if the user changes the input directory command factory will send this info to us in the output parameter 
101                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
102                         if (inputDir == "not found"){   inputDir = "";          }
103                         else {
104                                 string path;
105                                 it = parameters.find("fasta");
106                                 //user has given a template file
107                                 if(it != parameters.end()){ 
108                                         path = m->hasPath(it->second);
109                                         //if the user has not given a path then, add inputdir. else leave path alone.
110                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
111                                 }
112                                 
113                                 it = parameters.find("list");
114                                 //user has given a template file
115                                 if(it != parameters.end()){ 
116                                         path = m->hasPath(it->second);
117                                         //if the user has not given a path then, add inputdir. else leave path alone.
118                                         if (path == "") {       parameters["list"] = inputDir + it->second;             }
119                                 }
120                                 
121                                 it = parameters.find("group");
122                                 //user has given a template file
123                                 if(it != parameters.end()){ 
124                                         path = m->hasPath(it->second);
125                                         //if the user has not given a path then, add inputdir. else leave path alone.
126                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
127                                 }
128                         }
129
130                         
131                         //check for required parameters
132                         listfile = validParameter.validFile(parameters, "list", true);
133                         if (listfile == "not open") { abort = true; }
134                         else if (listfile == "not found") { listfile = ""; }    
135                         else {  globaldata->setListFile(listfile);  globaldata->setFormat("list");      }
136                         
137                         groupfile = validParameter.validFile(parameters, "group", true);
138                         if (groupfile == "not open") { abort = true; }  
139                         else if (groupfile == "not found") { groupfile = ""; }
140                                                 
141                         if ((listfile == "") || (groupfile == "")) { m->mothurOut("The list and group parameters are required."); m->mothurOutEndLine(); abort = true; }
142                         
143                         //check for optional parameter and set defaults
144                         // ...at some point should added some additional type checking...
145                         label = validParameter.validFile(parameters, "label", false);                   
146                         if (label == "not found") { label = ""; }
147                         else { 
148                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
149                                 else { allLines = 1;  }
150                         }
151                         
152                         output = validParameter.validFile(parameters, "output", false);                 
153                         if (output == "not found") { output = ""; }
154                         
155                         groups = validParameter.validFile(parameters, "unique", false);                 
156                         if (groups == "not found") { groups = ""; }
157                         else { 
158                                 userGroups = "unique." + groups;
159                                 m->splitAtDash(groups, Groups);
160                                 globaldata->Groups = Groups;
161                                 
162                         }
163                         
164                         groups = validParameter.validFile(parameters, "shared", false);                 
165                         if (groups == "not found") { groups = "";  }
166                         else { 
167                                 userGroups = groups;
168                                 m->splitAtDash(groups, Groups);
169                                 globaldata->Groups = Groups;
170                                 unique = false;
171                         }
172                         
173                         fastafile = validParameter.validFile(parameters, "fasta", true);
174                         if (fastafile == "not open") { abort = true; }
175                         else if (fastafile == "not found") {  fastafile = "";  }        
176                                 
177                 }
178
179         }
180         catch(exception& e) {
181                 m->errorOut(e, "GetSharedOTUCommand", "GetSharedOTUCommand");
182                 exit(1);
183         }
184 }
185 //**********************************************************************************************************************
186
187 void GetSharedOTUCommand::help(){
188         try {
189                 m->mothurOut("The get.sharedseqs command parameters are list, group, label, unique, shared, output and fasta.  The list and group parameters are required.\n");
190                 m->mothurOut("The label parameter allows you to select what distance levels you would like output files for, and are separated by dashes.\n");
191                 m->mothurOut("The unique and shared parameters allow you to select groups you would like to know the shared info for, and are separated by dashes.\n");
192                 m->mothurOut("If you enter your groups under the unique parameter mothur will return the otus that contain ONLY sequences from those groups.\n");
193                 m->mothurOut("If you enter your groups under the shared parameter mothur will return the otus that contain sequences from those groups and may also contain sequences from other groups.\n");
194                 m->mothurOut("If you do not enter any groups then the get.sharedseqs command will return sequences that are unique to all groups in your group file.\n");
195                 m->mothurOut("The fasta parameter allows you to input a fasta file and outputs a fasta file for each distance level containing only the sequences that are in OTUs shared by the groups specified.\n");
196                 m->mothurOut("The output parameter allows you to output the list of names without the group and bin number added. \n");
197                 m->mothurOut("With this option you can use the names file as an input in get.seqs and remove.seqs commands. To do this enter output=accnos. \n");
198                 m->mothurOut("The get.sharedseqs command outputs a .names file for each distance level containing a list of sequences in the OTUs shared by the groups specified.\n");
199                 m->mothurOut("The get.sharedseqs command should be in the following format: get.sharedseqs(label=yourLabels, groups=yourGroups, fasta=yourFastafile, output=yourOutput).\n");
200                 m->mothurOut("Example get.sharedseqs(list=amazon.fn.list, label=unique-0.01, group=forest-pasture, fasta=amazon.fasta, output=accnos).\n");
201                 m->mothurOut("The output to the screen is the distance and the number of otus at that distance for the groups you specified.\n");
202                 m->mothurOut("The default value for label is all labels in your inputfile. The default for groups is all groups in your file.\n");
203                 m->mothurOut("Note: No spaces between parameter labels (i.e. label), '=' and parameters (i.e.yourLabel).\n\n");
204         }
205         catch(exception& e) {
206                 m->errorOut(e, "GetSharedOTUCommand", "help");
207                 exit(1);
208         }
209 }
210
211 //**********************************************************************************************************************
212
213 GetSharedOTUCommand::~GetSharedOTUCommand(){}
214
215 //**********************************************************************************************************************
216
217 int GetSharedOTUCommand::execute(){
218         try {
219                 
220                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
221                 
222                 groupMap = new GroupMap(groupfile);
223                 int error = groupMap->readMap();
224                 if (error == 1) { delete groupMap; return 0; }
225                 
226                 if (m->control_pressed) { delete groupMap; return 0; }
227                 
228                 globaldata->gGroupmap = groupMap;
229                 
230                 if (Groups.size() == 0) {
231                         Groups = groupMap->namesOfGroups;
232                         
233                         //make string for outputfile name
234                         userGroups = "unique.";
235                         for(int i = 0; i < Groups.size(); i++) {  userGroups += Groups[i] + "-";  }
236                         userGroups = userGroups.substr(0, userGroups.length()-1);
237                 }
238         
239                 //put groups in map to find easier
240                 for(int i = 0; i < Groups.size(); i++) {
241                         groupFinder[Groups[i]] = Groups[i];
242                 }
243                 
244                 if (fastafile != "") {
245                         ifstream inFasta;
246                         m->openInputFile(fastafile, inFasta);
247                         
248                         while(!inFasta.eof()) {
249                                 if (m->control_pressed) { outputTypes.clear(); inFasta.close(); delete groupMap; return 0; }
250                                 
251                                 Sequence seq(inFasta); m->gobble(inFasta);
252                                 if (seq.getName() != "") {  seqs.push_back(seq);   }
253                         }
254                         inFasta.close();
255                 }
256                 
257                 ListVector* lastlist = NULL;
258                 string lastLabel = "";
259                 
260                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
261                 set<string> processedLabels;
262                 set<string> userLabels = labels;
263                 
264                 ifstream in;
265                 m->openInputFile(listfile, in);
266                 
267                 //as long as you are not at the end of the file or done wih the lines you want
268                 while((!in.eof()) && ((allLines == 1) || (userLabels.size() != 0))) {
269                         
270                         if (m->control_pressed) { 
271                                 if (lastlist != NULL) {         delete lastlist;        }
272                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str()); }  outputTypes.clear();
273                                 delete groupMap; return 0;
274                         }
275                         
276                         list = new ListVector(in);
277                         
278                         if(allLines == 1 || labels.count(list->getLabel()) == 1){                       
279                                 m->mothurOut(list->getLabel()); 
280                                 process(list);
281                                 
282                                 processedLabels.insert(list->getLabel());
283                                 userLabels.erase(list->getLabel());
284                         }
285                         
286                         if ((m->anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
287                                         string saveLabel = list->getLabel();
288                                         
289                                         m->mothurOut(lastlist->getLabel()); 
290                                         process(lastlist);
291                                         
292                                         processedLabels.insert(lastlist->getLabel());
293                                         userLabels.erase(lastlist->getLabel());
294                                         
295                                         //restore real lastlabel to save below
296                                         list->setLabel(saveLabel);
297                         }
298
299                         lastLabel = list->getLabel();
300                         
301                         if (lastlist != NULL) {         delete lastlist;        }
302                         lastlist = list;                        
303                 }
304                 
305                 in.close();
306                 
307                 //output error messages about any remaining user labels
308                 set<string>::iterator it;
309                 bool needToRun = false;
310                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
311                         m->mothurOut("Your file does not include the label " + *it); 
312                         if (processedLabels.count(lastLabel) != 1) {
313                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
314                                 needToRun = true;
315                         }else {
316                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
317                         }
318                 }
319                 
320                 //run last label if you need to
321                 if (needToRun == true)  {
322                                 m->mothurOut(lastlist->getLabel()); 
323                                 process(lastlist);
324                                         
325                                 processedLabels.insert(lastlist->getLabel());
326                                 userLabels.erase(lastlist->getLabel());
327                 }
328                 
329
330                 //reset groups parameter
331                 globaldata->Groups.clear();  
332                 
333                 if (lastlist != NULL) {         delete lastlist;        }
334                 
335                 if (m->control_pressed) { outputTypes.clear(); for (int i = 0; i < outputNames.size(); i++) {   remove(outputNames[i].c_str()); }  delete groupMap; return 0; } 
336                 
337                 m->mothurOutEndLine();
338                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
339                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
340                 m->mothurOutEndLine();
341
342
343                 return 0;
344         }
345
346         catch(exception& e) {
347                 m->errorOut(e, "GetSharedOTUCommand", "execute");
348                 exit(1);
349         }
350 }
351 /***********************************************************/
352 int GetSharedOTUCommand::process(ListVector* shared) {
353         try {
354                 
355                 map<string, string> fastaMap;
356                 
357                 ofstream outNames;
358                 string outputFileNames;
359                 
360                 if (outputDir == "") { outputDir += m->hasPath(listfile); }
361                 if (output != "accnos") {
362                         outputFileNames = outputDir + m->getRootName(m->getSimpleName(listfile)) + shared->getLabel() + userGroups + ".shared.seqs";
363                 }else {
364                         outputFileNames = outputDir + m->getRootName(m->getSimpleName(listfile)) + shared->getLabel() + userGroups + ".accnos";
365                 }
366                 m->openOutputFile(outputFileNames, outNames);
367                 
368                 bool wroteSomething = false;
369                 int num = 0;
370                                 
371                 //go through each bin, find out if shared
372                 for (int i = 0; i < shared->getNumBins(); i++) {
373                         if (m->control_pressed) { outNames.close(); remove(outputFileNames.c_str()); return 0; }
374                         
375                         bool uniqueOTU = true;
376                         
377                         map<string, int> atLeastOne;
378                         for (int f = 0; f < Groups.size(); f++) {
379                                 atLeastOne[Groups[f]] = 0;
380                         }
381                         
382                         vector<string> namesOfSeqsInThisBin;
383                         
384                         string names = shared->get(i);  
385                         while ((names.find_first_of(',') != -1)) { 
386                                 string name = names.substr(0,names.find_first_of(','));
387                                 names = names.substr(names.find_first_of(',')+1, names.length());
388                                 
389                                 //find group
390                                 string seqGroup = groupMap->getGroup(name);
391                                 if (output != "accnos") {
392                                         namesOfSeqsInThisBin.push_back((name + "|" + seqGroup + "|" + toString(i+1)));
393                                 }else {  namesOfSeqsInThisBin.push_back(name);  }
394                                 
395                                 if (seqGroup == "not found") { m->mothurOut(name + " is not in your groupfile. Please correct."); m->mothurOutEndLine(); exit(1);  }
396                                 
397                                 //is this seq in one of hte groups we care about
398                                 it = groupFinder.find(seqGroup);
399                                 if (it == groupFinder.end()) {  uniqueOTU = false;  } //you have a sequence from a group you don't want
400                                 else {  atLeastOne[seqGroup]++;  }
401                         }
402                         
403                         //get last name
404                         string seqGroup = groupMap->getGroup(names);
405                         if (output != "accnos") {
406                                 namesOfSeqsInThisBin.push_back((names + "|" + seqGroup + "|" + toString(i+1)));
407                         }else {  namesOfSeqsInThisBin.push_back(names); }
408                         
409                         if (seqGroup == "not found") { m->mothurOut(names + " is not in your groupfile. Please correct."); m->mothurOutEndLine(); exit(1);  }
410                         
411                         //is this seq in one of hte groups we care about
412                         it = groupFinder.find(seqGroup);
413                         if (it == groupFinder.end()) {  uniqueOTU = false;  } //you have a sequence from a group you don't want
414                         else {  atLeastOne[seqGroup]++;  }
415                         
416                         
417                         //make sure you have at least one seq from each group you want
418                         bool sharedByAll = true;
419                         map<string, int>::iterator it2;
420                         for (it2 = atLeastOne.begin(); it2 != atLeastOne.end(); it2++) {
421                                 if (it2->second == 0) {  sharedByAll = false;   }
422                         }
423                         
424                         //if the user wants unique bins and this is unique then print
425                         //or this the user wants shared bins and this bin is shared then print
426                         if ((unique && uniqueOTU && sharedByAll) || (!unique && sharedByAll)) {
427                                 
428                                 wroteSomething = true;
429                                 num++;
430                                 
431                                 //output list of names 
432                                 for (int j = 0; j < namesOfSeqsInThisBin.size(); j++) {
433                                         outNames << namesOfSeqsInThisBin[j] << endl;
434                                         
435                                         if (fastafile != "") { 
436                                                 if (output != "accnos") {
437                                                         string seqName = namesOfSeqsInThisBin[j].substr(0,namesOfSeqsInThisBin[j].find_last_of('|'));
438                                                         seqName = seqName.substr(0,seqName.find_last_of('|'));
439                                                         fastaMap[seqName] = namesOfSeqsInThisBin[j];  //fastaMap needs to contain just the seq name for output later
440                                                 }else {
441                                                         fastaMap[namesOfSeqsInThisBin[j]] = namesOfSeqsInThisBin[j];
442                                                 }
443                                         }
444                                 }
445                         }
446                 }
447                 
448                 outNames.close();
449                 
450                 if (!wroteSomething) {
451                         remove(outputFileNames.c_str());
452                         string outputString = "\t" + toString(num) + " - No otus shared by groups";
453                         
454                         string groupString = "";
455                         for (int h = 0; h < Groups.size(); h++) {
456                                 groupString += "  " + Groups[h];
457                         }
458                         
459                         outputString += groupString + ".";
460                         m->mothurOut(outputString); m->mothurOutEndLine();
461                 }else { 
462                         m->mothurOut("\t" + toString(num)); m->mothurOutEndLine(); 
463                         outputNames.push_back(outputFileNames);
464                         if (output != "accnos") { outputTypes["sharedseqs"].push_back(outputFileNames); }
465                         else { outputTypes["accnos"].push_back(outputFileNames); }
466                 }
467                 
468                 //if fasta file provided output new fasta file
469                 if ((fastafile != "") && wroteSomething) {
470                         if (outputDir == "") { outputDir += m->hasPath(fastafile); }
471                         string outputFileFasta = outputDir + m->getRootName(m->getSimpleName(fastafile)) + shared->getLabel() + userGroups + ".shared.fasta";
472                         ofstream outFasta;
473                         m->openOutputFile(outputFileFasta, outFasta);
474                         outputNames.push_back(outputFileFasta); outputTypes["fasta"].push_back(outputFileFasta);
475                         
476                         for (int k = 0; k < seqs.size(); k++) {
477                                 if (m->control_pressed) { outFasta.close(); return 0; }
478                         
479                                 //if this is a sequence we want, output it
480                                 it = fastaMap.find(seqs[k].getName());
481                                 if (it != fastaMap.end()) {
482                                 
483                                         if (output != "accnos") {
484                                                 outFasta << ">" << it->second << endl;
485                                         }else {
486                                                 outFasta << ">" << it->first << endl;
487                                         }
488                                         
489                                         outFasta << seqs[k].getAligned() << endl;
490                                 }
491                         }
492                         
493                         outFasta.close();
494                 }
495                 
496                 return 0;
497                 
498         }
499         catch(exception& e) {
500                 m->errorOut(e, "GetSharedOTUCommand", "process");
501                 exit(1);
502         }
503 }
504
505 //**********************************************************************************************************************