2 * chimeraccodecommand.cpp
5 * Created by westcott on 3/30/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "chimeraccodecommand.h"
13 //**********************************************************************************************************************
14 vector<string> ChimeraCcodeCommand::getValidParameters(){
16 string AlignArray[] = {"fasta", "filter", "processors", "window", "template", "mask", "numwanted", "outputdir","inputdir" };
17 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
21 m->errorOut(e, "ChimeraCcodeCommand", "getValidParameters");
25 //**********************************************************************************************************************
26 ChimeraCcodeCommand::ChimeraCcodeCommand(){
28 vector<string> tempOutNames;
29 outputTypes["chimera"] = tempOutNames;
30 outputTypes["mapinfo"] = tempOutNames;
31 outputTypes["accnos"] = tempOutNames;
34 m->errorOut(e, "ChimeraCcodeCommand", "ChimeraCcodeCommand");
38 //**********************************************************************************************************************
39 vector<string> ChimeraCcodeCommand::getRequiredParameters(){
41 string AlignArray[] = {"template","fasta"};
42 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
46 m->errorOut(e, "ChimeraCcodeCommand", "getRequiredParameters");
50 //**********************************************************************************************************************
51 vector<string> ChimeraCcodeCommand::getRequiredFiles(){
53 vector<string> myArray;
57 m->errorOut(e, "ChimeraCcodeCommand", "getRequiredFiles");
61 //***************************************************************************************************************
62 ChimeraCcodeCommand::ChimeraCcodeCommand(string option) {
66 //allow user to run help
67 if(option == "help") { help(); abort = true; }
70 //valid paramters for this command
71 string Array[] = {"fasta", "filter", "processors", "window", "template", "mask", "numwanted", "outputdir","inputdir" };
72 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
74 OptionParser parser(option);
75 map<string,string> parameters = parser.getParameters();
77 ValidParameters validParameter("chimera.ccode");
78 map<string,string>::iterator it;
80 //check to make sure all parameters are valid for command
81 for (it = parameters.begin(); it != parameters.end(); it++) {
82 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
85 vector<string> tempOutNames;
86 outputTypes["chimera"] = tempOutNames;
87 outputTypes["mapinfo"] = tempOutNames;
88 outputTypes["accnos"] = tempOutNames;
90 //if the user changes the input directory command factory will send this info to us in the output parameter
91 string inputDir = validParameter.validFile(parameters, "inputdir", false);
92 if (inputDir == "not found"){ inputDir = ""; }
95 it = parameters.find("template");
96 //user has given a template file
97 if(it != parameters.end()){
98 path = m->hasPath(it->second);
99 //if the user has not given a path then, add inputdir. else leave path alone.
100 if (path == "") { parameters["template"] = inputDir + it->second; }
104 //check for required parameters
105 fastafile = validParameter.validFile(parameters, "fasta", false);
106 if (fastafile == "not found") { fastafile = ""; m->mothurOut("fasta is a required parameter for the chimera.ccode command."); m->mothurOutEndLine(); abort = true; }
108 m->splitAtDash(fastafile, fastaFileNames);
110 //go through files and make sure they are good, if not, then disregard them
111 for (int i = 0; i < fastaFileNames.size(); i++) {
112 if (inputDir != "") {
113 string path = m->hasPath(fastaFileNames[i]);
114 //if the user has not given a path then, add inputdir. else leave path alone.
115 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
121 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
123 //if you can't open it, try default location
124 if (ableToOpen == 1) {
125 if (m->getDefaultPath() != "") { //default path is set
126 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
127 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
129 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
131 fastaFileNames[i] = tryPath;
135 //if you can't open it, try default location
136 if (ableToOpen == 1) {
137 if (m->getOutputDir() != "") { //default path is set
138 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
139 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
141 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
143 fastaFileNames[i] = tryPath;
149 if (ableToOpen == 1) {
150 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
151 //erase from file list
152 fastaFileNames.erase(fastaFileNames.begin()+i);
157 //make sure there is at least one valid file left
158 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
161 //if the user changes the output directory command factory will send this info to us in the output parameter
162 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
164 templatefile = validParameter.validFile(parameters, "template", true);
165 if (templatefile == "not open") { abort = true; }
166 else if (templatefile == "not found") { templatefile = ""; m->mothurOut("template is a required parameter for the chimera.ccode command."); m->mothurOutEndLine(); abort = true; }
168 maskfile = validParameter.validFile(parameters, "mask", false);
169 if (maskfile == "not found") { maskfile = ""; }
170 else if (maskfile != "default") {
171 if (inputDir != "") {
172 string path = m->hasPath(maskfile);
173 //if the user has not given a path then, add inputdir. else leave path alone.
174 if (path == "") { maskfile = inputDir + maskfile; }
178 int ableToOpen = m->openInputFile(maskfile, in);
179 if (ableToOpen == 1) { abort = true; }
184 temp = validParameter.validFile(parameters, "filter", false); if (temp == "not found") { temp = "F"; }
185 filter = m->isTrue(temp);
187 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found") { temp = "1"; }
188 convert(temp, processors);
190 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "0"; }
191 convert(temp, window);
193 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "20"; }
194 convert(temp, numwanted);
198 catch(exception& e) {
199 m->errorOut(e, "ChimeraCcodeCommand", "ChimeraCcodeCommand");
203 //**********************************************************************************************************************
205 void ChimeraCcodeCommand::help(){
208 m->mothurOut("The chimera.ccode command reads a fastafile and templatefile and outputs potentially chimeric sequences.\n");
209 m->mothurOut("This command was created using the algorythms described in the 'Evaluating putative chimeric sequences from PCR-amplified products' paper by Juan M. Gonzalez, Johannes Zimmerman and Cesareo Saiz-Jimenez.\n");
210 m->mothurOut("The chimera.ccode command parameters are fasta, template, filter, mask, processors, window and numwanted.\n");
211 m->mothurOut("The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required. \n");
212 m->mothurOut("You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n");
213 m->mothurOut("The template parameter allows you to enter a template file containing known non-chimeric sequences, and is required. \n");
214 m->mothurOut("The filter parameter allows you to specify if you would like to apply a vertical and 50% soft filter. \n");
215 m->mothurOut("The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n");
217 m->mothurOut("When using MPI, the processors parameter is set to the number of MPI processes running. \n");
219 m->mothurOut("The mask parameter allows you to specify a file containing one sequence you wish to use as a mask for the your sequences. \n");
220 m->mothurOut("The window parameter allows you to specify the window size for searching for chimeras. \n");
221 m->mothurOut("The numwanted parameter allows you to specify how many sequences you would each query sequence compared with.\n");
222 m->mothurOut("The chimera.ccode command should be in the following format: \n");
223 m->mothurOut("chimera.ccode(fasta=yourFastaFile, template=yourTemplate) \n");
224 m->mothurOut("Example: chimera.ccode(fasta=AD.align, template=core_set_aligned.imputed.fasta) \n");
225 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n\n");
227 catch(exception& e) {
228 m->errorOut(e, "ChimeraCcodeCommand", "help");
233 //***************************************************************************************************************
235 ChimeraCcodeCommand::~ChimeraCcodeCommand(){ /* do nothing */ }
237 //***************************************************************************************************************
239 int ChimeraCcodeCommand::execute(){
242 if (abort == true) { return 0; }
244 for (int s = 0; s < fastaFileNames.size(); s++) {
246 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
248 int start = time(NULL);
251 if (maskfile == "default") { m->mothurOut("I am using the default 236627 EU009184.1 Shigella dysenteriae str. FBD013."); m->mothurOutEndLine(); }
253 chimera = new Ccode(fastaFileNames[s], templatefile, filter, maskfile, window, numwanted, outputDir);
255 //is your template aligned?
256 if (chimera->getUnaligned()) { m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); delete chimera; return 0; }
257 templateSeqsLength = chimera->getLength();
259 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
260 string outputFileName, accnosFileName;
261 if (maskfile != "") {
262 outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + ".ccode.chimeras";
263 accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + ".ccode.accnos";
265 outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "ccode.chimeras";
266 accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "ccode.accnos";
269 string mapInfo = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "mapinfo";
271 if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear(); return 0; }
275 int pid, end, numSeqsPerProcessor;
277 vector<unsigned long int> MPIPos;
280 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
281 MPI_Comm_size(MPI_COMM_WORLD, &processors);
285 MPI_File outMPIAccnos;
287 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
288 int inMode=MPI_MODE_RDONLY;
290 char outFilename[1024];
291 strcpy(outFilename, outputFileName.c_str());
293 char outAccnosFilename[1024];
294 strcpy(outAccnosFilename, accnosFileName.c_str());
296 char inFileName[1024];
297 strcpy(inFileName, fastaFileNames[s].c_str());
299 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
300 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
301 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
303 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()); } outputTypes.clear(); delete chimera; return 0; }
305 if (pid == 0) { //you are the root process
306 string outTemp = "For full window mapping info refer to " + mapInfo + "\n\n";
309 int length = outTemp.length();
310 char* buf2 = new char[length];
311 memcpy(buf2, outTemp.c_str(), length);
313 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
316 MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
318 //send file positions to all processes
319 for(int i = 1; i < processors; i++) {
320 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
321 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
324 //figure out how many sequences you have to align
325 numSeqsPerProcessor = numSeqs / processors;
326 int startIndex = pid * numSeqsPerProcessor;
327 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
331 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
333 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPI); MPI_File_close(&outMPIAccnos); remove(outputFileName.c_str()); remove(accnosFileName.c_str()); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear(); delete chimera; return 0; }
335 }else{ //you are a child process
336 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
337 MPIPos.resize(numSeqs+1);
338 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
340 //figure out how many sequences you have to align
341 numSeqsPerProcessor = numSeqs / processors;
342 int startIndex = pid * numSeqsPerProcessor;
343 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
347 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
349 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()); } outputTypes.clear(); delete chimera; return 0; }
353 MPI_File_close(&inMPI);
354 MPI_File_close(&outMPI);
355 MPI_File_close(&outMPIAccnos);
357 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
361 string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + "ccode.chimeras.tempHeader";
362 m->openOutputFile(tempHeader, outHeader);
364 outHeader << "For full window mapping info refer to " << mapInfo << endl << endl;
368 vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
370 for (int i = 0; i < (positions.size()-1); i++) {
371 lines.push_back(new linePair(positions[i], positions[(i+1)]));
375 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
378 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
380 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]; } outputTypes.clear(); lines.clear(); delete chimera; return 0; }
383 processIDS.resize(0);
385 numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName);
387 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
388 rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
390 //append output files
391 for(int i=1;i<processors;i++){
392 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
393 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
396 //append output files
397 for(int i=1;i<processors;i++){
398 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
399 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
402 if (m->control_pressed) {
403 remove(outputFileName.c_str());
404 remove(accnosFileName.c_str());
405 for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear();
406 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
414 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
416 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]; } outputTypes.clear(); lines.clear(); delete chimera; return 0; }
420 m->appendFiles(outputFileName, tempHeader);
422 remove(outputFileName.c_str());
423 rename(tempHeader.c_str(), outputFileName.c_str());
428 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
429 outputNames.push_back(mapInfo); outputTypes["mapinfo"].push_back(mapInfo);
430 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
432 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
434 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
437 m->mothurOutEndLine();
438 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
439 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
440 m->mothurOutEndLine();
445 catch(exception& e) {
446 m->errorOut(e, "ChimeraCcodeCommand", "execute");
450 //**********************************************************************************************************************
452 int ChimeraCcodeCommand::driver(linePair* filePos, string outputFName, string filename, string accnos){
455 m->openOutputFile(outputFName, out);
458 m->openOutputFile(accnos, out2);
461 m->openInputFile(filename, inFASTA);
463 inFASTA.seekg(filePos->start);
470 if (m->control_pressed) { return 1; }
472 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
474 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
476 if (candidateSeq->getAligned().length() != templateSeqsLength) {
477 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
480 chimera->getChimeras(candidateSeq);
482 if (m->control_pressed) { delete candidateSeq; return 1; }
485 chimera->print(out, out2);
491 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
492 unsigned long int pos = inFASTA.tellg();
493 if ((pos == -1) || (pos >= filePos->end)) { break; }
495 if (inFASTA.eof()) { break; }
499 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
502 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
510 catch(exception& e) {
511 m->errorOut(e, "ChimeraCcodeCommand", "driver");
515 //**********************************************************************************************************************
517 int ChimeraCcodeCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, vector<unsigned long int>& MPIPos){
522 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
524 for(int i=0;i<num;i++){
526 if (m->control_pressed) { return 0; }
529 int length = MPIPos[start+i+1] - MPIPos[start+i];
531 char* buf4 = new char[length];
533 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
535 string tempBuf = buf4;
536 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
537 istringstream iss (tempBuf,istringstream::in);
540 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
542 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
544 if (candidateSeq->getAligned().length() != templateSeqsLength) {
545 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
548 chimera->getChimeras(candidateSeq);
550 if (m->control_pressed) { delete candidateSeq; return 1; }
553 bool isChimeric = 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"); }
567 catch(exception& e) {
568 m->errorOut(e, "ChimeraCcodeCommand", "driverMPI");
574 /**************************************************************************************************/
576 int ChimeraCcodeCommand::createProcesses(string outputFileName, string filename, string accnos) {
578 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
582 //loop through and create all the processes you want
583 while (process != processors) {
587 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
590 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp");
592 //pass numSeqs to parent
594 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
595 m->openOutputFile(tempFile, out);
600 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
603 //force parent to wait until all the processes are done
604 for (int i=0;i<processors;i++) {
605 int temp = processIDS[i];
609 for (int i = 0; i < processIDS.size(); i++) {
611 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
612 m->openInputFile(tempFile, in);
613 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
614 in.close(); remove(tempFile.c_str());
620 catch(exception& e) {
621 m->errorOut(e, "ChimeraCcodeCommand", "createProcesses");
625 //**********************************************************************************************************************