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