def program(z, psi, F):
"""What agent i runs at every tick: its measurements z_ij = x_i - x_j (one per neighbour), its sensing maps
psi (one per neighbour; None for perfect sensing) and its actuation map F (None for faithful actuation).
Returns the velocity it actually gets, F(u) with u = -sum_j psi_ij(z_ij)."""
u = 0.0
for k in range(len(z)):
u -= z[k] if (psi is None or psi[k] is None) else sft(psi[k], z[k])
return u if F is None else sft(F, u)Shifted interaction functions, explained
The paper (Xu, Morella Violeta, García de Marina), written out step by step for its own four agents: what a shifted actuator or sensor does to consensus, which motion the team ends up in, and the program each agent runs at every tick
From the Swarm Systems Lab, University of Granada. To try the results by hand, open the playground.
What this page does. It takes the paper Shifted Interaction Functions: A Unified Framework for Imperfect Actuation and Sensing in Consensus Networks (its LaTeX source, main.tex) and writes it out for the paper’s own example: four agents on the graph of its Fig. 1, and the three agents of its Fig. 5. It goes step by step: two measurement channels per edge (Section 2 of the paper), the shift functions that model imperfect actuators and sensors (Section 4), the one velocity a team with shifted actuators can share (Lemma 2 and Theorem 1), when that motion is a static consensus (Corollaries 1 and 2), what shifted sensors do instead (Theorems 2 and 3, Proposition 4), and the linear case, where everything has a closed form (Proposition 3). It ends with the program each agent runs at every tick, and with the paper’s simulations run again.
Source and status. The results are the paper’s, and this page does not re-prove them. It adds three things, each marked where it appears: the closed-form velocities of the two clusters of Fig. 5 (Section 5.2.1), a measurement of how conservative the rate of Theorem 3 is on the paper’s example (Section 5.3.1), and a re-run of every simulation of the paper with its parameters, recovered from the code that drew the figures, which finds one small mismatch in the text (Section 7). Every number on the page is computed by core.py when the page is rendered. The interactive figures run assets/core.js, and make check proves that the two agree.
1 The problem
agents (robots, drones, satellites) each have one number to agree on, : a position along a road, a heading, a phase on a path. Each agent is a single integrator,
Sensing. Agent measures, for each neighbour , the relative state . Nobody measures an absolute state, and nothing is shared beyond these measurements.
The ideal law. The standard consensus protocol sums the measurements, . On a connected undirected graph, every agent then converges to the average of the initial states, and stops there: a static consensus.
The imperfections. Real hardware does not compute that sum. A sensor reads instead of : with a bias, a gain error, a saturation, a dead zone. An actuator delivers instead of : a fixed-wing aircraft cannot fly backwards or below its stall speed, a thruster may only push, a motor may be jammed in part of its range. The paper writes the closed loop as
with every and a shift function: a monotone map that need not pass through the origin.
The question. Not whether the team reaches consensus, since with imperfections it usually does not, but what it does instead. The paper finds three outcomes: a static consensus (rare), a common drift velocity with fixed offsets between the agents (generic for actuators), and groups of agents that each share a velocity and drift apart (possible with sensors).
Why it is hard. The maps are unknown, different for every agent, and nonlinear. The two agents at the ends of an edge process the same physical distance with different maps, so the interaction is no longer symmetric: the graph is undirected, but the dynamics on it are not.
2 Step 1: two measurement channels on every edge
2.1 The graph of the example
The paper’s example has four agents and five edges, , , , , (its Fig. 1). Each edge carries two measurements: , taken by , and , taken by . The paper picks one orientation of each edge as positive, , and calls the other negative, . Here the positive one goes from the smaller index to the larger.
The incidence matrix has at the initial node and at the terminal node of each positive edge. It splits as : the out-incidence keeps the entries, the in-incidence the entries.
The columns are the edges in the order above, the rows the agents. The measurement along is taken by the initial node and enters the input through ; the one along enters through . Stacking the processed measurements of each orientation into and , the input of every agent is (eq. (9) of the paper)
With perfect sensors, and , and with the Laplacian
The graph is connected (one zero eigenvalue), which is Assumption 1. The paper insists that the two channels of an edge are independent (its Remark 1): the graph is undirected, but each agent processes its own measurement with its own map, so in practice the interaction is directed.
3 Step 2: shift functions
3.1 A monotone map moved off the origin
The ideal interactions in consensus are maps that are increasing and vanish at the origin, such as or . A shift function moves such a map horizontally and vertically and scales it,
A miscalibrated sensor reads a horizontal offset and a bias ; a one-way actuator is a map that is zero for negative inputs; a saturated one is flat beyond its limits. The paper asks only this of every map (Assumption 2): locally Lipschitz and non-decreasing. So flat pieces (dead zones, saturations, jammed ranges) are allowed, and need not be zero.
Two facts of Subsection 4.D matter later. The range moves with the vertical shift and stretches with the scale, but a horizontal shift never changes the range. And in the linear case the two shifts are the same thing, ; in the nonlinear case they are not.
4 Step 3: shifted actuation
4.1 The closed loop
With perfect sensors and shifted actuators, every agent computes the ideal input and gets the velocity (eq. (12)):
The paper works with , the vector of the agents’ disagreements. It lives in , so its entries sum to zero, . Its dynamics are .
4.2 Which velocity can the team share? Lemma 2
If all agents end up with the same velocity , each agent’s disagreement must satisfy , and the disagreements must still add up to zero. Lemma 2 says that, if the ranges share an interval of non-zero length (Assumption 3), there is exactly one such velocity .
The proof (Appendix A) minimises a convex potential for existence; uniqueness is one line: a higher needs a higher input at every agent, so the inputs cannot add up to zero at two different velocities. Geometrically (the paper’s Fig. 10): let be the set of with . It is an interval, a single point where is increasing and a segment where is flat. Their sum moves down as grows, and is where it crosses zero.
For the two maps of Fig. 10, and a piecewise-linear with a dead zone on , the common range is , and the page’s bisection on finds = -0.1140, with = (−0.2855, 0.2855). The two disagreements add up to zero, as they must.
4.3 Theorem 1: velocity alignment under shifted actuation
Theorem 1 (Shifted Actuation Alignment). On a connected graph, with monotone actuation maps whose ranges are compatible (Assumptions 1 to 3), every agent’s velocity converges to the same value, the of Lemma 2:
The proof uses the potential , which decreases along the motion, , and is zero exactly when all velocities are equal. LaSalle gives the alignment, and a monotone distance argument gives convergence of to one point.
The limit fixes the offsets between the agents: , where removes the average. So the team ends up as a rigid group moving at , . If the maps have flat pieces, several can give the same , and which one the team reaches depends on where it starts; the velocity does not.
On the example. The paper’s Fig. 7 gives every agent the smooth, invertible map , with = (−0.1, −0.2, 0.3, 0.1) and = (0.1, −0.1, 0.2, −0.3). These values are not in the paper; they were recovered from the vector data of the original figure, and the code that drew the revised figure uses them (TCNS_R1/img_shift/make_figures.py). The ranges are all of , so Assumption 3 holds. Since means , Lemma 2 is the scalar equation , whose root is = -0.0499. Then = (0.2504, 0.1498, −0.0475, −0.3527) and the predicted offsets are = (0.0626, 0.1003, −0.0119, −0.1510). The simulation (Euler, 1 ms) reaches the velocity -0.0499 at , and its offsets differ from the prediction by 2.9e-9 at most.
4.4 When is it a static consensus? Corollaries 1 and 2
With invertible maps (Assumption 5), is unique, and Corollary 1 reads off the outcome from the value of each map at zero input:
- the team reaches consensus (zero offsets) if and only if all maps agree at zero, for all ;
- the consensus is static if and only if all maps pass through the origin, .
In the example, = (0.200, 0.099, −0.096, −0.400): four different values, so the team neither stops nor agrees. This is the paper’s point: a single imperfect agent is enough to make the team drift with offsets, and static consensus is the exception. Read the other way, a known shift is a design tool: the maps decide both the drift and the offsets.
With purely horizontal shifts of one map (, the same and for all), Lemma 2 gives with the average shift, and : the average shift sets the drift, the deviations from it set the offsets, whatever is (Subsection 4.D). For the example’s , = 0.025 and, without the vertical shifts, the team would drift at = -0.0250.
Corollary 2 (Anchored Network). If one agent cannot move at all, , Assumption 3 fails (the common range is the single point 0), but the proof still works with : everybody stops. The drift becomes a static distortion, , with for . Anchoring agent 1 of the example at its start, the formula predicts = (0.0000, −0.0128, −0.1255, −0.2650), and the simulation is there at to within 3.1e-9.
A different kind of agent is one with a constant velocity , a leader. The paper notes (after Theorem 1) that if is inside every other agent’s range and is not one of their saturation levels, the whole team ends up moving at . The playground lets you jam a drone’s throttle and watch this happen, and break it.
5 Step 4: shifted sensing
5.1 The closed loop
Now the actuators are perfect and the sensors are not. Agent applies its own map to its measurement of each neighbour (eq. (17)):
In general : the two ends of an edge disagree about the same distance. Range compatibility is no longer enough. The ranges of the nodal inputs can overlap and the agents still not align, because all of them must realise the same velocity at one edge configuration , and the cycles of the graph constrain that configuration (Remark 4).
5.2 Theorem 2: a maximum principle, and clusters
Theorem 2(i). With monotone sensing maps (Assumption 2 only), the largest velocity never increases and the smallest never decreases. So the velocity spread never grows. The proof compares the solution with itself shifted in time: at the agent that leads the comparison, every measurement is larger than in the other copy, and monotonicity does the rest.
Theorem 2(ii). For smooth maps whose two orientations have comparable slopes, (the paired-sensitivity condition, eq. (18)), every velocity converges, and agents joined by edges with infinite accumulated sensitivity, , end with the same velocity. These edges form the active graph . The velocities obey a consensus protocol with time-varying weights , and the paired-sensitivity condition makes it cut-balanced, so a result of Hendrickx and Tsitsiklis applies. An edge whose sensors saturate, because the two agents drift apart, stops counting, and the team can split along it.
On the example (the paper’s Fig. 5). Three agents on a triangle, with and one large bias, . Each is bounded by 1, so the input of agent ranges over : centred at (0.4, 3.4, 0.0), these intervals overlap on 1.4 to 2.0. They are compatible, and still the agents do not align. The slopes of the two orientations of an edge are equal, , so Theorem 2(ii) applies with . The simulation ends with velocities (1.2000, 1.4000, 1.2000) at : two clusters, and , as the paper says. Over the run, the spread goes from 6.85 down to 0.22 at , and never increases between two samples.
5.2.1 The two cluster velocities, in closed form
This calculation is ours. Agent 2 drifts away from the others, so both its measurements saturate, and , and its velocity tends to = 1.4. Agents 1 and 3 see agent 2 saturated at , and each other at a bounded distance . Their velocities are and ; they are equal when . So the cluster moves at 1.2 with = 0.2027, the simulation’s 0.2027 at . The edges and have sensitivity of a distance that grows linearly, which is integrable: they leave the active graph, and the team splits along them.
Why must it split? Because is odd, the two measurements of an edge cancel in the sum of all velocities, and at every instant. So if the three agents aligned, they would align at , which is 1.267 for . Agent 2 would then need = 2.133, more than the largest value two can reach, 2. The aligned motion of Remark 4 exists only for ; below, agent 2 cannot be held back, and runs ahead at its own saturated velocity. The figure below lets you cross that threshold.
5.3 Theorem 3: global alignment when every sensor stays responsive
Assumption 4 (Uniform Sensing Sensitivity) asks every sensing map to have slopes between two positive constants, . It rules out saturation and dead zones: every edge stays in the active graph forever.
Theorem 3 (All-Edge Sensing Alignment). Under Assumptions 1, 2 and 4, all velocities converge to one value, and exponentially: for any , , with , , and (eq. (21)).
On the example (the paper’s Fig. 8). The four agents of Fig. 1 sense with . The slopes lie between 0.2 and 1.2, so , , as the paper says. The ten shifts and the four sums of biases (all the dynamics see) are not in the paper; they come from the original figure, through make_figures.py. The velocities start spread over 4.62 and align at 0.1987; the states keep drifting.
5.3.1 How conservative is the rate?
This measurement is ours. The paper says that “certifies an exponential rate rather than estimating it”. On the example (, ), the best certified rate over is 7.7·10⁻⁷ per unit of time, at = 0.14 (where = 1.1·10⁻⁷). The spread of the simulation shrinks at an average rate of 1.84 over . The bound is correct and about 2·10⁶ times slower than the team.
5.4 Proposition 4: when sensing gives a static consensus
If both ends of every edge use the same odd map, with , and the map is strictly positive for positive arguments, then the measurements of an edge cancel exactly, the edge potential is a Lyapunov function, and the team reaches a static consensus (Proposition 4). The strict sign condition matters: with an odd dead zone, every configuration where all neighbours are closer than the dead zone is already an equilibrium. Such perfectly matched endpoints are the exception; in general relative-state inconsistencies propagate and the team drifts.
6 Step 5: linear shifts
6.1 One affine system for both channels
With linear maps, , both channels lead to (eq. (24))
For actuation, . For sensing, with slopes and biases on the two orientations of each edge, and . In both cases is a weighted Laplacian with kernel , and its left null vector can be taken positive.
Actuation is a special case of sensing. A linear actuation is the linear sensing with and on every measurement of agent . Conversely, a linear sensing is an actuation if and only if each agent uses one slope for all its measurements. One consequence: is similar to a symmetric matrix and has real eigenvalues, while a sensing Laplacian can have complex ones.
An example with complex eigenvalues (ours). Give the sensing slopes 3 to the measurements that go around the triangle and 0.2 to the ones against it, with slopes = (3.0, 0.2, 1.0, 3.0, 1.5), = (0.2, 3.0, 1.0, 0.2, 0.5) and small biases. Then
No agent uses one slope for all its measurements, so this sensing is not an actuation (the page’s test sens_is_act says so too, and says yes for the actuation of Fig. 9 written as a sensing).
6.2 Proposition 3: the drift and the offsets, in closed form
Proposition 3 (Linear Drift Formula). The solution approaches a straight motion exponentially:
The bias splits in two: with sets the common velocity, and sets the non-consensus distortion , whose norm is at most .
In the rotating example, = (0.2313, 0.2289, 0.1928, 0.3470) (normalised to sum 1), so the team drifts at = -0.1275; the simulation’s velocities at are (−0.1275, −0.1275, −0.1275, −0.1275). The page computes as with and , a formula for rank-one-deficient matrices that matches numpy.linalg.pinv to 1.7e-16. The distortion has norm 0.213, under the bound 0.401.
6.3 Second-order agents
Section 7 of the paper shows the same mechanism one derivative higher: double integrators with linear actuation shifts, with . The left null vector of is , so , and the accelerations align at : a common constant acceleration, and velocities that grow linearly. With the paper’s = (1.0, 0.8, 1.2, 1.0), = (0.2, −0.1, 0.3, 0.0) and , = 0.0796. If instead, as for = (0.80, −0.96, 1.20, −0.60), agents that start at rest stop with the offsets = (0.2000, −0.3750, 0.2500, −0.0750).
7 Corrections to the published version
The page re-runs every simulation of the paper with the parameters of the code that drew its figures (TCNS_R1/img_shift/make_figures.py), and compares the result with what the text says. Everything matches but one number, and three figures depend on parameters that the paper does not state.
The second-order example (Section 7). The text says that the predicted acceleration is matched by the accelerations of Fig. 9 “to within ”. The exact solution (a matrix exponential of the linear system, computed on this page) gives, at the last time of the figure, , a largest deviation = 2.4·10⁻⁹. The slowest mode decays like with = 1.782 the smallest non-zero eigenvalue of , and it oscillates, so the deviation is still above at and below it by (table). The figure and the prediction are right; the sentence would read “to within ”.
| time | (exact) |
|---|---|
| 10 | 3.0·10⁻⁵ |
| 15 | 1.1·10⁻⁶ |
| 20 | 2.4·10⁻⁹ |
| 22 | 1.7·10⁻⁹ |
| 25 | 1.3·10⁻¹⁰ |
| 30 | 1.1·10⁻¹² |
Parameters not stated in the paper. Figs. 6, 7 and 8 use values that the reader cannot find in the text: the breakpoints of the four non-negative maps of Fig. 6, the shifts and of Fig. 7, and the ten shifts and four bias sums of Fig. 8. The figure script recovered them from the original figures. Stating them (in the captions or in a table) would make the simulations reproducible from the paper alone. The initial conditions are not stated either.
What does not change. No result, proof or claim about the qualitative behaviour is affected. Every number the text gives for Figs. 5 to 10 (the clusters and , the static consensus at the maximum initial state, the predicted drift and offsets, and , , the static offsets for ) is reproduced below.
8 The program each agent runs
Every agent runs the same short program; only its maps differ, and it does not know them.
Before take-off: nothing to configure. The agent knows who its neighbours are.
At every tick: 1. measure for every neighbour (the sensor delivers , not ); 2. compute the consensus input ; 3. send to the actuator, which delivers the velocity .
The shifts are in the hardware, not in the program: and are what the sensors and the actuator do to the ideal signals. In the simulator they are explicit, so that the page can say what the team will do.
9 The simulator
The whole model is one file, core.py: the graphs, the shift functions, the program above, the Euler simulator, the bisection of Lemma 2, the linear algebra of Proposition 3 and the paper’s examples. Every number on this page comes from it. The interactive figures run assets/core.js, a line-by-line port, and make check compares the two.
core.py: the core of this page (the JavaScript of the figures is a line-by-line port)
"""The Python core of the paper's pages: every number the explainer prints is computed here, at render time.
A line-by-line twin of assets/core.js: same functions, same names, same order of operations. `make check` runs
check() here and EX.core.check() in deno, and compares every value (1e-9).
The model (paper, eq. (6)-(8)): N agents on a line, x_i in R, single integrators. Agent i measures z_ij = x_i - x_j
for each neighbour j, passes it through its sensing map psi_ij, adds the results, and its actuator turns the sum into
a velocity: xdot_i = F_i(u_i), u_i = -sum_j psi_ij(z_ij). Every map is a "shift function" (monotone, Lipschitz).
The world is Euler with the velocities held for one tick. Plain lists and loops, so that the JavaScript computes
exactly the same sums in the same order.
"""
import math
BIG = 1e6 # the "infinity" of the preimage searches (Lemma 2): |u| < BIG
NBIS = 120 # bisection steps (from 2e6 wide to below 1e-29)
# ------------------------------------------------------------------ graphs
EDGES4 = [[0, 1], [0, 2], [0, 3], [1, 2], [2, 3]] # Fig. 1: {1,2},{1,3},{1,4},{2,3},{3,4}; positive orientation (i, j)
EDGES3 = [[0, 1], [0, 2], [1, 2]] # the triangle of Fig. 5
def neighbours(n, edges):
nb = [[] for _ in range(n)]
for e in edges:
nb[e[0]].append(e[1])
nb[e[1]].append(e[0])
return nb
def incidence(n, edges):
"""B, B^o (out) and B^i (in), N x M: [B]_{il} = +1 (-1) if i is the initial (terminal) node of edge l."""
m = len(edges)
B = [[0.0] * m for _ in range(n)]
Bo = [[0.0] * m for _ in range(n)]
Bi = [[0.0] * m for _ in range(n)]
for k in range(m):
i, j = edges[k][0], edges[k][1]
B[i][k] = 1.0
B[j][k] = -1.0
Bo[i][k] = 1.0
Bi[j][k] = -1.0
return B, Bo, Bi
def laplacian(n, edges):
L = [[0.0] * n for _ in range(n)]
for e in edges:
i, j = e[0], e[1]
L[i][i] += 1.0
L[j][j] += 1.0
L[i][j] -= 1.0
L[j][i] -= 1.0
return L
def ring(n, k):
"""The circulant graph: i is a neighbour of i +- 1, ..., i +- k (mod n)."""
edges = []
for i in range(n):
for d in range(1, k + 1):
j = (i + d) % n
if [j, i] not in edges and [i, j] not in edges:
edges.append([i, j] if i < j else [j, i])
return edges
# ------------------------------------------------------------------ shift functions
def interp(xs, ys, s):
"""Piecewise linear through the knots, flat outside them (numpy.interp)."""
if s <= xs[0]:
return ys[0]
n = len(xs)
if s >= xs[n - 1]:
return ys[n - 1]
k = 0
while xs[k + 1] < s:
k += 1
return ys[k] + (ys[k + 1] - ys[k]) * (s - xs[k]) / (xs[k + 1] - xs[k])
def sft(m, s):
"""A shift function, as a list [kind, parameters...]:
["lin", a, h, b] a (s - h) + b
["tanh", a, h, b, c] a tanh(s - h) + c s + b (Figs. 5 and 8; c > 0 gives Assumption 4)
["asinh", a, h, b] a asinh(s - h) + b (Fig. 7)
["pwl", xs, ys] piecewise linear, flat outside the knots (Figs. 6 and 10)
["sat", a, h, b, lo, hi] a (s - h) + b clipped to [lo, hi] (a speed band: no reverse, a top speed)
["dead", a, w] 0 on [-w, w], a (s -+ w) outside (the dead zone after Proposition 4)
["const", v] v whatever the input (a jammed actuator, or an anchor with v = 0)"""
k = m[0]
if k == "lin":
return m[1] * (s - m[2]) + m[3]
if k == "tanh":
return m[1] * math.tanh(s - m[2]) + m[4] * s + m[3]
if k == "asinh":
return m[1] * math.asinh(s - m[2]) + m[3]
if k == "pwl":
return interp(m[1], m[2], s)
if k == "sat":
v = m[1] * (s - m[2]) + m[3]
return m[4] if v < m[4] else (m[5] if v > m[5] else v)
if k == "dead":
if s > m[2]:
return m[1] * (s - m[2])
if s < -m[2]:
return m[1] * (s + m[2])
return 0.0
if k == "const":
return m[1]
raise ValueError(k)
def dsft(m, s):
"""The slope of a shift function (its sensitivity), where it has one; for pwl, sat and dead, the one-sided slope."""
k = m[0]
if k == "lin":
return m[1]
if k == "tanh":
c = math.cosh(s - m[2])
return m[1] / (c * c) + m[4]
if k == "asinh":
d = s - m[2]
return m[1] / math.sqrt(1 + d * d)
if k == "pwl":
xs, ys, n = m[1], m[2], len(m[1])
if s < xs[0] or s >= xs[n - 1]:
return 0.0
q = 0
while xs[q + 1] <= s:
q += 1
return (ys[q + 1] - ys[q]) / (xs[q + 1] - xs[q])
if k == "sat":
v = m[1] * (s - m[2]) + m[3]
return 0.0 if (v < m[4] or v > m[5]) else m[1]
if k == "dead":
return m[1] if (s > m[2] or s < -m[2]) else 0.0
return 0.0
# ------------------------------------------------------------------ the robots and the world
def program(z, psi, F):
"""What agent i runs at every tick: its measurements z_ij = x_i - x_j (one per neighbour), its sensing maps
psi (one per neighbour; None for perfect sensing) and its actuation map F (None for faithful actuation).
Returns the velocity it actually gets, F(u) with u = -sum_j psi_ij(z_ij)."""
u = 0.0
for k in range(len(z)):
u -= z[k] if (psi is None or psi[k] is None) else sft(psi[k], z[k])
return u if F is None else sft(F, u)
def network(n, edges, F=None, psi=None):
"""A team: the graph, an actuation map per agent (or None) and a sensing map per agent and neighbour (or None).
psi may be given as a dict {(i, j): map} over oriented edges; it is stored in the order of neighbours(n, edges)."""
nb = neighbours(n, edges)
P = None
if psi is not None:
P = [[psi.get((i, j)) for j in nb[i]] for i in range(n)]
return {"n": n, "edges": edges, "nb": nb, "F": F, "psi": P}
def velocity(net, x):
v = []
for i in range(net["n"]):
z = [x[i] - x[j] for j in net["nb"][i]]
v.append(program(z, None if net["psi"] is None else net["psi"][i], None if net["F"] is None else net["F"][i]))
return v
def simulate(net, x0, dt, steps, every=1):
"""The world: Euler with the velocities held for one tick. Returns the states and velocities every `every` ticks."""
n = net["n"]
x = [float(q) for q in x0]
v = velocity(net, x)
X, V = [x], [v]
for s in range(1, steps + 1):
x = [x[i] + dt * v[i] for i in range(n)]
v = velocity(net, x)
if s % every == 0:
X.append(x)
V.append(v)
return X, V
def simulate2(net2, x0, v0, dt, steps, every=1):
"""Double integrators with linear actuation shifts (Section 7): xddot = diag(a) u + b, u = -L (x + gamma xdot)."""
n, L, a, b, gam = net2["n"], net2["L"], net2["a"], net2["b"], net2["gamma"]
x = [float(q) for q in x0]
v = [float(q) for q in v0]
def acc(x, v):
out = []
for i in range(n):
u = 0.0
for j in range(n):
u -= L[i][j] * (x[j] + gam * v[j])
out.append(a[i] * u + b[i])
return out
A = acc(x, v)
X, Vs, As = [x], [v], [A]
for s in range(1, steps + 1):
x, v = [x[i] + dt * v[i] for i in range(n)], [v[i] + dt * A[i] for i in range(n)]
A = acc(x, v)
if s % every == 0:
X.append(x)
Vs.append(v)
As.append(A)
return X, Vs, As
def mean(v):
s = 0.0
for q in v:
s += q
return s / len(v)
def spread(v):
"""S = max_i v_i - min_i v_i, the velocity spread of Theorem 2."""
lo, hi = v[0], v[0]
for q in v:
lo = q if q < lo else lo
hi = q if q > hi else hi
return hi - lo
def project(x):
"""Pi x: the non-consensus part of the state (the mean removed)."""
m = mean(x)
return [q - m for q in x]
# ------------------------------------------------------------------ Lemma 2: the unique compatible velocity y*
def rng_of(m):
"""The range of a shift function, up to the closure: [sft(-BIG), sft(BIG)]."""
return [sft(m, -BIG), sft(m, BIG)]
def pre_lo(m, y):
"""inf { u : sft(u) >= y } (the lower end of the preimage of y)."""
lo, hi = -BIG, BIG
if sft(m, hi) < y:
return math.inf
if sft(m, lo) >= y:
return -math.inf
for _ in range(NBIS):
mid = 0.5 * (lo + hi)
if sft(m, mid) >= y:
hi = mid
else:
lo = mid
return hi
def pre_hi(m, y):
"""sup { u : sft(u) <= y } (the upper end of the preimage of y)."""
lo, hi = -BIG, BIG
if sft(m, lo) > y:
return -math.inf
if sft(m, hi) <= y:
return math.inf
for _ in range(NBIS):
mid = 0.5 * (lo + hi)
if sft(m, mid) <= y:
lo = mid
else:
hi = mid
return lo
def common_range(maps):
"""The set R of Assumption 3, [max_i inf R_i, min_i sup R_i] (empty if the first is not below the second)."""
lo, hi = -math.inf, math.inf
for m in maps:
r = rng_of(m)
lo = r[0] if r[0] > lo else lo
hi = r[1] if r[1] < hi else hi
return [lo, hi]
def ystar(maps):
"""The y* of Lemma 2: the one velocity y in R with u_i in sft_i^{-1}(y) and sum_i u_i = 0. NaN if R has no length.
Bisection on y: the sums of the preimages move up with y (the right panel of Fig. 10)."""
R = common_range(maps)
lo, hi = R[0], R[1]
if not lo < hi:
return math.nan
for _ in range(NBIS):
y = 0.5 * (lo + hi)
if y <= lo or y >= hi:
break
s = 0.0
for m in maps:
s += pre_lo(m, y)
if s > 0:
hi = y
continue
s = 0.0
for m in maps:
s += pre_hi(m, y)
if s < 0:
lo = y
continue
return y
return 0.5 * (lo + hi)
def etabar(maps, y):
"""For invertible maps: the limit of eta = L x, eta_i = -sft_i^{-1}(y*) (Theorem 1 and the text after it)."""
return [-pre_lo(m, y) for m in maps]
# ------------------------------------------------------------------ small dense linear algebra (the same in both)
def solve(A, b):
"""Gaussian elimination with partial pivoting; A is n x n (a copy is made), b a vector."""
n = len(A)
M = [list(A[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = c
for r in range(c + 1, n):
if abs(M[r][c]) > abs(M[p][c]):
p = r
M[c], M[p] = M[p], M[c]
for r in range(c + 1, n):
f = M[r][c] / M[c][c]
for k in range(c, n + 1):
M[r][k] -= f * M[c][k]
x = [0.0] * n
for r in range(n - 1, -1, -1):
s = M[r][n]
for k in range(r + 1, n):
s -= M[r][k] * x[k]
x[r] = s / M[r][r]
return x
def matvec(A, x):
out = []
for r in A:
s = 0.0
for k in range(len(x)):
s += r[k] * x[k]
out.append(s)
return out
def dot(a, b):
s = 0.0
for k in range(len(a)):
s += a[k] * b[k]
return s
def left_null(Lt):
"""The left null vector v of a weighted Laplacian (v^T Lt = 0), normalised to sum 1: solve Lt^T v = 0 with the last
equation replaced by sum v = 1."""
n = len(Lt)
A = [[Lt[j][i] for j in range(n)] for i in range(n)]
A[n - 1] = [1.0] * n
rhs = [0.0] * n
rhs[n - 1] = 1.0
return solve(A, rhs)
def pinv_laplacian(Lt, v):
"""The Moore-Penrose pseudoinverse of a rank n-1 matrix with right null vector 1 and left null vector v:
Lt^+ = (Lt + w u^T)^{-1} - u w^T, u = 1/sqrt(n), w = v/|v| (checked against numpy.linalg.pinv on the page)."""
n = len(Lt)
u = 1.0 / math.sqrt(n)
nv = math.sqrt(dot(v, v))
w = [q / nv for q in v]
M = [[Lt[i][j] + w[i] * u for j in range(n)] for i in range(n)]
cols = []
for j in range(n):
e = [0.0] * n
e[j] = 1.0
cols.append(solve(M, e))
return [[cols[j][i] - u * w[j] for j in range(n)] for i in range(n)]
# ------------------------------------------------------------------ Section 6: linear shift functions
def lin_act(n, edges, a, b):
"""Linear shifted actuation F_i(u) = a_i u + b_i: xdot = -diag(a) L x + b."""
L = laplacian(n, edges)
return [[a[i] * L[i][j] for j in range(n)] for i in range(n)], [float(q) for q in b]
def lin_sens(n, edges, ai, ao, bi, bo):
"""Linear shifted sensing psi_l(z) = a_l z + b_l on both orientations of each edge k = (i, j):
the positive one (measured by i) has slope ai[k], bias bi[k]; the negative one (by j) ao[k], bo[k].
Lt = B^o D^i B^T + B^i D^o B^T and b = -B^o b^i + B^i b^o, written out entry by entry."""
Lt = [[0.0] * n for _ in range(n)]
b = [0.0] * n
for k in range(len(edges)):
i, j = edges[k][0], edges[k][1]
Lt[i][i] += ai[k]
Lt[i][j] -= ai[k]
Lt[j][j] += ao[k]
Lt[j][i] -= ao[k]
b[i] -= bi[k]
b[j] -= bo[k]
return Lt, b
def act_as_sens(n, edges, a, b):
"""The linear sensing that reproduces a linear actuation: a_l = a_i and b_l = -b_i / |E_i| on the l measured by i."""
deg = [len(q) for q in neighbours(n, edges)]
ai = [a[e[0]] for e in edges]
ao = [a[e[1]] for e in edges]
bi = [-b[e[0]] / deg[e[0]] for e in edges]
bo = [-b[e[1]] / deg[e[1]] for e in edges]
return ai, ao, bi, bo
def linear_limit(Lt, b, x0):
"""Proposition 3: x(t) = c t 1 + x* + o(1), with c = v^T b / v^T 1 and x* = Lt^+ P2 b + c' 1.
Returns c, x* (the whole limiting offset, c' included), v and Lt^+."""
n = len(Lt)
v = left_null(Lt)
s1 = 0.0
for q in v:
s1 += q
c = dot(v, b) / s1
P2b = [b[i] - c for i in range(n)]
Lp = pinv_laplacian(Lt, v)
xs = matvec(Lp, P2b)
cp = (dot(v, x0) - dot(v, xs)) / s1
return c, [q + cp for q in xs], v, Lp
def sens_is_act(n, edges, ai, ao, tol=1e-12):
"""A linear sensing is a linear actuation iff each agent uses one slope for all its measurements."""
nb_slopes = [[] for _ in range(n)]
for k in range(len(edges)):
nb_slopes[edges[k][0]].append(ai[k])
nb_slopes[edges[k][1]].append(ao[k])
for s in nb_slopes:
for q in s:
if abs(q - s[0]) > tol:
return False
return True
# ------------------------------------------------------------------ Theorem 3: the certified contraction factor
def gamma_bound(T, n, dmax, klo, khi):
"""gamma = min_k gamma_k, gamma_k = e^{-aT} (klo tau e^{-aT})^k, a = dmax khi, tau = T/(n-1) (eq. (21))."""
a = dmax * khi
tau = T / (n - 1)
g0 = math.exp(-a * T)
q = klo * tau * g0
g, gk = g0, g0
for _ in range(1, n):
gk = gk * q
g = gk if gk < g else g
return g
# ------------------------------------------------------------------ a seeded generator (xorshift32, as in JavaScript)
class Rng:
def __init__(self, seed):
self.s = (seed & 0xFFFFFFFF) or 1
def u(self):
s = self.s
s ^= (s << 13) & 0xFFFFFFFF
s ^= s >> 17
s ^= (s << 5) & 0xFFFFFFFF
self.s = s
return s / 4294967296
def random_pwl(r, lo_max=-0.3, hi_min=0.3):
"""A random non-decreasing piecewise-linear map with flat pieces (a jammed or saturated actuator), whose range
contains [lo_max, hi_min]: five knots, every gap with probability 0.35 flat."""
xs, ys = [-3.0 + 2.0 * r.u()], [lo_max - 0.2 - 0.8 * r.u()]
for _ in range(4):
xs.append(xs[-1] + 0.3 + 1.2 * r.u())
ys.append(ys[-1] + (0.0 if r.u() < 0.35 else 0.2 + 0.6 * r.u()))
if ys[-1] < hi_min + 0.1:
ys[-1] = hi_min + 0.1 + 0.4 * r.u()
return ["pwl", xs, ys]
def census_act(count, seed, T=60.0, dt=0.01):
"""Theorem 1 on random teams: four agents on the graph of Fig. 1 with random piecewise-linear actuation (flat pieces
included) and a random start. Returns, per case, [y* of Lemma 2, the final mean velocity, the final spread]."""
r = Rng(seed)
out = []
for _ in range(count):
maps = [random_pwl(r) for _ in range(4)]
x0 = [4.0 * r.u() - 2.0 for _ in range(4)]
y = ystar(maps)
X, V = simulate(network(4, EDGES4, F=maps), x0, dt, int(round(T / dt)), int(round(T / dt)))
out.append([y, mean(V[-1]), spread(V[-1])])
return out
# ------------------------------------------------------------------ the paper's examples (TCNS_R1/img_shift/make_figures.py)
def fig5_net(b21=-3.5, c=0.0):
"""Fig. 5: the triangle, sft_ij(s) = tanh(s) + b_ij (+ c s, for Assumption 4)."""
b = {(0, 1): -0.3, (0, 2): -0.1, (1, 0): b21, (1, 2): 0.1, (2, 0): -0.2, (2, 1): 0.2}
return network(3, EDGES3, psi={k: ["tanh", 1.0, 0.0, v, c] for k, v in b.items()})
FIG5_X0 = [0.0, -1.0, 1.0]
FIG6_KNOTS = [[[0, 2, 6, 9, 10, 13], [0, 0.5, 0.5, 1.5, 1.5, 2.0]],
[[0, 1, 8, 9, 11, 12], [0, 0.4, 0.4, 1.4, 1.4, 1.9]],
[[0, 3, 7, 8, 10, 11], [0, 0.6, 0.6, 1.6, 1.6, 2.1]],
[[0, 5, 10, 11, 13, 14], [0, 0.45, 0.45, 1.45, 1.45, 1.95]]]
FIG6_MAPS = [["pwl", [float(q) for q in k[0]], [float(q) for q in k[1]]] for k in FIG6_KNOTS]
FIG6_X0 = [0.5, 1.0, -1.0, -1.5]
FIG7_H = [-0.1, -0.2, 0.3, 0.1]
FIG7_B = [0.1, -0.1, 0.2, -0.3]
FIG7_MAPS = [["asinh", 1.0, FIG7_H[i], FIG7_B[i]] for i in range(4)]
FIG7_X0 = [0.0, 1.0, -1.0, 2.0]
# Fig. 8: horizontal shifts h_ij and the bias sum of each agent (recovered from the original figure); the sum of an
# agent's biases is all the dynamics see, so it is split evenly over its measurements.
FIG8_H = {(0, 1): -0.274, (0, 2): 1.580, (0, 3): 0.416, (1, 0): -1.056, (1, 2): 0.187,
(2, 0): 0.549, (2, 1): -0.082, (2, 3): -0.590, (3, 0): -0.294, (3, 2): 1.077}
FIG8_BSUM = [-0.027, -0.204, 0.278, 0.196]
FIG8_X0 = [0.0, 1.0, -1.0, -2.0]
def fig8_net():
nb = neighbours(4, EDGES4)
psi = {}
for i in range(4):
for j in nb[i]:
psi[(i, j)] = ["tanh", 1.0, FIG8_H[(i, j)], FIG8_BSUM[i] / len(nb[i]), 0.2]
return network(4, EDGES4, psi=psi)
FIG9_A = [1.0, 0.8, 1.2, 1.0]
FIG9_B1 = [0.2, -0.1, 0.3, 0.0]
FIG9_B2 = [0.8, -0.96, 1.2, -0.6]
FIG9_X0 = [0.0, 1.0, -1.0, 2.0]
FIG10_MAPS = [["tanh", 1.0, 0.4, 0.0, 0.0], ["pwl", [-1.1, -0.2, 0.2, 0.8], [-1.2, 0.0, 0.0, 0.8]]]
# a linear sensing on the graph of Fig. 1 whose weights turn around the triangle 1 -> 2 -> 3: complex eigenvalues
ROT_AI = [3.0, 0.2, 1.0, 3.0, 1.5]
ROT_AO = [0.2, 3.0, 1.0, 0.2, 0.5]
ROT_BI = [0.3, -0.2, 0.1, 0.0, 0.4]
ROT_BO = [-0.1, 0.2, 0.0, 0.3, -0.2]
def fig_runs():
"""The paper's simulations, with Euler steps of 1 ms (the same calls the figures of the page make)."""
out = {}
out["fig5"] = simulate(fig5_net(), FIG5_X0, 1e-3, 7000, 10)
out["fig6"] = simulate(network(4, EDGES4, F=FIG6_MAPS), FIG6_X0, 1e-3, 70000, 100)
out["fig7"] = simulate(network(4, EDGES4, F=FIG7_MAPS), FIG7_X0, 1e-3, 3000, 5)
out["fig8"] = simulate(fig8_net(), FIG8_X0, 1e-3, 4000, 5)
return out
def check():
"""The same keys as EX.core.check() in assets/core.js."""
out = {}
L = laplacian(4, EDGES4)
out["L4"] = [q for r in L for q in r]
runs = fig_runs()
for k in ("fig5", "fig6", "fig7", "fig8"):
X, V = runs[k]
out[k + "_x"] = X[-1]
out[k + "_v"] = V[-1]
out["fig5_S"] = [spread(v) for v in runs["fig5"][1][::20]]
y7 = ystar(FIG7_MAPS)
e7 = etabar(FIG7_MAPS, y7)
Lt, b = lin_act(4, EDGES4, [1.0] * 4, [0.0] * 4)
v = left_null(Lt)
Lp = pinv_laplacian(Lt, v)
out["fig7_ystar"] = [y7]
out["fig7_offsets"] = matvec(Lp, e7)
out["fig6_ystar"] = [ystar(FIG6_MAPS)]
out["fig10_ystar"] = [ystar(FIG10_MAPS)]
out["fig10_eta"] = etabar(FIG10_MAPS, ystar(FIG10_MAPS))
out["fig8_slopes"] = [dsft(m, 0.3) for r in fig8_net()["psi"] for m in r]
# Section 6: the rotating sensing, and an actuation written as a sensing
Lt, b = lin_sens(4, EDGES4, ROT_AI, ROT_AO, ROT_BI, ROT_BO)
c, xs, v, Lp = linear_limit(Lt, b, FIG9_X0)
out["rot_c"] = [c]
out["rot_xstar"] = xs
out["rot_v"] = v
out["rot_pinv"] = [q for r in Lp for q in r]
psi = {}
for k in range(5):
i, j = EDGES4[k]
psi[(i, j)] = ["lin", ROT_AI[k], 0.0, ROT_BI[k]]
psi[(j, i)] = ["lin", ROT_AO[k], 0.0, ROT_BO[k]]
X, V = simulate(network(4, EDGES4, psi=psi), FIG9_X0, 1e-3, 8000, 8000)
out["rot_sim_x"] = X[-1]
out["rot_sim_v"] = V[-1]
ai, ao, bi, bo = act_as_sens(4, EDGES4, FIG9_A, FIG9_B1)
Lt2, b2 = lin_sens(4, EDGES4, ai, ao, bi, bo)
Lt1, b1 = lin_act(4, EDGES4, FIG9_A, FIG9_B1)
out["act_as_sens"] = [q for r in Lt2 for q in r] + b2 + [q for r in Lt1 for q in r] + b1
out["is_act"] = [1.0 if sens_is_act(4, EDGES4, ai, ao) else 0.0, 1.0 if sens_is_act(4, EDGES4, ROT_AI, ROT_AO) else 0.0]
net2 = {"n": 4, "L": laplacian(4, EDGES4), "a": FIG9_A, "b": FIG9_B1, "gamma": 1.0}
X, Vs, As = simulate2(net2, FIG9_X0, [0.0] * 4, 1e-3, 20000, 20000)
out["fig9_acc"] = As[-1]
out["gamma_log"] = [math.log(gamma_bound(T, 4, 3, 0.2, 1.2)) for T in (0.05, 0.1, 0.14, 0.5, 1.0)]
out["census"] = [q for row in census_act(6, 2026, 30.0, 0.01) for q in row]
r = Rng(7)
out["rng"] = [r.u() for _ in range(5)]
out["ring"] = [q for e in ring(10, 2) for q in e]
return out10 Running it: the paper’s simulations again
Every run below is the core’s Euler simulation with steps of 1 ms, with the parameters and initial states of make_figures.py. The paper’s figures were drawn with an adaptive integrator (solve_ivp, tolerance ); at this step the two agree to plotting accuracy, and the limits (which Euler preserves exactly, since its fixed points are those of the flow) agree to round-off.
10.1 Fig. 5: compatible ranges, and still two clusters
The paper: “the velocities form two clusters, and … a bounded and growing inter-cluster separations”. The run: at the velocities are (1.195, 1.410, 1.194), = 0.201 (its limit is 0.2027), and = 2.88 and growing. It matches.
10.2 Fig. 6: non-negative actuation, a static consensus
The ranges , , , meet on , and Lemma 2 gives = 0.000. Every is zero exactly on , so the set of compatible is : a static consensus. The agent at the top has and stays, the others can only move up: the consensus is at the maximum initial state, 1. At (the end of the figure) the agents are within 0.012 of it, still approaching.
10.3 Fig. 7: smooth invertible actuation, a predicted drift
The paper: “all velocities converge to the same nonzero value … the dashed reference lines … match the limits”. The run: = -0.0499, the velocities at are (−0.0498, −0.0444, −0.0497, −0.0555), and the offsets at are within 0.003 of the prediction (within 2.9e-9 at ). It matches.
10.4 Fig. 8: sensing with uniform sensitivity, global alignment
The paper: “their states do not approach static values, whereas the velocities align”. The run: the spread falls from 4.62 to 3.0e-3 at ; the certified bound of Theorem 3 (grey) is a flat line on this scale. It matches.
10.5 Fig. 9: second-order agents
The paper: , and static offsets for the second bias. The run: the accelerations at are (0.079592, 0.079592, 0.079592, 0.079592) against = 0.0796, and the offsets at are (0.2000, −0.3750, 0.2500, −0.0750) against (0.2000, −0.3750, 0.2500, −0.0750). It matches, up to the of Section 7.
10.6 Fig. 10: Lemma 2
The flat piece of at 0 gives a vertical segment of at , and the saturation at another one; neither contains 0, and the crossing is at = -0.1140, as in the paper’s figure.
11 What changes with more agents, and what the page does not cover
- Any connected graph. Theorems 1 to 3 and Proposition 3 hold on every connected graph, for any number of agents [proved]. The playground flies twenty drones on a ring with three neighbours on each side; that the predictions match there too is [numerical].
- States in the plane. The paper treats scalar states. Its Remark 1 says that with axis-wise shifts and a common orientation of the agents’ frames, a state in is scalar problems over the same graph [proved]. This page does not simulate states in the plane.
- Where the clusters form. Theorem 2 says that clusters share a velocity, not which clusters form or at which velocities; the paper says so (Remark 4) [open]. The closed form of Section 5.2.1 works for the triangle because agent 2 saturates both its links.
- Saturated or dead-zone sensing. Theorem 3 needs every sensor to stay responsive. Global alignment with saturating sensors is left for future work in the paper [open].
- Discontinuous actuators. On-off thrusters are not Lipschitz and are outside Assumption 2; the paper covers them only through a velocity-tracking loop that obeys the hypotheses (Remark 1) [open].
- Higher order. The page reproduces the linear second-order example [proved] for linear shifts; nonlinear shifts on second-order agents are not covered [open].
- The simulator. Euler steps of 1 ms with velocities held for one tick. The limits of Theorems 1 and 3 and of Proposition 3 are fixed points of the Euler map too, so the discretisation does not move them [numerical], and the maximum principle holds at every step of every run on this page [numerical].
12 Glossary
| symbol | meaning |
|---|---|
| the state of agent (a position, a phase) | |
| the relative state that agent measures of neighbour | |
| , | the sensing map of agent on its measurement of |
| , | the actuation map of agent : input in, velocity out |
| the stacked maps, | |
| the scale, horizontal shift and vertical shift of a shift function | |
| the positive and negative orientations of edge | |
| incidence, out-incidence and in-incidence matrices, | |
| the Laplacian | |
| the disagreement vector; its entries add up to zero | |
| , | the range of , and the common range (Assumption 3) |
| the unique compatible velocity of Lemma 2 | |
| the limit of ; the offsets are | |
| the projection that removes the average, | |
| the largest and smallest velocity, and the spread | |
| the active graph: edges with infinite accumulated sensitivity (Theorem 2) | |
| the paired-sensitivity constant (eq. (18)) | |
| the bounds on the slopes of the sensing maps (Assumption 4) | |
| the certified contraction factor of Theorem 3 | |
| , | the weighted Laplacian of the linear case, and its left null vector |
| the projections onto the drift and onto the distortion (Proposition 3) | |
| the drift velocity of the linear case, |