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