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