Python API Reference
This page exposes the current PHIDS Python API using mkdocstrings.
Schemas and ingress
Pydantic schemas for ECS components, configuration payloads, and REST API models.
This module defines payload and response models used by the REST API as well as schemata representing ECS components and species parameters.
AllOfConditionSchema
Bases: BaseModel
Boolean AND over nested activation predicates.
Source code in src/phids/api/schemas.py
157 158 159 160 161 162 163 164 165 | |
AnyOfConditionSchema
Bases: BaseModel
Boolean OR over nested activation predicates.
Source code in src/phids/api/schemas.py
168 169 170 171 172 173 174 175 176 | |
BatchJobState
Bases: BaseModel
Runtime state record for a single Monte Carlo batch simulation job.
Each batch job corresponds to N independent simulation runs dispatched
to a :class:concurrent.futures.ProcessPoolExecutor. Progress is tracked as
completed run count relative to the total, and the final aggregate summary is
persisted to disk for retrieval via the ledger and view endpoints.
Attributes:
| Name | Type | Description |
|---|---|---|
job_id |
str
|
Universally unique identifier assigned at job creation. |
status |
Literal['queued', 'running', 'done', 'failed']
|
Lifecycle state of the job. |
completed |
int
|
Number of runs that have completed (successfully or not). |
total |
int
|
Total number of runs requested. |
scenario_name |
str
|
Display label derived from the source scenario config. |
started_at |
str
|
ISO-8601 timestamp of job creation. |
finished_at |
str | None
|
ISO-8601 timestamp of completion, or |
max_ticks |
int
|
Maximum tick count per individual run. |
Source code in src/phids/api/schemas.py
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 | |
BatchStartPayload
Bases: BaseModel
HTTP request payload for initiating a Monte Carlo batch simulation job.
Encapsulates the simulation scenario and batch execution parameters
submitted via POST /api/batch/start. The scenario field accepts a
complete :class:SimulationConfig that overrides the current server-side
draft, enabling fully reproducible parameterized batch studies.
Attributes:
| Name | Type | Description |
|---|---|---|
runs |
int
|
Number of independent simulation runs to execute in parallel. |
max_ticks |
int
|
Maximum simulation tick count per run. |
scenario_name |
str
|
Optional display label for the ledger. |
Source code in src/phids/api/schemas.py
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 | |
DietCompatibilityMatrix
Bases: BaseModel
Boolean matrix [predator_species, flora_species] indicating edibility.
Source code in src/phids/api/schemas.py
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 | |
EnemyPresenceConditionSchema
Bases: BaseModel
Leaf predicate requiring a predator species at the owner's cell.
Source code in src/phids/api/schemas.py
122 123 124 125 126 127 128 129 130 131 | |
EnvironmentalSignalConditionSchema
Bases: BaseModel
Leaf predicate requiring a minimum ambient signal concentration at the owner's cell.
Source code in src/phids/api/schemas.py
143 144 145 146 147 148 149 150 151 152 153 154 | |
FloraSpeciesParams
Bases: BaseModel
Per-species parameters for flora.
Source code in src/phids/api/schemas.py
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 | |
InitialPlantPlacement
Bases: BaseModel
Single plant to place at simulation start.
Source code in src/phids/api/schemas.py
361 362 363 364 365 366 367 | |
InitialSwarmPlacement
Bases: BaseModel
Single swarm to place at simulation start.
Source code in src/phids/api/schemas.py
370 371 372 373 374 375 376 377 | |
PlantComponentSchema
Bases: BaseModel
Pydantic schema for the Plant ECS component.
Source code in src/phids/api/schemas.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
PredatorSpeciesParams
Bases: BaseModel
Per-species parameters for predators (herbivore swarms).
Source code in src/phids/api/schemas.py
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 | |
SimulationConfig
Bases: BaseModel
Complete simulation configuration payload (REST /api/scenario/load body).
Source code in src/phids/api/schemas.py
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 | |
SimulationStatusResponse
Bases: BaseModel
Response model for simulation state queries.
Source code in src/phids/api/schemas.py
468 469 470 471 472 473 474 475 | |
SubstanceActiveConditionSchema
Bases: BaseModel
Leaf predicate requiring another substance to already be active.
Source code in src/phids/api/schemas.py
134 135 136 137 138 139 140 | |
SubstanceComponentSchema
Bases: BaseModel
Pydantic schema for a Substance (signal or toxin) ECS component.
Source code in src/phids/api/schemas.py
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 | |
SwarmComponentSchema
Bases: BaseModel
Pydantic schema for the Herbivore Swarm ECS component.
Source code in src/phids/api/schemas.py
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 | |
TriggerConditionSchema
Bases: BaseModel
Trigger condition for substance synthesis (Interaction Matrix entry).
Maps a (plant species, predator species) pair to the substance that should be synthesised when the trigger conditions are met, together with all behavioural properties of the resulting substance.
Source code in src/phids/api/schemas.py
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 | |
WindUpdatePayload
Bases: BaseModel
REST payload for dynamically updating wind vectors.
Source code in src/phids/api/schemas.py
478 479 480 481 482 | |
Scenario I/O helpers for loading and serialising SimulationConfig.
This module provides convenience functions to parse and validate simulation configurations from Python mappings or JSON files.
load_scenario_from_dict(data)
Parse and validate a simulation configuration from a mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict[str, Any]
|
Raw configuration mapping (typically decoded from JSON). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SimulationConfig |
SimulationConfig
|
Validated Pydantic configuration instance. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If the configuration is invalid. |
Source code in src/phids/io/scenario.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | |
load_scenario_from_json(path)
Load and validate a simulation configuration from a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the JSON scenario file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
SimulationConfig |
SimulationConfig
|
Validated Pydantic configuration instance. |
Source code in src/phids/io/scenario.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
scenario_to_json(config, path=None)
Serialise a SimulationConfig to a JSON string or file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SimulationConfig
|
Configuration to serialise. |
required |
path
|
str | Path | None
|
Optional file path to write the JSON to. If |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
JSON representation of the configuration. |
Source code in src/phids/io/scenario.py
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
API and UI state surfaces
FastAPI application exposing REST endpoints and WebSocket streaming for PHIDS ecosystem simulation.
This module implements the FastAPI application for PHIDS, providing REST endpoints for scenario loading, simulation lifecycle control, environmental parameter updates, and telemetry export. A WebSocket endpoint streams per-tick grid snapshots, supporting real-time visualization and analysis. The application also serves a browser-oriented surface via Jinja2-rendered HTML under / and /ui/*, together with HTMX-driven config endpoints that mutate the server-side DraftState before committing scenarios to the engine. The architectural design ensures deterministic simulation, reproducibility, and scientific integrity, supporting rigorous validation, double-buffered state management, and compliance with the Rule of 16 and O(1) spatial hash invariants. The module is central to the API and UI’s ability to model complex ecological dynamics and emergent behaviors with maximal biological fidelity.
This module-level docstring is written in accordance with Google-style documentation standards, providing a comprehensive scholarly abstract of the application's architectural role, algorithmic mechanics, and biological rationale.
batch_export(job_id, format='csv', tick_interval=1, columns=None, title=None, x_label=None, y_label=None, chart_type='timeseries')
async
Export a batch aggregate summary as CSV, LaTeX table, or PGFPlots TikZ source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
job_id
|
str
|
Unique batch job identifier. |
required |
format
|
str
|
Output format — |
'csv'
|
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
File download with appropriate Content-Type headers. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if the summary file for |
Source code in src/phids/api/main.py
1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 | |
batch_ledger(request)
async
Return an HTMX HTML fragment listing all batch jobs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 | |
batch_load_persisted()
async
Load persisted batch summaries from disk into draft active_batch_jobs.
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
Number of jobs loaded into memory. |
Source code in src/phids/api/main.py
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 | |
batch_start(payload)
async
Enqueue a Monte Carlo batch simulation job for asynchronous execution.
Validates the current server-side draft scenario, creates a
:class:~phids.api.schemas.BatchJobState record, inserts it into the
draft's active_batch_jobs registry, and dispatches a background
:class:asyncio.Task that drives the
:class:~phids.engine.batch.BatchRunner in a
:class:concurrent.futures.ProcessPoolExecutor. The HTTP response returns
immediately with the job_id so the client can begin polling the status
endpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
BatchStartPayload
|
Batch execution parameters (runs, max_ticks, scenario_name). |
required |
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
|
Raises:
| Type | Description |
|---|---|
HTTPException
|
400 if the current draft cannot produce a valid
:class: |
Source code in src/phids/api/main.py
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 | |
batch_status(request, job_id)
async
Return an HTMX HTML fragment for a single batch job progress row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI request object. |
required |
job_id
|
str
|
Unique batch job identifier. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if |
Source code in src/phids/api/main.py
1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 | |
batch_view(request, job_id)
async
Return an HTMX fragment showing aggregate statistics for a completed batch job.
Reads the persisted {job_id}_summary.json from disk and renders the
aggregate mean±σ chart data. If the file does not exist (e.g., job still
running), a placeholder message is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI request object. |
required |
job_id
|
str
|
Unique batch job identifier. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 | |
config_biotope(request, grid_width=40, grid_height=40, max_ticks=1000, tick_rate_hz=10.0, wind_x=0.0, wind_y=0.0, num_signals=4, num_toxins=4, mycorrhizal_inter_species='off', mycorrhizal_connection_cost=1.0, mycorrhizal_growth_interval_ticks=8, mycorrhizal_signal_velocity=1)
async
Persist biotope parameters to the draft and return the updated partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
grid_width
|
Annotated[int, Form()]
|
Grid width (10–80). |
40
|
grid_height
|
Annotated[int, Form()]
|
Grid height (10–80). |
40
|
max_ticks
|
Annotated[int, Form()]
|
Tick budget. |
1000
|
tick_rate_hz
|
Annotated[float, Form()]
|
WebSocket stream rate. |
10.0
|
wind_x
|
Annotated[float, Form()]
|
Uniform wind x-component. |
0.0
|
wind_y
|
Annotated[float, Form()]
|
Uniform wind y-component. |
0.0
|
num_signals
|
Annotated[int, Form()]
|
Signal layer count. |
4
|
num_toxins
|
Annotated[int, Form()]
|
Toxin layer count. |
4
|
mycorrhizal_inter_species
|
Annotated[str, Form()]
|
Checkbox value ("on" or "off"). |
'off'
|
mycorrhizal_connection_cost
|
Annotated[float, Form()]
|
Root link energy cost. |
1.0
|
mycorrhizal_growth_interval_ticks
|
Annotated[int, Form()]
|
Ticks between new root-link attempts. |
8
|
mycorrhizal_signal_velocity
|
Annotated[int, Form()]
|
Signal hops per tick. |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated biotope config form partial. |
Source code in src/phids/api/main.py
2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 | |
config_flora_add(request, name='NewFlora', base_energy=10.0, max_energy=100.0, growth_rate=5.0, survival_threshold=1.0, reproduction_interval=10, seed_min_dist=1.0, seed_max_dist=3.0, seed_energy_cost=5.0, camouflage='off', camouflage_factor=1.0)
async
Add a new flora species to the draft and return the updated table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
name
|
Annotated[str, Form()]
|
Species name. |
'NewFlora'
|
base_energy
|
Annotated[float, Form()]
|
Starting energy. |
10.0
|
max_energy
|
Annotated[float, Form()]
|
Energy capacity. |
100.0
|
growth_rate
|
Annotated[float, Form()]
|
Per-tick growth percentage. |
5.0
|
survival_threshold
|
Annotated[float, Form()]
|
Minimum energy before death. |
1.0
|
reproduction_interval
|
Annotated[int, Form()]
|
Ticks between seeds. |
10
|
seed_min_dist
|
Annotated[float, Form()]
|
Minimum dispersal distance. |
1.0
|
seed_max_dist
|
Annotated[float, Form()]
|
Maximum dispersal distance. |
3.0
|
seed_energy_cost
|
Annotated[float, Form()]
|
Energy cost per seed event. |
5.0
|
camouflage
|
Annotated[str, Form()]
|
Checkbox value ("on" or "off"). |
'off'
|
camouflage_factor
|
Annotated[float, Form()]
|
Camouflage factor (0–1). |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated flora config table partial. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
400 if Rule of 16 limit is already reached. |
Source code in src/phids/api/main.py
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 | |
config_flora_delete(species_id)
async
Remove a flora species from the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_id
|
int
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
HTMLResponse |
HTMLResponse
|
Empty string (HTMX removes the row with |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if species_id not found. |
Source code in src/phids/api/main.py
2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 | |
config_flora_update(request, species_id, name=None, base_energy=None, max_energy=None, growth_rate=None, survival_threshold=None, reproduction_interval=None, seed_min_dist=None, seed_max_dist=None, seed_energy_cost=None, camouflage=None, camouflage_factor=None)
async
Patch a single flora species in the draft and return the updated row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
species_id
|
int
|
Target species id. |
required |
name
|
Annotated[str | None, Form()]
|
Updated name (optional). |
None
|
base_energy
|
Annotated[float | None, Form()]
|
Updated base energy (optional). |
None
|
max_energy
|
Annotated[float | None, Form()]
|
Updated max energy (optional). |
None
|
growth_rate
|
Annotated[float | None, Form()]
|
Updated growth rate (optional). |
None
|
survival_threshold
|
Annotated[float | None, Form()]
|
Updated survival threshold (optional). |
None
|
reproduction_interval
|
Annotated[int | None, Form()]
|
Updated reproduction interval (optional). |
None
|
seed_min_dist
|
Annotated[float | None, Form()]
|
Updated minimum seed distance (optional). |
None
|
seed_max_dist
|
Annotated[float | None, Form()]
|
Updated maximum seed distance (optional). |
None
|
seed_energy_cost
|
Annotated[float | None, Form()]
|
Updated seed energy cost (optional). |
None
|
camouflage
|
Annotated[str | None, Form()]
|
Checkbox value "on" or absent (optional). |
None
|
camouflage_factor
|
Annotated[float | None, Form()]
|
Updated camouflage factor 0–1 (optional). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if species_id not found. |
Source code in src/phids/api/main.py
2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 | |
config_placement_plant_add(request, species_id, x, y, energy=10.0)
async
Place a plant entity at the given grid position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
species_id
|
Annotated[int, Form()]
|
Flora species id. |
required |
x
|
Annotated[int, Form()]
|
Grid x-coordinate. |
required |
y
|
Annotated[int, Form()]
|
Grid y-coordinate. |
required |
energy
|
Annotated[float, Form()]
|
Starting energy. |
10.0
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated placement list partial. |
Source code in src/phids/api/main.py
3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 | |
config_placement_plant_delete(request, index)
async
Remove a plant placement by list index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
index
|
int
|
Position in the initial_plants list. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated placement list partial. |
Source code in src/phids/api/main.py
3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 | |
config_placement_swarm_add(request, species_id, x, y, population=10, energy=50.0)
async
Place a herbivore swarm at the given grid position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
species_id
|
Annotated[int, Form()]
|
Predator species id. |
required |
x
|
Annotated[int, Form()]
|
Grid x-coordinate. |
required |
y
|
Annotated[int, Form()]
|
Grid y-coordinate. |
required |
population
|
Annotated[int, Form()]
|
Initial swarm size. |
10
|
energy
|
Annotated[float, Form()]
|
Starting energy. |
50.0
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated placement list partial. |
Source code in src/phids/api/main.py
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 | |
config_placement_swarm_delete(request, index)
async
Remove a swarm placement by list index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
index
|
int
|
Position in the initial_swarms list. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated placement list partial. |
Source code in src/phids/api/main.py
3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 | |
config_placements_clear(request)
async
Remove all plant and swarm placements from the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated placement list partial. |
Source code in src/phids/api/main.py
3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 | |
config_predator_add(request, name='NewPredator', energy_min=5.0, velocity=2, consumption_rate=10.0, reproduction_energy_divisor=1.0, energy_upkeep_per_individual=0.05, split_population_threshold=0)
async
Add a new predator species to the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
name
|
Annotated[str, Form()]
|
Species name. |
'NewPredator'
|
energy_min
|
Annotated[float, Form()]
|
Minimum per-individual energy. |
5.0
|
velocity
|
Annotated[int, Form()]
|
Movement period in ticks. |
2
|
consumption_rate
|
Annotated[float, Form()]
|
Per-tick consumption scalar. |
10.0
|
reproduction_energy_divisor
|
Annotated[float, Form()]
|
Divisor for reproduction formula. |
1.0
|
energy_upkeep_per_individual
|
Annotated[float, Form()]
|
Per-individual metabolic upkeep scalar. |
0.05
|
split_population_threshold
|
Annotated[int, Form()]
|
Explicit mitosis threshold (0 keeps legacy behavior). |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated predator config table partial. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
400 if Rule of 16 limit is reached. |
Source code in src/phids/api/main.py
2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 | |
config_predator_delete(species_id)
async
Remove a predator species from the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_id
|
int
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
HTMLResponse |
HTMLResponse
|
Empty string (HTMX removes the row). |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if species_id not found. |
Source code in src/phids/api/main.py
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 | |
config_predator_update(request, species_id, name=None, energy_min=None, velocity=None, consumption_rate=None, reproduction_energy_divisor=None, energy_upkeep_per_individual=None, split_population_threshold=None)
async
Patch a single predator species in the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
species_id
|
int
|
Target species id. |
required |
name
|
Annotated[str | None, Form()]
|
Updated name (optional). |
None
|
energy_min
|
Annotated[float | None, Form()]
|
Updated energy minimum (optional). |
None
|
velocity
|
Annotated[int | None, Form()]
|
Updated velocity (optional). |
None
|
consumption_rate
|
Annotated[float | None, Form()]
|
Updated consumption rate (optional). |
None
|
reproduction_energy_divisor
|
Annotated[float | None, Form()]
|
Updated reproduction divisor (optional). |
None
|
energy_upkeep_per_individual
|
Annotated[float | None, Form()]
|
Updated metabolic upkeep scalar (optional). |
None
|
split_population_threshold
|
Annotated[int | None, Form()]
|
Updated mitosis threshold (optional). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if species_id not found. |
Source code in src/phids/api/main.py
2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 | |
config_substance_add(request, name='Signal', is_toxin='false', lethal='false', repellent='false', synthesis_duration=3, aftereffect_ticks=0, lethality_rate=0.0, repellent_walk_ticks=3, energy_cost_per_tick=1.0, irreversible='false')
async
Add a substance definition to the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
name
|
Annotated[str, Form()]
|
Substance name. |
'Signal'
|
is_toxin
|
Annotated[str, Form()]
|
|
'false'
|
lethal
|
Annotated[str, Form()]
|
|
'false'
|
repellent
|
Annotated[str, Form()]
|
|
'false'
|
synthesis_duration
|
Annotated[int, Form()]
|
Production ticks. |
3
|
aftereffect_ticks
|
Annotated[int, Form()]
|
Linger duration. |
0
|
lethality_rate
|
Annotated[float, Form()]
|
Population eliminated per tick. |
0.0
|
repellent_walk_ticks
|
Annotated[int, Form()]
|
Random-walk duration. |
3
|
energy_cost_per_tick
|
Annotated[float, Form()]
|
Energy drain per active tick. |
1.0
|
irreversible
|
Annotated[str, Form()]
|
|
'false'
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
Response object. |
Source code in src/phids/api/main.py
2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 | |
config_substance_delete(substance_id)
async
Remove a substance definition from the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
substance_id
|
int
|
The |
required |
Returns:
| Name | Type | Description |
|---|---|---|
HTMLResponse |
HTMLResponse
|
Empty string (HTMX removes the row). |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if substance_id not found. |
Source code in src/phids/api/main.py
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 | |
config_substance_update(request, substance_id, name=None, type_label=None, synthesis_duration=None, aftereffect_ticks=None, lethality_rate=None, repellent_walk_ticks=None, energy_cost_per_tick=None, irreversible=None)
async
Patch a substance definition in the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
substance_id
|
int
|
Target substance id. |
required |
name
|
Annotated[str | None, Form()]
|
Updated name (optional). |
None
|
type_label
|
Annotated[str | None, Form()]
|
One of |
None
|
synthesis_duration
|
Annotated[int | None, Form()]
|
Updated synthesis duration (optional). |
None
|
aftereffect_ticks
|
Annotated[int | None, Form()]
|
Updated aftereffect ticks (optional). |
None
|
lethality_rate
|
Annotated[float | None, Form()]
|
Updated lethality rate (optional). |
None
|
repellent_walk_ticks
|
Annotated[int | None, Form()]
|
Updated random-walk duration (optional). |
None
|
energy_cost_per_tick
|
Annotated[float | None, Form()]
|
Updated energy drain per tick (optional). |
None
|
irreversible
|
Annotated[str | None, Form()]
|
Updated irreversible activation flag (optional). |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated substance config table partial. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if substance_id not found. |
Source code in src/phids/api/main.py
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 | |
config_trigger_rule_add(request, flora_species_id, predator_species_id, substance_id, min_predator_population=5, activation_condition_json='')
async
Add a new trigger rule to the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
flora_species_id
|
Annotated[int, Form()]
|
Flora species index. |
required |
predator_species_id
|
Annotated[int, Form()]
|
Predator species index. |
required |
substance_id
|
Annotated[int, Form()]
|
Substance to synthesise. |
required |
min_predator_population
|
Annotated[int, Form()]
|
Minimum swarm size to trigger. |
5
|
activation_condition_json
|
Annotated[str, Form()]
|
Optional JSON condition tree controlling activation after synthesis completes. |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated trigger rules partial. |
Source code in src/phids/api/main.py
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 | |
config_trigger_rule_condition_child_add(request, index, node_kind, parent_path='')
async
Append a new child node to an existing group condition.
Source code in src/phids/api/main.py
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 | |
config_trigger_rule_condition_delete(request, index, path='')
async
Delete one activation-condition node or clear the whole tree.
Source code in src/phids/api/main.py
3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 | |
config_trigger_rule_condition_node_update(request, index, path, kind=None, predator_species_id=None, min_predator_population=None, substance_id=None, signal_id=None, min_concentration=None)
async
Update or replace a node in a trigger-rule activation-condition tree.
Source code in src/phids/api/main.py
3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 | |
config_trigger_rule_condition_root(request, index, node_kind)
async
Create the root activation condition for one trigger rule.
Source code in src/phids/api/main.py
3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 | |
config_trigger_rule_delete(request, index)
async
Remove a trigger rule from the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
index
|
int
|
Rule position in the list. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated trigger rules partial. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if index out of range. |
Source code in src/phids/api/main.py
3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 | |
config_trigger_rule_update(request, index, flora_species_id=None, predator_species_id=None, substance_id=None, min_predator_population=None, activation_condition_json=None)
async
Update an existing trigger rule in the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
index
|
int
|
Rule position in the list. |
required |
flora_species_id
|
Annotated[int | None, Form()]
|
New flora species id (optional). |
None
|
predator_species_id
|
Annotated[int | None, Form()]
|
New predator species id (optional). |
None
|
substance_id
|
Annotated[int | None, Form()]
|
New substance id (optional). |
None
|
min_predator_population
|
Annotated[int | None, Form()]
|
New minimum population (optional). |
None
|
activation_condition_json
|
Annotated[str | None, Form()]
|
Optional JSON condition tree. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated trigger rules partial. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if index out of range. |
Source code in src/phids/api/main.py
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 | |
export_telemetry_csv()
async
Stream Lotka-Volterra analytics as a downloadable CSV file.
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
FastAPI response containing CSV bytes and headers. |
Source code in src/phids/api/main.py
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 | |
export_telemetry_format(data_type, format='csv', prey_species_id=0, predator_species_id=0, columns=None, flora_ids=None, predator_ids=None, title=None, x_label=None, y_label=None, x_max=None, y_max=None, tick_interval=1)
async
Export telemetry data as CSV, LaTeX table, PGFPlots TikZ source, or PNG.
Supported data_type values are timeseries (per-species population
time series), phasespace (Lotka-Volterra phase-space trajectory),
defense_economy (defense-cost to energy ratio), and biomass_stack
(stacked flora biomass proxy).
Supported format values are csv, tex_table, tex_tikz, and
png. All export formats are generated server-side using the headless
matplotlib Agg backend and the PGFPlots template generator; no LaTeX
installation is required on the server for TikZ export.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_type
|
str
|
Chart type — |
required |
format
|
str
|
Output format — |
'csv'
|
prey_species_id
|
int
|
Flora species id for phase-space x-axis. |
0
|
predator_species_id
|
int
|
Predator species id for phase-space y-axis. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
File download response with appropriate Content-Type and |
Response
|
Content-Disposition headers. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
404 if no simulation is loaded; 400 if format is unknown. |
Source code in src/phids/api/main.py
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 | |
export_telemetry_json()
async
Stream Lotka-Volterra analytics as a downloadable NDJSON file.
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
FastAPI response containing NDJSON bytes and headers. |
Source code in src/phids/api/main.py
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 | |
load_scenario(config)
async
Initialise the simulation loop with the provided configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SimulationConfig
|
Validated :class: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
Confirmation message including grid dimensions. |
Source code in src/phids/api/main.py
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 | |
log_http_requests(request, call_next)
async
Log API/UI request timing with low overhead.
DEBUG logging is emitted for successful API, HTMX, and UI requests. WARNING logging is emitted for client/server error responses.
Source code in src/phids/api/main.py
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 | |
matrix_diet(request, predator_idx, flora_idx, compatible='toggle')
async
Toggle or set a diet compatibility matrix cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
Starlette request. |
required |
predator_idx
|
Annotated[int, Form()]
|
Row index (predator species list position). |
required |
flora_idx
|
Annotated[int, Form()]
|
Column index (flora species list position). |
required |
compatible
|
Annotated[str, Form()]
|
|
'toggle'
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Updated diet matrix partial. |
Source code in src/phids/api/main.py
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 | |
pause_simulation(request)
async
Toggle pause state of the running simulation.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Any
|
Message indicating current paused/resumed state. |
Source code in src/phids/api/main.py
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 | |
placement_data()
async
Return current plant and swarm placements as JSON for canvas rendering.
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
JSON with |
Source code in src/phids/api/main.py
3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 | |
reset_simulation(request)
async
Recreate the live simulation loop from the currently loaded config.
Returns:
| Type | Description |
|---|---|
Any
|
dict[str, Any]: Confirmation and reset tick. |
Source code in src/phids/api/main.py
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 | |
root(request)
async
Render the PHIDS Control Centre root page.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 | |
scenario_export()
async
Serialise the draft state as a downloadable JSON file.
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
JSON file download response. |
Source code in src/phids/api/main.py
3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 | |
scenario_import(file=File(...))
async
Parse an uploaded JSON scenario and replace the draft.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file
|
UploadFile
|
Uploaded |
File(...)
|
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
Confirmation with imported scenario grid dimensions. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
422 if the JSON does not validate against
:class: |
Source code in src/phids/api/main.py
3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 | |
scenario_load_draft(request)
async
Commit the current draft to the simulation engine.
Equivalent to POST /api/scenario/load but uses the server-side
draft rather than a request body.
Returns:
| Name | Type | Description |
|---|---|---|
HTMLResponse |
Any
|
Updated status badge HTML fragment. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
400 if draft is invalid or missing required species. |
Source code in src/phids/api/main.py
3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 | |
simulation_status()
async
Return the current tick and simulation state flags.
Returns:
| Name | Type | Description |
|---|---|---|
SimulationStatusResponse |
SimulationStatusResponse
|
Pydantic response model with status. |
Source code in src/phids/api/main.py
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 | |
simulation_stream(websocket)
async
Stream grid state snapshots over WebSocket at each simulation tick.
The state is serialised with :mod:msgpack and compressed with
:mod:zlib for compact binary transport. If no scenario is loaded the
connection is closed with code 1008 (Policy Violation).
Source code in src/phids/api/main.py
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 | |
start_simulation(request)
async
Begin background execution of the simulation loop.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Any
|
Message confirming the simulation was started. |
Source code in src/phids/api/main.py
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 | |
step_simulation(request)
async
Execute a single deterministic simulation tick.
Returns:
| Type | Description |
|---|---|
Any
|
dict[str, Any]: Updated simulation status after the step. |
Raises:
| Type | Description |
|---|---|
HTTPException
|
If the simulation is running in the background or has terminated. |
Source code in src/phids/api/main.py
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 | |
telemetry_chart(request)
async
Return an SVG chart fragment for the HTMX polling target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 | |
telemetry_chartjs_data()
async
Return per-species population and energy series as a Chart.js-compatible JSON payload.
Iterates over raw telemetry rows to extract per-species population and energy
time series keyed by species_id. The response is consumed by the
telemetry_tabs.html partial to populate line datasets and the Lotka-Volterra
phase-space scatter canvas without additional server round-trips.
Returns:
| Name | Type | Description |
|---|---|---|
JSONResponse |
JSONResponse
|
Dict with keys |
JSONResponse
|
|
Source code in src/phids/api/main.py
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 | |
telemetry_table_preview(request, columns=None, flora_ids=None, predator_ids=None, tick_interval=1, limit=200)
async
Render an HTMX table preview aligned with current telemetry visibility filters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI request object. |
required |
columns
|
str | None
|
Optional comma-delimited DataFrame columns to include. |
None
|
flora_ids
|
str | None
|
Optional comma-delimited flora species ids to include. |
None
|
predator_ids
|
str | None
|
Optional comma-delimited predator species ids to include. |
None
|
limit
|
int
|
Maximum preview rows for UI responsiveness. |
200
|
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 | |
ui_batch_dashboard(request)
async
Render the Monte Carlo batch runner dashboard partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 | |
ui_biotope(request)
async
Return the biotope configuration form partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 | |
ui_cell_details(x, y, expected_tick=None)
async
Return rich grid-cell details for dashboard tooltips.
When a live simulation exists, data is sourced from the current ECS world and environment layers. Otherwise the draft placement preview is returned.
Source code in src/phids/api/main.py
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 | |
ui_dashboard(request)
async
Return the dashboard HTMX partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 | |
ui_diagnostics_backend(request)
async
Render structured recent backend logs for the diagnostics rail.
Source code in src/phids/api/main.py
2161 2162 2163 2164 2165 2166 2167 2168 | |
ui_diagnostics_frontend(request)
async
Render the client-side diagnostics tab shell.
Source code in src/phids/api/main.py
2153 2154 2155 2156 2157 2158 | |
ui_diagnostics_model(request)
async
Render live model counters, telemetry, and energy-deficit watch.
Source code in src/phids/api/main.py
2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 | |
ui_diet_matrix(request)
async
Return the diet compatibility matrix partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 | |
ui_flora(request)
async
Return the flora species table partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 | |
ui_placements(request)
async
Return the placement editor partial with interactive grid canvas.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 | |
ui_predators(request)
async
Return the predator species table partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 | |
ui_status_badge()
async
Return a small status <span> for HTMX outerHTML swap.
Returns:
| Name | Type | Description |
|---|---|---|
HTMLResponse |
HTMLResponse
|
Styled |
Source code in src/phids/api/main.py
2101 2102 2103 2104 2105 2106 2107 2108 | |
ui_stream(websocket)
async
Stream lightweight JSON grid snapshots for the browser canvas.
Each message contains plant_energy (2-D list), swarms
(list of {x, y, population}), tick, and max_energy.
Reconnects are handled client-side with an exponential back-off.
Source code in src/phids/api/main.py
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 | |
ui_substances(request)
async
Return the substance definitions table partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 | |
ui_tick()
async
Return the current tick as plain text for HTMX innerHTML swap.
Returns:
| Name | Type | Description |
|---|---|---|
Response |
Response
|
Tick count as plain-text body. |
Source code in src/phids/api/main.py
2090 2091 2092 2093 2094 2095 2096 2097 2098 | |
ui_trigger_matrix_legacy(request)
async
Redirect-compatible alias for the trigger rules page.
Source code in src/phids/api/main.py
2317 2318 2319 2320 | |
ui_trigger_rules(request)
async
Return the trigger rules editor partial.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
request
|
Request
|
FastAPI/Starlette request object. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
TemplateResponse |
Any
|
Rendered |
Source code in src/phids/api/main.py
2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 | |
update_wind(payload)
async
Dynamically update the simulation wind vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
WindUpdatePayload
|
:class: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict[str, Any]
|
Confirmation and the applied wind vector. |
Source code in src/phids/api/main.py
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 | |
Server-side mutable draft state for the HTMX scenario-builder UI in PHIDS.
This module implements the DraftState, a mutable server-side configuration accumulator for the PHIDS scenario-builder UI. The DraftState collects all operator choices made through the web interface, including species, substances, trigger rules, and placements, before committing them to the simulation engine via POST /api/scenario/load-draft. The module exposes a single global DraftState instance, accessed through get_draft and reset_draft, which is mutated directly by route handlers. No concurrency-safe locking is applied, as the server is designed for single-operator workbench usage. The architectural design ensures deterministic scenario construction, reproducibility, and scientific integrity, supporting rigorous validation and compliance with the Rule of 16, O(1) spatial hash invariants, and double-buffered simulation logic. The module is central to the UI’s ability to model complex ecological dynamics and emergent behaviors with maximal biological fidelity.
This module-level docstring is written in accordance with Google-style documentation standards, providing a comprehensive scholarly abstract of the DraftState's architectural role, algorithmic mechanics, and biological rationale.
DraftState
dataclass
Mutable server-side configuration accumulator for the builder UI.
Attributes:
| Name | Type | Description |
|---|---|---|
scenario_name |
str
|
Human-readable label used in the UI header. |
grid_width |
int
|
Biotope width in cells (1–80). |
grid_height |
int
|
Biotope height in cells (1–80). |
max_ticks |
int
|
Simulation tick budget. |
tick_rate_hz |
float
|
WebSocket streaming rate in ticks per second. |
wind_x |
float
|
Initial uniform wind x-component. |
wind_y |
float
|
Initial uniform wind y-component. |
num_signals |
int
|
Number of airborne signal layers. |
num_toxins |
int
|
Number of toxin layers. |
mycorrhizal_inter_species |
bool
|
Allow root connections across species. |
mycorrhizal_connection_cost |
float
|
Energy to establish a root link. |
mycorrhizal_growth_interval_ticks |
int
|
Ticks between root-growth attempts. |
mycorrhizal_signal_velocity |
int
|
Signal hops per tick through roots. |
flora_species |
list[object]
|
Flora species parameter list (species_id == index). |
predator_species |
list[object]
|
Predator species parameter list (species_id == index). |
diet_matrix |
list[list[bool]]
|
Boolean matrix |
trigger_rules |
list[TriggerRule]
|
List of explicit chemical-defense trigger rules. Multiple rules per (flora, predator) pair are allowed. |
substance_definitions |
list[SubstanceDefinition]
|
Named substance registry indexed by substance_id. |
initial_plants |
list[PlacedPlant]
|
Plants placed on the grid before simulation start. |
initial_swarms |
list[PlacedSwarm]
|
Swarms placed on the grid before simulation start. |
active_batch_jobs |
dict[str, object]
|
Registry of batch simulation jobs keyed by job_id. |
Source code in src/phids/api/ui_state.py
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 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 | |
add_flora(params)
Append a flora species and extend the diet matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
object
|
:class: |
required |
Source code in src/phids/api/ui_state.py
402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
add_plant_placement(species_id, x, y, energy)
Add a plant placement to the draft.
Source code in src/phids/api/ui_state.py
745 746 747 748 749 750 751 752 753 754 | |
add_predator(params)
Append a predator species and extend the diet matrix.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
object
|
:class: |
required |
Source code in src/phids/api/ui_state.py
467 468 469 470 471 472 473 474 475 476 477 478 479 480 | |
add_swarm_placement(species_id, x, y, population, energy)
Add a swarm placement to the draft.
Source code in src/phids/api/ui_state.py
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 | |
add_trigger_rule(flora_species_id, predator_species_id, substance_id, min_predator_population=5, activation_condition=None, required_signal_ids=None)
Append a new trigger rule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flora_species_id
|
int
|
Flora species index. |
required |
predator_species_id
|
int
|
Predator species index. |
required |
substance_id
|
int
|
Substance to synthesise. |
required |
min_predator_population
|
int
|
Minimum swarm size threshold. |
5
|
activation_condition
|
dict[str, object] | None
|
Optional nested predicate tree. |
None
|
required_signal_ids
|
list[int] | None
|
Deprecated compatibility shorthand for signal-only AND gates. |
None
|
Source code in src/phids/api/ui_state.py
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 | |
append_trigger_rule_condition_child(index, parent_path, condition)
Append a child node to a group within one trigger rule's condition tree.
Source code in src/phids/api/ui_state.py
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 | |
build_sim_config()
Assemble a :class:~phids.api.schemas.SimulationConfig.
Returns:
| Name | Type | Description |
|---|---|---|
SimulationConfig |
SimulationConfig
|
Validated simulation configuration. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no flora or predator species defined. |
Source code in src/phids/api/ui_state.py
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 | |
clear_placements()
Remove all plant and swarm placements.
Source code in src/phids/api/ui_state.py
804 805 806 807 808 809 810 811 812 813 814 | |
default()
classmethod
Create the built-in default draft state.
Source code in src/phids/api/ui_state.py
943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 | |
delete_trigger_rule_condition_node(index, path)
Delete the node at path from one trigger rule's condition tree.
Source code in src/phids/api/ui_state.py
704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 | |
rebuild_species_ids()
Re-assign sequential species_id values after list mutation.
Source code in src/phids/api/ui_state.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 | |
remove_flora(species_id)
Remove a flora species by id and clean up dependent data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_id
|
int
|
The |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no species with the given id exists. |
Source code in src/phids/api/ui_state.py
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 | |
remove_plant_placement(index)
Remove a plant placement by list index.
Source code in src/phids/api/ui_state.py
778 779 780 781 782 783 784 785 786 787 788 789 | |
remove_predator(species_id)
Remove a predator species by id and clean up dependent data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_id
|
int
|
The |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no species with the given id exists. |
Source code in src/phids/api/ui_state.py
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 522 523 524 525 526 527 528 529 530 531 532 533 | |
remove_swarm_placement(index)
Remove a swarm placement by list index.
Source code in src/phids/api/ui_state.py
791 792 793 794 795 796 797 798 799 800 801 802 | |
remove_trigger_rule(index)
Remove a trigger rule by list index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Position in the trigger_rules list. |
required |
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range. |
Source code in src/phids/api/ui_state.py
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 | |
replace_trigger_rule_condition_node(index, path, condition)
Replace the node at path inside one trigger rule's condition tree.
Source code in src/phids/api/ui_state.py
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 | |
set_trigger_rule_activation_condition(index, condition)
Replace the full activation-condition tree for one trigger rule.
Source code in src/phids/api/ui_state.py
649 650 651 652 653 654 655 | |
update_trigger_rule(index, *, flora_species_id=None, predator_species_id=None, substance_id=None, min_predator_population=None, activation_condition=None, required_signal_ids=None)
Update fields of a trigger rule in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
index
|
int
|
Position in the trigger_rules list. |
required |
flora_species_id
|
int | None
|
New flora species id (optional). |
None
|
predator_species_id
|
int | None
|
New predator species id (optional). |
None
|
substance_id
|
int | None
|
New substance id (optional). |
None
|
min_predator_population
|
int | None
|
New minimum population (optional). |
None
|
activation_condition
|
dict[str, object] | None
|
New condition tree (optional). |
None
|
required_signal_ids
|
list[int] | None
|
Deprecated compatibility shorthand for signal-only AND gates. |
None
|
Raises:
| Type | Description |
|---|---|
IndexError
|
If index is out of range. |
Source code in src/phids/api/ui_state.py
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 | |
update_trigger_rule_condition_node(index, path, **fields)
Patch selected fields on the condition node at path.
Source code in src/phids/api/ui_state.py
726 727 728 729 730 731 732 733 734 735 736 737 738 739 | |
PlacedPlant
dataclass
A plant placed on the grid before the simulation starts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_id
|
int
|
Flora species index. |
required |
x
|
int
|
Grid x-coordinate. |
required |
y
|
int
|
Grid y-coordinate. |
required |
energy
|
float
|
Initial energy reserve. |
required |
Source code in src/phids/api/ui_state.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | |
PlacedSwarm
dataclass
A herbivore swarm placed on the grid before the simulation starts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
species_id
|
int
|
Predator species index. |
required |
x
|
int
|
Grid x-coordinate. |
required |
y
|
int
|
Grid y-coordinate. |
required |
population
|
int
|
Initial swarm population. |
required |
energy
|
float
|
Initial energy reserve. |
required |
Source code in src/phids/api/ui_state.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
SubstanceDefinition
dataclass
Named substance with physical/biological properties.
A substance definition captures how a chemical behaves once produced. The trigger matrix separately records which (flora, predator) pair activates synthesis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
substance_id
|
int
|
Layer index in |
required |
name
|
str
|
Human-readable label shown in the UI. |
'Signal'
|
is_toxin
|
bool
|
|
False
|
lethal
|
bool
|
Lethal-toxin flag (ignored if |
False
|
repellent
|
bool
|
Repellent-toxin flag. |
False
|
synthesis_duration
|
int
|
Ticks to complete synthesis (production time). |
3
|
aftereffect_ticks
|
int
|
Ticks the substance lingers after emission ceases. |
0
|
lethality_rate
|
float
|
Population units eliminated per tick (β). |
0.0
|
repellent_walk_ticks
|
int
|
Random-walk duration on repel trigger. |
3
|
energy_cost_per_tick
|
float
|
Energy drained from the plant per active tick. |
1.0
|
irreversible
|
bool
|
Keep the substance active permanently once activated. |
False
|
precursor_signal_id
|
int
|
Signal id required before activation (−1 = none). |
-1
|
min_predator_population
|
int
|
Minimum swarm size to trigger synthesis. |
5
|
Source code in src/phids/api/ui_state.py
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 | |
type_label
property
Human-readable substance type.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
One of |
TriggerRule
dataclass
One explicit chemical-defense trigger rule.
A rule says: "when flora species flora_species_id is attacked by
predator species predator_species_id with at least
min_predator_population individuals, synthesise substance
substance_id. Optional nested activation conditions can additionally
require active substances and/or other enemy presences via explicit
all_of / any_of predicate trees. None = unconditional."
Multiple rules may share the same (flora, predator) pair to express production of different substances simultaneously.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flora_species_id
|
int
|
Flora species index (0-based). |
required |
predator_species_id
|
int
|
Predator species index (0-based). |
required |
substance_id
|
int
|
Substance layer index to synthesise. |
required |
min_predator_population
|
int
|
Minimum swarm size to trigger this rule. |
5
|
activation_condition
|
dict[str, object] | None
|
Optional JSON-serialisable predicate tree. |
None
|
Source code in src/phids/api/ui_state.py
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 | |
get_draft()
Return the current draft state, initialising a default if needed.
Returns:
| Name | Type | Description |
|---|---|---|
DraftState |
DraftState
|
The active draft configuration. |
Source code in src/phids/api/ui_state.py
989 990 991 992 993 994 995 996 997 998 999 | |
reset_draft()
Reset the draft state to the built-in default.
Source code in src/phids/api/ui_state.py
1019 1020 1021 1022 1023 | |
set_draft(state)
Replace the active draft state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
DraftState
|
New :class: |
required |
Source code in src/phids/api/ui_state.py
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 | |
Engine orchestration
Simulation loop orchestration for deterministic, double-buffered ecosystem advancement.
This module implements the principal simulation driver for PHIDS, responsible for advancing the grid environment and ECS world through a rigorously ordered sequence of systems: flow field, lifecycle, interaction, signaling, and telemetry/termination. The simulation loop enforces deterministic update ordering via an asyncio lock, ensuring reproducibility and scientific validity. Double-buffering is employed to maintain a strict separation between read and write states, preventing race conditions and guaranteeing the integrity of biological phenomena such as systemic acquired resistance, metabolic attrition, and mitosis. Per-tick snapshots are captured for replay and telemetry, supporting comprehensive analysis of emergent behaviors and ecological dynamics. The architectural design reflects the project's commitment to data-oriented modeling, O(1) spatial hash lookups, and the Rule of 16 for memory allocation, thereby simulating complex plant-herbivore interactions with maximal computational efficiency and biological fidelity.
This module-level docstring is written in accordance with Google-style documentation standards, providing a detailed scholarly abstract of the simulation loop's algorithmic mechanics and biological rationale.
SimulationLoop
Orchestrate deterministic, double-buffered simulation ticks.
Double-buffering is achieved by keeping a read-copy of the grid state
while writing results to live objects; these writes become the read
state for the next tick. Concurrent access is protected by
asyncio.Lock.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SimulationConfig
|
Validated :class: |
required |
Source code in src/phids/engine/loop.py
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 522 523 524 525 526 527 528 529 530 531 532 533 | |
__init__(config)
Initialise the SimulationLoop with the provided configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
SimulationConfig
|
Validated SimulationConfig instance from the API payload. |
required |
Source code in src/phids/engine/loop.py
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 | |
get_state_snapshot()
Return a serialisable snapshot of the current grid state.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Snapshot containing tick, termination state and |
dict[str, Any]
|
environment dictionary (from :meth: |
Source code in src/phids/engine/loop.py
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 | |
pause()
Toggle the paused state.
Flips the paused boolean.
Source code in src/phids/engine/loop.py
269 270 271 272 273 274 275 276 277 | |
run()
async
Run the simulation loop until termination at configured tick rate.
The loop respects paused and sleeps to maintain tick_rate_hz.
Source code in src/phids/engine/loop.py
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 | |
start()
Mark the simulation as running.
Sets running state to True and clears the paused flag.
Source code in src/phids/engine/loop.py
260 261 262 263 264 265 266 267 | |
step()
async
Execute one deterministic simulation tick.
The method performs the ordered phases of the simulation (flow-field update, lifecycle, interaction, signaling, telemetry) while holding an asyncio lock to ensure async-safety. After processing it evaluates termination conditions.
Returns:
| Name | Type | Description |
|---|---|---|
TerminationResult |
TerminationResult
|
Termination state after the tick. |
Source code in src/phids/engine/loop.py
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 | |
stop()
Halt the simulation by clearing the running flag.
Source code in src/phids/engine/loop.py
279 280 281 282 | |
update_wind(vx, vy)
Update the environment uniform wind vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vx
|
float
|
Wind X component. |
required |
vy
|
float
|
Wind Y component. |
required |
Source code in src/phids/engine/loop.py
498 499 500 501 502 503 504 505 506 507 508 509 | |
ECS components
Plant ECS component dataclass.
This module defines the :class:PlantComponent dataclass which stores the
runtime state for a plant entity used by lifecycle and signaling systems.
PlantComponent
dataclass
Holds runtime state for a single plant entity.
Attributes:
| Name | Type | Description |
|---|---|---|
entity_id |
int
|
ECS entity identifier. |
species_id |
int
|
Flora species index. |
x, |
y
|
Current grid coordinates. |
energy |
float
|
Current energy reserve E_i,j(t). |
max_energy |
float
|
Species-specific energy capacity E_max. |
base_energy |
float
|
Initial energy used by growth formula. |
growth_rate |
float
|
Per-tick growth rate in percent. |
survival_threshold |
float
|
Energy threshold below which the plant dies. |
reproduction_interval |
int
|
Ticks between reproduction attempts. |
seed_min_dist |
float
|
Minimum seed dispersal distance. |
seed_max_dist |
float
|
Maximum seed dispersal distance. |
seed_energy_cost |
float
|
Energy cost paid for reproduction. |
camouflage |
bool
|
Whether constitutive camouflage is active. |
camouflage_factor |
float
|
Gradient multiplier when camouflaged. |
last_reproduction_tick |
int
|
Tick of the most recent reproduction. |
last_energy_loss_cause |
str | None
|
Most recent energetically relevant action label used for death diagnostics attribution. |
mycorrhizal_connections |
set[int]
|
Set of connected plant entity ids. |
Source code in src/phids/engine/components/plant.py
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 | |
Herbivore Swarm ECS component dataclass.
Defines :class:SwarmComponent storing runtime state for a herbivore
swarm entity used by interaction and telemetry subsystems.
SwarmComponent
dataclass
Holds runtime state for a single herbivore swarm entity.
Attributes:
| Name | Type | Description |
|---|---|---|
entity_id |
int
|
ECS entity identifier. |
species_id |
int
|
Predator species index. |
x, |
y
|
Current grid coordinates. |
population |
int
|
Current swarm head-count. |
initial_population |
int
|
Head-count at spawn; used for mitosis checks. |
energy |
float
|
Current energy reserve. |
energy_min |
float
|
Minimum energy per individual. |
velocity |
int
|
Movement period in ticks between moves. |
consumption_rate |
float
|
Per-tick consumption scalar. |
reproduction_energy_divisor |
float
|
Species-level growth throttle. |
energy_upkeep_per_individual |
float
|
Metabolic upkeep scalar applied each tick. |
split_population_threshold |
int
|
Explicit population threshold for mitosis (<=0 keeps legacy rule). |
repelled |
bool
|
Whether the swarm is currently repelled by toxin. |
repelled_ticks_remaining |
int
|
Remaining ticks of repelled behavior. |
move_cooldown |
int
|
Ticks remaining until the next movement. |
last_dx |
int
|
Last movement delta on the x-axis (-1, 0, 1). |
last_dy |
int
|
Last movement delta on the y-axis (-1, 0, 1). |
Source code in src/phids/engine/components/swarm.py
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 | |
Substance ECS component dataclass.
Defines :class:SubstanceComponent for volatile signals and toxins emitted
by plants in response to herbivore presence.
SubstanceComponent
dataclass
Holds runtime state for a single substance entity.
A substance represents either a volatile signal (VOC) or a toxin.
Attributes:
| Name | Type | Description |
|---|---|---|
entity_id |
int
|
ECS entity identifier. |
substance_id |
int
|
Layer index into signal or toxin layers. |
owner_plant_id |
int
|
Entity id of the producing plant. |
is_toxin |
bool
|
True for toxins, False for signals. |
synthesis_duration |
int
|
Configured synthesis duration in ticks. |
synthesis_remaining |
int
|
Ticks remaining before activation. |
active |
bool
|
Whether the substance is currently active. |
aftereffect_ticks |
int
|
Configured aftereffect duration after trigger removal. |
aftereffect_remaining_ticks |
int
|
Remaining aftereffect duration at runtime. |
lethal |
bool
|
Whether the toxin is lethal. |
lethality_rate |
float
|
Individuals eliminated per tick when lethal. |
repellent |
bool
|
Whether the toxin repels swarms. |
repellent_walk_ticks |
int
|
Duration of repelled random-walk in ticks. |
precursor_signal_id |
int
|
Single required precursor signal id (-1 = none). Legacy. |
precursor_signal_ids |
tuple[int, ...]
|
All signal ids that must ALL be active before this substance activates (AND logic). Empty tuple = no precursor required. |
activation_condition |
dict[str, object] | None
|
Optional nested activation predicate tree stored in JSON-serialisable form for runtime evaluation and tooltip display. |
energy_cost_per_tick |
float
|
Energy drained from the owner plant per active tick. |
irreversible |
bool
|
Whether activation remains permanently on once active. |
triggered_this_tick |
bool
|
Whether the trigger condition was satisfied in the current signaling pass. |
Source code in src/phids/engine/components/substances.py
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 | |
Core runtime structures
GridEnvironment: NumPy-backed biotope with 2-D convolution diffusion and explicit double-buffering.
This module implements the GridEnvironment, a cellular automata biotope for PHIDS, using NumPy arrays to represent all state layers. All layers are pre-allocated according to the Rule of 16, ensuring fixed memory allocation and avoiding dynamic resizing during simulation. The environment employs explicit read/write double-buffering to prevent race conditions and guarantee deterministic simulation of biological phenomena such as Gaussian diffusion, systemic acquired resistance, and metabolic attrition. The convolution kernel is pre-computed and truncated to eliminate subnormal floats, maintaining computational efficiency and scientific accuracy. The architectural design is tightly coupled to the ECSWorld and flow-field systems, supporting O(1) spatial hash lookups and reproducible ecological dynamics.
This module-level docstring is written in accordance with Google-style documentation standards, providing a comprehensive scholarly abstract of the biotope's algorithmic mechanics and biological rationale.
GridEnvironment
Manage vectorised biotope layers and diffusion helpers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
width
|
int
|
Grid width W (1 ≤ W ≤ GRID_W_MAX). |
40
|
height
|
int
|
Grid height H (1 ≤ H ≤ GRID_H_MAX). |
40
|
num_signals
|
int
|
Number of signal substance layers (1 ≤ n ≤ MAX_SUBSTANCE_TYPES). |
4
|
num_toxins
|
int
|
Number of toxin substance layers (1 ≤ n ≤ MAX_SUBSTANCE_TYPES). |
4
|
Source code in src/phids/engine/core/biotope.py
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 | |
__init__(width=40, height=40, num_signals=4, num_toxins=4)
Initialise grid layers and double-buffered storage.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
width
|
int
|
Grid width in cells. |
40
|
height
|
int
|
Grid height in cells. |
40
|
num_signals
|
int
|
Number of airborne signal layers. |
4
|
num_toxins
|
int
|
Number of toxin layers. |
4
|
Source code in src/phids/engine/core/biotope.py
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 | |
clear_plant_energy(x, y, species_id)
Clear a species-specific energy contribution in the write buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
int
|
X coordinate. |
required |
y
|
int
|
Y coordinate. |
required |
species_id
|
int
|
Species index. |
required |
Source code in src/phids/engine/core/biotope.py
256 257 258 259 260 261 262 263 264 | |
diffuse_signals()
Compute one diffusion tick for all signal layers.
This applies a 2-D convolution with a pre-computed Gaussian kernel, advects the result by a bounded integer cell shift (zero-filled at boundaries), and applies a sparsity threshold to zero small values.
Source code in src/phids/engine/core/biotope.py
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 | |
rebuild_energy_layer()
Recompute aggregate plant energy layer and swap buffers.
Aggregates per-species write buffers into the global write buffer, then swaps read/write buffers so that subsequent reads observe the newly-written values.
Source code in src/phids/engine/core/biotope.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
set_plant_energy(x, y, species_id, value)
Set a species-specific energy contribution in the write buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
int
|
X coordinate. |
required |
y
|
int
|
Y coordinate. |
required |
species_id
|
int
|
Species index. |
required |
value
|
float
|
Energy contribution (clamped to >= 0). |
required |
Source code in src/phids/engine/core/biotope.py
245 246 247 248 249 250 251 252 253 254 | |
set_uniform_wind(vx, vy)
Fill wind layers with a spatially uniform vector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vx
|
float
|
X component of the wind. |
required |
vy
|
float
|
Y component of the wind. |
required |
Source code in src/phids/engine/core/biotope.py
147 148 149 150 151 152 153 154 155 | |
to_dict()
Return a lightweight snapshot dict suitable for msgpack serialisation. Returns: dict: Mapping containing numpy arrays converted to nested lists.
Source code in src/phids/engine/core/biotope.py
270 271 272 273 274 275 276 277 278 279 280 281 282 | |
update_wind_at(x, y, vx, vy)
Update the wind vector at a single grid cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
int
|
X coordinate. |
required |
y
|
int
|
Y coordinate. |
required |
vx
|
float
|
X component of the wind. |
required |
vy
|
float
|
Y component of the wind. |
required |
Source code in src/phids/engine/core/biotope.py
157 158 159 160 161 162 163 164 165 166 167 | |
Entity-Component-System (ECS) registry with O(1) spatial hash support for deterministic ecosystem simulation.
This module implements the ECSWorld registry, a flat entity-component system designed to maximize computational efficiency and biological fidelity in the PHIDS simulation engine. The ECS maintains a flat entity registry, per-component indices for rapid queries, and a spatial hash grid enabling O(1) membership lookups for entities occupying a cell. This architecture is essential for simulating plant-herbivore interactions, metabolic attrition, and systemic acquired resistance without incurring O(N^2) locality costs. The design strictly adheres to data-oriented principles, avoiding Python object graphs in favor of NumPy-backed state matrices and pre-allocated buffers (Rule of 16). The spatial hash is central to the simulation's ability to model emergent ecological phenomena with deterministic reproducibility and scientific rigor.
This module-level docstring is written in accordance with Google-style documentation standards, providing a comprehensive scholarly abstract of the ECS registry's algorithmic mechanics and biological rationale.
ECSWorld
Central ECS registry managing entities, components and spatial hash.
The world provides helpers for entity lifecycle, component indexing and a spatial hash grid for efficient cell membership queries.
Source code in src/phids/engine/core/ecs.py
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 | |
__init__()
Initialise the ECS world and its internal indices.
Attributes initialized
_next_id: Next entity id to allocate. _entities: Mapping of entity id to Entity. _component_index: Index mapping component types to entity id sets. _spatial_hash: Grid cell roster mapping (x, y) to entity id sets.
Source code in src/phids/engine/core/ecs.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
add_component(entity_id, component)
Attach a component to an entity and update the component index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
int
|
Target entity id. |
required |
component
|
Any
|
Component instance to attach. |
required |
Source code in src/phids/engine/core/ecs.py
156 157 158 159 160 161 162 163 164 165 | |
collect_garbage(dead_entity_ids)
Bulk destroy a list of dead entities.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dead_entity_ids
|
list[int]
|
List of entity ids to remove. |
required |
Source code in src/phids/engine/core/ecs.py
255 256 257 258 259 260 261 262 | |
create_entity()
Allocate and register a new entity.
Returns:
| Name | Type | Description |
|---|---|---|
Entity |
Entity
|
Newly created entity object. |
Source code in src/phids/engine/core/ecs.py
102 103 104 105 106 107 108 109 110 111 112 | |
destroy_entity(entity_id)
Remove an entity and clean up index and spatial hash references.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
int
|
Identifier of the entity to destroy. |
required |
Source code in src/phids/engine/core/ecs.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
entities_at(x, y)
Return the set of entity ids occupying a cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
int
|
X coordinate. |
required |
y
|
int
|
Y coordinate. |
required |
Returns:
| Type | Description |
|---|---|
set[int]
|
set[int]: Entity ids occupying the cell. |
Source code in src/phids/engine/core/ecs.py
239 240 241 242 243 244 245 246 247 248 249 | |
get_entity(entity_id)
Return the entity instance for the given id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
int
|
Entity identifier. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Entity |
Entity
|
Matching entity. |
Source code in src/phids/engine/core/ecs.py
141 142 143 144 145 146 147 148 149 150 | |
has_entity(entity_id)
Return True if the entity exists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
int
|
Entity identifier. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if present. |
Source code in src/phids/engine/core/ecs.py
130 131 132 133 134 135 136 137 138 139 | |
move_entity(entity_id, old_x, old_y, new_x, new_y)
Atomically update spatial hash when an entity moves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
int
|
Entity identifier. |
required |
old_x
|
int
|
Previous X coordinate. |
required |
old_y
|
int
|
Previous Y coordinate. |
required |
new_x
|
int
|
New X coordinate. |
required |
new_y
|
int
|
New Y coordinate. |
required |
Source code in src/phids/engine/core/ecs.py
226 227 228 229 230 231 232 233 234 235 236 237 | |
query(*component_types)
Yield all entities that possess all listed component types.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*component_types
|
type[Any]
|
Component classes/types to require. |
()
|
Yields:
| Name | Type | Description |
|---|---|---|
Entity |
Entity
|
Entities matching the component set. |
Source code in src/phids/engine/core/ecs.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
register_position(entity_id, x, y)
Register an entity at grid cell (x, y).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
int
|
Entity identifier. |
required |
x
|
int
|
X coordinate of the cell. |
required |
y
|
int
|
Y coordinate of the cell. |
required |
Source code in src/phids/engine/core/ecs.py
204 205 206 207 208 209 210 211 212 | |
remove_component(entity_id, component_type)
Detach a component of the specified type from an entity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
int
|
Target entity id. |
required |
component_type
|
type[Any]
|
Component class/type to remove. |
required |
Source code in src/phids/engine/core/ecs.py
167 168 169 170 171 172 173 174 175 176 | |
unregister_position(entity_id, x, y)
Remove an entity from a grid cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
entity_id
|
int
|
Entity identifier. |
required |
x
|
int
|
X coordinate of the cell. |
required |
y
|
int
|
Y coordinate of the cell. |
required |
Source code in src/phids/engine/core/ecs.py
214 215 216 217 218 219 220 221 222 223 224 | |
Entity
dataclass
Lightweight wrapper holding an entity id and attached components.
Source code in src/phids/engine/core/ecs.py
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 | |
add_component(component)
Attach a component instance keyed by its type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component
|
Any
|
Component instance to attach. |
required |
Source code in src/phids/engine/core/ecs.py
31 32 33 34 35 36 37 | |
get_component(component_type)
Return attached component of the given type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component_type
|
type[C]
|
The component class/type to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
C
|
The component instance for the entity. |
Source code in src/phids/engine/core/ecs.py
39 40 41 42 43 44 45 46 47 48 | |
has_component(component_type)
Return True if the entity has a component of the given type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component_type
|
type[Any]
|
Component class/type to check for. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if present, False otherwise. |
Source code in src/phids/engine/core/ecs.py
50 51 52 53 54 55 56 57 58 59 | |
remove_component(component_type)
Detach a component of the given type (no-op if absent).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
component_type
|
type[Any]
|
Component class/type to remove. |
required |
Source code in src/phids/engine/core/ecs.py
61 62 63 64 65 66 67 | |
Flow-field gradient generation accelerated with Numba @njit for deterministic ecological simulation.
This module implements the flow-field gradient computation for PHIDS, leveraging Numba JIT compilation to accelerate iterative Jacobi propagation. The global attraction gradient is computed by combining plant attraction and toxin repulsion, then propagating values to neighbors. The scalar field is intended to populate GridEnvironment.flow_field, supporting O(1) spatial hash lookups and deterministic simulation of emergent ecological phenomena such as predator movement, systemic acquired resistance, and metabolic attrition. The design strictly adheres to data-oriented principles, using NumPy arrays and pre-allocated buffers, and truncates subnormal floats to maintain computational efficiency and scientific rigor. The module is central to the simulation's ability to model complex plant-herbivore interactions with maximal biological fidelity.
This module-level docstring is written in accordance with Google-style documentation standards, providing a comprehensive scholarly abstract of the flow-field's algorithmic mechanics and biological rationale.
apply_camouflage(flow_field, x, y, factor)
Attenuate the flow-field gradient at cell (x, y) in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
flow_field
|
NDArray[float64]
|
Mutable gradient array |
required |
x
|
int
|
X coordinate. |
required |
y
|
int
|
Y coordinate. |
required |
factor
|
float
|
Multiplier in [0, 1]; 0 = invisible, 1 = no attenuation. |
required |
Source code in src/phids/engine/core/flow_field.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | |
compute_flow_field(plant_energy, toxin_layers, width, height)
Public wrapper: sum toxin layers and delegate to the Numba kernel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plant_energy
|
NDArray[float64]
|
Shape |
required |
toxin_layers
|
NDArray[float64]
|
Shape |
required |
width
|
int
|
Grid width. |
required |
height
|
int
|
Grid height. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float64]
|
npt.NDArray[np.float64]: Flow-field gradient of shape |
Source code in src/phids/engine/core/flow_field.py
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
Engine systems
Lifecycle system: plant growth, reproduction, mycorrhizal networking and death.
This module implements per-tick plant updates including growth according to species parameters, reproduction attempts, establishment of symbiotic root connections, and culling of dead plants. It should run before interaction and signaling phases.
run_lifecycle(world, env, tick, flora_species_params, mycorrhizal_connection_cost=1.0, mycorrhizal_growth_interval_ticks=8, mycorrhizal_inter_species=False, plant_death_causes=None)
Execute one lifecycle tick: grow, connect, reproduce, and cull.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
world
|
ECSWorld
|
The ECS world registry. |
required |
env
|
GridEnvironment
|
The GridEnvironment instance. |
required |
tick
|
int
|
Current simulation tick index. |
required |
flora_species_params
|
dict[int, object]
|
Mapping of species_id to species parameters. |
required |
mycorrhizal_connection_cost
|
float
|
Energy cost per new root connection. |
1.0
|
mycorrhizal_growth_interval_ticks
|
int
|
Ticks between new root-growth attempts. At most one new link is created per attempt. |
8
|
mycorrhizal_inter_species
|
bool
|
Allow inter-species root connections. |
False
|
plant_death_causes
|
dict[str, int] | None
|
Mapping of death causes to their respective counts. |
None
|
Source code in src/phids/engine/systems/lifecycle.py
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 | |
Interaction system: swarm movement, feeding and continuous energy economy.
This module implements swarm behaviour including movement (gradient navigation or random walk), feeding using the diet compatibility matrix, metabolic attrition and mitosis. Spatial hash lookups provide O(1) co-occupancy checks.
run_interaction(world, env, diet_matrix, tick, plant_death_causes=None)
Execute one interaction tick for all swarm entities.
The routine performs movement, feeding using the diet matrix, toxin damage, metabolic attrition, and mitosis, then collects dead swarms and rebuilds the plant energy layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
world
|
ECSWorld
|
ECSWorld registry. |
required |
env
|
GridEnvironment
|
GridEnvironment instance (provides flow_field and toxin layers). |
required |
diet_matrix
|
list[list[bool]]
|
Compatibility matrix indexed by predator_id then flora_id. |
required |
tick
|
int
|
Current simulation tick (reserved for future use). |
required |
plant_death_causes
|
dict[str, int] | None
|
Mapping of death causes to their respective counts. |
None
|
Source code in src/phids/engine/systems/interaction.py
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 | |
Signaling system: substance synthesis, activation and local toxin effects.
This module manages the lifecycle of VOC signals and defensive toxins,
including trigger evaluation via the spatial hash, synthesis countdowns,
delegation of airborne signal diffusion to :class:GridEnvironment,
mycorrhizal signal relays and application of toxin effects to swarms.
run_signaling(world, env, trigger_conditions, mycorrhizal_inter_species, signal_velocity, tick, plant_death_causes=None)
Execute one signaling tick, handling synthesis, emission and diffusion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
world
|
ECSWorld
|
ECS world registry. |
required |
env
|
GridEnvironment
|
Grid environment holding signal/toxin layers. |
required |
trigger_conditions
|
dict[int, list[object]]
|
Mapping of flora species_id to trigger schemas. |
required |
mycorrhizal_inter_species
|
bool
|
Whether inter-species mycorrhizal signaling is permitted. |
required |
signal_velocity
|
int
|
Ticks per hop for root-network relays. |
required |
tick
|
int
|
Current simulation tick. |
required |
plant_death_causes
|
dict[str, int] | None
|
Mapping of death causes to their respective counts. |
None
|
Source code in src/phids/engine/systems/signaling.py
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 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 | |
Telemetry and replay
Telemetry analytics: accumulate per-tick Lotka-Volterra metrics into a Polars DataFrame.
The :class:TelemetryRecorder accumulates per-tick population and energy metrics into an
in-memory row buffer and exposes a lazily-constructed :class:polars.DataFrame for
downstream export, Chart.js serialisation, and statistical aggregation. Each recorded tick
captures both aggregate scalars (total flora energy, total predator population) and
granular per-species dictionaries (population and aggregate energy keyed by
species_id), thereby enabling precise Lotka-Volterra phase-space visualisation and
Monte Carlo batch evaluation.
The per-species data is accumulated via defaultdict accumulators inside
:meth:TelemetryRecorder.record so that sparse or absent species naturally resolve to
zero without requiring sentinel guards. Active defense-maintenance costs are also
attributed per flora species_id by querying
:class:~phids.engine.components.substances.SubstanceComponent entities whose active
flag is set, summing their energy_cost_per_tick contribution. This diagnostic
facilitates identification of runaway defense-maintenance scenarios in which an entire
connected mycorrhizal network commits metabolic resources to sustained chemical defense
under persistent herbivore pressure.
The :attr:TelemetryRecorder.dataframe property materialises a fully rectangular Polars
DataFrame that preserves per-species breakdowns as typed scalar columns
(plant_{id}_pop, plant_{id}_energy, defense_cost_{id},
swarm_{id}_pop). This columnar representation exposes the per-species data through
the primary CSV and NDJSON export routes without requiring callers to reach into the raw
_rows buffer or invoke the auxiliary
:func:~phids.telemetry.export.telemetry_to_dataframe pandas-conversion helper. Species
identifiers observed across the accumulated session are unioned and sorted before columns
are written, guaranteeing a consistent column order even when individual ticks contain
sparse species sets.
TelemetryRecorder
Accumulate per-tick Lotka-Volterra metrics into a Polars DataFrame.
The recorder appends one row per tick and materialises a lazily-built Polars
DataFrame containing aggregate scalars together with per-species flat columns.
Aggregate fields comprise tick, total_flora_energy, flora_population,
predator_clusters, predator_population, and the five per-tick plant death
cause counts (death_reproduction, death_mycorrhiza,
death_defense_maintenance, death_herbivore_feeding,
death_background_deficit). Per-species breakdowns are exposed as typed Polars
scalar columns following the naming convention plant_{id}_pop,
plant_{id}_energy, swarm_{id}_pop, and defense_cost_{id}, where
{id} denotes the integer species_id. Missing species in a given tick are
zero-filled to guarantee a fully rectangular DataFrame suitable for vectorised
statistical operations and direct CSV or NDJSON export.
Source code in src/phids/telemetry/analytics.py
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 | |
dataframe
property
Return recorded metrics as a Polars DataFrame with per-species flat columns (lazily built).
Per-species dictionary accumulators stored in each row's
plant_pop_by_species, plant_energy_by_species,
swarm_pop_by_species, and defense_cost_by_species fields are
flattened into typed Polars scalar columns named plant_{id}_pop
(Int64), plant_{id}_energy (Float64), swarm_{id}_pop
(Int64), and defense_cost_{id} (Float64) respectively.
Missing species values for a given tick are zero-filled, ensuring the
resulting DataFrame is fully rectangular and free of null entries.
All species identifiers observed across the full retention window are unioned and sorted prior to column construction, so that the column layout is deterministic and consistent even when individual ticks contain sparse species sets due to extinction or delayed colonisation events.
The empty-state DataFrame (no recorded ticks) retains only the stable aggregate schema; per-species columns are added dynamically once at least one tick has been recorded and at least one species has been observed, reflecting the inherently dynamic cardinality of the species pool across independent simulation sessions.
Returns:
| Type | Description |
|---|---|
DataFrame
|
pl.DataFrame: DataFrame containing aggregate and per-species flat |
DataFrame
|
telemetry columns for all accumulated ticks. |
__init__(max_rows=MAX_TELEMETRY_TICKS)
Create a TelemetryRecorder with empty in-memory buffers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_rows
|
int
|
Maximum in-memory tick rows retained in the rolling window. |
MAX_TELEMETRY_TICKS
|
Source code in src/phids/telemetry/analytics.py
67 68 69 70 71 72 73 74 75 | |
get_latest_metrics()
Return the latest recorded telemetry row, if available.
Returns:
| Type | Description |
|---|---|
dict[str, Any] | None
|
dict[str, Any] | None: Most recent metrics row or |
Source code in src/phids/telemetry/analytics.py
174 175 176 177 178 179 180 181 182 | |
get_species_ids()
Return the union of all flora and predator species ids seen so far.
Scans all accumulated rows to collect every species id that has appeared at least once in the simulation history, enabling Chart.js dataset generation to create series for species that may have gone extinct mid-simulation.
Returns:
| Type | Description |
|---|---|
dict[str, list[int]]
|
dict[str, list[int]]: Keys |
dict[str, list[int]]
|
each mapping to a sorted list of integer species identifiers. |
Source code in src/phids/telemetry/analytics.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
record(world, tick, plant_death_causes=None)
Snapshot current ECS metrics and append to the internal buffer.
Iterates over all :class:~phids.engine.components.plant.PlantComponent,
:class:~phids.engine.components.swarm.SwarmComponent, and active
:class:~phids.engine.components.substances.SubstanceComponent entities
to build aggregate and per-species counters. All per-species keys are
written unconditionally (with zero defaults) so that downstream pandas
and Polars operations encounter a fully rectangular schema without null
values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
world
|
ECSWorld
|
The ECS world to sample entity components from. |
required |
tick
|
int
|
Current simulation tick index. |
required |
plant_death_causes
|
dict[str, int] | None
|
Per-tick plant death diagnostics keyed by cause. |
None
|
Source code in src/phids/telemetry/analytics.py
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 | |
reset()
Clear accumulated telemetry and reset internal cache.
Source code in src/phids/telemetry/analytics.py
286 287 288 289 290 | |
Termination condition evaluators (Z1–Z7).
Provide checks for simulation termination conditions such as maximum ticks, species extinction and aggregate population/energy thresholds.
TerminationResult
dataclass
Result returned by :func:check_termination.
Attributes:
| Name | Type | Description |
|---|---|---|
terminated |
bool
|
True when a termination condition has been met. |
reason |
str
|
Human-readable explanation for termination. |
Source code in src/phids/telemetry/conditions.py
16 17 18 19 20 21 22 23 24 25 26 | |
check_termination(world, tick, max_ticks, z2_flora_species=-1, z3_check_all_flora=True, z4_predator_species=-1, z5_check_all_predators=True, z6_max_flora_energy=-1.0, z7_max_predator_population=-1)
Evaluate termination conditions and return the first triggered one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
world
|
ECSWorld
|
ECS world registry. |
required |
tick
|
int
|
Current simulation tick. |
required |
max_ticks
|
int
|
Z1 – maximum allowed ticks (halt when reached). |
required |
z2_flora_species
|
int
|
Species id that triggers Z2 on extinction (-1 disables). |
-1
|
z3_check_all_flora
|
bool
|
If True, halt when all flora are extinct (Z3). |
True
|
z4_predator_species
|
int
|
Species id that triggers Z4 on extinction (-1 disables). |
-1
|
z5_check_all_predators
|
bool
|
If True, halt when all predators are extinct (Z5). |
True
|
z6_max_flora_energy
|
float
|
Aggregate flora energy threshold for Z6 (-1 disables). |
-1.0
|
z7_max_predator_population
|
int
|
Aggregate predator population threshold for Z7 (-1 disables). |
-1
|
Returns:
| Name | Type | Description |
|---|---|---|
TerminationResult |
TerminationResult
|
Object indicating whether termination occurred and why. |
Source code in src/phids/telemetry/conditions.py
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 | |
Academic export pipeline for PHIDS telemetry data.
This module implements the export layer that transforms Polars DataFrames produced by
:class:~phids.telemetry.analytics.TelemetryRecorder into publication-ready artifacts
suitable for peer-reviewed manuscript submission. Four output formats are supported:
- CSV — Plain-text comma-separated values compatible with spreadsheet tools and statistical computing environments.
- NDJSON — Newline-delimited JSON for programmatic ingestion.
- PNG — Rasterized chart rendered via
matplotlibusing theAgg(headless) backend, supporting both time-series and Lotka-Volterra phase-space views. - PGFPlots TikZ — LaTeX
pgfplotssource code generated from matplotlib figures via thepgfbackend or an internal template generator, enabling vector-quality figures with full typography control for publication workflows. Note that TikZ generation does not require a local LaTeX installation at the Python level; the returned string is intended to be compiled by the end user's LaTeX toolchain. - LaTeX Table — A
\begin{tabular}environment generated viapandas.DataFrame.to_latexwithbooktabsformatting (\toprule,\midrule,\bottomrule), suitable for direct inclusion in manuscripts.
Per-species flattening is performed by :func:telemetry_to_dataframe, which converts the
nested per-species dicts stored in :attr:TelemetryRecorder._rows into a wide-format
pandas DataFrame with columns named plant_{id}_pop, plant_{id}_energy,
swarm_{id}_pop, and defense_cost_{id}. This columnar layout is compatible with
both the matplotlib plotting functions and the LaTeX table generator.
The matplotlib.use("Agg") call is scoped to the function body (not the module level)
to avoid conflicting with interactive display backends in notebook or GUI contexts.
aggregate_to_dataframe(aggregate, *, flora_names=None, predator_names=None)
Convert a batch aggregate summary dict to a wide pandas DataFrame.
Constructs a per-tick DataFrame from the mean and standard deviation arrays
stored inside the aggregate summary produced by
:func:~phids.engine.batch.aggregate_batch_telemetry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
aggregate
|
dict[str, Any]
|
Dict with keys |
required |
flora_names
|
dict[int, str] | None
|
Optional display name mapping for flora species. |
None
|
predator_names
|
dict[int, str] | None
|
Optional display name mapping for predator species. |
None
|
Returns:
| Type | Description |
|---|---|
'pd.DataFrame'
|
pd.DataFrame: Wide-format DataFrame ready for export. |
Source code in src/phids/telemetry/export.py
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 | |
decimate_dataframe(df, tick_interval)
Return a tick-decimated DataFrame using stride semantics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
'pd.DataFrame'
|
Input DataFrame. |
required |
tick_interval
|
int
|
Row stride; values below 1 are treated as 1. |
required |
Returns:
| Type | Description |
|---|---|
'pd.DataFrame'
|
pd.DataFrame: Decimated DataFrame. |
Source code in src/phids/telemetry/export.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 | |
export_bytes_csv(df)
Return the telemetry DataFrame serialized as CSV bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Polars DataFrame to serialize. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
CSV-encoded bytes. |
Source code in src/phids/telemetry/export.py
200 201 202 203 204 205 206 207 208 209 | |
export_bytes_json(df)
Return the telemetry DataFrame serialized as NDJSON bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Polars DataFrame to serialize. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
NDJSON-encoded bytes. |
Source code in src/phids/telemetry/export.py
212 213 214 215 216 217 218 219 220 221 | |
export_bytes_tex_table(rows, *, columns=None, include_flora_ids=None, include_predator_ids=None, tick_interval=1)
Render the telemetry rows as a booktabs LaTeX tabular environment.
Flattens per-species dicts into a wide pandas DataFrame via
:func:telemetry_to_dataframe, then serialises to LaTeX using
DataFrame.to_latex(index=False), which emits
\toprule, \midrule, and \bottomrule rules consistent with
the booktabs LaTeX package conventions expected in peer-reviewed journals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
list[dict[str, Any]]
|
Raw telemetry rows from |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
UTF-8 encoded LaTeX |
Source code in src/phids/telemetry/export.py
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 | |
export_csv(df, path)
Write the telemetry DataFrame to a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Polars DataFrame produced by the telemetry recorder. |
required |
path
|
str | Path
|
Destination file path. |
required |
Source code in src/phids/telemetry/export.py
180 181 182 183 184 185 186 187 | |
export_json(df, path)
Write the telemetry DataFrame to a newline-delimited JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Polars DataFrame produced by the telemetry recorder. |
required |
path
|
str | Path
|
Destination file path. |
required |
Source code in src/phids/telemetry/export.py
190 191 192 193 194 195 196 197 | |
filter_dataframe_columns(df, columns)
Return a DataFrame restricted to requested columns.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
'pd.DataFrame'
|
Input pandas DataFrame. |
required |
columns
|
str | None
|
Optional CSV column list. |
required |
Returns:
| Type | Description |
|---|---|
'pd.DataFrame'
|
pd.DataFrame: Filtered DataFrame containing only existing columns. |
Source code in src/phids/telemetry/export.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | |
filter_telemetry_rows(rows, *, flora_ids=None, predator_ids=None)
Filter per-species nested telemetry dictionaries by id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
list[dict[str, Any]]
|
Raw telemetry rows. |
required |
flora_ids
|
str | None
|
Optional CSV flora species-id list. |
None
|
predator_ids
|
str | None
|
Optional CSV predator species-id list. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
list[dict[str, Any]]: Row list with filtered species dictionaries. |
Source code in src/phids/telemetry/export.py
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 | |
generate_png_bytes(rows, plot_type='timeseries', *, flora_names=None, predator_names=None, prey_species_id=0, predator_species_id=0, include_flora_ids=None, include_predator_ids=None, title=None, x_label=None, y_label=None, x_max=None, y_max=None, dpi=150)
Render a matplotlib chart to PNG bytes using the headless Agg backend.
Supports five plot_type modes:
"timeseries"— Overlaid line chart with one series per flora and predator species, sharing a common tick x-axis and a left y-axis for population counts. Total flora energy is plotted on a secondary y-axis."phasespace"— Lotka-Volterra phase-space scatter withshowLine=Truesemantics, plotting the aggregate population ofprey_species_idflora on the x-axis and the aggregate population ofpredator_species_idherbivores on the y-axis as a connected trajectory through time, revealing orbital cycles."defense_economy"— Per-species ratio of defense maintenance cost to per-species stored plant energy."biomass_stack"— Stacked area chart of per-species flora population, used as a biomass proxy under fixed-cell carrying-capacity constraints."survival_probability"— Per-tick percentage of runs remaining alive.
The matplotlib.use("Agg") backend directive is applied locally before any
pyplot call to prevent interference with interactive display backends.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
list[dict[str, Any]]
|
Raw telemetry rows from |
required |
plot_type
|
str
|
Chart mode — |
'timeseries'
|
flora_names
|
dict[int, str] | None
|
Optional display names keyed by flora species id. |
None
|
predator_names
|
dict[int, str] | None
|
Optional display names keyed by predator species id. |
None
|
prey_species_id
|
int
|
Flora species id for phase-space x-axis. |
0
|
predator_species_id
|
int
|
Predator species id for phase-space y-axis. |
0
|
dpi
|
int
|
Output resolution in dots per inch. |
150
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
PNG-encoded figure bytes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/phids/telemetry/export.py
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 | |
generate_tikz_str(rows, plot_type='timeseries', *, flora_names=None, predator_names=None, prey_species_id=0, predator_species_id=0, include_flora_ids=None, include_predator_ids=None, title=None, x_label=None, y_label=None, x_max=None, y_max=None)
Generate a PGFPlots LaTeX source string for publication-quality figures.
Produces a self-contained tikzpicture environment using the pgfplots
package. The output does not require the tikzplotlib library; instead,
coordinates are injected directly into \addplot commands via a
\pgfplotstable-compatible inline coordinate format. This approach ensures
compatibility with any LaTeX installation providing pgfplots >= 1.16.
The generated code is intended for compilation with pdflatex, xelatex,
or lualatex after pasting into a document preamble that includes
\usepackage{pgfplots} and \pgfplotsset{compat=1.18}.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
list[dict[str, Any]]
|
Raw telemetry rows from |
required |
plot_type
|
str
|
Chart mode — |
'timeseries'
|
flora_names
|
dict[int, str] | None
|
Optional display names keyed by flora species id. |
None
|
predator_names
|
dict[int, str] | None
|
Optional display names keyed by predator species id. |
None
|
prey_species_id
|
int
|
Flora species id for phase-space x-axis. |
0
|
predator_species_id
|
int
|
Predator species id for phase-space y-axis. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
LaTeX source code for a complete |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/phids/telemetry/export.py
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 | |
telemetry_to_dataframe(rows)
Flatten per-species nested dicts from raw telemetry rows into a pandas DataFrame.
Converts the list of row dicts accumulated by
:class:~phids.telemetry.analytics.TelemetryRecorder into a wide-format
pandas DataFrame. Each per-species nested dictionary (plant_pop_by_species,
plant_energy_by_species, swarm_pop_by_species, defense_cost_by_species)
is exploded into individual columns named plant_{id}_pop, plant_{id}_energy,
swarm_{id}_pop, and defense_cost_{id} respectively. Missing species in a
given tick are filled with zero, ensuring a fully rectangular output suitable for
vectorised statistical operations and LaTeX table generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
rows
|
list[dict[str, Any]]
|
Raw row list from |
required |
Returns:
| Type | Description |
|---|---|
'pd.DataFrame'
|
pd.DataFrame: Wide-format DataFrame with one row per tick and one column per |
'pd.DataFrame'
|
scalar metric or per-species measurement. |
Source code in src/phids/telemetry/export.py
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 | |
Replay I/O for deterministic simulations.
This module provides compact binary serialisation of per-tick state
snapshots using :mod:msgpack. Each tick is stored as a discrete frame to
support deterministic re-simulation and on-disk replay files.
ReplayBuffer
Append-only buffer of binary-serialised tick frames.
Supports writing to and reading from a binary replay file for deterministic re-simulation.
Source code in src/phids/io/replay.py
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 | |
__init__()
Create an empty replay buffer.
The buffer stores msgpack-serialised frames in an append-only list.
Source code in src/phids/io/replay.py
52 53 54 55 56 57 | |
__len__()
Return number of stored frames.
Source code in src/phids/io/replay.py
67 68 69 | |
append(state)
Serialize and append a tick state to the buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
Tick state mapping to serialize and store. |
required |
Source code in src/phids/io/replay.py
59 60 61 62 63 64 65 | |
get_frame(tick)
Return the deserialised state for the specified tick index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tick
|
int
|
Index of the frame to retrieve (0-based). |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Decoded state mapping for the requested tick. |
Source code in src/phids/io/replay.py
71 72 73 74 75 76 77 78 79 80 | |
load(path)
classmethod
Load a replay file produced by :meth:save.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the binary replay file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
ReplayBuffer |
ReplayBuffer
|
Populated buffer ready for re-simulation. |
Source code in src/phids/io/replay.py
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 | |
save(path)
Write all frames to a binary replay file.
The file format is an append of records where each record begins with a 4-byte little-endian unsigned integer describing the following frame length, immediately followed by the frame bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Destination file path. |
required |
Source code in src/phids/io/replay.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
deserialise_state(data)
Deserialize a msgpack frame into a state mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
msgpack-encoded bytes produced by :func: |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: Decoded state mapping. |
Source code in src/phids/io/replay.py
32 33 34 35 36 37 38 39 40 41 42 | |
serialise_state(state)
Serialise a state snapshot to a msgpack frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
dict[str, Any]
|
Tick state mapping (for example, the output of
|
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
msgpack-encoded frame. |
Source code in src/phids/io/replay.py
19 20 21 22 23 24 25 26 27 28 29 | |
Shared utilities
Shared constants for PHIDS.
This module defines compile-time limits (Rule of 16), grid bounds and other numeric sentinel values used across the codebase.
Central logging configuration for PHIDS.
The package uses a single idempotent logging bootstrap so API, UI, engine, telemetry, and I/O modules share consistent formatting and levels. Configuration is environment-driven to keep detailed debugging available without paying for verbose logs by default.
InMemoryLogHandler
Bases: Handler
Capture recent structured log entries for the diagnostics UI.
Source code in src/phids/shared/logging_config.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
emit(record)
Append one formatted record to the in-memory diagnostics buffer.
Source code in src/phids/shared/logging_config.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
configure_logging(*, force=False)
Configure PHIDS package logging.
Environment variables
PHIDS_LOG_LEVEL: Package log level (default INFO).
PHIDS_LOG_FILE: Optional file path for a rotating debug log.
PHIDS_LOG_FILE_LEVEL: File handler level (default DEBUG).
PHIDS_LOG_SIM_DEBUG_INTERVAL: Tick interval for engine summaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
force
|
bool
|
Reconfigure logging even if already configured. |
False
|
Source code in src/phids/shared/logging_config.py
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 | |
get_recent_logs(*, limit=80)
Return the newest structured PHIDS log entries first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
limit
|
int
|
Maximum number of entries to return. |
80
|
Returns:
| Type | Description |
|---|---|
list[dict[str, str]]
|
list[dict[str, str]]: Structured log entries for diagnostics panels. |
Source code in src/phids/shared/logging_config.py
54 55 56 57 58 59 60 61 62 63 64 65 | |
get_simulation_debug_interval()
Return the interval used for periodic simulation debug summaries.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Tick interval for DEBUG summaries. |
Source code in src/phids/shared/logging_config.py
103 104 105 106 107 108 109 110 111 112 | |