]> git.donarmstrong.com Git - mothur.git/blob - filterseqscommand.cpp
b9436f8078df0da22408dafc889d16e62d8a7d6c
[mothur.git] / filterseqscommand.cpp
1 /*
2  *  filterseqscommand.cpp
3  *  Mothur
4  *
5  *  Created by Thomas Ryabin on 5/4/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "filterseqscommand.h"
11 #include "sequence.hpp"
12
13 //**********************************************************************************************************************
14 vector<string> FilterSeqsCommand::getValidParameters(){ 
15         try {
16                 string Array[] =  {"fasta", "trump", "soft", "hard", "vertical", "outputdir","inputdir", "processors"};
17                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
18                 return myArray;
19         }
20         catch(exception& e) {
21                 m->errorOut(e, "FilterSeqsCommand", "getValidParameters");
22                 exit(1);
23         }
24 }
25 //**********************************************************************************************************************
26 FilterSeqsCommand::FilterSeqsCommand(){ 
27         try {
28                 abort = true;
29                 //initialize outputTypes
30                 vector<string> tempOutNames;
31                 outputTypes["fasta"] = tempOutNames;
32                 outputTypes["filter"] = tempOutNames;
33         }
34         catch(exception& e) {
35                 m->errorOut(e, "FilterSeqsCommand", "FilterSeqsCommand");
36                 exit(1);
37         }
38 }
39 //**********************************************************************************************************************
40 vector<string> FilterSeqsCommand::getRequiredParameters(){      
41         try {
42                 string Array[] =  {"fasta"};
43                 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
44                 return myArray;
45         }
46         catch(exception& e) {
47                 m->errorOut(e, "FilterSeqsCommand", "getRequiredParameters");
48                 exit(1);
49         }
50 }
51 //**********************************************************************************************************************
52 vector<string> FilterSeqsCommand::getRequiredFiles(){   
53         try {
54                 vector<string> myArray;
55                 return myArray;
56         }
57         catch(exception& e) {
58                 m->errorOut(e, "FilterSeqsCommand", "getRequiredFiles");
59                 exit(1);
60         }
61 }
62 /**************************************************************************************/
63 FilterSeqsCommand::FilterSeqsCommand(string option)  {
64         try {
65                 abort = false;
66                 filterFileName = "";
67                 
68                 //allow user to run help
69                 if(option == "help") { help(); abort = true; }
70                 
71                 else {
72                         //valid paramters for this command
73                         string Array[] =  {"fasta", "trump", "soft", "hard", "vertical", "outputdir","inputdir", "processors"};
74                         vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
75                         
76                         OptionParser parser(option);
77                         map<string,string> parameters = parser.getParameters();
78                         
79                         ValidParameters validParameter("filter.seqs");
80                         map<string,string>::iterator it;
81                         
82                         //check to make sure all parameters are valid for command
83                         for (it = parameters.begin(); it != parameters.end(); it++) { 
84                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
85                         }
86                         
87                         //initialize outputTypes
88                         vector<string> tempOutNames;
89                         outputTypes["fasta"] = tempOutNames;
90                         outputTypes["filter"] = tempOutNames;
91                 
92                         //if the user changes the input directory command factory will send this info to us in the output parameter 
93                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
94                         if (inputDir == "not found"){   inputDir = "";          }
95                         else {
96                                 string path;
97                                 it = parameters.find("fasta");
98                                 //user has given a template file
99                                 if(it != parameters.end()){ 
100                                         path = m->hasPath(it->second);
101                                         //if the user has not given a path then, add inputdir. else leave path alone.
102                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
103                                 }
104                                 
105                                 it = parameters.find("hard");
106                                 //user has given a template file
107                                 if(it != parameters.end()){ 
108                                         path = m->hasPath(it->second);
109                                         //if the user has not given a path then, add inputdir. else leave path alone.
110                                         if (path == "") {       parameters["hard"] = inputDir + it->second;             }
111                                 }
112                         }
113                         
114                         //check for required parameters
115                         fasta = validParameter.validFile(parameters, "fasta", false);
116                         if (fasta == "not found") { m->mothurOut("fasta is a required parameter for the filter.seqs command."); m->mothurOutEndLine(); abort = true;  }
117                         else { 
118                                 m->splitAtDash(fasta, fastafileNames);
119                                 
120                                 //go through files and make sure they are good, if not, then disregard them
121                                 for (int i = 0; i < fastafileNames.size(); i++) {
122                                         if (inputDir != "") {
123                                                 string path = m->hasPath(fastafileNames[i]);
124                                                 //if the user has not given a path then, add inputdir. else leave path alone.
125                                                 if (path == "") {       fastafileNames[i] = inputDir + fastafileNames[i];               }
126                                         }
127
128                                         ifstream in;
129                                         int ableToOpen = m->openInputFile(fastafileNames[i], in, "noerror");
130                                 
131                                         //if you can't open it, try default location
132                                         if (ableToOpen == 1) {
133                                                 if (m->getDefaultPath() != "") { //default path is set
134                                                         string tryPath = m->getDefaultPath() + m->getSimpleName(fastafileNames[i]);
135                                                         m->mothurOut("Unable to open " + fastafileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
136                                                         ifstream in2;
137                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
138                                                         in2.close();
139                                                         fastafileNames[i] = tryPath;
140                                                 }
141                                         }
142                                         
143                                         //if you can't open it, try default location
144                                         if (ableToOpen == 1) {
145                                                 if (m->getOutputDir() != "") { //default path is set
146                                                         string tryPath = m->getOutputDir() + m->getSimpleName(fastafileNames[i]);
147                                                         m->mothurOut("Unable to open " + fastafileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
148                                                         ifstream in2;
149                                                         ableToOpen = m->openInputFile(tryPath, in2, "noerror");
150                                                         in2.close();
151                                                         fastafileNames[i] = tryPath;
152                                                 }
153                                         }
154                                         
155                                         in.close();
156                                         
157                                         if (ableToOpen == 1) { 
158                                                 m->mothurOut("Unable to open " + fastafileNames[i] + ". It will be disregarded."); m->mothurOutEndLine();
159                                                 //erase from file list
160                                                 fastafileNames.erase(fastafileNames.begin()+i);
161                                                 i--;
162                                         }else{  
163                                                 string simpleName = m->getSimpleName(fastafileNames[i]);
164                                                 filterFileName += simpleName.substr(0, simpleName.find_first_of('.'));
165                                         }
166                                         in.close();
167                                 }
168                                 
169                                 //make sure there is at least one valid file left
170                                 if (fastafileNames.size() == 0) { m->mothurOut("no valid files."); m->mothurOutEndLine(); abort = true; }
171                         }
172                         
173                         if (!abort) {
174                                 //if the user changes the output directory command factory will send this info to us in the output parameter 
175                                 outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
176                                         outputDir = ""; 
177                                         outputDir += m->hasPath(fastafileNames[0]); //if user entered a file with a path then preserve it       
178                                 }
179                         }
180                         //check for optional parameter and set defaults
181                         // ...at some point should added some additional type checking...
182                         
183                         string temp;
184                         hard = validParameter.validFile(parameters, "hard", true);                              if (hard == "not found") { hard = ""; }
185                         else if (hard == "not open") { hard = ""; abort = true; }       
186
187                         temp = validParameter.validFile(parameters, "trump", false);                    if (temp == "not found") { temp = "*"; }
188                         trump = temp[0];
189                         
190                         temp = validParameter.validFile(parameters, "soft", false);                             if (temp == "not found") { soft = 0; }
191                         else {  soft = (float)atoi(temp.c_str()) / 100.0;  }
192                         
193                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = "1";                             }
194                         convert(temp, processors); 
195                         
196                         vertical = validParameter.validFile(parameters, "vertical", false);             
197                         if (vertical == "not found") { 
198                                 if ((hard == "") && (trump == '*') && (soft == 0)) { vertical = "T"; } //you have not given a hard file or set the trump char.
199                                 else { vertical = "F";  }
200                         }
201                         
202                         numSeqs = 0;
203                 }
204                 
205         }
206         catch(exception& e) {
207                 m->errorOut(e, "FilterSeqsCommand", "FilterSeqsCommand");
208                 exit(1);
209         }
210 }
211
212 //**********************************************************************************************************************
213
214 void FilterSeqsCommand::help(){
215         try {
216                                 
217                 m->mothurOut("The filter.seqs command reads a file containing sequences and creates a .filter and .filter.fasta file.\n");
218                 m->mothurOut("The filter.seqs command parameters are fasta, trump, soft, hard, processors and vertical. \n");
219                 m->mothurOut("The fasta parameter is required. You may enter several fasta files to build the filter from and filter, by separating their names with -'s.\n");
220                 m->mothurOut("For example: fasta=abrecovery.fasta-amazon.fasta \n");
221                 m->mothurOut("The trump parameter .... The default is ...\n");
222                 m->mothurOut("The soft parameter .... The default is ....\n");
223                 m->mothurOut("The hard parameter allows you to enter a file containing the filter you want to use.\n");
224                 m->mothurOut("The vertical parameter removes columns where all sequences contain a gap character. The default is T.\n");
225                 m->mothurOut("The processors parameter allows you to specify the number of processors to use. The default is 1.\n");
226                 m->mothurOut("The filter.seqs command should be in the following format: \n");
227                 m->mothurOut("filter.seqs(fasta=yourFastaFile, trump=yourTrump) \n");
228                 m->mothurOut("Example filter.seqs(fasta=abrecovery.fasta, trump=.).\n");
229                 m->mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
230                 
231         }
232         catch(exception& e) {
233                 m->errorOut(e, "FilterSeqsCommand", "help");
234                 exit(1);
235         }
236 }
237
238 /**************************************************************************************/
239
240 int FilterSeqsCommand::execute() {      
241         try {
242         
243                 if (abort == true) { return 0; }
244                 
245                 ifstream inFASTA;
246                 m->openInputFile(fastafileNames[0], inFASTA);
247                 
248                 Sequence testSeq(inFASTA);
249                 alignmentLength = testSeq.getAlignLength();
250                 inFASTA.close();
251                 
252                 ////////////create filter/////////////////
253                 m->mothurOut("Creating Filter... "); m->mothurOutEndLine();
254                 
255                 filter = createFilter();
256                 
257                 m->mothurOutEndLine();  m->mothurOutEndLine();
258                 
259                 if (m->control_pressed) { outputTypes.clear(); return 0; }
260                 
261                 #ifdef USE_MPI
262                         int pid;
263                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
264                                         
265                         if (pid == 0) { //only one process should output the filter
266                 #endif
267                 
268                 ofstream outFilter;
269                 
270                 //prevent giantic file name
271                 string filterFile;
272                 if (fastafileNames.size() > 3) { filterFile = outputDir + "merge.filter"; }
273                 else {  filterFile = outputDir + filterFileName + ".filter";  }
274                 
275                 m->openOutputFile(filterFile, outFilter);
276                 outFilter << filter << endl;
277                 outFilter.close();
278                 outputNames.push_back(filterFile); outputTypes["filter"].push_back(filterFile);
279                 
280                 #ifdef USE_MPI
281                         }
282                 #endif
283                 
284                 ////////////run filter/////////////////
285                 
286                 m->mothurOut("Running Filter... "); m->mothurOutEndLine();
287                 
288                 filterSequences();
289                 
290                 m->mothurOutEndLine();  m->mothurOutEndLine();
291                                         
292                 int filteredLength = 0;
293                 for(int i=0;i<alignmentLength;i++){
294                         if(filter[i] == '1'){   filteredLength++;       }
295                 }
296                 
297                 if (m->control_pressed) {  outputTypes.clear(); for(int i = 0; i < outputNames.size(); i++) { remove(outputNames[i].c_str()); }  return 0; }
298
299                 
300                 m->mothurOutEndLine();
301                 m->mothurOut("Length of filtered alignment: " + toString(filteredLength)); m->mothurOutEndLine();
302                 m->mothurOut("Number of columns removed: " + toString((alignmentLength-filteredLength))); m->mothurOutEndLine();
303                 m->mothurOut("Length of the original alignment: " + toString(alignmentLength)); m->mothurOutEndLine();
304                 m->mothurOut("Number of sequences used to construct filter: " + toString(numSeqs)); m->mothurOutEndLine();
305                 
306                 
307                 m->mothurOutEndLine();
308                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
309                 for(int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();      }
310                 m->mothurOutEndLine();
311                 
312                 return 0;
313                 
314         }
315         catch(exception& e) {
316                 m->errorOut(e, "FilterSeqsCommand", "execute");
317                 exit(1);
318         }
319 }
320 /**************************************************************************************/
321 int FilterSeqsCommand::filterSequences() {      
322         try {
323                 
324                 numSeqs = 0;
325                 
326                 for (int s = 0; s < fastafileNames.size(); s++) {
327                         
328                                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
329                                 
330                                 string filteredFasta = outputDir + m->getRootName(m->getSimpleName(fastafileNames[s])) + "filter.fasta";
331 #ifdef USE_MPI  
332                                 int pid, start, end, numSeqsPerProcessor, num; 
333                                 int tag = 2001;
334                                 vector<unsigned long int>MPIPos;
335                                                 
336                                 MPI_Status status; 
337                                 MPI_Comm_size(MPI_COMM_WORLD, &processors); //set processors to the number of mpi processes running
338                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
339                                 
340                                 MPI_File outMPI;
341                                 MPI_File tempMPI;
342                                 MPI_File inMPI;
343                                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
344                                 int inMode=MPI_MODE_RDONLY; 
345                                 
346                                 char outFilename[1024];
347                                 strcpy(outFilename, filteredFasta.c_str());
348                         
349                                 char inFileName[1024];
350                                 strcpy(inFileName, fastafileNames[s].c_str());
351                                 
352                                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
353                                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
354
355                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI);  return 0;  }
356
357                                 if (pid == 0) { //you are the root process 
358                                         
359                                         MPIPos = m->setFilePosFasta(fastafileNames[s], num); //fills MPIPos, returns numSeqs
360                                         numSeqs += num;
361                                         
362                                         //send file positions to all processes
363                                         for(int i = 1; i < processors; i++) { 
364                                                 MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
365                                                 MPI_Send(&MPIPos[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
366                                         }
367                                         
368                                         //figure out how many sequences you have to do
369                                         numSeqsPerProcessor = num / processors;
370                                         int startIndex =  pid * numSeqsPerProcessor;
371                                         if(pid == (processors - 1)){    numSeqsPerProcessor = num - pid * numSeqsPerProcessor;  }
372                                         
373                                 
374                                         //do your part
375                                         driverMPIRun(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);
376                                         
377                                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI);  return 0;  }
378                                         
379                                         //wait on chidren
380                                         for(int i = 1; i < processors; i++) { 
381                                                 char buf[5];
382                                                 MPI_Recv(buf, 5, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status); 
383                                         }
384                                         
385                                 }else { //you are a child process
386                                         MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
387                                         MPIPos.resize(num+1);
388                                         numSeqs += num;
389                                         MPI_Recv(&MPIPos[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
390                                         
391                                         //figure out how many sequences you have to align
392                                         numSeqsPerProcessor = num / processors;
393                                         int startIndex =  pid * numSeqsPerProcessor;
394                                         if(pid == (processors - 1)){    numSeqsPerProcessor = num - pid * numSeqsPerProcessor;  }
395                                         
396                                         
397                                         //align your part
398                                         driverMPIRun(startIndex, numSeqsPerProcessor, inMPI, outMPI, MPIPos);           
399                                         
400                                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI);  return 0;  }
401                                         
402                                         char buf[5];
403                                         strcpy(buf, "done"); 
404                                         
405                                         //tell parent you are done.
406                                         MPI_Send(buf, 5, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
407                                 }
408                                 
409                                 MPI_File_close(&outMPI);
410                                 MPI_File_close(&inMPI);
411                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
412                                 
413 #else
414                         vector<unsigned long int> positions = m->divideFile(fastafileNames[s], processors);
415                                 
416                         for (int i = 0; i < (positions.size()-1); i++) {
417                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
418                         }       
419                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
420                                 if(processors == 1){
421                                         int numFastaSeqs = driverRunFilter(filter, filteredFasta, fastafileNames[s], lines[0]);
422                                         numSeqs += numFastaSeqs;
423                                 }else{
424                                         int numFastaSeqs = createProcessesRunFilter(filter, fastafileNames[s]); 
425                                         numSeqs += numFastaSeqs;
426                                 
427                                         rename((fastafileNames[s] + toString(processIDS[0]) + ".temp").c_str(), filteredFasta.c_str());
428                                 
429                                         //append fasta files
430                                         for(int i=1;i<processors;i++){
431                                                 m->appendFiles((fastafileNames[s] + toString(processIDS[i]) + ".temp"), filteredFasta);
432                                                 remove((fastafileNames[s] + toString(processIDS[i]) + ".temp").c_str());
433                                         }
434                                 }
435                                 
436                                 if (m->control_pressed) {  return 1; }
437                 #else
438                                 int numFastaSeqs = driverRunFilter(filter, filteredFasta, fastafileNames[s], lines[0]);
439                                 numSeqs += numFastaSeqs;
440
441                                 if (m->control_pressed) {  return 1; }
442                 #endif
443 #endif
444                         outputNames.push_back(filteredFasta); outputTypes["fasta"].push_back(filteredFasta);
445                 }
446
447                 return 0;
448         }
449         catch(exception& e) {
450                 m->errorOut(e, "FilterSeqsCommand", "filterSequences");
451                 exit(1);
452         }
453 }
454 #ifdef USE_MPI
455 /**************************************************************************************/
456 int FilterSeqsCommand::driverMPIRun(int start, int num, MPI_File& inMPI, MPI_File& outMPI, vector<unsigned long int>& MPIPos) { 
457         try {
458                 string outputString = "";
459                 int count = 0;
460                 MPI_Status status; 
461                 
462                 for(int i=0;i<num;i++){
463                 
464                         if (m->control_pressed) { return 0; }
465                 
466                         //read next sequence
467                         int length = MPIPos[start+i+1] - MPIPos[start+i];
468                         char* buf4 = new char[length];
469                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
470                         
471                         string tempBuf = buf4;
472                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
473                         istringstream iss (tempBuf,istringstream::in);
474                         delete buf4;
475         
476                         Sequence seq(iss);  m->gobble(iss);
477                         
478                         if (seq.getName() != "") {
479                                 string align = seq.getAligned();
480                                 string filterSeq = "";
481                                         
482                                 for(int j=0;j<alignmentLength;j++){
483                                         if(filter[j] == '1'){
484                                                 filterSeq += align[j];
485                                         }
486                                 }
487                                 
488                                 count++;
489                                 outputString += ">" + seq.getName() + "\n" + filterSeq + "\n";
490                                 
491                                 if(count % 10 == 0){ //output to file 
492                                         //send results to parent
493                                         int length = outputString.length();
494                                         char* buf = new char[length];
495                                         memcpy(buf, outputString.c_str(), length);
496                                 
497                                         MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
498                                         outputString = "";
499                                         delete buf;
500                                 }
501
502                         }
503                         
504                         if((i+1) % 100 == 0){   cout << (i+1) << endl;   m->mothurOutJustToLog(toString(i+1) + "\n");   }
505                 }
506                 
507                 if(outputString != ""){ //output to file 
508                         //send results to parent
509                         int length = outputString.length();
510                         char* buf = new char[length];
511                         memcpy(buf, outputString.c_str(), length);
512                         
513                         MPI_File_write_shared(outMPI, buf, length, MPI_CHAR, &status);
514                         outputString = "";
515                         delete buf;
516                 }
517                 
518                 if((num) % 100 != 0){   cout << (num) << endl;   m->mothurOutJustToLog(toString(num) + "\n");   }
519                         
520                 return 0;
521         }
522         catch(exception& e) {
523                 m->errorOut(e, "FilterSeqsCommand", "driverRunFilter");
524                 exit(1);
525         }
526 }
527 #endif
528 /**************************************************************************************/
529 int FilterSeqsCommand::driverRunFilter(string F, string outputFilename, string inputFilename, linePair* filePos) {      
530         try {
531                 ofstream out;
532                 m->openOutputFile(outputFilename, out);
533                 
534                 ifstream in;
535                 m->openInputFile(inputFilename, in);
536                                 
537                 in.seekg(filePos->start);
538
539                 bool done = false;
540                 int count = 0;
541         
542                 while (!done) {
543                                 
544                                 if (m->control_pressed) { in.close(); out.close(); return 0; }
545                                 
546                                 Sequence seq(in); m->gobble(in);
547                                 if (seq.getName() != "") {
548                                         string align = seq.getAligned();
549                                         string filterSeq = "";
550                                         
551                                         for(int j=0;j<alignmentLength;j++){
552                                                 if(filter[j] == '1'){
553                                                         filterSeq += align[j];
554                                                 }
555                                         }
556                                         
557                                         out << '>' << seq.getName() << endl << filterSeq << endl;
558                                 count++;
559                         }
560                         
561                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
562                                 unsigned long int pos = in.tellg();
563                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
564                         #else
565                                 if (in.eof()) { break; }
566                         #endif
567                         
568                         //report progress
569                         if((count) % 100 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine();           }
570                 }
571                 //report progress
572                 if((count) % 100 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine();           }
573                 
574                 
575                 out.close();
576                 in.close();
577                 
578                 return count;
579         }
580         catch(exception& e) {
581                 m->errorOut(e, "FilterSeqsCommand", "driverRunFilter");
582                 exit(1);
583         }
584 }
585 /**************************************************************************************************/
586
587 int FilterSeqsCommand::createProcessesRunFilter(string F, string filename) {
588         try {
589 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
590                 int process = 0;
591                 int num = 0;
592                 processIDS.clear();
593                 
594                 //loop through and create all the processes you want
595                 while (process != processors) {
596                         int pid = fork();
597                         
598                         if (pid > 0) {
599                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
600                                 process++;
601                         }else if (pid == 0){
602                                 string filteredFasta = filename + toString(getpid()) + ".temp";
603                                 num = driverRunFilter(F, filteredFasta, filename, lines[process]);
604                                 
605                                 //pass numSeqs to parent
606                                 ofstream out;
607                                 string tempFile = filename +  toString(getpid()) + ".num.temp";
608                                 m->openOutputFile(tempFile, out);
609                                 out << num << endl;
610                                 out.close();
611                                 
612                                 exit(0);
613                         }else { 
614                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
615                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
616                                 exit(0);
617                         }
618                 }
619                 
620                 //force parent to wait until all the processes are done
621                 for (int i=0;i<processors;i++) { 
622                         int temp = processIDS[i];
623                         wait(&temp);
624                 }       
625                                         
626                 for (int i = 0; i < processIDS.size(); i++) {
627                         ifstream in;
628                         string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
629                         m->openInputFile(tempFile, in);
630                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
631                         in.close(); remove(tempFile.c_str());
632                 }
633
634                 
635                 return num;
636 #endif          
637         }
638         catch(exception& e) {
639                 m->errorOut(e, "FilterSeqsCommand", "createProcessesRunFilter");
640                 exit(1);
641         }
642 }
643 /**************************************************************************************/
644 string FilterSeqsCommand::createFilter() {      
645         try {
646                 string filterString = "";                       
647                 Filters F;
648                 
649                 if (soft != 0)                  {  F.setSoft(soft);             }
650                 if (trump != '*')               {  F.setTrump(trump);   }
651                 
652                 F.setLength(alignmentLength);
653                 
654                 if(trump != '*' || m->isTrue(vertical) || soft != 0){
655                         F.initialize();
656                 }
657                 
658                 if(hard.compare("") != 0)       {       F.doHard(hard);         }
659                 else                                            {       F.setFilter(string(alignmentLength, '1'));      }
660                 
661                 numSeqs = 0;
662                 if(trump != '*' || m->isTrue(vertical) || soft != 0){
663                         for (int s = 0; s < fastafileNames.size(); s++) {
664                         
665                                 for (int i = 0; i < lines.size(); i++) {  delete lines[i];  }  lines.clear();
666                         
667 #ifdef USE_MPI  
668                                 int pid, numSeqsPerProcessor, num; 
669                                 int tag = 2001;
670                                 vector<unsigned long int> MPIPos;
671                                 
672                                 MPI_Status status; 
673                                 MPI_File inMPI; 
674                                 MPI_Comm_size(MPI_COMM_WORLD, &processors);
675                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
676                                                         
677                                 //char* tempFileName = new char(fastafileNames[s].length());
678                                 //tempFileName = &(fastafileNames[s][0]);
679                                 
680                                 char tempFileName[1024];
681                                 strcpy(tempFileName, fastafileNames[s].c_str());
682                 
683                                 MPI_File_open(MPI_COMM_WORLD, tempFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
684                                 
685                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  return 0;  }
686                                 
687                                 if (pid == 0) { //you are the root process
688                                                 MPIPos = m->setFilePosFasta(fastafileNames[s], num); //fills MPIPos, returns numSeqs
689                                                 numSeqs += num;
690                                                 
691                                                 //send file positions to all processes
692                                                 for(int i = 1; i < processors; i++) { 
693                                                         MPI_Send(&num, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
694                                                         MPI_Send(&MPIPos[0], (num+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
695                                                 }
696                                                                 
697                                                 //figure out how many sequences you have to do
698                                                 numSeqsPerProcessor = num / processors;
699                                                 int startIndex =  pid * numSeqsPerProcessor;
700                                                 if(pid == (processors - 1)){    numSeqsPerProcessor = num - pid * numSeqsPerProcessor;  }
701                                                 
702                                 
703                                                 //do your part
704                                                 MPICreateFilter(startIndex, numSeqsPerProcessor, F, inMPI, MPIPos);
705                                                 
706                                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  return 0;  }
707                                                                                                 
708                                 }else { //i am the child process
709                                         MPI_Recv(&num, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
710                                         MPIPos.resize(num+1);
711                                         numSeqs += num;
712                                         MPI_Recv(&MPIPos[0], (num+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
713                                         
714                                         //figure out how many sequences you have to align
715                                         numSeqsPerProcessor = num / processors;
716                                         int startIndex =  pid * numSeqsPerProcessor;
717                                         if(pid == (processors - 1)){    numSeqsPerProcessor = num - pid * numSeqsPerProcessor;  }
718                                         
719                                         
720                                         //do your part
721                                         MPICreateFilter(startIndex, numSeqsPerProcessor, F, inMPI,  MPIPos);
722                                         
723                                         if (m->control_pressed) {  MPI_File_close(&inMPI);  return 0;  }
724                                 }
725                                 
726                                 MPI_File_close(&inMPI);
727                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
728                                 
729 #else
730                 vector<unsigned long int> positions = m->divideFile(fastafileNames[s], processors);
731                                 
732                 for (int i = 0; i < (positions.size()-1); i++) {
733                         lines.push_back(new linePair(positions[i], positions[(i+1)]));
734                 }       
735                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
736                                 if(processors == 1){
737                                         int numFastaSeqs = driverCreateFilter(F, fastafileNames[s], lines[0]);
738                                         numSeqs += numFastaSeqs;
739                                 }else{
740                                         int numFastaSeqs = createProcessesCreateFilter(F, fastafileNames[s]); 
741                                         numSeqs += numFastaSeqs;
742                                 }
743                                 
744                                 if (m->control_pressed) {  return filterString; }
745                 #else
746                                 int numFastaSeqs = driverCreateFilter(F, fastafileNames[s], lines[0]);
747                                 numSeqs += numFastaSeqs;
748                                 if (m->control_pressed) {  return filterString; }
749                 #endif
750 #endif
751                         
752                         }
753                 }
754
755
756 #ifdef USE_MPI  
757                 int pid;
758                 int Atag = 1; int Ttag = 2; int Ctag = 3; int Gtag = 4; int Gaptag = 5;
759                 MPI_Status status;
760                 
761                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
762                 
763                 if(trump != '*' || m->isTrue(vertical) || soft != 0){
764                         
765                         if (pid == 0) { //only one process should output the filter
766                         
767                                 vector<int> temp; temp.resize(alignmentLength+1);
768                                                                 
769                                 //get the frequencies from the child processes
770                                 for(int i = 1; i < processors; i++) { 
771                                 
772                                         for (int j = 0; j < 5; j++) {
773                                         
774                                                 MPI_Recv(&temp[0], (alignmentLength+1), MPI_INT, i, 2001, MPI_COMM_WORLD, &status); 
775                                                 int receiveTag = temp[temp.size()-1];  //child process added a int to the end to indicate what letter count this is for
776                                                 
777                                                 if (receiveTag == Atag) { //you are recieveing the A frequencies
778                                                         for (int k = 0; k < alignmentLength; k++) {             F.a[k] += temp[k];      }
779                                                 }else if (receiveTag == Ttag) { //you are recieveing the T frequencies
780                                                         for (int k = 0; k < alignmentLength; k++) {             F.t[k] += temp[k];      }
781                                                 }else if (receiveTag == Ctag) { //you are recieveing the C frequencies
782                                                         for (int k = 0; k < alignmentLength; k++) {             F.c[k] += temp[k];      }
783                                                 }else if (receiveTag == Gtag) { //you are recieveing the G frequencies
784                                                         for (int k = 0; k < alignmentLength; k++) {             F.g[k] += temp[k];      }
785                                                 }else if (receiveTag == Gaptag) { //you are recieveing the gap frequencies
786                                                         for (int k = 0; k < alignmentLength; k++) {             F.gap[k] += temp[k];    }
787                                                 }
788                                         }
789                                 } 
790                         }else{
791                         
792                                 //send my fequency counts
793                                 F.a.push_back(Atag);
794                                 int ierr = MPI_Send(&(F.a[0]), (alignmentLength+1), MPI_INT, 0, 2001, MPI_COMM_WORLD);
795                                 F.t.push_back(Ttag);
796                                 ierr = MPI_Send (&(F.t[0]), (alignmentLength+1), MPI_INT, 0, 2001, MPI_COMM_WORLD);
797                                 F.c.push_back(Ctag);
798                                 ierr = MPI_Send(&(F.c[0]), (alignmentLength+1), MPI_INT, 0, 2001, MPI_COMM_WORLD);
799                                 F.g.push_back(Gtag);
800                                 ierr = MPI_Send(&(F.g[0]), (alignmentLength+1), MPI_INT, 0, 2001, MPI_COMM_WORLD);
801                                 F.gap.push_back(Gaptag);
802                                 ierr = MPI_Send(&(F.gap[0]), (alignmentLength+1), MPI_INT, 0, 2001, MPI_COMM_WORLD);
803                         }
804                         
805                 }
806                 
807                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
808                 
809                 if (pid == 0) { //only one process should output the filter
810 #endif
811
812                 F.setNumSeqs(numSeqs);
813                 if(m->isTrue(vertical) == 1)    {       F.doVertical(); }
814                 if(soft != 0)                           {       F.doSoft();             }
815                 filterString = F.getFilter();
816                 
817 #ifdef USE_MPI
818                 //send filter string to kids
819                 //for(int i = 1; i < processors; i++) { 
820                 //      MPI_Send(&filterString[0], alignmentLength, MPI_CHAR, i, 2001, MPI_COMM_WORLD);
821                 //}
822                 MPI_Bcast(&filterString[0], alignmentLength, MPI_CHAR, 0, MPI_COMM_WORLD);
823         }else{
824                 //recieve filterString
825                 char* tempBuf = new char[alignmentLength];
826                 //MPI_Recv(&tempBuf[0], alignmentLength, MPI_CHAR, 0, 2001, MPI_COMM_WORLD, &status);
827                 MPI_Bcast(tempBuf, alignmentLength, MPI_CHAR, 0, MPI_COMM_WORLD);
828                 
829                 filterString = tempBuf;
830                 if (filterString.length() > alignmentLength) { filterString = filterString.substr(0, alignmentLength);  }
831                 delete tempBuf; 
832         }
833         
834         MPI_Barrier(MPI_COMM_WORLD);
835 #endif
836                                 
837                 return filterString;
838         }
839         catch(exception& e) {
840                 m->errorOut(e, "FilterSeqsCommand", "createFilter");
841                 exit(1);
842         }
843 }
844 /**************************************************************************************/
845 int FilterSeqsCommand::driverCreateFilter(Filters& F, string filename, linePair* filePos) {     
846         try {
847                 
848                 ifstream in;
849                 m->openInputFile(filename, in);
850                                 
851                 in.seekg(filePos->start);
852
853                 bool done = false;
854                 int count = 0;
855         
856                 while (!done) {
857                                 
858                         if (m->control_pressed) { in.close(); return 1; }
859                                         
860                         Sequence seq(in); m->gobble(in);
861                         if (seq.getName() != "") {
862                                         if (seq.getAligned().length() != alignmentLength) { m->mothurOut("Sequences are not all the same length, please correct."); m->mothurOutEndLine(); m->control_pressed = true;  }
863                                         
864                                         if(trump != '*')                        {       F.doTrump(seq);         }
865                                         if(m->isTrue(vertical) || soft != 0)    {       F.getFreqs(seq);        }
866                                         cout.flush();
867                                         count++;
868                         }
869                         
870                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
871                                 unsigned long int pos = in.tellg();
872                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
873                         #else
874                                 if (in.eof()) { break; }
875                         #endif
876                         
877                         //report progress
878                         if((count) % 100 == 0){ m->mothurOut(toString(count)); m->mothurOutEndLine();           }
879                 }
880                 //report progress
881                 if((count) % 100 != 0){ m->mothurOut(toString(count)); m->mothurOutEndLine();           }
882                 in.close();
883                 
884                 return count;
885         }
886         catch(exception& e) {
887                 m->errorOut(e, "FilterSeqsCommand", "driverCreateFilter");
888                 exit(1);
889         }
890 }
891 #ifdef USE_MPI
892 /**************************************************************************************/
893 int FilterSeqsCommand::MPICreateFilter(int start, int num, Filters& F, MPI_File& inMPI, vector<unsigned long int>& MPIPos) {    
894         try {
895                 
896                 MPI_Status status; 
897                 int pid;
898                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
899                 
900                 for(int i=0;i<num;i++){
901                         
902                         if (m->control_pressed) { return 0; }
903                         
904                         //read next sequence
905                         int length = MPIPos[start+i+1] - MPIPos[start+i];
906         
907                         char* buf4 = new char[length];
908                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
909                         
910                         string tempBuf = buf4;
911                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
912                         istringstream iss (tempBuf,istringstream::in);
913                         delete buf4;
914
915                         Sequence seq(iss);  
916
917                         if (seq.getAligned().length() != alignmentLength) {  cout << "Alignment length is " << alignmentLength << " and sequence " << seq.getName() << " has length " << seq.getAligned().length() << ", please correct." << endl; exit(1);  }
918                         
919                         if(trump != '*'){       F.doTrump(seq); }
920                         if(m->isTrue(vertical) || soft != 0){   F.getFreqs(seq);        }
921                         cout.flush();
922                                                 
923                         //report progress
924                         if((i+1) % 100 == 0){   cout << (i+1) << endl;   m->mothurOutJustToLog(toString(i+1) + "\n");   }
925                 }
926                 
927                 //report progress
928                 if((num) % 100 != 0){   cout << num << endl; m->mothurOutJustToLog(toString(num) + "\n");       }
929                 
930                 return 0;
931         }
932         catch(exception& e) {
933                 m->errorOut(e, "FilterSeqsCommand", "MPICreateFilter");
934                 exit(1);
935         }
936 }
937 #endif
938 /**************************************************************************************************/
939
940 int FilterSeqsCommand::createProcessesCreateFilter(Filters& F, string filename) {
941         try {
942 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
943                 int process = 1;
944                 int num = 0;
945                 processIDS.clear();
946                 
947                 //loop through and create all the processes you want
948                 while (process != processors) {
949                         int pid = fork();
950                         
951                         if (pid > 0) {
952                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
953                                 process++;
954                         }else if (pid == 0){
955                                 //reset child's filter counts to 0;
956                                 F.a.clear(); F.a.resize(alignmentLength, 0);
957                                 F.t.clear(); F.t.resize(alignmentLength, 0);
958                                 F.g.clear(); F.g.resize(alignmentLength, 0);
959                                 F.c.clear(); F.c.resize(alignmentLength, 0);
960                                 F.gap.clear(); F.gap.resize(alignmentLength, 0);
961                                 
962                                 num = driverCreateFilter(F, filename, lines[process]);
963                                 
964                                 //write out filter counts to file
965                                 filename += toString(getpid()) + "filterValues.temp";
966                                 ofstream out;
967                                 m->openOutputFile(filename, out);
968                                 
969                                 out << num << endl;
970                                 out << F.getFilter() << endl;
971                                 for (int k = 0; k < alignmentLength; k++) {             out << F.a[k] << '\t'; }  out << endl;
972                                 for (int k = 0; k < alignmentLength; k++) {             out << F.t[k] << '\t'; }  out << endl;
973                                 for (int k = 0; k < alignmentLength; k++) {             out << F.g[k] << '\t'; }  out << endl;
974                                 for (int k = 0; k < alignmentLength; k++) {             out << F.c[k] << '\t'; }  out << endl;
975                                 for (int k = 0; k < alignmentLength; k++) {             out << F.gap[k] << '\t'; }  out << endl;
976
977                                 //cout << F.getFilter() << endl;
978                                 out.close();
979                                 
980                                 exit(0);
981                         }else { 
982                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
983                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
984                                 exit(0);
985                         }
986                 }
987                 
988                 //parent do your part
989                 num = driverCreateFilter(F, filename, lines[0]);
990                 
991                 //force parent to wait until all the processes are done
992                 for (int i=0;i<(processors-1);i++) { 
993                         int temp = processIDS[i];
994                         wait(&temp);
995                 }
996                 
997                 //parent reads in and combines Filter info
998                 for (int i = 0; i < processIDS.size(); i++) {
999                         string tempFilename = filename + toString(processIDS[i]) + "filterValues.temp";
1000                         ifstream in;
1001                         m->openInputFile(tempFilename, in);
1002                         
1003                         int temp, tempNum;
1004                         string tempFilterString;
1005
1006                         in >> tempNum; m->gobble(in); num += tempNum;
1007
1008                         in >> tempFilterString;
1009                         F.mergeFilter(tempFilterString);
1010
1011                         for (int k = 0; k < alignmentLength; k++) {             in >> temp; F.a[k] += temp; }           m->gobble(in);
1012                         for (int k = 0; k < alignmentLength; k++) {             in >> temp; F.t[k] += temp; }           m->gobble(in);
1013                         for (int k = 0; k < alignmentLength; k++) {             in >> temp; F.g[k] += temp; }           m->gobble(in);
1014                         for (int k = 0; k < alignmentLength; k++) {             in >> temp; F.c[k] += temp; }           m->gobble(in);
1015                         for (int k = 0; k < alignmentLength; k++) {             in >> temp; F.gap[k] += temp; } m->gobble(in);
1016                                 
1017                         in.close();
1018                         remove(tempFilename.c_str());
1019                 }
1020                 
1021                 return num;
1022 #endif          
1023         }
1024         catch(exception& e) {
1025                 m->errorOut(e, "FilterSeqsCommand", "createProcessesCreateFilter");
1026                 exit(1);
1027         }
1028 }
1029 /**************************************************************************************/