]> git.donarmstrong.com Git - mothur.git/blob - getsharedotucommand.cpp
created mothurOut class to handle logfiles
[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 = 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 = 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 = 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") {  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                                 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                                 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                 globaldata->gGroupmap = groupMap;
172                 
173                 if (Groups.size() == 0) {
174                         Groups = groupMap->namesOfGroups;
175                         
176                         //make string for outputfile name
177                         userGroups = "unique.";
178                         for(int i = 0; i < Groups.size(); i++) {  userGroups += Groups[i] + "-";  }
179                         userGroups = userGroups.substr(0, userGroups.length()-1);
180                 }
181         
182                 //put groups in map to find easier
183                 for(int i = 0; i < Groups.size(); i++) {
184                         groupFinder[Groups[i]] = Groups[i];
185                 }
186                 
187                 if (fastafile != "") {
188                         ifstream inFasta;
189                         openInputFile(fastafile, inFasta);
190                         
191                         while(!inFasta.eof()) {
192                                 Sequence seq(inFasta); gobble(inFasta);
193                                 if (seq.getName() != "") {  seqs.push_back(seq);   }
194                         }
195                         inFasta.close();
196                 }
197                 
198                 ListVector* lastlist = NULL;
199                 string lastLabel = "";
200                 
201                 //if the users enters label "0.06" and there is no "0.06" in their file use the next lowest label.
202                 set<string> processedLabels;
203                 set<string> userLabels = labels;
204                 
205                 ifstream in;
206                 openInputFile(listfile, in);
207                 
208                 //as long as you are not at the end of the file or done wih the lines you want
209                 while((!in.eof()) && ((allLines == 1) || (userLabels.size() != 0))) {
210                         
211                         list = new ListVector(in);
212                         
213                         if(allLines == 1 || labels.count(list->getLabel()) == 1){                       
214                                 m->mothurOut(list->getLabel()); 
215                                 process(list);
216                                 
217                                 processedLabels.insert(list->getLabel());
218                                 userLabels.erase(list->getLabel());
219                         }
220                         
221                         if ((anyLabelsToProcess(list->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
222                                         string saveLabel = list->getLabel();
223                                         
224                                         m->mothurOut(lastlist->getLabel()); 
225                                         process(lastlist);
226                                         
227                                         processedLabels.insert(lastlist->getLabel());
228                                         userLabels.erase(lastlist->getLabel());
229                                         
230                                         //restore real lastlabel to save below
231                                         list->setLabel(saveLabel);
232                         }
233
234                         lastLabel = list->getLabel();
235                         
236                         if (lastlist != NULL) {         delete lastlist;        }
237                         lastlist = list;                        
238                 }
239                 
240                 in.close();
241                 
242                 //output error messages about any remaining user labels
243                 set<string>::iterator it;
244                 bool needToRun = false;
245                 for (it = userLabels.begin(); it != userLabels.end(); it++) {  
246                         m->mothurOut("Your file does not include the label " + *it); 
247                         if (processedLabels.count(lastLabel) != 1) {
248                                 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
249                                 needToRun = true;
250                         }else {
251                                 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
252                         }
253                 }
254                 
255                 //run last label if you need to
256                 if (needToRun == true)  {
257                                 m->mothurOut(lastlist->getLabel()); 
258                                 process(lastlist);
259                                         
260                                 processedLabels.insert(lastlist->getLabel());
261                                 userLabels.erase(lastlist->getLabel());
262                 }
263                 
264
265                 //reset groups parameter
266                 globaldata->Groups.clear();  
267                 
268                 if (lastlist != NULL) {         delete lastlist;        }
269                 
270                 
271                 m->mothurOutEndLine();
272                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
273                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
274                 m->mothurOutEndLine();
275
276
277                 return 0;
278         }
279
280         catch(exception& e) {
281                 m->errorOut(e, "GetSharedOTUCommand", "execute");
282                 exit(1);
283         }
284 }
285 /***********************************************************/
286 void GetSharedOTUCommand::process(ListVector* shared) {
287         try {
288                 
289                 map<string, string> fastaMap;
290                 
291                 ofstream outNames;
292                 string outputFileNames;
293                 
294                 if (outputDir == "") { outputDir += hasPath(listfile); }
295                 if (output != "accnos") {
296                         outputFileNames = outputDir + getRootName(getSimpleName(listfile)) + shared->getLabel() + userGroups + ".shared.seqs";
297                 }else {
298                         outputFileNames = outputDir + getRootName(getSimpleName(listfile)) + shared->getLabel() + userGroups + ".accnos";
299                 }
300                 openOutputFile(outputFileNames, outNames);
301                 
302                 bool wroteSomething = false;
303                 int num = 0;
304                                 
305                 //go through each bin, find out if shared
306                 for (int i = 0; i < shared->getNumBins(); i++) {
307                         
308                         bool uniqueOTU = true;
309                         
310                         map<string, int> atLeastOne;
311                         for (int f = 0; f < Groups.size(); f++) {
312                                 atLeastOne[Groups[f]] = 0;
313                         }
314                         
315                         vector<string> namesOfSeqsInThisBin;
316                         
317                         string names = shared->get(i);  
318                         while ((names.find_first_of(',') != -1)) { 
319                                 string name = names.substr(0,names.find_first_of(','));
320                                 names = names.substr(names.find_first_of(',')+1, names.length());
321                                 
322                                 //find group
323                                 string seqGroup = groupMap->getGroup(name);
324                                 if (output != "accnos") {
325                                         namesOfSeqsInThisBin.push_back((name + "\t" + seqGroup + "\t" + toString(i+1)));
326                                 }else {  namesOfSeqsInThisBin.push_back(name);  }
327                                 
328                                 if (seqGroup == "not found") { m->mothurOut(name + " is not in your groupfile. Please correct."); m->mothurOutEndLine(); exit(1);  }
329                                 
330                                 //is this seq in one of hte groups we care about
331                                 it = groupFinder.find(seqGroup);
332                                 if (it == groupFinder.end()) {  uniqueOTU = false;  } //you have a sequence from a group you don't want
333                                 else {  atLeastOne[seqGroup]++;  }
334                         }
335                         
336                         //get last name
337                         string seqGroup = groupMap->getGroup(names);
338                         if (output != "accnos") {
339                                 namesOfSeqsInThisBin.push_back((names + "\t" + seqGroup + "\t" + toString(i+1)));
340                         }else {  namesOfSeqsInThisBin.push_back(names); }
341                         
342                         if (seqGroup == "not found") { m->mothurOut(names + " is not in your groupfile. Please correct."); m->mothurOutEndLine(); exit(1);  }
343                         
344                         //is this seq in one of hte groups we care about
345                         it = groupFinder.find(seqGroup);
346                         if (it == groupFinder.end()) {  uniqueOTU = false;  } //you have a sequence from a group you don't want
347                         else {  atLeastOne[seqGroup]++;  }
348                         
349                         
350                         //make sure you have at least one seq from each group you want
351                         bool sharedByAll = true;
352                         map<string, int>::iterator it2;
353                         for (it2 = atLeastOne.begin(); it2 != atLeastOne.end(); it2++) {
354                                 if (it2->second == 0) {  sharedByAll = false;   }
355                         }
356                         
357                         //if the user wants unique bins and this is unique then print
358                         //or this the user wants shared bins and this bin is shared then print
359                         if ((unique && uniqueOTU && sharedByAll) || (!unique && sharedByAll)) {
360                                 
361                                 wroteSomething = true;
362                                 num++;
363                                 
364                                 //output list of names 
365                                 for (int j = 0; j < namesOfSeqsInThisBin.size(); j++) {
366                                         outNames << namesOfSeqsInThisBin[j] << endl;
367                                         
368                                         if (fastafile != "") { 
369                                                 if (output != "accnos") {
370                                                         string seqName = namesOfSeqsInThisBin[j].substr(0,namesOfSeqsInThisBin[j].find_last_of('\t'));
371                                                         seqName = seqName.substr(0,seqName.find_last_of('\t'));
372                                                         fastaMap[seqName] = namesOfSeqsInThisBin[j];  //fastaMap needs to contain just the seq name for output later
373                                                 }else {
374                                                         fastaMap[namesOfSeqsInThisBin[j]] = namesOfSeqsInThisBin[j];
375                                                 }
376                                         }
377                                 }
378                         }
379                 }
380                 
381                 outNames.close();
382                 
383                 if (!wroteSomething) {
384                         remove(outputFileNames.c_str());
385                         string outputString = "\t" + toString(num) + " - No otus shared by groups";
386                         
387                         string groupString = "";
388                         for (int h = 0; h < Groups.size(); h++) {
389                                 groupString += "  " + Groups[h];
390                         }
391                         
392                         outputString += groupString + ".";
393                         m->mothurOut(outputString); m->mothurOutEndLine();
394                 }else { 
395                         m->mothurOut("\t" + toString(num)); m->mothurOutEndLine(); 
396                         outputNames.push_back(outputFileNames);
397                 }
398                 
399                 //if fasta file provided output new fasta file
400                 if ((fastafile != "") && wroteSomething) {
401                         if (outputDir == "") { outputDir += hasPath(fastafile); }
402                         string outputFileFasta = outputDir + getRootName(getSimpleName(fastafile)) + shared->getLabel() + userGroups + ".shared.fasta";
403                         ofstream outFasta;
404                         openOutputFile(outputFileFasta, outFasta);
405                         outputNames.push_back(outputFileFasta);
406                         
407                         for (int k = 0; k < seqs.size(); k++) {
408                                 //if this is a sequence we want, output it
409                                 it = fastaMap.find(seqs[k].getName());
410                                 if (it != fastaMap.end()) {
411                                 
412                                         if (output != "accnos") {
413                                                 outFasta << ">" << it->second << endl;
414                                         }else {
415                                                 outFasta << ">" << it->first << endl;
416                                         }
417                                         
418                                         outFasta << seqs[k].getAligned() << endl;
419                                 }
420                         }
421                         
422                         outFasta.close();
423                 }
424
425                 
426         }
427         catch(exception& e) {
428                 m->errorOut(e, "GetSharedOTUCommand", "process");
429                 exit(1);
430         }
431 }
432
433 //**********************************************************************************************************************