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 //**********************************************************************************************************************
30 vector<string> AlignCommand::getValidParameters(){
32 string AlignArray[] = {"template","candidate","search","ksize","align","match","mismatch","gapopen","gapextend", "processors","flip","threshold","outputdir","inputdir"};
33 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
37 m->errorOut(e, "AlignCommand", "getValidParameters");
41 //**********************************************************************************************************************
42 vector<string> AlignCommand::getRequiredParameters(){
44 string AlignArray[] = {"template","candidate"};
45 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
49 m->errorOut(e, "AlignCommand", "getRequiredParameters");
53 //**********************************************************************************************************************
54 vector<string> AlignCommand::getRequiredFiles(){
56 vector<string> myArray;
60 m->errorOut(e, "AlignCommand", "getRequiredFiles");
64 //**********************************************************************************************************************
65 AlignCommand::AlignCommand(){
67 abort = true; calledHelp = true;
68 vector<string> tempOutNames;
69 outputTypes["fasta"] = tempOutNames;
70 outputTypes["alignreport"] = tempOutNames;
71 outputTypes["accnos"] = tempOutNames;
74 m->errorOut(e, "AlignCommand", "AlignCommand");
78 //**********************************************************************************************************************
79 AlignCommand::AlignCommand(string option) {
81 abort = false; calledHelp = false;
83 //allow user to run help
84 if(option == "help") { help(); abort = true; calledHelp = true;}
88 //valid paramters for this command
89 string AlignArray[] = {"template","candidate","search","ksize","align","match","mismatch","gapopen","gapextend", "processors","flip","threshold","outputdir","inputdir"};
90 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
92 OptionParser parser(option);
93 map<string, string> parameters = parser.getParameters();
95 ValidParameters validParameter("align.seqs");
96 map<string, string>::iterator it;
98 //check to make sure all parameters are valid for command
99 for (it = parameters.begin(); it != parameters.end(); it++) {
100 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
103 //initialize outputTypes
104 vector<string> tempOutNames;
105 outputTypes["fasta"] = tempOutNames;
106 outputTypes["alignreport"] = tempOutNames;
107 outputTypes["accnos"] = tempOutNames;
109 //if the user changes the output directory command factory will send this info to us in the output parameter
110 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
113 //if the user changes the input directory command factory will send this info to us in the output parameter
114 string inputDir = validParameter.validFile(parameters, "inputdir", false);
116 if (inputDir == "not found"){ inputDir = ""; }
120 it = parameters.find("template");
122 //user has given a template file
123 if(it != parameters.end()){
124 path = m->hasPath(it->second);
125 //if the user has not given a path then, add inputdir. else leave path alone.
126 if (path == "") { parameters["template"] = inputDir + it->second; }
130 //check for required parameters
131 templateFileName = validParameter.validFile(parameters, "template", true);
133 if (templateFileName == "not found") {
134 m->mothurOut("template is a required parameter for the align.seqs command.");
135 m->mothurOutEndLine();
137 }else if (templateFileName == "not open") { abort = true; }
139 candidateFileName = validParameter.validFile(parameters, "candidate", false);
140 if (candidateFileName == "not found") {
142 m->splitAtDash(candidateFileName, candidateFileNames);
144 //go through files and make sure they are good, if not, then disregard them
145 for (int i = 0; i < candidateFileNames.size(); i++) {
146 //candidateFileNames[i] = m->getFullPathName(candidateFileNames[i]);
148 if (inputDir != "") {
149 string path = m->hasPath(candidateFileNames[i]);
150 //if the user has not given a path then, add inputdir. else leave path alone.
151 if (path == "") { candidateFileNames[i] = inputDir + candidateFileNames[i]; }
156 ableToOpen = m->openInputFile(candidateFileNames[i], in, "noerror");
159 //if you can't open it, try default location
160 if (ableToOpen == 1) {
161 if (m->getDefaultPath() != "") { //default path is set
162 string tryPath = m->getDefaultPath() + m->getSimpleName(candidateFileNames[i]);
163 m->mothurOut("Unable to open " + candidateFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
165 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
167 candidateFileNames[i] = tryPath;
171 //if you can't open it, try output location
172 if (ableToOpen == 1) {
173 if (m->getOutputDir() != "") { //default path is set
174 string tryPath = m->getOutputDir() + m->getSimpleName(candidateFileNames[i]);
175 m->mothurOut("Unable to open " + candidateFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
177 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
179 candidateFileNames[i] = tryPath;
185 if (ableToOpen == 1) {
186 m->mothurOut("Unable to open " + candidateFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
187 //erase from file list
188 candidateFileNames.erase(candidateFileNames.begin()+i);
194 //make sure there is at least one valid file left
195 if (candidateFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
198 //check for optional parameter and set defaults
199 // ...at some point should added some additional type checking...
201 temp = validParameter.validFile(parameters, "ksize", false); if (temp == "not found"){ temp = "8"; }
202 convert(temp, kmerSize);
204 temp = validParameter.validFile(parameters, "match", false); if (temp == "not found"){ temp = "1.0"; }
205 convert(temp, match);
207 temp = validParameter.validFile(parameters, "mismatch", false); if (temp == "not found"){ temp = "-1.0"; }
208 convert(temp, misMatch);
210 temp = validParameter.validFile(parameters, "gapopen", false); if (temp == "not found"){ temp = "-2.0"; }
211 convert(temp, gapOpen);
213 temp = validParameter.validFile(parameters, "gapextend", false); if (temp == "not found"){ temp = "-1.0"; }
214 convert(temp, gapExtend);
216 temp = validParameter.validFile(parameters, "processors", false); if (temp == "not found"){ temp = "1"; }
217 convert(temp, processors);
219 temp = validParameter.validFile(parameters, "flip", false); if (temp == "not found"){ temp = "f"; }
220 flip = m->isTrue(temp);
222 temp = validParameter.validFile(parameters, "threshold", false); if (temp == "not found"){ temp = "0.50"; }
223 convert(temp, threshold);
225 search = validParameter.validFile(parameters, "search", false); if (search == "not found"){ search = "kmer"; }
227 align = validParameter.validFile(parameters, "align", false); if (align == "not found"){ align = "needleman"; }
231 catch(exception& e) {
232 m->errorOut(e, "AlignCommand", "AlignCommand");
236 //**********************************************************************************************************************
238 AlignCommand::~AlignCommand(){
240 if (abort == false) {
241 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
247 //**********************************************************************************************************************
249 void AlignCommand::help(){
251 m->mothurOut("The align.seqs command reads a file containing sequences and creates an alignment file and a report file.\n");
252 m->mothurOut("The align.seqs command parameters are template, candidate, search, ksize, align, match, mismatch, gapopen, gapextend and processors.\n");
253 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");
254 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");
255 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");
256 m->mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate. The default is 8.\n");
257 m->mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
258 m->mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases. The default is -1.0.\n");
259 m->mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n");
260 m->mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment. The default is -1.0.\n");
261 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");
262 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");
263 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");
264 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");
265 m->mothurOut("The align.seqs command should be in the following format: \n");
266 m->mothurOut("align.seqs(template=yourTemplateFile, candidate=yourCandidateFile, align=yourAlignmentMethod, search=yourSearchmethod, ksize=yourKmerSize, match=yourMatchBonus, mismatch=yourMismatchpenalty, gapopen=yourGapopenPenalty, gapextend=yourGapExtendPenalty) \n");
267 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");
268 m->mothurOut("Note: No spaces between parameter labels (i.e. candidate), '=' and parameters (i.e.yourFastaFile).\n\n");
270 catch(exception& e) {
271 m->errorOut(e, "AlignCommand", "help");
277 //**********************************************************************************************************************
279 int AlignCommand::execute(){
281 if (abort == true) { if (calledHelp) { return 0; } return 2; }
283 templateDB = new AlignmentDB(templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch);
284 int longestBase = templateDB->getLongestBase();
286 if(align == "gotoh") { alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase); }
287 else if(align == "needleman") { alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase); }
288 else if(align == "blast") { alignment = new BlastAlignment(gapOpen, gapExtend, match, misMatch); }
289 else if(align == "noalign") { alignment = new NoAlign(); }
291 m->mothurOut(align + " is not a valid alignment option. I will run the command using needleman.");
292 m->mothurOutEndLine();
293 alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);
296 for (int s = 0; s < candidateFileNames.size(); s++) {
297 if (m->control_pressed) { outputTypes.clear(); return 0; }
299 m->mothurOut("Aligning sequences from " + candidateFileNames[s] + " ..." ); m->mothurOutEndLine();
301 if (outputDir == "") { outputDir += m->hasPath(candidateFileNames[s]); }
302 string alignFileName = outputDir + m->getRootName(m->getSimpleName(candidateFileNames[s])) + "align";
303 string reportFileName = outputDir + m->getRootName(m->getSimpleName(candidateFileNames[s])) + "align.report";
304 string accnosFileName = outputDir + m->getRootName(m->getSimpleName(candidateFileNames[s])) + "flip.accnos";
305 bool hasAccnos = true;
307 int numFastaSeqs = 0;
308 for (int i = 0; i < lines.size(); i++) { delete lines[i]; } lines.clear();
309 int start = time(NULL);
312 int pid, numSeqsPerProcessor;
314 vector<unsigned long int> MPIPos;
315 MPIWroteAccnos = false;
318 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
319 MPI_Comm_size(MPI_COMM_WORLD, &processors);
322 MPI_File outMPIAlign;
323 MPI_File outMPIReport;
324 MPI_File outMPIAccnos;
326 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY;
327 int inMode=MPI_MODE_RDONLY;
329 char outAlignFilename[1024];
330 strcpy(outAlignFilename, alignFileName.c_str());
332 char outReportFilename[1024];
333 strcpy(outReportFilename, reportFileName.c_str());
335 char outAccnosFilename[1024];
336 strcpy(outAccnosFilename, accnosFileName.c_str());
338 char inFileName[1024];
339 strcpy(inFileName, candidateFileNames[s].c_str());
341 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
342 MPI_File_open(MPI_COMM_WORLD, outAlignFilename, outMode, MPI_INFO_NULL, &outMPIAlign);
343 MPI_File_open(MPI_COMM_WORLD, outReportFilename, outMode, MPI_INFO_NULL, &outMPIReport);
344 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
346 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPIAlign); MPI_File_close(&outMPIReport); MPI_File_close(&outMPIAccnos); outputTypes.clear(); return 0; }
348 if (pid == 0) { //you are the root process
350 MPIPos = m->setFilePosFasta(candidateFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs
352 //send file positions to all processes
353 for(int i = 1; i < processors; i++) {
354 MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
355 MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
358 //figure out how many sequences you have to align
359 numSeqsPerProcessor = numFastaSeqs / processors;
360 int startIndex = pid * numSeqsPerProcessor;
361 if(pid == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor; }
364 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);
366 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPIAlign); MPI_File_close(&outMPIReport); MPI_File_close(&outMPIAccnos); outputTypes.clear(); return 0; }
368 for (int i = 1; i < processors; i++) {
370 MPI_Recv(&tempResult, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
371 if (tempResult != 0) { MPIWroteAccnos = true; }
373 }else{ //you are a child process
374 MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
375 MPIPos.resize(numFastaSeqs+1);
376 MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
379 //figure out how many sequences you have to align
380 numSeqsPerProcessor = numFastaSeqs / processors;
381 int startIndex = pid * numSeqsPerProcessor;
382 if(pid == (processors - 1)){ numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor; }
386 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);
388 if (m->control_pressed) { MPI_File_close(&inMPI); MPI_File_close(&outMPIAlign); MPI_File_close(&outMPIReport); MPI_File_close(&outMPIAccnos); outputTypes.clear(); return 0; }
390 MPI_Send(&MPIWroteAccnos, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
394 MPI_File_close(&inMPI);
395 MPI_File_close(&outMPIAlign);
396 MPI_File_close(&outMPIReport);
397 MPI_File_close(&outMPIAccnos);
399 //delete accnos file if blank
401 //delete accnos file if its blank else report to user
402 if (MPIWroteAccnos) {
403 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
405 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well.");
406 }else{ m->mothurOut(" If the reverse compliment proved to be better it was reported."); }
407 m->mothurOutEndLine();
410 //MPI_File_delete(outAccnosFilename, info);
412 remove(accnosFileName.c_str());
418 vector<unsigned long int> positions = m->divideFile(candidateFileNames[s], processors);
419 for (int i = 0; i < (positions.size()-1); i++) {
420 lines.push_back(new linePair(positions[i], positions[(i+1)]));
422 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
424 numFastaSeqs = driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
426 numFastaSeqs = createProcesses(alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
429 numFastaSeqs = driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
432 if (m->control_pressed) { remove(accnosFileName.c_str()); remove(alignFileName.c_str()); remove(reportFileName.c_str()); outputTypes.clear(); return 0; }
434 //delete accnos file if its blank else report to user
435 if (m->isBlank(accnosFileName)) { remove(accnosFileName.c_str()); hasAccnos = false; }
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();
448 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
450 if (pid == 0) { //only one process should output to screen
453 outputNames.push_back(alignFileName); outputTypes["fasta"].push_back(alignFileName);
454 outputNames.push_back(reportFileName); outputTypes["alignreport"].push_back(reportFileName);
455 if (hasAccnos) { outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName); }
461 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to align " + toString(numFastaSeqs) + " sequences.");
462 m->mothurOutEndLine();
463 m->mothurOutEndLine();
466 //set align file as new current fastafile
467 string currentFasta = "";
468 itTypes = outputTypes.find("fasta");
469 if (itTypes != outputTypes.end()) {
470 if ((itTypes->second).size() != 0) { currentFasta = (itTypes->second)[0]; m->setFastaFile(currentFasta); }
473 m->mothurOutEndLine();
474 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
475 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
476 m->mothurOutEndLine();
480 catch(exception& e) {
481 m->errorOut(e, "AlignCommand", "execute");
486 //**********************************************************************************************************************
488 int AlignCommand::driver(linePair* filePos, string alignFName, string reportFName, string accnosFName, string filename){
490 ofstream alignmentFile;
491 m->openOutputFile(alignFName, alignmentFile);
494 m->openOutputFile(accnosFName, accnosFile);
496 NastReport report(reportFName);
499 m->openInputFile(filename, inFASTA);
501 inFASTA.seekg(filePos->start);
508 if (m->control_pressed) { return 0; }
510 Sequence* candidateSeq = new Sequence(inFASTA); m->gobble(inFASTA);
511 report.setCandidate(candidateSeq);
513 int origNumBases = candidateSeq->getNumBases();
514 string originalUnaligned = candidateSeq->getUnaligned();
515 int numBasesNeeded = origNumBases * threshold;
517 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
518 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {
519 alignment->resize(candidateSeq->getUnaligned().length()+1);
522 Sequence temp = templateDB->findClosestSequence(candidateSeq);
523 Sequence* templateSeq = &temp;
525 float searchScore = templateDB->getSearchScore();
527 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);
532 bool needToDeleteCopy = false; //this is needed in case you have you enter the ifs below
533 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below
534 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place
535 //so this bool tells you if you need to delete it
537 //if there is a possibility that this sequence should be reversed
538 if (candidateSeq->getNumBases() < numBasesNeeded) {
540 string wasBetter = "";
541 //if the user wants you to try the reverse
544 //get reverse compliment
545 copy = new Sequence(candidateSeq->getName(), originalUnaligned);
546 copy->reverseComplement();
549 Sequence temp2 = templateDB->findClosestSequence(copy);
550 Sequence* templateSeq2 = &temp2;
552 searchScore = templateDB->getSearchScore();
554 nast2 = new Nast(alignment, copy, templateSeq2);
556 //check if any better
557 if (copy->getNumBases() > candidateSeq->getNumBases()) {
558 candidateSeq->setAligned(copy->getAligned()); //use reverse compliments alignment since its better
559 templateSeq = templateSeq2;
562 needToDeleteCopy = true;
563 wasBetter = "\treverse complement produced a better alignment, so mothur used the reverse complement.";
565 wasBetter = "\treverse complement did NOT produce a better alignment so it was not used, please check sequence.";
571 //create accnos file with names
572 accnosFile << candidateSeq->getName() << wasBetter << endl;
575 report.setTemplate(templateSeq);
576 report.setSearchParameters(search, searchScore);
577 report.setAlignmentParameters(align, alignment);
578 report.setNastParameters(*nast);
580 alignmentFile << '>' << candidateSeq->getName() << '\n' << candidateSeq->getAligned() << endl;
584 if (needToDeleteCopy) { delete copy; }
590 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
591 unsigned long int pos = inFASTA.tellg();
592 if ((pos == -1) || (pos >= filePos->end)) { break; }
594 if (inFASTA.eof()) { break; }
598 if((count) % 100 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
602 if((count) % 100 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine(); }
604 alignmentFile.close();
610 catch(exception& e) {
611 m->errorOut(e, "AlignCommand", "driver");
615 //**********************************************************************************************************************
617 int AlignCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& alignFile, MPI_File& reportFile, MPI_File& accnosFile, vector<unsigned long int>& MPIPos){
619 string outputString = "";
620 MPI_Status statusReport;
621 MPI_Status statusAlign;
622 MPI_Status statusAccnos;
625 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
630 outputString = report.getHeaders();
631 int length = outputString.length();
633 char* buf = new char[length];
634 memcpy(buf, outputString.c_str(), length);
636 MPI_File_write_shared(reportFile, buf, length, MPI_CHAR, &statusReport);
641 for(int i=0;i<num;i++){
643 if (m->control_pressed) { return 0; }
646 int length = MPIPos[start+i+1] - MPIPos[start+i];
648 char* buf4 = new char[length];
649 //memcpy(buf4, outputString.c_str(), length);
651 MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
653 string tempBuf = buf4;
657 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
659 istringstream iss (tempBuf,istringstream::in);
661 Sequence* candidateSeq = new Sequence(iss);
662 report.setCandidate(candidateSeq);
664 int origNumBases = candidateSeq->getNumBases();
665 string originalUnaligned = candidateSeq->getUnaligned();
666 int numBasesNeeded = origNumBases * threshold;
668 if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
669 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {
670 alignment->resize(candidateSeq->getUnaligned().length()+1);
673 Sequence temp = templateDB->findClosestSequence(candidateSeq);
674 Sequence* templateSeq = &temp;
676 float searchScore = templateDB->getSearchScore();
678 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);
682 bool needToDeleteCopy = false; //this is needed in case you have you enter the ifs below
683 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below
684 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place
685 //so this bool tells you if you need to delete it
687 //if there is a possibility that this sequence should be reversed
688 if (candidateSeq->getNumBases() < numBasesNeeded) {
690 string wasBetter = "";
691 //if the user wants you to try the reverse
693 //get reverse compliment
694 copy = new Sequence(candidateSeq->getName(), originalUnaligned);
695 copy->reverseComplement();
698 Sequence temp2 = templateDB->findClosestSequence(copy);
699 Sequence* templateSeq2 = &temp2;
701 searchScore = templateDB->getSearchScore();
703 nast2 = new Nast(alignment, copy, templateSeq2);
705 //check if any better
706 if (copy->getNumBases() > candidateSeq->getNumBases()) {
707 candidateSeq->setAligned(copy->getAligned()); //use reverse compliments alignment since its better
708 templateSeq = templateSeq2;
711 needToDeleteCopy = true;
712 wasBetter = "\treverse complement produced a better alignment, so mothur used the reverse complement.";
714 wasBetter = "\treverse complement did NOT produce a better alignment, please check sequence.";
720 //create accnos file with names
721 outputString = candidateSeq->getName() + wasBetter + "\n";
723 //send results to parent
724 int length = outputString.length();
726 char* buf = new char[length];
727 memcpy(buf, outputString.c_str(), length);
729 MPI_File_write_shared(accnosFile, buf, length, MPI_CHAR, &statusAccnos);
731 MPIWroteAccnos = true;
734 report.setTemplate(templateSeq);
735 report.setSearchParameters(search, searchScore);
736 report.setAlignmentParameters(align, alignment);
737 report.setNastParameters(*nast);
739 outputString = ">" + candidateSeq->getName() + "\n" + candidateSeq->getAligned() + "\n";
741 //send results to parent
742 int length = outputString.length();
743 char* buf2 = new char[length];
744 memcpy(buf2, outputString.c_str(), length);
746 MPI_File_write_shared(alignFile, buf2, length, MPI_CHAR, &statusAlign);
750 outputString = report.getReport();
752 //send results to parent
753 length = outputString.length();
754 char* buf3 = new char[length];
755 memcpy(buf3, outputString.c_str(), length);
757 MPI_File_write_shared(reportFile, buf3, length, MPI_CHAR, &statusReport);
761 if (needToDeleteCopy) { delete copy; }
766 if((i+1) % 100 == 0){ cout << (toString(i+1)) << endl; }
769 if((num) % 100 != 0){ cout << (toString(num)) << endl; }
773 catch(exception& e) {
774 m->errorOut(e, "AlignCommand", "driverMPI");
779 /**************************************************************************************************/
781 int AlignCommand::createProcesses(string alignFileName, string reportFileName, string accnosFName, string filename) {
783 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
784 processIDS.resize(0);
787 // processIDS.resize(0);
789 //loop through and create all the processes you want
790 while (process != processors) {
794 processIDS.push_back(pid); //create map from line number to pid so you can append files in correct order later
797 num = driver(lines[process], alignFileName + toString(getpid()) + ".temp", reportFileName + toString(getpid()) + ".temp", accnosFName + toString(getpid()) + ".temp", filename);
799 //pass numSeqs to parent
801 string tempFile = alignFileName + toString(getpid()) + ".num.temp";
802 m->openOutputFile(tempFile, out);
808 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine();
809 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
815 num = driver(lines[0], alignFileName, reportFileName, accnosFName, filename);
817 //force parent to wait until all the processes are done
818 for (int i=0;i<processors;i++) {
819 int temp = processIDS[i];
823 vector<string> nonBlankAccnosFiles;
824 if (!(m->isBlank(accnosFName))) { nonBlankAccnosFiles.push_back(accnosFName); }
825 else { remove(accnosFName.c_str()); } //remove so other files can be renamed to it
827 for (int i = 0; i < processIDS.size(); i++) {
829 string tempFile = alignFileName + toString(processIDS[i]) + ".num.temp";
830 m->openInputFile(tempFile, in);
831 if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
832 in.close(); remove(tempFile.c_str());
834 appendAlignFiles((alignFileName + toString(processIDS[i]) + ".temp"), alignFileName);
835 remove((alignFileName + toString(processIDS[i]) + ".temp").c_str());
837 appendReportFiles((reportFileName + toString(processIDS[i]) + ".temp"), reportFileName);
838 remove((reportFileName + toString(processIDS[i]) + ".temp").c_str());
840 if (!(m->isBlank(accnosFName + toString(processIDS[i]) + ".temp"))) {
841 nonBlankAccnosFiles.push_back(accnosFName + toString(processIDS[i]) + ".temp");
842 }else { remove((accnosFName + toString(processIDS[i]) + ".temp").c_str()); }
846 //append accnos files
847 if (nonBlankAccnosFiles.size() != 0) {
848 rename(nonBlankAccnosFiles[0].c_str(), accnosFName.c_str());
850 for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
851 appendAlignFiles(nonBlankAccnosFiles[h], accnosFName);
852 remove(nonBlankAccnosFiles[h].c_str());
854 }else { //recreate the accnosfile if needed
856 m->openOutputFile(accnosFName, out);
863 catch(exception& e) {
864 m->errorOut(e, "AlignCommand", "createProcesses");
868 /**************************************************************************************************/
870 void AlignCommand::appendAlignFiles(string temp, string filename) {
875 m->openOutputFileAppend(filename, output);
876 m->openInputFile(temp, input);
878 while(char c = input.get()){
879 if(input.eof()) { break; }
880 else { output << c; }
886 catch(exception& e) {
887 m->errorOut(e, "AlignCommand", "appendAlignFiles");
891 //**********************************************************************************************************************
893 void AlignCommand::appendReportFiles(string temp, string filename) {
898 m->openOutputFileAppend(filename, output);
899 m->openInputFile(temp, input);
901 while (!input.eof()) { char c = input.get(); if (c == 10 || c == 13){ break; } } // get header line
903 while(char c = input.get()){
904 if(input.eof()) { break; }
905 else { output << c; }
911 catch(exception& e) {
912 m->errorOut(e, "AlignCommand", "appendReportFiles");
916 //**********************************************************************************************************************