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