Spaces:
Running
Running
Download python/borderland/plant.py from FatUnc6969/borderland-rl: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/spaces/FatUnc6969/borderland-rl/resolve/main/python/borderland/plant.py
- Command line
-
hf download hf://spaces/FatUnc6969/borderland-rl/python/borderland/plant.py
-
curl -L -o plant.py https://huggingface.co/spaces/FatUnc6969/borderland-rl/resolve/main/python/borderland/plant.py
16.9 kB
| from __future__ import annotations | |
| from dataclasses import asdict, dataclass, field, replace | |
| import json | |
| from typing import Literal | |
| WIDTHS = {'compact': 4, 'standard': 8, 'extended': 12} | |
| BUDGETS = {'compact': 240, 'standard': 320, 'extended': 400} | |
| LANES = ('west', 'east') | |
| WITNESSES = ('Iris', 'Juno', 'Kade') | |
| SEALS = ('amber', 'cobalt', 'silver') | |
| class Calibration: | |
| id: str | |
| sensor_xor: int | |
| phase_offset: int | |
| class Transit: | |
| freight_lane: str | |
| delivery_residue: int | |
| closure_residue: int | |
| bridge_rating: int | |
| class CircuitClause: | |
| channel: str | |
| predecessors: tuple[str, ...] | |
| bus_shift: int | |
| kind: Literal['circuit'] = field(default='circuit',init=False) | |
| class DeliveryClause: | |
| channel: str | |
| lane: str | |
| kind: Literal['delivery'] = field(default='delivery',init=False) | |
| class PermitClause: | |
| channel: str | |
| witness: str | |
| seal: str | |
| kind: Literal['permit'] = field(default='permit',init=False) | |
| class EgressClause: | |
| channel: str | |
| track_delta: int | |
| valve_shift: int | |
| kind: Literal['egress'] = field(default='egress',init=False) | |
| Clause = CircuitClause | DeliveryClause | PermitClause | EgressClause | |
| def decode_clause(body): | |
| body = dict(body) | |
| kind = body.pop('kind') | |
| if kind == 'circuit': | |
| body['predecessors'] = tuple(body['predecessors']) | |
| return {'circuit': CircuitClause, 'delivery': DeliveryClause, | |
| 'permit': PermitClause, 'egress': EgressClause}[kind](**body) | |
| class CharterRevision: | |
| id: str | |
| service: str | |
| issued_at: int | |
| supersedes: str | None | |
| applies_channel: str | None | |
| applies_bit: int | None | |
| body: Clause | |
| authenticated: bool = True | |
| seal: str = 'civic' | |
| def subject(self): | |
| return self.service | |
| def statement(self): | |
| return json.dumps(asdict(self.body), sort_keys=True, separators=(',', ':')) | |
| def to_dict(self): | |
| return dict(id=self.id, subject=self.service, issued_at=self.issued_at, | |
| supersedes=self.supersedes, applies_channel=self.applies_channel, | |
| applies_bit=self.applies_bit, body=asdict(self.body), | |
| statement=self.statement, authenticated=self.authenticated, seal=self.seal) | |
| class OpponentLaw: | |
| kind: str | |
| window: int | |
| lag: int | |
| threshold: int | |
| tie: int | |
| class LoadRating: | |
| revision: str | |
| thresholds: tuple[int, ...] | |
| class LoadTest: | |
| band: int | |
| load: int | |
| class CircuitTests: | |
| service: str | |
| tests: tuple[LoadTest, ...] | |
| class LoadSchedule: | |
| ratings: tuple[LoadRating, ...] | |
| circuits: tuple[CircuitTests, ...] | |
| kind: Literal['commissioning'] = field(default='commissioning', init=False) | |
| def curve(self, revision): | |
| return next(r.thresholds for r in self.ratings if r.revision == revision) | |
| def test(self, service, index): | |
| return next(c.tests for c in self.circuits if c.service == service)[index] | |
| def validate(self, plant): | |
| if self.kind != 'commissioning' or type(self.ratings) is not tuple or type(self.circuits) is not tuple: | |
| raise ValueError('Invalid load schedule discriminator or collections.') | |
| revisions = {r.id for r in plant.revisions if isinstance(r.body, CircuitClause)} | |
| if any(type(r) is not LoadRating or type(r.revision) is not str or type(r.thresholds) is not tuple or len(r.thresholds) != 8 or any(type(t) is not int or t not in range(4) for t in r.thresholds) for r in self.ratings): | |
| raise ValueError('Invalid load rating curve.') | |
| if len(self.ratings) != len(revisions) or {r.revision for r in self.ratings} != revisions: | |
| raise ValueError('Load ratings must cover each circuit revision exactly once.') | |
| if any(type(c) is not CircuitTests or type(c.service) is not str or type(c.tests) is not tuple or len(c.tests) != 3 or any(type(t) is not LoadTest or type(t.band) is not int or t.band not in range(8) or type(t.load) is not int or t.load not in range(3) for t in c.tests) for c in self.circuits): | |
| raise ValueError('Invalid three-test load sequence.') | |
| if len(self.circuits) != len(plant.circuits()) or {c.service for c in self.circuits} != set(plant.circuits()): | |
| raise ValueError('Load tests must cover each circuit exactly once.') | |
| class Infrastructure: | |
| calibrations: tuple[Calibration, ...] | |
| transit: Transit | |
| revisions: tuple[CharterRevision, ...] | |
| opponent: OpponentLaw | |
| load_schedule: LoadSchedule | None = None | |
| def channel(self, channel_id): | |
| return next(c for c in self.calibrations if c.id == channel_id) | |
| def services(self): | |
| return tuple(sorted({r.service for r in self.revisions})) | |
| def current(self, service): | |
| applicable = [r for r in self.revisions if r.service == service and r.authenticated | |
| and (r.applies_channel is None or | |
| self.channel(r.applies_channel).sensor_xor == r.applies_bit)] | |
| return max(applicable, key=lambda r: r.issued_at) | |
| def clause(self, kind): | |
| return next(self.current(s).body for s in self.services if self.current(s).body.kind == kind) | |
| def circuits(self): | |
| return tuple(s for s in self.services if self.current(s).body.kind == 'circuit') | |
| def validate(self): | |
| if type(self.calibrations) is not tuple or len(self.calibrations) != 2 or any(not isinstance(c, Calibration) or type(c.id) is not str or not 0 < len(c.id) <= 64 for c in self.calibrations): | |
| raise ValueError('Invalid calibration identities.') | |
| channels = {c.id for c in self.calibrations} | |
| if len(channels) != 2 or any(type(c.sensor_xor) is not int or c.sensor_xor not in (0, 1) | |
| or type(c.phase_offset) is not int or c.phase_offset not in range(4) | |
| for c in self.calibrations): | |
| raise ValueError('Invalid calibration channels.') | |
| t = self.transit | |
| if not isinstance(t, Transit) or t.freight_lane not in LANES or any(type(value) is not int for value in (t.delivery_residue,t.closure_residue,t.bridge_rating)) or t.delivery_residue not in range(4) or t.closure_residue not in range(4) or t.bridge_rating not in (0, 1): | |
| raise ValueError('Invalid transit plate.') | |
| law = self.opponent | |
| if not isinstance(law, OpponentLaw) or law.kind not in ('tracker', 'denier', 'ambusher') or any(type(value) is not int for value in (law.window,law.lag,law.threshold,law.tie)) or law.window not in (2, 3) or law.lag not in (1, 2) or law.threshold not in (2, 3) or law.tie not in (0, 1): | |
| raise ValueError('Invalid finite opponent law.') | |
| if type(self.revisions) is not tuple or any(not isinstance(r,CharterRevision) or type(r.id) is not str or not 0 < len(r.id) <= 64 or type(r.service) is not str or not 0 < len(r.service) <= 64 or type(r.issued_at) is not int or type(r.body) not in (CircuitClause,DeliveryClause,PermitClause,EgressClause) or r.body.kind != type(r.body).kind for r in self.revisions): | |
| raise ValueError('Invalid charter records.') | |
| ids = {r.id for r in self.revisions} | |
| if len(ids) != len(self.revisions) or len(self.services) not in WIDTHS.values(): | |
| raise ValueError('Invalid service identities or width.') | |
| if any(r.body.channel not in channels or r.applies_channel not in channels | {None} for r in self.revisions): | |
| raise ValueError('Charter refers to an unknown calibration channel.') | |
| for service in self.services: | |
| records = sorted((r for r in self.revisions if r.service == service), key=lambda r: r.issued_at) | |
| if len(records) != 3 or [r.issued_at for r in records] != [1, 2, 3]: | |
| raise ValueError('Each service requires a baseline and two conditional amendments.') | |
| base, left, right = records | |
| if base.supersedes is not None or base.applies_channel is not None or base.applies_bit is not None: | |
| raise ValueError('Invalid baseline clause.') | |
| if left.supersedes != base.id or right.supersedes != base.id or left.applies_channel != right.applies_channel or left.applies_channel not in channels or type(left.applies_bit) is not int or type(right.applies_bit) is not int or (left.applies_bit, right.applies_bit) != (0, 1): | |
| raise ValueError('Amendments must authenticate a unique applicable endpoint.') | |
| for r in records: | |
| b = r.body | |
| if not r.authenticated or r.seal != 'civic' or b.channel not in channels or b.kind != base.body.kind: | |
| raise ValueError('Invalid service evidence.') | |
| if isinstance(b, CircuitClause) and (type(b.bus_shift) is not int or b.bus_shift not in (0, 1) or type(b.predecessors) is not tuple or len(set(b.predecessors)) != len(b.predecessors) or any(p not in self.circuits() or p == service for p in b.predecessors)): | |
| raise ValueError('Invalid circuit clause.') | |
| if isinstance(b, DeliveryClause) and b.lane not in LANES: | |
| raise ValueError('Invalid delivery clause.') | |
| if isinstance(b, PermitClause) and (b.witness not in WITNESSES or b.seal not in SEALS): | |
| raise ValueError('Invalid permit clause.') | |
| if isinstance(b, EgressClause) and (type(b.track_delta) is not int or type(b.valve_shift) is not int or b.track_delta not in range(3) or b.valve_shift not in (0, 1)): | |
| raise ValueError('Invalid egress clause.') | |
| if sorted(self.current(s).body.kind for s in self.services if s not in self.circuits()) != ['delivery', 'egress', 'permit']: | |
| raise ValueError('Exactly one delivery, permit and egress service is required.') | |
| for bit0 in (0, 1): | |
| for bit1 in (0, 1): | |
| twin = replace(self, calibrations=tuple(replace(c, sensor_xor=bit) for c, bit in zip(self.calibrations, (bit0, bit1)))) | |
| circuit_order(twin) | |
| if self.load_schedule is not None: | |
| if type(self.load_schedule) is not LoadSchedule: | |
| raise ValueError('Invalid typed load schedule.') | |
| self.load_schedule.validate(self) | |
| class Charter: | |
| workload: str | |
| pages: tuple | |
| def page(self, slot, page): | |
| return self.pages[slot][page] | |
| def revisions(self): | |
| return tuple(r for scroll in self.pages for page in scroll for r in page) | |
| def revision(self, record_id, issued_at): | |
| return next(r for r in self.revisions() if (r.id, r.issued_at) == (record_id, issued_at)) | |
| def current(self, record_id): | |
| return next(r for r in self.revisions() if r.id == record_id) | |
| def validate(self): | |
| if self.workload not in WIDTHS or type(self.pages) is not tuple or len(self.pages) != WIDTHS[self.workload] or any(type(scroll) is not tuple or len(scroll) != 3 or any(type(page) is not tuple or len(page) != 1 for page in scroll) for scroll in self.pages): | |
| raise ValueError('Invalid consequential Archive width.') | |
| def sensor_reading(channel, latch): | |
| return (latch & 1) ^ channel.sensor_xor | |
| def phase_reading(channel, latch): | |
| return (latch + channel.phase_offset) % 4 | |
| def shutter_open(plant, clock, index, rotor_offset): | |
| return (clock + plant.calibrations[0].phase_offset + index + rotor_offset) % 4 != 0 | |
| def bridge_fatigue(plant): | |
| return plant.transit.bridge_rating | |
| def delivery_lane(plant): | |
| clause = plant.clause('delivery') | |
| return LANES[LANES.index(plant.transit.freight_lane) ^ plant.channel(clause.channel).sensor_xor ^ LANES.index(clause.lane)] | |
| def delivery_ready(plant, clock): | |
| return (clock + plant.channel(plant.clause('delivery').channel).phase_offset) % 4 == plant.transit.delivery_residue | |
| def permit_decision(plant): | |
| clause = plant.clause('permit') | |
| channel = plant.channel(clause.channel) | |
| return (WITNESSES[(WITNESSES.index(clause.witness) + LANES.index(plant.transit.freight_lane)) % 3], | |
| SEALS[(SEALS.index(clause.seal) + channel.phase_offset) % 3]) | |
| def corridor_open(plant, clock): | |
| return (clock + plant.channel(plant.clause('permit').channel).phase_offset) % 4 != plant.transit.closure_residue | |
| def circuit_bus(plant, service): | |
| clause = plant.current(service).body | |
| return LANES[plant.channel(clause.channel).sensor_xor ^ LANES.index(plant.transit.freight_lane) ^ clause.bus_shift] | |
| def compensated_bus(base_bus, thresholds, band, load): | |
| return LANES[LANES.index(base_bus) ^ (load >= thresholds[band])] | |
| def circuit_ready(plant, service, live): | |
| return set(plant.current(service).body.predecessors) <= set(live) | |
| def circuit_order(plant): | |
| remaining = set(plant.circuits()) | |
| order = [] | |
| while remaining: | |
| ready = sorted(s for s in remaining if set(plant.current(s).body.predecessors) <= set(order)) | |
| if not ready: | |
| raise ValueError('Circuit precedence must be acyclic.') | |
| order.append(ready[0]); remaining.remove(ready[0]) | |
| return tuple(order) | |
| def exit_decision(plant): | |
| clause = plant.clause('egress') | |
| channel = plant.channel(clause.channel) | |
| return ((LANES.index(plant.transit.freight_lane) + channel.phase_offset + clause.track_delta) % 3, | |
| LANES[channel.sensor_xor ^ LANES.index(plant.transit.freight_lane) ^ clause.valve_shift]) | |
| def causal_uses(plant): | |
| uses = [] | |
| for service in plant.services: | |
| revision = plant.current(service) | |
| body = revision.body | |
| facts = ['charter.' + service, 'calibration.' + body.channel, 'transit.freight_lane'] | |
| if revision.applies_channel != body.channel: | |
| facts.append('calibration.' + revision.applies_channel) | |
| if body.kind == 'delivery': | |
| facts.append('transit.delivery_residue') | |
| if body.kind == 'permit': | |
| facts.append('transit.closure_residue') | |
| if isinstance(body, CircuitClause): | |
| facts.extend('charter.' + predecessor for predecessor in body.predecessors) | |
| uses.append(dict(service=service, rule={'delivery': 'delivery_lane/delivery_ready', 'permit': 'permit_decision/corridor_open', 'circuit': 'circuit_bus/circuit_ready', 'egress': 'exit_decision'}[body.kind], sources=tuple(facts))) | |
| return tuple(uses) | |
| def opponent_lane(law, history, turn, threats, loaded_crossings): | |
| visible = history[:max(0, len(history) - law.lag + 1)][-law.window:] | |
| counts = {lane: sum((i + 1) * (order == lane) for i, order in enumerate(visible)) for lane in LANES} | |
| tie = LANES[(turn + law.tie) % 2] | |
| if law.kind == 'tracker': | |
| return max(LANES, key=lambda lane: (counts[lane], lane == tie)) | |
| if law.kind == 'denier': | |
| if threats.get('enemy', 0): | |
| return 'enemy' | |
| values = {lane: 4 * threats.get(lane, 0) + counts[lane] for lane in LANES} | |
| return max(LANES, key=lambda lane: (values[lane], lane == tie)) | |
| if loaded_crossings < law.threshold: | |
| return LANES[law.tie] | |
| return max(LANES, key=lambda lane: (counts[lane] + 3 * threats.get(lane, 0), lane == tie)) | |
| def decode_infrastructure(value): | |
| schedule = value.get('load_schedule') | |
| if schedule is not None: | |
| if type(schedule) is not dict or set(schedule) != {'kind', 'ratings', 'circuits'} or schedule['kind'] != 'commissioning': | |
| raise ValueError('Invalid load schedule wire discriminator.') | |
| if type(schedule['ratings']) not in (list, tuple) or type(schedule['circuits']) not in (list, tuple) or any(type(r) is not dict or set(r) != {'revision', 'thresholds'} or type(r['thresholds']) not in (list, tuple) for r in schedule['ratings']) or any(type(c) is not dict or set(c) != {'service', 'tests'} or type(c['tests']) not in (list, tuple) or any(type(t) is not dict or set(t) != {'band', 'load'} for t in c['tests']) for c in schedule['circuits']): | |
| raise ValueError('Invalid load schedule wire records.') | |
| schedule = LoadSchedule(tuple(LoadRating(r['revision'], tuple(r['thresholds'])) for r in schedule['ratings']), | |
| tuple(CircuitTests(c['service'], tuple(LoadTest(**t) for t in c['tests'])) for c in schedule['circuits'])) | |
| plant = Infrastructure(tuple(Calibration(**c) for c in value['calibrations']), Transit(**value['transit']), | |
| tuple(CharterRevision(**{**r, 'body': decode_clause(r['body'])}) for r in value['revisions']), | |
| OpponentLaw(**value['opponent']), schedule) | |
| plant.validate() | |
| return plant | |