5 * Created by Sarah Westcott on 5/15/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
8 * This version of nast does everything I think that the greengenes nast server does and then some. I have added the
9 * feature of allowing users to define their database, kmer size for searching, alignment penalty values and alignment
10 * method. This latter feature is perhaps most significant. nastPlus enables a user to use either a Needleman-Wunsch
11 * (non-affine gap penalty) or Gotoh (affine gap penalty) pairwise alignment algorithm. This is significant because it
12 * allows for a global alignment and not the local alignment provided by bLAst. Furthermore, it has the potential to
13 * provide a better alignment because of the banding method employed by blast (I'm not sure about this).
17 #include "aligncommand.h"
18 #include "sequence.hpp"
20 #include "gotohoverlap.hpp"
21 #include "needlemanoverlap.hpp"
22 #include "blastalign.hpp"
23 #include "noalign.hpp"
26 #include "nastreport.hpp"
29 //**********************************************************************************************************************
31 AlignCommand::AlignCommand(string option) {
36 //allow user to run help
37 if(option == "help") { help(); abort = true; }
41 //valid paramters for this command
42 string AlignArray[] = {"template","candidate","search","ksize","align","match","mismatch","gapopen","gapextend", "processors","flip","threshold","outputdir","inputdir"};
43 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
45 OptionParser parser(option);
46 map<string, string> parameters = parser.getParameters();
48 ValidParameters validParameter("align.seqs");
49 map<string, string>::iterator it;
51 //check to make sure all parameters are valid for command
52 for (it = parameters.begin(); it != parameters.end(); it++) {
53 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
56 //if the user changes the output directory command factory will send this info to us in the output parameter
57 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
60 //if the user changes the input directory command factory will send this info to us in the output parameter
61 string inputDir = validParameter.validFile(parameters, "inputdir", false);
63 if (inputDir == "not found"){ inputDir = ""; }
67 it = parameters.find("template");
69 //user has given a template file
70 if(it != parameters.end()){
71 path = hasPath(it->second);
72 //if the user has not given a path then, add inputdir. else leave path alone.
73 if (path == "") { parameters["template"] = inputDir + it->second; }
77 //check for required parameters
78 templateFileName = validParameter.validFile(parameters, "template", true);
80 if (templateFileName == "not found") {
81 m->mothurOut("template is a required parameter for the align.seqs command.");
82 m->mothurOutEndLine();
84 }else if (templateFileName == "not open") { abort = true; }
86 candidateFileName = validParameter.validFile(parameters, "candidate", false);
87 if (candidateFileName == "not found") { m->mothurOut("candidate is a required parameter for the align.seqs command."); m->mothurOutEndLine(); abort = true; }
89 splitAtDash(candidateFileName, candidateFileNames);
91 //go through files and make sure they are good, if not, then disregard them
92 for (int i = 0; i < candidateFileNames.size(); i++) {
94 string path = hasPath(candidateFileNames[i]);
95 //if the user has not given a path then, add inputdir. else leave path alone.
96 if (path == "") { candidateFileNames[i] = inputDir + candidateFileNames[i]; }
102 ableToOpen = openInputFile(candidateFileNames[i], in, "noerror");
104 //if you can't open it, try default location
105 if (ableToOpen == 1) {
106 if (m->getDefaultPath() != "") { //default path is set
107 string tryPath = m->getDefaultPath() + getSimpleName(candidateFileNames[i]);
108 m->mothurOut("Unable to open " + candidateFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
109 ableToOpen = openInputFile(tryPath, in, "noerror");
110 candidateFileNames[i] = tryPath;
115 if (ableToOpen == 1) {
116 m->mothurOut("Unable to open " + candidateFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
117 //erase from file list
118 candidateFileNames.erase(candidateFileNames.begin()+i);
124 //make sure there is at least one valid file left
125 if (candidateFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
128 //check for optional parameter and set defaults
129 // ...at some point should added some additional type checking...
131 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found"){ temp = "8"; }
132 convert(temp, kmerSize);
134 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found"){ temp = "1.0"; }
135 convert(temp, match);
137 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found"){ temp = "-1.0"; }
138 convert(temp, misMatch);
140 temp = validParameter.validFile(parameters, "gapopen", false); if (temp == "not found"){ temp = "-2.0"; }
141 convert(temp, gapOpen);
143 temp = validParameter.validFile(parameters, "gapextend", false); if (temp == "not found"){ temp = "-1.0"; }
144 convert(temp, gapExtend);
146 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
147 convert(temp, processors);
149 temp = validParameter.validFile(parameters, "flip", false); if (temp == "not found"){ temp = "f"; }
152 temp = validParameter.validFile(parameters, "threshold", false); if (temp == "not found"){ temp = "0.50"; }
153 convert(temp, threshold);
155 search = validParameter.validFile(parameters, "search", false); if (search == "not found"){ search = "kmer"; }
157 align = validParameter.validFile(parameters, "align", false); if (align == "not found"){ align = "needleman"; }
161 catch(exception& e) {
162 m->errorOut(e, "AlignCommand", "AlignCommand");
167 //**********************************************************************************************************************
169 AlignCommand::~AlignCommand(){
171 if (abort == false) {
172 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
178 //**********************************************************************************************************************
180 void AlignCommand::help(){
182 m->mothurOut("The align.seqs command reads a file containing sequences and creates an alignment file and a report file.\n");
183 m->mothurOut("The align.seqs command parameters are template, candidate, search, ksize, align, match, mismatch, gapopen and gapextend.\n");
184 m->mothurOut("The template and candidate parameters are required. You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n");
185 m->mothurOut("The search parameter allows you to specify the method to find most similar template. Your options are: suffix, kmer and blast. The default is kmer.\n");
186 m->mothurOut("The align parameter allows you to specify the alignment method to use. Your options are: gotoh, needleman, blast and noalign. The default is needleman.\n");
187 m->mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate. The default is 8.\n");
188 m->mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
189 m->mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n");
190 m->mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n");
191 m->mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -1.0.\n");
192 m->mothurOut("The flip parameter is used to specify whether or not you want mothur to try the reverse complement if a sequence falls below the threshold. The default is false.\n");
193 m->mothurOut("The threshold is used to specify a cutoff at which an alignment is deemed 'bad' and the reverse complement may be tried. The default threshold is 0.50, meaning 50% of the bases are removed in the alignment.\n");
194 m->mothurOut("If the flip parameter is set to true the reverse complement of the sequence is aligned and the better alignment is reported.\n");
195 m->mothurOut("The default for the threshold parameter is 0.50, meaning at least 50% of the bases must remain or the sequence is reported as potentially reversed.\n");
196 m->mothurOut("The align.seqs command should be in the following format: \n");
197 m->mothurOut("align.seqs(template=yourTemplateFile, candidate=yourCandidateFile, align=yourAlignmentMethod, search=yourSearchmethod, ksize=yourKmerSize, match=yourMatchBonus, mismatch=yourMismatchpenalty, gapopen=yourGapopenPenalty, gapextend=yourGapExtendPenalty) \n");
198 m->mothurOut("Example align.seqs(candidate=candidate.fasta, template=core.filtered, align=kmer, search=gotoh, ksize=8, match=2.0, mismatch=3.0, gapopen=-2.0, gapextend=-1.0)\n");
199 m->mothurOut("Note: No spaces between parameter labels (i.e. candidate), '=' and parameters (i.e.yourFastaFile).\n\n");
201 catch(exception& e) {
202 m->errorOut(e, "AlignCommand", "help");
208 //**********************************************************************************************************************
210 int AlignCommand::execute(){
212 if (abort == true) { return 0; }
214 templateDB = new AlignmentDB(templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch);
215 int longestBase = templateDB->getLongestBase();
217 if(align == "gotoh") { alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase); }
218 else if(align == "needleman") { alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase); }
219 else if(align == "blast") { alignment = new BlastAlignment(gapOpen, gapExtend, match, misMatch); }
220 else if(align == "noalign") { alignment = new NoAlign(); }
222 m->mothurOut(align + " is not a valid alignment option. I will run the command using needleman.");
223 m->mothurOutEndLine();
224 alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);
226 vector<string> outputNames;
228 for (int s = 0; s < candidateFileNames.size(); s++) {
229 if (m->control_pressed) { return 0; }
231 m->mothurOut("Aligning sequences from " + candidateFileNames[s] + " ..." ); m->mothurOutEndLine();
233 if (outputDir == "") { outputDir += hasPath(candidateFileNames[s]); }
234 string alignFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "align";
235 string reportFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "align.report";
236 string accnosFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "flip.accnos";
237 bool hasAccnos = true;
239 int numFastaSeqs = 0;
240 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
241 int start = time(NULL);
244 int pid, end, numSeqsPerProcessor;
246 vector<unsigned long int> MPIPos;
247 MPIWroteAccnos = false;
250 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
251 MPI_Comm_size(MPI_COMM_WORLD, &processors);
254 MPI_File outMPIAlign;
255 MPI_File outMPIReport;
256 MPI_File outMPIAccnos;
258 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
259 int inMode=MPI_MODE_RDONLY;
261 char outAlignFilename[1024];
262 strcpy(outAlignFilename, alignFileName.c_str());
264 char outReportFilename[1024];
265 strcpy(outReportFilename, reportFileName.c_str());
267 char outAccnosFilename[1024];
268 strcpy(outAccnosFilename, accnosFileName.c_str());
270 char inFileName[1024];
271 strcpy(inFileName, candidateFileNames[s].c_str());
273 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
274 MPI_File_open(MPI_COMM_WORLD, outAlignFilename, outMode, MPI_INFO_NULL, &outMPIAlign);
275 MPI_File_open(MPI_COMM_WORLD, outReportFilename, outMode, MPI_INFO_NULL, &outMPIReport);
276 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
278 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPIAlign); MPI_File_close(&outMPIReport); MPI_File_close(&outMPIAccnos); return 0; }
280 if (pid == 0) { //you are the root process
282 MPIPos = setFilePosFasta(candidateFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs
284 //send file positions to all processes
285 for(int i = 1; i < processors; i++) {
286 MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
287 MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
290 //figure out how many sequences you have to align
291 numSeqsPerProcessor = numFastaSeqs / processors;
292 int startIndex = pid * numSeqsPerProcessor;
293 if(pid == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor; }
297 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);
299 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPIAlign); MPI_File_close(&outMPIReport); MPI_File_close(&outMPIAccnos); return 0; }
301 for (int i = 1; i < processors; i++) {
303 MPI_Recv(&tempResult, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
304 if (tempResult != 0) { MPIWroteAccnos = true; }
306 }else{ //you are a child process
307 MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
308 MPIPos.resize(numFastaSeqs+1);
309 MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
312 //figure out how many sequences you have to align
313 numSeqsPerProcessor = numFastaSeqs / processors;
314 int startIndex = pid * numSeqsPerProcessor;
315 if(pid == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor; }
319 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);
321 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPIAlign); MPI_File_close(&outMPIReport); MPI_File_close(&outMPIAccnos); return 0; }
323 MPI_Send(&MPIWroteAccnos, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
327 MPI_File_close(&inMPI);
328 MPI_File_close(&outMPIAlign);
329 MPI_File_close(&outMPIReport);
330 MPI_File_close(&outMPIAccnos);
332 //delete accnos file if blank
334 //delete accnos file if its blank else report to user
335 if (MPIWroteAccnos) {
336 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
338 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well.");
339 }else{ m->mothurOut(" If the reverse compliment proved to be better it was reported."); }
340 m->mothurOutEndLine();
343 //MPI_File_delete(outAccnosFilename, info);
345 remove(accnosFileName.c_str());
351 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
354 openInputFile(candidateFileNames[s], inFASTA);
355 getNumSeqs(inFASTA, numFastaSeqs);
358 lines.push_back(new linePair(0, numFastaSeqs));
360 driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
362 if (m->control_pressed) {
363 remove(accnosFileName.c_str());
364 remove(alignFileName.c_str());
365 remove(reportFileName.c_str());
369 //delete accnos file if its blank else report to user
370 if (isBlank(accnosFileName)) { remove(accnosFileName.c_str()); hasAccnos = false; }
372 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
374 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well.");
375 }else{ m->mothurOut(" If the reverse compliment proved to be better it was reported."); }
376 m->mothurOutEndLine();
380 vector<unsigned long int> positions;
381 processIDS.resize(0);
384 openInputFile(candidateFileNames[s], inFASTA);
387 while(!inFASTA.eof()){
388 input = getline(inFASTA);
389 if (input.length() != 0) {
390 if(input[0] == '>'){ unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
395 numFastaSeqs = positions.size();
397 int numSeqsPerProcessor = numFastaSeqs / processors;
399 for (int i = 0; i < processors; i++) {
400 unsigned long int startPos = positions[ i * numSeqsPerProcessor ];
401 if(i == processors - 1){
402 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
404 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
407 createProcesses(alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
409 rename((alignFileName + toString(processIDS[0]) + ".temp").c_str(), alignFileName.c_str());
410 rename((reportFileName + toString(processIDS[0]) + ".temp").c_str(), reportFileName.c_str());
412 //append alignment and report files
413 for(int i=1;i<processors;i++){
414 appendAlignFiles((alignFileName + toString(processIDS[i]) + ".temp"), alignFileName);
415 remove((alignFileName + toString(processIDS[i]) + ".temp").c_str());
417 appendReportFiles((reportFileName + toString(processIDS[i]) + ".temp"), reportFileName);
418 remove((reportFileName + toString(processIDS[i]) + ".temp").c_str());
421 vector<string> nonBlankAccnosFiles;
422 //delete blank accnos files generated with multiple processes
423 for(int i=0;i<processors;i++){
424 if (!(isBlank(accnosFileName + toString(processIDS[i]) + ".temp"))) {
425 nonBlankAccnosFiles.push_back(accnosFileName + toString(processIDS[i]) + ".temp");
426 }else { remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str()); }
429 //append accnos files
430 if (nonBlankAccnosFiles.size() != 0) {
431 rename(nonBlankAccnosFiles[0].c_str(), accnosFileName.c_str());
433 for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
434 appendAlignFiles(nonBlankAccnosFiles[h], accnosFileName);
435 remove(nonBlankAccnosFiles[h].c_str());
437 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
439 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well.");
440 }else{ m->mothurOut(" If the reverse compliment proved to be better it was reported."); }
441 m->mothurOutEndLine();
442 }else{ hasAccnos = false; }
444 if (m->control_pressed) {
445 remove(accnosFileName.c_str());
446 remove(alignFileName.c_str());
447 remove(reportFileName.c_str());
453 openInputFile(candidateFileNames[s], inFASTA);
454 getNumSeqs(inFASTA, numFastaSeqs);
457 lines.push_back(new linePair(0, numFastaSeqs));
459 driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
461 if (m->control_pressed) {
462 remove(accnosFileName.c_str());
463 remove(alignFileName.c_str());
464 remove(reportFileName.c_str());
468 //delete accnos file if its blank else report to user
469 if (isBlank(accnosFileName)) { remove(accnosFileName.c_str()); hasAccnos = false; }
471 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
473 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well.");
474 }else{ m->mothurOut(" If the reverse compliment proved to be better it was reported."); }
475 m->mothurOutEndLine();
484 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
486 if (pid == 0) { //only one process should output to screen
489 outputNames.push_back(alignFileName);
490 outputNames.push_back(reportFileName);
491 if (hasAccnos) { outputNames.push_back(accnosFileName); }
497 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to align " + toString(numFastaSeqs) + " sequences.");
498 m->mothurOutEndLine();
499 m->mothurOutEndLine();
503 m->mothurOutEndLine();
504 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
505 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
506 m->mothurOutEndLine();
510 catch(exception& e) {
511 m->errorOut(e, "AlignCommand", "execute");
516 //**********************************************************************************************************************
518 int AlignCommand::driver(linePair* line, string alignFName, string reportFName, string accnosFName, string filename){
520 ofstream alignmentFile;
521 openOutputFile(alignFName, alignmentFile);
524 openOutputFile(accnosFName, accnosFile);
526 NastReport report(reportFName);
529 openInputFile(filename, inFASTA);
531 inFASTA.seekg(line->start);
533 for(int i=0;i<line->numSeqs;i++){
535 if (m->control_pressed) { return 0; }
537 Sequence* candidateSeq = new Sequence(inFASTA); gobble(inFASTA);
539 int origNumBases = candidateSeq->getNumBases();
540 string originalUnaligned = candidateSeq->getUnaligned();
541 int numBasesNeeded = origNumBases * threshold;
543 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
544 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {
545 alignment->resize(candidateSeq->getUnaligned().length()+1);
548 Sequence temp = templateDB->findClosestSequence(candidateSeq);
549 Sequence* templateSeq = &temp;
551 float searchScore = templateDB->getSearchScore();
553 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);
557 bool needToDeleteCopy = false; //this is needed in case you have you enter the ifs below
558 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below
559 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place
560 //so this bool tells you if you need to delete it
562 //if there is a possibility that this sequence should be reversed
563 if (candidateSeq->getNumBases() < numBasesNeeded) {
565 string wasBetter = "";
566 //if the user wants you to try the reverse
568 //get reverse compliment
569 copy = new Sequence(candidateSeq->getName(), originalUnaligned);
570 copy->reverseComplement();
573 Sequence temp2 = templateDB->findClosestSequence(copy);
574 Sequence* templateSeq2 = &temp2;
576 searchScore = templateDB->getSearchScore();
578 nast2 = new Nast(alignment, copy, templateSeq2);
580 //check if any better
581 if (copy->getNumBases() > candidateSeq->getNumBases()) {
582 candidateSeq->setAligned(copy->getAligned()); //use reverse compliments alignment since its better
583 templateSeq = templateSeq2;
586 needToDeleteCopy = true;
587 wasBetter = "\treverse complement produced a better alignment, so mothur used the reverse complement.";
589 wasBetter = "\treverse complement did NOT produce a better alignment so it was not used, please check sequence.";
595 //create accnos file with names
596 accnosFile << candidateSeq->getName() << wasBetter << endl;
599 report.setCandidate(candidateSeq);
600 report.setTemplate(templateSeq);
601 report.setSearchParameters(search, searchScore);
602 report.setAlignmentParameters(align, alignment);
603 report.setNastParameters(*nast);
605 alignmentFile << '>' << candidateSeq->getName() << '\n' << candidateSeq->getAligned() << endl;
609 if (needToDeleteCopy) { delete copy; }
614 if((i+1) % 100 == 0){ m->mothurOut(toString(i+1)); m->mothurOutEndLine(); }
617 if((line->numSeqs) % 100 != 0){ m->mothurOut(toString(line->numSeqs)); m->mothurOutEndLine(); }
619 alignmentFile.close();
625 catch(exception& e) {
626 m->errorOut(e, "AlignCommand", "driver");
630 //**********************************************************************************************************************
632 int AlignCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& alignFile, MPI_File& reportFile, MPI_File& accnosFile, vector<unsigned long int>& MPIPos){
634 string outputString = "";
635 MPI_Status statusReport;
636 MPI_Status statusAlign;
637 MPI_Status statusAccnos;
640 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
645 outputString = report.getHeaders();
646 int length = outputString.length();
648 char* buf = new char[length];
649 memcpy(buf, outputString.c_str(), length);
651 MPI_File_write_shared(reportFile, buf, length, MPI_CHAR, &statusReport);
656 for(int i=0;i<num;i++){
658 if (m->control_pressed) { return 0; }
661 int length = MPIPos[start+i+1] - MPIPos[start+i];
663 char* buf4 = new char[length];
664 //memcpy(buf4, outputString.c_str(), length);
666 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
668 string tempBuf = buf4;
672 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
674 istringstream iss (tempBuf,istringstream::in);
676 Sequence* candidateSeq = new Sequence(iss);
678 int origNumBases = candidateSeq->getNumBases();
679 string originalUnaligned = candidateSeq->getUnaligned();
680 int numBasesNeeded = origNumBases * threshold;
682 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
683 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {
684 alignment->resize(candidateSeq->getUnaligned().length()+1);
687 Sequence temp = templateDB->findClosestSequence(candidateSeq);
688 Sequence* templateSeq = &temp;
690 float searchScore = templateDB->getSearchScore();
692 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);
696 bool needToDeleteCopy = false; //this is needed in case you have you enter the ifs below
697 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below
698 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place
699 //so this bool tells you if you need to delete it
701 //if there is a possibility that this sequence should be reversed
702 if (candidateSeq->getNumBases() < numBasesNeeded) {
704 string wasBetter = "";
705 //if the user wants you to try the reverse
707 //get reverse compliment
708 copy = new Sequence(candidateSeq->getName(), originalUnaligned);
709 copy->reverseComplement();
712 Sequence temp2 = templateDB->findClosestSequence(copy);
713 Sequence* templateSeq2 = &temp2;
715 searchScore = templateDB->getSearchScore();
717 nast2 = new Nast(alignment, copy, templateSeq2);
719 //check if any better
720 if (copy->getNumBases() > candidateSeq->getNumBases()) {
721 candidateSeq->setAligned(copy->getAligned()); //use reverse compliments alignment since its better
722 templateSeq = templateSeq2;
725 needToDeleteCopy = true;
727 wasBetter = "\treverse complement did NOT produce a better alignment, please check sequence.";
733 //create accnos file with names
734 outputString = candidateSeq->getName() + wasBetter + "\n";
736 //send results to parent
737 int length = outputString.length();
739 char* buf = new char[length];
740 memcpy(buf, outputString.c_str(), length);
742 MPI_File_write_shared(accnosFile, buf, length, MPI_CHAR, &statusAccnos);
744 MPIWroteAccnos = true;
747 report.setCandidate(candidateSeq);
748 report.setTemplate(templateSeq);
749 report.setSearchParameters(search, searchScore);
750 report.setAlignmentParameters(align, alignment);
751 report.setNastParameters(*nast);
753 outputString = ">" + candidateSeq->getName() + "\n" + candidateSeq->getAligned() + "\n";
755 //send results to parent
756 int length = outputString.length();
757 char* buf2 = new char[length];
758 memcpy(buf2, outputString.c_str(), length);
760 MPI_File_write_shared(alignFile, buf2, length, MPI_CHAR, &statusAlign);
764 outputString = report.getReport();
766 //send results to parent
767 length = outputString.length();
768 char* buf3 = new char[length];
769 memcpy(buf3, outputString.c_str(), length);
771 MPI_File_write_shared(reportFile, buf3, length, MPI_CHAR, &statusReport);
775 if (needToDeleteCopy) { delete copy; }
780 if((i+1) % 100 == 0){ cout << (toString(i+1)) << endl; }
783 if((num) % 100 != 0){ cout << (toString(num)) << endl; }
787 catch(exception& e) {
788 m->errorOut(e, "AlignCommand", "driverMPI");
793 /**************************************************************************************************/
795 int AlignCommand::createProcesses(string alignFileName, string reportFileName, string accnosFName, string filename) {
797 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
800 // processIDS.resize(0);
802 //loop through and create all the processes you want
803 while (process != processors) {
807 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
810 exitCommand = driver(lines[process], alignFileName + toString(getpid()) + ".temp", reportFileName + toString(getpid()) + ".temp", accnosFName + toString(getpid()) + ".temp", filename);
812 }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }
815 //force parent to wait until all the processes are done
816 for (int i=0;i<processors;i++) {
817 int temp = processIDS[i];
824 catch(exception& e) {
825 m->errorOut(e, "AlignCommand", "createProcesses");
830 /**************************************************************************************************/
832 void AlignCommand::appendAlignFiles(string temp, string filename) {
837 openOutputFileAppend(filename, output);
838 openInputFile(temp, input);
840 while(char c = input.get()){
841 if(input.eof()) { break; }
842 else { output << c; }
848 catch(exception& e) {
849 m->errorOut(e, "AlignCommand", "appendAlignFiles");
853 //**********************************************************************************************************************
855 void AlignCommand::appendReportFiles(string temp, string filename) {
860 openOutputFileAppend(filename, output);
861 openInputFile(temp, input);
863 while (!input.eof()) { char c = input.get(); if (c == 10 || c == 13){ break; } } // get header line
865 while(char c = input.get()){
866 if(input.eof()) { break; }
867 else { output << c; }
873 catch(exception& e) {
874 m->errorOut(e, "AlignCommand", "appendReportFiles");
878 //**********************************************************************************************************************