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