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