]> git.donarmstrong.com Git - mothur.git/blob - aligncommand.cpp
paralellized screen.seqs and added mpi code to it. fixed bug with all mpi commands...
[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 outAlignFilename[1024];\r
274                                 strcpy(outAlignFilename, alignFileName.c_str());\r
275 \r
276                                 //char* outReportFilename = new char[reportFileName.length()];\r
277                                 //memcpy(outReportFilename, reportFileName.c_str(), reportFileName.length());\r
278                                 \r
279                                 char outReportFilename[1024];\r
280                                 strcpy(outReportFilename, reportFileName.c_str());\r
281 \r
282                                 //char* outAccnosFilename = new char[accnosFileName.length()];\r
283                                 //memcpy(outAccnosFilename, accnosFileName.c_str(), accnosFileName.length());\r
284                                 \r
285                                 char outAccnosFilename[1024];\r
286                                 strcpy(outAccnosFilename, accnosFileName.c_str());\r
287 \r
288                                 //char* inFileName = new char[candidateFileNames[s].length()];\r
289                                 //memcpy(inFileName, candidateFileNames[s].c_str(), candidateFileNames[s].length());\r
290                                 \r
291                                 char inFileName[1024];\r
292                                 strcpy(inFileName, candidateFileNames[s].c_str());\r
293                                 \r
294                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer\r
295                                 MPI_File_open(MPI_COMM_WORLD, outAlignFilename, outMode, MPI_INFO_NULL, &outMPIAlign);\r
296                                 MPI_File_open(MPI_COMM_WORLD, outReportFilename, outMode, MPI_INFO_NULL, &outMPIReport);\r
297                                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);\r
298                                 \r
299                                 if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); return 0; }\r
300                                 \r
301                                 if (pid == 0) { //you are the root process \r
302                                         \r
303                                         MPIPos = setFilePosFasta(candidateFileNames[s], numFastaSeqs); //fills MPIPos, returns numSeqs\r
304                                         \r
305                                         //send file positions to all processes\r
306                                         MPI_Bcast(&numFastaSeqs, 1, MPI_INT, 0, MPI_COMM_WORLD);  //send numSeqs\r
307                                         MPI_Bcast(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, MPI_COMM_WORLD); //send file pos   \r
308                                         \r
309                                         //figure out how many sequences you have to align\r
310                                         numSeqsPerProcessor = numFastaSeqs / processors;\r
311                                         int startIndex =  pid * numSeqsPerProcessor;\r
312                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }\r
313                                         \r
314                                 \r
315                                         //align your part\r
316                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);\r
317                                         \r
318                                         if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); return 0; }\r
319 \r
320                                         for (int i = 1; i < processors; i++) {\r
321                                                 bool tempResult;\r
322                                                 MPI_Recv(&tempResult, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);\r
323                                                 if (tempResult != 0) { MPIWroteAccnos = true; }\r
324                                         }\r
325                                 }else{ //you are a child process\r
326                                         MPI_Bcast(&numFastaSeqs, 1, MPI_INT, 0, MPI_COMM_WORLD); //get numSeqs\r
327                                         MPIPos.resize(numFastaSeqs+1);\r
328                                         MPI_Bcast(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, MPI_COMM_WORLD); //get file positions\r
329                                         \r
330                                         //figure out how many sequences you have to align\r
331                                         numSeqsPerProcessor = numFastaSeqs / processors;\r
332                                         int startIndex =  pid * numSeqsPerProcessor;\r
333                                         if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }\r
334                                         \r
335                                         \r
336                                         //align your part\r
337                                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIAlign, outMPIReport, outMPIAccnos, MPIPos);\r
338                                         \r
339                                         if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIAlign);  MPI_File_close(&outMPIReport);  MPI_File_close(&outMPIAccnos); return 0; }\r
340 \r
341                                         MPI_Send(&MPIWroteAccnos, 1, MPI_INT, 0, tag, MPI_COMM_WORLD); \r
342                                 }\r
343                                 \r
344                                 //close files \r
345                                 MPI_File_close(&inMPI);\r
346                                 MPI_File_close(&outMPIAlign);\r
347                                 MPI_File_close(&outMPIReport);\r
348                                 MPI_File_close(&outMPIAccnos);\r
349                                 \r
350                                 //delete accnos file if blank\r
351                                 if (pid == 0) {\r
352                                         //delete accnos file if its blank else report to user\r
353                                         if (MPIWroteAccnos) { \r
354                                                 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");\r
355                                                 if (!flip) {\r
356                                                         m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); \r
357                                                 }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }\r
358                                                 m->mothurOutEndLine();\r
359                                         }else { \r
360                                                 //MPI_Info info;\r
361                                                 //MPI_File_delete(outAccnosFilename, info);\r
362                                                 hasAccnos = false;      \r
363                                                 remove(accnosFileName.c_str()); \r
364                                         }\r
365                                 }\r
366                                 \r
367 #else\r
368                         \r
369         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)\r
370                         if(processors == 1){\r
371                                 ifstream inFASTA;\r
372                                 openInputFile(candidateFileNames[s], inFASTA);\r
373                                 numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');\r
374                                 inFASTA.close();\r
375                                 \r
376                                 lines.push_back(new linePair(0, numFastaSeqs));\r
377                                 \r
378                                 driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);\r
379                                 \r
380                                 if (m->control_pressed) { \r
381                                         remove(accnosFileName.c_str()); \r
382                                         remove(alignFileName.c_str()); \r
383                                         remove(reportFileName.c_str()); \r
384                                         return 0; \r
385                                 }\r
386                                 \r
387                                 //delete accnos file if its blank else report to user\r
388                                 if (isBlank(accnosFileName)) {  remove(accnosFileName.c_str());  hasAccnos = false; }\r
389                                 else { \r
390                                         m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");\r
391                                         if (!flip) {\r
392                                                 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); \r
393                                         }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }\r
394                                         m->mothurOutEndLine();\r
395                                 }\r
396                         }\r
397                         else{\r
398                                 vector<int> positions;\r
399                                 processIDS.resize(0);\r
400                                 \r
401                                 ifstream inFASTA;\r
402                                 openInputFile(candidateFileNames[s], inFASTA);\r
403                                 \r
404                                 string input;\r
405                                 while(!inFASTA.eof()){\r
406                                         input = getline(inFASTA);\r
407                                         if (input.length() != 0) {\r
408                                                 if(input[0] == '>'){    long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1);  }\r
409                                         }\r
410                                 }\r
411                                 inFASTA.close();\r
412                                 \r
413                                 numFastaSeqs = positions.size();\r
414                                 \r
415                                 int numSeqsPerProcessor = numFastaSeqs / processors;\r
416                                 \r
417                                 for (int i = 0; i < processors; i++) {\r
418                                         long int startPos = positions[ i * numSeqsPerProcessor ];\r
419                                         if(i == processors - 1){\r
420                                                 numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;\r
421                                         }\r
422                                         lines.push_back(new linePair(startPos, numSeqsPerProcessor));\r
423                                 }\r
424                                 \r
425                                 createProcesses(alignFileName, reportFileName, accnosFileName, candidateFileNames[s]); \r
426                                 \r
427                                 rename((alignFileName + toString(processIDS[0]) + ".temp").c_str(), alignFileName.c_str());\r
428                                 rename((reportFileName + toString(processIDS[0]) + ".temp").c_str(), reportFileName.c_str());\r
429                                 \r
430                                 //append alignment and report files\r
431                                 for(int i=1;i<processors;i++){\r
432                                         appendAlignFiles((alignFileName + toString(processIDS[i]) + ".temp"), alignFileName);\r
433                                         remove((alignFileName + toString(processIDS[i]) + ".temp").c_str());\r
434                                         \r
435                                         appendReportFiles((reportFileName + toString(processIDS[i]) + ".temp"), reportFileName);\r
436                                         remove((reportFileName + toString(processIDS[i]) + ".temp").c_str());\r
437                                 }\r
438                                 \r
439                                 vector<string> nonBlankAccnosFiles;\r
440                                 //delete blank accnos files generated with multiple processes\r
441                                 for(int i=0;i<processors;i++){  \r
442                                         if (!(isBlank(accnosFileName + toString(processIDS[i]) + ".temp"))) {\r
443                                                 nonBlankAccnosFiles.push_back(accnosFileName + toString(processIDS[i]) + ".temp");\r
444                                         }else { remove((accnosFileName + toString(processIDS[i]) + ".temp").c_str());  }\r
445                                 }\r
446                                 \r
447                                 //append accnos files\r
448                                 if (nonBlankAccnosFiles.size() != 0) { \r
449                                         rename(nonBlankAccnosFiles[0].c_str(), accnosFileName.c_str());\r
450                                         \r
451                                         for (int h=1; h < nonBlankAccnosFiles.size(); h++) {\r
452                                                 appendAlignFiles(nonBlankAccnosFiles[h], accnosFileName);\r
453                                                 remove(nonBlankAccnosFiles[h].c_str());\r
454                                         }\r
455                                         m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");\r
456                                         if (!flip) {\r
457                                                 m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); \r
458                                         }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }\r
459                                         m->mothurOutEndLine();\r
460                                 }else{ hasAccnos = false;  }\r
461                                 \r
462                                 if (m->control_pressed) { \r
463                                         remove(accnosFileName.c_str()); \r
464                                         remove(alignFileName.c_str()); \r
465                                         remove(reportFileName.c_str()); \r
466                                         return 0; \r
467                                 }\r
468                         }\r
469         #else\r
470                         ifstream inFASTA;\r
471                         openInputFile(candidateFileNames[s], inFASTA);\r
472                         numFastaSeqs=count(istreambuf_iterator<char>(inFASTA),istreambuf_iterator<char>(), '>');\r
473                         inFASTA.close();\r
474                         \r
475                         lines.push_back(new linePair(0, numFastaSeqs));\r
476                         \r
477                         driver(lines[0], alignFileName, reportFileName, accnosFileName, candidateFileNames[s]);\r
478                         \r
479                         if (m->control_pressed) { \r
480                                 remove(accnosFileName.c_str()); \r
481                                 remove(alignFileName.c_str()); \r
482                                 remove(reportFileName.c_str()); \r
483                                 return 0; \r
484                         }\r
485                         \r
486                         //delete accnos file if its blank else report to user\r
487                         if (isBlank(accnosFileName)) {  remove(accnosFileName.c_str());  hasAccnos = false; }\r
488                         else { \r
489                                 m->mothurOut("Some of you sequences generated alignments that eliminated too many bases, a list is provided in " + accnosFileName + ".");\r
490                                 if (!flip) {\r
491                                         m->mothurOut(" If you set the flip parameter to true mothur will try aligning the reverse compliment as well."); \r
492                                 }else{  m->mothurOut(" If the reverse compliment proved to be better it was reported.");  }\r
493                                 m->mothurOutEndLine();\r
494                         }\r
495                         \r
496         #endif\r
497 \r
498 #endif          \r
499 \r
500 \r
501                 #ifdef USE_MPI\r
502                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); \r
503                                         \r
504                         if (pid == 0) { //only one process should output to screen\r
505                 #endif\r
506 \r
507                         outputNames.push_back(alignFileName);\r
508                         outputNames.push_back(reportFileName);\r
509                         if (hasAccnos)  {       outputNames.push_back(accnosFileName);          }\r
510                         \r
511                 #ifdef USE_MPI\r
512                         }\r
513                 #endif\r
514 \r
515                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to align " + toString(numFastaSeqs) + " sequences.");\r
516                         m->mothurOutEndLine();\r
517                         m->mothurOutEndLine();\r
518                 }\r
519                 \r
520                 \r
521                 m->mothurOutEndLine();\r
522                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();\r
523                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }\r
524                 m->mothurOutEndLine();\r
525 \r
526                 return 0;\r
527         }\r
528         catch(exception& e) {\r
529                 m->errorOut(e, "AlignCommand", "execute");\r
530                 exit(1);\r
531         }\r
532 }\r
533 \r
534 //**********************************************************************************************************************\r
535 \r
536 int AlignCommand::driver(linePair* line, string alignFName, string reportFName, string accnosFName, string filename){\r
537         try {\r
538                 ofstream alignmentFile;\r
539                 openOutputFile(alignFName, alignmentFile);\r
540                 \r
541                 ofstream accnosFile;\r
542                 openOutputFile(accnosFName, accnosFile);\r
543                 \r
544                 NastReport report(reportFName);\r
545                 \r
546                 ifstream inFASTA;\r
547                 openInputFile(filename, inFASTA);\r
548 \r
549                 inFASTA.seekg(line->start);\r
550         \r
551                 for(int i=0;i<line->numSeqs;i++){\r
552                         \r
553                         if (m->control_pressed) {  return 0; }\r
554                         \r
555                         Sequence* candidateSeq = new Sequence(inFASTA);  gobble(inFASTA);\r
556         \r
557                         int origNumBases = candidateSeq->getNumBases();\r
558                         string originalUnaligned = candidateSeq->getUnaligned();\r
559                         int numBasesNeeded = origNumBases * threshold;\r
560         \r
561                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file\r
562                                 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {\r
563                                         alignment->resize(candidateSeq->getUnaligned().length()+1);\r
564                                 }\r
565                                                                 \r
566                                 Sequence temp = templateDB->findClosestSequence(candidateSeq);\r
567                                 Sequence* templateSeq = &temp;\r
568                                 \r
569                                 float searchScore = templateDB->getSearchScore();\r
570                                                                 \r
571                                 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);\r
572                                 Sequence* copy;\r
573                                 \r
574                                 Nast* nast2;\r
575                                 bool needToDeleteCopy = false;  //this is needed in case you have you enter the ifs below\r
576                                                                                                 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below\r
577                                                                                                 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place\r
578                                                                                                 //so this bool tells you if you need to delete it\r
579                                                                                                 \r
580                                 //if there is a possibility that this sequence should be reversed\r
581                                 if (candidateSeq->getNumBases() < numBasesNeeded) {\r
582                                         \r
583                                         string wasBetter = "";\r
584                                         //if the user wants you to try the reverse\r
585                                         if (flip) {\r
586                                                 //get reverse compliment\r
587                                                 copy = new Sequence(candidateSeq->getName(), originalUnaligned);\r
588                                                 copy->reverseComplement();\r
589                                                 \r
590                                                 //rerun alignment\r
591                                                 Sequence temp2 = templateDB->findClosestSequence(copy);\r
592                                                 Sequence* templateSeq2 = &temp2;\r
593                                                 \r
594                                                 searchScore = templateDB->getSearchScore();\r
595                                                 \r
596                                                 nast2 = new Nast(alignment, copy, templateSeq2);\r
597                         \r
598                                                 //check if any better\r
599                                                 if (copy->getNumBases() > candidateSeq->getNumBases()) {\r
600                                                         candidateSeq->setAligned(copy->getAligned());  //use reverse compliments alignment since its better\r
601                                                         templateSeq = templateSeq2; \r
602                                                         delete nast;\r
603                                                         nast = nast2;\r
604                                                         needToDeleteCopy = true;\r
605                                                 }else{  \r
606                                                         wasBetter = "\treverse complement did NOT produce a better alignment, please check sequence.";\r
607                                                         delete nast2;\r
608                                                         delete copy;    \r
609                                                 }\r
610                                         }\r
611                                         \r
612                                         //create accnos file with names\r
613                                         accnosFile << candidateSeq->getName() << wasBetter << endl;\r
614                                 }\r
615                                 \r
616                                 report.setCandidate(candidateSeq);\r
617                                 report.setTemplate(templateSeq);\r
618                                 report.setSearchParameters(search, searchScore);\r
619                                 report.setAlignmentParameters(align, alignment);\r
620                                 report.setNastParameters(*nast);\r
621         \r
622                                 alignmentFile << '>' << candidateSeq->getName() << '\n' << candidateSeq->getAligned() << endl;\r
623                                 \r
624                                 report.print();\r
625                                 delete nast;\r
626                                 if (needToDeleteCopy) {   delete copy;   }\r
627                         }\r
628                         delete candidateSeq;\r
629                         \r
630                         //report progress\r
631                         if((i+1) % 100 == 0){   m->mothurOut(toString(i+1)); m->mothurOutEndLine();             }\r
632                 }\r
633                 //report progress\r
634                 if((line->numSeqs) % 100 != 0){ m->mothurOut(toString(line->numSeqs)); m->mothurOutEndLine();           }\r
635                 \r
636                 alignmentFile.close();\r
637                 inFASTA.close();\r
638                 accnosFile.close();\r
639                 \r
640                 return 1;\r
641         }\r
642         catch(exception& e) {\r
643                 m->errorOut(e, "AlignCommand", "driver");\r
644                 exit(1);\r
645         }\r
646 }\r
647 //**********************************************************************************************************************\r
648 #ifdef USE_MPI\r
649 int AlignCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& alignFile, MPI_File& reportFile, MPI_File& accnosFile, vector<long>& MPIPos){\r
650         try {\r
651                 string outputString = "";\r
652                 MPI_Status statusReport; \r
653                 MPI_Status statusAlign; \r
654                 MPI_Status statusAccnos; \r
655                 MPI_Status status; \r
656                 int pid;\r
657                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are\r
658         \r
659                 NastReport report;\r
660                 \r
661                 if (pid == 0) {\r
662                         outputString = report.getHeaders();\r
663                         int length = outputString.length();\r
664             \r
665                         char* buf = new char[length];\r
666                         memcpy(buf, outputString.c_str(), length);\r
667                 \r
668                         MPI_File_write_shared(reportFile, buf, length, MPI_CHAR, &statusReport);\r
669 \r
670             delete buf;\r
671                 }\r
672                 \r
673                 for(int i=0;i<num;i++){\r
674                 \r
675                         if (m->control_pressed) {  return 0; }\r
676 \r
677                         //read next sequence\r
678                         int length = MPIPos[start+i+1] - MPIPos[start+i];\r
679 \r
680                         char* buf4 = new char[length];\r
681                         memcpy(buf4, outputString.c_str(), length);\r
682 \r
683                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);\r
684                         \r
685                         string tempBuf = buf4;\r
686 \r
687                         delete buf4;\r
688 \r
689                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }\r
690                         istringstream iss (tempBuf,istringstream::in);\r
691         \r
692                         Sequence* candidateSeq = new Sequence(iss);  \r
693                         int origNumBases = candidateSeq->getNumBases();\r
694                         string originalUnaligned = candidateSeq->getUnaligned();\r
695                         int numBasesNeeded = origNumBases * threshold;\r
696         \r
697                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file\r
698                                 if (candidateSeq->getUnaligned().length() > alignment->getnRows()) {\r
699                                         alignment->resize(candidateSeq->getUnaligned().length()+1);\r
700                                 }\r
701                                                                 \r
702                                 Sequence temp = templateDB->findClosestSequence(candidateSeq);\r
703                                 Sequence* templateSeq = &temp;\r
704                                 \r
705                                 float searchScore = templateDB->getSearchScore();\r
706                                                                 \r
707                                 Nast* nast = new Nast(alignment, candidateSeq, templateSeq);\r
708                                 Sequence* copy;\r
709                                 \r
710                                 Nast* nast2;\r
711                                 bool needToDeleteCopy = false;  //this is needed in case you have you enter the ifs below\r
712                                                                                                 //since nast does not make a copy of hte sequence passed, and it is used by the reporter below\r
713                                                                                                 //you can't delete the copy sequence til after you report, but you may choose not to create it in the first place\r
714                                                                                                 //so this bool tells you if you need to delete it\r
715                                                                                                 \r
716                                 //if there is a possibility that this sequence should be reversed\r
717                                 if (candidateSeq->getNumBases() < numBasesNeeded) {\r
718                                         \r
719                                         string wasBetter = "";\r
720                                         //if the user wants you to try the reverse\r
721                                         if (flip) {\r
722                                                 //get reverse compliment\r
723                                                 copy = new Sequence(candidateSeq->getName(), originalUnaligned);\r
724                                                 copy->reverseComplement();\r
725                                                 \r
726                                                 //rerun alignment\r
727                                                 Sequence temp2 = templateDB->findClosestSequence(copy);\r
728                                                 Sequence* templateSeq2 = &temp2;\r
729                                                 \r
730                                                 searchScore = templateDB->getSearchScore();\r
731                                                 \r
732                                                 nast2 = new Nast(alignment, copy, templateSeq2);\r
733                         \r
734                                                 //check if any better\r
735                                                 if (copy->getNumBases() > candidateSeq->getNumBases()) {\r
736                                                         candidateSeq->setAligned(copy->getAligned());  //use reverse compliments alignment since its better\r
737                                                         templateSeq = templateSeq2; \r
738                                                         delete nast;\r
739                                                         nast = nast2;\r
740                                                         needToDeleteCopy = true;\r
741                                                 }else{  \r
742                                                         wasBetter = "\treverse complement did NOT produce a better alignment, please check sequence.";\r
743                                                         delete nast2;\r
744                                                         delete copy;    \r
745                                                 }\r
746                                         }\r
747                                         \r
748                                         //create accnos file with names\r
749                                         outputString = candidateSeq->getName() + wasBetter + "\n";\r
750                                         \r
751                                         //send results to parent\r
752                                         int length = outputString.length();\r
753 \r
754                                         char* buf = new char[length];\r
755                                         memcpy(buf, outputString.c_str(), length);\r
756                                 \r
757                                         MPI_File_write_shared(accnosFile, buf, length, MPI_CHAR, &statusAccnos);\r
758                                         delete buf;\r
759                                         MPIWroteAccnos = true;\r
760                                 }\r
761                                 \r
762                                 report.setCandidate(candidateSeq);\r
763                                 report.setTemplate(templateSeq);\r
764                                 report.setSearchParameters(search, searchScore);\r
765                                 report.setAlignmentParameters(align, alignment);\r
766                                 report.setNastParameters(*nast);\r
767         \r
768                                 outputString =  ">" + candidateSeq->getName() + "\n" + candidateSeq->getAligned() + "\n";\r
769                                 \r
770                                 //send results to parent\r
771                                 int length = outputString.length();\r
772                                 char* buf2 = new char[length];\r
773                                 memcpy(buf2, outputString.c_str(), length);\r
774                                 \r
775                                 MPI_File_write_shared(alignFile, buf2, length, MPI_CHAR, &statusAlign);\r
776                                 \r
777                                 delete buf2;\r
778 \r
779                                 outputString = report.getReport();\r
780                                 \r
781                                 //send results to parent\r
782                                 length = outputString.length();\r
783                                 char* buf3 = new char[length];\r
784                                 memcpy(buf3, outputString.c_str(), length);\r
785                                 \r
786                                 MPI_File_write_shared(reportFile, buf3, length, MPI_CHAR, &statusReport);\r
787                                 \r
788                                 delete buf3;\r
789                                 delete nast;\r
790                                 if (needToDeleteCopy) {   delete copy;   }\r
791                         }\r
792                         delete candidateSeq;\r
793                         \r
794                         //report progress\r
795                         if((i+1) % 100 == 0){   cout << (toString(i+1)) << endl;                }\r
796                 }\r
797                 //report progress\r
798                 if((num) % 100 != 0){   cout << (toString(num)) << endl;                }\r
799                 \r
800                 return 1;\r
801         }\r
802         catch(exception& e) {\r
803                 m->errorOut(e, "AlignCommand", "driverMPI");\r
804                 exit(1);\r
805         }\r
806 }\r
807 #endif\r
808 /**************************************************************************************************/\r
809 \r
810 int AlignCommand::createProcesses(string alignFileName, string reportFileName, string accnosFName, string filename) {\r
811         try {\r
812 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)\r
813                 int process = 0;\r
814                 int exitCommand = 1;\r
815                 //              processIDS.resize(0);\r
816                 \r
817                 //loop through and create all the processes you want\r
818                 while (process != processors) {\r
819                         int pid = fork();\r
820                         \r
821                         if (pid > 0) {\r
822                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later\r
823                                 process++;\r
824                         }else if (pid == 0){\r
825                                 exitCommand = driver(lines[process], alignFileName + toString(getpid()) + ".temp", reportFileName + toString(getpid()) + ".temp", accnosFName + toString(getpid()) + ".temp", filename);\r
826                                 exit(0);\r
827                         }else { m->mothurOut("unable to spawn the necessary processes."); m->mothurOutEndLine(); exit(0); }\r
828                 }\r
829                 \r
830                 //force parent to wait until all the processes are done\r
831                 for (int i=0;i<processors;i++) { \r
832                         int temp = processIDS[i];\r
833                         wait(&temp);\r
834                 }\r
835                 \r
836                 return exitCommand;\r
837 #endif          \r
838         }\r
839         catch(exception& e) {\r
840                 m->errorOut(e, "AlignCommand", "createProcesses");\r
841                 exit(1);\r
842         }\r
843 }\r
844 \r
845 /**************************************************************************************************/\r
846 \r
847 void AlignCommand::appendAlignFiles(string temp, string filename) {\r
848         try{\r
849                 \r
850                 ofstream output;\r
851                 ifstream input;\r
852                 openOutputFileAppend(filename, output);\r
853                 openInputFile(temp, input);\r
854                 \r
855                 while(char c = input.get()){\r
856                         if(input.eof())         {       break;                  }\r
857                         else                            {       output << c;    }\r
858                 }\r
859                 \r
860                 input.close();\r
861                 output.close();\r
862         }\r
863         catch(exception& e) {\r
864                 m->errorOut(e, "AlignCommand", "appendAlignFiles");\r
865                 exit(1);\r
866         }\r
867 }\r
868 //**********************************************************************************************************************\r
869 \r
870 void AlignCommand::appendReportFiles(string temp, string filename) {\r
871         try{\r
872                 \r
873                 ofstream output;\r
874                 ifstream input;\r
875                 openOutputFileAppend(filename, output);\r
876                 openInputFile(temp, input);\r
877 \r
878                 while (!input.eof())    {       char c = input.get(); if (c == 10 || c == 13){  break;  }       } // get header line\r
879                                 \r
880                 while(char c = input.get()){\r
881                         if(input.eof())         {       break;                  }\r
882                         else                            {       output << c;    }\r
883                 }\r
884                 \r
885                 input.close();\r
886                 output.close();\r
887         }\r
888         catch(exception& e) {\r
889                 m->errorOut(e, "AlignCommand", "appendReportFiles");\r
890                 exit(1);\r
891         }\r
892 }\r
893 //**********************************************************************************************************************\r