]> git.donarmstrong.com Git - mothur.git/blob - screenseqscommand.cpp
finished shhh.seqs command, fixed bug with remove.groups and get.groups that caused...
[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                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); 
671                 
672                 if (pid == 0) { //only one process should fix files
673                         driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
674                 }
675                 
676                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
677 #else
678                 int numSeqs = 0;
679                 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
680                         if(processors == 1){
681                                 numSeqs = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
682                         }else{
683                                 numSeqs = createProcessesCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile); 
684                         }
685                                 
686                         if (m->control_pressed) {  return 0; }
687                 #else
688                         numSeqs = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
689                         if (m->control_pressed) {  return 0; }
690                 #endif
691 #endif
692                 sort(startPosition.begin(), startPosition.end());
693                 sort(endPosition.begin(), endPosition.end());
694                 sort(seqLength.begin(), seqLength.end());
695                 sort(ambigBases.begin(), ambigBases.end());
696                 sort(longHomoPolymer.begin(), longHomoPolymer.end());
697                 
698                 //numSeqs is the number of unique seqs, startPosition.size() is the total number of seqs, we want to optimize using all seqs
699                 int criteriaPercentile  = int(startPosition.size() * (criteria / (float) 100));
700                 
701                 for (int i = 0; i < optimize.size(); i++) {
702                         if (optimize[i] == "start") { startPos = startPosition[criteriaPercentile]; m->mothurOut("Optimizing start to " + toString(startPos) + "."); m->mothurOutEndLine(); }
703                         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();}
704                         else if (optimize[i] == "maxambig") { maxAmbig = ambigBases[criteriaPercentile]; m->mothurOut("Optimizing maxambig to " + toString(maxAmbig) + "."); m->mothurOutEndLine(); }
705                         else if (optimize[i] == "maxhomop") { maxHomoP = longHomoPolymer[criteriaPercentile]; m->mothurOut("Optimizing maxhomop to " + toString(maxHomoP) + "."); m->mothurOutEndLine(); }
706                         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(); }
707                         else if (optimize[i] == "maxlength") { maxLength = seqLength[criteriaPercentile]; m->mothurOut("Optimizing maxlength to " + toString(maxLength) + "."); m->mothurOutEndLine(); }
708                 }
709
710                 return 0;
711         }
712         catch(exception& e) {
713                 m->errorOut(e, "ScreenSeqsCommand", "getSummary");
714                 exit(1);
715         }
716 }
717 /**************************************************************************************/
718 int ScreenSeqsCommand::driverCreateSummary(vector<int>& startPosition, vector<int>& endPosition, vector<int>& seqLength, vector<int>& ambigBases, vector<int>& longHomoPolymer, string filename, linePair* filePos) {   
719         try {
720                 
721                 ifstream in;
722                 m->openInputFile(filename, in);
723                                 
724                 in.seekg(filePos->start);
725
726                 bool done = false;
727                 int count = 0;
728         
729                 while (!done) {
730                                 
731                         if (m->control_pressed) { in.close(); return 1; }
732                                         
733                         Sequence current(in); m->gobble(in);
734         
735                         if (current.getName() != "") {
736                                 int num = 1;
737                                 if (namefile != "") {
738                                         //make sure this sequence is in the namefile, else error 
739                                         map<string, int>::iterator it = nameMap.find(current.getName());
740                                         
741                                         if (it == nameMap.end()) { m->mothurOut("[ERROR]: " + current.getName() + " is not in your namefile, please correct."); m->mothurOutEndLine(); m->control_pressed = true; }
742                                         else { num = it->second; }
743                                 }
744                                 
745                                 //for each sequence this sequence represents
746                                 for (int i = 0; i < num; i++) {
747                                         startPosition.push_back(current.getStartPos());
748                                         endPosition.push_back(current.getEndPos());
749                                         seqLength.push_back(current.getNumBases());
750                                         ambigBases.push_back(current.getAmbigBases());
751                                         longHomoPolymer.push_back(current.getLongHomoPolymer());
752                                 }
753                                 
754                                 count++;
755                         }
756                         
757                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
758                                 unsigned long long pos = in.tellg();
759                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
760                         #else
761                                 if (in.eof()) { break; }
762                         #endif
763                         
764                 }
765                 
766                 in.close();
767                 
768                 return count;
769         }
770         catch(exception& e) {
771                 m->errorOut(e, "ScreenSeqsCommand", "driverCreateSummary");
772                 exit(1);
773         }
774 }
775 /**************************************************************************************************/
776 int ScreenSeqsCommand::createProcessesCreateSummary(vector<int>& startPosition, vector<int>& endPosition, vector<int>& seqLength, vector<int>& ambigBases, vector<int>& longHomoPolymer, string filename) {
777         try {
778 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
779                 int process = 1;
780                 int num = 0;
781                 processIDS.clear();
782                 
783                 //loop through and create all the processes you want
784                 while (process != processors) {
785                         int pid = fork();
786                         
787                         if (pid > 0) {
788                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
789                                 process++;
790                         }else if (pid == 0){
791                                 num = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[process]);
792                                 
793                                 //pass numSeqs to parent
794                                 ofstream out;
795                                 string tempFile = fastafile + toString(getpid()) + ".num.temp";
796                                 m->openOutputFile(tempFile, out);
797                                 
798                                 out << num << endl;
799                                 out << startPosition.size() << endl;
800                                 for (int k = 0; k < startPosition.size(); k++)          {               out << startPosition[k] << '\t'; }  out << endl;
801                                 for (int k = 0; k < endPosition.size(); k++)            {               out << endPosition[k] << '\t'; }  out << endl;
802                                 for (int k = 0; k < seqLength.size(); k++)                      {               out << seqLength[k] << '\t'; }  out << endl;
803                                 for (int k = 0; k < ambigBases.size(); k++)                     {               out << ambigBases[k] << '\t'; }  out << endl;
804                                 for (int k = 0; k < longHomoPolymer.size(); k++)        {               out << longHomoPolymer[k] << '\t'; }  out << endl;
805                                 
806                                 out.close();
807                                 
808                                 exit(0);
809                         }else { 
810                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
811                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
812                                 exit(0);
813                         }
814                 }
815                 
816                 num = driverCreateSummary(startPosition, endPosition, seqLength, ambigBases, longHomoPolymer, fastafile, lines[0]);
817                 
818                 //force parent to wait until all the processes are done
819                 for (int i=0;i<processIDS.size();i++) { 
820                         int temp = processIDS[i];
821                         wait(&temp);
822                 }
823                 
824                 //parent reads in and combine Filter info
825                 for (int i = 0; i < processIDS.size(); i++) {
826                         string tempFilename = fastafile + toString(processIDS[i]) + ".num.temp";
827                         ifstream in;
828                         m->openInputFile(tempFilename, in);
829                         
830                         int temp, tempNum;
831                         in >> tempNum; m->gobble(in); num += tempNum;
832                         in >> tempNum; m->gobble(in);
833                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; startPosition.push_back(temp);              }               m->gobble(in);
834                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; endPosition.push_back(temp);                }               m->gobble(in);
835                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; seqLength.push_back(temp);                  }               m->gobble(in);
836                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; ambigBases.push_back(temp);                 }               m->gobble(in);
837                         for (int k = 0; k < tempNum; k++)                       {               in >> temp; longHomoPolymer.push_back(temp);    }               m->gobble(in);
838                                 
839                         in.close();
840                         m->mothurRemove(tempFilename);
841                 }
842                 
843                 return num;
844 #endif          
845         }
846         catch(exception& e) {
847                 m->errorOut(e, "ScreenSeqsCommand", "createProcessesCreateSummary");
848                 exit(1);
849         }
850 }
851
852 //***************************************************************************************************************
853
854 int ScreenSeqsCommand::screenGroupFile(set<string> badSeqNames){
855         try {
856                 ifstream inputGroups;
857                 m->openInputFile(groupfile, inputGroups);
858                 string seqName, group;
859                 set<string>::iterator it;
860                 
861                 string goodGroupFile = outputDir + m->getRootName(m->getSimpleName(groupfile)) + "good" + m->getExtension(groupfile);
862                 outputNames.push_back(goodGroupFile);  outputTypes["group"].push_back(goodGroupFile);
863                 ofstream goodGroupOut;  m->openOutputFile(goodGroupFile, goodGroupOut);
864                 
865                 while(!inputGroups.eof()){
866                         if (m->control_pressed) { goodGroupOut.close(); inputGroups.close(); m->mothurRemove(goodGroupFile); return 0; }
867
868                         inputGroups >> seqName >> group;
869                         it = badSeqNames.find(seqName);
870                         
871                         if(it != badSeqNames.end()){
872                                 badSeqNames.erase(it);
873                         }
874                         else{
875                                 goodGroupOut << seqName << '\t' << group << endl;
876                         }
877                         m->gobble(inputGroups);
878                 }
879                 
880                 if (m->control_pressed) { goodGroupOut.close();  inputGroups.close(); m->mothurRemove(goodGroupFile);  return 0; }
881
882                 //we were unable to remove some of the bad sequences
883                 if (badSeqNames.size() != 0) {
884                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
885                                 m->mothurOut("Your groupfile does not include the sequence " + *it + " please correct."); 
886                                 m->mothurOutEndLine();
887                         }
888                 }
889                 
890                 inputGroups.close();
891                 goodGroupOut.close();
892                 
893                 if (m->control_pressed) { m->mothurRemove(goodGroupFile);   }
894                 
895                 return 0;
896         
897         }
898         catch(exception& e) {
899                 m->errorOut(e, "ScreenSeqsCommand", "screenGroupFile");
900                 exit(1);
901         }
902 }
903
904 //***************************************************************************************************************
905
906 int ScreenSeqsCommand::screenAlignReport(set<string> badSeqNames){
907         try {
908                 ifstream inputAlignReport;
909                 m->openInputFile(alignreport, inputAlignReport);
910                 string seqName, group;
911                 set<string>::iterator it;
912                 
913                 string goodAlignReportFile = outputDir + m->getRootName(m->getSimpleName(alignreport)) + "good" + m->getExtension(alignreport);
914                 outputNames.push_back(goodAlignReportFile);  outputTypes["alignreport"].push_back(goodAlignReportFile);
915                 ofstream goodAlignReportOut;    m->openOutputFile(goodAlignReportFile, goodAlignReportOut);
916
917                 while (!inputAlignReport.eof()) {               //      need to copy header
918                         char c = inputAlignReport.get();
919                         goodAlignReportOut << c;
920                         if (c == 10 || c == 13){        break;  }       
921                 }
922
923                 while(!inputAlignReport.eof()){
924                         if (m->control_pressed) { goodAlignReportOut.close(); inputAlignReport.close(); m->mothurRemove(goodAlignReportFile); return 0; }
925
926                         inputAlignReport >> seqName;
927                         it = badSeqNames.find(seqName);
928                         string line;            
929                         while (!inputAlignReport.eof()) {               //      need to copy header
930                                 char c = inputAlignReport.get();
931                                 line += c;
932                                 if (c == 10 || c == 13){        break;  }       
933                         }
934                         
935                         if(it != badSeqNames.end()){
936                                 badSeqNames.erase(it);
937                         }
938                         else{
939                                 goodAlignReportOut << seqName << '\t' << line;
940                         }
941                         m->gobble(inputAlignReport);
942                 }
943                 
944                 if (m->control_pressed) { goodAlignReportOut.close();  inputAlignReport.close(); m->mothurRemove(goodAlignReportFile);  return 0; }
945
946                 //we were unable to remove some of the bad sequences
947                 if (badSeqNames.size() != 0) {
948                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
949                                 m->mothurOut("Your alignreport file does not include the sequence " + *it + " please correct."); 
950                                 m->mothurOutEndLine();
951                         }
952                 }
953
954                 inputAlignReport.close();
955                 goodAlignReportOut.close();
956                                 
957                 if (m->control_pressed) {  m->mothurRemove(goodAlignReportFile);  return 0; }
958                 
959                 return 0;
960         
961         }
962         catch(exception& e) {
963                 m->errorOut(e, "ScreenSeqsCommand", "screenAlignReport");
964                 exit(1);
965         }
966         
967 }
968 //***************************************************************************************************************
969
970 int ScreenSeqsCommand::screenTaxonomy(set<string> badSeqNames){
971         try {
972                 ifstream input;
973                 m->openInputFile(taxonomy, input);
974                 string seqName, tax;
975                 set<string>::iterator it;
976                 
977                 string goodTaxFile = outputDir + m->getRootName(m->getSimpleName(taxonomy)) + "good" + m->getExtension(taxonomy);
978                 outputNames.push_back(goodTaxFile);  outputTypes["taxonomy"].push_back(goodTaxFile);
979                 ofstream goodTaxOut;    m->openOutputFile(goodTaxFile, goodTaxOut);
980                                 
981                 while(!input.eof()){
982                         if (m->control_pressed) { goodTaxOut.close(); input.close(); m->mothurRemove(goodTaxFile); return 0; }
983                         
984                         input >> seqName >> tax;
985                         it = badSeqNames.find(seqName);
986                         
987                         if(it != badSeqNames.end()){ badSeqNames.erase(it); }
988                         else{
989                                 goodTaxOut << seqName << '\t' << tax << endl;
990                         }
991                         m->gobble(input);
992                 }
993                 
994                 if (m->control_pressed) { goodTaxOut.close(); input.close(); m->mothurRemove(goodTaxFile); return 0; }
995                 
996                 //we were unable to remove some of the bad sequences
997                 if (badSeqNames.size() != 0) {
998                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
999                                 m->mothurOut("Your taxonomy file does not include the sequence " + *it + " please correct."); 
1000                                 m->mothurOutEndLine();
1001                         }
1002                 }
1003                 
1004                 input.close();
1005                 goodTaxOut.close();
1006                 
1007                 if (m->control_pressed) {  m->mothurRemove(goodTaxFile);  return 0; }
1008                 
1009                 return 0;
1010                 
1011         }
1012         catch(exception& e) {
1013                 m->errorOut(e, "ScreenSeqsCommand", "screenTaxonomy");
1014                 exit(1);
1015         }
1016         
1017 }
1018 //***************************************************************************************************************
1019
1020 int ScreenSeqsCommand::screenQual(set<string> badSeqNames){
1021         try {
1022                 ifstream in;
1023                 m->openInputFile(qualfile, in);
1024                 set<string>::iterator it;
1025                 
1026                 string goodQualFile = outputDir + m->getRootName(m->getSimpleName(qualfile)) + "good" + m->getExtension(qualfile);
1027                 outputNames.push_back(goodQualFile);  outputTypes["qfile"].push_back(goodQualFile);
1028                 ofstream goodQual;      m->openOutputFile(goodQualFile, goodQual);
1029                 
1030                 while(!in.eof()){       
1031                         
1032                         if (m->control_pressed) { goodQual.close(); in.close(); m->mothurRemove(goodQualFile); return 0; }
1033
1034                         string saveName = "";
1035                         string name = "";
1036                         string scores = "";
1037                         
1038                         in >> name; 
1039                         
1040                         if (name.length() != 0) { 
1041                                 saveName = name.substr(1);
1042                                 while (!in.eof())       {       
1043                                         char c = in.get(); 
1044                                         if (c == 10 || c == 13){        break;  }
1045                                         else { name += c; }     
1046                                 } 
1047                                 m->gobble(in);
1048                         }
1049                         
1050                         while(in){
1051                                 char letter= in.get();
1052                                 if(letter == '>'){      in.putback(letter);     break;  }
1053                                 else{ scores += letter; }
1054                         }
1055                         
1056                         m->gobble(in);
1057                         
1058                         it = badSeqNames.find(saveName);
1059                         
1060                         if(it != badSeqNames.end()){
1061                                 badSeqNames.erase(it);
1062                         }else{                          
1063                                 goodQual << name << endl << scores;
1064                         }
1065                         
1066                         m->gobble(in);
1067                 }
1068                 
1069                 in.close();
1070                 goodQual.close();
1071                 
1072                 //we were unable to remove some of the bad sequences
1073                 if (badSeqNames.size() != 0) {
1074                         for (it = badSeqNames.begin(); it != badSeqNames.end(); it++) {  
1075                                 m->mothurOut("Your qual file does not include the sequence " + *it + " please correct."); 
1076                                 m->mothurOutEndLine();
1077                         }
1078                 }
1079                 
1080                 if (m->control_pressed) {  m->mothurRemove(goodQualFile);  return 0; }
1081                 
1082                 return 0;
1083                 
1084         }
1085         catch(exception& e) {
1086                 m->errorOut(e, "ScreenSeqsCommand", "screenQual");
1087                 exit(1);
1088         }
1089         
1090 }
1091 //**********************************************************************************************************************
1092
1093 int ScreenSeqsCommand::driver(linePair* filePos, string goodFName, string badAccnosFName, string filename, set<string>& badSeqNames){
1094         try {
1095                 ofstream goodFile;
1096                 m->openOutputFile(goodFName, goodFile);
1097                 
1098                 ofstream badAccnosFile;
1099                 m->openOutputFile(badAccnosFName, badAccnosFile);
1100                 
1101                 ifstream inFASTA;
1102                 m->openInputFile(filename, inFASTA);
1103
1104                 inFASTA.seekg(filePos->start);
1105
1106                 bool done = false;
1107                 int count = 0;
1108         
1109                 while (!done) {
1110                 
1111                         if (m->control_pressed) {  return 0; }
1112                         
1113                         Sequence currSeq(inFASTA); m->gobble(inFASTA);
1114                         if (currSeq.getName() != "") {
1115                                 bool goodSeq = 1;               //      innocent until proven guilty
1116                                 if(goodSeq == 1 && startPos != -1 && startPos < currSeq.getStartPos())                  {       goodSeq = 0;    }
1117                                 if(goodSeq == 1 && endPos != -1 && endPos > currSeq.getEndPos())                                {       goodSeq = 0;    }
1118                                 if(goodSeq == 1 && maxAmbig != -1 && maxAmbig < currSeq.getAmbigBases())                {       goodSeq = 0;    }
1119                                 if(goodSeq == 1 && maxHomoP != -1 && maxHomoP < currSeq.getLongHomoPolymer())   {       goodSeq = 0;    }
1120                                 if(goodSeq == 1 && minLength != -1 && minLength > currSeq.getNumBases())                {       goodSeq = 0;    }
1121                                 if(goodSeq == 1 && maxLength != -1 && maxLength < currSeq.getNumBases())                {       goodSeq = 0;    }
1122                                 
1123                                 if(goodSeq == 1){
1124                                         currSeq.printSequence(goodFile);        
1125                                 }
1126                                 else{
1127                                         badAccnosFile << currSeq.getName() << endl;
1128                                         badSeqNames.insert(currSeq.getName());
1129                                 }
1130                         count++;
1131                         }
1132                         
1133                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1134                                 unsigned long long pos = inFASTA.tellg();
1135                                 if ((pos == -1) || (pos >= filePos->end)) { break; }
1136                         #else
1137                                 if (inFASTA.eof()) { break; }
1138                         #endif
1139                         
1140                         //report progress
1141                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1142                 }
1143                 //report progress
1144                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1145                 
1146                         
1147                 goodFile.close();
1148                 inFASTA.close();
1149                 badAccnosFile.close();
1150                 
1151                 return count;
1152         }
1153         catch(exception& e) {
1154                 m->errorOut(e, "ScreenSeqsCommand", "driver");
1155                 exit(1);
1156         }
1157 }
1158 //**********************************************************************************************************************
1159 #ifdef USE_MPI
1160 int ScreenSeqsCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& goodFile, MPI_File& badAccnosFile, vector<unsigned long long>& MPIPos, set<string>& badSeqNames){
1161         try {
1162                 string outputString = "";
1163                 MPI_Status statusGood; 
1164                 MPI_Status statusBadAccnos; 
1165                 MPI_Status status; 
1166                 int pid;
1167                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1168
1169                 for(int i=0;i<num;i++){
1170                 
1171                         if (m->control_pressed) {  return 0; }
1172                         
1173                         //read next sequence
1174                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1175
1176                         char* buf4 = new char[length];
1177                         memcpy(buf4, outputString.c_str(), length);
1178
1179                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1180                         
1181                         string tempBuf = buf4;  delete buf4;
1182                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1183                         istringstream iss (tempBuf,istringstream::in);
1184                         
1185                         Sequence currSeq(iss);                  
1186                         
1187                         //process seq
1188                         if (currSeq.getName() != "") {
1189                                 bool goodSeq = 1;               //      innocent until proven guilty
1190                                 if(goodSeq == 1 && startPos != -1 && startPos < currSeq.getStartPos())                  {       goodSeq = 0;    }
1191                                 if(goodSeq == 1 && endPos != -1 && endPos > currSeq.getEndPos())                                {       goodSeq = 0;    }
1192                                 if(goodSeq == 1 && maxAmbig != -1 && maxAmbig < currSeq.getAmbigBases())                {       goodSeq = 0;    }
1193                                 if(goodSeq == 1 && maxHomoP != -1 && maxHomoP < currSeq.getLongHomoPolymer())   {       goodSeq = 0;    }
1194                                 if(goodSeq == 1 && minLength != -1 && minLength > currSeq.getNumBases())                {       goodSeq = 0;    }
1195                                 if(goodSeq == 1 && maxLength != -1 && maxLength < currSeq.getNumBases())                {       goodSeq = 0;    }
1196                                 
1197                                 if(goodSeq == 1){
1198                                         outputString =  ">" + currSeq.getName() + "\n" + currSeq.getAligned() + "\n";
1199                                 
1200                                         //print good seq
1201                                         length = outputString.length();
1202                                         char* buf2 = new char[length];
1203                                         memcpy(buf2, outputString.c_str(), length);
1204                                         
1205                                         MPI_File_write_shared(goodFile, buf2, length, MPI_CHAR, &statusGood);
1206                                         delete buf2;
1207                                 }
1208                                 else{
1209
1210                                         badSeqNames.insert(currSeq.getName());
1211                                         
1212                                         //write to bad accnos file
1213                                         outputString = currSeq.getName() + "\n";
1214                                 
1215                                         length = outputString.length();
1216                                         char* buf3 = new char[length];
1217                                         memcpy(buf3, outputString.c_str(), length);
1218                                         
1219                                         MPI_File_write_shared(badAccnosFile, buf3, length, MPI_CHAR, &statusBadAccnos);
1220                                         delete buf3;
1221                                 }
1222                         }
1223                         
1224                         //report progress
1225                         if((i) % 100 == 0){     m->mothurOut("Processing sequence: " + toString(i)); m->mothurOutEndLine();             }
1226                 }
1227                                 
1228                 return 1;
1229         }
1230         catch(exception& e) {
1231                 m->errorOut(e, "ScreenSeqsCommand", "driverMPI");
1232                 exit(1);
1233         }
1234 }
1235 #endif
1236 /**************************************************************************************************/
1237
1238 int ScreenSeqsCommand::createProcesses(string goodFileName, string badAccnos, string filename, set<string>& badSeqNames) {
1239         try {
1240 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
1241                 int process = 0;
1242                 int num = 0;
1243                 
1244                 //loop through and create all the processes you want
1245                 while (process != processors) {
1246                         int pid = fork();
1247                         
1248                         if (pid > 0) {
1249                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1250                                 process++;
1251                         }else if (pid == 0){
1252                                 num = driver(lines[process], goodFileName + toString(getpid()) + ".temp", badAccnos + toString(getpid()) + ".temp", filename, badSeqNames);
1253                                 
1254                                 //pass numSeqs to parent
1255                                 ofstream out;
1256                                 string tempFile = filename + toString(getpid()) + ".num.temp";
1257                                 m->openOutputFile(tempFile, out);
1258                                 out << num << endl;
1259                                 out.close();
1260                                 
1261                                 exit(0);
1262                         }else { 
1263                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1264                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1265                                 exit(0);
1266                         }
1267                 }
1268                 
1269                 //force parent to wait until all the processes are done
1270                 for (int i=0;i<processors;i++) { 
1271                         int temp = processIDS[i];
1272                         wait(&temp);
1273                 }
1274                 
1275                 for (int i = 0; i < processIDS.size(); i++) {
1276                         ifstream in;
1277                         string tempFile =  filename + toString(processIDS[i]) + ".num.temp";
1278                         m->openInputFile(tempFile, in);
1279                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1280                         in.close(); m->mothurRemove(tempFile);
1281                 }
1282                 
1283                 return num;
1284 #endif          
1285         }
1286         catch(exception& e) {
1287                 m->errorOut(e, "ScreenSeqsCommand", "createProcesses");
1288                 exit(1);
1289         }
1290 }
1291
1292 //***************************************************************************************************************
1293
1294