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