"""Headline plot for exp0: the within-posts karma effect. Comparing AF posts only to AF posts, denser rationalist dialect still tracks modestly higher karma. This isolates the real effect from the posts-vs-comments confound that inflates the pooled correlation. Output: figures/headline_within_posts_karma.png """ 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 COMPILED, count_all_terms, word_count DATA = Path(PROJECT_DIR) / "data" FIG = Path(PROJECT_DIR) / "figures" FIG.mkdir(parents=True, exist_ok=True) START_YEAR = 2022 def load_posts(): rows = [] with open(DATA / "alignmentforum_posts.jsonl") 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) rate = sum((c / wc) * 10000 for c in counts.values()) rows.append({"id": p["id"], "posted_at": p.get("posted_at"), "base_score": p.get("base_score"), "dialect_rate": rate}) 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") # posts only, 2022-2025 (drop the partial-2026 crawl artifact), valid karma df = df[(df["year"] >= START_YEAR) & (df["year"] <= 2025)] df = df.dropna(subset=["base_score"]).reset_index(drop=True) return df def main(): df = load_posts() n = len(df) rho, p = stats.spearmanr(df["dialect_rate"], df["base_score"]) pear_r, pear_p = stats.pearsonr(df["dialect_rate"], df["base_score"]) print(f"AF posts only, 2022-2025: n={n}") print(f" Spearman rho={rho:+.3f} (p={p:.2g})") print(f" Pearson r ={pear_r:+.3f} (p={pear_p:.2g})") bins = [-0.001, 0, 5, 15, 30, 1e6] labels = ["0", "(0, 5]", "(5, 15]", "(15, 30]", "> 30"] df["bin"] = pd.cut(df["dialect_rate"], bins=bins, labels=labels) g = df.groupby("bin", observed=True).agg( mean_karma=("base_score", "mean"), median_karma=("base_score", "median"), std=("base_score", "std"), n=("base_score", "count"), ).reindex(labels) ci = 1.96 * g["std"] / np.sqrt(g["n"].clip(lower=1)) fig, ax = plt.subplots(figsize=(9, 5.5)) x = np.arange(len(labels)) ax.bar(x, g["mean_karma"], 0.62, yerr=ci, capsize=5, color="tab:blue", alpha=0.88, label="mean karma (±95% CI)", error_kw={"elinewidth": 1.4, "ecolor": "black"}) ax.plot(x, g["median_karma"], "D--", color="tab:orange", markersize=8, linewidth=1.8, label="median karma") for i in x: top = g["mean_karma"].iloc[i] + (ci.iloc[i] if not np.isnan(ci.iloc[i]) else 0) ax.text(i, top + 2, f"n={int(g['n'].iloc[i])}", ha="center", va="bottom", fontsize=9, color="dimgray") ax.set_xticks(x) ax.set_xticklabels(labels) ax.set_xlabel("rationalist-dialect density (matches / 10k words, binned)", fontsize=11) ax.set_ylabel("post karma (base_score)", fontsize=11) ax.set_title("Within Alignment Forum posts, denser rationalist dialect\n" "tracks modestly higher karma", fontsize=13, fontweight="bold") ax.legend(fontsize=10, loc="upper left") ax.grid(alpha=0.3, axis="y") ax.margins(y=0.34) ax.text(0.975, 0.965, f"posts only, 2022–2025 n = {n:,}\n" f"Spearman ρ = {rho:+.2f} (p = {p:.1g})", transform=ax.transAxes, ha="right", va="top", fontsize=10, bbox=dict(boxstyle="round,pad=0.45", facecolor="whitesmoke", edgecolor="gray")) fig.tight_layout() out = FIG / "headline_within_posts_karma.png" fig.savefig(out, dpi=140) plt.close(fig) print(f"wrote {out}") if __name__ == "__main__": main()