-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodels.py
More file actions
521 lines (461 loc) · 18.1 KB
/
Copy pathmodels.py
File metadata and controls
521 lines (461 loc) · 18.1 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
from __future__ import annotations
import threading
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from backend.defaults import (
DEFAULT_ADJACENCY_MODE,
DEFAULT_GEOMETRY,
DEFAULT_HEIGHT,
DEFAULT_PATCH_DEPTH,
DEFAULT_SPEED,
DEFAULT_TILING_FAMILY,
DEFAULT_WIDTH,
MAX_GRID_SIZE,
MAX_SPEED,
MIN_PATCH_DEPTH,
MIN_SPEED,
)
from backend.payload_types import (
CellMutationDeltaPayload,
CellStatePayload,
RuleDefinitionPayload,
SimulationStatePayload,
TopologySpecInput,
TopologySpecPayload,
)
from backend.simulation.topology import (
LatticeTopology,
SimulationBoard,
)
from backend.simulation.topology_catalog import (
canonicalize_topology_identity,
get_topology_definition,
get_topology_variant_for_geometry,
maximum_patch_depth_for_tiling_family,
minimum_grid_dimension_for_geometry,
minimum_patch_depth_for_tiling_family,
normalize_adjacency_mode,
resolve_geometry_key,
unsafe_maximum_patch_depth_for_tiling_family,
)
from backend.simulation.topology_family_manifest import EDGE_ADJACENCY
if TYPE_CHECKING:
from backend.rules.base import AutomatonRule
def clamp_int(value: int, minimum: int, maximum: int) -> int:
return max(minimum, min(int(value), maximum))
def clamp_float(value: float, minimum: float, maximum: float) -> float:
return max(minimum, min(float(value), maximum))
def _coerce_optional_int(value: object, fallback: int) -> int:
if value is None:
return fallback
if isinstance(value, (str, bytes, bytearray, int, float)):
return int(value)
raise TypeError(f"Expected an int-compatible value, received {type(value).__name__}.")
def _normalize_realized_extent(value: int) -> int:
return max(1, int(value))
def _topology_spec_string_value(
topology_spec: TopologySpecInput,
key: str,
fallback: str,
) -> str:
value = topology_spec.get(key)
return fallback if value is None else str(value)
def _topology_spec_int_value(
topology_spec: TopologySpecInput,
key: str,
fallback: int,
) -> int:
return _coerce_optional_int(topology_spec.get(key), fallback)
def _topology_spec_bool_value(
topology_spec: TopologySpecInput,
key: str,
fallback: bool = False,
) -> bool:
value = topology_spec.get(key)
if value is None:
return fallback
if isinstance(value, bool):
return value
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"true", "1", "yes", "on"}:
return True
if normalized in {"false", "0", "no", "off"}:
return False
if isinstance(value, (int, float)):
return bool(value)
raise TypeError(f"Expected a bool-compatible value, received {type(value).__name__}.")
MAX_UNSAFE_PATCH_DEPTH = 12
def _maximum_unsafe_patch_depth_for_tiling_family(tiling_family: str) -> int:
"""Per-family unsafe ceiling falls back to the global default unless a family
publishes its own ``unsafe_maximum`` (typically when its generator is known
to scale safely well beyond the default ``MAX_UNSAFE_PATCH_DEPTH``)."""
family_unsafe_maximum = unsafe_maximum_patch_depth_for_tiling_family(tiling_family)
family_normal_maximum = maximum_patch_depth_for_tiling_family(tiling_family)
if family_unsafe_maximum is None:
return max(MAX_UNSAFE_PATCH_DEPTH, family_normal_maximum)
return max(family_unsafe_maximum, family_normal_maximum)
@dataclass(frozen=True)
class TopologySpec:
tiling_family: str = DEFAULT_TILING_FAMILY
adjacency_mode: str = DEFAULT_ADJACENCY_MODE
sizing_mode: str = "grid"
width: int = DEFAULT_WIDTH
height: int = DEFAULT_HEIGHT
patch_depth: int = DEFAULT_PATCH_DEPTH
unsafe_size_override: bool = False
@classmethod
def from_values(
cls,
tiling_family: str = DEFAULT_TILING_FAMILY,
adjacency_mode: str | None = DEFAULT_ADJACENCY_MODE,
width: int = DEFAULT_WIDTH,
height: int = DEFAULT_HEIGHT,
patch_depth: int = DEFAULT_PATCH_DEPTH,
unsafe_size_override: bool = False,
) -> TopologySpec:
tiling_family_id, adjacency_mode = canonicalize_topology_identity(
str(tiling_family),
adjacency_mode,
)
definition = get_topology_definition(tiling_family_id)
resolved_adjacency_mode = normalize_adjacency_mode(tiling_family_id, adjacency_mode)
geometry_id = resolve_geometry_key(tiling_family_id, resolved_adjacency_mode)
minimum_grid_size = minimum_grid_dimension_for_geometry(geometry_id)
if definition.sizing_mode != "patch_depth":
normalized_patch_depth = DEFAULT_PATCH_DEPTH
elif unsafe_size_override:
normalized_patch_depth = clamp_int(
patch_depth,
MIN_PATCH_DEPTH,
_maximum_unsafe_patch_depth_for_tiling_family(tiling_family_id),
)
else:
normalized_patch_depth = clamp_int(
patch_depth,
minimum_patch_depth_for_tiling_family(tiling_family_id),
maximum_patch_depth_for_tiling_family(tiling_family_id),
)
if definition.sizing_mode == "patch_depth":
normalized_width = _normalize_realized_extent(width)
normalized_height = _normalize_realized_extent(height)
else:
normalized_width = clamp_int(width, minimum_grid_size, MAX_GRID_SIZE)
normalized_height = clamp_int(height, minimum_grid_size, MAX_GRID_SIZE)
return cls(
tiling_family=tiling_family_id,
adjacency_mode=resolved_adjacency_mode,
sizing_mode=definition.sizing_mode,
width=normalized_width,
height=normalized_height,
patch_depth=normalized_patch_depth,
unsafe_size_override=bool(unsafe_size_override),
)
@classmethod
def from_geometry_key(
cls,
geometry: str = DEFAULT_GEOMETRY,
*,
width: int = DEFAULT_WIDTH,
height: int = DEFAULT_HEIGHT,
patch_depth: int = DEFAULT_PATCH_DEPTH,
) -> TopologySpec:
variant = get_topology_variant_for_geometry(str(geometry))
return cls.from_values(
tiling_family=variant.tiling_family,
adjacency_mode=variant.adjacency_mode,
width=width,
height=height,
patch_depth=patch_depth,
)
def updated(
self,
tiling_family: str | None = None,
adjacency_mode: str | None = None,
width: int | None = None,
height: int | None = None,
patch_depth: int | None = None,
unsafe_size_override: bool | None = None,
) -> TopologySpec:
return self.from_values(
tiling_family=self.tiling_family if tiling_family is None else tiling_family,
adjacency_mode=self.adjacency_mode if adjacency_mode is None else adjacency_mode,
width=self.width if width is None else width,
height=self.height if height is None else height,
patch_depth=self.patch_depth if patch_depth is None else patch_depth,
unsafe_size_override=self.unsafe_size_override
if unsafe_size_override is None
else unsafe_size_override,
)
@property
def geometry_key(self) -> str:
return resolve_geometry_key(self.tiling_family, self.adjacency_mode)
def to_dict(self) -> TopologySpecPayload:
return {
"tiling_family": self.tiling_family,
"adjacency_mode": self.adjacency_mode,
"sizing_mode": self.sizing_mode,
"width": self.width,
"height": self.height,
"patch_depth": self.patch_depth,
}
@dataclass(frozen=True)
class SimulationConfig:
topology_spec: TopologySpec = TopologySpec()
speed: float = DEFAULT_SPEED
@classmethod
def from_values(
cls,
*,
topology_spec: TopologySpec | TopologySpecInput | None = None,
tiling_family: str = DEFAULT_TILING_FAMILY,
adjacency_mode: str | None = DEFAULT_ADJACENCY_MODE,
width: int = DEFAULT_WIDTH,
height: int = DEFAULT_HEIGHT,
speed: float = DEFAULT_SPEED,
patch_depth: int = DEFAULT_PATCH_DEPTH,
) -> SimulationConfig:
resolved_topology_spec: TopologySpec
if isinstance(topology_spec, TopologySpec):
resolved_topology_spec = TopologySpec.from_values(
tiling_family=topology_spec.tiling_family,
adjacency_mode=topology_spec.adjacency_mode,
width=topology_spec.width,
height=topology_spec.height,
patch_depth=topology_spec.patch_depth,
unsafe_size_override=topology_spec.unsafe_size_override,
)
elif topology_spec is not None:
resolved_topology_spec = TopologySpec.from_values(
tiling_family=_topology_spec_string_value(
topology_spec, "tiling_family", tiling_family
),
adjacency_mode=_topology_spec_string_value(
topology_spec,
"adjacency_mode",
adjacency_mode or EDGE_ADJACENCY,
),
width=_topology_spec_int_value(topology_spec, "width", width),
height=_topology_spec_int_value(topology_spec, "height", height),
patch_depth=_topology_spec_int_value(topology_spec, "patch_depth", patch_depth),
unsafe_size_override=_topology_spec_bool_value(
topology_spec, "unsafe_size_override"
),
)
else:
resolved_topology_spec = TopologySpec.from_values(
tiling_family=tiling_family,
adjacency_mode=adjacency_mode,
width=width,
height=height,
patch_depth=patch_depth,
)
return cls(
topology_spec=resolved_topology_spec,
speed=clamp_float(speed, MIN_SPEED, MAX_SPEED),
)
@property
def geometry(self) -> str:
return self.topology_spec.geometry_key
@property
def tiling_family(self) -> str:
return self.topology_spec.tiling_family
@property
def adjacency_mode(self) -> str:
return self.topology_spec.adjacency_mode
@property
def sizing_mode(self) -> str:
return self.topology_spec.sizing_mode
@property
def width(self) -> int:
return self.topology_spec.width
@property
def height(self) -> int:
return self.topology_spec.height
@property
def patch_depth(self) -> int:
return self.topology_spec.patch_depth
def updated(
self,
topology_spec: TopologySpec | TopologySpecInput | None = None,
tiling_family: str | None = None,
adjacency_mode: str | None = None,
width: int | None = None,
height: int | None = None,
speed: float | None = None,
patch_depth: int | None = None,
) -> SimulationConfig:
if topology_spec is not None:
if isinstance(topology_spec, TopologySpec):
base_topology_spec = self.from_values(
topology_spec=topology_spec,
width=self.width if width is None else width,
height=self.height if height is None else height,
patch_depth=self.patch_depth if patch_depth is None else patch_depth,
).topology_spec
else:
next_width_value = topology_spec.get("width")
next_height_value = topology_spec.get("height")
next_patch_depth_value = topology_spec.get("patch_depth")
base_topology_spec = self.topology_spec.updated(
tiling_family=(
self.tiling_family
if topology_spec.get("tiling_family") is None
else str(topology_spec.get("tiling_family"))
),
adjacency_mode=(
self.adjacency_mode
if topology_spec.get("adjacency_mode") is None
else str(topology_spec.get("adjacency_mode"))
),
width=(
self.width
if next_width_value is None
else _coerce_optional_int(next_width_value, self.width)
),
height=(
self.height
if next_height_value is None
else _coerce_optional_int(next_height_value, self.height)
),
patch_depth=(
self.patch_depth
if next_patch_depth_value is None
else _coerce_optional_int(next_patch_depth_value, self.patch_depth)
),
unsafe_size_override=_topology_spec_bool_value(
topology_spec, "unsafe_size_override"
),
)
else:
base_topology_spec = self.topology_spec.updated(
tiling_family=self.tiling_family if tiling_family is None else tiling_family,
adjacency_mode=self.adjacency_mode if adjacency_mode is None else adjacency_mode,
width=self.width if width is None else width,
height=self.height if height is None else height,
patch_depth=self.patch_depth if patch_depth is None else patch_depth,
)
return self.from_values(
topology_spec=base_topology_spec,
speed=self.speed if speed is None else speed,
)
@dataclass(frozen=True)
class RuleSnapshot:
name: str
display_name: str
description: str
states: list[CellStatePayload]
default_paint_state: int
supports_randomize: bool
rule_protocol: str
supports_all_topologies: bool
compatible_tiling_families: list[str] | None
@classmethod
def from_rule(cls, rule: AutomatonRule) -> RuleSnapshot:
return cls(
name=rule.name,
display_name=rule.display_name,
description=rule.description,
states=[state.to_dict() for state in rule.state_definitions()],
default_paint_state=rule.default_paint_state,
supports_randomize=rule.supports_randomize,
rule_protocol=rule.rule_protocol,
supports_all_topologies=rule.supports_all_topologies,
compatible_tiling_families=(
list(rule.compatible_tiling_families)
if rule.compatible_tiling_families is not None
else None
),
)
def to_dict(self) -> RuleDefinitionPayload:
return {
"name": self.name,
"display_name": self.display_name,
"description": self.description,
"states": self.states,
"default_paint_state": self.default_paint_state,
"supports_randomize": self.supports_randomize,
"rule_protocol": self.rule_protocol,
"supports_all_topologies": self.supports_all_topologies,
"compatible_tiling_families": self.compatible_tiling_families,
}
_state_epoch_lock = threading.Lock()
_last_state_epoch = 0
def next_state_epoch() -> int:
"""Wall-clock microseconds, strictly increasing within this process.
The floor of previous epoch + 1 orders state lifetimes hosted by this
process even when they are constructed in the same microsecond. Wall-clock
time makes values useful in diagnostics but is not a persistent ordering
guarantee across process restarts. Microseconds stay far below 2**53, so
the value survives a JavaScript number round-trip exactly.
"""
global _last_state_epoch
with _state_epoch_lock:
epoch = max(time.time_ns() // 1_000, _last_state_epoch + 1)
_last_state_epoch = epoch
return epoch
@dataclass(frozen=True)
class CellMutationDelta:
base_state_revision: int
state_revision: int
state_epoch: int
topology_revision: str
generation: int
cell_updates: tuple[tuple[str, int], ...]
def to_dict(self) -> CellMutationDeltaPayload:
return {
"base_state_revision": self.base_state_revision,
"state_revision": self.state_revision,
"state_epoch": self.state_epoch,
"topology_revision": self.topology_revision,
"generation": self.generation,
"cell_updates": [
{"id": cell_id, "state": state} for cell_id, state in self.cell_updates
],
}
@dataclass(frozen=True)
class SimulationSnapshot:
board: SimulationBoard
config: SimulationConfig
running: bool
generation: int
rule: RuleSnapshot
state_revision: int = 0
state_epoch: int = 0
@property
def topology(self) -> LatticeTopology:
return self.board.topology
@property
def cell_states(self) -> list[int]:
return self.board.cell_states
@property
def cells_by_id(self) -> dict[str, int]:
return self.board.states_by_id(omit_zero=True)
def to_dict(self) -> SimulationStatePayload:
return {
"topology_spec": self.config.topology_spec.to_dict(),
"speed": self.config.speed,
"running": self.running,
"generation": self.generation,
"state_revision": self.state_revision,
"state_epoch": self.state_epoch,
"rule": self.rule.to_dict(),
"topology_revision": self.topology.topology_revision,
"cell_states": self.cell_states,
"topology": self.topology.to_dict(),
}
@dataclass
class SimulationStateData:
config: SimulationConfig
running: bool
generation: int
rule: AutomatonRule
board: SimulationBoard
state_revision: int = 0
# Every freshly constructed state (initial build, restore, replace) gets a
# new epoch; in-place mutations keep it while state_revision advances.
state_epoch: int = field(default_factory=next_state_epoch)
@property
def topology(self) -> LatticeTopology:
return self.board.topology