Algorithmadvanced
Histogram diff
Also called histogram diff algorithm.
Count the old lines of a range, keep the run of equal lines whose rarest line has the lowest count, and diff the parts before and after it again. From JGit; also in Git.
- Time
- O(c n^3) expected
- Space
- O(n) extra
- Where
- c = the bound on the count of a line that may start a run (64 in JGit); n = the total number of lines in both files
- Model
- Word RAM
- Properties
- adaptivedeterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
Histogram diff compares two files line by line. In a range of the files it counts how often each old line occurs, finds runs of equal lines in both files, and keeps the run whose rarest line has the lowest count, then the longest such run. It then diffs the parts before and after that run in the same way. It extends patience diff: patience diff can anchor only on a line that occurs once on both sides, while histogram diff can also anchor on a line with two or three copies. The method comes from JGit, the Java version of Git, and Git has it as the option --histogram. Like patience diff it does not always give a shortest edit script, as Myers' algorithm does, and like Heckel's algorithm it trusts rare lines more than common ones.
In plain words
Lines that are rare are good anchors. A function name usually occurs once. A closing brace occurs many times and says little about where you are.
So, for the part of the files that you work on, count how often each line occurs in the old version. Then go through the new version. For each line that also occurs in the old version, line up the copies and stretch the match up and down as long as the lines stay equal. Give the stretch the count of its rarest line.
Keep the stretch with the lowest count, and among those the longest one. Then do the same in the part above it and the part below it. If a part has common lines but all of them are very frequent, use an ordinary diff for that part.
The problem
The input is an old file and a new file , as sequences of lines with an equality test and a hash of a line. The output is a matching, a set of pairs with that increase in both files, and the edit script that keeps the matched lines. As for patience diff, the goal is a diff that a person can read, and the length of the matching is not the goal: a longest common subsequence can tie unrelated parts of the files together through braces and blank lines.
The algorithm
The pseudocode uses half-open ranges and . A run is a block of equal lines. For a line , is the number of its copies in the old side of the range, and the count of a run is the least of its lines. The bound is the parameter that JGit calls maxChainLength, 64 by default.
HISTOGRAM(A, B)- 1
match the equal first lines and the equal last lines of A and B - 2
MATCH on the range between them MATCH(alo, ahi, blo, bhi)- 3
if one side is empty then return; R ← REGION(alo, ahi, blo, bhi) - 4
if R = none then append the matching of FALLBACK(alo, ahi, blo, bhi), and return - 5
if R is empty then return ▷ no common line: the range is one replace - 6
MATCH on the part before R; append the pairs of R; MATCH on the part after R - 7
return the script that keeps the matched pairs REGION(alo, ahi, blo, bhi)- 8
count cnt(x) for each line x of A[alo .. ahi - 1], and list its copies in order - 9
best ← the empty run; cnt ← c + 1; common ← false - 10
for j ← blo while j < bhi, moving to next afterwards: - 11
next ← j + 1; if B[j] occurs in the old side then common ← true if B[j] occurs in the old side and cnt(B[j]) ≤ cnt then for each copy A[i] = B[j], skipping copies up to the end of the last run tried:- 12
grow the run (i, i + 1, j, j + 1) backward and forward while the lines stay equal and inside the range; rc ← its count - 13
next ← max(next, be) - 14
if the run is longer than best or rc < cnt then best ← the run; cnt ← rc - 15
if common and cnt > c then return none else return best
Line L1 runs once, for the whole files. JGit trims the common start and end before it starts, and the recursion does not trim again. Line L4 is the histogram that gives the method its name. Line L7 skips lines that are more frequent than the best run found so far, so as the scan goes on, only rarer lines are tried. Line L9 moves the scan of past the run just grown, so the lines inside a run are not tried again as starting points. Line L10 replaces the best run when the new run is longer or its rarest line is rarer; since only lines with cnt are tried, cnt never grows. Line L11 returns none, the signal for the fallback, when there are common lines but every one of them occurs more than times in the old side. JGit uses Myers' algorithm as the fallback; the implementation of this page uses the dynamic program for a longest common subsequence.
Example
Take the old file and the new file , numbered from 1.
| step | what happens |
|---|---|
| L1 | and differ, and and differ, so nothing is trimmed |
| L4 | , , |
| , | is . The run cannot grow: is the first line and the last. Run , count 1. It is the best run, and cnt |
| , a brace | , so the braces are not tried |
| , | is . The run grows backward over two braces: , with count . It is longer, so it becomes the best run |
| , | is not in |
The part before the run is empty and , and the part after it is and , which have no common line. So the result keeps the three lines , inserts at the top, and replaces with : 5 operations, which is the minimum here. The braces had the highest count but were matched anyway, because they belong to the run of .
The method is not always minimal. For and , line L1 matches . The scan first grows the run with count 3, then the run with count 1, which wins because it is rarer. The parts beside are empty on one side, so the script has 6 operations, while gives 2. And it can lose even when every line is unique, where patience diff is exact: for and , every run has count 1, so the longest run wins, and the result has 2 pairs instead of the 3 of .
Correctness
The proof file shows that each quadruple that REGION stores is a run inside the range, that REGION returns the empty run exactly when the two sides have no common line, and that it returns none exactly when the sides have common lines and each of them occurs more than times in the old side. The last part uses that cnt never grows: a run is tried only from a line with cnt, and its count is at most that. From these facts, by induction on the size of the range, each call of MATCH appends a matching of its range in increasing order, the recursion stops because the parts beside a run are smaller, and the script turns into . The examples above show that the matching is not always a longest one.
Proof: Histogram diff returns a matching of equal lines, and uses the fallback only where every common line is too frequentfull
We use the pseudocode of the page, with half-open ranges and . For a line , is the number of its copies in the old side of the current range. A run is a quadruple with and for ; its count is the least of its lines. The bound on counts is , the parameter max_chain.
Lemma 1 (the region step). Let REGION run on a range.
- If it returns a quadruple, that quadruple is a run inside the range.
- It returns an empty run if and only if no line occurs in both sides of the range.
- It returns no run, the answer None of line L11, if and only if some line occurs in both sides and every such line has .
Proof. Part 1. The start value is the empty run at . Line L8 starts from a pair inside the range, and the two loops grow it one equal pair at a time, backward while and , forward while and . So every quadruple stored at line L10 is a run inside the range.
Part 3. The value cnt starts at , and line L10 only replaces it with the count of a run tried at line L8. Such a run was tried only if cnt, and , so cnt never grows. Suppose a common line has . Look at a copy . If the scan visits and cnt is already at most , we are done. Otherwise line L7 tries the copies of , and after line L10 either the run was stored and cnt , or it was not stored, which needs cnt, so cnt . If the scan skips , then lies inside the part of a run grown at an earlier position, so that run contains and has , and the same two cases apply. In all cases cnt ends at most and line L11 does not return None. Conversely, if every common line has , every run has count above , cnt stays above , and line L11 returns None, since some line is common.
Part 2. If no line is common, line L7 never runs, the empty start value stays, and has_common stays false, so the empty run is returned. If some line is common, has_common becomes true at the first position of that holds a common line, since the scan visits that position: it lies before every run that the scan grows. Then either line L11 returns None, or cnt ends at most . In the second case cnt changed, which happens only when line L10 stores a run tried at line L8, and such a run has length at least 1. A later run replaces it only with another run of length at least 1. So the returned run is not empty.
Theorem 1 (a valid diff). The method terminates, the result is a matching of and , and the script of line L15 turns into .
Proof. Line L1 matches the equal first lines for head and the equal last lines, and leaves the range between them for MATCH. We show by induction on the size of the range that a call MATCH appends a matching of its range, in increasing order. If one side is empty, line L3 appends nothing. If REGION returns None, the fallback appends nothing, or a longest matching of the range from the helper, in order. If REGION returns the empty run, line L13 appends nothing. Otherwise, by Lemma 1, the run is a block of equal pairs inside the range, of length at least 1. Line L14 calls MATCH on the part before the run, which lies before it in both files, then appends the pairs of the run, then calls MATCH on the part after it. Both parts are strictly smaller than the range, since they leave out the run, so by induction they append matchings in order, and the three pieces follow each other in both files. With the pairs of line L1 before and after, is a matching of and . The helper matching_to_script keeps the pairs of and deletes and inserts the other lines in order, so the script turns into .
What the run choice gives. By Lemma 1, part 3, the fallback runs only in a range whose common lines all occur more than times in the old side. In every other range with a common line, the method makes progress with a run of its own. This is the property that separates histogram diff from patience diff, which needs a line that is unique on both sides.
The result is not always minimal. For and , line L1 matches . In the range that is left, and . The scan of first grows the run of count 3, then at position 4, in the numbering from 1, it grows the run of count 1, which replaces it since . The parts before and after are each empty on one side, so the result has 2 pairs and the script has 6 operations, while the common subsequence gives 2. Even when every line is unique, taking a longest run first can lose: for and the run is kept, the rest of lies before it and the rest of after it, and the result has 2 pairs, while has 3.
Cost. One call of REGION on a range of lines counts the old side in expected time. Each position of that the scan visits tries at most copies, since only lines with cnt are tried, and each try grows a run in steps; so the call costs . Ranges at the same depth of the recursion are disjoint, and each call removes at least one pair, so the depth is at most and the total is expected. The fallback runs on disjoint ranges, so the helper costs in total.
Complexity
Count in the word-RAM, with the total number of lines of both files, the bound on counts, and a hash table with expected time per operation.
- One range. Line L4 costs expected for a range of lines. Each position of that line L6 visits tries at most copies, and each try grows a run in at most steps, so one call of REGION costs in the worst case.
- The recursion. Each call removes at least one matched pair, ranges at the same depth are disjoint, and the depth is at most , which gives the bound expected. This bound is loose: line L9 skips the lines of each run that it grows, and in real files the runs are short and the counts small. The JGit source states that the method typically runs faster than its Myers diff.
- Common start and end. Line L1 is linear, so a small change in a large file is cheap.
- The fallback. The fallback runs on disjoint ranges; with the dynamic program of this page it costs in total, and with Myers' method it costs for the size of the edit script in those ranges.
- Space. The histogram, the lists of copies and the matching need , and the recursion is at most deep.
Properties
- Not minimal. The examples above give scripts longer than a shortest one, also for files whose lines are all unique.
- Rare lines first. The anchor of a range is a run whose rarest line has the lowest count, so names and statements win over braces and blank lines.
- Counts on one side. Only the old side is counted. A line that occurs once in and many times in still has count 1.
- Like patience diff on unique lines. When a range has a line that occurs once in it, the best run has count 1, as in patience diff. The two methods then still differ in which unique lines they keep: patience diff keeps a longest increasing set of them, histogram diff keeps one run and recurses.
- Adaptive. Equal start and end lines are matched in one pass, and a range with no common line is one replace, without further work.
Variants and improvements
- The bound . A larger lets more frequent lines start runs, and sends fewer ranges to the fallback, at a higher cost per range. JGit also stops with the fallback when a bucket of its hash table gets longer than , so that a bad hash does not make the scan slow.
- The fallback. JGit lets the caller set the fallback algorithm; without one, a range that needs it is reported as one replace.
- Patience diff. Patience diff keeps all the unique lines that do not cross, by a longest increasing subsequence, instead of one run.
- Heckel's passes. Heckel's algorithm grows matches of unique lines to their neighbors in the same way as line L8, but does not recurse and reports crossing matches as moves.
When to use it
Use it for diffs of source code that people read and that tools use to find the lines a commit changed. In Git it is the option --histogram, or the setting diff.algorithm = histogram. Nugroho, Hata and Matsumoto compared it with the default Myers diff of Git on 14 Java projects: the two options gave different numbers of changed lines in 1.7 to 8.2 percent of the commits, and in a manual study the histogram diffs described the code changes better more often, so they recommend it for code. Do not use it when a shortest script is needed, for example to compute an edit distance.
Pitfalls
- Counting both sides. The counts are of the old side of the current range only, and they must be counted again in each range of the recursion.
- The order of the scan. The result depends on the order of the scan of and on the rule of line L10: a run replaces the best one only if it is strictly longer or strictly rarer, so among equal runs the first one found wins.
- Frequent lines. A file made of lines that all occur more than times goes entirely to the fallback, and the method is then as slow as the fallback.
- Trimming in the recursion. JGit trims the common start and end only once, at the start. A version that trims again in each range is a different method, and its results can differ from those of JGit.
- Recursion depth. The depth can grow with the number of lines; an implementation in a language with a small call stack should use an explicit stack.
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/histogram-diff/. The authors are listed in prov/BNZ7EN.jsonl.
"""Histogram diff, after the rules of the HistogramDiff class of JGit.
The old file is a and the new file is b. The common start and end of the two
files are matched first, once. In each remaining range the method counts how
often each line occurs in the old side, scans the new side, and grows each
match of a line to the longest run of equal lines around it. It keeps the run
whose rarest line has the lowest count, and among those the longest one, and it
runs again before and after that run. Lines that occur more than max_chain times
in the old side are not used; if the range then has common lines but no usable
run, the fallback matches it. JGit uses Myers' method there. This file uses the
dynamic program of the shared helper, or nothing when fallback is None.
"""
from collections.abc import Hashable, Sequence
from txdiff import Op, lcs_matching, matching_to_script
Region = tuple[int, int, int, int] # (as, ae, bs, be): a[as:ae] == b[bs:be]
def best_region(a: Sequence[Hashable], b: Sequence[Hashable], alo: int, ahi: int, blo: int, bhi: int,
max_chain: int = 64) -> Region | None:
"""Return the run chosen in a[alo:ahi] and b[blo:bhi], an empty run if no line is common, or None.
None means that common lines exist, but each of them occurs more than max_chain times in a[alo:ahi].
"""
where: dict[Hashable, list[int]] = {} # @line L4
for i in range(alo, ahi):
where.setdefault(a[i], []).append(i)
best: Region = (alo, alo, blo, blo)
cnt = max_chain + 1 # @line L5
has_common = False
j = blo
while j < bhi: # @line L6
j_next = j + 1
places = where.get(b[j])
if places is not None:
has_common = True
if len(places) <= cnt: # @line L7
k = 0
while k < len(places):
as_, bs, ae, be = places[k], j, places[k] + 1, j + 1 # @line L8
rc = len(places)
while as_ > alo and bs > blo and a[as_ - 1] == b[bs - 1]:
as_, bs = as_ - 1, bs - 1
rc = min(rc, len(where[a[as_]]))
while ae < ahi and be < bhi and a[ae] == b[be]:
rc = min(rc, len(where[a[ae]]))
ae, be = ae + 1, be + 1
j_next = max(j_next, be) # @line L9
if best[1] - best[0] < ae - as_ or rc < cnt: # @line L10
best, cnt = (as_, ae, bs, be), rc
while k < len(places) and places[k] <= ae: # copies up to the end of the run are skipped, as in JGit
k += 1
j = j_next
if has_common and cnt > max_chain: # @line L11
return None
return best
def histogram_matching(a: Sequence[Hashable], b: Sequence[Hashable], max_chain: int = 64,
fallback: str | None = "lcs") -> list[tuple[int, int]]:
"""Return the matching (i, j) of histogram diff, increasing in both coordinates."""
if fallback not in (None, "lcs"):
raise ValueError("fallback must be None or 'lcs'")
n, m = len(a), len(b)
head = 0
while head < n and head < m and a[head] == b[head]: # @line L1
head += 1
tail = 0
while tail < n - head and tail < m - head and a[n - 1 - tail] == b[m - 1 - tail]:
tail += 1
pairs = [(t, t) for t in range(head)]
def match(alo: int, ahi: int, blo: int, bhi: int) -> None:
if alo == ahi or blo == bhi: # @line L3
return
region = best_region(a, b, alo, ahi, blo, bhi, max_chain)
if region is None: # @line L12
if fallback == "lcs":
pairs.extend((alo + i, blo + j) for i, j in lcs_matching(a[alo:ahi], b[blo:bhi]))
return
as_, ae, bs, be = region
if as_ == ae: # @line L13
return
match(alo, as_, blo, bs) # @line L14
pairs.extend((as_ + t, bs + t) for t in range(ae - as_))
match(ae, ahi, be, bhi)
match(head, n - tail, head, m - tail) # @line L2
pairs.extend((n - tail + t, m - tail + t) for t in range(tail))
return pairs
def histogram_diff(a: Sequence[Hashable], b: Sequence[Hashable], max_chain: int = 64,
fallback: str | None = "lcs") -> list[Op]:
"""Return the edit script from a to b that keeps the histogram matching."""
return matching_to_script(a, b, histogram_matching(a, b, max_chain, fallback)) # @line L15
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_histogram_diff.py 73 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/histogram-diff/. The authors are listed in prov/BNZ7EN.jsonl.
import random
from histogram_diff import best_region, histogram_diff, histogram_matching
from txdiff import is_matching, is_valid_script, lcs_matching, matching_to_script, script_cost
def test_page_example() -> None:
a = ["}", "}", "x", "}", "}", "y"]
b = ["y", "}", "}", "x", "w"]
# y is found first, with count 1. The braces have count 4 and are skipped as starting
# points. The match of x grows backward over two braces and wins, since it is longer.
assert best_region(a, b, 0, 6, 0, 5) == (0, 3, 1, 4)
assert histogram_matching(a, b) == [(0, 1), (1, 2), (2, 3)]
assert script_cost(histogram_diff(a, b)) == 5
def test_lower_count_wins_over_a_longer_run() -> None:
a = ["z", "s", "k", "s", "k", "u"]
b = ["s", "k", "v", "u", "w"]
assert best_region(a, b, 0, 6, 0, 5) == (5, 6, 3, 4)
assert histogram_matching(a, b) == [(1, 0), (2, 1), (5, 3)]
def test_check_value() -> None:
a, b = list("uaaav"), list("aaauv")
assert histogram_matching(a, b) == [(0, 3), (4, 4)]
assert script_cost(histogram_diff(a, b)) == 6
assert len(a) + len(b) - 2 * len(lcs_matching(a, b)) == 2
def test_unique_lines_are_not_enough_for_a_minimum() -> None:
# Every line is unique, but the longest run 6, 7 is taken before the longer subsequence 1, 3, 5.
a, b = [1, 2, 3, 4, 5, 6, 7], [6, 7, 1, 3, 5]
assert histogram_matching(a, b) == [(5, 0), (6, 1)]
assert len(lcs_matching(a, b)) == 3
def test_no_common_line_and_the_fallback() -> None:
assert best_region(list("ab"), list("cd"), 0, 2, 0, 2) == (0, 0, 0, 0)
assert histogram_matching(list("ab"), list("cd")) == []
a, b = list("abab"), list("baba")
assert histogram_matching(a, b) == [(1, 0), (2, 1), (3, 2)]
# With max_chain 1, every common line occurs too often, so the range goes to the fallback.
assert best_region(a, b, 0, 4, 0, 4, max_chain=1) is None
assert histogram_matching(a, b, max_chain=1) == lcs_matching(a, b)
assert histogram_matching(a, b, max_chain=1, fallback=None) == []
def test_common_start_and_end() -> None:
a = list("pqXYZrs")
b = list("pqZYXrs")
pairs = histogram_matching(a, b)
assert pairs[:2] == [(0, 0), (1, 1)] and pairs[-2:] == [(5, 5), (6, 6)]
def test_random_properties() -> None:
rng = random.Random(13)
for _ in range(500):
alpha = "abcdef"[: rng.randint(1, 6)]
a = [rng.choice(alpha) for _ in range(rng.randint(0, 12))]
b = [rng.choice(alpha) for _ in range(rng.randint(0, 12))]
best = len(lcs_matching(a, b))
for max_chain in (1, 2, 64):
full = histogram_matching(a, b, max_chain)
plain = histogram_matching(a, b, max_chain, None)
for pairs in (full, plain):
assert is_matching(a, b, pairs) and len(pairs) <= best
assert is_valid_script(a, b, matching_to_script(a, b, pairs))
assert set(plain) <= set(full)
assert len(histogram_matching(a, a)) == len(a)
History
Histogram diff was written for JGit, and its source file carries the copyright line of Google Inc. and others from 2010. Its class comment calls it an extended form of Bram Cohen's patience diff. Tay Ray Chuan ported it to the xdiff library of Git in 2011, and it appeared in Git 1.7.7 as the option --histogram. In 2020, Nugroho, Hata and Matsumoto measured how the choice of diff algorithm in Git changes the results of studies of code history, and recommended the histogram option for code changes.
References
- JGit, HistogramDiff.java (Copyright 2010, Google Inc. and others), the class comment, which calls the method an extended form of Bram Cohen's patience diff, the default maxChainLength of 64, the fallback algorithm (MyersDiff by default), and diffReplace, which recurses before and after the common region
- JGit, HistogramDiffIndex.java, scanA, which counts the lines of the old region, and tryLongestCommonSequence, which grows each match, takes the least count over the region, and keeps a region that is longer or has a lower count
- Tay Ray Chuan, teach --histogram to diff, Git commit 8c912ee, 2011, the port of JGit's HistogramDiff to the xdiff library of Git
- Yusuf Sulistyo Nugroho, Hideaki Hata and Kenichi Matsumoto, How different are different diff algorithms in Git? Use --histogram for code changes, Empirical Software Engineering 25(1), 2020, 790-823, the comparison of the Myers and Histogram options of Git on 14 Java projects, and the manual study that favors Histogram for code changes
- Bram Cohen, Patience Diff Advantages, blog post, 2010, patience diff, the method that histogram diff extends
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 BNZ7EN Edit this page History Report an error Markdown