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"
14 //**********************************************************************************************************************
15 vector<string> ChimeraSlayerCommand::setParameters(){
17 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
18 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
19 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
20 CommandParameter pwindow("window", "Number", "", "50", "", "", "",false,false); parameters.push_back(pwindow);
21 CommandParameter pksize("ksize", "Number", "", "7", "", "", "",false,false); parameters.push_back(pksize);
22 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "",false,false); parameters.push_back(pmatch);
23 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "",false,false); parameters.push_back(pmismatch);
24 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminsim);
25 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "",false,false); parameters.push_back(pmincov);
26 CommandParameter pminsnp("minsnp", "Number", "", "100", "", "", "",false,false); parameters.push_back(pminsnp);
27 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminbs);
28 CommandParameter psearch("search", "Multiple", "kmer-blast-distance", "distance", "", "", "",false,false); parameters.push_back(psearch);
29 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
30 CommandParameter prealign("realign", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(prealign);
31 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(ptrim);
32 CommandParameter psplit("split", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psplit);
33 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "",false,false); parameters.push_back(pnumwanted);
34 CommandParameter piters("iters", "Number", "", "100", "", "", "",false,false); parameters.push_back(piters);
35 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "",false,false); parameters.push_back(pdivergence);
36 CommandParameter pparents("parents", "Number", "", "3", "", "", "",false,false); parameters.push_back(pparents);
37 CommandParameter pincrement("increment", "Number", "", "5", "", "", "",false,false); parameters.push_back(pincrement);
38 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
39 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
41 vector<string> myArray;
42 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
46 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
50 //**********************************************************************************************************************
51 string ChimeraSlayerCommand::getHelpString(){
53 string helpString = "";
54 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
55 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
56 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 and numwanted.\n"; //realign,
57 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";
58 helpString += "The name parameter allows you to provide a name file, if you are using template=self. \n";
59 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
60 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";
61 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
63 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
65 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";
66 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";
67 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
68 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
69 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
70 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
71 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
72 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";
73 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
74 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
75 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=100.\n";
76 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
77 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
78 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
79 helpString += "The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 100) \n";
80 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are distance, blast, and kmer, default distance. \n";
81 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default false. \n";
82 helpString += "The chimera.slayer command should be in the following format: \n";
83 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
84 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
85 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
89 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
93 //**********************************************************************************************************************
94 ChimeraSlayerCommand::ChimeraSlayerCommand(){
96 abort = true; calledHelp = true;
98 vector<string> tempOutNames;
99 outputTypes["chimera"] = tempOutNames;
100 outputTypes["accnos"] = tempOutNames;
101 outputTypes["fasta"] = tempOutNames;
103 catch(exception& e) {
104 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
108 //***************************************************************************************************************
109 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
111 abort = false; calledHelp = false;
113 //allow user to run help
114 if(option == "help") { help(); abort = true; calledHelp = true; }
117 vector<string> myArray = setParameters();
119 OptionParser parser(option);
120 map<string,string> parameters = parser.getParameters();
122 ValidParameters validParameter("chimera.slayer");
123 map<string,string>::iterator it;
125 //check to make sure all parameters are valid for command
126 for (it = parameters.begin(); it != parameters.end(); it++) {
127 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
130 vector<string> tempOutNames;
131 outputTypes["chimera"] = tempOutNames;
132 outputTypes["accnos"] = tempOutNames;
133 outputTypes["fasta"] = tempOutNames;
135 //if the user changes the input directory command factory will send this info to us in the output parameter
136 string inputDir = validParameter.validFile(parameters, "inputdir", false);
137 if (inputDir == "not found"){ inputDir = ""; }
139 //check for required parameters
140 fastafile = validParameter.validFile(parameters, "fasta", false);
141 if (fastafile == "not found") {
142 //if there is a current fasta file, use it
143 string filename = m->getFastaFile();
144 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
145 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
147 m->splitAtDash(fastafile, fastaFileNames);
149 //go through files and make sure they are good, if not, then disregard them
150 for (int i = 0; i < fastaFileNames.size(); i++) {
151 if (inputDir != "") {
152 string path = m->hasPath(fastaFileNames[i]);
153 //if the user has not given a path then, add inputdir. else leave path alone.
154 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
160 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
162 //if you can't open it, try default location
163 if (ableToOpen == 1) {
164 if (m->getDefaultPath() != "") { //default path is set
165 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
166 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
168 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
170 fastaFileNames[i] = tryPath;
174 if (ableToOpen == 1) {
175 if (m->getOutputDir() != "") { //default path is set
176 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
177 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
179 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
181 fastaFileNames[i] = tryPath;
187 if (ableToOpen == 1) {
188 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
189 //erase from file list
190 fastaFileNames.erase(fastaFileNames.begin()+i);
195 //make sure there is at least one valid file left
196 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
200 //check for required parameters
202 namefile = validParameter.validFile(parameters, "name", false);
203 if (namefile == "not found") { namefile = ""; hasName = false; }
205 m->splitAtDash(namefile, nameFileNames);
207 //go through files and make sure they are good, if not, then disregard them
208 for (int i = 0; i < nameFileNames.size(); i++) {
209 if (inputDir != "") {
210 string path = m->hasPath(nameFileNames[i]);
211 //if the user has not given a path then, add inputdir. else leave path alone.
212 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
218 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
220 //if you can't open it, try default location
221 if (ableToOpen == 1) {
222 if (m->getDefaultPath() != "") { //default path is set
223 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
224 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
226 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
228 nameFileNames[i] = tryPath;
232 if (ableToOpen == 1) {
233 if (m->getOutputDir() != "") { //default path is set
234 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
235 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
237 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
239 nameFileNames[i] = tryPath;
245 if (ableToOpen == 1) {
246 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
247 //erase from file list
248 nameFileNames.erase(nameFileNames.begin()+i);
253 //make sure there is at least one valid file left
254 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
257 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; }
259 //if the user changes the output directory command factory will send this info to us in the output parameter
260 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
264 it = parameters.find("reference");
265 //user has given a template file
266 if(it != parameters.end()){
267 if (it->second == "self") { templatefile = "self"; }
269 path = m->hasPath(it->second);
270 //if the user has not given a path then, add inputdir. else leave path alone.
271 if (path == "") { parameters["reference"] = inputDir + it->second; }
273 templatefile = validParameter.validFile(parameters, "reference", true);
274 if (templatefile == "not open") { abort = true; }
275 else if (templatefile == "not found") { templatefile = ""; m->mothurOut("reference is a required parameter for the chimera.slayer command."); m->mothurOutEndLine(); abort = true; }
279 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
280 m->setProcessors(temp);
281 convert(temp, processors);
283 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
284 convert(temp, ksize);
286 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
287 convert(temp, window);
289 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
290 convert(temp, match);
292 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
293 convert(temp, mismatch);
295 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
298 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
299 convert(temp, minSimilarity);
301 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
302 convert(temp, minCoverage);
304 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
305 convert(temp, minBS);
307 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "100"; }
308 convert(temp, minSNP);
310 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
311 convert(temp, parents);
313 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "f"; }
314 realign = m->isTrue(temp);
316 temp = validParameter.validFile(parameters, "trim", false); if (temp == "not found") { temp = "f"; }
317 trim = m->isTrue(temp);
319 temp = validParameter.validFile(parameters, "split", false); if (temp == "not found") { temp = "f"; }
320 trimera = m->isTrue(temp);
322 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "distance"; }
324 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "100"; }
325 convert(temp, iters);
327 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
328 convert(temp, increment);
330 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
331 convert(temp, numwanted);
333 if ((search != "distance") && (search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
336 catch(exception& e) {
337 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
341 //***************************************************************************************************************
343 int ChimeraSlayerCommand::execute(){
346 if (abort == true) { if (calledHelp) { return 0; } return 2; }
348 for (int s = 0; s < fastaFileNames.size(); s++) {
350 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
352 int start = time(NULL);
354 if (templatefile != "self") { //you want to run slayer with a refernce template
355 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);
357 if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
358 string nameFile = "";
359 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
360 nameFile = nameFileNames[s];
362 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
364 //use unique.seqs to create new name and fastafile
365 string inputString = "fasta=" + fastaFileNames[s];
366 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
367 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine();
369 Command* uniqueCommand = new DeconvoluteCommand(inputString);
370 uniqueCommand->execute();
372 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
374 delete uniqueCommand;
376 m->mothurOut("/******************************************/"); m->mothurOutEndLine();
378 nameFile = filenames["name"][0];
379 fastaFileNames[s] = filenames["fasta"][0];
382 //sort fastafile by abundance, returns new sorted fastafile name
383 m->mothurOut("Sorting fastafile according to abundance..."); cout.flush();
384 fastaFileNames[s] = sortFastaFile(fastaFileNames[s], nameFile);
385 m->mothurOut("Done."); m->mothurOutEndLine();
387 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } return 0; }
389 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, trim, nameFile, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);
392 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
393 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
394 string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.accnos";
395 string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.fasta";
397 if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } return 0; }
399 if (chimera->getUnaligned()) {
400 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine();
404 templateSeqsLength = chimera->getLength();
407 int pid, numSeqsPerProcessor;
409 vector<unsigned long int> MPIPos;
412 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
413 MPI_Comm_size(MPI_COMM_WORLD, &processors);
417 MPI_File outMPIAccnos;
418 MPI_File outMPIFasta;
420 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
421 int inMode=MPI_MODE_RDONLY;
423 char outFilename[1024];
424 strcpy(outFilename, outputFileName.c_str());
426 char outAccnosFilename[1024];
427 strcpy(outAccnosFilename, accnosFileName.c_str());
429 char outFastaFilename[1024];
430 strcpy(outFastaFilename, trimFastaFileName.c_str());
432 char inFileName[1024];
433 strcpy(inFileName, fastaFileNames[s].c_str());
435 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
436 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
437 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
438 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
440 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; }
442 if (pid == 0) { //you are the root process
443 m->mothurOutEndLine();
444 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
445 m->mothurOutEndLine();
447 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
450 int length = outTemp.length();
451 char* buf2 = new char[length];
452 memcpy(buf2, outTemp.c_str(), length);
454 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
457 MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
459 //send file positions to all processes
460 for(int i = 1; i < processors; i++) {
461 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
462 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
465 //figure out how many sequences you have to align
466 numSeqsPerProcessor = numSeqs / processors;
467 int startIndex = pid * numSeqsPerProcessor;
468 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
471 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
473 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; }
475 }else{ //you are a child process
476 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
477 MPIPos.resize(numSeqs+1);
478 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
480 //figure out how many sequences you have to align
481 numSeqsPerProcessor = numSeqs / processors;
482 int startIndex = pid * numSeqsPerProcessor;
483 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
486 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos);
488 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; }
492 MPI_File_close(&inMPI);
493 MPI_File_close(&outMPI);
494 MPI_File_close(&outMPIAccnos);
495 if (trim) { MPI_File_close(&outMPIFasta); }
496 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
500 string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
501 m->openOutputFile(tempHeader, outHeader);
503 chimera->printHeader(outHeader);
506 vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
508 for (int i = 0; i < (positions.size()-1); i++) {
509 lines.push_back(new linePair(positions[i], positions[(i+1)]));
513 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
515 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
517 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; }
520 processIDS.resize(0);
522 numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
524 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
525 rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
526 if (trim) { rename((trimFastaFileName + toString(processIDS[0]) + ".temp").c_str(), trimFastaFileName.c_str()); }
528 //append output files
529 for(int i=1;i<processors;i++){
530 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
531 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
534 //append output files
535 for(int i=1;i<processors;i++){
536 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
537 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
541 for(int i=1;i<processors;i++){
542 m->appendFiles((trimFastaFileName + toString(processIDS[i]) + ".temp"), trimFastaFileName);
543 remove((trimFastaFileName + toString(processIDS[i]) + ".temp").c_str());
547 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; }
551 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName, trimFastaFileName);
553 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; }
557 m->appendFiles(outputFileName, tempHeader);
559 remove(outputFileName.c_str());
560 rename(tempHeader.c_str(), outputFileName.c_str());
566 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
568 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
569 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
570 if (trim) { outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }
572 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
575 //set accnos file as new current accnosfile
577 itTypes = outputTypes.find("accnos");
578 if (itTypes != outputTypes.end()) {
579 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
583 itTypes = outputTypes.find("fasta");
584 if (itTypes != outputTypes.end()) {
585 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
589 m->mothurOutEndLine();
590 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
591 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
592 m->mothurOutEndLine();
597 catch(exception& e) {
598 m->errorOut(e, "ChimeraSlayerCommand", "execute");
602 //**********************************************************************************************************************
604 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos, string fasta){
607 m->openOutputFile(outputFName, out);
610 m->openOutputFile(accnos, out2);
613 if (trim) { m->openOutputFile(fasta, out3); }
616 m->openInputFile(filename, inFASTA);
618 inFASTA.seekg(filePos->start);
625 if (m->control_pressed) { out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1; }
627 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
628 string candidateAligned = candidateSeq->getAligned();
630 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
632 if (candidateSeq->getAligned().length() != templateSeqsLength) {
633 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
636 chimera->getChimeras(candidateSeq);
638 if (m->control_pressed) { delete candidateSeq; return 1; }
640 //if you are not chimeric, then check each half
641 data_results wholeResults = chimera->getResults();
643 //determine if we need to split
644 bool isChimeric = false;
646 if (wholeResults.flag == "yes") {
647 string chimeraFlag = "no";
648 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
650 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
653 if (chimeraFlag == "yes") {
654 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
658 if ((!isChimeric) && trimera) {
660 //split sequence in half by bases
661 string leftQuery, rightQuery;
662 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
663 divideInHalf(tempSeq, leftQuery, rightQuery);
665 //run chimeraSlayer on each piece
666 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
667 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
670 chimera->getChimeras(left);
671 data_results leftResults = chimera->getResults();
673 chimera->getChimeras(right);
674 data_results rightResults = chimera->getResults();
676 //if either piece is chimeric then report
677 Sequence* trimmed = chimera->print(out, out2, leftResults, rightResults);
678 if (trim) { trimmed->printSequence(out3); delete trimmed; }
680 delete left; delete right;
682 }else { //already chimeric
684 Sequence* trimmed = chimera->print(out, out2);
685 if (trim) { trimmed->printSequence(out3); delete trimmed; }
694 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
695 unsigned long int pos = inFASTA.tellg();
696 if ((pos == -1) || (pos >= filePos->end)) { break; }
698 if (inFASTA.eof()) { break; }
702 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
705 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
709 if (trim) { out3.close(); }
714 catch(exception& e) {
715 m->errorOut(e, "ChimeraSlayerCommand", "driver");
719 //**********************************************************************************************************************
721 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long int>& MPIPos){
725 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
727 for(int i=0;i<num;i++){
729 if (m->control_pressed) { return 1; }
732 int length = MPIPos[start+i+1] - MPIPos[start+i];
734 char* buf4 = new char[length];
735 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
737 string tempBuf = buf4;
738 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
739 istringstream iss (tempBuf,istringstream::in);
743 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
744 string candidateAligned = candidateSeq->getAligned();
746 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
748 if (candidateSeq->getAligned().length() != templateSeqsLength) {
749 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
753 chimera->getChimeras(candidateSeq);
755 if (m->control_pressed) { delete candidateSeq; return 1; }
757 //if you are not chimeric, then check each half
758 data_results wholeResults = chimera->getResults();
760 //determine if we need to split
761 bool isChimeric = false;
763 if (wholeResults.flag == "yes") {
764 string chimeraFlag = "no";
765 if( (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
767 (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
770 if (chimeraFlag == "yes") {
771 if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
775 if ((!isChimeric) && trimera) {
776 //split sequence in half by bases
777 string leftQuery, rightQuery;
778 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
779 divideInHalf(tempSeq, leftQuery, rightQuery);
781 //run chimeraSlayer on each piece
782 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
783 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
786 chimera->getChimeras(left);
787 data_results leftResults = chimera->getResults();
789 chimera->getChimeras(right);
790 data_results rightResults = chimera->getResults();
792 //if either piece is chimeric then report
793 Sequence* trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
795 string outputString = ">" + trimmed->getName() + "\n" + trimmed->getAligned() + "\n";
798 //write to accnos file
799 int length = outputString.length();
800 char* buf2 = new char[length];
801 memcpy(buf2, outputString.c_str(), length);
803 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
807 delete left; delete right;
811 Sequence* trimmed = chimera->print(outMPI, outAccMPI);
814 string outputString = ">" + trimmed->getName() + "\n" + trimmed->getAligned() + "\n";
817 //write to accnos file
818 int length = outputString.length();
819 char* buf2 = new char[length];
820 memcpy(buf2, outputString.c_str(), length);
822 MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
832 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
835 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
840 catch(exception& e) {
841 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
847 /**************************************************************************************************/
849 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta) {
851 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
855 //loop through and create all the processes you want
856 while (process != processors) {
860 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
863 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp");
865 //pass numSeqs to parent
867 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
868 m->openOutputFile(tempFile, out);
874 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
875 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
880 //force parent to wait until all the processes are done
881 for (int i=0;i<processors;i++) {
882 int temp = processIDS[i];
886 for (int i = 0; i < processIDS.size(); i++) {
888 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
889 m->openInputFile(tempFile, in);
890 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
891 in.close(); remove(tempFile.c_str());
897 catch(exception& e) {
898 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
903 /**************************************************************************************************/
905 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
908 string queryUnAligned = querySeq.getUnaligned();
909 int numBases = int(queryUnAligned.length() * 0.5);
911 string queryAligned = querySeq.getAligned();
912 leftQuery = querySeq.getAligned();
913 rightQuery = querySeq.getAligned();
917 for (int i = 0; i < queryAligned.length(); i++) {
919 if (isalpha(queryAligned[i])) {
924 if (baseCount >= numBases) { leftSpot = i; break; } //first half
927 //blank out right side
928 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
930 //blank out left side
931 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
936 catch(exception& e) {
937 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
941 /**************************************************************************************************/
943 string ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
946 //read through fastafile and store info
947 map<string, string> seqs;
949 m->openInputFile(fastaFile, in);
953 if (m->control_pressed) { in.close(); return ""; }
955 Sequence seq(in); m->gobble(in);
956 seqs[seq.getName()] = seq.getAligned();
962 vector<seqPriorityNode> nameMapCount;
963 int error = m->readNames(nameFile, nameMapCount, seqs);
965 if (m->control_pressed) { return ""; }
967 if (error == 1) { m->control_pressed = true; return ""; }
968 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 ""; }
970 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
972 string newFasta = fastaFile + ".temp";
974 m->openOutputFile(newFasta, out);
976 //print new file in order of
977 for (int i = 0; i < nameMapCount.size(); i++) {
978 out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
982 rename(newFasta.c_str(), fastaFile.c_str());
987 catch(exception& e) {
988 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
993 /**************************************************************************************************/