File size: 4,152 Bytes
24aaa76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""Alignment and edit distance.

align_ops(ref, hyp): Levenshtein with unit costs and the SAME tie-break as the frozen J2 scorelib.align (backtrace from the end;
at a tie substitution or match first, then deletion, then insertion; rule v3 section 2, HR2). It returns the operation list
as well, which the per-letter, case, digit, punctuation, diacritic, homoglyph and word-level metrics need. Works on strings and
on lists of tokens. tests/test_core.py checks its counts against J2 align on thousands of random pairs.

lev_fast(a, b): distance only, bit-parallel (Myers 1999, Hyyro 2003) with Python integers. Used for page-level strings.
"""
import numpy as np


def align_ops(ref, hyp):
    """Returns (dist, ops). ops is a list of (op, i, j) in reading order, op in 'M','S','D','I';
    i is the index in ref (-1 for I), j the index in hyp (-1 for D)."""
    n, m = len(ref), len(hyp)
    if ref == hyp:
        return 0, [("M", i, i) for i in range(n)]
    if n == 0:
        return m, [("I", -1, j) for j in range(m)]
    if m == 0:
        return n, [("D", i, -1) for i in range(n)]
    prev = list(range(m + 1))
    rows = [prev]
    for i in range(1, n + 1):
        cur = [i] + [0] * m
        ri = ref[i - 1]
        for j in range(1, m + 1):
            cost = 0 if ri == hyp[j - 1] else 1
            a = prev[j - 1] + cost
            b = prev[j] + 1
            c = cur[j - 1] + 1
            cur[j] = a if (a <= b and a <= c) else (b if b <= c else c)
        rows.append(cur)
        prev = cur
    dist = rows[n][m]
    i, j = n, m
    ops = []
    while i > 0 or j > 0:
        if i > 0 and j > 0 and rows[i][j] == rows[i - 1][j - 1] + (0 if ref[i - 1] == hyp[j - 1] else 1):
            ops.append(("M" if ref[i - 1] == hyp[j - 1] else "S", i - 1, j - 1))
            i -= 1
            j -= 1
        elif i > 0 and rows[i][j] == rows[i - 1][j] + 1:
            ops.append(("D", i - 1, -1))
            i -= 1
        else:
            ops.append(("I", -1, j - 1))
            j -= 1
    ops.reverse()
    return dist, ops


def op_counts(ops):
    s = d = ins = 0
    for o, _, _ in ops:
        if o == "S":
            s += 1
        elif o == "D":
            d += 1
        elif o == "I":
            ins += 1
    return s, d, ins


def lev_fast(a, b):
    """Edit distance (unit costs) of two sequences of hashable items, bit-parallel."""
    if a == b:
        return 0
    if len(a) < len(b):
        a, b = b, a
    m = len(b)
    if m == 0:
        return len(a)
    peq = {}
    for i, c in enumerate(b):
        peq[c] = peq.get(c, 0) | (1 << i)
    mask = (1 << m) - 1
    pv, mv, score = mask, 0, m
    hb = 1 << (m - 1)
    for c in a:
        eq = peq.get(c, 0)
        xv = eq | mv
        xh = (((eq & pv) + pv) ^ pv) | eq
        ph = mv | (~(xh | pv) & mask)
        mh = pv & xh
        if ph & hb:
            score += 1
        elif mh & hb:
            score -= 1
        ph = ((ph << 1) | 1) & mask
        mh = (mh << 1) & mask
        pv = mh | (~(xv | ph) & mask)
        mv = ph & xv
    return score


def min_cost_line_assignment(ref_lines, out_lines):
    """Minimum total cost of a one-to-one assignment between reference lines and output lines (metric M29, G5).
    cost(pair) = edit distance; an unassigned reference line costs its length (all deleted); an unassigned output line
    costs its length (all inserted). Returns (total_cost, pairs) with pairs = list of (ref index, out index)."""
    from scipy.optimize import linear_sum_assignment
    R, O = len(ref_lines), len(out_lines)
    if R == 0:
        return sum(len(x) for x in out_lines), []
    if O == 0:
        return sum(len(x) for x in ref_lines), []
    big = 1e9
    N = R + O
    c = np.full((N, N), big, dtype=np.float64)
    for i, r in enumerate(ref_lines):
        for j, h in enumerate(out_lines):
            c[i, j] = lev_fast(r, h)
        c[i, O + i] = len(r)
    for j, h in enumerate(out_lines):
        c[R + j, j] = len(h)
    c[R:, O:] = 0.0
    ri, ci = linear_sum_assignment(c)
    total = float(c[ri, ci].sum())
    pairs = [(int(i), int(j)) for i, j in zip(ri, ci) if i < R and j < O]
    return total, pairs