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; }
86 vector<string> myArray = setParameters();
88 OptionParser parser(option);
89 map<string,string> parameters = parser.getParameters();
91 ValidParameters validParameter("chimera.check");
92 map<string,string>::iterator it;
94 //check to make sure all parameters are valid for command
95 for (it = parameters.begin(); it != parameters.end(); it++) {
96 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
99 vector<string> tempOutNames;
100 outputTypes["chimera"] = tempOutNames;
102 //if the user changes the input directory command factory will send this info to us in the output parameter
103 string inputDir = validParameter.validFile(parameters, "inputdir", false);
104 if (inputDir == "not found"){ inputDir = ""; }
106 it = parameters.find("reference");
107 //user has given a template file
108 if(it != parameters.end()){
109 string path = m->hasPath(it->second);
110 //if the user has not given a path then, add inputdir. else leave path alone.
111 if (path == "") { parameters["reference"] = inputDir + it->second; }
115 //check for required parameters
116 fastafile = validParameter.validFile(parameters, "fasta", false);
117 if (fastafile == "not found") {
118 //if there is a current fasta file, use it
119 string filename = m->getFastaFile();
120 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
121 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
123 m->splitAtDash(fastafile, fastaFileNames);
125 //go through files and make sure they are good, if not, then disregard them
126 for (int i = 0; i < fastaFileNames.size(); i++) {
127 if (inputDir != "") {
128 string path = m->hasPath(fastaFileNames[i]);
129 //if the user has not given a path then, add inputdir. else leave path alone.
130 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
136 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
138 //if you can't open it, try default location
139 if (ableToOpen == 1) {
140 if (m->getDefaultPath() != "") { //default path is set
141 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
142 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
144 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
146 fastaFileNames[i] = tryPath;
150 //if you can't open it, try default location
151 if (ableToOpen == 1) {
152 if (m->getOutputDir() != "") { //default path is set
153 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
154 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
156 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
158 fastaFileNames[i] = tryPath;
164 if (ableToOpen == 1) {
165 m->mothurOut("Unable to open " + fastaFileNames[i] +". It will be disregarded."); m->mothurOutEndLine();
166 //erase from file list
167 fastaFileNames.erase(fastaFileNames.begin()+i);
172 //make sure there is at least one valid file left
173 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
176 //if the user changes the output directory command factory will send this info to us in the output parameter
177 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
179 templatefile = validParameter.validFile(parameters, "reference", true);
180 if (templatefile == "not open") { abort = true; }
181 else if (templatefile == "not found") { templatefile = ""; m->mothurOut("reference is a required parameter for the chimera.check command."); m->mothurOutEndLine(); abort = true; }
183 namefile = validParameter.validFile(parameters, "name", false);
184 if (namefile == "not found") { namefile = ""; }
186 m->splitAtDash(namefile, nameFileNames);
188 //go through files and make sure they are good, if not, then disregard them
189 for (int i = 0; i < nameFileNames.size(); i++) {
190 if (inputDir != "") {
191 string path = m->hasPath(nameFileNames[i]);
192 //if the user has not given a path then, add inputdir. else leave path alone.
193 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
199 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
201 //if you can't open it, try default location
202 if (ableToOpen == 1) {
203 if (m->getDefaultPath() != "") { //default path is set
204 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
205 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
207 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
209 nameFileNames[i] = tryPath;
213 //if you can't open it, try default location
214 if (ableToOpen == 1) {
215 if (m->getOutputDir() != "") { //default path is set
216 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
217 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
219 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
221 nameFileNames[i] = tryPath;
227 if (ableToOpen == 1) {
228 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
229 //erase from file list
230 nameFileNames.erase(nameFileNames.begin()+i);
236 //make sure there is at least one valid file left
237 if (nameFileNames.size() != 0) {
238 if (nameFileNames.size() != fastaFileNames.size()) {
239 m->mothurOut("Different number of valid name files and fasta files, aborting command."); m->mothurOutEndLine();
245 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
246 m->setProcessors(temp);
247 convert(temp, processors);
249 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
250 convert(temp, ksize);
252 temp = validParameter.validFile(parameters, "svg", false); if (temp == "not found") { temp = "F"; }
253 svg = m->isTrue(temp);
254 if (nameFileNames.size() != 0) { svg = true; }
256 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "10"; }
257 convert(temp, increment);
260 catch(exception& e) {
261 m->errorOut(e, "ChimeraCheckCommand", "ChimeraCheckCommand");
265 //***************************************************************************************************************
267 int ChimeraCheckCommand::execute(){
270 if (abort == true) { if (calledHelp) { return 0; } return 2; }
272 for (int i = 0; i < fastaFileNames.size(); i++) {
274 m->mothurOut("Checking sequences from " + fastaFileNames[i] + " ..." ); m->mothurOutEndLine();
276 int start = time(NULL);
278 string thisNameFile = "";
279 if (nameFileNames.size() != 0) { thisNameFile = nameFileNames[i]; }
281 chimera = new ChimeraCheckRDP(fastaFileNames[i], templatefile, thisNameFile, svg, increment, ksize, outputDir);
283 if (m->control_pressed) { delete chimera; return 0; }
285 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[i]); }//if user entered a file with a path then preserve it
286 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i])) + "chimeracheck.chimeras";
287 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
291 int pid, numSeqsPerProcessor;
293 vector<unsigned long int> MPIPos;
296 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
297 MPI_Comm_size(MPI_COMM_WORLD, &processors);
302 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
303 int inMode=MPI_MODE_RDONLY;
305 char outFilename[1024];
306 strcpy(outFilename, outputFileName.c_str());
308 char inFileName[1024];
309 strcpy(inFileName, fastaFileNames[i].c_str());
311 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
312 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
314 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; }
316 if (pid == 0) { //you are the root process
317 MPIPos = m->setFilePosFasta(fastaFileNames[i], numSeqs); //fills MPIPos, returns numSeqs
319 //send file positions to all processes
320 for(int j = 1; j < processors; j++) {
321 MPI_Send(&numSeqs, 1, MPI_INT, j, tag, MPI_COMM_WORLD);
322 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, j, tag, MPI_COMM_WORLD);
325 //figure out how many sequences you have to align
326 numSeqsPerProcessor = numSeqs / processors;
327 int startIndex = pid * numSeqsPerProcessor;
328 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
332 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
334 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; }
337 for(int j = 1; j < processors; j++) {
339 MPI_Recv(buf, 5, MPI_CHAR, j, tag, MPI_COMM_WORLD, &status);
341 }else{ //you are a child process
342 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
343 MPIPos.resize(numSeqs+1);
344 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
346 //figure out how many sequences you have to align
347 numSeqsPerProcessor = numSeqs / processors;
348 int startIndex = pid * numSeqsPerProcessor;
349 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
352 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
354 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; }
356 //tell parent you are done.
359 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
363 MPI_File_close(&inMPI);
364 MPI_File_close(&outMPI);
365 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
368 vector<unsigned long int> positions = m->divideFile(fastaFileNames[i], processors);
370 for (int s = 0; s < (positions.size()-1); s++) {
371 lines.push_back(new linePair(positions[s], positions[(s+1)]));
375 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
377 numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
379 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; }
382 processIDS.resize(0);
384 numSeqs = createProcesses(outputFileName, fastaFileNames[i]);
386 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
388 //append output files
389 for(int j=1;j<processors;j++){
390 m->appendFiles((outputFileName + toString(processIDS[j]) + ".temp"), outputFileName);
391 remove((outputFileName + toString(processIDS[j]) + ".temp").c_str());
394 if (m->control_pressed) {
395 for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear();
396 for (int j = 0; j < lines.size(); j++) { delete lines[j]; } lines.clear();
403 numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
405 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; }
409 for (int j = 0; j < lines.size(); j++) { delete lines[j]; } lines.clear();
411 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();
412 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
416 m->mothurOutEndLine();
417 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
418 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
419 m->mothurOutEndLine();
424 catch(exception& e) {
425 m->errorOut(e, "ChimeraCheckCommand", "execute");
429 //**********************************************************************************************************************
431 int ChimeraCheckCommand::driver(linePair* filePos, string outputFName, string filename){
434 m->openOutputFile(outputFName, out);
439 m->openInputFile(filename, inFASTA);
441 inFASTA.seekg(filePos->start);
448 if (m->control_pressed) { return 1; }
450 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
452 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
454 chimera->getChimeras(candidateSeq);
456 if (m->control_pressed) { delete candidateSeq; return 1; }
459 chimera->print(out, out2);
463 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
464 unsigned long int pos = inFASTA.tellg();
465 if ((pos == -1) || (pos >= filePos->end)) { break; }
467 if (inFASTA.eof()) { break; }
471 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
474 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
481 catch(exception& e) {
482 m->errorOut(e, "ChimeraCheckCommand", "driver");
486 //**********************************************************************************************************************
488 int ChimeraCheckCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, vector<unsigned long int>& MPIPos){
493 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
495 for(int i=0;i<num;i++){
497 if (m->control_pressed) { return 0; }
500 int length = MPIPos[start+i+1] - MPIPos[start+i];
502 char* buf4 = new char[length];
503 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
505 string tempBuf = buf4;
506 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
507 istringstream iss (tempBuf,istringstream::in);
510 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
512 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
514 chimera->getChimeras(candidateSeq);
517 chimera->print(outMPI, outAccMPI);
522 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
525 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
529 catch(exception& e) {
530 m->errorOut(e, "ChimeraCheckCommand", "driverMPI");
536 /**************************************************************************************************/
538 int ChimeraCheckCommand::createProcesses(string outputFileName, string filename) {
540 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
544 //loop through and create all the processes you want
545 while (process != processors) {
549 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
552 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename);
554 //pass numSeqs to parent
556 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
557 m->openOutputFile(tempFile, out);
563 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
564 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
569 //force parent to wait until all the processes are done
570 for (int i=0;i<processors;i++) {
571 int temp = processIDS[i];
575 for (int i = 0; i < processIDS.size(); i++) {
577 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
578 m->openInputFile(tempFile, in);
579 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
580 in.close(); remove(tempFile.c_str());
586 catch(exception& e) {
587 m->errorOut(e, "ChimeraCheckCommand", "createProcesses");
591 /**************************************************************************************************/