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
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
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 , where is the number of nodes and 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 (old) and (new), whose nodes have identifiers, labels and values, and a matching : a set of pairs of a node of and a node of with the same label, each node in at most one pair. The four operations are INS, which inserts a new leaf with label and value as the -th child of ; DEL, which deletes a leaf; UPD, which sets the value of ; and MOV, which makes the -th child of , with its subtree. Inserts, deletes and moves cost 1, and an update costs compare, a number in . The output is a script of least cost that transforms into a tree that differs from only in identifiers, and whose final matching contains . The paper calls this the minimum conforming edit script (MCES) problem.
The algorithm
EditScript goes through in breadth-first order and changes as it writes each operation. When it reaches a node , its parent is already in place in , so it can put the partner of under the partner of . Each node of is marked "in order" once the position of its partner among its siblings is final.
EDIT-SCRIPT(T1, T2, M)- 1
if 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 - 2
for each node x of T2 in breadth-first order, with y = p(x): - 3
if 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 - 4
else w ← partner(x) - 5
if v(w) ≠ v(x) then UPD(w, v(x)) - 6
if x is not the root and (p(w), y) ∉ M then MOV(w, partner(y), FIND-POS(x)); mark x in order - 7
ALIGN-CHILDREN(partner(x), x) - 8
for each node w of T1 in post-order: if w has no partner then DEL(w) - 9
return the script and M ALIGN-CHILDREN(w, x)- 10
mark all children of x out of order - 11
S1 ← the children of w whose partners are children of x; S2 ← the children of x whose partners are children of w - 12
S ← LCS(S1, S2), where a equals b if (a, b) ∈ M; mark the nodes of S2 in S in order - 13
for each a in S1 that is not in S, with partner b: MOV(a, w, FIND-POS(b)); mark b in order FIND-POS(x)- 14
if no sibling of x to its left in T2 is marked in order then return 1 - 15
u ← 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 is with unmatched and is , counting only marked children puts the new at place 2, before , and if is with and new, an unmarked makes go directly after .
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 , with (Criterion 1). Two internal nodes may match if they have the same label and more than a fraction of the leaves below the larger one are matched to leaves below the other, with (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, , , , and ; 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 it adds , and . Last, it matches the documents, . 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 compares with , whose partners in are . A longest common subsequence has length 2, so one paragraph must move. The code takes the subsequence and writes MOV; the paper takes and writes MOV, 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. The delete phase writes DEL. The script has three operations, the least possible: sentence 6 must go, sentence 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 , 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 .
For the cost, every script that pairs exactly the nodes of must delete each unmatched node of , insert one for each unmatched node of , 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 , and it may also update an unmatched leaf into an unmatched leaf of , 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. and are ordered trees whose nodes have a label and a value , and is a matching of some nodes of with nodes of of the same label. We write for the parent of and partner for the other node of a pair. Line L1 makes the two roots a pair, so from now on we take and to be the trees with the new roots, and we count the new roots as a pair of . The algorithm applies each operation to when it writes it, and denotes this changing tree. The operations are those of Section 3.2 of the paper: INS adds a leaf as the -th child of a node, DEL removes a leaf, UPD changes a value, and MOV makes , with its subtree, the -th child of . INS, DEL and MOV of a node do not change the relative order of the other children of any node.
A node of 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 changes its parent only through a MOV of that node. When is processed, the only nodes that move are the partner of (line L6) and children of the partner of whose partners are children of (line L13). So once a node 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 of , and line L13 moves children of whose partners are children of , which come later in breadth-first order than and are not processed yet. A node processed earlier is neither of these, and the only update to its partner is at line L5 while is processed.
Invariant. For each node of whose children have been aligned at line L7, the partners of the children of that are marked "in order" are children of the partner of , and they stand there in the same order as their partners stand in .
Lemma 2 (FIND-POS). Let be a node of that meets the invariant, its partner and a child of that is not marked. If the algorithm puts a node , the new partner or the partner of , as the -th child of with $k = $ FIND-POS and then marks , the invariant still holds for .
Proof. If no sibling of to its left is marked, and becomes the first child of ; every marked sibling of is to its right in , and its partner is to the right of . Otherwise let be the rightmost marked sibling to the left of and its partner, which is a child of by the invariant. Line L15 counts the children of without and returns one more than the place of , so after the operation stands directly after . The marked siblings to the left of are and siblings to the left of , whose partners stand before or at . The marked siblings to the right of are to the right of , so their partners stand after , and so after . The order of the other marked partners does not change, as the operations do not change the relative order of other children.
Lemma 3 (ALIGN-CHILDREN). After ALIGN-CHILDREN, every child of whose partner is a child of is marked, and the invariant holds for .
Proof. Line L10 removes the marks of the children of , so no child of is marked. Line L12 marks the nodes of in the common subsequence; their partners are in in the same order as in , and and are in the orders of and of . So the invariant holds. Line L13 moves each other node of and marks its partner, and the invariant still holds by Lemma 2. At the end each node of is marked.
Lemma 4 (the loop). When the loop ends, every node of has a partner in with and ; if is not the root, is the partner of ; and the partners of the children of each node are children of the partner of , in the order of . Every operation of the loop can be applied.
Proof. Take when it is processed, with processed before. If has no partner, line L3 inserts a leaf with the label and the value of under the partner of , which exists. Else the partner has the label of by the definition of a matching, and line L5 gives it the value of . If is not the partner of , line L6 moves there. This move is legal: the ancestors of the partner of are the partners of the ancestors of , by the claim for the nodes processed before, and is not an ancestor of , so the partner of is not in the subtree of . The moves of line L13 stay inside one parent and are legal. Each position 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 are processed after ALIGN-CHILDREN at line L7. By Lemma 3, after it, the children of whose partners are children of are marked. Every other child of 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 is marked, and the invariant gives the claim on the order.
Lemma 5 (the delete phase). Line L8 deletes exactly the nodes of that have no partner, each one while it is a leaf.
Proof. Let be a node of without a partner. Such a node is a node of that does not match, since all inserted nodes get a partner. A child of cannot have a partner: by Lemma 4, the parent of a node with a partner is the partner of , which is not . So all descendants of have no partner either. The post-order visits them before and deletes them, so is a leaf when it is deleted. Nodes with partners are never deleted.
Theorem 1 (a conforming edit script). The script of EditScript transforms into a tree isomorphic to , and the final matching contains , so conforms to .
Proof. After line L8, by Lemma 5, the nodes of are the nodes with partners. By Lemma 4 the partner map is one to one and onto , 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 that is a child of the partner of has a partner with , so the partner of has no other children. So the partner map is an isomorphism. The pairs of are never changed, and the final matching is plus one pair for each inserted node.
Respecting the matching. We call a script that transforms into a tree isomorphic to respectful of if its final matching, restricted to the nodes of , is exactly . So it deletes each node of that does not match, and it pairs each node of that does not match with an inserted node. The script of EditScript is respectful. The paper calls a script conforming if its final matching contains ; such a script may also pair an unmatched node of with an unmatched node of . For and with leaves of the same label and , the script UPD conforms to and costs compare, while EditScript writes an insert and a delete, of cost 2. So minimality holds for respectful scripts, or for conforming scripts when is maximal in the sense of the paper, in which case no such pair is left.
Lemma 6 (the number of operations). Let be the children of in whose partners are children of in , in the order of , and their partners, in the order of . The script has
where and are the numbers of nodes of and that does not match, is the number of pairs of with , and is the number of pairs of , other than the roots, with .
Proof. Line L3 inserts one node for each node of without a partner, and line L8 deletes one node for each node of without a partner, by Lemma 5. Line L5 updates a pair of when the values differ, and never an inserted node, which has the value of its partner. By Lemma 1, when is processed, its partner has not moved yet, so is still its parent in , and line L6 moves it exactly when ; if has an inserted partner, is not in either. At ALIGN-CHILDREN with , the children of whose partners are children of are those of , in the order of : by Lemma 1, none of them has moved, and the nodes that come into later are partners of children of processed after this call. So the sequences of line L11 are and , and line L13 moves nodes. For an inserted , is empty. These are all the operations.
Theorem 2 (minimum cost). With unit costs for INS, DEL and MOV and a cost compare for each update, where compare meets the triangle inequality, no script that respects costs less than .
Proof. Take a respectful script . It contains a delete of each of the unmatched nodes of and an insert for each of the unmatched nodes of . For each pair of with , it updates ; the updates of go from to , so by the triangle inequality they cost at least compare, which is what pays. For each pair with , the final parent of is the final partner of , which is not : either has a partner in other than , or its final partner is an inserted node. Only a MOV of changes its parent, so moves . For each pair of , the nodes of are children of at the start and at the end. Those that 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 . So they form a common subsequence of and , and moves at least of them. These moved nodes differ from those of the pairs counted in , since their parents are a pair, and they differ between pairs . Adding up, costs at least the cost of given by Lemma 6. This is Lemma C.1 and Theorem C.2 of the paper.
Running time of the code. The breadth-first and post-order traversals take for trees with nodes in total. FIND-POS scans the children of one node, so it costs for each insert or move. ALIGN-CHILDREN with the dynamic program of the longest common subsequence costs , and the sizes of all the add up to at most . So the total is time and space in the worst case. The paper computes the common subsequence with Myers' algorithm, which takes , and states in total, with 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 for misaligned children, and states a total of , where is the number of nodes of both trees and 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 time and space in the worst case.
For the matching, let be the average cost of compare on two leaves. Algorithm Match takes time for leaves and internal nodes. For FastMatch, the paper bounds the time by , where is the number of internal labels and 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 was on average 3.4 times the number of operations.
Properties
- Conforming. The final matching contains every pair of ; matched nodes are never deleted or inserted.
- Minimum for the matching. No script that pairs exactly the nodes of 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 matched outside the partner of 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 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 makes the -th child after it is removed from its old place, which matters when 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.
# 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Y3W16W Edit this page History Report an error Markdown