]> git.donarmstrong.com Git - mothur.git/blob - screenseqscommand.cpp
added fontsize to heatmap.sim, paralellized chimera.slayer byGroup for all os's,...
[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 #include "sequence.hpp"
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                         convert(temp, startPos); 
224                 
225                         temp = validParameter.validFile(parameters, "end", false);                      if (temp == "not found") { temp = "-1"; }
226                         convert(temp, endPos);  
227
228                         temp = validParameter.validFile(parameters, "maxambig", false);         if (temp == "not found") { temp = "-1"; }
229                         convert(temp, maxAmbig);  
230
231                         temp = validParameter.validFile(parameters, "maxhomop", false);         if (temp == "not found") { temp = "-1"; }
232                         convert(temp, maxHomoP);  
233
234                         temp = validParameter.validFile(parameters, "minlength", false);        if (temp == "not found") { temp = "-1"; }
235                         convert(temp, minLength); 
236                         
237                         temp = validParameter.validFile(parameters, "maxlength", false);        if (temp == "not found") { temp = "-1"; }
238                         convert(temp, maxLength); 
239                         
240                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
241                         m->setProcessors(temp);
242                         convert(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                         convert(temp, criteria); 
263                 }
264
265         }
266         catch(exception& e) {
267                 m->errorOut(e, "ScreenSeqsCommand", "ScreenSeqsCommand");
268                 exit(1);
269         }
270 }
271 //***************************************************************************************************************
272
273 int ScreenSeqsCommand::execute(){
274         try{
275                 
276                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
277                 
278                 //if the user want to optimize we need to know the 90% mark
279                 vector<unsigned long long> positions;
280                 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
281                         //use the namefile to optimize correctly
282                         if (namefile != "") { nameMap = m->readNames(namefile); }
283                         getSummary(positions); 
284                 } 
285                 else { 
286                         positions = m->divideFile(fastafile, processors);
287                         for (int i = 0; i < (positions.size()-1); i++) {
288                                 lines.push_back(new linePair(positions[i], positions[(i+1)]));
289                         }       
290                 }
291                                 
292                 string goodSeqFile = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "good" + m->getExtension(fastafile);
293                 string badAccnosFile =  outputDir + m->getRootName(m->getSimpleName(fastafile)) + "bad.accnos";
294                 
295                 int numFastaSeqs = 0;
296                 set<string> badSeqNames;
297                 int start = time(NULL);
298         
299 #ifdef USE_MPI  
300                         int pid, numSeqsPerProcessor; 
301                         int tag = 2001;
302                         vector<unsigned long long> MPIPos;
303                         
304                         MPI_Status status; 
305                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
306                         MPI_Comm_size(MPI_COMM_WORLD, &processors); 
307         
308                         MPI_File inMPI;
309                         MPI_File outMPIGood;
310                         MPI_File outMPIBadAccnos;
311                         
312                         int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
313                         int inMode=MPI_MODE_RDONLY; 
314                         
315                         char outGoodFilename[1024];
316                         strcpy(outGoodFilename, goodSeqFile.c_str());
317
318                         char outBadAccnosFilename[1024];
319                         strcpy(outBadAccnosFilename, badAccnosFile.c_str());
320
321                         char inFileName[1024];
322                         strcpy(inFileName, fastafile.c_str());
323                         
324                         MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
325                         MPI_File_open(MPI_COMM_WORLD, outGoodFilename, outMode, MPI_INFO_NULL, &outMPIGood);
326                         MPI_File_open(MPI_COMM_WORLD, outBadAccnosFilename, outMode, MPI_INFO_NULL, &outMPIBadAccnos);
327                         
328                         if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIGood); MPI_File_close(&outMPIBadAccnos); return 0; }
329                         
330                         if (pid == 0) { //you are the root process 
331                                 
332                                 MPIPos = m->setFilePosFasta(fastafile, numFastaSeqs); //fills MPIPos, returns numSeqs
333                                 
334                                 //send file positions to all processes
335                                 for(int i = 1; i < processors; i++) { 
336                                         MPI_Send(&numFastaSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
337                                         MPI_Send(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
338                                 }
339                                 
340                                 //figure out how many sequences you have to align
341                                 numSeqsPerProcessor = numFastaSeqs / processors;
342                                 int startIndex =  pid * numSeqsPerProcessor;
343                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
344                 //      cout << pid << '\t' << numSeqsPerProcessor << '\t' <<   startIndex << endl;
345                                 //align your part
346                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIGood, outMPIBadAccnos, MPIPos, badSeqNames);
347                 //cout << pid << " done" << endl;
348                                 if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIGood);  MPI_File_close(&outMPIBadAccnos);  return 0; }
349
350                                 for (int i = 1; i < processors; i++) {
351                                 
352                                         //get bad lists
353                                         int badSize;
354                                         MPI_Recv(&badSize, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);
355                                         /*for (int j = 0; j < badSize; j++) {
356                                                 int length;
357                                                 MPI_Recv(&length, 1, MPI_INT, i, tag, MPI_COMM_WORLD, &status);  //recv the length of the name
358                                                 char* buf2 = new char[length];                                                                          //make space to recieve it
359                                                 MPI_Recv(buf2, length, MPI_CHAR, i, tag, MPI_COMM_WORLD, &status);  //get name
360                                                 
361                                                 string tempBuf = buf2;
362                                                 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
363                                                 delete buf2;
364                                                 
365                                                 badSeqNames.insert(tempBuf);
366                                         }*/
367                                 }
368                         }else{ //you are a child process
369                                 MPI_Recv(&numFastaSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
370                                 MPIPos.resize(numFastaSeqs+1);
371                                 MPI_Recv(&MPIPos[0], (numFastaSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
372
373                                 //figure out how many sequences you have to align
374                                 numSeqsPerProcessor = numFastaSeqs / processors;
375                                 int startIndex =  pid * numSeqsPerProcessor;
376                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numFastaSeqs - pid * numSeqsPerProcessor;         }
377                 //cout << pid << '\t' << numSeqsPerProcessor << '\t' <<         startIndex << endl;             
378                                 //align your part
379                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPIGood, outMPIBadAccnos, MPIPos, badSeqNames);
380 //cout << pid << " done" << endl;
381                                 if (m->control_pressed) { MPI_File_close(&inMPI);  MPI_File_close(&outMPIGood);  MPI_File_close(&outMPIBadAccnos); return 0; }
382                                 
383                                 //send bad list 
384                                 int badSize = badSeqNames.size();
385                                 MPI_Send(&badSize, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
386                                 
387                                 /*
388                                 set<string>::iterator it;
389                                 for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {
390                                         string name = *it;
391                                         int length = name.length();
392                                         char* buf2 = new char[length];
393                                         memcpy(buf2, name.c_str(), length);
394                                         
395                                         MPI_Send(&length, 1, MPI_INT, 0, tag, MPI_COMM_WORLD);
396                                         MPI_Send(buf2, length, MPI_CHAR, 0, tag, MPI_COMM_WORLD);
397                                 }*/
398                         }
399                         
400                         //close files 
401                         MPI_File_close(&inMPI);
402                         MPI_File_close(&outMPIGood);
403                         MPI_File_close(&outMPIBadAccnos);
404                         MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
405                                         
406 #else
407                                                 
408         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
409                         if(processors == 1){
410                                 numFastaSeqs = driver(lines[0], goodSeqFile, badAccnosFile, fastafile, badSeqNames);
411                                 
412                                 if (m->control_pressed) { m->mothurRemove(goodSeqFile); return 0; }
413                                 
414                         }else{
415                                 processIDS.resize(0);
416                                 
417                                 numFastaSeqs = createProcesses(goodSeqFile, badAccnosFile, fastafile, badSeqNames); 
418                                 
419                                 rename((goodSeqFile + toString(processIDS[0]) + ".temp").c_str(), goodSeqFile.c_str());
420                                 rename((badAccnosFile + toString(processIDS[0]) + ".temp").c_str(), badAccnosFile.c_str());
421                                 
422                                 //append alignment and report files
423                                 for(int i=1;i<processors;i++){
424                                         m->appendFiles((goodSeqFile + toString(processIDS[i]) + ".temp"), goodSeqFile);
425                                         m->mothurRemove((goodSeqFile + toString(processIDS[i]) + ".temp"));
426                         
427                                         m->appendFiles((badAccnosFile + toString(processIDS[i]) + ".temp"), badAccnosFile);
428                                         m->mothurRemove((badAccnosFile + toString(processIDS[i]) + ".temp"));
429                                 }
430                                 
431                                 if (m->control_pressed) { m->mothurRemove(goodSeqFile); return 0; }
432                                 
433                                 //read badSeqs in because root process doesnt know what other "bad" seqs the children found
434                                 ifstream inBad;
435                                 int ableToOpen = m->openInputFile(badAccnosFile, inBad, "no error");
436                                 
437                                 if (ableToOpen == 0) {
438                                         badSeqNames.clear();
439                                         string tempName;
440                                         while (!inBad.eof()) {
441                                                 inBad >> tempName; m->gobble(inBad);
442                                                 badSeqNames.insert(tempName);
443                                         }
444                                         inBad.close();
445                                 }
446                         }
447         #else
448                         numFastaSeqs = driver(lines[0], goodSeqFile, badAccnosFile, fastafile, badSeqNames);
449                         
450                         if (m->control_pressed) { m->mothurRemove(goodSeqFile); return 0; }
451                         
452         #endif
453
454 #endif          
455
456                 #ifdef USE_MPI
457                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
458                                         
459                         if (pid == 0) { //only one process should fix files
460                         
461                                 //read accnos file with all names in it, process 0 just has its names
462                                 MPI_File inMPIAccnos;
463                                 MPI_Offset size;
464                         
465                                 char inFileName[1024];
466                                 strcpy(inFileName, badAccnosFile.c_str());
467                         
468                                 MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPIAccnos);  //comm, filename, mode, info, filepointer
469                                 MPI_File_get_size(inMPIAccnos, &size);
470                         
471                                 char* buffer = new char[size];
472                                 MPI_File_read(inMPIAccnos, buffer, size, MPI_CHAR, &status);
473                         
474                                 string tempBuf = buffer;
475                                 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
476                                 istringstream iss (tempBuf,istringstream::in);
477
478                                 delete buffer;
479                                 MPI_File_close(&inMPIAccnos);
480                                 
481                                 badSeqNames.clear();
482                                 string tempName;
483                                 while (!iss.eof()) {
484                                         iss >> tempName; m->gobble(iss);
485                                         badSeqNames.insert(tempName);
486                                 }
487                 #endif
488                                                                                                                                                                         
489                 if(namefile != "" && groupfile != "")   {       
490                         screenNameGroupFile(badSeqNames);       
491                         if (m->control_pressed) {  m->mothurRemove(goodSeqFile); return 0; }
492                 }else if(namefile != "")        {       
493                         screenNameGroupFile(badSeqNames);
494                         if (m->control_pressed) {  m->mothurRemove(goodSeqFile);  return 0; }   
495                 }else if(groupfile != "")                               {       screenGroupFile(badSeqNames);           }       // this screens just the group
496                 
497                 if (m->control_pressed) { m->mothurRemove(goodSeqFile);  return 0; }
498
499                 if(alignreport != "")                                   {       screenAlignReport(badSeqNames);         }
500                 if(qualfile != "")                                              {       screenQual(badSeqNames);                        }
501                 if(taxonomy != "")                                              {       screenTaxonomy(badSeqNames);            }
502                 
503                 if (m->control_pressed) { m->mothurRemove(goodSeqFile);  return 0; }
504                 
505                 #ifdef USE_MPI
506                         }
507                 #endif
508
509                 m->mothurOutEndLine();
510                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
511                 m->mothurOut(goodSeqFile); m->mothurOutEndLine();       outputTypes["fasta"].push_back(goodSeqFile);
512                 m->mothurOut(badAccnosFile); m->mothurOutEndLine();      outputTypes["accnos"].push_back(badAccnosFile);
513                 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
514                 m->mothurOutEndLine();
515                 m->mothurOutEndLine();
516                 
517                 //set fasta file as new current fastafile
518                 string current = "";
519                 itTypes = outputTypes.find("fasta");
520                 if (itTypes != outputTypes.end()) {
521                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
522                 }
523                 
524                 itTypes = outputTypes.find("name");
525                 if (itTypes != outputTypes.end()) {
526                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
527                 }
528                 
529                 itTypes = outputTypes.find("group");
530                 if (itTypes != outputTypes.end()) {
531                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setGroupFile(current); }
532                 }
533                 
534                 itTypes = outputTypes.find("qfile");
535                 if (itTypes != outputTypes.end()) {
536                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setQualFile(current); }
537                 }
538                 
539                 itTypes = outputTypes.find("taxonomy");
540                 if (itTypes != outputTypes.end()) {
541                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTaxonomyFile(current); }
542                 }
543
544                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to screen " + toString(numFastaSeqs) + " sequences.");
545                 m->mothurOutEndLine();
546
547                 return 0;
548         }
549         catch(exception& e) {
550                 m->errorOut(e, "ScreenSeqsCommand", "execute");
551                 exit(1);
552         }
553 }
554
555 //***************************************************************************************************************
556
557 int ScreenSeqsCommand::screenNameGroupFile(set<string> badSeqNames){
558         try {
559                 ifstream inputNames;
560                 m->openInputFile(namefile, inputNames);
561                 set<string> badSeqGroups;
562                 string seqName, seqList, group;
563                 set<string>::iterator it;
564
565                 string goodNameFile = outputDir + m->getRootName(m->getSimpleName(namefile)) + "good" + m->getExtension(namefile);
566                 outputNames.push_back(goodNameFile);  outputTypes["name"].push_back(goodNameFile);
567                 
568                 ofstream goodNameOut;   m->openOutputFile(goodNameFile, goodNameOut);
569                 
570                 while(!inputNames.eof()){
571                         if (m->control_pressed) { goodNameOut.close();  inputNames.close(); m->mothurRemove(goodNameFile);  return 0; }
572
573                         inputNames >> seqName >> seqList;
574                         it = badSeqNames.find(seqName);
575                                 
576                         if(it != badSeqNames.end()){
577                                 badSeqNames.erase(it);
578                                 
579                                 if(namefile != ""){
580                                         int start = 0;
581                                         for(int i=0;i<seqList.length();i++){
582                                                 if(seqList[i] == ','){
583                                                         badSeqGroups.insert(seqList.substr(start,i-start));
584                                                         start = i+1;
585                                                 }                                       
586                                         }
587                                         badSeqGroups.insert(seqList.substr(start,seqList.length()-start));
588                                 }
589                         }
590                         else{
591                                 goodNameOut << seqName << '\t' << seqList << endl;
592                         }
593                         m->gobble(inputNames);
594                 }
595                 inputNames.close();
596                 goodNameOut.close();
597         
598                 //we were unable to remove some of the bad sequences
599                 if (badSeqNames.size() != 0) {
600                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
601                                 m->mothurOut("Your namefile does not include the sequence " + *it + " please correct."); 
602                                 m->mothurOutEndLine();
603                         }
604                 }
605
606                 if(groupfile != ""){
607                         
608                         ifstream inputGroups;
609                         m->openInputFile(groupfile, inputGroups);
610
611                         string goodGroupFile = outputDir + m->getRootName(m->getSimpleName(groupfile)) + "good" + m->getExtension(groupfile);
612                         outputNames.push_back(goodGroupFile);   outputTypes["group"].push_back(goodGroupFile);
613                         
614                         ofstream goodGroupOut;  m->openOutputFile(goodGroupFile, goodGroupOut);
615                         
616                         while(!inputGroups.eof()){
617                                 if (m->control_pressed) { goodGroupOut.close(); inputGroups.close(); m->mothurRemove(goodNameFile);  m->mothurRemove(goodGroupFile); return 0; }
618
619                                 inputGroups >> seqName >> group;
620                                 
621                                 it = badSeqGroups.find(seqName);
622                                 
623                                 if(it != badSeqGroups.end()){
624                                         badSeqGroups.erase(it);
625                                 }
626                                 else{
627                                         goodGroupOut << seqName << '\t' << group << endl;
628                                 }
629                                 m->gobble(inputGroups);
630                         }
631                         inputGroups.close();
632                         goodGroupOut.close();
633                         
634                         //we were unable to remove some of the bad sequences
635                         if (badSeqGroups.size() != 0) {
636                                 for (it = badSeqGroups.begin(); it != badSeqGroups.end(); it++) {  
637                                         m->mothurOut("Your groupfile does not include the sequence " + *it + " please correct."); 
638                                         m->mothurOutEndLine();
639                                 }
640                         }
641                 }
642                 
643                 
644                 return 0;
645         
646         }
647         catch(exception& e) {
648                 m->errorOut(e, "ScreenSeqsCommand", "screenNameGroupFile");
649                 exit(1);
650         }
651 }
652 //***************************************************************************************************************
653 int ScreenSeqsCommand::getSummary(vector<unsigned long long>& positions){
654         try {
655                 
656                 vector<int> startPosition;
657                 vector<int> endPosition;
658                 vector<int> seqLength;
659                 vector<int> ambigBases;
660                 vector<int> longHomoPolymer;
661                 
662                 vector<unsigned long long> positions = m->divideFile(fastafile, processors);
663                                 
664                 for (int i = 0; i < (positions.size()-1); i++) {
665                         lines.push_back(new linePair(positions[i], positions[(i+1)]));
666                 }       
667                 
668                 
669 #ifdef USE_MPI
670                 int pid;
671                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
672                 
673                 if (pid == 0) { 
674                         driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
675 #else
676                 int numSeqs = 0;
677                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
678                         if(processors == 1){
679                                 numSeqs = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
680                         }else{
681                                 numSeqs = createProcessesCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile); 
682                         }
683                                 
684                         if (m->control_pressed) {  return 0; }
685                 #else
686                         numSeqs = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
687                         if (m->control_pressed) {  return 0; }
688                 #endif
689 #endif
690                 sort(startPosition.begin(), startPosition.end());
691                 sort(endPosition.begin(), endPosition.end());
692                 sort(seqLength.begin(), seqLength.end());
693                 sort(ambigBases.begin(), ambigBases.end());
694                 sort(longHomoPolymer.begin(), longHomoPolymer.end());
695                 
696                 //numSeqs is the number of unique seqs, startPosition.size() is the total number of seqs, we want to optimize using all seqs
697                 int criteriaPercentile  = int(startPosition.size() * (criteria / (float) 100));
698                 
699                 for (int i = 0; i < optimize.size(); i++) {
700                         if (optimize[i] == "start") { startPos = startPosition[criteriaPercentile]; m->mothurOut("Optimizing start to " + toString(startPos) + "."); m->mothurOutEndLine(); }
701                         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();}
702                         else if (optimize[i] == "maxambig") { maxAmbig = ambigBases[criteriaPercentile]; m->mothurOut("Optimizing maxambig to " + toString(maxAmbig) + "."); m->mothurOutEndLine(); }
703                         else if (optimize[i] == "maxhomop") { maxHomoP = longHomoPolymer[criteriaPercentile]; m->mothurOut("Optimizing maxhomop to " + toString(maxHomoP) + "."); m->mothurOutEndLine(); }
704                         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(); }
705                         else if (optimize[i] == "maxlength") { maxLength = seqLength[criteriaPercentile]; m->mothurOut("Optimizing maxlength to " + toString(maxLength) + "."); m->mothurOutEndLine(); }
706                 }
707
708 #ifdef USE_MPI
709                 }
710                 
711                 MPI_Status status; 
712                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
713                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
714                         
715                 if (pid == 0) { 
716                         //send file positions to all processes
717                         for(int i = 1; i < processors; i++) { 
718                                 MPI_Send(&startPos, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
719                                 MPI_Send(&endPos, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
720                                 MPI_Send(&maxAmbig, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
721                                 MPI_Send(&maxHomoP, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
722                                 MPI_Send(&minLength, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
723                                 MPI_Send(&maxLength, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
724                         }
725                 }else {
726                         MPI_Recv(&startPos, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
727                         MPI_Recv(&endPos, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
728                         MPI_Recv(&maxAmbig, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
729                         MPI_Recv(&maxHomoP, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
730                         MPI_Recv(&minLength, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
731                         MPI_Recv(&maxLength, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
732                 }
733                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
734 #endif
735                 return 0;
736         }
737         catch(exception& e) {
738                 m->errorOut(e, "ScreenSeqsCommand", "getSummary");
739                 exit(1);
740         }
741 }
742 /**************************************************************************************/
743 int ScreenSeqsCommand::driverCreateSummary(vector<int>& startPosition, vector<int>& endPosition, vector<int>& seqLength, vector<int>& ambigBases, vector<int>& longHomoPolymer, string filename, linePair* filePos) {   
744         try {
745                 
746                 ifstream in;
747                 m->openInputFile(filename, in);
748                                 
749                 in.seekg(filePos->start);
750
751                 bool done = false;
752                 int count = 0;
753         
754                 while (!done) {
755                                 
756                         if (m->control_pressed) { in.close(); return 1; }
757                                         
758                         Sequence current(in); m->gobble(in);
759         
760                         if (current.getName() != "") {
761                                 int num = 1;
762                                 if (namefile != "") {
763                                         //make sure this sequence is in the namefile, else error 
764                                         map<string, int>::iterator it = nameMap.find(current.getName());
765                                         
766                                         if (it == nameMap.end()) { m->mothurOut("[ERROR]: " + current.getName() + " is not in your namefile, please correct."); m->mothurOutEndLine(); m->control_pressed = true; }
767                                         else { num = it->second; }
768                                 }
769                                 
770                                 //for each sequence this sequence represents
771                                 for (int i = 0; i < num; i++) {
772                                         startPosition.push_back(current.getStartPos());
773                                         endPosition.push_back(current.getEndPos());
774                                         seqLength.push_back(current.getNumBases());
775                                         ambigBases.push_back(current.getAmbigBases());
776                                         longHomoPolymer.push_back(current.getLongHomoPolymer());
777                                 }
778                                 
779                                 count++;
780                         }
781                         
782                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
783                                 unsigned long long pos = in.tellg();
784                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
785                         #else
786                                 if (in.eof()) { break; }
787                         #endif
788                         
789                 }
790                 
791                 in.close();
792                 
793                 return count;
794         }
795         catch(exception& e) {
796                 m->errorOut(e, "ScreenSeqsCommand", "driverCreateSummary");
797                 exit(1);
798         }
799 }
800 /**************************************************************************************************/
801 int ScreenSeqsCommand::createProcessesCreateSummary(vector<int>& startPosition, vector<int>& endPosition, vector<int>& seqLength, vector<int>& ambigBases, vector<int>& longHomoPolymer, string filename) {
802         try {
803 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
804                 int process = 1;
805                 int num = 0;
806                 processIDS.clear();
807                 
808                 //loop through and create all the processes you want
809                 while (process != processors) {
810                         int pid = fork();
811                         
812                         if (pid > 0) {
813                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
814                                 process++;
815                         }else if (pid == 0){
816                                 num = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[process]);
817                                 
818                                 //pass numSeqs to parent
819                                 ofstream out;
820                                 string tempFile = fastafile + toString(getpid()) + ".num.temp";
821                                 m->openOutputFile(tempFile, out);
822                                 
823                                 out << num << endl;
824                                 out << startPosition.size() << endl;
825                                 for (int k = 0; k < startPosition.size(); k++)          {               out << startPosition[k] << '\t'; }  out << endl;
826                                 for (int k = 0; k < endPosition.size(); k++)            {               out << endPosition[k] << '\t'; }  out << endl;
827                                 for (int k = 0; k < seqLength.size(); k++)                      {               out << seqLength[k] << '\t'; }  out << endl;
828                                 for (int k = 0; k < ambigBases.size(); k++)                     {               out << ambigBases[k] << '\t'; }  out << endl;
829                                 for (int k = 0; k < longHomoPolymer.size(); k++)        {               out << longHomoPolymer[k] << '\t'; }  out << endl;
830                                 
831                                 out.close();
832                                 
833                                 exit(0);
834                         }else { 
835                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
836                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
837                                 exit(0);
838                         }
839                 }
840                 
841                 num = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
842                 
843                 //force parent to wait until all the processes are done
844                 for (int i=0;i<processIDS.size();i++) { 
845                         int temp = processIDS[i];
846                         wait(&temp);
847                 }
848                 
849                 //parent reads in and combine Filter info
850                 for (int i = 0; i < processIDS.size(); i++) {
851                         string tempFilename = fastafile + toString(processIDS[i]) + ".num.temp";
852                         ifstream in;
853                         m->openInputFile(tempFilename, in);
854                         
855                         int temp, tempNum;
856                         in >> tempNum; m->gobble(in); num += tempNum;
857                         in >> tempNum; m->gobble(in);
858                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; startPosition.push_back(temp);              }               m->gobble(in);
859                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; endPosition.push_back(temp);                }               m->gobble(in);
860                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; seqLength.push_back(temp);                  }               m->gobble(in);
861                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; ambigBases.push_back(temp);                 }               m->gobble(in);
862                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; longHomoPolymer.push_back(temp);    }               m->gobble(in);
863                                 
864                         in.close();
865                         m->mothurRemove(tempFilename);
866                 }
867                 
868                 return num;
869 #endif          
870         }
871         catch(exception& e) {
872                 m->errorOut(e, "ScreenSeqsCommand", "createProcessesCreateSummary");
873                 exit(1);
874         }
875 }
876
877 //***************************************************************************************************************
878
879 int ScreenSeqsCommand::screenGroupFile(set<string> badSeqNames){
880         try {
881                 ifstream inputGroups;
882                 m->openInputFile(groupfile, inputGroups);
883                 string seqName, group;
884                 set<string>::iterator it;
885                 
886                 string goodGroupFile = outputDir + m->getRootName(m->getSimpleName(groupfile)) + "good" + m->getExtension(groupfile);
887                 outputNames.push_back(goodGroupFile);  outputTypes["group"].push_back(goodGroupFile);
888                 ofstream goodGroupOut;  m->openOutputFile(goodGroupFile, goodGroupOut);
889                 
890                 while(!inputGroups.eof()){
891                         if (m->control_pressed) { goodGroupOut.close(); inputGroups.close(); m->mothurRemove(goodGroupFile); return 0; }
892
893                         inputGroups >> seqName >> group;
894                         it = badSeqNames.find(seqName);
895                         
896                         if(it != badSeqNames.end()){
897                                 badSeqNames.erase(it);
898                         }
899                         else{
900                                 goodGroupOut << seqName << '\t' << group << endl;
901                         }
902                         m->gobble(inputGroups);
903                 }
904                 
905                 if (m->control_pressed) { goodGroupOut.close();  inputGroups.close(); m->mothurRemove(goodGroupFile);  return 0; }
906
907                 //we were unable to remove some of the bad sequences
908                 if (badSeqNames.size() != 0) {
909                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
910                                 m->mothurOut("Your groupfile does not include the sequence " + *it + " please correct."); 
911                                 m->mothurOutEndLine();
912                         }
913                 }
914                 
915                 inputGroups.close();
916                 goodGroupOut.close();
917                 
918                 if (m->control_pressed) { m->mothurRemove(goodGroupFile);   }
919                 
920                 return 0;
921         
922         }
923         catch(exception& e) {
924                 m->errorOut(e, "ScreenSeqsCommand", "screenGroupFile");
925                 exit(1);
926         }
927 }
928
929 //***************************************************************************************************************
930
931 int ScreenSeqsCommand::screenAlignReport(set<string> badSeqNames){
932         try {
933                 ifstream inputAlignReport;
934                 m->openInputFile(alignreport, inputAlignReport);
935                 string seqName, group;
936                 set<string>::iterator it;
937                 
938                 string goodAlignReportFile = outputDir + m->getRootName(m->getSimpleName(alignreport)) + "good" + m->getExtension(alignreport);
939                 outputNames.push_back(goodAlignReportFile);  outputTypes["alignreport"].push_back(goodAlignReportFile);
940                 ofstream goodAlignReportOut;    m->openOutputFile(goodAlignReportFile, goodAlignReportOut);
941
942                 while (!inputAlignReport.eof()) {               //      need to copy header
943                         char c = inputAlignReport.get();
944                         goodAlignReportOut << c;
945                         if (c == 10 || c == 13){        break;  }       
946                 }
947
948                 while(!inputAlignReport.eof()){
949                         if (m->control_pressed) { goodAlignReportOut.close(); inputAlignReport.close(); m->mothurRemove(goodAlignReportFile); return 0; }
950
951                         inputAlignReport >> seqName;
952                         it = badSeqNames.find(seqName);
953                         string line;            
954                         while (!inputAlignReport.eof()) {               //      need to copy header
955                                 char c = inputAlignReport.get();
956                                 line += c;
957                                 if (c == 10 || c == 13){        break;  }       
958                         }
959                         
960                         if(it != badSeqNames.end()){
961                                 badSeqNames.erase(it);
962                         }
963                         else{
964                                 goodAlignReportOut << seqName << '\t' << line;
965                         }
966                         m->gobble(inputAlignReport);
967                 }
968                 
969                 if (m->control_pressed) { goodAlignReportOut.close();  inputAlignReport.close(); m->mothurRemove(goodAlignReportFile);  return 0; }
970
971                 //we were unable to remove some of the bad sequences
972                 if (badSeqNames.size() != 0) {
973                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
974                                 m->mothurOut("Your alignreport file does not include the sequence " + *it + " please correct."); 
975                                 m->mothurOutEndLine();
976                         }
977                 }
978
979                 inputAlignReport.close();
980                 goodAlignReportOut.close();
981                                 
982                 if (m->control_pressed) {  m->mothurRemove(goodAlignReportFile);  return 0; }
983                 
984                 return 0;
985         
986         }
987         catch(exception& e) {
988                 m->errorOut(e, "ScreenSeqsCommand", "screenAlignReport");
989                 exit(1);
990         }
991         
992 }
993 //***************************************************************************************************************
994
995 int ScreenSeqsCommand::screenTaxonomy(set<string> badSeqNames){
996         try {
997                 ifstream input;
998                 m->openInputFile(taxonomy, input);
999                 string seqName, tax;
1000                 set<string>::iterator it;
1001                 
1002                 string goodTaxFile = outputDir + m->getRootName(m->getSimpleName(taxonomy)) + "good" + m->getExtension(taxonomy);
1003                 outputNames.push_back(goodTaxFile);  outputTypes["taxonomy"].push_back(goodTaxFile);
1004                 ofstream goodTaxOut;    m->openOutputFile(goodTaxFile, goodTaxOut);
1005                                 
1006                 while(!input.eof()){
1007                         if (m->control_pressed) { goodTaxOut.close(); input.close(); m->mothurRemove(goodTaxFile); return 0; }
1008                         
1009                         input >> seqName >> tax;
1010                         it = badSeqNames.find(seqName);
1011                         
1012                         if(it != badSeqNames.end()){ badSeqNames.erase(it); }
1013                         else{
1014                                 goodTaxOut << seqName << '\t' << tax << endl;
1015                         }
1016                         m->gobble(input);
1017                 }
1018                 
1019                 if (m->control_pressed) { goodTaxOut.close(); input.close(); m->mothurRemove(goodTaxFile); return 0; }
1020                 
1021                 //we were unable to remove some of the bad sequences
1022                 if (badSeqNames.size() != 0) {
1023                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
1024                                 m->mothurOut("Your taxonomy file does not include the sequence " + *it + " please correct."); 
1025                                 m->mothurOutEndLine();
1026                         }
1027                 }
1028                 
1029                 input.close();
1030                 goodTaxOut.close();
1031                 
1032                 if (m->control_pressed) {  m->mothurRemove(goodTaxFile);  return 0; }
1033                 
1034                 return 0;
1035                 
1036         }
1037         catch(exception& e) {
1038                 m->errorOut(e, "ScreenSeqsCommand", "screenTaxonomy");
1039                 exit(1);
1040         }
1041         
1042 }
1043 //***************************************************************************************************************
1044
1045 int ScreenSeqsCommand::screenQual(set<string> badSeqNames){
1046         try {
1047                 ifstream in;
1048                 m->openInputFile(qualfile, in);
1049                 set<string>::iterator it;
1050                 
1051                 string goodQualFile = outputDir + m->getRootName(m->getSimpleName(qualfile)) + "good" + m->getExtension(qualfile);
1052                 outputNames.push_back(goodQualFile);  outputTypes["qfile"].push_back(goodQualFile);
1053                 ofstream goodQual;      m->openOutputFile(goodQualFile, goodQual);
1054                 
1055                 while(!in.eof()){       
1056                         
1057                         if (m->control_pressed) { goodQual.close(); in.close(); m->mothurRemove(goodQualFile); return 0; }
1058
1059                         string saveName = "";
1060                         string name = "";
1061                         string scores = "";
1062                         
1063                         in >> name; 
1064                         
1065                         if (name.length() != 0) { 
1066                                 saveName = name.substr(1);
1067                                 while (!in.eof())       {       
1068                                         char c = in.get(); 
1069                                         if (c == 10 || c == 13){        break;  }
1070                                         else { name += c; }     
1071                                 } 
1072                                 m->gobble(in);
1073                         }
1074                         
1075                         while(in){
1076                                 char letter= in.get();
1077                                 if(letter == '>'){      in.putback(letter);     break;  }
1078                                 else{ scores += letter; }
1079                         }
1080                         
1081                         m->gobble(in);
1082                         
1083                         it = badSeqNames.find(saveName);
1084                         
1085                         if(it != badSeqNames.end()){
1086                                 badSeqNames.erase(it);
1087                         }else{                          
1088                                 goodQual << name << endl << scores;
1089                         }
1090                         
1091                         m->gobble(in);
1092                 }
1093                 
1094                 in.close();
1095                 goodQual.close();
1096                 
1097                 //we were unable to remove some of the bad sequences
1098                 if (badSeqNames.size() != 0) {
1099                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
1100                                 m->mothurOut("Your qual file does not include the sequence " + *it + " please correct."); 
1101                                 m->mothurOutEndLine();
1102                         }
1103                 }
1104                 
1105                 if (m->control_pressed) {  m->mothurRemove(goodQualFile);  return 0; }
1106                 
1107                 return 0;
1108                 
1109         }
1110         catch(exception& e) {
1111                 m->errorOut(e, "ScreenSeqsCommand", "screenQual");
1112                 exit(1);
1113         }
1114         
1115 }
1116 //**********************************************************************************************************************
1117
1118 int ScreenSeqsCommand::driver(linePair* filePos, string goodFName, string badAccnosFName, string filename, set<string>& badSeqNames){
1119         try {
1120                 ofstream goodFile;
1121                 m->openOutputFile(goodFName, goodFile);
1122                 
1123                 ofstream badAccnosFile;
1124                 m->openOutputFile(badAccnosFName, badAccnosFile);
1125                 
1126                 ifstream inFASTA;
1127                 m->openInputFile(filename, inFASTA);
1128
1129                 inFASTA.seekg(filePos->start);
1130
1131                 bool done = false;
1132                 int count = 0;
1133         
1134                 while (!done) {
1135                 
1136                         if (m->control_pressed) {  return 0; }
1137                         
1138                         Sequence currSeq(inFASTA); m->gobble(inFASTA);
1139                         if (currSeq.getName() != "") {
1140                                 bool goodSeq = 1;               //      innocent until proven guilty
1141                                 if(goodSeq == 1 && startPos != -1 && startPos < currSeq.getStartPos())                  {       goodSeq = 0;    }
1142                                 if(goodSeq == 1 && endPos != -1 && endPos > currSeq.getEndPos())                                {       goodSeq = 0;    }
1143                                 if(goodSeq == 1 && maxAmbig != -1 && maxAmbig < currSeq.getAmbigBases())                {       goodSeq = 0;    }
1144                                 if(goodSeq == 1 && maxHomoP != -1 && maxHomoP < currSeq.getLongHomoPolymer())   {       goodSeq = 0;    }
1145                                 if(goodSeq == 1 && minLength != -1 && minLength > currSeq.getNumBases())                {       goodSeq = 0;    }
1146                                 if(goodSeq == 1 && maxLength != -1 && maxLength < currSeq.getNumBases())                {       goodSeq = 0;    }
1147                                 
1148                                 if(goodSeq == 1){
1149                                         currSeq.printSequence(goodFile);        
1150                                 }
1151                                 else{
1152                                         badAccnosFile << currSeq.getName() << endl;
1153                                         badSeqNames.insert(currSeq.getName());
1154                                 }
1155                         count++;
1156                         }
1157                         
1158                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1159                                 unsigned long long pos = inFASTA.tellg();
1160                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
1161                         #else
1162                                 if (inFASTA.eof()) { break; }
1163                         #endif
1164                         
1165                         //report progress
1166                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1167                 }
1168                 //report progress
1169                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1170                 
1171                         
1172                 goodFile.close();
1173                 inFASTA.close();
1174                 badAccnosFile.close();
1175                 
1176                 return count;
1177         }
1178         catch(exception& e) {
1179                 m->errorOut(e, "ScreenSeqsCommand", "driver");
1180                 exit(1);
1181         }
1182 }
1183 //**********************************************************************************************************************
1184 #ifdef USE_MPI
1185 int ScreenSeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& goodFile, MPI_File& badAccnosFile, vector<unsigned long long>& MPIPos, set<string>& badSeqNames){
1186         try {
1187                 string outputString = "";
1188                 MPI_Status statusGood; 
1189                 MPI_Status statusBadAccnos; 
1190                 MPI_Status status; 
1191                 int pid;
1192                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1193
1194                 for(int i=0;i<num;i++){
1195                 
1196                         if (m->control_pressed) {  return 0; }
1197                         
1198                         //read next sequence
1199                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1200
1201                         char* buf4 = new char[length];
1202                         memcpy(buf4, outputString.c_str(), length);
1203
1204                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1205                         
1206                         string tempBuf = buf4;  delete buf4;
1207                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1208                         istringstream iss (tempBuf,istringstream::in);
1209                         
1210                         Sequence currSeq(iss);                  
1211                         
1212                         //process seq
1213                         if (currSeq.getName() != "") {
1214                                 bool goodSeq = 1;               //      innocent until proven guilty
1215                                 if(goodSeq == 1 && startPos != -1 && startPos < currSeq.getStartPos())                  {       goodSeq = 0;    }
1216                                 if(goodSeq == 1 && endPos != -1 && endPos > currSeq.getEndPos())                                {       goodSeq = 0;    }
1217                                 if(goodSeq == 1 && maxAmbig != -1 && maxAmbig < currSeq.getAmbigBases())                {       goodSeq = 0;    }
1218                                 if(goodSeq == 1 && maxHomoP != -1 && maxHomoP < currSeq.getLongHomoPolymer())   {       goodSeq = 0;    }
1219                                 if(goodSeq == 1 && minLength != -1 && minLength > currSeq.getNumBases())                {       goodSeq = 0;    }
1220                                 if(goodSeq == 1 && maxLength != -1 && maxLength < currSeq.getNumBases())                {       goodSeq = 0;    }
1221                                 
1222                                 if(goodSeq == 1){
1223                                         outputString =  ">" + currSeq.getName() + "\n" + currSeq.getAligned() + "\n";
1224                                 
1225                                         //print good seq
1226                                         length = outputString.length();
1227                                         char* buf2 = new char[length];
1228                                         memcpy(buf2, outputString.c_str(), length);
1229                                         
1230                                         MPI_File_write_shared(goodFile, buf2, length, MPI_CHAR, &statusGood);
1231                                         delete buf2;
1232                                 }
1233                                 else{
1234
1235                                         badSeqNames.insert(currSeq.getName());
1236                                         
1237                                         //write to bad accnos file
1238                                         outputString = currSeq.getName() + "\n";
1239                                 
1240                                         length = outputString.length();
1241                                         char* buf3 = new char[length];
1242                                         memcpy(buf3, outputString.c_str(), length);
1243                                         
1244                                         MPI_File_write_shared(badAccnosFile, buf3, length, MPI_CHAR, &statusBadAccnos);
1245                                         delete buf3;
1246                                 }
1247                         }
1248                         
1249                         //report progress
1250                         if((i) % 100 == 0){     m->mothurOut("Processing sequence: " + toString(i)); m->mothurOutEndLine();             }
1251                 }
1252                                 
1253                 return 1;
1254         }
1255         catch(exception& e) {
1256                 m->errorOut(e, "ScreenSeqsCommand", "driverMPI");
1257                 exit(1);
1258         }
1259 }
1260 #endif
1261 /**************************************************************************************************/
1262
1263 int ScreenSeqsCommand::createProcesses(string goodFileName, string badAccnos, string filename, set<string>& badSeqNames) {
1264         try {
1265 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1266                 int process = 0;
1267                 int num = 0;
1268                 
1269                 //loop through and create all the processes you want
1270                 while (process != processors) {
1271                         int pid = fork();
1272                         
1273                         if (pid > 0) {
1274                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1275                                 process++;
1276                         }else if (pid == 0){
1277                                 num = driver(lines[process], goodFileName + toString(getpid()) + ".temp", badAccnos + toString(getpid()) + ".temp", filename, badSeqNames);
1278                                 
1279                                 //pass numSeqs to parent
1280                                 ofstream out;
1281                                 string tempFile = filename + toString(getpid()) + ".num.temp";
1282                                 m->openOutputFile(tempFile, out);
1283                                 out << num << endl;
1284                                 out.close();
1285                                 
1286                                 exit(0);
1287                         }else { 
1288                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1289                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1290                                 exit(0);
1291                         }
1292                 }
1293                 
1294                 //force parent to wait until all the processes are done
1295                 for (int i=0;i<processors;i++) { 
1296                         int temp = processIDS[i];
1297                         wait(&temp);
1298                 }
1299                 
1300                 for (int i = 0; i < processIDS.size(); i++) {
1301                         ifstream in;
1302                         string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
1303                         m->openInputFile(tempFile, in);
1304                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1305                         in.close(); m->mothurRemove(tempFile);
1306                 }
1307                 
1308                 return num;
1309 #endif          
1310         }
1311         catch(exception& e) {
1312                 m->errorOut(e, "ScreenSeqsCommand", "createProcesses");
1313                 exit(1);
1314         }
1315 }
1316
1317 //***************************************************************************************************************
1318
1319