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