]> git.donarmstrong.com Git - mothur.git/blob - preclustercommand.cpp
metastats in progress
[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") { 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                         convert(temp, diffs); 
160                         
161                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
162                         m->setProcessors(temp);
163                         convert(temp, processors);
164                         
165                         
166                 }
167                                 
168         }
169         catch(exception& e) {
170                 m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
171                 exit(1);
172         }
173 }
174 //**********************************************************************************************************************
175
176 int PreClusterCommand::execute(){
177         try {
178                 
179                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
180                 
181                 int start = time(NULL);
182                 
183                 string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
184                 string newFastaFile = fileroot + "precluster" + m->getExtension(fastafile);
185                 string newNamesFile = fileroot + "precluster.names";
186                 string newMapFile = fileroot + "precluster.map"; //add group name if by group
187                 outputNames.push_back(newFastaFile); outputTypes["fasta"].push_back(newFastaFile);
188                 outputNames.push_back(newNamesFile); outputTypes["name"].push_back(newNamesFile);
189                 
190                 
191                 if (bygroup) {
192                         //clear out old files
193                         ofstream outFasta; m->openOutputFile(newFastaFile, outFasta); outFasta.close();
194                         ofstream outNames; m->openOutputFile(newNamesFile, outNames);  outNames.close();
195                         newMapFile = fileroot + "precluster.";
196                         
197                         //parse fasta and name file by group
198                         SequenceParser* parser;
199                         if (namefile != "") { parser = new SequenceParser(groupfile, fastafile, namefile);      }
200                         else                            { parser = new SequenceParser(groupfile, fastafile);                    }
201                         
202                         vector<string> groups = parser->getNamesOfGroups();
203                         
204                         if(processors == 1)     {       driverGroups(parser, newFastaFile, newNamesFile, newMapFile, 0, groups.size(), groups); }
205                         else                            {       createProcessesGroups(parser, newFastaFile, newNamesFile, newMapFile, groups);                  }
206                         
207                         delete parser;
208                         
209                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        }        return 0; }
210                         
211                         //run unique.seqs for deconvolute results
212                         string inputString = "fasta=" + newFastaFile;
213                         if (namefile != "") { inputString += ", name=" + newNamesFile; }
214                         m->mothurOutEndLine(); 
215                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
216                         m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
217                         
218                         Command* uniqueCommand = new DeconvoluteCommand(inputString);
219                         uniqueCommand->execute();
220                         
221                         map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
222                         
223                         delete uniqueCommand;
224                         
225                         m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
226                         
227                         m->renameFile(filenames["fasta"][0], newFastaFile);
228                         
229                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to run pre.cluster."); m->mothurOutEndLine(); 
230                                 
231                 }else {
232                         if (namefile != "") { readNameFile(); }
233                 
234                         //reads fasta file and return number of seqs
235                         int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
236                 
237                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
238         
239                         if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
240                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
241                         
242                         int count = process(newMapFile);
243                         outputNames.push_back(newMapFile); outputTypes["map"].push_back(newMapFile);
244                         
245                         if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }   
246                         
247                         m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
248                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
249                         printData(newFastaFile, newNamesFile);
250                         
251                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
252                 }
253                                 
254                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
255                 
256                 m->mothurOutEndLine();
257                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
258                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }               
259                 m->mothurOutEndLine();
260                 
261                 //set fasta file as new current fastafile
262                 string current = "";
263                 itTypes = outputTypes.find("fasta");
264                 if (itTypes != outputTypes.end()) {
265                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
266                 }
267                 
268                 itTypes = outputTypes.find("name");
269                 if (itTypes != outputTypes.end()) {
270                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
271                 }
272                 
273                 return 0;
274                 
275         }
276         catch(exception& e) {
277                 m->errorOut(e, "PreClusterCommand", "execute");
278                 exit(1);
279         }
280 }
281 /**************************************************************************************************/
282 int PreClusterCommand::createProcessesGroups(SequenceParser* parser, string newFName, string newNName, string newMFile, vector<string> groups) {
283         try {
284                 
285                 vector<int> processIDS;
286                 int process = 1;
287                 int num = 0;
288                 
289                 //sanity check
290                 if (groups.size() < processors) { processors = groups.size(); }
291                 
292                 //divide the groups between the processors
293                 vector<linePair> lines;
294                 int numGroupsPerProcessor = groups.size() / processors;
295                 for (int i = 0; i < processors; i++) {
296                         int startIndex =  i * numGroupsPerProcessor;
297                         int endIndex = (i+1) * numGroupsPerProcessor;
298                         if(i == (processors - 1)){      endIndex = groups.size();       }
299                         lines.push_back(linePair(startIndex, endIndex));
300                 }
301                 
302 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)           
303                 
304                 //loop through and create all the processes you want
305                 while (process != processors) {
306                         int pid = fork();
307                         
308                         if (pid > 0) {
309                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
310                                 process++;
311                         }else if (pid == 0){
312                                 num = driverGroups(parser, newFName + toString(getpid()) + ".temp", newNName + toString(getpid()) + ".temp", newMFile, lines[process].start, lines[process].end, groups);
313                                 exit(0);
314                         }else { 
315                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
316                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
317                                 exit(0);
318                         }
319                 }
320                 
321                 //do my part
322                 num = driverGroups(parser, newFName, newNName, newMFile, lines[0].start, lines[0].end, groups);
323                 
324                 //force parent to wait until all the processes are done
325                 for (int i=0;i<processIDS.size();i++) { 
326                         int temp = processIDS[i];
327                         wait(&temp);
328                 }
329                 
330 #else
331                 
332                 //////////////////////////////////////////////////////////////////////////////////////////////////////
333                 //Windows version shared memory, so be careful when passing variables through the preClusterData struct. 
334                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
335                 //////////////////////////////////////////////////////////////////////////////////////////////////////
336                 
337                 vector<preClusterData*> pDataArray; 
338                 DWORD   dwThreadIdArray[processors-1];
339                 HANDLE  hThreadArray[processors-1]; 
340                 
341                 //Create processor worker threads.
342                 for( int i=1; i<processors; i++ ){
343                         // Allocate memory for thread data.
344                         string extension = toString(i) + ".temp";
345                         
346                         preClusterData* tempPreCluster = new preClusterData(fastafile, namefile, groupfile, (newFName+extension), (newNName+extension), newMFile, groups, m, lines[i].start, lines[i].end, diffs, i);
347                         pDataArray.push_back(tempPreCluster);
348                         processIDS.push_back(i);
349                         
350                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
351                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
352                         hThreadArray[i-1] = CreateThread(NULL, 0, MyPreclusterThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
353                 }
354                 
355                                 
356                 //using the main process as a worker saves time and memory
357                 num = driverGroups(parser, newFName, newNName, newMFile, lines[0].start, lines[0].end, groups);
358                 
359                 //Wait until all threads have terminated.
360                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
361                 
362                 //Close all thread handles and free memory allocations.
363                 for(int i=0; i < pDataArray.size(); i++){
364                         for (int j = 0; j < pDataArray[i]->mapFileNames.size(); j++) {
365                                 outputNames.push_back(pDataArray[i]->mapFileNames[j]); outputTypes["map"].push_back(pDataArray[i]->mapFileNames[j]); 
366                         }
367                         CloseHandle(hThreadArray[i]);
368                         delete pDataArray[i];
369                 }
370                 
371 #endif          
372                 
373                 //append output files
374                 for(int i=0;i<processIDS.size();i++){
375                         m->appendFiles((newFName + toString(processIDS[i]) + ".temp"), newFName);
376                         m->mothurRemove((newFName + toString(processIDS[i]) + ".temp"));
377                         
378                         m->appendFiles((newNName + toString(processIDS[i]) + ".temp"), newNName);
379                         m->mothurRemove((newNName + toString(processIDS[i]) + ".temp"));
380                 }
381                 
382                 return num;     
383                 
384         }
385         catch(exception& e) {
386                 m->errorOut(e, "PreClusterCommand", "createProcessesGroups");
387                 exit(1);
388         }
389 }
390 /**************************************************************************************************/
391 int PreClusterCommand::driverGroups(SequenceParser* parser, string newFFile, string newNFile, string newMFile, int start, int end, vector<string> groups){
392         try {
393                 
394                 int numSeqs = 0;
395                 
396                 //precluster each group
397                 for (int i = start; i < end; i++) {
398                         
399                         start = time(NULL);
400                         
401                         if (m->control_pressed) {  return 0; }
402                         
403                         m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[i] + ":"); m->mothurOutEndLine();
404                         
405                         map<string, string> thisNameMap;
406                         if (namefile != "") { thisNameMap = parser->getNameMap(groups[i]); }
407                         vector<Sequence> thisSeqs = parser->getSeqs(groups[i]);
408                         
409                         //fill alignSeqs with this groups info.
410                         numSeqs = loadSeqs(thisNameMap, thisSeqs);
411                         
412                         if (m->control_pressed) {   return 0; }
413                         
414                         if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); m->control_pressed = true; return 0;  }
415                         
416                         int count = process(newMFile+groups[i]+".map");
417                         outputNames.push_back(newMFile+groups[i]+".map"); outputTypes["map"].push_back(newMFile+groups[i]+".map");
418                         
419                         if (m->control_pressed) {  return 0; }
420                         
421                         m->mothurOut("Total number of sequences before pre.cluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
422                         m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
423                         printData(newFFile, newNFile);
424                         
425                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
426                         
427                 }
428                 
429                 return numSeqs;
430         }
431         catch(exception& e) {
432                 m->errorOut(e, "PreClusterCommand", "driverGroups");
433                 exit(1);
434         }
435 }
436 /**************************************************************************************************/
437 int PreClusterCommand::process(string newMapFile){
438         try {
439                 ofstream out;
440                 m->openOutputFile(newMapFile, out);
441                 
442                 //sort seqs by number of identical seqs
443                 sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
444                 
445                 int count = 0;
446                 int numSeqs = alignSeqs.size();
447                 
448                 //think about running through twice...
449                 for (int i = 0; i < numSeqs; i++) {
450                         
451                         //are you active
452                         //                      itActive = active.find(alignSeqs[i].seq.getName());
453                         
454                         if (alignSeqs[i].active) {  //this sequence has not been merged yet
455                                 
456                                 string chunk = alignSeqs[i].seq.getName() + "\t" + toString(alignSeqs[i].numIdentical) + "\t" + toString(0) + "\t" + alignSeqs[i].seq.getAligned() + "\n";
457                                 
458                                 //try to merge it with all smaller seqs
459                                 for (int j = i+1; j < numSeqs; j++) {
460                                         
461                                         if (m->control_pressed) { out.close(); return 0; }
462                                         
463                                         if (alignSeqs[j].active) {  //this sequence has not been merged yet
464                                                 //are you within "diff" bases
465                                                 int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
466                                                 
467                                                 if (mismatch <= diffs) {
468                                                         //merge
469                                                         alignSeqs[i].names += ',' + alignSeqs[j].names;
470                                                         alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
471                                                         
472                                                         chunk += alignSeqs[j].seq.getName() + "\t" + toString(alignSeqs[j].numIdentical) + "\t" + toString(mismatch) + "\t" + alignSeqs[j].seq.getAligned() + "\n";
473                                                         
474                                                         alignSeqs[j].active = 0;
475                                                         alignSeqs[j].numIdentical = 0;
476                                                         count++;
477                                                 }
478                                         }//end if j active
479                                 }//end for loop j
480                                 
481                                 //remove from active list 
482                                 alignSeqs[i].active = 0;
483                                 
484                                 out << "ideal_seq_" << (i+1) << '\t' << alignSeqs[i].numIdentical << endl << chunk << endl;;
485                                 
486                         }//end if active i
487                         if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
488                 }
489                 out.close();
490                 
491                 if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }       
492                 
493                 return count;
494                 
495         }
496         catch(exception& e) {
497                 m->errorOut(e, "PreClusterCommand", "process");
498                 exit(1);
499         }
500 }
501 /**************************************************************************************************/
502 int PreClusterCommand::readFASTA(){
503         try {
504                 //ifstream inNames;
505                 ifstream inFasta;
506                 
507                 //m->openInputFile(namefile, inNames);
508                 m->openInputFile(fastafile, inFasta);
509                 
510                 //string firstCol, secondCol, nameString;
511                 length = 0;
512                 
513                 while (!inFasta.eof()) {
514                         
515                         if (m->control_pressed) { inFasta.close(); return 0; }
516                         
517                         //inNames >> firstCol >> secondCol;
518                         //nameString = secondCol;
519                         
520                         //m->gobble(inNames);
521                         //int size = 1;
522                         //while (secondCol.find_first_of(',') != -1) { 
523                         //      size++;
524                         //      secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
525                         //}
526                         
527                         Sequence seq(inFasta);  m->gobble(inFasta);
528                         
529                         if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
530                                 if (namefile != "") {
531                                         itSize = sizes.find(seq.getName());
532                                         
533                                         if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
534                                         else{
535                                                 seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
536                                                 alignSeqs.push_back(tempNode);
537                                                 if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
538                                         }       
539                                 }else { //no names file, you are identical to yourself 
540                                         seqPNode tempNode(1, seq, seq.getName());
541                                         alignSeqs.push_back(tempNode);
542                                         if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
543                                 }
544                         }
545                 }
546                 inFasta.close();
547                 //inNames.close();
548                 return alignSeqs.size();
549         }
550         
551         catch(exception& e) {
552                 m->errorOut(e, "PreClusterCommand", "readFASTA");
553                 exit(1);
554         }
555 }
556 /**************************************************************************************************/
557 int PreClusterCommand::loadSeqs(map<string, string>& thisName, vector<Sequence>& thisSeqs){
558         try {
559                 length = 0;
560                 alignSeqs.clear();
561                 map<string, string>::iterator it;
562                 bool error = false;
563                         
564                 for (int i = 0; i < thisSeqs.size(); i++) {
565                         
566                         if (m->control_pressed) { return 0; }
567                                                 
568                         if (namefile != "") {
569                                 it = thisName.find(thisSeqs[i].getName());
570                                 
571                                 //should never be true since parser checks for this
572                                 if (it == thisName.end()) { m->mothurOut(thisSeqs[i].getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); error = true; }
573                                 else{
574                                         //get number of reps
575                                         int numReps = 1;
576                                         for(int j=0;j<(it->second).length();j++){
577                                                 if((it->second)[j] == ','){     numReps++;      }
578                                         }
579                                         
580                                         seqPNode tempNode(numReps, thisSeqs[i], it->second);
581                                         alignSeqs.push_back(tempNode);
582                                         if (thisSeqs[i].getAligned().length() > length) {  length = thisSeqs[i].getAligned().length();  }
583                                 }       
584                         }else { //no names file, you are identical to yourself 
585                                 seqPNode tempNode(1, thisSeqs[i], thisSeqs[i].getName());
586                                 alignSeqs.push_back(tempNode);
587                                 if (thisSeqs[i].getAligned().length() > length) {  length = thisSeqs[i].getAligned().length();  }
588                         }
589                 }
590                 
591                 //sanity check
592                 if (error) { m->control_pressed = true; }
593                 
594                 thisSeqs.clear();
595                 
596                 return alignSeqs.size();
597         }
598         
599         catch(exception& e) {
600                 m->errorOut(e, "PreClusterCommand", "loadSeqs");
601                 exit(1);
602         }
603 }
604                                 
605 /**************************************************************************************************/
606
607 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
608         try {
609                 int numBad = 0;
610                 
611                 for (int i = 0; i < seq1.length(); i++) {
612                         //do they match
613                         if (seq1[i] != seq2[i]) { numBad++; }
614                         if (numBad > diffs) { return length;  } //to far to cluster
615                 }
616                 
617                 return numBad;
618         }
619         catch(exception& e) {
620                 m->errorOut(e, "PreClusterCommand", "calcMisMatches");
621                 exit(1);
622         }
623 }
624
625 /**************************************************************************************************/
626
627 void PreClusterCommand::printData(string newfasta, string newname){
628         try {
629                 ofstream outFasta;
630                 ofstream outNames;
631                 
632                 if (bygroup) {
633                         m->openOutputFileAppend(newfasta, outFasta);
634                         m->openOutputFileAppend(newname, outNames);
635                 }else {
636                         m->openOutputFile(newfasta, outFasta);
637                         m->openOutputFile(newname, outNames);
638                 }
639                 
640                 for (int i = 0; i < alignSeqs.size(); i++) {
641                         if (alignSeqs[i].numIdentical != 0) {
642                                 alignSeqs[i].seq.printSequence(outFasta); 
643                                 outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
644                         }
645                 }
646                 
647                 outFasta.close();
648                 outNames.close();
649                 
650         }
651         catch(exception& e) {
652                 m->errorOut(e, "PreClusterCommand", "printData");
653                 exit(1);
654         }
655 }
656 /**************************************************************************************************/
657
658 void PreClusterCommand::readNameFile(){
659         try {
660                 ifstream in;
661                 m->openInputFile(namefile, in);
662                 string firstCol, secondCol;
663                                 
664                 while (!in.eof()) {
665                         in >> firstCol >> secondCol; m->gobble(in);
666                         names[firstCol] = secondCol;
667                         int size = 1;
668
669                         for(int i=0;i<secondCol.size();i++){
670                                 if(secondCol[i] == ','){        size++; }
671                         }
672                         sizes[firstCol] = size;
673                 }
674                 in.close();
675         }
676         catch(exception& e) {
677                 m->errorOut(e, "PreClusterCommand", "readNameFile");
678                 exit(1);
679         }
680 }
681
682 /**************************************************************************************************/
683
684