]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
fixed bugs for 1.8
[mothur.git] / preclustercommand.cpp
1 /*
2  *  preclustercommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 12/21/09.
6  *  Copyright 2009 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "preclustercommand.h"
11
12 //**********************************************************************************************************************
13 inline bool comparePriority(seqPNode first, seqPNode second) {  return (first.numIdentical > second.numIdentical); }
14 //**********************************************************************************************************************
15
16 PreClusterCommand::PreClusterCommand(string option){
17         try {
18                 abort = false;
19                 
20                 //allow user to run help
21                 if(option == "help") { help(); abort = true; }
22                 
23                 else {
24                         //valid paramters for this command
25                         string Array[] =  {"fasta", "name", "diffs", "outputdir","inputdir"};
26                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
27                         
28                         OptionParser parser(option);
29                         map<string, string> parameters = parser.getParameters();
30                         
31                         ValidParameters validParameter;
32                         map<string, string>::iterator it;
33                 
34                         //check to make sure all parameters are valid for command
35                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
36                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
37                         }
38                         
39                         //if the user changes the input directory command factory will send this info to us in the output parameter 
40                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
41                         if (inputDir == "not found"){   inputDir = "";          }
42                         else {
43                                 string path;
44                                 it = parameters.find("fasta");
45                                 //user has given a template file
46                                 if(it != parameters.end()){ 
47                                         path = hasPath(it->second);
48                                         //if the user has not given a path then, add inputdir. else leave path alone.
49                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
50                                 }
51                                 
52                                 it = parameters.find("name");
53                                 //user has given a template file
54                                 if(it != parameters.end()){ 
55                                         path = hasPath(it->second);
56                                         //if the user has not given a path then, add inputdir. else leave path alone.
57                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
58                                 }
59                         }
60
61                         //check for required parameters
62                         fastafile = validParameter.validFile(parameters, "fasta", true);
63                         if (fastafile == "not found") { mothurOut("fasta is a required parameter for the pre.cluster command."); mothurOutEndLine(); abort = true; }
64                         else if (fastafile == "not open") { abort = true; }     
65                         
66                         //if the user changes the output directory command factory will send this info to us in the output parameter 
67                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
68                                 outputDir = ""; 
69                                 outputDir += hasPath(fastafile); //if user entered a file with a path then preserve it  
70                         }
71
72                         //check for optional parameter and set defaults
73                         // ...at some point should added some additional type checking...
74                         namefile = validParameter.validFile(parameters, "name", true);
75                         if (namefile == "not found") { namefile =  "";  }
76                         else if (namefile == "not open") { abort = true; }      
77                         else {  readNameFile();  }
78                         
79                         string temp     = validParameter.validFile(parameters, "diffs", false);                         if(temp == "not found"){        temp = "1"; }
80                         convert(temp, diffs); 
81                 }
82                                 
83         }
84         catch(exception& e) {
85                 errorOut(e, "PreClusterCommand", "PreClusterCommand");
86                 exit(1);
87         }
88 }
89
90 //**********************************************************************************************************************
91 PreClusterCommand::~PreClusterCommand(){}       
92 //**********************************************************************************************************************
93
94 void PreClusterCommand::help(){
95         try {
96                 mothurOut("The pre.cluster command groups sequences that are within a given number of base mismatches.\n");
97                 mothurOut("The pre.cluster command outputs a new fasta and name file.\n");
98                 mothurOut("The pre.cluster command parameters are fasta, names and diffs. The fasta parameter is required. \n");
99                 mothurOut("The names parameter allows you to give a list of seqs that are identical. This file is 2 columns, first column is name or representative sequence, second column is a list of its identical sequences separated by commas.\n");
100                 mothurOut("The diffs parameter allows you to specify maximum number of mismatched bases allowed between sequences in a grouping. The default is 1.\n");
101                 mothurOut("The pre.cluster command should be in the following format: \n");
102                 mothurOut("pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n");
103                 mothurOut("Example pre.cluster(fasta=amazon.fasta, diffs=2).\n");
104                 mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
105         }
106         catch(exception& e) {
107                 errorOut(e, "PreClusterCommand", "help");
108                 exit(1);
109         }
110 }
111 //**********************************************************************************************************************
112
113 int PreClusterCommand::execute(){
114         try {
115                 
116                 if (abort == true) { return 0; }
117                 
118                 //reads fasta file and return number of seqs
119                 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
120         
121                 if (numSeqs == 0) { mothurOut("Error reading fasta file...please correct."); mothurOutEndLine(); return 0;  }
122                 if (diffs > length) { mothurOut("Error: diffs is greater than your sequence length."); mothurOutEndLine(); return 0;  }
123                 
124                 //clear sizes since you only needed this info to build the alignSeqs seqPNode structs
125 //              sizes.clear();
126         
127                 //sort seqs by number of identical seqs
128                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
129         
130                 int count = 0;
131
132                 //think about running through twice...
133                 for (int i = 0; i < numSeqs; i++) {
134                         
135                         //are you active
136                         //                      itActive = active.find(alignSeqs[i].seq.getName());
137                         
138                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
139                                 
140                                 //try to merge it with all smaller seqs
141                                 for (int j = i+1; j < numSeqs; j++) {
142                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
143                                                 //are you within "diff" bases
144                                                 int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
145                                                 
146                                                 if (mismatch <= diffs) {
147                                                         //merge
148                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
149                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
150
151                                                         alignSeqs[j].active = 0;
152                                                         alignSeqs[j].numIdentical = 0;
153                                                         count++;
154                                                 }
155                                         }//end if j active
156                                 }//end if i != j
157                         
158                         //remove from active list 
159                                 alignSeqs[i].active = 0;
160                         }//end if active i
161                         if(i % 100 == 0)        { cout << i << '\t' << numSeqs - count << '\t' << count << endl;        }
162                 }
163                 
164                 string fileroot = outputDir + getRootName(getSimpleName(fastafile));
165                 
166                 string newFastaFile = fileroot + "precluster" + getExtension(fastafile);
167                 string newNamesFile = fileroot + "precluster.names";
168                 
169                 
170                 mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); mothurOutEndLine();
171                 mothurOut("pre.cluster removed " + toString(count) + " sequences."); mothurOutEndLine(); 
172                 printData(newFastaFile, newNamesFile);
173
174                 return 0;
175                 
176         }
177         catch(exception& e) {
178                 errorOut(e, "PreClusterCommand", "execute");
179                 exit(1);
180         }
181 }
182 /**************************************************************************************************
183 int PreClusterCommand::readFASTA(){
184         try {
185 //              ifstream inFasta;
186 //              openInputFile(fastafile, inFasta);
187 //              length = 0;
188 ////            map<string, string>::iterator it;
189 //
190 //              while (!inFasta.eof()) {
191 //                      Sequence temp(inFasta);  //read seq
192 //                      
193 //                      if (temp.getName() != "") {  
194 //                              if (namefile != "") {
195 //                                      //make sure fasta and name files match
196 //                                      it = names.find(temp.getName());
197 //                                      if (it == names.end()) { mothurOut(temp.getName() + " is not in your names file, please correct."); mothurOutEndLine(); exit(1); }
198 //                              }else { sizes[temp.getName()] = 1; }
199 //                              
200 //                              seqPNode tempNode(sizes[temp.getName()], temp);
201 //                              alignSeqs.push_back(tempNode); 
202 //                              active[temp.getName()] = true;
203 //                      }
204 //                      gobble(inFasta);
205 //              }
206 //              inFasta.close();
207 //              
208 //              if (alignSeqs.size() != 0) {  length = alignSeqs[0].seq.getAligned().length();  }
209 //              
210                 return alignSeqs.size();
211         }
212         catch(exception& e) {
213                 errorOut(e, "PreClusterCommand", "readFASTA");
214                 exit(1);
215         }
216 }
217 /**************************************************************************************************/
218 //this seems to require the names and fasta file to be in the same order???
219 int PreClusterCommand::readFASTA(){
220         try {
221                 //ifstream inNames;
222                 ifstream inFasta;
223                 
224                 //openInputFile(namefile, inNames);
225                 openInputFile(fastafile, inFasta);
226                 
227                 //string firstCol, secondCol, nameString;
228                 length = 0;
229                 
230                 while (!inFasta.eof()) {
231         
232                         //inNames >> firstCol >> secondCol;
233                         //nameString = secondCol;
234                         
235                         //gobble(inNames);
236                         //int size = 1;
237                         //while (secondCol.find_first_of(',') != -1) { 
238                         //      size++;
239                         //      secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
240                         //}
241                         
242                         Sequence seq(inFasta);  gobble(inFasta);
243                         
244                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
245                                 if (namefile != "") {
246                                         itSize = sizes.find(seq.getName());
247                                         
248                                         if (itSize == sizes.end()) { mothurOut(seq.getName() + " is not in your names file, please correct."); mothurOutEndLine(); exit(1); }
249                                         else{
250                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
251                                                 alignSeqs.push_back(tempNode);
252                                                 if (seq.getAligned().length() > length) {  length = alignSeqs[0].seq.getAligned().length();  }
253                                         }       
254                                 }else { //no names file, you are identical to yourself 
255                                         seqPNode tempNode(1, seq, seq.getName());
256                                         alignSeqs.push_back(tempNode);
257                                         if (seq.getAligned().length() > length) {  length = alignSeqs[0].seq.getAligned().length();  }
258                                 }
259                         }
260                 }
261                 inFasta.close();
262                 //inNames.close();
263                 return alignSeqs.size();
264         }
265         
266         catch(exception& e) {
267                 errorOut(e, "PreClusterCommand", "readFASTA");
268                 exit(1);
269         }
270 }
271
272 /**************************************************************************************************/
273
274 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
275         try {
276                 int numBad = 0;
277                 
278                 for (int i = 0; i < seq1.length(); i++) {
279                         //do they match
280                         if (seq1[i] != seq2[i]) { numBad++; }
281                         if (numBad > diffs) { return length;  } //to far to cluster
282                 }
283                 
284                 return numBad;
285         }
286         catch(exception& e) {
287                 errorOut(e, "PreClusterCommand", "calcMisMatches");
288                 exit(1);
289         }
290 }
291
292 /**************************************************************************************************/
293
294 void PreClusterCommand::printData(string newfasta, string newname){
295         try {
296                 ofstream outFasta;
297                 ofstream outNames;
298                 
299                 openOutputFile(newfasta, outFasta);
300                 openOutputFile(newname, outNames);
301                                 
302                 
303                 for (int i = 0; i < alignSeqs.size(); i++) {
304                         if (alignSeqs[i].numIdentical != 0) {
305                                 alignSeqs[i].seq.printSequence(outFasta); 
306                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
307                         }
308                 }
309                 
310                 outFasta.close();
311                 outNames.close();
312                 
313         }
314         catch(exception& e) {
315                 errorOut(e, "PreClusterCommand", "printData");
316                 exit(1);
317         }
318 }
319 /**************************************************************************************************/
320 void PreClusterCommand::readNameFile(){
321         try {
322                 ifstream in;
323                 openInputFile(namefile, in);
324                 string firstCol, secondCol;
325                                 
326                 while (!in.eof()) {
327                         in >> firstCol >> secondCol; gobble(in);
328                         names[firstCol] = secondCol;
329                         int size = 1;
330                         while (secondCol.find_first_of(',') != -1) { 
331                                 size++;
332                                 secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
333                         }
334                         sizes[firstCol] = size;
335                 }
336                 in.close();
337         }
338         catch(exception& e) {
339                 errorOut(e, "PreClusterCommand", "readNameFile");
340                 exit(1);
341         }
342 }
343
344 /**************************************************************************************************/
345
346