2 * classifyseqscommand.cpp
5 * Created by westcott on 11/2/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
10 #include "classifyseqscommand.h"
14 //**********************************************************************************************************************
15 vector<string> ClassifySeqsCommand::setParameters(){
17 CommandParameter ptaxonomy("taxonomy", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptaxonomy);
18 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
19 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
20 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
21 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
22 CommandParameter psearch("search", "Multiple", "kmer-blast-suffix-distance", "kmer", "", "", "",false,false); parameters.push_back(psearch);
23 CommandParameter pksize("ksize", "Number", "", "8", "", "", "",false,false); parameters.push_back(pksize);
24 CommandParameter pmethod("method", "Multiple", "bayesian-knn", "bayesian", "", "", "",false,false); parameters.push_back(pmethod);
25 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
26 CommandParameter pmatch("match", "Number", "", "1.0", "", "", "",false,false); parameters.push_back(pmatch);
27 CommandParameter pmismatch("mismatch", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pmismatch);
28 CommandParameter pgapopen("gapopen", "Number", "", "-2.0", "", "", "",false,false); parameters.push_back(pgapopen);
29 CommandParameter pgapextend("gapextend", "Number", "", "-1.0", "", "", "",false,false); parameters.push_back(pgapextend);
30 //CommandParameter pflip("flip", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pflip);
31 CommandParameter pcutoff("cutoff", "Number", "", "0", "", "", "",false,true); parameters.push_back(pcutoff);
32 CommandParameter pprobs("probs", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(pprobs);
33 CommandParameter piters("iters", "Number", "", "100", "", "", "",false,true); parameters.push_back(piters);
34 CommandParameter psave("save", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psave);
35 CommandParameter pnumwanted("numwanted", "Number", "", "10", "", "", "",false,true); parameters.push_back(pnumwanted);
36 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
37 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
39 vector<string> myArray;
40 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
44 m->errorOut(e, "ClassifySeqsCommand", "setParameters");
48 //**********************************************************************************************************************
49 string ClassifySeqsCommand::getHelpString(){
51 string helpString = "";
52 helpString += "The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n";
53 helpString += "The classify.seqs command parameters are reference, fasta, name, search, ksize, method, taxonomy, processors, match, mismatch, gapopen, gapextend, numwanted and probs.\n";
54 helpString += "The reference, fasta and taxonomy parameters are required. You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n";
55 helpString += "The search parameter allows you to specify the method to find most similar template. Your options are: suffix, kmer, blast and distance. The default is kmer.\n";
56 helpString += "The name parameter allows you add a names file with your fasta file, if you enter multiple fasta files, you must enter matching names files for them.\n";
57 helpString += "The group parameter allows you add a group file so you can have the summary totals broken up by group.\n";
58 helpString += "The method parameter allows you to specify classification method to use. Your options are: bayesian and knn. The default is bayesian.\n";
59 helpString += "The ksize parameter allows you to specify the kmer size for finding most similar template to candidate. The default is 8.\n";
60 helpString += "The processors parameter allows you to specify the number of processors to use. The default is 1.\n";
62 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
64 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
65 helpString += "The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n";
66 helpString += "The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n";
67 helpString += "The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n";
68 helpString += "The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -1.0.\n";
69 helpString += "The numwanted parameter allows you to specify the number of sequence matches you want with the knn method. The default is 10.\n";
70 helpString += "The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy. The default is 0.\n";
71 helpString += "The probs parameter shuts off the bootstrapping results for the bayesian method. The default is true, meaning you want the bootstrapping to be shown.\n";
72 helpString += "The iters parameter allows you to specify how many iterations to do when calculating the bootstrap confidence score for your taxonomy with the bayesian method. The default is 100.\n";
73 //helpString += "The flip parameter allows you shut off mothur's The default is T.\n";
74 helpString += "The classify.seqs command should be in the following format: \n";
75 helpString += "classify.seqs(reference=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n";
76 helpString += "Example classify.seqs(fasta=amazon.fasta, reference=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n";
77 helpString += "The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n";
78 helpString += "The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n";
79 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
83 m->errorOut(e, "ClassifySeqsCommand", "getHelpString");
87 //**********************************************************************************************************************
88 string ClassifySeqsCommand::getOutputFileNameTag(string type, string inputName=""){
90 string outputFileName = "";
91 map<string, vector<string> >::iterator it;
93 //is this a type this command creates
94 it = outputTypes.find(type);
95 if (it == outputTypes.end()) { m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
97 if (type == "taxonomy") { outputFileName = "taxonomy"; }
98 else if (type == "accnos") { outputFileName = "flip.accnos"; }
99 else if (type == "taxsummary") { outputFileName = "tax.summary"; }
100 else if (type == "matchdist") { outputFileName = "match.dist"; }
101 else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true; }
103 return outputFileName;
105 catch(exception& e) {
106 m->errorOut(e, "ClassifySeqsCommand", "getOutputFileNameTag");
110 //**********************************************************************************************************************
111 ClassifySeqsCommand::ClassifySeqsCommand(){
113 abort = true; calledHelp = true;
115 vector<string> tempOutNames;
116 outputTypes["taxonomy"] = tempOutNames;
117 outputTypes["accnos"] = tempOutNames;
118 outputTypes["taxsummary"] = tempOutNames;
119 outputTypes["matchdist"] = tempOutNames;
121 catch(exception& e) {
122 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
126 //**********************************************************************************************************************
127 ClassifySeqsCommand::ClassifySeqsCommand(string option) {
129 abort = false; calledHelp = false;
130 rdb = ReferenceDB::getInstance();
132 //allow user to run help
133 if(option == "help") { help(); abort = true; calledHelp = true; }
134 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
137 vector<string> myArray = setParameters();
139 OptionParser parser(option);
140 map<string, string> parameters = parser.getParameters();
142 ValidParameters validParameter("classify.seqs");
143 map<string, string>::iterator it;
145 //check to make sure all parameters are valid for command
146 for (it = parameters.begin(); it != parameters.end(); it++) {
147 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
150 //initialize outputTypes
151 vector<string> tempOutNames;
152 outputTypes["taxonomy"] = tempOutNames;
153 outputTypes["taxsummary"] = tempOutNames;
154 outputTypes["matchdist"] = tempOutNames;
155 outputTypes["accnos"] = tempOutNames;
157 //if the user changes the output directory command factory will send this info to us in the output parameter
158 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
160 //if the user changes the input directory command factory will send this info to us in the output parameter
161 string inputDir = validParameter.validFile(parameters, "inputdir", false);
162 if (inputDir == "not found"){ inputDir = ""; }
165 it = parameters.find("reference");
166 //user has given a template file
167 if(it != parameters.end()){
168 path = m->hasPath(it->second);
169 //if the user has not given a path then, add inputdir. else leave path alone.
170 if (path == "") { parameters["reference"] = inputDir + it->second; }
173 it = parameters.find("taxonomy");
174 //user has given a template file
175 if(it != parameters.end()){
176 path = m->hasPath(it->second);
177 //if the user has not given a path then, add inputdir. else leave path alone.
178 if (path == "") { parameters["taxonomy"] = inputDir + it->second; }
181 it = parameters.find("group");
182 //user has given a template file
183 if(it != parameters.end()){
184 path = m->hasPath(it->second);
185 //if the user has not given a path then, add inputdir. else leave path alone.
186 if (path == "") { parameters["group"] = inputDir + it->second; }
190 fastaFileName = validParameter.validFile(parameters, "fasta", false);
191 if (fastaFileName == "not found") {
192 //if there is a current fasta file, use it
193 string filename = m->getFastaFile();
194 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
195 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
198 m->splitAtDash(fastaFileName, fastaFileNames);
200 //go through files and make sure they are good, if not, then disregard them
201 for (int i = 0; i < fastaFileNames.size(); i++) {
204 if (fastaFileNames[i] == "current") {
205 fastaFileNames[i] = m->getFastaFile();
206 if (fastaFileNames[i] != "") { m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
208 m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true;
209 //erase from file list
210 fastaFileNames.erase(fastaFileNames.begin()+i);
217 if (inputDir != "") {
218 string path = m->hasPath(fastaFileNames[i]);
219 //if the user has not given a path then, add inputdir. else leave path alone.
220 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
226 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
228 //if you can't open it, try default location
229 if (ableToOpen == 1) {
230 if (m->getDefaultPath() != "") { //default path is set
231 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
232 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
234 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
236 fastaFileNames[i] = tryPath;
240 if (ableToOpen == 1) {
241 if (m->getOutputDir() != "") { //default path is set
242 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
243 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
245 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
247 fastaFileNames[i] = tryPath;
253 if (ableToOpen == 1) {
254 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
255 //erase from file list
256 fastaFileNames.erase(fastaFileNames.begin()+i);
259 m->setFastaFile(fastaFileNames[i]);
265 //make sure there is at least one valid file left
266 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
269 namefile = validParameter.validFile(parameters, "name", false);
270 if (namefile == "not found") { namefile = ""; }
273 m->splitAtDash(namefile, namefileNames);
275 //go through files and make sure they are good, if not, then disregard them
276 for (int i = 0; i < namefileNames.size(); i++) {
278 if (namefileNames[i] == "current") {
279 namefileNames[i] = m->getNameFile();
280 if (namefileNames[i] != "") { m->mothurOut("Using " + namefileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
282 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
283 //erase from file list
284 namefileNames.erase(namefileNames.begin()+i);
291 if (inputDir != "") {
292 string path = m->hasPath(namefileNames[i]);
293 //if the user has not given a path then, add inputdir. else leave path alone.
294 if (path == "") { namefileNames[i] = inputDir + namefileNames[i]; }
299 ableToOpen = m->openInputFile(namefileNames[i], in, "noerror");
301 //if you can't open it, try default location
302 if (ableToOpen == 1) {
303 if (m->getDefaultPath() != "") { //default path is set
304 string tryPath = m->getDefaultPath() + m->getSimpleName(namefileNames[i]);
305 m->mothurOut("Unable to open " + namefileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
307 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
309 namefileNames[i] = tryPath;
313 if (ableToOpen == 1) {
314 if (m->getOutputDir() != "") { //default path is set
315 string tryPath = m->getOutputDir() + m->getSimpleName(namefileNames[i]);
316 m->mothurOut("Unable to open " + namefileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
318 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
320 namefileNames[i] = tryPath;
325 if (ableToOpen == 1) {
326 m->mothurOut("Unable to open " + namefileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); abort = true;
327 //erase from file list
328 namefileNames.erase(namefileNames.begin()+i);
331 m->setNameFile(namefileNames[i]);
337 if (namefile != "") {
338 if (namefileNames.size() != fastaFileNames.size()) { abort = true; m->mothurOut("If you provide a name file, you must have one for each fasta file."); m->mothurOutEndLine(); }
341 groupfile = validParameter.validFile(parameters, "group", false);
342 if (groupfile == "not found") { groupfile = ""; }
344 m->splitAtDash(groupfile, groupfileNames);
346 //go through files and make sure they are good, if not, then disregard them
347 for (int i = 0; i < groupfileNames.size(); i++) {
348 if (inputDir != "") {
349 string path = m->hasPath(groupfileNames[i]);
350 //if the user has not given a path then, add inputdir. else leave path alone.
351 if (path == "") { groupfileNames[i] = inputDir + groupfileNames[i]; }
356 ableToOpen = m->openInputFile(groupfileNames[i], in, "noerror");
358 //if you can't open it, try default location
359 if (ableToOpen == 1) {
360 if (m->getDefaultPath() != "") { //default path is set
361 string tryPath = m->getDefaultPath() + m->getSimpleName(groupfileNames[i]);
362 m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
364 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
366 groupfileNames[i] = tryPath;
370 if (ableToOpen == 1) {
371 if (m->getOutputDir() != "") { //default path is set
372 string tryPath = m->getOutputDir() + m->getSimpleName(groupfileNames[i]);
373 m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
375 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
377 groupfileNames[i] = tryPath;
383 if (ableToOpen == 1) {
384 m->mothurOut("Unable to open " + groupfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); groupfileNames[i] = "";
385 //erase from file list
386 groupfileNames.erase(groupfileNames.begin()+i);
389 m->setGroupFile(groupfileNames[i]);
394 if (groupfile != "") {
395 if (groupfileNames.size() != fastaFileNames.size()) { abort = true; m->mothurOut("If you provide a group file, you must have one for each fasta file."); m->mothurOutEndLine(); }
397 for (int i = 0; i < fastaFileNames.size(); i++) { groupfileNames.push_back(""); }
400 //check for optional parameter and set defaults
401 // ...at some point should added some additional type checking...
403 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found"){ temp = "8"; }
404 m->mothurConvert(temp, kmerSize);
406 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
407 m->setProcessors(temp);
408 m->mothurConvert(temp, processors);
410 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
411 save = m->isTrue(temp);
413 if (save) { //clear out old references
417 //this has to go after save so that if the user sets save=t and provides no reference we abort
418 templateFileName = validParameter.validFile(parameters, "reference", true);
419 if (templateFileName == "not found") {
420 //check for saved reference sequences
421 if (rdb->referenceSeqs.size() != 0) {
422 templateFileName = "saved";
424 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required for the classify.seqs command.");
425 m->mothurOutEndLine();
428 }else if (templateFileName == "not open") { abort = true; }
429 else { if (save) { rdb->setSavedReference(templateFileName); } }
431 //this has to go after save so that if the user sets save=t and provides no reference we abort
432 taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
433 if (taxonomyFileName == "not found") {
434 //check for saved reference sequences
435 if (rdb->wordGenusProb.size() != 0) {
436 taxonomyFileName = "saved";
438 m->mothurOut("[ERROR]: You don't have any saved taxonomy information and the taxonomy parameter is a required for the classify.seqs command.");
439 m->mothurOutEndLine();
442 }else if (taxonomyFileName == "not open") { abort = true; }
443 else { if (save) { rdb->setSavedTaxonomy(taxonomyFileName); } }
445 search = validParameter.validFile(parameters, "search", false); if (search == "not found"){ search = "kmer"; }
447 method = validParameter.validFile(parameters, "method", false); if (method == "not found"){ method = "bayesian"; }
449 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found"){ temp = "1.0"; }
450 m->mothurConvert(temp, match);
452 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found"){ temp = "-1.0"; }
453 m->mothurConvert(temp, misMatch);
455 temp = validParameter.validFile(parameters, "gapopen", false); if (temp == "not found"){ temp = "-2.0"; }
456 m->mothurConvert(temp, gapOpen);
458 temp = validParameter.validFile(parameters, "gapextend", false); if (temp == "not found"){ temp = "-1.0"; }
459 m->mothurConvert(temp, gapExtend);
461 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found"){ temp = "10"; }
462 m->mothurConvert(temp, numWanted);
464 temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found"){ temp = "0"; }
465 m->mothurConvert(temp, cutoff);
467 temp = validParameter.validFile(parameters, "probs", false); if (temp == "not found"){ temp = "true"; }
468 probs = m->isTrue(temp);
470 //temp = validParameter.validFile(parameters, "flip", false); if (temp == "not found"){ temp = "T"; }
471 //flip = m->isTrue(temp);
474 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "100"; }
475 m->mothurConvert(temp, iters);
478 if ((method == "bayesian") && (search != "kmer")) {
479 m->mothurOut("The bayesian method requires the kmer search." + search + "will be disregarded." ); m->mothurOutEndLine();
484 if (namefileNames.size() == 0){
485 if (fastaFileNames.size() != 0) {
486 vector<string> files; files.push_back(fastaFileNames[fastaFileNames.size()-1]);
487 parser.getNameFile(files);
493 catch(exception& e) {
494 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
499 //**********************************************************************************************************************
500 ClassifySeqsCommand::~ClassifySeqsCommand(){
501 if (abort == false) {
502 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
505 //**********************************************************************************************************************
507 int ClassifySeqsCommand::execute(){
509 if (abort == true) { if (calledHelp) { return 0; } return 2; }
511 if(method == "bayesian"){ classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters, rand(), flip); }
512 else if(method == "knn"){ classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted, rand()); }
514 m->mothurOut(search + " is not a valid method option. I will run the command using bayesian.");
515 m->mothurOutEndLine();
516 classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters, rand(), flip);
519 if (m->control_pressed) { delete classify; return 0; }
521 for (int s = 0; s < fastaFileNames.size(); s++) {
523 m->mothurOut("Classifying sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
525 string baseTName = taxonomyFileName;
526 if (taxonomyFileName == "saved") {baseTName = rdb->getSavedTaxonomy(); }
528 //set rippedTaxName to
529 string RippedTaxName = "";
530 bool foundDot = false;
531 for (int i = baseTName.length()-1; i >= 0; i--) {
532 if (foundDot && (baseTName[i] != '.')) { RippedTaxName = baseTName[i] + RippedTaxName; }
533 else if (foundDot && (baseTName[i] == '.')) { break; }
534 else if (!foundDot && (baseTName[i] == '.')) { foundDot = true; }
536 if (RippedTaxName != "") { RippedTaxName += "."; }
538 if (outputDir == "") { outputDir += m->hasPath(fastaFileNames[s]); }
539 string newTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + getOutputFileNameTag("taxonomy");
540 string newaccnosFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + getOutputFileNameTag("accnos");
541 string tempTaxonomyFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "taxonomy.temp";
542 string taxSummary = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + RippedTaxName + getOutputFileNameTag("taxsummary");
544 if ((method == "knn") && (search == "distance")) {
545 string DistName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + getOutputFileNameTag("matchdist");
546 classify->setDistName(DistName); outputNames.push_back(DistName); outputTypes["matchdist"].push_back(DistName);
549 outputNames.push_back(newTaxonomyFile); outputTypes["taxonomy"].push_back(newTaxonomyFile);
550 outputNames.push_back(newaccnosFile); outputTypes["accnos"].push_back(newaccnosFile);
551 outputNames.push_back(taxSummary); outputTypes["taxsummary"].push_back(taxSummary);
553 int start = time(NULL);
554 int numFastaSeqs = 0;
555 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
558 int pid, numSeqsPerProcessor;
560 vector<unsigned long long> MPIPos;
563 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
564 MPI_Comm_size(MPI_COMM_WORLD, &processors);
567 MPI_File outMPINewTax;
568 MPI_File outMPITempTax;
571 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
572 int inMode=MPI_MODE_RDONLY;
574 char outNewTax[1024];
575 strcpy(outNewTax, newTaxonomyFile.c_str());
577 char outTempTax[1024];
578 strcpy(outTempTax, tempTaxonomyFile.c_str());
581 strcpy(outAcc, newaccnosFile.c_str());
583 char inFileName[1024];
584 strcpy(inFileName, fastaFileNames[s].c_str());
586 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
587 MPI_File_open(MPI_COMM_WORLD, outNewTax, outMode, MPI_INFO_NULL, &outMPINewTax);
588 MPI_File_open(MPI_COMM_WORLD, outTempTax, outMode, MPI_INFO_NULL, &outMPITempTax);
589 MPI_File_open(MPI_COMM_WORLD, outAcc, outMode, MPI_INFO_NULL, &outMPIAcc);
591 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&inMPI); MPI_File_close(&outMPINewTax); MPI_File_close(&outMPIAcc); MPI_File_close(&outMPITempTax); delete classify; return 0; }
593 if (pid == 0) { //you are the root process
595 MPIPos = m->setFilePosFasta(fastaFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs
597 //send file positions to all processes
598 for(int i = 1; i < processors; i++) {
599 MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
600 MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
603 //figure out how many sequences you have to align
604 numSeqsPerProcessor = numFastaSeqs / processors;
605 int startIndex = pid * numSeqsPerProcessor;
606 if(pid == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor; }
610 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, outMPIAcc, MPIPos);
612 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&inMPI); MPI_File_close(&outMPINewTax); MPI_File_close(&outMPIAcc); MPI_File_close(&outMPITempTax); for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } delete classify; return 0; }
614 for (int i = 1; i < processors; i++) {
616 MPI_Recv(&done, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
618 }else{ //you are a child process
619 MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
620 MPIPos.resize(numFastaSeqs+1);
621 MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
623 //figure out how many sequences you have to align
624 numSeqsPerProcessor = numFastaSeqs / processors;
625 int startIndex = pid * numSeqsPerProcessor;
626 if(pid == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor; }
630 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, outMPIAcc, MPIPos);
632 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&inMPI); MPI_File_close(&outMPINewTax); MPI_File_close(&outMPIAcc); MPI_File_close(&outMPITempTax); delete classify; return 0; }
635 MPI_Send(&done, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
639 MPI_File_close(&inMPI);
640 MPI_File_close(&outMPINewTax);
641 MPI_File_close(&outMPITempTax);
642 MPI_File_close(&outMPIAcc);
643 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
647 vector<unsigned long long> positions;
648 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
649 positions = m->divideFile(fastaFileNames[s], processors);
650 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(new linePair(positions[i], positions[(i+1)])); }
652 if (processors == 1) {
653 lines.push_back(new linePair(0, 1000));
655 positions = m->setFilePosFasta(fastaFileNames[s], numFastaSeqs);
656 if (positions.size() < processors) { processors = positions.size(); }
658 //figure out how many sequences you have to process
659 int numSeqsPerProcessor = numFastaSeqs / processors;
660 for (int i = 0; i < processors; i++) {
661 int startIndex = i * numSeqsPerProcessor;
662 if(i == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor; }
663 lines.push_back(new linePair(positions[startIndex], numSeqsPerProcessor));
668 numFastaSeqs = driver(lines[0], newTaxonomyFile, tempTaxonomyFile, newaccnosFile, fastaFileNames[s]);
670 numFastaSeqs = createProcesses(newTaxonomyFile, tempTaxonomyFile, newaccnosFile, fastaFileNames[s]);
674 if (!m->isBlank(newaccnosFile)) { m->mothurOutEndLine(); m->mothurOut("[WARNING]: mothur suspects some of your sequences may be reversed, please check " + newaccnosFile + " for the list of the sequences."); m->mothurOutEndLine(); }
676 m->mothurOutEndLine();
677 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
683 if (pid == 0) { //this part does not need to be paralellized
685 if(namefile != "") { m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush(); MPIReadNamesFile(namefileNames[s]); m->mothurOut(" Done."); m->mothurOutEndLine(); }
690 m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();
691 nameMap.clear(); //remove old names
692 m->readNames(namefileNames[s], nameMap);
693 m->mothurOut(" Done."); m->mothurOutEndLine();
698 if (groupfile != "") { group = groupfileNames[s]; }
700 PhyloSummary taxaSum(baseTName, group);
702 if (m->control_pressed) { outputTypes.clear(); for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } delete classify; return 0; }
704 if (namefile == "") { taxaSum.summarize(tempTaxonomyFile); }
707 m->openInputFile(tempTaxonomyFile, in);
709 //read in users taxonomy file and add sequences to tree
713 in >> name >> taxon; m->gobble(in);
715 itNames = nameMap.find(name);
717 if (itNames == nameMap.end()) {
718 m->mothurOut(name + " is not in your name file please correct."); m->mothurOutEndLine(); exit(1);
720 for (int i = 0; i < itNames->second.size(); i++) {
721 taxaSum.addSeqToTree(itNames->second[i], taxon); //add it as many times as there are identical seqs
723 itNames->second.clear();
724 nameMap.erase(itNames->first);
729 m->mothurRemove(tempTaxonomyFile);
731 if (m->control_pressed) { outputTypes.clear(); for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } delete classify; return 0; }
735 m->openOutputFile(taxSummary, outTaxTree);
736 taxaSum.print(outTaxTree);
739 //output taxonomy with the unclassified bins added
741 m->openInputFile(newTaxonomyFile, inTax);
744 string unclass = newTaxonomyFile + ".unclass.temp";
745 m->openOutputFile(unclass, outTax);
747 //get maxLevel from phylotree so you know how many 'unclassified's to add
748 int maxLevel = taxaSum.getMaxLevel();
750 //read taxfile - this reading and rewriting is done to preserve the confidence scores.
752 while (!inTax.eof()) {
753 if (m->control_pressed) { outputTypes.clear(); for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } m->mothurRemove(unclass); delete classify; return 0; }
755 inTax >> name >> taxon; m->gobble(inTax);
757 string newTax = addUnclassifieds(taxon, maxLevel);
759 outTax << name << '\t' << newTax << endl;
764 m->mothurRemove(newTaxonomyFile);
765 rename(unclass.c_str(), newTaxonomyFile.c_str());
767 m->mothurOutEndLine();
768 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
774 m->mothurOutEndLine();
775 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
776 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
777 m->mothurOutEndLine();
780 //set taxonomy file as new current taxonomyfile
782 itTypes = outputTypes.find("taxonomy");
783 if (itTypes != outputTypes.end()) {
784 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTaxonomyFile(current); }
788 itTypes = outputTypes.find("accnos");
789 if (itTypes != outputTypes.end()) {
790 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
797 catch(exception& e) {
798 m->errorOut(e, "ClassifySeqsCommand", "execute");
803 /**************************************************************************************************/
804 string ClassifySeqsCommand::addUnclassifieds(string tax, int maxlevel) {
806 string newTax, taxon;
809 //keep what you have counting the levels
810 while (tax.find_first_of(';') != -1) {
812 taxon = tax.substr(0,tax.find_first_of(';'))+';';
813 tax = tax.substr(tax.find_first_of(';')+1, tax.length());
818 //add "unclassified" until you reach maxLevel
819 while (level < maxlevel) {
820 newTax += "unclassified;";
826 catch(exception& e) {
827 m->errorOut(e, "ClassifySeqsCommand", "addUnclassifieds");
832 /**************************************************************************************************/
834 int ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile, string accnos, string filename) {
840 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
843 //loop through and create all the processes you want
844 while (process != processors) {
848 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
851 num = driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", filename);
853 //pass numSeqs to parent
855 string tempFile = filename + toString(getpid()) + ".num.temp";
856 m->openOutputFile(tempFile, out);
862 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
863 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
868 //parent does its part
869 num = driver(lines[0], taxFileName, tempTaxFile, accnos, filename);
871 //force parent to wait until all the processes are done
872 for (int i=0;i<processIDS.size();i++) {
873 int temp = processIDS[i];
877 for (int i = 0; i < processIDS.size(); i++) {
879 string tempFile = filename + toString(processIDS[i]) + ".num.temp";
880 m->openInputFile(tempFile, in);
881 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
882 in.close(); m->mothurRemove(m->getFullPathName(tempFile));
885 //////////////////////////////////////////////////////////////////////////////////////////////////////
886 //Windows version shared memory, so be careful when passing variables through the alignData struct.
887 //Above fork() will clone, so memory is separate, but that's not the case with windows,
888 //////////////////////////////////////////////////////////////////////////////////////////////////////
890 vector<classifyData*> pDataArray;
891 DWORD dwThreadIdArray[processors-1];
892 HANDLE hThreadArray[processors-1];
894 //Create processor worker threads.
895 for( int i=0; i<processors-1; i++ ){
896 // Allocate memory for thread data.
897 string extension = "";
898 if (i != 0) { extension = toString(i) + ".temp"; processIDS.push_back(i); }
900 classifyData* tempclass = new classifyData((accnos + extension), probs, method, templateFileName, taxonomyFileName, (taxFileName + extension), (tempTaxFile + extension), filename, search, kmerSize, iters, numWanted, m, lines[i]->start, lines[i]->end, match, misMatch, gapOpen, gapExtend, cutoff, i, flip);
901 pDataArray.push_back(tempclass);
903 //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
904 //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
905 hThreadArray[i] = CreateThread(NULL, 0, MyClassThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);
909 //parent does its part
910 num = driver(lines[processors-1], taxFileName + toString(processors-1) + ".temp", tempTaxFile + toString(processors-1) + ".temp", accnos + toString(processors-1) + ".temp", filename);
911 processIDS.push_back((processors-1));
913 //Wait until all threads have terminated.
914 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
916 //Close all thread handles and free memory allocations.
917 for(int i=0; i < pDataArray.size(); i++){
918 num += pDataArray[i]->count;
919 CloseHandle(hThreadArray[i]);
920 delete pDataArray[i];
924 vector<string> nonBlankAccnosFiles;
925 if (!(m->isBlank(accnos))) { nonBlankAccnosFiles.push_back(accnos); }
926 else { m->mothurRemove(accnos); } //remove so other files can be renamed to it
928 for(int i=0;i<processIDS.size();i++){
929 m->appendFiles((taxFileName + toString(processIDS[i]) + ".temp"), taxFileName);
930 m->appendFiles((tempTaxFile + toString(processIDS[i]) + ".temp"), tempTaxFile);
931 if (!(m->isBlank(accnos + toString(processIDS[i]) + ".temp"))) {
932 nonBlankAccnosFiles.push_back(accnos + toString(processIDS[i]) + ".temp");
933 }else { m->mothurRemove((accnos + toString(processIDS[i]) + ".temp")); }
935 m->mothurRemove((m->getFullPathName(taxFileName) + toString(processIDS[i]) + ".temp"));
936 m->mothurRemove((m->getFullPathName(tempTaxFile) + toString(processIDS[i]) + ".temp"));
939 //append accnos files
940 if (nonBlankAccnosFiles.size() != 0) {
941 rename(nonBlankAccnosFiles[0].c_str(), accnos.c_str());
943 for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
944 m->appendFiles(nonBlankAccnosFiles[h], accnos);
945 m->mothurRemove(nonBlankAccnosFiles[h]);
947 }else { //recreate the accnosfile if needed
949 m->openOutputFile(accnos, out);
956 catch(exception& e) {
957 m->errorOut(e, "ClassifySeqsCommand", "createProcesses");
961 //**********************************************************************************************************************
963 int ClassifySeqsCommand::driver(linePair* filePos, string taxFName, string tempTFName, string accnos, string filename){
966 m->openOutputFile(taxFName, outTax);
968 ofstream outTaxSimple;
969 m->openOutputFile(tempTFName, outTaxSimple);
972 m->openOutputFile(accnos, outAcc);
975 m->openInputFile(filename, inFASTA);
979 inFASTA.seekg(filePos->start);
985 if (m->control_pressed) {
988 outTaxSimple.close();
989 outAcc.close(); return 0; }
991 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
993 if (candidateSeq->getName() != "") {
995 taxonomy = classify->getTaxonomy(candidateSeq);
997 if (m->control_pressed) { delete candidateSeq; return 0; }
999 if (taxonomy == "unknown;") { m->mothurOut("[WARNING]: " + candidateSeq->getName() + " could not be classified. You can use the remove.lineage command with taxon=unknown; to remove such sequences."); m->mothurOutEndLine(); }
1001 //output confidence scores or not
1003 outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
1005 outTax << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
1008 if (classify->getFlipped()) { outAcc << candidateSeq->getName() << endl; }
1010 outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
1014 delete candidateSeq;
1016 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1017 unsigned long long pos = inFASTA.tellg();
1018 if ((pos == -1) || (pos >= filePos->end)) { break; }
1020 if (inFASTA.eof()) { break; }
1024 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1028 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
1032 outTaxSimple.close();
1037 catch(exception& e) {
1038 m->errorOut(e, "ClassifySeqsCommand", "driver");
1042 //**********************************************************************************************************************
1044 int ClassifySeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& newFile, MPI_File& tempFile, MPI_File& accFile, vector<unsigned long long>& MPIPos){
1046 MPI_Status statusNew;
1047 MPI_Status statusTemp;
1048 MPI_Status statusAcc;
1052 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1055 string outputString;
1057 for(int i=0;i<num;i++){
1059 if (m->control_pressed) { return 0; }
1061 //read next sequence
1062 int length = MPIPos[start+i+1] - MPIPos[start+i];
1063 char* buf4 = new char[length];
1064 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1066 string tempBuf = buf4;
1067 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
1068 istringstream iss (tempBuf,istringstream::in);
1071 Sequence* candidateSeq = new Sequence(iss);
1073 if (candidateSeq->getName() != "") {
1074 taxonomy = classify->getTaxonomy(candidateSeq);
1076 if (taxonomy == "unknown;") { m->mothurOut("[WARNING]: " + candidateSeq->getName() + " could not be classified. You can use the remove.lineage command with taxon=unknown; to remove such sequences."); m->mothurOutEndLine(); }
1078 //output confidence scores or not
1080 outputString = candidateSeq->getName() + "\t" + taxonomy + "\n";
1082 outputString = candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
1085 int length = outputString.length();
1086 char* buf2 = new char[length];
1087 memcpy(buf2, outputString.c_str(), length);
1089 MPI_File_write_shared(newFile, buf2, length, MPI_CHAR, &statusNew);
1092 outputString = candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
1093 length = outputString.length();
1094 char* buf = new char[length];
1095 memcpy(buf, outputString.c_str(), length);
1097 MPI_File_write_shared(tempFile, buf, length, MPI_CHAR, &statusTemp);
1100 if (classify->getFlipped()) {
1101 outputString = candidateSeq->getName() + "\n";
1102 length = outputString.length();
1103 char* buf3 = new char[length];
1104 memcpy(buf3, outputString.c_str(), length);
1106 MPI_File_write_shared(accFile, buf3, length, MPI_CHAR, &statusAcc);
1111 delete candidateSeq;
1113 if((i+1) % 100 == 0){ cout << "Classifying sequence " << (i+1) << endl; }
1116 if(num % 100 != 0){ cout << "Classifying sequence " << (num) << endl; }
1121 catch(exception& e) {
1122 m->errorOut(e, "ClassifySeqsCommand", "driverMPI");
1127 //**********************************************************************************************************************
1128 int ClassifySeqsCommand::MPIReadNamesFile(string nameFilename){
1131 nameMap.clear(); //remove old names
1137 //char* inFileName = new char[nameFilename.length()];
1138 //memcpy(inFileName, nameFilename.c_str(), nameFilename.length());
1140 char inFileName[1024];
1141 strcpy(inFileName, nameFilename.c_str());
1143 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
1144 MPI_File_get_size(inMPI, &size);
1145 //delete inFileName;
1147 char* buffer = new char[size];
1148 MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
1150 string tempBuf = buffer;
1151 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size); }
1152 istringstream iss (tempBuf,istringstream::in);
1155 string firstCol, secondCol;
1157 iss >> firstCol >> secondCol; m->gobble(iss);
1159 vector<string> temp;
1160 m->splitAtComma(secondCol, temp);
1162 nameMap[firstCol] = temp;
1165 MPI_File_close(&inMPI);
1169 catch(exception& e) {
1170 m->errorOut(e, "ClassifySeqsCommand", "MPIReadNamesFile");
1175 /**************************************************************************************************/