2 * preclustercommand.cpp
5 * Created by westcott on 12/21/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
10 #include "preclustercommand.h"
11 #include "sequenceparser.h"
12 #include "deconvolutecommand.h"
14 //**********************************************************************************************************************
15 inline bool comparePriority(seqPNode first, seqPNode second) { return (first.numIdentical > second.numIdentical); }
17 //**********************************************************************************************************************
18 vector<string> PreClusterCommand::setParameters(){
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);
28 vector<string> myArray;
29 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
33 m->errorOut(e, "PreClusterCommand", "setParameters");
37 //**********************************************************************************************************************
38 string PreClusterCommand::getHelpString(){
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";
55 m->errorOut(e, "PreClusterCommand", "getHelpString");
60 //**********************************************************************************************************************
61 PreClusterCommand::PreClusterCommand(){
63 abort = true; calledHelp = true;
65 vector<string> tempOutNames;
66 outputTypes["fasta"] = tempOutNames;
67 outputTypes["name"] = tempOutNames;
70 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
74 //**********************************************************************************************************************
76 PreClusterCommand::PreClusterCommand(string option) {
78 abort = false; calledHelp = false;
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;}
85 vector<string> myArray = setParameters();
87 OptionParser parser(option);
88 map<string, string> parameters = parser.getParameters();
90 ValidParameters validParameter;
91 map<string, string>::iterator it;
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; }
98 //initialize outputTypes
99 vector<string> tempOutNames;
100 outputTypes["fasta"] = tempOutNames;
101 outputTypes["name"] = tempOutNames;
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 = ""; }
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; }
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; }
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; }
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; }
140 else if (fastafile == "not open") { abort = true; }
141 else { m->setFastaFile(fastafile); }
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"){
146 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it
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); }
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); }
161 string temp = validParameter.validFile(parameters, "diffs", false); if(temp == "not found"){ temp = "1"; }
162 convert(temp, diffs);
164 temp = validParameter.validFile(parameters, "bygroup", false);
165 if (temp == "not found") {
166 if (groupfile != "") { temp = "T"; }
169 bygroup = m->isTrue(temp);
171 if (bygroup && (groupfile == "")) { m->mothurOut("You cannot set bygroup=T, unless you provide a groupfile."); m->mothurOutEndLine(); abort=true; }
176 catch(exception& e) {
177 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
181 //**********************************************************************************************************************
183 int PreClusterCommand::execute(){
186 if (abort == true) { if (calledHelp) { return 0; } return 2; }
188 int start = time(NULL);
190 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
191 string newFastaFile = fileroot + "precluster" + m->getExtension(fastafile);
192 string newNamesFile = fileroot + "precluster.names";
195 //clear out old files
196 ofstream outFasta; m->openOutputFile(newFastaFile, outFasta); outFasta.close();
197 ofstream outNames; m->openOutputFile(newNamesFile, outNames); outNames.close();
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); }
204 vector<string> groups = parser->getNamesOfGroups();
206 //precluster each group
207 for (int i = 0; i < groups.size(); i++) {
211 if (m->control_pressed) { delete parser; m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
213 m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[i] + ":"); m->mothurOutEndLine();
215 map<string, string> thisNameMap;
216 if (namefile != "") { thisNameMap = parser->getNameMap(groups[i]); }
217 vector<Sequence> thisSeqs = parser->getSeqs(groups[i]);
219 //fill alignSeqs with this groups info.
220 int numSeqs = loadSeqs(thisNameMap, thisSeqs);
222 if (m->control_pressed) { delete parser; m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
224 if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0; }
226 int count = process();
228 if (m->control_pressed) { delete parser; m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
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);
234 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
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();
245 Command* uniqueCommand = new DeconvoluteCommand(inputString);
246 uniqueCommand->execute();
248 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
250 delete uniqueCommand;
252 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
254 newNamesFile = filenames["name"][0];
255 newFastaFile = filenames["fasta"][0];
258 if (namefile != "") { readNameFile(); }
260 //reads fasta file and return number of seqs
261 int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
263 if (m->control_pressed) { return 0; }
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; }
268 int count = process();
270 if (m->control_pressed) { return 0; }
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);
276 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
279 if (m->control_pressed) { m->mothurRemove(newFastaFile); m->mothurRemove(newNamesFile); return 0; }
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();
287 //set fasta file as new current fastafile
289 itTypes = outputTypes.find("fasta");
290 if (itTypes != outputTypes.end()) {
291 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
294 itTypes = outputTypes.find("name");
295 if (itTypes != outputTypes.end()) {
296 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
302 catch(exception& e) {
303 m->errorOut(e, "PreClusterCommand", "execute");
307 /**************************************************************************************************/
308 int PreClusterCommand::process(){
311 //sort seqs by number of identical seqs
312 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
315 int numSeqs = alignSeqs.size();
317 //think about running through twice...
318 for (int i = 0; i < numSeqs; i++) {
321 // itActive = active.find(alignSeqs[i].seq.getName());
323 if (alignSeqs[i].active) { //this sequence has not been merged yet
325 //try to merge it with all smaller seqs
326 for (int j = i+1; j < numSeqs; j++) {
328 if (m->control_pressed) { return 0; }
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());
334 if (mismatch <= diffs) {
336 alignSeqs[i].names += ',' + alignSeqs[j].names;
337 alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
339 alignSeqs[j].active = 0;
340 alignSeqs[j].numIdentical = 0;
346 //remove from active list
347 alignSeqs[i].active = 0;
350 if(i % 100 == 0) { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
353 if(numSeqs % 100 != 0) { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
358 catch(exception& e) {
359 m->errorOut(e, "PreClusterCommand", "process");
363 /**************************************************************************************************/
364 int PreClusterCommand::readFASTA(){
369 //m->openInputFile(namefile, inNames);
370 m->openInputFile(fastafile, inFasta);
372 //string firstCol, secondCol, nameString;
375 while (!inFasta.eof()) {
377 if (m->control_pressed) { inFasta.close(); return 0; }
379 //inNames >> firstCol >> secondCol;
380 //nameString = secondCol;
382 //m->gobble(inNames);
384 //while (secondCol.find_first_of(',') != -1) {
386 // secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
389 Sequence seq(inFasta); m->gobble(inFasta);
391 if (seq.getName() != "") { //can get "" if commented line is at end of fasta file
392 if (namefile != "") {
393 itSize = sizes.find(seq.getName());
395 if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
397 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
398 alignSeqs.push_back(tempNode);
399 if (seq.getAligned().length() > length) { length = seq.getAligned().length(); }
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(); }
410 return alignSeqs.size();
413 catch(exception& e) {
414 m->errorOut(e, "PreClusterCommand", "readFASTA");
418 /**************************************************************************************************/
419 int PreClusterCommand::loadSeqs(map<string, string>& thisName, vector<Sequence>& thisSeqs){
423 map<string, string>::iterator it;
426 for (int i = 0; i < thisSeqs.size(); i++) {
428 if (m->control_pressed) { return 0; }
430 if (namefile != "") {
431 it = thisName.find(thisSeqs[i].getName());
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; }
438 for(int j=0;j<(it->second).length();j++){
439 if((it->second)[j] == ','){ numReps++; }
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(); }
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(); }
454 if (error) { m->control_pressed = true; }
458 return alignSeqs.size();
461 catch(exception& e) {
462 m->errorOut(e, "PreClusterCommand", "loadSeqs");
467 /**************************************************************************************************/
469 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
473 for (int i = 0; i < seq1.length(); i++) {
475 if (seq1[i] != seq2[i]) { numBad++; }
476 if (numBad > diffs) { return length; } //to far to cluster
481 catch(exception& e) {
482 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
487 /**************************************************************************************************/
489 void PreClusterCommand::printData(string newfasta, string newname){
495 m->openOutputFileAppend(newfasta, outFasta);
496 m->openOutputFileAppend(newname, outNames);
498 m->openOutputFile(newfasta, outFasta);
499 m->openOutputFile(newname, outNames);
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;
513 catch(exception& e) {
514 m->errorOut(e, "PreClusterCommand", "printData");
518 /**************************************************************************************************/
520 void PreClusterCommand::readNameFile(){
523 m->openInputFile(namefile, in);
524 string firstCol, secondCol;
527 in >> firstCol >> secondCol; m->gobble(in);
528 names[firstCol] = secondCol;
531 for(int i=0;i<secondCol.size();i++){
532 if(secondCol[i] == ','){ size++; }
534 sizes[firstCol] = size;
538 catch(exception& e) {
539 m->errorOut(e, "PreClusterCommand", "readNameFile");
544 /**************************************************************************************************/