File size: 9,473 Bytes
b3b12cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reproduce Table 3 (cross-factor predictive validity) from the paper.

Reads only the released CSVs — no DB, no network.

Expected output (paper, n=35):
    GitHub stars (log)              rho_s = 0.52   p < 0.01
    VS Code installs (log)          rho_s = 0.44   p < 0.05
    Stack Overflow question volume  rho_s = 0.49   p < 0.01

Usage:
    python reproduce_table3.py [--csv-dir ../data/csv]
"""

import argparse
import csv
import json
import math
import sys
from pathlib import Path
from typing import Dict, List, Tuple


# ───────────────────────────────────────────────────────────────────────────────
# Tiny stats utilities (avoid scipy/pandas dependency for reviewer reproducibility)
# ───────────────────────────────────────────────────────────────────────────────
def _rank(values: List[float]) -> List[float]:
    """Average-rank a sequence, handling ties."""
    indexed = sorted(enumerate(values), key=lambda kv: kv[1])
    ranks = [0.0] * len(values)
    i = 0
    while i < len(indexed):
        j = i
        while j + 1 < len(indexed) and indexed[j + 1][1] == indexed[i][1]:
            j += 1
        avg = (i + j) / 2.0 + 1.0   # 1-indexed average rank
        for k in range(i, j + 1):
            ranks[indexed[k][0]] = avg
        i = j + 1
    return ranks


def spearman(xs: List[float], ys: List[float]) -> float:
    rx, ry = _rank(xs), _rank(ys)
    n = len(xs)
    mx, my = sum(rx) / n, sum(ry) / n
    num = sum((rx[i] - mx) * (ry[i] - my) for i in range(n))
    dx = math.sqrt(sum((rx[i] - mx) ** 2 for i in range(n)))
    dy = math.sqrt(sum((ry[i] - my) ** 2 for i in range(n)))
    return num / (dx * dy) if dx and dy else float("nan")


def two_sided_p(rho: float, n: int) -> float:
    """Approximate two-sided p-value via the t-distribution approximation."""
    if abs(rho) >= 1.0 or n < 4:
        return 0.0 if abs(rho) >= 1.0 else 1.0
    t = rho * math.sqrt((n - 2) / (1 - rho * rho))
    df = n - 2
    # Survival of |t| via Student-t CDF approx (good enough at df ≥ 10)
    x = df / (df + t * t)
    # Regularized incomplete beta via continued fraction
    return _student_t_sf(t, df) * 2


def _student_t_sf(t: float, df: int) -> float:
    """One-sided survival function of Student-t (|t|)."""
    t = abs(t)
    a = df / 2.0
    b = 0.5
    x = df / (df + t * t)
    return 0.5 * _betai(a, b, x)


def _betai(a: float, b: float, x: float) -> float:
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    bt = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
                  + a * math.log(x) + b * math.log(1.0 - x))
    if x < (a + 1.0) / (a + b + 2.0):
        return bt * _betacf(a, b, x) / a
    return 1.0 - bt * _betacf(b, a, 1.0 - x) / b


def _betacf(a: float, b: float, x: float, max_iter: int = 200, eps: float = 1e-12) -> float:
    qab, qap, qam = a + b, a + 1.0, a - 1.0
    c, d = 1.0, 1.0 - qab * x / qap
    if abs(d) < 1e-30: d = 1e-30
    d, h = 1.0 / d, 1.0 / d
    for m in range(1, max_iter + 1):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < 1e-30: d = 1e-30
        c = 1.0 + aa / c
        if abs(c) < 1e-30: c = 1e-30
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < 1e-30: d = 1e-30
        c = 1.0 + aa / c
        if abs(c) < 1e-30: c = 1e-30
        d = 1.0 / d
        delta = d * c
        h *= delta
        if abs(delta - 1.0) < eps:
            return h
    return h


# ───────────────────────────────────────────────────────────────────────────────
# Load inputs
# ───────────────────────────────────────────────────────────────────────────────
def load_latest_scores(csv_dir: Path) -> Dict[str, dict]:
    """Latest agent_scores row per agent_name."""
    rows: Dict[str, dict] = {}
    with (csv_dir / "agent_scores.csv").open() as f:
        for r in csv.DictReader(f):
            ts = r["computed_at"]
            cur = rows.get(r["agent_name"])
            if cur is None or ts > cur["computed_at"]:
                rows[r["agent_name"]] = r
    return rows


def load_latest_signals(csv_dir: Path) -> Dict[str, dict]:
    """Latest signals_json row per agent_name (parsed)."""
    rows: Dict[str, dict] = {}
    with (csv_dir / "agent_signals_raw.csv").open() as f:
        for r in csv.DictReader(f):
            ts = r["collected_at"]
            cur = rows.get(r["agent_name"])
            if cur is None or ts > cur["collected_at"]:
                rows[r["agent_name"]] = r
    out: Dict[str, dict] = {}
    for name, row in rows.items():
        try:
            out[name] = json.loads(row["signals_json"])
        except Exception:
            out[name] = {}
    return out


def load_registry(csv_dir: Path) -> Dict[str, dict]:
    out: Dict[str, dict] = {}
    with (csv_dir / "agent_registry.csv").open() as f:
        for r in csv.DictReader(f):
            out[r["name"]] = r
    return out


# ───────────────────────────────────────────────────────────────────────────────
# Sub-composite construction (paper Section 5.2)
# ───────────────────────────────────────────────────────────────────────────────
def benchmark_sentiment_subcomposite(score_row: dict, signals: dict) -> float:
    """Benchmark + Sentiment only, normalized to weights summing to 1.

    Default paper weights: w_B=0.35, w_S=0.20. Renormalized: 0.6364 B + 0.3636 S.
    Excludes Adoption and Ecosystem to break GitHub-signal circularity.
    """
    sub = json.loads(score_row.get("sub_scores") or "[0.5, 0, 0]")
    b = sub[0] if sub else 0.5
    sent_raw = float(score_row.get("sentiment") or 0.0)
    # Paper S(a) is in [0,1]; raw sentiment is in [-1,1]. Linear remap:
    s_norm = max(0.0, min(1.0, (sent_raw + 1.0) / 2.0))
    return 0.6364 * b + 0.3636 * s_norm


# ───────────────────────────────────────────────────────────────────────────────
# Main
# ───────────────────────────────────────────────────────────────────────────────
def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--csv-dir", default="../data/csv",
                        help="Directory containing the released CSVs")
    args = parser.parse_args()
    csv_dir = Path(args.csv_dir).resolve()
    if not csv_dir.exists():
        print(f"error: csv-dir {csv_dir} does not exist", file=sys.stderr)
        return 1

    scores = load_latest_scores(csv_dir)
    signals = load_latest_signals(csv_dir)
    registry = load_registry(csv_dir)

    # The paper's n=35 subset: agents with a public GitHub repo.
    public_repo_agents = [
        name for name, cfg in registry.items()
        if cfg.get("github_repo")
    ]
    print(f"Agents with public GitHub repos in registry: {len(public_repo_agents)}")

    # Restrict to those with both a score row and a signals row
    eligible = [a for a in public_repo_agents if a in scores and a in signals]
    print(f"Of those, with scoring and signal data: {len(eligible)}\n")

    bs = []
    stars_log = []
    installs_log = []
    so_q = []
    for name in eligible:
        s = signals[name]
        bs.append(benchmark_sentiment_subcomposite(scores[name], s))
        stars_log.append(math.log10((s.get("github_stars") or 0) + 1))
        installs_log.append(math.log10((s.get("vscode_installs") or 0) + 1))
        so_q.append(s.get("so_questions") or 0)

    n = len(bs)
    print(f"{'External signal':<32} {'rho_s':>8} {'p (two-sided)':>15}")
    print("-" * 60)
    for label, ys in [("GitHub stars (log)", stars_log),
                      ("VS Code installs (log)", installs_log),
                      ("Stack Overflow question volume", so_q)]:
        rho = spearman(bs, ys)
        p = two_sided_p(rho, n)
        print(f"{label:<32} {rho:>8.3f} {p:>15.4g}")
    print(f"\nn = {n}")
    print("\nPaper-reported values (Table 3, n=35):")
    print("  GitHub stars (log)              rho_s = 0.52  p < 0.01")
    print("  VS Code installs (log)          rho_s = 0.44  p < 0.05  (illustrative; 11/35 non-zero)")
    print("  Stack Overflow question volume  rho_s = 0.49  p < 0.01")
    return 0


if __name__ == "__main__":
    sys.exit(main())