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