File size: 15,710 Bytes
21f57d7 | 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 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | """Second analysis of the attributable OGA diagnostics (rerun job 5715083), HF subset
(Urdatorn/oga-macronized-no-norma, 5d737f8):
1. Abstention by POS (and word shape / verb morphology) against the baseline distribution:
share of all OGA tokens, of tokens sent to the modules (= with an unmarked open-syllable
dichronon), and of abstentions; over-representation = rate / overall rate. Significance:
a pooled two-proportion z-test (reported, but with ~13M tokens nearly everything passes),
and, as the test that is relied on, a per-work paired comparison: for every work with at
least MIN_TOK tokens of the category, d_w = abstention rate of the category - rate of all
other tokens in that work; one-sample t-test and Wilcoxon signed-rank test of d_w = 0,
Cohen's d, Holm correction over all tests of the table. This treats works as the unit and
so accounts for texts differing in difficulty.
2. Coverage by dialect group, in relation to the hypotactic crawl: every OGA sentence is
checked for word 4-gram overlap with the 38 hypotactic works the lexicon was built from
(hypotactic/tsv); token-level coverage with and without the hypotactic module (it is last
in the cascade, so removing its credits is the exact counterfactual), per dialect group,
split into sentences inside and outside the crawl.
Usage: python analyze_v2.py DIAG_DIR RERUN_OUT HF_DATA_DIR HYPOTACTIC_TSV_DIR LOG_STATS_JSON OUT_DIR WORKERS
"""
import collections, glob, json, math, os, re, sys, unicodedata
from multiprocessing import Pool
import numpy as np
import pyarrow.parquet as pq
from scipy import stats
C = collections.Counter
CHUNK, MIN_TOK, N = 500, 30, 4
HF_KEEP = None
HYP_GRAMS = None
AUTHORS = {
"Epic": {"tlg0012": "Homer", "tlg0013": "Homeric Hymns", "tlg0020": "Hesiod", "tlg0001": "Apollonius Rhodius",
"tlg2046": "Quintus Smyrnaeus", "tlg2045": "Nonnus", "tlg0653": "Aratus"},
"Doric/Aeolic lyric and bucolic": {"tlg0033": "Pindar", "tlg0199": "Bacchylides", "tlg0005": "Theocritus",
"tlg0009": "Sappho", "tlg0035": "Moschus", "tlg0036": "Bion"},
"Ionic prose": {"tlg0016": "Herodotus", "tlg0627": "Hippocratic corpus"},
"Attic drama": {"tlg0019": "Aristophanes", "tlg0011": "Sophocles", "tlg0006": "Euripides", "tlg0085": "Aeschylus"},
"Classical Attic prose": {"tlg0059": "Plato", "tlg0032": "Xenophon", "tlg0003": "Thucydides", "tlg0014": "Demosthenes",
"tlg0540": "Lysias", "tlg0010": "Isocrates", "tlg0026": "Aeschines", "tlg0028": "Antiphon",
"tlg0017": "Isaeus", "tlg0030": "Hyperides", "tlg0034": "Lycurgus", "tlg0027": "Andocides",
"tlg0086": "Aristotle"},
"Koine": {"tlg0031": "New Testament", "tlg0527": "Septuagint", "tlg0543": "Polybius", "tlg0060": "Diodorus",
"tlg0099": "Strabo", "tlg0557": "Epictetus", "tlg0057": "Galen", "tlg0526": "Josephus", "tlg0018": "Philo"},
"Atticist / Imperial and late literary prose": {
"tlg0007": "Plutarch", "tlg0062": "Lucian", "tlg0284": "Aelius Aristides", "tlg0081": "Dionysius of Halicarnassus",
"tlg0525": "Pausanias", "tlg0551": "Appian", "tlg0385": "Cassius Dio", "tlg0008": "Athenaeus",
"tlg0612": "Dio Chrysostom", "tlg2200": "Libanius", "tlg2000": "Plotinus", "tlg2034": "Porphyry",
"tlg4013": "Simplicius", "tlg0732": "Alexander of Aphrodisias", "tlg2042": "Origen", "tlg2018": "Eusebius"},
}
GROUP_OF = {a: g for g, d in AUTHORS.items() for a in d}
NAME_OF = {a: n for d in AUTHORS.values() for a, n in d.items()}
DIALECTAL = {"Epic", "Doric/Aeolic lyric and bucolic", "Ionic prose"}
FEATURES = [("VERB", "VerbForm=Part"), ("VERB", "VerbForm=Fin"), ("VERB", "VerbForm=Inf"),
("VERB", "Voice=Act"), ("VERB", "Voice=Mid"), ("VERB", "Voice=Pass"),
("VERB", "Tense=Pres"), ("VERB", "Tense=Past"), ("VERB", "Tense=Fut"),
("ADJ", "Degree=Cmp"), ("ADJ", "Degree=Sup"), ("NOUN", "Number=Sing"), ("NOUN", "Number=Plur")]
APOS = {"'": "’", "ʼ": "’", "᾽": "’", "‘": "’", "᾿": "’"}
def norm_word(tok):
chars = [APOS.get(c, c) for c in unicodedata.normalize("NFC", tok) if c not in "^_[]{}"]
ok = lambda c: unicodedata.category(c)[0] in "LM"
s, e = 0, len(chars)
while s < e and not ok(chars[s]): s += 1
while e > s and not ok(chars[e - 1]) and not (chars[e - 1] == "’" and e - 1 > s): e -= 1
out = []
for ch in chars[s:e]:
d = unicodedata.normalize("NFD", ch.lower()).replace("̀", "́")
out.append(unicodedata.normalize("NFC", d))
return "".join(out).replace("ϲ", "σ")
def grams(text):
w = [x for x in (norm_word(t) for t in text.split()) if x]
return [tuple(w[i:i + N]) for i in range(len(w) - N + 1)]
def work_of(stem):
return stem.split(".tok")[0]
def new_acc():
return dict(sent=C(), abst=C(), before=0, after=0, hyp=0, credits=C(),
s_before=C(), s_after=C(), s_hyp=C()) # s_*: by sentence class "hyp"/"nonhyp"
def do_chunk(path):
tag = os.path.basename(path)[:-4]
stem, chunk = tag.rsplit(".", 1)
chunk = int(chunk)
keep = HF_KEEP.get(stem, {})
a = new_acc()
with open(path, encoding="utf-8") as fh:
next(fh)
for line in fh:
c = line.rstrip("\n").split("\t")
if len(c) != 9:
continue
cls = keep.get((chunk, int(c[0])))
if cls is None:
continue
sent, token, lemma, pos, morph, before, after, result, credits = c
before, after = int(before), int(after)
ab = after > 0
cats = ["POS=" + pos]
feats = set(morph.split("|"))
cats += [f"FEAT={p}:{f}" for p, f in FEATURES if p == pos and f in feats]
if "ϲ" in token or "Ϲ" in token: cats.append("SHAPE=lunate sigma")
if token[:1].isupper(): cats.append("SHAPE=capitalized")
if token.endswith("'"): cats.append("SHAPE=elided")
cats.append("ALL")
for k in cats:
a["sent"][k] += 1
if ab: a["abst"][k] += 1
hyp = sum(int(kv.split("=")[1]) for kv in credits.split(",") if kv.startswith("hypotactic="))
for kv in credits.split(","):
if kv: a["credits"][kv.split("=")[0]] += int(kv.split("=")[1])
a["before"] += before; a["after"] += after; a["hyp"] += hyp
a["s_before"][cls] += before; a["s_after"][cls] += after; a["s_hyp"][cls] += hyp
return stem, a
def holm(ps):
order = sorted(range(len(ps)), key=lambda i: ps[i])
adj, run = [None] * len(ps), 0.0
for rank, i in enumerate(order):
run = max(run, min(1.0, (len(ps) - rank) * ps[i]))
adj[i] = run
return adj
def category_table(per_work, total, cats, baseline_all=None):
rows = []
T = total["ALL"]; A = total["ALL_abst"]
p_all = A / T
for k in cats:
n, x = total.get(k, 0), total.get(k + "_abst", 0)
if n == 0:
continue
rate = x / n
n2, x2 = T - n, A - x
p_pool = A / T
se = math.sqrt(p_pool * (1 - p_pool) * (1 / n + 1 / n2)) if n2 else float("nan")
z = (rate - x2 / n2) / se if n2 and se else float("nan")
p_z = 2 * stats.norm.sf(abs(z)) if z == z else float("nan")
d = []
for w, (s, ab) in per_work.items():
nk, xk = s[k], ab[k]
no, xo = s["ALL"] - nk, ab["ALL"] - xk
if nk >= MIN_TOK and no >= MIN_TOK:
d.append(xk / nk - xo / no)
d = np.array(d)
if len(d) >= 5:
t = stats.ttest_1samp(d, 0.0)
try:
wil = stats.wilcoxon(d).pvalue
except ValueError:
wil = float("nan")
row_t = dict(works=len(d), mean_diff_pp=100 * d.mean(), median_diff_pp=100 * np.median(d), sd_pp=100 * d.std(ddof=1),
t=float(t.statistic), p_t=float(t.pvalue), p_wilcoxon=float(wil), cohens_d=float(d.mean() / d.std(ddof=1)) if d.std(ddof=1) else float("nan"))
else:
row_t = dict(works=len(d))
rows.append(dict(category=k, sent=n, abstained=x, share_of_sent=n / T, share_of_abstentions=x / A,
share_of_all_tokens=(baseline_all or {}).get(k), rate=rate, overrep=rate / p_all,
z=z, p_z=p_z, **row_t))
ps = [r.get("p_t", 1.0) for r in rows]
for r, h in zip(rows, holm(ps)):
r["p_t_holm"] = h
return rows
def main():
global HF_KEEP, HYP_GRAMS
diag, rerun, hf_dir, hyp_dir, logstats, out_dir, workers = sys.argv[1:8]
workers = int(workers)
os.makedirs(out_dir, exist_ok=True)
R = {}
# hypotactic 4-grams
HYP = set(); hyp_lines = 0
for f in glob.glob(os.path.join(hyp_dir, "*.tsv")):
for line in open(f, encoding="utf-8"):
hyp_lines += 1
HYP.update(grams(line.split("\t")[0]))
print(f"hypotactic: {hyp_lines:,} verse lines, {len(HYP):,} distinct 4-grams", flush=True)
# HF membership and per-sentence hypotactic overlap
hf = C()
for f in sorted(glob.glob(os.path.join(hf_dir, "*.parquet"))):
hf.update(pq.read_table(f, columns=["macronized"]).column(0).to_pylist())
keep, work_lines = {}, C()
hyp_sent = C()
for f in sorted(glob.glob(os.path.join(rerun, "parts", "*.txt"))):
stem = os.path.basename(f)[:-4]
d = {}
for i, line in enumerate(open(f, encoding="utf-8").read().splitlines()):
if hf[line] > 0:
hf[line] -= 1
g = grams(line.replace("^", "").replace("_", ""))
hit = sum(1 for x in g if x in HYP)
cls = "hyp" if g and hit / len(g) >= 0.5 else "nonhyp"
d[(i // CHUNK, i % CHUNK)] = cls
hyp_sent[(work_of(stem), cls)] += 1
keep[stem] = d
HF_KEEP = keep
print("membership done", flush=True)
# traces
traces = sorted(glob.glob(os.path.join(diag, "traces", "*.tsv")))
per_work = {}
with Pool(workers) as pool:
for i, (stem, a) in enumerate(pool.imap_unordered(do_chunk, traces, chunksize=8)):
w = work_of(stem)
if w not in per_work:
per_work[w] = new_acc()
for k, v in a.items():
if isinstance(v, C): per_work[w][k].update(v)
else: per_work[w][k] += v
if i % 1000 == 0: print(f" traces {i}/{len(traces)}", flush=True)
# 1. category tables
total = C()
pw = {}
for w, a in per_work.items():
for k, v in a["sent"].items(): total[k] += v
for k, v in a["abst"].items(): total[k + "_abst"] += v
pw[w] = (a["sent"], a["abst"])
log = json.load(open(logstats, encoding="utf-8"))
cons = dict(log["funnel_all_oga"]["considered_pos"]); n_cons = sum(cons.values())
base_all = {"POS=" + p: n / n_cons for p, n in cons.items()}
pos_cats = [k for k, _ in sorted(((k, v) for k, v in total.items() if k.startswith("POS=") and not k.endswith("_abst")), key=lambda x: -x[1])]
R["pos"] = category_table(pw, total, pos_cats, base_all)
R["features"] = category_table(pw, total, [f"FEAT={p}:{f}" for p, f in FEATURES])
R["shapes"] = category_table(pw, total, ["SHAPE=lunate sigma", "SHAPE=capitalized", "SHAPE=elided"])
R["overall"] = dict(sent=total["ALL"], abstained=total["ALL_abst"], rate=total["ALL_abst"] / total["ALL"],
works=len(per_work), min_tokens_per_work_and_category=MIN_TOK)
# 2. dialect x hypotactic
works = []
for w, a in per_work.items():
auth = w.split(".")[0]
if a["before"] == 0:
continue
works.append(dict(work=w, author=NAME_OF.get(auth, auth), group=GROUP_OF.get(auth, "other"),
dichrona=a["before"], cov=1 - a["after"] / a["before"],
cov_nohyp=1 - (a["after"] + a["hyp"]) / a["before"], hyp_share=a["hyp"] / a["before"],
sent_hyp=hyp_sent[(w, "hyp")], sent_nonhyp=hyp_sent[(w, "nonhyp")],
frac_sent_in_crawl=hyp_sent[(w, "hyp")] / max(1, hyp_sent[(w, "hyp")] + hyp_sent[(w, "nonhyp")]),
d_hyp=a["s_before"]["hyp"], a_hyp=a["s_after"]["hyp"], h_hyp=a["s_hyp"]["hyp"],
d_non=a["s_before"]["nonhyp"], a_non=a["s_after"]["nonhyp"], h_non=a["s_hyp"]["nonhyp"]))
R["works"] = works
groups = []
for g in list(AUTHORS) + ["other"]:
ws = [x for x in works if x["group"] == g]
if not ws:
continue
def pooled(sel_d, sel_a, sel_h):
D = sum(x[sel_d] for x in ws); Aa = sum(x[sel_a] for x in ws); H = sum(x[sel_h] for x in ws)
return (D, 1 - Aa / D if D else None, 1 - (Aa + H) / D if D else None)
D = sum(x["dichrona"] for x in ws)
cov = 1 - sum(x["dichrona"] * (1 - x["cov"]) for x in ws) / D
cov_nh = 1 - sum(x["dichrona"] * (1 - x["cov_nohyp"]) for x in ws) / D
dh, ch, chn = pooled("d_hyp", "a_hyp", "h_hyp")
dn, cn, cnn = pooled("d_non", "a_non", "h_non")
groups.append(dict(group=g, works=len(ws), dichrona=D, cov=cov, cov_nohyp=cov_nh,
dichrona_in_crawl_sentences=dh, cov_in_crawl=ch, cov_in_crawl_nohyp=chn,
dichrona_outside_crawl=dn, cov_outside=cn, cov_outside_nohyp=cnn,
per_work_cov_nohyp=[x["cov_nohyp"] for x in ws if x["dichrona"] >= 2000]))
R["groups"] = [{k: v for k, v in g.items() if k != "per_work_cov_nohyp"} for g in groups]
# Welch t-tests on per-work coverage without hypotactic (works with >= 2000 dichrona), outside-crawl works only
def sample(names, outside=True):
return np.array([x["cov_nohyp"] for x in works if x["group"] in names and x["dichrona"] >= 2000
and (not outside or x["frac_sent_in_crawl"] < 0.5)])
contrasts = []
attic = {"Attic drama", "Classical Attic prose"}
later = {"Koine", "Atticist / Imperial and late literary prose"}
for label, A_, B_ in [("dialectal vs Attic", DIALECTAL, attic), ("dialectal vs Koine/Atticist", DIALECTAL, later),
("Attic vs Koine/Atticist", attic, later), ("Epic vs Attic", {"Epic"}, attic),
("Ionic prose vs Classical Attic prose", {"Ionic prose"}, {"Classical Attic prose"})]:
for outside in (False, True):
a, b = sample(A_, outside), sample(B_, outside)
if len(a) >= 2 and len(b) >= 2:
t = stats.ttest_ind(a, b, equal_var=False)
u = stats.mannwhitneyu(a, b)
contrasts.append(dict(contrast=label, works_outside_crawl_only=outside, n_a=len(a), n_b=len(b),
mean_a=float(a.mean()), mean_b=float(b.mean()), diff_pp=float(100 * (a.mean() - b.mean())),
t=float(t.statistic), p_welch=float(t.pvalue), p_mannwhitney=float(u.pvalue)))
R["contrasts_cov_nohyp"] = contrasts
R["crawl_works"] = sorted([dict(work=x["work"], author=x["author"], frac_sent_in_crawl=x["frac_sent_in_crawl"],
cov=x["cov"], cov_nohyp=x["cov_nohyp"], hyp_share=x["hyp_share"])
for x in works if x["frac_sent_in_crawl"] >= 0.2], key=lambda x: -x["frac_sent_in_crawl"])
with open(os.path.join(out_dir, "stats_v2.json"), "w", encoding="utf-8") as f:
json.dump(R, f, ensure_ascii=False, indent=1, default=float)
print("done", flush=True)
if __name__ == "__main__":
main()
|