Spaces:
Running
Running
File size: 16,917 Bytes
2719bf4 | 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 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 | 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')
@dataclass(frozen=True)
class Calibration:
id: str
sensor_xor: int
phase_offset: int
@dataclass(frozen=True)
class Transit:
freight_lane: str
delivery_residue: int
closure_residue: int
bridge_rating: int
@dataclass(frozen=True)
class CircuitClause:
channel: str
predecessors: tuple[str, ...]
bus_shift: int
kind: Literal['circuit'] = field(default='circuit',init=False)
@dataclass(frozen=True)
class DeliveryClause:
channel: str
lane: str
kind: Literal['delivery'] = field(default='delivery',init=False)
@dataclass(frozen=True)
class PermitClause:
channel: str
witness: str
seal: str
kind: Literal['permit'] = field(default='permit',init=False)
@dataclass(frozen=True)
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)
@dataclass(frozen=True)
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'
@property
def subject(self):
return self.service
@property
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)
@dataclass(frozen=True)
class OpponentLaw:
kind: str
window: int
lag: int
threshold: int
tie: int
@dataclass(frozen=True)
class LoadRating:
revision: str
thresholds: tuple[int, ...]
@dataclass(frozen=True)
class LoadTest:
band: int
load: int
@dataclass(frozen=True)
class CircuitTests:
service: str
tests: tuple[LoadTest, ...]
@dataclass(frozen=True)
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.')
@dataclass(frozen=True)
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)
@property
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)
@dataclass(frozen=True)
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
|