]> git.donarmstrong.com Git - mothur.git/blob - aligncommand.cpp
added set.dir command and modified commands to redirect input and output, removed...
[mothur.git] / aligncommand.cpp
1 /*
2  *  aligncommand.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 5/15/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
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).
14  *
15  */
16
17 #include "aligncommand.h"
18 #include "sequence.hpp"
19
20 #include "gotohoverlap.hpp"
21 #include "needlemanoverlap.hpp"
22 #include "blastalign.hpp"
23 #include "noalign.hpp"
24
25 #include "nast.hpp"
26 #include "nastreport.hpp"
27
28
29 //**********************************************************************************************************************
30
31 AlignCommand::AlignCommand(string option){
32         try {
33                 //              globaldata = GlobalData::getInstance();
34                 abort = false;
35                 
36                 //allow user to run help
37                 if(option == "help") { help(); abort = true; }
38                 
39                 else {
40                         
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)));
44                         
45                         OptionParser parser(option);
46                         map<string, string> parameters = parser.getParameters(); 
47                         
48                         ValidParameters validParameter;
49                         map<string, string>::iterator it;
50                         
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;  }
54                         }
55                         
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 = "";         }
58                         
59                         //if the user changes the input directory command factory will send this info to us in the output parameter 
60                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
61                         if (inputDir == "not found"){   inputDir = "";          }
62                         else {
63                                 string path;
64                                 it = parameters.find("template");
65                                 //user has given a template file
66                                 if(it != parameters.end()){ 
67                                         path = hasPath(it->second);
68                                         //if the user has not given a path then, add inputdir. else leave path alone.
69                                         if (path == "") {       parameters["template"] = inputDir + it->second;         }
70                                 }
71                         }
72                         
73                         //check for required parameters
74                         templateFileName = validParameter.validFile(parameters, "template", true);
75                         if (templateFileName == "not found") { 
76                                 mothurOut("template is a required parameter for the align.seqs command."); 
77                                 mothurOutEndLine();
78                                 abort = true; 
79                         }else if (templateFileName == "not open") { abort = true; }     
80                         
81                         candidateFileName = validParameter.validFile(parameters, "candidate", false);
82                         if (candidateFileName == "not found") { mothurOut("candidate is a required parameter for the align.seqs command."); mothurOutEndLine(); abort = true;  }
83                         else { 
84                                 splitAtDash(candidateFileName, candidateFileNames);
85                                 
86                                 //go through files and make sure they are good, if not, then disregard them
87                                 for (int i = 0; i < candidateFileNames.size(); i++) {
88                                         if (inputDir != "") {
89                                                 string path = hasPath(candidateFileNames[i]);
90                                                 //if the user has not given a path then, add inputdir. else leave path alone.
91                                                 if (path == "") {       candidateFileNames[i] = inputDir + candidateFileNames[i];               }
92                                         }
93
94                                         int ableToOpen;
95                                         ifstream in;
96                                         ableToOpen = openInputFile(candidateFileNames[i], in);
97                                         if (ableToOpen == 1) { 
98                                                 mothurOut(candidateFileNames[i] + " will be disregarded."); mothurOutEndLine(); 
99                                                 //erase from file list
100                                                 candidateFileNames.erase(candidateFileNames.begin()+i);
101                                                 i--;
102                                         }
103                                         in.close();
104                                 }
105                                 
106                                 //make sure there is at least one valid file left
107                                 if (candidateFileNames.size() == 0) { mothurOut("no valid files."); mothurOutEndLine(); abort = true; }
108                         }
109                                 
110                         
111                         //check for optional parameter and set defaults
112                         // ...at some point should added some additional type checking...
113                         string temp;
114                         temp = validParameter.validFile(parameters, "ksize", false);            if (temp == "not found"){       temp = "8";                             }
115                         convert(temp, kmerSize); 
116                         
117                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }
118                         convert(temp, match);  
119                         
120                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }
121                         convert(temp, misMatch);  
122                         
123                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }
124                         convert(temp, gapOpen);  
125                         
126                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }
127                         convert(temp, gapExtend); 
128                         
129                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = "1";                             }
130                         convert(temp, processors); 
131                         
132                         temp = validParameter.validFile(parameters, "flip", false);                     if (temp == "not found"){       temp = "f";                             }
133                         flip = isTrue(temp); 
134                         
135                         temp = validParameter.validFile(parameters, "threshold", false);        if (temp == "not found"){       temp = "0.50";                  }
136                         convert(temp, threshold); 
137                         
138                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }
139                         
140                         align = validParameter.validFile(parameters, "align", false);           if (align == "not found"){      align = "needleman";    }
141                 }
142                 
143         }
144         catch(exception& e) {
145                 errorOut(e, "AlignCommand", "AlignCommand");
146                 exit(1);
147         }
148 }
149
150 //**********************************************************************************************************************
151
152 AlignCommand::~AlignCommand(){  
153
154         if (abort == false) {
155                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
156                 delete templateDB;
157                 delete alignment;
158         }
159 }
160
161 //**********************************************************************************************************************
162
163 void AlignCommand::help(){
164         try {
165                 mothurOut("The align.seqs command reads a file containing sequences and creates an alignment file and a report file.\n");
166                 mothurOut("The align.seqs command parameters are template, candidate, search, ksize, align, match, mismatch, gapopen and gapextend.\n");
167                 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");
168                 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");
169                 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");
170                 mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.\n");
171                 mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
172                 mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n");
173                 mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n");
174                 mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -1.0.\n");
175                 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");
176                 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");
177                 mothurOut("If the flip parameter is set to true the reverse complement of the sequence is aligned and the better alignment is reported.\n");
178                 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");
179                 mothurOut("The align.seqs command should be in the following format: \n");
180                 mothurOut("align.seqs(template=yourTemplateFile, candidate=yourCandidateFile, align=yourAlignmentMethod, search=yourSearchmethod, ksize=yourKmerSize, match=yourMatchBonus, mismatch=yourMismatchpenalty, gapopen=yourGapopenPenalty, gapextend=yourGapExtendPenalty) \n");
181                 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");
182                 mothurOut("Note: No spaces between parameter labels (i.e. candidate), '=' and parameters (i.e.yourFastaFile).\n\n");
183         }
184         catch(exception& e) {
185                 errorOut(e, "AlignCommand", "help");
186                 exit(1);
187         }
188 }
189
190
191 //**********************************************************************************************************************
192
193 int AlignCommand::execute(){
194         try {
195                 if (abort == true) {    return 0;       }
196                 
197                 templateDB = new AlignmentDB(templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch);
198                 int longestBase = templateDB->getLongestBase();
199         
200                 if(align == "gotoh")                    {       alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase);                 }
201                 else if(align == "needleman")   {       alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);                                }
202                 else if(align == "blast")               {       alignment = new BlastAlignment(gapOpen, gapExtend, match, misMatch);            }
203                 else if(align == "noalign")             {       alignment = new NoAlign();                                                                                                      }
204                 else {
205                         mothurOut(align + " is not a valid alignment option. I will run the command using needleman.");
206                         mothurOutEndLine();
207                         alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);
208                 }
209                 
210                 for (int s = 0; s < candidateFileNames.size(); s++) {
211                         mothurOut("Aligning sequences from " + candidateFileNames[s] + " ..." ); mothurOutEndLine();
212                         
213                         if (outputDir == "") {  outputDir += hasPath(candidateFileNames[s]); }
214                         string alignFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "align";
215                         string reportFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "align.report";
216                         string accnosFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "flip.accnos";
217                         
218                         int numFastaSeqs = 0;
219                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
220                         int start = time(NULL);
221                         
222 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
223                         if(processors == 1){
224                                 ifstream inFASTA;
225                                 openInputFile(candidateFileNames[s], inFASTA);
226                                 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
227                                 inFASTA.close();
228                                 
229                                 lines.push_back(new linePair(0, numFastaSeqs));
230                                 
231                                 driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
232                                 
233                                 //delete accnos file if its blank else report to user
234                                 if (isBlank(accnosFileName)) {  remove(accnosFileName.c_str());  }
235                                 else { 
236                                         mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
237                                         if (!flip) {
238                                                 mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); 
239                                         }else{  mothurOut(" If the reverse compliment proved to be better it was reported.");  }
240                                         mothurOutEndLine();
241                                 }
242                         }
243                         else{
244                                 vector<int> positions;
245                                 processIDS.resize(0);
246                                 
247                                 ifstream inFASTA;
248                                 openInputFile(candidateFileNames[s], inFASTA);
249                                 
250                                 string input;
251                                 while(!inFASTA.eof()){
252                                         input = getline(inFASTA);
253                                         if (input.length() != 0) {
254                                                 if(input[0] == '>'){    long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);  }
255                                         }
256                                 }
257                                 inFASTA.close();
258                                 
259                                 numFastaSeqs = positions.size();
260                                 
261                                 int numSeqsPerProcessor = numFastaSeqs / processors;
262                                 
263                                 for (int i = 0; i < processors; i++) {
264                                         long int startPos = positions[ i * numSeqsPerProcessor ];
265                                         if(i == processors - 1){
266                                                 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
267                                         }
268                                         lines.push_back(new linePair(startPos, numSeqsPerProcessor));
269                                 }
270                                 
271                                 createProcesses(alignFileName, reportFileName, accnosFileName, candidateFileNames[s]); 
272                                 
273                                 rename((alignFileName + toString(processIDS[0]) + ".temp").c_str(), alignFileName.c_str());
274                                 rename((reportFileName + toString(processIDS[0]) + ".temp").c_str(), reportFileName.c_str());
275                                 
276                                 //append alignment and report files
277                                 for(int i=1;i<processors;i++){
278                                         appendAlignFiles((alignFileName + toString(processIDS[i]) + ".temp"), alignFileName);
279                                         remove((alignFileName + toString(processIDS[i]) + ".temp").c_str());
280                                         
281                                         appendReportFiles((reportFileName + toString(processIDS[i]) + ".temp"), reportFileName);
282                                         remove((reportFileName + toString(processIDS[i]) + ".temp").c_str());
283                                 }
284                                 
285                                 vector<string> nonBlankAccnosFiles;
286                                 //delete blank accnos files generated with multiple processes
287                                 for(int i=0;i<processors;i++){  
288                                         if (!(isBlank(accnosFileName + toString(processIDS[i]) + ".temp"))) {
289                                                 nonBlankAccnosFiles.push_back(accnosFileName + toString(processIDS[i]) + ".temp");
290                                         }else { remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());  }
291                                 }
292                                 
293                                 //append accnos files
294                                 if (nonBlankAccnosFiles.size() != 0) { 
295                                         rename(nonBlankAccnosFiles[0].c_str(), accnosFileName.c_str());
296                                         
297                                         for (int h=1; h < nonBlankAccnosFiles.size(); h++) {
298                                                 appendAlignFiles(nonBlankAccnosFiles[h], accnosFileName);
299                                                 remove(nonBlankAccnosFiles[h].c_str());
300                                         }
301                                         mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
302                                         if (!flip) {
303                                                 mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); 
304                                         }else{  mothurOut(" If the reverse compliment proved to be better it was reported.");  }
305                                         mothurOutEndLine();
306                                 }
307                         }
308 #else
309                         ifstream inFASTA;
310                         openInputFile(candidateFileNames[s], inFASTA);
311                         numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
312                         inFASTA.close();
313                         
314                         lines.push_back(new linePair(0, numFastaSeqs));
315                         
316                         driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);
317                         
318                         //delete accnos file if its blank else report to user
319                         if (isBlank(accnosFileName)) {  remove(accnosFileName.c_str());  }
320                         else { 
321                                 mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");
322                                 if (!flip) {
323                                         mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); 
324                                 }else{  mothurOut(" If the reverse compliment proved to be better it was reported.");  }
325                                 mothurOutEndLine();
326                         }
327                         
328 #endif
329                         
330                         
331                         
332                         mothurOut("It took " + toString(time(NULL) - start) + " secs to align " + toString(numFastaSeqs) + " sequences.");
333                         mothurOutEndLine();
334                         mothurOutEndLine();
335                 }
336                 
337                 return 0;
338         }
339         catch(exception& e) {
340                 errorOut(e, "AlignCommand", "execute");
341                 exit(1);
342         }
343 }
344
345 //**********************************************************************************************************************
346
347 int AlignCommand::driver(linePair* line, string alignFName, string reportFName, string accnosFName, string filename){
348         try {
349                 ofstream alignmentFile;
350                 openOutputFile(alignFName, alignmentFile);
351                 
352                 ofstream accnosFile;
353                 openOutputFile(accnosFName, accnosFile);
354                 
355                 NastReport report(reportFName);
356                 
357                 ifstream inFASTA;
358                 openInputFile(filename, inFASTA);
359
360                 inFASTA.seekg(line->start);
361                 
362                 for(int i=0;i<line->numSeqs;i++){
363                 
364                         Sequence* candidateSeq = new Sequence(inFASTA);  gobble(inFASTA);
365                         int origNumBases = candidateSeq->getNumBases();
366                         string originalUnaligned = candidateSeq->getUnaligned();
367                         int numBasesNeeded = origNumBases * threshold;
368         
369                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
370                                 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {
371                                         alignment->resize(candidateSeq->getUnaligned().length()+1);
372                                 }
373                                                                 
374                                 Sequence temp = templateDB->findClosestSequence(candidateSeq);
375                                 Sequence* templateSeq = &temp;
376                                 
377                                 float searchScore = templateDB->getSearchScore();
378                                                                 
379                                 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);
380                                 Sequence* copy;
381                                 
382                                 Nast* nast2;
383                                 bool needToDeleteCopy = false;  //this is needed in case you have you enter the ifs below
384                                                                                                 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below
385                                                                                                 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place
386                                                                                                 //so this bool tells you if you need to delete it
387                                                                                                 
388                                 //if there is a possibility that this sequence should be reversed
389                                 if (candidateSeq->getNumBases() < numBasesNeeded) {
390                                         
391                                         string wasBetter = "";
392                                         //if the user wants you to try the reverse
393                                         if (flip) {
394                                                 //get reverse compliment
395                                                 copy = new Sequence(candidateSeq->getName(), originalUnaligned);
396                                                 copy->reverseComplement();
397                                                 
398                                                 //rerun alignment
399                                                 Sequence temp2 = templateDB->findClosestSequence(copy);
400                                                 Sequence* templateSeq2 = &temp2;
401                                                 
402                                                 searchScore = templateDB->getSearchScore();
403                                                 
404                                                 nast2 = new Nast(alignment, copy, templateSeq2);
405                         
406                                                 //check if any better
407                                                 if (copy->getNumBases() > candidateSeq->getNumBases()) {
408                                                         candidateSeq->setAligned(copy->getAligned());  //use reverse compliments alignment since its better
409                                                         templateSeq = templateSeq2; 
410                                                         delete nast;
411                                                         nast = nast2;
412                                                         needToDeleteCopy = true;
413                                                 }else{  
414                                                         wasBetter = "\treverse complement did NOT produce a better alignment, please check sequence.";
415                                                         delete nast2;
416                                                         delete copy;    
417                                                 }
418                                         }
419                                         
420                                         //create accnos file with names
421                                         accnosFile << candidateSeq->getName() << wasBetter << endl;
422                                 }
423                                 
424                                 report.setCandidate(candidateSeq);
425                                 report.setTemplate(templateSeq);
426                                 report.setSearchParameters(search, searchScore);
427                                 report.setAlignmentParameters(align, alignment);
428                                 report.setNastParameters(*nast);
429         
430                                 alignmentFile << '>' << candidateSeq->getName() << '\n' << candidateSeq->getAligned() << endl;
431                                 
432                                 report.print();
433                                 delete nast;
434                                 if (needToDeleteCopy) {   delete copy;   }
435                         }
436                         delete candidateSeq;
437                         
438                         //report progress
439                         if((i+1) % 100 == 0){   mothurOut(toString(i+1)); mothurOutEndLine();           }
440                 }
441                 //report progress
442                 if((line->numSeqs) % 100 != 0){ mothurOut(toString(line->numSeqs)); mothurOutEndLine();         }
443                 
444                 alignmentFile.close();
445                 inFASTA.close();
446                 accnosFile.close();
447                 
448                 return 1;
449         }
450         catch(exception& e) {
451                 errorOut(e, "AlignCommand", "driver");
452                 exit(1);
453         }
454 }
455
456 /**************************************************************************************************/
457
458 void AlignCommand::createProcesses(string alignFileName, string reportFileName, string accnosFName, string filename) {
459         try {
460 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
461                 int process = 0;
462                 //              processIDS.resize(0);
463                 
464                 //loop through and create all the processes you want
465                 while (process != processors) {
466                         int pid = fork();
467                         
468                         if (pid > 0) {
469                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
470                                 process++;
471                         }else if (pid == 0){
472                                 driver(lines[process], alignFileName + toString(getpid()) + ".temp", reportFileName + toString(getpid()) + ".temp", accnosFName + toString(getpid()) + ".temp", filename);
473                                 exit(0);
474                         }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
475                 }
476                 
477                 //force parent to wait until all the processes are done
478                 for (int i=0;i<processors;i++) { 
479                         int temp = processIDS[i];
480                         wait(&temp);
481                 }
482 #endif          
483         }
484         catch(exception& e) {
485                 errorOut(e, "AlignCommand", "createProcesses");
486                 exit(1);
487         }
488 }
489
490 /**************************************************************************************************/
491
492 void AlignCommand::appendAlignFiles(string temp, string filename) {
493         try{
494                 
495                 ofstream output;
496                 ifstream input;
497                 openOutputFileAppend(filename, output);
498                 openInputFile(temp, input);
499                 
500                 while(char c = input.get()){
501                         if(input.eof())         {       break;                  }
502                         else                            {       output << c;    }
503                 }
504                 
505                 input.close();
506                 output.close();
507         }
508         catch(exception& e) {
509                 errorOut(e, "AlignCommand", "appendAlignFiles");
510                 exit(1);
511         }
512 }
513 //**********************************************************************************************************************
514
515 void AlignCommand::appendReportFiles(string temp, string filename) {
516         try{
517                 
518                 ofstream output;
519                 ifstream input;
520                 openOutputFileAppend(filename, output);
521                 openInputFile(temp, input);
522
523                 while (!input.eof())    {       char c = input.get(); if (c == 10 || c == 13){  break;  }       } // get header line
524                                 
525                 while(char c = input.get()){
526                         if(input.eof())         {       break;                  }
527                         else                            {       output << c;    }
528                 }
529                 
530                 input.close();
531                 output.close();
532         }
533         catch(exception& e) {
534                 errorOut(e, "AlignCommand", "appendReportFiles");
535                 exit(1);
536         }
537 }
538
539 //**********************************************************************************************************************