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