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