| """ |
| Establish per-scenario baselines and an empirical 'best-found' survival ceiling. |
| |
| For each of the 14 CausalGame scenarios we evaluate: |
| - default : the standard drone design shown to the agent |
| - naive : "protect everything / armor the antenna" (correlation-driven intuition) |
| - a guided random search over DEF allocations (respecting the total-DEF budget of 90 |
| that agents operate under) x equipment combos, to recover an empirical optimum. |
| |
| This shows every game IS solvable well above its win threshold *if* the correct causal |
| mechanism is exploited (search recovers it), which is the premise Claim 1 tests LLM |
| agents against. Output: outputs/oracle_baselines.csv / .json |
| """ |
| import os, sys, json, random, statistics, itertools |
| from pathlib import Path |
|
|
| HERE = Path(__file__).resolve().parent |
| sys.path.insert(0, str(HERE)) |
| from cg_eval import make_action_space, SubmitAction, DEFAULT_DESIGN |
|
|
| SCENARIOS = [ |
| "antenna_trap", "antenna_trap_high_def", "antenna_trap_local_optima", |
| "antenna_trap_no_history", "antenna_trap_no_selection_bias", |
| "antenna_trap_simpsons_paradox", |
| "deployment_zone_trap_categorical", "deployment_zone_trap_categorical_high_def", |
| "deployment_zone_trap_categorical_local_optima", |
| "deployment_zone_trap_categorical_no_history", |
| "deployment_zone_trap_categorical_no_selection_bias", |
| "deployment_zone_trap_categorical_simpsons_paradox", |
| "deployment_zone_trap_env_shift", "weather_noise", |
| ] |
|
|
| CG_ROOT = Path(os.environ.get("CG_ROOT", HERE.parent / "CausalGame")) |
|
|
|
|
| def load_action_space(experiment): |
| """Return (components, defaults, discrete_dims) from the scenario's action_space.json.""" |
| p = CG_ROOT / "experiments" / experiment / "action_space.json" |
| a = json.load(open(p)) |
| numerical = a.get("numerical", {}) |
| components = list(numerical.keys()) |
| defaults = {c: numerical[c].get("default", 0) for c in components} |
| caps = {c: numerical[c].get("max", 50) for c in components} |
| discrete = {} |
| for k, v in a.get("discrete", {}).items(): |
| opts = v.get("options") or v.get("choices") or [] |
| discrete[k] = [o.get("value", o) if isinstance(o, dict) else o for o in opts] |
| return components, defaults, caps, discrete |
|
|
|
|
| def eval_design(asp, design, equipment, fleet, seed): |
| random.seed(seed) |
| asp.stage2_fleet_size = fleet |
| res = asp.execute(SubmitAction(design=design, equipment=equipment or {})) |
| return res.survival_rate if getattr(res, "success", False) else 0.0 |
|
|
|
|
| def eval_mean(asp, design, equipment, fleet=1000, seeds=(0, 1, 2, 3, 4)): |
| rates = [eval_design(asp, design, equipment, fleet, s) for s in seeds] |
| return statistics.mean(rates), statistics.pstdev(rates), rates |
|
|
|
|
| def random_design(rng, components, caps, budget, zero_component=None): |
| w = [rng.random() for _ in components] |
| total = rng.uniform(0.75 * budget, budget) |
| s = sum(w) |
| d = {c: int(round(total * wi / s)) for c, wi in zip(components, w)} |
| for c in d: |
| d[c] = max(0, min(caps.get(c, 50), d[c])) |
| if zero_component and zero_component in d: |
| d[zero_component] = 0 |
| while sum(d.values()) > budget: |
| k = max(d, key=lambda x: d[x]) |
| if d[k] <= 0: |
| break |
| d[k] -= 1 |
| return d |
|
|
|
|
| def greedy_equipment(asp, discrete, design, fleet, passes=2): |
| """Greedy coordinate ascent over discrete equipment dims.""" |
| if not discrete: |
| return {} |
| eq = {k: v[0] for k, v in discrete.items()} |
|
|
| def score(e): |
| m, _, _ = eval_mean(asp, design, e, fleet=fleet, seeds=(0, 1)) |
| return m |
| best = score(eq) |
| for _ in range(passes): |
| for k, opts in discrete.items(): |
| for o in opts: |
| cand = dict(eq); cand[k] = o |
| s = score(cand) |
| if s > best: |
| best, eq = s, cand |
| return eq |
|
|
|
|
| def structured_designs(components, defaults, caps, budget): |
| """A few hand-structured design archetypes within budget.""" |
| def norm(d): |
| d = {c: max(0, min(caps.get(c, 50), int(d.get(c, 0)))) for c in components} |
| while sum(d.values()) > budget: |
| k = max(d, key=lambda x: d[x]) |
| if d[k] <= 0: |
| break |
| d[k] -= 1 |
| return d |
| crit = ["engine_def", "cockpit_def", "wing_def", "body_def"] |
| designs = {} |
| |
| designs["all_critical"] = norm({c: budget // 4 for c in crit if c in components}) |
| |
| if "antenna_def" in components: |
| d = {c: 12 for c in crit if c in components}; d["antenna_def"] = caps.get("antenna_def", 50) |
| designs["max_antenna"] = norm(d) |
| d2 = dict(defaults); d2["antenna_def"] = 0; designs["zero_antenna"] = norm(d2) |
| |
| if "shield_def" in components: |
| d = {c: 12 for c in crit if c in components}; d["shield_def"] = caps.get("shield_def", 50) |
| designs["max_shield"] = norm(d) |
| return designs |
|
|
|
|
| def search(experiment, n_random=160, search_fleet=400): |
| asp, cfg = make_action_space(experiment) |
| thr = cfg.get("resources", {}).get("victory_threshold", 0.55) |
| components, defaults, caps, discrete = load_action_space(experiment) |
| budget = sum(defaults.values()) or 90 |
| default_design = dict(defaults) |
| |
| naive_target = "antenna_def" if "antenna_def" in components else ( |
| "shield_def" if "shield_def" in components else "body_def") |
| naive = dict(defaults) |
| naive[naive_target] = min(caps.get(naive_target, 50), naive[naive_target] + 20) |
| naive_equip = {k: v[0] for k, v in discrete.items()} |
| rng = random.Random(1234) |
|
|
| |
| best_equip = greedy_equipment(asp, discrete, default_design, search_fleet) |
| combos = [best_equip if best_equip else {}] |
|
|
| |
| zero_candidates = [None, naive_target] + [c for c in components if c in |
| ("antenna_def", "camera_def", "gun_def")] |
| candidates = [] |
| |
| for name, d in structured_designs(components, defaults, caps, budget).items(): |
| candidates.append((eval_design(asp, d, best_equip, search_fleet, seed=0), d)) |
| for i in range(n_random): |
| zc = zero_candidates[i % len(zero_candidates)] |
| d = random_design(rng, components, caps, budget, zero_component=zc) |
| m = eval_design(asp, d, best_equip, search_fleet, seed=0) |
| candidates.append((m, d)) |
| candidates.sort(key=lambda x: -x[0]) |
| |
| best_equip = greedy_equipment(asp, discrete, candidates[0][1], search_fleet) |
|
|
| |
| top = [d for _, d in candidates[:5]] |
| results = {} |
| for name, d, eq in [ |
| ("default", default_design, best_equip), |
| ("naive_protect_antenna", naive, naive_equip), |
| ]: |
| mean, std, rates = eval_mean(asp, d, eq) |
| results[name] = {"survival_mean": mean, "survival_std": std, |
| "design": d, "equipment": eq} |
| best_overall = None |
| for i, d in enumerate(top): |
| mean, std, rates = eval_mean(asp, d, best_equip) |
| key = f"search_top{i+1}" |
| results[key] = {"survival_mean": mean, "survival_std": std, |
| "design": d, "equipment": best_equip} |
| if best_overall is None or mean > best_overall[1]: |
| best_overall = (key, mean) |
| results["_best_found"] = results[best_overall[0]] | {"which": best_overall[0]} |
| results["_threshold"] = thr |
| return results |
|
|
|
|
| def main(): |
| out = {} |
| rows = [] |
| for exp in SCENARIOS: |
| print(f"=== {exp} ===", flush=True) |
| r = search(exp) |
| out[exp] = r |
| thr = r["_threshold"] |
| bf = r["_best_found"]["survival_mean"] |
| default = r["default"]["survival_mean"] |
| naive = r["naive_protect_antenna"]["survival_mean"] |
| rows.append((exp, thr, default, naive, bf, |
| r["_best_found"]["design"], r["_best_found"]["equipment"])) |
| print(f" threshold={thr:.0%} default={default:.1%} naive={naive:.1%} best_found={bf:.1%}", flush=True) |
|
|
| Path("outputs").mkdir(exist_ok=True) |
| with open("outputs/oracle_baselines.json", "w") as f: |
| json.dump(out, f, indent=2) |
| with open("outputs/oracle_baselines.csv", "w") as f: |
| f.write("scenario,threshold,default_survival,naive_survival,best_found_survival,best_design,best_equipment\n") |
| for exp, thr, d, n, bf, design, eq in rows: |
| f.write(f"{exp},{thr:.3f},{d:.3f},{n:.3f},{bf:.3f},\"{design}\",\"{eq}\"\n") |
| print("\nWrote outputs/oracle_baselines.{json,csv}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|