Algorithm Search⌘K

Algorithmresearch

Distance-based formation control

Also called gradient formation control.

Each robot follows the gradient of the squared errors of its distances to neighbors, which converges locally when the target framework is infinitesimally rigid.

Time
O(k (r + m)) totalO(r + m) per_step
Space
O(r + m) extra
Where
k = the number of integration steps; m = the number of edges; r = the number of robots
Properties
deterministiconlinenot randomized
Origin
Laura Krick, Mireille E. Broucke, Bruce A. Francis, 2009

Distance-based formation control turns a bar-and-joint framework into a control law. The robots are the joints, the graph edges are the bars, and each bar has a target length dijd_{ij}. Each robot moves down the gradient of V=14∑{i,j}(∥pi−pj∥2−dij2)2V = \frac14 \sum_{\{i,j\}} (\lVert p_i - p_j \rVert^2 - d_{ij}^2)^2, so p˙=−R(p)Te\dot p = -R(p)^T e, where RR is the rigidity matrix and ee is the vector of squared length errors. The robots need only the relative positions of their neighbors, in their own frames, and no common frame. If the target framework is infinitesimally rigid, the target shape is locally exponentially stable: from every start close to it, the robots converge to a congruent copy. A generic framework in the plane whose graph contains a spanning Laman graph is infinitesimally rigid, so the graph theory of rigidity tells which sensing graphs can hold a shape. Convergence is only local, and the law has other equilibria, for example collinear ones.

In plain words

Picture a few robots joined by invisible elastic bands of chosen lengths. Each robot can see its band partners, but it has no compass and no map. If a band is longer than its target, the two robots pull toward each other. If it is too short, they push apart. Each robot adds up the pulls and pushes on its bands and moves in that direction.

If enough bands are used, so that the bands alone fix the shape, the robots settle into that shape. The shape can end up shifted or turned, because no robot knows where north is. With too few bands, the group can settle into a bent version of the shape. A bad start, such as all robots in one straight line, can also trap the group in a wrong shape.

The problem

The model. There are rr robots in the plane with positions pi∈R2p_i \in \mathbb{R}^2 (in meters) and the single integrator model p˙i=ui\dot p_i = u_i. A fixed, undirected, connected graph G=(V,E)G = (V, E) with mm edges says which robots sense each other. Robot ii measures zij=pi−pjz_{ij} = p_i - p_j for each neighbor jj, in its own frame; the law needs no common orientation, because it is equivariant under rotations. Time is continuous, and all robots act at the same time. Unicycle robots can use the law after feedback linearization of a point ahead of the wheel axle, as Krick, Broucke and Francis do.

Input. The graph, a target distance dij>0d_{ij} > 0 for each edge, which must be realizable, and the initial positions p(0)p(0).

Output. A trajectory p(t)p(t) with ∥pi(t)−pj(t)∥→dij\lVert p_i(t) - p_j(t) \rVert \to d_{ij} on every edge. When the target framework is rigid, this fixes the shape up to a translation, a rotation and possibly a reflection.

How it differs from close pages. Formation control is the problem, with several kinds of specification. In displacement-based control the robots know a common orientation and run the Laplacian consensus protocol on pi−cip_i - c_i, which converges globally but needs a compass. In leader-follower formation control each follower tracks one or two leaders, and the graph is a tree. The distance-based law needs no compass, but it needs rigidity and gives only local convergence. The distance geometry problem asks for positions with given distances as a computation; this law solves it by a physical gradient flow, one robot per point.

The algorithm

  1. DISTANCE-FORMATION(G, d, p(0), T, h)
  2. 1each robot i learns its neighbors N_i and the target distances d_ij
  3. 2for each step of length h until time T do
  4. 3for each robot i, in parallel, do
  5. 4u_i ← 0
  6. 5for each neighbor j ∈ N_i do
  7. 6z ← p_i - p_j ▷ relative position, sensed by robot i
  8. 7e ← ‖z‖² - d_ij² ▷ squared distance error of the edge
  9. 8u_i ← u_i - e z
  10. 9move every robot with ṗ_i = u_i for time h
  11. 10return p

Lines L4 to L8 compute u=−∇V=−R(p)Te(p)u = -\nabla V = -R(p)^T e(p). Krick, Broucke and Francis use 12∥e∥2\frac12 \lVert e \rVert^2 as the potential, which is 2V2V; this only rescales time. Line L9 stands for the motion of the robots. The implementation integrates it with the classic fourth order Runge-Kutta method and a fixed step hh, and it has a function that computes the rank of RR to test infinitesimal rigidity.

Example

One evaluation by hand. Three robots stand at p1=(0,0)p_1 = (0, 0), p2=(1.2,0.1)p_2 = (1.2, 0.1) and p3=(0.4,0.8)p_3 = (0.4, 0.8), with the triangle graph and all target distances 1 m. The squared errors are e12=1.45−1=0.45e_{12} = 1.45 - 1 = 0.45, e23=1.13−1=0.13e_{23} = 1.13 - 1 = 0.13 and e13=0.8−1=−0.2e_{13} = 0.8 - 1 = -0.2, so V=(0.2025+0.0169+0.04)/4=0.06485V = (0.2025 + 0.0169 + 0.04)/4 = 0.06485. Robot 1 gets

u1=−0.45(p1−p2)+0.2(p1−p3)=(0.54,0.045)+(−0.08,−0.16)=(0.46,−0.115),u_1 = -0.45 (p_1 - p_2) + 0.2 (p_1 - p_3) = (0.54, 0.045) + (-0.08, -0.16) = (0.46, -0.115),

which moves it toward robot 2, whose edge is too long, and away from robot 3, whose edge is too short. The three inputs are (0.46,−0.115)(0.46, -0.115), (−0.644,0.046)(-0.644, 0.046) and (0.184,0.069)(0.184, 0.069), and they sum to zero, so the centroid does not move.

The run. With RK4 and h=0.005h = 0.005 s:

tt (s) VV ∥p1−p2∥\lVert p_1 - p_2 \rVert ∥p2−p3∥\lVert p_2 - p_3 \rVert ∥p1−p3∥\lVert p_1 - p_3 \rVert
0 0.06485 1.2042 1.0630 0.8944
0.5 0.0021619 1.0307 0.9989 0.9649
1 0.00010922 1.0070 0.9998 0.9923
2 2.7069e-7 1.0004 1.0000 0.9996
4 1.6632e-12 1.0000 1.0000 1.0000

The robots end at (0.0853,−0.0641)(0.0853, -0.0641), (1.0727,0.0940)(1.0727, 0.0940) and (0.4420,0.8701)(0.4420, 0.8701), a unit equilateral triangle that is turned with respect to the axes and has the start centroid (0.5333,0.3)(0.5333, 0.3). Between t=2t = 2 and t=4t = 4, VV drops by a factor of about 1.6×1051.6 \times 10^5, close to e−12e^{-12}. This matches the linearization: at the unit equilateral triangle the matrix 2RRT2 R R^T has the eigenvalues 6, 3 and 3, so the slowest error mode decays as e−3te^{-3t} and VV as e−6te^{-6t}.

A wrong equilibrium. From the collinear start (0,0)(0, 0), (1,0)(1, 0), (3,0)(3, 0) the robots stay on the line, as the proof shows. They stop at (0.8294,0)(0.8294, 0), (1.2073,0)(1.2073, 0) and (1.9633,0)(1.9633, 0), with distances 0.3780, 0.7559 and 1.1339 and V=0.25V = 0.25. Here ∇V=0\nabla V = 0, but the shape is wrong.

A flexible graph. With only the four sides of a square, all of length 1, the framework is not rigid: RR has rank 4, less than 2⋅4−3=52 \cdot 4 - 3 = 5. From (0,0)(0, 0), (1.1,0)(1.1, 0), (1.5,0.9)(1.5, 0.9), (0.3,1)(0.3, 1) all four sides reach length 1, but the robots stop in a rhombus with diagonals 1.6168 and 1.1772 instead of 2=1.4142\sqrt 2 = 1.4142. Adding one diagonal with target 2\sqrt 2 gives rank 5, and then starts near the square converge to the square.

Correctness

The proof shows that the law is the gradient flow p˙=−∇V\dot p = -\nabla V, so V˙=−∥∇V∥2≤0\dot V = -\lVert \nabla V \rVert^2 \le 0. The inputs sum to zero, so the centroid is fixed, and the law commutes with rotations and translations. With a connected graph the trajectories stay bounded, and by the LaSalle invariance principle they approach the set of equilibria. The collinear set is invariant, which gives wrong equilibria. The main step is a local gradient inequality ∥∇V∥2≥cV\lVert \nabla V \rVert^2 \ge c V near an infinitesimally rigid target, proved from the rank of RR and the Asimow-Roth theorem. It gives V(t)≤V(0)e−ctV(t) \le V(0) e^{-c t} and a finite path length, so starts close to the target converge to a congruent copy of it.

Proof: The distance gradient law decreases the formation error, keeps the centroid, and converges exponentially near an infinitesimally rigid targetfull

There are rr robots in the plane with positions pi∈R2p_i \in \mathbb{R}^2 and the model p˙i=ui\dot p_i = u_i. The graph G=(V,E)G = (V, E) is fixed, undirected and connected, with mm edges, and each edge {i,j}\{i, j\} has a target distance dij>0d_{ij} > 0. Write zij=pi−pjz_{ij} = p_i - p_j, eij=∥zij∥2−dij2e_{ij} = \lVert z_{ij} \rVert^2 - d_{ij}^2, and e∈Rme \in \mathbb{R}^m for the vector of the eije_{ij}. The potential is V(p)=14∑{i,j}∈Eeij2=14∥e∥2V(p) = \frac14 \sum_{\{i,j\} \in E} e_{ij}^2 = \frac14 \lVert e \rVert^2. The rigidity matrix R(p)R(p) is the m×2rm \times 2r matrix whose row for the edge {i,j}\{i, j\} holds zijTz_{ij}^T in the columns of robot ii and −zijT-z_{ij}^T in the columns of robot jj. The target set is E={p:e(p)=0}\mathcal{E} = \{p : e(p) = 0\}. Line numbers refer to the pseudocode on the distance-based formation control page.

Lemma 1 (the law is a gradient flow). Lines L4 to L8 compute ui=−∑j∈Nieijziju_i = -\sum_{j \in N_i} e_{ij} z_{ij}, and u=−∇V(p)=−R(p)Te(p)u = -\nabla V(p) = -R(p)^T e(p).

Proof. ∇pieij=2zij\nabla_{p_i} e_{ij} = 2 z_{ij} and ∇pjeij=−2zij\nabla_{p_j} e_{ij} = -2 z_{ij}. So ∇pi14eij2=12eij∇pieij=eijzij\nabla_{p_i} \frac14 e_{ij}^2 = \frac12 e_{ij} \nabla_{p_i} e_{ij} = e_{ij} z_{ij}, and summing over the edges at ii gives ∇piV=∑j∈Nieijzij\nabla_{p_i} V = \sum_{j \in N_i} e_{ij} z_{ij}. The block of RTeR^T e for robot ii is ∑j∈Nieijzij\sum_{j \in N_i} e_{ij} z_{ij} by the definition of RR, with the sign of zij=−zjiz_{ij} = -z_{ji} taken care of by the order of the edge. □\square

Lemma 2 (invariants). The centroid 1r∑ipi\frac1r \sum_i p_i is constant. If QQ is a rotation and bb a vector, the law maps Qpi+bQ p_i + b to QuiQ u_i. If all robots start on one line, they stay on that line.

Proof. Each edge adds −eijzij-e_{ij} z_{ij} to uiu_i and −eijzji=eijzij-e_{ij} z_{ji} = e_{ij} z_{ij} to uju_j, so ∑iui=0\sum_i u_i = 0 and the centroid does not move. Under pi↦Qpi+bp_i \mapsto Q p_i + b, zij↦Qzijz_{ij} \mapsto Q z_{ij} and eije_{ij} does not change, so ui↦Quiu_i \mapsto Q u_i. If all pip_i lie on a line ℓ\ell through the point cc with direction vv, each zijz_{ij} is parallel to vv, so each uiu_i is parallel to vv. The vector field restricted to the configurations on ℓ\ell is the field of the same law in one dimension, which has a solution on ℓ\ell. The field is polynomial, so solutions are unique, and the solution from a point of ℓr\ell^r is that one, which stays on ℓ\ell. □\square

Lemma 3 (descent and boundedness). Along every solution, V˙=−∥∇V∥2≤0\dot V = -\lVert \nabla V \rVert^2 \le 0. Every solution exists for all t≥0t \ge 0, stays bounded, and approaches the set of critical points of VV.

Proof. V˙=∇VTp˙=−∥∇V∥2\dot V = \nabla V^T \dot p = -\lVert \nabla V \rVert^2. So V(p(t))≤V(p(0))=V0V(p(t)) \le V(p(0)) = V_0, and each edge has ∥zij∥2≤dij2+2V0\lVert z_{ij} \rVert^2 \le d_{ij}^2 + 2 \sqrt{V_0}. The graph is connected, so every robot is within r−1r - 1 edges of every other, and with the fixed centroid of Lemma 2 all positions stay in a bounded set. So the solution exists for all time. The function VV is a Lyapunov function on that compact set, and the LaSalle invariance principle gives convergence to the largest invariant set in {∇V=0}\{\nabla V = 0\}, which is the set of equilibria. □\square

Lemma 3 does not say that the limit is in E\mathcal{E}. Lemma 2 gives a counterexample: with the triangle graph and a collinear start, the robots never leave the line, so they cannot reach a target triangle of positive area. The robots then stop at a collinear equilibrium with V>0V > 0.

Lemma 4 (a local gradient inequality). Let p∗p^* be in E\mathcal{E}, and let the framework (G,p∗)(G, p^*) be infinitesimally rigid in the plane, that is, rank⁡R(p∗)=2r−3\operatorname{rank} R(p^*) = 2r - 3, with r≥2r \ge 2. Then there are a neighborhood UU of p∗p^* and a constant c>0c > 0 such that ∥∇V(p)∥2≥c V(p)\lVert \nabla V(p) \rVert^2 \ge c \, V(p) for all p∈Up \in U.

Proof. An infinitesimally rigid framework is rigid (Asimow and Roth), so near p∗p^* the set E\mathcal{E} is the orbit of p∗p^* under the proper rigid motions of the plane. This orbit O\mathcal{O} is a smooth manifold of dimension 3 near p∗p^*, because the points of p∗p^* are not all equal, and its tangent space at each of its points qq is the space of infinitesimal rigid motions, which is ker⁡R(q)\ker R(q) by infinitesimal rigidity. All points of O\mathcal{O} are congruent to p∗p^*, so they have the same singular values of RR; let σ>0\sigma > 0 be the smallest positive one.

For pp near p∗p^*, let qq be a nearest point of O\mathcal{O} to pp and δ=p−q\delta = p - q. Then δ\delta is normal to O\mathcal{O} at qq, that is, δ⊥ker⁡R(q)\delta \perp \ker R(q), so ∥R(q)δ∥≥σ∥δ∥\lVert R(q) \delta \rVert \ge \sigma \lVert \delta \rVert and ∥R(q)TR(q)δ∥≥σ2∥δ∥\lVert R(q)^T R(q) \delta \rVert \ge \sigma^2 \lVert \delta \rVert. Since e(q)=0e(q) = 0 and eije_{ij} is quadratic in pp, e(p)=2R(q)δ+se(p) = 2 R(q) \delta + s, where sij=∥δi−δj∥2s_{ij} = \lVert \delta_i - \delta_j \rVert^2, so ∥s∥≤C1∥δ∥2\lVert s \rVert \le C_1 \lVert \delta \rVert^2. The matrix RR is linear in pp, so R(p)=R(q)+R(δ)R(p) = R(q) + R(\delta) with ∥R(δ)∥≤C2∥δ∥\lVert R(\delta) \rVert \le C_2 \lVert \delta \rVert. Then

∇V(p)=R(p)Te(p)=2R(q)TR(q)δ+R(q)Ts+R(δ)Te(p),\nabla V(p) = R(p)^T e(p) = 2 R(q)^T R(q) \delta + R(q)^T s + R(\delta)^T e(p),

and the last two terms are at most C3∥δ∥2C_3 \lVert \delta \rVert^2 in norm. So ∥∇V(p)∥≥2σ2∥δ∥−C3∥δ∥2≥σ2∥δ∥\lVert \nabla V(p) \rVert \ge 2 \sigma^2 \lVert \delta \rVert - C_3 \lVert \delta \rVert^2 \ge \sigma^2 \lVert \delta \rVert when ∥δ∥≤σ2/C3\lVert \delta \rVert \le \sigma^2 / C_3. Also ∥e(p)∥≤C4∥δ∥\lVert e(p) \rVert \le C_4 \lVert \delta \rVert, so V(p)≤14C42∥δ∥2V(p) \le \frac14 C_4^2 \lVert \delta \rVert^2. Together, ∥∇V∥2≥σ4∥δ∥2≥(4σ4/C42)V\lVert \nabla V \rVert^2 \ge \sigma^4 \lVert \delta \rVert^2 \ge (4 \sigma^4 / C_4^2) V. The constants are uniform on a small ball around p∗p^*, because the nearest point qq is then close to p∗p^*. □\square

Theorem (local exponential convergence). Under the hypotheses of Lemma 4, there is a ρ>0\rho > 0 such that every solution with ∥p(0)−p∗∥<ρ\lVert p(0) - p^* \rVert < \rho converges to a point p∞∈Ep_\infty \in \mathcal{E}, and V(p(t))≤V(p(0))e−ctV(p(t)) \le V(p(0)) e^{-c t}. So every distance ∥pi−pj∥\lVert p_i - p_j \rVert on an edge converges to dijd_{ij} exponentially, and p∞p_\infty is congruent to p∗p^*.

Proof. Choose a ball BB of radius β\beta around p∗p^* inside the set UU of Lemma 4. While p(t)p(t) stays in BB, V˙=−∥∇V∥2≤−cV\dot V = -\lVert \nabla V \rVert^2 \le -c V, so V(t)≤V(0)e−ctV(t) \le V(0) e^{-c t}. Also, where V>0V > 0,

ddtV=V˙2V=−∥∇V∥22V≤−c2∥∇V∥=−c2∥p˙∥.\frac{d}{dt} \sqrt{V} = \frac{\dot V}{2 \sqrt V} = -\frac{\lVert \nabla V \rVert^2}{2 \sqrt V} \le -\frac{\sqrt c}{2} \lVert \nabla V \rVert = -\frac{\sqrt c}{2} \lVert \dot p \rVert.

Integrating, the length of the path from time 0 to tt is at most (2/c)V(p(0))(2 / \sqrt c) \sqrt{V(p(0))}. VV is continuous and V(p∗)=0V(p^*) = 0, so for ρ\rho small enough, ρ+(2/c)V(p(0))<β\rho + (2/\sqrt c) \sqrt{V(p(0))} < \beta whenever ∥p(0)−p∗∥<ρ\lVert p(0) - p^* \rVert < \rho. Then the path never leaves BB, the bound on VV holds for all tt, and the path has finite length, so p(t)p(t) converges to a point p∞∈Bp_\infty \in B. By continuity, V(p∞)=0V(p_\infty) = 0, so p∞∈Ep_\infty \in \mathcal{E}, and near p∗p^* the set E\mathcal{E} consists of the congruent copies of p∗p^*. Each eij(t)2≤4V(t)e_{ij}(t)^2 \le 4 V(t), so each squared distance error decays at least like e−ct/2e^{-c t / 2}. ■\blacksquare

What is not proved here. The theorem is local: the size ρ\rho of the region depends on the target and is not computed. Krick, Broucke and Francis (2009) prove the same local stability with the center manifold theorem. A proof that almost every start converges to E\mathcal{E} is known only for special graphs, for example the triangle (Dörfler and Francis 2010), and the other equilibria, such as the collinear ones of Lemma 2, make a global result impossible. Convergence of every bounded solution to a single equilibrium, not only to the set of equilibria, follows from the Lojasiewicz inequality for the polynomial VV; it is cited, not proved here.

Complexity

  • Per step. Robot ii does O(∣Ni∣)O(|N_i|) work in lines L4 to L8, so one evaluation of all inputs costs O(r+m)O(r + m) in the real RAM model, and an RK4 step costs four evaluations. No messages are sent: each robot senses the relative positions zijz_{ij}.
  • Rate, proved locally. Near an infinitesimally rigid target, VV decays exponentially. The rate cc depends on the smallest positive singular value of RR at the target, so a nearly flexible target, where RR is close to losing rank, converges slowly.
  • Global behavior. There is no bound on the time from an arbitrary start, and some starts do not reach the target at all.

Properties

  • Needs only relative positions in local frames. The law commutes with rotations, so each robot can use its own orientation.
  • Gradient system. VV never increases, and the centroid never moves.
  • Local convergence. It is proved for infinitesimally rigid targets in the plane by Krick, Broucke and Francis, and by the proof on this site.
  • Not global. Other equilibria exist, among them configurations on a line for the triangle.
  • Shape up to congruence. The final formation can be any translated and turned copy of the target, or its mirror image. A target that is rigid but not globally rigid also has other realizations with the same edge lengths that are not congruent to it, and a start far from the target can end in one of them.
  • Deterministic and distributed. Each robot uses only its own edges.

Variants and improvements

  • Other potentials. Any potential ∑γ(∥zij∥2−dij2)\sum \gamma(\lVert z_{ij} \rVert^2 - d_{ij}^2) with γ≥0\gamma \ge 0, γ(0)=0\gamma(0) = 0 and γ′(0)=0\gamma'(0) = 0 gives a law with the same structure. The square of the error is the most common choice. Oh, Park and Ahn (2015) list the forms used in the literature.
  • Triangle and global results. For three robots, Dörfler and Francis (2010) show that every start that is not collinear converges to the target triangle.
  • Unicycles. Feedback linearization of a point at a small distance ahead of the axle turns a unicycle into a single integrator, and the law applies to that point.
  • Bearing and displacement laws. If the robots share a compass, displacement-based control with the Laplacian converges globally. Bearing-based laws use directions instead of distances.
  • Moving formations. Adding a common velocity to every uiu_i moves the whole formation while the gradient term holds the shape.

When to use it

Use the distance law when the robots can measure the relative positions of their neighbors, as with cameras or range sensors, but do not share a compass or a global frame, and when they start close to the target shape. Pick the sensing graph from rigidity theory: a minimally rigid graph built by a Henneberg construction has 2r−32r - 3 edges in the plane and is generically infinitesimally rigid. Use displacement-based consensus when the robots share an orientation, and leader-follower control when a tree of pairs is enough.

Pitfalls

  • Rigidity is required. A graph that is not rigid, like the four sides of a square, reaches the right edge lengths in a wrong shape. Check the rank of RR at the target, not only the edge count.
  • Non-generic targets. A target that has the right graph but a special position, such as three robots on a line, is not infinitesimally rigid, and the local theorem does not apply.
  • Wrong equilibria. A start on a line, or near some other wrong equilibrium, can stop at a wrong shape. Start near the target or use a law with a global result for the case at hand.
  • Mirror images. Distances do not fix the handedness of a shape. From a start far from the target, the robots can converge to its mirror image.
  • Inconsistent distances. If the targets are not realizable, VV cannot reach 0, and the robots stop at a compromise. Some robots can also drift if the measured distances are biased.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

distance_based_formation_control.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/distance-based-formation-control/. The authors are listed in prov/W2E44J.jsonl.

"""Gradient control of inter-robot distances for single integrator robots.

Robot i has position p_i in R^dim and the model p_i' = u_i. The target is a
set of distances d_ij on the edges of an undirected graph. The potential is

    V(p) = 1/4 * sum over edges of (|p_i - p_j|^2 - d_ij^2)^2

and the control is u = -grad V, that is

    u_i = - sum over neighbors j of (|p_i - p_j|^2 - d_ij^2) (p_i - p_j).

Positions are lists of tuples or lists of floats. Edges are pairs (i, j).
"""

from typing import Sequence

Point = Sequence[float]


def _sub(a: Point, b: Point) -> list[float]:
    return [x - y for x, y in zip(a, b)]


def _dot(a: Point, b: Point) -> float:
    return sum(x * y for x, y in zip(a, b))


def potential(p: Sequence[Point], edges: Sequence[tuple], dist: Sequence[float]) -> float:
    """V(p) = 1/4 sum (|p_i - p_j|^2 - d_ij^2)^2."""
    total = 0.0
    for (i, j), d in zip(edges, dist):
        z = _sub(p[i], p[j])
        e = _dot(z, z) - d * d
        total += e * e
    return total / 4


def control(p: Sequence[Point], edges: Sequence[tuple], dist: Sequence[float]) -> list[list[float]]:
    """Return u_i = -sum_j e_ij (p_i - p_j) for all robots, where e_ij is the squared distance error."""
    nbrs: list[list[tuple]] = [[] for _ in p]
    for (i, j), d in zip(edges, dist):  # @line L1
        nbrs[i].append((j, d))
        nbrs[j].append((i, d))
    u = []
    for i in range(len(p)):  # @line L3
        ui = [0.0] * len(p[i])  # @line L4
        for j, d in nbrs[i]:  # @line L5
            z = _sub(p[i], p[j])  # @line L6
            e = _dot(z, z) - d * d  # @line L7
            ui = [a - e * b for a, b in zip(ui, z)]  # @line L8
        u.append(ui)
    return u


def rk4_step(p: Sequence[Point], edges, dist, h: float) -> list[list[float]]:
    """One step of the classic RK4 method for p' = u(p)."""

    def add(q, k, s):
        return [[a + s * b for a, b in zip(qi, ki)] for qi, ki in zip(q, k)]

    k1 = control(p, edges, dist)
    k2 = control(add(p, k1, h / 2), edges, dist)
    k3 = control(add(p, k2, h / 2), edges, dist)
    k4 = control(add(p, k3, h), edges, dist)
    return [[a + h / 6 * (b1 + 2 * b2 + 2 * b3 + b4) for a, b1, b2, b3, b4 in zip(pi, c1, c2, c3, c4)]
            for pi, c1, c2, c3, c4 in zip(p, k1, k2, k3, k4)]


def run_formation(p0: Sequence[Point], edges, dist, t: float, h: float) -> list[list[float]]:
    """Integrate the closed loop from 0 to t with fixed step h."""
    p = [list(map(float, q)) for q in p0]
    steps = max(1, round(t / h))  # @line L2
    for _ in range(steps):
        p = rk4_step(p, edges, dist, t / steps)  # @line L9
    return p  # @line L10


def rigidity_matrix(p: Sequence[Point], edges) -> list[list[float]]:
    """Row for edge (i, j): p_i - p_j in the columns of i, p_j - p_i in the columns of j."""
    dim = len(p[0])
    rows = []
    for i, j in edges:
        row = [0.0] * (dim * len(p))
        z = _sub(p[i], p[j])
        for c in range(dim):
            row[dim * i + c] = z[c]
            row[dim * j + c] = -z[c]
        rows.append(row)
    return rows


def rank(m: list[list[float]], tol: float = 1e-9) -> int:
    """Rank by Gaussian elimination with partial pivoting."""
    a = [list(r) for r in m]
    rk = 0
    cols = len(a[0]) if a else 0
    for c in range(cols):
        piv = max(range(rk, len(a)), key=lambda k: abs(a[k][c]), default=None)
        if piv is None or abs(a[piv][c]) <= tol:
            continue
        a[rk], a[piv] = a[piv], a[rk]
        for k in range(rk + 1, len(a)):
            f = a[k][c] / a[rk][c]
            a[k] = [x - f * y for x, y in zip(a[k], a[rk])]
        rk += 1
        if rk == len(a):
            break
    return rk


def is_infinitesimally_rigid_2d(p: Sequence[Point], edges) -> bool:
    """A planar framework with n >= 2 points is infinitesimally rigid when rank R = 2n - 3."""
    n = len(p)
    return rank(rigidity_matrix(p, edges)) == 2 * n - 3
test_distance_based_formation_control.py 138 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/distance-based-formation-control/. The authors are listed in prov/W2E44J.jsonl.

import math
import random

from distance_based_formation_control import (
    control,
    is_infinitesimally_rigid_2d,
    potential,
    rank,
    rigidity_matrix,
    rk4_step,
    run_formation,
)

TRI = [(0, 1), (1, 2), (0, 2)]
SQUARE = [(0, 1), (1, 2), (2, 3), (3, 0)]
SQUARE_DIAG = SQUARE + [(0, 2)]


def dists(p, edges):
    return [math.dist(p[i], p[j]) for i, j in edges]


def centroid(p):
    n = len(p)
    return [sum(q[c] for q in p) / n for c in range(len(p[0]))]


def test_control_is_minus_gradient() -> None:
    rng = random.Random(1)
    h = 1e-6
    for _ in range(20):
        n = rng.randrange(3, 6)
        p = [[rng.uniform(-2, 2), rng.uniform(-2, 2)] for _ in range(n)]
        edges = [(i, j) for i in range(n) for j in range(i + 1, n) if rng.random() < 0.7]
        if not edges:
            edges = [(0, 1)]
        d = [rng.uniform(0.5, 2) for _ in edges]
        u = control(p, edges, d)
        for i in range(n):
            for c in range(2):
                pp = [list(q) for q in p]
                pm = [list(q) for q in p]
                pp[i][c] += h
                pm[i][c] -= h
                g = (potential(pp, edges, d) - potential(pm, edges, d)) / (2 * h)
                assert abs(u[i][c] + g) < 1e-6 * max(1.0, abs(g))


def test_hand_value() -> None:
    p = [(0.0, 0.0), (2.0, 0.0), (0.0, 1.0)]
    u = control(p, [(0, 1), (0, 2)], [1.0, 1.0])
    # e_01 = 4 - 1 = 3, e_02 = 1 - 1 = 0, so u_0 = -3 (0 - 2, 0) = (6, 0)
    assert u[0] == [6.0, 0.0]
    assert u[1] == [-6.0, 0.0]
    assert u[2] == [0.0, 0.0]
    assert potential(p, [(0, 1), (0, 2)], [1.0, 1.0]) == 2.25


def test_centroid_and_equivariance() -> None:
    rng = random.Random(2)
    p = [[rng.uniform(-1, 1), rng.uniform(-1, 1)] for _ in range(4)]
    d = [1.0] * 5
    u = control(p, SQUARE_DIAG, d)
    assert all(abs(sum(ui[c] for ui in u)) < 1e-12 for c in range(2))
    th, tx, ty = 0.7, 3.0, -1.0
    cs, sn = math.cos(th), math.sin(th)
    q = [[cs * x - sn * y + tx, sn * x + cs * y + ty] for x, y in p]
    uq = control(q, SQUARE_DIAG, d)
    for a, b in zip(u, uq):
        assert abs(cs * a[0] - sn * a[1] - b[0]) < 1e-12
        assert abs(sn * a[0] + cs * a[1] - b[1]) < 1e-12


def test_potential_decreases_and_centroid_is_fixed() -> None:
    rng = random.Random(3)
    p = [[rng.uniform(-1, 1), rng.uniform(-1, 1)] for _ in range(4)]
    d = [1.0, 1.0, 1.0, 1.0, math.sqrt(2)]
    c0 = centroid(p)
    v = potential(p, SQUARE_DIAG, d)
    for _ in range(300):
        p = rk4_step(p, SQUARE_DIAG, d, 0.01)
        nv = potential(p, SQUARE_DIAG, d)
        assert nv <= v + 1e-12
        v = nv
    assert max(abs(a - b) for a, b in zip(centroid(p), c0)) < 1e-9


def test_local_convergence_triangle() -> None:
    rng = random.Random(4)
    target = [(0.0, 0.0), (1.0, 0.0), (0.5, math.sqrt(3) / 2)]
    d = [1.0, 1.0, 1.0]
    for _ in range(5):
        p0 = [[x + rng.uniform(-0.2, 0.2), y + rng.uniform(-0.2, 0.2)] for x, y in target]
        p = run_formation(p0, TRI, d, 10.0, 0.01)
        assert max(abs(a - b) for a, b in zip(dists(p, TRI), d)) < 1e-9
        assert max(abs(a - b) for a, b in zip(centroid(p), centroid(p0))) < 1e-9


def test_local_convergence_rigid_square() -> None:
    rng = random.Random(5)
    d = [1.0, 1.0, 1.0, 1.0, math.sqrt(2)]
    target = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
    assert is_infinitesimally_rigid_2d(target, SQUARE_DIAG)
    for _ in range(3):
        p0 = [[x + rng.uniform(-0.15, 0.15), y + rng.uniform(-0.15, 0.15)] for x, y in target]
        p = run_formation(p0, SQUARE_DIAG, d, 15.0, 0.01)
        assert max(abs(a - b) for a, b in zip(dists(p, SQUARE_DIAG), d)) < 1e-8
        # the other diagonal is then also right: the shape is a unit square
        assert abs(math.dist(p[1], p[3]) - math.sqrt(2)) < 1e-7


def test_flexible_square_keeps_sides_but_not_shape() -> None:
    assert not is_infinitesimally_rigid_2d([(0, 0), (1, 0), (1, 1), (0, 1)], SQUARE)
    p0 = [[0.0, 0.0], [1.1, 0.0], [1.5, 0.9], [0.3, 1.0]]
    p = run_formation(p0, SQUARE, [1.0] * 4, 20.0, 0.01)
    assert max(abs(a - 1.0) for a in dists(p, SQUARE)) < 1e-8
    assert abs(math.dist(p[0], p[2]) - math.sqrt(2)) > 0.05


def test_collinear_start_stays_collinear() -> None:
    p0 = [[0.0, 0.0], [1.0, 0.0], [3.0, 0.0]]
    p = run_formation(p0, TRI, [1.0, 1.0, 1.0], 20.0, 0.01)
    assert all(abs(q[1]) < 1e-12 for q in p)
    assert potential(p, TRI, [1.0, 1.0, 1.0]) > 0.1
    u = control(p, TRI, [1.0, 1.0, 1.0])
    assert max(abs(c) for ui in u for c in ui) < 1e-6


def test_rigidity_ranks() -> None:
    tri = [(0.0, 0.0), (1.0, 0.0), (0.5, 0.8)]
    assert rank(rigidity_matrix(tri, TRI)) == 3
    assert rank(rigidity_matrix([(0, 0), (1, 0), (2, 0)], TRI)) == 2
    sq = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
    assert rank(rigidity_matrix(sq, SQUARE)) == 4
    assert rank(rigidity_matrix(sq, SQUARE_DIAG)) == 5

History

Krick, Broucke and Francis (2009) gave the local stability theorem for infinitesimally rigid targets, with a center manifold argument and a link to the rigidity theory of frameworks. Dörfler and Francis (2010) analyzed the triangle in detail and its wrong equilibria. The survey of Oh, Park and Ahn (2015) classifies formation control into position-based, displacement-based and distance-based methods by what the robots sense and control.

References

  1. Laura Krick, Mireille E. Broucke and Bruce A. Francis, Stabilisation of infinitesimally rigid formations of multi-robot networks, International Journal of Control 82(3), 2009, pages 423 to 439 (the gradient law, the invariance of the centroid and of the collinear set, and local asymptotic stability of infinitesimally rigid targets by center manifold theory)
  2. Kwang-Kyo Oh, Myoung-Chul Park and Hyo-Sung Ahn, A survey of multi-agent formation control, Automatica 53, 2015, pages 424 to 440 (the distance-based class of formation control and its sensing and interaction requirements)
  3. Florian Dörfler and Bruce Francis, Geometric analysis of the formation problem for autonomous robots, IEEE Transactions on Automatic Control 55(10), 2010, pages 2379 to 2384 (the triangle formation, its incorrect equilibria, and convergence from every start that is not collinear)
  4. Mehran Mesbahi and Magnus Egerstedt, Graph Theoretic Methods in Multiagent Networks, Princeton University Press, 2010, Chapter 6, Formation Control (Section 6.3 on shape-based control), and Chapter 7, Section 7.4 (formation control revisited with weighted graphs)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per_step
  • a full proof of time.total
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example