]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
working on windows paralellization, added trimOligos class to be used by trim.flows...
[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 #include "sequenceparser.h"
12 #include "deconvolutecommand.h"
13
14 //**********************************************************************************************************************
15 inline bool comparePriority(seqPNode first, seqPNode second) {  return (first.numIdentical > second.numIdentical); }
16
17 //**********************************************************************************************************************
18 vector<string> PreClusterCommand::setParameters(){      
19         try {
20                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
21                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
22                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
23                 CommandParameter pdiffs("diffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pdiffs);
24                 CommandParameter pbygroup("bygroup", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pbygroup);
25                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
26                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
27                 
28                 vector<string> myArray;
29                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
30                 return myArray;
31         }
32         catch(exception& e) {
33                 m->errorOut(e, "PreClusterCommand", "setParameters");
34                 exit(1);
35         }
36 }
37 //**********************************************************************************************************************
38 string PreClusterCommand::getHelpString(){      
39         try {
40                 string helpString = "";
41                 helpString += "The pre.cluster command groups sequences that are within a given number of base mismatches.\n";
42                 helpString += "The pre.cluster command outputs a new fasta and name file.\n";
43                 helpString += "The pre.cluster command parameters are fasta, names and diffs. The fasta parameter is required. \n";
44                 helpString += "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";
45                 helpString += "The group parameter allows you to provide a group file. \n";
46                 helpString += "The diffs parameter allows you to specify maximum number of mismatched bases allowed between sequences in a grouping. The default is 1.\n";
47                 helpString += "The bygroup parameter allows you to indicate you whether you want to cluster sequences only within each group, default=T, when a groupfile is given. \n";
48                 helpString += "The pre.cluster command should be in the following format: \n";
49                 helpString += "pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n";
50                 helpString += "Example pre.cluster(fasta=amazon.fasta, diffs=2).\n";
51                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
52                 return helpString;
53         }
54         catch(exception& e) {
55                 m->errorOut(e, "PreClusterCommand", "getHelpString");
56                 exit(1);
57         }
58 }
59
60 //**********************************************************************************************************************
61 PreClusterCommand::PreClusterCommand(){ 
62         try {
63                 abort = true; calledHelp = true; 
64                 setParameters();
65                 vector<string> tempOutNames;
66                 outputTypes["fasta"] = tempOutNames;
67                 outputTypes["name"] = tempOutNames;
68         }
69         catch(exception& e) {
70                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
71                 exit(1);
72         }
73 }
74 //**********************************************************************************************************************
75
76 PreClusterCommand::PreClusterCommand(string option) {
77         try {
78                 abort = false; calledHelp = false;   
79                 
80                 //allow user to run help
81                 if(option == "help") { help(); abort = true; calledHelp = true; }
82                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
83                 
84                 else {
85                         vector<string> myArray = setParameters();
86                         
87                         OptionParser parser(option);
88                         map<string, string> parameters = parser.getParameters();
89                         
90                         ValidParameters validParameter;
91                         map<string, string>::iterator it;
92                 
93                         //check to make sure all parameters are valid for command
94                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
95                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
96                         }
97                         
98                         //initialize outputTypes
99                         vector<string> tempOutNames;
100                         outputTypes["fasta"] = tempOutNames;
101                         outputTypes["name"] = tempOutNames;
102                 
103                         //if the user changes the input directory command factory will send this info to us in the output parameter 
104                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
105                         if (inputDir == "not found"){   inputDir = "";          }
106                         else {
107                                 string path;
108                                 it = parameters.find("fasta");
109                                 //user has given a template file
110                                 if(it != parameters.end()){ 
111                                         path = m->hasPath(it->second);
112                                         //if the user has not given a path then, add inputdir. else leave path alone.
113                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
114                                 }
115                                 
116                                 it = parameters.find("name");
117                                 //user has given a template file
118                                 if(it != parameters.end()){ 
119                                         path = m->hasPath(it->second);
120                                         //if the user has not given a path then, add inputdir. else leave path alone.
121                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
122                                 }
123                                 
124                                 it = parameters.find("group");
125                                 //user has given a template file
126                                 if(it != parameters.end()){ 
127                                         path = m->hasPath(it->second);
128                                         //if the user has not given a path then, add inputdir. else leave path alone.
129                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
130                                 }
131                         }
132
133                         //check for required parameters
134                         fastafile = validParameter.validFile(parameters, "fasta", true);
135                         if (fastafile == "not found") {                                 
136                                 fastafile = m->getFastaFile(); 
137                                 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
138                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
139                         }
140                         else if (fastafile == "not open") { abort = true; }     
141                         else { m->setFastaFile(fastafile); }
142                         
143                         //if the user changes the output directory command factory will send this info to us in the output parameter 
144                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
145                                 outputDir = ""; 
146                                 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it       
147                         }
148
149                         //check for optional parameter and set defaults
150                         // ...at some point should added some additional type checking...
151                         namefile = validParameter.validFile(parameters, "name", true);
152                         if (namefile == "not found") { namefile =  "";  }
153                         else if (namefile == "not open") { abort = true; }      
154                         else {  m->setNameFile(namefile); }
155                         
156                         groupfile = validParameter.validFile(parameters, "group", true);
157                         if (groupfile == "not found") { groupfile =  "";  }
158                         else if (groupfile == "not open") { abort = true; groupfile =  ""; }    
159                         else {   m->setGroupFile(groupfile); }
160                         
161                         string temp     = validParameter.validFile(parameters, "diffs", false);         if(temp == "not found"){        temp = "1"; }
162                         convert(temp, diffs); 
163                         
164                         temp = validParameter.validFile(parameters, "bygroup", false);                  
165                         if (temp == "not found") { 
166                                 if (groupfile != "") { temp = "T"; }
167                                 else { temp = "F"; }
168                         }
169                         bygroup = m->isTrue(temp); 
170                         
171                         if (bygroup && (groupfile == "")) { m->mothurOut("You cannot set bygroup=T, unless you provide a groupfile."); m->mothurOutEndLine(); abort=true; }
172
173                 }
174                                 
175         }
176         catch(exception& e) {
177                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
178                 exit(1);
179         }
180 }
181 //**********************************************************************************************************************
182
183 int PreClusterCommand::execute(){
184         try {
185                 
186                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
187                 
188                 int start = time(NULL);
189                 
190                 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
191                 string newFastaFile = fileroot + "precluster" + m->getExtension(fastafile);
192                 string newNamesFile = fileroot + "precluster.names";
193                 
194                 if (bygroup) {
195                         //clear out old files
196                         ofstream outFasta; m->openOutputFile(newFastaFile, outFasta); outFasta.close();
197                         ofstream outNames; m->openOutputFile(newNamesFile, outNames);  outNames.close();
198                         
199                         //parse fasta and name file by group
200                         SequenceParser* parser;
201                         if (namefile != "") { parser = new SequenceParser(groupfile, fastafile, namefile);      }
202                         else                            { parser = new SequenceParser(groupfile, fastafile);                    }
203                         
204                         vector<string> groups = parser->getNamesOfGroups();
205                         
206                         //precluster each group
207                         for (int i = 0; i < groups.size(); i++) {
208                                 
209                                 start = time(NULL);
210                                 
211                                 if (m->control_pressed) {  delete parser; m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
212                                 
213                                 m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[i] + ":"); m->mothurOutEndLine();
214                                 
215                                 map<string, string> thisNameMap;
216                                 if (namefile != "") { thisNameMap = parser->getNameMap(groups[i]); }
217                                 vector<Sequence> thisSeqs = parser->getSeqs(groups[i]);
218                                 
219                                 //fill alignSeqs with this groups info.
220                                 int numSeqs = loadSeqs(thisNameMap, thisSeqs);
221                                 
222                                 if (m->control_pressed) {  delete parser; m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
223                                 
224                                 if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
225                                 
226                                 int count = process();
227                                 
228                                 if (m->control_pressed) {  delete parser; m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
229
230                                 m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
231                                 m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
232                                 printData(newFastaFile, newNamesFile);
233                                 
234                                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
235                                 
236                         }
237                         
238                         //run unique.seqs for deconvolute results
239                         string inputString = "fasta=" + newFastaFile;
240                         if (namefile != "") { inputString += ", name=" + newNamesFile; }
241                         m->mothurOutEndLine(); 
242                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
243                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
244                         
245                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
246                         uniqueCommand->execute();
247                         
248                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
249                         
250                         delete uniqueCommand;
251                         
252                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
253                         
254                         newNamesFile = filenames["name"][0];
255                         newFastaFile = filenames["fasta"][0];
256                         
257                 }else {
258                         if (namefile != "") { readNameFile(); }
259                 
260                         //reads fasta file and return number of seqs
261                         int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
262                 
263                         if (m->control_pressed) { return 0; }
264         
265                         if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
266                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
267                         
268                         int count = process();
269                         
270                         if (m->control_pressed) { return 0; }   
271                         
272                         m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
273                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
274                         printData(newFastaFile, newNamesFile);
275                         
276                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
277                 }
278                 
279                 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
280                 
281                 m->mothurOutEndLine();
282                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
283                 m->mothurOut(newFastaFile); m->mothurOutEndLine();      outputNames.push_back(newFastaFile); outputTypes["fasta"].push_back(newFastaFile);
284                 m->mothurOut(newNamesFile); m->mothurOutEndLine();      outputNames.push_back(newNamesFile); outputTypes["name"].push_back(newNamesFile);
285                 m->mothurOutEndLine();
286                 
287                 //set fasta file as new current fastafile
288                 string current = "";
289                 itTypes = outputTypes.find("fasta");
290                 if (itTypes != outputTypes.end()) {
291                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
292                 }
293                 
294                 itTypes = outputTypes.find("name");
295                 if (itTypes != outputTypes.end()) {
296                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
297                 }
298                 
299                 return 0;
300                 
301         }
302         catch(exception& e) {
303                 m->errorOut(e, "PreClusterCommand", "execute");
304                 exit(1);
305         }
306 }
307 /**************************************************************************************************/
308 int PreClusterCommand::process(){
309         try {
310                 
311                 //sort seqs by number of identical seqs
312                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
313                 
314                 int count = 0;
315                 int numSeqs = alignSeqs.size();
316                 
317                 //think about running through twice...
318                 for (int i = 0; i < numSeqs; i++) {
319                         
320                         //are you active
321                         //                      itActive = active.find(alignSeqs[i].seq.getName());
322                         
323                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
324                                 
325                                 //try to merge it with all smaller seqs
326                                 for (int j = i+1; j < numSeqs; j++) {
327                                         
328                                         if (m->control_pressed) { return 0; }
329                                         
330                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
331                                                 //are you within "diff" bases
332                                                 int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
333                                                 
334                                                 if (mismatch <= diffs) {
335                                                         //merge
336                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
337                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
338                                                         
339                                                         alignSeqs[j].active = 0;
340                                                         alignSeqs[j].numIdentical = 0;
341                                                         count++;
342                                                 }
343                                         }//end if j active
344                                 }//end if i != j
345                                 
346                                 //remove from active list 
347                                 alignSeqs[i].active = 0;
348                                 
349                         }//end if active i
350                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
351                 }
352                 
353                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }       
354                 
355                 return count;
356                 
357         }
358         catch(exception& e) {
359                 m->errorOut(e, "PreClusterCommand", "process");
360                 exit(1);
361         }
362 }
363 /**************************************************************************************************/
364 int PreClusterCommand::readFASTA(){
365         try {
366                 //ifstream inNames;
367                 ifstream inFasta;
368                 
369                 //m->openInputFile(namefile, inNames);
370                 m->openInputFile(fastafile, inFasta);
371                 
372                 //string firstCol, secondCol, nameString;
373                 length = 0;
374                 
375                 while (!inFasta.eof()) {
376                         
377                         if (m->control_pressed) { inFasta.close(); return 0; }
378                         
379                         //inNames >> firstCol >> secondCol;
380                         //nameString = secondCol;
381                         
382                         //m->gobble(inNames);
383                         //int size = 1;
384                         //while (secondCol.find_first_of(',') != -1) { 
385                         //      size++;
386                         //      secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
387                         //}
388                         
389                         Sequence seq(inFasta);  m->gobble(inFasta);
390                         
391                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
392                                 if (namefile != "") {
393                                         itSize = sizes.find(seq.getName());
394                                         
395                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
396                                         else{
397                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
398                                                 alignSeqs.push_back(tempNode);
399                                                 if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
400                                         }       
401                                 }else { //no names file, you are identical to yourself 
402                                         seqPNode tempNode(1, seq, seq.getName());
403                                         alignSeqs.push_back(tempNode);
404                                         if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
405                                 }
406                         }
407                 }
408                 inFasta.close();
409                 //inNames.close();
410                 return alignSeqs.size();
411         }
412         
413         catch(exception& e) {
414                 m->errorOut(e, "PreClusterCommand", "readFASTA");
415                 exit(1);
416         }
417 }
418 /**************************************************************************************************/
419 int PreClusterCommand::loadSeqs(map<string, string>& thisName, vector<Sequence>& thisSeqs){
420         try {
421                 length = 0;
422                 alignSeqs.clear();
423                 map<string, string>::iterator it;
424                 bool error = false;
425                         
426                 for (int i = 0; i < thisSeqs.size(); i++) {
427                         
428                         if (m->control_pressed) { return 0; }
429                                                 
430                         if (namefile != "") {
431                                 it = thisName.find(thisSeqs[i].getName());
432                                 
433                                 //should never be true since parser checks for this
434                                 if (it == thisName.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); error = true; }
435                                 else{
436                                         //get number of reps
437                                         int numReps = 0;
438                                         for(int j=0;j<(it->second).length();j++){
439                                                 if((it->second)[j] == ','){     numReps++;      }
440                                         }
441                                         
442                                         seqPNode tempNode(numReps, thisSeqs[i], it->second);
443                                         alignSeqs.push_back(tempNode);
444                                         if (thisSeqs[i].getAligned().length() > length) {  length = thisSeqs[i].getAligned().length();  }
445                                 }       
446                         }else { //no names file, you are identical to yourself 
447                                 seqPNode tempNode(1, thisSeqs[i], thisSeqs[i].getName());
448                                 alignSeqs.push_back(tempNode);
449                                 if (thisSeqs[i].getAligned().length() > length) {  length = thisSeqs[i].getAligned().length();  }
450                         }
451                 }
452                 
453                 //sanity check
454                 if (error) { m->control_pressed = true; }
455                 
456                 thisSeqs.clear();
457                 
458                 return alignSeqs.size();
459         }
460         
461         catch(exception& e) {
462                 m->errorOut(e, "PreClusterCommand", "loadSeqs");
463                 exit(1);
464         }
465 }
466                                 
467 /**************************************************************************************************/
468
469 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
470         try {
471                 int numBad = 0;
472                 
473                 for (int i = 0; i < seq1.length(); i++) {
474                         //do they match
475                         if (seq1[i] != seq2[i]) { numBad++; }
476                         if (numBad > diffs) { return length;  } //to far to cluster
477                 }
478                 
479                 return numBad;
480         }
481         catch(exception& e) {
482                 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
483                 exit(1);
484         }
485 }
486
487 /**************************************************************************************************/
488
489 void PreClusterCommand::printData(string newfasta, string newname){
490         try {
491                 ofstream outFasta;
492                 ofstream outNames;
493                 
494                 if (bygroup) {
495                         m->openOutputFileAppend(newfasta, outFasta);
496                         m->openOutputFileAppend(newname, outNames);
497                 }else {
498                         m->openOutputFile(newfasta, outFasta);
499                         m->openOutputFile(newname, outNames);
500                 }
501                                 
502                 for (int i = 0; i < alignSeqs.size(); i++) {
503                         if (alignSeqs[i].numIdentical != 0) {
504                                 alignSeqs[i].seq.printSequence(outFasta); 
505                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
506                         }
507                 }
508                 
509                 outFasta.close();
510                 outNames.close();
511                 
512         }
513         catch(exception& e) {
514                 m->errorOut(e, "PreClusterCommand", "printData");
515                 exit(1);
516         }
517 }
518 /**************************************************************************************************/
519
520 void PreClusterCommand::readNameFile(){
521         try {
522                 ifstream in;
523                 m->openInputFile(namefile, in);
524                 string firstCol, secondCol;
525                                 
526                 while (!in.eof()) {
527                         in >> firstCol >> secondCol; m->gobble(in);
528                         names[firstCol] = secondCol;
529                         int size = 1;
530
531                         for(int i=0;i<secondCol.size();i++){
532                                 if(secondCol[i] == ','){        size++; }
533                         }
534                         sizes[firstCol] = size;
535                 }
536                 in.close();
537         }
538         catch(exception& e) {
539                 m->errorOut(e, "PreClusterCommand", "readNameFile");
540                 exit(1);
541         }
542 }
543
544 /**************************************************************************************************/
545
546