]> git.donarmstrong.com Git - mothur.git/blob - aligncommand.cpp
final fixes for 1.7
[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"};
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                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }
94                         
95                         align = validParameter.validFile(parameters, "align", false);           if (align == "not found"){      align = "needleman";    }
96                 }
97                 
98         }
99         catch(exception& e) {
100                 errorOut(e, "AlignCommand", "AlignCommand");
101                 exit(1);
102         }
103 }
104
105 //**********************************************************************************************************************
106
107 AlignCommand::~AlignCommand(){  
108
109         if (abort == false) {
110                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
111                 delete templateDB;
112                 delete alignment;
113         }
114 }
115
116 //**********************************************************************************************************************
117
118 void AlignCommand::help(){
119         try {
120                 mothurOut("The align.seqs command reads a file containing sequences and creates an alignment file and a report file.\n");
121                 mothurOut("The align.seqs command parameters are template, candidate, search, ksize, align, match, mismatch, gapopen and gapextend.\n");
122                 mothurOut("The template and candidate parameters are required.\n");
123                 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");
124                 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");
125                 mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.\n");
126                 mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");
127                 mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n");
128                 mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -1.0.\n");
129                 mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -2.0.\n");
130                 mothurOut("The align.seqs command should be in the following format: \n");
131                 mothurOut("align.seqs(template=yourTemplateFile, candidate=yourCandidateFile, align=yourAlignmentMethod, search=yourSearchmethod, ksize=yourKmerSize, match=yourMatchBonus, mismatch=yourMismatchpenalty, gapopen=yourGapopenPenalty, gapextend=yourGapExtendPenalty) \n");
132                 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");
133                 mothurOut("Note: No spaces between parameter labels (i.e. candidate), '=' and parameters (i.e.yourFastaFile).\n\n");
134         }
135         catch(exception& e) {
136                 errorOut(e, "AlignCommand", "help");
137                 exit(1);
138         }
139 }
140
141
142 //**********************************************************************************************************************
143
144 int AlignCommand::execute(){
145         try {
146                 if (abort == true) {    return 0;       }
147                 
148                 templateDB = new AlignmentDB(templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch);
149                 int longestBase = templateDB->getLongestBase();
150         
151                 if(align == "gotoh")                    {       alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase);                 }
152                 else if(align == "needleman")   {       alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);                                }
153                 else if(align == "blast")               {       alignment = new BlastAlignment(gapOpen, gapExtend, match, misMatch);            }
154                 else if(align == "noalign")             {       alignment = new NoAlign();                                                                                                      }
155                 else {
156                         mothurOut(align + " is not a valid alignment option. I will run the command using needleman.");
157                         mothurOutEndLine();
158                         alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);
159                 }
160                 mothurOut("Aligning sequences...");
161                 mothurOutEndLine();
162                 
163                 string alignFileName = candidateFileName.substr(0,candidateFileName.find_last_of(".")+1) + "align";
164                 string reportFileName = candidateFileName.substr(0,candidateFileName.find_last_of(".")+1) + "align.report";
165                 
166                 int numFastaSeqs = 0;
167                 int start = time(NULL);
168                 
169 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
170                 if(processors == 1){
171                         ifstream inFASTA;
172                         openInputFile(candidateFileName, inFASTA);
173                         numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
174                         inFASTA.close();
175                         
176                         lines.push_back(new linePair(0, numFastaSeqs));
177                 
178                         driver(lines[0], alignFileName, reportFileName);
179                         
180                 }
181                 else{
182                         vector<int> positions;
183                         processIDS.resize(0);
184                         
185                         ifstream inFASTA;
186                         openInputFile(candidateFileName, inFASTA);
187                         
188                         string input;
189                         while(!inFASTA.eof()){
190                                 input = getline(inFASTA);
191                                 if (input.length() != 0) {
192                                         if(input[0] == '>'){    int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);       }
193                                 }
194                         }
195                         inFASTA.close();
196                         
197                         numFastaSeqs = positions.size();
198                         
199                         int numSeqsPerProcessor = numFastaSeqs / processors;
200                         
201                         for (int i = 0; i < processors; i++) {
202                                 int startPos = positions[ i * numSeqsPerProcessor ];
203                                 if(i == processors - 1){
204                                         numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;
205                                 }
206                                 lines.push_back(new linePair(startPos, numSeqsPerProcessor));
207                         }
208                         createProcesses(alignFileName, reportFileName); 
209                         
210                         rename((alignFileName + toString(processIDS[0]) + ".temp").c_str(), alignFileName.c_str());
211                         rename((reportFileName + toString(processIDS[0]) + ".temp").c_str(), reportFileName.c_str());
212                         
213                         for(int i=1;i<processors;i++){
214                                 appendAlignFiles((alignFileName + toString(processIDS[i]) + ".temp"), alignFileName);
215                                 remove((alignFileName + toString(processIDS[i]) + ".temp").c_str());
216                                 
217                                 appendReportFiles((reportFileName + toString(processIDS[i]) + ".temp"), reportFileName);
218                                 remove((reportFileName + toString(processIDS[i]) + ".temp").c_str());
219                         }
220                         
221                 }
222 #else
223                 ifstream inFASTA;
224                 openInputFile(candidateFileName, inFASTA);
225                 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');
226                 inFASTA.close();
227                 
228                 lines.push_back(new linePair(0, numFastaSeqs));
229                 
230                 driver(lines[0], alignFileName, reportFileName);
231 #endif
232                 
233                 mothurOut("It took " + toString(time(NULL) - start) + " secs to align " + toString(numFastaSeqs) + " sequences.");
234                 mothurOutEndLine();
235                 mothurOutEndLine();
236                 
237                 return 0;
238         }
239         catch(exception& e) {
240                 errorOut(e, "AlignCommand", "execute");
241                 exit(1);
242         }
243 }
244
245 //**********************************************************************************************************************
246
247 int AlignCommand::driver(linePair* line, string alignFName, string reportFName){
248         try {
249                 ofstream alignmentFile;
250                 openOutputFile(alignFName, alignmentFile);
251                 NastReport report(reportFName);
252                 
253                 ifstream inFASTA;
254                 openInputFile(candidateFileName, inFASTA);
255
256                 inFASTA.seekg(line->start);
257
258                 for(int i=0;i<line->numSeqs;i++){
259                         
260                         Sequence* candidateSeq = new Sequence(inFASTA);
261
262                         if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {
263                                 alignment->resize(candidateSeq->getUnaligned().length()+1);
264                         }
265         
266                         report.setCandidate(candidateSeq);
267         
268                         Sequence temp = templateDB->findClosestSequence(candidateSeq);
269
270                         Sequence* templateSeq = &temp;
271
272                         report.setTemplate(templateSeq);
273                         report.setSearchParameters(search, templateDB->getSearchScore());
274                                 
275                         Nast nast(alignment, candidateSeq, templateSeq);
276
277                         report.setAlignmentParameters(align, alignment);
278         
279                         report.setNastParameters(nast);
280         
281                         alignmentFile << '>' << candidateSeq->getName() << '\n' << candidateSeq->getAligned() << endl;
282                                 
283                         report.print();
284                         
285                         delete candidateSeq;
286                 
287                 }
288                 
289                 alignmentFile.close();
290                 inFASTA.close();
291                 
292                 return 1;
293         }
294         catch(exception& e) {
295                 errorOut(e, "AlignCommand", "driver");
296                 exit(1);
297         }
298 }
299
300 /**************************************************************************************************/
301
302 void AlignCommand::createProcesses(string alignFileName, string reportFileName) {
303         try {
304 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
305                 int process = 0;
306                 //              processIDS.resize(0);
307                 
308                 //loop through and create all the processes you want
309                 while (process != processors) {
310                         int pid = fork();
311                         
312                         if (pid > 0) {
313                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
314                                 process++;
315                         }else if (pid == 0){
316                                 driver(lines[process], alignFileName + toString(getpid()) + ".temp", reportFileName + toString(getpid()) + ".temp");
317                                 exit(0);
318                         }else { mothurOut("unable to spawn the necessary processes."); mothurOutEndLine(); exit(0); }
319                 }
320                 
321                 //force parent to wait until all the processes are done
322                 for (int i=0;i<processors;i++) { 
323                         int temp = processIDS[i];
324                         wait(&temp);
325                 }
326 #endif          
327         }
328         catch(exception& e) {
329                 errorOut(e, "AlignCommand", "createProcesses");
330                 exit(1);
331         }
332 }
333
334 /**************************************************************************************************/
335
336 void AlignCommand::appendAlignFiles(string temp, string filename) {
337         try{
338                 
339                 ofstream output;
340                 ifstream input;
341                 openOutputFileAppend(filename, output);
342                 openInputFile(temp, input);
343                 
344                 while(char c = input.get()){
345                         if(input.eof())         {       break;                  }
346                         else                            {       output << c;    }
347                 }
348                 
349                 input.close();
350                 output.close();
351         }
352         catch(exception& e) {
353                 errorOut(e, "AlignCommand", "appendAlignFiles");
354                 exit(1);
355         }
356 }
357
358 /**************************************************************************************************/
359
360 void AlignCommand::appendReportFiles(string temp, string filename) {
361         try{
362                 
363                 ofstream output;
364                 ifstream input;
365                 openOutputFileAppend(filename, output);
366                 openInputFile(temp, input);
367
368                 while (!input.eof())    {       char c = input.get(); if (c == 10 || c == 13){  break;  }       } // get header line
369                                 
370                 while(char c = input.get()){
371                         if(input.eof())         {       break;                  }
372                         else                            {       output << c;    }
373                 }
374                 
375                 input.close();
376                 output.close();
377         }
378         catch(exception& e) {
379                 errorOut(e, "AlignCommand", "appendReportFiles");
380                 exit(1);
381         }
382 }
383
384 //**********************************************************************************************************************