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::getValidParameters(){
15 string AlignArray[] = {"fasta","processors","increment","template","ksize","svg", "name","outputdir","inputdir" };
16 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
20 m->errorOut(e, "ChimeraCheckCommand", "getValidParameters");
24 //**********************************************************************************************************************
25 vector<string> ChimeraCheckCommand::getRequiredParameters(){
27 string AlignArray[] = {"template","fasta"};
28 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
32 m->errorOut(e, "ChimeraCheckCommand", "getRequiredParameters");
36 //**********************************************************************************************************************
37 vector<string> ChimeraCheckCommand::getRequiredFiles(){
39 vector<string> myArray;
43 m->errorOut(e, "ChimeraCheckCommand", "getRequiredFiles");
47 //**********************************************************************************************************************
48 ChimeraCheckCommand::ChimeraCheckCommand(){
50 abort = true; calledHelp = true;
51 vector<string> tempOutNames;
52 outputTypes["chimera"] = tempOutNames;
55 m->errorOut(e, "ChimeraCheckCommand", "ChimeraCheckCommand");
59 //***************************************************************************************************************
60 ChimeraCheckCommand::ChimeraCheckCommand(string option) {
62 abort = false; calledHelp = false;
64 //allow user to run help
65 if(option == "help") { help(); abort = true; calledHelp = true; }
68 //valid paramters for this command
69 string Array[] = {"fasta","processors","increment","template","ksize","svg", "name","outputdir","inputdir" };
70 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
72 OptionParser parser(option);
73 map<string,string> parameters = parser.getParameters();
75 ValidParameters validParameter("chimera.check");
76 map<string,string>::iterator it;
78 //check to make sure all parameters are valid for command
79 for (it = parameters.begin(); it != parameters.end(); it++) {
80 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
83 vector<string> tempOutNames;
84 outputTypes["chimera"] = tempOutNames;
86 //if the user changes the input directory command factory will send this info to us in the output parameter
87 string inputDir = validParameter.validFile(parameters, "inputdir", false);
88 if (inputDir == "not found"){ inputDir = ""; }
90 it = parameters.find("template");
91 //user has given a template file
92 if(it != parameters.end()){
93 string path = m->hasPath(it->second);
94 //if the user has not given a path then, add inputdir. else leave path alone.
95 if (path == "") { parameters["template"] = inputDir + it->second; }
99 //check for required parameters
100 fastafile = validParameter.validFile(parameters, "fasta", false);
101 if (fastafile == "not found") { fastafile = ""; m->mothurOut("fasta is a required parameter for the chimera.check command."); m->mothurOutEndLine(); abort = true; }
103 m->splitAtDash(fastafile, fastaFileNames);
105 //go through files and make sure they are good, if not, then disregard them
106 for (int i = 0; i < fastaFileNames.size(); i++) {
107 if (inputDir != "") {
108 string path = m->hasPath(fastaFileNames[i]);
109 //if the user has not given a path then, add inputdir. else leave path alone.
110 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
116 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
118 //if you can't open it, try default location
119 if (ableToOpen == 1) {
120 if (m->getDefaultPath() != "") { //default path is set
121 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
122 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
124 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
126 fastaFileNames[i] = tryPath;
130 //if you can't open it, try default location
131 if (ableToOpen == 1) {
132 if (m->getOutputDir() != "") { //default path is set
133 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
134 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
136 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
138 fastaFileNames[i] = tryPath;
144 if (ableToOpen == 1) {
145 m->mothurOut("Unable to open " + fastaFileNames[i] +". It will be disregarded."); m->mothurOutEndLine();
146 //erase from file list
147 fastaFileNames.erase(fastaFileNames.begin()+i);
152 //make sure there is at least one valid file left
153 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
156 //if the user changes the output directory command factory will send this info to us in the output parameter
157 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
159 templatefile = validParameter.validFile(parameters, "template", true);
160 if (templatefile == "not open") { abort = true; }
161 else if (templatefile == "not found") { templatefile = ""; m->mothurOut("template is a required parameter for the chimera.check command."); m->mothurOutEndLine(); abort = true; }
163 namefile = validParameter.validFile(parameters, "name", false);
164 if (namefile == "not found") { namefile = ""; }
166 m->splitAtDash(namefile, nameFileNames);
168 //go through files and make sure they are good, if not, then disregard them
169 for (int i = 0; i < nameFileNames.size(); i++) {
170 if (inputDir != "") {
171 string path = m->hasPath(nameFileNames[i]);
172 //if the user has not given a path then, add inputdir. else leave path alone.
173 if (path == "") { nameFileNames[i] = inputDir + nameFileNames[i]; }
179 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
181 //if you can't open it, try default location
182 if (ableToOpen == 1) {
183 if (m->getDefaultPath() != "") { //default path is set
184 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
185 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
187 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
189 nameFileNames[i] = tryPath;
193 //if you can't open it, try default location
194 if (ableToOpen == 1) {
195 if (m->getOutputDir() != "") { //default path is set
196 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
197 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
199 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
201 nameFileNames[i] = tryPath;
207 if (ableToOpen == 1) {
208 m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
209 //erase from file list
210 nameFileNames.erase(nameFileNames.begin()+i);
216 //make sure there is at least one valid file left
217 if (nameFileNames.size() != 0) {
218 if (nameFileNames.size() != fastaFileNames.size()) {
219 m->mothurOut("Different number of valid name files and fasta files, aborting command."); m->mothurOutEndLine();
225 string temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found") { temp = "1"; }
226 convert(temp, processors);
228 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found") { temp = "7"; }
229 convert(temp, ksize);
231 temp = validParameter.validFile(parameters, "svg", false); if (temp == "not found") { temp = "F"; }
232 svg = m->isTrue(temp);
233 if (nameFileNames.size() != 0) { svg = true; }
235 temp = validParameter.validFile(parameters, "increment", false); if (temp == "not found") { temp = "10"; }
236 convert(temp, increment);
239 catch(exception& e) {
240 m->errorOut(e, "ChimeraCheckCommand", "ChimeraCheckCommand");
244 //**********************************************************************************************************************
246 void ChimeraCheckCommand::help(){
249 m->mothurOut("The chimera.check command reads a fastafile and templatefile and outputs potentially chimeric sequences.\n");
250 m->mothurOut("This command was created using the algorythms described in CHIMERA_CHECK version 2.7 written by Niels Larsen. \n");
251 m->mothurOut("The chimera.check command parameters are fasta, template, processors, ksize, increment, svg and name.\n");
252 m->mothurOut("The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required. \n");
253 m->mothurOut("You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n");
254 m->mothurOut("The template parameter allows you to enter a template file containing known non-chimeric sequences, and is required. \n");
255 m->mothurOut("The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n");
257 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
259 m->mothurOut("The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default is 10.\n");
260 m->mothurOut("The ksize parameter allows you to input kmersize, default is 7. \n");
261 m->mothurOut("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");
262 m->mothurOut("The name parameter allows you to enter a file containing names of sequences you would like .svg files for.\n");
263 m->mothurOut("You may enter multiple name files by separating their names with dashes. ie. fasta=abrecovery.svg.names-amzon.svg.names \n");
264 m->mothurOut("The chimera.check command should be in the following format: \n");
265 m->mothurOut("chimera.check(fasta=yourFastaFile, template=yourTemplateFile, processors=yourProcessors, ksize=yourKmerSize) \n");
266 m->mothurOut("Example: chimera.check(fasta=AD.fasta, template=core_set_aligned,imputed.fasta, processors=4, ksize=8) \n");
267 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
269 catch(exception& e) {
270 m->errorOut(e, "ChimeraCheckCommand", "help");
275 //***************************************************************************************************************
277 ChimeraCheckCommand::~ChimeraCheckCommand(){ /* do nothing */ }
279 //***************************************************************************************************************
281 int ChimeraCheckCommand::execute(){
284 if (abort == true) { if (calledHelp) { return 0; } return 2; }
286 for (int i = 0; i < fastaFileNames.size(); i++) {
288 m->mothurOut("Checking sequences from " + fastaFileNames[i] + " ..." ); m->mothurOutEndLine();
290 int start = time(NULL);
292 string thisNameFile = "";
293 if (nameFileNames.size() != 0) { thisNameFile = nameFileNames[i]; }
295 chimera = new ChimeraCheckRDP(fastaFileNames[i], templatefile, thisNameFile, svg, increment, ksize, outputDir);
297 if (m->control_pressed) { delete chimera; return 0; }
299 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[i]); }//if user entered a file with a path then preserve it
300 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[i])) + "chimeracheck.chimeras";
301 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
305 int pid, numSeqsPerProcessor;
307 vector<unsigned long int> MPIPos;
310 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
311 MPI_Comm_size(MPI_COMM_WORLD, &processors);
316 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
317 int inMode=MPI_MODE_RDONLY;
319 char outFilename[1024];
320 strcpy(outFilename, outputFileName.c_str());
322 char inFileName[1024];
323 strcpy(inFileName, fastaFileNames[i].c_str());
325 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
326 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
328 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; }
330 if (pid == 0) { //you are the root process
331 MPIPos = m->setFilePosFasta(fastaFileNames[i], numSeqs); //fills MPIPos, returns numSeqs
333 //send file positions to all processes
334 for(int j = 1; j < processors; j++) {
335 MPI_Send(&numSeqs, 1, MPI_INT, j, tag, MPI_COMM_WORLD);
336 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, j, tag, MPI_COMM_WORLD);
339 //figure out how many sequences you have to align
340 numSeqsPerProcessor = numSeqs / processors;
341 int startIndex = pid * numSeqsPerProcessor;
342 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
346 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
348 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; }
351 for(int j = 1; j < processors; j++) {
353 MPI_Recv(buf, 5, MPI_CHAR, j, tag, MPI_COMM_WORLD, &status);
355 }else{ //you are a child process
356 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
357 MPIPos.resize(numSeqs+1);
358 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
360 //figure out how many sequences you have to align
361 numSeqsPerProcessor = numSeqs / processors;
362 int startIndex = pid * numSeqsPerProcessor;
363 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
366 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
368 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; }
370 //tell parent you are done.
373 MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
377 MPI_File_close(&inMPI);
378 MPI_File_close(&outMPI);
379 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
382 vector<unsigned long int> positions = m->divideFile(fastaFileNames[i], processors);
384 for (int s = 0; s < (positions.size()-1); s++) {
385 lines.push_back(new linePair(positions[s], positions[(s+1)]));
389 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
391 numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
393 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; }
396 processIDS.resize(0);
398 numSeqs = createProcesses(outputFileName, fastaFileNames[i]);
400 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
402 //append output files
403 for(int j=1;j<processors;j++){
404 m->appendFiles((outputFileName + toString(processIDS[j]) + ".temp"), outputFileName);
405 remove((outputFileName + toString(processIDS[j]) + ".temp").c_str());
408 if (m->control_pressed) {
409 for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear();
410 for (int j = 0; j < lines.size(); j++) { delete lines[j]; } lines.clear();
417 numSeqs = driver(lines[0], outputFileName, fastaFileNames[i]);
419 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; }
423 for (int j = 0; j < lines.size(); j++) { delete lines[j]; } lines.clear();
425 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();
426 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine();
430 m->mothurOutEndLine();
431 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
432 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
433 m->mothurOutEndLine();
438 catch(exception& e) {
439 m->errorOut(e, "ChimeraCheckCommand", "execute");
443 //**********************************************************************************************************************
445 int ChimeraCheckCommand::driver(linePair* filePos, string outputFName, string filename){
448 m->openOutputFile(outputFName, out);
453 m->openInputFile(filename, inFASTA);
455 inFASTA.seekg(filePos->start);
462 if (m->control_pressed) { return 1; }
464 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
466 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
468 chimera->getChimeras(candidateSeq);
470 if (m->control_pressed) { delete candidateSeq; return 1; }
473 chimera->print(out, out2);
477 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
478 unsigned long int pos = inFASTA.tellg();
479 if ((pos == -1) || (pos >= filePos->end)) { break; }
481 if (inFASTA.eof()) { break; }
485 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
488 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
495 catch(exception& e) {
496 m->errorOut(e, "ChimeraCheckCommand", "driver");
500 //**********************************************************************************************************************
502 int ChimeraCheckCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, vector<unsigned long int>& MPIPos){
507 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
509 for(int i=0;i<num;i++){
511 if (m->control_pressed) { return 0; }
514 int length = MPIPos[start+i+1] - MPIPos[start+i];
516 char* buf4 = new char[length];
517 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
519 string tempBuf = buf4;
520 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
521 istringstream iss (tempBuf,istringstream::in);
524 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
526 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
528 chimera->getChimeras(candidateSeq);
531 chimera->print(outMPI, outAccMPI);
536 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
539 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
543 catch(exception& e) {
544 m->errorOut(e, "ChimeraCheckCommand", "driverMPI");
550 /**************************************************************************************************/
552 int ChimeraCheckCommand::createProcesses(string outputFileName, string filename) {
554 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
558 //loop through and create all the processes you want
559 while (process != processors) {
563 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
566 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename);
568 //pass numSeqs to parent
570 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
571 m->openOutputFile(tempFile, out);
577 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
578 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
583 //force parent to wait until all the processes are done
584 for (int i=0;i<processors;i++) {
585 int temp = processIDS[i];
589 for (int i = 0; i < processIDS.size(); i++) {
591 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
592 m->openInputFile(tempFile, in);
593 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
594 in.close(); remove(tempFile.c_str());
600 catch(exception& e) {
601 m->errorOut(e, "ChimeraCheckCommand", "createProcesses");
605 /**************************************************************************************************/