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 pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
40 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
41 CommandParameter psave("save", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psave);
43 vector<string> myArray;
44 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
48 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
52 //**********************************************************************************************************************
53 string ChimeraSlayerCommand::getHelpString(){
55 string helpString = "";
56 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
57 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
58 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, and realign.\n";
59 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";
60 helpString += "The name parameter allows you to provide a name file, if you are using reference=self. \n";
61 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
62 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";
63 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
65 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
67 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";
68 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";
69 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
70 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
71 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
72 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
73 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
74 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";
75 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
76 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
77 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
78 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
79 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
80 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
81 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";
82 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
83 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true. \n";
84 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.";
85 helpString += "The chimera.slayer command should be in the following format: \n";
86 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
87 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
88 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
92 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
96 //**********************************************************************************************************************
97 ChimeraSlayerCommand::ChimeraSlayerCommand(){
99 abort = true; calledHelp = true;
101 vector<string> tempOutNames;
102 outputTypes["chimera"] = tempOutNames;
103 outputTypes["accnos"] = tempOutNames;
104 outputTypes["fasta"] = tempOutNames;
106 catch(exception& e) {
107 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
111 //***************************************************************************************************************
112 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
114 abort = false; calledHelp = false;
115 ReferenceDB* rdb = ReferenceDB::getInstance();
117 //allow user to run help
118 if(option == "help") { help(); abort = true; calledHelp = true; }
119 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
122 vector<string> myArray = setParameters();
124 OptionParser parser(option);
125 map<string,string> parameters = parser.getParameters();
127 ValidParameters validParameter("chimera.slayer");
128 map<string,string>::iterator it;
130 //check to make sure all parameters are valid for command
131 for (it = parameters.begin(); it != parameters.end(); it++) {
132 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
135 vector<string> tempOutNames;
136 outputTypes["chimera"] = tempOutNames;
137 outputTypes["accnos"] = tempOutNames;
138 outputTypes["fasta"] = tempOutNames;
140 //if the user changes the input directory command factory will send this info to us in the output parameter
141 string inputDir = validParameter.validFile(parameters, "inputdir", false);
142 if (inputDir == "not found"){ inputDir = ""; }
144 //check for required parameters
145 fastafile = validParameter.validFile(parameters, "fasta", false);
146 if (fastafile == "not found") {
147 //if there is a current fasta file, use it
148 string filename = m->getFastaFile();
149 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
150 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
152 m->splitAtDash(fastafile, fastaFileNames);
154 //go through files and make sure they are good, if not, then disregard them
155 for (int i = 0; i < fastaFileNames.size(); i++) {
158 if (fastaFileNames[i] == "current") {
159 fastaFileNames[i] = m->getFastaFile();
160 if (fastaFileNames[i] != "") { m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
162 m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true;
163 //erase from file list
164 fastaFileNames.erase(fastaFileNames.begin()+i);
171 if (inputDir != "") {
172 string path = m->hasPath(fastaFileNames[i]);
173 //if the user has not given a path then, add inputdir. else leave path alone.
174 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
180 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
182 //if you can't open it, try default location
183 if (ableToOpen == 1) {
184 if (m->getDefaultPath() != "") { //default path is set
185 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
186 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
188 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
190 fastaFileNames[i] = tryPath;
194 if (ableToOpen == 1) {
195 if (m->getOutputDir() != "") { //default path is set
196 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
197 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
199 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
201 fastaFileNames[i] = tryPath;
207 if (ableToOpen == 1) {
208 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
209 //erase from file list
210 fastaFileNames.erase(fastaFileNames.begin()+i);
213 m->setFastaFile(fastaFileNames[i]);
218 //make sure there is at least one valid file left
219 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
223 //check for required parameters
225 namefile = validParameter.validFile(parameters, "name", false);
226 if (namefile == "not found") { namefile = ""; hasName = false; }
228 m->splitAtDash(namefile, nameFileNames);
230 //go through files and make sure they are good, if not, then disregard them
231 for (int i = 0; i < nameFileNames.size(); i++) {
234 if (nameFileNames[i] == "current") {
235 nameFileNames[i] = m->getNameFile();
236 if (nameFileNames[i] != "") { m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
238 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
239 //erase from file list
240 nameFileNames.erase(nameFileNames.begin()+i);
247 if (inputDir != "") {
248 string path = m->hasPath(nameFileNames[i]);
249 //if the user has not given a path then, add inputdir. else leave path alone.
250 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
256 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
258 //if you can't open it, try default location
259 if (ableToOpen == 1) {
260 if (m->getDefaultPath() != "") { //default path is set
261 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
262 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
264 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
266 nameFileNames[i] = tryPath;
270 if (ableToOpen == 1) {
271 if (m->getOutputDir() != "") { //default path is set
272 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
273 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
275 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
277 nameFileNames[i] = tryPath;
283 if (ableToOpen == 1) {
284 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
285 //erase from file list
286 nameFileNames.erase(nameFileNames.begin()+i);
289 m->setNameFile(nameFileNames[i]);
294 //make sure there is at least one valid file left
295 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
298 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; }
300 //if the user changes the output directory command factory will send this info to us in the output parameter
301 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
303 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
304 m->setProcessors(temp);
305 convert(temp, processors);
307 temp = validParameter.validFile(parameters, "save", false); if (temp == "not found"){ temp = "f"; }
308 save = m->isTrue(temp);
310 if (save) { //clear out old references
315 it = parameters.find("reference");
316 //user has given a template file
317 if(it != parameters.end()){
318 if (it->second == "self") {
319 templatefile = "self";
321 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
322 m->mothurOutEndLine();
327 path = m->hasPath(it->second);
328 //if the user has not given a path then, add inputdir. else leave path alone.
329 if (path == "") { parameters["reference"] = inputDir + it->second; }
331 templatefile = validParameter.validFile(parameters, "reference", true);
332 if (templatefile == "not open") { abort = true; }
333 else if (templatefile == "not found") { //check for saved reference sequences
334 if (rdb->referenceSeqs.size() != 0) {
335 templatefile = "saved";
337 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
338 m->mothurOutEndLine();
341 }else { if (save) { rdb->setSavedReference(templatefile); } }
343 }else if (hasName) { templatefile = "self";
345 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save.");
346 m->mothurOutEndLine();
351 if (rdb->referenceSeqs.size() != 0) {
352 templatefile = "saved";
354 m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required.");
355 m->mothurOutEndLine();
356 templatefile = ""; abort = true;
362 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
363 convert(temp, ksize);
365 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
366 convert(temp, window);
368 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
369 convert(temp, match);
371 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
372 convert(temp, mismatch);
374 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
377 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
378 convert(temp, minSimilarity);
380 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
381 convert(temp, minCoverage);
383 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
384 convert(temp, minBS);
386 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "10"; }
387 convert(temp, minSNP);
389 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
390 convert(temp, parents);
392 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "t"; }
393 realign = m->isTrue(temp);
395 temp = validParameter.validFile(parameters, "trim", false); if (temp == "not found") { temp = "f"; }
396 trim = m->isTrue(temp);
398 temp = validParameter.validFile(parameters, "split", false); if (temp == "not found") { temp = "f"; }
399 trimera = m->isTrue(temp);
401 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "blast"; }
403 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "1000"; }
404 convert(temp, iters);
406 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
407 convert(temp, increment);
409 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
410 convert(temp, numwanted);
412 if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
414 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; }
417 catch(exception& e) {
418 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
422 //***************************************************************************************************************
424 int ChimeraSlayerCommand::execute(){
426 if (abort == true) { if (calledHelp) { return 0; } return 2; }
428 for (int s = 0; s < fastaFileNames.size(); s++) {
430 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
432 int start = time(NULL);
434 if (templatefile != "self") { //you want to run slayer with a refernce template
435 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);
437 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
438 string nameFile = "";
439 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
440 nameFile = nameFileNames[s];
442 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
444 //use unique.seqs to create new name and fastafile
445 string inputString = "fasta=" + fastaFileNames[s];
446 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
447 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
449 Command* uniqueCommand = new DeconvoluteCommand(inputString);
450 uniqueCommand->execute();
452 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
454 delete uniqueCommand;
456 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
458 nameFile = filenames["name"][0];
459 fastaFileNames[s] = filenames["fasta"][0];
462 //sort fastafile by abundance, returns new sorted fastafile name
463 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
464 map<string, int> priority = sortFastaFile(fastaFileNames[s], nameFile);
465 m->mothurOut("Done."); m->mothurOutEndLine();
467 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } return 0; }
469 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);
472 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
473 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
474 string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.accnos";
475 string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.fasta";
477 if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } return 0; }
479 if (chimera->getUnaligned()) {
480 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine();
484 templateSeqsLength = chimera->getLength();
487 int pid, numSeqsPerProcessor;
489 vector<unsigned long int> MPIPos;
492 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
493 MPI_Comm_size(MPI_COMM_WORLD, &processors);
497 MPI_File outMPIAccnos;
498 MPI_File outMPIFasta;
500 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
501 int inMode=MPI_MODE_RDONLY;
503 char outFilename[1024];
504 strcpy(outFilename, outputFileName.c_str());
506 char outAccnosFilename[1024];
507 strcpy(outAccnosFilename, accnosFileName.c_str());
509 char outFastaFilename[1024];
510 strcpy(outFastaFilename, trimFastaFileName.c_str());
512 char inFileName[1024];
513 strcpy(inFileName, fastaFileNames[s].c_str());
515 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
516 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
517 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
518 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
520 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++) { remove(outputNames[j].c_str()); } delete chimera; return 0; }
522 if (pid == 0) { //you are the root process
523 m->mothurOutEndLine();
524 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
525 m->mothurOutEndLine();
527 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
530 int length = outTemp.length();
531 char* buf2 = new char[length];
532 memcpy(buf2, outTemp.c_str(), length);
534 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
537 MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
539 if (templatefile != "self") { //if template=self we can only use 1 processor
540 //send file positions to all processes
541 for(int i = 1; i < processors; i++) {
542 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
543 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
546 //figure out how many sequences you have to align
547 numSeqsPerProcessor = numSeqs / processors;
548 int startIndex = pid * numSeqsPerProcessor;
549 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
551 if (templatefile == "self") { //if template=self we can only use 1 processor
553 numSeqsPerProcessor = numSeqs;
557 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
559 int numNoParents = chimera->getNumNoParents();
561 for(int i = 1; i < processors; i++) {
562 MPI_Recv(&temp, 1, MPI_INT, 1, tag, MPI_COMM_WORLD, &status);
563 numNoParents += temp;
567 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(); }
569 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++) { remove(outputNames[j].c_str()); } remove(outputFileName.c_str()); remove(accnosFileName.c_str()); delete chimera; return 0; }
571 }else{ //you are a child process
572 if (templatefile != "self") { //if template=self we can only use 1 processor
573 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
574 MPIPos.resize(numSeqs+1);
575 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
577 //figure out how many sequences you have to align
578 numSeqsPerProcessor = numSeqs / processors;
579 int startIndex = pid * numSeqsPerProcessor;
580 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
583 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
585 int numNoParents = chimera->getNumNoParents();
586 MPI_Send(&numNoParents, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
588 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++) { remove(outputNames[j].c_str()); } delete chimera; return 0; }
594 MPI_File_close(&inMPI);
595 MPI_File_close(&outMPI);
596 MPI_File_close(&outMPIAccnos);
597 if (trim) { MPI_File_close(&outMPIFasta); }
598 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
602 string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
603 m->openOutputFile(tempHeader, outHeader);
605 chimera->printHeader(outHeader);
608 vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
610 for (int i = 0; i < (positions.size()-1); i++) {
611 lines.push_back(new linePair(positions[i], positions[(i+1)]));
615 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
617 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
619 int numNoParents = chimera->getNumNoParents();
620 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(); }
622 if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(tempHeader.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear(); delete chimera; return 0; }
625 processIDS.resize(0);
627 numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
629 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
630 rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
631 if (trim) { rename((trimFastaFileName + toString(processIDS[0]) + ".temp").c_str(), trimFastaFileName.c_str()); }
633 //append output files
634 for(int i=1;i<processors;i++){
635 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
636 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
639 //append output files
640 for(int i=1;i<processors;i++){
641 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
642 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
646 for(int i=1;i<processors;i++){
647 m->appendFiles((trimFastaFileName + toString(processIDS[i]) + ".temp"), trimFastaFileName);
648 remove((trimFastaFileName + toString(processIDS[i]) + ".temp").c_str());
652 if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear(); delete chimera; return 0; }
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(); }
662 if (m->control_pressed) { outputTypes.clear(); if (trim) { remove(trimFastaFileName.c_str()); } remove(outputFileName.c_str()); remove(tempHeader.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear(); delete chimera; return 0; }
666 m->appendFiles(outputFileName, tempHeader);
668 remove(outputFileName.c_str());
669 rename(tempHeader.c_str(), outputFileName.c_str());
675 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
677 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
678 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
679 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
681 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
684 //set accnos file as new current accnosfile
686 itTypes = outputTypes.find("accnos");
687 if (itTypes != outputTypes.end()) {
688 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
692 itTypes = outputTypes.find("fasta");
693 if (itTypes != outputTypes.end()) {
694 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
698 m->mothurOutEndLine();
699 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
700 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
701 m->mothurOutEndLine();
706 catch(exception& e) {
707 m->errorOut(e, "ChimeraSlayerCommand", "execute");
711 //**********************************************************************************************************************
713 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos, string fasta){
716 m->openOutputFile(outputFName, out);
719 m->openOutputFile(accnos, out2);
722 if (trim) { m->openOutputFile(fasta, out3); }
725 m->openInputFile(filename, inFASTA);
727 inFASTA.seekg(filePos->start);
734 if (m->control_pressed) { out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
736 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
737 string candidateAligned = candidateSeq->getAligned();
739 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
740 if (candidateSeq->getAligned().length() != templateSeqsLength) {
741 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
744 chimera->getChimeras(candidateSeq);
746 if (m->control_pressed) { delete candidateSeq; return 1; }
748 //if you are not chimeric, then check each half
749 data_results wholeResults = chimera->getResults();
751 //determine if we need to split
752 bool isChimeric = false;
754 if (wholeResults.flag == "yes") {
755 string chimeraFlag = "no";
756 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
758 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
761 if (chimeraFlag == "yes") {
762 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
766 if ((!isChimeric) && trimera) {
768 //split sequence in half by bases
769 string leftQuery, rightQuery;
770 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
771 divideInHalf(tempSeq, leftQuery, rightQuery);
773 //run chimeraSlayer on each piece
774 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
775 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
778 chimera->getChimeras(left);
779 data_results leftResults = chimera->getResults();
781 chimera->getChimeras(right);
782 data_results rightResults = chimera->getResults();
784 //if either piece is chimeric then report
785 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
786 if (trim) { trimmed.printSequence(out3); }
788 delete left; delete right;
790 }else { //already chimeric
792 Sequence trimmed = chimera->print(out, out2);
793 if (trim) { trimmed.printSequence(out3); }
801 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
802 unsigned long int pos = inFASTA.tellg();
803 if ((pos == -1) || (pos >= filePos->end)) { break; }
805 if (inFASTA.eof()) { break; }
810 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
813 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
817 if (trim) { out3.close(); }
822 catch(exception& e) {
823 m->errorOut(e, "ChimeraSlayerCommand", "driver");
827 //**********************************************************************************************************************
829 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long int>& MPIPos){
833 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
835 for(int i=0;i<num;i++){
837 if (m->control_pressed) { return 1; }
840 int length = MPIPos[start+i+1] - MPIPos[start+i];
842 char* buf4 = new char[length];
843 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
845 string tempBuf = buf4;
846 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
847 istringstream iss (tempBuf,istringstream::in);
851 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
852 string candidateAligned = candidateSeq->getAligned();
854 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
856 if (candidateSeq->getAligned().length() != templateSeqsLength) {
857 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
861 chimera->getChimeras(candidateSeq);
863 if (m->control_pressed) { delete candidateSeq; return 1; }
865 //if you are not chimeric, then check each half
866 data_results wholeResults = chimera->getResults();
868 //determine if we need to split
869 bool isChimeric = false;
871 if (wholeResults.flag == "yes") {
872 string chimeraFlag = "no";
873 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
875 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
878 if (chimeraFlag == "yes") {
879 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
883 if ((!isChimeric) && trimera) {
884 //split sequence in half by bases
885 string leftQuery, rightQuery;
886 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
887 divideInHalf(tempSeq, leftQuery, rightQuery);
889 //run chimeraSlayer on each piece
890 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
891 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
894 chimera->getChimeras(left);
895 data_results leftResults = chimera->getResults();
897 chimera->getChimeras(right);
898 data_results rightResults = chimera->getResults();
900 //if either piece is chimeric then report
901 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
903 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
905 //write to accnos file
906 int length = outputString.length();
907 char* buf2 = new char[length];
908 memcpy(buf2, outputString.c_str(), length);
910 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
914 delete left; delete right;
918 Sequence trimmed = chimera->print(outMPI, outAccMPI);
921 string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
923 //write to accnos file
924 int length = outputString.length();
925 char* buf2 = new char[length];
926 memcpy(buf2, outputString.c_str(), length);
928 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
938 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
941 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
946 catch(exception& e) {
947 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
953 /**************************************************************************************************/
955 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta) {
957 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
961 //loop through and create all the processes you want
962 while (process != processors) {
966 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
969 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp");
971 //pass numSeqs to parent
973 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
974 m->openOutputFile(tempFile, out);
975 out << num << '\t' << chimera->getNumNoParents() << endl;
979 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
980 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
985 //force parent to wait until all the processes are done
986 for (int i=0;i<processors;i++) {
987 int temp = processIDS[i];
991 int numNoParents = 0;
992 for (int i = 0; i < processIDS.size(); i++) {
994 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
995 m->openInputFile(tempFile, in);
996 if (!in.eof()) { int tempNum = 0; int tempNumParents = 0; in >> tempNum >> tempNumParents; num += tempNum; numNoParents += tempNumParents; }
997 in.close(); remove(tempFile.c_str());
1000 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(); }
1005 catch(exception& e) {
1006 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1011 /**************************************************************************************************/
1013 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1016 string queryUnAligned = querySeq.getUnaligned();
1017 int numBases = int(queryUnAligned.length() * 0.5);
1019 string queryAligned = querySeq.getAligned();
1020 leftQuery = querySeq.getAligned();
1021 rightQuery = querySeq.getAligned();
1025 for (int i = 0; i < queryAligned.length(); i++) {
1027 if (isalpha(queryAligned[i])) {
1032 if (baseCount >= numBases) { leftSpot = i; break; } //first half
1035 //blank out right side
1036 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1038 //blank out left side
1039 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1044 catch(exception& e) {
1045 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1049 /**************************************************************************************************/
1050 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1052 map<string, int> nameAbund;
1054 //read through fastafile and store info
1055 map<string, string> seqs;
1057 m->openInputFile(fastaFile, in);
1061 if (m->control_pressed) { in.close(); return nameAbund; }
1063 Sequence seq(in); m->gobble(in);
1064 seqs[seq.getName()] = seq.getAligned();
1070 vector<seqPriorityNode> nameMapCount;
1071 int error = m->readNames(nameFile, nameMapCount, seqs);
1073 if (m->control_pressed) { return nameAbund; }
1075 if (error == 1) { m->control_pressed = true; return nameAbund; }
1076 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; }
1078 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1080 string newFasta = fastaFile + ".temp";
1082 m->openOutputFile(newFasta, out);
1084 //print new file in order of
1085 for (int i = 0; i < nameMapCount.size(); i++) {
1086 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1087 nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1091 rename(newFasta.c_str(), fastaFile.c_str());
1096 catch(exception& e) {
1097 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1102 /**************************************************************************************************/