2 * chimeraccodecommand.cpp
5 * Created by westcott on 3/30/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "chimeraccodecommand.h"
12 //**********************************************************************************************************************
13 vector<string> ChimeraCcodeCommand::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 pfilter("filter", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(pfilter);
18 CommandParameter pwindow("window", "Number", "", "0", "", "", "",false,false); parameters.push_back(pwindow);
19 CommandParameter pnumwanted("numwanted", "Number", "", "20", "", "", "",false,false); parameters.push_back(pnumwanted);
20 CommandParameter pmask("mask", "String", "", "", "", "", "",false,false); parameters.push_back(pmask);
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, "ChimeraCcodeCommand", "setParameters");
34 //**********************************************************************************************************************
35 string ChimeraCcodeCommand::getHelpString(){
37 string helpString = "";
38 helpString += "The chimera.ccode command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
39 helpString += "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";
40 helpString += "The chimera.ccode command parameters are fasta, reference, filter, mask, processors, window and numwanted.\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 filter parameter allows you to specify if you would like to apply a vertical and 50% soft filter. \n";
45 helpString += "The processors parameter allows you to specify how many processors you would like to use. The default is 1. \n";
47 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
49 helpString += "The mask parameter allows you to specify a file containing one sequence you wish to use as a mask for the your sequences. \n";
50 helpString += "The window parameter allows you to specify the window size for searching for chimeras. \n";
51 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with.\n";
52 helpString += "The chimera.ccode command should be in the following format: \n";
53 helpString += "chimera.ccode(fasta=yourFastaFile, reference=yourTemplate) \n";
54 helpString += "Example: chimera.ccode(fasta=AD.align, reference=core_set_aligned.imputed.fasta) \n";
55 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";
59 m->errorOut(e, "ChimeraCcodeCommand", "getHelpString");
63 //**********************************************************************************************************************
64 ChimeraCcodeCommand::ChimeraCcodeCommand(){
66 abort = true; calledHelp = true;
68 vector<string> tempOutNames;
69 outputTypes["chimera"] = tempOutNames;
70 outputTypes["mapinfo"] = tempOutNames;
71 outputTypes["accnos"] = tempOutNames;
74 m->errorOut(e, "ChimeraCcodeCommand", "ChimeraCcodeCommand");
78 //***************************************************************************************************************
79 ChimeraCcodeCommand::ChimeraCcodeCommand(string option) {
81 abort = false; calledHelp = false;
83 //allow user to run help
84 if(option == "help") { help(); abort = true; calledHelp = true; }
87 vector<string> myArray = setParameters();
89 OptionParser parser(option);
90 map<string,string> parameters = parser.getParameters();
92 ValidParameters validParameter("chimera.ccode");
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;
102 outputTypes["mapinfo"] = tempOutNames;
103 outputTypes["accnos"] = tempOutNames;
105 //if the user changes the input directory command factory will send this info to us in the output parameter
106 string inputDir = validParameter.validFile(parameters, "inputdir", false);
107 if (inputDir == "not found"){ inputDir = ""; }
110 it = parameters.find("reference");
111 //user has given a template file
112 if(it != parameters.end()){
113 path = m->hasPath(it->second);
114 //if the user has not given a path then, add inputdir. else leave path alone.
115 if (path == "") { parameters["reference"] = inputDir + it->second; }
119 //check for required parameters
120 fastafile = validParameter.validFile(parameters, "fasta", false);
121 if (fastafile == "not found") { //if there is a current fasta file, use it
122 string filename = m->getFastaFile();
123 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
124 else { m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
126 m->splitAtDash(fastafile, fastaFileNames);
128 //go through files and make sure they are good, if not, then disregard them
129 for (int i = 0; i < fastaFileNames.size(); i++) {
130 if (inputDir != "") {
131 string path = m->hasPath(fastaFileNames[i]);
132 //if the user has not given a path then, add inputdir. else leave path alone.
133 if (path == "") { fastaFileNames[i] = inputDir + fastaFileNames[i]; }
139 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
141 //if you can't open it, try default location
142 if (ableToOpen == 1) {
143 if (m->getDefaultPath() != "") { //default path is set
144 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
145 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
147 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
149 fastaFileNames[i] = tryPath;
153 //if you can't open it, try default location
154 if (ableToOpen == 1) {
155 if (m->getOutputDir() != "") { //default path is set
156 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
157 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
159 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
161 fastaFileNames[i] = tryPath;
167 if (ableToOpen == 1) {
168 m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
169 //erase from file list
170 fastaFileNames.erase(fastaFileNames.begin()+i);
175 //make sure there is at least one valid file left
176 if (fastaFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
179 //if the user changes the output directory command factory will send this info to us in the output parameter
180 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
182 templatefile = validParameter.validFile(parameters, "reference", true);
183 if (templatefile == "not open") { abort = true; }
184 else if (templatefile == "not found") { templatefile = ""; m->mothurOut("reference is a required parameter for the chimera.ccode command."); m->mothurOutEndLine(); abort = true; }
186 maskfile = validParameter.validFile(parameters, "mask", false);
187 if (maskfile == "not found") { maskfile = ""; }
188 else if (maskfile != "default") {
189 if (inputDir != "") {
190 string path = m->hasPath(maskfile);
191 //if the user has not given a path then, add inputdir. else leave path alone.
192 if (path == "") { maskfile = inputDir + maskfile; }
196 int ableToOpen = m->openInputFile(maskfile, in);
197 if (ableToOpen == 1) { abort = true; }
202 temp = validParameter.validFile(parameters, "filter", false); if (temp == "not found") { temp = "F"; }
203 filter = m->isTrue(temp);
205 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = m->getProcessors(); }
206 m->setProcessors(temp);
207 convert(temp, processors);
209 temp = validParameter.validFile(parameters, "window", false); if (temp == "not found") { temp = "0"; }
210 convert(temp, window);
212 temp = validParameter.validFile(parameters, "numwanted", false); if (temp == "not found") { temp = "20"; }
213 convert(temp, numwanted);
217 catch(exception& e) {
218 m->errorOut(e, "ChimeraCcodeCommand", "ChimeraCcodeCommand");
222 //***************************************************************************************************************
223 int ChimeraCcodeCommand::execute(){
226 if (abort == true) { if (calledHelp) { return 0; } return 2; }
228 for (int s = 0; s < fastaFileNames.size(); s++) {
230 m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
232 int start = time(NULL);
235 if (maskfile == "default") { m->mothurOut("I am using the default 236627 EU009184.1 Shigella dysenteriae str. FBD013."); m->mothurOutEndLine(); }
237 chimera = new Ccode(fastaFileNames[s], templatefile, filter, maskfile, window, numwanted, outputDir);
239 //is your template aligned?
240 if (chimera->getUnaligned()) { m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); delete chimera; return 0; }
241 templateSeqsLength = chimera->getLength();
243 if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]); }//if user entered a file with a path then preserve it
244 string outputFileName, accnosFileName;
245 if (maskfile != "") {
246 outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + ".ccode.chimeras";
247 accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + ".ccode.accnos";
249 outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "ccode.chimeras";
250 accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "ccode.accnos";
253 string mapInfo = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "mapinfo";
255 if (m->control_pressed) { delete chimera; for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear(); return 0; }
259 int pid, numSeqsPerProcessor;
261 vector<unsigned long int> MPIPos;
264 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
265 MPI_Comm_size(MPI_COMM_WORLD, &processors);
269 MPI_File outMPIAccnos;
271 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
272 int inMode=MPI_MODE_RDONLY;
274 char outFilename[1024];
275 strcpy(outFilename, outputFileName.c_str());
277 char outAccnosFilename[1024];
278 strcpy(outAccnosFilename, accnosFileName.c_str());
280 char inFileName[1024];
281 strcpy(inFileName, fastaFileNames[s].c_str());
283 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
284 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
285 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
287 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; }
289 if (pid == 0) { //you are the root process
290 string outTemp = "For full window mapping info refer to " + mapInfo + "\n";
293 int length = outTemp.length();
294 char* buf2 = new char[length];
295 memcpy(buf2, outTemp.c_str(), length);
297 MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
300 MPIPos = m->setFilePosFasta(fastaFileNames[s], numSeqs); //fills MPIPos, returns numSeqs
302 //send file positions to all processes
303 for(int i = 1; i < processors; i++) {
304 MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
305 MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
308 //figure out how many sequences you have to align
309 numSeqsPerProcessor = numSeqs / processors;
310 int startIndex = pid * numSeqsPerProcessor;
311 if(pid == (processors - 1)){ numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor; }
315 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, MPIPos);
317 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; }
319 }else{ //you are a child process
320 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
321 MPIPos.resize(numSeqs+1);
322 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
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); for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear(); delete chimera; return 0; }
337 MPI_File_close(&inMPI);
338 MPI_File_close(&outMPI);
339 MPI_File_close(&outMPIAccnos);
341 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
345 string tempHeader = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + maskfile + "ccode.chimeras.tempHeader";
346 m->openOutputFile(tempHeader, outHeader);
348 outHeader << "For full window mapping info refer to " << mapInfo << endl << endl;
352 vector<unsigned long int> positions = m->divideFile(fastaFileNames[s], processors);
354 for (int i = 0; i < (positions.size()-1); i++) {
355 lines.push_back(new linePair(positions[i], positions[(i+1)]));
359 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
362 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
364 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; }
367 processIDS.resize(0);
369 numSeqs = createProcesses(outputFileName, fastaFileNames[s], accnosFileName);
371 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
372 rename((accnosFileName + toString(processIDS[0]) + ".temp").c_str(), accnosFileName.c_str());
374 //append output files
375 for(int i=1;i<processors;i++){
376 m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
377 remove((outputFileName + toString(processIDS[i]) + ".temp").c_str());
380 //append output files
381 for(int i=1;i<processors;i++){
382 m->appendFiles((accnosFileName + toString(processIDS[i]) + ".temp"), accnosFileName);
383 remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());
386 if (m->control_pressed) {
387 remove(outputFileName.c_str());
388 remove(accnosFileName.c_str());
389 for (int j = 0; j < outputNames.size(); j++) { remove(outputNames[j].c_str()); } outputTypes.clear();
390 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
398 numSeqs = driver(lines[0], outputFileName, fastaFileNames[s], accnosFileName);
400 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; }
404 m->appendFiles(outputFileName, tempHeader);
406 remove(outputFileName.c_str());
407 rename(tempHeader.c_str(), outputFileName.c_str());
412 outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
413 outputNames.push_back(mapInfo); outputTypes["mapinfo"].push_back(mapInfo);
414 outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
416 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
418 m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences."); m->mothurOutEndLine();
422 //set accnos file as new current accnosfile
424 itTypes = outputTypes.find("accnos");
425 if (itTypes != outputTypes.end()) {
426 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
429 m->mothurOutEndLine();
430 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
431 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
432 m->mothurOutEndLine();
437 catch(exception& e) {
438 m->errorOut(e, "ChimeraCcodeCommand", "execute");
442 //**********************************************************************************************************************
444 int ChimeraCcodeCommand::driver(linePair* filePos, string outputFName, string filename, string accnos){
447 m->openOutputFile(outputFName, out);
450 m->openOutputFile(accnos, out2);
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 if (candidateSeq->getAligned().length() != templateSeqsLength) {
469 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
472 chimera->getChimeras(candidateSeq);
474 if (m->control_pressed) { delete candidateSeq; return 1; }
477 chimera->print(out, out2);
483 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
484 unsigned long int pos = inFASTA.tellg();
485 if ((pos == -1) || (pos >= filePos->end)) { break; }
487 if (inFASTA.eof()) { break; }
491 if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
494 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine(); }
502 catch(exception& e) {
503 m->errorOut(e, "ChimeraCcodeCommand", "driver");
507 //**********************************************************************************************************************
509 int ChimeraCcodeCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, vector<unsigned long int>& MPIPos){
514 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
516 for(int i=0;i<num;i++){
518 if (m->control_pressed) { return 0; }
521 int length = MPIPos[start+i+1] - MPIPos[start+i];
523 char* buf4 = new char[length];
525 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
527 string tempBuf = buf4;
528 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
529 istringstream iss (tempBuf,istringstream::in);
532 Sequence* candidateSeq = new Sequence(iss); m->gobble(iss);
534 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
536 if (candidateSeq->getAligned().length() != templateSeqsLength) {
537 m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
540 chimera->getChimeras(candidateSeq);
542 if (m->control_pressed) { delete candidateSeq; return 1; }
545 chimera->print(outMPI, outAccMPI);
551 if((i+1) % 100 == 0){ cout << "Processing sequence: " << (i+1) << endl; m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n"); }
554 if(num % 100 != 0){ cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n"); }
559 catch(exception& e) {
560 m->errorOut(e, "ChimeraCcodeCommand", "driverMPI");
566 /**************************************************************************************************/
568 int ChimeraCcodeCommand::createProcesses(string outputFileName, string filename, string accnos) {
570 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
574 //loop through and create all the processes you want
575 while (process != processors) {
579 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
582 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp");
584 //pass numSeqs to parent
586 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
587 m->openOutputFile(tempFile, out);
593 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
594 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
599 //force parent to wait until all the processes are done
600 for (int i=0;i<processors;i++) {
601 int temp = processIDS[i];
605 for (int i = 0; i < processIDS.size(); i++) {
607 string tempFile = outputFileName + toString(processIDS[i]) + ".num.temp";
608 m->openInputFile(tempFile, in);
609 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
610 in.close(); remove(tempFile.c_str());
616 catch(exception& e) {
617 m->errorOut(e, "ChimeraCcodeCommand", "createProcesses");
621 //**********************************************************************************************************************