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