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"
14 //***************************************************************************************************************
16 ChimeraSlayerCommand::ChimeraSlayerCommand(string option) {
20 //allow user to run help
21 if(option == "help") { help(); abort = true; }
24 //valid paramters for this command
25 string Array[] = {"fasta", "processors", "window", "template","numwanted", "ksize", "match","mismatch",
26 "divergence", "minsim","mincov","minbs", "minsnp","parents", "iters","outputdir","inputdir", "search","realign" };
27 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
29 OptionParser parser(option);
30 map<string,string> parameters = parser.getParameters();
32 ValidParameters validParameter("chimera.slayer");
33 map<string,string>::iterator it;
35 //check to make sure all parameters are valid for command
36 for (it = parameters.begin(); it != parameters.end(); it++) {
37 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
40 //if the user changes the input directory command factory will send this info to us in the output parameter
41 string inputDir = validParameter.validFile(parameters, "inputdir", false);
42 if (inputDir == "not found"){ inputDir = ""; }
45 it = parameters.find("template");
46 //user has given a template file
47 if(it != parameters.end()){
48 path = m->hasPath(it->second);
49 //if the user has not given a path then, add inputdir. else leave path alone.
50 if (path == "") { parameters["template"] = inputDir + it->second; }
55 //check for required parameters
56 fastafile = validParameter.validFile(parameters, "fasta", false);
57 if (fastafile == "not found") { fastafile = ""; m->mothurOut("fasta is a required parameter for the chimera.slayer command."); m->mothurOutEndLine(); abort = true; }
59 m->splitAtDash(fastafile, fastaFileNames);
61 //go through files and make sure they are good, if not, then disregard them
62 for (int i = 0; i < fastaFileNames.size(); i++) {
64 string path = m->hasPath(fastaFileNames[i]);
65 //if the user has not given a path then, add inputdir. else leave path alone.
66 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
72 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
74 //if you can't open it, try default location
75 if (ableToOpen == 1) {
76 if (m->getDefaultPath() != "") { //default path is set
77 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
78 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
79 ableToOpen = m->openInputFile(tryPath, in, "noerror");
80 fastaFileNames[i] = tryPath;
85 if (ableToOpen == 1) {
86 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
87 //erase from file list
88 fastaFileNames.erase(fastaFileNames.begin()+i);
93 //make sure there is at least one valid file left
94 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
97 //if the user changes the output directory command factory will send this info to us in the output parameter
98 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
100 templatefile = validParameter.validFile(parameters, "template", true);
101 if (templatefile == "not open") { abort = true; }
102 else if (templatefile == "not found") { templatefile = ""; m->mothurOut("template is a required parameter for the chimera.slayer command."); m->mothurOutEndLine(); abort = true; }
104 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found") { temp = "1"; }
105 convert(temp, processors);
107 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
108 convert(temp, ksize);
110 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "50"; }
111 convert(temp, window);
113 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found") { temp = "5"; }
114 convert(temp, match);
116 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found") { temp = "-4"; }
117 convert(temp, mismatch);
119 temp = validParameter.validFile(parameters, "divergence", false); if (temp == "not found") { temp = "1.007"; }
122 temp = validParameter.validFile(parameters, "minsim", false); if (temp == "not found") { temp = "90"; }
123 convert(temp, minSimilarity);
125 temp = validParameter.validFile(parameters, "mincov", false); if (temp == "not found") { temp = "70"; }
126 convert(temp, minCoverage);
128 temp = validParameter.validFile(parameters, "minbs", false); if (temp == "not found") { temp = "90"; }
129 convert(temp, minBS);
131 temp = validParameter.validFile(parameters, "minsnp", false); if (temp == "not found") { temp = "100"; }
132 convert(temp, minSNP);
134 temp = validParameter.validFile(parameters, "parents", false); if (temp == "not found") { temp = "3"; }
135 convert(temp, parents);
137 temp = validParameter.validFile(parameters, "realign", false); if (temp == "not found") { temp = "f"; }
138 realign = m->isTrue(temp);
140 search = validParameter.validFile(parameters, "search", false); if (search == "not found") { search = "distance"; }
142 temp = validParameter.validFile(parameters, "iters", false); if (temp == "not found") { temp = "100"; }
143 convert(temp, iters);
145 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "5"; }
146 convert(temp, increment);
148 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "15"; }
149 convert(temp, numwanted);
151 if ((search != "distance") && (search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true; }
154 catch(exception& e) {
155 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
159 //**********************************************************************************************************************
161 void ChimeraSlayerCommand::help(){
164 m->mothurOut("The chimera.slayer command reads a fastafile and templatefile and outputs potentially chimeric sequences.\n");
165 m->mothurOut("This command was modeled after the chimeraSlayer written by the Broad Institute.\n");
166 m->mothurOut("The chimera.slayer command parameters are fasta, template, processors, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment and numwanted.\n"); //realign,
167 m->mothurOut("The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required. \n");
168 m->mothurOut("You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n");
169 m->mothurOut("The template parameter allows you to enter a template file containing known non-chimeric sequences, and is required. \n");
170 m->mothurOut("The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n");
172 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
174 m->mothurOut("The window parameter allows you to specify the window size for searching for chimeras, default=50. \n");
175 m->mothurOut("The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n");
176 m->mothurOut("The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n");
177 m->mothurOut("The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n");
178 m->mothurOut("The match parameter allows you to reward matched bases in blast search, default is 5. \n");
179 m->mothurOut("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");
180 m->mothurOut("The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n");
181 m->mothurOut("The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n");
182 m->mothurOut("The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=100.\n");
183 m->mothurOut("The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n");
184 m->mothurOut("The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n");
185 m->mothurOut("The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n");
186 m->mothurOut("The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 100) \n");
187 m->mothurOut("The search parameter allows you to specify search method for finding the closest parent. Choices are distance, blast, and kmer, default distance. \n");
188 m->mothurOut("The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default false. \n");
189 m->mothurOut("The chimera.slayer command should be in the following format: \n");
190 m->mothurOut("chimera.slayer(fasta=yourFastaFile, template=yourTemplate, search=yourSearch) \n");
191 m->mothurOut("Example: chimera.slayer(fasta=AD.align, template=core_set_aligned.imputed.fasta, search=kmer) \n");
192 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
194 catch(exception& e) {
195 m->errorOut(e, "ChimeraSlayerCommand", "help");
200 //***************************************************************************************************************
202 ChimeraSlayerCommand::~ChimeraSlayerCommand(){ /* do nothing */ }
204 //***************************************************************************************************************
206 int ChimeraSlayerCommand::execute(){
209 if (abort == true) { return 0; }
211 for (int s = 0; s < fastaFileNames.size(); s++) {
213 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
215 int start = time(NULL);
217 chimera = new ChimeraSlayer(fastaFileNames[s], templatefile, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign);
219 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
220 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras";
221 string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.accnos";
223 if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } return 0; }
225 if (chimera->getUnaligned()) {
226 m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine();
230 templateSeqsLength = chimera->getLength();
233 int pid, end, numSeqsPerProcessor;
235 vector<unsigned long int> MPIPos;
238 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
239 MPI_Comm_size(MPI_COMM_WORLD, &processors);
243 MPI_File outMPIAccnos;
245 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
246 int inMode=MPI_MODE_RDONLY;
248 char outFilename[1024];
249 strcpy(outFilename, outputFileName.c_str());
251 char outAccnosFilename[1024];
252 strcpy(outAccnosFilename, accnosFileName.c_str());
254 char inFileName[1024];
255 strcpy(inFileName, fastaFileNames[s].c_str());
257 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
258 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
259 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
261 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); MPI_File_close(&outMPIAccnos); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } delete chimera; return 0; }
263 if (pid == 0) { //you are the root process
264 m->mothurOutEndLine();
265 m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
266 m->mothurOutEndLine();
268 string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
271 int length = outTemp.length();
272 char* buf2 = new char[length];
273 memcpy(buf2, outTemp.c_str(), length);
275 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
278 MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
280 //send file positions to all processes
281 for(int i = 1; i < processors; i++) {
282 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
283 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
286 //figure out how many sequences you have to align
287 numSeqsPerProcessor = numSeqs / processors;
288 int startIndex = pid * numSeqsPerProcessor;
289 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
292 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
294 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); 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; }
296 }else{ //you are a child process
297 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
298 MPIPos.resize(numSeqs+1);
299 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
301 //figure out how many sequences you have to align
302 numSeqsPerProcessor = numSeqs / processors;
303 int startIndex = pid * numSeqsPerProcessor;
304 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
307 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
309 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); MPI_File_close(&outMPIAccnos); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } delete chimera; return 0; }
313 MPI_File_close(&inMPI);
314 MPI_File_close(&outMPI);
315 MPI_File_close(&outMPIAccnos);
316 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
320 string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimeras.tempHeader";
321 m->openOutputFile(tempHeader, outHeader);
323 chimera->printHeader(outHeader);
326 vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
328 for (int i = 0; i < (positions.size()-1); i++) {
329 lines.push_back(new linePair(positions[i], positions[(i+1)]));
333 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
335 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
337 if (m->control_pressed) { 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; }
340 processIDS.resize(0);
342 numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName);
344 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
345 rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
347 //append output files
348 for(int i=1;i<processors;i++){
349 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
350 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
353 //append output files
354 for(int i=1;i<processors;i++){
355 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
356 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
359 if (m->control_pressed) { 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; }
363 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
365 if (m->control_pressed) { 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; }
369 m->appendFiles(outputFileName, tempHeader);
371 remove(outputFileName.c_str());
372 rename(tempHeader.c_str(), outputFileName.c_str());
378 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
380 outputNames.push_back(outputFileName);
381 outputNames.push_back(accnosFileName);
383 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
386 m->mothurOutEndLine();
387 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
388 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
389 m->mothurOutEndLine();
394 catch(exception& e) {
395 m->errorOut(e, "ChimeraSlayerCommand", "execute");
399 //**********************************************************************************************************************
401 int ChimeraSlayerCommand::driver(linePair* filePos, string outputFName, string filename, string accnos){
404 m->openOutputFile(outputFName, out);
407 m->openOutputFile(accnos, out2);
410 m->openInputFile(filename, inFASTA);
412 inFASTA.seekg(filePos->start);
419 if (m->control_pressed) { return 1; }
421 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
423 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
425 if (candidateSeq->getAligned().length() != templateSeqsLength) {
426 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
429 chimera->getChimeras(candidateSeq);
431 if (m->control_pressed) { delete candidateSeq; return 1; }
434 chimera->print(out, out2);
440 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
441 unsigned long int pos = inFASTA.tellg();
442 if ((pos == -1) || (pos >= filePos->end)) { break; }
444 if (inFASTA.eof()) { break; }
448 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
451 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
459 catch(exception& e) {
460 m->errorOut(e, "ChimeraSlayerCommand", "driver");
464 //**********************************************************************************************************************
466 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, vector<unsigned long int>& MPIPos){
470 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
472 for(int i=0;i<num;i++){
474 if (m->control_pressed) { return 1; }
477 int length = MPIPos[start+i+1] - MPIPos[start+i];
479 char* buf4 = new char[length];
480 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
482 string tempBuf = buf4;
483 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
484 istringstream iss (tempBuf,istringstream::in);
488 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
490 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
492 if (candidateSeq->getAligned().length() != templateSeqsLength) {
493 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
497 chimera->getChimeras(candidateSeq);
499 if (m->control_pressed) { delete candidateSeq; return 1; }
500 //cout << "about to print" << endl;
502 bool isChimeric = chimera->print(outMPI, outAccMPI);
508 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
511 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
516 catch(exception& e) {
517 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
523 /**************************************************************************************************/
525 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos) {
527 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
531 //loop through and create all the processes you want
532 while (process != processors) {
536 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
539 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp");
541 //pass numSeqs to parent
543 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
544 m->openOutputFile(tempFile, out);
549 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
552 //force parent to wait until all the processes are done
553 for (int i=0;i<processors;i++) {
554 int temp = processIDS[i];
558 for (int i = 0; i < processIDS.size(); i++) {
560 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
561 m->openInputFile(tempFile, in);
562 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
563 in.close(); remove(tempFile.c_str());
569 catch(exception& e) {
570 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
575 /**************************************************************************************************/