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