Algorithm Search⌘K

Algorithmadvanced

Chawathe change detection

Also called change detection in hierarchically structured information.

Turn a node matching of two ordered labeled trees into a least cost script of inserts, deletes, updates and subtree moves that keeps it, in O(n d) time for d misaligned nodes.

Time
O(n + n d) worst
Space
O(n) extra
Where
d = the number of misaligned nodes; n = the total number of nodes of the two trees
Properties
deterministicofflineiterative

Chawathe change detection finds the changes between two versions of a tree, such as two versions of a structured document, as an edit script: a list of inserts and deletes of leaves, updates of values, and moves of whole subtrees. It works in two steps. First it matches the nodes of the old tree with the nodes of the new tree that stand for the same thing. Then Algorithm EditScript turns the matching into a script that keeps all the matched pairs and has the smallest cost among such scripts, in time O(nd)O(n d), where nn is the number of nodes and dd the number of misaligned nodes. Sudarshan Chawathe, Anand Rajaraman, Hector Garcia-Molina and Jennifer Widom described the method at Stanford in 1996, with Algorithm FastMatch for the matching of documents without keys, and built it into LaDiff, a tool that marks the changes between two LaTeX documents.

In plain words

Think of a document as a tree: the document has sections, sections have paragraphs, and paragraphs have sentences. Between two versions, some sentences are new, some are gone, some have new words, and some paragraphs moved.

First decide which old parts are the same as which new parts. A sentence matches a sentence with almost the same words, and a paragraph matches a paragraph that keeps most of its sentences.

Then walk through the new tree from the top, one level at a time. For each new part, take its old partner, fix its words if they changed, and move it under the right parent if it is somewhere else. Put the children in the right order with as few moves as possible. Add the new parts that have no partner. At the end, remove the old parts that nobody matched.

The problem

The input is two ordered trees T1T_1 (old) and T2T_2 (new), whose nodes have identifiers, labels and values, and a matching MM: a set of pairs (x,y)(x, y) of a node of T1T_1 and a node of T2T_2 with the same label, each node in at most one pair. The four operations are INS((w,l,v),y,k)((w, l, v), y, k), which inserts a new leaf ww with label ll and value vv as the kk-th child of yy; DEL(x)(x), which deletes a leaf; UPD(x,v)(x, v), which sets the value of xx; and MOV(x,y,k)(x, y, k), which makes xx the kk-th child of yy, with its subtree. Inserts, deletes and moves cost 1, and an update costs compare(v,v′)(v, v'), a number in [0,2][0, 2]. The output is a script of least cost that transforms T1T_1 into a tree that differs from T2T_2 only in identifiers, and whose final matching contains MM. The paper calls this the minimum conforming edit script (MCES) problem.

The algorithm

EditScript goes through T2T_2 in breadth-first order and changes T1T_1 as it writes each operation. When it reaches a node xx, its parent is already in place in T1T_1, so it can put the partner of xx under the partner of p(x)p(x). Each node of T2T_2 is marked "in order" once the position of its partner among its siblings is final.

  1. EDIT-SCRIPT(T1, T2, M)
  2. 1if the roots of T1 and T2 are not a pair of M then put new roots above T1 and T2 and add them to M as a pair
  3. 2for each node x of T2 in breadth-first order, with y = p(x):
  4. 3if x has no partner then INS((w, l(x), v(x)), partner(y), FIND-POS(x)) for a new w; add (w, x) to M; mark x in order
  5. 4else w ← partner(x)
  6. 5if v(w) ≠ v(x) then UPD(w, v(x))
  7. 6if x is not the root and (p(w), y) ∉ M then MOV(w, partner(y), FIND-POS(x)); mark x in order
  8. 7ALIGN-CHILDREN(partner(x), x)
  9. 8for each node w of T1 in post-order: if w has no partner then DEL(w)
  10. 9return the script and M
  11. ALIGN-CHILDREN(w, x)
  12. 10mark all children of x out of order
  13. 11S1 ← the children of w whose partners are children of x; S2 ← the children of x whose partners are children of w
  14. 12S ← LCS(S1, S2), where a equals b if (a, b) ∈ M; mark the nodes of S2 in S in order
  15. 13for each a in S1 that is not in S, with partner b: MOV(a, w, FIND-POS(b)); mark b in order
  16. FIND-POS(x)
  17. 14if no sibling of x to its left in T2 is marked in order then return 1
  18. 15u ← the partner of the rightmost such sibling; return 1 + the place of u among the children of p(u), without the partner of x

The longest common subsequence of line L12 keeps the most children in place, and only the others move. Lines L14 and L15 differ from Figure 9 of the paper in two details. The paper counts only the children that are marked in order, and it does not mark the nodes that lines L3 and L6 place. Both are needed: if T1T_1 is r(d,a)r(d, a) with dd unmatched and T2T_2 is r(a,b)r(a, b), counting only marked children puts the new bb at place 2, before aa, and if T2T_2 is r(a,b,c)r(a, b, c) with bb and cc new, an unmarked bb makes cc go directly after aa.

Finding the matching. When the nodes have keys, the matching is simple. For documents without keys, the paper uses these rules. Two leaves may match if they have the same label and compare of their values is at most ff, with 0≤f≤10 \le f \le 1 (Criterion 1). Two internal nodes may match if they have the same label and more than a fraction tt of the leaves below the larger one are matched to leaves below the other, with 12≤t≤1\frac12 \le t \le 1 (Criterion 2). Algorithm FastMatch puts the nodes with each label in a chain from left to right. For each leaf label and then for each internal label, it computes an LCS of the two chains, with equal as the test, adds its pairs to the matching, and then pairs each node that is still unmatched with the first unmatched node of the other chain that passes the test. Algorithm Match does only this last step, for all nodes, from the bottom up.

Example

This is the running example of the paper (Figure 1). The labels D, P and S stand for document, paragraph and sentence, the letters are the values of the sentences, and the numbers are the identifiers.

T1:  1 D                         T2:  11 D
       2 P:  5 a, 6 b, 7 c              12 P:  15 a, 16 c
       3 P:  8 d, 9 e                   13 P:  17 f
       4 P:  10 f                       14 P:  18 d, 19 e, 20 g

FastMatch first matches the sentences with equal values, (5,15)(5, 15), (7,16)(7, 16), (8,18)(8, 18), (9,19)(9, 19) and (10,17)(10, 17); sentence 6 has no partner. Then it matches the paragraphs: 2 has two of its three sentences matched into 12, 3 has two of the three sentences of 14, and 4 has the one sentence of 13, so with t=0.6t = 0.6 it adds (2,12)(2, 12), (3,14)(3, 14) and (4,13)(4, 13). Last, it matches the documents, (1,11)(1, 11). Algorithm Match gives the same matching in Example 5.1 of the paper.

EditScript starts at the root 11. The roots are a pair, so line L1 does nothing. ALIGN-CHILDREN(1,11)(1, 11) compares S1=2,3,4S_1 = 2, 3, 4 with S2=12,13,14S_2 = 12, 13, 14, whose partners in T1T_1 are 2,4,32, 4, 3. A longest common subsequence has length 2, so one paragraph must move. The code takes the subsequence 2,42, 4 and writes MOV(3,1,3)(3, 1, 3); the paper takes 2,32, 3 and writes MOV(4,1,2)(4, 1, 2), which costs the same. The children of 12, 13 and 14 are already aligned. Node 20 has no partner. Its marked left sibling is 19, whose partner 9 is the second child of 3, so line L3 writes INS((21,S,g),3,3)((21, S, g), 3, 3). The delete phase writes DEL(6)(6). The script has three operations, the least possible: sentence 6 must go, sentence gg must come, and the order of the paragraphs needs a move.

Correctness

The proof file shows that EditScript is correct and minimal. When the loop reaches a node, its parent is processed, so the partner of the parent exists and no later operation changes its place. FIND-POS puts each node directly after the partner of its rightmost marked left sibling, so the marked partners stay in the order of T2T_2, and at the end all children of each node are marked. A node without a partner has no children with partners, so the post-order deletes it as a leaf. The resulting tree has the shape, the labels and the values of T2T_2.

For the cost, every script that pairs exactly the nodes of MM must delete each unmatched node of T1T_1, insert one for each unmatched node of T2T_2, update each pair with different values, and move each matched node whose parent is not the partner of its new parent. Among the children of a matched pair, the ones that never move keep their order, so they form a common subsequence, and at least the others must move. EditScript writes exactly these operations. With the definition of the paper, a script only needs to keep the pairs of MM, and it may also update an unmatched leaf into an unmatched leaf of T2T_2, which can be cheaper than a delete and an insert. So minimality holds when the matching is maximal, which is what the matching criteria aim for.

Proof: EditScript turns T1 into T2, keeps the matching, and uses the fewest operations of all scripts that respect the matchingfull

We use the pseudocode of the page. T1T_1 and T2T_2 are ordered trees whose nodes have a label ll and a value vv, and MM is a matching of some nodes of T1T_1 with nodes of T2T_2 of the same label. We write p(x)p(x) for the parent of xx and partner for the other node of a pair. Line L1 makes the two roots a pair, so from now on we take T1T_1 and T2T_2 to be the trees with the new roots, and we count the new roots as a pair of MM. The algorithm applies each operation to T1T_1 when it writes it, and tt denotes this changing tree. The operations are those of Section 3.2 of the paper: INS adds a leaf as the kk-th child of a node, DEL removes a leaf, UPD changes a value, and MOV(a,w,k)(a, w, k) makes aa, with its subtree, the kk-th child of ww. INS, DEL and MOV of a node do not change the relative order of the other children of any node.

A node xx of T2T_2 is processed when the loop of line L2 has done lines L3 to L7 for it. Since the loop goes in breadth-first order, a node is processed after its parent, and the children of a node are processed one after the other, from left to right.

Lemma 1 (what changes a placed node). A node of tt changes its parent only through a MOV of that node. When xx is processed, the only nodes that move are the partner of xx (line L6) and children of the partner of xx whose partners are children of xx (line L13). So once a node xx is processed, the parent and the value of its partner do not change again during the loop.

Proof. DEL and INS act on leaves and move no other node. Line L6 moves the partner ww of xx, and line L13 moves children aa of ww whose partners are children of xx, which come later in breadth-first order than xx and are not processed yet. A node xx processed earlier is neither of these, and the only update to its partner is at line L5 while xx is processed. □\square

Invariant. For each node yy of T2T_2 whose children have been aligned at line L7, the partners of the children of yy that are marked "in order" are children of the partner of yy, and they stand there in the same order as their partners stand in T2T_2.

Lemma 2 (FIND-POS). Let yy be a node of T2T_2 that meets the invariant, ww its partner and xx a child of yy that is not marked. If the algorithm puts a node aa, the new partner or the partner of xx, as the kk-th child of ww with $k = $ FIND-POS(x)(x) and then marks xx, the invariant still holds for yy.

Proof. If no sibling of xx to its left is marked, k=1k = 1 and aa becomes the first child of ww; every marked sibling of xx is to its right in T2T_2, and its partner is to the right of aa. Otherwise let vv be the rightmost marked sibling to the left of xx and uu its partner, which is a child of ww by the invariant. Line L15 counts the children of ww without aa and returns one more than the place of uu, so after the operation aa stands directly after uu. The marked siblings to the left of xx are vv and siblings to the left of vv, whose partners stand before or at uu. The marked siblings to the right of xx are to the right of vv, so their partners stand after uu, and so after aa. The order of the other marked partners does not change, as the operations do not change the relative order of other children. □\square

Lemma 3 (ALIGN-CHILDREN). After ALIGN-CHILDREN(w,x)(w, x), every child of xx whose partner is a child of ww is marked, and the invariant holds for xx.

Proof. Line L10 removes the marks of the children of xx, so no child of xx is marked. Line L12 marks the nodes of S2S_2 in the common subsequence; their partners are in S1S_1 in the same order as in S2S_2, and S1S_1 and S2S_2 are in the orders of tt and of T2T_2. So the invariant holds. Line L13 moves each other node of S1S_1 and marks its partner, and the invariant still holds by Lemma 2. At the end each node of S2S_2 is marked. □\square

Lemma 4 (the loop). When the loop ends, every node xx of T2T_2 has a partner ww in tt with l(w)=l(x)l(w) = l(x) and v(w)=v(x)v(w) = v(x); if xx is not the root, p(w)p(w) is the partner of p(x)p(x); and the partners of the children of each node yy are children of the partner of yy, in the order of T2T_2. Every operation of the loop can be applied.

Proof. Take xx when it is processed, with y=p(x)y = p(x) processed before. If xx has no partner, line L3 inserts a leaf with the label and the value of xx under the partner of yy, which exists. Else the partner ww has the label of xx by the definition of a matching, and line L5 gives it the value of xx. If p(w)p(w) is not the partner of yy, line L6 moves ww there. This move is legal: the ancestors of the partner of yy are the partners of the ancestors of yy, by the claim for the nodes processed before, and xx is not an ancestor of yy, so the partner of yy is not in the subtree of ww. The moves of line L13 stay inside one parent and are legal. Each position kk is between 1 and the number of children plus 1, since FIND-POS returns 1 or one more than the place of a child that stays. By Lemma 1, the parent and the value fixed now stay until the end of the loop.

The children of xx are processed after ALIGN-CHILDREN(w,x)(w, x) at line L7. By Lemma 3, after it, the children of xx whose partners are children of ww are marked. Every other child of xx is marked when it is processed, by lines L3 or L6, and Lemma 2 keeps the invariant. Line L10 is the only place where marks are removed, and it is done once for each node. So at the end every child of yy is marked, and the invariant gives the claim on the order. □\square

Lemma 5 (the delete phase). Line L8 deletes exactly the nodes of T1T_1 that have no partner, each one while it is a leaf.

Proof. Let uu be a node of tt without a partner. Such a node is a node of T1T_1 that MM does not match, since all inserted nodes get a partner. A child cc of uu cannot have a partner: by Lemma 4, the parent of a node with a partner zz is the partner of p(z)p(z), which is not uu. So all descendants of uu have no partner either. The post-order visits them before uu and deletes them, so uu is a leaf when it is deleted. Nodes with partners are never deleted. □\square

Theorem 1 (a conforming edit script). The script EE of EditScript transforms T1T_1 into a tree isomorphic to T2T_2, and the final matching contains MM, so EE conforms to MM.

Proof. After line L8, by Lemma 5, the nodes of tt are the nodes with partners. By Lemma 4 the partner map is one to one and onto T2T_2, keeps labels and values, maps the parent of a node to the parent of its partner, and keeps the order of children. A node of tt that is a child of the partner of yy has a partner zz with p(z)=yp(z) = y, so the partner of yy has no other children. So the partner map is an isomorphism. The pairs of MM are never changed, and the final matching is MM plus one pair for each inserted node. □\square

Respecting the matching. We call a script that transforms T1T_1 into a tree isomorphic to T2T_2 respectful of MM if its final matching, restricted to the nodes of T1T_1, is exactly MM. So it deletes each node of T1T_1 that MM does not match, and it pairs each node of T2T_2 that MM does not match with an inserted node. The script of EditScript is respectful. The paper calls a script conforming if its final matching contains MM; such a script may also pair an unmatched node of T1T_1 with an unmatched node of T2T_2. For T1=r(a)T_1 = r(a) and T2=r(b)T_2 = r(b) with leaves of the same label and M={(r,r)}M = \{(r, r)\}, the script UPD(a,b)(a, b) conforms to MM and costs compare(a,b)(a, b), while EditScript writes an insert and a delete, of cost 2. So minimality holds for respectful scripts, or for conforming scripts when MM is maximal in the sense of the paper, in which case no such pair is left.

Lemma 6 (the number of operations). Let S1(u,v)S_1(u, v) be the children of uu in T1T_1 whose partners are children of vv in T2T_2, in the order of T1T_1, and S2(u,v)S_2(u, v) their partners, in the order of T2T_2. The script EE has

∣E∣=d1+d2+c+m+∑(u,v)∈M(∣S1(u,v)∣−∣LCS(S1(u,v),S2(u,v))∣),|E| = d_1 + d_2 + c + m + \sum_{(u, v) \in M} \big(|S_1(u, v)| - |\mathrm{LCS}(S_1(u, v), S_2(u, v))|\big),

where d1d_1 and d2d_2 are the numbers of nodes of T1T_1 and T2T_2 that MM does not match, cc is the number of pairs (a,b)(a, b) of MM with v(a)≠v(b)v(a) \ne v(b), and mm is the number of pairs (a,b)(a, b) of MM, other than the roots, with (p(a),p(b))∉M(p(a), p(b)) \notin M.

Proof. Line L3 inserts one node for each node of T2T_2 without a partner, and line L8 deletes one node for each node of T1T_1 without a partner, by Lemma 5. Line L5 updates a pair of MM when the values differ, and never an inserted node, which has the value of its partner. By Lemma 1, when xx is processed, its partner ww has not moved yet, so p(w)p(w) is still its parent in T1T_1, and line L6 moves it exactly when (p(w),p(x))∉M(p(w), p(x)) \notin M; if p(x)p(x) has an inserted partner, (p(w),p(x))(p(w), p(x)) is not in MM either. At ALIGN-CHILDREN(w,x)(w, x) with (w,x)∈M(w, x) \in M, the children of ww whose partners are children of xx are those of T1T_1, in the order of T1T_1: by Lemma 1, none of them has moved, and the nodes that come into ww later are partners of children of xx processed after this call. So the sequences of line L11 are S1(w,x)S_1(w, x) and S2(w,x)S_2(w, x), and line L13 moves ∣S1∣−∣LCS∣|S_1| - |\mathrm{LCS}| nodes. For an inserted ww, S1S_1 is empty. These are all the operations. □\square

Theorem 2 (minimum cost). With unit costs for INS, DEL and MOV and a cost compare(v,v′)(v, v') for each update, where compare meets the triangle inequality, no script that respects MM costs less than EE.

Proof. Take a respectful script E′E'. It contains a delete of each of the d1d_1 unmatched nodes of T1T_1 and an insert for each of the d2d_2 unmatched nodes of T2T_2. For each pair (a,b)(a, b) of MM with v(a)≠v(b)v(a) \ne v(b), it updates aa; the updates of aa go from v(a)v(a) to v(b)v(b), so by the triangle inequality they cost at least compare(v(a),v(b))(v(a), v(b)), which is what EE pays. For each pair (a,b)(a, b) with (p(a),p(b))∉M(p(a), p(b)) \notin M, the final parent of aa is the final partner of p(b)p(b), which is not p(a)p(a): either p(b)p(b) has a partner in MM other than p(a)p(a), or its final partner is an inserted node. Only a MOV of aa changes its parent, so E′E' moves aa. For each pair (u,v)(u, v) of MM, the nodes of S1(u,v)S_1(u, v) are children of uu at the start and at the end. Those that E′E' never moves keep their relative order, since no operation on other nodes changes it, and at the end they stand in the order of their partners in T2T_2. So they form a common subsequence of S1S_1 and S2S_2, and E′E' moves at least ∣S1∣−∣LCS∣|S_1| - |\mathrm{LCS}| of them. These moved nodes differ from those of the pairs counted in mm, since their parents are a pair, and they differ between pairs (u,v)(u, v). Adding up, E′E' costs at least the cost of EE given by Lemma 6. This is Lemma C.1 and Theorem C.2 of the paper. □\square

Running time of the code. The breadth-first and post-order traversals take O(n)O(n) for trees with nn nodes in total. FIND-POS scans the children of one node, so it costs O(n)O(n) for each insert or move. ALIGN-CHILDREN with the dynamic program of the longest common subsequence costs O(∣S1∣∣S2∣)O(|S_1| |S_2|), and the sizes of all the S1S_1 add up to at most nn. So the total is O(n2)O(n^2) time and space in the worst case. The paper computes the common subsequence with Myers' algorithm, which takes O((∣S1∣+∣S2∣)⋅(∣S1∣−∣LCS∣))O((|S_1| + |S_2|) \cdot (|S_1| - |\mathrm{LCS}|)), and states O(nd)O(n d) in total, with dd the number of misaligned nodes.

The matching of FastMatch. Every pair that fast_match adds passes the test equal at the time it is added. For leaves the test does not change. For internal nodes, all leaf pairs are made before the first internal pair, so the count of common leaves is the final one. So the result is a matching of nodes with the same labels that meets Matching Criteria 1 and 2. The paper shows that, with acyclic labels and Criteria 1 to 3, there is a unique maximal matching of this kind (Theorem 5.2), and states that its matching algorithms give an optimal matching when Criterion 3 holds. This file does not prove that statement.

Complexity

EditScript visits each node a constant number of times, apart from ALIGN-CHILDREN and FIND-POS. The paper computes the LCS of line L12 with Myers' algorithm, in time O((∣S1∣+∣S2∣)d′)O((|S_1| + |S_2|) d') for d′d' misaligned children, and states a total of O(nd)O(n d), where nn is the number of nodes of both trees and dd the number of misaligned nodes: the least number of moves inside one parent over all minimum cost scripts. The code of this page uses the quadratic dynamic program for the LCS and scans the children at each call, so it takes O(n2)O(n^2) time and space in the worst case.

For the matching, let cc be the average cost of compare on two leaves. Algorithm Match takes time O(n2c+mn)O(n^2 c + m n) for nn leaves and mm internal nodes. For FastMatch, the paper bounds the time by (ne+e2)c+2lne(n e + e^2) c + 2 l n e, where ll is the number of internal labels and ee is the weighted edit distance: the cost of a shortest script in which inserts and deletes weigh 1, a move weighs the number of leaves of the moved subtree, and updates weigh 0. This bound assumes that leaf labels and internal labels are different, that all compares cost the same on average, and that a node with a given label has the average number of leaves. In the experiments on versions of three papers, FastMatch made about 20 times fewer comparisons than the bound, and ee was on average 3.4 times the number of operations.

Properties

  • Conforming. The final matching contains every pair of MM; matched nodes are never deleted or inserted.
  • Minimum for the matching. No script that pairs exactly the nodes of MM costs less. The quality of the result depends on the matching.
  • Moves of subtrees. A moved node takes its subtree with it, so a moved paragraph costs one operation, not one per sentence.
  • Leaves only. Inserts and deletes act on leaves. To delete an internal node, its children must first be moved away or deleted, which the post-order of line L8 does.
  • Order of the script. An insert can come before a move into the new node, and the deletes come last, so the script can be applied in its order.
  • Unique matching. With labels that form no cycles and Criteria 1 to 3, where Criterion 3 says that each leaf has at most one leaf on the other side with compare at most 1, there is a unique maximal matching (Theorem 5.2).

Variants and improvements

  • Keys. If the nodes have keys or object identifiers that stay the same between versions, the matching is given, and only EditScript is needed.
  • Post-processing of the matching. When Criterion 3 fails, for example with many equal sentences, FastMatch can pair a leaf with the wrong copy. The paper corrects many such cases from the top down: a child of xx matched outside the partner of xx is matched again to a close child of the partner, if there is one.
  • Delta trees. Section 6 of the paper writes the changes on the new tree, with marks for the inserted, deleted, updated and moved nodes, which is how LaDiff shows them.
  • General tree edit distance. The tree edit distance of the Zhang and Shasha algorithm finds a least cost script without a given matching, but takes at least quadratic time and has no moves; its delete makes the children of the deleted node children of its parent.
  • Line diffs with moves. On flat sequences, Heckel's diff and Tichy's block moves also report moved pieces.

When to use it

Use it to find the changes between two versions of large hierarchical data, such as structured documents, XML or HTML pages, object databases or syntax trees, when moves of whole subtrees should count as one change. It is fastest when the versions are close. If the data has keys, the matching is free; if not, the criteria of FastMatch work when values seldom repeat. When the shortest script over all matchings is needed and the trees are small, use a general tree edit distance instead.

Pitfalls

  • Unmatched roots. If the roots are not a pair, add new roots above both trees, as line L1 does; the root of T1T_1 cannot be deleted while it has children.
  • FIND-POS as printed. Counting only the children marked in order, or not marking the nodes placed by inserts and moves, puts new nodes at the wrong places; see the two cases under the algorithm.
  • The matching decides the result. A bad matching gives a correct but long script. Two internal nodes with the same label are matched by their leaves, so a matching error at the leaves can carry up to the paragraphs and sections.
  • Repeated values. Criterion 3 fails for documents with many equal or nearly equal sentences, and the matching may then not be optimal.
  • The LCS test. The LCS of line L12 and of FastMatch can only test two items for equality. An LCS routine that sorts the items needs more than that; the paper notes that it could not use the LCS of the Unix diff for this reason.
  • Positions are 1-based. MOV(x,y,k)(x, y, k) makes xx the kk-th child after it is removed from its old place, which matters when xx moves inside its own parent.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

chawathe_tree_diff.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chawathe-tree-diff/. The authors are listed in prov/Y3W16W.jsonl.
"""Change detection in ordered labeled trees, after Chawathe, Rajaraman, Garcia-Molina and Widom (SIGMOD 1996).

Trees have node identifiers, labels and values. fast_match finds a matching of the
nodes of two trees (Figure 11 of the paper), and edit_script turns a matching into an
edit script of inserts, deletes, updates and moves (Figures 8 and 9). Positions k
count from 1, as in the paper: MOV(x, y, k) makes x the k-th child of y.

Two details differ from the text of Figure 9. FIND-POS counts all the children of
the parent, not only the ones marked "in order", and the nodes that are inserted or
moved to their final place are marked "in order". Without these, a node can be
placed before an unmatched sibling or before a sibling inserted just before it.
"""

from collections import deque
from collections.abc import Callable, Hashable, Iterable, Sequence
from typing import Any, NamedTuple, Optional

from txdiff import lcs_matching


class Ins(NamedTuple):
    node: int
    label: Hashable
    value: Any
    parent: int
    k: int

    def __str__(self) -> str:
        return f"INS(({self.node},{self.label},{self.value}),{self.parent},{self.k})"


class Del(NamedTuple):
    node: int

    def __str__(self) -> str:
        return f"DEL({self.node})"


class Upd(NamedTuple):
    node: int
    value: Any

    def __str__(self) -> str:
        return f"UPD({self.node},{self.value})"


class Mov(NamedTuple):
    node: int
    parent: int
    k: int

    def __str__(self) -> str:
        return f"MOV({self.node},{self.parent},{self.k})"


class Tree:
    """An ordered tree with node identifiers; each node has a label, a value, a parent and a list of children."""

    def __init__(self) -> None:
        self.root: Optional[int] = None
        self.label: dict[int, Hashable] = {}
        self.value: dict[int, Any] = {}
        self.parent: dict[int, Optional[int]] = {}
        self.children: dict[int, list[int]] = {}

    @classmethod
    def from_nested(cls, spec: tuple, first_id: int = 1) -> "Tree":
        """Build a tree from (label, value, [children]) or (label, value); the ids go in breadth-first order."""
        tree = cls()
        queue = deque([(spec, None)])
        next_id = first_id
        while queue:
            node_spec, parent = queue.popleft()
            label, value = node_spec[0], node_spec[1]
            kids = node_spec[2] if len(node_spec) > 2 else []
            tree._add(next_id, label, value, parent, None)
            for kid in kids:
                queue.append((kid, next_id))
            next_id += 1
        return tree

    def _add(self, x: int, label: Hashable, value: Any, parent: Optional[int], k: Optional[int]) -> None:
        if x in self.label:
            raise ValueError(f"node {x} exists")
        self.label[x], self.value[x], self.parent[x], self.children[x] = label, value, parent, []
        if parent is None:
            if self.root is not None:
                raise ValueError("the tree has a root")
            self.root = x
        else:
            kids = self.children[parent]
            kids.insert(len(kids) if k is None else k - 1, x)

    def copy(self) -> "Tree":
        t = Tree()
        t.root, t.label, t.value, t.parent = self.root, dict(self.label), dict(self.value), dict(self.parent)
        t.children = {x: list(c) for x, c in self.children.items()}
        return t

    def bfs(self) -> list[int]:
        out, queue = [], deque([self.root] if self.root is not None else [])
        while queue:
            x = queue.popleft()
            out.append(x)
            queue.extend(self.children[x])
        return out

    def postorder(self) -> list[int]:
        out: list[int] = []
        stack = [(self.root, False)] if self.root is not None else []
        while stack:
            x, done = stack.pop()
            if done:
                out.append(x)
            else:
                stack.append((x, True))
                stack.extend((c, False) for c in reversed(self.children[x]))
        return out

    def preorder(self) -> list[int]:
        out: list[int] = []
        stack = [self.root] if self.root is not None else []
        while stack:
            x = stack.pop()
            out.append(x)
            stack.extend(reversed(self.children[x]))
        return out

    def leaves_below(self, x: int) -> list[int]:
        out, stack = [], [x]
        while stack:
            y = stack.pop()
            if self.children[y]:
                stack.extend(self.children[y])
            else:
                out.append(y)
        return out

    def nested(self, x: Optional[int] = None) -> tuple:
        """Return the tree without its ids, as (label, value, (children...))."""
        x = self.root if x is None else x
        return (self.label[x], self.value[x], tuple(self.nested(c) for c in self.children[x]))

    # The four edit operations of Section 3.2.
    def insert(self, x: int, label: Hashable, value: Any, y: int, k: int) -> None:
        if not 1 <= k <= len(self.children[y]) + 1:
            raise ValueError(f"bad position {k}")
        self._add(x, label, value, y, k)

    def delete(self, x: int) -> None:
        if self.children[x] or x == self.root:
            raise ValueError(f"node {x} is not a leaf")
        self.children[self.parent[x]].remove(x)
        for d in (self.label, self.value, self.parent, self.children):
            del d[x]

    def update(self, x: int, value: Any) -> None:
        self.value[x] = value

    def move(self, x: int, y: int, k: int) -> None:
        z = y
        while z is not None:
            if z == x:
                raise ValueError(f"node {y} is in the subtree of {x}")
            z = self.parent[z]
        self.children[self.parent[x]].remove(x)
        if not 1 <= k <= len(self.children[y]) + 1:
            raise ValueError(f"bad position {k}")
        self.children[y].insert(k - 1, x)
        self.parent[x] = y

    def apply(self, op: Any) -> None:
        if isinstance(op, Ins):
            self.insert(op.node, op.label, op.value, op.parent, op.k)
        elif isinstance(op, Del):
            self.delete(op.node)
        elif isinstance(op, Upd):
            self.update(op.node, op.value)
        elif isinstance(op, Mov):
            self.move(op.node, op.parent, op.k)
        else:
            raise ValueError(f"unknown operation {op!r}")


def add_root(tree: Tree, x: int, label: Hashable = "(root)") -> Tree:
    """Return a copy of the tree under a new root x, with the old root as its only child."""
    t = tree.copy()
    old = t.root
    t.label[x], t.value[x], t.parent[x], t.children[x] = label, None, None, [old]
    t.parent[old] = x
    t.root = x
    return t


def apply_script(tree: Tree, script: Iterable[Any]) -> Tree:
    """Apply the operations to a copy of the tree and return it; raise ValueError if one does not fit."""
    t = tree.copy()
    for op in script:
        t.apply(op)
    return t


class EditResult(NamedTuple):
    script: list  # the operations, in order
    matching: dict[int, int]  # the total matching of the final T1 with T2, as T1 node -> T2 node
    root1: Optional[int]  # the dummy root added to T1, or None
    root2: Optional[int]  # the dummy root added to T2, or None


def edit_script(t1: Tree, t2: Tree, matching: Iterable[tuple[int, int]]) -> EditResult:
    """Return an edit script that turns t1 into t2 and keeps the pairs (x of t1, y of t2) of the matching."""
    partner: dict[int, int] = {}
    back: dict[int, int] = {}
    for x, y in matching:
        if x not in t1.label or y not in t2.label or x in partner or y in back or t1.label[x] != t2.label[y]:
            raise ValueError(f"({x}, {y}) does not fit a matching of nodes with equal labels")
        partner[x], back[y] = y, x
    fresh = max(list(t1.label) + list(t2.label)) + 1
    t, target, root1, root2 = t1.copy(), t2, None, None
    if partner.get(t.root) != target.root:  # @line L1
        root1, root2, fresh = fresh, fresh + 1, fresh + 2
        t, target = add_root(t, root1), add_root(t2, root2)
        partner[root1], back[root2] = root2, root1
    script: list = []
    # The nodes of T2 marked "in order": their partners already have their final place
    # among the siblings. The paper marks the partners in T1 too, but FIND-POS reads only these.
    in_order: set[int] = set()

    def do(op: Any) -> None:
        script.append(op)
        t.apply(op)

    def find_pos(x: int) -> int:
        kids = target.children[target.parent[x]]
        left = [v for v in kids[:kids.index(x)] if v in in_order]
        if not left:  # @line L14
            return 1
        u = back[left[-1]]  # @line L15
        siblings = [s for s in t.children[t.parent[u]] if s != back.get(x)]
        return siblings.index(u) + 2

    def align_children(w: int, x: int) -> None:
        in_order.difference_update(target.children[x])  # @line L10
        kids1, kids2 = set(t.children[w]), set(target.children[x])
        s1 = [a for a in t.children[w] if partner.get(a) in kids2]  # @line L11
        s2 = [b for b in target.children[x] if back.get(b) in kids1]
        keep = lcs_matching(s1, s2, lambda a, b: partner[a] == b)  # @line L12
        kept = {s1[i] for i, _ in keep}
        in_order.update(s2[j] for _, j in keep)
        for a in s1:  # @line L13
            if a not in kept:
                do(Mov(a, w, find_pos(partner[a])))
                in_order.add(partner[a])

    for x in target.bfs():  # @line L2
        y = target.parent[x]
        if x not in back:  # @line L3
            k = find_pos(x)
            w = fresh
            fresh += 1
            do(Ins(w, target.label[x], target.value[x], back[y], k))
            partner[w], back[x] = x, w
            in_order.add(x)
        else:
            w = back[x]  # @line L4
            if t.value[w] != target.value[x]:  # @line L5
                do(Upd(w, target.value[x]))
            if y is not None and t.parent[w] != back[y]:  # @line L6
                do(Mov(w, back[y], find_pos(x)))
                in_order.add(x)
        align_children(back[x], x)  # @line L7
    for w in t.postorder():  # @line L8
        if w not in partner:
            do(Del(w))
    return EditResult(script, partner, root1, root2)  # @line L9


def word_compare(u: Any, v: Any) -> float:
    """Return a distance in [0, 2] of two values: 0 if equal, 2 if they share no word, by a longest common subsequence."""
    if u == v:
        return 0.0
    a, b = str(u).split(), str(v).split()
    if not a or not b:
        return 2.0
    return 2.0 - 4.0 * len(lcs_matching(a, b)) / (len(a) + len(b))


def fast_match(t1: Tree, t2: Tree, compare: Callable[[Any, Any], float] = word_compare,
               f: float = 0.5, t: float = 0.6) -> list[tuple[int, int]]:
    """Return a matching of the nodes of t1 and t2 by Algorithm FastMatch.

    Leaves x and y may match if they have the same label and compare(v(x), v(y)) <= f
    (Matching Criterion 1). Internal nodes may match if they have the same label and
    more than a fraction t of the leaves below the larger one are matched to leaves
    below the other (Matching Criterion 2).
    """
    if not (0 <= f <= 1 and 0.5 <= t <= 1):
        raise ValueError("need 0 <= f <= 1 and 1/2 <= t <= 1")
    match: dict[int, int] = {}
    back: dict[int, int] = {}
    leaves1 = {x: t1.leaves_below(x) for x in t1.label}
    leaves2 = {y: set(t2.leaves_below(y)) for y in t2.label}

    def equal(x: int, y: int) -> bool:
        if t1.label[x] != t2.label[y]:
            return False
        if not t1.children[x] and not t2.children[y]:
            return compare(t1.value[x], t2.value[y]) <= f
        if not t1.children[x] or not t2.children[y]:
            return False
        common = sum(1 for w in leaves1[x] if match.get(w) in leaves2[y])
        return common / max(len(leaves1[x]), len(leaves2[y])) > t

    def labels(tree: Tree, leaf: bool) -> dict[Hashable, list[int]]:
        chains: dict[Hashable, list[int]] = {}
        for x in tree.preorder():
            if (not tree.children[x]) == leaf:
                chains.setdefault(tree.label[x], []).append(x)
        return chains

    # Leaves first, so that the test of Criterion 2 can count matched leaves. The paper
    # chains the nodes in in-order; for the leaves, preorder gives the same order.
    for leaf in (True, False):
        chains1, chains2 = labels(t1, leaf), labels(t2, leaf)
        for lab, s1 in chains1.items():
            s2 = chains2.get(lab, [])
            for i, j in lcs_matching(s1, s2, equal):
                match[s1[i]], back[s2[j]] = s2[j], s1[i]
            for x in s1:
                if x in match:
                    continue
                y = next((y for y in s2 if y not in back and equal(x, y)), None)
                if y is not None:
                    match[x], back[y] = y, x
    return sorted(match.items())


def isomorphic(t1: Tree, t2: Tree) -> bool:
    """Return True if the trees are equal except for their node ids."""
    return t1.nested() == t2.nested()


def lower_bound(t1: Tree, t2: Tree, matching: Sequence[tuple[int, int]]) -> int:
    """Return the least number of operations of a script that keeps exactly the pairs of the matching.

    The count is: unmatched nodes of t1 (deletes), unmatched nodes of t2 (inserts),
    pairs with different values (updates), pairs whose parents are not a pair (moves to
    another parent), and for each pair of parents, the number of child pairs between
    them minus a longest common subsequence of them (moves among siblings).
    """
    # The parent None stands for the dummy roots, which are always a pair.
    partner = dict(matching)
    pairs = set(matching) | {(None, None)}
    cost = (len(t1.label) - len(partner)) + (len(t2.label) - len(partner))
    for x, y in matching:
        cost += t1.value[x] != t2.value[y]
        cost += (t1.parent[x], t2.parent[y]) not in pairs
    for u, v in pairs:
        kids1 = t1.children[u] if u is not None else [t1.root]
        kids2 = t2.children[v] if v is not None else [t2.root]
        s1 = [a for a in kids1 if partner.get(a) in kids2]
        s2 = [b for b in kids2 if b in {partner[a] for a in s1}]
        cost += len(s1) - len(lcs_matching(s1, s2, lambda a, b: partner[a] == b))
    return cost
txdiff.py 221 lines
# SPDX-License-Identifier: MIT
# Shared helper of the text processing and typesetting pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Common parts of the diff and merge pages: lines, edit scripts, the LCS matcher and a unified diff printer.

An edit script turns a sequence a into a sequence b. It is a list of Op values in
order. Each Op has a kind, an index i into a, an index j into b, and the item:

- Op(KEEP, i, j, a[i]): a[i] is kept, and it is b[j];
- Op(DELETE, i, j, a[i]): a[i] is deleted; j is the number of items of b made so far;
- Op(INSERT, i, j, b[j]): b[j] is inserted; i is the number of items of a used so far.

A matching is a list of pairs (i, j), increasing in both coordinates, of items
that the script keeps. The named algorithms of the pages are not in this file.
"""

from collections.abc import Callable, Sequence
from typing import Any, NamedTuple

KEEP = "="
DELETE = "-"
INSERT = "+"


class Op(NamedTuple):
    kind: str
    i: int
    j: int
    item: Any


def split_lines(text: str) -> list[str]:
    """Split text at each "\\n" into lines without the line feed; a final line feed adds no empty line."""
    if text == "":
        return []
    lines = text.split("\n")
    if lines[-1] == "":
        lines.pop()
    return lines


def is_matching(a: Sequence[Any], b: Sequence[Any], pairs: Sequence[tuple[int, int]],
                eq: Callable[[Any, Any], bool] | None = None) -> bool:
    """Return True if pairs is strictly increasing in both coordinates and each pair is equal by eq."""
    eq = eq if eq is not None else (lambda x, y: x == y)
    pi, pj = -1, -1
    for i, j in pairs:
        if not (pi < i < len(a) and pj < j < len(b)) or not eq(a[i], b[j]):
            return False
        pi, pj = i, j
    return True


def lcs_matching(a: Sequence[Any], b: Sequence[Any],
                 eq: Callable[[Any, Any], bool] | None = None) -> list[tuple[int, int]]:
    """Return a longest matching of a and b by the O(n m) dynamic program.

    eq(x, y) decides whether x and y may be matched; the default is ==. Ties go to
    the earliest pair, so the result is fixed for given inputs.
    """
    eq = eq if eq is not None else (lambda x, y: x == y)
    n, m = len(a), len(b)
    # length[i][j] is the length of a longest matching of a[i:] and b[j:].
    length = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(n - 1, -1, -1):
        row, below = length[i], length[i + 1]
        ai = a[i]
        for j in range(m - 1, -1, -1):
            if eq(ai, b[j]):
                row[j] = below[j + 1] + 1
            else:
                row[j] = below[j] if below[j] >= row[j + 1] else row[j + 1]
    pairs: list[tuple[int, int]] = []
    i = j = 0
    while i < n and j < m:
        if eq(a[i], b[j]):
            pairs.append((i, j))
            i += 1
            j += 1
        elif length[i + 1][j] >= length[i][j + 1]:
            i += 1
        else:
            j += 1
    return pairs


def matching_to_script(a: Sequence[Any], b: Sequence[Any], pairs: Sequence[tuple[int, int]]) -> list[Op]:
    """Return the edit script that keeps the pairs; in each gap the deletes come before the inserts."""
    script: list[Op] = []
    i = j = 0
    for pi, pj in list(pairs) + [(len(a), len(b))]:
        if pi < i or pj < j:
            raise ValueError("the pairs are not increasing")
        while i < pi:
            script.append(Op(DELETE, i, j, a[i]))
            i += 1
        while j < pj:
            script.append(Op(INSERT, i, j, b[j]))
            j += 1
        if pi < len(a) and pj < len(b):
            script.append(Op(KEEP, i, j, a[i]))
            i += 1
            j += 1
    return script


def script_matching(script: Sequence[Op]) -> list[tuple[int, int]]:
    """Return the pairs (i, j) that the script keeps."""
    return [(op.i, op.j) for op in script if op.kind == KEEP]


def apply_script(a: Sequence[Any], script: Sequence[Op]) -> list[Any]:
    """Apply the script to a and return the new sequence; raise ValueError if the script does not fit a."""
    out: list[Any] = []
    i = 0
    for op in script:
        if op.kind == INSERT:
            if op.i != i or op.j != len(out):
                raise ValueError(f"bad insert {op}")
            out.append(op.item)
        elif op.kind in (KEEP, DELETE):
            if op.i != i or i >= len(a) or op.item != a[i] or op.j != len(out):
                raise ValueError(f"bad {op.kind} {op}")
            if op.kind == KEEP:
                out.append(a[i])
            i += 1
        else:
            raise ValueError(f"unknown kind {op.kind!r}")
    if i != len(a):
        raise ValueError("the script does not use all of a")
    return out


def is_valid_script(a: Sequence[Any], b: Sequence[Any], script: Sequence[Op]) -> bool:
    """Return True if the script fits a and turns a into b."""
    try:
        return apply_script(a, script) == list(b)
    except ValueError:
        return False


def script_cost(script: Sequence[Op]) -> int:
    """Return the number of deletes and inserts of the script."""
    return sum(1 for op in script if op.kind != KEEP)


def _opcodes(script: Sequence[Op]) -> list[tuple[str, int, int, int, int]]:
    """Group the script into runs in the format of difflib: equal, delete, insert or replace."""
    codes: list[tuple[str, int, int, int, int]] = []
    i = j = 0
    k = 0
    while k < len(script):
        i1, j1 = i, j
        if script[k].kind == KEEP:
            while k < len(script) and script[k].kind == KEEP:
                i, j, k = i + 1, j + 1, k + 1
            codes.append(("equal", i1, i, j1, j))
        else:
            while k < len(script) and script[k].kind != KEEP:
                if script[k].kind == DELETE:
                    i += 1
                else:
                    j += 1
                k += 1
            tag = "replace" if i > i1 and j > j1 else ("delete" if i > i1 else "insert")
            codes.append((tag, i1, i, j1, j))
    return codes


def _range(start: int, stop: int) -> str:
    length = stop - start
    first = start + 1
    if length == 1:
        return f"{first}"
    if length == 0:
        first -= 1
    return f"{first},{length}"


def unified_diff(a: Sequence[str], b: Sequence[str], script: Sequence[Op], context: int = 3,
                 from_name: str = "a", to_name: str = "b") -> list[str]:
    """Return the lines of a unified diff of the script, without line feeds, in the layout of GNU diff -u.

    The hunks are grouped as difflib.unified_diff groups them, so for the same
    matching the output is the same. If the script changes nothing, the result is [].
    """
    codes = _opcodes(script)
    if not codes:
        codes = [("equal", 0, 1, 0, 1)]
    n = context
    if codes[0][0] == "equal":
        tag, i1, i2, j1, j2 = codes[0]
        codes[0] = (tag, max(i1, i2 - n), i2, max(j1, j2 - n), j2)
    if codes[-1][0] == "equal":
        tag, i1, i2, j1, j2 = codes[-1]
        codes[-1] = (tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n))
    groups: list[list[tuple[str, int, int, int, int]]] = []
    group: list[tuple[str, int, int, int, int]] = []
    for tag, i1, i2, j1, j2 in codes:
        if tag == "equal" and i2 - i1 > 2 * n:
            group.append((tag, i1, min(i2, i1 + n), j1, min(j2, j1 + n)))
            groups.append(group)
            group = []
            i1, j1 = max(i1, i2 - n), max(j1, j2 - n)
        group.append((tag, i1, i2, j1, j2))
    if group and not (len(group) == 1 and group[0][0] == "equal"):
        groups.append(group)
    out: list[str] = []
    for group in groups:
        if not out:
            out += [f"--- {from_name}", f"+++ {to_name}"]
        first, last = group[0], group[-1]
        out.append(f"@@ -{_range(first[1], last[2])} +{_range(first[3], last[4])} @@")
        for tag, i1, i2, j1, j2 in group:
            if tag == "equal":
                out += [" " + line for line in a[i1:i2]]
                continue
            if tag in ("replace", "delete"):
                out += ["-" + line for line in a[i1:i2]]
            if tag in ("replace", "insert"):
                out += ["+" + line for line in b[j1:j2]]
    return out
test_chawathe_tree_diff.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/chawathe-tree-diff/. The authors are listed in prov/Y3W16W.jsonl.

import random

from chawathe_tree_diff import (Del, Ins, Mov, Tree, Upd, add_root, apply_script, edit_script, fast_match,
                                isomorphic, lower_bound, word_compare)


def S(value: str) -> tuple:
    return ("S", value)


# Figure 1 of the paper: documents (D) of paragraphs (P) of sentences (S).
T1 = Tree.from_nested(("D", None, [("P", None, [S("a"), S("b"), S("c")]), ("P", None, [S("d"), S("e")]),
                                   ("P", None, [S("f")])]))
T2 = Tree.from_nested(("D", None, [("P", None, [S("a"), S("c")]), ("P", None, [S("f")]),
                                   ("P", None, [S("d"), S("e"), S("g")])]), first_id=11)


def test_running_example() -> None:
    m = fast_match(T1, T2)
    # The matching of Example 5.1, which Algorithm Match finds there.
    assert m == sorted([(5, 15), (7, 16), (8, 18), (9, 19), (10, 17), (2, 12), (3, 14), (4, 13), (1, 11)])
    result = edit_script(T1, T2, m)
    # The paper moves node 4 where this LCS moves node 3; both scripts have three operations.
    assert result.script == [Mov(3, 1, 3), Ins(21, "S", "g", 3, 3), Del(6)]
    assert [str(op) for op in result.script] == ["MOV(3,1,3)", "INS((21,S,g),3,3)", "DEL(6)"]
    assert isomorphic(apply_script(T1, result.script), T2)
    assert isomorphic(apply_script(T1, [Mov(4, 1, 2), Ins(21, "S", "g", 3, 3), Del(6)]), T2)
    assert lower_bound(T1, T2, m) == 3 and result.root1 is None
    assert result.matching[21] == 20 and all(result.matching[x] == y for x, y in m)


def test_align_children_of_figure_7() -> None:
    t1 = Tree.from_nested(("A", None, [("B", i) for i in range(5)]))
    t2 = Tree.from_nested(("A", None, [("B", i) for i in (1, 3, 4, 0, 2)]), first_id=11)
    m = [(1, 11), (3, 12), (5, 13), (6, 14), (2, 15), (4, 16)]
    result = edit_script(t1, t2, m)
    assert result.script == [Mov(2, 1, 5), Mov(4, 1, 5)]
    assert isomorphic(apply_script(t1, result.script), t2)


def test_find_pos_counts_all_children() -> None:
    # The unmatched child d is still there when b is inserted; counting only the
    # children marked in order would put b at position 2, before a.
    t1 = Tree.from_nested(("r", None, [("x", "d"), ("x", "a")]))
    t2 = Tree.from_nested(("r", None, [("x", "a"), ("x", "b")]), first_id=11)
    result = edit_script(t1, t2, [(1, 11), (3, 12)])
    assert result.script == [Ins(14, "x", "b", 1, 3), Del(2)]
    assert isomorphic(apply_script(t1, result.script), t2)
    assert not isomorphic(apply_script(t1, [Ins(14, "x", "b", 1, 2), Del(2)]), t2)
    # Two new nodes in a row: the first one must count as placed when the second is placed.
    t3 = Tree.from_nested(("r", None, [("x", "a"), ("x", "b"), ("x", "c")]), first_id=11)
    result = edit_script(t1, t3, [(1, 11), (3, 12)])
    assert result.script == [Ins(15, "x", "b", 1, 3), Ins(16, "x", "c", 1, 4), Del(2)]
    assert isomorphic(apply_script(t1, result.script), t3)


def test_dummy_roots_and_updates() -> None:
    t1 = Tree.from_nested(("r", None, [("x", "u")]))
    t2 = Tree.from_nested(("s", None, [("x", "v")]), first_id=11)
    result = edit_script(t1, t2, [(2, 12)])
    assert (result.root1, result.root2) == (13, 14)
    assert result.script == [Ins(15, "s", None, 13, 1), Upd(2, "v"), Mov(2, 15, 1), Del(1)]
    assert isomorphic(apply_script(add_root(t1, 13), result.script), add_root(t2, 14))
    assert len(result.script) == lower_bound(t1, t2, [(2, 12)])
    # The script respects the matching: without the pair (2, 12), x is deleted and inserted.
    t3 = Tree.from_nested(("r", None, [("x", "v")]), first_id=11)
    assert edit_script(t1, t3, [(1, 11), (2, 12)]).script == [Upd(2, "v")]
    assert edit_script(t1, t3, [(1, 11)]).script == [Ins(13, "x", "v", 1, 1), Del(2)]
    for bad in ([(1, 12)], [(1, 11), (2, 11)], [(9, 11)]):
        try:
            edit_script(t1, t3, bad)
        except ValueError:
            continue
        raise AssertionError(f"{bad} was accepted")


def _random_spec(rng: random.Random, depth: int) -> tuple:
    if depth == 0 or rng.random() < 0.3:
        return (rng.choice("xy"), rng.choice("pqr"))
    return (rng.choice("AB"), None, [_random_spec(rng, depth - 1) for _ in range(rng.randint(1, 4))])


def _random_matching(rng: random.Random, t1: Tree, t2: Tree) -> list[tuple[int, int]]:
    nodes2 = list(t2.label)
    rng.shuffle(nodes2)
    used: set[int] = set()
    pairs = []
    for x in t1.label:
        if rng.random() < 0.75:
            for y in nodes2:
                if y not in used and t2.label[y] == t1.label[x]:
                    pairs.append((x, y))
                    used.add(y)
                    break
    return pairs


def test_random_scripts_are_correct_and_minimal() -> None:
    rng = random.Random(16)
    for trial in range(400):
        t1 = Tree.from_nested(_random_spec(rng, 3))
        t2 = Tree.from_nested(_random_spec(rng, 3), first_id=1 if trial % 2 else 100)
        m = _random_matching(rng, t1, t2)
        result = edit_script(t1, t2, m)
        start, goal = t1, t2
        if result.root1 is not None:
            start, goal = add_root(t1, result.root1), add_root(t2, result.root2)
        final = apply_script(start, result.script)
        assert isomorphic(final, goal)
        # The total matching extends the given one and maps the final tree onto T2.
        total = result.matching
        assert all(total[x] == y for x, y in m)
        assert sorted(total) == sorted(final.label) and sorted(total.values()) == sorted(goal.label)
        for w, x in total.items():
            assert final.label[w] == goal.label[x] and final.value[w] == goal.value[x]
            if w != final.root:
                assert total[final.parent[w]] == goal.parent[x]
        assert len(result.script) == lower_bound(t1, t2, m)


def test_fast_match() -> None:
    assert word_compare("the cat sat", "the cat sat") == 0
    assert word_compare("the cat sat", "a dog ran") == 2
    assert word_compare("the cat sat", "the cat ran") == 2 - 4 * 2 / 6
    rng = random.Random(5)
    words = "alpha beta gamma delta epsilon zeta eta theta".split()
    for _ in range(100):
        # Distinct sentences meet Matching Criterion 3, so a copy with moved subtrees matches in full.
        values = iter(rng.sample([f"{a} {b}" for a in words for b in words], 40))

        def spec(depth: int) -> tuple:
            if depth == 0 or rng.random() < 0.3:
                return ("S", next(values))
            return ("P", None, [spec(depth - 1) for _ in range(rng.randint(1, 3))])

        t1 = Tree.from_nested(("D", None, [spec(2) for _ in range(rng.randint(1, 3))]))
        nested = t1.nested()
        kids = list(nested[2])
        rng.shuffle(kids)

        def to_spec(n: tuple) -> tuple:
            return (n[0], n[1], [to_spec(c) for c in n[2]]) if n[0] != "S" else (n[0], n[1])

        t2 = Tree.from_nested(to_spec((nested[0], nested[1], tuple(kids))), first_id=100)
        m = fast_match(t1, t2)
        assert len(m) == len(t1.label)
        result = edit_script(t1, t2, m)
        assert not any(isinstance(op, (Ins, Del, Upd)) for op in result.script)
        assert isomorphic(apply_script(t1, result.script), t2)
    try:
        fast_match(T1, T2, t=0.4)
    except ValueError:
        return
    raise AssertionError("t below 1/2 was accepted")

History

Chawathe, Rajaraman, Garcia-Molina and Widom worked at Stanford on change management for data warehouses, active databases and version management, where the old and new data often come as snapshots without keys. Earlier work on changes had dealt with flat files and relations, and the tree edit distance of Zhang and Shasha from 1989 was exact but at least quadratic. They set up the problem as a matching and a minimum conforming edit script, gave EditScript, Match and FastMatch, and built LaDiff, which marks the changes between two LaTeX documents with sentences, paragraphs, sections, lists and items. The work appeared at SIGMOD 1996, and as a Stanford report with the proofs and the analysis in appendices.

References

  1. Sudarshan S. Chawathe, Anand Rajaraman, Hector Garcia-Molina and Jennifer Widom, Change detection in hierarchically structured information, SIGMOD 1996, 493-504, the conference version of the report below; the section, figure and example numbers on this page are those of the report
  2. Sudarshan S. Chawathe, Anand Rajaraman, Hector Garcia-Molina and Jennifer Widom, Change detection in hierarchically structured information, Stanford InfoLab report 1995-46, with appendices, Section 3.2, the edit operations, Example 3.1 and the cost model; Section 4, the running example of Figure 1, the align phase with the LCS and Figure 7, Algorithm EditScript in Figure 8, AlignChildren and FindPos in Figure 9, and the O(ND) bound; Section 5, Matching Criteria 1 to 3, Theorem 5.2, Algorithm Match in Figure 10, Example 5.1 and Algorithm FastMatch in Figure 11; Section 7, LaDiff; Section 8 and Table 1, the experiments and the post-processing; Appendix B, the running times of Match and FastMatch; Appendix C, Lemma C.1 and Theorem C.2

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example