source: branches/stable/GDE/MUSCLE/src/difftrees.cpp

Last change on this file was 10390, checked in by aboeckma, 11 years ago

added muscle sourcles amd makefile

File size: 10.9 KB
Line 
1#include "muscle.h"
2#include "tree.h"
3
4#define TRACE   0
5
6/***
7Algorithm to compare two trees, X and Y.
8
9A node x in X and node y in Y are defined to be
10similar iff the set of leaves in the subtree under
11x is identical to the set of leaves under y.
12
13A node is defined to be dissimilar iff it is not
14similar to any node in the other tree.
15
16Nodes x and y are defined to be married iff every
17node in the subtree under x is similar to a node
18in the subtree under y. Married nodes are considered
19to be equal. The subtrees under two married nodes can
20at most differ by exchanges of left and right branches,
21which we do not consider to be significant here.
22
23A node is defined to be a bachelor iff it is not
24married. If a node is a bachelor, then it has a
25dissimilar node in its subtree, and it follows
26immediately from the definition of marriage that its
27parent is also a bachelor. Hence all nodes on the path
28from a bachelor node to the root are bachelors.
29
30We assume the trees have the same set of leaves, so
31every leaf is trivially both similar and married to
32the same leaf in the opposite tree. Bachelor nodes
33are therefore always internal (i.e., non-leaf) nodes.
34
35A node is defined to be a diff iff (a) it is married
36and (b) its parent is a bachelor. The subtree under
37a diff is maximally similar to the other tree. (In
38other words, you cannot extend the subtree without
39adding a bachelor).
40
41The set of diffs is the subset of the two trees that
42we consider to be identical.
43
44Example:
45
46              -----A
47        -----k
48   ----j      -----B
49--i     -----C
50   ------D
51
52
53              -----A
54        -----p
55   ----n      -----B
56--m     -----D
57   ------C
58
59
60The following pairs of internal nodes are similar.
61
62        Nodes   Set of leaves
63        -----   -------------
64        k,p             A,B
65        i,m             A,B,C,D
66
67Bachelors in the first tree are i and j, bachelors
68in the second tree are m and n.
69
70Node k and p are married, but i and m are not (because j
71and n are bachelors). The diffs are C, D and k.
72
73The set of bachelor nodes can be viewed as the internal
74nodes of a tree, the leaves of which are diffs. (To see
75that there can't be disjoint subtrees, note that the path
76from a diff to a root is all bachelor nodes, so there is
77always a path between two diffs that goes through the root).
78We call this tree the "diffs tree".
79
80There is a simple O(N) algorithm to build the diffs tree.
81To achieve O(N) we avoid traversing a given subtree multiple
82times and also avoid comparing lists of leaves.
83
84We visit nodes in depth-first order (i.e., a node is visited
85before its parent).
86
87If either child of a node is a bachelor, we flag it as
88a bachelor.
89
90If both children of the node we are visiting are married,
91we check whether the spouses of those children have the
92same parent in the other tree. If the parents are different,
93the current node is a bachelor. If they have the same parent,
94then the node we are visiting is the spouse of that parent.
95We assign this newly identified married couple a unique integer
96id. The id of a node is in one-to-one correspondence with the
97set of leaves in its subtree. Two nodes have the same set of
98leaves iff they have the same id. Bachelor nodes do not get
99an id.
100***/
101
102static void BuildDiffs(const Tree &tree, unsigned uTreeNodeIndex,
103  const bool bIsDiff[], Tree &Diffs, unsigned uDiffsNodeIndex,
104  unsigned IdToDiffsLeafNodeIndex[])
105        {
106#if     TRACE
107        Log("BuildDiffs(TreeNode=%u IsDiff=%d IsLeaf=%d)\n",
108          uTreeNodeIndex, bIsDiff[uTreeNodeIndex], tree.IsLeaf(uTreeNodeIndex));
109#endif
110        if (bIsDiff[uTreeNodeIndex])
111                {
112                unsigned uLeafCount = tree.GetLeafCount();
113                unsigned *Leaves = new unsigned[uLeafCount];
114                GetLeaves(tree, uTreeNodeIndex, Leaves, &uLeafCount);
115                for (unsigned n = 0; n < uLeafCount; ++n)
116                        {
117                        const unsigned uLeafNodeIndex = Leaves[n];
118                        const unsigned uId = tree.GetLeafId(uLeafNodeIndex);
119                        if (uId >= tree.GetLeafCount())
120                                Quit("BuildDiffs, id out of range");
121                        IdToDiffsLeafNodeIndex[uId] = uDiffsNodeIndex;
122#if     TRACE
123                        Log("  Leaf id=%u DiffsNode=%u\n", uId, uDiffsNodeIndex);
124#endif
125                        }
126                delete[] Leaves;
127                return;
128                }
129
130        if (tree.IsLeaf(uTreeNodeIndex))
131                Quit("BuildDiffs: should never reach leaf");
132
133        const unsigned uTreeLeft = tree.GetLeft(uTreeNodeIndex);
134        const unsigned uTreeRight = tree.GetRight(uTreeNodeIndex);
135
136        const unsigned uDiffsLeft = Diffs.AppendBranch(uDiffsNodeIndex);
137        const unsigned uDiffsRight = uDiffsLeft + 1;
138
139        BuildDiffs(tree, uTreeLeft, bIsDiff, Diffs, uDiffsLeft, IdToDiffsLeafNodeIndex);
140        BuildDiffs(tree, uTreeRight, bIsDiff, Diffs, uDiffsRight, IdToDiffsLeafNodeIndex);
141        }
142
143void DiffTrees(const Tree &Tree1, const Tree &Tree2, Tree &Diffs,
144  unsigned IdToDiffsLeafNodeIndex[])
145        {
146#if     TRACE
147        Log("Tree1:\n");
148        Tree1.LogMe();
149        Log("\n");
150        Log("Tree2:\n");
151        Tree2.LogMe();
152#endif
153
154        if (!Tree1.IsRooted() || !Tree2.IsRooted())
155                Quit("DiffTrees: requires rooted trees");
156
157        const unsigned uNodeCount = Tree1.GetNodeCount();
158        const unsigned uNodeCount2 = Tree2.GetNodeCount();
159       
160        const unsigned uLeafCount = Tree1.GetLeafCount();
161        const unsigned uLeafCount2 = Tree2.GetLeafCount();
162        assert(uLeafCount == uLeafCount2);
163
164        if (uNodeCount != uNodeCount2)
165                Quit("DiffTrees: different node counts");
166
167// Allocate tables so we can convert tree node index to
168// and from the unique id with a O(1) lookup.
169        unsigned *NodeIndexToId1 = new unsigned[uNodeCount];
170        unsigned *IdToNodeIndex2 = new unsigned[uNodeCount];
171
172        bool *bIsBachelor1 = new bool[uNodeCount];
173        bool *bIsDiff1 = new bool[uNodeCount];
174
175        for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
176                {
177                NodeIndexToId1[uNodeIndex] = uNodeCount;
178                bIsBachelor1[uNodeIndex] = false;
179                bIsDiff1[uNodeIndex] = false;
180
181        // Use uNodeCount as value meaning "not set".
182                IdToNodeIndex2[uNodeIndex] = uNodeCount;
183                }
184
185// Initialize node index <-> id lookup tables
186        for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
187                {
188                if (Tree1.IsLeaf(uNodeIndex))
189                        {
190                        const unsigned uId = Tree1.GetLeafId(uNodeIndex);
191                        if (uId >= uNodeCount)
192                                Quit("Diff trees requires existing leaf ids in range 0 .. (N-1)");
193                        NodeIndexToId1[uNodeIndex] = uId;
194                        }
195
196                if (Tree2.IsLeaf(uNodeIndex))
197                        {
198                        const unsigned uId = Tree2.GetLeafId(uNodeIndex);
199                        if (uId >= uNodeCount)
200                                Quit("Diff trees requires existing leaf ids in range 0 .. (N-1)");
201                        IdToNodeIndex2[uId] = uNodeIndex;
202                        }
203                }
204
205// Validity check. This verifies that the ids
206// pre-assigned to the leaves in Tree1 are unique
207// (note that the id<N check above does not rule
208// out two leaves having duplicate ids).
209        for (unsigned uId = 0; uId < uLeafCount; ++uId)
210                {
211                unsigned uNodeIndex2 = IdToNodeIndex2[uId];
212                if (uNodeCount == uNodeIndex2)
213                        Quit("DiffTrees, check 2");
214                }
215
216// Ids assigned to internal nodes are N, N+1 ...
217// An internal node id uniquely identifies a set
218// of two or more leaves.
219        unsigned uInternalNodeId = uLeafCount;
220
221// Depth-first traversal of tree.
222// The order guarantees that a node is visited before
223// its parent is visited.
224        for (unsigned uNodeIndex1 = Tree1.FirstDepthFirstNode();
225          NULL_NEIGHBOR != uNodeIndex1;
226          uNodeIndex1 = Tree1.NextDepthFirstNode(uNodeIndex1))
227                {
228#if     TRACE
229                Log("Main loop: Node1=%u IsLeaf=%d IsBachelor=%d\n",
230                  uNodeIndex1,
231                  Tree1.IsLeaf(uNodeIndex1),
232                  bIsBachelor1[uNodeIndex1]);
233#endif
234
235        // Leaves are trivial; nothing to do.
236                if (Tree1.IsLeaf(uNodeIndex1) || bIsBachelor1[uNodeIndex1])
237                        continue;
238
239        // If either child is a bachelor, flag
240        // this node as a bachelor and continue.
241                unsigned uLeft1 = Tree1.GetLeft(uNodeIndex1);
242                if (bIsBachelor1[uLeft1])
243                        {
244                        bIsBachelor1[uNodeIndex1] = true;
245                        continue;
246                        }
247
248                unsigned uRight1 = Tree1.GetRight(uNodeIndex1);
249                if (bIsBachelor1[uRight1])
250                        {
251                        bIsBachelor1[uNodeIndex1] = true;
252                        continue;
253                        }
254
255        // Both children are married.
256        // Married nodes are guaranteed to have an id.
257                unsigned uIdLeft = NodeIndexToId1[uLeft1];
258                unsigned uIdRight = NodeIndexToId1[uRight1];
259
260                if (uIdLeft == uNodeCount || uIdRight == uNodeCount)
261                        Quit("DiffTrees, check 5");
262
263        // uLeft2 is the spouse of uLeft1, and similarly for uRight2.
264                unsigned uLeft2 = IdToNodeIndex2[uIdLeft];
265                unsigned uRight2 = IdToNodeIndex2[uIdRight];
266
267                if (uLeft2 == uNodeCount || uRight2 == uNodeCount)
268                        Quit("DiffTrees, check 6");
269
270        // If the spouses of uLeft1 and uRight1 have the same
271        // parent, then this parent is the spouse of uNodeIndex1.
272        // Otherwise, uNodeIndex1 is a diff.
273                unsigned uParentLeft2 = Tree2.GetParent(uLeft2);
274                unsigned uParentRight2 = Tree2.GetParent(uRight2);
275
276#if     TRACE
277                Log("L1=%u R1=%u L2=%u R2=%u PL2=%u PR2=%u\n",
278                  uLeft1,
279                  uRight1,
280                  uLeft2,
281                  uRight2,
282                  uParentLeft2,
283                  uParentRight2);
284#endif
285
286                if (uParentLeft2 == uParentRight2)
287                        {
288                        NodeIndexToId1[uNodeIndex1] = uInternalNodeId;
289                        IdToNodeIndex2[uInternalNodeId] = uParentLeft2;
290                        ++uInternalNodeId;
291                        }
292                else
293                        bIsBachelor1[uNodeIndex1] = true;
294                }
295
296        unsigned uDiffCount = 0;
297        for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex)
298                {
299                if (bIsBachelor1[uNodeIndex])
300                        continue;
301                if (Tree1.IsRoot(uNodeIndex))
302                        {
303                // Special case: if no bachelors, consider the
304                // root a diff.
305                        if (!bIsBachelor1[uNodeIndex])
306                                bIsDiff1[uNodeIndex] = true;
307                        continue;
308                        }
309                const unsigned uParent = Tree1.GetParent(uNodeIndex);
310                if (bIsBachelor1[uParent])
311                        {
312                        bIsDiff1[uNodeIndex] = true;
313                        ++uDiffCount;
314                        }
315                }
316
317#if     TRACE
318        Log("Tree1:\n");
319        Log("Node    Id  Bach  Diff  Name\n");
320        Log("----  ----  ----  ----  ----\n");
321        for (unsigned n = 0; n < uNodeCount; ++n)
322                {
323                Log("%4u  %4u     %d     %d",
324                  n,
325                  NodeIndexToId1[n],
326                  bIsBachelor1[n],
327                  bIsDiff1[n]);
328                if (Tree1.IsLeaf(n))
329                        Log("  %s", Tree1.GetLeafName(n));
330                Log("\n");
331                }
332        Log("\n");
333        Log("Tree2:\n");
334        Log("Node    Id              Name\n");
335        Log("----  ----              ----\n");
336        for (unsigned n = 0; n < uNodeCount; ++n)
337                {
338                Log("%4u                  ", n);
339                if (Tree2.IsLeaf(n))
340                        Log("  %s", Tree2.GetLeafName(n));
341                Log("\n");
342                }
343#endif
344
345        Diffs.CreateRooted();
346        const unsigned uDiffsRootIndex = Diffs.GetRootNodeIndex();
347        const unsigned uRootIndex1 = Tree1.GetRootNodeIndex();
348
349        for (unsigned n = 0; n < uLeafCount; ++n)
350                IdToDiffsLeafNodeIndex[n] = uNodeCount;
351
352        BuildDiffs(Tree1, uRootIndex1, bIsDiff1, Diffs, uDiffsRootIndex,
353          IdToDiffsLeafNodeIndex);
354
355#if TRACE
356        Log("\n");
357        Log("Diffs:\n");
358        Diffs.LogMe();
359        Log("\n");
360        Log("IdToDiffsLeafNodeIndex:");
361        for (unsigned n = 0; n < uLeafCount; ++n)
362                {
363                if (n%16 == 0)
364                        Log("\n");
365                else
366                        Log(" ");
367                Log("%u=%u", n, IdToDiffsLeafNodeIndex[n]);
368                }
369        Log("\n");
370#endif
371
372        for (unsigned n = 0; n < uLeafCount; ++n)
373                if (IdToDiffsLeafNodeIndex[n] == uNodeCount)
374                        Quit("TreeDiffs check 7");
375
376        delete[] NodeIndexToId1;
377        delete[] IdToNodeIndex2;
378
379        delete[] bIsBachelor1;
380        delete[] bIsDiff1;
381        }
Note: See TracBrowser for help on using the repository browser.