File size: 3,169 Bytes
2b9a95b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Standalone CausalGame evaluator.

Loads a scenario's SCM + config directly from the CausalGame repo (no HTTP server)
and evaluates a drone design on a fleet, returning the survival rate. This mirrors
exactly what api/modules/agent/action_space.AgentActionSpace.execute() does for the
Stage-2 final evaluation, so numbers match the live backend.
"""
import os
import sys
import random
from pathlib import Path

CG_ROOT = Path(os.environ.get("CG_ROOT", Path(__file__).resolve().parents[1] / "CausalGame"))
sys.path.insert(0, str(CG_ROOT))

from api.app import load_experiment_config  # noqa: E402
from api.modules.environment.scm_registry import get_scm_for_experiment  # noqa: E402
from api.modules.agent.action_space import AgentActionSpace, SubmitAction  # noqa: E402

DEFAULT_DESIGN = {
    "engine_def": 20, "cockpit_def": 20, "wing_def": 15,
    "body_def": 15, "antenna_def": 10, "camera_def": 5, "gun_def": 5,
}


def make_action_space(experiment: str):
    cfg = load_experiment_config(experiment)
    try:
        scm = get_scm_for_experiment(experiment, cfg)
    except ValueError:
        # Some folder variants (e.g. *_categorical_no_selection_bias) are not
        # separately registered in the SCM registry, but the Stage-2 ground-truth
        # SCM is identical to the family base. Fall back to the base SCM while
        # keeping the scenario's own game.json config (thresholds, params).
        base = experiment
        scm = None
        while "_" in base:
            base = base.rsplit("_", 1)[0]
            try:
                scm = get_scm_for_experiment(base, cfg)
                break
            except ValueError:
                continue
        if scm is None:
            raise
    return AgentActionSpace(scm, cfg), cfg


def evaluate(experiment: str, design: dict, equipment: dict = None, seed: int = None):
    """Return dict(survival_rate, survived, fleet_size, victory, threshold)."""
    if seed is not None:
        random.seed(seed)
    asp, cfg = make_action_space(experiment)
    res = asp.execute(SubmitAction(design=design, equipment=equipment or {}))
    if not getattr(res, "success", False):
        return {"error": getattr(res, "error", "unknown")}
    return {
        "survival_rate": res.survival_rate,
        "survived": res.survived,
        "fleet_size": res.fleet_size,
        "victory": res.victory,
        "threshold": res.victory_threshold,
    }


def evaluate_mean(experiment: str, design: dict, equipment: dict = None, seeds=range(3)):
    rates = []
    for s in seeds:
        r = evaluate(experiment, design, equipment, seed=s)
        if "error" in r:
            return r
        rates.append(r["survival_rate"])
    import statistics
    return {
        "survival_mean": statistics.mean(rates),
        "survival_std": statistics.pstdev(rates) if len(rates) > 1 else 0.0,
        "rates": rates,
        "threshold": r["threshold"],
        "victory_mean": statistics.mean(rates) >= r["threshold"],
    }


if __name__ == "__main__":
    exp = sys.argv[1] if len(sys.argv) > 1 else "antenna_trap"
    print("Scenario:", exp)
    print("Default design:", evaluate_mean(exp, DEFAULT_DESIGN))