Skip to content

phyelds.libraries

phyelds.libraries.device

Device library: what a device knows about itself, its sensors and its outputs.

A Sensor or an Actuator names a sensor or an output once: the program and its host share the object, rather than repeating a string that nobody checks.

velocity = Actuator('velocity', check=_finite_numbers) module-attribute

Where the device moves, and how fast: a sequence of finite numbers, one per axis.

source = Sensor('source') module-attribute

Whether the device is the source its host is configured with; false if none is.

heading = Sensor('heading') module-attribute

Where the device faces: a horizontal unit vector, in the frame of the world.

obstacle = Sensor('obstacle') module-attribute

Away from what the proximity sensors of the device see; None without them.

led = Actuator('led') module-attribute

The colour of the LEDs of the device: three integer RGB channels, 0–255.

label = Actuator('label') module-attribute

A text about the device, which its host shows or logs.

Sensor(name)

Bases: Generic[T]

A sensor of the devices, by name: source = Sensor("source"), then source.sense().

Parameters:

Name Type Description Default
name str

The name the host gives the sensor.

required

sense()

The value of the sensor on the current device.

Actuator(name, check=None)

Bases: Generic[T]

An actuator of the devices: the program sends it a value, the host reads it.

The value is an output (see store): it holds until the next round of the device, which sends another one, or none.

Parameters:

Name Type Description Default
name str

The name of the output.

required
check Callable[[T], bool] | None

Whether a value is valid, if only some are: send refuses the others.

None

send(value)

Send value to the actuator of the current device.

Parameters:

Name Type Description Default
value T

What the actuator does, in this round.

required

Returns:

Type Description
T

value, so that a program can return what it does: return velocity.send(v).

Raises:

Type Description
ValueError

If the check of the actuator refuses value.

read(outputs, default=None)

What a program sent, among the outputs of its device; default if nothing.

local_id()

Return the ID of the current device.

Returns:

Type Description
int

The ID of the device running the program.

sense(sensor)

Read a sensor of the current device.

Parameters:

Name Type Description Default
sensor str

The name of the sensor.

required

Returns:

Type Description
Any

The value of the sensor.

local_position()

Return the position of the current device.

Returns:

Type Description
Tuple[float, float]

The position of the device, as given by its "position" sensor.

store(output, value)

Write an output of the current device, replacing its previous value.

Outputs leave the program: the simulator, for instance, collects them in each node's "outputs".

Parameters:

Name Type Description Default
output str

The name of the output.

required
value Any

The value to store.

required

phyelds.libraries.distances

This module contains functions to calculate distances between nodes in the neighborhood. These functions may be used by other libraries to compute system-wise properties.

neighbors_distances(position=None)

Read measured neighbor distances, or compute them from shared positions.

Parameters:

Name Type Description Default
position Sequence[float] | None

Optional coordinate sequence for the current node. When omitted, the neighbors_distances sensor (an ID-to-distance map) is used if present, otherwise local_position() is used. Supports any dimension (2D, 3D, N-D). Measured distances use the host's units and only include neighbors aligned at this call.

None

Returns:

Type Description
NeighborhoodField[float]

A NeighborhoodField[float] with the distance to each neighbor (0.0 for the local node).

hops_distance()

Return the distance to each neighbor in hops.

Returns:

Type Description
NeighborhoodField[int]

A field that is 1 for every neighbor and 0 for the current device.

phyelds.libraries.spreading

Diffusion (information) library for phyelds.

Provides high-level spreading primitives (distance_to, cast_from, broadcast) parameterized by pluggable propagation strategies (bellman_ford, path_coherent).

bellman_ford(*, bottom=0.0, top=float('inf'), distance_accumulator=lambda a, b: a + b)

Create a Bellman-Ford spreading strategy.

Parameters:

Name Type Description Default
bottom float

Zero-distance value at a source.

0.0
top float

Maximum distance bound.

float('inf')
distance_accumulator Callable[[float, float], float]

Function combining two distances.

lambda a, b: a + b

Returns:

Type Description
SpreadingStrategy

A pluggable SpreadingStrategy.

path_coherent(max_diameter=sys.maxsize, *, bottom=0.0, top=float('inf'), distance_accumulator=lambda a, b: a + b)

Create a fast self-healing spreading strategy based on coherent loop-free paths.

Parameters:

Name Type Description Default
max_diameter int

Maximum number of hops allowed along any path.

maxsize
bottom float

Zero-distance value at a source.

0.0
top float

Maximum distance bound.

float('inf')
distance_accumulator Callable[[float, float], float]

Function combining two distances.

lambda a, b: a + b

Returns:

Type Description
SpreadingStrategy

A pluggable SpreadingStrategy immune to the rising-value problem.

distance_to(source, distances=None, *, strategy=None)

Calculate the distance to the nearest source node in the network.

Parameters:

Name Type Description Default
source bool

True if the current node is a source.

required
distances NeighborhoodField[float] | None

Field of edge distances to neighbors. Defaults to hops_distance().

None
strategy SpreadingStrategy | None

Optional spreading strategy (e.g. path_coherent()). When omitted, uses classic Bellman-Ford propagation.

None

Returns:

Type Description
float

The estimated distance to the nearest source.

cast_from(source, data, accumulation, distances=None, *, strategy=None)

Propagate and transform data from the nearest source node along a gradient.

Parameters:

Name Type Description Default
source bool

True if the current node is a source.

required
data T

Value produced at a source (and fallback when no source is reachable).

required
accumulation Callable[..., T]

Transformation applied at each hop. May accept (neighbor_data), (edge_distance, neighbor_data), or (from_source, edge_distance, neighbor_data).

required
distances NeighborhoodField[float] | None

Field of edge distances to neighbors. Defaults to hops_distance().

None
strategy SpreadingStrategy | None

Optional spreading strategy (bellman_ford() or path_coherent()).

None

Returns:

Type Description
T

The propagated and accumulated value at the current node.

broadcast(source, data, distances=None, *, strategy=None)

Broadcast data from the nearest source node across the network.

Parameters:

Name Type Description Default
source bool

True if the current node is a source.

required
data T

Value to broadcast from the source (and fallback when unreachable).

required
distances NeighborhoodField[float] | None

Field of edge distances to neighbors. Defaults to hops_distance().

None
strategy SpreadingStrategy | None

Optional spreading strategy (bellman_ford() or path_coherent()).

None

Returns:

Type Description
T

The value broadcast from the nearest source.

distance_between(source, target, distances=None, *, strategy=None)

Compute the distance between source and target and broadcast it across the network.

Parameters:

Name Type Description Default
source bool

True on source devices.

required
target bool

True on target devices.

required
distances NeighborhoodField[float] | None

Field of edge distances to neighbors. Defaults to hops_distance().

None
strategy SpreadingStrategy | None

Optional spreading strategy (bellman_ford() or path_coherent()).

None

Returns:

Type Description
float

The distance between the nearest source and target.

channel(source, target, width=0.0, distances=None, *, strategy=None)

Select the devices on a near-shortest route from source to target.

A device belongs to the channel when the shortest route from source to target through it is at most width longer than the shortest route overall.

Parameters:

Name Type Description Default
source bool

True on source devices.

required
target bool

True on target devices.

required
width float

Non-negative slack around the shortest path length.

0.0
distances NeighborhoodField[float] | None

Field of edge distances to neighbors. Defaults to hops_distance().

None
strategy SpreadingStrategy | None

Optional spreading strategy (bellman_ford() or path_coherent()).

None

Returns:

Type Description
bool

True if the current device belongs to the channel between source and target.

Raises:

Type Description
ValueError

If width < 0 or is NaN.

phyelds.libraries.collect

Collect library.

Functions used to collect and aggregate information from the network toward source nodes along a potential gradient, with pluggable collection strategies.

find_parent(potential)

Find the neighbor to send data to along a potential field.

Parameters:

Name Type Description Default
potential float

Local potential value (such as a distance) at the current node.

required

Returns:

Type Description
Optional[int]

The ID of the neighbor with the lowest potential, or None if no neighbor has a potential lower than potential.

find_parents(potential, predicate=None)

Find all parent neighbor IDs along a potential field.

Parameters:

Name Type Description Default
potential float

Local potential value at the current node.

required
predicate Callable[[int, float], bool] | None

Optional filter (neighbor_id, neighbor_potential) -> bool. Defaults to selecting neighbors with potential strictly less than potential.

None

Returns:

Type Description
set[int]

Set of neighbor IDs that act as parents of the current device.

broadcast_collect()

Create a broadcast-based collection strategy (default).

point_to_point()

Create an anisotropic exchange-based collection strategy (sends data only to parent).

multi_path(divide=lambda val, count: val / count)

Create a multi-path DAG collection strategy (FCPP mp_collection).

Each node divides its accumulated value across all neighbors with lower potential using divide(value, num_parents).

Parameters:

Name Type Description Default
divide Callable[[Any, int], Any]

Function splitting a value across count parents.

lambda val, count: val / count

Returns:

Type Description
CollectStrategy

A pluggable CollectStrategy.

collect_with(potential, local, accumulation, *, strategy=None)

Accumulate local values from children to parents along potential.

Parameters:

Name Type Description Default
potential float

Potential value used to determine parent-child relationships.

required
local T

Local value to start with at each node.

required
accumulation Callable[[T, T], T]

Binary function combining two values (e.g. sum, max, union).

required
strategy CollectStrategy | None

Optional collection strategy (broadcast_collect() or point_to_point()).

None

Returns:

Type Description
T

The accumulated value at the current node.

count_nodes(potential, *, strategy=None)

Count the number of nodes in the sub-tree defined by potential.

Parameters:

Name Type Description Default
potential float

The potential field.

required
strategy CollectStrategy | None

Optional collection strategy.

None

Returns:

Type Description
int

The count of nodes in the sub-tree rooted at the current device.

sum_values(potential, local, *, strategy=None)

Sum numeric values up the potential gradient.

Parameters:

Name Type Description Default
potential float

The potential field.

required
local Union[int, float]

The local numeric value.

required
strategy CollectStrategy | None

Optional collection strategy.

None

Returns:

Type Description
Union[int, float]

The sum of values in the sub-tree rooted at the current device.

mean_values(potential, local, *, strategy=None)

Compute the arithmetic mean of local values across the sub-tree defined by potential.

Parameters:

Name Type Description Default
potential float

The potential field.

required
local Union[int, float]

The local numeric value.

required
strategy CollectStrategy | None

Optional collection strategy.

None

Returns:

Type Description
float

The mean of values in the sub-tree rooted at the current device.

collect_or(potential, local, *, strategy=None)

Perform a logical OR collection up the potential gradient.

Parameters:

Name Type Description Default
potential float

The potential field.

required
local bool

The local boolean condition.

required
strategy CollectStrategy | None

Optional collection strategy.

None

Returns:

Type Description
bool

True if any node in the sub-tree satisfies local.

summarize(sink, local, accumulation, distances=None, *, spreading_strategy=None, collect_strategy=None)

Collect local values into sink and broadcast the aggregated result back out.

Implements the G -> C -> G coordination pattern from ScaFi (BlocksWithGC.summarize).

Parameters:

Name Type Description Default
sink bool

True on sink/leader devices that aggregate the region's values.

required
local T

Local value contributed by each device.

required
accumulation Callable[[T, T], T]

Binary function combining two values.

required
distances NeighborhoodField[float] | None

Field of edge distances to neighbors. Defaults to hops_distance().

None
spreading_strategy SpreadingStrategy | None

Optional strategy for gradient and broadcast steps.

None
collect_strategy CollectStrategy | None

Optional strategy for the collection step.

None

Returns:

Type Description
T

The aggregated value broadcast from the nearest sink.

phyelds.libraries.gossip

Gossip library.

Provides network-wide gossip reductions (gossip, gossip_max, gossip_min, any_node) with pluggable stabilization strategies (monotonic_gossip, path_coherent_gossip, time_replicated_gossip).

monotonic_gossip()

Create the default non-stabilizing gossip strategy.

path_coherent_gossip(max_diameter=sys.maxsize)

Create a spatial self-stabilizing gossip strategy based on PathValue.

Parameters:

Name Type Description Default
max_diameter int

Maximum hop count allowed for propagated paths.

maxsize

Returns:

Type Description
GossipStrategy

A pluggable GossipStrategy.

time_replicated_gossip(period, *, max_replicas=2, clock=None)

Create a temporal self-stabilizing gossip strategy using overlapping time replicas.

Parameters:

Name Type Description Default
period float

Time interval between consecutive replica spawns.

required
max_replicas int

Number of concurrent replicas kept alive.

2
clock float | None

Optional local clock reading.

None

Returns:

Type Description
GossipStrategy

A pluggable GossipStrategy.

gossip(value, callback, *, strategy=None)

Gossip value across the network using callback and an optional strategy.

Parameters:

Name Type Description Default
value T

Local value contributed by the current device.

required
callback Callable[..., T]

Reduction function combining values across neighbors.

required
strategy GossipStrategy | None

Optional gossip strategy (monotonic_gossip(), path_coherent_gossip(), or time_replicated_gossip(...)).

None

Returns:

Type Description
T

The gossiped value.

gossip_max(value, *, key=None, strategy=None)

Gossip the maximum value across the network.

Parameters:

Name Type Description Default
value T

Local value to compare.

required
key Callable[[T], Any] | None

Optional key function extracting a comparison key from each value.

None
strategy GossipStrategy | None

Optional gossip strategy.

None

Returns:

Type Description
T

The maximum value across the network.

gossip_min(value, *, key=None, strategy=None)

Gossip the minimum value across the network.

Parameters:

Name Type Description Default
value T

Local value to compare.

required
key Callable[[T], Any] | None

Optional key function extracting a comparison key from each value.

None
strategy GossipStrategy | None

Optional gossip strategy.

None

Returns:

Type Description
T

The minimum value across the network.

any_node(condition, *, strategy=None)

Check whether condition holds on at least one device in the network.

With the default monotonic_gossip() strategy, this behaves like ever_happened (once True on any node, it remains True). With path_coherent_gossip() or time_replicated_gossip(...), it self-stabilizes to reflect whether condition is currently True on any active node.

Parameters:

Name Type Description Default
condition bool

Local boolean condition on the current device.

required
strategy GossipStrategy | None

Optional gossip strategy.

None

Returns:

Type Description
bool

True if condition is satisfied according to strategy.

gossip_mean(value)

Smooth and diffuse value across the network by neighborhood averaging.

At each round, averages the current local value with the estimates received from neighbors, remaining self-stabilizing when input values change.

Parameters:

Name Type Description Default
value float

Local numeric value.

required

Returns:

Type Description
float

The locally averaged estimate.

stabilizing_gossip(value, max_diameter, callback)

Combine value with the values of the devices within max_diameter hops.

Each device broadcasts its own value, and the result is recomputed every round from the values received, so it follows the values as they change.

Parameters:

Name Type Description Default
value T

Local value contributed by the current device.

required
max_diameter int

The maximum number of hops a value travels.

required
callback Callable[..., T]

Function called as callback(value, *values), with the values of the devices within max_diameter hops (the current one included).

required

Returns:

Type Description
T

The result of callback.

phyelds.libraries.leader_election

Self-stabilizing leader election library with pluggable election strategies.

Candidacy(candidate, distance, strength, hops=()) dataclass

A candidate in a priority-based bounded leader election.

Attributes:

Name Type Description
candidate int

ID of the candidate device.

distance float

Accumulated distance from the candidate to the current device.

strength Any

Priority of the candidate (larger values win; ties prefer shorter distance).

hops tuple[int, ...]

Ordered tuple of intermediate node IDs traversed from the candidate.

candidacy(strength=None)

Create a deterministic, priority-based bounded leader election strategy.

Parameters:

Name Type Description Default
strength Any

Optional candidate priority (either a comparable value or a zero-argument callable returning one). Defaults to local_id().

None

Returns:

Type Description
ElectionStrategy

A pluggable ElectionStrategy.

uuid_competition()

Create the classic UUID symmetry-breaking leader election strategy (default).

elect_leader(area, distances=None, *, strategy=None)

Elect a leader within area and return the elected leader's node ID.

Parameters:

Name Type Description Default
area float

Finite positive spatial bound of the election region.

required
distances NeighborhoodField[float] | None

Field of edge distances to neighbors. Defaults to hops_distance().

None
strategy ElectionStrategy | None

Optional election strategy (uuid_competition() or candidacy()).

None

Returns:

Type Description
int | None

The node ID of the leader for the current node's region (or None during transient).

Raises:

Type Description
ValueError

If area is not a finite positive number.

elect_leaders(area, distances=None, *, strategy=None)

Elect leaders across the network and return True if the current node is a leader.

Parameters:

Name Type Description Default
area float

Finite positive spatial bound of the election region.

required
distances NeighborhoodField[float] | None

Field of edge distances to neighbors. Defaults to hops_distance().

None
strategy ElectionStrategy | None

Optional election strategy (uuid_competition() or candidacy()).

None

Returns:

Type Description
bool

True if the current node is the elected leader of its region, False otherwise.

Raises:

Type Description
ValueError

If area is not a finite positive number.

random_uuid()

Draw a random identifier for the current device, kept across rounds.

Returns:

Type Description
Tuple[float, int]

A tuple (random_value, device_id): the random number in [0, 1) is drawn on the first round, and the device ID breaks ties.

breaking_using_uids(uid, area, distances)

Elect leaders by competition on uid: the lowest one wins within its area.

Parameters:

Name Type Description Default
uid Tuple[float, int]

The identifier of the current device, as returned by random_uuid.

required
area float

The size of a leader's area, in the units of distances.

required
distances NeighborhoodField[float]

Field of edge distances to neighbors.

required

Returns:

Type Description
tuple[float, int]

The identifier of the leader the current device follows after this round.

distance_competition(current_distance, area, uid, lead, distances)

Choose the next leader of the current device from those of its neighbors.

Identifiers are tuples, so they compare by random value and then by device ID, which breaks ties.

Parameters:

Name Type Description Default
current_distance float

The distance of the current device from its leader.

required
area float

The size of a leader's area, in the units of distances.

required
uid Tuple[float, int]

The identifier of the current device.

required
lead Tuple[float, int] | NeighborhoodField[Tuple[float, int]]

The identifier of the current leader (or the field of neighbor leaders).

required
distances NeighborhoodField[float]

Field of edge distances to neighbors.

required

Returns:

Type Description
Tuple[float, int]

uid if the device is farther than area from its leader; an identifier with an infinite value, which loses every competition, if it is farther than half of area; otherwise the lowest leader among the neighbors (itself included) that are less than half of area from their leader, through the edge to them (uid if there are none).

phyelds.libraries.time

Time-based aggregate primitives and time-replicated processes.

local_time()

Return the time of the current round, as perceived by the device.

Returns:

Type Description
float

The value of the device's "time" sensor.

counter()

Count the consecutive rounds in which this call runs on the current device.

Returns:

Type Description
int

The number of rounds so far, this one included: 1 on the first round.

decay(value, rate)

Decrease a value by rate each round, down to 0.

Parameters:

Name Type Description Default
value float | int

The starting value; later changes to it are ignored.

required
rate float | int

The amount subtracted each round.

required

Returns:

Type Description
float | int

The decayed value, never below 0: max(0, value - rate) on the first round when value is positive, and value itself when it is not.

delta_time(clock=None)

Compute the non-negative time elapsed since the previous round on this device.

Parameters:

Name Type Description Default
clock float | None

Optional timestamp to track. When omitted, local_time() is used.

None

Returns:

Type Description
float

Elapsed time since the last round (0.0 on the first round).

shared_clock(clock=None)

Synchronize a monotonic shared clock across the network driven by the fastest node.

Parameters:

Name Type Description Default
clock float | None

Optional locally perceived time. Defaults to local_time().

None

Returns:

Type Description
float

The synchronized network timestamp.

timer(duration, *, periodic=False, clock=None)

Count down from duration using clock (or local_time() by default).

Parameters:

Name Type Description Default
duration float

Initial countdown duration.

required
periodic bool

If True, resets the timer to duration for the next round once it reaches <= 0.0.

False
clock float | None

Optional clock value (e.g. shared_clock()) used to measure elapsed time.

None

Returns:

Type Description
float

The time left on the timer (<= 0.0 when expired).

time_replicated(process, period, *, max_replicas=2, clock=None)

Periodically spawn overlapping replicas of process to discard obsolete state.

Each replica with ID r runs in the fixed positional slot r % max_replicas, ensuring alignment stability across rounds as older replicas expire.

Parameters:

Name Type Description Default
process Callable[[], T]

Zero-argument callable running an aggregate computation.

required
period float

Time interval between consecutive replica spawns (must be > 0).

required
max_replicas int

Maximum number of concurrent replicas kept alive (must be >= 1).

2
clock float | None

Optional local clock reading passed to shared_clock.

None

Returns:

Type Description
T

The result produced by the oldest active replica.

Raises:

Type Description
ValueError

If period <= 0 or max_replicas < 1.

delay(value, initial=None)

Return the value held by value in the previous round.

Parameters:

Name Type Description Default
value T

Current value to remember for the next round.

required
initial T | None

Optional value returned on the very first round. When omitted, value itself is returned on the first round.

None

Returns:

Type Description
T

The previous round's value (or initial on the first round).

has_changed(value, *, initially=False)

Return True when value differs from its value in the previous round.

Parameters:

Name Type Description Default
value T

Value to observe across rounds.

required
initially bool

Result returned on the first observation round.

False

Returns:

Type Description
bool

True if value changed since the last round, False otherwise.

rising_edge(condition)

Return True on the round where condition transitions from False to True.

falling_edge(condition)

Return True on the round where condition transitions from True to False.

once(value)

Return value on the first round it is evaluated, and None thereafter.

periodic_impulse(period, *, clock=None)

Emit True every period time units, and False on intermediate rounds.

Parameters:

Name Type Description Default
period float

Interval between impulses.

required
clock float | None

Optional clock value (defaults to local_time()).

None

Returns:

Type Description
bool

True when the periodic timer expires in the current round.

recently_true(condition, duration, *, clock=None)

Return True while condition is True and for duration time units after.

Parameters:

Name Type Description Default
condition bool

Boolean condition to monitor.

required
duration float

How long the True state persists after condition becomes False.

required
clock float | None

Optional clock value (defaults to local_time()).

None

Returns:

Type Description
bool

True if condition held within the last duration time units.

exponential_filter(signal, alpha)

Smooth a numeric signal over time with an exponential moving average.

Computes alpha * previous + (1 - alpha) * signal at each round.

Parameters:

Name Type Description Default
signal float

Current numeric reading.

required
alpha float

Smoothing factor in [0.0, 1.0] (higher retains more history).

required

Returns:

Type Description
float

The smoothed signal value.

Raises:

Type Description
ValueError

If alpha is outside [0.0, 1.0].

phyelds.libraries.processes

Aggregate processes library.

Supports spawning dynamic, spatially and temporally scoped aggregate computations identified by keys, using either the Pythonic @process decorator with guard functions (in_bubble, terminate_if, emit_if) / with bubble(...): or explicit ProcessOutput values.

ProcessStatus

Bases: Enum

Lifecycle status of an aggregate process on the local device.

ProcessOutput(value, status=ProcessStatus.OUTPUT) dataclass

Bases: Generic[R]

Result and lifecycle status returned by a spawned process instance.

Attributes:

Name Type Description
value R

Local output value computed by the process.

status ProcessStatus | bool

Either a ProcessStatus or a bool (True -> OUTPUT, False -> EXTERNAL).

normalized_status()

Convert boolean shorthand into a ProcessStatus.

in_bubble(condition)

Declare that the current device belongs to the process bubble only if condition holds.

When condition is False, execution of the process stops immediately for this device (EXTERNAL), discarding any state and messages produced so far.

Parameters:

Name Type Description Default
condition bool

True if the current device is inside the bubble.

required

leave()

Immediately exit the current process bubble as EXTERNAL.

terminate_if(condition)

Trigger termination of the entire process bubble when condition holds.

Parameters:

Name Type Description Default
condition bool

True to initiate a termination wave for the current process key.

required

terminate()

Immediately trigger termination of the entire process bubble (TERMINATED).

emit_if(condition)

Control whether the current device emits the process value in the spawn output dict.

When condition is False, the device still participates in and relays the process bubble (BUBBLE status), but its local value is omitted from the returned dict.

Parameters:

Name Type Description Default
condition bool

True to emit the output (OUTPUT), False for a silent relay (BUBBLE).

required

bubble(*, inside=True, terminate=False, emit=True)

Context manager declaring the spatial/temporal boundary of a @process body.

Checks terminate first, then inside (exiting immediately if False so the body inside the with block only runs on nodes inside the bubble), and sets emit for the returned value.

Parameters:

Name Type Description Default
inside bool

True if the current node belongs to the bubble.

True
terminate bool

True to shut down the entire bubble across the network.

False
emit bool

True to include this node's result in the output dictionary.

True

process(func)

Decorate a function as an aggregate process and attach .spawn(keys, *args, **kwargs).

Inside a @process function, return plain values directly and control the bubble lifecycle with in_bubble(...), terminate_if(...), emit_if(...), or with bubble(...):.

spawn(proc_fn, keys, *call_args, **call_kwargs)

Dynamically spawn and manage spatially scoped aggregate processes.

Supports both @process functions (using in_bubble, terminate_if, emit_if, or with bubble(...): and returning plain values) and functions returning ProcessOutput or (value, status) tuples.

Parameters:

Name Type Description Default
proc_fn Callable[..., Any]

Aggregate process callable.

required
keys Iterable[K]

Iterable of process keys to generate on the current device in this round.

required
*call_args Any

Positional arguments forwarded to proc_fn after key.

()
**call_kwargs Any

Keyword arguments forwarded to proc_fn.

{}

Returns:

Type Description
dict[K, Any]

Dictionary mapping each active OUTPUT process key to its local result.

phyelds.libraries.logic

Spatial and temporal logic operators for aggregate computing (from FCPP slcs and past_ctl).

Provides:

  • Spatial Logic for Closure Spaces (SLCS): interior, closure, boundary, interior_boundary, closure_boundary, somewhere, everywhere, reaches, touches, surrounds;
  • Past Computation Tree Logic (Past-CTL): yesterday, since, previously, historically with scope in ("local", "all", "any").

interior(region)

Return True on devices in the topological interior of region (SLCS I).

Holds when region is True on the current device and on all its neighbors.

closure(region)

Return True on devices in the topological closure of region (SLCS C).

Holds when region is True on the current device or on at least one neighbor.

boundary(region)

Return True on the full topological boundary of region (SLCS B).

Holds on devices in closure(region) that are not in interior(region).

interior_boundary(region)

Return True on the inner frontier of region (SLCS IB).

Holds on devices inside region that have at least one neighbor outside region.

closure_boundary(region)

Return True on the outer fringe of region (SLCS CB).

Holds on devices outside region that have at least one neighbor inside region.

somewhere(condition, *, max_diameter=20.0, strategy=None)

Return True if condition holds on any reachable device within max_diameter (SLCS F).

Parameters:

Name Type Description Default
condition bool

Local boolean formula.

required
max_diameter float

Upper bound on the hop distance considered reachable.

20.0
strategy SpreadingStrategy | None

Optional spreading strategy (e.g. path_coherent()).

None

everywhere(condition, *, max_diameter=20.0, strategy=None)

Return True if condition holds on all reachable devices within max_diameter.

Parameters:

Name Type Description Default
condition bool

Local boolean formula.

required
max_diameter float

Upper bound on the hop distance considered reachable.

20.0
strategy SpreadingStrategy | None

Optional spreading strategy (e.g. path_coherent()).

None

reaches(region, target, *, max_diameter=20.0, strategy=None)

Return True if a path entirely contained in region reaches a target node (SLCS R).

Because the if region branch splits alignment, reachability only propagates across devices where region holds.

touches(region, target, *, max_diameter=20.0, strategy=None)

Return True on nodes in region whose component is adjacent to target (SLCS T).

Equivalent to reaches(region, closure(target)).

surrounds(region, barrier, *, max_diameter=20.0, strategy=None)

Return True on nodes in region enclosed by barrier (SLCS U / surrounding).

Holds on devices in region whose neighborhood cannot reach not region without passing through barrier.

yesterday(condition, *, scope='local')

Check whether condition held in the previous round (Past-CTL Y, AY, EY).

Parameters:

Name Type Description Default
condition bool

Local boolean formula.

required
scope PastScope

"local" (same device, Y), "all" (all neighbors, AY), or "any" (at least one neighbor, EY).

'local'

since(sustained, triggered, *, scope='local')

Check whether sustained has held continuously since triggered held (Past-CTL).

Parameters:

Name Type Description Default
sustained bool

Condition that must remain True after triggered.

required
triggered bool

Condition that initiates the interval.

required
scope PastScope

"local" (S), "all" (AS), or "any" (ES).

'local'

previously(condition, *, scope='local')

Check whether condition held at least once in the past (Past-CTL P, AP, EP).

Parameters:

Name Type Description Default
condition bool

Local boolean formula.

required
scope PastScope

"local" (P), "all" (AP), or "any" (EP).

'local'

historically(condition, *, scope='local')

Check whether condition has always held in the past (Past-CTL H, AH, EH).

Parameters:

Name Type Description Default
condition bool

Local boolean formula.

required
scope PastScope

"local" (H), "all" (AH), or "any" (EH).

'local'

phyelds.libraries.utils

This module contains utility functions and classes for various purposes.

PathValue(distance, data, hops=()) dataclass

Bases: Generic[T]

Immutable value carried along a loop-free network path.

Attributes:

Name Type Description
distance float

Total accumulated distance from the path origin.

data T

Payload carried along the path.

hops tuple[int, ...]

Ordered tuple of node IDs traversed from origin to the sender.

source property

Return the ID of the origin node, or None if no hops were taken.

next_hop property

Return the ID of the last hop toward the current node, or None if empty.

length property

Return the number of hops in this path.

extend(neighbor_id, edge_distance, accumulate_data, *, bottom=0.0, top=float('inf'), distance_accumulator=lambda a, b: a + b)

Return a new PathValue extended through neighbor_id.

Parameters:

Name Type Description Default
neighbor_id int

ID of the neighbor forwarding this path.

required
edge_distance float

Distance from neighbor_id to the current node.

required
accumulate_data Callable[[float, float, T], T]

Function (from_source, to_neighbor, data) -> new_data.

required
bottom float

Minimum allowed distance.

0.0
top float

Maximum allowed distance.

float('inf')
distance_accumulator Callable[[float, float], float]

Function combining two distances.

lambda a, b: a + b

Returns:

Type Description
PathValue[T]

The extended PathValue.

is_invalid_via_shortcut(accumulated_dist, neighbor_ids, neighbor_accumulated_distances)

Check whether an intermediate hop in the current neighborhood offers a shorter path.

all_common_hops_in_same_order(other, paths_hop_sets)

Check that all hops shared between self and other appear in the same order.

min_with_default(iterable, default=None)

Return the minimum of a collection, or default if it is empty.

Parameters:

Name Type Description Default
iterable Any

A list, tuple, set or range, or a dict, whose values are compared.

required
default Any

The value returned when iterable is empty or of another type.

None

Returns:

Type Description
Any

The minimum value, or default.

accumulate_distance(bottom, top, distance, edge_distance, accumulator=lambda a, b: a + b)

Combine two distances with bounds clamping and triangle-inequality validation.

Parameters:

Name Type Description Default
bottom float

Minimum allowed distance.

required
top float

Maximum allowed distance.

required
distance float

Current accumulated distance.

required
edge_distance float

Edge distance to add.

required
accumulator Callable[[float, float], float]

Function combining two distances.

lambda a, b: a + b

Returns:

Type Description
float

The clamped combined distance.

Raises:

Type Description
ValueError

If the combined distance violates the triangle inequality.

non_looping_paths(neighbor_data, distances, local_id, max_diameter=sys.maxsize, accumulate_data=lambda _s, _e, data: data, bottom=0.0, top=float('inf'), distance_accumulator=lambda a, b: a + b)

Build all valid, loop-free paths from neighbors, sorted by accumulated distance.

Parameters:

Name Type Description Default
neighbor_data NeighborhoodField[PathValue[T] | None]

Field of PathValue | None received from neighbors.

required
distances NeighborhoodField[float]

Field of edge distances to neighbors.

required
local_id int

ID of the current device.

required
max_diameter int

Maximum allowed hop count.

maxsize
accumulate_data Callable[[float, float, T], T]

Function updating payload across an edge.

lambda _s, _e, data: data
bottom float

Minimum distance bound.

0.0
top float

Maximum distance bound.

float('inf')
distance_accumulator Callable[[float, float], float]

Function combining two distances.

lambda a, b: a + b

Returns:

Type Description
list[PathValue[T]]

List of extended PathValue instances sorted by total distance.

path_coherence(paths)

Filter paths to retain only those that are mutually hop-order coherent.

Parameters:

Name Type Description Default
paths Sequence[PathValue[T]]

Sequence of loop-free PathValue candidates sorted by distance.

required

Returns:

Type Description
list[PathValue[T]]

Filtered list of path-coherent PathValue instances.