File size: 6,458 Bytes
4010358 3b54ca9 4010358 3b54ca9 4010358 3b54ca9 4010358 3b54ca9 4010358 3b54ca9 4010358 3b54ca9 4010358 3b54ca9 4010358 3b54ca9 4010358 3b54ca9 4010358 3b54ca9 4010358 | 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 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | """Environment API.
env = GoingConcernEnv()
obs = env.reset(seed=7, tier=1) # or env.reset(config=FirmConfig(...))
while not env.done:
obs, done, info = env.step(action) # action: dict or JSON string
env.log # full episode log (replayable, viewer input)
Replay the successfully recorded weeks with GoingConcernEnv.replay_log(env.log)."""
from __future__ import annotations
import json
from copy import deepcopy
from dataclasses import replace
from pathlib import Path
from .actions import parse_action
from .config import FirmConfig
from .engine import Sim
from .firms import firm_from_seed
from .ledger import InvariantViolation
from .observe import d, observe, render_text
from .version import ENGINE_VERSION
def snapshot(sim: Sim) -> dict:
L = sim.ledger.bal
return {
"week": sim.week, "cash": sim.cash, "debt": sim.credit.drawn, "ap": sim.ap_total(),
"inventory_value": sim.inventory_value(), "prepaid": sim.prepaid_total(),
"equity": sim.ledger.equity(), "headcount": sim.headcount, "goodwill": round(sim.goodwill, 4),
"on_hand": {k: s.on_hand for k, s in sim.skus.items()},
"prices": {k: s.price for k, s in sim.skus.items()},
"revenue_total": L["sales_retail"] + L["sales_bulk"] + L["liquidation_proceeds"],
"frozen": sim.credit.frozen, "in_breach": sim.credit.in_breach,
"bankrupt": sim.bankrupt,
}
class GoingConcernEnv:
def __init__(self, record: bool = True):
self.record = record
self.sim: Sim | None = None
self.log: dict = {}
self.violation: str | None = None
def reset(self, seed: int | None = None, tier: int = 1, config: FirmConfig | None = None,
weeks: int | None = None, *, firm: int | None = None) -> dict:
"""Use the supplied config, then an explicit firm, then the seed. Default to firm 1."""
if config is None:
if tier != 1:
raise ValueError("The public firms are tier 1. Pass config= for a custom firm.")
if firm is None:
firm = 1 if seed is None else firm_from_seed(seed)
config = load_firm(firm)
if weeks is not None:
if type(weeks) is not int or weeks < 1:
raise ValueError("weeks must be a positive integer")
config = replace(config, weeks=weeks)
self.sim = Sim(config)
self.violation = None
self._last_errors: list[str] = []
self.log = {"engine_version": ENGINE_VERSION, "seed": config.seed, "tier": config.tier,
"config": config.to_dict(), "initial": snapshot(self.sim), "steps": []}
return self.observe()
def observe(self) -> dict:
return observe(self.sim, self._last_errors)
def observe_text(self) -> str:
return render_text(self.observe())
@property
def done(self) -> bool:
return self.sim is None or self.sim.done or self.violation is not None
def step(self, action) -> tuple[dict, bool, dict]:
if self.done:
raise RuntimeError("call reset() first")
return self._step(parse_action(action))
def replay_step(self, step: dict) -> tuple[dict, bool, dict]:
"""Replay one successfully recorded week, using its parsed action in integer cents."""
if self.done:
raise RuntimeError("call reset() first")
return self._step(deepcopy(step["action"]), recorded_errors=step["errors"])
@classmethod
def replay_log(cls, log: dict) -> GoingConcernEnv:
"""Replay successfully recorded weeks only. Reject a log with an unrecorded failed week."""
if log.get("violation") is not None:
raise ValueError("Cannot replay the whole log. An engine exception left a week "
f"unrecorded: {log['violation']}")
replay = cls()
replay.reset(config=FirmConfig.from_dict(log["config"]))
for week in log["steps"]:
replay.replay_step(week)
if replay.violation is not None:
raise RuntimeError(f"Engine exception during replay: {replay.violation}")
return replay
def _step(self, act: dict, recorded_errors: list[str] | None = None) -> tuple[dict, bool, dict]:
try:
info = self.sim.step(act)
except Exception as e: # InvariantViolation, or any engine bug: stop, log, never crash the caller
self.violation = f"{type(e).__name__}: {e}"
# a crashed episode is scored like a bankruptcy (no continuation): crashing never pays
self.sim.bankrupt, self.sim.done = True, True
self.sim.bankrupt_reason = f"run stopped: {self.violation}"
info = {"invariant_violation": self.violation, "errors": act.get("_errors", [])}
if self.record:
self.log["violation"] = self.violation
return self.observe(), True, info
if recorded_errors is not None:
# The log retains diagnostics for malformed fields that parsing discarded.
info["errors"] = list(recorded_errors)
self._last_errors = info["errors"]
if self.record:
self.log["steps"].append({
"action": {k: v for k, v in act.items() if k != "_errors" and v not in ([], {}, 0)},
"errors": info["errors"], "events": info["events"],
"flows": info["flows"], "state": snapshot(self.sim),
})
if self.sim.done and self.record:
self.log["final"] = snapshot(self.sim)
self.log["bankrupt_reason"] = self.sim.bankrupt_reason
return self.observe(), self.sim.done, info
def save_log(self, path: str) -> None:
with open(path, "w") as f:
json.dump(self.log, f, default=str)
__all__ = ["GoingConcernEnv", "run_episode", "snapshot", "d"]
def load_firm(i: int) -> FirmConfig:
"""One of the 100 Corner Shop firms (1..100)."""
path = Path(__file__).parent.parent / "firms" / f"corner_shop_{i:02d}.json"
return FirmConfig.from_json(path.read_text(encoding="utf-8"))
def run_episode(agent, firm: int, record: bool = False):
env = GoingConcernEnv(record=record)
obs = env.reset(config=load_firm(firm))
if hasattr(agent, "reset"):
agent.reset()
done = False
while not done:
obs, done, info = env.step(agent.act(obs))
return env
|