]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
4b04529af1f8181efff2dff2986cf0ab52065a58
[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 pre.cluster 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                         delete parser;
239                         
240                         //run unique.seqs for deconvolute results
241                         string inputString = "fasta=" + newFastaFile;
242                         if (namefile != "") { inputString += ", name=" + newNamesFile; }
243                         m->mothurOutEndLine(); 
244                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
245                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
246                         
247                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
248                         uniqueCommand->execute();
249                         
250                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
251                         
252                         delete uniqueCommand;
253                         
254                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
255                         
256                         m->renameFile(filenames["fasta"][0], newFastaFile);
257                                 
258                 }else {
259                         if (namefile != "") { readNameFile(); }
260                 
261                         //reads fasta file and return number of seqs
262                         int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
263                 
264                         if (m->control_pressed) { return 0; }
265         
266                         if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
267                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
268                         
269                         int count = process();
270                         
271                         if (m->control_pressed) { return 0; }   
272                         
273                         m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
274                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
275                         printData(newFastaFile, newNamesFile);
276                         
277                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
278                 }
279                 
280                 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
281                 
282                 m->mothurOutEndLine();
283                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
284                 m->mothurOut(newFastaFile); m->mothurOutEndLine();      outputNames.push_back(newFastaFile); outputTypes["fasta"].push_back(newFastaFile);
285                 m->mothurOut(newNamesFile); m->mothurOutEndLine();      outputNames.push_back(newNamesFile); outputTypes["name"].push_back(newNamesFile);
286                 m->mothurOutEndLine();
287                 
288                 //set fasta file as new current fastafile
289                 string current = "";
290                 itTypes = outputTypes.find("fasta");
291                 if (itTypes != outputTypes.end()) {
292                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
293                 }
294                 
295                 itTypes = outputTypes.find("name");
296                 if (itTypes != outputTypes.end()) {
297                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
298                 }
299                 
300                 return 0;
301                 
302         }
303         catch(exception& e) {
304                 m->errorOut(e, "PreClusterCommand", "execute");
305                 exit(1);
306         }
307 }
308 /**************************************************************************************************/
309 int PreClusterCommand::process(){
310         try {
311                 
312                 //sort seqs by number of identical seqs
313                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
314                 
315                 int count = 0;
316                 int numSeqs = alignSeqs.size();
317                 
318                 //think about running through twice...
319                 for (int i = 0; i < numSeqs; i++) {
320                         
321                         //are you active
322                         //                      itActive = active.find(alignSeqs[i].seq.getName());
323                         
324                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
325                                 
326                                 //try to merge it with all smaller seqs
327                                 for (int j = i+1; j < numSeqs; j++) {
328                                         
329                                         if (m->control_pressed) { return 0; }
330                                         
331                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
332                                                 //are you within "diff" bases
333                                                 int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
334                                                 
335                                                 if (mismatch <= diffs) {
336                                                         //merge
337                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
338                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
339                                                         
340                                                         alignSeqs[j].active = 0;
341                                                         alignSeqs[j].numIdentical = 0;
342                                                         count++;
343                                                 }
344                                         }//end if j active
345                                 }//end if i != j
346                                 
347                                 //remove from active list 
348                                 alignSeqs[i].active = 0;
349                                 
350                         }//end if active i
351                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
352                 }
353                 
354                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }       
355                 
356                 return count;
357                 
358         }
359         catch(exception& e) {
360                 m->errorOut(e, "PreClusterCommand", "process");
361                 exit(1);
362         }
363 }
364 /**************************************************************************************************/
365 int PreClusterCommand::readFASTA(){
366         try {
367                 //ifstream inNames;
368                 ifstream inFasta;
369                 
370                 //m->openInputFile(namefile, inNames);
371                 m->openInputFile(fastafile, inFasta);
372                 
373                 //string firstCol, secondCol, nameString;
374                 length = 0;
375                 
376                 while (!inFasta.eof()) {
377                         
378                         if (m->control_pressed) { inFasta.close(); return 0; }
379                         
380                         //inNames >> firstCol >> secondCol;
381                         //nameString = secondCol;
382                         
383                         //m->gobble(inNames);
384                         //int size = 1;
385                         //while (secondCol.find_first_of(',') != -1) { 
386                         //      size++;
387                         //      secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
388                         //}
389                         
390                         Sequence seq(inFasta);  m->gobble(inFasta);
391                         
392                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
393                                 if (namefile != "") {
394                                         itSize = sizes.find(seq.getName());
395                                         
396                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
397                                         else{
398                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
399                                                 alignSeqs.push_back(tempNode);
400                                                 if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
401                                         }       
402                                 }else { //no names file, you are identical to yourself 
403                                         seqPNode tempNode(1, seq, seq.getName());
404                                         alignSeqs.push_back(tempNode);
405                                         if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
406                                 }
407                         }
408                 }
409                 inFasta.close();
410                 //inNames.close();
411                 return alignSeqs.size();
412         }
413         
414         catch(exception& e) {
415                 m->errorOut(e, "PreClusterCommand", "readFASTA");
416                 exit(1);
417         }
418 }
419 /**************************************************************************************************/
420 int PreClusterCommand::loadSeqs(map<string, string>& thisName, vector<Sequence>& thisSeqs){
421         try {
422                 length = 0;
423                 alignSeqs.clear();
424                 map<string, string>::iterator it;
425                 bool error = false;
426                         
427                 for (int i = 0; i < thisSeqs.size(); i++) {
428                         
429                         if (m->control_pressed) { return 0; }
430                                                 
431                         if (namefile != "") {
432                                 it = thisName.find(thisSeqs[i].getName());
433                                 
434                                 //should never be true since parser checks for this
435                                 if (it == thisName.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); error = true; }
436                                 else{
437                                         //get number of reps
438                                         int numReps = 1;
439                                         for(int j=0;j<(it->second).length();j++){
440                                                 if((it->second)[j] == ','){     numReps++;      }
441                                         }
442                                         
443                                         seqPNode tempNode(numReps, thisSeqs[i], it->second);
444                                         alignSeqs.push_back(tempNode);
445                                         if (thisSeqs[i].getAligned().length() > length) {  length = thisSeqs[i].getAligned().length();  }
446                                 }       
447                         }else { //no names file, you are identical to yourself 
448                                 seqPNode tempNode(1, thisSeqs[i], thisSeqs[i].getName());
449                                 alignSeqs.push_back(tempNode);
450                                 if (thisSeqs[i].getAligned().length() > length) {  length = thisSeqs[i].getAligned().length();  }
451                         }
452                 }
453                 
454                 //sanity check
455                 if (error) { m->control_pressed = true; }
456                 
457                 thisSeqs.clear();
458                 
459                 return alignSeqs.size();
460         }
461         
462         catch(exception& e) {
463                 m->errorOut(e, "PreClusterCommand", "loadSeqs");
464                 exit(1);
465         }
466 }
467                                 
468 /**************************************************************************************************/
469
470 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
471         try {
472                 int numBad = 0;
473                 
474                 for (int i = 0; i < seq1.length(); i++) {
475                         //do they match
476                         if (seq1[i] != seq2[i]) { numBad++; }
477                         if (numBad > diffs) { return length;  } //to far to cluster
478                 }
479                 
480                 return numBad;
481         }
482         catch(exception& e) {
483                 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
484                 exit(1);
485         }
486 }
487
488 /**************************************************************************************************/
489
490 void PreClusterCommand::printData(string newfasta, string newname){
491         try {
492                 ofstream outFasta;
493                 ofstream outNames;
494                 
495                 if (bygroup) {
496                         m->openOutputFileAppend(newfasta, outFasta);
497                         m->openOutputFileAppend(newname, outNames);
498                 }else {
499                         m->openOutputFile(newfasta, outFasta);
500                         m->openOutputFile(newname, outNames);
501                 }
502                                 
503                 for (int i = 0; i < alignSeqs.size(); i++) {
504                         if (alignSeqs[i].numIdentical != 0) {
505                                 alignSeqs[i].seq.printSequence(outFasta); 
506                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
507                         }
508                 }
509                 
510                 outFasta.close();
511                 outNames.close();
512                 
513         }
514         catch(exception& e) {
515                 m->errorOut(e, "PreClusterCommand", "printData");
516                 exit(1);
517         }
518 }
519 /**************************************************************************************************/
520
521 void PreClusterCommand::readNameFile(){
522         try {
523                 ifstream in;
524                 m->openInputFile(namefile, in);
525                 string firstCol, secondCol;
526                                 
527                 while (!in.eof()) {
528                         in >> firstCol >> secondCol; m->gobble(in);
529                         names[firstCol] = secondCol;
530                         int size = 1;
531
532                         for(int i=0;i<secondCol.size();i++){
533                                 if(secondCol[i] == ','){        size++; }
534                         }
535                         sizes[firstCol] = size;
536                 }
537                 in.close();
538         }
539         catch(exception& e) {
540                 m->errorOut(e, "PreClusterCommand", "readNameFile");
541                 exit(1);
542         }
543 }
544
545 /**************************************************************************************************/
546
547