|
| 1 | +import argparse |
| 2 | +import importlib.util |
| 3 | +import json |
| 4 | +import random |
| 5 | +import re |
| 6 | +import traceback |
| 7 | +from pathlib import Path |
| 8 | +from statistics import mean |
| 9 | + |
| 10 | +import numpy as np |
| 11 | +from CybORG import CybORG |
| 12 | +from CybORG.Agents import BaseAgent |
| 13 | +from CybORG.Agents.Wrappers.PettingZooParallelWrapper import PettingZooParallelWrapper |
| 14 | +from CybORG.Simulator.Scenarios import DroneSwarmScenarioGenerator |
| 15 | + |
| 16 | +CRASH_SCORE = -1_000_000.0 |
| 17 | + |
| 18 | + |
| 19 | +def safe_module_name(player_name: str) -> str: |
| 20 | + safe = re.sub(r"\W+", "_", player_name) |
| 21 | + if not safe or safe[0].isdigit(): |
| 22 | + safe = f"player_{safe}" |
| 23 | + return f"codeclash_cyborg_{safe.lower()}" |
| 24 | + |
| 25 | + |
| 26 | +def load_agent_class(player_name: str, path: str): |
| 27 | + spec = importlib.util.spec_from_file_location(safe_module_name(player_name), path) |
| 28 | + if spec is None or spec.loader is None: |
| 29 | + raise RuntimeError(f"Could not load module spec from {path}") |
| 30 | + module = importlib.util.module_from_spec(spec) |
| 31 | + spec.loader.exec_module(module) |
| 32 | + if not hasattr(module, "MyAgent"): |
| 33 | + raise RuntimeError(f"{path} does not define MyAgent") |
| 34 | + agent_class = module.MyAgent |
| 35 | + if not issubclass(agent_class, BaseAgent): |
| 36 | + raise RuntimeError(f"{path} MyAgent must inherit from CybORG BaseAgent") |
| 37 | + return agent_class |
| 38 | + |
| 39 | + |
| 40 | +def make_agent(agent_class: type, agent_name: str): |
| 41 | + try: |
| 42 | + return agent_class(name=agent_name) |
| 43 | + except TypeError: |
| 44 | + try: |
| 45 | + return agent_class(agent_name) |
| 46 | + except TypeError: |
| 47 | + return agent_class() |
| 48 | + |
| 49 | + |
| 50 | +def evaluate_player( |
| 51 | + player_name: str, |
| 52 | + agent_class: type, |
| 53 | + *, |
| 54 | + episode_idx: int, |
| 55 | + steps: int, |
| 56 | + drones: int, |
| 57 | +) -> dict: |
| 58 | + seed = 4100 + episode_idx |
| 59 | + random.seed(seed) |
| 60 | + np.random.seed(seed) |
| 61 | + |
| 62 | + try: |
| 63 | + scenario = DroneSwarmScenarioGenerator(num_drones=drones) |
| 64 | + env = PettingZooParallelWrapper(CybORG(scenario, "sim")) |
| 65 | + observations = env.reset() |
| 66 | + action_spaces = env.action_spaces |
| 67 | + agents = {agent_name: make_agent(agent_class, agent_name) for agent_name in env.possible_agents} |
| 68 | + |
| 69 | + for agent_name, agent in agents.items(): |
| 70 | + if hasattr(agent, "set_initial_values"): |
| 71 | + agent.set_initial_values(action_spaces[agent_name], observations[agent_name]) |
| 72 | + |
| 73 | + step_rewards = [] |
| 74 | + for _ in range(steps): |
| 75 | + actions = { |
| 76 | + agent_name: agents[agent_name].get_action(observations[agent_name], action_spaces[agent_name]) |
| 77 | + for agent_name in env.agents |
| 78 | + } |
| 79 | + observations, rewards, done, _info = env.step(actions) |
| 80 | + step_rewards.append(mean(rewards.values())) |
| 81 | + if all(done.values()): |
| 82 | + break |
| 83 | + |
| 84 | + for agent in agents.values(): |
| 85 | + if hasattr(agent, "end_episode"): |
| 86 | + agent.end_episode() |
| 87 | + |
| 88 | + return { |
| 89 | + "player": player_name, |
| 90 | + "episode": episode_idx, |
| 91 | + "score": float(sum(step_rewards)), |
| 92 | + "steps_completed": len(step_rewards), |
| 93 | + "status": "ok", |
| 94 | + } |
| 95 | + except Exception as exc: |
| 96 | + return { |
| 97 | + "player": player_name, |
| 98 | + "episode": episode_idx, |
| 99 | + "score": CRASH_SCORE, |
| 100 | + "steps_completed": 0, |
| 101 | + "status": "error", |
| 102 | + "error": f"{type(exc).__name__}: {exc}", |
| 103 | + "traceback": traceback.format_exc(limit=5), |
| 104 | + } |
| 105 | + |
| 106 | + |
| 107 | +def parse_agent_arg(value: str) -> tuple[str, str]: |
| 108 | + if "=" not in value: |
| 109 | + raise argparse.ArgumentTypeError("--agent values must be NAME=/path/to/cyborg_agent.py") |
| 110 | + name, path = value.split("=", 1) |
| 111 | + if not name: |
| 112 | + raise argparse.ArgumentTypeError("agent name cannot be empty") |
| 113 | + if not Path(path).exists(): |
| 114 | + raise argparse.ArgumentTypeError(f"agent path does not exist: {path}") |
| 115 | + return name, path |
| 116 | + |
| 117 | + |
| 118 | +def main() -> None: |
| 119 | + parser = argparse.ArgumentParser() |
| 120 | + parser.add_argument("--agent", action="append", type=parse_agent_arg, required=True) |
| 121 | + parser.add_argument("--episodes", type=int, default=3) |
| 122 | + parser.add_argument("--steps", type=int, default=30) |
| 123 | + parser.add_argument("--drones", type=int, default=18) |
| 124 | + parser.add_argument("--output", required=True) |
| 125 | + args = parser.parse_args() |
| 126 | + |
| 127 | + agent_classes = {name: load_agent_class(name, path) for name, path in args.agent} |
| 128 | + totals = {name: 0.0 for name in agent_classes} |
| 129 | + details = [] |
| 130 | + |
| 131 | + for episode_idx in range(args.episodes): |
| 132 | + for player_name, agent_class in agent_classes.items(): |
| 133 | + result = evaluate_player( |
| 134 | + player_name, |
| 135 | + agent_class, |
| 136 | + episode_idx=episode_idx, |
| 137 | + steps=args.steps, |
| 138 | + drones=args.drones, |
| 139 | + ) |
| 140 | + totals[player_name] += result["score"] |
| 141 | + details.append(result) |
| 142 | + |
| 143 | + averages = {player: score / args.episodes for player, score in totals.items()} |
| 144 | + output = { |
| 145 | + "average_scores": averages, |
| 146 | + "total_scores": totals, |
| 147 | + "episodes": args.episodes, |
| 148 | + "details": [json.dumps(item, sort_keys=True) for item in details], |
| 149 | + } |
| 150 | + Path(args.output).parent.mkdir(parents=True, exist_ok=True) |
| 151 | + Path(args.output).write_text(json.dumps(output, indent=2, sort_keys=True)) |
| 152 | + |
| 153 | + |
| 154 | +if __name__ == "__main__": |
| 155 | + main() |
0 commit comments