2 * chimeraslayercommand.cpp
5 * Created by westcott on 3/31/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "chimeraslayercommand.h"
11 #include "chimeraslayer.h"
12 #include "deconvolutecommand.h"
13 #include "referencedb.h"
15 //**********************************************************************************************************************
16 vector<string> ChimeraSlayerCommand::setParameters(){
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 pwindow("window", "Number", "", "50", "", "", "",false,false); parameters.push_back(pwindow);
22 CommandParameter pksize("ksize", "Number", "", "7", "", "", "",false,false); parameters.push_back(pksize);
23 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "",false,false); parameters.push_back(pmatch);
24 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "",false,false); parameters.push_back(pmismatch);
25 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminsim);
26 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "",false,false); parameters.push_back(pmincov);
27 CommandParameter pminsnp("minsnp", "Number", "", "10", "", "", "",false,false); parameters.push_back(pminsnp);
28 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminbs);
29 CommandParameter psearch("search", "Multiple", "kmer-blast", "blast", "", "", "",false,false); parameters.push_back(psearch);
30 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
31 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(prealign);
32 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(ptrim);
33 CommandParameter psplit("split", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psplit);
34 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "",false,false); parameters.push_back(pnumwanted);
35 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
36 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "",false,false); parameters.push_back(pdivergence);
37 CommandParameter pparents("parents", "Number", "", "3", "", "", "",false,false); parameters.push_back(pparents);
38 CommandParameter pincrement("increment", "Number", "", "5", "", "", "",false,false); parameters.push_back(pincrement);
39 CommandParameter pblastlocation("blastlocation", "String", "", "", "", "", "",false,false); parameters.push_back(pblastlocation);
40 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
41 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
42 CommandParameter psave("save", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psave);
44 vector<string> myArray;
45 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
49 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
53 //**********************************************************************************************************************
54 string ChimeraSlayerCommand::getHelpString(){
56 string helpString = "";
57 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
58 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
59 helpString += "The chimera.slayer command parameters are fasta, name, template, processors, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment, numwanted, blastlocation and realign.\n";
60 helpString += "The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required, unless you have a valid current fasta file. \n";
61 helpString += "The name parameter allows you to provide a name file, if you are using reference=self. \n";
62 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
63 helpString += "The reference parameter allows you to enter a reference file containing known non-chimeric sequences, and is required. You may also set template=self, in this case the abundant sequences will be used as potential parents. \n";
64 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
66 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
68 helpString += "The trim parameter allows you to output a new fasta file containing your sequences with the chimeric ones trimmed to include only their longest piece, default=F. \n";
69 helpString += "The split parameter allows you to check both pieces of non-chimeric sequence for chimeras, thus looking for trimeras and quadmeras. default=F. \n";
70 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
71 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
72 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
73 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
74 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
75 helpString += "The parents parameter allows you to select the number of potential parents to investigate from the numwanted best matches after rating them, default is 3. \n";
76 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
77 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
78 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
79 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
80 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
81 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
82 helpString += "The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 10) \n";
83 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
84 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true. \n";
85 helpString += "The blastlocation parameter allows you to specify the location of your blast executable. By default mothur will look in ./blast/bin relative to mothur's executable. \n";
86 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.";
87 helpString += "The chimera.slayer command should be in the following format: \n";
88 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
89 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
90 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
94 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
98 //**********************************************************************************************************************
99 ChimeraSlayerCommand::ChimeraSlayerCommand(){
101 abort = true; calledHelp = true;
103 vector<string> tempOutNames;
104 outputTypes["chimera"] = tempOutNames;
105 outputTypes["accnos"] = tempOutNames;
106 outputTypes["fasta"] = tempOutNames;
108 catch(exception& e) {
109 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
113 //***************************************************************************************************************
114 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
116 abort = false; calledHelp = false;
117 ReferenceDB* rdb = ReferenceDB::getInstance();
119 //allow user to run help
120 if(option == "help") { help(); abort = true; calledHelp = true; }
121 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
124 vector<string> myArray = setParameters();
126 OptionParser parser(option);
127 map<string,string> parameters = parser.getParameters();
129 ValidParameters validParameter("chimera.slayer");
130 map<string,string>::iterator it;
132 //check to make sure all parameters are valid for command
133 for (it = parameters.begin(); it != parameters.end(); it++) {
134 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
137 vector<string> tempOutNames;
138 outputTypes["chimera"] = tempOutNames;
139 outputTypes["accnos"] = tempOutNames;
140 outputTypes["fasta"] = tempOutNames;
142 //if the user changes the input directory command factory will send this info to us in the output parameter
143 string inputDir = validParameter.validFile(parameters, "inputdir", false);
144 if (inputDir == "not found"){ inputDir = ""; }
146 //check for required parameters
147 fastafile = validParameter.validFile(parameters, "fasta", false);
148 if (fastafile == "not found") {
149 //if there is a current fasta file, use it
150 string filename = m->getFastaFile();
151 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
152 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
154 m->splitAtDash(fastafile, fastaFileNames);
156 //go through files and make sure they are good, if not, then disregard them
157 for (int i = 0; i < fastaFileNames.size(); i++) {
160 if (fastaFileNames[i] == "current") {
161 fastaFileNames[i] = m->getFastaFile();
162 if (fastaFileNames[i] != "") { m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
164 m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true;
165 //erase from file list
166 fastaFileNames.erase(fastaFileNames.begin()+i);
173 if (inputDir != "") {
174 string path = m->hasPath(fastaFileNames[i]);
175 //if the user has not given a path then, add inputdir. else leave path alone.
176 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
182 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
184 //if you can't open it, try default location
185 if (ableToOpen == 1) {
186 if (m->getDefaultPath() != "") { //default path is set
187 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
188 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
190 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
192 fastaFileNames[i] = tryPath;
196 if (ableToOpen == 1) {
197 if (m->getOutputDir() != "") { //default path is set
198 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
199 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
201 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
203 fastaFileNames[i] = tryPath;
209 if (ableToOpen == 1) {
210 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
211 //erase from file list
212 fastaFileNames.erase(fastaFileNames.begin()+i);
215 m->setFastaFile(fastaFileNames[i]);
220 //make sure there is at least one valid file left
221 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
225 //check for required parameters
227 namefile = validParameter.validFile(parameters, "name", false);
228 if (namefile == "not found") { namefile = ""; hasName = false; }
230 m->splitAtDash(namefile, nameFileNames);
232 //go through files and make sure they are good, if not, then disregard them
233 for (int i = 0; i < nameFileNames.size(); i++) {
236 if (nameFileNames[i] == "current") {
237 nameFileNames[i] = m->getNameFile();
238 if (nameFileNames[i] != "") { m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
240 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
241 //erase from file list
242 nameFileNames.erase(nameFileNames.begin()+i);
249 if (inputDir != "") {
250 string path = m->hasPath(nameFileNames[i]);
251 //if the user has not given a path then, add inputdir. else leave path alone.
252 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
258 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
260 //if you can't open it, try default location
261 if (ableToOpen == 1) {
262 if (m->getDefaultPath() != "") { //default path is set
263 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
264 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
266 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
268 nameFileNames[i] = tryPath;
272 if (ableToOpen == 1) {
273 if (m->getOutputDir() != "") { //default path is set
274 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
275 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
277 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
279 nameFileNames[i] = tryPath;
285 if (ableToOpen == 1) {
286 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
287 //erase from file list
288 nameFileNames.erase(nameFileNames.begin()+i);
291 m->setNameFile(nameFileNames[i]);
296 //make sure there is at least one valid file left
297 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
300 if (hasName && (nameFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of namefiles does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
302 //if the user changes the output directory command factory will send this info to us in the output parameter
303 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
305 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
306 m->setProcessors(temp);
307 convert(temp, processors);
309 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
310 save = m->isTrue(temp);
312 if (save) { //clear out old references
317 it = parameters.find("reference");
318 //user has given a template file
319 if(it != parameters.end()){
320 if (it->second == "self") {
321 templatefile = "self";
323 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
324 m->mothurOutEndLine();
329 path = m->hasPath(it->second);
330 //if the user has not given a path then, add inputdir. else leave path alone.
331 if (path == "") { parameters["reference"] = inputDir + it->second; }
333 templatefile = validParameter.validFile(parameters, "reference", true);
334 if (templatefile == "not open") { abort = true; }
335 else if (templatefile == "not found") { //check for saved reference sequences
336 if (rdb->referenceSeqs.size() != 0) {
337 templatefile = "saved";
339 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
340 m->mothurOutEndLine();
343 }else { if (save) { rdb->setSavedReference(templatefile); } }
345 }else if (hasName) { templatefile = "self";
347 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
348 m->mothurOutEndLine();
353 if (rdb->referenceSeqs.size() != 0) {
354 templatefile = "saved";
356 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
357 m->mothurOutEndLine();
358 templatefile = ""; abort = true;
364 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
365 convert(temp, ksize);
367 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
368 convert(temp, window);
370 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
371 convert(temp, match);
373 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
374 convert(temp, mismatch);
376 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
379 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
380 convert(temp, minSimilarity);
382 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
383 convert(temp, minCoverage);
385 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
386 convert(temp, minBS);
388 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "10"; }
389 convert(temp, minSNP);
391 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
392 convert(temp, parents);
394 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "t"; }
395 realign = m->isTrue(temp);
397 temp = validParameter.validFile(parameters, "trim", false); if (temp == "not found") { temp = "f"; }
398 trim = m->isTrue(temp);
400 temp = validParameter.validFile(parameters, "split", false); if (temp == "not found") { temp = "f"; }
401 trimera = m->isTrue(temp);
403 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "blast"; }
405 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
406 convert(temp, iters);
408 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
409 convert(temp, increment);
411 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
412 convert(temp, numwanted);
414 blastlocation = validParameter.validFile(parameters, "blastlocation", false);
415 if (blastlocation == "not found") { blastlocation = ""; }
417 //add / to name if needed
418 string lastChar = blastlocation.substr(blastlocation.length()-1);
419 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
420 if (lastChar != "/") { blastlocation += "/"; }
422 if (lastChar != "\\") { blastlocation += "\\"; }
424 blastlocation = m->getFullPathName(blastlocation);
425 string formatdbCommand = "";
426 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
427 formatdbCommand = blastlocation + "formatdb";
429 formatdbCommand = blastlocation + "formatdb.exe";
432 //test to make sure formatdb exists
434 formatdbCommand = m->getFullPathName(formatdbCommand);
435 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
436 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
438 string blastCommand = "";
439 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
440 blastCommand = blastlocation + "megablast";
442 blastCommand = blastlocation + "megablast.exe";
444 //test to make sure formatdb exists
446 blastCommand = m->getFullPathName(blastCommand);
447 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
448 if(ableToOpen == 1) { m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
451 if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
453 if (hasName && (templatefile != "self")) { m->mothurOut("You have provided a namefile and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
456 catch(exception& e) {
457 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
461 //***************************************************************************************************************
463 int ChimeraSlayerCommand::execute(){
465 if (abort == true) { if (calledHelp) { return 0; } return 2; }
467 for (int s = 0; s < fastaFileNames.size(); s++) {
469 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
471 int start = time(NULL);
473 if (templatefile != "self") { //you want to run slayer with a refernce template
474 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation);
476 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
477 string nameFile = "";
478 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
479 nameFile = nameFileNames[s];
481 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
483 //use unique.seqs to create new name and fastafile
484 string inputString = "fasta=" + fastaFileNames[s];
485 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
486 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
488 Command* uniqueCommand = new DeconvoluteCommand(inputString);
489 uniqueCommand->execute();
491 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
493 delete uniqueCommand;
495 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
497 nameFile = filenames["name"][0];
498 fastaFileNames[s] = filenames["fasta"][0];
501 //sort fastafile by abundance, returns new sorted fastafile name
502 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
503 map<string, int> priority = sortFastaFile(fastaFileNames[s], nameFile);
504 m->mothurOut("Done."); m->mothurOutEndLine();
506 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
508 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation);
511 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
512 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
513 string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.accnos";
514 string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.fasta";
516 if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } return 0; }
518 if (chimera->getUnaligned()) {
519 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine();
523 templateSeqsLength = chimera->getLength();
526 int pid, numSeqsPerProcessor;
528 vector<unsigned long int> MPIPos;
531 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
532 MPI_Comm_size(MPI_COMM_WORLD, &processors);
536 MPI_File outMPIAccnos;
537 MPI_File outMPIFasta;
539 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
540 int inMode=MPI_MODE_RDONLY;
542 char outFilename[1024];
543 strcpy(outFilename, outputFileName.c_str());
545 char outAccnosFilename[1024];
546 strcpy(outAccnosFilename, accnosFileName.c_str());
548 char outFastaFilename[1024];
549 strcpy(outFastaFilename, trimFastaFileName.c_str());
551 char inFileName[1024];
552 strcpy(inFileName, fastaFileNames[s].c_str());
554 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
555 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
556 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
557 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
559 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } delete chimera; return 0; }
561 if (pid == 0) { //you are the root process
562 m->mothurOutEndLine();
563 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
564 m->mothurOutEndLine();
566 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
569 int length = outTemp.length();
570 char* buf2 = new char[length];
571 memcpy(buf2, outTemp.c_str(), length);
573 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
576 MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
578 if (templatefile != "self") { //if template=self we can only use 1 processor
579 //send file positions to all processes
580 for(int i = 1; i < processors; i++) {
581 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
582 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
585 //figure out how many sequences you have to align
586 numSeqsPerProcessor = numSeqs / processors;
587 int startIndex = pid * numSeqsPerProcessor;
588 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
590 if (templatefile == "self") { //if template=self we can only use 1 processor
592 numSeqsPerProcessor = numSeqs;
596 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
598 int numNoParents = chimera->getNumNoParents();
600 for(int i = 1; i < processors; i++) {
601 MPI_Recv(&temp, 1, MPI_INT, 1, tag, MPI_COMM_WORLD, &status);
602 numNoParents += temp;
606 if (numSeqs == numNoParents) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
608 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); delete chimera; return 0; }
610 }else{ //you are a child process
611 if (templatefile != "self") { //if template=self we can only use 1 processor
612 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
613 MPIPos.resize(numSeqs+1);
614 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
616 //figure out how many sequences you have to align
617 numSeqsPerProcessor = numSeqs / processors;
618 int startIndex = pid * numSeqsPerProcessor;
619 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
622 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
624 int numNoParents = chimera->getNumNoParents();
625 MPI_Send(&numNoParents, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
627 if (m->control_pressed) { outputTypes.clear(); MPI_File_close(&inMPI); MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); } MPI_File_close(&outMPIAccnos); for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } delete chimera; return 0; }
633 MPI_File_close(&inMPI);
634 MPI_File_close(&outMPI);
635 MPI_File_close(&outMPIAccnos);
636 if (trim) { MPI_File_close(&outMPIFasta); }
637 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
641 string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
642 m->openOutputFile(tempHeader, outHeader);
644 chimera->printHeader(outHeader);
647 vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
649 for (int i = 0; i < (positions.size()-1); i++) {
650 lines.push_back(new linePair(positions[i], positions[(i+1)]));
654 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
656 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
658 int numNoParents = chimera->getNumNoParents();
659 if (numNoParents == numSeqs) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
661 if (m->control_pressed) { outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(tempHeader); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear(); delete chimera; return 0; }
664 processIDS.resize(0);
666 numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
668 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
669 rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
670 if (trim) { rename((trimFastaFileName + toString(processIDS[0]) + ".temp").c_str(), trimFastaFileName.c_str()); }
672 //append output files
673 for(int i=1;i<processors;i++){
674 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
675 m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
678 //append output files
679 for(int i=1;i<processors;i++){
680 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
681 m->mothurRemove((accnosFileName + toString(processIDS[i]) + ".temp"));
685 for(int i=1;i<processors;i++){
686 m->appendFiles((trimFastaFileName + toString(processIDS[i]) + ".temp"), trimFastaFileName);
687 m->mothurRemove((trimFastaFileName + toString(processIDS[i]) + ".temp"));
691 if (m->control_pressed) { outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear(); delete chimera; return 0; }
695 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
697 int numNoParents = chimera->getNumNoParents();
698 if (numNoParents == numSeqs) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
701 if (m->control_pressed) { outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(tempHeader); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]); } for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear(); delete chimera; return 0; }
705 m->appendFiles(outputFileName, tempHeader);
707 m->mothurRemove(outputFileName);
708 rename(tempHeader.c_str(), outputFileName.c_str());
714 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
716 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
717 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
718 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
720 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
723 //set accnos file as new current accnosfile
725 itTypes = outputTypes.find("accnos");
726 if (itTypes != outputTypes.end()) {
727 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
731 itTypes = outputTypes.find("fasta");
732 if (itTypes != outputTypes.end()) {
733 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
737 m->mothurOutEndLine();
738 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
739 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
740 m->mothurOutEndLine();
745 catch(exception& e) {
746 m->errorOut(e, "ChimeraSlayerCommand", "execute");
750 //**********************************************************************************************************************
752 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos, string fasta){
755 m->openOutputFile(outputFName, out);
758 m->openOutputFile(accnos, out2);
761 if (trim) { m->openOutputFile(fasta, out3); }
764 m->openInputFile(filename, inFASTA);
766 inFASTA.seekg(filePos->start);
773 if (m->control_pressed) { out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
775 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
776 string candidateAligned = candidateSeq->getAligned();
778 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
779 if (candidateSeq->getAligned().length() != templateSeqsLength) {
780 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
783 chimera->getChimeras(candidateSeq);
785 if (m->control_pressed) { delete candidateSeq; return 1; }
787 //if you are not chimeric, then check each half
788 data_results wholeResults = chimera->getResults();
790 //determine if we need to split
791 bool isChimeric = false;
793 if (wholeResults.flag == "yes") {
794 string chimeraFlag = "no";
795 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
797 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
800 if (chimeraFlag == "yes") {
801 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
805 if ((!isChimeric) && trimera) {
807 //split sequence in half by bases
808 string leftQuery, rightQuery;
809 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
810 divideInHalf(tempSeq, leftQuery, rightQuery);
812 //run chimeraSlayer on each piece
813 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
814 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
817 chimera->getChimeras(left);
818 data_results leftResults = chimera->getResults();
820 chimera->getChimeras(right);
821 data_results rightResults = chimera->getResults();
823 //if either piece is chimeric then report
824 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
825 if (trim) { trimmed.printSequence(out3); }
827 delete left; delete right;
829 }else { //already chimeric
831 Sequence trimmed = chimera->print(out, out2);
832 if (trim) { trimmed.printSequence(out3); }
840 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
841 unsigned long int pos = inFASTA.tellg();
842 if ((pos == -1) || (pos >= filePos->end)) { break; }
844 if (inFASTA.eof()) { break; }
849 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
852 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
856 if (trim) { out3.close(); }
861 catch(exception& e) {
862 m->errorOut(e, "ChimeraSlayerCommand", "driver");
866 //**********************************************************************************************************************
868 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long int>& MPIPos){
872 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
874 for(int i=0;i<num;i++){
876 if (m->control_pressed) { return 1; }
879 int length = MPIPos[start+i+1] - MPIPos[start+i];
881 char* buf4 = new char[length];
882 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
884 string tempBuf = buf4;
885 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
886 istringstream iss (tempBuf,istringstream::in);
890 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
891 string candidateAligned = candidateSeq->getAligned();
893 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
895 if (candidateSeq->getAligned().length() != templateSeqsLength) {
896 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
900 chimera->getChimeras(candidateSeq);
902 if (m->control_pressed) { delete candidateSeq; return 1; }
904 //if you are not chimeric, then check each half
905 data_results wholeResults = chimera->getResults();
907 //determine if we need to split
908 bool isChimeric = false;
910 if (wholeResults.flag == "yes") {
911 string chimeraFlag = "no";
912 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
914 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
917 if (chimeraFlag == "yes") {
918 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
922 if ((!isChimeric) && trimera) {
923 //split sequence in half by bases
924 string leftQuery, rightQuery;
925 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
926 divideInHalf(tempSeq, leftQuery, rightQuery);
928 //run chimeraSlayer on each piece
929 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
930 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
933 chimera->getChimeras(left);
934 data_results leftResults = chimera->getResults();
936 chimera->getChimeras(right);
937 data_results rightResults = chimera->getResults();
939 //if either piece is chimeric then report
940 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
942 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
944 //write to accnos file
945 int length = outputString.length();
946 char* buf2 = new char[length];
947 memcpy(buf2, outputString.c_str(), length);
949 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
953 delete left; delete right;
957 Sequence trimmed = chimera->print(outMPI, outAccMPI);
960 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
962 //write to accnos file
963 int length = outputString.length();
964 char* buf2 = new char[length];
965 memcpy(buf2, outputString.c_str(), length);
967 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
977 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
980 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
985 catch(exception& e) {
986 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
992 /**************************************************************************************************/
994 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta) {
996 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1000 //loop through and create all the processes you want
1001 while (process != processors) {
1005 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
1007 }else if (pid == 0){
1008 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp");
1010 //pass numSeqs to parent
1012 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1013 m->openOutputFile(tempFile, out);
1014 out << num << '\t' << chimera->getNumNoParents() << endl;
1018 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
1019 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1024 //force parent to wait until all the processes are done
1025 for (int i=0;i<processors;i++) {
1026 int temp = processIDS[i];
1030 int numNoParents = 0;
1031 for (int i = 0; i < processIDS.size(); i++) {
1033 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
1034 m->openInputFile(tempFile, in);
1035 if (!in.eof()) { int tempNum = 0; int tempNumParents = 0; in >> tempNum >> tempNumParents; num += tempNum; numNoParents += tempNumParents; }
1036 in.close(); m->mothurRemove(tempFile);
1039 if (num == numNoParents) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); }
1044 catch(exception& e) {
1045 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1050 /**************************************************************************************************/
1052 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1055 string queryUnAligned = querySeq.getUnaligned();
1056 int numBases = int(queryUnAligned.length() * 0.5);
1058 string queryAligned = querySeq.getAligned();
1059 leftQuery = querySeq.getAligned();
1060 rightQuery = querySeq.getAligned();
1064 for (int i = 0; i < queryAligned.length(); i++) {
1066 if (isalpha(queryAligned[i])) {
1071 if (baseCount >= numBases) { leftSpot = i; break; } //first half
1074 //blank out right side
1075 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1077 //blank out left side
1078 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1083 catch(exception& e) {
1084 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1088 /**************************************************************************************************/
1089 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1091 map<string, int> nameAbund;
1093 //read through fastafile and store info
1094 map<string, string> seqs;
1096 m->openInputFile(fastaFile, in);
1100 if (m->control_pressed) { in.close(); return nameAbund; }
1102 Sequence seq(in); m->gobble(in);
1103 seqs[seq.getName()] = seq.getAligned();
1109 vector<seqPriorityNode> nameMapCount;
1110 int error = m->readNames(nameFile, nameMapCount, seqs);
1112 if (m->control_pressed) { return nameAbund; }
1114 if (error == 1) { m->control_pressed = true; return nameAbund; }
1115 if (seqs.size() != nameMapCount.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your namefile, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return nameAbund; }
1117 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1119 string newFasta = fastaFile + ".temp";
1121 m->openOutputFile(newFasta, out);
1123 //print new file in order of
1124 for (int i = 0; i < nameMapCount.size(); i++) {
1125 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1126 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1130 rename(newFasta.c_str(), fastaFile.c_str());
1135 catch(exception& e) {
1136 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1141 /**************************************************************************************************/