]> git.donarmstrong.com Git - mothur.git/blob - hclustercommand.cpp
added groups option to read.otu, added qtrim option to trim.seqs, fixed bug in get...
[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","showabund","timing","phylip","column","name","sorted"};
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                 
32                         //check to make sure all parameters are valid for command
33                         for (map<string,string>::iterator it = parameters.begin(); it != parameters.end(); it++) { 
34                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {
35                                         abort = true;
36                                 }
37                         }
38                         
39                         globaldata->newRead();
40                         
41                         //check for required parameters
42                         phylipfile = validParameter.validFile(parameters, "phylip", true);
43                         if (phylipfile == "not open") { abort = true; }
44                         else if (phylipfile == "not found") { phylipfile = ""; }        
45                         else {  distfile = phylipfile;  format = "phylip";      }
46                         
47                         columnfile = validParameter.validFile(parameters, "column", true);
48                         if (columnfile == "not open") { abort = true; } 
49                         else if (columnfile == "not found") { columnfile = ""; }
50                         else {  distfile = columnfile; format = "column";       }
51                         
52                         namefile = validParameter.validFile(parameters, "name", true);
53                         if (namefile == "not open") { abort = true; }   
54                         else if (namefile == "not found") { namefile = ""; }
55                         
56                         if ((phylipfile == "") && (columnfile == "")) { mothurOut("When executing a cluster command you must enter a phylip or a column."); mothurOutEndLine(); abort = true; }
57                         else if ((phylipfile != "") && (columnfile != "")) { mothurOut("When executing a cluster command you must enter ONLY ONE of the following: phylip or column."); mothurOutEndLine(); abort = true; }
58                 
59                         if (columnfile != "") {
60                                 if (namefile == "") {  cout << "You need to provide a namefile if you are going to use the column format." << endl; abort = true; }
61                         }
62                         
63                         //check for optional parameter and set defaults
64                         // ...at some point should added some additional type checking...
65                         //get user cutoff and precision or use defaults
66                         string temp;
67                         temp = validParameter.validFile(parameters, "precision", false);
68                         if (temp == "not found") { temp = "100"; }
69                         //saves precision legnth for formatting below
70                         length = temp.length();
71                         convert(temp, precision); 
72                         
73                         temp = validParameter.validFile(parameters, "cutoff", false);
74                         if (temp == "not found") { temp = "10"; }
75                         convert(temp, cutoff); 
76                         cutoff += (5 / (precision * 10.0));
77                         
78                         method = validParameter.validFile(parameters, "method", false);
79                         if (method == "not found") { method = "nearest"; }
80                         
81                         if ((method == "furthest") || (method == "nearest") || (method == "average")) { }
82                         else { mothurOut("Not a valid clustering method.  Valid clustering algorithms are furthest, nearest or average."); mothurOutEndLine(); abort = true; }
83
84                         showabund = validParameter.validFile(parameters, "showabund", false);
85                         if (showabund == "not found") { showabund = "T"; }
86                         
87                         sort = validParameter.validFile(parameters, "sorted", false);
88                         if (sort == "not found") { sort = "F"; }
89                         sorted = isTrue(sort);
90
91                         timing = validParameter.validFile(parameters, "timing", false);
92                         if (timing == "not found") { timing = "F"; }
93                         
94                                 
95                         if (abort == false) {
96                                                                                         
97                                 fileroot = getRootName(distfile);
98                                 
99                                 tag = "fn";  //until we figure out average and nearest methods
100                         
101                                 openOutputFile(fileroot+ tag + ".sabund",       sabundFile);
102                                 openOutputFile(fileroot+ tag + ".rabund",       rabundFile);
103                                 openOutputFile(fileroot+ tag + ".list",         listFile);
104                         }
105                 }
106         }
107         catch(exception& e) {
108                 errorOut(e, "HClusterCommand", "HClusterCommand");
109                 exit(1);
110         }
111 }
112
113 //**********************************************************************************************************************
114
115 void HClusterCommand::help(){
116         try {
117                 mothurOut("The cluster command can only be executed after a successful read.dist command.\n");
118                 mothurOut("The cluster command parameter options are method, cuttoff, precision, showabund and timing. No parameters are required.\n");
119                 mothurOut("The cluster command should be in the following format: \n");
120                 mothurOut("cluster(method=yourMethod, cutoff=yourCutoff, precision=yourPrecision) \n");
121                 mothurOut("The acceptable cluster methods are furthest, nearest and average.  If no method is provided then furthest is assumed.\n\n"); 
122         }
123         catch(exception& e) {
124                 errorOut(e, "HClusterCommand", "help");
125                 exit(1);
126         }
127 }
128
129 //**********************************************************************************************************************
130
131 HClusterCommand::~HClusterCommand(){}
132
133 //**********************************************************************************************************************
134
135 int HClusterCommand::execute(){
136         try {
137         
138                 if (abort == true) {    return 0;       }
139                 
140                 if(namefile != ""){     
141                         globaldata->nameMap = new NameAssignment(namefile);
142                         globaldata->nameMap->readMap();
143                 }else{
144                         globaldata->nameMap = NULL;
145                 }
146                 
147                 time_t estart = time(NULL);
148                 
149                 if (!sorted) {
150                         read = new ReadCluster(distfile, cutoff);       
151                         read->setFormat(format);
152                         read->read(globaldata->nameMap);
153                         distfile = read->getOutputFile();
154                 
155                         list = read->getListVector();
156                         delete read;
157                 }else {
158                         list = new ListVector(globaldata->nameMap->getListVector());
159                 }
160         
161                 mothurOut("It took " + toString(time(NULL) - estart) + " seconds to sort. "); mothurOutEndLine();
162                 estart = time(NULL);
163                 
164                 //list vector made by read contains all sequence names
165                 if(list != NULL){
166                         rabund = new RAbundVector(list->getRAbundVector());
167                 }else{
168                         mothurOut("Error: no list vector!"); mothurOutEndLine(); return 0;
169                 }
170                 
171                 float previousDist = 0.00000;
172                 float rndPreviousDist = 0.00000;
173                 oldRAbund = *rabund;
174                 oldList = *list;
175                 
176                 print_start = true;
177                 start = time(NULL);
178                 
179 //cout << "here" << endl;       
180                 ifstream in;
181                 openInputFile(distfile, in);
182                 string firstName, secondName;
183                 float distance;
184                 
185                 cluster = new HCluster(rabund, list);
186                 bool clusteredSomething;
187                 vector<seqDist> seqs; seqs.resize(1); // to start loop
188                 exitedBreak = false;  //lets you know if there is a distance stored in next
189                 
190                 while (seqs.size() != 0){
191                 
192                         seqs = getSeqs(in);
193                         random_shuffle(seqs.begin(), seqs.end());
194                         
195                         if (seqs.size() == 0) { break; } //there are no more distances
196                 
197                         for (int i = 0; i < seqs.size(); i++) {  //-1 means skip me
198
199                                 if (print_start && isTrue(timing)) {
200                                         mothurOut("Clustering (" + tag + ") dist " + toString(distance) + "/" 
201                                                           + toString(roundDist(distance, precision)) 
202                                                           + "\t(precision: " + toString(precision) + ")");
203                                         cout.flush();
204                                         print_start = false;
205                                 }
206                                 
207         ///cout << "before cluster update" << endl;
208                                 if (seqs[i].seq1 != seqs[i].seq2) {
209                                         clusteredSomething = cluster->update(seqs[i].seq1, seqs[i].seq2, seqs[i].dist);
210                                         
211                                         float rndDist = roundDist(seqs[i].dist, precision);
212                                         //cout << "after cluster update clusterSomething = " << clusteredSomething << " rndDist = " << rndDist << " rndPreviousDist = " << rndPreviousDist << endl;                     
213                                         
214                                         
215                                         if((previousDist <= 0.0000) && (seqs[i].dist != previousDist)){
216                                                 printData("unique");
217                                         }
218                                         else if((rndDist != rndPreviousDist)){
219                                                 printData(toString(rndPreviousDist,  length-1));
220                                         }
221                                         
222                                         previousDist = seqs[i].dist;
223                                         rndPreviousDist = rndDist;
224                                         oldRAbund = *rabund;
225                                         oldList = *list;
226                                 }
227                         }
228                 }
229                 
230                 in.close();
231
232                 if (print_start && isTrue(timing)) {
233                         //mothurOut("Clustering (" + tag + ") for distance " + toString(previousDist) + "/" + toString(rndPreviousDist) 
234                                          //+ "\t(precision: " + toString(precision) + ", Nodes: " + toString(matrix->getNNodes()) + ")");
235                         cout.flush();
236                         print_start = false;
237                 }
238         
239                 if(previousDist <= 0.0000){
240                         printData("unique");
241                 }
242                 else if(rndPreviousDist<cutoff){
243                         printData(toString(rndPreviousDist, length-1));
244                 }
245                 
246                 //delete globaldata's copy of the sparsematrix and listvector to free up memory
247                 delete globaldata->gListVector;  globaldata->gListVector = NULL;
248                 
249                 //saves .list file so you can do the collect, rarefaction and summary commands without doing a read.list
250                 if (globaldata->getFormat() == "phylip") { globaldata->setPhylipFile(""); }
251                 else if (globaldata->getFormat() == "column") { globaldata->setColumnFile(""); }
252                 
253                 globaldata->setListFile(fileroot+ tag + ".list");
254                 globaldata->setNameFile("");
255                 globaldata->setFormat("list");
256                 
257                 sabundFile.close();
258                 rabundFile.close();
259                 listFile.close();
260                 
261                 delete cluster;
262                 //if (isTrue(timing)) {
263                         mothurOut("It took " + toString(time(NULL) - estart) + " seconds to cluster. "); mothurOutEndLine();
264                 //}
265                 return 0;
266         }
267         catch(exception& e) {
268                 errorOut(e, "HClusterCommand", "execute");
269                 exit(1);
270         }
271 }
272
273 //**********************************************************************************************************************
274
275 void HClusterCommand::printData(string label){
276         try {
277                 if (isTrue(timing)) {
278                         mothurOut("\tTime: " + toString(time(NULL) - start) + "\tsecs for " + toString(oldRAbund.getNumBins()) 
279                      + "\tclusters. Updates: " + toString(loops)); mothurOutEndLine();
280                 }
281                 print_start = true;
282                 loops = 0;
283                 start = time(NULL);
284
285                 oldRAbund.setLabel(label);
286                 if (isTrue(showabund)) {
287                         oldRAbund.getSAbundVector().print(cout);
288                 }
289                 oldRAbund.print(rabundFile);
290                 oldRAbund.getSAbundVector().print(sabundFile);
291         
292                 oldList.setLabel(label);
293                 oldList.print(listFile);
294         }
295         catch(exception& e) {
296                 errorOut(e, "HClusterCommand", "printData");
297                 exit(1);
298         }
299
300
301 }
302 //**********************************************************************************************************************
303
304 vector<seqDist> HClusterCommand::getSeqs(ifstream& filehandle){
305         try {
306                 string firstName, secondName;
307                 float distance, prevDistance;
308                 vector<seqDist> sameSeqs;
309                 prevDistance = -1;
310                 
311                 //if you are not at the beginning of the file
312                 if (exitedBreak) { 
313                         sameSeqs.push_back(next);
314                         prevDistance = next.dist;
315                         exitedBreak = false;
316                 }
317         
318                 //get entry
319                 while (filehandle) {
320                         
321                         filehandle >> firstName >> secondName >> distance;  
322 //cout << firstName << '\t' << secondName << '\t' << distance << endl;
323                         gobble(filehandle);
324                         
325                         //save first one
326                         if (prevDistance == -1) { prevDistance = distance; }
327                         
328                         map<string,int>::iterator itA = globaldata->nameMap->find(firstName);
329                         map<string,int>::iterator itB = globaldata->nameMap->find(secondName);
330                         
331                         if(itA == globaldata->nameMap->end()){
332                                 cerr << "AAError: Sequence '" << firstName << "' was not found in the names file, please correct\n";
333                         }
334                         if(itB == globaldata->nameMap->end()){
335                                 cerr << "ABError: Sequence '" << secondName << "' was not found in the names file, please correct\n";
336                         }
337                         
338                         //using cutoff
339                         if (distance > cutoff) { break; }
340                         
341                         if (distance != -1) { //-1 means skip me
342                                 
343                                 //are the distances the same
344                                 if (distance == prevDistance) { //save in vector
345                                         seqDist temp;
346                                         temp.seq1 = itA->second;
347                                         temp.seq2 = itB->second;
348                                         temp.dist = distance;
349                                         sameSeqs.push_back(temp);
350                                         exitedBreak = false;
351                                         //what about precision??
352                                         
353                                 }else{ 
354                                         next.seq1 = itA->second;
355                                         next.seq2 = itB->second;
356                                         next.dist = distance;
357                                         exitedBreak = true;
358                                         break;
359                                 }
360                                 
361                         }
362                 }
363
364                 return sameSeqs;
365         }
366         catch(exception& e) {
367                 errorOut(e, "HClusterCommand", "getSeqs");
368                 exit(1);
369         }
370
371
372 }
373
374 //**********************************************************************************************************************
375