File size: 9,243 Bytes
aaee816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
"""Which combination of Wikipedias covers the most of one language's articles.

A single partner language's shared-article count overstates its usefulness, because large
Wikipedias overlap heavily with each other: English and Spanish both carry the same
bot-generated geographic stubs, so adding Spanish to English buys almost nothing. What
matters for building parallel data is the *union* of concept-aligned articles a set of
languages covers.

This greedily selects the partner language that adds the most previously uncovered Wikidata
items at each step, which is the standard approximation for maximum set cover. Partners whose
marginal contribution exceeds one percent of the target's own articles are kept as that
language's "material" partner set; the rest are redundancy.
"""

from __future__ import annotations

import argparse
import json
import time
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
CACHE = ROOT / "cache" / "lang_audit"
QID_DIR = CACHE / "qids"
# A partner must add at least this share of the target's own articles to be called material.
MATERIAL_GAIN_SHARE = 0.01
GREEDY_ROUNDS = 15


def _membership(values, other):
    """Boolean mask: which of ``values`` appear in the sorted unique array ``other``."""
    import numpy as np

    if other.size == 0 or values.size == 0:
        return np.zeros(values.size, dtype=bool)
    index = np.searchsorted(other, values)
    index[index >= other.size] = 0
    return other[index] == values


def _intersection_size(left, right) -> int:
    """Intersection count, searching the larger array with the smaller one."""
    if left.size > right.size:
        left, right = right, left
    return int(_membership(left, right).sum())


def _difference(values, other):
    return values[~_membership(values, other)]


def load_arrays(order: list[str]) -> dict:
    import numpy as np

    return {code: np.load(QID_DIR / f"{code}.npy") for code in order}


def load_matrix() -> tuple[list[str], object]:
    import numpy as np

    archive = np.load(CACHE / "overlap_matrix.npz", allow_pickle=True)
    return [str(name) for name in archive["order"]], archive["shared"]


def item_language_counts(order: list[str], arrays: dict):
    """For every Wikidata item, how many of the audited Wikipedias carry it."""
    import numpy as np

    concatenated = np.concatenate([arrays[code] for code in order])
    unique, counts = np.unique(concatenated, return_counts=True)
    return unique, counts


def greedy_cover(
    target: str,
    candidates: list[str],
    arrays: dict,
    shared_row: dict,
    rounds: int = GREEDY_ROUNDS,
) -> list[dict]:
    """Greedy maximum set cover of ``target``'s items by other languages.

    ``shared_row`` gives each candidate's total overlap with the whole target set, which is
    an upper bound on what it can still add. Sorting by it and stopping once the bound falls
    below the best gain found so far makes each round examine only a few candidates.
    """
    base = arrays[target]
    total = base.size
    if total == 0:
        return []
    uncovered = base
    ranked = sorted(
        (c for c in candidates if shared_row.get(c, 0) > 0),
        key=lambda c: (-shared_row[c], c),
    )
    picks: list[dict] = []
    covered = 0
    for _ in range(rounds):
        if uncovered.size == 0 or not ranked:
            break
        best, best_gain = None, 0
        for code in ranked:
            bound = min(shared_row[code], uncovered.size)
            if bound <= best_gain:
                break
            gain = _intersection_size(arrays[code], uncovered)
            if gain > best_gain:
                best, best_gain = code, gain
        if best is None or best_gain == 0:
            break
        uncovered = _difference(uncovered, arrays[best])
        covered += best_gain
        picks.append({
            "rank": len(picks) + 1,
            "language": best,
            "adds_new_items": best_gain,
            "adds_share_of_own": round(best_gain / total, 5),
            "own_shared_items": int(shared_row[best]),
            "cumulative_items": covered,
            "cumulative_share": round(covered / total, 5),
        })
        ranked.remove(best)
    return picks


def build(rounds: int = GREEDY_ROUNDS) -> dict:
    import numpy as np

    order, shared = load_matrix()
    print(f"languages: {len(order)}; loading cached item sets", flush=True)
    arrays = load_arrays(order)
    unique, counts = item_language_counts(order, arrays)
    index = {code: position for position, code in enumerate(order)}

    results = {}
    started = time.time()
    for position, target in enumerate(order, 1):
        base = arrays[target]
        total = base.size
        row = shared[index[target]]
        shared_row = {
            code: int(row[index[code]]) for code in order if code != target and row[index[code]] > 0
        }
        picks = greedy_cover(target, list(shared_row), arrays, shared_row, rounds=rounds)
        material = [p for p in picks if p["adds_share_of_own"] > MATERIAL_GAIN_SHARE]

        # An item is reachable from some other Wikipedia exactly when at least two of the
        # audited wikis carry it, so the ceiling needs no per-target union.
        if total:
            positions = np.searchsorted(unique, base)
            reachable = int((counts[positions] >= 2).sum())
        else:
            reachable = 0

        results[target] = {
            "own_items": total,
            "greedy_selection": picks,
            "material_partners": [p["language"] for p in material],
            "material_partner_count": len(material),
            "material_items": material[-1]["cumulative_items"] if material else 0,
            "material_share": material[-1]["cumulative_share"] if material else 0.0,
            "best_partner": picks[0]["language"] if picks else None,
            "best_partner_items": picks[0]["adds_new_items"] if picks else 0,
            "ceiling_items": reachable,
            "ceiling_share": round(reachable / total, 5) if total else None,
            "items_unique_to_this_wiki": total - reachable,
        }
        if position % 25 == 0 or position == len(order):
            print(f"  {position}/{len(order)} ({time.time() - started:.0f}s)", flush=True)

    payload = {
        "method": (
            "Greedy maximum set cover of each language's Wikidata items by the other audited "
            "Wikipedias. At each rank the partner adding the most previously uncovered items "
            "is selected. A partner is 'material' when it adds more than "
            f"{MATERIAL_GAIN_SHARE:.0%} of the target's own article count."
        ),
        "material_gain_share": MATERIAL_GAIN_SHARE,
        "greedy_rounds": rounds,
        "languages": results,
        "language_count": len(results),
    }
    out = CACHE / "coverage.json"
    out.write_text(json.dumps(payload, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    print(f"wrote {out}", flush=True)
    return payload


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--language", default=None, help="report one FineWiki config only")
    parser.add_argument("--rounds", type=int, default=GREEDY_ROUNDS)
    parser.add_argument(
        "--all", action="store_true", help="compute every language into cache/lang_audit/coverage.json"
    )
    parser.add_argument(
        "--anchors-from", type=Path, default=None,
        help="manifest.json whose high_resource_anchors restrict the candidate set",
    )
    parser.add_argument("--output", type=Path, default=None)
    args = parser.parse_args(argv)

    if args.all:
        build(rounds=args.rounds)
        return 0

    target = args.language or "glk"
    order, shared = load_matrix()
    index = {code: position for position, code in enumerate(order)}
    candidates = [c for c in order if c != target]
    label = "all FineWiki languages"
    if args.anchors_from:
        manifest = json.loads(args.anchors_from.read_text(encoding="utf-8"))
        anchors = set(manifest["derived"]["high_resource_anchors"])
        candidates = [c for c in candidates if c in anchors]
        label = "high-resource anchors only"

    arrays = load_arrays([target] + candidates)
    row = shared[index[target]]
    shared_row = {c: int(row[index[c]]) for c in candidates if row[index[c]] > 0}
    picks = greedy_cover(target, list(shared_row), arrays, shared_row, rounds=args.rounds)
    total = arrays[target].size
    print(f"{target}: {total:,} Wikidata items; {label}")
    for pick in picks:
        print(
            f"  {pick['rank']:>2}. +{pick['language']:<12} new={pick['adds_new_items']:>7,}  "
            f"(alone {pick['own_shared_items']:>7,})  cumulative={pick['cumulative_items']:>7,} "
            f"({pick['cumulative_share'] * 100:5.1f}%)"
        )
    if args.output:
        args.output.parent.mkdir(parents=True, exist_ok=True)
        args.output.write_text(
            json.dumps({"target": target, "candidate_set": label, "selection": picks},
                       ensure_ascii=False, indent=1) + "\n",
            encoding="utf-8",
        )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())