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