math-stratum / tools /coverage_report.py
tailot's picture
publish math-stratum bundle
e9dac18 verified
Raw History Blame Contribute Delete
5.42 kB
#!/usr/bin/env python3
"""Reading coverage: which variety reads which kind, and how often the two readers agree.
This is the one table the corpus cannot fake. A language covers a kind only if its data file
writes the verbs, the patterns and the joints for it, and a reading only counts as confirmed when
reader A (which matches the surface shapes) and reader B (which follows the joints of the math
language) reach it by different routes. The math stratum is not consulted by default: a coverage
report asks what the stratum *understood*, not what the math layer could prove, and the two
ceilings are reported apart on purpose. Pass ``--math`` to add the math verdicts to the same run.
Usage: python math-stratum/tools/coverage_report.py [--math]
python math-stratum/tools/coverage_report.py --out math-stratum/results/coverage.json
"""
import argparse
import collections
import json
import sys
from pathlib import Path
from typing import Any, Dict, List
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from lgstratum import corpus, lexicon, pipeline # noqa: E402
OUT = ROOT / "results" / "coverage.json"
def inventory() -> Dict[str, Dict[str, Any]]:
"""What the data files of each variety actually carry, counted rather than claimed."""
table: Dict[str, Dict[str, Any]] = {}
for lang in lexicon.codes():
patterns = lexicon.patterns(lang)
verbs = lexicon.verbs(lang)
table[lang] = {
"kinds": sorted(patterns),
"patterns": sum(len(entries) for entries in patterns.values()),
"verb_phrases": len(verbs),
"markers": sum(len(words) for words in lexicon.markers(lang).values()),
"connectives": sum(len(words) for words in lexicon.connectives(lang).values()),
"noise_words": len(lexicon.noise(lang)),
"pattern_words": len(lexicon.pattern_literals(lang)),
}
return table
def ask(item: Dict[str, Any], use_math: bool) -> Dict[str, Any]:
"""One corpus question through the eight nodes, in memory, with the fault catalogue closed."""
result = pipeline.ask(item["question"], item["lang"], call_math=use_math)
reading_a = result["dossier"].get("reading_a") or {}
reading_b = result["dossier"].get("reading_b") or {}
return {"id": item["id"], "lang": item["lang"], "kind": item.get("kind", "?"),
"state": str(result["final"].get("state", "NONE")),
"assurance": int(result["final"].get("assurance", 0)),
"reader_a": str(reading_a.get("status", "NONE")),
"reader_b": str(reading_b.get("status", "NONE")),
"math_status": str((result["dossier"].get("math") or {}).get("status", "SKIPPED"))}
def tally(rows: List[Dict[str, Any]]) -> Dict[str, int]:
counts: Dict[str, int] = collections.Counter()
for row in rows:
counts["items"] += 1
counts[row["state"].lower()] += 1
counts["reader_a_read"] += 1 if row["reader_a"] in ("READ", "DIRECT") else 0
counts["reader_b_read"] += 1 if row["reader_b"] in ("READ", "DIRECT") else 0
return dict(sorted(counts.items()))
def main(argv: List[str] = None) -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--math", action="store_true",
help="consult the math stratum too, and report its verdicts in the same run")
parser.add_argument("--out", default=str(OUT), help="where to write the JSON report")
args = parser.parse_args(argv)
items = corpus.load()
rows = []
for item in items:
row = ask(item, args.math)
rows.append(row)
print("%-9s %-4s %-11s %-12s a=%-11s b=%-11s assurance %d"
% (row["id"], row["lang"], row["kind"], row["state"], row["reader_a"],
row["reader_b"], row["assurance"]))
by_pair: Dict[str, Dict[str, int]] = {}
for lang in lexicon.codes():
for kind in sorted({row["kind"] for row in rows if row["lang"] == lang}):
subset = [row for row in rows if row["lang"] == lang and row["kind"] == kind]
by_pair["%s/%s" % (lang, kind)] = tally(subset)
languages = {lang: tally([row for row in rows if row["lang"] == lang])
for lang in lexicon.codes()}
print("")
print("%-6s %-12s %5s %7s %7s %7s %7s" % ("lang", "kind", "items", "agree", "single", "other", "read by A/B"))
for key in sorted(by_pair):
cell = by_pair[key]
print("%-6s %-12s %5d %7d %7d %7d %4d/%-3d"
% (key.split("/")[0], key.split("/")[1], cell.get("items", 0),
cell.get("agreed", 0), cell.get("single", 0),
cell.get("not_covered", 0) + cell.get("disputed", 0) + cell.get("ambiguous", 0),
cell.get("reader_a_read", 0), cell.get("reader_b_read", 0)))
report = {"items": len(items), "math_consulted": bool(args.math),
"inventory": inventory(), "languages": languages, "pairs": by_pair, "rows": rows}
destination = Path(args.out)
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8")
print("")
print("wrote %s (%d items, math consulted: %s)"
% (destination, len(items), "yes" if args.math else "no"))
return 0
if __name__ == "__main__":
raise SystemExit(main())