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