2 * classifyseqscommand.cpp
5 * Created by westcott on 11/2/09.
6 * Copyright 2009 Schloss Lab. All rights reserved.
10 #include "classifyseqscommand.h"
11 #include "sequence.hpp"
13 #include "phylotree.h"
14 #include "phylosummary.h"
17 //**********************************************************************************************************************
19 ClassifySeqsCommand::ClassifySeqsCommand(string option) {
23 //allow user to run help
24 if(option == "help") { help(); abort = true; }
28 //valid paramters for this command
29 string AlignArray[] = {"template","fasta","name","group","search","ksize","method","processors","taxonomy","match","mismatch","gapopen","gapextend","numwanted","cutoff","probs","iters", "outputdir","inputdir"};
30 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
32 OptionParser parser(option);
33 map<string, string> parameters = parser.getParameters();
35 ValidParameters validParameter("classify.seqs");
36 map<string, string>::iterator it;
38 //check to make sure all parameters are valid for command
39 for (it = parameters.begin(); it != parameters.end(); it++) {
40 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
43 //if the user changes the output directory command factory will send this info to us in the output parameter
44 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
46 //if the user changes the input directory command factory will send this info to us in the output parameter
47 string inputDir = validParameter.validFile(parameters, "inputdir", false);
48 if (inputDir == "not found"){ inputDir = ""; }
51 it = parameters.find("template");
52 //user has given a template file
53 if(it != parameters.end()){
54 path = hasPath(it->second);
55 //if the user has not given a path then, add inputdir. else leave path alone.
56 if (path == "") { parameters["template"] = inputDir + it->second; }
59 it = parameters.find("taxonomy");
60 //user has given a template file
61 if(it != parameters.end()){
62 path = hasPath(it->second);
63 //if the user has not given a path then, add inputdir. else leave path alone.
64 if (path == "") { parameters["taxonomy"] = inputDir + it->second; }
67 it = parameters.find("group");
68 //user has given a template file
69 if(it != parameters.end()){
70 path = hasPath(it->second);
71 //if the user has not given a path then, add inputdir. else leave path alone.
72 if (path == "") { parameters["group"] = inputDir + it->second; }
76 //check for required parameters
77 templateFileName = validParameter.validFile(parameters, "template", true);
78 if (templateFileName == "not found") {
79 m->mothurOut("template is a required parameter for the classify.seqs command.");
80 m->mothurOutEndLine();
83 else if (templateFileName == "not open") { abort = true; }
86 fastaFileName = validParameter.validFile(parameters, "fasta", false);
87 if (fastaFileName == "not found") { m->mothurOut("fasta is a required parameter for the classify.seqs command."); m->mothurOutEndLine(); abort = true; }
89 splitAtDash(fastaFileName, fastaFileNames);
91 //go through files and make sure they are good, if not, then disregard them
92 for (int i = 0; i < fastaFileNames.size(); i++) {
94 string path = hasPath(fastaFileNames[i]);
95 //if the user has not given a path then, add inputdir. else leave path alone.
96 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
103 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
104 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
110 ableToOpen = openInputFile(fastaFileNames[i], in, "noerror");
112 //if you can't open it, try default location
113 if (ableToOpen == 1) {
114 if (m->getDefaultPath() != "") { //default path is set
115 string tryPath = m->getDefaultPath() + getSimpleName(fastaFileNames[i]);
116 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
117 ableToOpen = openInputFile(tryPath, in, "noerror");
118 fastaFileNames[i] = tryPath;
124 for (int j = 1; j < processors; j++) {
125 MPI_Send(&ableToOpen, 1, MPI_INT, j, 2001, MPI_COMM_WORLD);
129 MPI_Recv(&ableToOpen, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
134 if (ableToOpen == 1) {
135 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
136 //erase from file list
137 fastaFileNames.erase(fastaFileNames.begin()+i);
143 //make sure there is at least one valid file left
144 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
148 taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
149 if (taxonomyFileName == "not found") {
150 m->mothurOut("taxonomy is a required parameter for the classify.seqs command.");
151 m->mothurOutEndLine();
154 else if (taxonomyFileName == "not open") { abort = true; }
157 namefile = validParameter.validFile(parameters, "name", false);
158 if (namefile == "not found") { namefile = ""; }
161 splitAtDash(namefile, namefileNames);
163 //go through files and make sure they are good, if not, then disregard them
164 for (int i = 0; i < namefileNames.size(); i++) {
165 if (inputDir != "") {
166 string path = hasPath(namefileNames[i]);
167 //if the user has not given a path then, add inputdir. else leave path alone.
168 if (path == "") { namefileNames[i] = inputDir + namefileNames[i]; }
174 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
175 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
181 ableToOpen = openInputFile(namefileNames[i], in, "noerror");
183 //if you can't open it, try default location
184 if (ableToOpen == 1) {
185 if (m->getDefaultPath() != "") { //default path is set
186 string tryPath = m->getDefaultPath() + getSimpleName(namefileNames[i]);
187 m->mothurOut("Unable to open " + namefileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
188 ableToOpen = openInputFile(tryPath, in, "noerror");
189 namefileNames[i] = tryPath;
195 for (int j = 1; j < processors; j++) {
196 MPI_Send(&ableToOpen, 1, MPI_INT, j, 2001, MPI_COMM_WORLD);
200 MPI_Recv(&ableToOpen, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
205 if (ableToOpen == 1) {
206 m->mothurOut("Unable to open " + namefileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); abort = true;
207 //erase from file list
208 namefileNames.erase(namefileNames.begin()+i);
215 if (namefile != "") {
216 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(); }
219 groupfile = validParameter.validFile(parameters, "group", false);
220 if (groupfile == "not found") { groupfile = ""; }
222 splitAtDash(groupfile, groupfileNames);
224 //go through files and make sure they are good, if not, then disregard them
225 for (int i = 0; i < groupfileNames.size(); i++) {
226 if (inputDir != "") {
227 string path = hasPath(groupfileNames[i]);
228 //if the user has not given a path then, add inputdir. else leave path alone.
229 if (path == "") { groupfileNames[i] = inputDir + groupfileNames[i]; }
235 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
236 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
242 ableToOpen = openInputFile(groupfileNames[i], in, "noerror");
244 //if you can't open it, try default location
245 if (ableToOpen == 1) {
246 if (m->getDefaultPath() != "") { //default path is set
247 string tryPath = m->getDefaultPath() + getSimpleName(groupfileNames[i]);
248 m->mothurOut("Unable to open " + groupfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
249 ableToOpen = openInputFile(tryPath, in, "noerror");
250 groupfileNames[i] = tryPath;
256 for (int j = 1; j < processors; j++) {
257 MPI_Send(&ableToOpen, 1, MPI_INT, j, 2001, MPI_COMM_WORLD);
261 MPI_Recv(&ableToOpen, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
266 if (ableToOpen == 1) {
267 m->mothurOut("Unable to open " + groupfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); groupfileNames[i] = "";
268 //erase from file list
269 groupfileNames.erase(groupfileNames.begin()+i);
275 if (groupfile != "") {
276 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(); }
278 for (int i = 0; i < fastaFileNames.size(); i++) { groupfileNames.push_back(""); }
281 //check for optional parameter and set defaults
282 // ...at some point should added some additional type checking...
284 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found"){ temp = "8"; }
285 convert(temp, kmerSize);
287 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
288 convert(temp, processors);
290 search = validParameter.validFile(parameters, "search", false); if (search == "not found"){ search = "kmer"; }
292 method = validParameter.validFile(parameters, "method", false); if (method == "not found"){ method = "bayesian"; }
294 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found"){ temp = "1.0"; }
295 convert(temp, match);
297 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found"){ temp = "-1.0"; }
298 convert(temp, misMatch);
300 temp = validParameter.validFile(parameters, "gapopen", false); if (temp == "not found"){ temp = "-2.0"; }
301 convert(temp, gapOpen);
303 temp = validParameter.validFile(parameters, "gapextend", false); if (temp == "not found"){ temp = "-1.0"; }
304 convert(temp, gapExtend);
306 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found"){ temp = "10"; }
307 convert(temp, numWanted);
309 temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found"){ temp = "0"; }
310 convert(temp, cutoff);
312 temp = validParameter.validFile(parameters, "probs", false); if (temp == "not found"){ temp = "true"; }
313 probs = isTrue(temp);
315 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "100"; }
316 convert(temp, iters);
320 if ((method == "bayesian") && (search != "kmer")) {
321 m->mothurOut("The bayesian method requires the kmer search." + search + "will be disregarded." ); m->mothurOutEndLine();
327 catch(exception& e) {
328 m->errorOut(e, "ClassifySeqsCommand", "ClassifySeqsCommand");
333 //**********************************************************************************************************************
335 ClassifySeqsCommand::~ClassifySeqsCommand(){
337 if (abort == false) {
338 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
342 //**********************************************************************************************************************
344 void ClassifySeqsCommand::help(){
346 m->mothurOut("The classify.seqs command reads a fasta file containing sequences and creates a .taxonomy file and a .tax.summary file.\n");
347 m->mothurOut("The classify.seqs command parameters are template, fasta, name, search, ksize, method, taxonomy, processors, match, mismatch, gapopen, gapextend, numwanted and probs.\n");
348 m->mothurOut("The template, 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");
349 m->mothurOut("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");
350 m->mothurOut("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");
351 m->mothurOut("The group parameter allows you add a group file so you can have the summary totals broken up by group.\n");
352 m->mothurOut("The method parameter allows you to specify classification method to use. Your options are: bayesian and knn. The default is bayesian.\n");
353 m->mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate. The default is 8.\n");
354 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
356 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
358 m->mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
359 m->mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n");
360 m->mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n");
361 m->mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -1.0.\n");
362 m->mothurOut("The numwanted parameter allows you to specify the number of sequence matches you want with the knn method. The default is 10.\n");
363 m->mothurOut("The cutoff parameter allows you to specify a bootstrap confidence threshold for your taxonomy. The default is 0.\n");
364 m->mothurOut("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");
365 m->mothurOut("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");
366 m->mothurOut("The classify.seqs command should be in the following format: \n");
367 m->mothurOut("classify.seqs(template=yourTemplateFile, fasta=yourFastaFile, method=yourClassificationMethod, search=yourSearchmethod, ksize=yourKmerSize, taxonomy=yourTaxonomyFile, processors=yourProcessors) \n");
368 m->mothurOut("Example classify.seqs(fasta=amazon.fasta, template=core.filtered, method=knn, search=gotoh, ksize=8, processors=2)\n");
369 m->mothurOut("The .taxonomy file consists of 2 columns: 1 = your sequence name, 2 = the taxonomy for your sequence. \n");
370 m->mothurOut("The .tax.summary is a summary of the different taxonomies represented in your fasta file. \n");
371 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
373 catch(exception& e) {
374 m->errorOut(e, "ClassifySeqsCommand", "help");
380 //**********************************************************************************************************************
382 int ClassifySeqsCommand::execute(){
384 if (abort == true) { return 0; }
386 if(method == "bayesian"){ classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters); }
387 else if(method == "knn"){ classify = new Knn(taxonomyFileName, templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch, numWanted); }
389 m->mothurOut(search + " is not a valid method option. I will run the command using bayesian.");
390 m->mothurOutEndLine();
391 classify = new Bayesian(taxonomyFileName, templateFileName, search, kmerSize, cutoff, iters);
394 if (m->control_pressed) { delete classify; return 0; }
396 vector<string> outputNames;
398 for (int s = 0; s < fastaFileNames.size(); s++) {
400 m->mothurOut("Classifying sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
402 string RippedTaxName = getRootName(getSimpleName(taxonomyFileName));
403 RippedTaxName = getExtension(RippedTaxName.substr(0, RippedTaxName.length()-1));
404 if (RippedTaxName[0] == '.') { RippedTaxName = RippedTaxName.substr(1, RippedTaxName.length()); }
405 RippedTaxName += ".";
407 if (outputDir == "") { outputDir += hasPath(fastaFileNames[s]); }
408 string newTaxonomyFile = outputDir + getRootName(getSimpleName(fastaFileNames[s])) + RippedTaxName + "taxonomy";
409 string tempTaxonomyFile = outputDir + getRootName(getSimpleName(fastaFileNames[s])) + "taxonomy.temp";
410 string taxSummary = outputDir + getRootName(getSimpleName(fastaFileNames[s])) + RippedTaxName + "tax.summary";
412 if ((method == "knn") && (search == "distance")) {
413 string DistName = outputDir + getRootName(getSimpleName(fastaFileNames[s])) + "match.dist";
414 classify->setDistName(DistName); outputNames.push_back(DistName);
417 outputNames.push_back(newTaxonomyFile);
418 outputNames.push_back(taxSummary);
420 int start = time(NULL);
421 int numFastaSeqs = 0;
422 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
425 int pid, end, numSeqsPerProcessor;
427 vector<unsigned long int> MPIPos;
430 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
431 MPI_Comm_size(MPI_COMM_WORLD, &processors);
434 MPI_File outMPINewTax;
435 MPI_File outMPITempTax;
437 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
438 int inMode=MPI_MODE_RDONLY;
440 //char* outNewTax = new char[newTaxonomyFile.length()];
441 //memcpy(outNewTax, newTaxonomyFile.c_str(), newTaxonomyFile.length());
443 char outNewTax[1024];
444 strcpy(outNewTax, newTaxonomyFile.c_str());
446 //char* outTempTax = new char[tempTaxonomyFile.length()];
447 //memcpy(outTempTax, tempTaxonomyFile.c_str(), tempTaxonomyFile.length());
449 char outTempTax[1024];
450 strcpy(outTempTax, tempTaxonomyFile.c_str());
452 //char* inFileName = new char[fastaFileNames[s].length()];
453 //memcpy(inFileName, fastaFileNames[s].c_str(), fastaFileNames[s].length());
455 char inFileName[1024];
456 strcpy(inFileName, fastaFileNames[s].c_str());
458 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
459 MPI_File_open(MPI_COMM_WORLD, outNewTax, outMode, MPI_INFO_NULL, &outMPINewTax);
460 MPI_File_open(MPI_COMM_WORLD, outTempTax, outMode, MPI_INFO_NULL, &outMPITempTax);
466 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPINewTax); MPI_File_close(&outMPITempTax); delete classify; return 0; }
468 if (pid == 0) { //you are the root process
470 MPIPos = setFilePosFasta(fastaFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs
472 //send file positions to all processes
473 for(int i = 1; i < processors; i++) {
474 MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
475 MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
478 //figure out how many sequences you have to align
479 numSeqsPerProcessor = numFastaSeqs / processors;
480 int startIndex = pid * numSeqsPerProcessor;
481 if(pid == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor; }
485 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, MPIPos);
487 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPINewTax); MPI_File_close(&outMPITempTax); for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } delete classify; return 0; }
489 for (int i = 1; i < processors; i++) {
491 MPI_Recv(&done, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
493 }else{ //you are a child process
494 MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
495 MPIPos.resize(numFastaSeqs+1);
496 MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
498 //figure out how many sequences you have to align
499 numSeqsPerProcessor = numFastaSeqs / processors;
500 int startIndex = pid * numSeqsPerProcessor;
501 if(pid == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor; }
505 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPINewTax, outMPITempTax, MPIPos);
507 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPINewTax); MPI_File_close(&outMPITempTax); delete classify; return 0; }
510 MPI_Send(&done, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
514 MPI_File_close(&inMPI);
515 MPI_File_close(&outMPINewTax);
516 MPI_File_close(&outMPITempTax);
517 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
520 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
523 openInputFile(fastaFileNames[s], inFASTA);
524 getNumSeqs(inFASTA, numFastaSeqs);
527 lines.push_back(new linePair(0, numFastaSeqs));
529 driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
532 vector<unsigned long int> positions;
533 processIDS.resize(0);
536 openInputFile(fastaFileNames[s], inFASTA);
539 while(!inFASTA.eof()){
540 input = getline(inFASTA);
541 if (input.length() != 0) {
542 if(input[0] == '>'){ unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
547 numFastaSeqs = positions.size();
549 int numSeqsPerProcessor = numFastaSeqs / processors;
551 for (int i = 0; i < processors; i++) {
552 unsigned long int startPos = positions[ i * numSeqsPerProcessor ];
553 if(i == processors - 1){
554 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
556 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
558 createProcesses(newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
560 rename((newTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), newTaxonomyFile.c_str());
561 rename((tempTaxonomyFile + toString(processIDS[0]) + ".temp").c_str(), tempTaxonomyFile.c_str());
563 for(int i=1;i<processors;i++){
564 appendTaxFiles((newTaxonomyFile + toString(processIDS[i]) + ".temp"), newTaxonomyFile);
565 appendTaxFiles((tempTaxonomyFile + toString(processIDS[i]) + ".temp"), tempTaxonomyFile);
566 remove((newTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
567 remove((tempTaxonomyFile + toString(processIDS[i]) + ".temp").c_str());
573 openInputFile(fastaFileNames[s], inFASTA);
574 getNumSeqs(inFASTA, numFastaSeqs);
577 lines.push_back(new linePair(0, numFastaSeqs));
579 driver(lines[0], newTaxonomyFile, tempTaxonomyFile, fastaFileNames[s]);
583 m->mothurOutEndLine();
584 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to classify " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
589 if (pid == 0) { //this part does not need to be paralellized
591 if(namefile != "") { m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush(); MPIReadNamesFile(namefileNames[s]); m->mothurOut(" Done."); m->mothurOutEndLine(); }
596 m->mothurOut("Reading " + namefileNames[s] + "..."); cout.flush();
598 nameMap.clear(); //remove old names
601 openInputFile(namefileNames[s], inNames);
603 string firstCol, secondCol;
604 while(!inNames.eof()) {
605 inNames >> firstCol >> secondCol; gobble(inNames);
608 splitAtComma(secondCol, temp);
610 nameMap[firstCol] = temp;
614 m->mothurOut(" Done."); m->mothurOutEndLine();
619 if (groupfile != "") { group = groupfileNames[s]; }
621 PhyloSummary taxaSum(taxonomyFileName, group);
623 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } delete classify; return 0; }
625 if (namefile == "") { taxaSum.summarize(tempTaxonomyFile); }
628 openInputFile(tempTaxonomyFile, in);
630 //read in users taxonomy file and add sequences to tree
634 in >> name >> taxon; gobble(in);
636 itNames = nameMap.find(name);
638 if (itNames == nameMap.end()) {
639 m->mothurOut(name + " is not in your name file please correct."); m->mothurOutEndLine(); exit(1);
641 for (int i = 0; i < itNames->second.size(); i++) {
642 taxaSum.addSeqToTree(itNames->second[i], taxon); //add it as many times as there are identical seqs
644 itNames->second.clear();
645 nameMap.erase(itNames->first);
650 remove(tempTaxonomyFile.c_str());
652 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } delete classify; return 0; }
656 openOutputFile(taxSummary, outTaxTree);
657 taxaSum.print(outTaxTree);
660 //output taxonomy with the unclassified bins added
662 openInputFile(newTaxonomyFile, inTax);
665 string unclass = newTaxonomyFile + ".unclass.temp";
666 openOutputFile(unclass, outTax);
668 //get maxLevel from phylotree so you know how many 'unclassified's to add
669 int maxLevel = taxaSum.getMaxLevel();
671 //read taxfile - this reading and rewriting is done to preserve the confidence scores.
673 while (!inTax.eof()) {
674 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); } remove(unclass.c_str()); delete classify; return 0; }
676 inTax >> name >> taxon; gobble(inTax);
678 string newTax = addUnclassifieds(taxon, maxLevel);
680 outTax << name << '\t' << newTax << endl;
685 remove(newTaxonomyFile.c_str());
686 rename(unclass.c_str(), newTaxonomyFile.c_str());
688 m->mothurOutEndLine();
689 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to create the summary file for " + toString(numFastaSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
695 m->mothurOutEndLine();
696 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
697 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
698 m->mothurOutEndLine();
704 catch(exception& e) {
705 m->errorOut(e, "ClassifySeqsCommand", "execute");
710 /**************************************************************************************************/
711 string ClassifySeqsCommand::addUnclassifieds(string tax, int maxlevel) {
713 string newTax, taxon;
716 //keep what you have counting the levels
717 while (tax.find_first_of(';') != -1) {
719 taxon = tax.substr(0,tax.find_first_of(';'))+';';
720 tax = tax.substr(tax.find_first_of(';')+1, tax.length());
725 //add "unclassified" until you reach maxLevel
726 while (level < maxlevel) {
727 newTax += "unclassified;";
733 catch(exception& e) {
734 m->errorOut(e, "ClassifySeqsCommand", "addUnclassifieds");
739 /**************************************************************************************************/
741 void ClassifySeqsCommand::createProcesses(string taxFileName, string tempTaxFile, string filename) {
743 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
745 // processIDS.resize(0);
747 //loop through and create all the processes you want
748 while (process != processors) {
752 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
755 driver(lines[process], taxFileName + toString(getpid()) + ".temp", tempTaxFile + toString(getpid()) + ".temp", filename);
757 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
760 //force parent to wait until all the processes are done
761 for (int i=0;i<processors;i++) {
762 int temp = processIDS[i];
767 catch(exception& e) {
768 m->errorOut(e, "ClassifySeqsCommand", "createProcesses");
772 /**************************************************************************************************/
774 void ClassifySeqsCommand::appendTaxFiles(string temp, string filename) {
779 openOutputFileAppend(filename, output);
780 openInputFile(temp, input);
782 while(char c = input.get()){
783 if(input.eof()) { break; }
784 else { output << c; }
790 catch(exception& e) {
791 m->errorOut(e, "ClassifySeqsCommand", "appendTaxFiles");
796 //**********************************************************************************************************************
798 int ClassifySeqsCommand::driver(linePair* line, string taxFName, string tempTFName, string filename){
801 openOutputFile(taxFName, outTax);
803 ofstream outTaxSimple;
804 openOutputFile(tempTFName, outTaxSimple);
807 openInputFile(filename, inFASTA);
809 inFASTA.seekg(line->start);
813 for(int i=0;i<line->numSeqs;i++){
814 if (m->control_pressed) { return 0; }
816 Sequence* candidateSeq = new Sequence(inFASTA); gobble(inFASTA);
818 if (candidateSeq->getName() != "") {
819 taxonomy = classify->getTaxonomy(candidateSeq);
821 if (m->control_pressed) { delete candidateSeq; return 0; }
823 if (taxonomy != "bad seq") {
824 //output confidence scores or not
826 outTax << candidateSeq->getName() << '\t' << taxonomy << endl;
828 outTax << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
831 outTaxSimple << candidateSeq->getName() << '\t' << classify->getSimpleTax() << endl;
836 if((i+1) % 100 == 0){
837 m->mothurOut("Classifying sequence " + toString(i+1)); m->mothurOutEndLine();
843 outTaxSimple.close();
847 catch(exception& e) {
848 m->errorOut(e, "ClassifySeqsCommand", "driver");
852 //**********************************************************************************************************************
854 int ClassifySeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& newFile, MPI_File& tempFile, vector<unsigned long int>& MPIPos){
856 MPI_Status statusNew;
857 MPI_Status statusTemp;
861 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
866 for(int i=0;i<num;i++){
868 if (m->control_pressed) { return 0; }
871 int length = MPIPos[start+i+1] - MPIPos[start+i];
872 char* buf4 = new char[length];
873 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
875 string tempBuf = buf4;
876 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
877 istringstream iss (tempBuf,istringstream::in);
880 Sequence* candidateSeq = new Sequence(iss);
882 if (candidateSeq->getName() != "") {
883 taxonomy = classify->getTaxonomy(candidateSeq);
885 if (taxonomy != "bad seq") {
886 //output confidence scores or not
888 outputString = candidateSeq->getName() + "\t" + taxonomy + "\n";
890 outputString = candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
893 int length = outputString.length();
894 char* buf2 = new char[length];
895 memcpy(buf2, outputString.c_str(), length);
897 MPI_File_write_shared(newFile, buf2, length, MPI_CHAR, &statusNew);
900 outputString = candidateSeq->getName() + "\t" + classify->getSimpleTax() + "\n";
901 length = outputString.length();
902 char* buf = new char[length];
903 memcpy(buf, outputString.c_str(), length);
905 MPI_File_write_shared(tempFile, buf, length, MPI_CHAR, &statusTemp);
911 if((i+1) % 100 == 0){ cout << "Classifying sequence " << (i+1) << endl; }
914 if(num % 100 != 0){ cout << "Classifying sequence " << (num) << endl; }
919 catch(exception& e) {
920 m->errorOut(e, "ClassifySeqsCommand", "driverMPI");
925 //**********************************************************************************************************************
926 int ClassifySeqsCommand::MPIReadNamesFile(string nameFilename){
929 nameMap.clear(); //remove old names
935 //char* inFileName = new char[nameFilename.length()];
936 //memcpy(inFileName, nameFilename.c_str(), nameFilename.length());
938 char inFileName[1024];
939 strcpy(inFileName, nameFilename.c_str());
941 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
942 MPI_File_get_size(inMPI, &size);
945 char* buffer = new char[size];
946 MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
948 string tempBuf = buffer;
949 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size); }
950 istringstream iss (tempBuf,istringstream::in);
953 string firstCol, secondCol;
955 iss >> firstCol >> secondCol; gobble(iss);
958 splitAtComma(secondCol, temp);
960 nameMap[firstCol] = temp;
963 MPI_File_close(&inMPI);
967 catch(exception& e) {
968 m->errorOut(e, "ClassifySeqsCommand", "MPIReadNamesFile");
973 /**************************************************************************************************/