miscusi's picture
AutoScientist Part 2 source dataset
e58251b verified
Raw
History Blame Contribute Delete
12.8 kB
"""Independently re-derive every numeric claim in the generated datasets.
This deliberately does NOT import the generators' arithmetic. It parses the
*question text* for its inputs, recomputes the answer from scratch (or, for the
market set, from the source XBRL facts on disk), and compares against the number
the stored response actually states. A shared helper would make a wrong formula
agree with itself; re-deriving from the question is what makes disagreement
detectable.
Exit code is non-zero if any claim disagrees, so it can gate a release.
"""
from __future__ import annotations
import json
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
HR = ROOT / "datasets" / "hr"
MKT = ROOT / "datasets" / "market"
SEC = ROOT / "data" / "sec" / "companies.json"
def close(stated: float, expected: float, decimals: int) -> bool:
"""Agree to within half a unit of the last digit the response displays.
Precision has to come from the field's own format string, not one global
tolerance: a rate rendered "62%" carries 62.5 underneath, while a ratio
rendered "1.64" is pinned to two decimals. A single tolerance is necessarily
either too loose for the ratios or too tight for the percentages — the first
run of this script reported 61 mismatches, every one of them that mistake.
"""
return abs(stated - expected) <= 0.5 * 10 ** (-decimals) + 1e-9
def headline_number(text: str, unit: str) -> float | None:
"""Pull the first bolded figure of the given unit out of a response."""
if unit == "pct":
m = re.search(r"\*\*([+-]?[\d,]+\.?\d*)%", text)
elif unit == "usd":
m = re.search(r"\*\*\$([\d,]+\.?\d*)", text)
else:
m = re.search(r"\*\*([\d,]+\.?\d*)\*\*", text)
return float(m.group(1).replace(",", "")) if m else None
# --------------------------------------------------------------------- HR ---
def verify_hr() -> tuple[int, int, list[str]]:
rows = [json.loads(l) for l in (HR / "hr_train.jsonl").read_text().splitlines()]
rows += [json.loads(l) for l in (HR / "hr_eval.jsonl").read_text().splitlines()]
checked, bad = 0, []
for r in rows:
if r["task_family"] != "hr_analytics":
continue
q, a = r["instruction"], r["response"]
# Must start on a digit: [\d,]+ also matches a bare comma in the prose.
nums = [
float(x.replace(",", ""))
for x in re.findall(r"\d[\d,]*(?:\.\d+)?", q.replace("$", ""))
]
if "turnover rate" in q:
start, end, leavers = nums[0], nums[1], nums[2]
expected = leavers / ((start + end) / 2) * 100
got, decimals = headline_number(a, "pct"), 1
elif "cost per hire" in q:
external, internal, hires = nums[0], nums[1], nums[2]
expected = (internal + external) / hires
got, decimals = headline_number(a, "usd"), 0
elif "time to fill" in q:
days = sorted(nums[1:]) # nums[0] is the count of vacancies
mid = len(days) // 2
expected = days[mid] if len(days) % 2 else (days[mid - 1] + days[mid]) / 2
m = re.search(r"\*\*Median ([\d.]+) days", a)
got, decimals = (float(m.group(1)) if m else None), 1
elif "compa-ratio" in q:
salary, midpoint = nums[0], nums[1]
expected = salary / midpoint
m = re.search(r"\*\*Compa-ratio ([\d.]+)\*\*", a)
got, decimals = (float(m.group(1)) if m else None), 2
elif "budget for" in q:
current, attrition, growth = nums[0], nums[1], nums[2]
expected = current * attrition / 100 + current * growth / 100
m = re.search(r"\*\*About ([\d,]+) hires", a)
got, decimals = (float(m.group(1).replace(",", "")) if m else None), 0
elif "offers" in q:
offers, accepted = nums[0], nums[1]
expected = accepted / offers * 100
got, decimals = headline_number(a, "pct"), 0
else:
bad.append(f"{r['id']}: unrecognised analytics question")
continue
checked += 1
if got is None:
bad.append(f"{r['id']}: no headline figure parsed")
elif not close(got, expected, decimals):
bad.append(f"{r['id']}: stated {got}, recomputed {expected:.3f}{q[:70]}")
return checked, len(rows), bad
# ----------------------------------------------------------------- market ---
def verify_market() -> tuple[int, int, list[str]]:
rows = [json.loads(l) for l in (MKT / "market_train.jsonl").read_text().splitlines()]
rows += [json.loads(l) for l in (MKT / "market_eval.jsonl").read_text().splitlines()]
companies = {int(k): v for k, v in json.loads(SEC.read_text()).items()}
checked, bad = 0, []
def fact(cik: int, field: str, year: int):
return companies[cik]["facts"].get(field, {}).get(str(year))
for r in rows:
fam, q, a, cik = r["task_family"], r["instruction"], r["response"], r["cik"]
years = [int(y) for y in re.findall(r"(?:FY|\b)(20\d\d)\b", q)]
if fam == "yoy_growth" and len(years) >= 1:
field = "revenue" if "revenue" in q else "net_income"
y1 = max(years)
v0, v1 = fact(cik, field, y1 - 1), fact(cik, field, y1)
if v0 is None or v1 is None or v0 == 0 or (v0 < 0) != (v1 < 0):
continue # sign-flip and missing rows state no percentage by design
expected = (v1 - v0) / abs(v0) * 100
if "Essentially flat" in a:
# These deliberately omit a bolded percentage and print exact dollars.
m = re.search(r"Exact figures: \$([\d,]+) to \$([\d,]+)", a)
checked += 1
if not m or float(m.group(1).replace(",", "")) != v0 or float(
m.group(2).replace(",", "")
) != v1:
bad.append(f"{r['id']}: flat-case exact figures disagree with source")
continue
got = headline_number(a, "pct")
checked += 1
if got is None or not close(got, expected, 1):
bad.append(f"{r['id']}: stated {got}, recomputed {expected:.2f}% ({field} FY{y1})")
elif fam == "margin_analysis" and years:
kind = "gross" if "gross" in q else "operating" if "operating" in q else "net"
field = {"net": "net_income", "operating": "operating_income", "gross": "gross_profit"}[kind]
y = years[0]
num, rev = fact(cik, field, y), fact(cik, "revenue", y)
if num is None or not rev:
continue
expected = num / rev * 100
got = headline_number(a, "pct")
checked += 1
if got is None or not close(got, expected, 1):
bad.append(f"{r['id']}: stated {got}, recomputed {expected:.2f}% ({kind} margin FY{y})")
elif fam == "cagr" and len(years) >= 2:
y0, y1 = min(years), max(years)
v0, v1 = fact(cik, "revenue", y0), fact(cik, "revenue", y1)
if not v0 or not v1 or v0 <= 0 or v1 <= 0:
continue
expected = ((v1 / v0) ** (1 / (y1 - y0)) - 1) * 100
got = headline_number(a, "pct")
checked += 1
if got is None or not close(got, expected, 1):
bad.append(f"{r['id']}: stated {got}, recomputed {expected:.2f}% CAGR")
elif fam == "ratio_analysis" and years:
y = years[0]
if "current ratio" in q or "short-term obligations" in q:
ca, cl = fact(cik, "current_assets", y), fact(cik, "current_liabilities", y)
if not ca or not cl:
continue
expected, got, decimals = ca / cl, headline_number(a, "plain"), 2
elif "debt-to-equity" in q or "leveraged" in q:
li, eq = fact(cik, "liabilities", y), fact(cik, "equity", y)
if not li or not eq or eq <= 0:
continue
expected, got, decimals = li / eq, headline_number(a, "plain"), 2
else:
ni, eq = fact(cik, "net_income", y), fact(cik, "equity", y)
if ni is None or not eq or eq <= 0:
continue
expected, got, decimals = ni / eq * 100, headline_number(a, "pct"), 1
checked += 1
if got is None or not close(got, expected, decimals):
bad.append(f"{r['id']}: stated {got}, recomputed {expected:.3f} ({fam} FY{y})")
elif fam == "news_extraction":
m = re.search(r"```json\n(.*?)\n```", a, re.S)
if not m:
bad.append(f"{r['id']}: no JSON block")
continue
rec = json.loads(m.group(1))
y = rec["fiscal_year"]
rev, ni = fact(cik, "revenue", y), fact(cik, "net_income", y)
checked += 1
if rec["revenue_usd"] != int(rev) or rec["net_income_usd"] != int(ni):
bad.append(f"{r['id']}: JSON dollars disagree with filed facts FY{y}")
elif not close(rec["net_margin_pct"], ni / rev * 100, 1):
bad.append(f"{r['id']}: JSON net margin disagrees with recomputation")
elif fam == "news_fact_check":
my = re.search(r"\*\*The FY(20\d\d) revenue figure is wrong", a)
mv = re.search(r"Filed figure: \$([\d,]+)", a)
checked += 1
if not my or not mv:
bad.append(f"{r['id']}: fact-check response missing year or filed figure")
continue
rev = fact(cik, "revenue", int(my.group(1)))
if rev is None or float(mv.group(1).replace(",", "")) != float(int(rev)):
bad.append(f"{r['id']}: corrected figure disagrees with filed revenue")
elif fam == "news_summary" and years:
y1 = max(years)
v0, v1 = fact(cik, "revenue", y1 - 1), fact(cik, "revenue", y1)
if v0 is None or v1 is None or v0 == 0 or (v0 < 0) != (v1 < 0):
continue # sign-flip bullets state no percentage by design
got = headline_number(a, "pct")
if got is None:
continue # near-flat wording carries no bolded pct
checked += 1
if not close(got, (v1 - v0) / abs(v0) * 100, 1):
bad.append(f"{r['id']}: summary growth pct disagrees (FY{y1})")
elif fam == "headline_sentiment" and years:
y1 = max(years)
rev0, rev1 = fact(cik, "revenue", y1 - 1), fact(cik, "revenue", y1)
ni0, ni1 = fact(cik, "net_income", y1 - 1), fact(cik, "net_income", y1)
if None in (rev0, rev1, ni0, ni1):
continue
g = None if rev0 == 0 or (rev0 < 0) != (rev1 < 0) else (rev1 - rev0) / abs(rev0) * 100
rev_up = (g or 0) > 0.1 or (g is None and rev1 > rev0)
ni_up = ni1 > ni0
expected = (
"positive" if rev_up and ni_up and ni1 > 0
else "negative" if not rev_up and not ni_up
else "mixed"
)
m = re.search(r"\*\*(positive|negative|mixed)\*\*", a)
checked += 1
if not m or m.group(1) != expected:
bad.append(f"{r['id']}: tone label disagrees with recomputed rule (FY{y1})")
elif fam == "news_commentary" and years:
y1 = max(years)
v0, v1 = fact(cik, "revenue", y1 - 1), fact(cik, "revenue", y1)
m = re.search(r"([+-][\d.]+)% on the year", a)
if m is None or v0 is None or v1 is None or v0 == 0 or (v0 < 0) != (v1 < 0):
continue
checked += 1
if not close(float(m.group(1)), (v1 - v0) / abs(v0) * 100, 1):
bad.append(f"{r['id']}: commentary growth pct disagrees (FY{y1})")
return checked, len(rows), bad
def main() -> int:
total_bad = []
print("Independent re-derivation of stated numeric claims\n")
for name, fn in (("HR", verify_hr), ("Market", verify_market)):
checked, rows, bad = fn()
status = "OK" if not bad else f"{len(bad)} MISMATCH"
print(f"{name:8s} {checked:5d} numeric claims re-derived across {rows} rows — {status}")
for line in bad[:10]:
print(f" {line}")
if len(bad) > 10:
print(f" ... and {len(bad) - 10} more")
total_bad += bad
print()
if total_bad:
print(f"FAIL: {len(total_bad)} claims disagree with independent recomputation")
return 1
print("PASS: every re-derived claim matches the stated figure")
return 0
if __name__ == "__main__":
raise SystemExit(main())