]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
e2b93316a4ade033f6ce4db3988cfd09cbf432e9
[mothur.git] / chimeraslayercommand.cpp
1 /*
2  *  chimeraslayercommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 3/31/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "chimeraslayercommand.h"
11 #include "deconvolutecommand.h"
12 #include "referencedb.h"
13 #include "sequenceparser.h"
14
15 //**********************************************************************************************************************
16 vector<string> ChimeraSlayerCommand::setParameters(){   
17         try {
18                 CommandParameter ptemplate("reference", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptemplate);
19                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
20                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
21                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
22                 CommandParameter pwindow("window", "Number", "", "50", "", "", "",false,false); parameters.push_back(pwindow);
23                 CommandParameter pksize("ksize", "Number", "", "7", "", "", "",false,false); parameters.push_back(pksize);
24                 CommandParameter pmatch("match", "Number", "", "5.0", "", "", "",false,false); parameters.push_back(pmatch);
25                 CommandParameter pmismatch("mismatch", "Number", "", "-4.0", "", "", "",false,false); parameters.push_back(pmismatch);
26                 CommandParameter pminsim("minsim", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminsim);
27                 CommandParameter pmincov("mincov", "Number", "", "70", "", "", "",false,false); parameters.push_back(pmincov);
28                 CommandParameter pminsnp("minsnp", "Number", "", "10", "", "", "",false,false); parameters.push_back(pminsnp);
29                 CommandParameter pminbs("minbs", "Number", "", "90", "", "", "",false,false); parameters.push_back(pminbs);
30                 CommandParameter psearch("search", "Multiple", "kmer-blast", "blast", "", "", "",false,false); parameters.push_back(psearch);
31                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
32                 CommandParameter prealign("realign", "Boolean", "", "T", "", "", "",false,false); parameters.push_back(prealign);
33                 CommandParameter ptrim("trim", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(ptrim);
34                 CommandParameter psplit("split", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psplit);
35                 CommandParameter pnumwanted("numwanted", "Number", "", "15", "", "", "",false,false); parameters.push_back(pnumwanted);
36                 CommandParameter piters("iters", "Number", "", "1000", "", "", "",false,false); parameters.push_back(piters);
37                 CommandParameter pdivergence("divergence", "Number", "", "1.007", "", "", "",false,false); parameters.push_back(pdivergence);
38                 CommandParameter pparents("parents", "Number", "", "3", "", "", "",false,false); parameters.push_back(pparents);
39                 CommandParameter pincrement("increment", "Number", "", "5", "", "", "",false,false); parameters.push_back(pincrement);
40                 CommandParameter pblastlocation("blastlocation", "String", "", "", "", "", "",false,false); parameters.push_back(pblastlocation);
41                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
42                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
43                 CommandParameter psave("save", "Boolean", "", "F", "", "", "",false,false); parameters.push_back(psave);
44
45                 vector<string> myArray;
46                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
47                 return myArray;
48         }
49         catch(exception& e) {
50                 m->errorOut(e, "ChimeraSlayerCommand", "setParameters");
51                 exit(1);
52         }
53 }
54 //**********************************************************************************************************************
55 string ChimeraSlayerCommand::getHelpString(){   
56         try {
57                 string helpString = "";
58                 helpString += "The chimera.slayer command reads a fastafile and referencefile and outputs potentially chimeric sequences.\n";
59                 helpString += "This command was modeled after the chimeraSlayer written by the Broad Institute.\n";
60                 helpString += "The chimera.slayer command parameters are fasta, name, template, processors, trim, ksize, window, match, mismatch, divergence. minsim, mincov, minbs, minsnp, parents, search, iters, increment, numwanted, blastlocation and realign.\n";
61                 helpString += "The fasta parameter allows you to enter the fasta file containing your potentially chimeric sequences, and is required, unless you have a valid current fasta file. \n";
62                 helpString += "The name parameter allows you to provide a name file, if you are using reference=self. \n";
63                 helpString += "The group parameter allows you to provide a group file. The group file can be used with a namesfile and reference=self. When checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
64                 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
65                 helpString += "The reference parameter allows you to enter a reference file containing known non-chimeric sequences, and is required. You may also set template=self, in this case the abundant sequences will be used as potential parents. \n";
66                 helpString += "The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n";
67 #ifdef USE_MPI
68                 helpString += "When using MPI, the processors parameter is set to the number of MPI processes running. \n";
69 #endif
70                 helpString += "The trim parameter allows you to output a new fasta file containing your sequences with the chimeric ones trimmed to include only their longest piece, default=F. \n";
71                 helpString += "The split parameter allows you to check both pieces of non-chimeric sequence for chimeras, thus looking for trimeras and quadmeras. default=F. \n";
72                 helpString += "The window parameter allows you to specify the window size for searching for chimeras, default=50. \n";
73                 helpString += "The increment parameter allows you to specify how far you move each window while finding chimeric sequences, default=5.\n";
74                 helpString += "The numwanted parameter allows you to specify how many sequences you would each query sequence compared with, default=15.\n";
75                 helpString += "The ksize parameter allows you to input kmersize, default is 7, used if search is kmer. \n";
76                 helpString += "The match parameter allows you to reward matched bases in blast search, default is 5. \n";
77                 helpString += "The parents parameter allows you to select the number of potential parents to investigate from the numwanted best matches after rating them, default is 3. \n";
78                 helpString += "The mismatch parameter allows you to penalize mismatched bases in blast search, default is -4. \n";
79                 helpString += "The divergence parameter allows you to set a cutoff for chimera determination, default is 1.007. \n";
80                 helpString += "The iters parameter allows you to specify the number of bootstrap iters to do with the chimeraslayer method, default=1000.\n";
81                 helpString += "The minsim parameter allows you to specify a minimum similarity with the parent fragments, default=90. \n";
82                 helpString += "The mincov parameter allows you to specify minimum coverage by closest matches found in template. Default is 70, meaning 70%. \n";
83                 helpString += "The minbs parameter allows you to specify minimum bootstrap support for calling a sequence chimeric. Default is 90, meaning 90%. \n";
84                 helpString += "The minsnp parameter allows you to specify percent of SNPs to sample on each side of breakpoint for computing bootstrap support (default: 10) \n";
85                 helpString += "The search parameter allows you to specify search method for finding the closest parent. Choices are blast, and kmer, default blast. \n";
86                 helpString += "The realign parameter allows you to realign the query to the potential parents. Choices are true or false, default true.  \n";
87                 helpString += "The blastlocation parameter allows you to specify the location of your blast executable. By default mothur will look in ./blast/bin relative to mothur's executable.  \n";
88                 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
89                 helpString += "The chimera.slayer command should be in the following format: \n";
90                 helpString += "chimera.slayer(fasta=yourFastaFile, reference=yourTemplate, search=yourSearch) \n";
91                 helpString += "Example: chimera.slayer(fasta=AD.align, reference=core_set_aligned.imputed.fasta, search=kmer) \n";
92                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";       
93                 return helpString;
94         }
95         catch(exception& e) {
96                 m->errorOut(e, "ChimeraSlayerCommand", "getHelpString");
97                 exit(1);
98         }
99 }
100 //**********************************************************************************************************************
101 ChimeraSlayerCommand::ChimeraSlayerCommand(){   
102         try {
103                 abort = true; calledHelp = true;
104                 setParameters();
105                 vector<string> tempOutNames;
106                 outputTypes["chimera"] = tempOutNames;
107                 outputTypes["accnos"] = tempOutNames;
108                 outputTypes["fasta"] = tempOutNames;
109         }
110         catch(exception& e) {
111                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
112                 exit(1);
113         }
114 }
115 //***************************************************************************************************************
116 ChimeraSlayerCommand::ChimeraSlayerCommand(string option)  {
117         try {
118                 abort = false; calledHelp = false;   
119                 ReferenceDB* rdb = ReferenceDB::getInstance();
120                 
121                 //allow user to run help
122                 if(option == "help") { help(); abort = true; calledHelp = true; }
123                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
124                 
125                 else {
126                         vector<string> myArray = setParameters();
127                         
128                         OptionParser parser(option);
129                         map<string,string> parameters = parser.getParameters();
130                         
131                         ValidParameters validParameter("chimera.slayer");
132                         map<string,string>::iterator it;
133                         
134                         //check to make sure all parameters are valid for command
135                         for (it = parameters.begin(); it != parameters.end(); it++) { 
136                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
137                         }
138                         
139                         vector<string> tempOutNames;
140                         outputTypes["chimera"] = tempOutNames;
141                         outputTypes["accnos"] = tempOutNames;
142                         outputTypes["fasta"] = tempOutNames;
143                 
144                         //if the user changes the input directory command factory will send this info to us in the output parameter 
145                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
146                         if (inputDir == "not found"){   inputDir = "";          }
147                                                 
148                         //check for required parameters
149                         fastafile = validParameter.validFile(parameters, "fasta", false);
150                         if (fastafile == "not found") {                                 
151                                 //if there is a current fasta file, use it
152                                 string filename = m->getFastaFile(); 
153                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
154                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
155                         }else { 
156                                 m->splitAtDash(fastafile, fastaFileNames);
157                                 
158                                 //go through files and make sure they are good, if not, then disregard them
159                                 for (int i = 0; i < fastaFileNames.size(); i++) {
160                                         
161                                         bool ignore = false;
162                                         if (fastaFileNames[i] == "current") { 
163                                                 fastaFileNames[i] = m->getFastaFile(); 
164                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
165                                                 else {  
166                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
167                                                         //erase from file list
168                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
169                                                         i--;
170                                                 }
171                                         }
172                                         
173                                         if (!ignore) {
174                                                 
175                                                 if (inputDir != "") {
176                                                         string path = m->hasPath(fastaFileNames[i]);
177                                                         //if the user has not given a path then, add inputdir. else leave path alone.
178                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
179                                                 }
180                 
181                                                 int ableToOpen;
182                                                 ifstream in;
183                                                 
184                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
185                                         
186                                                 //if you can't open it, try default location
187                                                 if (ableToOpen == 1) {
188                                                         if (m->getDefaultPath() != "") { //default path is set
189                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
190                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
191                                                                 ifstream in2;
192                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
193                                                                 in2.close();
194                                                                 fastaFileNames[i] = tryPath;
195                                                         }
196                                                 }
197                                                 
198                                                 if (ableToOpen == 1) {
199                                                         if (m->getOutputDir() != "") { //default path is set
200                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
201                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
202                                                                 ifstream in2;
203                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
204                                                                 in2.close();
205                                                                 fastaFileNames[i] = tryPath;
206                                                         }
207                                                 }
208                                                 
209                                                 in.close();
210                                                 
211                                                 if (ableToOpen == 1) { 
212                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
213                                                         //erase from file list
214                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
215                                                         i--;
216                                                 }else {
217                                                         m->setFastaFile(fastaFileNames[i]);
218                                                 }
219                                         }
220                                 }
221                                 
222                                 //make sure there is at least one valid file left
223                                 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
224                         }
225                         
226                         
227                         //check for required parameters
228                         bool hasName = true;
229                         namefile = validParameter.validFile(parameters, "name", false);
230                         if (namefile == "not found") { namefile = "";  hasName = false; }
231                         else { 
232                                 m->splitAtDash(namefile, nameFileNames);
233                                 
234                                 //go through files and make sure they are good, if not, then disregard them
235                                 for (int i = 0; i < nameFileNames.size(); i++) {
236                                         
237                                         bool ignore = false;
238                                         if (nameFileNames[i] == "current") { 
239                                                 nameFileNames[i] = m->getNameFile(); 
240                                                 if (nameFileNames[i] != "") {  m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
241                                                 else {  
242                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
243                                                         //erase from file list
244                                                         nameFileNames.erase(nameFileNames.begin()+i);
245                                                         i--;
246                                                 }
247                                         }
248                                         
249                                         if (!ignore) {
250                                                 
251                                                 if (inputDir != "") {
252                                                         string path = m->hasPath(nameFileNames[i]);
253                                                         //if the user has not given a path then, add inputdir. else leave path alone.
254                                                         if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
255                                                 }
256                                                 
257                                                 int ableToOpen;
258                                                 ifstream in;
259                                                 
260                                                 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
261                                                 
262                                                 //if you can't open it, try default location
263                                                 if (ableToOpen == 1) {
264                                                         if (m->getDefaultPath() != "") { //default path is set
265                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
266                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
267                                                                 ifstream in2;
268                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
269                                                                 in2.close();
270                                                                 nameFileNames[i] = tryPath;
271                                                         }
272                                                 }
273                                                 
274                                                 if (ableToOpen == 1) {
275                                                         if (m->getOutputDir() != "") { //default path is set
276                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
277                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
278                                                                 ifstream in2;
279                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
280                                                                 in2.close();
281                                                                 nameFileNames[i] = tryPath;
282                                                         }
283                                                 }
284                                                 
285                                                 in.close();
286                                                 
287                                                 if (ableToOpen == 1) { 
288                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
289                                                         //erase from file list
290                                                         nameFileNames.erase(nameFileNames.begin()+i);
291                                                         i--;
292                                                 }else {
293                                                         m->setNameFile(nameFileNames[i]);
294                                                 }
295                                         }
296                                 }
297                                 
298                                 //make sure there is at least one valid file left
299                                 if (nameFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid name files."); m->mothurOutEndLine(); abort = true; }
300                         }
301                         
302                         if (hasName && (nameFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of namefiles does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
303                         
304                         bool hasGroup = true;
305                         groupfile = validParameter.validFile(parameters, "group", false);
306                         if (groupfile == "not found") { groupfile = "";  hasGroup = false; }
307                         else { 
308                                 m->splitAtDash(groupfile, groupFileNames);
309                                 
310                                 //go through files and make sure they are good, if not, then disregard them
311                                 for (int i = 0; i < groupFileNames.size(); i++) {
312                                         
313                                         bool ignore = false;
314                                         if (groupFileNames[i] == "current") { 
315                                                 groupFileNames[i] = m->getGroupFile(); 
316                                                 if (groupFileNames[i] != "") {  m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
317                                                 else {  
318                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
319                                                         //erase from file list
320                                                         groupFileNames.erase(groupFileNames.begin()+i);
321                                                         i--;
322                                                 }
323                                         }
324                                         
325                                         if (!ignore) {
326                                                 
327                                                 if (inputDir != "") {
328                                                         string path = m->hasPath(groupFileNames[i]);
329                                                         //if the user has not given a path then, add inputdir. else leave path alone.
330                                                         if (path == "") {       groupFileNames[i] = inputDir + groupFileNames[i];               }
331                                                 }
332                                                 
333                                                 int ableToOpen;
334                                                 ifstream in;
335                                                 
336                                                 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
337                                                 
338                                                 //if you can't open it, try default location
339                                                 if (ableToOpen == 1) {
340                                                         if (m->getDefaultPath() != "") { //default path is set
341                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
342                                                                 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
343                                                                 ifstream in2;
344                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
345                                                                 in2.close();
346                                                                 groupFileNames[i] = tryPath;
347                                                         }
348                                                 }
349                                                 
350                                                 if (ableToOpen == 1) {
351                                                         if (m->getOutputDir() != "") { //default path is set
352                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
353                                                                 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
354                                                                 ifstream in2;
355                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
356                                                                 in2.close();
357                                                                 groupFileNames[i] = tryPath;
358                                                         }
359                                                 }
360                                                 
361                                                 in.close();
362                                                 
363                                                 if (ableToOpen == 1) { 
364                                                         m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
365                                                         //erase from file list
366                                                         groupFileNames.erase(groupFileNames.begin()+i);
367                                                         i--;
368                                                 }else {
369                                                         m->setGroupFile(groupFileNames[i]);
370                                                 }
371                                         }
372                                 }
373                                 
374                                 //make sure there is at least one valid file left
375                                 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
376                         }
377                         
378                         if (hasGroup && (groupFileNames.size() != fastaFileNames.size())) { m->mothurOut("[ERROR]: The number of groupfiles does not match the number of fastafiles, please correct."); m->mothurOutEndLine(); abort=true; }
379                         
380                         
381                         //if the user changes the output directory command factory will send this info to us in the output parameter 
382                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
383                         
384                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
385                         m->setProcessors(temp);
386                         m->mothurConvert(temp, processors);
387                         
388                         temp = validParameter.validFile(parameters, "save", false);                     if (temp == "not found"){       temp = "f";                             }
389                         save = m->isTrue(temp); 
390                         rdb->save = save; 
391                         if (save) { //clear out old references
392                                 rdb->clearMemory();     
393                         }
394                         
395                         string path;
396                         it = parameters.find("reference");
397                         //user has given a template file
398                         if(it != parameters.end()){ 
399                                 if (it->second == "self") { 
400                                         templatefile = "self"; 
401                                         if (save) {
402                                                 m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
403                                                 m->mothurOutEndLine();
404                                                 save = false;
405                                         }
406                                 }
407                                 else {
408                                         path = m->hasPath(it->second);
409                                         //if the user has not given a path then, add inputdir. else leave path alone.
410                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
411                                         
412                                         templatefile = validParameter.validFile(parameters, "reference", true);
413                                         if (templatefile == "not open") { abort = true; }
414                                         else if (templatefile == "not found") { //check for saved reference sequences
415                                                 if (rdb->referenceSeqs.size() != 0) {
416                                                         templatefile = "saved";
417                                                 }else {
418                                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
419                                                         m->mothurOutEndLine();
420                                                         abort = true; 
421                                                 }
422                                         }else { if (save) {     rdb->setSavedReference(templatefile);   }       }       
423                                 }
424                         }else if (hasName) {  templatefile = "self"; 
425                                 if (save) {
426                                         m->mothurOut("[WARNING]: You can't save reference=self, ignoring save."); 
427                                         m->mothurOutEndLine();
428                                         save = false;
429                                 }
430                         }
431                         else { 
432                                 if (rdb->referenceSeqs.size() != 0) {
433                                         templatefile = "saved";
434                                 }else {
435                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
436                                         m->mothurOutEndLine();
437                                         templatefile = ""; abort = true; 
438                                 } 
439                         }
440                         
441                         
442                         
443                         temp = validParameter.validFile(parameters, "ksize", false);                    if (temp == "not found") { temp = "7"; }
444                         m->mothurConvert(temp, ksize);
445                                                 
446                         temp = validParameter.validFile(parameters, "window", false);                   if (temp == "not found") { temp = "50"; }                       
447                         m->mothurConvert(temp, window);
448                         
449                         temp = validParameter.validFile(parameters, "match", false);                    if (temp == "not found") { temp = "5"; }
450                         m->mothurConvert(temp, match);
451                         
452                         temp = validParameter.validFile(parameters, "mismatch", false);                 if (temp == "not found") { temp = "-4"; }
453                         m->mothurConvert(temp, mismatch);
454                         
455                         temp = validParameter.validFile(parameters, "divergence", false);               if (temp == "not found") { temp = "1.007"; }
456                         m->mothurConvert(temp, divR);
457                         
458                         temp = validParameter.validFile(parameters, "minsim", false);                   if (temp == "not found") { temp = "90"; }
459                         m->mothurConvert(temp, minSimilarity);
460                         
461                         temp = validParameter.validFile(parameters, "mincov", false);                   if (temp == "not found") { temp = "70"; }
462                         m->mothurConvert(temp, minCoverage);
463                         
464                         temp = validParameter.validFile(parameters, "minbs", false);                    if (temp == "not found") { temp = "90"; }
465                         m->mothurConvert(temp, minBS);
466                         
467                         temp = validParameter.validFile(parameters, "minsnp", false);                   if (temp == "not found") { temp = "10"; }
468                         m->mothurConvert(temp, minSNP);
469
470                         temp = validParameter.validFile(parameters, "parents", false);                  if (temp == "not found") { temp = "3"; }
471                         m->mothurConvert(temp, parents); 
472                         
473                         temp = validParameter.validFile(parameters, "realign", false);                  if (temp == "not found") { temp = "t"; }
474                         realign = m->isTrue(temp); 
475                         
476                         temp = validParameter.validFile(parameters, "trim", false);                             if (temp == "not found") { temp = "f"; }
477                         trim = m->isTrue(temp); 
478                         
479                         temp = validParameter.validFile(parameters, "split", false);                    if (temp == "not found") { temp = "f"; }
480                         trimera = m->isTrue(temp); 
481                         
482                         search = validParameter.validFile(parameters, "search", false);                 if (search == "not found") { search = "blast"; }
483                         
484                         temp = validParameter.validFile(parameters, "iters", false);                    if (temp == "not found") { temp = "1000"; }             
485                         m->mothurConvert(temp, iters); 
486                          
487                         temp = validParameter.validFile(parameters, "increment", false);                if (temp == "not found") { temp = "5"; }
488                         m->mothurConvert(temp, increment);
489                         
490                         temp = validParameter.validFile(parameters, "numwanted", false);                if (temp == "not found") { temp = "15"; }               
491                         m->mothurConvert(temp, numwanted);
492                         
493                         blastlocation = validParameter.validFile(parameters, "blastlocation", false);   
494                         if (blastlocation == "not found") { blastlocation = ""; }
495                         else {
496                                 //add / to name if needed
497                                 string lastChar = blastlocation.substr(blastlocation.length()-1);
498 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
499                                 if (lastChar != "/") { blastlocation += "/"; }
500 #else
501                                 if (lastChar != "\\") { blastlocation += "\\"; }        
502 #endif
503                                 blastlocation = m->getFullPathName(blastlocation);
504                                 string formatdbCommand = "";
505 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
506                                 formatdbCommand = blastlocation + "formatdb";   
507 #else
508                                 formatdbCommand = blastlocation + "formatdb.exe";
509 #endif
510                                 
511                                 //test to make sure formatdb exists
512                                 ifstream in;
513                                 formatdbCommand = m->getFullPathName(formatdbCommand);
514                                 int ableToOpen = m->openInputFile(formatdbCommand, in, "no error"); in.close();
515                                 if(ableToOpen == 1) {   m->mothurOut("[ERROR]: " + formatdbCommand + " file does not exist. mothur requires formatdb.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
516                                 
517                                 string blastCommand = "";
518 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
519                                 blastCommand = blastlocation + "megablast";     
520 #else
521                                 blastCommand = blastlocation + "megablast.exe";
522 #endif
523                                 //test to make sure formatdb exists
524                                 ifstream in2;
525                                 blastCommand = m->getFullPathName(blastCommand);
526                                 ableToOpen = m->openInputFile(blastCommand, in2, "no error"); in2.close();
527                                 if(ableToOpen == 1) {   m->mothurOut("[ERROR]: " + blastCommand + " file does not exist. mothur requires blastall.exe to run chimera.slayer."); m->mothurOutEndLine(); abort = true; }
528                         }
529
530                         if ((search != "blast") && (search != "kmer")) { m->mothurOut(search + " is not a valid search."); m->mothurOutEndLine(); abort = true;  }
531                         
532                         if (hasName && (templatefile != "self")) { m->mothurOut("You have provided a namefile and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
533                         if (hasGroup && (templatefile != "self")) { m->mothurOut("You have provided a group file and the reference parameter is not set to self. I am not sure what reference you are trying to use, aborting."); m->mothurOutEndLine(); abort=true; }
534
535                         //until we resolve the issue 10-18-11
536 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
537 #else
538                         //processors=1;
539 #endif
540                 }
541         }
542         catch(exception& e) {
543                 m->errorOut(e, "ChimeraSlayerCommand", "ChimeraSlayerCommand");
544                 exit(1);
545         }
546 }
547 //***************************************************************************************************************
548
549 int ChimeraSlayerCommand::execute(){
550         try{
551                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
552
553                 for (int s = 0; s < fastaFileNames.size(); s++) {
554                                 
555                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
556                 
557                         int start = time(NULL); 
558                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it                               
559                         string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + "slayer.chimera";
560                         string accnosFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.accnos";
561                         string trimFastaFileName = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]))  + "slayer.fasta";           
562                         
563                         //clears files
564                         ofstream out, out1, out2;
565                         m->openOutputFile(outputFileName, out); out.close(); 
566                         m->openOutputFile(accnosFileName, out1); out1.close();
567                         if (trim) { m->openOutputFile(trimFastaFileName, out2); out2.close(); }
568                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
569                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
570                         if (trim) {  outputNames.push_back(trimFastaFileName); outputTypes["fasta"].push_back(trimFastaFileName); }                     
571                         
572                         //maps a filename to priority map. 
573                         //if no groupfile this is fastafileNames[s] -> prioirity
574                         //if groupfile then this is each groups seqs -> priority
575                         map<string, map<string, int> > fileToPriority; 
576                         map<string, map<string, int> >::iterator itFile;
577                         map<string, string> fileGroup;
578                         fileToPriority[fastaFileNames[s]] = priority; //default
579                         fileGroup[fastaFileNames[s]] = "noGroup";
580                         SequenceParser* parser = NULL;
581                         int totalChimeras = 0;
582                         lines.clear();
583                         
584                         if (templatefile == "self") { setUpForSelfReference(parser, fileGroup, fileToPriority, s); }
585                         
586                         if (m->control_pressed) {  if (parser != NULL) { delete parser; } for (int j = 0; j < outputNames.size(); j++) {        m->mothurRemove(outputNames[j]);        }  return 0;    }
587
588                         if (fileToPriority.size() == 1) { //you running without a groupfile
589                                 itFile = fileToPriority.begin();
590                                 string thisFastaName = itFile->first;
591                                 map<string, int> thisPriority = itFile->second;
592 #ifdef USE_MPI  
593                                 MPIExecute(thisFastaName, outputFileName, accnosFileName, trimFastaFileName, thisPriority);
594 #else
595                                 //break up file
596                                 vector<unsigned long long> positions; 
597 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
598                                 positions = m->divideFile(thisFastaName, processors);
599                                 for (int i = 0; i < (positions.size()-1); i++) {        lines.push_back(linePair(positions[i], positions[(i+1)]));      }
600 #else
601                                 if (processors == 1) {  lines.push_back(linePair(0, 1000)); }
602                                 else {
603                                         positions = m->setFilePosFasta(thisFastaName, numSeqs); 
604                     if (positions.size() < processors) { processors = positions.size(); }
605                                         
606                                         //figure out how many sequences you have to process
607                                         int numSeqsPerProcessor = numSeqs / processors;
608                                         for (int i = 0; i < processors; i++) {
609                                                 int startIndex =  i * numSeqsPerProcessor;
610                                                 if(i == (processors - 1)){      numSeqsPerProcessor = numSeqs - i * numSeqsPerProcessor;        }
611                                                 lines.push_back(linePair(positions[startIndex], numSeqsPerProcessor));
612                                         }
613                                 }
614 #endif
615                                 if(processors == 1){ numSeqs = driver(lines[0], outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority);  }
616                                 else{ numSeqs = createProcesses(outputFileName, thisFastaName, accnosFileName, trimFastaFileName, thisPriority); }
617                                 
618                                 if (m->control_pressed) { if (parser != NULL) { delete parser; }  outputTypes.clear(); if (trim) { m->mothurRemove(trimFastaFileName); } m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); for (int j = 0; j < outputNames.size(); j++) {       m->mothurRemove(outputNames[j]);        }  return 0; }                          
619 #endif
620                         }else { //you have provided a groupfile
621 #ifdef USE_MPI  
622                                 MPIExecuteGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);
623 #else
624                                 if (processors == 1) { numSeqs = driverGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);    }
625                                 else {  numSeqs = createProcessesGroups(outputFileName, accnosFileName, trimFastaFileName, fileToPriority, fileGroup);          } //destroys fileToPriority
626 #endif
627
628 #ifdef USE_MPI  
629                                 int pid; 
630                                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
631                                 
632                                 if (pid == 0) {
633 #endif
634                                 
635                                 totalChimeras = deconvoluteResults(parser, outputFileName, accnosFileName, trimFastaFileName);
636                 m->mothurOutEndLine(); m->mothurOut(toString(totalChimeras) + " chimera found."); m->mothurOutEndLine();
637 #ifdef USE_MPI  
638                                 }
639                                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
640 #endif
641                         }
642         
643                         if (parser != NULL) { delete parser; } 
644                         
645             m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences.");    m->mothurOutEndLine();
646                 }
647                 
648                 //set accnos file as new current accnosfile
649                 string current = "";
650                 itTypes = outputTypes.find("accnos");
651                 if (itTypes != outputTypes.end()) {
652                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
653                 }
654                 
655                 if (trim) {
656                         itTypes = outputTypes.find("fasta");
657                         if (itTypes != outputTypes.end()) {
658                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
659                         }
660                 }
661                 
662                 m->mothurOutEndLine();
663                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
664                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
665                 m->mothurOutEndLine();
666
667                 return 0;
668                 
669         }
670         catch(exception& e) {
671                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
672                 exit(1);
673         }
674 }
675 //**********************************************************************************************************************
676 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
677         try {
678 #ifdef USE_MPI  
679                 int pid; 
680                 int tag = 2001;
681                 
682                 MPI_Status status; 
683                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
684                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
685         
686                 //put filenames in a vector, then pass each process a starting and ending point in the vector
687                 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
688                 map<string, map<string, int> >::iterator itFile;
689                 vector<string> filenames;
690                 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
691                 
692                 int numGroupsPerProcessor = filenames.size() / processors;
693                 int startIndex =  pid * numGroupsPerProcessor;
694                 int endIndex = (pid+1) * numGroupsPerProcessor;
695                 if(pid == (processors - 1)){    endIndex = filenames.size();    }
696                 
697                 vector<unsigned long long> MPIPos;
698                 
699                 MPI_File outMPI;
700                 MPI_File outMPIAccnos;
701                 MPI_File outMPIFasta;
702                 
703                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
704                 int inMode=MPI_MODE_RDONLY; 
705                 
706                 char outFilename[1024];
707                 strcpy(outFilename, outputFileName.c_str());
708                 
709                 char outAccnosFilename[1024];
710                 strcpy(outAccnosFilename, accnosFileName.c_str());
711                 
712                 char outFastaFilename[1024];
713                 strcpy(outFastaFilename, trimFastaFileName.c_str());
714                 
715                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
716                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
717                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
718                 
719                 if (m->control_pressed) {   MPI_File_close(&outMPI); if (trim) {  MPI_File_close(&outMPIFasta);  } MPI_File_close(&outMPIAccnos);  return 0;  }
720                 
721                 //print headers
722                 if (pid == 0) { //you are the root process 
723                         m->mothurOutEndLine();
724                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
725                         m->mothurOutEndLine();
726                         
727                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
728                         
729                         //print header
730                         int length = outTemp.length();
731                         char* buf2 = new char[length];
732                         memcpy(buf2, outTemp.c_str(), length);
733                         
734                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
735                         delete buf2;
736                 }
737                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
738                 
739                 for (int i = startIndex; i < endIndex; i++) {
740                         
741                         int start = time(NULL);
742                         int num = 0;
743                         string thisFastaName = filenames[i];
744                         map<string, int> thisPriority = fileToPriority[thisFastaName];
745                         
746                         char inFileName[1024];
747                         strcpy(inFileName, thisFastaName.c_str());
748                         MPI_File inMPI;
749                         MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
750                         
751                         MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
752                         
753                         cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl; 
754                         
755                         driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, thisFastaName, thisPriority, true);
756                         numSeqs += num;
757                         
758                         MPI_File_close(&inMPI);
759                         m->mothurRemove(thisFastaName);
760                                                 
761                         cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
762                 }
763                 
764                 if (pid == 0) {
765                         for(int i = 1; i < processors; i++) { 
766                                 int temp = 0;
767                                 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
768                                 numSeqs += temp;
769                         }
770                 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
771                 
772                 MPI_File_close(&outMPI);
773                 MPI_File_close(&outMPIAccnos); 
774                 if (trim) { MPI_File_close(&outMPIFasta); }
775                 
776                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
777 #endif
778                 return 0;
779                 
780         }catch(exception& e) {
781                 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
782                 exit(1);
783         }
784 }               
785 //**********************************************************************************************************************
786 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
787         try {
788                 
789 #ifdef USE_MPI  
790                 int pid, numSeqsPerProcessor; 
791                 int tag = 2001;
792                 vector<unsigned long long> MPIPos;
793                 
794                 MPI_Status status; 
795                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
796                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
797                 
798                 MPI_File inMPI;
799                 MPI_File outMPI;
800                 MPI_File outMPIAccnos;
801                 MPI_File outMPIFasta;
802                 
803                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
804                 int inMode=MPI_MODE_RDONLY; 
805                 
806                 char outFilename[1024];
807                 strcpy(outFilename, outputFileName.c_str());
808                 
809                 char outAccnosFilename[1024];
810                 strcpy(outAccnosFilename, accnosFileName.c_str());
811                 
812                 char outFastaFilename[1024];
813                 strcpy(outFastaFilename, trimFastaFileName.c_str());
814                 
815                 char inFileName[1024];
816                 strcpy(inFileName, inputFile.c_str());
817                 
818                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
819                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
820                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
821                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
822                 
823                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) {  MPI_File_close(&outMPIFasta);  } MPI_File_close(&outMPIAccnos);  return 0;  }
824                 
825                 if (pid == 0) { //you are the root process 
826                         m->mothurOutEndLine();
827                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
828                         m->mothurOutEndLine();
829                         
830                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
831                         
832                         //print header
833                         int length = outTemp.length();
834                         char* buf2 = new char[length];
835                         memcpy(buf2, outTemp.c_str(), length);
836                         
837                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
838                         delete buf2;
839                         
840                         MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
841                         
842                         if (templatefile != "self") { //if template=self we can only use 1 processor
843                                 //send file positions to all processes
844                                 for(int i = 1; i < processors; i++) { 
845                                         MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
846                                         MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
847                                 }
848                         }
849                         //figure out how many sequences you have to align
850                         numSeqsPerProcessor = numSeqs / processors;
851                         int startIndex =  pid * numSeqsPerProcessor;
852                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
853                         
854                         if (templatefile == "self") { //if template=self we can only use 1 processor
855                                 startIndex = 0;
856                                 numSeqsPerProcessor = numSeqs;
857                         }
858                         
859                         //do your part
860                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
861                                                 
862                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);   return 0;  }
863                         
864                 }else{ //you are a child process
865                         if (templatefile != "self") { //if template=self we can only use 1 processor
866                                 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
867                                 MPIPos.resize(numSeqs+1);
868                                 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
869                                 
870                                 //figure out how many sequences you have to align
871                                 numSeqsPerProcessor = numSeqs / processors;
872                                 int startIndex =  pid * numSeqsPerProcessor;
873                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
874                                 
875                                 //do your part
876                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, MPIPos, inputFile, priority, false);
877                                 
878                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  return 0;  }
879                                 
880                         }
881                 }
882                 
883                 //close files 
884                 MPI_File_close(&inMPI);
885                 MPI_File_close(&outMPI);
886                 MPI_File_close(&outMPIAccnos); 
887                 if (trim) { MPI_File_close(&outMPIFasta); }
888                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
889                 
890                 
891 #endif          
892                 return numSeqs;
893         }
894         catch(exception& e) {
895                 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
896                 exit(1);
897         }
898 }
899 //**********************************************************************************************************************
900 int ChimeraSlayerCommand::deconvoluteResults(SequenceParser* parser, string outputFileName, string accnosFileName, string trimFileName){
901         try {
902                 map<string, string> uniqueNames = parser->getAllSeqsMap();
903                 map<string, string>::iterator itUnique;
904                 int total = 0;
905         
906         if (trimera) { //add in more potential uniqueNames
907             map<string, string> newUniqueNames = uniqueNames;
908             for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
909                 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
910                 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
911             }
912             uniqueNames = newUniqueNames;
913             newUniqueNames.clear();
914         }
915                 
916                 //edit accnos file
917                 ifstream in2; 
918                 m->openInputFile(accnosFileName, in2, "no error");
919                 
920                 ofstream out2;
921                 m->openOutputFile(accnosFileName+".temp", out2);
922                 
923                 string name; name = "";
924                 set<string> chimerasInFile;
925                 set<string>::iterator itChimeras;
926                 
927                 while (!in2.eof()) {
928                         if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
929                         
930                         in2 >> name; m->gobble(in2);
931                         
932                         //find unique name
933                         itUnique = uniqueNames.find(name);
934                         
935                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
936                         else {
937                                 itChimeras = chimerasInFile.find((itUnique->second));
938                                 
939                                 if (itChimeras == chimerasInFile.end()) {
940                                         out2 << itUnique->second << endl;
941                                         chimerasInFile.insert((itUnique->second));
942                                         total++;
943                                 }
944                         }
945                 }
946                 in2.close();
947                 out2.close();
948                 
949                 m->mothurRemove(accnosFileName);
950                 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
951                 
952                 
953                 //edit chimera file
954                 ifstream in; 
955                 m->openInputFile(outputFileName, in);
956                 
957                 ofstream out;
958                 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
959
960                 string rest, parent1, parent2, line;
961                 set<string> namesInFile; //this is so if a sequence is found to be chimera in several samples we dont write it to the results file more than once
962                 set<string>::iterator itNames;
963                 
964                 //assumptions - in file each read will always look like...
965                 /*
966                  F11Fcsw_92754  no
967                  F11Fcsw_63104  F11Fcsw_33372   F11Fcsw_37007   0.89441 80.4469 0.2     1.03727 93.2961 52.2    no      0-241   243-369 
968                  */
969                 
970                 //get header line
971                 if (!in.eof()) {
972                         line = m->getline(in); m->gobble(in);
973                         out << line << endl;
974                 }
975                 
976                 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do, 
977                 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file, 
978                 //then ignore this report and continue until we find the report that found it to be chimeric
979                 
980                 while (!in.eof()) {
981                         
982                         if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
983                         
984                         in >> name;             m->gobble(in);
985                         in >> parent1;  m->gobble(in);
986                         
987                         if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
988                                 line = m->getline(in); m->gobble(in);
989                         }else {
990                                 if (parent1 == "no") {
991                                         //find unique name
992                                         itUnique = uniqueNames.find(name);
993                                         
994                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
995                                         else {
996                                                 //is this sequence really not chimeric??
997                                                 itChimeras = chimerasInFile.find(itUnique->second);
998                                                 
999                                                 if (itChimeras == chimerasInFile.end()) {
1000                                                         //is this sequence not already in the file
1001                                                         itNames = namesInFile.find((itUnique->second));
1002                                                         
1003                                                         if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1004                                                 }
1005                                         }
1006                                 }else { //read the rest of the line
1007                                         double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1008                                         string flag, range1, range2;
1009                                         bool print = false;
1010                                         in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2;  m->gobble(in);
1011                                         
1012                                         //find unique name
1013                                         itUnique = uniqueNames.find(name);
1014                                         
1015                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1016                                         else {
1017                                                 name = itUnique->second;
1018                                                 //is this name already in the file
1019                                                 itNames = namesInFile.find((name));
1020                                                 
1021                                                 if (itNames == namesInFile.end()) { //no not in file
1022                                                         if (flag == "no") { //are you really a no??
1023                                                                 //is this sequence really not chimeric??
1024                                                                 itChimeras = chimerasInFile.find(name);
1025                                                                 
1026                                                                 //then you really are a no so print, otherwise skip
1027                                                                 if (itChimeras == chimerasInFile.end()) { print = true; }
1028                                                                 
1029                                                         }else{ print = true; }
1030                                                 }
1031                                         }
1032                                         
1033                                         if (print) {
1034                                                 out << name << '\t';
1035                                                 
1036                                                 namesInFile.insert(name);
1037
1038                                                 //output parent1's name
1039                                                 itUnique = uniqueNames.find(parent1);
1040                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1041                                                 else { out << itUnique->second << '\t'; }
1042                                                 
1043                                                 //output parent2's name
1044                                                 itUnique = uniqueNames.find(parent2);
1045                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1046                                                 else { out << itUnique->second << '\t'; }
1047                                                 
1048                                                 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1049                                         }
1050                                 }                               
1051                         }
1052                 }
1053                 in.close();
1054                 out.close();
1055                 
1056                 m->mothurRemove(outputFileName);
1057                 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1058                 
1059                 //edit fasta file
1060                 if (trim) {
1061                         ifstream in3; 
1062                         m->openInputFile(trimFileName, in3);
1063                         
1064                         ofstream out3;
1065                         m->openOutputFile(trimFileName+".temp", out3);
1066                         
1067                         namesInFile.clear();
1068                         
1069                         while (!in3.eof()) {
1070                                 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1071                                 
1072                                 Sequence seq(in3); m->gobble(in3);
1073                                 
1074                                 if (seq.getName() != "") {
1075                                         //find unique name
1076                                         itUnique = uniqueNames.find(seq.getName());
1077                                         
1078                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1079                                         else {
1080                                                 itNames = namesInFile.find((itUnique->second));
1081                                                 
1082                                                 if (itNames == namesInFile.end()) {
1083                                                         seq.printSequence(out3);
1084                                                 }
1085                                         }
1086                                 }
1087                         }
1088                         in3.close();
1089                         out3.close();
1090                         
1091                         m->mothurRemove(trimFileName);
1092                         rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1093                 }
1094                 
1095                 return total;
1096         }
1097         catch(exception& e) {
1098                 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1099                 exit(1);
1100         }
1101 }
1102 //**********************************************************************************************************************
1103 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1104         try {
1105                 fileGroup.clear();
1106                 fileToPriority.clear();
1107                 
1108                 string nameFile = "";
1109                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1110                         nameFile = nameFileNames[s];
1111                 }else {  nameFile = getNamesFile(fastaFileNames[s]); }
1112                 
1113                 //you provided a groupfile
1114                 string groupFile = "";
1115                 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1116                 
1117                 if (groupFile == "") { 
1118                         if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1119                                                 
1120                         //sort fastafile by abundance, returns new sorted fastafile name
1121                         m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
1122                         priority = sortFastaFile(fastaFileNames[s], nameFile);
1123                         m->mothurOut("Done."); m->mothurOutEndLine();
1124                         
1125                         fileToPriority[fastaFileNames[s]] = priority;
1126                         fileGroup[fastaFileNames[s]] = "noGroup";
1127                 }else {
1128                         //Parse sequences by group
1129                         parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1130                         vector<string> groups = parser->getNamesOfGroups();
1131                         
1132                         for (int i = 0; i < groups.size(); i++) {
1133                                 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1134                                 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1135                                 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1136                                 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile); 
1137                                 fileToPriority[newFastaFile] = priority;
1138                                 fileGroup[newFastaFile] = groups[i];
1139                         }
1140                 }
1141                 
1142                 
1143                 return 0;
1144         }
1145         catch(exception& e) {
1146                 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1147                 exit(1);
1148         }
1149 }
1150
1151 //**********************************************************************************************************************
1152 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1153         try {
1154                 string nameFile = "";
1155                 
1156                 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1157                 
1158                 //use unique.seqs to create new name and fastafile
1159                 string inputString = "fasta=" + inputFile;
1160                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1161                 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
1162                 m->mothurCalling = true;
1163         
1164                 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1165                 uniqueCommand->execute();
1166                 
1167                 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1168                 
1169                 delete uniqueCommand;
1170                 m->mothurCalling = false;
1171                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1172                 
1173                 nameFile = filenames["name"][0];
1174                 inputFile = filenames["fasta"][0];
1175                 
1176                 return nameFile;
1177         }
1178         catch(exception& e) {
1179                 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1180                 exit(1);
1181         }
1182 }
1183 //**********************************************************************************************************************
1184
1185 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup){
1186         try {
1187                 int totalSeqs = 0;
1188                 
1189                 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1190                         
1191                         if (m->control_pressed) {  return 0;  }
1192                         
1193                         int start = time(NULL);
1194                         string thisFastaName = itFile->first;
1195                         map<string, int> thisPriority = itFile->second;
1196                         string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1197                         string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1198                         string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1199                         
1200                         m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine(); 
1201                         
1202                         lines.clear();
1203 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1204                         int proc = 1;
1205                         vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1206                         lines.push_back(linePair(positions[0], positions[1]));  
1207 #else
1208                         lines.push_back(linePair(0, 1000)); 
1209 #endif                  
1210                         int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1211                         
1212                         //append files
1213                         m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName); 
1214                         m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1215                         if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1216                         m->mothurRemove(thisFastaName);
1217                         
1218                         totalSeqs += numSeqs;
1219                         
1220                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + ".");     m->mothurOutEndLine();
1221                 }
1222                 
1223                 return totalSeqs;
1224         }
1225         catch(exception& e) {
1226                 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1227                 exit(1);
1228         }
1229 }
1230 /**************************************************************************************************/
1231 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup) {
1232         try {
1233                 int process = 1;
1234                 int num = 0;
1235                 processIDS.clear();
1236                 
1237                 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1238                 
1239                 int groupsPerProcessor = fileToPriority.size() / processors;
1240                 int remainder = fileToPriority.size() % processors;
1241                 
1242                 vector< map<string, map<string, int> > > breakUp;
1243                 
1244                 for (int i = 0; i < processors; i++) {
1245                         map<string, map<string, int> > thisFileToPriority;
1246                         map<string, map<string, int> >::iterator itFile;
1247                         int count = 0;
1248                         int enough = groupsPerProcessor;
1249                         if (i == 0) { enough = groupsPerProcessor + remainder; }
1250                         
1251                         for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1252                                 thisFileToPriority[itFile->first] = itFile->second;
1253                                 fileToPriority.erase(itFile++);
1254                                 count++;
1255                                 if (count == enough) { break; }
1256                         }       
1257                         breakUp.push_back(thisFileToPriority);
1258                 }
1259                                 
1260 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1261                 //loop through and create all the processes you want
1262                 while (process != processors) {
1263                         int pid = fork();
1264                         
1265                         if (pid > 0) {
1266                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1267                                 process++;
1268                         }else if (pid == 0){
1269                                 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup);
1270                                 
1271                                 //pass numSeqs to parent
1272                                 ofstream out;
1273                                 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1274                                 m->openOutputFile(tempFile, out);
1275                                 out << num << endl;
1276                                 out.close();
1277                                 exit(0);
1278                         }else { 
1279                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1280                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1281                                 exit(0);
1282                         }
1283                 }
1284                 
1285                 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1286
1287                 //force parent to wait until all the processes are done
1288                 for (int i=0;i<processors;i++) { 
1289                         int temp = processIDS[i];
1290                         wait(&temp);
1291                 }
1292                 
1293                 for (int i = 0; i < processIDS.size(); i++) {
1294                         ifstream in;
1295                         string tempFile =  outputFName + toString(processIDS[i]) + ".num.temp";
1296                         m->openInputFile(tempFile, in);
1297                         if (!in.eof()) { int tempNum = 0;  in >> tempNum; num += tempNum; }
1298                         in.close(); m->mothurRemove(tempFile);
1299                 }
1300 #else
1301                 
1302                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1303                 //Windows version shared memory, so be careful when passing variables through the slayerData struct. 
1304                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
1305                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1306                 
1307                 vector<slayerData*> pDataArray; 
1308                 DWORD   dwThreadIdArray[processors-1];
1309                 HANDLE  hThreadArray[processors-1]; 
1310                 
1311                 //Create processor worker threads.
1312                 for(int i=1; i<processors; i++ ){
1313                         string extension = toString(i) + ".temp";
1314                         slayerData* tempslayer = new slayerData((outputFName + extension), (fasta + extension), (accnos + extension), templatefile, search, blastlocation, trimera, trim, realign, m, breakUp[i], fileGroup, ksize, match, mismatch, window, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, divR, priority, i);
1315                         pDataArray.push_back(tempslayer);
1316                         processIDS.push_back(i);
1317                         
1318                         //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1319                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1320                         hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
1321                 }
1322                 
1323                 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup);
1324                 
1325                 //Wait until all threads have terminated.
1326                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1327                 
1328                 //Close all thread handles and free memory allocations.
1329                 for(int i=0; i < pDataArray.size(); i++){
1330                         num += pDataArray[i]->count;
1331                         CloseHandle(hThreadArray[i]);
1332                         delete pDataArray[i];
1333                 }
1334 #endif  
1335                 
1336                 //append output files
1337                 for(int i=0;i<processIDS.size();i++){
1338                         m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1339                         m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1340                         
1341                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1342                         m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1343                         
1344                         if (trim) {
1345                                 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1346                                 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1347                         }
1348                 }
1349                 
1350                 
1351                 return num;
1352         }
1353         catch(exception& e) {
1354                 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1355                 exit(1);
1356         }
1357 }
1358 //**********************************************************************************************************************
1359
1360 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1361         try {
1362                 
1363                 Chimera* chimera;
1364                 if (templatefile != "self") { //you want to run slayer with a reference template
1365                         chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());       
1366                 }else {
1367                         chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());     
1368                 }
1369                 
1370                 if (m->control_pressed) { delete chimera; return 0; }
1371                 
1372                 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1373                 templateSeqsLength = chimera->getLength();
1374                 
1375                 ofstream out;
1376                 m->openOutputFile(outputFName, out);
1377                 
1378                 ofstream out2;
1379                 m->openOutputFile(accnos, out2);
1380                 
1381                 ofstream out3;
1382                 if (trim) {  m->openOutputFile(fasta, out3); }
1383                 
1384                 ifstream inFASTA;
1385                 m->openInputFile(filename, inFASTA);
1386
1387                 inFASTA.seekg(filePos.start);
1388                 
1389                 if (filePos.start == 0) { chimera->printHeader(out); }
1390
1391                 bool done = false;
1392                 int count = 0;
1393         
1394                 while (!done) {
1395                 
1396                         if (m->control_pressed) {       delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1;       }
1397                 
1398                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
1399                         string candidateAligned = candidateSeq->getAligned();
1400                         
1401                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1402                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
1403                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1404                                 }else{
1405                                         //find chimeras
1406                                         chimera->getChimeras(candidateSeq);
1407                                         
1408                                         if (m->control_pressed) {       delete chimera; delete candidateSeq; return 1;  }
1409                                                 
1410                                         //if you are not chimeric, then check each half
1411                                         data_results wholeResults = chimera->getResults();
1412                                         
1413                                         //determine if we need to split
1414                                         bool isChimeric = false;
1415                                         
1416                                         if (wholeResults.flag == "yes") {
1417                                                 string chimeraFlag = "no";
1418                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1419                                                    ||
1420                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1421                                                 
1422                                                 
1423                                                 if (chimeraFlag == "yes") {     
1424                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1425                                                 }
1426                                         }
1427                                         
1428                                         if ((!isChimeric) && trimera) {
1429                                                 
1430                                                 //split sequence in half by bases
1431                                                 string leftQuery, rightQuery;
1432                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1433                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
1434                                                 
1435                                                 //run chimeraSlayer on each piece
1436                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1437                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1438                                                 
1439                                                 //find chimeras
1440                                                 chimera->getChimeras(left);
1441                                                 data_results leftResults = chimera->getResults();
1442                                                 
1443                                                 chimera->getChimeras(right);
1444                                                 data_results rightResults = chimera->getResults();
1445                                                 
1446                                                 //if either piece is chimeric then report
1447                                                 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1448                                                 if (trim) { trimmed.printSequence(out3);  }
1449                                                 
1450                                                 delete left; delete right;
1451                                                 
1452                                         }else { //already chimeric
1453                                                 //print results
1454                                                 Sequence trimmed = chimera->print(out, out2);
1455                                                 if (trim) { trimmed.printSequence(out3);  }
1456                                         }
1457                                         
1458                                         
1459                                 }
1460                                 count++;
1461                         }
1462                         
1463                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1464                                 unsigned long long pos = inFASTA.tellg();
1465                                 if ((pos == -1) || (pos >= filePos.end)) { break; }
1466                         #else
1467                                 if (inFASTA.eof()) { break; }
1468                         #endif
1469                         
1470                         delete candidateSeq;
1471                         //report progress
1472                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1473                 }
1474                 //report progress
1475                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1476                 
1477                 int numNoParents = chimera->getNumNoParents();
1478                 if (numNoParents == count) { m->mothurOut("[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors."); m->mothurOutEndLine(); } 
1479                 
1480                 out.close();
1481                 out2.close();
1482                 if (trim) { out3.close(); }
1483                 inFASTA.close();
1484                 delete chimera;
1485                                 
1486                 return count;
1487                 
1488                 
1489         }
1490         catch(exception& e) {
1491                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1492                 exit(1);
1493         }
1494 }
1495 //**********************************************************************************************************************
1496 #ifdef USE_MPI
1497 int ChimeraSlayerCommand::driverMPI(int start, int num, MPI_File& inMPI, MPI_File& outMPI, MPI_File& outAccMPI, MPI_File& outFastaMPI, vector<unsigned long long>& MPIPos, string filename, map<string, int>& priority, bool byGroup){
1498         try {
1499                 MPI_Status status; 
1500                 int pid;
1501                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1502                 
1503                 Chimera* chimera;
1504                 if (templatefile != "self") { //you want to run slayer with a reference template
1505                         chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());       
1506                 }else {
1507                         chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand(), byGroup);    
1508                 }
1509                 
1510                 if (m->control_pressed) { delete chimera; return 0; }
1511                 
1512                 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1513                 templateSeqsLength = chimera->getLength();
1514                 
1515                 for(int i=0;i<num;i++){
1516                         
1517                         if (m->control_pressed) {       delete chimera; return 1;       }
1518                         
1519                         //read next sequence
1520                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1521
1522                         char* buf4 = new char[length];
1523                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1524         
1525                         string tempBuf = buf4;
1526                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1527                         istringstream iss (tempBuf,istringstream::in);
1528
1529                         delete buf4;
1530
1531                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
1532                         string candidateAligned = candidateSeq->getAligned();
1533                 
1534                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1535                                 
1536                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
1537                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1538                                 }else{
1539                 
1540                                         //find chimeras
1541                                         chimera->getChimeras(candidateSeq);
1542                         
1543                                         if (m->control_pressed) {       delete chimera; delete candidateSeq; return 1;  }
1544                                         
1545                                         //if you are not chimeric, then check each half
1546                                         data_results wholeResults = chimera->getResults();
1547                                         
1548                                         //determine if we need to split
1549                                         bool isChimeric = false;
1550                                         
1551                                         if (wholeResults.flag == "yes") {
1552                                                 string chimeraFlag = "no";
1553                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1554                                                    ||
1555                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1556                                                 
1557                                                 
1558                                                 if (chimeraFlag == "yes") {     
1559                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1560                                                 }
1561                                         }
1562                                         
1563                                         if ((!isChimeric) && trimera) {                                                 
1564                                                 //split sequence in half by bases
1565                                                 string leftQuery, rightQuery;
1566                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1567                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
1568                                                 
1569                                                 //run chimeraSlayer on each piece
1570                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1571                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1572                                                 
1573                                                 //find chimeras
1574                                                 chimera->getChimeras(left);
1575                                                 data_results leftResults = chimera->getResults();
1576                                                 
1577                                                 chimera->getChimeras(right);
1578                                                 data_results rightResults = chimera->getResults();
1579                                                 
1580                                                 //if either piece is chimeric then report
1581                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults);
1582                                                 if (trim) {  
1583                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1584                                                         
1585                                                         //write to accnos file
1586                                                         int length = outputString.length();
1587                                                         char* buf2 = new char[length];
1588                                                         memcpy(buf2, outputString.c_str(), length);
1589                                                         
1590                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1591                                                         delete buf2;
1592                                                 }
1593                                                 
1594                                                 delete left; delete right;
1595                                                 
1596                                         }else { 
1597                                                 //print results
1598                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1599                                                 
1600                                                 if (trim) {  
1601                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1602                                                         
1603                                                         //write to accnos file
1604                                                         int length = outputString.length();
1605                                                         char* buf2 = new char[length];
1606                                                         memcpy(buf2, outputString.c_str(), length);
1607                                                         
1608                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1609                                                         delete buf2;
1610                                                 }
1611                                         }
1612                                         
1613                                 }
1614                         }
1615                         delete candidateSeq;
1616                         
1617                         //report progress
1618                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
1619                 }
1620                 //report progress
1621                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
1622                 
1623                 int numNoParents = chimera->getNumNoParents();
1624                 if (numNoParents == num) { cout << "[WARNING]: megablast returned 0 potential parents for all your sequences. This could be due to formatdb.exe not being setup properly, please check formatdb.log for errors." << endl; }
1625                 
1626                 delete chimera;         
1627                 return 0;
1628         }
1629         catch(exception& e) {
1630                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1631                 exit(1);
1632         }
1633 }
1634 #endif
1635
1636 /**************************************************************************************************/
1637
1638 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
1639         try {
1640                 int process = 0;
1641                 int num = 0;
1642                 processIDS.clear();
1643                 
1644 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1645                 //loop through and create all the processes you want
1646                 while (process != processors) {
1647                         int pid = fork();
1648                         
1649                         if (pid > 0) {
1650                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1651                                 process++;
1652                         }else if (pid == 0){
1653                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
1654                                 
1655                                 //pass numSeqs to parent
1656                                 ofstream out;
1657                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
1658                                 m->openOutputFile(tempFile, out);
1659                                 out << num << endl;
1660                                 out.close();
1661                                 exit(0);
1662                         }else { 
1663                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1664                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1665                                 exit(0);
1666                         }
1667                 }
1668                 
1669                 //force parent to wait until all the processes are done
1670                 for (int i=0;i<processors;i++) { 
1671                         int temp = processIDS[i];
1672                         wait(&temp);
1673                 }
1674                 
1675                 for (int i = 0; i < processIDS.size(); i++) {
1676                         ifstream in;
1677                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
1678                         m->openInputFile(tempFile, in);
1679                         if (!in.eof()) { int tempNum = 0;  in >> tempNum; num += tempNum; }
1680                         in.close(); m->mothurRemove(tempFile);
1681                 }
1682 #else
1683                 
1684                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1685                 //Windows version shared memory, so be careful when passing variables through the slayerData struct. 
1686                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
1687                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1688                 
1689                 vector<slayerData*> pDataArray; 
1690                 DWORD   dwThreadIdArray[processors];
1691                 HANDLE  hThreadArray[processors]; 
1692                 
1693                 //Create processor worker threads.
1694                 for( int i=0; i<processors; i++ ){
1695                         string extension = toString(i) + ".temp";
1696                         slayerData* tempslayer = new slayerData((outputFileName + extension), (fasta + extension), (accnos + extension), filename, templatefile, search, blastlocation, trimera, trim, realign, m, lines[i].start, lines[i].end, ksize, match, mismatch, window, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, divR, priority, i);
1697                         pDataArray.push_back(tempslayer);
1698                         processIDS.push_back(i);
1699                         
1700                         //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1701                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1702                         hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
1703                 }
1704                                 
1705                 //Wait until all threads have terminated.
1706                 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
1707                 
1708                 //Close all thread handles and free memory allocations.
1709                 for(int i=0; i < pDataArray.size(); i++){
1710                         num += pDataArray[i]->count;
1711                         CloseHandle(hThreadArray[i]);
1712                         delete pDataArray[i];
1713                 }
1714 #endif  
1715                 
1716                 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
1717                 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
1718                 if (trim) {  rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
1719                 
1720                 //append output files
1721                 for(int i=1;i<processIDS.size();i++){
1722                         m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
1723                         m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
1724                         
1725                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1726                         m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1727                         
1728                         if (trim) {
1729                                 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1730                                 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1731                         }
1732                 }
1733                 
1734                 
1735                 return num;
1736         }
1737         catch(exception& e) {
1738                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
1739                 exit(1);
1740         }
1741 }
1742
1743 /**************************************************************************************************/
1744
1745 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
1746         try {
1747                 
1748                 string queryUnAligned = querySeq.getUnaligned();
1749                 int numBases = int(queryUnAligned.length() * 0.5);
1750                 
1751                 string queryAligned = querySeq.getAligned();
1752                 leftQuery = querySeq.getAligned();
1753                 rightQuery = querySeq.getAligned();
1754                 
1755                 int baseCount = 0;
1756                 int leftSpot = 0;
1757                 for (int i = 0; i < queryAligned.length(); i++) {
1758                         //if you are a base
1759                         if (isalpha(queryAligned[i])) {         
1760                                 baseCount++; 
1761                         }
1762                         
1763                         //if you have half
1764                         if (baseCount >= numBases) {  leftSpot = i; break; } //first half
1765                 }
1766                 
1767                 //blank out right side
1768                 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
1769                 
1770                 //blank out left side
1771                 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
1772                 
1773                 return 0;
1774                 
1775         }
1776         catch(exception& e) {
1777                 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
1778                 exit(1);
1779         }
1780 }
1781 /**************************************************************************************************/
1782 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
1783         try {
1784                 map<string, int> nameAbund;
1785                 
1786                 //read through fastafile and store info
1787                 map<string, string> seqs;
1788                 ifstream in;
1789                 m->openInputFile(fastaFile, in);
1790                 
1791                 while (!in.eof()) {
1792                         
1793                         if (m->control_pressed) { in.close(); return nameAbund; }
1794                         
1795                         Sequence seq(in); m->gobble(in);
1796                         seqs[seq.getName()] = seq.getAligned();
1797                 }
1798                 
1799                 in.close();
1800                 
1801                 //read namefile
1802                 vector<seqPriorityNode> nameMapCount;
1803                 int error = m->readNames(nameFile, nameMapCount, seqs);
1804                 
1805                 if (m->control_pressed) { return nameAbund; }
1806                 
1807                 if (error == 1) { m->control_pressed = true; return nameAbund; }
1808                 if (seqs.size() != nameMapCount.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your namefile, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return nameAbund; }
1809
1810                 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
1811                 
1812                 string newFasta = fastaFile + ".temp";
1813                 ofstream out;
1814                 m->openOutputFile(newFasta, out);
1815                 
1816                 //print new file in order of
1817                 for (int i = 0; i < nameMapCount.size(); i++) {
1818                         out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
1819                         nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
1820                 }
1821                 out.close();
1822                 
1823                 rename(newFasta.c_str(), fastaFile.c_str());
1824                                 
1825                 return nameAbund;
1826                 
1827         }
1828         catch(exception& e) {
1829                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1830                 exit(1);
1831         }
1832 }
1833 /**************************************************************************************************/
1834 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
1835         try {
1836                 map<string, int> nameAbund;
1837                 vector<seqPriorityNode> nameVector;
1838                 
1839                 //read through fastafile and store info
1840                 map<string, string> seqs;
1841                                 
1842                 for (int i = 0; i < thisseqs.size(); i++) {
1843                         
1844                         if (m->control_pressed) { return nameAbund; }
1845                         
1846                         map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
1847                         
1848                         if (itNameMap == nameMap.end()){
1849                                 m->control_pressed = true;
1850                                 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
1851                         }else {
1852                                 int num = m->getNumNames(itNameMap->second);
1853                                 
1854                                 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
1855                                 nameVector.push_back(temp);
1856                         }
1857                 }
1858         
1859                 //sort by num represented
1860                 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
1861         
1862                 if (m->control_pressed) { return nameAbund; }
1863                 
1864                 if (thisseqs.size() != nameVector.size()) { m->mothurOut( "The number of sequences in your fastafile does not match the number of sequences in your namefile, aborting."); m->mothurOutEndLine(); m->control_pressed = true; return nameAbund; }
1865                                 
1866                 ofstream out;
1867                 m->openOutputFile(newFile, out);
1868                 
1869                 //print new file in order of
1870                 for (int i = 0; i < nameVector.size(); i++) {
1871                         out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
1872                         nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
1873                 }
1874                 out.close();
1875                 
1876                 return nameAbund;
1877                 
1878         }
1879         catch(exception& e) {
1880                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
1881                 exit(1);
1882         }
1883 }
1884 /**************************************************************************************************/
1885