]> git.donarmstrong.com Git - mothur.git/blob - screenseqscommand.cpp
fixed bug in windows summary.seqs and summary.qual paralellization. paralellized...
[mothur.git] / screenseqscommand.cpp
1 /*
2  *  screenseqscommand.cpp
3  *  Mothur
4  *
5  *  Created by Pat Schloss on 6/3/09.
6  *  Copyright 2009 Patrick D. Schloss. All rights reserved.
7  *
8  */
9
10 #include "screenseqscommand.h"
11
12
13 //**********************************************************************************************************************
14 vector<string> ScreenSeqsCommand::setParameters(){      
15         try {
16                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
17                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
18                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
19                 CommandParameter pqfile("qfile", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pqfile);
20                 CommandParameter palignreport("alignreport", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(palignreport);
21                 CommandParameter ptax("taxonomy", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(ptax);
22                 CommandParameter pstart("start", "Number", "", "-1", "", "", "",false,false); parameters.push_back(pstart);
23                 CommandParameter pend("end", "Number", "", "-1", "", "", "",false,false); parameters.push_back(pend);
24                 CommandParameter pmaxambig("maxambig", "Number", "", "-1", "", "", "",false,false); parameters.push_back(pmaxambig);
25                 CommandParameter pmaxhomop("maxhomop", "Number", "", "-1", "", "", "",false,false); parameters.push_back(pmaxhomop);
26                 CommandParameter pminlength("minlength", "Number", "", "-1", "", "", "",false,false); parameters.push_back(pminlength);
27                 CommandParameter pmaxlength("maxlength", "Number", "", "-1", "", "", "",false,false); parameters.push_back(pmaxlength);
28                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
29                 CommandParameter pcriteria("criteria", "Number", "", "90", "", "", "",false,false); parameters.push_back(pcriteria);
30                 CommandParameter poptimize("optimize", "Multiple", "none-start-end-maxambig-maxhomop-minlength-maxlength", "none", "", "", "",true,false); parameters.push_back(poptimize);
31                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
32                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
33                 
34                 vector<string> myArray;
35                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
36                 return myArray;
37         }
38         catch(exception& e) {
39                 m->errorOut(e, "ScreenSeqsCommand", "setParameters");
40                 exit(1);
41         }
42 }
43 //**********************************************************************************************************************
44 string ScreenSeqsCommand::getHelpString(){      
45         try {
46                 string helpString = "";
47                 helpString += "The screen.seqs command reads a fastafile and creates .....\n";
48                 helpString += "The screen.seqs command parameters are fasta, start, end, maxambig, maxhomop, minlength, maxlength, name, group, qfile, alignreport, taxonomy, optimize, criteria and processors.\n";
49                 helpString += "The fasta parameter is required.\n";
50                 helpString += "The alignreport and taxonomy parameters allow you to remove bad seqs from taxonomy and alignreport files.\n";
51                 helpString += "The start parameter .... The default is -1.\n";
52                 helpString += "The end parameter .... The default is -1.\n";
53                 helpString += "The maxambig parameter allows you to set the maximum number of ambigious bases allowed. The default is -1.\n";
54                 helpString += "The maxhomop parameter allows you to set a maximum homopolymer length. \n";
55                 helpString += "The minlength parameter allows you to set and minimum sequence length. \n";
56                 helpString += "The maxlength parameter allows you to set and maximum sequence length. \n";
57                 helpString += "The processors parameter allows you to specify the number of processors to use while running the command. The default is 1.\n";
58                 helpString += "The optimize and criteria parameters allow you set the start, end, maxabig, maxhomop, minlength and maxlength parameters relative to your set of sequences .\n";
59                 helpString += "For example optimize=start-end, criteria=90, would set the start and end values to the position 90% of your sequences started and ended.\n";
60                 helpString += "The name parameter allows you to provide a namesfile, and the group parameter allows you to provide a groupfile.\n";
61                 helpString += "The screen.seqs command should be in the following format: \n";
62                 helpString += "screen.seqs(fasta=yourFastaFile, name=youNameFile, group=yourGroupFIle, start=yourStart, end=yourEnd, maxambig=yourMaxambig,  \n";
63                 helpString += "maxhomop=yourMaxhomop, minlength=youMinlength, maxlength=yourMaxlength)  \n";    
64                 helpString += "Example screen.seqs(fasta=abrecovery.fasta, name=abrecovery.names, group=abrecovery.groups, start=..., end=..., maxambig=..., maxhomop=..., minlength=..., maxlength=...).\n";
65                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
66                 return helpString;
67         }
68         catch(exception& e) {
69                 m->errorOut(e, "ScreenSeqsCommand", "getHelpString");
70                 exit(1);
71         }
72 }
73 //**********************************************************************************************************************
74 ScreenSeqsCommand::ScreenSeqsCommand(){ 
75         try {
76                 abort = true; calledHelp = true; 
77                 setParameters();
78                 vector<string> tempOutNames;
79                 outputTypes["fasta"] = tempOutNames;
80                 outputTypes["name"] = tempOutNames;
81                 outputTypes["group"] = tempOutNames;
82                 outputTypes["alignreport"] = tempOutNames;
83                 outputTypes["accnos"] = tempOutNames;
84                 outputTypes["qfile"] = tempOutNames;
85                 outputTypes["taxonomy"] = tempOutNames;
86         }
87         catch(exception& e) {
88                 m->errorOut(e, "ScreenSeqsCommand", "ScreenSeqsCommand");
89                 exit(1);
90         }
91 }
92 //***************************************************************************************************************
93
94 ScreenSeqsCommand::ScreenSeqsCommand(string option)  {
95         try {
96                 abort = false; calledHelp = false;   
97                 
98                 //allow user to run help
99                 if(option == "help") { help(); abort = true; calledHelp = true; }
100                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
101                 
102                 else {
103                         vector<string> myArray = setParameters();
104                         
105                         OptionParser parser(option);
106                         map<string,string> parameters = parser.getParameters();
107                         
108                         ValidParameters validParameter("screen.seqs");
109                         map<string,string>::iterator it;
110                         
111                         //check to make sure all parameters are valid for command
112                         for (it = parameters.begin(); it != parameters.end(); it++) { 
113                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
114                         }
115                         
116                         //initialize outputTypes
117                         vector<string> tempOutNames;
118                         outputTypes["fasta"] = tempOutNames;
119                         outputTypes["name"] = tempOutNames;
120                         outputTypes["group"] = tempOutNames;
121                         outputTypes["alignreport"] = tempOutNames;
122                         outputTypes["accnos"] = tempOutNames;
123                         outputTypes["qfile"] = tempOutNames;
124                         outputTypes["taxonomy"] = tempOutNames;
125                         
126                         //if the user changes the input directory command factory will send this info to us in the output parameter 
127                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
128                         if (inputDir == "not found"){   inputDir = "";          }
129                         else {
130                                 string path;
131                                 it = parameters.find("fasta");
132                                 //user has given a template file
133                                 if(it != parameters.end()){ 
134                                         path = m->hasPath(it->second);
135                                         //if the user has not given a path then, add inputdir. else leave path alone.
136                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
137                                 }
138                                 
139                                 it = parameters.find("group");
140                                 //user has given a template file
141                                 if(it != parameters.end()){ 
142                                         path = m->hasPath(it->second);
143                                         //if the user has not given a path then, add inputdir. else leave path alone.
144                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
145                                 }
146                                 
147                                 it = parameters.find("name");
148                                 //user has given a template file
149                                 if(it != parameters.end()){ 
150                                         path = m->hasPath(it->second);
151                                         //if the user has not given a path then, add inputdir. else leave path alone.
152                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
153                                 }
154                                 
155                                 it = parameters.find("alignreport");
156                                 //user has given a template file
157                                 if(it != parameters.end()){ 
158                                         path = m->hasPath(it->second);
159                                         //if the user has not given a path then, add inputdir. else leave path alone.
160                                         if (path == "") {       parameters["alignreport"] = inputDir + it->second;              }
161                                 }
162                                 
163                                 it = parameters.find("qfile");
164                                 //user has given a template file
165                                 if(it != parameters.end()){ 
166                                         path = m->hasPath(it->second);
167                                         //if the user has not given a path then, add inputdir. else leave path alone.
168                                         if (path == "") {       parameters["qfile"] = inputDir + it->second;            }
169                                 }
170                                 
171                                 it = parameters.find("taxonomy");
172                                 //user has given a template file
173                                 if(it != parameters.end()){ 
174                                         path = m->hasPath(it->second);
175                                         //if the user has not given a path then, add inputdir. else leave path alone.
176                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
177                                 }
178                         }
179
180                         //check for required parameters
181                         fastafile = validParameter.validFile(parameters, "fasta", true);
182                         if (fastafile == "not found") {                         
183                                 fastafile = m->getFastaFile(); 
184                                 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
185                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
186                         }
187                         else if (fastafile == "not open") { abort = true; }
188                         else { m->setFastaFile(fastafile); }
189         
190                         groupfile = validParameter.validFile(parameters, "group", true);
191                         if (groupfile == "not open") { abort = true; }  
192                         else if (groupfile == "not found") { groupfile = ""; }
193                         else { m->setGroupFile(groupfile); }
194                         
195                         qualfile = validParameter.validFile(parameters, "qfile", true);
196                         if (qualfile == "not open") { abort = true; }   
197                         else if (qualfile == "not found") { qualfile = ""; }
198                         else { m->setQualFile(qualfile); }
199                         
200                         namefile = validParameter.validFile(parameters, "name", true);
201                         if (namefile == "not open") { namefile = ""; abort = true; }
202                         else if (namefile == "not found") { namefile = ""; }    
203                         else { m->setNameFile(namefile); }
204                         
205                         alignreport = validParameter.validFile(parameters, "alignreport", true);
206                         if (alignreport == "not open") { abort = true; }
207                         else if (alignreport == "not found") { alignreport = ""; }
208                         
209                         taxonomy = validParameter.validFile(parameters, "taxonomy", true);
210                         if (taxonomy == "not open") { abort = true; }
211                         else if (taxonomy == "not found") { taxonomy = ""; }    
212                         
213                         //if the user changes the output directory command factory will send this info to us in the output parameter 
214                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
215                                 outputDir = ""; 
216                                 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it       
217                         }
218
219                         //check for optional parameter and set defaults
220                         // ...at some point should added some additional type checking...
221                         string temp;
222                         temp = validParameter.validFile(parameters, "start", false);            if (temp == "not found") { temp = "-1"; }
223                         m->mothurConvert(temp, startPos); 
224                 
225                         temp = validParameter.validFile(parameters, "end", false);                      if (temp == "not found") { temp = "-1"; }
226                         m->mothurConvert(temp, endPos);  
227
228                         temp = validParameter.validFile(parameters, "maxambig", false);         if (temp == "not found") { temp = "-1"; }
229                         m->mothurConvert(temp, maxAmbig);  
230
231                         temp = validParameter.validFile(parameters, "maxhomop", false);         if (temp == "not found") { temp = "-1"; }
232                         m->mothurConvert(temp, maxHomoP);  
233
234                         temp = validParameter.validFile(parameters, "minlength", false);        if (temp == "not found") { temp = "-1"; }
235                         m->mothurConvert(temp, minLength); 
236                         
237                         temp = validParameter.validFile(parameters, "maxlength", false);        if (temp == "not found") { temp = "-1"; }
238                         m->mothurConvert(temp, maxLength); 
239                         
240                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
241                         m->setProcessors(temp);
242                         m->mothurConvert(temp, processors);
243                         
244                         temp = validParameter.validFile(parameters, "optimize", false); //optimizing trumps the optimized values original value
245                         if (temp == "not found"){       temp = "none";          }
246                         m->splitAtDash(temp, optimize);         
247                         
248                         //check for invalid optimize options
249                         set<string> validOptimizers;
250                         validOptimizers.insert("none"); validOptimizers.insert("start"); validOptimizers.insert("end"); validOptimizers.insert("maxambig"); validOptimizers.insert("maxhomop"); validOptimizers.insert("minlength"); validOptimizers.insert("maxlength");
251                         for (int i = 0; i < optimize.size(); i++) { 
252                                 if (validOptimizers.count(optimize[i]) == 0) { 
253                                         m->mothurOut(optimize[i] + " is not a valid optimizer. Valid options are start, end, maxambig, maxhomop, minlength and maxlength."); m->mothurOutEndLine();
254                                         optimize.erase(optimize.begin()+i);
255                                         i--;
256                                 }
257                         }
258                         
259                         if (optimize.size() == 1) { if (optimize[0] == "none") { optimize.clear(); } }
260                         
261                         temp = validParameter.validFile(parameters, "criteria", false); if (temp == "not found"){       temp = "90";                            }
262                         m->mothurConvert(temp, criteria); 
263                         
264                         if (namefile == "") {
265                                 vector<string> files; files.push_back(fastafile);
266                                 parser.getNameFile(files);
267                         }
268                 }
269
270         }
271         catch(exception& e) {
272                 m->errorOut(e, "ScreenSeqsCommand", "ScreenSeqsCommand");
273                 exit(1);
274         }
275 }
276 //***************************************************************************************************************
277
278 int ScreenSeqsCommand::execute(){
279         try{
280                 
281                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
282                 
283                 //if the user want to optimize we need to know the 90% mark
284                 vector<unsigned long long> positions;
285                 if (optimize.size() != 0) {  //get summary is paralellized so we need to divideFile, no need to do this step twice so I moved it here
286                         //use the namefile to optimize correctly
287                         if (namefile != "") { nameMap = m->readNames(namefile); }
288                         getSummary(positions); 
289                 } 
290                 else { 
291                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
292                 positions = m->divideFile(fastafile, processors);
293                 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }
294                         #else 
295                 if(processors == 1){ lines.push_back(linePair(0, 1000));  }
296                 else {
297                     int numFastaSeqs = 0;
298                     positions = m->setFilePosFasta(fastafile, numFastaSeqs); 
299                 
300                     //figure out how many sequences you have to process
301                     int numSeqsPerProcessor = numFastaSeqs / processors;
302                     for (int i = 0; i < processors; i++) {
303                         int startIndex =  i * numSeqsPerProcessor;
304                         if(i == (processors - 1)){      numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;   }
305                         lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
306                     }
307                 }
308                         #endif
309                 }
310                                         
311                 string goodSeqFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "good" + m->getExtension(fastafile);
312                 string badAccnosFile =  outputDir + m->getRootName(m->getSimpleName(fastafile)) + "bad.accnos";
313                 
314                 int numFastaSeqs = 0;
315                 set<string> badSeqNames;
316                 int start = time(NULL);
317         
318 #ifdef USE_MPI  
319                         int pid, numSeqsPerProcessor; 
320                         int tag = 2001;
321                         vector<unsigned long long> MPIPos;
322                         
323                         MPI_Status status; 
324                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
325                         MPI_Comm_size(MPI_COMM_WORLD, &processors); 
326         
327                         MPI_File inMPI;
328                         MPI_File outMPIGood;
329                         MPI_File outMPIBadAccnos;
330                         
331                         int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
332                         int inMode=MPI_MODE_RDONLY; 
333                         
334                         char outGoodFilename[1024];
335                         strcpy(outGoodFilename, goodSeqFile.c_str());
336
337                         char outBadAccnosFilename[1024];
338                         strcpy(outBadAccnosFilename, badAccnosFile.c_str());
339
340                         char inFileName[1024];
341                         strcpy(inFileName, fastafile.c_str());
342                         
343                         MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
344                         MPI_File_open(MPI_COMM_WORLD, outGoodFilename, outMode, MPI_INFO_NULL, &outMPIGood);
345                         MPI_File_open(MPI_COMM_WORLD, outBadAccnosFilename, outMode, MPI_INFO_NULL, &outMPIBadAccnos);
346                         
347                         if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIGood); MPI_File_close(&outMPIBadAccnos); return 0; }
348                         
349                         if (pid == 0) { //you are the root process 
350                                 
351                                 MPIPos = m->setFilePosFasta(fastafile, numFastaSeqs); //fills MPIPos, returns numSeqs
352                                 
353                                 //send file positions to all processes
354                                 for(int i = 1; i < processors; i++) { 
355                                         MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
356                                         MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
357                                 }
358                                 
359                                 //figure out how many sequences you have to align
360                                 numSeqsPerProcessor = numFastaSeqs / processors;
361                                 int startIndex =  pid * numSeqsPerProcessor;
362                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
363
364                                 //align your part
365                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIGood, outMPIBadAccnos, MPIPos, badSeqNames);
366
367                                 if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIGood);  MPI_File_close(&outMPIBadAccnos);  return 0; }
368
369                                 for (int i = 1; i < processors; i++) {
370                                         //get bad lists
371                                         int badSize;
372                                         MPI_Recv(&badSize, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
373                                 }
374                         }else{ //you are a child process
375                                 MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
376                                 MPIPos.resize(numFastaSeqs+1);
377                                 MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
378
379                                 //figure out how many sequences you have to align
380                                 numSeqsPerProcessor = numFastaSeqs / processors;
381                                 int startIndex =  pid * numSeqsPerProcessor;
382                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
383
384                                 //align your part
385                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIGood, outMPIBadAccnos, MPIPos, badSeqNames);
386
387                                 if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIGood);  MPI_File_close(&outMPIBadAccnos); return 0; }
388                                 
389                                 //send bad list 
390                                 int badSize = badSeqNames.size();
391                                 MPI_Send(&badSize, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
392                         }
393                         
394                         //close files 
395                         MPI_File_close(&inMPI);
396                         MPI_File_close(&outMPIGood);
397                         MPI_File_close(&outMPIBadAccnos);
398                         MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
399                                         
400 #else
401         if(processors == 1){ numFastaSeqs = driver(lines[0], goodSeqFile, badAccnosFile, fastafile, badSeqNames);       }       
402         else{ numFastaSeqs = createProcesses(goodSeqFile, badAccnosFile, fastafile, badSeqNames); }
403         
404         if (m->control_pressed) { m->mothurRemove(goodSeqFile); return 0; }
405 #endif          
406
407                 #ifdef USE_MPI
408                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
409                                         
410                         if (pid == 0) { //only one process should fix files
411                         
412                                 //read accnos file with all names in it, process 0 just has its names
413                                 MPI_File inMPIAccnos;
414                                 MPI_Offset size;
415                         
416                                 char inFileName[1024];
417                                 strcpy(inFileName, badAccnosFile.c_str());
418                         
419                                 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPIAccnos);  //comm, filename, mode, info, filepointer
420                                 MPI_File_get_size(inMPIAccnos, &size);
421                         
422                                 char* buffer = new char[size];
423                                 MPI_File_read(inMPIAccnos, buffer, size, MPI_CHAR, &status);
424                         
425                                 string tempBuf = buffer;
426                                 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
427                                 istringstream iss (tempBuf,istringstream::in);
428
429                                 delete buffer;
430                                 MPI_File_close(&inMPIAccnos);
431                                 
432                                 badSeqNames.clear();
433                                 string tempName;
434                                 while (!iss.eof()) {
435                                         iss >> tempName; m->gobble(iss);
436                                         badSeqNames.insert(tempName);
437                                 }
438                 #endif
439                                                                                                                                                                         
440                 if(namefile != "" && groupfile != "")   {       
441                         screenNameGroupFile(badSeqNames);       
442                         if (m->control_pressed) {  m->mothurRemove(goodSeqFile); return 0; }
443                 }else if(namefile != "")        {       
444                         screenNameGroupFile(badSeqNames);
445                         if (m->control_pressed) {  m->mothurRemove(goodSeqFile);  return 0; }   
446                 }else if(groupfile != "")                               {       screenGroupFile(badSeqNames);           }       // this screens just the group
447                 
448                 if (m->control_pressed) { m->mothurRemove(goodSeqFile);  return 0; }
449
450                 if(alignreport != "")                                   {       screenAlignReport(badSeqNames);         }
451                 if(qualfile != "")                                              {       screenQual(badSeqNames);                        }
452                 if(taxonomy != "")                                              {       screenTaxonomy(badSeqNames);            }
453                 
454                 if (m->control_pressed) { m->mothurRemove(goodSeqFile);  return 0; }
455                 
456                 #ifdef USE_MPI
457                         }
458                 #endif
459
460                 m->mothurOutEndLine();
461                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
462                 m->mothurOut(goodSeqFile); m->mothurOutEndLine();       outputTypes["fasta"].push_back(goodSeqFile);
463                 m->mothurOut(badAccnosFile); m->mothurOutEndLine();      outputTypes["accnos"].push_back(badAccnosFile);
464                 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
465                 m->mothurOutEndLine();
466                 m->mothurOutEndLine();
467                 
468                 //set fasta file as new current fastafile
469                 string current = "";
470                 itTypes = outputTypes.find("fasta");
471                 if (itTypes != outputTypes.end()) {
472                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
473                 }
474                 
475                 itTypes = outputTypes.find("name");
476                 if (itTypes != outputTypes.end()) {
477                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
478                 }
479                 
480                 itTypes = outputTypes.find("group");
481                 if (itTypes != outputTypes.end()) {
482                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
483                 }
484                 
485                 itTypes = outputTypes.find("qfile");
486                 if (itTypes != outputTypes.end()) {
487                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setQualFile(current); }
488                 }
489                 
490                 itTypes = outputTypes.find("taxonomy");
491                 if (itTypes != outputTypes.end()) {
492                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTaxonomyFile(current); }
493                 }
494
495                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to screen " + toString(numFastaSeqs) + " sequences.");
496                 m->mothurOutEndLine();
497
498                 return 0;
499         }
500         catch(exception& e) {
501                 m->errorOut(e, "ScreenSeqsCommand", "execute");
502                 exit(1);
503         }
504 }
505
506 //***************************************************************************************************************
507
508 int ScreenSeqsCommand::screenNameGroupFile(set<string> badSeqNames){
509         try {
510                 ifstream inputNames;
511                 m->openInputFile(namefile, inputNames);
512                 set<string> badSeqGroups;
513                 string seqName, seqList, group;
514                 set<string>::iterator it;
515
516                 string goodNameFile = outputDir + m->getRootName(m->getSimpleName(namefile)) + "good" + m->getExtension(namefile);
517                 outputNames.push_back(goodNameFile);  outputTypes["name"].push_back(goodNameFile);
518                 
519                 ofstream goodNameOut;   m->openOutputFile(goodNameFile, goodNameOut);
520                 
521                 while(!inputNames.eof()){
522                         if (m->control_pressed) { goodNameOut.close();  inputNames.close(); m->mothurRemove(goodNameFile);  return 0; }
523
524                         inputNames >> seqName >> seqList;
525                         it = badSeqNames.find(seqName);
526                                 
527                         if(it != badSeqNames.end()){
528                                 badSeqNames.erase(it);
529                                 
530                                 if(namefile != ""){
531                                         int start = 0;
532                                         for(int i=0;i<seqList.length();i++){
533                                                 if(seqList[i] == ','){
534                                                         badSeqGroups.insert(seqList.substr(start,i-start));
535                                                         start = i+1;
536                                                 }                                       
537                                         }
538                                         badSeqGroups.insert(seqList.substr(start,seqList.length()-start));
539                                 }
540                         }
541                         else{
542                                 goodNameOut << seqName << '\t' << seqList << endl;
543                         }
544                         m->gobble(inputNames);
545                 }
546                 inputNames.close();
547                 goodNameOut.close();
548         
549                 //we were unable to remove some of the bad sequences
550                 if (badSeqNames.size() != 0) {
551                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
552                                 m->mothurOut("Your namefile does not include the sequence " + *it + " please correct."); 
553                                 m->mothurOutEndLine();
554                         }
555                 }
556
557                 if(groupfile != ""){
558                         
559                         ifstream inputGroups;
560                         m->openInputFile(groupfile, inputGroups);
561
562                         string goodGroupFile = outputDir + m->getRootName(m->getSimpleName(groupfile)) + "good" + m->getExtension(groupfile);
563                         outputNames.push_back(goodGroupFile);   outputTypes["group"].push_back(goodGroupFile);
564                         
565                         ofstream goodGroupOut;  m->openOutputFile(goodGroupFile, goodGroupOut);
566                         
567                         while(!inputGroups.eof()){
568                                 if (m->control_pressed) { goodGroupOut.close(); inputGroups.close(); m->mothurRemove(goodNameFile);  m->mothurRemove(goodGroupFile); return 0; }
569
570                                 inputGroups >> seqName >> group;
571                                 
572                                 it = badSeqGroups.find(seqName);
573                                 
574                                 if(it != badSeqGroups.end()){
575                                         badSeqGroups.erase(it);
576                                 }
577                                 else{
578                                         goodGroupOut << seqName << '\t' << group << endl;
579                                 }
580                                 m->gobble(inputGroups);
581                         }
582                         inputGroups.close();
583                         goodGroupOut.close();
584                         
585                         //we were unable to remove some of the bad sequences
586                         if (badSeqGroups.size() != 0) {
587                                 for (it = badSeqGroups.begin(); it != badSeqGroups.end(); it++) {  
588                                         m->mothurOut("Your groupfile does not include the sequence " + *it + " please correct."); 
589                                         m->mothurOutEndLine();
590                                 }
591                         }
592                 }
593                 
594                 
595                 return 0;
596         
597         }
598         catch(exception& e) {
599                 m->errorOut(e, "ScreenSeqsCommand", "screenNameGroupFile");
600                 exit(1);
601         }
602 }
603 //***************************************************************************************************************
604 int ScreenSeqsCommand::getSummary(vector<unsigned long long>& positions){
605         try {
606                 
607                 vector<int> startPosition;
608                 vector<int> endPosition;
609                 vector<int> seqLength;
610                 vector<int> ambigBases;
611                 vector<int> longHomoPolymer;
612                 
613         vector<unsigned long long> positions;
614 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
615                 positions = m->divideFile(fastafile, processors);
616                 for (int i = 0; i < (positions.size()-1); i++) { lines.push_back(linePair(positions[i], positions[(i+1)])); }   
617 #else
618                 if(processors == 1){ lines.push_back(linePair(0, 1000));  }
619         else {
620             int numFastaSeqs = 0;
621             positions = m->setFilePosFasta(fastafile, numFastaSeqs); 
622             
623             //figure out how many sequences you have to process
624             int numSeqsPerProcessor = numFastaSeqs / processors;
625             for (int i = 0; i < processors; i++) {
626                 int startIndex =  i * numSeqsPerProcessor;
627                 if(i == (processors - 1)){      numSeqsPerProcessor = numFastaSeqs - i * numSeqsPerProcessor;   }
628                 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
629             }
630         }
631 #endif
632                 
633 #ifdef USE_MPI
634                 int pid;
635                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
636                 
637                 if (pid == 0) { 
638                         driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
639 #else
640                 int numSeqs = 0;
641                 //#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
642                         if(processors == 1){
643                                 numSeqs = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
644                         }else{
645                                 numSeqs = createProcessesCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile); 
646                         }
647                                 
648                         if (m->control_pressed) {  return 0; }
649                 //#else
650                 //      numSeqs = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
651                 //      if (m->control_pressed) {  return 0; }
652                 //#endif
653 #endif
654                 sort(startPosition.begin(), startPosition.end());
655                 sort(endPosition.begin(), endPosition.end());
656                 sort(seqLength.begin(), seqLength.end());
657                 sort(ambigBases.begin(), ambigBases.end());
658                 sort(longHomoPolymer.begin(), longHomoPolymer.end());
659                 
660                 //numSeqs is the number of unique seqs, startPosition.size() is the total number of seqs, we want to optimize using all seqs
661                 int criteriaPercentile  = int(startPosition.size() * (criteria / (float) 100));
662                 
663                 for (int i = 0; i < optimize.size(); i++) {
664                         if (optimize[i] == "start") { startPos = startPosition[criteriaPercentile]; m->mothurOut("Optimizing start to " + toString(startPos) + "."); m->mothurOutEndLine(); }
665                         else if (optimize[i] == "end") { int endcriteriaPercentile = int(endPosition.size() * ((100 - criteria) / (float) 100));  endPos = endPosition[endcriteriaPercentile]; m->mothurOut("Optimizing end to " + toString(endPos) + "."); m->mothurOutEndLine();}
666                         else if (optimize[i] == "maxambig") { maxAmbig = ambigBases[criteriaPercentile]; m->mothurOut("Optimizing maxambig to " + toString(maxAmbig) + "."); m->mothurOutEndLine(); }
667                         else if (optimize[i] == "maxhomop") { maxHomoP = longHomoPolymer[criteriaPercentile]; m->mothurOut("Optimizing maxhomop to " + toString(maxHomoP) + "."); m->mothurOutEndLine(); }
668                         else if (optimize[i] == "minlength") { int mincriteriaPercentile = int(seqLength.size() * ((100 - criteria) / (float) 100)); minLength = seqLength[mincriteriaPercentile]; m->mothurOut("Optimizing minlength to " + toString(minLength) + "."); m->mothurOutEndLine(); }
669                         else if (optimize[i] == "maxlength") { maxLength = seqLength[criteriaPercentile]; m->mothurOut("Optimizing maxlength to " + toString(maxLength) + "."); m->mothurOutEndLine(); }
670                 }
671
672 #ifdef USE_MPI
673                 }
674                 
675                 MPI_Status status; 
676                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
677                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
678                         
679                 if (pid == 0) { 
680                         //send file positions to all processes
681                         for(int i = 1; i < processors; i++) { 
682                                 MPI_Send(&startPos, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
683                                 MPI_Send(&endPos, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
684                                 MPI_Send(&maxAmbig, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
685                                 MPI_Send(&maxHomoP, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
686                                 MPI_Send(&minLength, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
687                                 MPI_Send(&maxLength, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
688                         }
689                 }else {
690                         MPI_Recv(&startPos, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
691                         MPI_Recv(&endPos, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
692                         MPI_Recv(&maxAmbig, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
693                         MPI_Recv(&maxHomoP, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
694                         MPI_Recv(&minLength, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
695                         MPI_Recv(&maxLength, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
696                 }
697                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
698 #endif
699                 return 0;
700         }
701         catch(exception& e) {
702                 m->errorOut(e, "ScreenSeqsCommand", "getSummary");
703                 exit(1);
704         }
705 }
706 /**************************************************************************************/
707 int ScreenSeqsCommand::driverCreateSummary(vector<int>& startPosition, vector<int>& endPosition, vector<int>& seqLength, vector<int>& ambigBases, vector<int>& longHomoPolymer, string filename, linePair filePos) {    
708         try {
709                 
710                 ifstream in;
711                 m->openInputFile(filename, in);
712                                 
713                 in.seekg(filePos.start);
714
715                 bool done = false;
716                 int count = 0;
717         
718                 while (!done) {
719                                 
720                         if (m->control_pressed) { in.close(); return 1; }
721                                         
722                         Sequence current(in); m->gobble(in);
723         
724                         if (current.getName() != "") {
725                                 int num = 1;
726                                 if (namefile != "") {
727                                         //make sure this sequence is in the namefile, else error 
728                                         map<string, int>::iterator it = nameMap.find(current.getName());
729                                         
730                                         if (it == nameMap.end()) { m->mothurOut("[ERROR]: " + current.getName() + " is not in your namefile, please correct."); m->mothurOutEndLine(); m->control_pressed = true; }
731                                         else { num = it->second; }
732                                 }
733                                 
734                                 //for each sequence this sequence represents
735                                 for (int i = 0; i < num; i++) {
736                                         startPosition.push_back(current.getStartPos());
737                                         endPosition.push_back(current.getEndPos());
738                                         seqLength.push_back(current.getNumBases());
739                                         ambigBases.push_back(current.getAmbigBases());
740                                         longHomoPolymer.push_back(current.getLongHomoPolymer());
741                                 }
742                                 
743                                 count++;
744                         }
745                         //if((count) % 100 == 0){       m->mothurOut("Optimizing sequence: " + toString(count)); m->mothurOutEndLine();         }
746                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
747                                 unsigned long long pos = in.tellg();
748                                 if ((pos == -1) || (pos >= filePos.end)) { break; }
749                         #else
750                                 if (in.eof()) { break; }
751                         #endif
752                         
753                 }
754                 
755                 in.close();
756                 
757                 return count;
758         }
759         catch(exception& e) {
760                 m->errorOut(e, "ScreenSeqsCommand", "driverCreateSummary");
761                 exit(1);
762         }
763 }
764 /**************************************************************************************************/
765 int ScreenSeqsCommand::createProcessesCreateSummary(vector<int>& startPosition, vector<int>& endPosition, vector<int>& seqLength, vector<int>& ambigBases, vector<int>& longHomoPolymer, string filename) {
766         try {
767         
768         int process = 1;
769                 int num = 0;
770                 vector<int> processIDS;
771
772 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
773                                 
774                 //loop through and create all the processes you want
775                 while (process != processors) {
776                         int pid = fork();
777                         
778                         if (pid > 0) {
779                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
780                                 process++;
781                         }else if (pid == 0){
782                                 num = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[process]);
783                                 
784                                 //pass numSeqs to parent
785                                 ofstream out;
786                                 string tempFile = fastafile + toString(getpid()) + ".num.temp";
787                                 m->openOutputFile(tempFile, out);
788                                 
789                                 out << num << endl;
790                                 out << startPosition.size() << endl;
791                                 for (int k = 0; k < startPosition.size(); k++)          {               out << startPosition[k] << '\t'; }  out << endl;
792                                 for (int k = 0; k < endPosition.size(); k++)            {               out << endPosition[k] << '\t'; }  out << endl;
793                                 for (int k = 0; k < seqLength.size(); k++)                      {               out << seqLength[k] << '\t'; }  out << endl;
794                                 for (int k = 0; k < ambigBases.size(); k++)                     {               out << ambigBases[k] << '\t'; }  out << endl;
795                                 for (int k = 0; k < longHomoPolymer.size(); k++)        {               out << longHomoPolymer[k] << '\t'; }  out << endl;
796                                 
797                                 out.close();
798                                 
799                                 exit(0);
800                         }else { 
801                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
802                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
803                                 exit(0);
804                         }
805                 }
806                 
807                 num = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
808                 
809                 //force parent to wait until all the processes are done
810                 for (int i=0;i<processIDS.size();i++) { 
811                         int temp = processIDS[i];
812                         wait(&temp);
813                 }
814                 
815                 //parent reads in and combine Filter info
816                 for (int i = 0; i < processIDS.size(); i++) {
817                         string tempFilename = fastafile + toString(processIDS[i]) + ".num.temp";
818                         ifstream in;
819                         m->openInputFile(tempFilename, in);
820                         
821                         int temp, tempNum;
822                         in >> tempNum; m->gobble(in); num += tempNum;
823                         in >> tempNum; m->gobble(in);
824                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; startPosition.push_back(temp);              }               m->gobble(in);
825                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; endPosition.push_back(temp);                }               m->gobble(in);
826                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; seqLength.push_back(temp);                  }               m->gobble(in);
827                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; ambigBases.push_back(temp);                 }               m->gobble(in);
828                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; longHomoPolymer.push_back(temp);    }               m->gobble(in);
829                                 
830                         in.close();
831                         m->mothurRemove(tempFilename);
832                 }
833                 
834                 
835 #else 
836         //////////////////////////////////////////////////////////////////////////////////////////////////////
837                 //Windows version shared memory, so be careful when passing variables through the seqSumData struct. 
838                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
839                 //Taking advantage of shared memory to allow both threads to add info to vectors.
840                 //////////////////////////////////////////////////////////////////////////////////////////////////////
841                 
842                 vector<sumData*> pDataArray; 
843                 DWORD   dwThreadIdArray[processors-1];
844                 HANDLE  hThreadArray[processors-1]; 
845                 
846                 //Create processor worker threads.
847                 for( int i=0; i<processors-1; i++ ){
848             
849                         // Allocate memory for thread data.
850                         sumData* tempSum = new sumData(filename, m, lines[i].start, lines[i].end, namefile, nameMap);
851                         pDataArray.push_back(tempSum);
852                         
853                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
854                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
855                         hThreadArray[i] = CreateThread(NULL, 0, MySumThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
856                 }
857                 
858         //do your part
859                 num = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[processors-1]);
860          
861                 //Wait until all threads have terminated.
862                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
863                 
864                 //Close all thread handles and free memory allocations.
865                 for(int i=0; i < pDataArray.size(); i++){
866                         num += pDataArray[i]->count;
867             for (int k = 0; k < pDataArray[i]->startPosition.size(); k++) {     startPosition.push_back(pDataArray[i]->startPosition[k]);       }
868                         for (int k = 0; k < pDataArray[i]->endPosition.size(); k++) {   endPosition.push_back(pDataArray[i]->endPosition[k]);       }
869             for (int k = 0; k < pDataArray[i]->seqLength.size(); k++) { seqLength.push_back(pDataArray[i]->seqLength[k]);       }
870             for (int k = 0; k < pDataArray[i]->ambigBases.size(); k++) {        ambigBases.push_back(pDataArray[i]->ambigBases[k]);       }
871             for (int k = 0; k < pDataArray[i]->longHomoPolymer.size(); k++) {   longHomoPolymer.push_back(pDataArray[i]->longHomoPolymer[k]);       }
872                         CloseHandle(hThreadArray[i]);
873                         delete pDataArray[i];
874                 }
875
876 #endif          
877         return num;
878         }
879         catch(exception& e) {
880                 m->errorOut(e, "ScreenSeqsCommand", "createProcessesCreateSummary");
881                 exit(1);
882         }
883 }
884
885 //***************************************************************************************************************
886
887 int ScreenSeqsCommand::screenGroupFile(set<string> badSeqNames){
888         try {
889                 ifstream inputGroups;
890                 m->openInputFile(groupfile, inputGroups);
891                 string seqName, group;
892                 set<string>::iterator it;
893                 
894                 string goodGroupFile = outputDir + m->getRootName(m->getSimpleName(groupfile)) + "good" + m->getExtension(groupfile);
895                 outputNames.push_back(goodGroupFile);  outputTypes["group"].push_back(goodGroupFile);
896                 ofstream goodGroupOut;  m->openOutputFile(goodGroupFile, goodGroupOut);
897                 
898                 while(!inputGroups.eof()){
899                         if (m->control_pressed) { goodGroupOut.close(); inputGroups.close(); m->mothurRemove(goodGroupFile); return 0; }
900
901                         inputGroups >> seqName >> group;
902                         it = badSeqNames.find(seqName);
903                         
904                         if(it != badSeqNames.end()){
905                                 badSeqNames.erase(it);
906                         }
907                         else{
908                                 goodGroupOut << seqName << '\t' << group << endl;
909                         }
910                         m->gobble(inputGroups);
911                 }
912                 
913                 if (m->control_pressed) { goodGroupOut.close();  inputGroups.close(); m->mothurRemove(goodGroupFile);  return 0; }
914
915                 //we were unable to remove some of the bad sequences
916                 if (badSeqNames.size() != 0) {
917                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
918                                 m->mothurOut("Your groupfile does not include the sequence " + *it + " please correct."); 
919                                 m->mothurOutEndLine();
920                         }
921                 }
922                 
923                 inputGroups.close();
924                 goodGroupOut.close();
925                 
926                 if (m->control_pressed) { m->mothurRemove(goodGroupFile);   }
927                 
928                 return 0;
929         
930         }
931         catch(exception& e) {
932                 m->errorOut(e, "ScreenSeqsCommand", "screenGroupFile");
933                 exit(1);
934         }
935 }
936
937 //***************************************************************************************************************
938
939 int ScreenSeqsCommand::screenAlignReport(set<string> badSeqNames){
940         try {
941                 ifstream inputAlignReport;
942                 m->openInputFile(alignreport, inputAlignReport);
943                 string seqName, group;
944                 set<string>::iterator it;
945                 
946                 string goodAlignReportFile = outputDir + m->getRootName(m->getSimpleName(alignreport)) + "good" + m->getExtension(alignreport);
947                 outputNames.push_back(goodAlignReportFile);  outputTypes["alignreport"].push_back(goodAlignReportFile);
948                 ofstream goodAlignReportOut;    m->openOutputFile(goodAlignReportFile, goodAlignReportOut);
949
950                 while (!inputAlignReport.eof()) {               //      need to copy header
951                         char c = inputAlignReport.get();
952                         goodAlignReportOut << c;
953                         if (c == 10 || c == 13){        break;  }       
954                 }
955
956                 while(!inputAlignReport.eof()){
957                         if (m->control_pressed) { goodAlignReportOut.close(); inputAlignReport.close(); m->mothurRemove(goodAlignReportFile); return 0; }
958
959                         inputAlignReport >> seqName;
960                         it = badSeqNames.find(seqName);
961                         string line;            
962                         while (!inputAlignReport.eof()) {               //      need to copy header
963                                 char c = inputAlignReport.get();
964                                 line += c;
965                                 if (c == 10 || c == 13){        break;  }       
966                         }
967                         
968                         if(it != badSeqNames.end()){
969                                 badSeqNames.erase(it);
970                         }
971                         else{
972                                 goodAlignReportOut << seqName << '\t' << line;
973                         }
974                         m->gobble(inputAlignReport);
975                 }
976                 
977                 if (m->control_pressed) { goodAlignReportOut.close();  inputAlignReport.close(); m->mothurRemove(goodAlignReportFile);  return 0; }
978
979                 //we were unable to remove some of the bad sequences
980                 if (badSeqNames.size() != 0) {
981                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
982                                 m->mothurOut("Your alignreport file does not include the sequence " + *it + " please correct."); 
983                                 m->mothurOutEndLine();
984                         }
985                 }
986
987                 inputAlignReport.close();
988                 goodAlignReportOut.close();
989                                 
990                 if (m->control_pressed) {  m->mothurRemove(goodAlignReportFile);  return 0; }
991                 
992                 return 0;
993         
994         }
995         catch(exception& e) {
996                 m->errorOut(e, "ScreenSeqsCommand", "screenAlignReport");
997                 exit(1);
998         }
999         
1000 }
1001 //***************************************************************************************************************
1002
1003 int ScreenSeqsCommand::screenTaxonomy(set<string> badSeqNames){
1004         try {
1005                 ifstream input;
1006                 m->openInputFile(taxonomy, input);
1007                 string seqName, tax;
1008                 set<string>::iterator it;
1009                 
1010                 string goodTaxFile = outputDir + m->getRootName(m->getSimpleName(taxonomy)) + "good" + m->getExtension(taxonomy);
1011                 outputNames.push_back(goodTaxFile);  outputTypes["taxonomy"].push_back(goodTaxFile);
1012                 ofstream goodTaxOut;    m->openOutputFile(goodTaxFile, goodTaxOut);
1013                                 
1014                 while(!input.eof()){
1015                         if (m->control_pressed) { goodTaxOut.close(); input.close(); m->mothurRemove(goodTaxFile); return 0; }
1016                         
1017                         input >> seqName >> tax;
1018                         it = badSeqNames.find(seqName);
1019                         
1020                         if(it != badSeqNames.end()){ badSeqNames.erase(it); }
1021                         else{
1022                                 goodTaxOut << seqName << '\t' << tax << endl;
1023                         }
1024                         m->gobble(input);
1025                 }
1026                 
1027                 if (m->control_pressed) { goodTaxOut.close(); input.close(); m->mothurRemove(goodTaxFile); return 0; }
1028                 
1029                 //we were unable to remove some of the bad sequences
1030                 if (badSeqNames.size() != 0) {
1031                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
1032                                 m->mothurOut("Your taxonomy file does not include the sequence " + *it + " please correct."); 
1033                                 m->mothurOutEndLine();
1034                         }
1035                 }
1036                 
1037                 input.close();
1038                 goodTaxOut.close();
1039                 
1040                 if (m->control_pressed) {  m->mothurRemove(goodTaxFile);  return 0; }
1041                 
1042                 return 0;
1043                 
1044         }
1045         catch(exception& e) {
1046                 m->errorOut(e, "ScreenSeqsCommand", "screenTaxonomy");
1047                 exit(1);
1048         }
1049         
1050 }
1051 //***************************************************************************************************************
1052
1053 int ScreenSeqsCommand::screenQual(set<string> badSeqNames){
1054         try {
1055                 ifstream in;
1056                 m->openInputFile(qualfile, in);
1057                 set<string>::iterator it;
1058                 
1059                 string goodQualFile = outputDir + m->getRootName(m->getSimpleName(qualfile)) + "good" + m->getExtension(qualfile);
1060                 outputNames.push_back(goodQualFile);  outputTypes["qfile"].push_back(goodQualFile);
1061                 ofstream goodQual;      m->openOutputFile(goodQualFile, goodQual);
1062                 
1063                 while(!in.eof()){       
1064                         
1065                         if (m->control_pressed) { goodQual.close(); in.close(); m->mothurRemove(goodQualFile); return 0; }
1066
1067                         string saveName = "";
1068                         string name = "";
1069                         string scores = "";
1070                         
1071                         in >> name; 
1072                         
1073                         if (name.length() != 0) { 
1074                                 saveName = name.substr(1);
1075                                 while (!in.eof())       {       
1076                                         char c = in.get(); 
1077                                         if (c == 10 || c == 13){        break;  }
1078                                         else { name += c; }     
1079                                 } 
1080                                 m->gobble(in);
1081                         }
1082                         
1083                         while(in){
1084                                 char letter= in.get();
1085                                 if(letter == '>'){      in.putback(letter);     break;  }
1086                                 else{ scores += letter; }
1087                         }
1088                         
1089                         m->gobble(in);
1090                         
1091                         it = badSeqNames.find(saveName);
1092                         
1093                         if(it != badSeqNames.end()){
1094                                 badSeqNames.erase(it);
1095                         }else{                          
1096                                 goodQual << name << endl << scores;
1097                         }
1098                         
1099                         m->gobble(in);
1100                 }
1101                 
1102                 in.close();
1103                 goodQual.close();
1104                 
1105                 //we were unable to remove some of the bad sequences
1106                 if (badSeqNames.size() != 0) {
1107                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
1108                                 m->mothurOut("Your qual file does not include the sequence " + *it + " please correct."); 
1109                                 m->mothurOutEndLine();
1110                         }
1111                 }
1112                 
1113                 if (m->control_pressed) {  m->mothurRemove(goodQualFile);  return 0; }
1114                 
1115                 return 0;
1116                 
1117         }
1118         catch(exception& e) {
1119                 m->errorOut(e, "ScreenSeqsCommand", "screenQual");
1120                 exit(1);
1121         }
1122         
1123 }
1124 //**********************************************************************************************************************
1125
1126 int ScreenSeqsCommand::driver(linePair filePos, string goodFName, string badAccnosFName, string filename, set<string>& badSeqNames){
1127         try {
1128                 ofstream goodFile;
1129                 m->openOutputFile(goodFName, goodFile);
1130                 
1131                 ofstream badAccnosFile;
1132                 m->openOutputFile(badAccnosFName, badAccnosFile);
1133                 
1134                 ifstream inFASTA;
1135                 m->openInputFile(filename, inFASTA);
1136
1137                 inFASTA.seekg(filePos.start);
1138
1139                 bool done = false;
1140                 int count = 0;
1141         
1142                 while (!done) {
1143                 
1144                         if (m->control_pressed) {  return 0; }
1145                         
1146                         Sequence currSeq(inFASTA); m->gobble(inFASTA);
1147                         if (currSeq.getName() != "") {
1148                                 bool goodSeq = 1;               //      innocent until proven guilty
1149                                 if(goodSeq == 1 && startPos != -1 && startPos < currSeq.getStartPos())                  {       goodSeq = 0;    }
1150                                 if(goodSeq == 1 && endPos != -1 && endPos > currSeq.getEndPos())                                {       goodSeq = 0;    }
1151                                 if(goodSeq == 1 && maxAmbig != -1 && maxAmbig < currSeq.getAmbigBases())                {       goodSeq = 0;    }
1152                                 if(goodSeq == 1 && maxHomoP != -1 && maxHomoP < currSeq.getLongHomoPolymer())   {       goodSeq = 0;    }
1153                                 if(goodSeq == 1 && minLength != -1 && minLength > currSeq.getNumBases())                {       goodSeq = 0;    }
1154                                 if(goodSeq == 1 && maxLength != -1 && maxLength < currSeq.getNumBases())                {       goodSeq = 0;    }
1155                                 
1156                                 if(goodSeq == 1){
1157                                         currSeq.printSequence(goodFile);        
1158                                 }
1159                                 else{
1160                                         badAccnosFile << currSeq.getName() << endl;
1161                                         badSeqNames.insert(currSeq.getName());
1162                                 }
1163                         count++;
1164                         }
1165                         
1166                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1167                                 unsigned long long pos = inFASTA.tellg();
1168                                 if ((pos == -1) || (pos >= filePos.end)) { break; }
1169                         #else
1170                                 if (inFASTA.eof()) { break; }
1171                         #endif
1172                         
1173                         //report progress
1174                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1175                 }
1176                 //report progress
1177                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1178                 
1179                         
1180                 goodFile.close();
1181                 inFASTA.close();
1182                 badAccnosFile.close();
1183                 
1184                 return count;
1185         }
1186         catch(exception& e) {
1187                 m->errorOut(e, "ScreenSeqsCommand", "driver");
1188                 exit(1);
1189         }
1190 }
1191 //**********************************************************************************************************************
1192 #ifdef USE_MPI
1193 int ScreenSeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& goodFile, MPI_File& badAccnosFile, vector<unsigned long long>& MPIPos, set<string>& badSeqNames){
1194         try {
1195                 string outputString = "";
1196                 MPI_Status statusGood; 
1197                 MPI_Status statusBadAccnos; 
1198                 MPI_Status status; 
1199                 int pid;
1200                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1201
1202                 for(int i=0;i<num;i++){
1203                 
1204                         if (m->control_pressed) {  return 0; }
1205                         
1206                         //read next sequence
1207                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1208
1209                         char* buf4 = new char[length];
1210                         memcpy(buf4, outputString.c_str(), length);
1211
1212                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1213                         
1214                         string tempBuf = buf4;  delete buf4;
1215                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1216                         istringstream iss (tempBuf,istringstream::in);
1217                         
1218                         Sequence currSeq(iss);                  
1219                         
1220                         //process seq
1221                         if (currSeq.getName() != "") {
1222                                 bool goodSeq = 1;               //      innocent until proven guilty
1223                                 if(goodSeq == 1 && startPos != -1 && startPos < currSeq.getStartPos())                  {       goodSeq = 0;    }
1224                                 if(goodSeq == 1 && endPos != -1 && endPos > currSeq.getEndPos())                                {       goodSeq = 0;    }
1225                                 if(goodSeq == 1 && maxAmbig != -1 && maxAmbig < currSeq.getAmbigBases())                {       goodSeq = 0;    }
1226                                 if(goodSeq == 1 && maxHomoP != -1 && maxHomoP < currSeq.getLongHomoPolymer())   {       goodSeq = 0;    }
1227                                 if(goodSeq == 1 && minLength != -1 && minLength > currSeq.getNumBases())                {       goodSeq = 0;    }
1228                                 if(goodSeq == 1 && maxLength != -1 && maxLength < currSeq.getNumBases())                {       goodSeq = 0;    }
1229                                 
1230                                 if(goodSeq == 1){
1231                                         outputString =  ">" + currSeq.getName() + "\n" + currSeq.getAligned() + "\n";
1232                                 
1233                                         //print good seq
1234                                         length = outputString.length();
1235                                         char* buf2 = new char[length];
1236                                         memcpy(buf2, outputString.c_str(), length);
1237                                         
1238                                         MPI_File_write_shared(goodFile, buf2, length, MPI_CHAR, &statusGood);
1239                                         delete buf2;
1240                                 }
1241                                 else{
1242
1243                                         badSeqNames.insert(currSeq.getName());
1244                                         
1245                                         //write to bad accnos file
1246                                         outputString = currSeq.getName() + "\n";
1247                                 
1248                                         length = outputString.length();
1249                                         char* buf3 = new char[length];
1250                                         memcpy(buf3, outputString.c_str(), length);
1251                                         
1252                                         MPI_File_write_shared(badAccnosFile, buf3, length, MPI_CHAR, &statusBadAccnos);
1253                                         delete buf3;
1254                                 }
1255                         }
1256                         
1257                         //report progress
1258                         if((i) % 100 == 0){     m->mothurOut("Processing sequence: " + toString(i)); m->mothurOutEndLine();             }
1259                 }
1260                                 
1261                 return 1;
1262         }
1263         catch(exception& e) {
1264                 m->errorOut(e, "ScreenSeqsCommand", "driverMPI");
1265                 exit(1);
1266         }
1267 }
1268 #endif
1269 /**************************************************************************************************/
1270
1271 int ScreenSeqsCommand::createProcesses(string goodFileName, string badAccnos, string filename, set<string>& badSeqNames) {
1272         try {
1273         
1274         vector<int> processIDS;   
1275         int process = 1;
1276                 int num = 0;
1277
1278 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1279                                 
1280                 //loop through and create all the processes you want
1281                 while (process != processors) {
1282                         int pid = fork();
1283                         
1284                         if (pid > 0) {
1285                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1286                                 process++;
1287                         }else if (pid == 0){
1288                                 num = driver(lines[process], goodFileName + toString(getpid()) + ".temp", badAccnos + toString(getpid()) + ".temp", filename, badSeqNames);
1289                                 
1290                                 //pass numSeqs to parent
1291                                 ofstream out;
1292                                 string tempFile = filename + toString(getpid()) + ".num.temp";
1293                                 m->openOutputFile(tempFile, out);
1294                                 out << num << endl;
1295                                 out.close();
1296                                 
1297                                 exit(0);
1298                         }else { 
1299                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1300                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1301                                 exit(0);
1302                         }
1303                 }
1304                 
1305         num = driver(lines[0], goodFileName, badAccnos, filename, badSeqNames);
1306         
1307                 //force parent to wait until all the processes are done
1308                 for (int i=0;i<processIDS.size();i++) { 
1309                         int temp = processIDS[i];
1310                         wait(&temp);
1311                 }
1312                 
1313                 for (int i = 0; i < processIDS.size(); i++) {
1314                         ifstream in;
1315                         string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
1316                         m->openInputFile(tempFile, in);
1317                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1318                         in.close(); m->mothurRemove(tempFile);
1319             
1320             m->appendFiles((goodFileName + toString(processIDS[i]) + ".temp"), goodFileName);
1321             m->mothurRemove((goodFileName + toString(processIDS[i]) + ".temp"));
1322                         
1323             m->appendFiles((badAccnos + toString(processIDS[i]) + ".temp"), badAccnos);
1324             m->mothurRemove((badAccnos + toString(processIDS[i]) + ".temp"));
1325                 }
1326                 
1327         //read badSeqs in because root process doesnt know what other "bad" seqs the children found
1328         ifstream inBad;
1329         int ableToOpen = m->openInputFile(badAccnos, inBad, "no error");
1330         
1331         if (ableToOpen == 0) {
1332             badSeqNames.clear();
1333             string tempName;
1334             while (!inBad.eof()) {
1335                 inBad >> tempName; m->gobble(inBad);
1336                 badSeqNames.insert(tempName);
1337             }
1338             inBad.close();
1339         }
1340 #else
1341         
1342         //////////////////////////////////////////////////////////////////////////////////////////////////////
1343                 //Windows version shared memory, so be careful when passing variables through the sumScreenData struct. 
1344                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
1345                 //Taking advantage of shared memory to allow both threads to add info to badSeqNames.
1346                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1347                 
1348                 vector<sumScreenData*> pDataArray; 
1349                 DWORD   dwThreadIdArray[processors-1];
1350                 HANDLE  hThreadArray[processors-1]; 
1351                 
1352                 //Create processor worker threads.
1353                 for( int i=0; i<processors-1; i++ ){
1354             
1355             string extension = "";
1356             if (i!=0) {extension += toString(i) + ".temp"; processIDS.push_back(i); }
1357             
1358                         // Allocate memory for thread data.
1359                         sumScreenData* tempSum = new sumScreenData(startPos, endPos, maxAmbig, maxHomoP, minLength, maxLength, filename, m, lines[i].start, lines[i].end,goodFileName+extension, badAccnos+extension, &badSeqNames);
1360                         pDataArray.push_back(tempSum);
1361                         
1362                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1363                         hThreadArray[i] = CreateThread(NULL, 0, MySumScreenThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
1364                 }
1365                 
1366         //do your part
1367         num = driver(lines[processors-1], (goodFileName+toString(processors-1)+".temp"), (badAccnos+toString(processors-1)+".temp"), filename, badSeqNames);
1368         processIDS.push_back(processors-1);
1369         
1370                 //Wait until all threads have terminated.
1371                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1372                 
1373                 //Close all thread handles and free memory allocations.
1374                 for(int i=0; i < pDataArray.size(); i++){
1375                         num += pDataArray[i]->count;
1376                         CloseHandle(hThreadArray[i]);
1377                         delete pDataArray[i];
1378                 }
1379         
1380         for (int i = 0; i < processIDS.size(); i++) {
1381             m->appendFiles((goodFileName + toString(processIDS[i]) + ".temp"), goodFileName);
1382             m->mothurRemove((goodFileName + toString(processIDS[i]) + ".temp"));
1383                         
1384             m->appendFiles((badAccnos + toString(processIDS[i]) + ".temp"), badAccnos);
1385             m->mothurRemove((badAccnos + toString(processIDS[i]) + ".temp"));
1386                 }
1387
1388 #endif  
1389         
1390         return num;
1391         
1392         }
1393         catch(exception& e) {
1394                 m->errorOut(e, "ScreenSeqsCommand", "createProcesses");
1395                 exit(1);
1396         }
1397 }
1398
1399 //***************************************************************************************************************
1400
1401