]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
added pcr.seqs command. fixed bug in rarefacftion.single that caused parsing error...
[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",false,true); parameters.push_back(pfasta);
17                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
18                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
19                 CommandParameter pdiffs("diffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pdiffs);
20                 CommandParameter pprocessors("processors", "Number", "", "1", "", "", "",false,false); parameters.push_back(pprocessors);
21                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
22                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
23                 
24                 vector<string> myArray;
25                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
26                 return myArray;
27         }
28         catch(exception& e) {
29                 m->errorOut(e, "PreClusterCommand", "setParameters");
30                 exit(1);
31         }
32 }
33 //**********************************************************************************************************************
34 string PreClusterCommand::getHelpString(){      
35         try {
36                 string helpString = "";
37                 helpString += "The pre.cluster command groups sequences that are within a given number of base mismatches.\n";
38                 helpString += "The pre.cluster command outputs a new fasta and name file.\n";
39                 helpString += "The pre.cluster command parameters are fasta, names and diffs. The fasta parameter is required. \n";
40                 helpString += "The names 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";
41                 helpString += "The group parameter allows you to provide a group file so you can cluster by group. \n";
42                 helpString += "The diffs parameter allows you to specify maximum number of mismatched bases allowed between sequences in a grouping. The default is 1.\n";
43                 helpString += "The pre.cluster command should be in the following format: \n";
44                 helpString += "pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n";
45                 helpString += "Example pre.cluster(fasta=amazon.fasta, diffs=2).\n";
46                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
47                 return helpString;
48         }
49         catch(exception& e) {
50                 m->errorOut(e, "PreClusterCommand", "getHelpString");
51                 exit(1);
52         }
53 }
54
55 //**********************************************************************************************************************
56 PreClusterCommand::PreClusterCommand(){ 
57         try {
58                 abort = true; calledHelp = true; 
59                 setParameters();
60                 vector<string> tempOutNames;
61                 outputTypes["fasta"] = tempOutNames;
62                 outputTypes["name"] = tempOutNames;
63                 outputTypes["map"] = tempOutNames;
64         }
65         catch(exception& e) {
66                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
67                 exit(1);
68         }
69 }
70 //**********************************************************************************************************************
71
72 PreClusterCommand::PreClusterCommand(string option) {
73         try {
74                 abort = false; calledHelp = false;   
75                 
76                 //allow user to run help
77                 if(option == "help") { help(); abort = true; calledHelp = true; }
78                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
79                 
80                 else {
81                         vector<string> myArray = setParameters();
82                         
83                         OptionParser parser(option);
84                         map<string, string> parameters = parser.getParameters();
85                         
86                         ValidParameters validParameter;
87                         map<string, string>::iterator it;
88                 
89                         //check to make sure all parameters are valid for command
90                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
91                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
92                         }
93                         
94                         //initialize outputTypes
95                         vector<string> tempOutNames;
96                         outputTypes["fasta"] = tempOutNames;
97                         outputTypes["name"] = tempOutNames;
98                         outputTypes["map"] = tempOutNames;
99                 
100                         //if the user changes the input directory command factory will send this info to us in the output parameter 
101                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
102                         if (inputDir == "not found"){   inputDir = "";          }
103                         else {
104                                 string path;
105                                 it = parameters.find("fasta");
106                                 //user has given a template file
107                                 if(it != parameters.end()){ 
108                                         path = m->hasPath(it->second);
109                                         //if the user has not given a path then, add inputdir. else leave path alone.
110                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
111                                 }
112                                 
113                                 it = parameters.find("name");
114                                 //user has given a template file
115                                 if(it != parameters.end()){ 
116                                         path = m->hasPath(it->second);
117                                         //if the user has not given a path then, add inputdir. else leave path alone.
118                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
119                                 }
120                                 
121                                 it = parameters.find("group");
122                                 //user has given a template file
123                                 if(it != parameters.end()){ 
124                                         path = m->hasPath(it->second);
125                                         //if the user has not given a path then, add inputdir. else leave path alone.
126                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
127                                 }
128                         }
129
130                         //check for required parameters
131                         fastafile = validParameter.validFile(parameters, "fasta", true);
132                         if (fastafile == "not found") {                                 
133                                 fastafile = m->getFastaFile(); 
134                                 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
135                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
136                         }
137                         else if (fastafile == "not open") { abort = true; }     
138                         else { m->setFastaFile(fastafile); }
139                         
140                         //if the user changes the output directory command factory will send this info to us in the output parameter 
141                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
142                                 outputDir = ""; 
143                                 outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it       
144                         }
145
146                         //check for optional parameter and set defaults
147                         // ...at some point should added some additional type checking...
148                         namefile = validParameter.validFile(parameters, "name", true);
149                         if (namefile == "not found") { namefile =  "";  }
150                         else if (namefile == "not open") { namefile = ""; abort = true; }       
151                         else {  m->setNameFile(namefile); }
152                         
153                         groupfile = validParameter.validFile(parameters, "group", true);
154                         if (groupfile == "not found") { groupfile =  "";  bygroup = false; }
155                         else if (groupfile == "not open") { abort = true; groupfile =  ""; }    
156                         else {   m->setGroupFile(groupfile); bygroup = true;  }
157                         
158                         string temp     = validParameter.validFile(parameters, "diffs", false);         if(temp == "not found"){        temp = "1"; }
159                         m->mothurConvert(temp, diffs); 
160                         
161                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
162                         m->setProcessors(temp);
163                         m->mothurConvert(temp, processors);
164                         
165                         if (namefile == "") {
166                                 vector<string> files; files.push_back(fastafile);
167                                 parser.getNameFile(files);
168                         }
169                 }
170                                 
171         }
172         catch(exception& e) {
173                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
174                 exit(1);
175         }
176 }
177 //**********************************************************************************************************************
178
179 int PreClusterCommand::execute(){
180         try {
181                 
182                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
183                 
184                 int start = time(NULL);
185                 
186                 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
187                 string newFastaFile = fileroot + "precluster" + m->getExtension(fastafile);
188                 string newNamesFile = fileroot + "precluster.names";
189                 string newMapFile = fileroot + "precluster.map"; //add group name if by group
190                 outputNames.push_back(newFastaFile); outputTypes["fasta"].push_back(newFastaFile);
191                 outputNames.push_back(newNamesFile); outputTypes["name"].push_back(newNamesFile);
192                 
193                 
194                 if (bygroup) {
195                         //clear out old files
196                         ofstream outFasta; m->openOutputFile(newFastaFile, outFasta); outFasta.close();
197                         ofstream outNames; m->openOutputFile(newNamesFile, outNames);  outNames.close();
198                         newMapFile = fileroot + "precluster.";
199                         
200                         //parse fasta and name file by group
201                         SequenceParser* parser;
202                         if (namefile != "") { parser = new SequenceParser(groupfile, fastafile, namefile);      }
203                         else                            { parser = new SequenceParser(groupfile, fastafile);                    }
204                         
205                         vector<string> groups = parser->getNamesOfGroups();
206                         
207                         if(processors == 1)     {       driverGroups(parser, newFastaFile, newNamesFile, newMapFile, 0, groups.size(), groups); }
208                         else                            {       createProcessesGroups(parser, newFastaFile, newNamesFile, newMapFile, groups);                  }
209                         
210                         delete parser;
211                         
212                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        }        return 0; }
213                         
214                         //run unique.seqs for deconvolute results
215                         string inputString = "fasta=" + newFastaFile;
216                         if (namefile != "") { inputString += ", name=" + newNamesFile; }
217                         m->mothurOutEndLine(); 
218                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
219                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
220                         m->mothurCalling = true;
221             
222                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
223                         uniqueCommand->execute();
224                         
225                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
226                         
227                         delete uniqueCommand;
228                         m->mothurCalling = false;
229                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
230                         
231                         m->renameFile(filenames["fasta"][0], newFastaFile);
232                         
233                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run pre.cluster."); m->mothurOutEndLine(); 
234                                 
235                 }else {
236                         if (namefile != "") { readNameFile(); }
237                 
238                         //reads fasta file and return number of seqs
239                         int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
240                 
241                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
242         
243                         if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
244                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
245                         
246                         int count = process(newMapFile);
247                         outputNames.push_back(newMapFile); outputTypes["map"].push_back(newMapFile);
248                         
249                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }   
250                         
251                         m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
252                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
253                         printData(newFastaFile, newNamesFile);
254                         
255                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
256                 }
257                                 
258                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
259                 
260                 m->mothurOutEndLine();
261                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
262                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }               
263                 m->mothurOutEndLine();
264                 
265                 //set fasta file as new current fastafile
266                 string current = "";
267                 itTypes = outputTypes.find("fasta");
268                 if (itTypes != outputTypes.end()) {
269                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
270                 }
271                 
272                 itTypes = outputTypes.find("name");
273                 if (itTypes != outputTypes.end()) {
274                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
275                 }
276                 
277                 return 0;
278                 
279         }
280         catch(exception& e) {
281                 m->errorOut(e, "PreClusterCommand", "execute");
282                 exit(1);
283         }
284 }
285 /**************************************************************************************************/
286 int PreClusterCommand::createProcessesGroups(SequenceParser* parser, string newFName, string newNName, string newMFile, vector<string> groups) {
287         try {
288                 
289                 vector<int> processIDS;
290                 int process = 1;
291                 int num = 0;
292                 
293                 //sanity check
294                 if (groups.size() < processors) { processors = groups.size(); }
295                 
296                 //divide the groups between the processors
297                 vector<linePair> lines;
298                 int numGroupsPerProcessor = groups.size() / processors;
299                 for (int i = 0; i < processors; i++) {
300                         int startIndex =  i * numGroupsPerProcessor;
301                         int endIndex = (i+1) * numGroupsPerProcessor;
302                         if(i == (processors - 1)){      endIndex = groups.size();       }
303                         lines.push_back(linePair(startIndex, endIndex));
304                 }
305                 
306 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)          
307                 
308                 //loop through and create all the processes you want
309                 while (process != processors) {
310                         int pid = fork();
311                         
312                         if (pid > 0) {
313                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
314                                 process++;
315                         }else if (pid == 0){
316                                 num = driverGroups(parser, newFName + toString(getpid()) + ".temp", newNName + toString(getpid()) + ".temp", newMFile, lines[process].start, lines[process].end, groups);
317                                 exit(0);
318                         }else { 
319                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
320                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
321                                 exit(0);
322                         }
323                 }
324                 
325                 //do my part
326                 num = driverGroups(parser, newFName, newNName, newMFile, lines[0].start, lines[0].end, groups);
327                 
328                 //force parent to wait until all the processes are done
329                 for (int i=0;i<processIDS.size();i++) { 
330                         int temp = processIDS[i];
331                         wait(&temp);
332                 }
333                 
334 #else
335                 
336                 //////////////////////////////////////////////////////////////////////////////////////////////////////
337                 //Windows version shared memory, so be careful when passing variables through the preClusterData struct. 
338                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
339                 //////////////////////////////////////////////////////////////////////////////////////////////////////
340                 
341                 vector<preClusterData*> pDataArray; 
342                 DWORD   dwThreadIdArray[processors-1];
343                 HANDLE  hThreadArray[processors-1]; 
344                 
345                 //Create processor worker threads.
346                 for( int i=1; i<processors; i++ ){
347                         // Allocate memory for thread data.
348                         string extension = toString(i) + ".temp";
349                         
350                         preClusterData* tempPreCluster = new preClusterData(fastafile, namefile, groupfile, (newFName+extension), (newNName+extension), newMFile, groups, m, lines[i].start, lines[i].end, diffs, i);
351                         pDataArray.push_back(tempPreCluster);
352                         processIDS.push_back(i);
353                         
354                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
355                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
356                         hThreadArray[i-1] = CreateThread(NULL, 0, MyPreclusterThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
357                 }
358                 
359                                 
360                 //using the main process as a worker saves time and memory
361                 num = driverGroups(parser, newFName, newNName, newMFile, lines[0].start, lines[0].end, groups);
362                 
363                 //Wait until all threads have terminated.
364                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
365                 
366                 //Close all thread handles and free memory allocations.
367                 for(int i=0; i < pDataArray.size(); i++){
368                         for (int j = 0; j < pDataArray[i]->mapFileNames.size(); j++) {
369                                 outputNames.push_back(pDataArray[i]->mapFileNames[j]); outputTypes["map"].push_back(pDataArray[i]->mapFileNames[j]); 
370                         }
371                         CloseHandle(hThreadArray[i]);
372                         delete pDataArray[i];
373                 }
374                 
375 #endif          
376                 
377                 //append output files
378                 for(int i=0;i<processIDS.size();i++){
379                         //newFName = m->getFullPathName(".\\" + newFName);
380                         //newNName = m->getFullPathName(".\\" + newNName);
381                         
382                         m->appendFiles((newFName + toString(processIDS[i]) + ".temp"), newFName);
383                         m->mothurRemove((newFName + toString(processIDS[i]) + ".temp"));
384                         
385                         m->appendFiles((newNName + toString(processIDS[i]) + ".temp"), newNName);
386                         m->mothurRemove((newNName + toString(processIDS[i]) + ".temp"));
387                 }
388                 
389                 return num;     
390                 
391         }
392         catch(exception& e) {
393                 m->errorOut(e, "PreClusterCommand", "createProcessesGroups");
394                 exit(1);
395         }
396 }
397 /**************************************************************************************************/
398 int PreClusterCommand::driverGroups(SequenceParser* parser, string newFFile, string newNFile, string newMFile, int start, int end, vector<string> groups){
399         try {
400                 
401                 int numSeqs = 0;
402                 
403                 //precluster each group
404                 for (int i = start; i < end; i++) {
405                         
406                         start = time(NULL);
407                         
408                         if (m->control_pressed) {  return 0; }
409                         
410                         m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[i] + ":"); m->mothurOutEndLine();
411                         
412                         map<string, string> thisNameMap;
413                         if (namefile != "") { thisNameMap = parser->getNameMap(groups[i]); }
414                         vector<Sequence> thisSeqs = parser->getSeqs(groups[i]);
415                         
416                         //fill alignSeqs with this groups info.
417                         numSeqs = loadSeqs(thisNameMap, thisSeqs);
418                         
419                         if (m->control_pressed) {   return 0; }
420                         
421                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); m->control_pressed = true; return 0;  }
422                         
423                         int count = process(newMFile+groups[i]+".map");
424                         outputNames.push_back(newMFile+groups[i]+".map"); outputTypes["map"].push_back(newMFile+groups[i]+".map");
425                         
426                         if (m->control_pressed) {  return 0; }
427                         
428                         m->mothurOut("Total number of sequences before pre.cluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
429                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
430                         printData(newFFile, newNFile);
431                         
432                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
433                         
434                 }
435                 
436                 return numSeqs;
437         }
438         catch(exception& e) {
439                 m->errorOut(e, "PreClusterCommand", "driverGroups");
440                 exit(1);
441         }
442 }
443 /**************************************************************************************************/
444 int PreClusterCommand::process(string newMapFile){
445         try {
446                 ofstream out;
447                 m->openOutputFile(newMapFile, out);
448                 
449                 //sort seqs by number of identical seqs
450                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
451                 
452                 int count = 0;
453                 int numSeqs = alignSeqs.size();
454                 
455                 //think about running through twice...
456                 for (int i = 0; i < numSeqs; i++) {
457                         
458                         //are you active
459                         //                      itActive = active.find(alignSeqs[i].seq.getName());
460                         
461                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
462                                 
463                                 string chunk = alignSeqs[i].seq.getName() + "\t" + toString(alignSeqs[i].numIdentical) + "\t" + toString(0) + "\t" + alignSeqs[i].seq.getAligned() + "\n";
464                                 
465                                 //try to merge it with all smaller seqs
466                                 for (int j = i+1; j < numSeqs; j++) {
467                                         
468                                         if (m->control_pressed) { out.close(); return 0; }
469                                         
470                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
471                                                 //are you within "diff" bases
472                                                 int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
473                                                 
474                                                 if (mismatch <= diffs) {
475                                                         //merge
476                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
477                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
478                                                         
479                                                         chunk += alignSeqs[j].seq.getName() + "\t" + toString(alignSeqs[j].numIdentical) + "\t" + toString(mismatch) + "\t" + alignSeqs[j].seq.getAligned() + "\n";
480                                                         
481                                                         alignSeqs[j].active = 0;
482                                                         alignSeqs[j].numIdentical = 0;
483                                                         count++;
484                                                 }
485                                         }//end if j active
486                                 }//end for loop j
487                                 
488                                 //remove from active list 
489                                 alignSeqs[i].active = 0;
490                                 
491                                 out << "ideal_seq_" << (i+1) << '\t' << alignSeqs[i].numIdentical << endl << chunk << endl;;
492                                 
493                         }//end if active i
494                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
495                 }
496                 out.close();
497                 
498                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }       
499                 
500                 return count;
501                 
502         }
503         catch(exception& e) {
504                 m->errorOut(e, "PreClusterCommand", "process");
505                 exit(1);
506         }
507 }
508 /**************************************************************************************************/
509 int PreClusterCommand::readFASTA(){
510         try {
511                 //ifstream inNames;
512                 ifstream inFasta;
513                 
514                 //m->openInputFile(namefile, inNames);
515                 m->openInputFile(fastafile, inFasta);
516                 
517                 //string firstCol, secondCol, nameString;
518                 set<int> lengths;
519                 
520                 while (!inFasta.eof()) {
521                         
522                         if (m->control_pressed) { inFasta.close(); return 0; }
523                         
524                         //inNames >> firstCol >> secondCol;
525                         //nameString = secondCol;
526                         
527                         //m->gobble(inNames);
528                         //int size = 1;
529                         //while (secondCol.find_first_of(',') != -1) { 
530                         //      size++;
531                         //      secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
532                         //}
533                         
534                         Sequence seq(inFasta);  m->gobble(inFasta);
535                         
536                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
537                                 if (namefile != "") {
538                                         itSize = sizes.find(seq.getName());
539                                         
540                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
541                                         else{
542                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
543                                                 alignSeqs.push_back(tempNode);
544                                                 lengths.insert(seq.getAligned().length());
545                                         }       
546                                 }else { //no names file, you are identical to yourself 
547                                         seqPNode tempNode(1, seq, seq.getName());
548                                         alignSeqs.push_back(tempNode);
549                                         lengths.insert(seq.getAligned().length());
550                                 }
551                         }
552                 }
553                 inFasta.close();
554                 //inNames.close();
555         
556         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(); }
557         else if (lengths.size() == 1) { length = *(lengths.begin()); }
558         
559                 return alignSeqs.size();
560         }
561         
562         catch(exception& e) {
563                 m->errorOut(e, "PreClusterCommand", "readFASTA");
564                 exit(1);
565         }
566 }
567 /**************************************************************************************************/
568 int PreClusterCommand::loadSeqs(map<string, string>& thisName, vector<Sequence>& thisSeqs){
569         try {
570                 set<int> lengths;
571                 alignSeqs.clear();
572                 map<string, string>::iterator it;
573                 bool error = false;
574                         
575                 for (int i = 0; i < thisSeqs.size(); i++) {
576                         
577                         if (m->control_pressed) { return 0; }
578                                                 
579                         if (namefile != "") {
580                                 it = thisName.find(thisSeqs[i].getName());
581                                 
582                                 //should never be true since parser checks for this
583                                 if (it == thisName.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); error = true; }
584                                 else{
585                                         //get number of reps
586                                         int numReps = 1;
587                                         for(int j=0;j<(it->second).length();j++){
588                                                 if((it->second)[j] == ','){     numReps++;      }
589                                         }
590                                         
591                                         seqPNode tempNode(numReps, thisSeqs[i], it->second);
592                                         alignSeqs.push_back(tempNode);
593                     lengths.insert(thisSeqs[i].getAligned().length());
594                                 }       
595                         }else { //no names file, you are identical to yourself 
596                                 seqPNode tempNode(1, thisSeqs[i], thisSeqs[i].getName());
597                                 alignSeqs.push_back(tempNode);
598                                 lengths.insert(thisSeqs[i].getAligned().length());
599                         }
600                 }
601                 
602         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(); }
603         else if (lengths.size() == 1) { length = *(lengths.begin()); }
604         
605                 //sanity check
606                 if (error) { m->control_pressed = true; }
607                 
608                 thisSeqs.clear();
609                 
610                 return alignSeqs.size();
611         }
612         
613         catch(exception& e) {
614                 m->errorOut(e, "PreClusterCommand", "loadSeqs");
615                 exit(1);
616         }
617 }
618                                 
619 /**************************************************************************************************/
620
621 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
622         try {
623                 int numBad = 0;
624                 
625                 for (int i = 0; i < seq1.length(); i++) {
626                         //do they match
627                         if (seq1[i] != seq2[i]) { numBad++; }
628                         if (numBad > diffs) { return length;  } //to far to cluster
629                 }
630                 
631                 return numBad;
632         }
633         catch(exception& e) {
634                 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
635                 exit(1);
636         }
637 }
638
639 /**************************************************************************************************/
640
641 void PreClusterCommand::printData(string newfasta, string newname){
642         try {
643                 ofstream outFasta;
644                 ofstream outNames;
645                 
646                 if (bygroup) {
647                         m->openOutputFileAppend(newfasta, outFasta);
648                         m->openOutputFileAppend(newname, outNames);
649                 }else {
650                         m->openOutputFile(newfasta, outFasta);
651                         m->openOutputFile(newname, outNames);
652                 }
653                 
654                 for (int i = 0; i < alignSeqs.size(); i++) {
655                         if (alignSeqs[i].numIdentical != 0) {
656                                 alignSeqs[i].seq.printSequence(outFasta); 
657                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
658                         }
659                 }
660                 
661                 outFasta.close();
662                 outNames.close();
663                 
664         }
665         catch(exception& e) {
666                 m->errorOut(e, "PreClusterCommand", "printData");
667                 exit(1);
668         }
669 }
670 /**************************************************************************************************/
671
672 void PreClusterCommand::readNameFile(){
673         try {
674                 ifstream in;
675                 m->openInputFile(namefile, in);
676                 string firstCol, secondCol;
677                                 
678                 while (!in.eof()) {
679                         in >> firstCol >> secondCol; m->gobble(in);
680                         names[firstCol] = secondCol;
681                         int size = 1;
682
683                         for(int i=0;i<secondCol.size();i++){
684                                 if(secondCol[i] == ','){        size++; }
685                         }
686                         sizes[firstCol] = size;
687                 }
688                 in.close();
689         }
690         catch(exception& e) {
691                 m->errorOut(e, "PreClusterCommand", "readNameFile");
692                 exit(1);
693         }
694 }
695
696 /**************************************************************************************************/
697
698