]> git.donarmstrong.com Git - mothur.git/blob - aligncommand.cpp
1.9
[mothur.git] / aligncommand.cpp
1 /*\r
2  *  aligncommand.cpp\r
3  *  Mothur\r
4  *\r
5  *  Created by Sarah Westcott on 5/15/09.\r
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.\r
7  *\r
8  *      This version of nast does everything I think that the greengenes nast server does and then some.  I have added the \r
9  *      feature of allowing users to define their database, kmer size for searching, alignment penalty values and alignment \r
10  *      method.  This latter feature is perhaps most significant.  nastPlus enables a user to use either a Needleman-Wunsch \r
11  *      (non-affine gap penalty) or Gotoh (affine gap penalty) pairwise alignment algorithm.  This is significant because it\r
12  *      allows for a global alignment and not the local alignment provided by bLAst.  Furthermore, it has the potential to\r
13  *      provide a better alignment because of the banding method employed by blast (I'm not sure about this).\r
14  *\r
15  */\r
16 \r
17 #include "aligncommand.h"\r
18 #include "sequence.hpp"\r
19 \r
20 #include "gotohoverlap.hpp"\r
21 #include "needlemanoverlap.hpp"\r
22 #include "blastalign.hpp"\r
23 #include "noalign.hpp"\r
24 \r
25 #include "nast.hpp"\r
26 #include "nastreport.hpp"\r
27 \r
28 \r
29 //**********************************************************************************************************************\r
30 \r
31 AlignCommand::AlignCommand(string option)  {\r
32         try {\r
33                 \r
34                 abort = false;\r
35         \r
36                 //allow user to run help\r
37                 if(option == "help") { help(); abort = true; }\r
38                 \r
39                 else {\r
40                         \r
41                         //valid paramters for this command\r
42                         string AlignArray[] =  {"template","candidate","search","ksize","align","match","mismatch","gapopen","gapextend", "processors","flip","threshold","outputdir","inputdir"};\r
43                         vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));\r
44                         \r
45                         OptionParser parser(option);\r
46                         map<string, string> parameters = parser.getParameters(); \r
47                         \r
48                         ValidParameters validParameter;\r
49                         map<string, string>::iterator it;\r
50                         \r
51                         //check to make sure all parameters are valid for command\r
52                         for (it = parameters.begin(); it != parameters.end(); it++) { \r
53                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }\r
54                         }\r
55 \r
56                         //if the user changes the output directory command factory will send this info to us in the output parameter \r
57                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }\r
58                         \r
59 \r
60                         //if the user changes the input directory command factory will send this info to us in the output parameter \r
61                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              \r
62                         \r
63                         if (inputDir == "not found"){   inputDir = "";          }\r
64                         else {\r
65                                 string path;\r
66 \r
67                                 it = parameters.find("template");\r
68 \r
69                                 //user has given a template file\r
70                                 if(it != parameters.end()){ \r
71                                         path = hasPath(it->second);\r
72                                         //if the user has not given a path then, add inputdir. else leave path alone.\r
73                                         if (path == "") {       parameters["template"] = inputDir + it->second;         }\r
74                                 }\r
75                         }\r
76 \r
77                         //check for required parameters\r
78                         templateFileName = validParameter.validFile(parameters, "template", true);\r
79                         \r
80                         if (templateFileName == "not found") { \r
81                                 m->mothurOut("template is a required parameter for the align.seqs command."); \r
82                                 m->mothurOutEndLine();\r
83                                 abort = true; \r
84                         }else if (templateFileName == "not open") { abort = true; }     \r
85                         \r
86                         candidateFileName = validParameter.validFile(parameters, "candidate", false);\r
87                         if (candidateFileName == "not found") { m->mothurOut("candidate is a required parameter for the align.seqs command."); m->mothurOutEndLine(); abort = true;  }\r
88                         else { \r
89                                 splitAtDash(candidateFileName, candidateFileNames);\r
90                                 \r
91                                 //go through files and make sure they are good, if not, then disregard them\r
92                                 for (int i = 0; i < candidateFileNames.size(); i++) {\r
93                                         if (inputDir != "") {\r
94                                                 string path = hasPath(candidateFileNames[i]);\r
95                                                 //if the user has not given a path then, add inputdir. else leave path alone.\r
96                                                 if (path == "") {       candidateFileNames[i] = inputDir + candidateFileNames[i];               }\r
97                                         }\r
98         \r
99                                         int ableToOpen;\r
100                                         ifstream in;\r
101                                         \r
102                                         #ifdef USE_MPI  \r
103                                                 int pid;\r
104                                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running\r
105                                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are\r
106                                 \r
107                                                 if (pid == 0) {\r
108                                         #endif\r
109 \r
110                                         ableToOpen = openInputFile(candidateFileNames[i], in);\r
111                                         in.close();\r
112                                         \r
113                                         #ifdef USE_MPI  \r
114                                                         for (int j = 1; j < processors; j++) {\r
115                                                                 MPI_Send(&ableToOpen, 1, MPI_INT, j, 2001, MPI_COMM_WORLD); \r
116                                                         }\r
117                                                 }else{\r
118                                                         MPI_Status status;\r
119                                                         MPI_Recv(&ableToOpen, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);\r
120                                                 }\r
121                                                 \r
122                                         #endif\r
123 \r
124                                         if (ableToOpen == 1) { \r
125                                                 m->mothurOut(candidateFileNames[i] + " will be disregarded."); m->mothurOutEndLine(); \r
126                                                 //erase from file list\r
127                                                 candidateFileNames.erase(candidateFileNames.begin()+i);\r
128                                                 i--;\r
129                                         }\r
130                                         \r
131                                 }\r
132                                 \r
133                                 //make sure there is at least one valid file left\r
134                                 if (candidateFileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }\r
135                         }\r
136                 \r
137                         //check for optional parameter and set defaults\r
138                         // ...at some point should added some additional type checking...\r
139                         string temp;\r
140                         temp = validParameter.validFile(parameters, "ksize", false);            if (temp == "not found"){       temp = "8";                             }\r
141                         convert(temp, kmerSize); \r
142                         \r
143                         temp = validParameter.validFile(parameters, "match", false);            if (temp == "not found"){       temp = "1.0";                   }\r
144                         convert(temp, match);  \r
145                         \r
146                         temp = validParameter.validFile(parameters, "mismatch", false);         if (temp == "not found"){       temp = "-1.0";                  }\r
147                         convert(temp, misMatch);  \r
148                         \r
149                         temp = validParameter.validFile(parameters, "gapopen", false);          if (temp == "not found"){       temp = "-2.0";                  }\r
150                         convert(temp, gapOpen);  \r
151                         \r
152                         temp = validParameter.validFile(parameters, "gapextend", false);        if (temp == "not found"){       temp = "-1.0";                  }\r
153                         convert(temp, gapExtend); \r
154                         \r
155                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = "1";                             }\r
156                         convert(temp, processors); \r
157                         \r
158                         temp = validParameter.validFile(parameters, "flip", false);                     if (temp == "not found"){       temp = "f";                             }\r
159                         flip = isTrue(temp); \r
160                         \r
161                         temp = validParameter.validFile(parameters, "threshold", false);        if (temp == "not found"){       temp = "0.50";                  }\r
162                         convert(temp, threshold); \r
163                         \r
164                         search = validParameter.validFile(parameters, "search", false);         if (search == "not found"){     search = "kmer";                }\r
165                         \r
166                         align = validParameter.validFile(parameters, "align", false);           if (align == "not found"){      align = "needleman";    }\r
167                 }\r
168                 \r
169         }\r
170         catch(exception& e) {\r
171                 m->errorOut(e, "AlignCommand", "AlignCommand");\r
172                 exit(1);\r
173         }\r
174 }\r
175 \r
176 //**********************************************************************************************************************\r
177 \r
178 AlignCommand::~AlignCommand(){  \r
179 \r
180         if (abort == false) {\r
181                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();\r
182                 delete templateDB;\r
183                 delete alignment;\r
184         }\r
185 }\r
186 \r
187 //**********************************************************************************************************************\r
188 \r
189 void AlignCommand::help(){\r
190         try {\r
191                 m->mothurOut("The align.seqs command reads a file containing sequences and creates an alignment file and a report file.\n");\r
192                 m->mothurOut("The align.seqs command parameters are template, candidate, search, ksize, align, match, mismatch, gapopen and gapextend.\n");\r
193                 m->mothurOut("The template and candidate parameters are required. You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amzon.fasta \n");\r
194                 m->mothurOut("The search parameter allows you to specify the method to find most similar template.  Your options are: suffix, kmer and blast. The default is kmer.\n");\r
195                 m->mothurOut("The align parameter allows you to specify the alignment method to use.  Your options are: gotoh, needleman, blast and noalign. The default is needleman.\n");\r
196                 m->mothurOut("The ksize parameter allows you to specify the kmer size for finding most similar template to candidate.  The default is 8.\n");\r
197                 m->mothurOut("The match parameter allows you to specify the bonus for having the same base. The default is 1.0.\n");\r
198                 m->mothurOut("The mistmatch parameter allows you to specify the penalty for having different bases.  The default is -1.0.\n");\r
199                 m->mothurOut("The gapopen parameter allows you to specify the penalty for opening a gap in an alignment. The default is -2.0.\n");\r
200                 m->mothurOut("The gapextend parameter allows you to specify the penalty for extending a gap in an alignment.  The default is -1.0.\n");\r
201                 m->mothurOut("The flip parameter is used to specify whether or not you want mothur to try the reverse complement if a sequence falls below the threshold.  The default is false.\n");\r
202                 m->mothurOut("The threshold is used to specify a cutoff at which an alignment is deemed 'bad' and the reverse complement may be tried. The default threshold is 0.50, meaning 50% of the bases are removed in the alignment.\n");\r
203                 m->mothurOut("If the flip parameter is set to true the reverse complement of the sequence is aligned and the better alignment is reported.\n");\r
204                 m->mothurOut("The default for the threshold parameter is 0.50, meaning at least 50% of the bases must remain or the sequence is reported as potentially reversed.\n");\r
205                 m->mothurOut("The align.seqs command should be in the following format: \n");\r
206                 m->mothurOut("align.seqs(template=yourTemplateFile, candidate=yourCandidateFile, align=yourAlignmentMethod, search=yourSearchmethod, ksize=yourKmerSize, match=yourMatchBonus, mismatch=yourMismatchpenalty, gapopen=yourGapopenPenalty, gapextend=yourGapExtendPenalty) \n");\r
207                 m->mothurOut("Example align.seqs(candidate=candidate.fasta, template=core.filtered, align=kmer, search=gotoh, ksize=8, match=2.0, mismatch=3.0, gapopen=-2.0, gapextend=-1.0)\n");\r
208                 m->mothurOut("Note: No spaces between parameter labels (i.e. candidate), '=' and parameters (i.e.yourFastaFile).\n\n");\r
209         }\r
210         catch(exception& e) {\r
211                 m->errorOut(e, "AlignCommand", "help");\r
212                 exit(1);\r
213         }\r
214 }\r
215 \r
216 \r
217 //**********************************************************************************************************************\r
218 \r
219 int AlignCommand::execute(){\r
220         try {\r
221                 if (abort == true) {    return 0;       }\r
222 \r
223                 templateDB = new AlignmentDB(templateFileName, search, kmerSize, gapOpen, gapExtend, match, misMatch);\r
224                 int longestBase = templateDB->getLongestBase();\r
225                 \r
226                 if(align == "gotoh")                    {       alignment = new GotohOverlap(gapOpen, gapExtend, match, misMatch, longestBase);                 }\r
227                 else if(align == "needleman")   {       alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);                                }\r
228                 else if(align == "blast")               {       alignment = new BlastAlignment(gapOpen, gapExtend, match, misMatch);            }\r
229                 else if(align == "noalign")             {       alignment = new NoAlign();                                                                                                      }\r
230                 else {\r
231                         m->mothurOut(align + " is not a valid alignment option. I will run the command using needleman.");\r
232                         m->mothurOutEndLine();\r
233                         alignment = new NeedlemanOverlap(gapOpen, match, misMatch, longestBase);\r
234                 }\r
235                 vector<string> outputNames;\r
236                 \r
237                 for (int s = 0; s < candidateFileNames.size(); s++) {\r
238                         if (m->control_pressed) { return 0; }\r
239                         \r
240                         m->mothurOut("Aligning sequences from " + candidateFileNames[s] + " ..." ); m->mothurOutEndLine();\r
241                         \r
242                         if (outputDir == "") {  outputDir += hasPath(candidateFileNames[s]); }\r
243                         string alignFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "align";\r
244                         string reportFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "align.report";\r
245                         string accnosFileName = outputDir + getRootName(getSimpleName(candidateFileNames[s])) + "flip.accnos";\r
246                         bool hasAccnos = true;\r
247                         \r
248                         int numFastaSeqs = 0;\r
249                         for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();\r
250                         int start = time(NULL);\r
251                 \r
252 #ifdef USE_MPI  \r
253                                 int pid, end, numSeqsPerProcessor; \r
254                                 int tag = 2001;\r
255                                 vector<long> MPIPos;\r
256                                 MPIWroteAccnos = false;\r
257                                 \r
258                                 MPI_Status status; \r
259                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are\r
260                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); \r
261 \r
262                                 MPI_File inMPI;\r
263                                 MPI_File outMPIAlign;\r
264                                 MPI_File outMPIReport;\r
265                                 MPI_File outMPIAccnos;\r
266                                 \r
267                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; \r
268                                 int inMode=MPI_MODE_RDONLY; \r
269                                 \r
270                                 char* outAlignFilename = new char[alignFileName.length()];\r
271                                 memcpy(outAlignFilename, alignFileName.c_str(), alignFileName.length());\r
272 \r
273                                 char* outReportFilename = new char[reportFileName.length()];\r
274                                 memcpy(outReportFilename, reportFileName.c_str(), reportFileName.length());\r
275 \r
276                                 char* outAccnosFilename = new char[accnosFileName.length()];\r
277                                 memcpy(outAccnosFilename, accnosFileName.c_str(), accnosFileName.length());\r
278 \r
279                                 char* inFileName = new char[candidateFileNames[s].length()];\r
280                                 memcpy(inFileName, candidateFileNames[s].c_str(), candidateFileNames[s].length());\r
281 \r
282                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer\r
283                                 MPI_File_open(MPI_COMM_WORLD, outAlignFilename, outMode, MPI_INFO_NULL, &outMPIAlign);\r
284                                 MPI_File_open(MPI_COMM_WORLD, outReportFilename, outMode, MPI_INFO_NULL, &outMPIReport);\r
285                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);\r
286                                 \r
287                                 delete outAlignFilename;\r
288                                 delete inFileName;\r
289                                 delete outReportFilename;\r
290                                 delete outAccnosFilename;\r
291 \r
292                                 if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); return 0; }\r
293                                 \r
294                                 if (pid == 0) { //you are the root process \r
295                                         \r
296                                         MPIPos = setFilePosFasta(candidateFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs\r
297                                         \r
298                                         //send file positions to all processes\r
299                                         MPI_Bcast(&numFastaSeqs, 1, MPI_INT, 0, MPI_COMM_WORLD);  //send numSeqs\r
300                                         MPI_Bcast(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, MPI_COMM_WORLD); //send file pos   \r
301                                         \r
302                                         //figure out how many sequences you have to align\r
303                                         numSeqsPerProcessor = numFastaSeqs / processors;\r
304                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }\r
305                                         int startIndex =  pid * numSeqsPerProcessor;\r
306                                 \r
307                                         //align your part\r
308                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);\r
309                                         \r
310                                         if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); return 0; }\r
311 \r
312                                         for (int i = 1; i < processors; i++) {\r
313                                                 bool tempResult;\r
314                                                 MPI_Recv(&tempResult, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);\r
315                                                 if (tempResult != 0) { MPIWroteAccnos = true; }\r
316                                         }\r
317                                 }else{ //you are a child process\r
318                                         MPI_Bcast(&numFastaSeqs, 1, MPI_INT, 0, MPI_COMM_WORLD); //get numSeqs\r
319                                         MPIPos.resize(numFastaSeqs+1);\r
320                                         MPI_Bcast(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, MPI_COMM_WORLD); //get file positions\r
321                                         \r
322                                         //figure out how many sequences you have to align\r
323                                         numSeqsPerProcessor = numFastaSeqs / processors;\r
324                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }\r
325                                         int startIndex =  pid * numSeqsPerProcessor;\r
326                                         \r
327                                         //align your part\r
328                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);\r
329                                         \r
330                                         if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); return 0; }\r
331 \r
332                                         MPI_Send(&MPIWroteAccnos, 1, MPI_INT, 0, tag, MPI_COMM_WORLD); \r
333                                 }\r
334                                 \r
335                                 //close files \r
336                                 MPI_File_close(&inMPI);\r
337                                 MPI_File_close(&outMPIAlign);\r
338                                 MPI_File_close(&outMPIReport);\r
339                                 MPI_File_close(&outMPIAccnos);\r
340                                 \r
341                                 //delete accnos file if blank\r
342                                 if (pid == 0) {\r
343                                         //delete accnos file if its blank else report to user\r
344                                         if (MPIWroteAccnos) { \r
345                                                 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");\r
346                                                 if (!flip) {\r
347                                                         m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); \r
348                                                 }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }\r
349                                                 m->mothurOutEndLine();\r
350                                         }else { \r
351                                                 //MPI_Info info;\r
352                                                 //MPI_File_delete(outAccnosFilename, info);\r
353                                                 hasAccnos = false;      \r
354                                                 remove(accnosFileName.c_str()); \r
355                                         }\r
356                                 }\r
357                                 \r
358 #else\r
359                         \r
360         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)\r
361                         if(processors == 1){\r
362                                 ifstream inFASTA;\r
363                                 openInputFile(candidateFileNames[s], inFASTA);\r
364                                 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');\r
365                                 inFASTA.close();\r
366                                 \r
367                                 lines.push_back(new linePair(0, numFastaSeqs));\r
368                                 \r
369                                 driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);\r
370                                 \r
371                                 if (m->control_pressed) { \r
372                                         remove(accnosFileName.c_str()); \r
373                                         remove(alignFileName.c_str()); \r
374                                         remove(reportFileName.c_str()); \r
375                                         return 0; \r
376                                 }\r
377                                 \r
378                                 //delete accnos file if its blank else report to user\r
379                                 if (isBlank(accnosFileName)) {  remove(accnosFileName.c_str());  hasAccnos = false; }\r
380                                 else { \r
381                                         m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");\r
382                                         if (!flip) {\r
383                                                 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); \r
384                                         }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }\r
385                                         m->mothurOutEndLine();\r
386                                 }\r
387                         }\r
388                         else{\r
389                                 vector<int> positions;\r
390                                 processIDS.resize(0);\r
391                                 \r
392                                 ifstream inFASTA;\r
393                                 openInputFile(candidateFileNames[s], inFASTA);\r
394                                 \r
395                                 string input;\r
396                                 while(!inFASTA.eof()){\r
397                                         input = getline(inFASTA);\r
398                                         if (input.length() != 0) {\r
399                                                 if(input[0] == '>'){    long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);  }\r
400                                         }\r
401                                 }\r
402                                 inFASTA.close();\r
403                                 \r
404                                 numFastaSeqs = positions.size();\r
405                                 \r
406                                 int numSeqsPerProcessor = numFastaSeqs / processors;\r
407                                 \r
408                                 for (int i = 0; i < processors; i++) {\r
409                                         long int startPos = positions[ i * numSeqsPerProcessor ];\r
410                                         if(i == processors - 1){\r
411                                                 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;\r
412                                         }\r
413                                         lines.push_back(new linePair(startPos, numSeqsPerProcessor));\r
414                                 }\r
415                                 \r
416                                 createProcesses(alignFileName, reportFileName, accnosFileName, candidateFileNames[s]); \r
417                                 \r
418                                 rename((alignFileName + toString(processIDS[0]) + ".temp").c_str(), alignFileName.c_str());\r
419                                 rename((reportFileName + toString(processIDS[0]) + ".temp").c_str(), reportFileName.c_str());\r
420                                 \r
421                                 //append alignment and report files\r
422                                 for(int i=1;i<processors;i++){\r
423                                         appendAlignFiles((alignFileName + toString(processIDS[i]) + ".temp"), alignFileName);\r
424                                         remove((alignFileName + toString(processIDS[i]) + ".temp").c_str());\r
425                                         \r
426                                         appendReportFiles((reportFileName + toString(processIDS[i]) + ".temp"), reportFileName);\r
427                                         remove((reportFileName + toString(processIDS[i]) + ".temp").c_str());\r
428                                 }\r
429                                 \r
430                                 vector<string> nonBlankAccnosFiles;\r
431                                 //delete blank accnos files generated with multiple processes\r
432                                 for(int i=0;i<processors;i++){  \r
433                                         if (!(isBlank(accnosFileName + toString(processIDS[i]) + ".temp"))) {\r
434                                                 nonBlankAccnosFiles.push_back(accnosFileName + toString(processIDS[i]) + ".temp");\r
435                                         }else { remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());  }\r
436                                 }\r
437                                 \r
438                                 //append accnos files\r
439                                 if (nonBlankAccnosFiles.size() != 0) { \r
440                                         rename(nonBlankAccnosFiles[0].c_str(), accnosFileName.c_str());\r
441                                         \r
442                                         for (int h=1; h < nonBlankAccnosFiles.size(); h++) {\r
443                                                 appendAlignFiles(nonBlankAccnosFiles[h], accnosFileName);\r
444                                                 remove(nonBlankAccnosFiles[h].c_str());\r
445                                         }\r
446                                         m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");\r
447                                         if (!flip) {\r
448                                                 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); \r
449                                         }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }\r
450                                         m->mothurOutEndLine();\r
451                                 }else{ hasAccnos = false;  }\r
452                                 \r
453                                 if (m->control_pressed) { \r
454                                         remove(accnosFileName.c_str()); \r
455                                         remove(alignFileName.c_str()); \r
456                                         remove(reportFileName.c_str()); \r
457                                         return 0; \r
458                                 }\r
459                         }\r
460         #else\r
461                         ifstream inFASTA;\r
462                         openInputFile(candidateFileNames[s], inFASTA);\r
463                         numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');\r
464                         inFASTA.close();\r
465                         \r
466                         lines.push_back(new linePair(0, numFastaSeqs));\r
467                         \r
468                         driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);\r
469                         \r
470                         if (m->control_pressed) { \r
471                                 remove(accnosFileName.c_str()); \r
472                                 remove(alignFileName.c_str()); \r
473                                 remove(reportFileName.c_str()); \r
474                                 return 0; \r
475                         }\r
476                         \r
477                         //delete accnos file if its blank else report to user\r
478                         if (isBlank(accnosFileName)) {  remove(accnosFileName.c_str());  hasAccnos = false; }\r
479                         else { \r
480                                 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");\r
481                                 if (!flip) {\r
482                                         m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); \r
483                                 }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }\r
484                                 m->mothurOutEndLine();\r
485                         }\r
486                         \r
487         #endif\r
488 \r
489 #endif          \r
490 \r
491 \r
492                 #ifdef USE_MPI\r
493                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); \r
494                                         \r
495                         if (pid == 0) { //only one process should output to screen\r
496                 #endif\r
497 \r
498                         outputNames.push_back(alignFileName);\r
499                         outputNames.push_back(reportFileName);\r
500                         if (hasAccnos)  {       outputNames.push_back(accnosFileName);          }\r
501                         \r
502                 #ifdef USE_MPI\r
503                         }\r
504                 #endif\r
505 \r
506                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to align " + toString(numFastaSeqs) + " sequences.");\r
507                         m->mothurOutEndLine();\r
508                         m->mothurOutEndLine();\r
509                 }\r
510                 \r
511                 \r
512                 m->mothurOutEndLine();\r
513                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();\r
514                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }\r
515                 m->mothurOutEndLine();\r
516 \r
517                 return 0;\r
518         }\r
519         catch(exception& e) {\r
520                 m->errorOut(e, "AlignCommand", "execute");\r
521                 exit(1);\r
522         }\r
523 }\r
524 \r
525 //**********************************************************************************************************************\r
526 \r
527 int AlignCommand::driver(linePair* line, string alignFName, string reportFName, string accnosFName, string filename){\r
528         try {\r
529                 ofstream alignmentFile;\r
530                 openOutputFile(alignFName, alignmentFile);\r
531                 \r
532                 ofstream accnosFile;\r
533                 openOutputFile(accnosFName, accnosFile);\r
534                 \r
535                 NastReport report(reportFName);\r
536                 \r
537                 ifstream inFASTA;\r
538                 openInputFile(filename, inFASTA);\r
539 \r
540                 inFASTA.seekg(line->start);\r
541         \r
542                 for(int i=0;i<line->numSeqs;i++){\r
543                         \r
544                         if (m->control_pressed) {  return 0; }\r
545                         \r
546                         Sequence* candidateSeq = new Sequence(inFASTA);  gobble(inFASTA);\r
547         \r
548                         int origNumBases = candidateSeq->getNumBases();\r
549                         string originalUnaligned = candidateSeq->getUnaligned();\r
550                         int numBasesNeeded = origNumBases * threshold;\r
551         \r
552                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file\r
553                                 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {\r
554                                         alignment->resize(candidateSeq->getUnaligned().length()+1);\r
555                                 }\r
556                                                                 \r
557                                 Sequence temp = templateDB->findClosestSequence(candidateSeq);\r
558                                 Sequence* templateSeq = &temp;\r
559                                 \r
560                                 float searchScore = templateDB->getSearchScore();\r
561                                                                 \r
562                                 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);\r
563                                 Sequence* copy;\r
564                                 \r
565                                 Nast* nast2;\r
566                                 bool needToDeleteCopy = false;  //this is needed in case you have you enter the ifs below\r
567                                                                                                 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below\r
568                                                                                                 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place\r
569                                                                                                 //so this bool tells you if you need to delete it\r
570                                                                                                 \r
571                                 //if there is a possibility that this sequence should be reversed\r
572                                 if (candidateSeq->getNumBases() < numBasesNeeded) {\r
573                                         \r
574                                         string wasBetter = "";\r
575                                         //if the user wants you to try the reverse\r
576                                         if (flip) {\r
577                                                 //get reverse compliment\r
578                                                 copy = new Sequence(candidateSeq->getName(), originalUnaligned);\r
579                                                 copy->reverseComplement();\r
580                                                 \r
581                                                 //rerun alignment\r
582                                                 Sequence temp2 = templateDB->findClosestSequence(copy);\r
583                                                 Sequence* templateSeq2 = &temp2;\r
584                                                 \r
585                                                 searchScore = templateDB->getSearchScore();\r
586                                                 \r
587                                                 nast2 = new Nast(alignment, copy, templateSeq2);\r
588                         \r
589                                                 //check if any better\r
590                                                 if (copy->getNumBases() > candidateSeq->getNumBases()) {\r
591                                                         candidateSeq->setAligned(copy->getAligned());  //use reverse compliments alignment since its better\r
592                                                         templateSeq = templateSeq2; \r
593                                                         delete nast;\r
594                                                         nast = nast2;\r
595                                                         needToDeleteCopy = true;\r
596                                                 }else{  \r
597                                                         wasBetter = "\treverse complement did NOT produce a better alignment, please check sequence.";\r
598                                                         delete nast2;\r
599                                                         delete copy;    \r
600                                                 }\r
601                                         }\r
602                                         \r
603                                         //create accnos file with names\r
604                                         accnosFile << candidateSeq->getName() << wasBetter << endl;\r
605                                 }\r
606                                 \r
607                                 report.setCandidate(candidateSeq);\r
608                                 report.setTemplate(templateSeq);\r
609                                 report.setSearchParameters(search, searchScore);\r
610                                 report.setAlignmentParameters(align, alignment);\r
611                                 report.setNastParameters(*nast);\r
612         \r
613                                 alignmentFile << '>' << candidateSeq->getName() << '\n' << candidateSeq->getAligned() << endl;\r
614                                 \r
615                                 report.print();\r
616                                 delete nast;\r
617                                 if (needToDeleteCopy) {   delete copy;   }\r
618                         }\r
619                         delete candidateSeq;\r
620                         \r
621                         //report progress\r
622                         if((i+1) % 100 == 0){   m->mothurOut(toString(i+1)); m->mothurOutEndLine();             }\r
623                 }\r
624                 //report progress\r
625                 if((line->numSeqs) % 100 != 0){ m->mothurOut(toString(line->numSeqs)); m->mothurOutEndLine();           }\r
626                 \r
627                 alignmentFile.close();\r
628                 inFASTA.close();\r
629                 accnosFile.close();\r
630                 \r
631                 return 1;\r
632         }\r
633         catch(exception& e) {\r
634                 m->errorOut(e, "AlignCommand", "driver");\r
635                 exit(1);\r
636         }\r
637 }\r
638 //**********************************************************************************************************************\r
639 #ifdef USE_MPI\r
640 int AlignCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& alignFile, MPI_File& reportFile, MPI_File& accnosFile, vector<long>& MPIPos){\r
641         try {\r
642                 string outputString = "";\r
643                 MPI_Status statusReport; \r
644                 MPI_Status statusAlign; \r
645                 MPI_Status statusAccnos; \r
646                 MPI_Status status; \r
647                 int pid;\r
648                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are\r
649         \r
650                 NastReport report;\r
651                 \r
652                 if (pid == 0) {\r
653                         outputString = report.getHeaders();\r
654                         int length = outputString.length();\r
655             \r
656                         char* buf = new char[length];\r
657                         memcpy(buf, outputString.c_str(), length);\r
658                 \r
659                         MPI_File_write_shared(reportFile, buf, length, MPI_CHAR, &statusReport);\r
660 \r
661             delete buf;\r
662                 }\r
663                 \r
664                 for(int i=0;i<num;i++){\r
665                 \r
666                         if (m->control_pressed) {  return 0; }\r
667 \r
668                         //read next sequence\r
669                         int length = MPIPos[start+i+1] - MPIPos[start+i];\r
670 \r
671                         char* buf4 = new char[length];\r
672                         memcpy(buf4, outputString.c_str(), length);\r
673 \r
674                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);\r
675                         \r
676                         string tempBuf = buf4;\r
677 \r
678                         delete buf4;\r
679 \r
680                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }\r
681                         istringstream iss (tempBuf,istringstream::in);\r
682         \r
683                         Sequence* candidateSeq = new Sequence(iss);  \r
684                         int origNumBases = candidateSeq->getNumBases();\r
685                         string originalUnaligned = candidateSeq->getUnaligned();\r
686                         int numBasesNeeded = origNumBases * threshold;\r
687         \r
688                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file\r
689                                 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {\r
690                                         alignment->resize(candidateSeq->getUnaligned().length()+1);\r
691                                 }\r
692                                                                 \r
693                                 Sequence temp = templateDB->findClosestSequence(candidateSeq);\r
694                                 Sequence* templateSeq = &temp;\r
695                                 \r
696                                 float searchScore = templateDB->getSearchScore();\r
697                                                                 \r
698                                 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);\r
699                                 Sequence* copy;\r
700                                 \r
701                                 Nast* nast2;\r
702                                 bool needToDeleteCopy = false;  //this is needed in case you have you enter the ifs below\r
703                                                                                                 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below\r
704                                                                                                 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place\r
705                                                                                                 //so this bool tells you if you need to delete it\r
706                                                                                                 \r
707                                 //if there is a possibility that this sequence should be reversed\r
708                                 if (candidateSeq->getNumBases() < numBasesNeeded) {\r
709                                         \r
710                                         string wasBetter = "";\r
711                                         //if the user wants you to try the reverse\r
712                                         if (flip) {\r
713                                                 //get reverse compliment\r
714                                                 copy = new Sequence(candidateSeq->getName(), originalUnaligned);\r
715                                                 copy->reverseComplement();\r
716                                                 \r
717                                                 //rerun alignment\r
718                                                 Sequence temp2 = templateDB->findClosestSequence(copy);\r
719                                                 Sequence* templateSeq2 = &temp2;\r
720                                                 \r
721                                                 searchScore = templateDB->getSearchScore();\r
722                                                 \r
723                                                 nast2 = new Nast(alignment, copy, templateSeq2);\r
724                         \r
725                                                 //check if any better\r
726                                                 if (copy->getNumBases() > candidateSeq->getNumBases()) {\r
727                                                         candidateSeq->setAligned(copy->getAligned());  //use reverse compliments alignment since its better\r
728                                                         templateSeq = templateSeq2; \r
729                                                         delete nast;\r
730                                                         nast = nast2;\r
731                                                         needToDeleteCopy = true;\r
732                                                 }else{  \r
733                                                         wasBetter = "\treverse complement did NOT produce a better alignment, please check sequence.";\r
734                                                         delete nast2;\r
735                                                         delete copy;    \r
736                                                 }\r
737                                         }\r
738                                         \r
739                                         //create accnos file with names\r
740                                         outputString = candidateSeq->getName() + wasBetter + "\n";\r
741                                         \r
742                                         //send results to parent\r
743                                         int length = outputString.length();\r
744 \r
745                                         char* buf = new char[length];\r
746                                         memcpy(buf, outputString.c_str(), length);\r
747                                 \r
748                                         MPI_File_write_shared(accnosFile, buf, length, MPI_CHAR, &statusAccnos);\r
749                                         delete buf;\r
750                                         MPIWroteAccnos = true;\r
751                                 }\r
752                                 \r
753                                 report.setCandidate(candidateSeq);\r
754                                 report.setTemplate(templateSeq);\r
755                                 report.setSearchParameters(search, searchScore);\r
756                                 report.setAlignmentParameters(align, alignment);\r
757                                 report.setNastParameters(*nast);\r
758         \r
759                                 outputString =  ">" + candidateSeq->getName() + "\n" + candidateSeq->getAligned() + "\n";\r
760                                 \r
761                                 //send results to parent\r
762                                 int length = outputString.length();\r
763                                 char* buf2 = new char[length];\r
764                                 memcpy(buf2, outputString.c_str(), length);\r
765                                 \r
766                                 MPI_File_write_shared(alignFile, buf2, length, MPI_CHAR, &statusAlign);\r
767                                 \r
768                                 delete buf2;\r
769 \r
770                                 outputString = report.getReport();\r
771                                 \r
772                                 //send results to parent\r
773                                 length = outputString.length();\r
774                                 char* buf3 = new char[length];\r
775                                 memcpy(buf3, outputString.c_str(), length);\r
776                                 \r
777                                 MPI_File_write_shared(reportFile, buf3, length, MPI_CHAR, &statusReport);\r
778                                 \r
779                                 delete buf3;\r
780                                 delete nast;\r
781                                 if (needToDeleteCopy) {   delete copy;   }\r
782                         }\r
783                         delete candidateSeq;\r
784                         \r
785                         //report progress\r
786                         if((i+1) % 100 == 0){   cout << (toString(i+1)) << endl;                }\r
787                 }\r
788                 //report progress\r
789                 if((num) % 100 != 0){   cout << (toString(num)) << endl;                }\r
790                 \r
791                 return 1;\r
792         }\r
793         catch(exception& e) {\r
794                 m->errorOut(e, "AlignCommand", "driverMPI");\r
795                 exit(1);\r
796         }\r
797 }\r
798 #endif\r
799 /**************************************************************************************************/\r
800 \r
801 int AlignCommand::createProcesses(string alignFileName, string reportFileName, string accnosFName, string filename) {\r
802         try {\r
803 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)\r
804                 int process = 0;\r
805                 int exitCommand = 1;\r
806                 //              processIDS.resize(0);\r
807                 \r
808                 //loop through and create all the processes you want\r
809                 while (process != processors) {\r
810                         int pid = fork();\r
811                         \r
812                         if (pid > 0) {\r
813                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later\r
814                                 process++;\r
815                         }else if (pid == 0){\r
816                                 exitCommand = driver(lines[process], alignFileName + toString(getpid()) + ".temp", reportFileName + toString(getpid()) + ".temp", accnosFName + toString(getpid()) + ".temp", filename);\r
817                                 exit(0);\r
818                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }\r
819                 }\r
820                 \r
821                 //force parent to wait until all the processes are done\r
822                 for (int i=0;i<processors;i++) { \r
823                         int temp = processIDS[i];\r
824                         wait(&temp);\r
825                 }\r
826                 \r
827                 return exitCommand;\r
828 #endif          \r
829         }\r
830         catch(exception& e) {\r
831                 m->errorOut(e, "AlignCommand", "createProcesses");\r
832                 exit(1);\r
833         }\r
834 }\r
835 \r
836 /**************************************************************************************************/\r
837 \r
838 void AlignCommand::appendAlignFiles(string temp, string filename) {\r
839         try{\r
840                 \r
841                 ofstream output;\r
842                 ifstream input;\r
843                 openOutputFileAppend(filename, output);\r
844                 openInputFile(temp, input);\r
845                 \r
846                 while(char c = input.get()){\r
847                         if(input.eof())         {       break;                  }\r
848                         else                            {       output << c;    }\r
849                 }\r
850                 \r
851                 input.close();\r
852                 output.close();\r
853         }\r
854         catch(exception& e) {\r
855                 m->errorOut(e, "AlignCommand", "appendAlignFiles");\r
856                 exit(1);\r
857         }\r
858 }\r
859 //**********************************************************************************************************************\r
860 \r
861 void AlignCommand::appendReportFiles(string temp, string filename) {\r
862         try{\r
863                 \r
864                 ofstream output;\r
865                 ifstream input;\r
866                 openOutputFileAppend(filename, output);\r
867                 openInputFile(temp, input);\r
868 \r
869                 while (!input.eof())    {       char c = input.get(); if (c == 10 || c == 13){  break;  }       } // get header line\r
870                                 \r
871                 while(char c = input.get()){\r
872                         if(input.eof())         {       break;                  }\r
873                         else                            {       output << c;    }\r
874                 }\r
875                 \r
876                 input.close();\r
877                 output.close();\r
878         }\r
879         catch(exception& e) {\r
880                 m->errorOut(e, "AlignCommand", "appendReportFiles");\r
881                 exit(1);\r
882         }\r
883 }\r
884 //**********************************************************************************************************************\r