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