Running phyelds anywhere¶
The phyelds simulator is just one host. Any system that can, for each device, run Python code periodically and deliver messages to its neighbors can run phyelds programs: a robotics simulator, real robots, a game engine, or a network simulator.
The round protocol¶
A phyelds program does not know where it runs. For each device and each round, the host goes through the three phases of the execution model:
Build NodeContext(id, sensors), gather the inbox from the current neighbors, and load the state of the device.
Call setup(context, inbox, state) on a fresh engine, and run the @aggregate function.
Call cooldown() (which returns the outbox and prunes unused state), then save state_trace() and apply outputs.
In detail, the host:
- Builds a
NodeContextwith the device ID and a dictionary of sensors (by conventionpositionandtime, plus anything the programsenses); - Collects the inbox: the last outbox of each current neighbor, as
{neighbor_id: outbox}; - Loads the state the device kept from its previous round (
{}the first time); - Sets a fresh
MutableEngineinengine(aContextVar), callsengine.get().setup(context, inbox, state), and runs the@aggregateprogram; - Saves the new outbox (
cooldown()), the new state (state_trace()), and the outputs the programstored, and sends the outbox to the neighbors.
def run_round(device: Device, inbox: dict[int, dict[str, Any]], program: Callable) -> Any:
"""
Run one round of ``program`` on ``device``.
Args:
device: the device, updated in place with its new state, outbox and outputs.
inbox: the last outbox of each neighbor, by neighbor id.
program: an ``@aggregate`` function.
Returns:
The value computed by the program in this round.
"""
engine.set(MutableEngine())
engine.get().setup(NodeContext(device.device_id, device.sensors), inbox, device.state)
result = program()
device.outbox = engine.get().cooldown() # first: it also drops the state not used
device.state = engine.get().state_trace()
device.outputs = engine.get().node_context.outputs
return result
The complete, runnable example, which drives a line of devices with plain Python objects, is docs/examples/custom_runtime.py.
phyelds.vm.rounds.run_round goes through steps 4 and 5 in one call, in the right order: give it the program, the id, the sensors, the inbox and the state, and it returns a Round with the result, the outbox, the new state and the outputs. Gathering the inbox, keeping the states and delivering the outboxes stay with the host:
from phyelds.vm.rounds import run_round
done = run_round(program, device_id, sensors, inbox, states.get(device_id))
states[device_id], outboxes[device_id] = done.state, done.outbox
The runtimes below and Device run their rounds with it.
Rules for a host¶
- Call
cooldown()beforestate_trace().cooldownalso drops the state the program did not use in this round; reading the trace first would keep stale state. - Use one engine per round.
phyelds.vm.engineis aContextVar: set a freshMutableEnginebefore each round. Being aContextVar, each thread orasynciotask sees its own engine. - Deliver copies. Outboxes and states are plain dictionaries of your values. A real network serializes them; an in-process host should copy them, or devices will be able to mutate each other's state.
- Keep the state per device. The state is opaque: store it as it is and give it back in the next round. It must survive between rounds; across a restart, the self-stabilising building blocks converge again without it, but what the program counts or remembers starts over. A
Devicekeeps its state for you, and its snapshot carries it, with the messages it holds, to another process. - Send to the current neighbors only. Neighbors that disappear simply stop appearing in the inbox; the program adapts.
- Read actuations from the outputs. Programs act on the world through
store(name, value); the host applies them (moving a robot, switching a LED).
Ways to integrate¶
- Reuse the phyelds simulator with a custom
Environment, when the host can be stepped from Python: the simulator's runner already implements the protocol (phyelds.simulator.runner.aggregate_program_runner), and you only map the host's state to nodes. This is how VMAS is integrated. - Run rounds from another simulator, when it owns the agents and the time: Mesa models do it with
phyelds-mesa, which runs a round on every agent at each step of the model, or spikes individual agents. For a host of your own,phyelds.vm.synchronous.SynchronousRuntimeandphyelds.vm.asynchronous.AsynchronousRuntimerun these rounds on devices known by their ids: give them the sensors and the neighbors of each device, as in the parallel rounds below. - Drive rounds yourself, as in the example above, when the host owns the loop (a real device, ROS node, or an external simulator calling back into Python).
-
Run each device on its own, when every device has its own process and sends its messages as bytes over a radio:
phyelds.vm.device.Deviceruns its rounds, and the host only moves the bytes. This is how MicroPython and the ESP32, Webots and ROS 2 robots run phyelds. -
Embed Python in a native simulator, when it calls C++ controllers in one process: ARGoS runs a
Deviceper robot and transports its messages over the simulated radio.
Ideal and delivered neighborhoods¶
A host builds the inbox of a device in one of two ways:
- Ideal: the host computes the neighbors, from positions or a graph, and hands the device the last outbox of each one. No message is ever lost or late. The simulator, VMAS and Mesa work this way.
- Delivered: the inbox is what the transport actually delivered. The neighbors are the devices heard from, and a lost message is simply missing. Webots, ARGoS, ROS 2 and the ESP32 work this way, through a
Device.
A host that simulates a network, such as a network simulator or a V2X model, must use the delivered model. An inbox built from positions around the network would hide the losses and delays the network is there to show.
Rounds of each host¶
Each host makes its own choices about time, scheduling and membership. A new host can pick the row closest to it as the reference to match.
| Host | Clock | Rounds | Neighborhood | Message lifetime | Join and leave |
|---|---|---|---|---|---|
| Simulator | The time of its events | One event per node per period. Nodes due at the same time run one after the other, in no set order, and read what their neighbors already sent in this round | Ideal: the neighborhood function | The last outbox of a neighbor, while it is a neighbor | Add a node and schedule its rounds; a removed node stops running |
| VMAS | The simulator's | As the simulator; VMAS steps in an event of its own | Ideal, on the positions of the VMAS agents | As the simulator | The agents of the scenario, fixed |
| Mesa | model.time |
Synchronous: each run_round runs every agent once, and each agent reads what its neighbors sent in the previous round |
Ideal: within, cell_neighbors or any function |
One round | An agent joins when it is among the agents of a round; one missing from a round is forgotten, with its state and messages |
| Webots | The simulation time | One per robot every --steps-per-round steps, each robot in its own process. Synchronous, as Webots delivers a message in the next step |
Delivered: the robots its Emitter reaches |
One round | The robots of the world; one that stops sending is forgotten at the next round |
| ARGoS | The simulation clock | One per robot per tick, one robot at a time. Synchronous, as the radio delivers on the next tick | Delivered: the range-and-bearing or simple radios | One round | The robots of the experiment; a reset clears the state and the messages |
| ROS 2 | The clock of each node: the simulation time with use_sim_time |
Each node on its own timer, every --period. Asynchronous: the rounds of neighbors are not aligned |
Delivered: the nodes heard on the shared topic, filtered by a neighbourhood strategy | --lifetime rounds (2 by default) |
A node joins with its first message, and is forgotten after lifetime silent rounds |
| GPU | The clock of each device, or rounds | BatchSynchronousRuntime: synchronous, every device at once. BatchWavefrontRuntime: wavefronts of devices that do not depend on each other |
Ideal: radius_topology or a mapping of neighbors |
Synchronous: one round. Wavefronts: the channel's retention |
The devices of the graph, fixed |
| MicroPython | The clock of each device | Each device on its own, with a round every ROUND_MS. Asynchronous: the rounds of neighbors are not aligned |
Delivered: the ESP-NOW broadcasts received | lifetime rounds (4 in the example) |
A device joins with its first message, and is forgotten after lifetime silent rounds |
Two schedules cover these hosts, and Device reproduces both round by round, on the same topology:
- Synchronous (Mesa, Webots, ARGoS): every device runs its round, and then every device sends.
packages/phyelds-mesa/tests/test_runtime_matches_devices.pychecks Mesa against such a loop, andsrc/tests/vm/test_synchronous.pychecksSynchronousRuntime. - Sequential (the simulator and VMAS): each device sends right after its own round, so a device reads what its neighbors already sent in the current round.
src/tests/vm/test_device_matches_simulator.pychecks the simulator against such a loop, andsrc/tests/vm/test_asynchronous.pychecksAsynchronousRuntime.AsynchronousRuntime.spikealso runs one device at a time when an event triggers it, keeping the state and messages of silent devices for up toretentiontime units (or untilforget).
When the rounds of neighbors are not aligned, a device can run two rounds between two messages of the same neighbor. This happens with asynchronous devices, or over a simulated network. With lifetime=1, such neighbors drop in and out from one round to the next. Keep their messages for two rounds or more.
Parallel rounds¶
In a synchronous round each device reads only what its neighbors sent in the previous round, so the rounds of the devices are independent. SynchronousRuntime can run them in a pool of threads, with the same results:
from phyelds.vm.synchronous import SynchronousRuntime
runtime = SynchronousRuntime(program, workers=8)
for step in range(steps):
sensors = {agent: {"source": agent == 0} for agent in agents}
results = runtime.run_round(sensors, neighbors) # neighbors: the ids around each id
Threads run Python in parallel only on a free-threaded Python (3.14t), and only while no imported module enables the GIL again. pandas does, and Mesa imports it, so its programs gain nothing from workers. Elsewhere one thread at a time runs Python, and more workers only add their cost. On 10,000 devices with about 8 neighbors each, 8 workers on 4 cores run the rounds of the benchmark programs 2–3 times as fast as one.