]> git.donarmstrong.com Git - mothur.git/blob - shhhseqscommand.cpp
fixed bug with shhh.flow from file path name in write functions, added "smart" featur...
[mothur.git] / shhhseqscommand.cpp
1 /*
2  *  shhhseqscommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 11/8/11.
6  *  Copyright 2011 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "shhhseqscommand.h"
11
12
13
14 //**********************************************************************************************************************
15 vector<string> ShhhSeqsCommand::setParameters(){        
16         try {
17                 CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
18                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pname);
19                 CommandParameter pgroup("group", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pgroup);
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                 CommandParameter psigma("sigma", "Number", "", "0.01", "", "", "",false,false); parameters.push_back(psigma);
24                 
25                 vector<string> myArray;
26                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
27                 return myArray;
28         }
29         catch(exception& e) {
30                 m->errorOut(e, "ShhhSeqsCommand", "setParameters");
31                 exit(1);
32         }
33 }
34 //**********************************************************************************************************************
35 string ShhhSeqsCommand::getHelpString(){        
36         try {
37                 string helpString = "";
38                 helpString += "The shhh.seqs command reads a fasta and name file and ....\n";
39                 helpString += "The shhh.seqs command parameters are fasta, name, group, sigma and processors.\n";
40                 helpString += "The fasta parameter allows you to enter the fasta file containing your sequences, and is required, unless you have a valid current fasta file. \n";
41                 helpString += "The name parameter allows you to provide a name file associated with your fasta file. It is required. \n";
42                 helpString += "The group parameter allows you to provide a group file.  When checking sequences, only sequences from the same group as the query sequence will be used as the reference. \n";
43                 helpString += "The processors parameter allows you to specify how many processors you would like to use.  The default is 1. \n";
44                 helpString += "The sigma parameter ....  The default is 0.01. \n";
45                 helpString += "The shhh.seqs command should be in the following format: \n";
46                 helpString += "shhh.seqs(fasta=yourFastaFile, name=yourNameFile) \n";
47                 helpString += "Example: shhh.seqs(fasta=AD.align, name=AD.names) \n";
48                 helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFastaFile).\n";       
49                 return helpString;
50                 
51         }
52         catch(exception& e) {
53                 m->errorOut(e, "ShhhSeqsCommand", "getHelpString");
54                 exit(1);
55         }
56 }
57 //**********************************************************************************************************************
58
59 ShhhSeqsCommand::ShhhSeqsCommand(){     
60         try {
61                 abort = true; calledHelp = true;
62                 setParameters();
63                 vector<string> tempOutNames;
64                 outputTypes["fasta"] = tempOutNames;
65                 outputTypes["name"] = tempOutNames;
66                 outputTypes["map"] = tempOutNames;
67         }
68         catch(exception& e) {
69                 m->errorOut(e, "ShhhSeqsCommand", "ShhhSeqsCommand");
70                 exit(1);
71         }
72 }
73
74 //**********************************************************************************************************************
75 ShhhSeqsCommand::ShhhSeqsCommand(string option) {
76         try {
77                 abort = false; calledHelp = false;   
78                 
79                 //allow user to run help
80                 if(option == "help") { help(); abort = true; calledHelp = true; }
81                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
82                 
83                 else {
84                         vector<string> myArray = setParameters();
85                         
86                         OptionParser parser(option);
87                         map<string, string> parameters = parser.getParameters();
88                         
89                         ValidParameters validParameter;
90                         map<string, string>::iterator it;
91                         
92                         //check to make sure all parameters are valid for command
93                         for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
94                                 if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
95                         }
96                         
97                         //initialize outputTypes
98                         vector<string> tempOutNames;
99                         outputTypes["fasta"] = tempOutNames;
100                         outputTypes["name"] = tempOutNames;
101                         outputTypes["map"] = tempOutNames;
102                         
103                         //if the user changes the input directory command factory will send this info to us in the output parameter 
104                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
105                         if (inputDir == "not found"){   inputDir = "";          }
106                         else {
107                                 string path;
108                                 it = parameters.find("fasta");
109                                 //user has given a template file
110                                 if(it != parameters.end()){ 
111                                         path = m->hasPath(it->second);
112                                         //if the user has not given a path then, add inputdir. else leave path alone.
113                                         if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
114                                 }
115                                 
116                                 it = parameters.find("name");
117                                 //user has given a template file
118                                 if(it != parameters.end()){ 
119                                         path = m->hasPath(it->second);
120                                         //if the user has not given a path then, add inputdir. else leave path alone.
121                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
122                                 }
123                                 
124                                 it = parameters.find("group");
125                                 //user has given a template file
126                                 if(it != parameters.end()){ 
127                                         path = m->hasPath(it->second);
128                                         //if the user has not given a path then, add inputdir. else leave path alone.
129                                         if (path == "") {       parameters["group"] = inputDir + it->second;            }
130                                 }
131                         }
132                         
133                         //check for required parameters
134                         fastafile = validParameter.validFile(parameters, "fasta", true);
135                         if (fastafile == "not found") {                                 
136                                 fastafile = m->getFastaFile(); 
137                                 if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
138                                 else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
139                         }
140                         else if (fastafile == "not open") { abort = true; }     
141                         else { m->setFastaFile(fastafile); }
142                         
143                         //if the user changes the output directory command factory will send this info to us in the output parameter 
144                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
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") {                  
150                                 namefile = m->getNameFile(); 
151                                 if (namefile != "") { m->mothurOut("Using " + namefile + " as input file for the name parameter."); m->mothurOutEndLine(); }
152                                 else {  m->mothurOut("You have no current namefile and the name parameter is required."); m->mothurOutEndLine(); abort = true; }
153                         }
154                         else if (namefile == "not open") { namefile =  ""; abort = true; }      
155                         else {  m->setNameFile(namefile); }
156                         
157                         groupfile = validParameter.validFile(parameters, "group", true);
158                         if (groupfile == "not found") { groupfile =  "";   }
159                         else if (groupfile == "not open") { abort = true; groupfile =  ""; }    
160                         else {   m->setGroupFile(groupfile);  }
161                         
162                         string temp     = validParameter.validFile(parameters, "sigma", false);         if(temp == "not found"){        temp = "0.01"; }
163                         m->mothurConvert(temp, sigma); 
164                         
165                         temp = validParameter.validFile(parameters, "processors", false);       if (temp == "not found"){       temp = m->getProcessors();      }
166                         m->setProcessors(temp);
167                         m->mothurConvert(temp, processors);
168                         
169                         if (namefile == "") {
170                                 vector<string> files; files.push_back(fastafile);
171                                 parser.getNameFile(files);
172                         }
173                 }
174         }
175         catch(exception& e) {
176                 m->errorOut(e, "ShhhSeqsCommand", "ShhhSeqsCommand");
177                 exit(1);
178         }
179 }
180 //**********************************************************************************************************************
181 int ShhhSeqsCommand::execute() {
182         try {
183                 
184                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
185                 
186                 if (outputDir == "") { outputDir = m->hasPath(fastafile);  }//if user entered a file with a path then preserve it                               
187                 string outputFileName = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "shhh.fasta";
188                 string nameFileName = outputDir + m->getRootName(m->getSimpleName(fastafile))  + "shhh.names";
189                 string mapFileName = outputDir + m->getRootName(m->getSimpleName(fastafile))  + "shhh.map";
190                 
191                 if (groupfile != "") {
192                         //Parse sequences by group
193                         SequenceParser parser(groupfile, fastafile, namefile);
194                         vector<string> groups = parser.getNamesOfGroups();
195                         
196                         if (m->control_pressed) {  return 0; }
197                         
198                         //clears files
199                         ofstream out, out1, out2;
200                         m->openOutputFile(outputFileName, out); out.close(); 
201                         m->openOutputFile(nameFileName, out1); out1.close();
202                         mapFileName = outputDir + m->getRootName(m->getSimpleName(fastafile))  + "shhh.";
203                         
204                         vector<string> mapFileNames;
205                         if(processors == 1)     {       mapFileNames = driverGroups(parser, outputFileName, nameFileName, mapFileName, 0, groups.size(), groups);       }
206                         else                            {       mapFileNames = createProcessesGroups(parser, outputFileName, nameFileName, mapFileName, groups);                        }
207                         
208                         if (m->control_pressed) {    return 0;  }       
209                         
210                         for (int j = 0; j < mapFileNames.size(); j++) { outputNames.push_back(mapFileNames[j]); outputTypes["map"].push_back(mapFileNames[j]); }
211                         
212                         //deconvolute results by running unique.seqs
213                         deconvoluteResults(outputFileName, nameFileName);
214                         
215                         if (m->control_pressed) {   return 0;   }                               
216                         
217                 }else{  
218                         vector<string> sequences;
219                         vector<string> uniqueNames;
220                         vector<string> redundantNames;
221                         vector<int> seqFreq;
222                         
223                         seqNoise noise;
224                         correctDist* correct = new correctDist(processors);
225                         
226                         //reads fasta and name file and loads them in order
227                         readData(correct, noise, sequences, uniqueNames, redundantNames, seqFreq);
228                         if (m->control_pressed) { return 0; }
229                         
230                         //calc distances for cluster
231                         string distFileName = outputDir + m->getRootName(m->getSimpleName(fastafile)) + "shhh.dist";
232                         correct->execute(distFileName);
233                         delete correct;
234                         
235                         if (m->control_pressed) { m->mothurRemove(distFileName); return 0; }
236                         
237                         driver(noise, sequences, uniqueNames, redundantNames, seqFreq, distFileName, outputFileName, nameFileName, mapFileName); 
238                         outputNames.push_back(mapFileName); outputTypes["map"].push_back(mapFileName);
239                 }
240                 
241                 if (m->control_pressed) { for (int j = 0; j < outputNames.size(); j++) {        m->mothurRemove(outputNames[j]);        } return 0; }
242                 
243                 outputNames.push_back(outputFileName); outputTypes["fasta"].push_back(outputFileName);
244                 outputNames.push_back(nameFileName); outputTypes["name"].push_back(nameFileName);
245                 
246                 m->mothurOutEndLine();
247                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
248                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }       
249                 m->mothurOutEndLine();
250                 
251                 //set accnos file as new current accnosfile
252                 string current = "";
253                 itTypes = outputTypes.find("fasta");
254                 if (itTypes != outputTypes.end()) {
255                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
256                 }
257                 
258                 itTypes = outputTypes.find("name");
259                 if (itTypes != outputTypes.end()) {
260                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
261                 }
262                 
263                 
264                 return 0;
265         }
266         catch(exception& e) {
267                 m->errorOut(e, "ShhhSeqsCommand", "execute");
268                 exit(1);
269         }
270 }
271 //**********************************************************************************************************************
272 int ShhhSeqsCommand::readData(correctDist* correct, seqNoise& noise, vector<string>& seqs, vector<string>& uNames, vector<string>& rNames, vector<int>& freq) {
273         try {
274                 map<string, string> nameMap; 
275                 map<string, string>::iterator it;
276                 m->readNames(namefile, nameMap);
277                 bool error = false;
278                 
279                 ifstream in;
280                 m->openInputFile(fastafile, in);
281                 
282                 while (!in.eof()) {
283                         
284                         if (m->control_pressed) { in.close(); return 0; }
285                         
286                         Sequence seq(in); m->gobble(in);
287                         
288                         if (seq.getName() != "") {
289                                 correct->addSeq(seq.getName(), seq.getAligned());
290                                 
291                                 it = nameMap.find(seq.getName());
292                                 if (it != nameMap.end()) {
293                                         noise.addSeq(seq.getAligned(), seqs);
294                                         noise.addRedundantName(it->first, it->second, uNames, rNames, freq);
295                                 }else {
296                                         m->mothurOut("[ERROR]: " + seq.getName() + " is in your fasta file and not in your namefile, please correct.");
297                                         error = true;
298                                 }
299                         }
300                 }
301                 in.close();
302                 
303                 if (error) { m->control_pressed = true; }
304                 
305                 return seqs.size();
306                 
307         }catch(exception& e) {
308                 m->errorOut(e, "ShhhSeqsCommand", "readData");
309                 exit(1);
310         }
311 }
312 //**********************************************************************************************************************
313 int ShhhSeqsCommand::loadData(correctDist* correct, seqNoise& noise, vector<string>& seqs, vector<string>& uNames, vector<string>& rNames, vector<int>& freq, map<string, string>& nameMap, vector<Sequence>& sequences) {
314         try {
315                 bool error = false;
316                 map<string, string>::iterator it;
317                 
318                 for (int i = 0; i < sequences.size(); i++) {
319                         
320                         if (m->control_pressed) { return 0; }
321                         
322                         if (sequences[i].getName() != "") {
323                                 correct->addSeq(sequences[i].getName(), sequences[i].getAligned());
324                                 
325                                 it = nameMap.find(sequences[i].getName());
326                                 if (it != nameMap.end()) {
327                                         noise.addSeq(sequences[i].getAligned(), seqs);
328                                         noise.addRedundantName(it->first, it->second, uNames, rNames, freq);
329                                 }else {
330                                         m->mothurOut("[ERROR]: " + sequences[i].getName() + " is in your fasta file and not in your namefile, please correct.");
331                                         error = true;
332                                 }
333                         }
334                 }
335                                 
336                 if (error) { m->control_pressed = true; }
337                 
338                 return seqs.size();
339                 
340         }catch(exception& e) {
341                 m->errorOut(e, "ShhhSeqsCommand", "loadData");
342                 exit(1);
343         }
344 }
345 /**************************************************************************************************/
346 vector<string> ShhhSeqsCommand::createProcessesGroups(SequenceParser& parser, string newFName, string newNName, string newMName, vector<string> groups) {
347         try {
348                 
349                 vector<int> processIDS;
350                 int process = 1;
351                 vector<string> mapfileNames;
352                 
353                 //sanity check
354                 if (groups.size() < processors) { processors = groups.size(); }
355                 
356                 //divide the groups between the processors
357                 vector<linePair> lines;
358                 int numGroupsPerProcessor = groups.size() / processors;
359                 for (int i = 0; i < processors; i++) {
360                         int startIndex =  i * numGroupsPerProcessor;
361                         int endIndex = (i+1) * numGroupsPerProcessor;
362                         if(i == (processors - 1)){      endIndex = groups.size();       }
363                         lines.push_back(linePair(startIndex, endIndex));
364                 }
365                 
366 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)           
367                 
368                 //loop through and create all the processes you want
369                 while (process != processors) {
370                         int pid = fork();
371                         
372                         if (pid > 0) {
373                                 processIDS.push_back(pid);  //create map from line number to pid so you can append files in correct order later
374                                 process++;
375                         }else if (pid == 0){
376                                 mapfileNames = driverGroups(parser, newFName + toString(getpid()) + ".temp", newNName + toString(getpid()) + ".temp", newMName, lines[process].start, lines[process].end, groups);
377                                 
378                                 //pass filenames to parent
379                                 ofstream out;
380                                 string tempFile = newMName + toString(getpid()) + ".temp";
381                                 m->openOutputFile(tempFile, out);
382                                 out << mapfileNames.size() << endl;
383                                 for (int i = 0; i < mapfileNames.size(); i++) {
384                                         out << mapfileNames[i] << endl;
385                                 }
386                                 out.close();
387                                 
388                                 exit(0);
389                         }else { 
390                                 m->mothurOut("[ERROR]: unable to spawn the necessary processes."); m->mothurOutEndLine(); 
391                                 for (int i = 0; i < processIDS.size(); i++) { kill (processIDS[i], SIGINT); }
392                                 exit(0);
393                         }
394                 }
395                 
396                 //do my part
397                 mapfileNames = driverGroups(parser, newFName, newNName, newMName, lines[0].start, lines[0].end, groups);
398                 
399                 //force parent to wait until all the processes are done
400                 for (int i=0;i<processIDS.size();i++) { 
401                         int temp = processIDS[i];
402                         wait(&temp);
403                 }
404                 
405                 //append output files
406                 for(int i=0;i<processIDS.size();i++){
407                         ifstream in;
408                         string tempFile =  newMName + toString(processIDS[i]) + ".temp";
409                         m->openInputFile(tempFile, in);
410                         if (!in.eof()) { 
411                                 int tempNum = 0; in >> tempNum;  m->gobble(in);
412                                 for (int j = 0; j < tempNum; j++) {
413                                         string filename;
414                                         in >> filename; m->gobble(in);
415                                         mapfileNames.push_back(filename);
416                                 }
417                         }
418                         in.close(); m->mothurRemove(tempFile);
419                         
420                 }
421 #else
422                 
423                 //////////////////////////////////////////////////////////////////////////////////////////////////////
424                 //Windows version shared memory, so be careful when passing variables through the shhhseqsData struct. 
425                 //Above fork() will clone, so memory is separate, but that's not the case with windows, 
426                 //////////////////////////////////////////////////////////////////////////////////////////////////////
427                 
428                 vector<shhhseqsData*> pDataArray; 
429                 DWORD   dwThreadIdArray[processors-1];
430                 HANDLE  hThreadArray[processors-1]; 
431                 
432                 //Create processor worker threads.
433                 for( int i=1; i<processors; i++ ){
434                         // Allocate memory for thread data.
435                         string extension = toString(i) + ".temp";
436
437                         shhhseqsData* tempShhhseqs = new shhhseqsData(fastafile, namefile, groupfile, (newFName+extension), (newNName+extension), newMName, groups, m, lines[i].start, lines[i].end, sigma, i);
438                         pDataArray.push_back(tempShhhseqs);
439                         processIDS.push_back(i);
440                         
441                         //MySeqSumThreadFunction is in header. It must be global or static to work with the threads.
442                         //default security attributes, thread function name, argument to thread function, use default creation flags, returns the thread identifier
443                         hThreadArray[i-1] = CreateThread(NULL, 0, MyShhhSeqsThreadFunction, pDataArray[i-1], 0, &dwThreadIdArray[i-1]);   
444                 }
445                 
446                 
447                 //using the main process as a worker saves time and memory
448                 mapfileNames = driverGroups(parser, newFName, newNName, newMName, lines[0].start, lines[0].end, groups);
449                 
450                 //Wait until all threads have terminated.
451                 WaitForMultipleObjects(processors-1, hThreadArray, TRUE, INFINITE);
452                 
453                 //Close all thread handles and free memory allocations.
454                 for(int i=0; i < pDataArray.size(); i++){
455                         for (int j = 0; j < pDataArray[i]->mapfileNames.size(); j++) {
456                                 mapfileNames.push_back(pDataArray[i]->mapfileNames[j]);
457                         }
458                         CloseHandle(hThreadArray[i]);
459                         delete pDataArray[i];
460                 }
461                 
462 #endif          
463                 
464                 //append output files
465                 for(int i=0;i<processIDS.size();i++){
466                         m->appendFiles((newFName + toString(processIDS[i]) + ".temp"), newFName);
467                         m->mothurRemove((newFName + toString(processIDS[i]) + ".temp"));
468                         
469                         m->appendFiles((newNName + toString(processIDS[i]) + ".temp"), newNName);
470                         m->mothurRemove((newNName + toString(processIDS[i]) + ".temp"));
471                 }
472                 
473                 return mapfileNames;    
474                 
475         }
476         catch(exception& e) {
477                 m->errorOut(e, "ShhhSeqsCommand", "createProcessesGroups");
478                 exit(1);
479         }
480 }
481 /**************************************************************************************************/
482 vector<string> ShhhSeqsCommand::driverGroups(SequenceParser& parser, string newFFile, string newNFile, string newMFile, int start, int end, vector<string> groups){
483         try {
484                 
485                 vector<string> mapFileNames;
486                 
487                 for (int i = start; i < end; i++) {
488                         
489                         start = time(NULL);
490                         
491                         if (m->control_pressed) {  return mapFileNames; }
492                         
493                         m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[i] + ":"); m->mothurOutEndLine();
494                         
495                         map<string, string> thisNameMap;
496                         thisNameMap = parser.getNameMap(groups[i]); 
497                         vector<Sequence> thisSeqs = parser.getSeqs(groups[i]);
498                         
499                         vector<string> sequences;
500                         vector<string> uniqueNames;
501                         vector<string> redundantNames;
502                         vector<int> seqFreq;
503                         
504                         seqNoise noise;
505                         correctDist* correct = new correctDist(1); //we use one processor since we already split up the work load.
506                         
507                         //load this groups info in order
508                         loadData(correct, noise, sequences, uniqueNames, redundantNames, seqFreq, thisNameMap, thisSeqs);
509                         if (m->control_pressed) { return mapFileNames; }
510                         
511                         //calc distances for cluster
512                         string distFileName = outputDir + m->getRootName(m->getSimpleName(fastafile)) + groups[i] + ".shhh.dist";
513                         correct->execute(distFileName);
514                         delete correct;
515                         
516                         if (m->control_pressed) { m->mothurRemove(distFileName); return mapFileNames; }
517                         
518                         driver(noise, sequences, uniqueNames, redundantNames, seqFreq, distFileName, newFFile+groups[i], newNFile+groups[i], newMFile+groups[i]+".map"); 
519                         
520                         if (m->control_pressed) { return mapFileNames; }
521                         
522                         m->appendFiles(newFFile+groups[i], newFFile); m->mothurRemove(newFFile+groups[i]);
523                         m->appendFiles(newNFile+groups[i], newNFile); m->mothurRemove(newNFile+groups[i]);
524                         mapFileNames.push_back(newMFile+groups[i]+".map");
525                         
526                         m->mothurOut("It took " + toString(time(NULL) - start) + " secs to process group " + groups[i] + "."); m->mothurOutEndLine(); 
527                 }
528                 
529                 return mapFileNames;
530         }
531         catch(exception& e) {
532                 m->errorOut(e, "ShhhSeqsCommand", "driverGroups");
533                 exit(1);
534         }
535 }
536 //**********************************************************************************************************************
537 int ShhhSeqsCommand::driver(seqNoise& noise, 
538                                                         vector<string>& sequences, 
539                                                         vector<string>& uniqueNames, 
540                                                         vector<string>& redundantNames, 
541                                                         vector<int>& seqFreq, 
542                                                         string distFileName, string outputFileName, string nameFileName, string mapFileName) {
543         try {
544                 double cutOff = 0.08;
545                 int minIter = 10;
546                 int maxIter = 1000;
547                 double minDelta = 1e-6;
548                 int numIters = 0;
549                 double maxDelta = 1e6;
550                 int numSeqs = sequences.size();
551                                 
552                 //run cluster command
553                 string inputString = "phylip=" + distFileName + ", method=furthest, cutoff=0.08";
554                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
555                 m->mothurOut("Running command: cluster(" + inputString + ")"); m->mothurOutEndLine(); 
556                 
557                 Command* clusterCommand = new ClusterCommand(inputString);
558                 clusterCommand->execute();
559                 
560                 map<string, vector<string> > filenames = clusterCommand->getOutputFiles();
561                 string listFileName = filenames["list"][0];
562                 string rabundFileName = filenames["rabund"][0]; m->mothurRemove(rabundFileName);
563                 string sabundFileName = filenames["sabund"][0]; m->mothurRemove(sabundFileName);
564         
565                 delete clusterCommand;
566                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
567                 
568                 if (m->control_pressed) { m->mothurRemove(distFileName); m->mothurRemove(listFileName); return 0; }
569                 
570                 vector<double> distances(numSeqs * numSeqs);
571                 noise.getDistanceData(distFileName, distances);
572                 m->mothurRemove(distFileName); 
573                 if (m->control_pressed) { m->mothurRemove(listFileName); return 0; }
574                 
575                 vector<int> otuData(numSeqs);
576                 vector<int> otuFreq;
577                 vector<vector<int> > otuBySeqLookUp;
578                 noise.getListData(listFileName, cutOff, otuData, otuFreq, otuBySeqLookUp);
579                 m->mothurRemove(listFileName);
580                 if (m->control_pressed) { return 0; }
581                 
582                 int numOTUs = otuFreq.size();
583                 
584                 vector<double> weights(numOTUs, 0);
585                 vector<int> change(numOTUs, 1);
586                 vector<int> centroids(numOTUs, -1);
587                 vector<int> cumCount(numOTUs, 0);
588                 
589                 vector<double> tau(numSeqs, 1);
590                 vector<int> anP(numSeqs, 0);
591                 vector<int> anI(numSeqs, 0);
592                 vector<int> anN(numSeqs, 0);
593                 vector<vector<int> > aanI = otuBySeqLookUp;
594                 
595                 while(numIters < minIter || ((maxDelta > minDelta) && (numIters < maxIter))){
596                         
597                         if (m->control_pressed) { return 0; }
598                         
599                         noise.updateOTUCountData(otuFreq, otuBySeqLookUp, aanI, anP, anI, cumCount); if (m->control_pressed) { return 0; }
600                         maxDelta = noise.calcNewWeights(weights, seqFreq, anI, cumCount, anP, otuFreq, tau);  if (m->control_pressed) { return 0; }
601                         
602                         noise.calcCentroids(anI, anP, change, centroids, cumCount, distances, seqFreq, otuFreq, tau); if (m->control_pressed) { return 0; }
603                         noise.checkCentroids(weights, centroids); if (m->control_pressed) { return 0; }
604                          
605                         otuFreq.assign(numOTUs, 0);
606                         
607                         int total = 0;
608                         
609                         for(int i=0;i<numSeqs;i++){
610                                 if (m->control_pressed) { return 0; }
611                                 
612                                 double offset = 1e6;
613                                 double norm = 0.0000;
614                                 double minWeight = 0.1;
615                                 vector<double> currentTau(numOTUs);
616                                 
617                                 for(int j=0;j<numOTUs;j++){
618                                         if (m->control_pressed) { return 0; }
619                                         if(weights[j] > minWeight && distances[i * numSeqs+centroids[j]] < offset){
620                                                 offset = distances[i * numSeqs+centroids[j]];
621                                         }
622                                 }
623                                 
624                                 for(int j=0;j<numOTUs;j++){
625                                         if (m->control_pressed) { return 0; }
626                                         if(weights[j] > minWeight){
627                                                 currentTau[j] = exp(sigma * (-distances[(i * numSeqs + centroids[j])] + offset)) * weights[j];
628                                                 norm += currentTau[j];
629                                         }
630                                         else{
631                                                 currentTau[j] = 0.0000;
632                                         }
633                                 }                       
634                                 
635                                 for(int j=0;j<numOTUs;j++){
636                                         if (m->control_pressed) { return 0; }
637                                         currentTau[j] /= norm;
638                                 }
639                                 
640                                 for(int j=0;j<numOTUs;j++){
641                                         if (m->control_pressed) { return 0; }
642                                         
643                                         if(currentTau[j] > 1.0e-4){
644                                                 int oldTotal = total;
645                                                 total++;
646                                                 
647                                                 tau.resize(oldTotal+1);
648                                                 tau[oldTotal] = currentTau[j];
649                                                 otuBySeqLookUp[j][otuFreq[j]] = oldTotal;
650                                                 aanI[j][otuFreq[j]] = i;
651                                                 otuFreq[j]++;
652                                                 
653                                         }
654                                 }
655                                 
656                                 anP.resize(total);
657                                 anI.resize(total);
658                         }
659                         
660                         numIters++;
661                 }
662                 
663                 noise.updateOTUCountData(otuFreq, otuBySeqLookUp, aanI, anP, anI, cumCount);  if (m->control_pressed) { return 0; }
664                 
665                 vector<double> percentage(numSeqs);
666                 noise.setUpOTUData(otuData, percentage, cumCount, tau, otuFreq, anP, anI);  if (m->control_pressed) { return 0; }
667                 noise.finishOTUData(otuData, otuFreq, anP, anI, cumCount, otuBySeqLookUp, aanI, tau);  if (m->control_pressed) { return 0; }
668                 
669                 change.assign(numOTUs, 1);
670                 noise.calcCentroids(anI, anP, change, centroids, cumCount, distances, seqFreq, otuFreq, tau); if (m->control_pressed) { return 0; }
671                 
672                 
673                 vector<int> finalTau(numOTUs, 0);
674                 for(int i=0;i<numSeqs;i++){
675                         if (m->control_pressed) { return 0; }
676                         finalTau[otuData[i]] += int(seqFreq[i]);
677                 }
678                 
679                 noise.writeOutput(outputFileName, nameFileName, mapFileName, finalTau, centroids, otuData, sequences, uniqueNames, redundantNames, seqFreq, distances);
680                 
681                 return 0;
682                 
683         }catch(exception& e) {
684                 m->errorOut(e, "ShhhSeqsCommand", "driver");
685                 exit(1);
686         }
687 }       
688 //**********************************************************************************************************************
689 int ShhhSeqsCommand::deconvoluteResults(string fastaFile, string nameFile){
690         try {
691                 m->mothurOutEndLine(); m->mothurOut("Deconvoluting results:"); m->mothurOutEndLine(); m->mothurOutEndLine();
692                 
693                 //use unique.seqs to create new name and fastafile
694                 string inputString = "fasta=" + fastaFile + ", name=" + nameFile;
695                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
696                 m->mothurOut("Running command: unique.seqs(" + inputString + ")"); m->mothurOutEndLine(); 
697                 
698                 Command* uniqueCommand = new DeconvoluteCommand(inputString);
699                 uniqueCommand->execute();
700                 
701                 map<string, vector<string> > filenames = uniqueCommand->getOutputFiles();
702                 
703                 delete uniqueCommand;
704                 
705                 m->mothurOut("/******************************************/"); m->mothurOutEndLine(); 
706                 
707                 string newnameFile = filenames["name"][0];
708                 string newfastaFile = filenames["fasta"][0];
709                 
710                 m->mothurRemove(fastaFile); rename(newfastaFile.c_str(), fastaFile.c_str()); 
711                 if (nameFile != newnameFile) { m->mothurRemove(nameFile); rename(newnameFile.c_str(), nameFile.c_str()); }
712                 
713                 return 0;
714         }
715         catch(exception& e) {
716                 m->errorOut(e, "ShhhSeqsCommand", "deconvoluteResults");
717                 exit(1);
718         }
719 }
720 //**********************************************************************************************************************
721
722
723