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