"""exp0 headline: posts/comments that use ANY rationalist dialect vs NONE. The honest, defensible claim from exp0 is a step, not a gradient: AF documents that use any rationalist/EA dialect score higher than documents that use none. This script tests that for posts and comments separately. Karma is heavy-tailed, so we use Mann-Whitney U (rank-based) for significance and report the rank-biserial / common-language effect size alongside means. Outputs: figures/dialect_vs_none_karma.png results/dialect_vs_none.txt """ import json import os import sys from pathlib import Path import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import stats PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, PROJECT_DIR) from config import count_all_terms, word_count DATA = Path(PROJECT_DIR) / "data" FIG = Path(PROJECT_DIR) / "figures" RES = Path(PROJECT_DIR) / "results" FIG.mkdir(parents=True, exist_ok=True) RES.mkdir(parents=True, exist_ok=True) def load(path, year_range=None): """year_range=(lo, hi) to restrict; None to keep all years.""" rows = [] with open(path) as f: for line in f: p = json.loads(line) text = p.get("body") or "" wc = max(1, word_count(text)) counts = count_all_terms(text) rows.append({ "posted_at": p.get("posted_at"), "base_score": p.get("base_score"), "n_matches": sum(counts.values()), "dialect_rate": sum((c / wc) * 10000 for c in counts.values()), }) df = pd.DataFrame(rows) df["posted_at"] = pd.to_datetime(df["posted_at"], errors="coerce", utc=True) df["year"] = df["posted_at"].dt.year df["base_score"] = pd.to_numeric(df["base_score"], errors="coerce") if year_range is not None: lo, hi = year_range df = df[(df["year"] >= lo) & (df["year"] <= hi)] df = df.dropna(subset=["base_score"]).reset_index(drop=True) # group: did the doc use ANY dialect term at all? df["uses_dialect"] = df["n_matches"] > 0 return df def boot_median_ci(a, n_boot=2000, seed=0): """95% bootstrap CI for the median (half-widths around the point median).""" rng = np.random.default_rng(seed) a = np.asarray(a) meds = np.median(rng.choice(a, size=(n_boot, len(a)), replace=True), axis=1) lo, hi = np.percentile(meds, [2.5, 97.5]) m = float(np.median(a)) return m, m - lo, hi - m def analyze(name, df, lines): none = df.loc[~df["uses_dialect"], "base_score"].values some = df.loc[df["uses_dialect"], "base_score"].values n0, n1 = len(none), len(some) # Mann-Whitney U (two-sided), rank-based — robust to karma's heavy tail U, p = stats.mannwhitneyu(some, none, alternative="two-sided") # common-language effect size: P(random dialect doc outscores no-dialect doc) cles = U / (n0 * n1) rank_biserial = 2 * cles - 1 med0, lo0, hi0 = boot_median_ci(none) med1, lo1, hi1 = boot_median_ci(some) stat = { "name": name, "n0": n0, "n1": n1, "mean0": float(np.mean(none)), "mean1": float(np.mean(some)), "med0": med0, "med1": med1, "ci0": (lo0, hi0), "ci1": (lo1, hi1), "p": p, "cles": cles, "rb": rank_biserial, } lines.append(f"{name}") lines.append("-" * 60) lines.append(f" no dialect : n={n0:>6} median={med0:6.1f} mean={stat['mean0']:7.2f}") lines.append(f" any dialect: n={n1:>6} median={med1:6.1f} mean={stat['mean1']:7.2f}") lines.append(f" median uplift: {med1 - med0:+.1f} karma") lines.append(f" mean uplift : {stat['mean1'] - stat['mean0']:+.2f} karma " "(mean is outlier-sensitive on heavy-tailed karma — see CLES)") lines.append(f" Mann-Whitney U: p = {p:.2g}") lines.append(f" effect size : common-language (CLES) = {cles:.3f} " f"(P a dialect doc outranks a no-dialect doc); " f"rank-biserial = {rank_biserial:+.3f}") lines.append("") return stat def panel(ax, stat, color): x = [0, 1] meds = [stat["med0"], stat["med1"]] yerr = np.array([[stat["ci0"][0], stat["ci1"][0]], [stat["ci0"][1], stat["ci1"][1]]]) ns = [stat["n0"], stat["n1"]] means = [stat["mean0"], stat["mean1"]] ax.bar(x, meds, 0.6, yerr=yerr, capsize=6, color=["tab:gray", color], alpha=0.88, error_kw={"elinewidth": 1.5, "ecolor": "black"}) for i in x: top = meds[i] + yerr[1][i] ax.text(i, top, f" n={ns[i]:,}\n median {meds[i]:.0f}\n (mean {means[i]:.1f})", ha="center", va="bottom", fontsize=8.5, color="dimgray") ax.set_xticks(x) ax.set_xticklabels(["uses NO\ndialect", "uses SOME\ndialect"], fontsize=10) ax.set_ylabel("median karma (base_score)", fontsize=11) ax.margins(y=0.34) ax.grid(alpha=0.3, axis="y") star = "p < 0.001" if stat["p"] < 1e-3 else f"p = {stat['p']:.3f}" ax.set_title(f"{stat['name']}\n" f"Mann-Whitney {star} · CLES = {stat['cles']:.2f}", fontsize=11, fontweight="bold") def main(): lines = ["exp0 — does using rationalist dialect predict higher karma?", "Group split: 'any dialect' = >=1 dialect-term match in the doc.", "Posts: 2022-2025 window (comparable recent era).", "Comments: full crawl, which is a recent ~May-2026 snapshot only.", "=" * 60, ""] posts = load(DATA / "alignmentforum_posts.jsonl", year_range=(2022, 2025)) comments = load(DATA / "alignmentforum_comments.jsonl", year_range=None) s_posts = analyze("Alignment Forum POSTS (2022-2025)", posts, lines) s_comments = analyze("Alignment Forum COMMENTS (2026 snapshot)", comments, lines) txt = "\n".join(lines) print(txt) (RES / "dialect_vs_none.txt").write_text(txt + "\n") print(f"\nwrote {RES / 'dialect_vs_none.txt'}") fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5.8)) panel(ax1, s_posts, "tab:blue") panel(ax2, s_comments, "tab:orange") fig.suptitle("Alignment Forum: documents using rationalist dialect outrank " "documents using none\n" "median karma, bootstrap 95% CI · rank-based test (karma is heavy-tailed)", fontsize=12.5, fontweight="bold") fig.tight_layout(rect=(0, 0, 1, 0.91)) out = FIG / "dialect_vs_none_karma.png" fig.savefig(out, dpi=140) plt.close(fig) print(f"wrote {out}") if __name__ == "__main__": main()