]> git.donarmstrong.com Git - mothur.git/blob - seqerrorcommand.cpp
update .gitignore
[mothur.git] / seqerrorcommand.cpp
1 /*
2  *  seqerrorcommand.cpp
3  *  Mothur
4  *
5  *  Created by Pat Schloss on 7/15/10.
6  *  Copyright 2010 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "seqerrorcommand.h"
11 #include "reportfile.h"
12 #include "qualityscores.h"
13 #include "refchimeratest.h"
14 #include "myPerseus.h"
15 #include "filterseqscommand.h"
16
17
18 //**********************************************************************************************************************
19
20 vector<string> SeqErrorCommand::setParameters(){        
21         try {
22                 CommandParameter pquery("fasta", "InputTypes", "", "", "none", "none", "none","errorType",false,true,true); parameters.push_back(pquery);
23                 CommandParameter preference("reference", "InputTypes", "", "", "none", "none", "none","",false,true,true); parameters.push_back(preference);
24                 CommandParameter pqfile("qfile", "InputTypes", "", "", "none", "none", "QualReport","",false,false); parameters.push_back(pqfile);
25                 CommandParameter preport("report", "InputTypes", "", "", "none", "none", "QualReport","",false,false); parameters.push_back(preport);
26                 CommandParameter pname("name", "InputTypes", "", "", "namecount", "none", "none","",false,false,true); parameters.push_back(pname);
27         CommandParameter pcount("count", "InputTypes", "", "", "namecount", "none", "none","",false,false,true); parameters.push_back(pcount);
28                 CommandParameter pignorechimeras("ignorechimeras", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(pignorechimeras);
29                 CommandParameter pthreshold("threshold", "Number", "", "1.0", "", "", "","",false,false); parameters.push_back(pthreshold);
30                 CommandParameter paligned("aligned", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(paligned);
31                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
32                 CommandParameter psave("save", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psave);
33                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
34                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
35                 
36                 vector<string> myArray;
37                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
38                 return myArray;
39         }
40         catch(exception& e) {
41                 m->errorOut(e, "SeqErrorCommand", "setParameters");
42                 exit(1);
43         }
44 }
45
46 //**********************************************************************************************************************
47
48 string SeqErrorCommand::getHelpString(){        
49         try {
50                 string helpString = "";
51                 helpString += "The seq.error command reads a query alignment file and a reference alignment file and creates .....\n";
52                 helpString += "The fasta parameter...\n";
53                 helpString += "The reference parameter...\n";
54                 helpString += "The qfile parameter...\n";
55                 helpString += "The report parameter...\n";
56                 helpString += "The name parameter allows you to provide a name file associated with the fasta file.\n";
57         helpString += "The count parameter allows you to provide a count file associated with the fasta file.\n";
58                 helpString += "The ignorechimeras parameter...\n";
59                 helpString += "The threshold parameter...\n";
60                 helpString += "The processors parameter...\n";
61                 helpString += "If the save parameter is set to true the reference sequences will be saved in memory, to clear them later you can use the clear.memory command. Default=f.";
62                 helpString += "Example seq.error(...).\n";
63                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
64                 helpString += "For more details please check out the wiki http://www.mothur.org/wiki/seq.error .\n";
65                 return helpString;
66         }
67         catch(exception& e) {
68                 m->errorOut(e, "SeqErrorCommand", "getHelpString");
69                 exit(1);
70         }
71 }
72
73 //**********************************************************************************************************************
74
75 string SeqErrorCommand::getOutputPattern(string type) {
76     try {
77         string pattern = "";
78         
79         if (type == "errorsummary")            {   pattern = "[filename],error.summary";   }
80         else if (type == "errorseq")            {   pattern = "[filename],error.seq";   }
81         else if (type == "errorquality")            {   pattern = "[filename],error.quality";   }
82         else if (type == "errorqualforward")            {   pattern = "[filename],error.qual.forward";   }
83         else if (type == "errorqualreverse")            {   pattern = "[filename],error.qual.reverse";   }
84         else if (type == "errorforward")            {   pattern = "[filename],error.seq.forward";   }
85         else if (type == "errorreverse")            {   pattern = "[filename],error.seq.reverse";   }
86         else if (type == "errorcount")            {   pattern = "[filename],error.count";   }
87         else if (type == "errormatrix")            {   pattern = "[filename],error.matrix";   }
88         else if (type == "errorchimera")            {   pattern = "[filename],error.chimera";   }
89         else if (type == "errorref-query")            {   pattern = "[filename],error.ref-query";   }
90         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
91         
92         return pattern;
93     }
94     catch(exception& e) {
95         m->errorOut(e, "SeqErrorCommand", "getOutputPattern");
96         exit(1);
97     }
98 }
99
100 //**********************************************************************************************************************
101
102 SeqErrorCommand::SeqErrorCommand(){     
103         try {
104                 abort = true; calledHelp = true; 
105                 setParameters();
106                 vector<string> tempOutNames;
107                 outputTypes["errorsummary"] = tempOutNames;
108                 outputTypes["errorseq"] = tempOutNames;
109                 outputTypes["errorquality"] = tempOutNames;
110                 outputTypes["errorqualforward"] = tempOutNames;
111                 outputTypes["errorqualreverse"] = tempOutNames;
112                 outputTypes["errorforward"] = tempOutNames;
113                 outputTypes["errorreverse"] = tempOutNames;
114                 outputTypes["errorcount"] = tempOutNames;
115                 outputTypes["errormatrix"] = tempOutNames;
116         outputTypes["errorchimera"] = tempOutNames;
117         outputTypes["errorref-query"] = tempOutNames;
118         }
119         catch(exception& e) {
120                 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
121                 exit(1);
122         }
123 }
124
125 //***************************************************************************************************************
126
127 SeqErrorCommand::SeqErrorCommand(string option)  {
128         try {
129                 
130                 abort = false; calledHelp = false;   
131                 rdb = ReferenceDB::getInstance();
132                 
133                 //allow user to run help
134                 if(option == "help") { help(); abort = true; calledHelp = true; }
135                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
136                 
137                 else {
138                         string temp;
139                         vector<string> myArray = setParameters();
140                         
141                         OptionParser parser(option);
142                         map<string,string> parameters = parser.getParameters();
143                         
144                         ValidParameters validParameter;
145                         map<string,string>::iterator it;
146                         
147                         //check to make sure all parameters are valid for command
148                         for (it = parameters.begin(); it != parameters.end(); it++) { 
149                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
150                         }
151                         
152                         //initialize outputTypes
153                         vector<string> tempOutNames;
154                         outputTypes["errorsummary"] = tempOutNames;
155                         outputTypes["errorseq"] = tempOutNames;
156                         outputTypes["errorquality"] = tempOutNames;
157                         outputTypes["errorqualforward"] = tempOutNames;
158                         outputTypes["errorqualreverse"] = tempOutNames;
159                         outputTypes["errorforward"] = tempOutNames;
160                         outputTypes["errorreverse"] = tempOutNames;
161                         outputTypes["errorcount"] = tempOutNames;
162                         outputTypes["errormatrix"] = tempOutNames;
163             outputTypes["errorchimera"] = tempOutNames;
164             outputTypes["errorref-query"] = tempOutNames;
165
166                         
167                         //if the user changes the input directory command factory will send this info to us in the output parameter 
168                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
169                         if (inputDir == "not found"){   inputDir = "";          }
170                         else {
171                                 string path;
172                                 it = parameters.find("fasta");
173                                 //user has given a template file
174                                 if(it != parameters.end()){ 
175                                         path = m->hasPath(it->second);
176                                         //if the user has not given a path then, add inputdir. else leave path alone.
177                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
178                                 }
179                                 
180                                 it = parameters.find("reference");
181                                 //user has given a template file
182                                 if(it != parameters.end()){ 
183                                         path = m->hasPath(it->second);
184                                         //if the user has not given a path then, add inputdir. else leave path alone.
185                                         if (path == "") {       parameters["reference"] = inputDir + it->second;                }
186                                 }
187                                 
188                                 it = parameters.find("name");
189                                 //user has given a names file
190                                 if(it != parameters.end()){ 
191                                         path = m->hasPath(it->second);
192                                         //if the user has not given a path then, add inputdir. else leave path alone.
193                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
194                                 }
195                 
196                 it = parameters.find("count");
197                                 //user has given a names file
198                                 if(it != parameters.end()){
199                                         path = m->hasPath(it->second);
200                                         //if the user has not given a path then, add inputdir. else leave path alone.
201                                         if (path == "") {       parameters["count"] = inputDir + it->second;            }
202                                 }
203
204                                 it = parameters.find("qfile");
205                                 //user has given a quality score file
206                                 if(it != parameters.end()){ 
207                                         path = m->hasPath(it->second);
208                                         //if the user has not given a path then, add inputdir. else leave path alone.
209                                         if (path == "") {       parameters["qfile"] = inputDir + it->second;            }
210                                 }
211                                 
212                                 it = parameters.find("report");
213                                 //user has given a alignment report file
214                                 if(it != parameters.end()){ 
215                                         path = m->hasPath(it->second);
216                                         //if the user has not given a path then, add inputdir. else leave path alone.
217                                         if (path == "") {       parameters["report"] = inputDir + it->second;           }
218                                 }
219                                 
220                         }
221                         //check for required parameters
222                         queryFileName = validParameter.validFile(parameters, "fasta", true);
223                         if (queryFileName == "not found") { 
224                                 queryFileName = m->getFastaFile(); 
225                                 if (queryFileName != "") { m->mothurOut("Using " + queryFileName + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
226                                 else {  m->mothurOut("You have no current fasta file and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
227                         }
228                         else if (queryFileName == "not open") { queryFileName = ""; abort = true; }     
229                         else { m->setFastaFile(queryFileName); }
230                         
231                         referenceFileName = validParameter.validFile(parameters, "reference", true);
232                         if (referenceFileName == "not found") { m->mothurOut("reference is a required parameter for the seq.error command."); m->mothurOutEndLine(); abort = true; }
233                         else if (referenceFileName == "not open") { abort = true; }     
234                         
235                         //check for optional parameters
236                         namesFileName = validParameter.validFile(parameters, "name", true);
237                         if(namesFileName == "not found"){       namesFileName = "";     }
238                         else if (namesFileName == "not open") { namesFileName = ""; abort = true; }     
239                         else { m->setNameFile(namesFileName); }
240             
241             //check for optional parameters
242                         countfile = validParameter.validFile(parameters, "count", true);
243                         if(countfile == "not found"){   countfile = ""; }
244                         else if (countfile == "not open") { countfile = ""; abort = true; }
245                         else { m->setCountTableFile(countfile); }
246                         
247                         qualFileName = validParameter.validFile(parameters, "qfile", true);
248                         if(qualFileName == "not found"){        qualFileName = "";      }
249                         else if (qualFileName == "not open") { qualFileName = ""; abort = true; }       
250                         else { m->setQualFile(qualFileName); }
251                         
252                         reportFileName = validParameter.validFile(parameters, "report", true);
253                         if(reportFileName == "not found"){      reportFileName = "";    }
254                         else if (reportFileName == "not open") { reportFileName = ""; abort = true; }   
255                         
256                         outputDir = validParameter.validFile(parameters, "outputdir", false);
257                         if (outputDir == "not found"){  
258                                 outputDir = ""; 
259                                 outputDir += m->hasPath(queryFileName); //if user entered a file with a path then preserve it   
260                         }
261                         
262             if ((countfile != "") && (namesFileName != "")) { m->mothurOut("You must enter ONLY ONE of the following: count or name."); m->mothurOutEndLine(); abort = true; }
263             
264                         //check for optional parameter and set defaults
265                         // ...at some point should added some additional type checking...
266                         temp = validParameter.validFile(parameters, "threshold", false);        if (temp == "not found") { temp = "1.00"; }
267                         m->mothurConvert(temp, threshold);  
268             
269                         
270                         temp = validParameter.validFile(parameters, "save", false);                     if (temp == "not found"){       temp = "f";                             }
271                         save = m->isTrue(temp); 
272                         rdb->save = save; 
273                         if (save) { //clear out old references
274                                 rdb->clearMemory();     
275                         }
276                         
277                         //this has to go after save so that if the user sets save=t and provides no reference we abort
278                         referenceFileName = validParameter.validFile(parameters, "reference", true);
279                         if (referenceFileName == "not found") { 
280                                 //check for saved reference sequences
281                                 if (rdb->referenceSeqs.size() != 0) {
282                                         referenceFileName = "saved";
283                                 }else {
284                                         m->mothurOut("[ERROR]: You don't have any saved reference sequences and the reference parameter is a required."); 
285                                         m->mothurOutEndLine();
286                                         abort = true; 
287                                 }
288                         }else if (referenceFileName == "not open") { abort = true; }    
289                         else {  if (save) {     rdb->setSavedReference(referenceFileName);      }       }
290                         
291                         
292                         temp = validParameter.validFile(parameters, "ignorechimeras", false);   if (temp == "not found") { temp = "T"; }
293                         ignoreChimeras = m->isTrue(temp);
294                         
295             temp = validParameter.validFile(parameters, "aligned", false);                      if (temp == "not found"){       temp = "t";                             }
296                         aligned = m->isTrue(temp); 
297
298                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
299                         m->setProcessors(temp);
300                         m->mothurConvert(temp, processors); 
301
302                         substitutionMatrix.resize(6);
303                         for(int i=0;i<6;i++){   substitutionMatrix[i].resize(6,0);      }
304                         
305                         if ((namesFileName == "") && (queryFileName != "")){
306                                 vector<string> files; files.push_back(queryFileName); 
307                                 parser.getNameFile(files);
308                         }
309
310             if(aligned == true){
311                 if((reportFileName != "" && qualFileName == "") || (reportFileName == "" && qualFileName != "")){
312                     m->mothurOut("if you use either a qual file or a report file, you have to have both.");
313                     m->mothurOutEndLine();
314                     abort = true; 
315                 }
316                         }
317             else{
318                 if(reportFileName != ""){
319                     m->mothurOut("we are ignoring the report file if your sequences are not aligned.  we will check that the sequences in your fasta and and qual file are the same length.");
320                     m->mothurOutEndLine();
321                 }
322             }
323             
324
325                 }
326         }
327         catch(exception& e) {
328                 m->errorOut(e, "SeqErrorCommand", "SeqErrorCommand");
329                 exit(1);
330         }
331 }
332
333 //***************************************************************************************************************
334
335 int SeqErrorCommand::execute(){
336         try{
337                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
338                 
339                 int start = time(NULL);
340                 maxLength = 5000;
341                 totalBases = 0;
342                 totalMatches = 0;
343                 
344         string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
345         map<string, string> variables; 
346                 variables["[filename]"] = fileNameRoot;
347                 string errorSummaryFileName = getOutputFileName("errorsummary",variables);
348                 outputNames.push_back(errorSummaryFileName); outputTypes["errorsummary"].push_back(errorSummaryFileName);
349                         
350                 string errorSeqFileName = getOutputFileName("errorseq",variables);
351                 outputNames.push_back(errorSeqFileName); outputTypes["errorseq"].push_back(errorSeqFileName);
352                 
353                 string errorChimeraFileName = getOutputFileName("errorchimera",variables);
354                 outputNames.push_back(errorChimeraFileName); outputTypes["errorchimera"].push_back(errorChimeraFileName);
355                 
356                 getReferences();        //read in reference sequences - make sure there's no ambiguous bases
357
358                 if(namesFileName != "")     {   weights = getWeights();         }
359         else if (countfile != "")   {
360             CountTable ct;
361             ct.readTable(countfile, false, false);
362             weights = ct.getNameMap();
363         }
364                 
365                 vector<unsigned long long> fastaFilePos;
366                 vector<unsigned long long> qFilePos;
367                 vector<unsigned long long> reportFilePos;
368                 
369                 setLines(queryFileName, qualFileName, reportFileName, fastaFilePos, qFilePos, reportFilePos);
370                 
371                 if (m->control_pressed) { return 0; }
372                 
373                 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
374                         lines.push_back(linePair(fastaFilePos[i], fastaFilePos[(i+1)]));
375                         if (qualFileName != "") {  qLines.push_back(linePair(qFilePos[i], qFilePos[(i+1)]));  }
376                         if (reportFileName != "" && aligned == true) {  rLines.push_back(linePair(reportFilePos[i], reportFilePos[(i+1)]));  }
377                 }       
378                 if(qualFileName == "")  {       qLines = lines; rLines = lines; } //fills with duds
379         if(aligned == false){   rLines = lines; }
380                 int numSeqs = 0;
381 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
382                 if(processors == 1){
383                         numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
384             
385                 }else{
386                         numSeqs = createProcesses(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName);
387                 }       
388 #else
389                 numSeqs = driver(queryFileName, qualFileName, reportFileName, errorSummaryFileName, errorSeqFileName, errorChimeraFileName, lines[0], qLines[0], rLines[0]);
390 #endif
391
392                 if(qualFileName != ""){         
393                         printErrorQuality(qScoreErrorMap);
394                         printQualityFR(qualForwardMap, qualReverseMap);
395                 }
396                 
397                 printErrorFRFile(errorForward, errorReverse);
398                 
399                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
400
401                 string errorCountFileName = getOutputFileName("errorcount",variables);
402                 ofstream errorCountFile;
403                 m->openOutputFile(errorCountFileName, errorCountFile);
404                 outputNames.push_back(errorCountFileName);  outputTypes["errorcount"].push_back(errorCountFileName);
405                 m->mothurOut("Overall error rate:\t" + toString((double)(totalBases - totalMatches) / (double)totalBases) + "\n");
406                 m->mothurOut("Errors\tSequences\n");
407                 errorCountFile << "Errors\tSequences\n";                
408                 for(int i=0;i<misMatchCounts.size();i++){
409                         m->mothurOut(toString(i) + '\t' + toString(misMatchCounts[i]) + '\n');
410                         errorCountFile << i << '\t' << misMatchCounts[i] << endl;
411                 }
412                 errorCountFile.close();
413                 
414 //              if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
415
416                 printSubMatrix();
417         
418                 string megAlignmentFileName = getOutputFileName("errorref-query",variables);
419                 ofstream megAlignmentFile;
420                 m->openOutputFile(megAlignmentFileName, megAlignmentFile);
421                 outputNames.push_back(megAlignmentFileName);  outputTypes["errorref-query"].push_back(megAlignmentFileName);
422         
423                 for(int i=0;i<numRefs;i++){
424                         megAlignmentFile << referenceSeqs[i].getInlineSeq() << endl;
425                         megAlignmentFile << megaAlignVector[i] << endl;
426                 }
427         megAlignmentFile.close();
428         
429                 
430                 m->mothurOut("It took " + toString(time(NULL) - start) + " secs to check " + toString(numSeqs) + " sequences.");
431                 m->mothurOutEndLine();
432                 
433                 m->mothurOutEndLine();
434                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
435                 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
436                 m->mothurOutEndLine();
437                 
438                 return 0;       
439         }
440         catch(exception& e) {
441                 m->errorOut(e, "SeqErrorCommand", "execute");
442                 exit(1);
443         }
444 }
445
446 //**********************************************************************************************************************
447
448 int SeqErrorCommand::createProcesses(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName) {   
449         try {
450                 int process = 1;
451                 processIDS.clear();
452                 map<char, vector<int> >::iterator it;
453                 int num = 0;
454 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
455                 
456                 //loop through and create all the processes you want
457                 while (process != processors) {
458                         pid_t pid = fork();
459                         
460                         if (pid > 0) {
461                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
462                                 process++;
463                         }else if (pid == 0){
464                                 
465                                 num = driver(filename, qFileName, rFileName, summaryFileName + m->mothurGetpid(process) + ".temp", errorOutputFileName+ m->mothurGetpid(process) + ".temp", chimeraOutputFileName + m->mothurGetpid(process) + ".temp", lines[process], qLines[process], rLines[process]);
466                                 
467                                 //pass groupCounts to parent
468                                 ofstream out;
469                                 string tempFile = filename + m->mothurGetpid(process) + ".info.temp";
470                                 m->openOutputFile(tempFile, out);
471                                 
472                                 //output totalBases and totalMatches
473                                 out << num << '\t' << totalBases << '\t' << totalMatches << endl << endl;
474                                 
475                                 //output substitutionMatrix
476                                 for(int i = 0; i < substitutionMatrix.size(); i++) {
477                                         for (int j = 0; j < substitutionMatrix[i].size(); j++) {
478                                                 out << substitutionMatrix[i][j] << '\t';
479                                         }
480                                         out << endl;
481                                 }
482                                 out << endl;
483                                 
484                                 //output qScoreErrorMap
485                                 for (it = qScoreErrorMap.begin(); it != qScoreErrorMap.end(); it++) {
486                                         vector<int> thisScoreErrorMap = it->second;
487                                         out << it->first << '\t';
488                                         for (int i = 0; i < thisScoreErrorMap.size(); i++) {
489                                                 out << thisScoreErrorMap[i] << '\t';
490                                         }
491                                         out << endl;
492                                 }
493                                 out << endl;
494                                 
495                                 //output qualForwardMap
496                                 for(int i = 0; i < qualForwardMap.size(); i++) {
497                                         for (int j = 0; j < qualForwardMap[i].size(); j++) {
498                                                 out << qualForwardMap[i][j] << '\t';
499                                         }
500                                         out << endl;
501                                 }
502                                 out << endl;
503                                 
504                                 //output qualReverseMap
505                                 for(int i = 0; i < qualReverseMap.size(); i++) {
506                                         for (int j = 0; j < qualReverseMap[i].size(); j++) {
507                                                 out << qualReverseMap[i][j] << '\t';
508                                         }
509                                         out << endl;
510                                 }
511                                 out << endl;
512                                 
513                                 
514                                 //output errorForward
515                                 for (it = errorForward.begin(); it != errorForward.end(); it++) {
516                                         vector<int> thisErrorForward = it->second;
517                                         out << it->first << '\t';
518                                         for (int i = 0; i < thisErrorForward.size(); i++) {
519                                                 out << thisErrorForward[i] << '\t';
520                                         }
521                                         out << endl;
522                                 }
523                                 out << endl;
524                                 
525                                 //output errorReverse
526                                 for (it = errorReverse.begin(); it != errorReverse.end(); it++) {
527                                         vector<int> thisErrorReverse = it->second;
528                                         out << it->first << '\t';
529                                         for (int i = 0; i < thisErrorReverse.size(); i++) {
530                                                 out << thisErrorReverse[i] << '\t';
531                                         }
532                                         out << endl;
533                                 }
534                                 out << endl;
535                                 
536                                 //output misMatchCounts
537                                 out << misMatchCounts.size() << endl;
538                                 for (int j = 0; j < misMatchCounts.size(); j++) {
539                                         out << misMatchCounts[j] << '\t';
540                                 }
541                                 out << endl;
542                                 
543                                 
544                                 //output megaAlignVector
545                                 for (int j = 0; j < megaAlignVector.size(); j++) {
546                                         out << megaAlignVector[j] << endl;
547                                 }
548                                 out << endl;
549                                 
550                                 out.close();
551                                 
552                                 exit(0);
553                         }else { 
554                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
555                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
556                                 exit(0);
557                         }
558                 }
559                 
560                 //do my part
561                 num = driver(filename, qFileName, rFileName, summaryFileName, errorOutputFileName, chimeraOutputFileName, lines[0], qLines[0], rLines[0]);
562                 
563                 //force parent to wait until all the processes are done
564                 for (int i=0;i<processIDS.size();i++) { 
565                         int temp = processIDS[i];
566                         wait(&temp);
567                 }
568                 
569                 //append files
570                 for(int i=0;i<processIDS.size();i++){
571                         
572                         m->mothurOut("Appending files from process " + toString(processIDS[i])); m->mothurOutEndLine();
573                         
574                         m->appendFiles((summaryFileName + toString(processIDS[i]) + ".temp"), summaryFileName);
575                         m->mothurRemove((summaryFileName + toString(processIDS[i]) + ".temp"));
576                         m->appendFiles((errorOutputFileName + toString(processIDS[i]) + ".temp"), errorOutputFileName);
577                         m->mothurRemove((errorOutputFileName + toString(processIDS[i]) + ".temp"));
578                         m->appendFiles((chimeraOutputFileName + toString(processIDS[i]) + ".temp"), chimeraOutputFileName);
579                         m->mothurRemove((chimeraOutputFileName + toString(processIDS[i]) + ".temp"));
580                         
581                         ifstream in;
582                         string tempFile =  filename + toString(processIDS[i]) + ".info.temp";
583                         m->openInputFile(tempFile, in);
584                         
585                         //input totalBases and totalMatches
586                         int tempBases, tempMatches, tempNumSeqs;
587                         in >> tempNumSeqs >> tempBases >> tempMatches; m->gobble(in);
588                         totalBases += tempBases; totalMatches += tempMatches; num += tempNumSeqs;
589                         
590                         //input substitutionMatrix
591                         int tempNum;
592                         for(int i = 0; i < substitutionMatrix.size(); i++) {
593                                 for (int j = 0; j < substitutionMatrix[i].size(); j++) {
594                                         in >> tempNum; substitutionMatrix[i][j] += tempNum;
595                                 }
596                                 m->gobble(in);
597                         }
598                         m->gobble(in);
599                         
600                         //input qScoreErrorMap
601                         char first;
602                         for (int i = 0; i < qScoreErrorMap.size(); i++) {
603                                 in >> first;
604                                 vector<int> thisScoreErrorMap = qScoreErrorMap[first];
605                                 
606                                 for (int i = 0; i < thisScoreErrorMap.size(); i++) {
607                                         in >> tempNum; thisScoreErrorMap[i] += tempNum;
608                                 }
609                                 qScoreErrorMap[first] = thisScoreErrorMap;
610                                 m->gobble(in);
611                         }
612                         m->gobble(in);
613                         
614                         //input qualForwardMap
615                         for(int i = 0; i < qualForwardMap.size(); i++) {
616                                 for (int j = 0; j < qualForwardMap[i].size(); j++) {
617                                         in >> tempNum; qualForwardMap[i][j] += tempNum;
618                                 }
619                                 m->gobble(in);
620                         }
621                         m->gobble(in);
622                         
623                         //input qualReverseMap
624                         for(int i = 0; i < qualReverseMap.size(); i++) {
625                                 for (int j = 0; j < qualReverseMap[i].size(); j++) {
626                                         in >> tempNum; qualReverseMap[i][j] += tempNum;
627                                 }
628                                 m->gobble(in);
629                         }
630                         m->gobble(in);
631                         
632                         //input errorForward
633                         for (int i = 0; i < errorForward.size(); i++) {
634                                 in >> first;
635                                 vector<int> thisErrorForward = errorForward[first];
636                                 
637                                 for (int i = 0; i < thisErrorForward.size(); i++) {
638                                         in >> tempNum; thisErrorForward[i] += tempNum;
639                                 }
640                                 errorForward[first] = thisErrorForward;
641                                 m->gobble(in);
642                         }
643                         m->gobble(in);
644                         
645                         //input errorReverse
646                         for (int i = 0; i < errorReverse.size(); i++) {
647                                 in >> first;
648                                 vector<int> thisErrorReverse = errorReverse[first];
649                                 
650                                 for (int i = 0; i < thisErrorReverse.size(); i++) {
651                                         in >> tempNum; thisErrorReverse[i] += tempNum;
652                                 }
653                                 errorReverse[first] = thisErrorReverse;
654                                 m->gobble(in);
655                         }
656                         m->gobble(in);
657                         
658                         //input misMatchCounts
659                         int misMatchSize;
660                         in >> misMatchSize; m->gobble(in);
661                         if (misMatchSize > misMatchCounts.size()) {     misMatchCounts.resize(misMatchSize, 0); }
662                         for (int j = 0; j < misMatchSize; j++) {
663                                 in >> tempNum; misMatchCounts[j] += tempNum;
664                         }
665                         m->gobble(in);
666                         
667                         //input megaAlignVector
668                         string thisLine;
669                         for (int j = 0; j < megaAlignVector.size(); j++) {
670                                 thisLine = m->getline(in); m->gobble(in); megaAlignVector[j] += thisLine + '\n';
671                         }
672                         m->gobble(in);
673                         
674                         in.close(); m->mothurRemove(tempFile);
675                         
676                 }
677 #endif          
678                 return num;
679         }
680         catch(exception& e) {
681                 m->errorOut(e, "SeqErrorCommand", "createProcesses");
682                 exit(1);
683         }
684 }
685
686 //**********************************************************************************************************************
687
688 int SeqErrorCommand::driver(string filename, string qFileName, string rFileName, string summaryFileName, string errorOutputFileName, string chimeraOutputFileName, linePair line, linePair qline, linePair rline) {     
689         
690         try {
691                 ReportFile report;
692                 QualityScores quality;
693                 
694                 misMatchCounts.resize(11, 0);
695                 int maxMismatch = 0;
696                 int numSeqs = 0;
697                 
698                 map<string, int>::iterator it;
699                 qScoreErrorMap['m'].assign(101, 0);
700                 qScoreErrorMap['s'].assign(101, 0);
701                 qScoreErrorMap['i'].assign(101, 0);
702                 qScoreErrorMap['a'].assign(101, 0);
703                 
704                 errorForward['m'].assign(maxLength,0);
705                 errorForward['s'].assign(maxLength,0);
706                 errorForward['i'].assign(maxLength,0);
707                 errorForward['d'].assign(maxLength,0);
708                 errorForward['a'].assign(maxLength,0);
709                 
710                 errorReverse['m'].assign(maxLength,0);
711                 errorReverse['s'].assign(maxLength,0);
712                 errorReverse['i'].assign(maxLength,0);
713                 errorReverse['d'].assign(maxLength,0);
714                 errorReverse['a'].assign(maxLength,0);  
715                 
716                 //open inputfiles and go to beginning place for this processor
717                 ifstream queryFile;
718                 m->openInputFile(filename, queryFile);
719         
720                 queryFile.seekg(line.start);
721                 
722                 ifstream reportFile;
723                 ifstream qualFile;
724                 if((qFileName != "" && rFileName != "" && aligned)){
725                         m->openInputFile(qFileName, qualFile);
726                         qualFile.seekg(qline.start);  
727                         
728                         //gobble headers
729                         if (rline.start == 0) {  report = ReportFile(reportFile, rFileName); } 
730                         else{
731                                 m->openInputFile(rFileName, reportFile);
732                                 reportFile.seekg(rline.start); 
733                         }
734                         
735                         qualForwardMap.resize(maxLength);
736                         qualReverseMap.resize(maxLength);
737                         for(int i=0;i<maxLength;i++){
738                                 qualForwardMap[i].assign(101,0);
739                                 qualReverseMap[i].assign(101,0);
740                         }       
741                 }
742                 else if(qFileName != "" && !aligned){
743
744             m->openInputFile(qFileName, qualFile);
745                         qualFile.seekg(qline.start);  
746                         
747                         qualForwardMap.resize(maxLength);
748                         qualReverseMap.resize(maxLength);
749                         for(int i=0;i<maxLength;i++){
750                                 qualForwardMap[i].assign(101,0);
751                                 qualReverseMap[i].assign(101,0);
752                         }       
753         }
754         
755                 ofstream outChimeraReport;
756                 m->openOutputFile(chimeraOutputFileName, outChimeraReport);
757                 
758         
759         RefChimeraTest chimeraTest;
760         
761         chimeraTest = RefChimeraTest(referenceSeqs, aligned);
762         if (line.start == 0) { chimeraTest.printHeader(outChimeraReport); }        
763         
764                 
765                 ofstream errorSummaryFile;
766                 m->openOutputFile(summaryFileName, errorSummaryFile);
767                 if (line.start == 0) { printErrorHeader(errorSummaryFile); }
768                 
769                 ofstream errorSeqFile;
770                 m->openOutputFile(errorOutputFileName, errorSeqFile);
771                 
772                 megaAlignVector.assign(numRefs, "");
773                 
774                 int index = 0;
775                 bool ignoreSeq = 0;
776                 
777                 bool moreSeqs = 1;
778                 while (moreSeqs) {
779                                                 
780                         Sequence query(queryFile);
781                         Sequence reference;
782             int numParentSeqs = -1;
783             int closestRefIndex = -1;
784                         
785             string querySeq = query.getAligned();
786             if (!aligned) {  querySeq = query.getUnaligned();  }
787             
788             numParentSeqs = chimeraTest.analyzeQuery(query.getName(), querySeq, outChimeraReport);
789             
790             closestRefIndex = chimeraTest.getClosestRefIndex();
791             
792             reference = referenceSeqs[closestRefIndex];
793             
794             reference.setAligned(chimeraTest.getClosestRefAlignment());
795             query.setAligned(chimeraTest.getQueryAlignment());
796             
797                         if(numParentSeqs > 1 && ignoreChimeras == 1)    {       ignoreSeq = 1;  }
798             else                                                                                        {       ignoreSeq = 0;  }
799
800                         Compare minCompare;
801             
802             getErrors(query, reference, minCompare);
803                         
804                         if((namesFileName != "") || (countfile != "")){
805                                 it = weights.find(query.getName());
806                                 minCompare.weight = it->second;
807                         }
808                         else{   minCompare.weight = 1;  }
809                         
810             
811                         printErrorData(minCompare, numParentSeqs, errorSummaryFile, errorSeqFile);
812                         
813                         if(!ignoreSeq){
814                                 for(int i=0;i<minCompare.sequence.length();i++){
815                                         char letter = minCompare.sequence[i];
816                                         if(letter != 'r'){
817                                                 errorForward[letter][i] += minCompare.weight;
818                                                 errorReverse[letter][minCompare.total-i-1] += minCompare.weight;        
819                                         }
820                                 }                
821                         }
822                         
823                         if(aligned && qualFileName != "" && reportFileName != ""){
824                                 report = ReportFile(reportFile);
825                                 
826                                 //                              int origLength = report.getQueryLength();
827                                 int startBase = report.getQueryStart();
828                                 int endBase = report.getQueryEnd();
829                                 
830                                 quality = QualityScores(qualFile);
831                                 
832                                 if(!ignoreSeq){
833                                         quality.updateQScoreErrorMap(qScoreErrorMap, minCompare.sequence, startBase, endBase, minCompare.weight);
834                                         quality.updateForwardMap(qualForwardMap, startBase, endBase, minCompare.weight);
835                                         quality.updateReverseMap(qualReverseMap, startBase, endBase, minCompare.weight);
836                                 }
837                         }
838             else if(aligned == false && qualFileName != ""){
839
840                 quality = QualityScores(qualFile);
841                 int qualityLength = quality.getLength();
842                 
843                 if(qualityLength != query.getNumBases()){   cout << "warning - quality and fasta sequence files do not match at " << query.getName() << '\t' << qualityLength <<'\t' << query.getNumBases() << endl;   }
844                 
845                 int startBase = 1;
846                 int endBase = qualityLength;
847
848                 if(!ignoreSeq){
849                                         quality.updateQScoreErrorMap(qScoreErrorMap, minCompare.sequence, startBase, endBase, minCompare.weight);
850                                         quality.updateForwardMap(qualForwardMap, startBase, endBase, minCompare.weight);
851                                         quality.updateReverseMap(qualReverseMap, startBase, endBase, minCompare.weight);
852                                 }
853             }
854             
855                         if(minCompare.errorRate <= threshold && !ignoreSeq){                
856                                 totalBases += (minCompare.total * minCompare.weight);
857                                 totalMatches += minCompare.matches * minCompare.weight;
858                                 if(minCompare.mismatches > maxMismatch){
859                                         maxMismatch = minCompare.mismatches;
860                                         misMatchCounts.resize(maxMismatch + 1, 0);
861                                 }                               
862                                 misMatchCounts[minCompare.mismatches] += minCompare.weight;
863                                 numSeqs++;
864                                 
865                                 megaAlignVector[closestRefIndex] += query.getInlineSeq() + '\n';
866                         }
867                         
868                         index++;
869                         
870                         #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
871                                 unsigned long long pos = queryFile.tellg();
872                                 if ((pos == -1) || (pos >= line.end)) { break; }
873                         #else
874                                 if (queryFile.eof()) { break; }
875                         #endif
876                         
877                         if(index % 100 == 0){   m->mothurOutJustToScreen(toString(index)+"\n");  }
878                 }
879                 queryFile.close();
880                 outChimeraReport.close();
881         errorSummaryFile.close();       
882                 errorSeqFile.close();
883         
884         if(qFileName != "" && rFileName != "")      {   reportFile.close(); qualFile.close();   }
885                 else if(qFileName != "" && aligned == false){   qualFile.close();                       }
886         
887                 //report progress
888                 m->mothurOutJustToScreen(toString(index)+"\n"); 
889                 
890                 return index;
891         }
892         catch(exception& e) {
893                 m->errorOut(e, "SeqErrorCommand", "driver");
894                 exit(1);
895         }
896 }
897
898 //***************************************************************************************************************
899
900 void SeqErrorCommand::getReferences(){
901         try {
902                 int numAmbigSeqs = 0;
903                 
904                 int maxStartPos = 0;
905                 int minEndPos = 100000;
906                 
907                 if (referenceFileName == "saved") {
908                         int start = time(NULL);
909                         m->mothurOutEndLine();  m->mothurOut("Using sequences from " + rdb->getSavedReference() + " that are saved in memory.");        m->mothurOutEndLine();
910                         
911                         for (int i = 0; i < rdb->referenceSeqs.size(); i++) {
912                                 int numAmbigs = rdb->referenceSeqs[i].getAmbigBases();
913                                 if(numAmbigs > 0){      numAmbigSeqs++; }
914                                 
915                                 //                      int startPos = rdb->referenceSeqs[i].getStartPos();
916                                 //                      if(startPos > maxStartPos)      {       maxStartPos = startPos; }
917                                 //
918                                 //                      int endPos = rdb->referenceSeqs[i].getEndPos();
919                                 //                      if(endPos < minEndPos)          {       minEndPos = endPos;             }                               
920                                 if (rdb->referenceSeqs[i].getNumBases() == 0) {
921                     m->mothurOut("[WARNING]: " + rdb->referenceSeqs[i].getName() + " is blank, ignoring.");m->mothurOutEndLine(); 
922                 }else {
923                     referenceSeqs.push_back(rdb->referenceSeqs[i]);
924                 }
925                                 
926                         }
927                         referenceFileName = rdb->getSavedReference();
928                         
929                         m->mothurOut("It took " + toString(time(NULL) - start) + " to load " + toString(referenceSeqs.size()) + " sequences.");m->mothurOutEndLine();  
930                 
931                 }else {
932                         int start = time(NULL);
933
934                         ifstream referenceFile;
935                         m->openInputFile(referenceFileName, referenceFile);
936                         
937                         while(referenceFile){
938                                 Sequence currentSeq(referenceFile);
939                                 int numAmbigs = currentSeq.getAmbigBases();
940                                 if(numAmbigs > 0){      numAmbigSeqs++; }
941                                 
942         //                      int startPos = currentSeq.getStartPos();
943         //                      if(startPos > maxStartPos)      {       maxStartPos = startPos; }
944         //
945         //                      int endPos = currentSeq.getEndPos();
946         //                      if(endPos < minEndPos)          {       minEndPos = endPos;             }
947                 if (currentSeq.getNumBases() == 0) {
948                     m->mothurOut("[WARNING]: " + currentSeq.getName() + " is blank, ignoring.");m->mothurOutEndLine(); 
949                 }else {
950                     referenceSeqs.push_back(currentSeq);
951                     if (rdb->save) { rdb->referenceSeqs.push_back(currentSeq); }
952                 }
953                                         
954                                 m->gobble(referenceFile);
955                         }
956                         referenceFile.close();
957                         
958                         m->mothurOut("It took " + toString(time(NULL) - start) + " to read " + toString(referenceSeqs.size()) + " sequences.");m->mothurOutEndLine();  
959                 }
960                 
961                 numRefs = referenceSeqs.size();
962                 
963                 for(int i=0;i<numRefs;i++){
964                         referenceSeqs[i].padToPos(maxStartPos);
965                         referenceSeqs[i].padFromPos(minEndPos);
966         }
967                 
968                 if(numAmbigSeqs != 0){
969                         m->mothurOut("Warning: " + toString(numAmbigSeqs) + " reference sequences have ambiguous bases, these bases will be ignored\n");
970                 }       
971                 
972         }
973         catch(exception& e) {
974                 m->errorOut(e, "SeqErrorCommand", "getReferences");
975                 exit(1);
976         }
977 }
978
979 //***************************************************************************************************************
980
981 int SeqErrorCommand::getErrors(Sequence query, Sequence reference, Compare& errors){
982         try {
983                 if(query.getAlignLength() != reference.getAlignLength()){
984                         m->mothurOut("Warning: " + toString(query.getName()) + " and " + toString(reference.getName()) + " are different lengths\n");
985                 }
986                 int alignLength = query.getAlignLength();
987         
988                 string q = query.getAligned();
989                 string r = reference.getAligned();
990
991                 int started = 0;
992                 //Compare errors;
993         
994         errors.sequence = "";
995                 for(int i=0;i<alignLength;i++){
996
997                         if(q[i] != '.' && r[i] != '.' && (q[i] != '-' || r[i] != '-')){                 //      no missing data and no double gaps
998                                 if(r[i] != 'N'){
999                                         started = 1;
1000                                         
1001                                         if(q[i] == 'A'){
1002                                                 if(r[i] == 'A'){        errors.AA++;    errors.matches++;       errors.sequence += 'm'; }
1003                                                 if(r[i] == 'T'){        errors.AT++;    errors.sequence += 's'; }
1004                                                 if(r[i] == 'G'){        errors.AG++;    errors.sequence += 's'; }
1005                                                 if(r[i] == 'C'){        errors.AC++;    errors.sequence += 's'; }
1006                                                 if(r[i] == '-'){        errors.Ai++;    errors.sequence += 'i'; }
1007                                         }
1008                                         else if(q[i] == 'T'){
1009                                                 if(r[i] == 'A'){        errors.TA++;    errors.sequence += 's'; }
1010                                                 if(r[i] == 'T'){        errors.TT++;    errors.matches++;       errors.sequence += 'm'; }
1011                                                 if(r[i] == 'G'){        errors.TG++;    errors.sequence += 's'; }
1012                                                 if(r[i] == 'C'){        errors.TC++;    errors.sequence += 's'; }
1013                                                 if(r[i] == '-'){        errors.Ti++;    errors.sequence += 'i'; }
1014                                         }
1015                                         else if(q[i] == 'G'){
1016                                                 if(r[i] == 'A'){        errors.GA++;    errors.sequence += 's'; }
1017                                                 if(r[i] == 'T'){        errors.GT++;    errors.sequence += 's'; }
1018                                                 if(r[i] == 'G'){        errors.GG++;    errors.matches++;       errors.sequence += 'm'; }
1019                                                 if(r[i] == 'C'){        errors.GC++;    errors.sequence += 's'; }
1020                                                 if(r[i] == '-'){        errors.Gi++;    errors.sequence += 'i'; }
1021                                         }
1022                                         else if(q[i] == 'C'){
1023                                                 if(r[i] == 'A'){        errors.CA++;    errors.sequence += 's'; }
1024                                                 if(r[i] == 'T'){        errors.CT++;    errors.sequence += 's'; }
1025                                                 if(r[i] == 'G'){        errors.CG++;    errors.sequence += 's'; }
1026                                                 if(r[i] == 'C'){        errors.CC++;    errors.matches++;       errors.sequence += 'm'; }
1027                                                 if(r[i] == '-'){        errors.Ci++;    errors.sequence += 'i'; }
1028                                         }
1029                                         else if(q[i] == 'N'){
1030                                                 if(r[i] == 'A'){        errors.NA++;    errors.sequence += 'a'; }
1031                                                 if(r[i] == 'T'){        errors.NT++;    errors.sequence += 'a'; }
1032                                                 if(r[i] == 'G'){        errors.NG++;    errors.sequence += 'a'; }
1033                                                 if(r[i] == 'C'){        errors.NC++;    errors.sequence += 'a'; }
1034                                                 if(r[i] == '-'){        errors.Ni++;    errors.sequence += 'a'; }
1035                                         }
1036                                         else if(q[i] == '-' && r[i] != '-'){
1037                                                 if(r[i] == 'A'){        errors.dA++;    errors.sequence += 'd'; }
1038                                                 if(r[i] == 'T'){        errors.dT++;    errors.sequence += 'd'; }
1039                                                 if(r[i] == 'G'){        errors.dG++;    errors.sequence += 'd'; }
1040                                                 if(r[i] == 'C'){        errors.dC++;    errors.sequence += 'd'; }
1041                                         }
1042                                         errors.total++; 
1043                                 }
1044                                 else{
1045                                         
1046                                         if(q[i] == '-'){
1047                                                 errors.sequence += 'd'; errors.total++;
1048                                         }                                               
1049                                         else{
1050                                                 errors.sequence += 'r';
1051                                         }
1052                                 }
1053                         }            
1054                         else if(q[i] == '.' && r[i] != '.'){            //      reference extends beyond query
1055                                 if(started == 1){       break;  }
1056                         }
1057                         else if(q[i] != '.' && r[i] == '.'){            //      query extends beyond reference
1058                                 if(started == 1){       break;  }
1059                         }
1060                         else if(q[i] == '.' && r[i] == '.'){            //      both are missing data
1061                                 if(started == 1){       break;  }                       
1062                         }
1063                 }
1064
1065                 errors.mismatches = errors.total-errors.matches;
1066         if(errors.total != 0){  errors.errorRate = (double)(errors.total-errors.matches) / (double)errors.total;    }
1067         else{   errors.errorRate = 0;   }
1068
1069                 errors.queryName = query.getName();
1070                 errors.refName = reference.getName();
1071
1072         return 0;
1073         }
1074         catch(exception& e) {
1075                 m->errorOut(e, "SeqErrorCommand", "getErrors");
1076                 exit(1);
1077         }
1078 }
1079
1080 //***************************************************************************************************************
1081
1082 map<string, int> SeqErrorCommand::getWeights(){
1083         ifstream nameFile;
1084         m->openInputFile(namesFileName, nameFile);
1085         
1086         string seqName;
1087         string redundantSeqs;
1088         map<string, int> nameCountMap;
1089         
1090         while(nameFile){
1091                 nameFile >> seqName >> redundantSeqs;
1092                 nameCountMap[seqName] = m->getNumNames(redundantSeqs); 
1093                 m->gobble(nameFile);
1094         }
1095     
1096     nameFile.close();
1097     
1098         return nameCountMap;
1099 }
1100
1101 //***************************************************************************************************************
1102
1103 void SeqErrorCommand::printErrorHeader(ofstream& errorSummaryFile){
1104         try {
1105                 errorSummaryFile << "query\treference\tweight\t";
1106                 errorSummaryFile << "AA\tAT\tAG\tAC\tTA\tTT\tTG\tTC\tGA\tGT\tGG\tGC\tCA\tCT\tCG\tCC\tNA\tNT\tNG\tNC\tAi\tTi\tGi\tCi\tNi\tdA\tdT\tdG\tdC\t";
1107                 errorSummaryFile << "insertions\tdeletions\tsubstitutions\tambig\tmatches\tmismatches\ttotal\terror\tnumparents\n";
1108                 
1109                 errorSummaryFile << setprecision(6);
1110                 errorSummaryFile.setf(ios::fixed);
1111         }
1112         catch(exception& e) {
1113                 m->errorOut(e, "SeqErrorCommand", "printErrorHeader");
1114                 exit(1);
1115         }
1116 }
1117
1118 //***************************************************************************************************************
1119
1120 void SeqErrorCommand::printErrorData(Compare error, int numParentSeqs, ofstream& errorSummaryFile, ofstream& errorSeqFile){
1121         try {
1122
1123                 errorSummaryFile << error.queryName << '\t' << error.refName << '\t' << error.weight << '\t';
1124                 errorSummaryFile << error.AA << '\t' << error.AT << '\t' << error.AG << '\t' << error.AC << '\t';
1125                 errorSummaryFile << error.TA << '\t' << error.TT << '\t' << error.TG << '\t' << error.TC << '\t';
1126                 errorSummaryFile << error.GA << '\t' << error.GT << '\t' << error.GG << '\t' << error.GC << '\t';
1127                 errorSummaryFile << error.CA << '\t' << error.CT << '\t' << error.CG << '\t' << error.CC << '\t';
1128                 errorSummaryFile << error.NA << '\t' << error.NT << '\t' << error.NG << '\t' << error.NC << '\t';
1129                 errorSummaryFile << error.Ai << '\t' << error.Ti << '\t' << error.Gi << '\t' << error.Ci << '\t' << error.Ni << '\t';
1130                 errorSummaryFile << error.dA << '\t' << error.dT << '\t' << error.dG << '\t' << error.dC << '\t';
1131                 
1132                 errorSummaryFile << error.Ai + error.Ti + error.Gi + error.Ci << '\t';                  //insertions
1133                 errorSummaryFile << error.dA + error.dT + error.dG + error.dC << '\t';                  //deletions
1134                 errorSummaryFile << error.mismatches - (error.Ai + error.Ti + error.Gi + error.Ci) - (error.dA + error.dT + error.dG + error.dC) - (error.NA + error.NT + error.NG + error.NC + error.Ni) << '\t';      //substitutions
1135                 errorSummaryFile << error.NA + error.NT + error.NG + error.NC + error.Ni << '\t';       //ambiguities
1136                 errorSummaryFile << error.matches << '\t' << error.mismatches << '\t' << error.total << '\t' << error.errorRate << '\t' << numParentSeqs << endl;
1137
1138                 errorSeqFile << '>' << error.queryName << "\tref:" << error.refName << '\n' << error.sequence << endl;
1139                 
1140                 int a=0;                int t=1;                int g=2;                int c=3;
1141                 int gap=4;              int n=5;
1142
1143                 if(numParentSeqs == 1 || ignoreChimeras == 0){
1144                         substitutionMatrix[a][a] += error.weight * error.AA;
1145                         substitutionMatrix[a][t] += error.weight * error.TA;
1146                         substitutionMatrix[a][g] += error.weight * error.GA;
1147                         substitutionMatrix[a][c] += error.weight * error.CA;
1148                         substitutionMatrix[a][gap] += error.weight * error.dA;
1149                         substitutionMatrix[a][n] += error.weight * error.NA;
1150                         
1151                         substitutionMatrix[t][a] += error.weight * error.AT;
1152                         substitutionMatrix[t][t] += error.weight * error.TT;
1153                         substitutionMatrix[t][g] += error.weight * error.GT;
1154                         substitutionMatrix[t][c] += error.weight * error.CT;
1155                         substitutionMatrix[t][gap] += error.weight * error.dT;
1156                         substitutionMatrix[t][n] += error.weight * error.NT;
1157
1158                         substitutionMatrix[g][a] += error.weight * error.AG;
1159                         substitutionMatrix[g][t] += error.weight * error.TG;
1160                         substitutionMatrix[g][g] += error.weight * error.GG;
1161                         substitutionMatrix[g][c] += error.weight * error.CG;
1162                         substitutionMatrix[g][gap] += error.weight * error.dG;
1163                         substitutionMatrix[g][n] += error.weight * error.NG;
1164
1165                         substitutionMatrix[c][a] += error.weight * error.AC;
1166                         substitutionMatrix[c][t] += error.weight * error.TC;
1167                         substitutionMatrix[c][g] += error.weight * error.GC;
1168                         substitutionMatrix[c][c] += error.weight * error.CC;
1169                         substitutionMatrix[c][gap] += error.weight * error.dC;
1170                         substitutionMatrix[c][n] += error.weight * error.NC;
1171
1172                         substitutionMatrix[gap][a] += error.weight * error.Ai;
1173                         substitutionMatrix[gap][t] += error.weight * error.Ti;
1174                         substitutionMatrix[gap][g] += error.weight * error.Gi;
1175                         substitutionMatrix[gap][c] += error.weight * error.Ci;
1176                         substitutionMatrix[gap][n] += error.weight * error.Ni;
1177                 }
1178         }
1179         catch(exception& e) {
1180                 m->errorOut(e, "SeqErrorCommand", "printErrorData");
1181                 exit(1);
1182         }
1183 }
1184
1185 //***************************************************************************************************************
1186
1187 void SeqErrorCommand::printSubMatrix(){
1188         try {
1189         string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
1190         map<string, string> variables; 
1191                 variables["[filename]"] = fileNameRoot;
1192                 string subMatrixFileName = getOutputFileName("errormatrix",variables);
1193                 ofstream subMatrixFile;
1194                 m->openOutputFile(subMatrixFileName, subMatrixFile);
1195                 outputNames.push_back(subMatrixFileName);  outputTypes["errormatrix"].push_back(subMatrixFileName);
1196                 vector<string> bases(6);
1197                 bases[0] = "A";
1198                 bases[1] = "T";
1199                 bases[2] = "G";
1200                 bases[3] = "C";
1201                 bases[4] = "Gap";
1202                 bases[5] = "N";
1203                 vector<int> refSums(5,1);
1204
1205                 for(int i=0;i<5;i++){
1206                         subMatrixFile << "\tr" << bases[i];
1207                         
1208                         for(int j=0;j<6;j++){
1209                                 refSums[i] += substitutionMatrix[i][j];                         
1210                         }
1211                 }
1212                 subMatrixFile << endl;
1213                 
1214                 for(int i=0;i<6;i++){
1215                         subMatrixFile << 'q' << bases[i];
1216                         for(int j=0;j<5;j++){
1217                                 subMatrixFile << '\t' << substitutionMatrix[j][i];                              
1218                         }
1219                         subMatrixFile << endl;
1220                 }
1221
1222                 subMatrixFile << "total";
1223                 for(int i=0;i<5;i++){
1224                         subMatrixFile << '\t' << refSums[i];
1225                 }
1226                 subMatrixFile << endl;
1227                 subMatrixFile.close();
1228         }
1229         catch(exception& e) {
1230                 m->errorOut(e, "SeqErrorCommand", "printSubMatrix");
1231                 exit(1);
1232         }
1233 }
1234
1235 //***************************************************************************************************************
1236
1237 void SeqErrorCommand::printErrorFRFile(map<char, vector<int> > errorForward, map<char, vector<int> > errorReverse){
1238         try{
1239         string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
1240         map<string, string> variables; 
1241                 variables["[filename]"] = fileNameRoot;
1242                 string errorForwardFileName = getOutputFileName("errorforward",variables);
1243                 ofstream errorForwardFile;
1244                 m->openOutputFile(errorForwardFileName, errorForwardFile);
1245                 outputNames.push_back(errorForwardFileName);  outputTypes["errorforward"].push_back(errorForwardFileName);
1246
1247                 errorForwardFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1248                 for(int i=0;i<maxLength;i++){
1249                         float match = (float)errorForward['m'][i];
1250                         float subst = (float)errorForward['s'][i];
1251                         float insert = (float)errorForward['i'][i];
1252                         float del = (float)errorForward['d'][i];
1253                         float amb = (float)errorForward['a'][i];
1254                         float total = match + subst + insert + del + amb;
1255                         if(total == 0){ break;  }
1256                         errorForwardFile << i+1 << '\t' << total << '\t' << match/total  << '\t' << subst/total  << '\t' << insert/total  << '\t' << del/total  << '\t' << amb/total << endl;
1257                 }
1258                 errorForwardFile.close();
1259
1260                 string errorReverseFileName = getOutputFileName("errorreverse",variables);
1261                 ofstream errorReverseFile;
1262                 m->openOutputFile(errorReverseFileName, errorReverseFile);
1263                 outputNames.push_back(errorReverseFileName);  outputTypes["errorreverse"].push_back(errorReverseFileName);
1264
1265                 errorReverseFile << "position\ttotalseqs\tmatch\tsubstitution\tinsertion\tdeletion\tambiguous" << endl;
1266                 for(int i=0;i<maxLength;i++){
1267                         float match = (float)errorReverse['m'][i];
1268                         float subst = (float)errorReverse['s'][i];
1269                         float insert = (float)errorReverse['i'][i];
1270                         float del = (float)errorReverse['d'][i];
1271                         float amb = (float)errorReverse['a'][i];
1272                         float total = match + subst + insert + del + amb;
1273                         if(total == 0){ break;  }
1274                         errorReverseFile << i+1 << '\t' << total << '\t' << match/total  << '\t' << subst/total  << '\t' << insert/total  << '\t' << del/total  << '\t' << amb/total << endl;
1275                 }
1276                 errorReverseFile.close();
1277         }
1278         catch(exception& e) {
1279                 m->errorOut(e, "SeqErrorCommand", "printErrorFRFile");
1280                 exit(1);
1281         }
1282 }
1283
1284 //***************************************************************************************************************
1285
1286 void SeqErrorCommand::printErrorQuality(map<char, vector<int> > qScoreErrorMap){
1287         try{
1288         string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
1289         map<string, string> variables; 
1290                 variables["[filename]"] = fileNameRoot;
1291                 string errorQualityFileName = getOutputFileName("errorquality",variables);
1292                 ofstream errorQualityFile;
1293                 m->openOutputFile(errorQualityFileName, errorQualityFile);
1294                 outputNames.push_back(errorQualityFileName);  outputTypes["errorquality"].push_back(errorQualityFileName);
1295
1296                 errorQualityFile << "qscore\tmatches\tsubstitutions\tinsertions\tambiguous" << endl;
1297                 for(int i=0;i<101;i++){
1298                         errorQualityFile << i << '\t' << qScoreErrorMap['m'][i] << '\t' << qScoreErrorMap['s'][i] << '\t' << qScoreErrorMap['i'][i] << '\t'<< qScoreErrorMap['a'][i] << endl;
1299                 }
1300                 errorQualityFile.close();
1301         }
1302         catch(exception& e) {
1303                 m->errorOut(e, "SeqErrorCommand", "printErrorQuality");
1304                 exit(1);
1305         }
1306 }
1307
1308 //***************************************************************************************************************
1309
1310 void SeqErrorCommand::printQualityFR(vector<vector<int> > qualForwardMap, vector<vector<int> > qualReverseMap){
1311
1312         try{
1313                 int numRows = 0;
1314                 int numColumns = qualForwardMap[0].size();
1315
1316                 for(int i=0;i<qualForwardMap.size();i++){
1317                         for(int j=0;j<numColumns;j++){
1318                                 if(qualForwardMap[i][j] != 0){
1319                                         if(numRows < i)         {       numRows = i+20;         }
1320                                 }
1321                         }
1322                 }
1323         string fileNameRoot = outputDir + m->getRootName(m->getSimpleName(queryFileName));
1324         map<string, string> variables; 
1325                 variables["[filename]"] = fileNameRoot;
1326                 string qualityForwardFileName = getOutputFileName("errorqualforward",variables);
1327                 ofstream qualityForwardFile;
1328                 m->openOutputFile(qualityForwardFileName, qualityForwardFile);
1329                 outputNames.push_back(qualityForwardFileName);  outputTypes["errorqualforward"].push_back(qualityForwardFileName);
1330
1331                 for(int i=0;i<numColumns;i++){  qualityForwardFile << '\t' << i;        }       qualityForwardFile << endl;
1332
1333                 for(int i=0;i<numRows;i++){
1334                         qualityForwardFile << i+1;
1335                         for(int j=0;j<numColumns;j++){
1336                                 qualityForwardFile << '\t' << qualForwardMap[i][j];
1337                         }
1338
1339                         qualityForwardFile << endl;
1340                 }
1341                 qualityForwardFile.close();
1342
1343                 
1344                 string qualityReverseFileName = getOutputFileName("errorqualreverse",variables);
1345                 ofstream qualityReverseFile;
1346                 m->openOutputFile(qualityReverseFileName, qualityReverseFile);
1347                 outputNames.push_back(qualityReverseFileName);  outputTypes["errorqualreverse"].push_back(qualityReverseFileName);
1348                 
1349                 for(int i=0;i<numColumns;i++){  qualityReverseFile << '\t' << i;        }       qualityReverseFile << endl;
1350                 for(int i=0;i<numRows;i++){
1351                         
1352                         qualityReverseFile << i+1;
1353                         for(int j=0;j<numColumns;j++){
1354                                 qualityReverseFile << '\t' << qualReverseMap[i][j];
1355                         }
1356                         qualityReverseFile << endl;
1357                 }
1358                 qualityReverseFile.close();
1359         }
1360         catch(exception& e) {
1361                 m->errorOut(e, "SeqErrorCommand", "printQualityFR");
1362                 exit(1);
1363         }
1364         
1365 }
1366
1367 /**************************************************************************************************/
1368
1369 int SeqErrorCommand::setLines(string filename, string qfilename, string rfilename, vector<unsigned long long>& fastaFilePos, vector<unsigned long long>& qfileFilePos, vector<unsigned long long>& rfileFilePos) {
1370         try {
1371 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
1372                 //set file positions for fasta file
1373                 fastaFilePos = m->divideFile(filename, processors);
1374                 
1375                 if (qfilename == "") { return processors; }
1376                 
1377                 //get name of first sequence in each chunk
1378                 map<string, int> firstSeqNames;
1379                 for (int i = 0; i < (fastaFilePos.size()-1); i++) {
1380                         ifstream in;
1381                         m->openInputFile(filename, in);
1382                         in.seekg(fastaFilePos[i]);
1383                         
1384                         Sequence temp(in); 
1385                         firstSeqNames[temp.getName()] = i;
1386                         
1387                         in.close();
1388                 }
1389                 
1390                 //make copy to use below
1391                 map<string, int> firstSeqNamesReport = firstSeqNames;
1392                 
1393                 //seach for filePos of each first name in the qfile and save in qfileFilePos
1394                 ifstream inQual;
1395                 m->openInputFile(qfilename, inQual);
1396                 
1397                 string input;
1398                 while(!inQual.eof()){   
1399                         input = m->getline(inQual);
1400                         
1401                         if (input.length() != 0) {
1402                                 if(input[0] == '>'){ //this is a sequence name line
1403                                         istringstream nameStream(input);
1404                                         
1405                                         string sname = "";  nameStream >> sname;
1406                                         sname = sname.substr(1);
1407                     
1408                     m->checkName(sname);
1409                                         
1410                                         map<string, int>::iterator it = firstSeqNames.find(sname);
1411                                         
1412                                         if(it != firstSeqNames.end()) { //this is the start of a new chunk
1413                                                 unsigned long long pos = inQual.tellg(); 
1414                                                 qfileFilePos.push_back(pos - input.length() - 1);       
1415                                                 firstSeqNames.erase(it);
1416                                         }
1417                                 }
1418                         }
1419                         
1420                         if (firstSeqNames.size() == 0) { break; }
1421                 }
1422                 inQual.close();
1423                 
1424                 if (firstSeqNames.size() != 0) { 
1425                         for (map<string, int>::iterator it = firstSeqNames.begin(); it != firstSeqNames.end(); it++) {
1426                                 m->mothurOut(it->first + " is in your fasta file and not in your quality file, aborting."); m->mothurOutEndLine();
1427                         }
1428                         m->control_pressed = true;
1429                         return processors;
1430                 }
1431                 
1432                 //get last file position of qfile
1433                 FILE * pFile;
1434                 unsigned long long size;
1435                 
1436                 //get num bytes in file
1437                 pFile = fopen (qfilename.c_str(),"rb");
1438                 if (pFile==NULL) perror ("Error opening file");
1439                 else{
1440                         fseek (pFile, 0, SEEK_END);
1441                         size=ftell (pFile);
1442                         fclose (pFile);
1443                 }
1444                 
1445                 qfileFilePos.push_back(size);
1446                 
1447         if(aligned){
1448             //seach for filePos of each first name in the rfile and save in rfileFilePos
1449             string junk;
1450             ifstream inR;
1451
1452             m->openInputFile(rfilename, inR);
1453
1454             //read column headers
1455             for (int i = 0; i < 16; i++) {  
1456                 if (!inR.eof()) {       inR >> junk;    }
1457                 else                    {       break;                  }
1458             }
1459             
1460             while(!inR.eof()){
1461                 
1462                 input = m->getline(inR);        
1463                 
1464                 if (input.length() != 0) {
1465                     
1466                     istringstream nameStream(input);
1467                     string sname = "";  nameStream >> sname;
1468                     
1469                     m->checkName(sname);
1470                     
1471                     map<string, int>::iterator it = firstSeqNamesReport.find(sname);
1472                 
1473                     if(it != firstSeqNamesReport.end()) { //this is the start of a new chunk
1474                         unsigned long long pos = inR.tellg(); 
1475                         rfileFilePos.push_back(pos - input.length() - 1);       
1476                         firstSeqNamesReport.erase(it);
1477                     }
1478                 }
1479                 
1480                 if (firstSeqNamesReport.size() == 0) { break; }
1481                 m->gobble(inR);
1482             }
1483             inR.close();
1484             
1485             if (firstSeqNamesReport.size() != 0) { 
1486                 for (map<string, int>::iterator it = firstSeqNamesReport.begin(); it != firstSeqNamesReport.end(); it++) {
1487                     m->mothurOut(it->first + " is in your fasta file and not in your report file, aborting."); m->mothurOutEndLine();
1488                 }
1489                 m->control_pressed = true;
1490                 return processors;
1491             }
1492             
1493             //get last file position of qfile
1494             FILE * rFile;
1495             unsigned long long sizeR;
1496             
1497             //get num bytes in file
1498             rFile = fopen (rfilename.c_str(),"rb");
1499             if (rFile==NULL) perror ("Error opening file");
1500             else{
1501                 fseek (rFile, 0, SEEK_END);
1502                 sizeR=ftell (rFile);
1503                 fclose (rFile);
1504             }
1505             
1506             rfileFilePos.push_back(sizeR);
1507                 }
1508                 return processors;
1509                 
1510 #else
1511                 
1512                 fastaFilePos.push_back(0); qfileFilePos.push_back(0);
1513                 //get last file position of fastafile
1514                 FILE * pFile;
1515                 unsigned long long size;
1516                 
1517                 //get num bytes in file
1518                 pFile = fopen (filename.c_str(),"rb");
1519                 if (pFile==NULL) perror ("Error opening file");
1520                 else{
1521                         fseek (pFile, 0, SEEK_END);
1522                         size=ftell (pFile);
1523                         fclose (pFile);
1524                 }
1525                 fastaFilePos.push_back(size);
1526                 
1527                 //get last file position of fastafile
1528                 FILE * qFile;
1529                 
1530                 //get num bytes in file
1531                 qFile = fopen (qfilename.c_str(),"rb");
1532                 if (qFile==NULL) perror ("Error opening file");
1533                 else{
1534                         fseek (qFile, 0, SEEK_END);
1535                         size=ftell (qFile);
1536                         fclose (qFile);
1537                 }
1538                 qfileFilePos.push_back(size);
1539                 
1540                 return 1;
1541                 
1542 #endif
1543         }
1544         catch(exception& e) {
1545                 m->errorOut(e, "SeqErrorCommand", "setLines");
1546                 exit(1);
1547         }
1548 }
1549
1550 //***************************************************************************************************************