]> git.donarmstrong.com Git - mothur.git/blob - hclustercommand.cpp
changes while setting up test files
[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",false,false); parameters.push_back(pphylip);
16                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "ColumnName",false,false); parameters.push_back(pname);
17                 CommandParameter pcolumn("column", "InputTypes", "", "", "PhylipColumn", "PhylipColumn", "ColumnName",false,false); parameters.push_back(pcolumn);
18                 CommandParameter pcutoff("cutoff", "Number", "", "10", "", "", "",false,false); 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", "furthest", "", "", "",false,false); parameters.push_back(pmethod);
21                 CommandParameter phard("hard", "Boolean", "", "F", "", "", "",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 HClusterCommand::HClusterCommand(){     
56         try {
57                 abort = true; calledHelp = true; 
58                 setParameters();
59                 vector<string> tempOutNames;
60                 outputTypes["list"] = tempOutNames;
61                 outputTypes["rabund"] = tempOutNames;
62                 outputTypes["sabund"] = tempOutNames;
63         }
64         catch(exception& e) {
65                 m->errorOut(e, "HClusterCommand", "HClusterCommand");
66                 exit(1);
67         }
68 }
69 //**********************************************************************************************************************
70 //This function checks to make sure the cluster command has no errors and then clusters based on the method chosen.
71 HClusterCommand::HClusterCommand(string option)  {
72         try{
73                 abort = false; calledHelp = false;   
74                 
75                 //allow user to run help
76                 if(option == "help") { help(); abort = true; calledHelp = true; }
77                 
78                 else {
79                         vector<string> myArray = setParameters();
80                         
81                         OptionParser parser(option);
82                         map<string,string> parameters = parser.getParameters();
83                         
84                         ValidParameters validParameter;
85                         map<string,string>::iterator it;
86                 
87                         //check to make sure all parameters are valid for command
88                         for (it = parameters.begin(); it != parameters.end(); it++) { 
89                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {
90                                         abort = true;
91                                 }
92                         }
93                         
94                         //initialize outputTypes
95                         vector<string> tempOutNames;
96                         outputTypes["list"] = tempOutNames;
97                         outputTypes["rabund"] = tempOutNames;
98                         outputTypes["sabund"] = tempOutNames;
99                 
100                         //if the user changes the input directory command factory will send this info to us in the output parameter 
101                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
102                         if (inputDir == "not found"){   inputDir = "";          }
103                         else {
104                                 string path;
105                                 it = parameters.find("phylip");
106                                 //user has given a template file
107                                 if(it != parameters.end()){ 
108                                         path = m->hasPath(it->second);
109                                         //if the user has not given a path then, add inputdir. else leave path alone.
110                                         if (path == "") {       parameters["phylip"] = inputDir + it->second;           }
111                                 }
112                                 
113                                 it = parameters.find("column");
114                                 //user has given a template file
115                                 if(it != parameters.end()){ 
116                                         path = m->hasPath(it->second);
117                                         //if the user has not given a path then, add inputdir. else leave path alone.
118                                         if (path == "") {       parameters["column"] = inputDir + it->second;           }
119                                 }
120                                 
121                                 it = parameters.find("name");
122                                 //user has given a template file
123                                 if(it != parameters.end()){ 
124                                         path = m->hasPath(it->second);
125                                         //if the user has not given a path then, add inputdir. else leave path alone.
126                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
127                                 }
128                         }
129
130                         //if the user changes the output directory command factory will send this info to us in the output parameter 
131                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = "";         }
132                         
133                         //check for required parameters
134                         phylipfile = validParameter.validFile(parameters, "phylip", true);
135                         if (phylipfile == "not open") { abort = true; }
136                         else if (phylipfile == "not found") { phylipfile = ""; }        
137                         else {  distfile = phylipfile;  format = "phylip";      }
138                         
139                         columnfile = validParameter.validFile(parameters, "column", true);
140                         if (columnfile == "not open") { abort = true; } 
141                         else if (columnfile == "not found") { columnfile = ""; }
142                         else {  distfile = columnfile; format = "column";       }
143                         
144                         namefile = validParameter.validFile(parameters, "name", true);
145                         if (namefile == "not open") { abort = true; }   
146                         else if (namefile == "not found") { namefile = ""; }
147                         
148                         if ((phylipfile == "") && (columnfile == "")) { 
149                                 //is there are current file available for either of these?
150                                 //give priority to column, then phylip
151                                 columnfile = m->getColumnFile(); 
152                                 if (columnfile != "") {  m->mothurOut("Using " + columnfile + " as input file for the column parameter."); m->mothurOutEndLine(); }
153                                 else { 
154                                         phylipfile = m->getPhylipFile(); 
155                                         if (phylipfile != "") {  m->mothurOut("Using " + phylipfile + " as input file for the phylip parameter."); m->mothurOutEndLine(); }
156                                         else { 
157                                                 m->mothurOut("No valid current files. You must provide a phylip or column file before you can use the hcluster command."); m->mothurOutEndLine(); 
158                                                 abort = true;
159                                         }
160                                 }
161                         }
162                         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; }
163                 
164                         if (columnfile != "") {
165                                 if (namefile == "") { 
166                                         namefile = m->getNameFile(); 
167                                         if (namefile != "") {  m->mothurOut("Using " + namefile + " as input file for the name parameter."); m->mothurOutEndLine(); }
168                                         else { 
169                                                 m->mothurOut("You need to provide a namefile if you are going to use the column format."); m->mothurOutEndLine(); 
170                                                 abort = true; 
171                                         }       
172                                 }
173                         }
174                         
175                         //check for optional parameter and set defaults
176                         // ...at some point should added some additional type checking...
177                         //get user cutoff and precision or use defaults
178                         string temp;
179                         temp = validParameter.validFile(parameters, "precision", false);
180                         if (temp == "not found") { temp = "100"; }
181                         //saves precision legnth for formatting below
182                         length = temp.length();
183                         convert(temp, precision); 
184                         
185                         temp = validParameter.validFile(parameters, "hard", false);                     if (temp == "not found") { temp = "F"; }
186                         hard = m->isTrue(temp);
187                         
188                         temp = validParameter.validFile(parameters, "cutoff", false);
189                         if (temp == "not found") { temp = "10"; }
190                         convert(temp, cutoff); 
191                         cutoff += (5 / (precision * 10.0)); 
192                         
193                         method = validParameter.validFile(parameters, "method", false);
194                         if (method == "not found") { method = "furthest"; }
195                         
196                         if ((method == "furthest") || (method == "nearest") || (method == "average") || (method == "weighted")) { }
197                         else { m->mothurOut("Not a valid clustering method.  Valid clustering algorithms are furthest, nearest, average or weighted."); m->mothurOutEndLine(); abort = true; }
198
199                         showabund = validParameter.validFile(parameters, "showabund", false);
200                         if (showabund == "not found") { showabund = "T"; }
201                         
202                         sort = validParameter.validFile(parameters, "sorted", false);
203                         if (sort == "not found") { sort = "F"; }
204                         sorted = m->isTrue(sort);
205
206                         timing = validParameter.validFile(parameters, "timing", false);
207                         if (timing == "not found") { timing = "F"; }
208                         
209                                 
210                         if (abort == false) {
211                                 
212                                 if (outputDir == "") {  outputDir += m->hasPath(distfile); }
213                                 fileroot = outputDir + m->getRootName(m->getSimpleName(distfile));
214                                 
215                                 if (method == "furthest")               { tag = "fn";  }
216                                 else if (method == "nearest")   { tag = "nn";  }
217                                 else if (method == "weighted")  { tag = "wn";  }
218                                 else                                                    { tag = "an";  }
219                         
220                                 m->openOutputFile(fileroot+ tag + ".sabund",    sabundFile);
221                                 m->openOutputFile(fileroot+ tag + ".rabund",    rabundFile);
222                                 m->openOutputFile(fileroot+ tag + ".list",              listFile);
223                                 
224                                 outputNames.push_back(fileroot+ tag + ".sabund"); outputTypes["sabund"].push_back(fileroot+ tag + ".sabund");
225                                 outputNames.push_back(fileroot+ tag + ".rabund"); outputTypes["rabund"].push_back(fileroot+ tag + ".rabund");
226                                 outputNames.push_back(fileroot+ tag + ".list"); outputTypes["list"].push_back(fileroot+ tag + ".list");
227                         }
228                 }
229         }
230         catch(exception& e) {
231                 m->errorOut(e, "HClusterCommand", "HClusterCommand");
232                 exit(1);
233         }
234 }
235
236 //**********************************************************************************************************************
237
238 int HClusterCommand::execute(){
239         try {
240         
241                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
242                 
243                 NameAssignment* nameMap = NULL;
244                 if(namefile != ""){     
245                         nameMap = new NameAssignment(namefile);
246                         nameMap->readMap();
247                 }               
248                 
249                 time_t estart = time(NULL);
250                 
251                 if (!sorted) {
252                         read = new ReadCluster(distfile, cutoff, outputDir, true);      
253                         read->setFormat(format);
254                         read->read(nameMap);
255                         
256                         if (m->control_pressed) {  
257                                 delete read; 
258                                 sabundFile.close();
259                                 rabundFile.close();
260                                 listFile.close();
261                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  } outputTypes.clear();
262                                 return 0;  
263                         }
264                         
265                         distfile = read->getOutputFile();
266                 
267                         list = read->getListVector();
268                         delete read;
269                 }else {
270                         list = new ListVector(nameMap->getListVector());
271                 }
272                 
273                 if (m->control_pressed) {  
274                         sabundFile.close();
275                         rabundFile.close();
276                         listFile.close();
277                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  } outputTypes.clear();
278                         return 0;  
279                 }
280
281                 m->mothurOut("It took " + toString(time(NULL) - estart) + " seconds to sort. "); m->mothurOutEndLine();
282                 estart = time(NULL);
283         
284                 //list vector made by read contains all sequence names
285                 if(list != NULL){
286                         rabund = new RAbundVector(list->getRAbundVector());
287                 }else{
288                         m->mothurOut("Error: no list vector!"); m->mothurOutEndLine(); return 0;
289                 }
290                 
291                 float previousDist = 0.00000;
292                 float rndPreviousDist = 0.00000;
293                 oldRAbund = *rabund;
294                 oldList = *list;
295                 
296                 print_start = true;
297                 start = time(NULL);
298                                 
299                 cluster = new HCluster(rabund, list, method, distfile, nameMap, cutoff);
300                 vector<seqDist> seqs; seqs.resize(1); // to start loop
301                 
302                 if (m->control_pressed) {  
303                                 delete cluster;
304                                 sabundFile.close();
305                                 rabundFile.close();
306                                 listFile.close();
307                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  } outputTypes.clear();
308                                 return 0;  
309                 }
310
311                 
312                 while (seqs.size() != 0){
313                 
314                         seqs = cluster->getSeqs();
315                         
316                         if (m->control_pressed) {  
317                                 delete cluster;
318                                 sabundFile.close();
319                                 rabundFile.close();
320                                 listFile.close();
321                                 for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  } outputTypes.clear();
322                                 return 0;  
323                         }
324
325                         for (int i = 0; i < seqs.size(); i++) {  //-1 means skip me
326                                 
327                                 if (seqs[i].seq1 != seqs[i].seq2) {
328                                         cluster->update(seqs[i].seq1, seqs[i].seq2, seqs[i].dist);
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++) {  remove(outputNames[i].c_str());  } outputTypes.clear();
336                                                 return 0;  
337                                         }
338
339                         
340                                         float rndDist;
341                                         if (hard) {
342                                                 rndDist = m->ceilDist(seqs[i].dist, precision); 
343                                         }else{
344                                                 rndDist = m->roundDist(seqs[i].dist, precision); 
345                                         }
346
347                                         
348                                         if((previousDist <= 0.0000) && (seqs[i].dist != previousDist)){
349                                                 printData("unique");
350                                         }
351                                         else if((rndDist != rndPreviousDist)){
352                                                 printData(toString(rndPreviousDist,  length-1));
353                                         }
354                                 
355                                         previousDist = seqs[i].dist;
356                                         rndPreviousDist = rndDist;
357                                         oldRAbund = *rabund;
358                                         oldList = *list;
359                                 }
360                         }
361                 }
362
363                 if (m->control_pressed) {  
364                         delete cluster;
365                         sabundFile.close();
366                         rabundFile.close();
367                         listFile.close();
368                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  } outputTypes.clear();
369                         return 0;  
370                 }
371                                         
372                 if(previousDist <= 0.0000){
373                         printData("unique");
374                 }
375                 else if(rndPreviousDist<cutoff){
376                         printData(toString(rndPreviousDist, length-1));
377                 }
378                                 
379                 sabundFile.close();
380                 rabundFile.close();
381                 listFile.close();
382                 delete cluster;
383                 
384                 if (m->control_pressed) {  
385                         for (int i = 0; i < outputNames.size(); i++) {  remove(outputNames[i].c_str());  } outputTypes.clear();
386                         return 0;  
387                 }
388                 
389                 //set list file as new current listfile
390                 string current = "";
391                 itTypes = outputTypes.find("list");
392                 if (itTypes != outputTypes.end()) {
393                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
394                 }
395                 
396                 //set rabund file as new current rabundfile
397                 itTypes = outputTypes.find("rabund");
398                 if (itTypes != outputTypes.end()) {
399                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
400                 }
401                 
402                 //set sabund file as new current sabundfile
403                 itTypes = outputTypes.find("sabund");
404                 if (itTypes != outputTypes.end()) {
405                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
406                 }
407                 
408                 
409                 m->mothurOutEndLine();
410                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
411                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
412                 m->mothurOutEndLine();
413                 
414                 m->mothurOut("It took " + toString(time(NULL) - estart) + " seconds to cluster. "); m->mothurOutEndLine();
415                 
416                 return 0;
417         }
418         catch(exception& e) {
419                 m->errorOut(e, "HClusterCommand", "execute");
420                 exit(1);
421         }
422 }
423
424 //**********************************************************************************************************************
425
426 void HClusterCommand::printData(string label){
427         try {
428                 if (m->isTrue(timing)) {
429                         m->mothurOut("\tTime: " + toString(time(NULL) - start) + "\tsecs for " + toString(oldRAbund.getNumBins()) 
430                      + "\tclusters. Updates: " + toString(loops)); m->mothurOutEndLine();
431                 }
432                 print_start = true;
433                 loops = 0;
434                 start = time(NULL);
435
436                 oldRAbund.setLabel(label);
437                 if (m->isTrue(showabund)) {
438                         oldRAbund.getSAbundVector().print(cout);
439                 }
440                 oldRAbund.print(rabundFile);
441                 oldRAbund.getSAbundVector().print(sabundFile);
442         
443                 oldList.setLabel(label);
444                 oldList.print(listFile);
445         }
446         catch(exception& e) {
447                 m->errorOut(e, "HClusterCommand", "printData");
448                 exit(1);
449         }
450
451
452 }
453 //**********************************************************************************************************************
454