]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
working on pam
[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", "", "1", "", "", "","",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, meaning 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, true, false);
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 (processors != 1) { m->mothurOut("When using running without group information mothur can only use 1 processor, continuing."); m->mothurOutEndLine(); processors = 1; }
304                         if (namefile != "") { readNameFile(); }
305                 
306                         //reads fasta file and return number of seqs
307                         int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
308                 
309                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
310         
311                         if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
312                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
313                         
314                         int count = process(newMapFile);
315                         outputNames.push_back(newMapFile); outputTypes["map"].push_back(newMapFile);
316                         
317                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }   
318                         
319                         m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
320                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
321                         if (countfile != "") { newNamesFile = newCountFile; }
322             printData(newFastaFile, newNamesFile, "");
323                                 
324                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
325                 }
326                                 
327                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
328                 
329                 m->mothurOutEndLine();
330                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
331                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }               
332                 m->mothurOutEndLine();
333                 
334                 //set fasta file as new current fastafile
335                 string current = "";
336                 itTypes = outputTypes.find("fasta");
337                 if (itTypes != outputTypes.end()) {
338                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
339                 }
340                 
341                 itTypes = outputTypes.find("name");
342                 if (itTypes != outputTypes.end()) {
343                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
344                 }
345         
346         itTypes = outputTypes.find("count");
347                 if (itTypes != outputTypes.end()) {
348                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setCountTableFile(current); }
349                 }
350                 
351                 return 0;
352                 
353         }
354         catch(exception& e) {
355                 m->errorOut(e, "PreClusterCommand", "execute");
356                 exit(1);
357         }
358 }
359 /**************************************************************************************************/
360 int PreClusterCommand::createProcessesGroups(string newFName, string newNName, string newMFile, vector<string> groups) {
361         try {
362                 
363                 vector<int> processIDS;
364                 int process = 1;
365                 int num = 0;
366                 
367                 //sanity check
368                 if (groups.size() < processors) { processors = groups.size(); }
369                 
370                 //divide the groups between the processors
371                 vector<linePair> lines;
372                 int numGroupsPerProcessor = groups.size() / processors;
373                 for (int i = 0; i < processors; i++) {
374                         int startIndex =  i * numGroupsPerProcessor;
375                         int endIndex = (i+1) * numGroupsPerProcessor;
376                         if(i == (processors - 1)){      endIndex = groups.size();       }
377                         lines.push_back(linePair(startIndex, endIndex));
378                 }
379                 
380 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)          
381                 
382                 //loop through and create all the processes you want
383                 while (process != processors) {
384                         int pid = fork();
385                         
386                         if (pid > 0) {
387                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
388                                 process++;
389                         }else if (pid == 0){
390                 outputNames.clear();
391                                 num = driverGroups(newFName + toString(getpid()) + ".temp", newNName + toString(getpid()) + ".temp", newMFile, lines[process].start, lines[process].end, groups);
392                 
393                 string tempFile = toString(getpid()) + ".outputNames.temp";
394                 ofstream outTemp;
395                 m->openOutputFile(tempFile, outTemp);
396                 
397                 outTemp << outputNames.size();
398                 for (int i = 0; i < outputNames.size(); i++) { outTemp << outputNames[i] << endl; }
399                 outTemp.close();
400                 
401                                 exit(0);
402                         }else { 
403                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
404                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
405                                 exit(0);
406                         }
407                 }
408                 
409                 //do my part
410                 num = driverGroups(newFName, newNName, newMFile, lines[0].start, lines[0].end, groups);
411                 
412                 //force parent to wait until all the processes are done
413                 for (int i=0;i<processIDS.size();i++) { 
414                         int temp = processIDS[i];
415                         wait(&temp);
416                 }
417         
418         for (int i = 0; i < processIDS.size(); i++) {
419             string tempFile = toString(processIDS[i]) +  ".outputNames.temp";
420             ifstream intemp;
421             m->openInputFile(tempFile, intemp);
422             
423             int num;
424             intemp >> num;
425             for (int k = 0; k < num; k++) {
426                 string name = "";
427                 intemp >> name; m->gobble(intemp);
428                 
429                 outputNames.push_back(name); outputTypes["map"].push_back(name);
430             }
431             intemp.close();
432             m->mothurRemove(tempFile);
433         }
434 #else
435                 
436                 //////////////////////////////////////////////////////////////////////////////////////////////////////
437                 //Windows version shared memory, so be careful when passing variables through the preClusterData struct. 
438                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
439                 //////////////////////////////////////////////////////////////////////////////////////////////////////
440                 
441                 vector<preClusterData*> pDataArray; 
442                 DWORD   dwThreadIdArray[processors-1];
443                 HANDLE  hThreadArray[processors-1]; 
444                 
445                 //Create processor worker threads.
446                 for( int i=1; i<processors; i++ ){
447                         // Allocate memory for thread data.
448                         string extension = toString(i) + ".temp";
449                         
450                         preClusterData* tempPreCluster = new preClusterData(fastafile, namefile, groupfile, countfile, (newFName+extension), (newNName+extension), newMFile, groups, m, lines[i].start, lines[i].end, diffs, topdown, i);
451                         pDataArray.push_back(tempPreCluster);
452                         processIDS.push_back(i);
453                         
454                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
455                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
456                         hThreadArray[i-1] = CreateThread(NULL, 0, MyPreclusterThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
457                 }
458                 
459                                 
460                 //using the main process as a worker saves time and memory
461                 num = driverGroups(newFName, newNName, newMFile, lines[0].start, lines[0].end, groups);
462                 
463                 //Wait until all threads have terminated.
464                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
465                 
466                 //Close all thread handles and free memory allocations.
467                 for(int i=0; i < pDataArray.size(); i++){
468             if (pDataArray[i]->count != (pDataArray[i]->end-pDataArray[i]->start)) {
469                 m->mothurOut("[ERROR]: process " + toString(i) + " only processed " + toString(pDataArray[i]->count) + " of " + toString(pDataArray[i]->end-pDataArray[i]->start) + " groups assigned to it, quitting. \n"); m->control_pressed = true; 
470             }
471                         for (int j = 0; j < pDataArray[i]->mapFileNames.size(); j++) {
472                                 outputNames.push_back(pDataArray[i]->mapFileNames[j]); outputTypes["map"].push_back(pDataArray[i]->mapFileNames[j]); 
473                         }
474                         CloseHandle(hThreadArray[i]);
475                         delete pDataArray[i];
476                 }
477                 
478 #endif          
479                 
480                 //append output files
481                 for(int i=0;i<processIDS.size();i++){
482                         //newFName = m->getFullPathName(".\\" + newFName);
483                         //newNName = m->getFullPathName(".\\" + newNName);
484                         
485                         m->appendFiles((newFName + toString(processIDS[i]) + ".temp"), newFName);
486                         m->mothurRemove((newFName + toString(processIDS[i]) + ".temp"));
487                         
488                         m->appendFiles((newNName + toString(processIDS[i]) + ".temp"), newNName);
489                         m->mothurRemove((newNName + toString(processIDS[i]) + ".temp"));
490                 }
491                 
492                 return num;     
493                 
494         }
495         catch(exception& e) {
496                 m->errorOut(e, "PreClusterCommand", "createProcessesGroups");
497                 exit(1);
498         }
499 }
500 /**************************************************************************************************/
501 int PreClusterCommand::driverGroups(string newFFile, string newNFile, string newMFile, int start, int end, vector<string> groups){
502         try {
503                 
504                 int numSeqs = 0;
505                 
506                 //precluster each group
507                 for (int i = start; i < end; i++) {
508                         
509                         start = time(NULL);
510                         
511                         if (m->control_pressed) {  return 0; }
512                         
513                         m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[i] + ":"); m->mothurOutEndLine();
514                         
515                         map<string, string> thisNameMap;
516             vector<Sequence> thisSeqs;
517                         if (groupfile != "") { 
518                 thisSeqs = parser->getSeqs(groups[i]);
519             }else if (countfile != "") {
520                 thisSeqs = cparser->getSeqs(groups[i]);
521             }
522                         if (namefile != "") {  thisNameMap = parser->getNameMap(groups[i]); }
523             
524                         //fill alignSeqs with this groups info.
525                         numSeqs = loadSeqs(thisNameMap, thisSeqs, groups[i]);
526                         
527                         if (m->control_pressed) {   return 0; }
528                         
529                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); m->control_pressed = true; return 0;  }
530                         
531                         int count= process(newMFile+groups[i]+".map");
532                         outputNames.push_back(newMFile+groups[i]+".map"); outputTypes["map"].push_back(newMFile+groups[i]+".map");
533                         
534                         if (m->control_pressed) {  return 0; }
535                         
536                         m->mothurOut("Total number of sequences before pre.cluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
537                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
538                         printData(newFFile, newNFile, groups[i]);
539                         
540                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
541                         
542                 }
543                 
544                 return numSeqs;
545         }
546         catch(exception& e) {
547                 m->errorOut(e, "PreClusterCommand", "driverGroups");
548                 exit(1);
549         }
550 }
551 /**************************************************************************************************/
552 int PreClusterCommand::process(string newMapFile){
553         try {
554                 ofstream out;
555                 m->openOutputFile(newMapFile, out);
556                 
557                 //sort seqs by number of identical seqs
558         if (topdown) { sort(alignSeqs.begin(), alignSeqs.end(), comparePriorityTopDown);  }
559         else {  sort(alignSeqs.begin(), alignSeqs.end(), comparePriorityDownTop);  }
560                 
561                 int count = 0;
562                 int numSeqs = alignSeqs.size();
563                 
564         if (topdown) {
565             //think about running through twice...
566             for (int i = 0; i < numSeqs; i++) {
567                 
568                 if (alignSeqs[i].active) {  //this sequence has not been merged yet
569                     
570                     string chunk = alignSeqs[i].seq.getName() + "\t" + toString(alignSeqs[i].numIdentical) + "\t" + toString(0) + "\t" + alignSeqs[i].seq.getAligned() + "\n";
571                     
572                     //try to merge it with all smaller seqs
573                     for (int j = i+1; j < numSeqs; j++) {
574                         
575                         if (m->control_pressed) { out.close(); return 0; }
576                         
577                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
578                             //are you within "diff" bases
579                             int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
580                             
581                             if (mismatch <= diffs) {
582                                 //merge
583                                 alignSeqs[i].names += ',' + alignSeqs[j].names;
584                                 alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
585                                 
586                                 chunk += alignSeqs[j].seq.getName() + "\t" + toString(alignSeqs[j].numIdentical) + "\t" + toString(mismatch) + "\t" + alignSeqs[j].seq.getAligned() + "\n";
587                                 
588                                 alignSeqs[j].active = 0;
589                                 alignSeqs[j].numIdentical = 0;
590                                 count++;
591                             }
592                         }//end if j active
593                     }//end for loop j
594                     
595                     //remove from active list 
596                     alignSeqs[i].active = 0;
597                     
598                     out << "ideal_seq_" << (i+1) << '\t' << alignSeqs[i].numIdentical << endl << chunk << endl;;
599                     
600                 }//end if active i
601                 if(i % 100 == 0)        { m->mothurOutJustToScreen(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)+"\n");       }
602             }
603         }else {
604             map<int, string> mapFile;
605             map<int, int> originalCount;
606             map<int, int>::iterator itCount;
607             for (int i = 0; i < numSeqs; i++) { mapFile[i] = ""; originalCount[i] = alignSeqs[i].numIdentical; }
608             
609             //think about running through twice...
610             for (int i = 0; i < numSeqs; i++) {
611                 
612                 //try to merge it into larger seqs
613                 for (int j = i+1; j < numSeqs; j++) {
614                     
615                     if (m->control_pressed) { out.close(); return 0; }
616                     
617                     if (originalCount[j] > originalCount[i]) {  //this sequence is more abundant than I am
618                         //are you within "diff" bases
619                         int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
620                         
621                         if (mismatch <= diffs) {
622                             //merge
623                             alignSeqs[j].names += ',' + alignSeqs[i].names;
624                             alignSeqs[j].numIdentical += alignSeqs[i].numIdentical;
625                             
626                             mapFile[j] = alignSeqs[i].seq.getName() + "\t" + toString(alignSeqs[i].numIdentical) + "\t" + toString(mismatch) + "\t" + alignSeqs[i].seq.getAligned() + "\n" + mapFile[i];
627                             alignSeqs[i].numIdentical = 0;
628                             originalCount.erase(i);
629                             mapFile[i] = "";
630                             count++;
631                             j+=numSeqs; //exit search, we merged this one in.
632                         }
633                     }//end abundance check
634                 }//end for loop j
635                 
636                 if(i % 100 == 0)        { m->mothurOutJustToScreen(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)+"\n");       }
637             }
638             
639             for (int i = 0; i < numSeqs; i++) {
640                 if (alignSeqs[i].numIdentical != 0) {
641                     out << "ideal_seq_" << (i+1) << '\t' << alignSeqs[i].numIdentical << endl  << alignSeqs[i].seq.getName() + "\t" + toString(alignSeqs[i].numIdentical) + "\t" + toString(0) + "\t" + alignSeqs[i].seq.getAligned() + "\n" << mapFile[i] << endl;
642                 }
643             }
644             
645         }
646                 out.close();
647                 
648                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }       
649                 
650                 return count;
651                 
652         }
653         catch(exception& e) {
654                 m->errorOut(e, "PreClusterCommand", "process");
655                 exit(1);
656         }
657 }
658 /**************************************************************************************************/
659 int PreClusterCommand::readFASTA(){
660         try {
661                 //ifstream inNames;
662                 ifstream inFasta;
663                 
664                 m->openInputFile(fastafile, inFasta);
665                 set<int> lengths;
666                 
667                 while (!inFasta.eof()) {
668                         
669                         if (m->control_pressed) { inFasta.close(); return 0; }
670                                                 
671                         Sequence seq(inFasta);  m->gobble(inFasta);
672                         
673                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
674                                 if (namefile != "") {
675                                         itSize = sizes.find(seq.getName());
676                                         
677                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
678                                         else{
679                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
680                                                 alignSeqs.push_back(tempNode);
681                                                 lengths.insert(seq.getAligned().length());
682                                         }       
683                                 }else { //no names file, you are identical to yourself 
684                     int numRep = 1;
685                     if (countfile != "") { numRep = ct.getNumSeqs(seq.getName()); }
686                                         seqPNode tempNode(numRep, seq, seq.getName());
687                                         alignSeqs.push_back(tempNode);
688                                         lengths.insert(seq.getAligned().length());
689                                 }
690                         }
691                 }
692                 inFasta.close();
693         
694         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(); }
695         else if (lengths.size() == 1) { length = *(lengths.begin()); }
696         
697                 return alignSeqs.size();
698         }
699         
700         catch(exception& e) {
701                 m->errorOut(e, "PreClusterCommand", "readFASTA");
702                 exit(1);
703         }
704 }
705 /**************************************************************************************************/
706 int PreClusterCommand::loadSeqs(map<string, string>& thisName, vector<Sequence>& thisSeqs, string group){
707         try {
708                 set<int> lengths;
709                 alignSeqs.clear();
710                 map<string, string>::iterator it;
711                 bool error = false;
712         map<string, int> thisCount;
713         if (countfile != "") { thisCount = cparser->getCountTable(group);  }
714                 
715                 for (int i = 0; i < thisSeqs.size(); i++) {
716                         
717                         if (m->control_pressed) { return 0; }
718                                                 
719                         if (namefile != "") {
720                                 it = thisName.find(thisSeqs[i].getName());
721                                 
722                                 //should never be true since parser checks for this
723                                 if (it == thisName.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); error = true; }
724                                 else{
725                                         //get number of reps
726                                         int numReps = 1;
727                                         for(int j=0;j<(it->second).length();j++){
728                                                 if((it->second)[j] == ','){     numReps++;      }
729                                         }
730                                         
731                                         seqPNode tempNode(numReps, thisSeqs[i], it->second);
732                                         alignSeqs.push_back(tempNode);
733                     lengths.insert(thisSeqs[i].getAligned().length());
734                                 }       
735                         }else { //no names file, you are identical to yourself 
736                 int numRep = 1;
737                 if (countfile != "") { 
738                     map<string, int>::iterator it2 = thisCount.find(thisSeqs[i].getName());
739                     
740                     //should never be true since parser checks for this
741                     if (it2 == thisCount.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your count file, please correct."); m->mothurOutEndLine(); error = true; }
742                     else { numRep = it2->second;  }
743                 }
744                                 seqPNode tempNode(numRep, thisSeqs[i], thisSeqs[i].getName());
745                                 alignSeqs.push_back(tempNode);
746                                 lengths.insert(thisSeqs[i].getAligned().length());
747                         }
748                 }
749     
750         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(); }
751         else if (lengths.size() == 1) { length = *(lengths.begin()); }
752         
753                 //sanity check
754                 if (error) { m->control_pressed = true; }
755                 
756                 thisSeqs.clear();
757                 
758                 return alignSeqs.size();
759         }
760         
761         catch(exception& e) {
762                 m->errorOut(e, "PreClusterCommand", "loadSeqs");
763                 exit(1);
764         }
765 }
766                                 
767 /**************************************************************************************************/
768
769 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
770         try {
771                 int numBad = 0;
772                 
773                 for (int i = 0; i < seq1.length(); i++) {
774                         //do they match
775                         if (seq1[i] != seq2[i]) { numBad++; }
776                         if (numBad > diffs) { return length;  } //to far to cluster
777                 }
778                 
779                 return numBad;
780         }
781         catch(exception& e) {
782                 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
783                 exit(1);
784         }
785 }
786 /**************************************************************************************************/
787
788 int PreClusterCommand::mergeGroupCounts(string newcount, string newname, string newfasta){
789         try {
790                 ifstream inNames;
791         m->openInputFile(newname, inNames);
792         
793         string group, first, second;
794         set<string> uniqueNames;
795         while (!inNames.eof()) {
796             if (m->control_pressed) { break; }
797             inNames >> group; m->gobble(inNames);
798             inNames >> first; m->gobble(inNames);
799             inNames >> second; m->gobble(inNames);
800             
801             vector<string> names;
802             m->splitAtComma(second, names);
803             
804             uniqueNames.insert(first);
805             
806             int total = ct.getGroupCount(first, group);
807             for (int i = 1; i < names.size(); i++) {
808                 total += ct.getGroupCount(names[i], group);
809                 ct.setAbund(names[i], group, 0);
810             }
811             ct.setAbund(first, group, total);
812         }
813         inNames.close();
814         
815         vector<string> namesOfSeqs = ct.getNamesOfSeqs();
816         for (int i = 0; i < namesOfSeqs.size(); i++) {
817             if (ct.getNumSeqs(namesOfSeqs[i]) == 0) {
818                 ct.remove(namesOfSeqs[i]);
819             }
820         }
821         
822         ct.printTable(newcount); 
823         m->mothurRemove(newname);
824         
825         if (bygroup) { //if by group, must remove the duplicate seqs that are named the same
826             ifstream in;
827             m->openInputFile(newfasta, in);
828             
829             ofstream out;
830             m->openOutputFile(newfasta+"temp", out);
831             
832             int count = 0;
833             set<string> already;
834             while(!in.eof()) {
835                 if (m->control_pressed) { break; }
836                 
837                 Sequence seq(in); m->gobble(in);
838                 
839                 if (seq.getName() != "") {
840                     count++;
841                     if (already.count(seq.getName()) == 0) {
842                         seq.printSequence(out);
843                         already.insert(seq.getName());
844                     }
845                 }
846             }
847             in.close();
848             out.close();
849             m->mothurRemove(newfasta);
850             m->renameFile(newfasta+"temp", newfasta);
851         }
852                         return 0;
853                 
854         }
855         catch(exception& e) {
856                 m->errorOut(e, "PreClusterCommand", "mergeGroupCounts");
857                 exit(1);
858         }
859 }
860
861 /**************************************************************************************************/
862
863 void PreClusterCommand::printData(string newfasta, string newname, string group){
864         try {
865                 ofstream outFasta;
866                 ofstream outNames;
867                 
868                 if (bygroup) {
869                         m->openOutputFileAppend(newfasta, outFasta);
870                         m->openOutputFileAppend(newname, outNames);
871                 }else {
872                         m->openOutputFile(newfasta, outFasta);
873                         m->openOutputFile(newname, outNames);
874                 }
875                 
876         if ((countfile != "") && (group == ""))  { outNames << "Representative_Sequence\ttotal\n";  }
877                 for (int i = 0; i < alignSeqs.size(); i++) {
878                         if (alignSeqs[i].numIdentical != 0) {
879                                 alignSeqs[i].seq.printSequence(outFasta); 
880                                 if (countfile != "") {  
881                     if (group != "") {  outNames << group << '\t' << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl; }
882                     else {  outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].numIdentical << endl;  }
883                 }else {  outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;  }
884                         }
885                 }
886                 
887                 outFasta.close();
888                 outNames.close();
889                 
890         }
891         catch(exception& e) {
892                 m->errorOut(e, "PreClusterCommand", "printData");
893                 exit(1);
894         }
895 }
896 /**************************************************************************************************/
897
898 void PreClusterCommand::readNameFile(){
899         try {
900                 ifstream in;
901                 m->openInputFile(namefile, in);
902                 string firstCol, secondCol;
903                                 
904                 while (!in.eof()) {
905                         in >> firstCol >> secondCol; m->gobble(in);
906             
907             m->checkName(firstCol);
908             m->checkName(secondCol);
909             int size = m->getNumNames(secondCol);
910             
911                         names[firstCol] = secondCol;
912             sizes[firstCol] = size;
913                 }
914                 in.close();
915         }
916         catch(exception& e) {
917                 m->errorOut(e, "PreClusterCommand", "readNameFile");
918                 exit(1);
919         }
920 }
921
922 /**************************************************************************************************/
923
924