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