]> git.donarmstrong.com Git - mothur.git/blob - chimeraperseuscommand.cpp
changes while testing
[mothur.git] / chimeraperseuscommand.cpp
1 /*
2  *  chimeraperseuscommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 10/26/11.
6  *  Copyright 2011 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "chimeraperseuscommand.h"
11 #include "deconvolutecommand.h"
12 #include "sequence.hpp"
13 #include "counttable.h"
14 #include "sequencecountparser.h"
15 //**********************************************************************************************************************
16 vector<string> ChimeraPerseusCommand::setParameters(){  
17         try {
18                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none","chimera-accnos",false,true,true); parameters.push_back(pfasta);
19                 CommandParameter pname("name", "InputTypes", "", "", "NameCount", "NameCount", "none","",false,false,true); parameters.push_back(pname);
20         CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "NameCount", "none","",false,false,true); parameters.push_back(pcount);
21                 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","",false,false,true); parameters.push_back(pgroup);
22                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
23         CommandParameter pdups("dereplicate", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(pdups);
24
25                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
26                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
27                 CommandParameter pcutoff("cutoff", "Number", "", "0.5", "", "", "","",false,false); parameters.push_back(pcutoff);
28                 CommandParameter palpha("alpha", "Number", "", "-5.54", "", "", "","",false,false); parameters.push_back(palpha);
29                 CommandParameter pbeta("beta", "Number", "", "0.33", "", "", "","",false,false); parameters.push_back(pbeta);
30                         
31                 vector<string> myArray;
32                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
33                 return myArray;
34         }
35         catch(exception& e) {
36                 m->errorOut(e, "ChimeraPerseusCommand", "setParameters");
37                 exit(1);
38         }
39 }
40 //**********************************************************************************************************************
41 string ChimeraPerseusCommand::getHelpString(){  
42         try {
43                 string helpString = "";
44                 helpString += "The chimera.perseus command reads a fastafile and namefile or countfile and outputs potentially chimeric sequences.\n";
45                 helpString += "The chimera.perseus command parameters are fasta, name, group, cutoff, processors, dereplicate, alpha and beta.\n";
46                 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";
47                 helpString += "The name parameter allows you to provide a name file associated with your fasta file.\n";
48         helpString += "The count parameter allows you to provide a count file associated with your fasta file. A count or name file is required. 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";
49                 helpString += "You may enter multiple fasta files by separating their names with dashes. ie. fasta=abrecovery.fasta-amazon.fasta \n";
50                 helpString += "The group parameter allows you to provide a group file.  When checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
51                 helpString += "The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n";
52         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";
53                 helpString += "The alpha parameter ....  The default is -5.54. \n";
54                 helpString += "The beta parameter ....  The default is 0.33. \n";
55                 helpString += "The cutoff parameter ....  The default is 0.50. \n";
56                 helpString += "The chimera.perseus command should be in the following format: \n";
57                 helpString += "chimera.perseus(fasta=yourFastaFile, name=yourNameFile) \n";
58                 helpString += "Example: chimera.perseus(fasta=AD.align, name=AD.names) \n";
59                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";       
60                 return helpString;
61         }
62         catch(exception& e) {
63                 m->errorOut(e, "ChimeraPerseusCommand", "getHelpString");
64                 exit(1);
65         }
66 }
67 //**********************************************************************************************************************
68 string ChimeraPerseusCommand::getOutputPattern(string type) {
69     try {
70         string pattern = "";
71         
72         if (type == "chimera") {  pattern = "[filename],perseus.chimeras"; } 
73         else if (type == "accnos") {  pattern = "[filename],perseus.accnos"; }
74         else if (type == "count") {  pattern = "[filename],perseus.pick.count_table"; }
75         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
76         
77         return pattern;
78     }
79     catch(exception& e) {
80         m->errorOut(e, "ChimeraPerseusCommand", "getOutputPattern");
81         exit(1);
82     }
83 }
84 //**********************************************************************************************************************
85 ChimeraPerseusCommand::ChimeraPerseusCommand(){ 
86         try {
87                 abort = true; calledHelp = true;
88                 setParameters();
89                 vector<string> tempOutNames;
90                 outputTypes["chimera"] = tempOutNames;
91                 outputTypes["accnos"] = tempOutNames;
92         outputTypes["count"] = tempOutNames;
93         }
94         catch(exception& e) {
95                 m->errorOut(e, "ChimeraPerseusCommand", "ChimeraPerseusCommand");
96                 exit(1);
97         }
98 }
99 //***************************************************************************************************************
100 ChimeraPerseusCommand::ChimeraPerseusCommand(string option)  {
101         try {
102                 abort = false; calledHelp = false; 
103         hasCount = false;
104         hasName = false;
105                 
106                 //allow user to run help
107                 if(option == "help") { help(); abort = true; calledHelp = true; }
108                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
109                 
110                 else {
111                         vector<string> myArray = setParameters();
112                         
113                         OptionParser parser(option);
114                         map<string,string> parameters = parser.getParameters();
115                         
116                         ValidParameters validParameter("chimera.perseus");
117                         map<string,string>::iterator it;
118                         
119                         //check to make sure all parameters are valid for command
120                         for (it = parameters.begin(); it != parameters.end(); it++) { 
121                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
122                         }
123                         
124                         vector<string> tempOutNames;
125                         outputTypes["chimera"] = tempOutNames;
126                         outputTypes["accnos"] = tempOutNames;
127             outputTypes["count"] = tempOutNames;
128                         
129                         //if the user changes the input directory command factory will send this info to us in the output parameter 
130                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
131                         if (inputDir == "not found"){   inputDir = "";          }
132                         
133                         //check for required parameters
134                         fastafile = validParameter.validFile(parameters, "fasta", false);
135                         if (fastafile == "not found") {                                 
136                                 //if there is a current fasta file, use it
137                                 string filename = m->getFastaFile(); 
138                                 if (filename != "") { fastaFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
139                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
140                         }else { 
141                                 m->splitAtDash(fastafile, fastaFileNames);
142                                 
143                                 //go through files and make sure they are good, if not, then disregard them
144                                 for (int i = 0; i < fastaFileNames.size(); i++) {
145                                         
146                                         bool ignore = false;
147                                         if (fastaFileNames[i] == "current") { 
148                                                 fastaFileNames[i] = m->getFastaFile(); 
149                                                 if (fastaFileNames[i] != "") {  m->mothurOut("Using " + fastaFileNames[i] + " as input file for the fasta parameter where you had given current."); m->mothurOutEndLine(); }
150                                                 else {  
151                                                         m->mothurOut("You have no current fastafile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
152                                                         //erase from file list
153                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
154                                                         i--;
155                                                 }
156                                         }
157                                         
158                                         if (!ignore) {
159                                                 
160                                                 if (inputDir != "") {
161                                                         string path = m->hasPath(fastaFileNames[i]);
162                                                         //if the user has not given a path then, add inputdir. else leave path alone.
163                                                         if (path == "") {       fastaFileNames[i] = inputDir + fastaFileNames[i];               }
164                                                 }
165                                                 
166                                                 int ableToOpen;
167                                                 ifstream in;
168                                                 
169                                                 ableToOpen = m->openInputFile(fastaFileNames[i], in, "noerror");
170                                                 
171                                                 //if you can't open it, try default location
172                                                 if (ableToOpen == 1) {
173                                                         if (m->getDefaultPath() != "") { //default path is set
174                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(fastaFileNames[i]);
175                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
176                                                                 ifstream in2;
177                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
178                                                                 in2.close();
179                                                                 fastaFileNames[i] = tryPath;
180                                                         }
181                                                 }
182                                                 
183                                                 if (ableToOpen == 1) {
184                                                         if (m->getOutputDir() != "") { //default path is set
185                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(fastaFileNames[i]);
186                                                                 m->mothurOut("Unable to open " + fastaFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
187                                                                 ifstream in2;
188                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
189                                                                 in2.close();
190                                                                 fastaFileNames[i] = tryPath;
191                                                         }
192                                                 }
193                                                 
194                                                 in.close();
195                                                 
196                                                 if (ableToOpen == 1) { 
197                                                         m->mothurOut("Unable to open " + fastaFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
198                                                         //erase from file list
199                                                         fastaFileNames.erase(fastaFileNames.begin()+i);
200                                                         i--;
201                                                 }else {
202                                                         m->setFastaFile(fastaFileNames[i]);
203                                                 }
204                                         }
205                                 }
206                                 
207                                 //make sure there is at least one valid file left
208                                 if (fastaFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid files."); m->mothurOutEndLine(); abort = true; }
209                         }
210                         
211                         
212                         //check for required parameters
213                         namefile = validParameter.validFile(parameters, "name", false);
214                         if (namefile == "not found") { namefile = "";   }
215                         else { 
216                                 m->splitAtDash(namefile, nameFileNames);
217                                 
218                                 //go through files and make sure they are good, if not, then disregard them
219                                 for (int i = 0; i < nameFileNames.size(); i++) {
220                                         
221                                         bool ignore = false;
222                                         if (nameFileNames[i] == "current") { 
223                                                 nameFileNames[i] = m->getNameFile(); 
224                                                 if (nameFileNames[i] != "") {  m->mothurOut("Using " + nameFileNames[i] + " as input file for the name parameter where you had given current."); m->mothurOutEndLine(); }
225                                                 else {  
226                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
227                                                         //erase from file list
228                                                         nameFileNames.erase(nameFileNames.begin()+i);
229                                                         i--;
230                                                 }
231                                         }
232                                         
233                                         if (!ignore) {
234                                                 
235                                                 if (inputDir != "") {
236                                                         string path = m->hasPath(nameFileNames[i]);
237                                                         //if the user has not given a path then, add inputdir. else leave path alone.
238                                                         if (path == "") {       nameFileNames[i] = inputDir + nameFileNames[i];         }
239                                                 }
240                                                 
241                                                 int ableToOpen;
242                                                 ifstream in;
243                                                 
244                                                 ableToOpen = m->openInputFile(nameFileNames[i], in, "noerror");
245                                                 
246                                                 //if you can't open it, try default location
247                                                 if (ableToOpen == 1) {
248                                                         if (m->getDefaultPath() != "") { //default path is set
249                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(nameFileNames[i]);
250                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
251                                                                 ifstream in2;
252                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
253                                                                 in2.close();
254                                                                 nameFileNames[i] = tryPath;
255                                                         }
256                                                 }
257                                                 
258                                                 if (ableToOpen == 1) {
259                                                         if (m->getOutputDir() != "") { //default path is set
260                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(nameFileNames[i]);
261                                                                 m->mothurOut("Unable to open " + nameFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
262                                                                 ifstream in2;
263                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
264                                                                 in2.close();
265                                                                 nameFileNames[i] = tryPath;
266                                                         }
267                                                 }
268                                                 
269                                                 in.close();
270                                                 
271                                                 if (ableToOpen == 1) { 
272                                                         m->mothurOut("Unable to open " + nameFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
273                                                         //erase from file list
274                                                         nameFileNames.erase(nameFileNames.begin()+i);
275                                                         i--;
276                                                 }else {
277                                                         m->setNameFile(nameFileNames[i]);
278                                                 }
279                                         }
280                                 }
281                         }
282             
283             if (nameFileNames.size() != 0) { hasName = true; }
284             
285             //check for required parameters
286             vector<string> countfileNames;
287                         countfile = validParameter.validFile(parameters, "count", false);
288                         if (countfile == "not found") { 
289                 countfile = "";  
290                         }else { 
291                                 m->splitAtDash(countfile, countfileNames);
292                                 
293                                 //go through files and make sure they are good, if not, then disregard them
294                                 for (int i = 0; i < countfileNames.size(); i++) {
295                                         
296                                         bool ignore = false;
297                                         if (countfileNames[i] == "current") { 
298                                                 countfileNames[i] = m->getCountTableFile(); 
299                                                 if (countfileNames[i] != "") {  m->mothurOut("Using " + countfileNames[i] + " as input file for the count parameter where you had given current."); m->mothurOutEndLine(); }
300                                                 else {  
301                                                         m->mothurOut("You have no current count file, ignoring current."); m->mothurOutEndLine(); ignore=true; 
302                                                         //erase from file list
303                                                         countfileNames.erase(countfileNames.begin()+i);
304                                                         i--;
305                                                 }
306                                         }
307                                         
308                                         if (!ignore) {
309                                                 
310                                                 if (inputDir != "") {
311                                                         string path = m->hasPath(countfileNames[i]);
312                                                         //if the user has not given a path then, add inputdir. else leave path alone.
313                                                         if (path == "") {       countfileNames[i] = inputDir + countfileNames[i];               }
314                                                 }
315                                                 
316                                                 int ableToOpen;
317                                                 ifstream in;
318                                                 
319                                                 ableToOpen = m->openInputFile(countfileNames[i], in, "noerror");
320                                                 
321                                                 //if you can't open it, try default location
322                                                 if (ableToOpen == 1) {
323                                                         if (m->getDefaultPath() != "") { //default path is set
324                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(countfileNames[i]);
325                                                                 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
326                                                                 ifstream in2;
327                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
328                                                                 in2.close();
329                                                                 countfileNames[i] = tryPath;
330                                                         }
331                                                 }
332                                                 
333                                                 if (ableToOpen == 1) {
334                                                         if (m->getOutputDir() != "") { //default path is set
335                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(countfileNames[i]);
336                                                                 m->mothurOut("Unable to open " + countfileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
337                                                                 ifstream in2;
338                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
339                                                                 in2.close();
340                                                                 countfileNames[i] = tryPath;
341                                                         }
342                                                 }
343                                                 
344                                                 in.close();
345                                                 
346                                                 if (ableToOpen == 1) { 
347                                                         m->mothurOut("Unable to open " + countfileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
348                                                         //erase from file list
349                                                         countfileNames.erase(countfileNames.begin()+i);
350                                                         i--;
351                                                 }else {
352                                                         m->setCountTableFile(countfileNames[i]);
353                                                 }
354                                         }
355                                 }
356                         }
357             
358             if (countfileNames.size() != 0) { hasCount = true; }
359             
360                         //make sure there is at least one valid file left
361             if (hasName && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
362             
363             if (!hasName && !hasCount) { 
364                 //if there is a current name file, use it, else look for current count file
365                                 string filename = m->getNameFile(); 
366                                 if (filename != "") { hasName = true; nameFileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the name parameter."); m->mothurOutEndLine(); }
367                                 else { 
368                     filename = m->getCountTableFile();
369                     if (filename != "") { hasCount = true; countfileNames.push_back(filename); m->mothurOut("Using " + filename + " as input file for the count parameter."); m->mothurOutEndLine(); }
370                     else { m->mothurOut("[ERROR]: You must provide a count or name file."); m->mothurOutEndLine(); abort = true;  }
371                 }
372             }
373             if (!hasName && hasCount) { nameFileNames = countfileNames; }
374             
375                         if (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; }
376                         
377                         bool hasGroup = true;
378                         groupfile = validParameter.validFile(parameters, "group", false);
379                         if (groupfile == "not found") { groupfile = "";  hasGroup = false; }
380                         else { 
381                                 m->splitAtDash(groupfile, groupFileNames);
382                                 
383                                 //go through files and make sure they are good, if not, then disregard them
384                                 for (int i = 0; i < groupFileNames.size(); i++) {
385                                         
386                                         bool ignore = false;
387                                         if (groupFileNames[i] == "current") { 
388                                                 groupFileNames[i] = m->getGroupFile(); 
389                                                 if (groupFileNames[i] != "") {  m->mothurOut("Using " + groupFileNames[i] + " as input file for the group parameter where you had given current."); m->mothurOutEndLine(); }
390                                                 else {  
391                                                         m->mothurOut("You have no current namefile, ignoring current."); m->mothurOutEndLine(); ignore=true; 
392                                                         //erase from file list
393                                                         groupFileNames.erase(groupFileNames.begin()+i);
394                                                         i--;
395                                                 }
396                                         }
397                                         
398                                         if (!ignore) {
399                                                 
400                                                 if (inputDir != "") {
401                                                         string path = m->hasPath(groupFileNames[i]);
402                                                         //if the user has not given a path then, add inputdir. else leave path alone.
403                                                         if (path == "") {       groupFileNames[i] = inputDir + groupFileNames[i];               }
404                                                 }
405                                                 
406                                                 int ableToOpen;
407                                                 ifstream in;
408                                                 
409                                                 ableToOpen = m->openInputFile(groupFileNames[i], in, "noerror");
410                                                 
411                                                 //if you can't open it, try default location
412                                                 if (ableToOpen == 1) {
413                                                         if (m->getDefaultPath() != "") { //default path is set
414                                                                 string tryPath = m->getDefaultPath() + m->getSimpleName(groupFileNames[i]);
415                                                                 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying default " + tryPath); m->mothurOutEndLine();
416                                                                 ifstream in2;
417                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
418                                                                 in2.close();
419                                                                 groupFileNames[i] = tryPath;
420                                                         }
421                                                 }
422                                                 
423                                                 if (ableToOpen == 1) {
424                                                         if (m->getOutputDir() != "") { //default path is set
425                                                                 string tryPath = m->getOutputDir() + m->getSimpleName(groupFileNames[i]);
426                                                                 m->mothurOut("Unable to open " + groupFileNames[i] + ". Trying output directory " + tryPath); m->mothurOutEndLine();
427                                                                 ifstream in2;
428                                                                 ableToOpen = m->openInputFile(tryPath, in2, "noerror");
429                                                                 in2.close();
430                                                                 groupFileNames[i] = tryPath;
431                                                         }
432                                                 }
433                                                 
434                                                 in.close();
435                                                 
436                                                 if (ableToOpen == 1) { 
437                                                         m->mothurOut("Unable to open " + groupFileNames[i] + ". It will be disregarded."); m->mothurOutEndLine(); 
438                                                         //erase from file list
439                                                         groupFileNames.erase(groupFileNames.begin()+i);
440                                                         i--;
441                                                 }else {
442                                                         m->setGroupFile(groupFileNames[i]);
443                                                 }
444                                         }
445                                 }
446                                 
447                                 //make sure there is at least one valid file left
448                                 if (groupFileNames.size() == 0) { m->mothurOut("[ERROR]: no valid group files."); m->mothurOutEndLine(); abort = true; }
449                         }
450                         
451                         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; }
452                         
453             if (hasGroup && hasCount) { m->mothurOut("[ERROR]: You must enter ONLY ONE of the following: count or group."); m->mothurOutEndLine(); abort = true; }
454                         
455                         //if the user changes the output directory command factory will send this info to us in the output parameter 
456                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
457                         
458                         string temp = validParameter.validFile(parameters, "processors", false);        if (temp == "not found"){       temp = m->getProcessors();      }
459                         m->setProcessors(temp);
460                         m->mothurConvert(temp, processors);
461                         
462                         temp = validParameter.validFile(parameters, "cutoff", false);   if (temp == "not found"){       temp = "0.50";  }
463                         m->mothurConvert(temp, cutoff);
464                         
465                         temp = validParameter.validFile(parameters, "alpha", false);    if (temp == "not found"){       temp = "-5.54"; }
466                         m->mothurConvert(temp, alpha);
467                         
468                         temp = validParameter.validFile(parameters, "cutoff", false);   if (temp == "not found"){       temp = "0.33";  }
469                         m->mothurConvert(temp, beta);
470             
471                         temp = validParameter.validFile(parameters, "dereplicate", false);      
472                         if (temp == "not found") { temp = "false";                      }
473                         dups = m->isTrue(temp);
474                 }
475         }
476         catch(exception& e) {
477                 m->errorOut(e, "ChimeraPerseusCommand", "ChimeraPerseusCommand");
478                 exit(1);
479         }
480 }
481 //***************************************************************************************************************
482
483 int ChimeraPerseusCommand::execute(){
484         try{
485                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
486                 
487                                 
488                 //process each file
489                 for (int s = 0; s < fastaFileNames.size(); s++) {
490                         
491                         m->mothurOut("Checking sequences from " + fastaFileNames[s] + " ..." ); m->mothurOutEndLine();
492                         
493                         int start = time(NULL); 
494                         if (outputDir == "") { outputDir = m->hasPath(fastaFileNames[s]);  }//if user entered a file with a path then preserve it       
495                         map<string, string> variables;
496                         variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(fastaFileNames[s]));
497                         string outputFileName = getOutputFileName("chimera", variables);
498                         string accnosFileName = getOutputFileName("accnos", variables);
499             string newCountFile = "";
500
501                         //string newFasta = m->getRootName(fastaFileNames[s]) + "temp";
502                         
503                         //you provided a groupfile
504                         string groupFile = "";
505                         if (groupFileNames.size() != 0) { groupFile = groupFileNames[s]; }
506                         
507                         string nameFile = "";
508                         if (nameFileNames.size() != 0) { //you provided a namefile and we don't need to create one
509                                 nameFile = nameFileNames[s];
510                         }else { nameFile = getNamesFile(fastaFileNames[s]); }
511                         
512                         if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {       m->mothurRemove(outputNames[j]);        } return 0;     }                               
513                         
514                         int numSeqs = 0;
515                         int numChimeras = 0;
516             
517             if (hasCount) {
518                 CountTable* ct = new CountTable();
519                 ct->readTable(nameFile, true);
520                 
521                 if (ct->hasGroupInfo()) {
522                     cparser = new SequenceCountParser(fastaFileNames[s], *ct);
523                     variables["[filename]"] = outputDir + m->getRootName(m->getSimpleName(nameFile));
524                     newCountFile = getOutputFileName("count", variables);
525                     
526                     vector<string> groups = cparser->getNamesOfGroups();
527                     
528                     if (m->control_pressed) { delete ct; delete cparser; for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]);        }  return 0; }
529                     
530                     //clears files
531                     ofstream out, out1, out2;
532                     m->openOutputFile(outputFileName, out); out.close(); 
533                     m->openOutputFile(accnosFileName, out1); out1.close();
534                     
535                     if(processors == 1) {       numSeqs = driverGroups(outputFileName, accnosFileName, newCountFile, 0, groups.size(), groups);
536                         if (dups) {
537                             CountTable c; c.readTable(nameFile, true);
538                             if (!m->isBlank(newCountFile)) {
539                                 ifstream in2;
540                                 m->openInputFile(newCountFile, in2);
541                                 
542                                 string name, group;
543                                 while (!in2.eof()) {
544                                     in2 >> name >> group; m->gobble(in2);
545                                     c.setAbund(name, group, 0);
546                                 }
547                                 in2.close();
548                             }
549                             m->mothurRemove(newCountFile);
550                             c.printTable(newCountFile);
551                         }
552
553                     }
554                     else                                {       numSeqs = createProcessesGroups(outputFileName, accnosFileName, newCountFile, groups, groupFile, fastaFileNames[s], nameFile);                  }
555                     
556                     if (m->control_pressed) {  delete ct; delete cparser; for (int j = 0; j < outputNames.size(); j++) {        m->mothurRemove(outputNames[j]);        }  return 0;    }                               
557                     map<string, string> uniqueNames = cparser->getAllSeqsMap();
558                     if (!dups) { 
559                         numChimeras = deconvoluteResults(uniqueNames, outputFileName, accnosFileName);
560                     }else {
561                         set<string> doNotRemove;
562                         CountTable c; c.readTable(newCountFile, true);
563                         vector<string> namesInTable = c.getNamesOfSeqs();
564                         for (int i = 0; i < namesInTable.size(); i++) {
565                             int temp = c.getNumSeqs(namesInTable[i]);
566                             if (temp == 0) {  c.remove(namesInTable[i]);  }
567                             else { doNotRemove.insert((namesInTable[i])); }
568                         }
569                         //remove names we want to keep from accnos file.
570                         set<string> accnosNames = m->readAccnos(accnosFileName);
571                         ofstream out2;
572                         m->openOutputFile(accnosFileName, out2);
573                         for (set<string>::iterator it = accnosNames.begin(); it != accnosNames.end(); it++) {
574                             if (doNotRemove.count(*it) == 0) {  out2 << (*it) << endl; }
575                         }
576                         out2.close();
577                         c.printTable(newCountFile);
578                         outputNames.push_back(newCountFile); outputTypes["count"].push_back(newCountFile);
579
580                     }
581                     delete cparser;
582
583                     m->mothurOut("The number of sequences checked may be larger than the number of unique sequences because some sequences are found in several samples."); m->mothurOutEndLine(); 
584                     
585                     if (m->control_pressed) {  delete ct; for (int j = 0; j < outputNames.size(); j++) {        m->mothurRemove(outputNames[j]);        }  return 0;  } 
586                     
587                 }else {
588                     if (processors != 1) { m->mothurOut("Your count file does not contain group information, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
589                     
590                     //read sequences and store sorted by frequency
591                     vector<seqData> sequences = readFiles(fastaFileNames[s], ct);
592                     
593                     if (m->control_pressed) { delete ct; for (int j = 0; j < outputNames.size(); j++) { m->mothurRemove(outputNames[j]);        } return 0; }
594                     
595                     numSeqs = driver(outputFileName, sequences, accnosFileName, numChimeras);   
596                 }
597                 delete ct;
598             }else {
599                 if (groupFile != "") {
600                     //Parse sequences by group
601                     parser = new SequenceParser(groupFile, fastaFileNames[s], nameFile);
602                     vector<string> groups = parser->getNamesOfGroups();
603                     
604                     if (m->control_pressed) { delete parser; for (int j = 0; j < outputNames.size(); j++) {     m->mothurRemove(outputNames[j]);        }  return 0; }
605                     
606                     //clears files
607                     ofstream out, out1, out2;
608                     m->openOutputFile(outputFileName, out); out.close(); 
609                     m->openOutputFile(accnosFileName, out1); out1.close();
610                     
611                     if(processors == 1) {       numSeqs = driverGroups(outputFileName, accnosFileName, "", 0, groups.size(), groups);   }
612                     else                                {       numSeqs = createProcessesGroups(outputFileName, accnosFileName, "", groups, groupFile, fastaFileNames[s], nameFile);                    }
613                     
614                     if (m->control_pressed) {  delete parser; for (int j = 0; j < outputNames.size(); j++) {    m->mothurRemove(outputNames[j]);        }  return 0;    }                               
615                     map<string, string> uniqueNames = parser->getAllSeqsMap();
616                     if (!dups) { 
617                         numChimeras = deconvoluteResults(uniqueNames, outputFileName, accnosFileName);
618                     }
619                     delete parser;
620                     
621                     m->mothurOut("The number of sequences checked may be larger than the number of unique sequences because some sequences are found in several samples."); m->mothurOutEndLine(); 
622                     
623                     if (m->control_pressed) {  for (int j = 0; j < outputNames.size(); j++) {   m->mothurRemove(outputNames[j]);        }  return 0;  }         
624                 }else{
625                     if (processors != 1) { m->mothurOut("Without a groupfile, mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
626                     
627                     //read sequences and store sorted by frequency
628                     vector<seqData> sequences = readFiles(fastaFileNames[s], nameFile);
629                     
630                     if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {    m->mothurRemove(outputNames[j]);        } return 0; }
631                     
632                     numSeqs = driver(outputFileName, sequences, accnosFileName, numChimeras); 
633                 }
634                         }
635             
636                         if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {        m->mothurRemove(outputNames[j]);        } return 0; }
637                         
638                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences. " + toString(numChimeras) + " chimeras were found.");      m->mothurOutEndLine();
639                         outputNames.push_back(outputFileName); outputTypes["chimera"].push_back(outputFileName);
640                         outputNames.push_back(accnosFileName); outputTypes["accnos"].push_back(accnosFileName);
641                 }
642                 
643                 //set accnos file as new current accnosfile
644                 string current = "";
645                 itTypes = outputTypes.find("accnos");
646                 if (itTypes != outputTypes.end()) {
647                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setAccnosFile(current); }
648                 }
649         
650         itTypes = outputTypes.find("count");
651                 if (itTypes != outputTypes.end()) {
652                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
653                 }
654                 
655                 m->mothurOutEndLine();
656                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
657                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
658                 m->mothurOutEndLine();
659                 
660                 return 0;
661                 
662         }
663         catch(exception& e) {
664                 m->errorOut(e, "ChimeraPerseusCommand", "execute");
665                 exit(1);
666         }
667 }
668 //**********************************************************************************************************************
669 string ChimeraPerseusCommand::getNamesFile(string& inputFile){
670         try {
671                 string nameFile = "";
672                 
673                 m->mothurOutEndLine(); m->mothurOut("No namesfile given, running unique.seqs command to generate one."); m->mothurOutEndLine(); m->mothurOutEndLine();
674                 
675                 //use unique.seqs to create new name and fastafile
676                 string inputString = "fasta=" + inputFile;
677                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
678                 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
679                 m->mothurCalling = true;
680         
681                 Command* uniqueCommand = new DeconvoluteCommand(inputString);
682                 uniqueCommand->execute();
683                 
684                 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
685                 
686                 delete uniqueCommand;
687                 m->mothurCalling = false;
688                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
689                 
690                 nameFile = filenames["name"][0];
691                 inputFile = filenames["fasta"][0];
692                 
693                 return nameFile;
694         }
695         catch(exception& e) {
696                 m->errorOut(e, "ChimeraPerseusCommand", "getNamesFile");
697                 exit(1);
698         }
699 }
700 //**********************************************************************************************************************
701 int ChimeraPerseusCommand::driverGroups(string outputFName, string accnos, string countlist, int start, int end, vector<string> groups){
702         try {
703                 
704                 int totalSeqs = 0;
705                 int numChimeras = 0;
706         
707         ofstream outCountList;
708         if (hasCount && dups) { m->openOutputFile(countlist, outCountList); }
709                 
710                 for (int i = start; i < end; i++) {
711                         
712                         m->mothurOutEndLine(); m->mothurOut("Checking sequences from group " + groups[i] + "...");      m->mothurOutEndLine();                                  
713                         
714                         int start = time(NULL);  if (m->control_pressed) {  return 0; }
715                         
716                         vector<seqData> sequences = loadSequences(groups[i]);
717                         
718                         if (m->control_pressed) { return 0; }
719                         
720                         int numSeqs = driver((outputFName + groups[i]), sequences, (accnos+groups[i]), numChimeras);
721                         totalSeqs += numSeqs;
722                         
723                         if (m->control_pressed) { return 0; }
724             
725             if (dups) {
726                 if (!m->isBlank(accnos+groups[i])) {
727                     ifstream in;
728                     m->openInputFile(accnos+groups[i], in);
729                     string name;
730                     if (hasCount) {
731                         while (!in.eof()) {
732                             in >> name; m->gobble(in);
733                             outCountList << name << '\t' << groups[i] << endl;
734                         }
735                         in.close();
736                     }else {
737                         map<string, string> thisnamemap = parser->getNameMap(groups[i]);
738                         map<string, string>::iterator itN;
739                         ofstream out;
740                         m->openOutputFile(accnos+groups[i]+".temp", out);
741                         while (!in.eof()) {
742                             in >> name; m->gobble(in);
743                             itN = thisnamemap.find(name);
744                             if (itN != thisnamemap.end()) {
745                                 vector<string> tempNames; m->splitAtComma(itN->second, tempNames);
746                                 for (int j = 0; j < tempNames.size(); j++) { out << tempNames[j] << endl; }
747                                 
748                             }else { m->mothurOut("[ERROR]: parsing cannot find " + name + ".\n"); m->control_pressed = true; }
749                         }
750                         out.close();
751                         in.close();
752                         m->renameFile(accnos+groups[i]+".temp", accnos+groups[i]);
753                     }
754                     
755                 }
756             }
757                         
758                         //append files
759                         m->appendFiles((outputFName+groups[i]), outputFName); m->mothurRemove((outputFName+groups[i]));
760                         m->appendFiles((accnos+groups[i]), accnos); m->mothurRemove((accnos+groups[i]));
761                         
762                         m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences from group " + groups[i] + ".");    m->mothurOutEndLine();                                  
763                 }       
764                 
765         if (hasCount && dups) { outCountList.close(); }
766         
767                 return totalSeqs;
768                 
769         }
770         catch(exception& e) {
771                 m->errorOut(e, "ChimeraPerseusCommand", "driverGroups");
772                 exit(1);
773         }
774 }       
775 //**********************************************************************************************************************
776 vector<seqData> ChimeraPerseusCommand::loadSequences(string group){
777         try {
778         bool error = false;
779                 alignLength = 0;
780         vector<seqData> sequences;
781         if (hasCount) {
782             vector<Sequence> thisGroupsSeqs = cparser->getSeqs(group);
783             map<string, int> counts = cparser->getCountTable(group);
784             map<string, int>::iterator it;
785             
786             for (int i = 0; i < thisGroupsSeqs.size(); i++) {
787                 
788                 if (m->control_pressed) {  return sequences; }
789                 
790                 it = counts.find(thisGroupsSeqs[i].getName());
791                 if (it == counts.end()) { error = true; m->mothurOut("[ERROR]: " + thisGroupsSeqs[i].getName() + " is in your fasta file and not in your count file, please correct."); m->mothurOutEndLine(); }
792                 else {
793                     thisGroupsSeqs[i].setAligned(removeNs(thisGroupsSeqs[i].getUnaligned()));
794                     sequences.push_back(seqData(thisGroupsSeqs[i].getName(), thisGroupsSeqs[i].getUnaligned(), it->second));
795                     if (thisGroupsSeqs[i].getUnaligned().length() > alignLength) { alignLength = thisGroupsSeqs[i].getUnaligned().length(); }
796                 }
797             }
798         }else{
799             vector<Sequence> thisGroupsSeqs = parser->getSeqs(group);
800             map<string, string> nameMap = parser->getNameMap(group);
801             map<string, string>::iterator it;
802            
803             for (int i = 0; i < thisGroupsSeqs.size(); i++) {
804                 
805                 if (m->control_pressed) {  return sequences; }
806                 
807                 it = nameMap.find(thisGroupsSeqs[i].getName());
808                 if (it == nameMap.end()) { error = true; m->mothurOut("[ERROR]: " + thisGroupsSeqs[i].getName() + " is in your fasta file and not in your namefile, please correct."); m->mothurOutEndLine(); }
809                 else {
810                     int num = m->getNumNames(it->second);
811                     thisGroupsSeqs[i].setAligned(removeNs(thisGroupsSeqs[i].getUnaligned()));
812                     sequences.push_back(seqData(thisGroupsSeqs[i].getName(), thisGroupsSeqs[i].getUnaligned(), num));
813                     if (thisGroupsSeqs[i].getUnaligned().length() > alignLength) { alignLength = thisGroupsSeqs[i].getUnaligned().length(); }
814                 }
815             }
816             
817                 }
818                 
819         if (error) { m->control_pressed = true; }
820                 //sort by frequency
821                 sort(sequences.rbegin(), sequences.rend());
822                 
823                 return sequences;
824         }
825         catch(exception& e) {
826                 m->errorOut(e, "ChimeraPerseusCommand", "loadSequences");
827                 exit(1);
828         }
829 }
830
831 //**********************************************************************************************************************
832 vector<seqData> ChimeraPerseusCommand::readFiles(string inputFile, string name){
833         try {
834                 map<string, int>::iterator it;
835                 map<string, int> nameMap = m->readNames(name);
836                 
837                 //read fasta file and create sequenceData structure - checking for file mismatches
838                 vector<seqData> sequences;
839                 bool error = false;
840                 ifstream in;
841                 m->openInputFile(inputFile, in);
842                 alignLength = 0;
843         
844                 while (!in.eof()) {
845                         
846                         if (m->control_pressed) { in.close(); return sequences; }
847                         
848                         Sequence temp(in); m->gobble(in);
849                         
850                         it = nameMap.find(temp.getName());
851                         if (it == nameMap.end()) { error = true; m->mothurOut("[ERROR]: " + temp.getName() + " is in your fasta file and not in your namefile, please correct."); m->mothurOutEndLine(); }
852                         else {
853                 temp.setAligned(removeNs(temp.getUnaligned()));
854                                 sequences.push_back(seqData(temp.getName(), temp.getUnaligned(), it->second));
855                 if (temp.getUnaligned().length() > alignLength) { alignLength = temp.getUnaligned().length(); }
856                         }
857                 }
858                 in.close();
859                 
860                 if (error) { m->control_pressed = true; }
861                 
862                 //sort by frequency
863                 sort(sequences.rbegin(), sequences.rend());
864                 
865                 return sequences;
866         }
867         catch(exception& e) {
868                 m->errorOut(e, "ChimeraPerseusCommand", "readFiles");
869                 exit(1);
870         }
871 }
872 //**********************************************************************************************************************
873 string ChimeraPerseusCommand::removeNs(string seq){
874         try {
875         string newSeq = "";
876         for (int i = 0; i < seq.length(); i++) {
877             if (seq[i] != 'N') {  newSeq += seq[i]; }
878         }
879         return newSeq;
880     }
881         catch(exception& e) {
882                 m->errorOut(e, "ChimeraPerseusCommand", "removeNs");
883                 exit(1);
884         }
885 }
886 //**********************************************************************************************************************
887 vector<seqData> ChimeraPerseusCommand::readFiles(string inputFile, CountTable* ct){
888         try {           
889                 //read fasta file and create sequenceData structure - checking for file mismatches
890                 vector<seqData> sequences;
891                 ifstream in;
892                 m->openInputFile(inputFile, in);
893                 alignLength = 0;
894         
895                 while (!in.eof()) {
896             Sequence temp(in); m->gobble(in);
897                         
898                         int count = ct->getNumSeqs(temp.getName());
899                         if (m->control_pressed) { break; }
900                         else {
901                 temp.setAligned(removeNs(temp.getUnaligned()));
902                                 sequences.push_back(seqData(temp.getName(), temp.getUnaligned(), count));
903                 if (temp.getUnaligned().length() > alignLength) { alignLength = temp.getUnaligned().length(); }
904                         }
905                 }
906                 in.close();
907                 
908                 //sort by frequency
909                 sort(sequences.rbegin(), sequences.rend());
910                 
911                 return sequences;
912         }
913         catch(exception& e) {
914                 m->errorOut(e, "ChimeraPerseusCommand", "getNamesFile");
915                 exit(1);
916         }
917 }
918 //**********************************************************************************************************************
919 int ChimeraPerseusCommand::driver(string chimeraFileName, vector<seqData>& sequences, string accnosFileName, int& numChimeras){
920         try {
921                 
922                 vector<vector<double> > correctModel(4);        //could be an option in the future to input own model matrix
923                 for(int i=0;i<4;i++){   correctModel[i].resize(4);      }
924                 
925                 correctModel[0][0] = 0.000000;  //AA
926                 correctModel[1][0] = 11.619259; //CA
927                 correctModel[2][0] = 11.694004; //TA
928                 correctModel[3][0] = 7.748623;  //GA
929                 
930                 correctModel[1][1] = 0.000000;  //CC
931                 correctModel[2][1] = 7.619657;  //TC
932                 correctModel[3][1] = 12.852562; //GC
933                 
934                 correctModel[2][2] = 0.000000;  //TT
935                 correctModel[3][2] = 10.964048; //TG
936                 
937                 correctModel[3][3] = 0.000000;  //GG
938                 
939                 for(int i=0;i<4;i++){
940                         for(int j=0;j<i;j++){
941                                 correctModel[j][i] = correctModel[i][j];
942                         }
943                 }
944                 
945                 int numSeqs = sequences.size();
946                 //int alignLength = sequences[0].sequence.size();
947                 
948                 ofstream chimeraFile;
949                 ofstream accnosFile;
950                 m->openOutputFile(chimeraFileName, chimeraFile); 
951                 m->openOutputFile(accnosFileName, accnosFile); 
952                 
953                 Perseus myPerseus;
954                 vector<vector<double> > binMatrix = myPerseus.binomial(alignLength);
955                 
956                 chimeraFile << "SequenceIndex\tName\tDiffsToBestMatch\tBestMatchIndex\tBestMatchName\tDiffstToChimera\tIndexofLeftParent\tIndexOfRightParent\tNameOfLeftParent\tNameOfRightParent\tDistanceToBestMatch\tcIndex\t(cIndex - singleDist)\tloonIndex\tMismatchesToChimera\tMismatchToTrimera\tChimeraBreakPoint\tLogisticProbability\tTypeOfSequence\n";
957                 
958                 vector<bool> chimeras(numSeqs, 0);
959                 
960                 for(int i=0;i<numSeqs;i++){     
961                         if (m->control_pressed) { chimeraFile.close(); m->mothurRemove(chimeraFileName); accnosFile.close(); m->mothurRemove(accnosFileName); return 0; }
962     
963                         vector<bool> restricted = chimeras;
964                         
965                         vector<vector<int> > leftDiffs(numSeqs);
966                         vector<vector<int> > leftMaps(numSeqs);
967                         vector<vector<int> > rightDiffs(numSeqs);
968                         vector<vector<int> > rightMaps(numSeqs);
969                         
970                         vector<int> singleLeft, bestLeft;
971                         vector<int> singleRight, bestRight;
972                         
973                         int bestSingleIndex, bestSingleDiff;
974                         vector<pwAlign> alignments(numSeqs);
975                         
976                         int comparisons = myPerseus.getAlignments(i, sequences, alignments, leftDiffs, leftMaps, rightDiffs, rightMaps, bestSingleIndex, bestSingleDiff, restricted);
977                         if (m->control_pressed) { chimeraFile.close(); m->mothurRemove(chimeraFileName); accnosFile.close(); m->mothurRemove(accnosFileName); return 0; }
978
979                         int minMismatchToChimera, leftParentBi, rightParentBi, breakPointBi;
980                         
981                         string dummyA, dummyB;
982                         
983             if (sequences[i].sequence.size() < 3) { 
984                 chimeraFile << i << '\t' << sequences[i].seqName << "\t0\t0\tNull\t0\t0\t0\tNull\tNull\t0.0\t0.0\t0.0\t0\t0\t0\t0.0\t0.0\tgood" << endl;
985             }else if(comparisons >= 2){ 
986                                 minMismatchToChimera = myPerseus.getChimera(sequences, leftDiffs, rightDiffs, leftParentBi, rightParentBi, breakPointBi, singleLeft, bestLeft, singleRight, bestRight, restricted);
987                                 if (m->control_pressed) { chimeraFile.close(); m->mothurRemove(chimeraFileName); accnosFile.close(); m->mothurRemove(accnosFileName); return 0; }
988
989                                 int minMismatchToTrimera = numeric_limits<int>::max();
990                                 int leftParentTri, middleParentTri, rightParentTri, breakPointTriA, breakPointTriB;
991                                 
992                                 if(minMismatchToChimera >= 3 && comparisons >= 3){
993                                         minMismatchToTrimera = myPerseus.getTrimera(sequences, leftDiffs, leftParentTri, middleParentTri, rightParentTri, breakPointTriA, breakPointTriB, singleLeft, bestLeft, singleRight, bestRight, restricted);
994                                         if (m->control_pressed) { chimeraFile.close(); m->mothurRemove(chimeraFileName); accnosFile.close(); m->mothurRemove(accnosFileName); return 0; }
995                                 }
996                                 
997                                 double singleDist = myPerseus.modeledPairwiseAlignSeqs(sequences[i].sequence, sequences[bestSingleIndex].sequence, dummyA, dummyB, correctModel);
998                                 
999                                 if (m->control_pressed) { chimeraFile.close(); m->mothurRemove(chimeraFileName); accnosFile.close(); m->mothurRemove(accnosFileName); return 0; }
1000
1001                                 string type;
1002                                 string chimeraRefSeq;
1003                                 
1004                                 if(minMismatchToChimera - minMismatchToTrimera >= 3){
1005                                         type = "trimera";
1006                                         chimeraRefSeq = myPerseus.stitchTrimera(alignments, leftParentTri, middleParentTri, rightParentTri, breakPointTriA, breakPointTriB, leftMaps, rightMaps);
1007                                 }
1008                                 else{
1009                                         type = "chimera";
1010                                         chimeraRefSeq = myPerseus.stitchBimera(alignments, leftParentBi, rightParentBi, breakPointBi, leftMaps, rightMaps);
1011                                 }
1012
1013                 if (m->control_pressed) { chimeraFile.close(); m->mothurRemove(chimeraFileName); accnosFile.close(); m->mothurRemove(accnosFileName); return 0; }
1014                                 
1015                                 double chimeraDist = myPerseus.modeledPairwiseAlignSeqs(sequences[i].sequence, chimeraRefSeq, dummyA, dummyB, correctModel);
1016                                 
1017                                 if (m->control_pressed) { chimeraFile.close(); m->mothurRemove(chimeraFileName); accnosFile.close(); m->mothurRemove(accnosFileName); return 0; }
1018
1019                                 double cIndex = chimeraDist;//modeledPairwiseAlignSeqs(sequences[i].sequence, chimeraRefSeq);
1020                                 double loonIndex = myPerseus.calcLoonIndex(sequences[i].sequence, sequences[leftParentBi].sequence, sequences[rightParentBi].sequence, breakPointBi, binMatrix);                
1021                                 
1022                                 if (m->control_pressed) { chimeraFile.close(); m->mothurRemove(chimeraFileName); accnosFile.close(); m->mothurRemove(accnosFileName); return 0; }
1023
1024                                 chimeraFile << i << '\t' << sequences[i].seqName << '\t' << bestSingleDiff << '\t' << bestSingleIndex << '\t' << sequences[bestSingleIndex].seqName << '\t';
1025                                 chimeraFile << minMismatchToChimera << '\t' << leftParentBi << '\t' << rightParentBi << '\t' << sequences[leftParentBi].seqName << '\t' << sequences[rightParentBi].seqName << '\t';
1026                                 chimeraFile << singleDist << '\t' << cIndex << '\t' << (cIndex - singleDist) << '\t' << loonIndex << '\t';
1027                                 chimeraFile << minMismatchToChimera << '\t' << minMismatchToTrimera << '\t' << breakPointBi << '\t';
1028                                 
1029                                 double probability = myPerseus.classifyChimera(singleDist, cIndex, loonIndex, alpha, beta);
1030                                 
1031                                 chimeraFile << probability << '\t';
1032                                 
1033                                 if(probability > cutoff){ 
1034                                         chimeraFile << type << endl;
1035                                         accnosFile << sequences[i].seqName << endl;
1036                                         chimeras[i] = 1;
1037                                         numChimeras++;
1038                                 }
1039                                 else{
1040                                         chimeraFile << "good" << endl;
1041                                 }
1042                                 
1043                         }
1044                         else{
1045                                 chimeraFile << i << '\t' << sequences[i].seqName << "\t0\t0\tNull\t0\t0\t0\tNull\tNull\t0.0\t0.0\t0.0\t0\t0\t0\t0.0\t0.0\tgood" << endl;
1046                         }
1047         
1048                         //report progress
1049                         if((i+1) % 100 == 0){   m->mothurOutJustToScreen("Processing sequence: " + toString(i+1) + "\n");               }
1050                 }
1051                 
1052                 if((numSeqs) % 100 != 0){       m->mothurOutJustToScreen("Processing sequence: " + toString(numSeqs) + "\n");           }
1053                 
1054                 chimeraFile.close();
1055                 accnosFile.close();
1056                 
1057                 return numSeqs;
1058         }
1059         catch(exception& e) {
1060                 m->errorOut(e, "ChimeraPerseusCommand", "driver");
1061                 exit(1);
1062         }
1063 }
1064 /**************************************************************************************************/
1065 int ChimeraPerseusCommand::createProcessesGroups(string outputFName, string accnos, string newCountFile, vector<string> groups, string group, string fasta, string name) {
1066         try {
1067                 
1068                 vector<int> processIDS;
1069                 int process = 1;
1070                 int num = 0;
1071                 
1072         CountTable newCount;
1073         if (hasCount && dups) { newCount.readTable(name, true); }
1074         
1075                 //sanity check
1076                 if (groups.size() < processors) { processors = groups.size(); }
1077                 
1078                 //divide the groups between the processors
1079                 vector<linePair> lines;
1080                 int numGroupsPerProcessor = groups.size() / processors;
1081                 for (int i = 0; i < processors; i++) {
1082                         int startIndex =  i * numGroupsPerProcessor;
1083                         int endIndex = (i+1) * numGroupsPerProcessor;
1084                         if(i == (processors - 1)){      endIndex = groups.size();       }
1085                         lines.push_back(linePair(startIndex, endIndex));
1086                 }
1087                 
1088 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)          
1089                 
1090                 //loop through and create all the processes you want
1091                 while (process != processors) {
1092                         int pid = fork();
1093                         
1094                         if (pid > 0) {
1095                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
1096                                 process++;
1097                         }else if (pid == 0){
1098                                 num = driverGroups(outputFName + toString(getpid()) + ".temp", accnos + toString(getpid()) + ".temp", accnos + ".byCount." + toString(getpid()) + ".temp", lines[process].start, lines[process].end, groups);
1099                                 
1100                                 //pass numSeqs to parent
1101                                 ofstream out;
1102                                 string tempFile = outputFName + toString(getpid()) + ".num.temp";
1103                                 m->openOutputFile(tempFile, out);
1104                                 out << num << endl;
1105                                 out.close();
1106                                 
1107                                 exit(0);
1108                         }else { 
1109                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
1110                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
1111                                 exit(0);
1112                         }
1113                 }
1114                 
1115                 //do my part
1116                 num = driverGroups(outputFName, accnos, accnos + ".byCount", lines[0].start, lines[0].end, groups);
1117                 
1118                 //force parent to wait until all the processes are done
1119                 for (int i=0;i<processIDS.size();i++) { 
1120                         int temp = processIDS[i];
1121                         wait(&temp);
1122                 }
1123                 
1124                 for (int i = 0; i < processIDS.size(); i++) {
1125                         ifstream in;
1126                         string tempFile =  outputFName + toString(processIDS[i]) + ".num.temp";
1127                         m->openInputFile(tempFile, in);
1128                         if (!in.eof()) { int tempNum = 0; in >> tempNum; num += tempNum; }
1129                         in.close(); m->mothurRemove(tempFile);
1130                 }
1131                 
1132 #else
1133                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1134                 //Windows version shared memory, so be careful when passing variables through the preClusterData struct. 
1135                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
1136                 //////////////////////////////////////////////////////////////////////////////////////////////////////
1137                 
1138                 vector<perseusData*> pDataArray; 
1139                 DWORD   dwThreadIdArray[processors-1];
1140                 HANDLE  hThreadArray[processors-1]; 
1141                 
1142                 //Create processor worker threads.
1143                 for( int i=1; i<processors; i++ ){
1144                         // Allocate memory for thread data.
1145                         string extension = toString(i) + ".temp";
1146                         
1147                         perseusData* tempPerseus = new perseusData(dups, hasName, hasCount, alpha, beta, cutoff, outputFName+extension, fasta, name, group, accnos+extension,  accnos+".byCount."+extension, groups, m, lines[i].start, lines[i].end, i);
1148                         
1149                         pDataArray.push_back(tempPerseus);
1150                         processIDS.push_back(i);
1151                         
1152                         //MyPerseusThreadFunction is in header. It must be global or static to work with the threads.
1153                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
1154                         hThreadArray[i-1] = CreateThread(NULL, 0, MyPerseusThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
1155                 }
1156                 
1157                 
1158                 //using the main process as a worker saves time and memory
1159                 num = driverGroups(outputFName, accnos, accnos + ".byCount", lines[0].start, lines[0].end, groups);
1160                 
1161                 //Wait until all threads have terminated.
1162                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
1163                         
1164                 //Close all thread handles and free memory allocations.
1165                 for(int i=0; i < pDataArray.size(); i++){
1166                         num += pDataArray[i]->count;
1167                         CloseHandle(hThreadArray[i]);
1168                         delete pDataArray[i];
1169                 }
1170 #endif          
1171                 //read my own
1172         if (hasCount && dups) {
1173             if (!m->isBlank(accnos + ".byCount")) {
1174                 ifstream in2;
1175                 m->openInputFile(accnos + ".byCount", in2);
1176                 
1177                 string name, group;
1178                 while (!in2.eof()) {
1179                     in2 >> name >> group; m->gobble(in2);
1180                     newCount.setAbund(name, group, 0);
1181                 }
1182                 in2.close();
1183             }
1184             m->mothurRemove(accnos + ".byCount");
1185         }
1186
1187                 
1188                 //append output files
1189                 for(int i=0;i<processIDS.size();i++){
1190                         m->appendFiles((outputFName + toString(processIDS[i]) + ".temp"), outputFName);
1191                         m->mothurRemove((outputFName + toString(processIDS[i]) + ".temp"));
1192                         
1193                         m->appendFiles((accnos + toString(processIDS[i]) + ".temp"), accnos);
1194                         m->mothurRemove((accnos + toString(processIDS[i]) + ".temp"));
1195             
1196             if (hasCount && dups) {
1197                 if (!m->isBlank(accnos + ".byCount." + toString(processIDS[i]) + ".temp")) {
1198                     ifstream in2;
1199                     m->openInputFile(accnos + ".byCount." + toString(processIDS[i]) + ".temp", in2);
1200                     
1201                     string name, group;
1202                     while (!in2.eof()) {
1203                         in2 >> name >> group; m->gobble(in2);
1204                         newCount.setAbund(name, group, 0);
1205                     }
1206                     in2.close();
1207                 }
1208                 m->mothurRemove(accnos + ".byCount." + toString(processIDS[i]) + ".temp");
1209             }
1210
1211                 }
1212                 
1213         //print new *.pick.count_table
1214         if (hasCount && dups) {  newCount.printTable(newCountFile);   }
1215
1216                 return num;     
1217                 
1218         }
1219         catch(exception& e) {
1220                 m->errorOut(e, "ChimeraPerseusCommand", "createProcessesGroups");
1221                 exit(1);
1222         }
1223 }
1224 //**********************************************************************************************************************
1225 int ChimeraPerseusCommand::deconvoluteResults(map<string, string>& uniqueNames, string outputFileName, string accnosFileName){
1226         try {
1227                 map<string, string>::iterator itUnique;
1228                 int total = 0;
1229                 
1230                 //edit accnos file
1231                 ifstream in2; 
1232                 m->openInputFile(accnosFileName, in2);
1233                 
1234                 ofstream out2;
1235                 m->openOutputFile(accnosFileName+".temp", out2);
1236                 
1237                 string name;
1238                 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
1239                 set<string>::iterator itNames;
1240                 set<string> chimerasInFile;
1241                 set<string>::iterator itChimeras;
1242                 
1243                 
1244                 while (!in2.eof()) {
1245                         if (m->control_pressed) { in2.close(); out2.close(); m->mothurRemove(outputFileName); m->mothurRemove((accnosFileName+".temp")); return 0; }
1246                         
1247                         in2 >> name; m->gobble(in2);
1248                         
1249                         //find unique name
1250                         itUnique = uniqueNames.find(name);
1251                         
1252                         if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing accnos results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1253                         else {
1254                                 itChimeras = chimerasInFile.find((itUnique->second));
1255                                 
1256                                 if (itChimeras == chimerasInFile.end()) {
1257                                         out2 << itUnique->second << endl;
1258                                         chimerasInFile.insert((itUnique->second));
1259                                         total++;
1260                                 }
1261                         }
1262                 }
1263                 in2.close();
1264                 out2.close();
1265                 
1266                 m->mothurRemove(accnosFileName);
1267                 rename((accnosFileName+".temp").c_str(), accnosFileName.c_str());
1268                 
1269                 //edit chimera file
1270                 ifstream in; 
1271                 m->openInputFile(outputFileName, in);
1272                 
1273                 ofstream out;
1274                 m->openOutputFile(outputFileName+".temp", out); out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
1275                 
1276                 int DiffsToBestMatch, BestMatchIndex, DiffstToChimera, IndexofLeftParent, IndexOfRightParent;
1277                 float temp1,temp2, temp3, temp4, temp5, temp6, temp7, temp8;
1278                 string index, BestMatchName, parent1, parent2, flag;
1279                 name = "";
1280                 namesInFile.clear();    
1281                 //assumptions - in file each read will always look like 
1282                 /*                                                                              
1283                  SequenceIndex  Name    DiffsToBestMatch        BestMatchIndex  BestMatchName   DiffstToChimera IndexofLeftParent       IndexOfRightParent      NameOfLeftParent        NameOfRightParent       DistanceToBestMatch     cIndex  (cIndex - singleDist)   loonIndex       MismatchesToChimera     MismatchToTrimera       ChimeraBreakPoint       LogisticProbability     TypeOfSequence
1284                  0      F01QG4L02JVBQY  0       0       Null    0       0       0       Null    Null    0.0     0.0     0.0     0.0     0       0       0       0.0     0.0     good
1285                  1      F01QG4L02ICTC6  0       0       Null    0       0       0       Null    Null    0.0     0.0     0.0     0.0     0       0       0       0.0     0.0     good
1286                  2      F01QG4L02JZOEC  48      0       F01QG4L02JVBQY  47      0       0       F01QG4L02JVBQY  F01QG4L02JVBQY  2.0449  2.03545 -0.00944493     0       47      2147483647      138     0       good
1287                  3      F01QG4L02G7JEC  42      0       F01QG4L02JVBQY  40      1       0       F01QG4L02ICTC6  F01QG4L02JVBQY  1.87477 1.81113 -0.0636404      5.80145 40      2147483647      25      0       good
1288                  */
1289                 
1290                 //get and print headers
1291                 BestMatchName = m->getline(in); m->gobble(in);
1292                 out << BestMatchName << endl;
1293                 
1294                 while (!in.eof()) {
1295                         
1296                         if (m->control_pressed) { in.close(); out.close(); m->mothurRemove((outputFileName+".temp")); return 0; }
1297                         
1298                         bool print = false;
1299                         in >> index;    m->gobble(in);
1300                         
1301                         if (index != "SequenceIndex") { //if you are not a header line, there will be a header line for each group if group file is given
1302                                 in >> name;             m->gobble(in);
1303                                 in >> DiffsToBestMatch; m->gobble(in);
1304                                 in >> BestMatchIndex; m->gobble(in);
1305                                 in >> BestMatchName; m->gobble(in);
1306                                 in >> DiffstToChimera; m->gobble(in);
1307                                 in >> IndexofLeftParent; m->gobble(in);
1308                                 in >> IndexOfRightParent; m->gobble(in);
1309                                 in >> parent1;  m->gobble(in);
1310                                 in >> parent2;  m->gobble(in);
1311                                 in >> temp1 >> temp2 >> temp3 >> temp4 >> temp5 >> temp6 >> temp7 >> temp8 >> flag; m->gobble(in);
1312                                 
1313                                 //find unique name
1314                                 itUnique = uniqueNames.find(name);
1315                                 
1316                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find "+ name + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1317                                 else {
1318                                         name = itUnique->second;
1319                                         //is this name already in the file
1320                                         itNames = namesInFile.find((name));
1321                                         
1322                                         if (itNames == namesInFile.end()) { //no not in file
1323                                                 if (flag == "good") { //are you really a no??
1324                                                         //is this sequence really not chimeric??
1325                                                         itChimeras = chimerasInFile.find(name);
1326                                                         
1327                                                         //then you really are a no so print, otherwise skip
1328                                                         if (itChimeras == chimerasInFile.end()) { print = true; }
1329                                                 }else{ print = true; }
1330                                         }
1331                                 }
1332                                 
1333                                 if (print) {
1334                                         out << index << '\t' << name  << '\t' << DiffsToBestMatch << '\t' << BestMatchIndex << '\t';
1335                                         namesInFile.insert(name);
1336                                         
1337                                         if (BestMatchName != "Null") {
1338                                                 itUnique = uniqueNames.find(BestMatchName);
1339                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find BestMatchName "+ BestMatchName + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1340                                                 else {  out << itUnique->second << '\t';        }                                       
1341                                         }else { out << "Null" << '\t'; }
1342                                         
1343                                         out << DiffstToChimera << '\t' << IndexofLeftParent << '\t' << IndexOfRightParent << '\t';
1344                                         
1345                                         if (parent1 != "Null") {
1346                                                 itUnique = uniqueNames.find(parent1);
1347                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parent1 "+ parent1 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1348                                                 else {  out << itUnique->second << '\t';        }
1349                                         }else { out << "Null" << '\t'; }
1350                                         
1351                                         if (parent1 != "Null") {
1352                                                 itUnique = uniqueNames.find(parent2);
1353                                                 if (itUnique == uniqueNames.end()) { m->mothurOut("[ERROR]: trouble parsing chimera results. Cannot find parent2 "+ parent2 + "."); m->mothurOutEndLine(); m->control_pressed = true; }
1354                                                 else {  out << itUnique->second << '\t';        }
1355                                         }else { out << "Null" << '\t'; }
1356                                         
1357                                         out << temp1 << '\t' << temp2 << '\t' << temp3 << '\t' << temp4 << '\t' << temp5 << '\t' << temp6 << '\t' << temp7 << '\t' << temp8 << '\t' << flag << endl;    
1358                                 }
1359                         }else { index = m->getline(in); m->gobble(in); }
1360                 }
1361                 in.close();
1362                 out.close();
1363                 
1364                 m->mothurRemove(outputFileName);
1365                 rename((outputFileName+".temp").c_str(), outputFileName.c_str());
1366                 
1367                 return total;
1368         }
1369         catch(exception& e) {
1370                 m->errorOut(e, "ChimeraPerseusCommand", "deconvoluteResults");
1371                 exit(1);
1372         }
1373 }       
1374 //**********************************************************************************************************************
1375
1376