File: UPGMAAlgorithm.cpp

package info (click to toggle)
clustalx 2.1%2Blgpl-5
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,868 kB
  • sloc: cpp: 40,050; sh: 163; xml: 102; makefile: 15
file content (460 lines) | stat: -rw-r--r-- 14,271 bytes parent folder | download | duplicates (11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#ifdef HAVE_CONFIG_H
    #include "config.h"
#endif
#include "UPGMAAlgorithm.h"
#include <cmath>
#include <ctime>
#include <iomanip>
#include <sstream>

#include "../../general/SymMatrix.h"
#include "../../general/debuglogObject.h"
#include "../../general/clustalw.h"
#include "upgmadata.h"

namespace clustalw
{

UPGMAAlgorithm::UPGMAAlgorithm()
: overwriteMatrix(false),
  numSeqs(0),
  verbose(false),
  orderNode1(0),
  orderNode2(0),
  orderNewNode(0)
{}

auto_ptr<AlignmentSteps> UPGMAAlgorithm::generateTree(RootedGuideTree* phyTree,
                                          DistMatrix* distMat,
                                          SeqInfo* seqInfo, bool overwrite,
                                          ofstream* tree)
{
    if (tree == 0 || !tree->is_open())
    {
        verbose = false;
    }  

    if (verbose)
    {
        (*tree) << "\n\n\t\t\tUPGMA Method\n"
                << "\n\n This is a ROOTED tree\n"
                << "\n Numbers in parentheses are branch lengths\n\n";
    }
          
    progSteps.reset(new AlignmentSteps);
    
    Node** clusters; 
    Node* root;
    numSeqs = seqInfo->numSeqs;
    const int sizeDistMat = ((numSeqs + 1) * (numSeqs + 2)) / 2;
        
    double* elements = overwrite ? 
                      distMat->getDistMatrix(seqInfo->firstSeq, seqInfo->numSeqs) : 
                      (double *)memcpy(new double[sizeDistMat], 
                      distMat->getDistMatrix(seqInfo->firstSeq, seqInfo->numSeqs),
                      sizeDistMat * sizeof(double));
       
    clusters = initialiseNodes(elements, seqInfo->firstSeq);
    root = doUPGMA(clusters, tree);
    
    phyTree->setRoot(root);
    delete [] clusters;

    if(!overwrite)
    {
        delete [] elements;
    }
    distMat->clearSubArray(); 
    
    return progSteps;  
}


Node** UPGMAAlgorithm::initialiseNodes(double* distanceMatrix, int fSeq)
{    
    int firstSeq = fSeq; 

    
    Node** nodes = new Node*[numSeqs];
    Node** nodeIter = nodes;

    *nodes = new Node(firstSeq, 0, 0);
    
    distanceMatrix++;
    
    // Move to first position in distanceMatrix.
    for(int elementIndex = 1, e = numSeqs; elementIndex < e; 
        distanceMatrix += ++elementIndex) 
    {
        Node* newcluster = new Node(elementIndex + firstSeq, 
                                    distanceMatrix, elementIndex);             
        (*nodeIter++)->next = newcluster;
        *nodeIter = newcluster;
    }

  return nodes;
}

void UPGMAAlgorithm::printAllNodes(Node** nodes)
{
    int numNodes = 0;
    for(Node* nodeIter = *nodes; nodeIter; nodeIter = nodeIter->next)
    {
        numNodes++;
        cout << "Node " << numNodes << "\n";
        nodeIter->printElements();
        cout << "\n\n";
    }
    cout << "There are " << numNodes << " nodes\n";  
}

Node* UPGMAAlgorithm::doUPGMA(Node** nodes, ofstream* tree)
{
    if (tree == 0 || !tree->is_open())
    {
        verbose = false;
    } 
        
    string type1, type2;
    int step = 0;
    
    while((*nodes)->next) // While there is more than 1 node.
    {        
        step++;
        if (verbose)
        {
            (*tree) <<  "\n Cycle" << setw(4) << step << "     = ";
        }
        Node** ptrNodeWithMin;
        
        /** 
         * STEP 1 find node with min distance
         */
        ptrNodeWithMin = getNodeWithMinDist(nodes); 
        Node* nodeToJoin2 = *ptrNodeWithMin; 
        const int indexToMinDist = nodeToJoin2->indexToMinDist; 
        Node* const nodeToJoin1 = nodes[indexToMinDist];

        orderNode1 = nodeToJoin1->size;
        orderNode2 = nodeToJoin2->size;
        orderNewNode = orderNode1 + orderNode2;

        /**
         * STEP 2 Recompute the dist Matrix row for nodeToJoin1
         * example: Join nodes 2 and 6
         * 
         * 1  0
         * 2  X 0
         * 3  0 0 0
         * 4  0 0 0 0
         * 5  0 0 0 0 0
         * 6  0 0 0 0 0 0
         * 7  0 0 0 0 0 0 0
         */
        double* nodeToJoin2DistIter = nodeToJoin2->ptrToDistMatRow;
                
        if (indexToMinDist != 0)
        {
            recomputeNodeToJoin1DistMatRow(nodeToJoin1, &nodeToJoin2DistIter);
        }
        
        /**
         * STEP 3 Recompute all distances in column 
         * example: Join nodes 2 and 6
         * 
         * 1  0
         * 2  C 0
         * 3  0 X 0
         * 4  0 X 0 0
         * 5  0 X 0 0 0
         * 6  0 0 0 0 0 0
         * 7  0 X 0 0 0 0 0
         */
                 
        computeAllOtherDistsToNewNode(nodeToJoin1, nodeToJoin2, &nodeToJoin2DistIter);

        /**
         * STEP 4 Add the step to the progSteps.
         * This creates the multiple alignment steps.
         */     
        addAlignmentStep(&nodeToJoin1->allElements, &nodeToJoin2->allElements);

        
        double minDistance = (*ptrNodeWithMin)->minDist;
        
        double height = 0.0;                                  
        height = minDistance / 2.0;
        
        if(verbose)
        {
            if(nodeToJoin1->allElements.size() > 1)
            {
                type1 = "NODE: ";
            }
            else
            {
                type1 = "SEQ: ";
            }
            if(nodeToJoin2->allElements.size() > 1)
            {
                type2 = "NODE: ";
            }
            else
            {
                type2 = "SEQ: ";
            }
            (*tree) << type1 << nodeToJoin1->allElements[0] << " (" << setw(9) 
                    << setprecision(5) << height << ") joins " << type2 
                    << setw(4) << nodeToJoin2->allElements[0] << " (" 
                    << setw(9) << setprecision(5) << height << ")";
        }
        /**
         * STEP 5 merge 2 nodes
         */              
        nodeToJoin1->merge(ptrNodeWithMin, height);
  
    }

    return *nodes; 
}

/**
 * This function returns a Node object that has the minimum distance of
 * all the nodes left.
 */
Node** UPGMAAlgorithm::getNodeWithMinDist(Node** nodes)
{
    Node** ptrMinNode = NULL;
    double minDistance = numeric_limits<double>::max();
    //Start at node 1, check see if it points to something, then move on the next one.
    Node** nodeIter;
    for(nodeIter = &((*nodes)->next); *nodeIter; 
        nodeIter = &(*nodeIter)->next)
    {
        if ((*nodeIter)->getMinDist() < minDistance) 
        {
            minDistance = (*nodeIter)->getMinDist();
            ptrMinNode = nodeIter; // ptrMinNode will hold a ptr to node with sm'st dist
        }
    }
    return ptrMinNode;    
}

/**
 * This function is used to recompute the nodeToJoin1 dist mat row. Each row in the distance
 * matrix has the distances to all nodes before it, not after. For example the dist mat row
 * for Node 3 would have the distances to nodes 1 and 2.
         * 1  0
         * 2  0 0
         * 3  X X 0      Dists to node 1 and 2.
         * 4  0 0 0 0
         * 5  0 0 0 0 0
         * 6  0 0 0 0 0 0
         * 7  0 0 0 0 0 0 0 
 */
void UPGMAAlgorithm::recomputeNodeToJoin1DistMatRow(Node* nodeToJoin1, 
                                                    double** nodeToJoin2DistIter)
{
    double* nodeToJoin1DistIter = nodeToJoin1->ptrToDistMatRow;
    // calculate new distance
    *nodeToJoin1DistIter = calcNewDist(*nodeToJoin1DistIter, **nodeToJoin2DistIter);
                             
    const double* minIndex1 = nodeToJoin1DistIter;
    nodeToJoin1DistIter++; 
    (*nodeToJoin2DistIter)++;
    int numDistToUpdate = nodeToJoin1->numDists - 1;
            
    // For each of the distances in nodeToJoin1           
    while(numDistToUpdate > 0)
    {
        if (*nodeToJoin1DistIter >= 0) 
        {
            // Calculate the average
            *nodeToJoin1DistIter = calcNewDist(*nodeToJoin1DistIter, **nodeToJoin2DistIter);
            
            if (*nodeToJoin1DistIter < *minIndex1)
            {
                minIndex1 = nodeToJoin1DistIter;
            }
        }
        nodeToJoin1DistIter++;
        (*nodeToJoin2DistIter)++;
        numDistToUpdate--;
    }

    // We have found the minimum distance            
    nodeToJoin1->minDist = *minIndex1;
    nodeToJoin1->indexToMinDist = minIndex1 - nodeToJoin1->ptrToDistMatRow;
}

/**
 * This function is used to recompute all the other distances. It does this by calling
 * two other functions. We first compute all the distances until we get to node 2. 
 * Then we call another function to do the rest. This is because nodes after node 2 may
 * have had EITHER node1 of node2 as their min distance.
 */
void UPGMAAlgorithm::computeAllOtherDistsToNewNode(Node* nodeToJoin1, Node* nodeToJoin2,
                                                   double** nodeToJoin2DistIter)
{
    computeDistsUpToNodeToJoin2(nodeToJoin1, nodeToJoin2, nodeToJoin2DistIter);
    computeDistsForNodesAfterNode2(nodeToJoin2);
}

/**
 * STEP 3A:
 * This function recomputes the distances in column until we get to nodeToJoin2 
 * example: Join nodes 2 and 6
 * 
 * 1  0
 * 2  C 0
 * 3  0 X 0
 * 4  0 X 0 0
 * 5  0 X 0 0 0
 * 6  0 0 0 0 0 0
 * 7  0 0 0 0 0 0 0
 *
 * For each node until we get to nodeToJoin2    
 *    If newdistance is less than the old min distance, set it to this.
 *    else if its greater than old minDist and indexTominDist is the same, recompute min
 *    else leave the min the same as it hasnt changed.
 */
void UPGMAAlgorithm::computeDistsUpToNodeToJoin2(Node* nodeToJoin1, Node* nodeToJoin2, double** nodeToJoin2DistIter)
{
    const int indexToMinDist = nodeToJoin2->indexToMinDist;
    
    movePtrPastUnusedDistances(nodeToJoin2DistIter);
    
    Node* nodeIter;
    // For each node until we get to the second node we are joining           
    for(nodeIter = nodeToJoin1->next; nodeIter != nodeToJoin2; nodeIter = nodeIter->next) 
    {            
        (*nodeToJoin2DistIter)++; // Skip the distance to the node we are joining with
        movePtrPastUnusedDistances(nodeToJoin2DistIter);
                       
        double distToNode = nodeIter->ptrToDistMatRow[indexToMinDist];
            
        double newDistToNode = calcNewDist(distToNode, **nodeToJoin2DistIter);
        nodeIter->ptrToDistMatRow[indexToMinDist] = newDistToNode;
            
                        
        if (newDistToNode < nodeIter->minDist)
        { /** new value is smaller than current min. */
            nodeIter->minDist = newDistToNode;
            nodeIter->indexToMinDist = indexToMinDist;
        }
        else if ((newDistToNode > nodeIter->minDist) && 
                 (nodeIter->indexToMinDist == indexToMinDist)) 
        { /** indexToMinDist was the min dist, but it is now a larger num, recompute */
            nodeIter->findMinDist();
        }
            
    }

}

/**
 * STEP 3B Recompute distance for nodes after nodeToJoin2
 * example: Join nodes 2 and 6
 * 
 * 1  0
 * 2  C 0
 * 3  0 C 0
 * 4  0 C 0 0
 * 5  0 C 0 0 0
 * 6  0 0 0 0 0 0
 * 7  0 X 0 0 0 0 0
 *
 * For each node until we get to the end.            
 *     if dist is less than minDist, set mindist to new distance, set index to index
 *     else if dist is greater than mindist and the index was either nodetojoin1 or
 *     nodetojoin2, recompute distance, set entry for nodetojoin2 to NOTUSED
 *     else set the distance to unused. 
 */        

void UPGMAAlgorithm::computeDistsForNodesAfterNode2(Node* nodeToJoin2)
{
    int indexToNode2 = nodeToJoin2->numDists;
    const int indexToMinDist = nodeToJoin2->indexToMinDist;
    
    Node* nodeIter;       

    for(nodeIter = nodeToJoin2->next; nodeIter; nodeIter = nodeIter->next) 
    {              
        double &distUpdate = nodeIter->ptrToDistMatRow[indexToMinDist];
        
        distUpdate = 
	  ((distUpdate * orderNode1) + 
	   (nodeIter->ptrToDistMatRow[indexToNode2] * orderNode2)) 
	  / orderNewNode;

	/* The comparison (distUpdate > nodeIter->minDist) is unsafe. 
	 * Specifically, we get different results for 32/64bit machines, 
	 * which leads to different branching in the if/else statement 
	 * and nasty behaviour down the line. 
	 * Using all of Pfam as a benchmark distUpdate can 'wobble' by 40 ULPs
         * (Unit of Least Precision) which is difficult to translate into 
	 * a maximum relative error, so we pick COMPARE_REL_EPSILON 
	 * phenomenologically: approx 2E-15 was the biggest we saw in Pfam, 
	 * but suggest 1E-14 (for good measure). 
	 * Using ULPs, eg, *(long long int*)&(distUpdate),
	 * would be better (more elegant?) but gives problems 
	 * with aliasing and/or performance reduction. 
	 * FS, 2009-04-30 
	 */
#define COMPARE_REL_EPSILON 1E-14
        if ( (distUpdate < nodeIter->minDist) &&
	     ((nodeIter->minDist-distUpdate) /
	      nodeIter->minDist > COMPARE_REL_EPSILON) )
	  { /** new distance is smaller */
            nodeIter->minDist = distUpdate;
            nodeIter->indexToMinDist = indexToMinDist;
	  }
        else if (((distUpdate > nodeIter->minDist) &&
		  ((distUpdate-nodeIter->minDist) / 
		   distUpdate > COMPARE_REL_EPSILON) &&
		  (nodeIter->indexToMinDist == indexToMinDist)) ||
		 (nodeIter->indexToMinDist == indexToNode2))
	  { /** if old min dist was to either nodeToJoin1 or nodeToJoin2 */
            nodeIter->ptrToDistMatRow[indexToNode2] = BLANKDIST;
            nodeIter->findMinDist();
	  }
        else
	  {
            nodeIter->ptrToDistMatRow[indexToNode2] = BLANKDIST;
	  }
    }        

}

void UPGMAAlgorithm::addAlignmentStep(vector<int>* group1, vector<int>* group2)
{
    int sizeGroup1 = group1->size();
    int sizeGroup2 = group2->size();
    
    vector<int> groups;
    groups.resize(numSeqs + 1, 0);
    int sizeGroup = groups.size();
    
    for(int i = 0; i < sizeGroup1 && (*group1)[i] < sizeGroup; i++)
    {
        groups[(*group1)[i]] = 1; // Set to be apart of group1
    }
    
    for(int i = 0; i < sizeGroup2 && (*group2)[i] < sizeGroup; i++)
    {
        groups[(*group2)[i]] = 2; // Set to be apart of group1
    }
    
    progSteps->saveSet(&groups); 
}

/**
 * At the moment we are only using average distance, UPGMA, but we can also use this 
 * function to have different distance measures, min, max etc.
 */
double UPGMAAlgorithm::calcNewDist(double dist1, double dist2)
{
    return ((dist1 * orderNode1) + (dist2 * orderNode2)) / orderNewNode;
}
  
}