SPB Git

spb/wp44_uqo

Public
76.5 KB · 512 lines python
1#!/usr/bin/env python32"""WP44 — generate LaTeX tables (booktabs) from result files into manuscript/tables/*.tex. Every table is regenerated from3CSV/JSON artefacts; the inventory manuscript/tables/TABLES.json records source files and captions for Appendix G."""4import json, os, sys, csv, glob5import pandas as pd6R = sys.argv[1] if len(sys.argv) > 1 else os.path.dirname(os.path.dirname(os.path.abspath(__file__)))7OUT = os.path.join(R, "manuscript/tables"); os.makedirs(OUT, exist_ok=True); INV = []8910def tex_escape(s):11    s = str(s).replace("&", "\\&").replace("%", "\\%").replace("_", "\\_").replace("#", "\\#")12    for a, b in (("↔", "$\\leftrightarrow$"), ("→", "$\\rightarrow$"), ("…", "\\ldots{}"), ("∨", "$\\vee$"), ("∧", "$\\wedge$"), ("≥", "$\\geq$"), ("≤", "$\\leq$"), ("–", "--"), ("—", "---"), ("×", "$\\times$")):13        s = s.replace(a, b)14    return s151617def write(name, df, caption, label, sources, fmt=None, col_names=None, longtable=False, note=None):18    df = df.copy()19    if col_names: df.columns = col_names20    for c in df.columns:21        if pd.api.types.is_float_dtype(df[c]):22            df[c] = df[c].map(lambda v: "" if pd.isna(v) else (fmt or {}).get(c, "{:,.3f}").format(v).replace(",", "{,}"))23        elif pd.api.types.is_integer_dtype(df[c]):24            df[c] = df[c].map(lambda v: f"{v:,}".replace(",", "{,}"))25        else:26            df[c] = df[c].map(lambda v: tex_escape("" if pd.isna(v) else v))27    cols = "l" + "r" * (len(df.columns) - 1)28    head = " & ".join(f"\\textbf{{{tex_escape(c)}}}" for c in df.columns) + " \\\\"29    body = "\n".join(" & ".join(map(str, r)) + " \\\\" for r in df.itertuples(index=False))30    env = "longtable" if longtable else "tabular"31    s = f"% generated by tables/make_tables.py from {', '.join(sources)}\n"32    if longtable:33        s += f"\\begin{{longtable}}{{{cols}}}\n\\caption{{{caption}}}\\label{{{label}}}\\\\\n\\toprule\n{head}\n\\midrule\n\\endfirsthead\n\\toprule\n{head}\n\\midrule\n\\endhead\n{body}\n\\bottomrule\n"34        if note: s += f"\\multicolumn{{{len(df.columns)}}}{{p{{0.95\\linewidth}}}}{{\\footnotesize {note}}}\\\\\n"35        s += "\\end{longtable}\n"36    else:37        s += f"\\begin{{table}}[htbp]\\centering\\caption{{{caption}}}\\label{{{label}}}\n\\begin{{threeparttable}}\\small\n\\begin{{tabular}}{{{cols}}}\n\\toprule\n{head}\n\\midrule\n{body}\n\\bottomrule\n\\end{{tabular}}\n"38        if note: s += f"\\begin{{tablenotes}}\\footnotesize\\item {note}\\end{{tablenotes}}\n"39        s += "\\end{threeparttable}\\end{table}\n"40    open(os.path.join(OUT, name + ".tex"), "w").write(s); INV.append({"file": name + ".tex", "caption": caption, "label": label, "sources": sources, "rows": int(len(df))})414243def main():44    p = f"{R}/data/metadata/prisma_counts.json"45    if os.path.exists(p):46        P = json.load(open(p)); rows = [("Identified: OpenAlex works with a CS topic, 2018–2026 (snapshot 2026-10-14, both passes)", P["identified"]["openalex_total_records_loaded"])]47        labels = {"e1_outside_window": "E1 outside the window", "e2_type": "E2 non-research document type", "e3_xpac": "E3 XPAC expansion record (not DBLP-linked)", "e4_no_title": "E4 no title", "e5_duplicate": "E5 preprint merged into its published version", "e7_generic_deposit": "E7 generic deposit platform without DBLP/arXiv support"}48        rows += [("Excluded " + labels.get(k, k), v) for k, v in P["excluded_sequential"].items()]49        rows += [("After exclusions", P["after_exclusions"]), ("CS core (mapping corpus)", P["cs_core_eligible"]), ("CS penumbra (sensitivity set)", P["cs_penumbra_eligible_otherwise"]), ("Strict core: DBLP-indexed and primary field CS", P["strict_core_dblp_and_cs_primary"])]50        write("tab_prisma", pd.DataFrame(rows, columns=["Stage", "Records"]), "Record flow of the mapping corpus (PRISMA-style, sequential exclusions).", "tab:prisma", ["data/metadata/prisma_counts.json"])51        write("tab_eligible_by_year", pd.DataFrame(sorted(P["eligible_by_year"].items()), columns=["Year", "Eligible works"]), "Eligible works by publication year (2026 incomplete).", "tab:eligible_year", ["data/metadata/prisma_counts.json"])52        write("tab_eligible_by_type", pd.DataFrame(P["eligible_by_type"].items(), columns=["OpenAlex type", "Eligible works"]), "Eligible works by document type.", "tab:eligible_type", ["data/metadata/prisma_counts.json"])53    p = f"{R}/data/metadata/linkage_report.json"54    if os.path.exists(p):55        L = json.load(open(p)); rows = [("DBLP records 2018–2026", L["dblp_2018_2026"]), ("… with DOI", L["dblp_with_doi"]), ("DBLP ↔ OpenAlex links by DOI", L["link_dblp_oa"].get("doi", 0)), ("… by normalised title + year (+ first author)", L["link_dblp_oa"].get("title_year", 0)), ("DBLP records linked (distinct)", L["dblp_linked_distinct"]), ("DBLP records without OpenAlex record", L["dblp_unlinked"]),56                                       ("arXiv cs records created 2018–2026", L["arxiv_created_2018_2026"]), ("arXiv ↔ OpenAlex by arXiv id", L["link_arxiv_oa"].get("arxiv_id", 0)), ("… by DOI", L["link_arxiv_oa"].get("doi", 0)), ("… by title + year", L["link_arxiv_oa"].get("title_year", 0)), ("ACL entries 2018–2026", L["acl_2018_2026"]), ("ACL ↔ OpenAlex linked (2018–2026)", L["acl_linked_distinct_2018_2026"])]57        write("tab_linkage", pd.DataFrame(rows, columns=["Quantity", "Count"]), "Record linkage between sources.", "tab:linkage", ["data/metadata/linkage_report.json"])58    for f, name, cap, cols in [("volume_yearly", "tab_volume_yearly", "Yearly volume and composition of the eligible corpus.", ["year", "n", "n_dblp", "n_cs_primary", "n_arxiv", "n_abstract", "n_oa", "n_preprint", "n_conf", "n_article", "mean_authors", "mean_refs"]),59                               ("citation_windows_yearly", "tab_citation_windows", "Fixed-window citation statistics by publication year (c12: publication year + 1; c36: + 2 calendar years).", ["year", "n", "mean_c12", "mean_c36", "med_c36", "share_uncited_36", "p99_c36", "gini_c36", "gini_c12", "mean_fwci"]),60                               ("team_size_yearly", "tab_team_size", "Team size and collaboration by year.", ["year", "n", "mean_authors", "med_authors", "single", "five_plus", "ten_plus", "intl", "multi_inst"]),61                               ("industry_share_yearly", "tab_industry", "Works with a company affiliation by year.", ["year", "n_with_inst", "n_company", "share_company"]),62                               ("venue_hhi_yearly", "tab_venue_hhi", "Venue concentration by year.", ["year", "n", "n_sources", "hhi", "top1_share"]),63                               ("diversity_yearly", "tab_diversity", "Rao–Stirling and Leinster–Cobbold diversity of the category mix by year (bootstrap 95\\% CI).", ["year", "n", "rao_stirling", "rs_ci_low", "rs_ci_high", "leinster_cobbold_q2"]),64                               ("cagr_by_category", "tab_cagr", "Compound annual growth by category, baseline (2018–2022) and post (2023–2025).", ["category", "n_2018", "n_2022", "n_2025", "cagr_baseline", "cagr_post", "share_2018", "share_2025"])]:65        p = f"{R}/results/bibliometrics/{f}.csv"66        if os.path.exists(p):67            d = pd.read_csv(p)68            if "period" in d.columns: d = d[d.period.isin(["baseline", "post"])]69            d = d[[c for c in cols if c in d.columns]]70            if "team" in f or "volume" in f: d = d[d.iloc[:, 0] <= 2026]71            write(name, d, cap, f"tab:{name[4:]}", [f"results/bibliometrics/{f}.csv"], longtable=len(d) > 30)72    p = f"{R}/results/bibliometrics/countries_yearly.csv"73    if os.path.exists(p):74        d = pd.read_csv(p); top = d.groupby("country").n_frac.sum().nlargest(15).index; piv = d[d.country.isin(top)].pivot_table(index="country", columns="year", values="n_frac").loc[top]75        piv = piv.round(0).astype(int).reset_index(); write("tab_countries", piv, "Fractional output of the fifteen largest countries by year.", "tab:countries", [p])76    p = f"{R}/results/econometrics/breaks.csv"77    if os.path.exists(p):78        d = pd.read_csv(p); cols = ["series", "chatgpt_level", "chatgpt_level_p", "chatgpt_slope", "chatgpt_slope_p", "placebo_level_p", "placebo_slope_p", "bp_breaks_bic", "pelt"]79        write("tab_breaks", d[[c for c in cols if c in d.columns]], "Structural-change estimates by series: ITS level and slope changes at 2022-12 (HAC p-values), placebo p-values, Bai–Perron (BIC) and PELT break dates.", "tab:breaks", [p], longtable=len(d) > 25)80    p = f"{R}/taxonomy/validation/metrics.json"81    if os.path.exists(p):82        M = json.load(open(p)); rows = []83        for k, v in M.items():84            if isinstance(v, dict) and "per_category" in v:85                for c, m in v["per_category"].items():86                    rows.append({"comparison": k, "category": c, "precision": m["precision"], "recall": m["recall"], "f1": m["f1"], "tp": m["tp"], "fp": m["fp"], "fn": m["fn"]})87        if rows: write("tab_validation", pd.DataFrame(rows), "Taxonomy validation: precision, recall and F1 of the rule-based assignment against each rater and the rater consensus, by category.", "tab:validation", [p], longtable=True)88    for f in glob.glob(f"{R}/results/emerging/metrics_h*.json"):89        M = json.load(open(f)); rows = [{"model": m, "AUC": M[m]["auc"], "P@20": M[m]["precision_at_20"], "P@50": M[m]["precision_at_50"]} for m in ("zscore_baseline", "logistic", "gbm") if m in M]90        write("tab_emerging_h%d" % M["horizon"], pd.DataFrame(rows), f"Out-of-time performance of the emerging-topic detectors at horizon {M['horizon']} months (test cutoffs {M['test_cutoffs'][0]}–{M['test_cutoffs'][-1]}).", f"tab:emerging_h{M['horizon']}", [f])91    p = f"{R}/results/emerging/known_set_lead_times.csv"92    if os.path.exists(p):93        d = pd.read_csv(p)[["concept", "total_works", "detection_month", "peak_growth_month", "lead_months"]]; write("tab_known_set", d, "Preregistered known-emergence set: detection month, peak-growth month and lead time.", "tab:known_set", [p])94    tables_part08()  # Part VIII tables (appended 2026-11-03)95    tables_part08_categories()  # Part VIII category-level tables, corpus v3 (Agent L/I, 2026-11-03 20:15)96    tables_part05()  # Part V tables (Agent E, appended 2026-11-03)97    tables_part07b()  # Part VII-b security tables (Agent H, appended 2026-11-03)98    tables_part06()  # Part VI systems table (appended by Agent F, 2026-11-03)99    tables_part09()  # Part IX results tables (appended by the Part IX writer, 2026-11-03)100    tables_part07a()  # Part VII-a theory tables (Agent G, appended 2026-11-03)101    json.dump(INV, open(os.path.join(OUT, "TABLES.json"), "w"), indent=1); print(len(INV), "tables")102103104# ---------------- Part VIII (Scientific Knowledge Networks): tables appended by Agent L/I, 2026-11-03 ----------------105def _ascii(s, n=None):106    """Titles and venue names contain characters (U+2010, curly quotes, ...) that inputenc does not define; normalise to ASCII."""107    import unicodedata108    t = str(s).replace("‐", "-").replace("‑", "-").replace("–", "-").replace("—", "-").replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"').replace("×", "x")109    t = unicodedata.normalize("NFKD", t).encode("ascii", "ignore").decode("ascii").replace("$", "\\$").replace("^", "").replace("~", "-").replace("{", "").replace("}", "")110    return (t[: n - 3].rstrip() + "\\dots") if (n and len(t) > n) else t111112113def tables_part08():114    B = f"{R}/results/bibliometrics"; G = f"{R}/results/graph"115    p = f"{B}/team_size_yearly.csv"; q = f"{B}/international_collab_yearly.csv"116    if os.path.exists(p):117        d = pd.read_csv(p); d = d[d.year <= 2026]118        d["sum_authors"] = d.mean_authors * d.n119        g = d.groupby("year").agg(n=("n", "sum"), sum_authors=("sum_authors", "sum"), single=("single", "sum"), five_plus=("five_plus", "sum"), ten_plus=("ten_plus", "sum"), multi_inst=("multi_inst", "sum"), no_country=("no_country", "sum")).reset_index()120        t = pd.DataFrame({"Year": g.year, "Works": g.n, "Mean authors": g.sum_authors / g.n, "Single (%)": 100 * g.single / g.n, "5+ (%)": 100 * g.five_plus / g.n, "10+ (%)": 100 * g.ten_plus / g.n, "Multi-inst. (%)": 100 * g.multi_inst / g.n, "No country (%)": 100 * g.no_country / g.n})121        if os.path.exists(q):122            i = pd.read_csv(q); t = t.merge(pd.DataFrame({"Year": i.year, "Intl. (%)": 100 * i.share_intl}), on="Year", how="left")123        t["Year"] = t.Year.astype(str)124        write("tab_collaboration", t, "Team size and collaboration indicators by publication year (all eligible works; periods of the source file summed).", "tab:collaboration", [p, q], fmt={"Mean authors": "{:.3f}", "Single (%)": "{:.1f}", "5+ (%)": "{:.1f}", "10+ (%)": "{:.1f}", "Multi-inst. (%)": "{:.1f}", "No country (%)": "{:.1f}", "Intl. (%)": "{:.1f}"},125              note="Columns: works with one author, five or more, ten or more authors, and more than one institution. Shares are over all eligible works of the year, including works without affiliation data (column `No country'); the international share is over works with at least one resolved country (ICS, Part IV). 2026 is incomplete.")126    p = f"{B}/institution_types_yearly.csv"127    if os.path.exists(p):128        d = pd.read_csv(p); d = d[d.year <= 2026]; tot = d.groupby("year").n.transform("sum"); d["share"] = 100 * d.n / tot129        piv = d.pivot_table(index="itype", columns="year", values="share").fillna(0); piv = piv.loc[piv.sum(axis=1).sort_values(ascending=False).index].reset_index(); piv.columns = ["Institution type"] + [str(c) for c in piv.columns[1:]]130        write("tab_institution_types", piv, "Share of typed affiliations by OpenAlex institution type and year (per cent of affiliation-work pairs).", "tab:institution_types", [p], fmt={c: "{:.2f}" for c in piv.columns[1:]}, note="A work with affiliations of several types counts once under each type; shares therefore describe the mix of affiliation types, not of works. Types follow the OpenAlex institution ontology (education, facility, company, government, healthcare, nonprofit, funder, archive, other).")131    p = f"{B}/countries_yearly.csv"132    if os.path.exists(p):133        d = pd.read_csv(p); d = d[d.year <= 2026]; tot = d.groupby("year")[["n_full", "n_frac"]].sum()134        top = d.groupby("country").n_frac.sum().nlargest(15).index135        sh = d[d.country.isin(top)].copy(); sh["share"] = 100 * sh.n_frac / sh.year.map(tot.n_frac); piv = sh.pivot_table(index="country", columns="year", values="share").loc[top].reset_index(); piv.columns = ["Country"] + [str(c) for c in piv.columns[1:]]136        write("tab_country_shares", piv, "Share of fractional output of the fifteen largest countries by year (per cent).", "tab:country_shares", [p], fmt={c: "{:.2f}" for c in piv.columns[1:]}, note="Fractional counting: each work is divided equally among its distinct author countries, so the shares of all countries sum to 100 within a year. ISO 3166-1 alpha-2 codes. 2026 is incomplete.")137        rows = []138        for y, g in d.groupby("year"):139            pf = g.n_frac / g.n_frac.sum(); cn = g[g.country == "CN"]; us = g[g.country == "US"]140            rows.append({"Year": str(y), "Works": int(round(g.n_frac.sum())), "Countries": int(len(g)), "HHI": float((pf ** 2).sum()), "Top-5 (%)": 100 * pf.nlargest(5).sum(), "Top-10 (%)": 100 * pf.nlargest(10).sum(), "CN works (%)": 100 * float(cn.n_full.sum()) / g.n_frac.sum(), "US works (%)": 100 * float(us.n_full.sum()) / g.n_frac.sum(), "CN full/frac": float(cn.n_full.sum()) / float(cn.n_frac.sum()), "US full/frac": float(us.n_full.sum()) / float(us.n_frac.sum())})141        write("tab_country_concentration", pd.DataFrame(rows), "Concentration of output across countries by year, and the two largest producers under full counting.", "tab:country_concentration", [p], fmt={"HHI": "{:.4f}", "Top-5 (%)": "{:.1f}", "Top-10 (%)": "{:.1f}", "CN works (%)": "{:.2f}", "US works (%)": "{:.2f}", "CN full/frac": "{:.3f}", "US full/frac": "{:.3f}"},142              note="Works: fractional total of works with at least one country; Countries: number of countries with any output; HHI: Herfindahl--Hirschman index of fractional country shares; Top-5/Top-10: fractional share of the five and ten largest countries. CN/US works: share of works with at least one author in the country among works with a country (full counting); CN/US full/frac: ratio of the country's full count to its fractional count, which exceeds one by the extent to which its works are co-authored with other countries.")143    p = f"{B}/country_pairs_by_period.csv"144    if os.path.exists(p):145        d = pd.read_csv(p); d = d[d.period.isin(["baseline", "post"])]146        rows = []147        for per in ["baseline", "post"]:148            g = d[d.period == per]; w = g.n.sum(); cu = g[g.c1.isin(["CN", "US"]) & g.c2.isin(["CN", "US"])].n.sum(); st = pd.concat([g[["c1", "n"]].rename(columns={"c1": "c"}), g[["c2", "n"]].rename(columns={"c2": "c"})]).groupby("c").n.sum().sort_values(ascending=False)149            rows.append({"Period": per, "Edges": int(len(g)), "Countries": int(len(set(g.c1) | set(g.c2))), "Weight": int(w), "CN--US": int(cu), "CN--US (%)": 100 * cu / w, "Top strength": st.index[0] + ", " + st.index[1] + ", " + st.index[2]})150        write("tab_country_network", pd.DataFrame(rows), "The country co-authorship network by period: edges with at least fifty joint works.", "tab:country_network", [p], fmt={"CN--US (%)": "{:.2f}"}, note="Edges: country pairs with at least fifty joint works; Weight: total joint works over these edges; CN--US: weight of the China--United States edge and its share of the total; Top strength: the three countries with the largest strength (sum of edge weights). Baseline: 2018-01-01 to 2022-11-29; post: 2022-11-30 to 2026-11-02 (incomplete).")151        b = d[d.period == "baseline"].sort_values("n", ascending=False).head(20).reset_index(drop=True); q = d[d.period == "post"].sort_values("n", ascending=False).head(20).reset_index(drop=True)152        t = pd.DataFrame({"Rank": [str(i + 1) for i in range(20)], "Pair (baseline)": b.c1 + "--" + b.c2, "Joint works (baseline)": b.n.astype(int), "Pair (post)": q.c1 + "--" + q.c2, "Joint works (post)": q.n.astype(int)})153        write("tab_country_pairs", t, "The twenty strongest country pairs by period (number of joint works).", "tab:country_pairs", [p], note="Pairs are unordered; HK and MO are OpenAlex country codes for Hong Kong and Macau and are distinct from CN in the affiliation data. The post period is incomplete.")154    p = f"{B}/top_institutions_by_period.csv"155    if os.path.exists(p):156        d = pd.read_csv(p); b = d[d.period == "baseline"].set_index("inst_id"); q = d[d.period == "post"].set_index("inst_id"); j = b.join(q, lsuffix="_b", rsuffix="_p", how="inner")157        rows = []158        for per, g in [("baseline", b), ("post", q)]:159            pf = g.n_frac / g.n_frac.sum()160            rows.append({"Period": per, "Institutions": int(len(g)), "Fractional works": int(round(g.n_frac.sum())), "Full-count works": int(g.n_full.sum()), "Top-10 (%)": 100 * pf.nlargest(10).sum(), "Top-50 (%)": 100 * pf.nlargest(50).sum(), "Top-100 (%)": 100 * pf.nlargest(100).sum()})161        rows.append({"Period": "both periods", "Institutions": int(len(j)), "Fractional works": int(round(j.n_frac_b.sum())), "Full-count works": int(j.n_full_b.sum()), "Top-10 (%)": float("nan"), "Top-50 (%)": float("nan"), "Top-100 (%)": float("nan")})162        t = pd.DataFrame(rows); write("tab_institution_concentration", t, "Institutions with at least two hundred works per period: coverage and concentration (fractional counting).", "tab:institution_concentration", [p], fmt={"Top-10 (%)": "{:.2f}", "Top-50 (%)": "{:.2f}", "Top-100 (%)": "{:.2f}"},163              note=f"Institutions: number with at least two hundred works in the period; Top-10/50/100: fractional share of the largest listed institutions relative to the listed institutions, not to all works. The row `both periods' counts the institutions present in both lists (its work columns are their baseline totals); the Spearman rank correlation of their fractional counts across periods is {j.n_frac_b.rank().corr(j.n_frac_p.rank(), method='spearman'):.3f}.")164        top = j.sort_values("n_frac_p", ascending=False).head(25)165        t = pd.DataFrame({"OpenAlex id": ["I" + str(i) for i in top.index], "Full, base": top.n_full_b.astype(int).values, "Frac., base": top.n_frac_b.values, "Full, post": top.n_full_p.astype(int).values, "Frac., post": top.n_frac_p.values, "Ratio": (top.n_frac_p / top.n_frac_b).values})166        write("tab_top_institutions", t, "The twenty-five institutions with the largest fractional output in the post period, with their baseline output.", "tab:top_institutions", [p], fmt={"Frac., base": "{:,.0f}", "Frac., post": "{:,.0f}", "Ratio": "{:.2f}"}, longtable=False,167              note="Full and fractional counts in the baseline and post periods; Ratio is the post-to-baseline ratio of fractional counts. Institution names are not stored in the result file; the identifiers resolve at https://openalex.org/I<id>. The post period is about ten months shorter than the baseline, so a ratio below the corpus-wide ratio does not indicate decline.")168    p = f"{B}/top_sources_by_period.csv"169    if os.path.exists(p):170        d = pd.read_csv(p); d = d[d.period.isin(["baseline", "post"])]171        rows = []172        for per in ["baseline", "post"]:173            g = d[d.period == per]; bt = g.groupby("source_type").n.sum(); w = bt.sum()174            r = {"Period": per, "Sources": int(len(g)), "Works": int(w)}175            for ty in ["journal", "conference", "repository", "book series", "ebook platform"]:176                r[ty.replace("ebook platform", "ebook").replace("book series", "series") + " (%)"] = 100 * float(bt.get(ty, 0)) / w177            rows.append(r)178        write("tab_source_types", pd.DataFrame(rows), "Distribution of works over source types among the listed sources, by period (per cent).", "tab:source_types", [p], fmt={c: "{:.1f}" for c in ["journal (%)", "conference (%)", "repository (%)", "series (%)", "ebook (%)"]}, note="Source types are OpenAlex's (series = book series; ebook = ebook platform). The listed sources are those retained by the bibliometric script for each period; works whose primary source is not listed are excluded from the denominators.")179        b = d[d.period == "baseline"].sort_values("n", ascending=False).head(20).reset_index(drop=True); q = d[d.period == "post"].sort_values("n", ascending=False).head(20).reset_index(drop=True)180        t = pd.DataFrame({"Rank": [str(i + 1) for i in range(20)], "Source (baseline)": [_ascii(x, 30) for x in b.source_name], "Type": [_ascii(x).replace("ebook platform", "ebook").replace("book series", "series").replace("repository", "repos.").replace("conference", "conf.") for x in b.source_type], "Works": b.n.astype(int), "Source (post)": [_ascii(x, 30) for x in q.source_name], "Type ": [_ascii(x).replace("ebook platform", "ebook").replace("book series", "series").replace("repository", "repos.").replace("conference", "conf.") for x in q.source_type], "Works ": q.n.astype(int)})181        write("tab_top_sources", t, "The twenty largest sources (venues) by period, with OpenAlex source type.", "tab:top_sources", [p], longtable=True, note="Source names are OpenAlex display names, truncated; types abbreviated (repos. = repository, conf. = conference, series = book series, ebook = ebook platform).")182    p = f"{G}/cited_age_yearly.csv"183    if os.path.exists(p):184        d = pd.read_csv(p); rows = []185        for y, g in d.groupby("citing_year"):186            if y < 2018 or y > 2026: continue187            n = g.n.sum(); neg = g[g.age < 0].n.sum(); gg = g[g.age >= 0].sort_values("age"); w = gg.n.values; ag = gg.age.values188            import numpy as np189            cum = np.cumsum(w) / w.sum(); med = int(ag[np.searchsorted(cum, 0.5)])190            rows.append({"Citing year": str(y), "References": int(n), "Negative (%)": 100 * neg / n, "Mean age": float((w * ag).sum() / w.sum()), "Median": med, "0--2 y (%)": 100 * gg[gg.age <= 2].n.sum() / w.sum(), "0--5 y (%)": 100 * gg[gg.age <= 5].n.sum() / w.sum(), "over 10 y (%)": 100 * gg[gg.age > 10].n.sum() / w.sum()})191        write("tab_cited_age", pd.DataFrame(rows), "Age of cited works by citing year (resolved references of eligible works; corpus version of the result file at generation time).", "tab:cited_age", [p], fmt={"Negative (%)": "{:.2f}", "Mean age": "{:.2f}", "0--2 y (%)": "{:.1f}", "0--5 y (%)": "{:.1f}", "over 10 y (%)": "{:.1f}"},192              note="References: resolved references of eligible works of the citing year. Age is the citing year minus the cited work's publication year. Negative ages (cited work dated after the citing work: preprints cited before their published version, or year-only dates) are excluded from the age statistics and reported as a share. The 2026 row is incomplete.")193    p = f"{B}/top_cited_by_year.csv"194    if os.path.exists(p):195        d = pd.read_csv(p); d = d[(d.year >= 2018) & (d.year <= 2025) & (d.rk <= 10)].sort_values(["year", "rk"])196        t = pd.DataFrame({"Year": d.year.astype(str).values, "Rk": d.rk.astype(str).values, "Title (truncated)": [_ascii(x, 44) for x in d.title], "c36": d.c36.astype(int).values, "Total": d.cited_by_count.astype(int).values})197        write("tab_top_cited", t, "The ten most cited works of each publication year by 36-month window citations (c36), with total citations to date.", "tab:top_cited", [p], longtable=True, note="As recorded in OpenAlex (snapshot 2026-10-14 plus increment). Several entries are duplicate or misdated records of canonical works, or records whose citation counts are inconsistent with their total (c36 larger than the total, or a total of zero); they are kept because the table documents what the database returns, and are discussed in the text.")198    p = f"{B}/dblp_only_yearly.csv"199    if os.path.exists(p):200        d = pd.read_csv(p); piv = d.pivot_table(index="year", columns="rec_type", values="n", aggfunc="sum").fillna(0).astype(int); piv["total"] = piv.sum(axis=1); piv["with DOI (%)"] = 100 * d.groupby("year").with_doi.sum() / d.groupby("year").n.sum()201        piv = piv.reset_index(); piv["year"] = piv.year.astype(str); piv.columns = ["Year"] + [str(c) for c in piv.columns[1:]]202        write("tab_dblp_only", piv, "DBLP records of 2018--2026 without an OpenAlex counterpart, by DBLP record type and year.", "tab:dblp_only", [p], fmt={"with DOI (%)": "{:.1f}"}, note="These records are in DBLP but were not linked to any OpenAlex work by DOI, arXiv identifier or normalised title (Part IV). They are not in the eligible corpus; the table bounds what DBLP-based studies would see that this corpus does not.")203    p = f"{B}/indexing_lag.csv"204    if os.path.exists(p):205        d = pd.read_csv(p); d["year"] = d.pub_month.str[:4].astype(int); rows = []206        for y, g in d.groupby("year"):207            jan = g[g.pub_month.str.endswith("-01")]; jun = g[g.pub_month.str.endswith("-06")]208            rows.append({"Year": str(y), "Works": int(g.n.sum()), "Lag, Jan. (d)": float(jan.lag_days_p50.iloc[0]) if len(jan) else float("nan"), "Lag, June (d)": float(jun.lag_days_p50.iloc[0]) if len(jun) else float("nan"), "Within 90 d (%)": 100 * g.n_indexed_within_90d.sum() / g.n.sum(), "After 180 d (%)": 100 * g.n_indexed_after_180d.sum() / g.n.sum()})209        write("tab_indexing_lag", pd.DataFrame(rows), "The OpenAlex \\texttt{created\\_date} relative to the publication date, by publication year.", "tab:indexing_lag", [p], fmt={"Lag, Jan. (d)": "{:.0f}", "Lag, June (d)": "{:.0f}", "Within 90 d (%)": "{:.1f}", "After 180 d (%)": "{:.1f}"},210              note="Lag is created\\_date minus publication date; the two lag columns give the median lag in days for works published in January and in June of the year; the last two columns give the shares of the year's works whose record was created within 90 days and after 180 days of publication. The near-constant decline of the median by one month per publication month in 2018--2024 identifies a single creation date for most records (a re-ingestion), not an indexing delay; see Part III.")211    # ---- corpus v3 graph tables (appended by Agent L/M, 2026-11-03): reference coverage and field-level inflows ----212    p = f"{G}/reference_coverage_yearly.csv"213    if os.path.exists(p):214        d = pd.read_csv(p); d = d[(d.year >= 2018) & (d.year <= 2026)].copy(); res = d.n_internal + d.n_external215        t = pd.DataFrame({"Year": d.year.astype(str), "Works": d.n_works.astype(int), "Declared refs.": d.n_refs_declared.astype(int), "Refs./work": d.n_refs_declared / d.n_works, "Resolved (%)": 100 * res / d.n_refs_declared, "Internal": d.n_internal.astype(int), "External": d.n_external.astype(int), "Internal (%)": 100 * d.n_internal / res})216        write("tab_reference_coverage", t, "Reference coverage by citing year: declared, resolved, internal and external references of eligible works.", "tab:reference_coverage", [p], fmt={"Refs./work": "{:.2f}", "Resolved (%)": "{:.2f}", "Internal (%)": "{:.2f}"},217              note="Works: eligible works of the year (including works with no reference list); Declared: entries of their OpenAlex \\texttt{referenced\\_works} lists; Resolved: declared references that resolve to an OpenAlex record (internal = cited work in the eligible corpus; external = cited work outside it), as a share of the declared count; Internal (\\%): internal share of resolved references. The resolved share of 2025--2026 is higher than in earlier years because the recent cohorts carry fewer parsed references per work (reference extraction lags publication) and the parsed ones resolve more often; it describes the database, not citing behaviour. The 2026 row is incomplete.")218    p = f"{G}/field_flows_yearly.csv"219    if os.path.exists(p):220        d = pd.read_csv(p); d = d[(d.citing_year >= 2018) & (d.citing_year <= 2026)]; tot = d.groupby("citing_year").n.sum()221        names = {17: "CS", 22: "Eng.", 33: "Soc.", 27: "Med.", 26: "Math.", 18: "Dec.", 32: "Psy.", 31: "Phys."}222        ext = d[d.kind == "external"]; internal = d[d.kind == "internal"].groupby("citing_year").n.sum().reindex(tot.index).fillna(0)223        byf = ext.pivot_table(index="citing_year", columns="cited_field_id", values="n", aggfunc="sum").reindex(tot.index).fillna(0)224        cs = byf[17.0] if 17.0 in byf.columns else 0 * tot225        t = pd.DataFrame({"Year": [str(y) for y in tot.index], "Inside": 100 * internal.values / tot.values, "CS out": 100 * cs.values / tot.values, "Other": 100 * (tot.values - internal.values - cs.values) / tot.values})226        for fid in [22, 33, 27, 26, 18, 32, 31]:227            t[names[fid]] = 100 * (byf[float(fid)].values if float(fid) in byf.columns else 0) / tot.values228        write("tab_field_flows", t, "Destination of the resolved references of eligible works by citing year: inside the corpus, computer science outside it, and the seven largest other OpenAlex fields (per cent of resolved references).", "tab:field_flows", [p], fmt={c: "{:.2f}" for c in t.columns[1:]},229              note="Shares of all resolved references of the citing year. Inside: cited work is an eligible work (computer science, 2018--2026); CS out: cited work outside the corpus whose primary OpenAlex field is Computer Science (field 17; mostly pre-2018 work); Other: all remaining external references, including those without a field. The seven field columns are the largest components of `Other': Eng. = Engineering (OpenAlex field 22), Soc. = Social Sciences (33), Med. = Medicine (27), Math. = Mathematics (26), Dec. = Decision Sciences (18), Psy. = Psychology (32), Phys. = Physics and Astronomy (31). The rise of the inside-corpus share is mechanical: the corpus starts in 2018, so later citing years have more corpus to cite. The 2026 row is incomplete.")230231232def tables_part06():233    """Part VI — the eleven systems categories: primary-category counts and CAGR (cagr_by_category.csv) joined with the234    structural-change estimates of breaks.csv (ITS slope change at 2022-12, HAC p, placebo p, Bai–Perron BIC break dates)."""235    B = f"{R}/results/bibliometrics"; E = f"{R}/results/econometrics"236    cats = ["computer_architecture", "ai_accelerators", "operating_systems", "distributed_computing", "cloud_computing", "edge_computing", "computer_networks", "database_systems", "information_retrieval", "quantum_computing", "sustainable_computing"]237    names = {"computer_architecture": "Computer architecture", "ai_accelerators": "Accelerators and AI hardware", "operating_systems": "Operating systems", "distributed_computing": "Distributed computing", "cloud_computing": "Cloud computing", "edge_computing": "Edge computing", "computer_networks": "Computer networks", "database_systems": "Database systems", "information_retrieval": "Information retrieval", "quantum_computing": "Quantum computing", "sustainable_computing": "Sustainable computing"}238    p, q = f"{B}/cagr_by_category.csv", f"{E}/breaks.csv"239    if os.path.exists(p) and os.path.exists(q):240        c = pd.read_csv(p).set_index("category"); b = pd.read_csv(q).set_index("series"); rows = []241        for k in cats:242            if k not in c.index: continue243            r = c.loc[k]; s = b.loc["cat_" + k] if ("cat_" + k) in b.index else None244            rows.append({"Category": names[k], "n 2018": int(r.n_2018), "n 2022": int(r.n_2022), "n 2025": int(r.n_2025), "CAGR base": float(r.cagr_baseline), "CAGR post": float(r.cagr_post),245                         "Slope ch.": float(s.chatgpt_slope) if s is not None else float("nan"), "p": float(s.chatgpt_slope_p) if s is not None else float("nan"),246                         "Placebo p": float(s.placebo_slope_p) if s is not None else float("nan"), "BP breaks": str(s.bp_breaks_bic) if s is not None else ""})247        write("tab_systems_categories", pd.DataFrame(rows), "The systems and infrastructure categories of Part VI: primary-category output, compound annual growth, and structural-change estimates of the monthly log-volume series.", "tab:systems_categories", [p, q],248              fmt={"CAGR base": "{:.3f}", "CAGR post": "{:.3f}", "Slope ch.": "{:.3f}", "p": "{:.3f}", "Placebo p": "{:.3f}"},249              note="Counts are eligible works whose primary category is the row category (multi-label memberships are larger). CAGR base: 2018 to 2022; CAGR post: 2023 to 2025 (complete years). Slope ch.: change in the monthly trend of the log-volume series at 2022-12 in the interrupted time-series model of Part IV, with its HAC p-value; Placebo p: share of placebo event dates whose slope statistic is at least as extreme; BP breaks: Bai--Perron break dates selected by BIC. 2026 is incomplete and excluded from the growth columns.")250251252253# ---------------- Part VII-b (security half of Part VII): tables appended by Agent H, 2026-11-03 ----------------254def tables_part07b():255    G = f"{R}/results/graph"; B = f"{R}/results/bibliometrics"; E = f"{R}/results/econometrics"256    SEC = ["cybersecurity", "applied_cryptography", "blockchain", "privacy_preserving_computation", "federated_learning"]257    NAMES = {"cybersecurity": "Cybersecurity", "applied_cryptography": "Applied cryptography", "blockchain": "Blockchain systems", "privacy_preserving_computation": "Privacy-preserving computation", "federated_learning": "Federated learning"}258    SHORT = {"cybersecurity": "Cyber.", "applied_cryptography": "Crypto.", "blockchain": "Blockch.", "privacy_preserving_computation": "Privacy", "federated_learning": "Fed. learn."}259    p = f"{G}/category_counts_yearly.csv"; agg = None260    if os.path.exists(p):261        d = pd.read_csv(p); d = d[d.category_id.isin(SEC)].groupby(["year", "category_id"])[["n_multilabel", "n_primary"]].sum().reset_index()262        agg = d263        t = pd.DataFrame({"Year": sorted(d.year.unique().astype(str))})264        for v, suffix in (("n_multilabel", " (all)"), ("n_primary", " (prim.)")):265            piv = d.pivot_table(index="year", columns="category_id", values=v, aggfunc="sum", fill_value=0).astype(int)266            for c in SEC: t[SHORT[c] + suffix] = piv[c].values267        write("tab_security_counts", t, "Eligible works in the five security-and-privacy categories by publication year: works carrying the category (all) and works whose primary category it is (prim.).", "tab:security_counts", [p], longtable=True,268              note="Counts of eligible works (Part III) per publication year, summed over the pre/baseline/post period labels of the result file. `all' counts every work to which the multi-label classifier assigns the category (a work can carry several categories); `prim.' counts works for which the category is the argmax of the assignment score (Part IV). Cyber. = cybersecurity; Crypto. = applied cryptography; Blockch. = blockchain systems; Privacy = privacy-preserving computation; Fed. learn. = federated learning. The 2026 row is incomplete (the corpus ends on 2026-11-02 and recent months are under-indexed).")269    # --- The three generators below were lost on 2026-11-03 ~20:06 in a concurrent edit of this file (Agent E's patch replaced270    # --- the slice between the two anchors it searched for, which crossed into this function). Reconstructed by Agent E from the271    # --- generated tab_security_summary.tex / tab_security_llm_cooccurrence.tex / tab_security_landmarks.tex; Agent H to verify.272    p = f"{E}/breaks.csv"; q = f"{G}/category_counts_yearly.csv"273    if os.path.exists(p) and agg is not None:274        b = pd.read_csv(p).set_index("series"); piv = agg.pivot_table(index="year", columns="category_id", values="n_multilabel", aggfunc="sum"); rows = []275        for c in SEC:276            s_ = b.loc["cat_" + c] if ("cat_" + c) in b.index else None277            rows.append({"Category": NAMES[c], "Works 2018": int(piv.loc[2018, c]), "Works 2025": int(piv.loc[2025, c]), "CAGR 18--22 (%)": 100 * ((piv.loc[2022, c] / piv.loc[2018, c]) ** 0.25 - 1), "CAGR 23--25 (%)": 100 * ((piv.loc[2025, c] / piv.loc[2023, c]) ** 0.5 - 1),278                         "Level 2022-12": float(s_.chatgpt_level) if s_ is not None else float("nan"), "p": float(s_.chatgpt_level_p) if s_ is not None else float("nan"), "Slope change": float(s_.chatgpt_slope) if s_ is not None else float("nan"), "p ": float(s_.chatgpt_slope_p) if s_ is not None else float("nan"),279                         "Placebo p (slope)": float(s_.placebo_slope_p) if s_ is not None else float("nan"), "Bai--Perron": str(s_.bp_breaks_bic) if s_ is not None else "", "PELT": str(s_.pelt).replace(";", ", ") if s_ is not None else ""})280        write("tab_security_summary", pd.DataFrame(rows), "Growth and structural-change summary for the five security-and-privacy categories (multi-label counts).", "tab:security_summary", [q, p], fmt={"CAGR 18--22 (%)": "{:.1f}", "CAGR 23--25 (%)": "{:.1f}", "Level 2022-12": "{:.3f}", "p": "{:.3f}", "Slope change": "{:.3f}", "p ": "{:.3f}", "Placebo p (slope)": "{:.3f}"},281              note="Works: eligible works carrying the category (multi-label). CAGR: compound annual growth of the multi-label count between the years shown (2026 excluded as incomplete). Level and slope change: interrupted-time-series estimates on the log monthly series at the 2022-12 reference month with HAC p-values (Part IV, Section~\\ref{sec:m-its}); Placebo p: share of placebo event months whose slope t-statistic exceeds the one at 2022-12 (Section~\\ref{sec:m-placebo}); Bai--Perron: BIC-selected break months (Section~\\ref{sec:m-bp}); PELT: penalised change-point months. The ITS, placebo and break columns are those of Table~\\ref{tab:breaks}.")282    p = f"{G}/category_cooccurrence_yearly.csv"283    if os.path.exists(p) and agg is not None:284        co = pd.read_csv(p); piv = agg.pivot_table(index="year", columns="category_id", values="n_multilabel", aggfunc="sum")285        def pair(a_, b_):286            m = co[((co.cat_a == a_) & (co.cat_b == b_)) | ((co.cat_a == b_) & (co.cat_b == a_))].groupby("year").n.sum(); return m287        pairs = [("cybersecurity", "llm", "LLM"), ("cybersecurity", "ai_safety", "AI safety"), ("cybersecurity", "ai_agents", "AI agents"), ("applied_cryptography", "llm", "LLM"), ("blockchain", "llm", "LLM"), ("privacy_preserving_computation", "llm", "LLM"), ("federated_learning", "llm", "LLM")]288        years = sorted(y for y in piv.index if y <= 2026); t = pd.DataFrame({"Year": [str(y) for y in years]})289        for sc, ac, lab in pairs:290            m = pair(sc, ac); t[f"{SHORT[sc]} x {lab}"] = [int(m.get(y, 0)) for y in years]; t[f"{SHORT[sc]} x {lab} (%)"] = [100 * m.get(y, 0) / piv.loc[y, sc] if piv.loc[y, sc] else 0.0 for y in years]291        write("tab_security_llm_cooccurrence", t, "Co-classification of security-and-privacy works with the LLM, AI-safety and AI-agents categories, by publication year: number of works carrying both categories and share of the security category's works.", "tab:security_llm_cooccurrence", [p, q], fmt={c: "{:.1f}" for c in t.columns if c.endswith("(%)")}, longtable=True,292              note="A work is co-classified when the multi-label classifier assigns both categories (Part IV). Shares are relative to all eligible works carrying the security category in the year (multi-label count). Non-zero counts before 2022 reflect the breadth of the keyword patterns of the AI categories (for example `language model' matches pre-transformer work), not the use of LLMs; the table should be read for its trend, not its level. The 2026 row is incomplete.")293    p = f"{R}/literature_synthesis/landmarks/security_privacy_landmarks.csv"294    if os.path.exists(p):295        d = pd.read_csv(p, dtype={"doi": str}); rows = []296        for c in SEC:297            x = d[d.primary_category == c]298            rows.append({"Category": NAMES[c], "Works": len(x), "Post-period": int((x.period == "post").sum()), "Dated 2026": int((x.year == 2026).sum()), "Articles": int(x.type.isin(["article", "review"]).sum()), "Conf.": int((x.type == "conference-paper").sum()), "Preprints": int((x.type == "preprint").sum()),299                         "Grey": int(x.type.isin(["dissertation", "report", "book-chapter", "book"]).sum()), "Abstract": int(x.has_abstract.astype(str).eq("True").sum()), "No DOI": int(x.doi.isna().sum() + (x.doi.astype(str).str.strip() == "").sum())})300        write("tab_security_landmarks", pd.DataFrame(rows), "Composition of the automatically selected landmark set of the security-and-privacy area, by category.", "tab:security_landmarks", [p],301              note="Landmarks are the works with the highest field-normalised 36-month citation score (NCS36; 2025--2026 works ranked by 12-month citations) within each primary category, with a floor of fifteen per category, plus the 200 most cited works of the corpus overall (\\texttt{literature\\_synthesis/select\\_landmarks.py}). Grey = dissertations, reports, book chapters and books as typed by OpenAlex. Abstract = works whose abstract is available in the metadata; the synthesis of Part VII reads these abstracts only, never full texts. The set is flagged for principal-investigator review; Part VII documents the records that are duplicates, misdated or misclassified.")302303304# ---------------- Part V (The Artificial Intelligence Transformation): tables appended by Agent E, 2026-11-03 ----------------305AI_CATS = ["llm", "foundation_models", "multimodal_ai", "generative_ai", "ai_agents", "reinforcement_learning", "ml_theory", "deep_learning_architectures", "ai_safety"]306AI_NAMES = {"llm": "Large language models", "foundation_models": "Foundation models", "multimodal_ai": "Multimodal AI", "generative_ai": "Generative AI", "ai_agents": "AI agents", "reinforcement_learning": "Reinforcement learning", "ml_theory": "ML theory", "deep_learning_architectures": "DL architectures", "ai_safety": "AI safety and alignment"}307AI_SHORT = {"llm": "LLM", "foundation_models": "Foundation", "multimodal_ai": "Multimodal", "generative_ai": "Generative", "ai_agents": "Agents", "reinforcement_learning": "RL", "ml_theory": "ML theory", "deep_learning_architectures": "DL arch.", "ai_safety": "AI safety"}308309310def tables_part05():311    B = f"{R}/results/bibliometrics"; G = f"{R}/results/graph"; E = f"{R}/results/econometrics"; S = f"{R}/literature_synthesis"312    p = f"{B}/cagr_by_category.csv"313    if os.path.exists(p):314        d = pd.read_csv(p).drop_duplicates("category"); d = d[d.category.isin(AI_CATS)].set_index("category").loc[AI_CATS].reset_index()315        t = pd.DataFrame({"Category": d.category.map(AI_SHORT), "2018": d.n_2018, "2022": d.n_2022, "2023": d.n_2023, "2025": d.n_2025, "CAGR 18--22": d.cagr_baseline, "CAGR 23--25": d.cagr_post, "Share 2018": 100 * d.share_2018, "Share 2022": 100 * d.share_2022, "Share 2025": 100 * d.share_2025})316        write("tab_ai_growth", t, "Volume, compound annual growth and corpus share of the nine AI categories, baseline (2018--2022) and post (2023--2025) periods.", "tab:ai_growth", [p], fmt={"CAGR 18--22": "{:.3f}", "CAGR 23--25": "{:.3f}", "Share 2018": "{:.2f}", "Share 2022": "{:.2f}", "Share 2025": "{:.2f}"},317              note="Counts and shares as stored in the source file (works whose primary category is the row category; shares in per cent of all eligible works of the year). CAGR as in Part IV, eq.~\\ref{eq:cagr}; the post-period CAGR uses the 2023 and 2025 end points. Category abbreviations: LLM = large language models; Foundation = foundation models; Generative = generative AI; Agents = AI agents; RL = reinforcement learning; DL arch. = deep-learning architectures; AI safety = AI safety and alignment.")318    p = f"{G}/category_counts_yearly.csv"319    if os.path.exists(p):320        d = pd.read_csv(p); d = d[d.category_id.isin(AI_CATS) & (d.year <= 2026)].groupby(["category_id", "year"]).n_multilabel.sum().unstack("year").loc[AI_CATS]321        d.columns = [str(c) for c in d.columns]; d = d.reset_index(); d["category_id"] = d.category_id.map(AI_SHORT); d = d.rename(columns={"category_id": "Category"})322        write("tab_ai_counts", d, "Yearly multi-label counts of the nine AI categories (all period rows summed; 2026 incomplete).", "tab:ai_counts", [p], note="Multi-label counts: a work counts in every category it is assigned to. The source file splits each year into period rows (baseline / pre / post relative to 30 November 2022); they are summed here. 2026 covers publications dated up to the snapshot of 14 October 2026. Category abbreviations as in Table~\\ref{tab:ai_growth}.")323    p = f"{E}/breaks.csv"324    if os.path.exists(p):325        d = pd.read_csv(p); d = d[d.series.isin(["cat_" + c for c in AI_CATS])].set_index("series").loc[["cat_" + c for c in AI_CATS]].reset_index()326        dates = lambda col: d[col].fillna("").astype(str).str.replace("-01;", ";").str.replace(r"-01$", "", regex=True).str.replace(";", "; ")327        t = pd.DataFrame({"Category": d.series.str[4:].map(AI_SHORT), "Level": d.chatgpt_level, "p (level)": d.chatgpt_level_p, "Slope": d.chatgpt_slope, "p (slope)": d.chatgpt_slope_p, "Placebo p (level)": d.placebo_level_p, "Placebo p (slope)": d.placebo_slope_p, "Bai--Perron": dates("bp_breaks_bic"), "PELT": dates("pelt")})328        write("tab_ai_breaks", t, "Structural change at 30 November 2022 in the nine AI categories: interrupted-time-series level and slope changes, placebo p-values, Bai--Perron and PELT break dates.", "tab:ai_breaks", [p], fmt={c: "{:.3f}" for c in ["Level", "p (level)", "Slope", "p (slope)", "Placebo p (level)", "Placebo p (slope)"]},329              note="Monthly log counts, seasonally adjusted; HAC p-values (Part IV, Section~\\ref{sec:m-its}). Level change in log points of the monthly count at 2022-12; slope change in log points per month. Placebo p-values: share of placebo event dates (Section~\\ref{sec:m-placebo}) whose t-statistic exceeds the true one. Bai--Perron: break months selected by BIC with trimming h = 15 months; PELT: penalised exact linear-time change points. Categories are multi-label, so the series overlap. Category abbreviations as in Table~\\ref{tab:ai_growth}.")330        t = pd.DataFrame({"Category": d.series.str[4:].map(AI_SHORT), "GPT-3 (2020-06)": d.gpt3_level, "p": d.gpt3_level_p, "DALL-E 2 (2022-05)": d.dalle2_level, "p ": d.dalle2_level_p, "GPT-4 (2023-04)": d.gpt4_level, "p  ": d.gpt4_level_p, "o1 (2024-10)": d.o1_level, "p   ": d.o1_level_p})331        write("tab_ai_altdates", t, "Interrupted-time-series level changes of the nine AI categories at the alternative event dates (GPT-3, DALL-E 2, GPT-4, o1).", "tab:ai_altdates", [p], fmt={c: "{:.3f}" for c in t.columns[1:]},332              note="Each column pair is a separate ITS fit with the event moved to the stated month (Part IV, Section~\\ref{sec:m-altdates}); level change in log points, HAC p-value to its right. Category abbreviations as in Table~\\ref{tab:ai_growth}.")333    p = f"{G}/category_flows_yearly.csv"334    if os.path.exists(p):335        d = pd.read_csv(p); rows = []336        for c in AI_CATS:337            for y in (2019, 2022, 2025):338                s_ = d[(d.citing_cat == c) & (d.citing_year == y)].set_index("cited_cat").row_share339                rows.append({"Category": AI_SHORT[c], "Year": str(y), "Self": 100 * s_.get(c, 0), "LLM": 100 * s_.get("llm", 0), "NLP": 100 * s_.get("nlp", 0), "Vision": 100 * s_.get("computer_vision", 0), "HCI": 100 * s_.get("hci", 0), "Robotics": 100 * s_.get("robotics", 0), "Softw. eng.": 100 * s_.get("software_engineering", 0), "AI safety": 100 * s_.get("ai_safety", 0)})340        t = pd.DataFrame(rows); write("tab_ai_flows", t, "Destination of the in-corpus references of the nine AI categories in 2019, 2022 and 2025 (per cent of in-corpus references of the citing category).", "tab:ai_flows", [p], fmt={c: "{:.1f}" for c in ["Self", "LLM", "NLP", "Vision", "HCI", "Robotics", "Softw. eng.", "AI safety"]}, longtable=True,341              note="Row shares of category-to-category citation flows (Part IV, eq.~\\ref{eq:flow}); references outside the eligible corpus are excluded. `Self' is the share going to the citing category itself (for LLM the Self and LLM columns coincide). Categories are multi-label, so a reference can count under several destination categories. Category abbreviations as in Table~\\ref{tab:ai_growth}.")342    p = f"{S}/agent_E/contributions.csv"343    if os.path.exists(p):344        d = pd.read_csv(p, dtype={"openalex_id": str})345        piv = pd.crosstab(d.primary_category.map(AI_NAMES), d.data_quality_flag).loc[[AI_NAMES[c] for c in AI_CATS]]346        piv["total"] = piv.sum(axis=1); piv = piv.reset_index().rename(columns={"primary_category": "Primary category"})347        write("tab_ai_landmark_flags", piv, "Specialist screening of the 234 AI/ML landmark candidates: records by primary category and data-quality flag.", "tab:ai_landmark_flags", [p], note="Flags assigned by Agent E from title, venue, identifiers, citation counts and (where available) the abstract: identifier\\_mismatch = title/abstract do not correspond to the arXiv identifier or citation count attached to the record; abstract\\_mismatch = stored abstract belongs to another work; year\\_implausible = OpenAlex year contradicts the first publication; normalisation\\_artefact = very small c36 with very large NCS36; off\\_scope = not an AI contribution; no\\_abstract = metadata only. `ok' records were judged from the abstract.")348        ct = pd.crosstab(d.primary_category.map(AI_NAMES), d.contribution_type).loc[[AI_NAMES[c] for c in AI_CATS]]; ct["total"] = ct.sum(axis=1); ct = ct.reset_index().rename(columns={"primary_category": "Primary category"})349        write("tab_ai_contribution_types", ct, "Contribution type of the 234 AI/ML landmark candidates by primary category (specialist judgement from abstract or metadata).", "tab:ai_contribution_types", [p], note="Types follow CLAUDE.md~\\S1 item 6: theory, method, empirical, benchmark, engineering, survey. Judged from the abstract for 190 records and from title/venue/type for 44 records without abstract (column judged\\_from of the source file).")350        f = d[["openalex_id", "year", "type", "primary_category", "c36", "ncs36", "contribution_type", "data_quality_flag"]].copy(); f["primary_category"] = f.primary_category.map(AI_SHORT); f["c36"] = f.c36.astype(int); f["year"] = f.year.astype(str); f["data_quality_flag"] = f.data_quality_flag.str.replace("_", " ")351        f.columns = ["OpenAlex id", "Year", "Type", "Category", "c36", "NCS36", "Contribution", "Flag"]352        write("tab_ai_landmarks", f, "The 234 AI/ML landmark candidates with the specialist's contribution type and data-quality flag (titles in literature\\_synthesis/agent\\_E/contributions.csv).", "tab:ai_landmarks", [p], fmt={"NCS36": "{:.1f}"}, longtable=True, note="Selection score and windows as in Part IV (Section~\\ref{sec:m-score}); c36 and NCS36 as stored in the landmark file. Category abbreviations as in Table~\\ref{tab:ai_growth}.")353354355def tables_part09():356    """PLACEHOLDER (Agent E, 2026-11-03 ~20:10): the Part IX generator (21 tab_p9_*.tex tables, generated 20:05) was lost in the357    concurrent edits of this file described above and must be re-appended by the Part IX writer; the existing tab_p9_*.tex files358    are left untouched meanwhile. Remove this placeholder when the real function is restored."""359    print("WARNING: tables_part09() placeholder — Part IX table generator missing; existing tab_p9_*.tex not regenerated", file=sys.stderr)360361362# ---------------- Part VIII, corpus v3 category-level tables (appended by Agent L/I, 2026-11-03 20:15) ----------------363def tables_part08_categories():364    """Category flows, modularity, actor shares and citation inequality by primary category (results of the classification)."""365    import yaml, numpy as np366    B = f"{R}/results/bibliometrics"; G = f"{R}/results/graph"; onto = f"{R}/taxonomy/ontology.yaml"367    if not os.path.exists(onto): return368    o = yaml.safe_load(open(onto)); cname = {c["id"]: c["name"] for c in o["categories"]}; carea = {c["id"]: c["area"] for c in o["categories"]}; cnum = {c["id"]: c["number"] for c in o["categories"]}369    AREAS = ["ai_ml", "perception_interaction", "software_pl", "theory", "data_distributed", "security_privacy", "hardware_emerging", "computational_science"]370    ashort = {"ai_ml": "AI/ML", "perception_interaction": "Percept.", "software_pl": "Softw./PL", "theory": "Theory", "data_distributed": "Data/Distr.", "security_privacy": "Security", "hardware_emerging": "Hardware", "computational_science": "Comp. sci."}371    cats = sorted(cname, key=lambda c: cnum[c]); per = lambda y: "baseline" if y <= 2022 else "post"372    # 1. area flow matrices by period (row shares)373    p = f"{G}/area_flows_yearly.csv"374    if os.path.exists(p):375        d = pd.read_csv(p); d = d[(d.citing_year >= 2018) & (d.citing_year <= 2026)].copy(); d["period"] = d.citing_year.map(per)376        g = d.groupby(["period", "citing_area", "cited_area"]).n.sum().unstack("cited_area").reindex(columns=AREAS).fillna(0)377        rows = []378        for pr in ["baseline", "post"]:379            for a in AREAS:380                r = g.loc[(pr, a)]; rows.append({"Period": pr, "Citing area": ashort[a], **{ashort[b]: 100 * r[b] / r.sum() for b in AREAS}})381        write("tab_net_area_flows", pd.DataFrame(rows), "Citation-flow matrices between the eight areas of the ontology by period: share of each citing area's internal references received by each cited area (per cent).", "tab:net_area_flows", [p], fmt={ashort[b]: "{:.1f}" for b in AREAS},382              note="Internal references with a primary category at both ends, pooled over citing years 2018--2022 (baseline) and 2023--2026 (post, incomplete); the citing year 2022 contains one post-boundary month. Rows sum to 100. Area abbreviations: AI/ML = Artificial Intelligence and Machine Learning; Percept. = Perception, Language, Robotics and Interaction; Softw./PL = Software, Programming Languages and Formal Methods; Data/Distr. = Data, Information and Distributed Systems; Security = Security, Privacy and Trust; Hardware = Hardware, Architecture and Emerging Computing; Comp. sci. = Computational Science and Discovery.")383    # 2. modularity and cross-area shares by year (raw and composition-adjusted)384    p = f"{G}/modularity_yearly.csv"; q = f"{G}/cross_area_share_yearly.csv"385    if os.path.exists(p) and os.path.exists(q):386        m = pd.read_csv(p); x = pd.read_csv(q); x = x[(x.citing_year >= 2018) & (x.citing_year <= 2026)]387        raw = x.groupby("citing_year").apply(lambda g: 100 * g.n_cross.sum() / g.n.sum()); bw = x[x.citing_year <= 2022].groupby("citing_area").n.sum(); bw = bw / bw.sum()388        adj = 100 * x.pivot_table(index="citing_year", columns="citing_area", values="share_cross").mul(bw, axis=1).sum(axis=1)389        m = m[(m.year >= 2018) & (m.year <= 2026)]390        t = pd.DataFrame({"Year": m.year.astype(str), "Internal citations": m.edges.astype(int), "Q (categories)": m.Q_categories, "Q (areas)": m.Q_areas, "Self-share (%)": 100 * m.self_share, "Cross-area, raw (%)": m.year.map(raw), "Cross-area, adjusted (%)": m.year.map(adj)})391        bm = m[m.year <= 2022]; pm = m[m.year >= 2023]392        write("tab_net_modularity", t, "Modularity of the yearly category citation-flow network at the category and area partitions, the within-category self-share, and the aggregate cross-area share of internal references, raw and composition-adjusted.", "tab:net_modularity", [p, q], fmt={"Q (categories)": "{:.4f}", "Q (areas)": "{:.4f}", "Self-share (%)": "{:.2f}", "Cross-area, raw (%)": "{:.2f}", "Cross-area, adjusted (%)": "{:.2f}"},393              note=f"Equation~\\eqref{{eq:modularity}} at the fixed partitions (Section~\\ref{{sec:m-networks}}); the self-share is $\\operatorname{{tr}}(F_t)/m$. Cross-area, raw: share of all internal references of the citing year that leave the citing area (equation~\\eqref{{eq:cross-area}} aggregated over areas); adjusted: the same with the citing areas weighted by their baseline (2018--2022) shares of internal references, which removes the effect of the changing mix of citing areas. Period means of $Q$ at the category and area partitions: baseline {bm.Q_categories.mean():.4f} and {bm.Q_areas.mean():.4f}; post {pm.Q_categories.mean():.4f} and {pm.Q_areas.mean():.4f}. The 2018 network is small because few cited works of 2018 or later existed; 2026 is incomplete.")394    # 3. share of each category's internal references going to the AI/ML area, by year395    p = f"{G}/category_flows_yearly.csv"396    if os.path.exists(p):397        d = pd.read_csv(p); d = d[(d.citing_year >= 2018) & (d.citing_year <= 2026)].copy(); d["to_ai"] = d.cited_cat.map(carea) == "ai_ml"398        tot = d.groupby(["citing_cat", "citing_year"]).n.sum(); ai = d[d.to_ai].groupby(["citing_cat", "citing_year"]).n.sum().reindex(tot.index).fillna(0); s = (100 * ai / tot).unstack("citing_year")399        rows = [{"Category": cname[c], "Area": ashort[carea[c]], **{str(y): float(s.loc[c, y]) if c in s.index and y in s.columns else float("nan") for y in range(2018, 2027)}} for c in cats]400        t = pd.DataFrame(rows); write("tab_net_category_to_ai", t, "Share of each category's internal references received by the nine categories of the AI/ML area, by citing year (per cent).", "tab:net_category_to_ai", [p], fmt={str(y): "{:.1f}" for y in range(2018, 2027)}, longtable=True,401              note="Rows: citing primary category (ontology order); the nine AI/ML rows measure within-area citation, the other thirty-one rows measure citation into the AI/ML area. Denominator: the category's internal references with a classified cited work in the citing year. 2026 is incomplete.")402    # 4. actor shares by category and period, and AI/ML area against the rest403    p = f"{B}/category_actors_yearly.csv"404    if os.path.exists(p):405        a = pd.read_csv(p); a = a[a.period.isin(["baseline", "post"])].copy()406        for c in ["cn", "us", "company", "intl", "arxiv", "oa"]: a[c] = a["share_" + c] * a.n407        g = a.groupby(["primary_category", "period"])[["n", "cn", "us", "company", "intl"]].sum()408        for c in ["cn", "us", "company", "intl"]: g[c] = 100 * g[c] / g.n409        rows = []410        for c in cats:411            if (c, "baseline") not in g.index or (c, "post") not in g.index: continue412            b = g.loc[(c, "baseline")]; q = g.loc[(c, "post")]413            rows.append({"Category": cname[c], "Works, base": int(b.n), "Works, post": int(q.n), "CN, base": b.cn, "CN, post": q.cn, "US, base": b.us, "US, post": q.us, "Comp., base": b.company, "Comp., post": q.company, "Intl., base": b.intl, "Intl., post": q.intl})414        ra = pd.DataFrame(rows); ra["ai"] = [carea[c] == "ai_ml" for c in cats if (c, "baseline") in g.index and (c, "post") in g.index]415        cnt = lambda col_b, col_p, ai: int(((ra[col_p] > ra[col_b]) & (ra.ai == ai)).sum()); nai = int(ra.ai.sum()); not_ = int((~ra.ai).sum())416        write("tab_net_category_actors", pd.DataFrame(rows), "Shares of works with a China-affiliated author, a United States-affiliated author, a company affiliation and authors in at least two countries, by primary category and period (per cent).", "tab:net_category_actors", [p], fmt={k: "{:.1f}" for k in ["CN, base", "CN, post", "US, base", "US, post", "Comp., base", "Comp., post", "Intl., base", "Intl., post"]}, longtable=True,417              note=f"Baseline: works dated 2018-01-01 to 2022-11-29; post: 2022-11-30 to 2026-11-02 (incomplete). Shares are over all works of the category, including works without affiliation data, so they are depressed where affiliation coverage is low (recent cohorts, preprint-heavy categories) and are not comparable with the typed-denominator shares of Tables~\\ref{{tab:industry}} and~\\ref{{tab:country_concentration}}; comparisons across periods within a category carry this caveat. Comp. = at least one company-typed affiliation; Intl. = at least two author countries. Categories whose post share exceeds their baseline share: China-affiliated, {cnt('CN, base', 'CN, post', True)} of the {nai} AI/ML categories and {cnt('CN, base', 'CN, post', False)} of the {not_} others; company, {cnt('Comp., base', 'Comp., post', True)} of {nai} and {cnt('Comp., base', 'Comp., post', False)} of {not_}; international, {cnt('Intl., base', 'Intl., post', True)} of {nai} and {cnt('Intl., base', 'Intl., post', False)} of {not_}.")418        a["grp"] = np.where(a.primary_category.map(carea) == "ai_ml", "AI/ML area", "Other areas"); h = a.groupby(["grp", "period"])[["n", "cn", "us", "company", "intl", "arxiv", "oa"]].sum()419        for c in ["cn", "us", "company", "intl", "arxiv", "oa"]: h[c] = 100 * h[c] / h.n420        rows = [{"Group": grp, "Period": pr, "Works": int(h.loc[(grp, pr)].n), "CN (%)": h.loc[(grp, pr)].cn, "US (%)": h.loc[(grp, pr)].us, "Company (%)": h.loc[(grp, pr)].company, "Intl. (%)": h.loc[(grp, pr)].intl, "arXiv (%)": h.loc[(grp, pr)].arxiv, "OA (%)": h.loc[(grp, pr)].oa} for grp in ["AI/ML area", "Other areas"] for pr in ["baseline", "post"]]421        write("tab_net_ai_vs_rest", pd.DataFrame(rows), "Actor shares of works whose primary category is in the AI/ML area against all other areas, by period (per cent).", "tab:net_ai_vs_rest", [p], fmt={k: "{:.2f}" for k in ["CN (%)", "US (%)", "Company (%)", "Intl. (%)", "arXiv (%)", "OA (%)"]},422              note="Works with a primary category, grouped by the area of that category; shares over all works of the group (works without affiliation data included), as in Table~\\ref{tab:net_category_actors}. arXiv: works linked to an arXiv record; OA: open access as recorded by OpenAlex. Periods as in Table~\\ref{tab:net_category_actors}.")423        yy = a.groupby(["grp", "year"])[["n", "cn", "company", "intl"]].sum()424        for c in ["cn", "company", "intl"]: yy[c] = 100 * yy[c] / yy.n425        rows = [{"Year": str(y), "CN, AI/ML (%)": yy.loc[("AI/ML area", y)].cn, "CN, other (%)": yy.loc[("Other areas", y)].cn, "Company, AI/ML (%)": yy.loc[("AI/ML area", y)].company, "Company, other (%)": yy.loc[("Other areas", y)].company, "Intl., AI/ML (%)": yy.loc[("AI/ML area", y)].intl, "Intl., other (%)": yy.loc[("Other areas", y)].intl} for y in range(2018, 2027) if ("AI/ML area", y) in yy.index]426        write("tab_net_ai_vs_rest_yearly", pd.DataFrame(rows), "China-affiliated, company-affiliated and international shares of works by year, AI/ML area against all other areas (per cent).", "tab:net_ai_vs_rest_yearly", [p], fmt={k: "{:.2f}" for k in ["CN, AI/ML (%)", "CN, other (%)", "Company, AI/ML (%)", "Company, other (%)", "Intl., AI/ML (%)", "Intl., other (%)"]},427              note="Shares over all works of the group and year, works without affiliation data included; the decline of all three series after 2023 is partly the lower affiliation coverage of the most recent cohorts (Section~\\ref{sec:net-teams}). 2026 is incomplete.")428    # 5. citation inequality by category (complete 36-month windows), and AI/ML area against the rest429    p = f"{B}/category_impact_yearly.csv"430    if os.path.exists(p):431        i = pd.read_csv(p); i = i[i.c36_complete == True].copy(); yrs = sorted(int(y) for y in i.year.unique()); last = max(yrs); base = [y for y in yrs if y <= 2022]432        pv = i.pivot_table(index="primary_category", columns="year", values="gini_c36"); un = i.pivot_table(index="primary_category", columns="year", values="share_uncited_36")433        rows = []434        for c in cats:435            if c not in pv.index: continue436            r = {"Category": cname[c], **{str(y): float(pv.loc[c, y]) if y in pv.columns else float("nan") for y in yrs}}437            bmean = pv.loc[c, base].mean(); r["Base mean"] = float(bmean); r[f"{last} $-$ base"] = float(pv.loc[c, last] - bmean) if last in pv.columns else float("nan")438            r[f"Uncited {last} (%)"] = 100 * float(un.loc[c, last]) if last in un.columns else float("nan"); rows.append(r)439        up = {g: int(sum(1 for c in cats if c in pv.index and last in pv.columns and pd.notna(pv.loc[c, last]) and carea[c] == g and pv.loc[c, last] > pv.loc[c, base].mean())) for g in ["ai_ml"]}; up["other"] = int(sum(1 for c in cats if c in pv.index and last in pv.columns and pd.notna(pv.loc[c, last]) and carea[c] != "ai_ml" and pv.loc[c, last] > pv.loc[c, base].mean()))440        tot_ai = sum(1 for c in cats if c in pv.index and last in pv.columns and pd.notna(pv.loc[c, last]) and carea[c] == "ai_ml"); tot_ot = sum(1 for c in cats if c in pv.index and last in pv.columns and pd.notna(pv.loc[c, last]) and carea[c] != "ai_ml")441        t = pd.DataFrame(rows); write("tab_net_category_gini", t, f"Gini coefficient of 36-month citations $c^{{(36)}}$ by primary category and publication year, for years with a complete window; baseline mean, change of the last complete year against it, and share uncited at 36 months in that year.", "tab:net_category_gini", [p], fmt={**{str(y): "{:.3f}" for y in yrs}, "Base mean": "{:.3f}", f"{last} $-$ base": "{:+.3f}", f"Uncited {last} (%)": "{:.1f}"}, longtable=True,442              note=f"Gini of $c^{{(36)}}$ over the works whose primary category is the row category (Section~\\ref{{sec:m-citations}}); a blank cell is a category with no works in the year. Base mean: mean over {base[0]}--{base[-1]}. The {last} window ends in {last + 2}, whose slower indexing channels were incomplete at the snapshot, so the {last} values carry the right-truncation caveat of Table~\\ref{{tab:citation_windows}}. Very small categories and categories whose {last} value is far from every earlier value may reflect single misattributed records (Section~\\ref{{sec:net-topcited}}). Count of categories whose {last} Gini exceeds their baseline mean: {up['ai_ml']} of the {tot_ai} AI/ML categories and {up['other']} of the {tot_ot} other categories.")443        i["grp"] = np.where(i.primary_category.map(carea) == "ai_ml", "AI/ML", "Other"); i["g"] = i.gini_c36 * i.n; i["u"] = i.share_uncited_36 * i.n; i["t10"] = i.share_top10_fwci * i.n; i["m"] = i.mean_c36 * i.n444        h = i.groupby(["grp", "year"])[["n", "g", "u", "t10", "m"]].sum()445        rows = [{"Year": str(y), "Works, AI/ML": int(h.loc[("AI/ML", y)].n), "Works, other": int(h.loc[("Other", y)].n), "Gini, AI/ML": h.loc[("AI/ML", y)].g / h.loc[("AI/ML", y)].n, "Gini, other": h.loc[("Other", y)].g / h.loc[("Other", y)].n, "Mean c36, AI/ML": h.loc[("AI/ML", y)].m / h.loc[("AI/ML", y)].n, "Mean c36, other": h.loc[("Other", y)].m / h.loc[("Other", y)].n, "Uncited, AI/ML (%)": 100 * h.loc[("AI/ML", y)].u / h.loc[("AI/ML", y)].n, "Uncited, other (%)": 100 * h.loc[("Other", y)].u / h.loc[("Other", y)].n, "Top decile FWCI, AI/ML (%)": 100 * h.loc[("AI/ML", y)].t10 / h.loc[("AI/ML", y)].n, "Top decile FWCI, other (%)": 100 * h.loc[("Other", y)].t10 / h.loc[("Other", y)].n} for y in yrs]446        write("tab_net_gini_ai_vs_rest", pd.DataFrame(rows), "Citation inequality and levels at 36 months, AI/ML area against all other areas, by publication year with a complete window.", "tab:net_gini_ai_vs_rest", [p], fmt={"Gini, AI/ML": "{:.3f}", "Gini, other": "{:.3f}", "Mean c36, AI/ML": "{:.2f}", "Mean c36, other": "{:.2f}", "Uncited, AI/ML (%)": "{:.1f}", "Uncited, other (%)": "{:.1f}", "Top decile FWCI, AI/ML (%)": "{:.1f}", "Top decile FWCI, other (%)": "{:.1f}"},447              note="Group statistics are work-weighted means of the category statistics of Table~\\ref{tab:net_category_gini} (the Gini is therefore a weighted mean of within-category Ginis, not the Gini of the pooled group). Top decile FWCI: share of works in the top decile of OpenAlex field-weighted citation impact. The last year carries the right-truncation caveat.")448449450451452# ---------------- Part VII-a (theory half of Part VII): tables appended by Agent G, 2026-11-03 ----------------453def tables_part07a():454    G = f"{R}/results/graph"; B = f"{R}/results/bibliometrics"; E = f"{R}/results/econometrics"455    THY = ["algorithms", "computational_complexity", "programming_languages", "compilers", "formal_verification", "software_engineering"]456    NAMES = {"algorithms": "Algorithms and data structures", "computational_complexity": "Computational complexity", "programming_languages": "Programming languages", "compilers": "Compilers", "formal_verification": "Formal verification", "software_engineering": "Software engineering"}457    SHORT = {"algorithms": "Algo.", "computational_complexity": "Compl.", "programming_languages": "PL", "compilers": "Comp.", "formal_verification": "FV", "software_engineering": "SE"}458    p = f"{G}/category_counts_yearly.csv"; agg = None459    if os.path.exists(p):460        d = pd.read_csv(p); d = d[d.category_id.isin(THY)].groupby(["year", "category_id"])[["n_multilabel", "n_primary"]].sum().reset_index(); agg = d461        t = pd.DataFrame({"Year": sorted(d.year.unique().astype(str))})462        for v, suffix in (("n_multilabel", " (all)"), ("n_primary", " (prim.)")):463            piv = d.pivot_table(index="year", columns="category_id", values=v, aggfunc="sum", fill_value=0).astype(int)464            for c in THY: t[SHORT[c] + suffix] = piv[c].values465        write("tab_theory_counts", t, "Eligible works in the six theory and software categories by publication year: works carrying the category (all) and works whose primary category it is (prim.).", "tab:theory_counts", [p], longtable=True,466              note="Counts of eligible works (Part III) per publication year, summed over the pre/baseline/post period labels of the result file; 2026 is incomplete. `all' counts every work to which the multi-label classifier assigns the category; `prim.' counts works whose highest-scoring category it is (Part IV). Algo. = algorithms and data structures, Compl. = computational complexity, PL = programming languages, Comp. = compilers, FV = formal verification, SE = software engineering.")467    p = f"{E}/breaks.csv"468    if os.path.exists(p) and agg is not None:469        b = pd.read_csv(p).set_index("series"); rows = []470        for c in THY:471            g = agg[agg.category_id == c].set_index("year")472            m18, m22, m23, m25 = (int(g.loc[y, "n_multilabel"]) if y in g.index else 0 for y in (2018, 2022, 2023, 2025)); r = b.loc[f"cat_{c}"]473            rows.append({"Category": NAMES[c], "Works 2018": m18, "Works 2025": m25, "CAGR 18--22 (%)": 100 * ((m22 / m18) ** 0.25 - 1) if m18 else float("nan"), "CAGR 23--25 (%)": 100 * ((m25 / m23) ** 0.5 - 1) if m23 else float("nan"),474                         "Level 2022-12": float(r.chatgpt_level), "p": float(r.chatgpt_level_p), "Slope change": float(r.chatgpt_slope), "p ": float(r.chatgpt_slope_p), "Placebo p (slope)": float(r.placebo_slope_p), "Bai--Perron": str(r.bp_breaks_bic).replace(";", ", "), "PELT": str(r.pelt).replace(";", ", ")})475        write("tab_theory_summary", pd.DataFrame(rows), "Growth and structural-change summary for the six theory and software categories (multi-label counts).", "tab:theory_summary", [f"{G}/category_counts_yearly.csv", p], fmt={"CAGR 18--22 (%)": "{:.1f}", "CAGR 23--25 (%)": "{:.1f}", "Level 2022-12": "{:.3f}", "p": "{:.3f}", "Slope change": "{:.4f}", "p ": "{:.3f}", "Placebo p (slope)": "{:.3f}"},476              note="Works: eligible works carrying the category (multi-label). CAGR: compound annual growth of the multi-label count between the years shown (2026 excluded as incomplete). Level and slope change: interrupted-time-series estimates on the log monthly count of works with the category as primary label, event month 2022-12, with HAC p-values (Part IV); placebo p: share of baseline-period pseudo-events whose slope t-statistic exceeds the observed one (Section~\\ref{sec:m-placebo}); Bai--Perron and PELT: estimated break dates (results/econometrics/breaks.csv). The ITS series are primary-label counts while the CAGR columns use multi-label counts; the two populations differ (Table~\\ref{tab:theory_counts}).")477    p = f"{G}/category_cooccurrence_yearly.csv"478    if os.path.exists(p) and agg is not None:479        d = pd.read_csv(p); rows = []480        for y in sorted(d.year.unique()):481            if y < 2018 or y > 2026: continue482            row = {"Year": str(y)}483            for a in THY:484                n = d[(d.year == y) & (((d.cat_a == a) & (d.cat_b == "llm")) | ((d.cat_a == "llm") & (d.cat_b == a)))].n.sum(); m = agg[(agg.year == y) & (agg.category_id == a)].n_multilabel.sum()485                row[f"{SHORT[a]} x LLM"] = int(n); row[f"{SHORT[a]} x LLM (%)"] = 100 * n / m if m else float("nan")486            rows.append(row)487        t = pd.DataFrame(rows)488        write("tab_theory_llm_cooccurrence", t, "Co-classification of theory and software works with the LLM category, by publication year: number of works carrying both categories and share of the category's multi-label count.", "tab:theory_llm_cooccurrence", [p, f"{G}/category_counts_yearly.csv"], fmt={c: "{:.1f}" for c in t.columns if "(%)" in c}, longtable=True,489              note="A work is co-classified when the multi-label classifier assigns both categories (Part IV). Shares are relative to all eligible works carrying the theory/software category in the year. Non-zero counts before 2022 reflect the lexical breadth of the LLM category (language-model and pretrained-model vocabulary), not retroactive labelling. 2026 is incomplete.")490    p = f"{R}/literature_synthesis/agent_G/contributions.csv"491    if os.path.exists(p):492        d = pd.read_csv(p); VERD = ["in_scope_research", "in_scope_survey", "textbook", "reprint_misdated", "dissertation", "metaheuristic", "misclassified", "duplicate"]493        VL = {"in_scope_research": "Research (in scope)", "in_scope_survey": "Survey / report (in scope)", "textbook": "Textbook / chapter", "reprint_misdated": "Re-deposited classic", "dissertation": "Thesis", "metaheuristic": "Metaphor metaheuristic", "misclassified": "Misclassified", "duplicate": "Duplicate record"}494        rows = []495        for v in VERD:496            g = d[d.verdict == v]; row = {"Verdict": VL[v]}497            for c in THY: row[SHORT[c]] = int((g.primary_category == c).sum())498            row["Total"] = int(len(g)); row["Post-period"] = int((g.period == "post").sum()); row["Id mismatch"] = int((g.id_resolves_to_other_work == "yes").sum()); rows.append(row)499        row = {"Verdict": "All candidates"}500        for c in THY: row[SHORT[c]] = int((d.primary_category == c).sum())501        row["Total"] = int(len(d)); row["Post-period"] = int((d.period == "post").sum()); row["Id mismatch"] = int((d.id_resolves_to_other_work == "yes").sum()); rows.append(row)502        write("tab_theory_landmark_audit", pd.DataFrame(rows), "Specialist audit of the automatically selected landmark candidates of the theory and software areas, by verdict and primary category.", "tab:theory_landmark_audit", [p, f"{R}/literature_synthesis/landmarks/theory_landmarks.csv", f"{R}/literature_synthesis/landmarks/software_pl_landmarks.csv"],503              note="Candidates are the works with the highest field-normalised 36-month citation score within each primary category (floor of fifteen per category) plus the 200 most cited works overall (\\texttt{literature\\_synthesis/select\\_landmarks.py}). Verdicts were assigned by Agent G from title, venue and type metadata and, where available, the abstract (never the full text); see literature_synthesis/agent_G/contributions.csv. `Id mismatch': the OpenAlex identifier of the record, resolved live on 2026-11-03, returned a different work whose citation count matches the record's 36-month window (literature_synthesis/agent_G/verification_lookups_raw.txt).")504        g = d[d.verdict.isin(["in_scope_research", "in_scope_survey"])].sort_values(["primary_category", "year"])505        t = pd.DataFrame({"Category": g.primary_category.map(SHORT), "Year": g.year.astype(str), "Type": g.type.str.replace("conference-paper", "conf.").str.replace("book-chapter", "chapter"), "Work": [_ascii(x, 88) for x in g.title], "Contribution": g.contribution_type, "Id mismatch": g.id_resolves_to_other_work})506        write("tab_theory_landmarks_discussed", t, "Landmark candidates of the theory and software areas retained as in-scope research or survey contributions, with the contribution type judged from the abstract or metadata.", "tab:theory_landmarks_discussed", [p], longtable=True,507              note="Contribution types follow the protocol (theory, method, empirical, benchmark, engineering, survey). `Id mismatch' as in Table~\\ref{tab:theory_landmark_audit}. Titles are shortened.")508509510if __name__ == "__main__":511    main()512
Files · f3ac605f769fce69cafdd85867168794149698fe
Menu

Theme