Spaces:
Running
Running
Download python/borderland/domain.py from FatUnc6969/borderland-rl: direct link, hf CLI and curl.
- Browser
- Download file 13 kB
-
https://huggingface.co/spaces/FatUnc6969/borderland-rl/resolve/main/python/borderland/domain.py
- Command line
-
hf download hf://spaces/FatUnc6969/borderland-rl/python/borderland/domain.py
-
curl -L -o domain.py https://huggingface.co/spaces/FatUnc6969/borderland-rl/resolve/main/python/borderland/domain.py
13 kB
| from __future__ import annotations | |
| from dataclasses import asdict, dataclass, field | |
| from enum import IntEnum | |
| import json | |
| from typing import Any, TYPE_CHECKING | |
| if TYPE_CHECKING: | |
| from .plant import Infrastructure, Charter | |
| class Phase(IntEnum): | |
| RULE_CHAMBER = 1 | |
| MOVING_MAZE = 2 | |
| ARCHIVE = 3 | |
| OSMOSIS = 4 | |
| WITNESS_BLOCK = 5 | |
| BLACKOUT = 6 | |
| FINAL_EXIT = 7 | |
| def primitive(value: Any) -> Any: | |
| if isinstance(value, IntEnum): | |
| return int(value) | |
| if hasattr(value, 'to_dict'): | |
| return value.to_dict() | |
| if isinstance(value, dict): | |
| return {str(k): primitive(v) for k, v in value.items()} | |
| if isinstance(value, (tuple, list)): | |
| return [primitive(v) for v in value] | |
| return value | |
| class Action: | |
| tag: str | |
| arguments: dict = field(default_factory=dict) | |
| def to_dict(self): | |
| return {'tag': self.tag, 'arguments': primitive(self.arguments)} | |
| class ActionError: | |
| code: str | |
| message: str | |
| def to_dict(self): | |
| return asdict(self) | |
| class Observation: | |
| phase: Phase | |
| tick: int | |
| charge: int | |
| team: tuple | |
| inventory: tuple | |
| notebook: dict | |
| rules: tuple | |
| board: dict | |
| outcome: str | |
| def to_dict(self): | |
| return {k: primitive(v) for k, v in self.__dict__.items()} | |
| class Transition: | |
| observation: Observation | |
| legal_actions: tuple[Action, ...] | |
| reward: float = 0.0 | |
| terminated: bool = False | |
| truncated: bool = False | |
| outcome: str = 'running' | |
| error: ActionError | None = None | |
| context_reset: bool = False | |
| revision: int = 0 | |
| diagnostics: tuple = () | |
| def done(self): | |
| return self.terminated or self.truncated | |
| def to_dict(self): | |
| return {k: primitive(v) for k, v in self.__dict__.items()} | |
| class RecordRevision: | |
| id: str | |
| subject: str | |
| statement: str | |
| issued_at: int | |
| supersedes: str | None | |
| seal: str | |
| authenticated: bool | |
| def __getitem__(self, key): | |
| return getattr(self, key) | |
| def to_dict(self): | |
| return asdict(self) | |
| ARCHIVE_WORKLOADS = {'compact': 4, 'standard': 16, 'extended': 64} | |
| ARCHIVE_SUBJECTS = ('restoration', 'authorization', 'egress') | |
| class ArchiveSpec: | |
| workload: str | |
| pages: tuple | |
| def page(self, slot, page): | |
| return self.pages[slot][page] | |
| def revisions(self): | |
| return tuple(record for scroll in self.pages for page in scroll for record in page) | |
| def revision(self, record_id, issued_at): | |
| return next(record for record in self.revisions() if record.id == record_id and record.issued_at == issued_at) | |
| def current(self, record_id): | |
| return max((record for record in self.revisions() if record.id == record_id and record.authenticated), key=lambda record: record.issued_at) | |
| def authoritative(self): | |
| return tuple(max((record for record in self.revisions() if record.subject == subject and record.authenticated), key=lambda record: record.issued_at) for subject in ARCHIVE_SUBJECTS) | |
| def validate(self): | |
| if self.workload not in ARCHIVE_WORKLOADS or type(self.pages) is not tuple or len(self.pages) != 6: | |
| raise ValueError('Invalid Archive workload or scroll count.') | |
| keys, subjects = set(), {} | |
| for scroll in self.pages: | |
| if type(scroll) is not tuple or len(scroll) != 3: | |
| raise ValueError('Archive scrolls require three pages.') | |
| series = set() | |
| for page in scroll: | |
| if type(page) is not tuple or len(page) != ARCHIVE_WORKLOADS[self.workload]: | |
| raise ValueError('Archive packet size differs from workload.') | |
| for record in page: | |
| if not isinstance(record, RecordRevision) or type(record.issued_at) is not int or record.issued_at < 1 or type(record.id) is not str or not record.id or type(record.subject) is not str or type(record.statement) is not str: | |
| raise ValueError('Invalid revision identity.') | |
| key = record.id, record.issued_at | |
| if key in keys or record.subject not in ARCHIVE_SUBJECTS or subjects.get(record.id, record.subject) != record.subject: | |
| raise ValueError('Duplicate revision or inconsistent subject.') | |
| if record.seal != 'civic' or record.authenticated is not True: | |
| raise ValueError('Revision packets require authenticated civic evidence.') | |
| if record.subject == 'restoration' and sorted(record.statement.split('>')) != ['alpha', 'beta', 'gamma']: | |
| raise ValueError('Invalid restoration statement.') | |
| if record.subject == 'authorization' and record.statement not in {w+'/'+s for w in ('Iris','Juno','Kade') for s in ('amber','cobalt','silver')}: | |
| raise ValueError('Invalid authorization statement.') | |
| if record.subject == 'egress' and record.statement not in ('0','1','2'): | |
| raise ValueError('Invalid egress statement.') | |
| keys.add(key); series.add(record.id); subjects[record.id] = record.subject | |
| if len(series) != 1: | |
| raise ValueError('Each scroll must contain one stable series.') | |
| if len(subjects) != 6 or any(list(subjects.values()).count(subject) != 2 for subject in ARCHIVE_SUBJECTS): | |
| raise ValueError('Archive requires two series for each subject.') | |
| for record in self.revisions(): | |
| if record.supersedes is not None and (record.supersedes == record.id or subjects.get(record.supersedes) != record.subject): | |
| raise ValueError('Invalid predecessor series.') | |
| for current in self.authoritative(): | |
| peers = [self.current(rid) for rid, subject in subjects.items() if subject == current.subject] | |
| if peers[0].issued_at == peers[1].issued_at or current.supersedes is None: | |
| raise ValueError('Ambiguous endpoint or missing endpoint predecessor.') | |
| predecessor = self.current(current.supersedes) | |
| if predecessor.supersedes is not None or predecessor.issued_at >= current.issued_at: | |
| raise ValueError('Invalid endpoint chain.') | |
| class WorldSpec: | |
| generation_version: int | |
| ruleset: str | |
| private_seed: int | |
| polarity: int | |
| doctrine: str | |
| maze_rotation: int | |
| archive: ArchiveSpec | Charter | |
| restoration_order: tuple | |
| current_witness: str | |
| current_seal: str | |
| correct_track: int | |
| initial_charge: int | |
| reference_cost: int | |
| infrastructure: Infrastructure | None = None | |
| notebook_bytes: int = 768 | |
| memory_profile: str = 'static' | |
| def __post_init__(self): | |
| if self.memory_profile not in ('static', 'commissioning') or (self.memory_profile == 'commissioning' and self.generation_version != 3): | |
| raise ValueError('Unsupported memory profile or generation.') | |
| if self.generation_version == 3: | |
| from .plant import Infrastructure, Charter, circuit_order, permit_decision, exit_decision, BUDGETS | |
| p = self.infrastructure | |
| if not isinstance(p, Infrastructure) or not isinstance(self.archive, Charter) or self.ruleset != 'campaign': | |
| raise ValueError('Generation three requires typed campaign infrastructure and charter.') | |
| p.validate(); self.archive.validate() | |
| if (p.load_schedule is not None) != (self.memory_profile == 'commissioning'): | |
| raise ValueError('Memory profile must match the infrastructure load schedule.') | |
| if sorted(self.archive.revisions(), key=lambda r: r.id) != sorted(p.revisions, key=lambda r: r.id): | |
| raise ValueError('Archive evidence contradicts infrastructure.') | |
| witness, seal = permit_decision(p) | |
| if (self.polarity, self.maze_rotation, self.restoration_order, self.current_witness, self.current_seal, self.correct_track, self.doctrine) != (p.calibrations[0].sensor_xor, p.calibrations[0].phase_offset, circuit_order(p), witness, seal, exit_decision(p)[0], p.opponent.kind): | |
| raise ValueError('Legacy compatibility values must be derived from infrastructure.') | |
| if self.initial_charge != BUDGETS[self.archive.workload]: | |
| raise ValueError('Generation three uses a profile-fixed initial charge budget.') | |
| if type(self.notebook_bytes) is not int or self.notebook_bytes < 0: | |
| raise ValueError('Notebook bytes must be a nonnegative integer.') | |
| return | |
| if self.generation_version != 2 or self.infrastructure is not None: | |
| raise ValueError('Unsupported generation. Use the pinned source for historical worlds.') | |
| self.archive.validate() | |
| statements = {record.subject: record.statement for record in self.archive.authoritative()} | |
| if statements != dict(restoration='>'.join(self.restoration_order), authorization=self.current_witness+'/'+self.current_seal, egress=str(self.correct_track)): | |
| raise ValueError('Archive endpoints contradict causal world facts.') | |
| def correct_records(self): | |
| if self.generation_version == 3: | |
| return tuple(self.infrastructure.current(service).id for service in self.infrastructure.services) | |
| return tuple(record.id for record in self.archive.authoritative()) | |
| class RuleState: | |
| kind: str = 'rule_chamber' | |
| latch: int = 0 | |
| fixture: str | None = None | |
| live_sensor: int | None = None | |
| gate_open: bool = False | |
| sensor_visible: bool = False | |
| pulse_count: int = 0 | |
| experiments: list = field(default_factory=list) | |
| channel: str | None = None | |
| phase_mark: int | None = None | |
| class MazeState: | |
| kind: str = 'moving_maze' | |
| cell: int = 0 | |
| clock: int = 0 | |
| rotor_offset: int = 0 | |
| scanned: bool = False | |
| collected: list = field(default_factory=list) | |
| discovered: list = field(default_factory=list) | |
| class ArchiveState: | |
| kind: str = 'archive' | |
| slot: int | None = None | |
| page: int = 0 | |
| exposed_versions: dict = field(default_factory=dict) | |
| compared_versions: set = field(default_factory=set) | |
| result: str | None = None | |
| filed: dict = field(default_factory=dict) | |
| class OsmosisState: | |
| kind: str = 'osmosis' | |
| turn: int = 0 | |
| allies: list = field(default_factory=lambda: [dict(actor=a, node='home', power=p, exhaustion=0, flag=False, support=0) for a, p in [('Ada', 5), ('Bo', 4), ('Cy', 3)]]) | |
| enemies: list = field(default_factory=lambda: [dict(actor='guard', node='east', power=5, exhaustion=0, flag=False), dict(actor='keeper', node='enemy', power=3, exhaustion=0, flag=True)]) | |
| allied_points: int = 0 | |
| enemy_points: int = 0 | |
| west_commitments: int = 0 | |
| east_commitments: int = 0 | |
| raid_telegraph: bool = False | |
| reaction: str = 'No opponent move yet.' | |
| bridge_available: bool = False | |
| contest_over: bool = False | |
| relay_claimed: bool = False | |
| relay_cooldown: int = 0 | |
| base_captured: bool = False | |
| orders: list = field(default_factory=list) | |
| loaded_crossings: int = 0 | |
| class WitnessState: | |
| kind: str = 'witness_block' | |
| player_cell: int = 0 | |
| witness_cells: dict = field(default_factory=lambda: {'Iris': 1, 'Juno': 2, 'Kade': 3}) | |
| claim: dict | None = None | |
| checks: list = field(default_factory=list) | |
| checkpoint_test: str | None = None | |
| closure_in: int = 12 | |
| clock: int = 0 | |
| class BlackoutState: | |
| kind: str = 'blackout' | |
| circuits: list = field(default_factory=lambda: [dict(id=x, bus=None, status='isolated') for x in ['alpha', 'beta', 'gamma']]) | |
| activation_order: list = field(default_factory=list) | |
| discount_used: bool = False | |
| class ExitState: | |
| kind: str = 'final_exit' | |
| installed: dict = field(default_factory=dict) | |
| track: int = 0 | |
| boarded: list = field(default_factory=list) | |
| armed_with: str | None = None | |
| valve: str | None = None | |
| pressure_vented: bool = False | |
| RoomState = RuleState | MazeState | ArchiveState | OsmosisState | WitnessState | BlackoutState | ExitState | |
| class CampaignState: | |
| phase: Phase | |
| tick: int | |
| charge: int | |
| room: RoomState | |
| team: list = field(default_factory=lambda: [dict(id=a, power=p, exhaustion=0, available=True) for a, p in [('Ada', 5), ('Bo', 4), ('Cy', 3)]]) | |
| inventory: list = field(default_factory=list) | |
| notebook: str = '' | |
| witness_authorization: str | None = None | |
| docket: dict = field(default_factory=dict) | |
| outcome: str = 'running' | |
| revision: int = 0 | |
| feedback: Any = None | |
| def canonical(value): | |
| return json.dumps(primitive(value), sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False) | |