]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
numSeqs passing fix
[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") { m->mothurOut("fasta is a required parameter for the pre.cluster command."); m->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                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
86                 exit(1);
87         }
88 }
89
90 //**********************************************************************************************************************
91 PreClusterCommand::~PreClusterCommand(){}       
92 //**********************************************************************************************************************
93
94 void PreClusterCommand::help(){
95         try {
96                 m->mothurOut("The pre.cluster command groups sequences that are within a given number of base mismatches.\n");
97                 m->mothurOut("The pre.cluster command outputs a new fasta and name file.\n");
98                 m->mothurOut("The pre.cluster command parameters are fasta, names and diffs. The fasta parameter is required. \n");
99                 m->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                 m->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                 m->mothurOut("The pre.cluster command should be in the following format: \n");
102                 m->mothurOut("pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n");
103                 m->mothurOut("Example pre.cluster(fasta=amazon.fasta, diffs=2).\n");
104                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
105         }
106         catch(exception& e) {
107                 m->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                 int start = time(NULL);
119                 
120                 //reads fasta file and return number of seqs
121                 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
122                 
123                 if (m->control_pressed) { return 0; }
124         
125                 if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
126                 if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
127                 
128                 string fileroot = outputDir + getRootName(getSimpleName(fastafile));
129                 string newFastaFile = fileroot + "precluster" + getExtension(fastafile);
130                 string newNamesFile = fileroot + "precluster.names";
131                 ofstream outFasta;
132                 ofstream outNames;
133                 
134                 openOutputFile(newFastaFile, outFasta);
135                 openOutputFile(newNamesFile, outNames);
136
137                 //sort seqs by number of identical seqs
138                 alignSeqs.sort(comparePriority);
139
140                 int count = 0;
141                 int i = 0;
142                 //think about running through twice...
143                 list<seqPNode>::iterator itList;
144                 list<seqPNode>::iterator itList2;
145                 for (itList = alignSeqs.begin(); itList != alignSeqs.end();) {
146                         
147                         //try to merge it with all smaller seqs
148                         for (itList2 = alignSeqs.begin(); itList2 != alignSeqs.end();) {
149                                 
150                                 if (m->control_pressed) { outFasta.close(); outNames.close(); remove(newFastaFile.c_str()); remove(newNamesFile.c_str());  return 0; }
151                                 
152                         
153                                 if (itList->seq.getName() != itList2->seq.getName()) { //you don't want to merge with yourself
154                                         //are you within "diff" bases
155                                         
156                                         int mismatch = calcMisMatches((*itList).seq.getAligned(), (*itList2).seq.getAligned());
157
158                                         if (mismatch <= diffs) {
159                                                 //merge
160                                                 (*itList).names += ',' + (*itList2).names;
161                                                 (*itList).numIdentical += (*itList2).numIdentical;
162                                                 
163                                                 itList2 = alignSeqs.erase(itList2); //itList2--;
164                                                 count++;
165                                         }else{ itList2++; }
166                                 }else{ itList2++; }
167
168                         }
169
170                         //ouptut this sequence
171                         printData(outFasta, outNames, (*itList));
172                         
173                         //remove sequence
174                         itList = alignSeqs.erase(itList); 
175                         
176                         i++;
177                         
178                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
179                 }
180                                 
181                 if(i % 100 != 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
182                 
183                 outFasta.close();
184                 outNames.close();
185                 
186                 if (m->control_pressed) {  remove(newFastaFile.c_str()); remove(newNamesFile.c_str());  return 0; }
187
188                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences.");
189                 m->mothurOut("Total number of sequences before precluster was " + toString(numSeqs) + "."); m->mothurOutEndLine();
190                 m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); 
191                 
192                 if (m->control_pressed) { remove(newFastaFile.c_str()); remove(newNamesFile.c_str()); return 0; }
193                 
194                 m->mothurOutEndLine();
195                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
196                 m->mothurOut(newFastaFile); m->mothurOutEndLine();      
197                 m->mothurOut(newNamesFile); m->mothurOutEndLine();      
198                 m->mothurOutEndLine();
199
200                 return 0;
201                 
202         }
203         catch(exception& e) {
204                 m->errorOut(e, "PreClusterCommand", "execute");
205                 exit(1);
206         }
207 }
208
209 /**************************************************************************************************/
210
211 //this requires the names and fasta file to be in the same order
212
213 int PreClusterCommand::readFASTA(){
214         try {
215                 //ifstream inNames;
216                 ifstream inFasta;
217                 
218                 //openInputFile(namefile, inNames);
219                 openInputFile(fastafile, inFasta);
220                 
221                 //string firstCol, secondCol, nameString;
222                 length = 0;
223                 
224                 while (!inFasta.eof()) {
225                         
226                         if (m->control_pressed) { inFasta.close(); return 0; }
227                         
228                         //inNames >> firstCol >> secondCol;
229                         //nameString = secondCol;
230                         
231                         //gobble(inNames);
232                         //int size = 1;
233                         //while (secondCol.find_first_of(',') != -1) { 
234                         //      size++;
235                         //      secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
236                         //}
237                         
238                         Sequence seq(inFasta);  gobble(inFasta);
239                         
240                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
241                                 if (namefile != "") {
242                                         itSize = sizes.find(seq.getName());
243                                         
244                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
245                                         else{
246                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
247                                                 alignSeqs.push_back(tempNode);
248                                                 if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
249                                         }       
250                                 }else { //no names file, you are identical to yourself 
251                                         seqPNode tempNode(1, seq, seq.getName());
252                                         alignSeqs.push_back(tempNode);
253                                         if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
254                                 }
255                         }
256                 }
257                 inFasta.close();
258                 //inNames.close();
259                 return alignSeqs.size();
260         }
261         
262         catch(exception& e) {
263                 m->errorOut(e, "PreClusterCommand", "readFASTA");
264                 exit(1);
265         }
266 }
267
268 /**************************************************************************************************/
269
270 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
271         try {
272                 int numBad = 0;
273                 
274                 for (int i = 0; i < seq1.length(); i++) {
275                         //do they match
276                         if (seq1[i] != seq2[i]) { numBad++; }
277                         if (numBad > diffs) { return length;  } //to far to cluster
278                 }
279                 
280                 return numBad;
281         }
282         catch(exception& e) {
283                 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
284                 exit(1);
285         }
286 }
287
288 /**************************************************************************************************/
289
290 void PreClusterCommand::printData(ofstream& outFasta, ofstream& outNames, seqPNode thisSeq){
291         try {
292                 thisSeq.seq.printSequence(outFasta); 
293                 outNames << thisSeq.seq.getName() << '\t' << thisSeq.names << endl;
294         }
295         catch(exception& e) {
296                 m->errorOut(e, "PreClusterCommand", "printData");
297                 exit(1);
298         }
299 }
300 /**************************************************************************************************/
301
302 void PreClusterCommand::readNameFile(){
303         try {
304                 ifstream in;
305                 openInputFile(namefile, in);
306                 string firstCol, secondCol;
307                                 
308                 while (!in.eof()) {
309                         in >> firstCol >> secondCol; gobble(in);
310                         names[firstCol] = secondCol;
311                         int size = 1;
312
313                         for(int i=0;i<secondCol.size();i++){
314                                 if(secondCol[i] == ','){        size++; }
315                         }
316                         sizes[firstCol] = size;
317                 }
318                 in.close();
319         }
320         catch(exception& e) {
321                 m->errorOut(e, "PreClusterCommand", "readNameFile");
322                 exit(1);
323         }
324 }
325
326 /**************************************************************************************************/
327
328