]> git.donarmstrong.com Git - mothur.git/blob - chimeraslayercommand.cpp
fceef2180163f60e3c33cfecb7e861839c4bd1c7
[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         itTypes = outputTypes.find("count");
841                 if (itTypes != outputTypes.end()) {
842                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
843                 }
844         
845                 m->mothurOutEndLine();
846                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
847                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
848                 m->mothurOutEndLine();
849
850                 return 0;
851                 
852         }
853         catch(exception& e) {
854                 m->errorOut(e, "ChimeraSlayerCommand", "execute");
855                 exit(1);
856         }
857 }
858 //**********************************************************************************************************************
859 int ChimeraSlayerCommand::MPIExecuteGroups(string outputFileName, string accnosFileName, string trimFastaFileName, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist, string countfile){
860         try {
861 #ifdef USE_MPI  
862                 int pid; 
863                 int tag = 2001;
864                 
865                 MPI_Status status; 
866                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
867                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
868         
869                 //put filenames in a vector, then pass each process a starting and ending point in the vector
870                 //all processes already have the fileToPriority and fileGroup, they just need to know which files to process
871                 map<string, map<string, int> >::iterator itFile;
872                 vector<string> filenames;
873                 for(itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) { filenames.push_back(itFile->first); }
874                 
875                 int numGroupsPerProcessor = filenames.size() / processors;
876                 int startIndex =  pid * numGroupsPerProcessor;
877                 int endIndex = (pid+1) * numGroupsPerProcessor;
878                 if(pid == (processors - 1)){    endIndex = filenames.size();    }
879                 
880                 vector<unsigned long long> MPIPos;
881                 
882                 MPI_File outMPI;
883                 MPI_File outMPIAccnos;
884                 MPI_File outMPIFasta;
885         MPI_File outMPICount;
886                 
887                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
888                 int inMode=MPI_MODE_RDONLY; 
889                 
890                 char outFilename[1024];
891                 strcpy(outFilename, outputFileName.c_str());
892                 
893                 char outAccnosFilename[1024];
894                 strcpy(outAccnosFilename, accnosFileName.c_str());
895                 
896                 char outFastaFilename[1024];
897                 strcpy(outFastaFilename, trimFastaFileName.c_str());
898         
899         char outCountFilename[1024];
900                 strcpy(outCountFilename, countlist.c_str());
901                 
902                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
903                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
904                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
905         if (hasCount && dups) {  MPI_File_open(MPI_COMM_WORLD, outCountFilename, outMode, MPI_INFO_NULL, &outMPICount); }
906                 
907                 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;  }
908                 
909                 //print headers
910                 if (pid == 0) { //you are the root process 
911                         m->mothurOutEndLine();
912                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
913                         m->mothurOutEndLine();
914                         
915                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
916                         
917                         //print header
918                         int length = outTemp.length();
919                         char* buf2 = new char[length];
920                         memcpy(buf2, outTemp.c_str(), length);
921                         
922                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
923                         delete buf2;
924                 }
925                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
926                 
927                 for (int i = startIndex; i < endIndex; i++) {
928                         
929                         int start = time(NULL);
930                         int num = 0;
931                         string thisFastaName = filenames[i];
932                         map<string, int> thisPriority = fileToPriority[thisFastaName];
933                         
934                         char inFileName[1024];
935                         strcpy(inFileName, thisFastaName.c_str());
936                         MPI_File inMPI;
937                         MPI_File_open(MPI_COMM_SELF, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
938             
939                         MPIPos = m->setFilePosFasta(thisFastaName, num); //fills MPIPos, returns numSeqs
940                         
941                         cout << endl << "Checking sequences from group: " << fileGroup[thisFastaName] << "." << endl; 
942                         
943             set<string> cnames;
944                         driverMPI(0, num, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, thisFastaName, thisPriority, true);
945                         numSeqs += num;
946                         
947                         MPI_File_close(&inMPI);
948                         m->mothurRemove(thisFastaName);
949             
950             if (dups) {
951                 if (cnames.size() != 0) {
952                     if (hasCount) {
953                         for (set<string>::iterator it = cnames.begin(); it != cnames.end(); it++) {
954                             string outputString = (*it) + "\t" + fileGroup[thisFastaName] + "\n";
955                             int length = outputString.length();
956                             char* buf2 = new char[length];
957                             memcpy(buf2, outputString.c_str(), length);
958                             MPI_File_write_shared(outMPICount, buf2, length, MPI_CHAR, &status);
959                             delete buf2;
960                         }
961                     }else {
962                         map<string, map<string, string> >::iterator itGroupNameMap = group2NameMap.find(fileGroup[thisFastaName]);
963                         if (itGroupNameMap != group2NameMap.end()) {
964                             map<string, string> thisnamemap = itGroupNameMap->second;
965                             map<string, string>::iterator itN;
966                             for (set<string>::iterator it = cnames.begin(); it != cnames.end(); it++) {
967                                 itN = thisnamemap.find(*it);
968                                 if (itN != thisnamemap.end()) {
969                                     vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
970                                     for (int j = 0; j < tempNames.size(); j++) { //write to accnos file
971                                         string outputString = tempNames[j] + "\n";
972                                         int length = outputString.length();
973                                         char* buf2 = new char[length];
974                                         memcpy(buf2, outputString.c_str(), length);
975                                         
976                                         MPI_File_write_shared(outMPIAccnos, buf2, length, MPI_CHAR, &status);
977                                         delete buf2;
978                                     }
979                                     
980                                 }else { m->mothurOut("[ERROR]: parsing cannot find " + *it + ".\n"); m->control_pressed = true; }
981                             }
982                         }else { m->mothurOut("[ERROR]: parsing cannot find " + fileGroup[thisFastaName] + ".\n"); m->control_pressed = true; }
983                     }
984                     
985                 }
986             }
987                                                 
988                         cout << endl << "It took " << toString(time(NULL) - start) << " secs to check " + toString(num) + " sequences from group " << fileGroup[thisFastaName] << "." << endl;
989                 }
990                 
991                 if (pid == 0) {
992                         for(int i = 1; i < processors; i++) { 
993                                 int temp = 0;
994                                 MPI_Recv(&temp, 1, MPI_INT, i, 2001, MPI_COMM_WORLD, &status);
995                                 numSeqs += temp;
996                         }
997                 }else{ MPI_Send(&numSeqs, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD); }
998                 
999                 MPI_File_close(&outMPI);
1000                 MPI_File_close(&outMPIAccnos); 
1001                 if (trim) { MPI_File_close(&outMPIFasta); }
1002         if (hasCount && dups) { MPI_File_close(&outMPICount); }
1003                 
1004                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait
1005 #endif
1006                 return 0;
1007                 
1008         }catch(exception& e) {
1009                 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecuteGroups");
1010                 exit(1);
1011         }
1012 }               
1013 //**********************************************************************************************************************
1014 int ChimeraSlayerCommand::MPIExecute(string inputFile, string outputFileName, string accnosFileName, string trimFastaFileName, map<string, int>& priority){
1015         try {
1016                 
1017 #ifdef USE_MPI  
1018                 int pid, numSeqsPerProcessor; 
1019                 int tag = 2001;
1020                 vector<unsigned long long> MPIPos;
1021                 
1022                 MPI_Status status; 
1023                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1024                 MPI_Comm_size(MPI_COMM_WORLD, &processors); 
1025                 
1026                 MPI_File inMPI;
1027                 MPI_File outMPI;
1028                 MPI_File outMPIAccnos;
1029                 MPI_File outMPIFasta;
1030                 
1031                 int outMode=MPI_MODE_CREATE|MPI_MODE_WRONLY; 
1032                 int inMode=MPI_MODE_RDONLY; 
1033                 
1034                 char outFilename[1024];
1035                 strcpy(outFilename, outputFileName.c_str());
1036                 
1037                 char outAccnosFilename[1024];
1038                 strcpy(outAccnosFilename, accnosFileName.c_str());
1039                 
1040                 char outFastaFilename[1024];
1041                 strcpy(outFastaFilename, trimFastaFileName.c_str());
1042                 
1043                 char inFileName[1024];
1044                 strcpy(inFileName, inputFile.c_str());
1045                 
1046                 MPI_File_open(MPI_COMM_WORLD, inFileName, inMode, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
1047                 MPI_File_open(MPI_COMM_WORLD, outFilename, outMode, MPI_INFO_NULL, &outMPI);
1048                 MPI_File_open(MPI_COMM_WORLD, outAccnosFilename, outMode, MPI_INFO_NULL, &outMPIAccnos);
1049                 if (trim) { MPI_File_open(MPI_COMM_WORLD, outFastaFilename, outMode, MPI_INFO_NULL, &outMPIFasta); }
1050                 
1051                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) {  MPI_File_close(&outMPIFasta);  } MPI_File_close(&outMPIAccnos);  return 0;  }
1052                 
1053                 if (pid == 0) { //you are the root process 
1054                         m->mothurOutEndLine();
1055                         m->mothurOut("Only reporting sequence supported by " + toString(minBS) + "% of bootstrapped results.");
1056                         m->mothurOutEndLine();
1057                         
1058                         string outTemp = "Name\tLeftParent\tRightParent\tDivQLAQRB\tPerIDQLAQRB\tBootStrapA\tDivQLBQRA\tPerIDQLBQRA\tBootStrapB\tFlag\tLeftWindow\tRightWindow\n";
1059                         
1060                         //print header
1061                         int length = outTemp.length();
1062                         char* buf2 = new char[length];
1063                         memcpy(buf2, outTemp.c_str(), length);
1064                         
1065                         MPI_File_write_shared(outMPI, buf2, length, MPI_CHAR, &status);
1066                         delete buf2;
1067                         
1068                         MPIPos = m->setFilePosFasta(inputFile, numSeqs); //fills MPIPos, returns numSeqs
1069                         
1070                         if (templatefile != "self") { //if template=self we can only use 1 processor
1071                                 //send file positions to all processes
1072                                 for(int i = 1; i < processors; i++) { 
1073                                         MPI_Send(&numSeqs, 1, MPI_INT, i, tag, MPI_COMM_WORLD);
1074                                         MPI_Send(&MPIPos[0], (numSeqs+1), MPI_LONG, i, tag, MPI_COMM_WORLD);
1075                                 }
1076                         }
1077                         //figure out how many sequences you have to align
1078                         numSeqsPerProcessor = numSeqs / processors;
1079                         int startIndex =  pid * numSeqsPerProcessor;
1080                         if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
1081                         
1082                         if (templatefile == "self") { //if template=self we can only use 1 processor
1083                                 startIndex = 0;
1084                                 numSeqsPerProcessor = numSeqs;
1085                         }
1086                         
1087                         //do your part
1088             set<string> cnames;
1089                         driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, inputFile, priority, false);
1090                                                 
1091                         if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);   return 0;  }
1092                         
1093                 }else{ //you are a child process
1094                         if (templatefile != "self") { //if template=self we can only use 1 processor
1095                                 MPI_Recv(&numSeqs, 1, MPI_INT, 0, tag, MPI_COMM_WORLD, &status);
1096                                 MPIPos.resize(numSeqs+1);
1097                                 MPI_Recv(&MPIPos[0], (numSeqs+1), MPI_LONG, 0, tag, MPI_COMM_WORLD, &status);
1098                                 
1099                                 //figure out how many sequences you have to align
1100                                 numSeqsPerProcessor = numSeqs / processors;
1101                                 int startIndex =  pid * numSeqsPerProcessor;
1102                                 if(pid == (processors - 1)){    numSeqsPerProcessor = numSeqs - pid * numSeqsPerProcessor;      }
1103                                 
1104                                 //do your part
1105                 set<string> cnames;
1106                                 driverMPI(startIndex, numSeqsPerProcessor, inMPI, outMPI, outMPIAccnos, outMPIFasta, cnames, MPIPos, inputFile, priority, false);
1107                                 
1108                                 if (m->control_pressed) {  MPI_File_close(&inMPI);  MPI_File_close(&outMPI); if (trim) { MPI_File_close(&outMPIFasta); }  MPI_File_close(&outMPIAccnos);  return 0;  }
1109                                 
1110                         }
1111                 }
1112                 
1113                 //close files 
1114                 MPI_File_close(&inMPI);
1115                 MPI_File_close(&outMPI);
1116                 MPI_File_close(&outMPIAccnos); 
1117                 if (trim) { MPI_File_close(&outMPIFasta); }
1118                 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
1119                 
1120                 
1121 #endif          
1122                 return numSeqs;
1123         }
1124         catch(exception& e) {
1125                 m->errorOut(e, "ChimeraSlayerCommand", "MPIExecute");
1126                 exit(1);
1127         }
1128 }
1129 //**********************************************************************************************************************
1130 int ChimeraSlayerCommand::deconvoluteResults(map<string, string>& uniqueNames, string outputFileName, string accnosFileName, string trimFileName){
1131         try {
1132                 map<string, string>::iterator itUnique;
1133                 int total = 0;
1134         
1135         if (trimera) { //add in more potential uniqueNames
1136             map<string, string> newUniqueNames = uniqueNames;
1137             for (map<string, string>::iterator it = uniqueNames.begin(); it != uniqueNames.end(); it++) {
1138                 newUniqueNames[(it->first)+"_LEFT"] = (it->first)+"_LEFT";
1139                 newUniqueNames[(it->first)+"_RIGHT"] = (it->first)+"_RIGHT";
1140             }
1141             uniqueNames = newUniqueNames;
1142             newUniqueNames.clear();
1143         }
1144                 
1145                 //edit accnos file
1146                 ifstream in2; 
1147                 m->openInputFile(accnosFileName, in2, "no error");
1148                 
1149                 ofstream out2;
1150                 m->openOutputFile(accnosFileName+".temp", out2);
1151                 
1152                 string name; name = "";
1153                 set<string> chimerasInFile;
1154                 set<string>::iterator itChimeras;
1155                 
1156                 while (!in2.eof()) {
1157                         if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
1158                         
1159                         in2 >> name; m->gobble(in2);
1160                         
1161                         //find unique name
1162                         itUnique = uniqueNames.find(name);
1163                         
1164                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1165                         else {
1166                                 itChimeras = chimerasInFile.find((itUnique->second));
1167                                 
1168                                 if (itChimeras == chimerasInFile.end()) {
1169                                         out2 << itUnique->second << endl;
1170                                         chimerasInFile.insert((itUnique->second));
1171                                         total++;
1172                                 }
1173                         }
1174                 }
1175                 in2.close();
1176                 out2.close();
1177                 
1178                 m->mothurRemove(accnosFileName);
1179                 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
1180                 
1181                 
1182                 //edit chimera file
1183                 ifstream in; 
1184                 m->openInputFile(outputFileName, in);
1185                 
1186                 ofstream out;
1187                 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1188
1189                 string rest, parent1, parent2, line;
1190                 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
1191                 set<string>::iterator itNames;
1192                 
1193                 //assumptions - in file each read will always look like...
1194                 /*
1195                  F11Fcsw_92754  no
1196                  F11Fcsw_63104  F11Fcsw_33372   F11Fcsw_37007   0.89441 80.4469 0.2     1.03727 93.2961 52.2    no      0-241   243-369 
1197                  */
1198                 
1199                 //get header line
1200                 if (!in.eof()) {
1201                         line = m->getline(in); m->gobble(in);
1202                         out << line << endl;
1203                 }
1204                 
1205                 //for the chimera file, we want to make sure if any group finds a sequence to be chimeric then all groups do, 
1206                 //so if this is a report that did not find it to be chimeric, but it appears in the accnos file, 
1207                 //then ignore this report and continue until we find the report that found it to be chimeric
1208                 
1209                 while (!in.eof()) {
1210                         
1211                         if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1212                         
1213                         in >> name;             m->gobble(in);
1214                         in >> parent1;  m->gobble(in);
1215                         
1216                         if (name == "Name") { //name = "Name" because we append the header line each time we add results from the groups
1217                                 line = m->getline(in); m->gobble(in);
1218                         }else {
1219                                 if (parent1 == "no") {
1220                                         //find unique name
1221                                         itUnique = uniqueNames.find(name);
1222                                         
1223                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1224                                         else {
1225                                                 //is this sequence really not chimeric??
1226                                                 itChimeras = chimerasInFile.find(itUnique->second);
1227                                                 
1228                                                 if (itChimeras == chimerasInFile.end()) {
1229                                                         //is this sequence not already in the file
1230                                                         itNames = namesInFile.find((itUnique->second));
1231                                                         
1232                                                         if (itNames == namesInFile.end()) { out << itUnique->second << '\t' << "no" << endl; namesInFile.insert(itUnique->second); }
1233                                                 }
1234                                         }
1235                                 }else { //read the rest of the line
1236                                         double DivQLAQRB,PerIDQLAQRB,BootStrapA,DivQLBQRA,PerIDQLBQRA,BootStrapB;
1237                                         string flag, range1, range2;
1238                                         bool print = false;
1239                                         in >> parent2 >> DivQLAQRB >> PerIDQLAQRB >> BootStrapA >> DivQLBQRA >> PerIDQLBQRA >> BootStrapB >> flag >> range1 >> range2;  m->gobble(in);
1240                                         
1241                                         //find unique name
1242                                         itUnique = uniqueNames.find(name);
1243                                         
1244                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1245                                         else {
1246                                                 name = itUnique->second;
1247                                                 //is this name already in the file
1248                                                 itNames = namesInFile.find((name));
1249                                                 
1250                                                 if (itNames == namesInFile.end()) { //no not in file
1251                                                         if (flag == "no") { //are you really a no??
1252                                                                 //is this sequence really not chimeric??
1253                                                                 itChimeras = chimerasInFile.find(name);
1254                                                                 
1255                                                                 //then you really are a no so print, otherwise skip
1256                                                                 if (itChimeras == chimerasInFile.end()) { print = true; }
1257                                                                 
1258                                                         }else{ print = true; }
1259                                                 }
1260                                         }
1261                                         
1262                                         if (print) {
1263                                                 out << name << '\t';
1264                                                 
1265                                                 namesInFile.insert(name);
1266
1267                                                 //output parent1's name
1268                                                 itUnique = uniqueNames.find(parent1);
1269                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1270                                                 else { out << itUnique->second << '\t'; }
1271                                                 
1272                                                 //output parent2's name
1273                                                 itUnique = uniqueNames.find(parent2);
1274                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parentA "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1275                                                 else { out << itUnique->second << '\t'; }
1276                                                 
1277                                                 out << DivQLAQRB << '\t' << PerIDQLAQRB << '\t' << BootStrapA << '\t' << DivQLBQRA << '\t' << PerIDQLBQRA << '\t' << BootStrapB << '\t' << flag << '\t' << range1 << '\t' << range2 << endl;
1278                                         }
1279                                 }                               
1280                         }
1281                 }
1282                 in.close();
1283                 out.close();
1284                 
1285                 m->mothurRemove(outputFileName);
1286                 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1287                 
1288                 //edit fasta file
1289                 if (trim) {
1290                         ifstream in3; 
1291                         m->openInputFile(trimFileName, in3);
1292                         
1293                         ofstream out3;
1294                         m->openOutputFile(trimFileName+".temp", out3);
1295                         
1296                         namesInFile.clear();
1297                         
1298                         while (!in3.eof()) {
1299                                 if (m->control_pressed) { in3.close(); out3.close(); m->mothurRemove(outputFileName); m->mothurRemove(accnosFileName); m->mothurRemove((trimFileName+".temp")); return 0; }
1300                                 
1301                                 Sequence seq(in3); m->gobble(in3);
1302                                 
1303                                 if (seq.getName() != "") {
1304                                         //find unique name
1305                                         itUnique = uniqueNames.find(seq.getName());
1306                                         
1307                                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ seq.getName() + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1308                                         else {
1309                                                 itNames = namesInFile.find((itUnique->second));
1310                                                 
1311                                                 if (itNames == namesInFile.end()) {
1312                                                         seq.printSequence(out3);
1313                                                 }
1314                                         }
1315                                 }
1316                         }
1317                         in3.close();
1318                         out3.close();
1319                         
1320                         m->mothurRemove(trimFileName);
1321                         rename((trimFileName+".temp").c_str(), trimFileName.c_str());
1322                 }
1323                 
1324                 return total;
1325         }
1326         catch(exception& e) {
1327                 m->errorOut(e, "ChimeraSlayerCommand", "deconvoluteResults");
1328                 exit(1);
1329         }
1330 }
1331 //**********************************************************************************************************************
1332 int ChimeraSlayerCommand::setUpForSelfReference(SequenceParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1333         try {
1334                 fileGroup.clear();
1335                 fileToPriority.clear();
1336                 
1337                 string nameFile = "";
1338                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1339                         nameFile = nameFileNames[s];
1340                 }else {  nameFile = getNamesFile(fastaFileNames[s]); }
1341                 
1342                 //you provided a groupfile
1343                 string groupFile = "";
1344                 if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
1345                 
1346                 if (groupFile == "") { 
1347                         if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1348                                                 
1349                         //sort fastafile by abundance, returns new sorted fastafile name
1350                         m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
1351                         priority = sortFastaFile(fastaFileNames[s], nameFile);
1352                         m->mothurOut("Done."); m->mothurOutEndLine();
1353                         
1354                         fileToPriority[fastaFileNames[s]] = priority;
1355                         fileGroup[fastaFileNames[s]] = "noGroup";
1356                 }else {
1357                         //Parse sequences by group
1358                         parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
1359                         vector<string> groups = parser->getNamesOfGroups();
1360                         
1361                         for (int i = 0; i < groups.size(); i++) {
1362                                 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1363                                 map<string, string> thisGroupsMap = parser->getNameMap(groups[i]);
1364                 group2NameMap[groups[i]] = thisGroupsMap;
1365                                 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1366                                 priority = sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile); 
1367                                 fileToPriority[newFastaFile] = priority;
1368                                 fileGroup[newFastaFile] = groups[i];
1369                         }
1370                 }
1371                 
1372                 
1373                 return 0;
1374         }
1375         catch(exception& e) {
1376                 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1377                 exit(1);
1378         }
1379 }
1380 //**********************************************************************************************************************
1381 int ChimeraSlayerCommand::setUpForSelfReference(SequenceCountParser*& parser, map<string, string>& fileGroup, map<string, map<string, int> >& fileToPriority, int s){
1382         try {
1383                 fileGroup.clear();
1384                 fileToPriority.clear();
1385                 
1386                 string nameFile = "";
1387                 if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
1388                         nameFile = nameFileNames[s];
1389                 }else {  m->control_pressed = true; return 0; }
1390          
1391                 CountTable ct;
1392                 if (!ct.testGroups(nameFile)) {  
1393                         if (processors != 1) { m->mothurOut("When using template=self, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
1394             
1395                         //sort fastafile by abundance, returns new sorted fastafile name
1396                         m->mothurOut("Sorting fastafile according to abundance..."); cout.flush(); 
1397                         priority = sortFastaFile(fastaFileNames[s], nameFile);
1398                         m->mothurOut("Done."); m->mothurOutEndLine();
1399                         
1400                         fileToPriority[fastaFileNames[s]] = priority;
1401                         fileGroup[fastaFileNames[s]] = "noGroup";
1402                 }else {
1403                         //Parse sequences by group
1404                         parser = new SequenceCountParser(nameFile, fastaFileNames[s]);
1405                         vector<string> groups = parser->getNamesOfGroups();
1406                         
1407                         for (int i = 0; i < groups.size(); i++) {
1408                                 vector<Sequence> thisGroupsSeqs = parser->getSeqs(groups[i]);
1409                                 map<string, int> thisGroupsMap = parser->getCountTable(groups[i]);
1410                                 string newFastaFile = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s])) + groups[i] + "-sortedTemp.fasta";
1411                                 sortFastaFile(thisGroupsSeqs, thisGroupsMap, newFastaFile); 
1412                                 fileToPriority[newFastaFile] = thisGroupsMap;
1413                                 fileGroup[newFastaFile] = groups[i];
1414                         }
1415                 }
1416                 
1417                 
1418                 return 0;
1419         }
1420         catch(exception& e) {
1421                 m->errorOut(e, "ChimeraSlayerCommand", "setUpForSelfReference");
1422                 exit(1);
1423         }
1424 }
1425 //**********************************************************************************************************************
1426 string ChimeraSlayerCommand::getNamesFile(string& inputFile){
1427         try {
1428                 string nameFile = "";
1429                 
1430                 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
1431                 
1432                 //use unique.seqs to create new name and fastafile
1433                 string inputString = "fasta=" + inputFile;
1434                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1435                 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
1436                 m->mothurCalling = true;
1437         
1438                 Command* uniqueCommand = new DeconvoluteCommand(inputString);
1439                 uniqueCommand->execute();
1440                 
1441                 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
1442                 
1443                 delete uniqueCommand;
1444                 m->mothurCalling = false;
1445                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
1446                 
1447                 nameFile = filenames["name"][0];
1448                 inputFile = filenames["fasta"][0];
1449                 
1450                 return nameFile;
1451         }
1452         catch(exception& e) {
1453                 m->errorOut(e, "ChimeraSlayerCommand", "getNamesFile");
1454                 exit(1);
1455         }
1456 }
1457 //**********************************************************************************************************************
1458
1459 int ChimeraSlayerCommand::driverGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist){
1460         try {
1461                 int totalSeqs = 0;
1462         ofstream outCountList;
1463
1464         if (hasCount && dups) { m->openOutputFile(countlist, outCountList); }
1465                 
1466                 for (map<string, map<string, int> >::iterator itFile = fileToPriority.begin(); itFile != fileToPriority.end(); itFile++) {
1467                         
1468                         if (m->control_pressed) {  return 0;  }
1469                         
1470                         int start = time(NULL);
1471                         string thisFastaName = itFile->first;
1472                         map<string, int> thisPriority = itFile->second;
1473                         string thisoutputFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.chimera";
1474                         string thisaccnosFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.accnos";
1475                         string thistrimFastaFileName = outputDir + m->getRootName(m->getSimpleName(thisFastaName)) + fileGroup[thisFastaName] + "slayer.fasta";
1476                         
1477                         m->mothurOutEndLine(); m->mothurOut("Checking sequences from group: " + fileGroup[thisFastaName] + "."); m->mothurOutEndLine(); 
1478                         
1479                         lines.clear();
1480 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1481                         int proc = 1;
1482                         vector<unsigned long long> positions = m->divideFile(thisFastaName, proc);
1483                         lines.push_back(linePair(positions[0], positions[1]));  
1484 #else
1485                         lines.push_back(linePair(0, 1000)); 
1486 #endif                  
1487                         int numSeqs = driver(lines[0], thisoutputFileName, thisFastaName, thisaccnosFileName, thistrimFastaFileName, thisPriority);
1488                         
1489             //if we provided a count file with group info and set dereplicate=t, then we want to create a *.pick.count_table
1490             //This table will zero out group counts for seqs determined to be chimeric by that group.
1491             if (dups) {
1492                 if (!m->isBlank(thisaccnosFileName)) {
1493                     ifstream in;
1494                     m->openInputFile(thisaccnosFileName, in);
1495                     string name;
1496                     if (hasCount) {
1497                         while (!in.eof()) {
1498                             in >> name; m->gobble(in);
1499                             outCountList << name << '\t' << fileGroup[thisFastaName] << endl;
1500                         }
1501                         in.close();
1502                     }else {
1503                         map<string, map<string, string> >::iterator itGroupNameMap = group2NameMap.find(fileGroup[thisFastaName]);
1504                         if (itGroupNameMap != group2NameMap.end()) {
1505                             map<string, string> thisnamemap = itGroupNameMap->second;
1506                             map<string, string>::iterator itN;
1507                             ofstream out;
1508                             m->openOutputFile(thisaccnosFileName+".temp", out);
1509                             while (!in.eof()) {
1510                                 in >> name; m->gobble(in);
1511                                 itN = thisnamemap.find(name);
1512                                 if (itN != thisnamemap.end()) {
1513                                     vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
1514                                     for (int j = 0; j < tempNames.size(); j++) { out << tempNames[j] << endl; }
1515                                 
1516                                 }else { m->mothurOut("[ERROR]: parsing cannot find " + name + ".\n"); m->control_pressed = true; }
1517                             }
1518                             out.close();
1519                             in.close();
1520                             m->renameFile(thisaccnosFileName+".temp", thisaccnosFileName);
1521                         }else { m->mothurOut("[ERROR]: parsing cannot find " + fileGroup[thisFastaName] + ".\n"); m->control_pressed = true; }
1522                     }
1523                     
1524                 }
1525             }
1526
1527                         //append files
1528                         m->appendFiles(thisoutputFileName, outputFName); m->mothurRemove(thisoutputFileName); 
1529                         m->appendFiles(thisaccnosFileName, accnos); m->mothurRemove(thisaccnosFileName);
1530                         if (trim) { m->appendFiles(thistrimFastaFileName, fasta); m->mothurRemove(thistrimFastaFileName); }
1531                         m->mothurRemove(thisFastaName);
1532                         
1533                         totalSeqs += numSeqs;
1534                         
1535                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + fileGroup[thisFastaName] + ".");     m->mothurOutEndLine();
1536                 }
1537                 
1538         if (hasCount && dups) { outCountList.close(); }
1539         
1540                 return totalSeqs;
1541         }
1542         catch(exception& e) {
1543                 m->errorOut(e, "ChimeraSlayerCommand", "driverGroups");
1544                 exit(1);
1545         }
1546 }
1547 /**************************************************************************************************/
1548 int ChimeraSlayerCommand::createProcessesGroups(string outputFName, string accnos, string fasta, map<string, map<string, int> >& fileToPriority, map<string, string>& fileGroup, string countlist, string countFile) {
1549         try {
1550                 int process = 1;
1551                 int num = 0;
1552                 processIDS.clear();
1553                 
1554                 if (fileToPriority.size() < processors) { processors = fileToPriority.size(); }
1555         
1556         CountTable newCount;
1557         if (hasCount && dups) { newCount.readTable(countFile); }
1558                 
1559                 int groupsPerProcessor = fileToPriority.size() / processors;
1560                 int remainder = fileToPriority.size() % processors;
1561                 
1562                 vector< map<string, map<string, int> > > breakUp;
1563                 
1564                 for (int i = 0; i < processors; i++) {
1565                         map<string, map<string, int> > thisFileToPriority;
1566                         map<string, map<string, int> >::iterator itFile;
1567                         int count = 0;
1568                         int enough = groupsPerProcessor;
1569                         if (i == 0) { enough = groupsPerProcessor + remainder; }
1570                         
1571                         for (itFile = fileToPriority.begin(); itFile != fileToPriority.end();) {
1572                                 thisFileToPriority[itFile->first] = itFile->second;
1573                                 fileToPriority.erase(itFile++);
1574                                 count++;
1575                                 if (count == enough) { break; }
1576                         }       
1577                         breakUp.push_back(thisFileToPriority);
1578                 }
1579                                 
1580 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1581                 //loop through and create all the processes you want
1582                 while (process != processors) {
1583                         int pid = fork();
1584                         
1585                         if (pid > 0) {
1586                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1587                                 process++;
1588                         }else if (pid == 0){
1589                                 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", breakUp[process], fileGroup, accnos + toString(getpid()) + ".byCount");
1590                                 
1591                                 //pass numSeqs to parent
1592                                 ofstream out;
1593                                 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1594                                 m->openOutputFile(tempFile, out);
1595                                 out << num << endl;
1596                                 out.close();
1597                                 exit(0);
1598                         }else { 
1599                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1600                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1601                                 exit(0);
1602                         }
1603                 }
1604                 
1605                 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup, accnos + ".byCount");
1606
1607                 //force parent to wait until all the processes are done
1608                 for (int i=0;i<processors;i++) { 
1609                         int temp = processIDS[i];
1610                         wait(&temp);
1611                 }
1612                 
1613                 for (int i = 0; i < processIDS.size(); i++) {
1614                         ifstream in;
1615                         string tempFile =  outputFName + toString(processIDS[i]) + ".num.temp";
1616                         m->openInputFile(tempFile, in);
1617                         if (!in.eof()) { int tempNum = 0;  in >> tempNum; num += tempNum; }
1618                         in.close(); m->mothurRemove(tempFile);
1619                 }
1620 #else
1621                 
1622                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1623                 //Windows version shared memory, so be careful when passing variables through the slayerData struct. 
1624                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
1625                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1626                 
1627                 vector<slayerData*> pDataArray; 
1628                 DWORD   dwThreadIdArray[processors-1];
1629                 HANDLE  hThreadArray[processors-1]; 
1630                 
1631                 //Create processor worker threads.
1632                 for(int i=1; i<processors; i++ ){
1633                         string extension = toString(i) + ".temp";
1634                         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);
1635                         pDataArray.push_back(tempslayer);
1636                         processIDS.push_back(i);
1637                         
1638                         //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
1639                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1640                         hThreadArray[i-1] = CreateThread(NULL, 0, MySlayerGroupThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
1641                 }
1642                 
1643                 num = driverGroups(outputFName, accnos, fasta, breakUp[0], fileGroup, accnos + ".byCount");
1644                 
1645                 //Wait until all threads have terminated.
1646                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1647                 
1648                 //Close all thread handles and free memory allocations.
1649                 for(int i=0; i < pDataArray.size(); i++){
1650             if (pDataArray[i]->fileToPriority.size() != pDataArray[i]->end) {
1651                 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;
1652             }
1653                         num += pDataArray[i]->count;
1654                         CloseHandle(hThreadArray[i]);
1655                         delete pDataArray[i];
1656                 }
1657 #endif  
1658         //read my own
1659         if (hasCount && dups) {
1660             if (!m->isBlank(accnos + ".byCount")) {
1661                 ifstream in2;
1662                 m->openInputFile(accnos + ".byCount", in2);
1663                 
1664                 string name, group;
1665                 while (!in2.eof()) {
1666                     in2 >> name >> group; m->gobble(in2);
1667                     newCount.setAbund(name, group, 0);
1668                 }
1669                 in2.close();
1670             }
1671             m->mothurRemove(accnos + ".byCount");
1672         }
1673
1674                 
1675                 //append output files
1676                 for(int i=0;i<processIDS.size();i++){
1677                         m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1678                         m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1679                         
1680                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1681                         m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1682                         
1683                         if (trim) {
1684                                 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
1685                                 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
1686                         }
1687             
1688             if (hasCount && dups) {
1689                 if (!m->isBlank(accnos + toString(processIDS[i]) + ".byCount")) {
1690                     ifstream in2;
1691                     m->openInputFile(accnos  + toString(processIDS[i]) + ".byCount", in2);
1692                     
1693                     string name, group;
1694                     while (!in2.eof()) {
1695                         in2 >> name >> group; m->gobble(in2);
1696                         newCount.setAbund(name, group, 0);
1697                     }
1698                     in2.close();
1699                 }
1700                 m->mothurRemove(accnos + toString(processIDS[i]) + ".byCount");
1701             }
1702
1703                 }
1704                 
1705         //print new *.pick.count_table
1706         if (hasCount && dups) {  newCount.printTable(countlist);   }
1707                 
1708                 return num;
1709         }
1710         catch(exception& e) {
1711                 m->errorOut(e, "ChimeraSlayerCommand", "createProcessesGroups");
1712                 exit(1);
1713         }
1714 }
1715 //**********************************************************************************************************************
1716
1717 int ChimeraSlayerCommand::driver(linePair filePos, string outputFName, string filename, string accnos, string fasta, map<string, int>& priority){
1718         try {
1719                 
1720                 Chimera* chimera;
1721                 if (templatefile != "self") { //you want to run slayer with a reference template
1722                         chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());       
1723                 }else {
1724                         chimera = new ChimeraSlayer(filename, templatefile, trim, priority, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());     
1725                 }
1726                 
1727                 if (m->control_pressed) { delete chimera; return 0; }
1728                 
1729                 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1730                 templateSeqsLength = chimera->getLength();
1731                 
1732                 ofstream out;
1733                 m->openOutputFile(outputFName, out);
1734                 
1735                 ofstream out2;
1736                 m->openOutputFile(accnos, out2);
1737                 
1738                 ofstream out3;
1739                 if (trim) {  m->openOutputFile(fasta, out3); }
1740                 
1741                 ifstream inFASTA;
1742                 m->openInputFile(filename, inFASTA);
1743
1744                 inFASTA.seekg(filePos.start);
1745                 
1746                 if (filePos.start == 0) { chimera->printHeader(out); }
1747
1748                 bool done = false;
1749                 int count = 0;
1750         
1751                 while (!done) {
1752                 
1753                         if (m->control_pressed) {       delete chimera; out.close(); out2.close(); if (trim) { out3.close(); } inFASTA.close(); return 1;       }
1754                 
1755                         Sequence* candidateSeq = new Sequence(inFASTA);  m->gobble(inFASTA);
1756                         string candidateAligned = candidateSeq->getAligned();
1757                         
1758                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1759                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
1760                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1761                                 }else{
1762                                         //find chimeras
1763                                         chimera->getChimeras(candidateSeq);
1764                                         
1765                                         if (m->control_pressed) {       delete chimera; delete candidateSeq; return 1;  }
1766                                                 
1767                                         //if you are not chimeric, then check each half
1768                                         data_results wholeResults = chimera->getResults();
1769                                         
1770                                         //determine if we need to split
1771                                         bool isChimeric = false;
1772                                         
1773                                         if (wholeResults.flag == "yes") {
1774                                                 string chimeraFlag = "no";
1775                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1776                                                    ||
1777                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1778                                                 
1779                                                 
1780                                                 if (chimeraFlag == "yes") {     
1781                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1782                                                 }
1783                                         }
1784                                         
1785                                         if ((!isChimeric) && trimera) {
1786                                                 
1787                                                 //split sequence in half by bases
1788                                                 string leftQuery, rightQuery;
1789                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1790                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
1791                                                 
1792                                                 //run chimeraSlayer on each piece
1793                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1794                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1795                                                 
1796                                                 //find chimeras
1797                                                 chimera->getChimeras(left);
1798                                                 data_results leftResults = chimera->getResults();
1799                                                 
1800                                                 chimera->getChimeras(right);
1801                                                 data_results rightResults = chimera->getResults();
1802                                                 
1803                                                 //if either piece is chimeric then report
1804                                                 Sequence trimmed = chimera->print(out, out2, leftResults, rightResults);
1805                                                 if (trim) { trimmed.printSequence(out3);  }
1806                                                 
1807                                                 delete left; delete right;
1808                                                 
1809                                         }else { //already chimeric
1810                                                 //print results
1811                                                 Sequence trimmed = chimera->print(out, out2);
1812                                                 if (trim) { trimmed.printSequence(out3);  }
1813                                         }
1814                                         
1815                                         
1816                                 }
1817                                 count++;
1818                         }
1819                         
1820                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1821                                 unsigned long long pos = inFASTA.tellg();
1822                                 if ((pos == -1) || (pos >= filePos.end)) { break; }
1823                         #else
1824                                 if (inFASTA.eof()) { break; }
1825                         #endif
1826                         
1827                         delete candidateSeq;
1828                         //report progress
1829                         if((count) % 100 == 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1830                 }
1831                 //report progress
1832                 if((count) % 100 != 0){ m->mothurOut("Processing sequence: " + toString(count)); m->mothurOutEndLine();         }
1833                 
1834                 int numNoParents = chimera->getNumNoParents();
1835                 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(); } 
1836                 
1837                 out.close();
1838                 out2.close();
1839                 if (trim) { out3.close(); }
1840                 inFASTA.close();
1841                 delete chimera;
1842                                 
1843                 return count;
1844                 
1845                 
1846         }
1847         catch(exception& e) {
1848                 m->errorOut(e, "ChimeraSlayerCommand", "driver");
1849                 exit(1);
1850         }
1851 }
1852 //**********************************************************************************************************************
1853 #ifdef USE_MPI
1854 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){
1855         try {
1856                 MPI_Status status; 
1857                 int pid;
1858                 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
1859                 
1860                 Chimera* chimera;
1861                 if (templatefile != "self") { //you want to run slayer with a reference template
1862                         chimera = new ChimeraSlayer(filename, templatefile, trim, search, ksize, match, mismatch, window, divR, minSimilarity, minCoverage, minBS, minSNP, parents, iters, increment, numwanted, realign, blastlocation, rand());       
1863                 }else {
1864                         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);    
1865                 }
1866                 
1867                 if (m->control_pressed) { delete chimera; return 0; }
1868                 
1869                 if (chimera->getUnaligned()) { delete chimera; m->mothurOut("Your template sequences are different lengths, please correct."); m->mothurOutEndLine(); m->control_pressed = true; return 0; }
1870                 templateSeqsLength = chimera->getLength();
1871                 
1872                 for(int i=0;i<num;i++){
1873                         
1874                         if (m->control_pressed) {       delete chimera; return 1;       }
1875                         
1876                         //read next sequence
1877                         int length = MPIPos[start+i+1] - MPIPos[start+i];
1878
1879                         char* buf4 = new char[length];
1880                         MPI_File_read_at(inMPI, MPIPos[start+i], buf4, length, MPI_CHAR, &status);
1881         
1882                         string tempBuf = buf4;
1883                         if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length);  }
1884                         istringstream iss (tempBuf,istringstream::in);
1885
1886                         delete buf4;
1887
1888                         Sequence* candidateSeq = new Sequence(iss);  m->gobble(iss);
1889                         string candidateAligned = candidateSeq->getAligned();
1890                 
1891                         if (candidateSeq->getName() != "") { //incase there is a commented sequence at the end of a file
1892                                 
1893                                 if (candidateSeq->getAligned().length() != templateSeqsLength) {  
1894                                         m->mothurOut(candidateSeq->getName() + " is not the same length as the template sequences. Skipping."); m->mothurOutEndLine();
1895                                 }else{
1896                 
1897                                         //find chimeras
1898                                         chimera->getChimeras(candidateSeq);
1899                         
1900                                         if (m->control_pressed) {       delete chimera; delete candidateSeq; return 1;  }
1901                                         
1902                                         //if you are not chimeric, then check each half
1903                                         data_results wholeResults = chimera->getResults();
1904                                         
1905                                         //determine if we need to split
1906                                         bool isChimeric = false;
1907                                         
1908                                         if (wholeResults.flag == "yes") {
1909                                                 string chimeraFlag = "no";
1910                                                 if(  (wholeResults.results[0].bsa >= minBS && wholeResults.results[0].divr_qla_qrb >= divR)
1911                                                    ||
1912                                                    (wholeResults.results[0].bsb >= minBS && wholeResults.results[0].divr_qlb_qra >= divR) ) { chimeraFlag = "yes"; }
1913                                                 
1914                                                 
1915                                                 if (chimeraFlag == "yes") {     
1916                                                         if ((wholeResults.results[0].bsa >= minBS) || (wholeResults.results[0].bsb >= minBS)) { isChimeric = true; }
1917                                                 }
1918                                         }
1919                                         
1920                                         if ((!isChimeric) && trimera) {                                                 
1921                                                 //split sequence in half by bases
1922                                                 string leftQuery, rightQuery;
1923                                                 Sequence tempSeq(candidateSeq->getName(), candidateAligned);
1924                                                 divideInHalf(tempSeq, leftQuery, rightQuery);
1925                                                 
1926                                                 //run chimeraSlayer on each piece
1927                                                 Sequence* left = new Sequence(candidateSeq->getName(), leftQuery);
1928                                                 Sequence* right = new Sequence(candidateSeq->getName(), rightQuery);
1929                                                 
1930                                                 //find chimeras
1931                                                 chimera->getChimeras(left);
1932                                                 data_results leftResults = chimera->getResults();
1933                                                 
1934                                                 chimera->getChimeras(right);
1935                                                 data_results rightResults = chimera->getResults();
1936                                                 
1937                                                 //if either piece is chimeric then report
1938                         bool flag = false;
1939                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI, leftResults, rightResults, flag);
1940                         if (flag) { cnames.insert(candidateSeq->getName()); }
1941                             
1942                                                 if (trim) {  
1943                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1944                                                         
1945                                                         //write to accnos file
1946                                                         int length = outputString.length();
1947                                                         char* buf2 = new char[length];
1948                                                         memcpy(buf2, outputString.c_str(), length);
1949                                                         
1950                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1951                                                         delete buf2;
1952                                                 }
1953                                                 
1954                                                 delete left; delete right;
1955                                                 
1956                                         }else { 
1957                                                 //print results
1958                                                 Sequence trimmed = chimera->print(outMPI, outAccMPI);
1959                         cnames.insert(candidateSeq->getName());
1960                                                 
1961                                                 if (trim) {  
1962                                                         string outputString = ">" + trimmed.getName() + "\n" + trimmed.getAligned() + "\n";
1963                                                         
1964                                                         //write to accnos file
1965                                                         int length = outputString.length();
1966                                                         char* buf2 = new char[length];
1967                                                         memcpy(buf2, outputString.c_str(), length);
1968                                                         
1969                                                         MPI_File_write_shared(outFastaMPI, buf2, length, MPI_CHAR, &status);
1970                                                         delete buf2;
1971                                                 }
1972                                         }
1973                                         
1974                                 }
1975                         }
1976                         delete candidateSeq;
1977                         
1978                         //report progress
1979                         if((i+1) % 100 == 0){  cout << "Processing sequence: " << (i+1) << endl;        m->mothurOutJustToLog("Processing sequence: " + toString(i+1) + "\n");          }
1980                 }
1981                 //report progress
1982                 if(num % 100 != 0){             cout << "Processing sequence: " << num << endl; m->mothurOutJustToLog("Processing sequence: " + toString(num) + "\n");  }
1983                 
1984                 int numNoParents = chimera->getNumNoParents();
1985                 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; }
1986                 
1987                 delete chimera;         
1988                 return 0;
1989         }
1990         catch(exception& e) {
1991                 m->errorOut(e, "ChimeraSlayerCommand", "driverMPI");
1992                 exit(1);
1993         }
1994 }
1995 #endif
1996
1997 /**************************************************************************************************/
1998
1999 int ChimeraSlayerCommand::createProcesses(string outputFileName, string filename, string accnos, string fasta, map<string, int>& thisPriority) {
2000         try {
2001                 int process = 0;
2002                 int num = 0;
2003                 processIDS.clear();
2004                 
2005 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
2006                 //loop through and create all the processes you want
2007                 while (process != processors) {
2008                         int pid = fork();
2009                         
2010                         if (pid > 0) {
2011                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
2012                                 process++;
2013                         }else if (pid == 0){
2014                                 num = driver(lines[process], outputFileName + toString(getpid()) + ".temp", filename, accnos + toString(getpid()) + ".temp", fasta + toString(getpid()) + ".temp", thisPriority);
2015                                 
2016                                 //pass numSeqs to parent
2017                                 ofstream out;
2018                                 string tempFile = outputFileName + toString(getpid()) + ".num.temp";
2019                                 m->openOutputFile(tempFile, out);
2020                                 out << num << endl;
2021                                 out.close();
2022                                 exit(0);
2023                         }else { 
2024                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
2025                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
2026                                 exit(0);
2027                         }
2028                 }
2029                 
2030                 //force parent to wait until all the processes are done
2031                 for (int i=0;i<processors;i++) { 
2032                         int temp = processIDS[i];
2033                         wait(&temp);
2034                 }
2035                 
2036                 for (int i = 0; i < processIDS.size(); i++) {
2037                         ifstream in;
2038                         string tempFile =  outputFileName + toString(processIDS[i]) + ".num.temp";
2039                         m->openInputFile(tempFile, in);
2040                         if (!in.eof()) { int tempNum = 0;  in >> tempNum; num += tempNum; }
2041                         in.close(); m->mothurRemove(tempFile);
2042                 }
2043 #else
2044                 
2045                 //////////////////////////////////////////////////////////////////////////////////////////////////////
2046                 //Windows version shared memory, so be careful when passing variables through the slayerData struct. 
2047                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
2048                 //////////////////////////////////////////////////////////////////////////////////////////////////////
2049                 
2050                 vector<slayerData*> pDataArray; 
2051                 DWORD   dwThreadIdArray[processors];
2052                 HANDLE  hThreadArray[processors]; 
2053                 
2054                 //Create processor worker threads.
2055                 for( int i=0; i<processors; i++ ){
2056                         string extension = toString(i) + ".temp";
2057                         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);
2058                         pDataArray.push_back(tempslayer);
2059                         processIDS.push_back(i);
2060                         
2061                         //MySlayerThreadFunction is in header. It must be global or static to work with the threads.
2062                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
2063                         hThreadArray[i] = CreateThread(NULL, 0, MySlayerThreadFunction, pDataArray[i], 0, &dwThreadIdArray[i]);   
2064                 }
2065                                 
2066                 //Wait until all threads have terminated.
2067                 WaitForMultipleObjects(processors, hThreadArray, TRUE, INFINITE);
2068                 
2069                 //Close all thread handles and free memory allocations.
2070                 for(int i=0; i < pDataArray.size(); i++){
2071                         num += pDataArray[i]->count;
2072                         CloseHandle(hThreadArray[i]);
2073                         delete pDataArray[i];
2074                 }
2075 #endif  
2076                 
2077                 rename((outputFileName + toString(processIDS[0]) + ".temp").c_str(), outputFileName.c_str());
2078                 rename((accnos + toString(processIDS[0]) + ".temp").c_str(), accnos.c_str());
2079                 if (trim) {  rename((fasta + toString(processIDS[0]) + ".temp").c_str(), fasta.c_str()); }
2080                 
2081                 //append output files
2082                 for(int i=1;i<processIDS.size();i++){
2083                         m->appendFiles((outputFileName + toString(processIDS[i]) + ".temp"), outputFileName);
2084                         m->mothurRemove((outputFileName + toString(processIDS[i]) + ".temp"));
2085                         
2086                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
2087                         m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
2088                         
2089                         if (trim) {
2090                                 m->appendFiles((fasta + toString(processIDS[i]) + ".temp"), fasta);
2091                                 m->mothurRemove((fasta + toString(processIDS[i]) + ".temp"));
2092                         }
2093                 }
2094                 
2095                 
2096                 return num;
2097         }
2098         catch(exception& e) {
2099                 m->errorOut(e, "ChimeraSlayerCommand", "createProcesses");
2100                 exit(1);
2101         }
2102 }
2103
2104 /**************************************************************************************************/
2105
2106 int ChimeraSlayerCommand::divideInHalf(Sequence querySeq, string& leftQuery, string& rightQuery) {
2107         try {
2108                 
2109                 string queryUnAligned = querySeq.getUnaligned();
2110                 int numBases = int(queryUnAligned.length() * 0.5);
2111                 
2112                 string queryAligned = querySeq.getAligned();
2113                 leftQuery = querySeq.getAligned();
2114                 rightQuery = querySeq.getAligned();
2115                 
2116                 int baseCount = 0;
2117                 int leftSpot = 0;
2118                 for (int i = 0; i < queryAligned.length(); i++) {
2119                         //if you are a base
2120                         if (isalpha(queryAligned[i])) {         
2121                                 baseCount++; 
2122                         }
2123                         
2124                         //if you have half
2125                         if (baseCount >= numBases) {  leftSpot = i; break; } //first half
2126                 }
2127                 
2128                 //blank out right side
2129                 for (int i = leftSpot; i < leftQuery.length(); i++) { leftQuery[i] = '.'; }
2130                 
2131                 //blank out left side
2132                 for (int i = 0; i < leftSpot; i++) { rightQuery[i] = '.'; }
2133                 
2134                 return 0;
2135                 
2136         }
2137         catch(exception& e) {
2138                 m->errorOut(e, "ChimeraSlayerCommand", "divideInHalf");
2139                 exit(1);
2140         }
2141 }
2142 /**************************************************************************************************/
2143 map<string, int> ChimeraSlayerCommand::sortFastaFile(string fastaFile, string nameFile) {
2144         try {
2145                 map<string, int> nameAbund;
2146                 
2147                 //read through fastafile and store info
2148                 map<string, string> seqs;
2149                 ifstream in;
2150                 m->openInputFile(fastaFile, in);
2151                 
2152                 while (!in.eof()) {
2153                         
2154                         if (m->control_pressed) { in.close(); return nameAbund; }
2155                         
2156                         Sequence seq(in); m->gobble(in);
2157                         seqs[seq.getName()] = seq.getAligned();
2158                 }
2159                 
2160                 in.close();
2161                 
2162                 //read namefile or countfile
2163                 vector<seqPriorityNode> nameMapCount;
2164         int error;
2165         if (hasCount) { 
2166             CountTable ct;
2167             ct.readTable(nameFile);
2168             
2169             for(map<string, string>::iterator it = seqs.begin(); it != seqs.end(); it++) {
2170                 int num = ct.getNumSeqs(it->first);
2171                 if (num == 0) { error = 1; }
2172                 else {
2173                     seqPriorityNode temp(num, it->second, it->first);
2174                     nameMapCount.push_back(temp);
2175                 }
2176             }
2177         }else { error = m->readNames(nameFile, nameMapCount, seqs); }
2178                 
2179                 if (m->control_pressed) { return nameAbund; }
2180                 
2181                 if (error == 1) { m->control_pressed = true; return nameAbund; }
2182                 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; }
2183
2184                 sort(nameMapCount.begin(), nameMapCount.end(), compareSeqPriorityNodes);
2185                 
2186                 string newFasta = fastaFile + ".temp";
2187                 ofstream out;
2188                 m->openOutputFile(newFasta, out);
2189                 
2190                 //print new file in order of
2191                 for (int i = 0; i < nameMapCount.size(); i++) {
2192                         out << ">" << nameMapCount[i].name << endl << nameMapCount[i].seq << endl;
2193                         nameAbund[nameMapCount[i].name] = nameMapCount[i].numIdentical;
2194                 }
2195                 out.close();
2196                 
2197                 rename(newFasta.c_str(), fastaFile.c_str());
2198                                 
2199                 return nameAbund;
2200                 
2201         }
2202         catch(exception& e) {
2203                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2204                 exit(1);
2205         }
2206 }
2207 /**************************************************************************************************/
2208 map<string, int> ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, string>& nameMap, string newFile) {
2209         try {
2210                 map<string, int> nameAbund;
2211                 vector<seqPriorityNode> nameVector;
2212                 
2213                 //read through fastafile and store info
2214                 map<string, string> seqs;
2215                                 
2216                 for (int i = 0; i < thisseqs.size(); i++) {
2217                         
2218                         if (m->control_pressed) { return nameAbund; }
2219                         
2220                         map<string, string>::iterator itNameMap = nameMap.find(thisseqs[i].getName());
2221                         
2222                         if (itNameMap == nameMap.end()){
2223                                 m->control_pressed = true;
2224                                 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your namesfile, please correct."); m->mothurOutEndLine();
2225                         }else {
2226                                 int num = m->getNumNames(itNameMap->second);
2227                                 
2228                                 seqPriorityNode temp(num, thisseqs[i].getAligned(), thisseqs[i].getName());
2229                                 nameVector.push_back(temp);
2230                         }
2231                 }
2232         
2233                 //sort by num represented
2234                 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2235         
2236                 if (m->control_pressed) { return nameAbund; }
2237                 
2238                 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; }
2239                                 
2240                 ofstream out;
2241                 m->openOutputFile(newFile, out);
2242                 
2243                 //print new file in order of
2244                 for (int i = 0; i < nameVector.size(); i++) {
2245                         out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2246                         nameAbund[nameVector[i].name] = nameVector[i].numIdentical;
2247                 }
2248                 out.close();
2249                 
2250                 return nameAbund;
2251                 
2252         }
2253         catch(exception& e) {
2254                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2255                 exit(1);
2256         }
2257 }
2258 /**************************************************************************************************/
2259 int ChimeraSlayerCommand::sortFastaFile(vector<Sequence>& thisseqs, map<string, int>& countMap, string newFile) {
2260         try {
2261                 vector<seqPriorityNode> nameVector;
2262                 
2263                 //read through fastafile and store info
2264                 map<string, string> seqs;
2265         
2266                 for (int i = 0; i < thisseqs.size(); i++) {
2267                         
2268                         if (m->control_pressed) { return 0; }
2269                         
2270                         map<string, int>::iterator itCountMap = countMap.find(thisseqs[i].getName());
2271                         
2272                         if (itCountMap == countMap.end()){
2273                                 m->control_pressed = true;
2274                                 m->mothurOut("[ERROR]: " + thisseqs[i].getName() + " is in your fastafile, but is not in your count file, please correct."); m->mothurOutEndLine();
2275                         }else {
2276                 seqPriorityNode temp(itCountMap->second, thisseqs[i].getAligned(), thisseqs[i].getName());
2277                                 nameVector.push_back(temp);
2278                         }
2279                 }
2280         
2281                 //sort by num represented
2282                 sort(nameVector.begin(), nameVector.end(), compareSeqPriorityNodes);
2283         
2284                 if (m->control_pressed) { return 0; }
2285                 
2286                 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; }
2287         
2288                 ofstream out;
2289                 m->openOutputFile(newFile, out);
2290                 
2291                 //print new file in order of
2292                 for (int i = 0; i < nameVector.size(); i++) {
2293                         out << ">" << nameVector[i].name << endl << nameVector[i].seq << endl;
2294                 }
2295                 out.close();
2296                 
2297                 return 0;
2298                 
2299         }
2300         catch(exception& e) {
2301                 m->errorOut(e, "ChimeraSlayerCommand", "sortFastaFile");
2302                 exit(1);
2303         }
2304 }
2305 /**************************************************************************************************/
2306