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