]> git.donarmstrong.com Git - mothur.git/blob - hclustercommand.cpp
changes while testing
[mothur.git] / hclustercommand.cpp
1 /*
2  *  hclustercommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 10/13/09.
6  *  Copyright 2009 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "hclustercommand.h"
11
12 //**********************************************************************************************************************
13 vector<string> HClusterCommand::setParameters(){        
14         try {
15                 CommandParameter pphylip("phylip", "InputTypes", "", "", "PhylipColumn", "PhylipColumn", "none","list-rabund-sabund",false,false,true); parameters.push_back(pphylip);
16                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "ColumnName","",false,false,true); parameters.push_back(pname);
17                 CommandParameter pcolumn("column", "InputTypes", "", "", "PhylipColumn", "PhylipColumn", "ColumnName","list-rabund-sabund",false,false,true); parameters.push_back(pcolumn);
18                 CommandParameter pcutoff("cutoff", "Number", "", "10", "", "", "","",false,false,true); parameters.push_back(pcutoff);
19                 CommandParameter pprecision("precision", "Number", "", "100", "", "", "","",false,false); parameters.push_back(pprecision);
20                 CommandParameter pmethod("method", "Multiple", "furthest-nearest-average-weighted", "average", "", "", "","",false,false); parameters.push_back(pmethod);
21                 CommandParameter phard("hard", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(phard);
22                 CommandParameter psorted("sorted", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(psorted);
23                 CommandParameter pshowabund("showabund", "Boolean", "", "T", "", "", "","",false,false); parameters.push_back(pshowabund);
24                 CommandParameter ptiming("timing", "Boolean", "", "F", "", "", "","",false,false); parameters.push_back(ptiming);               
25                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
26                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
27                         
28                 vector<string> myArray;
29                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
30                 return myArray;
31         }
32         catch(exception& e) {
33                 m->errorOut(e, "HClusterCommand", "setParameters");
34                 exit(1);
35         }
36 }
37 //**********************************************************************************************************************
38 string HClusterCommand::getHelpString(){        
39         try {
40                 string helpString = "";
41                 helpString += "The hcluster command parameter options are cutoff, precision, method, phylip, column, name, showabund, timing and sorted. Phylip or column and name are required, unless you have valid current files.\n";
42                 helpString += "The phylip and column parameter allow you to enter your distance file, and sorted indicates whether your column distance file is already sorted. \n";
43                 helpString += "The name parameter allows you to enter your name file and is required if your distance file is in column format. \n";
44                 helpString += "The hcluster command should be in the following format: \n";
45                 helpString += "hcluster(column=youDistanceFile, name=yourNameFile, method=yourMethod, cutoff=yourCutoff, precision=yourPrecision) \n";
46                 helpString += "The acceptable hcluster methods are furthest, nearest, weighted and average.\n"; 
47                 return helpString;
48         }
49         catch(exception& e) {
50                 m->errorOut(e, "HClusterCommand", "getHelpString");
51                 exit(1);
52         }
53 }
54 //**********************************************************************************************************************
55 string HClusterCommand::getOutputPattern(string type) {
56     try {
57         string pattern = "";
58         
59         if (type == "list") {  pattern = "[filename],[clustertag],list"; } 
60         else if (type == "rabund") {  pattern = "[filename],[clustertag],rabund"; } 
61         else if (type == "sabund") {  pattern = "[filename],[clustertag],sabund"; }
62         else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true;  }
63         
64         return pattern;
65     }
66     catch(exception& e) {
67         m->errorOut(e, "HClusterCommand", "getOutputPattern");
68         exit(1);
69     }
70 }
71
72 //**********************************************************************************************************************
73 HClusterCommand::HClusterCommand(){     
74         try {
75                 abort = true; calledHelp = true; 
76                 setParameters();
77                 vector<string> tempOutNames;
78                 outputTypes["list"] = tempOutNames;
79                 outputTypes["rabund"] = tempOutNames;
80                 outputTypes["sabund"] = tempOutNames;
81         }
82         catch(exception& e) {
83                 m->errorOut(e, "HClusterCommand", "HClusterCommand");
84                 exit(1);
85         }
86 }
87 //**********************************************************************************************************************
88 //This function checks to make sure the cluster command has no errors and then clusters based on the method chosen.
89 HClusterCommand::HClusterCommand(string option)  {
90         try{
91                 abort = false; calledHelp = false;   
92                 
93                 //allow user to run help
94                 if(option == "help") { help(); abort = true; calledHelp = true; }
95                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
96                 
97                 else {
98                         vector<string> myArray = setParameters();
99                         
100                         OptionParser parser(option);
101                         map<string,string> parameters = parser.getParameters();
102                         
103                         ValidParameters validParameter;
104                         map<string,string>::iterator it;
105                 
106                         //check to make sure all parameters are valid for command
107                         for (it = parameters.begin(); it != parameters.end(); it++) { 
108                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {
109                                         abort = true;
110                                 }
111                         }
112                         
113                         //initialize outputTypes
114                         vector<string> tempOutNames;
115                         outputTypes["list"] = tempOutNames;
116                         outputTypes["rabund"] = tempOutNames;
117                         outputTypes["sabund"] = tempOutNames;
118                 
119                         //if the user changes the input directory command factory will send this info to us in the output parameter 
120                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
121                         if (inputDir == "not found"){   inputDir = "";          }
122                         else {
123                                 string path;
124                                 it = parameters.find("phylip");
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["phylip"] = inputDir + it->second;           }
130                                 }
131                                 
132                                 it = parameters.find("column");
133                                 //user has given a template file
134                                 if(it != parameters.end()){ 
135                                         path = m->hasPath(it->second);
136                                         //if the user has not given a path then, add inputdir. else leave path alone.
137                                         if (path == "") {       parameters["column"] = inputDir + it->second;           }
138                                 }
139                                 
140                                 it = parameters.find("name");
141                                 //user has given a template file
142                                 if(it != parameters.end()){ 
143                                         path = m->hasPath(it->second);
144                                         //if the user has not given a path then, add inputdir. else leave path alone.
145                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
146                                 }
147                         }
148
149                         //if the user changes the output directory command factory will send this info to us in the output parameter 
150                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
151                         
152                         //check for required parameters
153                         phylipfile = validParameter.validFile(parameters, "phylip", true);
154                         if (phylipfile == "not open") { abort = true; }
155                         else if (phylipfile == "not found") { phylipfile = ""; }        
156                         else {  distfile = phylipfile;  format = "phylip";      m->setPhylipFile(phylipfile); }
157                         
158                         columnfile = validParameter.validFile(parameters, "column", true);
159                         if (columnfile == "not open") { abort = true; } 
160                         else if (columnfile == "not found") { columnfile = ""; }
161                         else {  distfile = columnfile; format = "column";       m->setColumnFile(columnfile); }
162                         
163                         namefile = validParameter.validFile(parameters, "name", true);
164                         if (namefile == "not open") { abort = true; }   
165                         else if (namefile == "not found") { namefile = ""; }
166                         else { m->setNameFile(namefile); }
167                         
168                         if ((phylipfile == "") && (columnfile == "")) { 
169                                 //is there are current file available for either of these?
170                                 //give priority to column, then phylip
171                                 columnfile = m->getColumnFile(); 
172                                 if (columnfile != "") {  m->mothurOut("Using " + columnfile + " as input file for the column parameter."); m->mothurOutEndLine(); }
173                                 else { 
174                                         phylipfile = m->getPhylipFile(); 
175                                         if (phylipfile != "") {  m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
176                                         else { 
177                                                 m->mothurOut("No valid current files. You must provide a phylip or column file before you can use the hcluster command."); m->mothurOutEndLine(); 
178                                                 abort = true;
179                                         }
180                                 }
181                         }
182                         else if ((phylipfile != "") && (columnfile != "")) { m->mothurOut("When executing a hcluster command you must enter ONLY ONE of the following: phylip or column."); m->mothurOutEndLine(); abort = true; }
183                 
184                         if (columnfile != "") {
185                                 if (namefile == "") { 
186                                         namefile = m->getNameFile(); 
187                                         if (namefile != "") {  m->mothurOut("Using " + namefile + " as input file for the name parameter."); m->mothurOutEndLine(); }
188                                         else { 
189                                                 m->mothurOut("You need to provide a namefile if you are going to use the column format."); m->mothurOutEndLine(); 
190                                                 abort = true; 
191                                         }       
192                                 }
193                         }
194                         
195                         //check for optional parameter and set defaults
196                         // ...at some point should added some additional type checking...
197                         //get user cutoff and precision or use defaults
198                         string temp;
199                         temp = validParameter.validFile(parameters, "precision", false);
200                         if (temp == "not found") { temp = "100"; }
201                         //saves precision legnth for formatting below
202                         length = temp.length();
203                         m->mothurConvert(temp, precision); 
204                         
205                         temp = validParameter.validFile(parameters, "hard", false);                     if (temp == "not found") { temp = "T"; }
206                         hard = m->isTrue(temp);
207                         
208                         temp = validParameter.validFile(parameters, "cutoff", false);
209                         if (temp == "not found") { temp = "10"; }
210                         m->mothurConvert(temp, cutoff); 
211                         cutoff += (5 / (precision * 10.0)); 
212                         
213                         method = validParameter.validFile(parameters, "method", false);
214                         if (method == "not found") { method = "average"; }
215                         
216                         if ((method == "furthest") || (method == "nearest") || (method == "average") || (method == "weighted")) { }
217                         else { m->mothurOut("Not a valid clustering method.  Valid clustering algorithms are furthest, nearest, average or weighted."); m->mothurOutEndLine(); abort = true; }
218
219                         showabund = validParameter.validFile(parameters, "showabund", false);
220                         if (showabund == "not found") { showabund = "T"; }
221                         
222                         sort = validParameter.validFile(parameters, "sorted", false);
223                         if (sort == "not found") { sort = "F"; }
224                         sorted = m->isTrue(sort);
225
226                         timing = validParameter.validFile(parameters, "timing", false);
227                         if (timing == "not found") { timing = "F"; }
228                         
229                                 
230                         if (abort == false) {
231                                 
232                                 if (outputDir == "") {  outputDir += m->hasPath(distfile); }
233                                 fileroot = outputDir + m->getRootName(m->getSimpleName(distfile));
234                                 
235                                 if (method == "furthest")               { tag = "fn";  }
236                                 else if (method == "nearest")   { tag = "nn";  }
237                                 else if (method == "weighted")  { tag = "wn";  }
238                                 else                                                    { tag = "an";  }
239                 
240                 map<string, string> variables;
241                 variables["[filename]"] = fileroot;
242                 variables["[clustertag]"] = tag;
243                         
244                                 string sabundFileName = getOutputFileName("sabund",variables);
245                 string rabundFileName = getOutputFileName("rabund",variables);
246                 string listFileName = getOutputFileName("list", variables);
247                 
248                 m->openOutputFile(sabundFileName,       sabundFile);
249                 m->openOutputFile(rabundFileName,       rabundFile);
250                 m->openOutputFile(listFileName, listFile);
251                 
252                 outputNames.push_back(sabundFileName); outputTypes["sabund"].push_back(sabundFileName);
253                 outputNames.push_back(rabundFileName); outputTypes["rabund"].push_back(rabundFileName);
254                 outputNames.push_back(listFileName); outputTypes["list"].push_back(listFileName);
255                         }
256                 }
257         }
258         catch(exception& e) {
259                 m->errorOut(e, "HClusterCommand", "HClusterCommand");
260                 exit(1);
261         }
262 }
263
264 //**********************************************************************************************************************
265
266 int HClusterCommand::execute(){
267         try {
268         
269                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
270                 
271                 NameAssignment* nameMap = NULL;
272                 if(namefile != ""){     
273                         nameMap = new NameAssignment(namefile);
274                         nameMap->readMap();
275                 }               
276                 
277                 time_t estart = time(NULL);
278                 
279                 if (!sorted) {
280                         read = new ReadCluster(distfile, cutoff, outputDir, true);      
281                         read->setFormat(format);
282                         read->read(nameMap);
283                         
284                         if (m->control_pressed) {  
285                                 delete read; 
286                                 sabundFile.close();
287                                 rabundFile.close();
288                                 listFile.close();
289                                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } outputTypes.clear();
290                                 return 0;  
291                         }
292                         
293                         distfile = read->getOutputFile();
294                 
295                         list = read->getListVector();
296                         delete read;
297                 }else {
298                         list = new ListVector(nameMap->getListVector());
299                 }
300                 
301                 if (m->control_pressed) {  
302                         sabundFile.close();
303                         rabundFile.close();
304                         listFile.close();
305                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } outputTypes.clear();
306                         return 0;  
307                 }
308
309                 m->mothurOut("It took " + toString(time(NULL) - estart) + " seconds to sort. "); m->mothurOutEndLine();
310                 estart = time(NULL);
311         
312                 //list vector made by read contains all sequence names
313                 if(list != NULL){
314                         rabund = new RAbundVector(list->getRAbundVector());
315                 }else{
316                         m->mothurOut("Error: no list vector!"); m->mothurOutEndLine(); return 0;
317                 }
318                 
319                 float previousDist = 0.00000;
320                 float rndPreviousDist = 0.00000;
321                 oldRAbund = *rabund;
322                 oldList = *list;
323                 
324                 print_start = true;
325                 start = time(NULL);
326                                 
327                 cluster = new HCluster(rabund, list, method, distfile, nameMap, cutoff);
328                 vector<seqDist> seqs; seqs.resize(1); // to start loop
329                 
330                 if (m->control_pressed) {  
331                                 delete cluster;
332                                 sabundFile.close();
333                                 rabundFile.close();
334                                 listFile.close();
335                                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } outputTypes.clear();
336                                 return 0;  
337                 }
338
339                 float saveCutoff = cutoff;
340                 
341                 while (seqs.size() != 0){
342                 
343                         seqs = cluster->getSeqs();
344                         
345                         //to account for cutoff change in average neighbor
346                         if (seqs.size() != 0) {
347                                 if (seqs[0].dist > cutoff) { break; }
348                         }
349                         
350                         if (m->control_pressed) {  
351                                 delete cluster;
352                                 sabundFile.close();
353                                 rabundFile.close();
354                                 listFile.close();
355                                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } outputTypes.clear();
356                                 return 0;  
357                         }
358
359                         for (int i = 0; i < seqs.size(); i++) {  //-1 means skip me
360                                 
361                                 if (seqs[i].seq1 != seqs[i].seq2) {
362                                         cutoff = cluster->update(seqs[i].seq1, seqs[i].seq2, seqs[i].dist);
363                                         
364                                         if (m->control_pressed) {  
365                                                 delete cluster;
366                                                 sabundFile.close();
367                                                 rabundFile.close();
368                                                 listFile.close();
369                                                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } outputTypes.clear();
370                                                 return 0;  
371                                         }
372
373                         
374                                         float rndDist;
375                                         if (hard) {
376                                                 rndDist = m->ceilDist(seqs[i].dist, precision); 
377                                         }else{
378                                                 rndDist = m->roundDist(seqs[i].dist, precision); 
379                                         }
380
381                                         
382                                         if((previousDist <= 0.0000) && (seqs[i].dist != previousDist)){
383                                                 printData("unique");
384                                         }
385                                         else if((rndDist != rndPreviousDist)){
386                                                 printData(toString(rndPreviousDist,  length-1));
387                                         }
388                                 
389                                         previousDist = seqs[i].dist;
390                                         rndPreviousDist = rndDist;
391                                         oldRAbund = *rabund;
392                                         oldList = *list;
393                                 }
394                         }
395                 }
396
397                 if (m->control_pressed) {  
398                         delete cluster;
399                         sabundFile.close();
400                         rabundFile.close();
401                         listFile.close();
402                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } outputTypes.clear();
403                         return 0;  
404                 }
405                                         
406                 if(previousDist <= 0.0000){
407                         printData("unique");
408                 }
409                 else if(rndPreviousDist<cutoff){
410                         printData(toString(rndPreviousDist, length-1));
411                 }
412                                 
413                 sabundFile.close();
414                 rabundFile.close();
415                 listFile.close();
416                 delete cluster;
417                 
418                 if (m->control_pressed) {  
419                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  } outputTypes.clear();
420                         return 0;  
421                 }
422                 
423                 
424                 if (saveCutoff != cutoff) { 
425                         if (hard)       {  saveCutoff = m->ceilDist(saveCutoff, precision);     }
426                         else            {       saveCutoff = m->roundDist(saveCutoff, precision);  }
427                         
428                         m->mothurOut("changed cutoff to " + toString(cutoff)); m->mothurOutEndLine(); 
429                 }
430                 
431                 //set list file as new current listfile
432                 string current = "";
433                 itTypes = outputTypes.find("list");
434                 if (itTypes != outputTypes.end()) {
435                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
436                 }
437                 
438                 //set rabund file as new current rabundfile
439                 itTypes = outputTypes.find("rabund");
440                 if (itTypes != outputTypes.end()) {
441                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
442                 }
443                 
444                 //set sabund file as new current sabundfile
445                 itTypes = outputTypes.find("sabund");
446                 if (itTypes != outputTypes.end()) {
447                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
448                 }
449                 
450                 
451                 m->mothurOutEndLine();
452                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
453                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
454                 m->mothurOutEndLine();
455                 
456                 m->mothurOut("It took " + toString(time(NULL) - estart) + " seconds to cluster. "); m->mothurOutEndLine();
457                 
458                 return 0;
459         }
460         catch(exception& e) {
461                 m->errorOut(e, "HClusterCommand", "execute");
462                 exit(1);
463         }
464 }
465
466 //**********************************************************************************************************************
467
468 void HClusterCommand::printData(string label){
469         try {
470                 if (m->isTrue(timing)) {
471                         m->mothurOut("\tTime: " + toString(time(NULL) - start) + "\tsecs for " + toString(oldRAbund.getNumBins()) 
472                      + "\tclusters. Updates: " + toString(loops)); m->mothurOutEndLine();
473                 }
474                 print_start = true;
475                 loops = 0;
476                 start = time(NULL);
477
478                 oldRAbund.setLabel(label);
479                 if (m->isTrue(showabund)) {
480                         oldRAbund.getSAbundVector().print(cout);
481                 }
482                 oldRAbund.print(rabundFile);
483                 oldRAbund.getSAbundVector().print(sabundFile);
484         
485                 oldList.setLabel(label);
486                 oldList.print(listFile);
487         }
488         catch(exception& e) {
489                 m->errorOut(e, "HClusterCommand", "printData");
490                 exit(1);
491         }
492
493
494 }
495 //**********************************************************************************************************************
496