]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
19616d8b0e4ce5d46e6753bbc58b776d1b5dd656
[mothur.git] / preclustercommand.cpp
1 /*
2  *  preclustercommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 12/21/09.
6  *  Copyright 2009 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "preclustercommand.h"
11 #include "deconvolutecommand.h"
12
13 //**********************************************************************************************************************
14 vector<string> PreClusterCommand::setParameters(){      
15         try {
16                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none","fasta-name",false,true,true); parameters.push_back(pfasta);
17                 CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","name",false,false,true); parameters.push_back(pname);
18         CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","count",false,false,true); parameters.push_back(pcount);
19                 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","",false,false,true); parameters.push_back(pgroup);
20                 CommandParameter pdiffs("diffs", "Number", "", "0", "", "", "","",false,false,true); parameters.push_back(pdiffs);
21                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "","",false,false,true); parameters.push_back(pprocessors);
22         CommandParameter ptopdown("topdown", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(ptopdown);
23
24                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
25                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
26                 
27                 vector<string> myArray;
28                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
29                 return myArray;
30         }
31         catch(exception& e) {
32                 m->errorOut(e, "PreClusterCommand", "setParameters");
33                 exit(1);
34         }
35 }
36 //**********************************************************************************************************************
37 string PreClusterCommand::getHelpString(){      
38         try {
39                 string helpString = "";
40                 helpString += "The pre.cluster command groups sequences that are within a given number of base mismatches.\n";
41                 helpString += "The pre.cluster command outputs a new fasta and name file.\n";
42                 helpString += "The pre.cluster command parameters are fasta, name, group, count, topdown, processors and diffs. The fasta parameter is required. \n";
43                 helpString += "The name parameter allows you to give a list of seqs that are identical. This file is 2 columns, first column is name or representative sequence, second column is a list of its identical sequences separated by commas.\n";
44                 helpString += "The group parameter allows you to provide a group file so you can cluster by group. \n";
45         helpString += "The count parameter allows you to provide a count file so you can cluster by group. \n";
46                 helpString += "The diffs parameter allows you to specify maximum number of mismatched bases allowed between sequences in a grouping. The default is 1.\n";
47         helpString += "The topdown parameter allows you to specify whether to cluster from largest abundance to smallest or smallest to largest.  Default=T, meanging largest to smallest.\n";
48                 helpString += "The pre.cluster command should be in the following format: \n";
49                 helpString += "pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n";
50                 helpString += "Example pre.cluster(fasta=amazon.fasta, diffs=2).\n";
51                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
52                 return helpString;
53         }
54         catch(exception& e) {
55                 m->errorOut(e, "PreClusterCommand", "getHelpString");
56                 exit(1);
57         }
58 }
59 //**********************************************************************************************************************
60 string PreClusterCommand::getOutputPattern(string type) {
61     try {
62         string pattern = "";
63         
64         if (type == "fasta") {  pattern = "[filename],precluster,[extension]"; } 
65         else if (type == "name") {  pattern = "[filename],precluster.names"; } 
66         else if (type == "count") {  pattern = "[filename],precluster.count_table"; }
67         else if (type == "map") {  pattern =  "[filename],precluster.map"; }
68         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
69         
70         return pattern;
71     }
72     catch(exception& e) {
73         m->errorOut(e, "PreClusterCommand", "getOutputPattern");
74         exit(1);
75     }
76 }
77 //**********************************************************************************************************************
78 PreClusterCommand::PreClusterCommand(){ 
79         try {
80                 abort = true; calledHelp = true; 
81                 setParameters();
82                 vector<string> tempOutNames;
83                 outputTypes["fasta"] = tempOutNames;
84                 outputTypes["name"] = tempOutNames;
85         outputTypes["count"] = tempOutNames;
86                 outputTypes["map"] = tempOutNames;
87         }
88         catch(exception& e) {
89                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
90                 exit(1);
91         }
92 }
93 //**********************************************************************************************************************
94
95 PreClusterCommand::PreClusterCommand(string option) {
96         try {
97                 abort = false; calledHelp = false;   
98                 
99                 //allow user to run help
100                 if(option == "help") { help(); abort = true; calledHelp = true; }
101                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
102                 
103                 else {
104                         vector<string> myArray = setParameters();
105                         
106                         OptionParser parser(option);
107                         map<string, string> parameters = parser.getParameters();
108                         
109                         ValidParameters validParameter;
110                         map<string, string>::iterator it;
111                 
112                         //check to make sure all parameters are valid for command
113                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
114                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
115                         }
116                         
117                         //initialize outputTypes
118                         vector<string> tempOutNames;
119                         outputTypes["fasta"] = tempOutNames;
120                         outputTypes["name"] = tempOutNames;
121                         outputTypes["map"] = tempOutNames;
122             outputTypes["count"] = tempOutNames;
123                 
124                         //if the user changes the input directory command factory will send this info to us in the output parameter 
125                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
126                         if (inputDir == "not found"){   inputDir = "";          }
127                         else {
128                                 string path;
129                                 it = parameters.find("fasta");
130                                 //user has given a template file
131                                 if(it != parameters.end()){ 
132                                         path = m->hasPath(it->second);
133                                         //if the user has not given a path then, add inputdir. else leave path alone.
134                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
135                                 }
136                                 
137                                 it = parameters.find("name");
138                                 //user has given a template file
139                                 if(it != parameters.end()){ 
140                                         path = m->hasPath(it->second);
141                                         //if the user has not given a path then, add inputdir. else leave path alone.
142                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
143                                 }
144                                 
145                                 it = parameters.find("group");
146                                 //user has given a template file
147                                 if(it != parameters.end()){ 
148                                         path = m->hasPath(it->second);
149                                         //if the user has not given a path then, add inputdir. else leave path alone.
150                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
151                                 }
152                 
153                 it = parameters.find("count");
154                                 //user has given a template file
155                                 if(it != parameters.end()){ 
156                                         path = m->hasPath(it->second);
157                                         //if the user has not given a path then, add inputdir. else leave path alone.
158                                         if (path == "") {       parameters["count"] = inputDir + it->second;            }
159                                 }
160                         }
161
162                         //check for required parameters
163                         fastafile = validParameter.validFile(parameters, "fasta", true);
164                         if (fastafile == "not found") {                                 
165                                 fastafile = m->getFastaFile(); 
166                                 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
167                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
168                         }
169                         else if (fastafile == "not open") { abort = true; }     
170                         else { m->setFastaFile(fastafile); }
171                         
172                         //if the user changes the output directory command factory will send this info to us in the output parameter 
173                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
174                                 outputDir = ""; 
175                                 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it       
176                         }
177
178                         //check for optional parameter and set defaults
179                         // ...at some point should added some additional type checking...
180                         namefile = validParameter.validFile(parameters, "name", true);
181                         if (namefile == "not found") { namefile =  "";  }
182                         else if (namefile == "not open") { namefile = ""; abort = true; }       
183                         else {  m->setNameFile(namefile); }
184                         
185                         groupfile = validParameter.validFile(parameters, "group", true);
186                         if (groupfile == "not found") { groupfile =  "";  bygroup = false; }
187                         else if (groupfile == "not open") { abort = true; groupfile =  ""; }    
188                         else {   m->setGroupFile(groupfile); bygroup = true;  }
189             
190             countfile = validParameter.validFile(parameters, "count", true);
191                         if (countfile == "not found") { countfile =  "";   }
192                         else if (countfile == "not open") { abort = true; countfile =  ""; }    
193                         else {   
194                 m->setCountTableFile(countfile); 
195                 ct.readTable(countfile);
196                 if (ct.hasGroupInfo()) { bygroup = true; }
197                 else { bygroup = false;  }
198             }
199             
200             if ((namefile != "") && (countfile != "")) {
201                 m->mothurOut("[ERROR]: you may only use one of the following: name or count."); m->mothurOutEndLine(); abort = true;
202             }
203             
204             if ((groupfile != "") && (countfile != "")) {
205                 m->mothurOut("[ERROR]: you may only use one of the following: group or count."); m->mothurOutEndLine(); abort=true;
206             }
207
208                         
209                         string temp     = validParameter.validFile(parameters, "diffs", false);         if(temp == "not found"){        temp = "1"; }
210                         m->mothurConvert(temp, diffs); 
211                         
212                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
213                         m->setProcessors(temp);
214                         m->mothurConvert(temp, processors);
215                         
216             temp = validParameter.validFile(parameters, "topdown", false);              if(temp == "not found"){  temp = "T"; }
217                         topdown = m->isTrue(temp);
218             
219             if (countfile == "") {
220                 if (namefile == "") {
221                     vector<string> files; files.push_back(fastafile);
222                     parser.getNameFile(files);
223                 }
224             }
225                 }
226                                 
227         }
228         catch(exception& e) {
229                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
230                 exit(1);
231         }
232 }
233 //**********************************************************************************************************************
234
235 int PreClusterCommand::execute(){
236         try {
237                 
238                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
239                 
240                 int start = time(NULL);
241                 
242                 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
243         map<string, string> variables; 
244         variables["[filename]"] = fileroot;
245                 string newNamesFile = getOutputFileName("name",variables);
246         string newCountFile = getOutputFileName("count",variables);
247                 string newMapFile = getOutputFileName("map",variables); //add group name if by group
248         variables["[extension]"] = m->getExtension(fastafile);
249                 string newFastaFile = getOutputFileName("fasta", variables);
250                 outputNames.push_back(newFastaFile); outputTypes["fasta"].push_back(newFastaFile);
251                 if (countfile == "") { outputNames.push_back(newNamesFile); outputTypes["name"].push_back(newNamesFile); }
252                 else { outputNames.push_back(newCountFile); outputTypes["count"].push_back(newCountFile); }
253                 
254                 if (bygroup) {
255                         //clear out old files
256                         ofstream outFasta; m->openOutputFile(newFastaFile, outFasta); outFasta.close();
257                         ofstream outNames; m->openOutputFile(newNamesFile, outNames);  outNames.close();
258                         newMapFile = fileroot + "precluster.";
259                         
260                         //parse fasta and name file by group
261             vector<string> groups;
262                         if (countfile != "") {
263                 cparser = new SequenceCountParser(countfile, fastafile);
264                 groups = cparser->getNamesOfGroups();
265             }else {
266                 if (namefile != "") { parser = new SequenceParser(groupfile, fastafile, namefile);      }
267                 else                            { parser = new SequenceParser(groupfile, fastafile);                    }
268                 groups = parser->getNamesOfGroups();
269                         }
270             
271                         if(processors == 1)     {       driverGroups(newFastaFile, newNamesFile, newMapFile, 0, groups.size(), groups); }
272                         else                            {       createProcessesGroups(newFastaFile, newNamesFile, newMapFile, groups);                  }
273                         
274                         if (countfile != "") { 
275                 mergeGroupCounts(newCountFile, newNamesFile, newFastaFile);
276                 delete cparser; 
277             }else {  
278                 delete parser; 
279                 //run unique.seqs for deconvolute results
280                 string inputString = "fasta=" + newFastaFile;
281                 if (namefile != "") { inputString += ", name=" + newNamesFile; }
282                 m->mothurOutEndLine(); 
283                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
284                 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
285                 m->mothurCalling = true;
286                 
287                 Command* uniqueCommand = new DeconvoluteCommand(inputString);
288                 uniqueCommand->execute();
289                 
290                 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
291                 
292                 delete uniqueCommand;
293                 m->mothurCalling = false;
294                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
295                 
296                 m->renameFile(filenames["fasta"][0], newFastaFile);
297                 m->renameFile(filenames["name"][0], newNamesFile); 
298                         }
299             if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {    m->mothurRemove(outputNames[i]);        }        return 0; }
300                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run pre.cluster."); m->mothurOutEndLine(); 
301                                 
302                 }else {
303                         if (namefile != "") { readNameFile(); }
304                 
305                         //reads fasta file and return number of seqs
306                         int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
307                 
308                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
309         
310                         if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
311                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
312                         
313                         int count = process(newMapFile);
314                         outputNames.push_back(newMapFile); outputTypes["map"].push_back(newMapFile);
315                         
316                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }   
317                         
318                         m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
319                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
320                         if (countfile != "") { newNamesFile = newCountFile; }
321             printData(newFastaFile, newNamesFile, "");
322                                 
323                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
324                 }
325                                 
326                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
327                 
328                 m->mothurOutEndLine();
329                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
330                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }               
331                 m->mothurOutEndLine();
332                 
333                 //set fasta file as new current fastafile
334                 string current = "";
335                 itTypes = outputTypes.find("fasta");
336                 if (itTypes != outputTypes.end()) {
337                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
338                 }
339                 
340                 itTypes = outputTypes.find("name");
341                 if (itTypes != outputTypes.end()) {
342                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
343                 }
344         
345         itTypes = outputTypes.find("count");
346                 if (itTypes != outputTypes.end()) {
347                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
348                 }
349                 
350                 return 0;
351                 
352         }
353         catch(exception& e) {
354                 m->errorOut(e, "PreClusterCommand", "execute");
355                 exit(1);
356         }
357 }
358 /**************************************************************************************************/
359 int PreClusterCommand::createProcessesGroups(string newFName, string newNName, string newMFile, vector<string> groups) {
360         try {
361                 
362                 vector<int> processIDS;
363                 int process = 1;
364                 int num = 0;
365                 
366                 //sanity check
367                 if (groups.size() < processors) { processors = groups.size(); }
368                 
369                 //divide the groups between the processors
370                 vector<linePair> lines;
371                 int numGroupsPerProcessor = groups.size() / processors;
372                 for (int i = 0; i < processors; i++) {
373                         int startIndex =  i * numGroupsPerProcessor;
374                         int endIndex = (i+1) * numGroupsPerProcessor;
375                         if(i == (processors - 1)){      endIndex = groups.size();       }
376                         lines.push_back(linePair(startIndex, endIndex));
377                 }
378                 
379 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)          
380                 
381                 //loop through and create all the processes you want
382                 while (process != processors) {
383                         int pid = fork();
384                         
385                         if (pid > 0) {
386                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
387                                 process++;
388                         }else if (pid == 0){
389                 outputNames.clear();
390                                 num = driverGroups(newFName + toString(getpid()) + ".temp", newNName + toString(getpid()) + ".temp", newMFile, lines[process].start, lines[process].end, groups);
391                 
392                 string tempFile = toString(getpid()) + ".outputNames.temp";
393                 ofstream outTemp;
394                 m->openOutputFile(tempFile, outTemp);
395                 
396                 outTemp << outputNames.size();
397                 for (int i = 0; i < outputNames.size(); i++) { outTemp << outputNames[i] << endl; }
398                 outTemp.close();
399                 
400                                 exit(0);
401                         }else { 
402                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
403                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
404                                 exit(0);
405                         }
406                 }
407                 
408                 //do my part
409                 num = driverGroups(newFName, newNName, newMFile, lines[0].start, lines[0].end, groups);
410                 
411                 //force parent to wait until all the processes are done
412                 for (int i=0;i<processIDS.size();i++) { 
413                         int temp = processIDS[i];
414                         wait(&temp);
415                 }
416         
417         for (int i = 0; i < processIDS.size(); i++) {
418             string tempFile = toString(processIDS[i]) +  ".outputNames.temp";
419             ifstream intemp;
420             m->openInputFile(tempFile, intemp);
421             
422             int num;
423             intemp >> num;
424             for (int k = 0; k < num; k++) {
425                 string name = "";
426                 intemp >> name; m->gobble(intemp);
427                 
428                 outputNames.push_back(name); outputTypes["map"].push_back(name);
429             }
430             intemp.close();
431             m->mothurRemove(tempFile);
432         }
433 #else
434                 
435                 //////////////////////////////////////////////////////////////////////////////////////////////////////
436                 //Windows version shared memory, so be careful when passing variables through the preClusterData struct. 
437                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
438                 //////////////////////////////////////////////////////////////////////////////////////////////////////
439                 
440                 vector<preClusterData*> pDataArray; 
441                 DWORD   dwThreadIdArray[processors-1];
442                 HANDLE  hThreadArray[processors-1]; 
443                 
444                 //Create processor worker threads.
445                 for( int i=1; i<processors; i++ ){
446                         // Allocate memory for thread data.
447                         string extension = toString(i) + ".temp";
448                         
449                         preClusterData* tempPreCluster = new preClusterData(fastafile, namefile, groupfile, countfile, (newFName+extension), (newNName+extension), newMFile, groups, m, lines[i].start, lines[i].end, diffs, topdown, i);
450                         pDataArray.push_back(tempPreCluster);
451                         processIDS.push_back(i);
452                         
453                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
454                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
455                         hThreadArray[i-1] = CreateThread(NULL, 0, MyPreclusterThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
456                 }
457                 
458                                 
459                 //using the main process as a worker saves time and memory
460                 num = driverGroups(newFName, newNName, newMFile, lines[0].start, lines[0].end, groups);
461                 
462                 //Wait until all threads have terminated.
463                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
464                 
465                 //Close all thread handles and free memory allocations.
466                 for(int i=0; i < pDataArray.size(); i++){
467                         for (int j = 0; j < pDataArray[i]->mapFileNames.size(); j++) {
468                                 outputNames.push_back(pDataArray[i]->mapFileNames[j]); outputTypes["map"].push_back(pDataArray[i]->mapFileNames[j]); 
469                         }
470                         CloseHandle(hThreadArray[i]);
471                         delete pDataArray[i];
472                 }
473                 
474 #endif          
475                 
476                 //append output files
477                 for(int i=0;i<processIDS.size();i++){
478                         //newFName = m->getFullPathName(".\\" + newFName);
479                         //newNName = m->getFullPathName(".\\" + newNName);
480                         
481                         m->appendFiles((newFName + toString(processIDS[i]) + ".temp"), newFName);
482                         m->mothurRemove((newFName + toString(processIDS[i]) + ".temp"));
483                         
484                         m->appendFiles((newNName + toString(processIDS[i]) + ".temp"), newNName);
485                         m->mothurRemove((newNName + toString(processIDS[i]) + ".temp"));
486                 }
487                 
488                 return num;     
489                 
490         }
491         catch(exception& e) {
492                 m->errorOut(e, "PreClusterCommand", "createProcessesGroups");
493                 exit(1);
494         }
495 }
496 /**************************************************************************************************/
497 int PreClusterCommand::driverGroups(string newFFile, string newNFile, string newMFile, int start, int end, vector<string> groups){
498         try {
499                 
500                 int numSeqs = 0;
501                 
502                 //precluster each group
503                 for (int i = start; i < end; i++) {
504                         
505                         start = time(NULL);
506                         
507                         if (m->control_pressed) {  return 0; }
508                         
509                         m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[i] + ":"); m->mothurOutEndLine();
510                         
511                         map<string, string> thisNameMap;
512             vector<Sequence> thisSeqs;
513                         if (groupfile != "") { 
514                 thisSeqs = parser->getSeqs(groups[i]);
515             }else if (countfile != "") {
516                 thisSeqs = cparser->getSeqs(groups[i]);
517             }
518                         if (namefile != "") {  thisNameMap = parser->getNameMap(groups[i]); }
519             
520                         //fill alignSeqs with this groups info.
521                         numSeqs = loadSeqs(thisNameMap, thisSeqs, groups[i]);
522                         
523                         if (m->control_pressed) {   return 0; }
524                         
525                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); m->control_pressed = true; return 0;  }
526                         
527                         int count= process(newMFile+groups[i]+".map");
528                         outputNames.push_back(newMFile+groups[i]+".map"); outputTypes["map"].push_back(newMFile+groups[i]+".map");
529                         
530                         if (m->control_pressed) {  return 0; }
531                         
532                         m->mothurOut("Total number of sequences before pre.cluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
533                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
534                         printData(newFFile, newNFile, groups[i]);
535                         
536                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
537                         
538                 }
539                 
540                 return numSeqs;
541         }
542         catch(exception& e) {
543                 m->errorOut(e, "PreClusterCommand", "driverGroups");
544                 exit(1);
545         }
546 }
547 /**************************************************************************************************/
548 int PreClusterCommand::process(string newMapFile){
549         try {
550                 ofstream out;
551                 m->openOutputFile(newMapFile, out);
552                 
553                 //sort seqs by number of identical seqs
554         if (topdown) { sort(alignSeqs.begin(), alignSeqs.end(), comparePriorityTopDown);  }
555         else {  sort(alignSeqs.begin(), alignSeqs.end(), comparePriorityDownTop);  }
556                 
557                 int count = 0;
558                 int numSeqs = alignSeqs.size();
559                 
560                 //think about running through twice...
561                 for (int i = 0; i < numSeqs; i++) {
562                         
563                         //are you active
564                         //                      itActive = active.find(alignSeqs[i].seq.getName());
565                         
566                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
567                                 
568                                 string chunk = alignSeqs[i].seq.getName() + "\t" + toString(alignSeqs[i].numIdentical) + "\t" + toString(0) + "\t" + alignSeqs[i].seq.getAligned() + "\n";
569                                 
570                                 //try to merge it with all smaller seqs
571                                 for (int j = i+1; j < numSeqs; j++) {
572                                         
573                                         if (m->control_pressed) { out.close(); return 0; }
574                                         
575                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
576                                                 //are you within "diff" bases
577                                                 int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
578                                                 
579                                                 if (mismatch <= diffs) {
580                                                         //merge
581                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
582                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
583                                                         
584                                                         chunk += alignSeqs[j].seq.getName() + "\t" + toString(alignSeqs[j].numIdentical) + "\t" + toString(mismatch) + "\t" + alignSeqs[j].seq.getAligned() + "\n";
585                                                         
586                                                         alignSeqs[j].active = 0;
587                                                         alignSeqs[j].numIdentical = 0;
588                                                         count++;
589                                                 }
590                                         }//end if j active
591                                 }//end for loop j
592                                 
593                                 //remove from active list 
594                                 alignSeqs[i].active = 0;
595                                 
596                                 out << "ideal_seq_" << (i+1) << '\t' << alignSeqs[i].numIdentical << endl << chunk << endl;;
597                                 
598                         }//end if active i
599                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
600                 }
601                 out.close();
602                 
603                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }       
604                 
605                 return count;
606                 
607         }
608         catch(exception& e) {
609                 m->errorOut(e, "PreClusterCommand", "process");
610                 exit(1);
611         }
612 }
613 /**************************************************************************************************/
614 int PreClusterCommand::readFASTA(){
615         try {
616                 //ifstream inNames;
617                 ifstream inFasta;
618                 
619                 m->openInputFile(fastafile, inFasta);
620                 set<int> lengths;
621                 
622                 while (!inFasta.eof()) {
623                         
624                         if (m->control_pressed) { inFasta.close(); return 0; }
625                                                 
626                         Sequence seq(inFasta);  m->gobble(inFasta);
627                         
628                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
629                                 if (namefile != "") {
630                                         itSize = sizes.find(seq.getName());
631                                         
632                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
633                                         else{
634                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
635                                                 alignSeqs.push_back(tempNode);
636                                                 lengths.insert(seq.getAligned().length());
637                                         }       
638                                 }else { //no names file, you are identical to yourself 
639                     int numRep = 1;
640                     if (countfile != "") { numRep = ct.getNumSeqs(seq.getName()); }
641                                         seqPNode tempNode(numRep, seq, seq.getName());
642                                         alignSeqs.push_back(tempNode);
643                                         lengths.insert(seq.getAligned().length());
644                                 }
645                         }
646                 }
647                 inFasta.close();
648         
649         if (lengths.size() > 1) { m->control_pressed = true; m->mothurOut("[ERROR]: your sequences are not all the same length. pre.cluster requires sequences to be aligned."); m->mothurOutEndLine(); }
650         else if (lengths.size() == 1) { length = *(lengths.begin()); }
651         
652                 return alignSeqs.size();
653         }
654         
655         catch(exception& e) {
656                 m->errorOut(e, "PreClusterCommand", "readFASTA");
657                 exit(1);
658         }
659 }
660 /**************************************************************************************************/
661 int PreClusterCommand::loadSeqs(map<string, string>& thisName, vector<Sequence>& thisSeqs, string group){
662         try {
663                 set<int> lengths;
664                 alignSeqs.clear();
665                 map<string, string>::iterator it;
666                 bool error = false;
667         map<string, int> thisCount;
668         if (countfile != "") { thisCount = cparser->getCountTable(group);  }
669                 
670                 for (int i = 0; i < thisSeqs.size(); i++) {
671                         
672                         if (m->control_pressed) { return 0; }
673                                                 
674                         if (namefile != "") {
675                                 it = thisName.find(thisSeqs[i].getName());
676                                 
677                                 //should never be true since parser checks for this
678                                 if (it == thisName.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); error = true; }
679                                 else{
680                                         //get number of reps
681                                         int numReps = 1;
682                                         for(int j=0;j<(it->second).length();j++){
683                                                 if((it->second)[j] == ','){     numReps++;      }
684                                         }
685                                         
686                                         seqPNode tempNode(numReps, thisSeqs[i], it->second);
687                                         alignSeqs.push_back(tempNode);
688                     lengths.insert(thisSeqs[i].getAligned().length());
689                                 }       
690                         }else { //no names file, you are identical to yourself 
691                 int numRep = 1;
692                 if (countfile != "") { 
693                     map<string, int>::iterator it2 = thisCount.find(thisSeqs[i].getName());
694                     
695                     //should never be true since parser checks for this
696                     if (it2 == thisCount.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your count file, please correct."); m->mothurOutEndLine(); error = true; }
697                     else { numRep = it2->second;  }
698                 }
699                                 seqPNode tempNode(numRep, thisSeqs[i], thisSeqs[i].getName());
700                                 alignSeqs.push_back(tempNode);
701                                 lengths.insert(thisSeqs[i].getAligned().length());
702                         }
703                 }
704     
705         if (lengths.size() > 1) { error = true; m->mothurOut("[ERROR]: your sequences are not all the same length. pre.cluster requires sequences to be aligned."); m->mothurOutEndLine(); }
706         else if (lengths.size() == 1) { length = *(lengths.begin()); }
707         
708                 //sanity check
709                 if (error) { m->control_pressed = true; }
710                 
711                 thisSeqs.clear();
712                 
713                 return alignSeqs.size();
714         }
715         
716         catch(exception& e) {
717                 m->errorOut(e, "PreClusterCommand", "loadSeqs");
718                 exit(1);
719         }
720 }
721                                 
722 /**************************************************************************************************/
723
724 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
725         try {
726                 int numBad = 0;
727                 
728                 for (int i = 0; i < seq1.length(); i++) {
729                         //do they match
730                         if (seq1[i] != seq2[i]) { numBad++; }
731                         if (numBad > diffs) { return length;  } //to far to cluster
732                 }
733                 
734                 return numBad;
735         }
736         catch(exception& e) {
737                 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
738                 exit(1);
739         }
740 }
741 /**************************************************************************************************/
742
743 int PreClusterCommand::mergeGroupCounts(string newcount, string newname, string newfasta){
744         try {
745                 ifstream inNames;
746         m->openInputFile(newname, inNames);
747         
748         string group, first, second;
749         set<string> uniqueNames;
750         while (!inNames.eof()) {
751             if (m->control_pressed) { break; }
752             inNames >> group; m->gobble(inNames);
753             inNames >> first; m->gobble(inNames);
754             inNames >> second; m->gobble(inNames);
755             
756             vector<string> names;
757             m->splitAtComma(second, names);
758             
759             uniqueNames.insert(first);
760             
761             int total = ct.getGroupCount(first, group);
762             for (int i = 1; i < names.size(); i++) {
763                 total += ct.getGroupCount(names[i], group);
764                 ct.setAbund(names[i], group, 0);
765             }
766             ct.setAbund(first, group, total);
767         }
768         inNames.close();
769         
770         vector<string> namesOfSeqs = ct.getNamesOfSeqs();
771         for (int i = 0; i < namesOfSeqs.size(); i++) {
772             if (ct.getNumSeqs(namesOfSeqs[i]) == 0) {
773                 ct.remove(namesOfSeqs[i]);
774             }
775         }
776         
777         ct.printTable(newcount); 
778         m->mothurRemove(newname);
779         
780         if (bygroup) { //if by group, must remove the duplicate seqs that are named the same
781             ifstream in;
782             m->openInputFile(newfasta, in);
783             
784             ofstream out;
785             m->openOutputFile(newfasta+"temp", out);
786             
787             int count = 0;
788             set<string> already;
789             while(!in.eof()) {
790                 if (m->control_pressed) { break; }
791                 
792                 Sequence seq(in); m->gobble(in);
793                 
794                 if (seq.getName() != "") {
795                     count++;
796                     if (already.count(seq.getName()) == 0) {
797                         seq.printSequence(out);
798                         already.insert(seq.getName());
799                     }
800                 }
801             }
802             in.close();
803             out.close();
804             m->mothurRemove(newfasta);
805             m->renameFile(newfasta+"temp", newfasta);
806         }
807                         return 0;
808                 
809         }
810         catch(exception& e) {
811                 m->errorOut(e, "PreClusterCommand", "mergeGroupCounts");
812                 exit(1);
813         }
814 }
815
816 /**************************************************************************************************/
817
818 void PreClusterCommand::printData(string newfasta, string newname, string group){
819         try {
820                 ofstream outFasta;
821                 ofstream outNames;
822                 
823                 if (bygroup) {
824                         m->openOutputFileAppend(newfasta, outFasta);
825                         m->openOutputFileAppend(newname, outNames);
826                 }else {
827                         m->openOutputFile(newfasta, outFasta);
828                         m->openOutputFile(newname, outNames);
829                 }
830                 
831         if ((countfile != "") && (group == ""))  { outNames << "Representative_Sequence\ttotal\n";  }
832                 for (int i = 0; i < alignSeqs.size(); i++) {
833                         if (alignSeqs[i].numIdentical != 0) {
834                                 alignSeqs[i].seq.printSequence(outFasta); 
835                                 if (countfile != "") {  
836                     if (group != "") {  outNames << group << '\t' << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl; }
837                     else {  outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].numIdentical << endl;  }
838                 }else {  outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;  }
839                         }
840                 }
841                 
842                 outFasta.close();
843                 outNames.close();
844                 
845         }
846         catch(exception& e) {
847                 m->errorOut(e, "PreClusterCommand", "printData");
848                 exit(1);
849         }
850 }
851 /**************************************************************************************************/
852
853 void PreClusterCommand::readNameFile(){
854         try {
855                 ifstream in;
856                 m->openInputFile(namefile, in);
857                 string firstCol, secondCol;
858                                 
859                 while (!in.eof()) {
860                         in >> firstCol >> secondCol; m->gobble(in);
861                         names[firstCol] = secondCol;
862                         int size = 1;
863
864                         for(int i=0;i<secondCol.size();i++){
865                                 if(secondCol[i] == ','){        size++; }
866                         }
867                         sizes[firstCol] = size;
868                 }
869                 in.close();
870         }
871         catch(exception& e) {
872                 m->errorOut(e, "PreClusterCommand", "readNameFile");
873                 exit(1);
874         }
875 }
876
877 /**************************************************************************************************/
878
879