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