2 * chimeracheckcommand.cpp
5 * Created by westcott on 3/31/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "chimeracheckcommand.h"
12 //**********************************************************************************************************************
13 vector<string> ChimeraCheckCommand::setParameters(){
15 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
16 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
17 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
18 CommandParameter psvg("svg", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psvg);
19 CommandParameter pincrement("increment", "Number", "", "10", "", "", "",false,false); parameters.push_back(pincrement);
20 CommandParameter pksize("ksize", "Number", "", "7", "", "", "",false,false); parameters.push_back(pksize);
21 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
22 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
23 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
25 vector<string> myArray;
26 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
30 m->errorOut(e, "ChimeraCheckCommand", "setParameters");
34 //**********************************************************************************************************************
35 string ChimeraCheckCommand::getHelpString(){
37 string helpString = "";
38 helpString += "The chimera.check command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
39 helpString += "This command was created using the algorythms described in CHIMERA_CHECK version 2.7 written by Niels Larsen. \n";
40 helpString += "The chimera.check command parameters are fasta, reference, processors, ksize, increment, svg and name.\n";
41 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";
42 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n";
43 helpString += "The reference parameter allows you to enter a reference file containing known non-chimeric sequences, and is required. \n";
44 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
46 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
48 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default is 10.\n";
49 helpString += "The ksize parameter allows you to input kmersize, default is 7. \n";
50 helpString += "The svg parameter allows you to specify whether or not you would like a svg file outputted for each query sequence, default is False.\n";
51 helpString += "The name parameter allows you to enter a file containing names of sequences you would like .svg files for.\n";
52 helpString += "You may enter multiple name files by separating their names with dashes. ie. fasta=abrecovery.svg.names-amzon.svg.names \n";
53 helpString += "The chimera.check command should be in the following format: \n";
54 helpString += "chimera.check(fasta=yourFastaFile, reference=yourTemplateFile, processors=yourProcessors, ksize=yourKmerSize) \n";
55 helpString += "Example: chimera.check(fasta=AD.fasta, reference=core_set_aligned,imputed.fasta, processors=4, ksize=8) \n";
56 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
60 m->errorOut(e, "ChimeraCheckCommand", "getHelpString");
64 //**********************************************************************************************************************
65 ChimeraCheckCommand::ChimeraCheckCommand(){
67 abort = true; calledHelp = true;
69 vector<string> tempOutNames;
70 outputTypes["chimera"] = tempOutNames;
73 m->errorOut(e, "ChimeraCheckCommand", "ChimeraCheckCommand");
77 //***************************************************************************************************************
78 ChimeraCheckCommand::ChimeraCheckCommand(string option) {
80 abort = false; calledHelp = false;
82 //allow user to run help
83 if(option == "help") { help(); abort = true; calledHelp = true; }
84 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
87 vector<string> myArray = setParameters();
89 OptionParser parser(option);
90 map<string,string> parameters = parser.getParameters();
92 ValidParameters validParameter("chimera.check");
93 map<string,string>::iterator it;
95 //check to make sure all parameters are valid for command
96 for (it = parameters.begin(); it != parameters.end(); it++) {
97 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
100 vector<string> tempOutNames;
101 outputTypes["chimera"] = tempOutNames;
103 //if the user changes the input directory command factory will send this info to us in the output parameter
104 string inputDir = validParameter.validFile(parameters, "inputdir", false);
105 if (inputDir == "not found"){ inputDir = ""; }
107 it = parameters.find("reference");
108 //user has given a template file
109 if(it != parameters.end()){
110 string path = m->hasPath(it->second);
111 //if the user has not given a path then, add inputdir. else leave path alone.
112 if (path == "") { parameters["reference"] = inputDir + it->second; }
116 //check for required parameters
117 fastafile = validParameter.validFile(parameters, "fasta", false);
118 if (fastafile == "not found") {
119 //if there is a current fasta file, use it
120 string filename = m->getFastaFile();
121 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
122 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
124 m->splitAtDash(fastafile, fastaFileNames);
126 //go through files and make sure they are good, if not, then disregard them
127 for (int i = 0; i < fastaFileNames.size(); i++) {
130 if (fastaFileNames[i] == "current") {
131 fastaFileNames[i] = m->getFastaFile();
132 if (fastaFileNames[i] != "") { m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
134 m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true;
135 //erase from file list
136 fastaFileNames.erase(fastaFileNames.begin()+i);
144 if (inputDir != "") {
145 string path = m->hasPath(fastaFileNames[i]);
146 //if the user has not given a path then, add inputdir. else leave path alone.
147 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
153 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
155 //if you can't open it, try default location
156 if (ableToOpen == 1) {
157 if (m->getDefaultPath() != "") { //default path is set
158 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
159 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
161 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
163 fastaFileNames[i] = tryPath;
167 //if you can't open it, try default location
168 if (ableToOpen == 1) {
169 if (m->getOutputDir() != "") { //default path is set
170 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
171 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
173 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
175 fastaFileNames[i] = tryPath;
181 if (ableToOpen == 1) {
182 m->mothurOut("Unable to open " + fastaFileNames[i] +". It will be disregarded."); m->mothurOutEndLine();
183 //erase from file list
184 fastaFileNames.erase(fastaFileNames.begin()+i);
187 m->setFastaFile(fastaFileNames[i]);
192 //make sure there is at least one valid file left
193 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
196 //if the user changes the output directory command factory will send this info to us in the output parameter
197 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
199 templatefile = validParameter.validFile(parameters, "reference", true);
200 if (templatefile == "not open") { abort = true; }
201 else if (templatefile == "not found") { templatefile = ""; m->mothurOut("reference is a required parameter for the chimera.check command."); m->mothurOutEndLine(); abort = true; }
203 namefile = validParameter.validFile(parameters, "name", false);
204 if (namefile == "not found") { namefile = ""; }
206 m->splitAtDash(namefile, nameFileNames);
208 //go through files and make sure they are good, if not, then disregard them
209 for (int i = 0; i < nameFileNames.size(); i++) {
212 if (nameFileNames[i] == "current") {
213 nameFileNames[i] = m->getNameFile();
214 if (nameFileNames[i] != "") { m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
216 m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true;
217 //erase from file list
218 nameFileNames.erase(nameFileNames.begin()+i);
225 if (inputDir != "") {
226 string path = m->hasPath(nameFileNames[i]);
227 //if the user has not given a path then, add inputdir. else leave path alone.
228 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
234 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
236 //if you can't open it, try default location
237 if (ableToOpen == 1) {
238 if (m->getDefaultPath() != "") { //default path is set
239 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
240 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
242 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
244 nameFileNames[i] = tryPath;
248 //if you can't open it, try default location
249 if (ableToOpen == 1) {
250 if (m->getOutputDir() != "") { //default path is set
251 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
252 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
254 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
256 nameFileNames[i] = tryPath;
262 if (ableToOpen == 1) {
263 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
264 //erase from file list
265 nameFileNames.erase(nameFileNames.begin()+i);
268 m->setNameFile(nameFileNames[i]);
273 //make sure there is at least one valid file left
274 if (nameFileNames.size() != 0) {
275 if (nameFileNames.size() != fastaFileNames.size()) {
276 m->mothurOut("Different number of valid name files and fasta files, aborting command."); m->mothurOutEndLine();
282 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
283 m->setProcessors(temp);
284 convert(temp, processors);
286 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
287 convert(temp, ksize);
289 temp = validParameter.validFile(parameters, "svg", false); if (temp == "not found") { temp = "F"; }
290 svg = m->isTrue(temp);
291 if (nameFileNames.size() != 0) { svg = true; }
293 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "10"; }
294 convert(temp, increment);
297 catch(exception& e) {
298 m->errorOut(e, "ChimeraCheckCommand", "ChimeraCheckCommand");
302 //***************************************************************************************************************
304 int ChimeraCheckCommand::execute(){
307 if (abort == true) { if (calledHelp) { return 0; } return 2; }
309 for (int i = 0; i < fastaFileNames.size(); i++) {
311 m->mothurOut("Checking sequences from " + fastaFileNames[i] + " ..." ); m->mothurOutEndLine();
313 int start = time(NULL);
315 string thisNameFile = "";
316 if (nameFileNames.size() != 0) { thisNameFile = nameFileNames[i]; }
318 chimera = new ChimeraCheckRDP(fastaFileNames[i], templatefile, thisNameFile, svg, increment, ksize, outputDir);
320 if (m->control_pressed) { delete chimera; return 0; }
322 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[i]); }//if user entered a file with a path then preserve it
323 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i])) + "chimeracheck.chimeras";
324 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
328 int pid, numSeqsPerProcessor;
330 vector<unsigned long int> MPIPos;
333 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
334 MPI_Comm_size(MPI_COMM_WORLD, &processors);
339 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
340 int inMode=MPI_MODE_RDONLY;
342 char outFilename[1024];
343 strcpy(outFilename, outputFileName.c_str());
345 char inFileName[1024];
346 strcpy(inFileName, fastaFileNames[i].c_str());
348 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
349 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
351 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear(); delete chimera; return 0; }
353 if (pid == 0) { //you are the root process
354 MPIPos = m->setFilePosFasta(fastaFileNames[i], numSeqs); //fills MPIPos, returns numSeqs
356 //send file positions to all processes
357 for(int j = 1; j < processors; j++) {
358 MPI_Send(&numSeqs, 1, MPI_INT, j, tag, MPI_COMM_WORLD);
359 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, j, tag, MPI_COMM_WORLD);
362 //figure out how many sequences you have to align
363 numSeqsPerProcessor = numSeqs / processors;
364 int startIndex = pid * numSeqsPerProcessor;
365 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
369 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
371 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear(); delete chimera; return 0; }
374 for(int j = 1; j < processors; j++) {
376 MPI_Recv(buf, 5, MPI_CHAR, j, tag, MPI_COMM_WORLD, &status);
378 }else{ //you are a child process
379 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
380 MPIPos.resize(numSeqs+1);
381 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
383 //figure out how many sequences you have to align
384 numSeqsPerProcessor = numSeqs / processors;
385 int startIndex = pid * numSeqsPerProcessor;
386 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
389 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
391 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear(); delete chimera; return 0; }
393 //tell parent you are done.
396 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
400 MPI_File_close(&inMPI);
401 MPI_File_close(&outMPI);
402 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
405 vector<unsigned long int> positions = m->divideFile(fastaFileNames[i], processors);
407 for (int s = 0; s < (positions.size()-1); s++) {
408 lines.push_back(new linePair(positions[s], positions[(s+1)]));
412 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
414 numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
416 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } for (int j = 0; j < lines.size(); j++) { delete lines[j]; } outputTypes.clear(); lines.clear(); delete chimera; return 0; }
419 processIDS.resize(0);
421 numSeqs = createProcesses(outputFileName, fastaFileNames[i]);
423 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
425 //append output files
426 for(int j=1;j<processors;j++){
427 m->appendFiles((outputFileName + toString(processIDS[j]) + ".temp"), outputFileName);
428 remove((outputFileName + toString(processIDS[j]) + ".temp").c_str());
431 if (m->control_pressed) {
432 for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear();
433 for (int j = 0; j < lines.size(); j++) { delete lines[j]; } lines.clear();
440 numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
442 if (m->control_pressed) { for (int j = 0; j < lines.size(); j++) { delete lines[j]; } lines.clear(); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear(); delete chimera; return 0; }
446 for (int j = 0; j < lines.size(); j++) { delete lines[j]; } lines.clear();
448 m->mothurOutEndLine(); m->mothurOut("This method does not determine if a sequence is chimeric, but allows you to make that determination based on the IS values."); m->mothurOutEndLine();
449 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
453 m->mothurOutEndLine();
454 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
455 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
456 m->mothurOutEndLine();
461 catch(exception& e) {
462 m->errorOut(e, "ChimeraCheckCommand", "execute");
466 //**********************************************************************************************************************
468 int ChimeraCheckCommand::driver(linePair* filePos, string outputFName, string filename){
471 m->openOutputFile(outputFName, out);
476 m->openInputFile(filename, inFASTA);
478 inFASTA.seekg(filePos->start);
485 if (m->control_pressed) { return 1; }
487 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
489 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
491 chimera->getChimeras(candidateSeq);
493 if (m->control_pressed) { delete candidateSeq; return 1; }
496 chimera->print(out, out2);
500 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
501 unsigned long int pos = inFASTA.tellg();
502 if ((pos == -1) || (pos >= filePos->end)) { break; }
504 if (inFASTA.eof()) { break; }
508 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
511 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
518 catch(exception& e) {
519 m->errorOut(e, "ChimeraCheckCommand", "driver");
523 //**********************************************************************************************************************
525 int ChimeraCheckCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, vector<unsigned long int>& MPIPos){
530 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
532 for(int i=0;i<num;i++){
534 if (m->control_pressed) { return 0; }
537 int length = MPIPos[start+i+1] - MPIPos[start+i];
539 char* buf4 = new char[length];
540 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
542 string tempBuf = buf4;
543 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
544 istringstream iss (tempBuf,istringstream::in);
547 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
549 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
551 chimera->getChimeras(candidateSeq);
554 chimera->print(outMPI, outAccMPI);
559 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
562 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
566 catch(exception& e) {
567 m->errorOut(e, "ChimeraCheckCommand", "driverMPI");
573 /**************************************************************************************************/
575 int ChimeraCheckCommand::createProcesses(string outputFileName, string filename) {
577 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
581 //loop through and create all the processes you want
582 while (process != processors) {
586 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
589 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename);
591 //pass numSeqs to parent
593 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
594 m->openOutputFile(tempFile, out);
600 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
601 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
606 //force parent to wait until all the processes are done
607 for (int i=0;i<processors;i++) {
608 int temp = processIDS[i];
612 for (int i = 0; i < processIDS.size(); i++) {
614 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
615 m->openInputFile(tempFile, in);
616 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
617 in.close(); remove(tempFile.c_str());
623 catch(exception& e) {
624 m->errorOut(e, "ChimeraCheckCommand", "createProcesses");
628 /**************************************************************************************************/