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