astra-cadfem-failures / scripts /classify_tasks_and_failures.py
Conditiondark's picture
Astra CAD+FEM failures v0.1: 51 cases from CADFEM-Bench v1.9 (part 3)
6d52e65 verified
Raw History Blame Contribute Delete
14.1 kB
"""Taxonomy of the CADFEM-Bench v1.9 tasks and of every recorded Astra attempt (no model calls).
Tasks: topic (physics), analysis type, geometry class, track, reference class and suite, from each task row.
Attempts: outcome and mechanism, from the saved run records, the strict/scheme audits, the buckle-trap
adjudication and the earlier admitted/excluded failure-case package. Task defects and infrastructure outcomes are
listed but never counted as model failures.
tmp/cq-env/bin/python scripts/classify_tasks_and_failures.py --out output/audits/astra-failure-taxonomy-20261028
"""
import argparse, collections, glob, json, re
from pathlib import Path
CV = Path(__file__).resolve().parents[1]
PKG = CV.parent / "cadfem-bench-v1.9"
TOPICS = [("fracture", ("fract", "crack")), ("contact", ("contact",)), ("plasticity", ("plastic", "limit")),
("stability", ("buckl",)), ("dynamics", ("modal", "frequenc", "vibration")),
("thermal", ("transient thermal", "heat", "thermal")), ("structural static", ())]
GEOMETRY = {"agentfem-bracket": "bracket", "cadworld-freecad-fem": "machined part", "cycloidal-drive-components": "gear/drive part",
"fcvm-buckling": "beam/girder", "fcvm-plastic-limit": "pipe joint ring", "feenox-valve-transient": "valve assembly",
"geopinonet-holed-plate": "plate", "morphing-wing-plates": "plate", "rigging-plate": "plate", "simjeb-analysis": "bracket",
"femcad-hard": "plate/tube", "codeaster-piping": "pipe/shell", "codeaster-fracture-3d": "cracked solid",
"codeaster-stability": "plate/bar", "codeaster-contact": "two-body contact", "rect-cantilever": "bar", "round-cantilever": "bar/tube",
"fixed-pinned": "bar/tube", "i-section": "open section", "open-section": "open section", "plate": "plate", "stepped": "bar",
"tapered": "bar", "ltb": "deep beam", "perforated": "perforated strip", "nafems-benchmarks": "plate/solid"}
MECHANISMS = {
"M1": "silent wrong value: trusted the solver output without a sanity check",
"M2": "no answer: own script, parser or solver-handling error",
"M3": "declined the analysis (no-tools protocol)",
"M4": "silent wrong engineering verdict",
"M5": "CAD code does not run, parse or attach",
"M6": "output-token budget exhausted before the script was complete",
"M7": "minor: geometry fidelity or convergence evidence (numbers within tolerance)",
"M8": "refused to report after its own verification check failed (no wrong number)",
}
def jl(p):
return [json.loads(l) for l in Path(p).read_text().splitlines() if l.strip()]
def topic_of(task):
text = " ".join(task.get("physics", []) + [task.get("family", ""), task.get("title", "")]).lower()
hits = [name for name, keys in TOPICS if any(k in text for k in keys)]
return hits[0] if hits else "structural static", hits[1:]
def analysis_of(task):
text = " ".join(task.get("physics", []) + [task["prompt"][:600]]).lower().replace("no contact", "").replace("no gravity", "")
for k, v in [("stress intensity", "fracture SIF/G"), ("energy release", "fracture SIF/G"), ("buckling", "linear eigen-buckling"),
("limit load", "plastic limit load"), ("collapse", "plastic limit load"), ("modal", "eigen-frequency"),
("frequenc", "eigen-frequency"), ("transient", "transient"), ("contact", "contact (nonlinear)"),
("heat", "steady heat conduction")]:
if k in text:
return v
return "linear static"
def classify_tasks():
rows = []
suites = [("primary", PKG / "candidate/tasks.jsonl")] + [(d.name, d / "tasks.jsonl") for d in sorted((PKG / "evaluator/suites").iterdir())
if d.name != "primary" and (d / "tasks.jsonl").exists()]
refs = {}
for f in [PKG / "evaluator/references.jsonl"] + list((PKG / "evaluator/suites").glob("*/references.jsonl")):
for r in jl(f):
refs[r["task_id"]] = r
for suite, f in suites:
for t in jl(f):
topic, also = topic_of(t)
ref = refs.get(t["task_id"], {})
classes = sorted({q.get("ref_class") for q in (ref.get("references") or {}).values()})
rows.append(dict(task_id=t["task_id"], suite=suite, status=t.get("status", "active"), track=t["track"], family=t["family"],
topic=topic, also=also, analysis=analysis_of(t), geometry=GEOMETRY.get(t["family"], "other"),
reference_class=classes, published_reference=not any(c and c.startswith("evaluator") for c in classes)))
return rows
def attempt(rows, **kw):
rows.append(kw)
def classify_attempts():
A = []
# 1. October CAD+FEM runs (single-shot hunt, rechecks, solver-feedback repair)
strict = {r["run"]: r for r in json.loads((CV / "output/audits/astra-scheme-review-20261027/strict-checks.json").read_text())["runs"]}
for o in sorted(glob.glob(str(CV / "runs/astra-*-20261015/*/outcome.json"))):
d = json.loads(Path(o).read_text()); run = str(Path(o).parent.relative_to(CV)); tid = d.get("task_id")
st = d.get("status", ""); s = d.get("score") or {}; num = s.get("numerical_passed")
proto = "repair with solver feedback" if "hardest" in run else ("execution-feedback recheck" if "recheck" in run else "single shot")
if "memory" in st or "connection" in st or "token_budget" in st:
cls, mech = "excluded_infrastructure_or_resource", None
elif tid and tid.startswith("A-SIMJEB") and num is False:
cls, mech = "excluded_task_defect", "prompt gives the wrong diameter for bolt bore 1; script left it unclamped"
elif "script_failure" in st:
cls, mech = "failure", "M2"
elif tid == "A-FCVM-Plate_girder_EC3" and num is False:
cls, mech = "failure", "M1"
elif num is None and "pass" not in st:
cls, mech = "failure", "M2"
elif num or "pass" in st:
g = (strict.get(run) or {}).get("gates") or {}
minor = [k for k, v in g.items() if v is False]
cls, mech = ("pass_with_minor_flags", "M7") if minor or tid == "B-FEMCAD-062" else ("pass", None)
else:
cls, mech = "failure", "M1"
attempt(A, source="CADFEM v1.7 runs (Oct 15-16)", run=run, task=tid, protocol=proto, outcome=cls, mechanism=mech, status=st)
# 2. v1.8 Code_Aster and bar trials
for r in json.loads((CV / "runs/astra-v18-20261027/summary.json").read_text())["runs"]:
k = r["kind"]
if k.startswith("infrastructure") or k == "not_dispatched_budget_cap":
cls, mech = "excluded_infrastructure_or_resource", None
elif k == "inconclusive_generation":
cls, mech = "failure", "M6"
elif r.get("scheme_joint") == "verified_pass" or (r.get("qoi") and all(v["ok"] for v in r["qoi"].values())):
cls, mech = "pass", None
else:
cls, mech = "failure", "M1"
attempt(A, source="CADFEM v1.8 trials (Oct 27)", run="runs/astra-v18-20261027/" + r["run"], task=r["task_id"],
protocol="single shot", outcome=cls, mechanism=mech, status=k)
# 3. buckle-trap batch runs
for r in json.loads((CV / "runs/astra-buckle-results-20261028.json").read_text())["runs"]:
v = r["verdict"]
mech = {"wrong_trap_confirmed": "M1", "wrong_other": "M1"}.get(v, "M2" if v.startswith("no_result") else None)
attempt(A, source="buckle-trap suite (Oct 27-28)", run=f"runs/{r['run']}/{r['task']}", task=r["task"], protocol="single shot (batch)",
outcome="pass" if v == "pass" else "failure", mechanism=mech, status=v)
# 4. variety batches, when scored and reviewed
for vb in sorted(CV.glob("runs/astra-variety-batch*-20261028/classification.json")):
for r in json.loads(vb.read_text()):
attempt(A, source="variety batch (Oct 28)", **r)
# 5. earlier admitted and excluded failure cases (CAD editing, pipe network, frames)
fc = CV / "output/datasets/astra-failure-cases-v0.1"
for c in jl(fc / "cases.jsonl"):
dom = c["domain"]
mech = "M5" if dom.startswith("CAD editing") else ("M4" if "network" in dom else "M3")
attempt(A, source="failure-cases v0.1 (Sep-Oct)", run=c["case_id"], task=c["case_id"], protocol=c.get("protocol", ""),
outcome="failure", mechanism=mech, status="admitted")
for c in jl(fc / "excluded.jsonl"):
attempt(A, source="failure-cases v0.1 (Sep-Oct)", run=c["case_id"], task=c["case_id"], protocol=c.get("protocol", ""),
outcome="excluded_task_defect", mechanism=None, status=str(c.get("cls", ""))[:60])
return A
def main():
ap = argparse.ArgumentParser(); ap.add_argument("--out", type=Path, required=True); a = ap.parse_args()
a.out.mkdir(parents=True, exist_ok=True)
tasks = classify_tasks(); att = classify_attempts()
topic_of_task = {t["task_id"]: t["topic"] for t in tasks}
for r in att:
r["topic"] = topic_of_task.get(r["task"]) or ("CAD editing" if str(r["task"]).startswith("cad-edit") else
"hydraulic network" if "network" in str(r["task"]) else
"frame analysis" if "frame" in str(r["task"]) else "other")
C = collections.Counter
# per task, CAD+FEM only: failed in every counted attempt (no pass), or in at least one; a task with a recorded
# task defect (e.g. the SimJEB bolt-bore prompt) is left out entirely, whatever its other attempts did
defect = {r["task"] for r in att if r["outcome"] == "excluded_task_defect"}
per = collections.defaultdict(list)
for r in att:
if r["topic"] not in ("CAD editing", "hydraulic network", "frame analysis", "other") and r["task"] not in defect \
and r["outcome"] in ("failure", "pass", "pass_with_minor_flags"):
per[r["task"]].append(r)
always = sorted(t for t, rs in per.items() if all(r["outcome"] == "failure" for r in rs))
summary = {
"tasks": len(tasks), "tasks_by_suite": dict(C(t["suite"] for t in tasks)),
"tasks_by_topic": dict(C(t["topic"] for t in tasks)), "tasks_by_analysis": dict(C(t["analysis"] for t in tasks)),
"tasks_by_geometry": dict(C(t["geometry"] for t in tasks)), "tasks_by_track": dict(C(t["track"] for t in tasks)),
"attempts": len(att), "attempts_by_outcome": dict(C(r["outcome"] for r in att)),
"failures_by_mechanism": {k: {"label": MECHANISMS[k], "count": n} for k, n in C(r["mechanism"] for r in att if r["outcome"] == "failure").items()},
"failures_by_topic": dict(C(r["topic"] for r in att if r["outcome"] == "failure")),
"attempts_by_topic": {tp: dict(C(r["outcome"] for r in att if r["topic"] == tp)) for tp in sorted({r["topic"] for r in att})},
"cadfem_tasks_attempted": len(per),
"cadfem_tasks_failed_at_least_once": sum(any(r["outcome"] == "failure" for r in rs) for rs in per.values()),
"cadfem_tasks_failed_every_attempt": len(always),
"cadfem_tasks_failed_every_attempt_by_topic": dict(C(per[t][0]["topic"] for t in always)),
"cadfem_tasks_failed_every_attempt_by_mechanism": dict(C(per[t][-1]["mechanism"] for t in always)),
"cadfem_tasks_failed_every_attempt_list": always,
"mechanisms": MECHANISMS,
"rules": "Task defects (wrong prompt data, reference errors) and infrastructure/resource outcomes are excluded from failure counts."}
(a.out / "tasks.json").write_text(json.dumps(tasks, indent=1) + "\n")
(a.out / "attempts.json").write_text(json.dumps(att, indent=1) + "\n")
(a.out / "summary.json").write_text(json.dumps(summary, indent=1) + "\n")
(a.out / "README.md").write_text(report(tasks, att, summary))
print(json.dumps({k: v for k, v in summary.items() if k not in ("mechanisms",)}, indent=1))
def table(rows, cols, keyname):
head = "| " + keyname + " | " + " | ".join(cols) + " | total |\n|" + "---|" * (len(cols) + 2) + "\n"
body = "".join("| " + k + " | " + " | ".join(str(v.get(c, "")) for c in cols) + f" | {sum(v.values())} |\n" for k, v in rows.items())
return head + body
def report(tasks, att, s):
C = collections.Counter
suites = sorted({t["suite"] for t in tasks})
by_topic = {tp: dict(C(t["suite"] for t in tasks if t["topic"] == tp)) for tp in sorted({t["topic"] for t in tasks})}
outcomes = ["pass", "pass_with_minor_flags", "failure", "excluded_task_defect", "excluded_infrastructure_or_resource"]
att_topic = {tp: dict(C(r["outcome"] for r in att if r["topic"] == tp)) for tp in sorted({r["topic"] for r in att})}
mech_rows = []
for k, label in MECHANISMS.items():
ex = [r for r in att if r["outcome"] == "failure" and r["mechanism"] == k]
if ex:
tops = dict(C(r["topic"] for r in ex))
mech_rows.append(f"| {k} | {label} | {len(ex)} | {', '.join(f'{t} {n}' for t, n in tops.items())} | {ex[0]['task']} |")
return (
"# CADFEM-Bench v1.9 tasks and Astra attempts: classification\n\n"
f"Generated by `scripts/classify_tasks_and_failures.py` (no model calls). {s['tasks']} tasks in v1.9 (all suites; held trap "
f"cases excluded) and {s['attempts']} recorded Astra attempts. Task defects and infrastructure/resource outcomes are listed "
"separately and never counted as model failures. Attempts are per run: one task can appear under several protocols.\n\n"
"## Tasks by topic and suite\n\n" + table(by_topic, suites, "topic") +
"\n## Tasks by analysis type\n\n" + "".join(f"- {k}: {v}\n" for k, v in s["tasks_by_analysis"].items()) +
"\n## Astra attempts by topic and outcome\n\n" + table(att_topic, outcomes, "topic") +
"\n## Failure mechanisms\n\n| Code | Mechanism | Failures | Topics | Example |\n|---|---|---|---|---|\n" + "\n".join(mech_rows) + "\n")
if __name__ == "__main__":
main()