Algorithm Search⌘K

Algorithmresearch

Distributed Lloyd coverage algorithm

Also called Cortes-Martinez-Karatas-Bullo coverage control.

Each robot moves toward the centroid of its Voronoi cell, which never increases the coverage cost and drives the group toward a centroidal Voronoi configuration.

Time
O(s r^2 (n + r)) totalO(r (n + r)) per_robotO(r^2 (n + r)) per_step
Space
O(r (n + r)) extra
Where
n = the number of vertices of the region; r = the number of robots; s = the number of steps
Properties
deterministiconlinenot randomized
Origin
Jorge Cortes, Sonia Martinez, Timur Karatas, Francesco Bullo, 2004

The distributed Lloyd coverage algorithm of Cortés, Martínez, Karatas and Bullo places rr robots in a convex region QQ so that each point of QQ is near some robot. Each robot computes its Voronoi cell, the part of QQ that is nearer to it than to any other robot, and moves toward the centroid of that cell. This is Lloyd's algorithm run by the robots themselves. Each step never increases the coverage cost H(P)=∑i∫Vi∥q−pi∥2ϕ(q) dqH(P) = \sum_i \int_{V_i} \lVert q - p_i \rVert^2 \phi(q)\, dq, the expected squared distance from a point of QQ with density ϕ\phi to its nearest robot, and the robots approach a centroidal Voronoi tessellation, where each robot sits at the centroid of its own cell. To find its cell a robot needs only the positions of its Voronoi neighbors, so the law is distributed.

In plain words

Some robots must watch a room, and each spot of the room is watched best by the nearest robot. Each robot owns the part of the room that is closer to it than to any other robot.

Each robot finds the middle of its own part, the balance point of that area, and moves toward it. When a robot moves, the borders between the parts move too, so the robots repeat the step.

A robot at the middle of its part is as close as it can be, on average, to the spots it owns. So each step makes the average distance from a spot to its nearest robot smaller or keeps it the same. The robots spread out by themselves and stop when each one is at the middle of its own part.

The problem

The model. The region QQ is a convex polygon with nn vertices, and ϕ≥0\phi \ge 0 is a density on QQ that says how important each point is. The implementation uses the uniform density ϕ=1\phi = 1. The robots are points p1,…,prp_1, \dots, p_r in QQ with the dynamics pi(t+1)=pi(t)+uip_i(t+1) = p_i(t) + u_i. Each robot knows QQ and ϕ\phi and can learn the positions of the robots whose cells touch its own cell. The steps are synchronous.

Input. The region QQ, the start positions, a gain kk with 0<k≤10 < k \le 1, and the number ss of steps.

Output. The positions after ss steps. The goal is a configuration that is a local minimum of the coverage cost HH, see coverage control.

How it differs from close pages. Lloyd's algorithm is the same iteration for points in a computer, where one program computes the whole diagram. k-means is the same iteration on a finite set of data points. Here the points are robots, each robot computes only its own cell, and the gain k<1k < 1 lets a robot move only part of the way in each step, which is the time step of the continuous law p˙i=−k(pi−Ci)\dot p_i = -k (p_i - C_i).

The algorithm

  1. COVERAGE(Q, p, k, s)
  2. 1for step = 1 to s do
  3. 2for each robot i, in parallel, do
  4. 3V_i ← Q
  5. 4for each other robot j that can bound the cell do ▷ the Voronoi neighbors are enough
  6. 5V_i ← V_i ∩ { q : ‖q - p_i‖ ≤ ‖q - p_j‖ } ▷ clip with a half-plane
  7. 6M_i ← mass of V_i; C_i ← centroid of V_i
  8. 7p_i ← p_i + k (C_i - p_i)
  9. 8return p

Line L5 is one clip of a convex polygon with the half-plane (pj−pi)⋅q≤12(∥pj∥2−∥pi∥2)(p_j - p_i) \cdot q \le \frac12 (\lVert p_j \rVert^2 - \lVert p_i \rVert^2), as in the Sutherland-Hodgman method. Line L6 uses the shoelace formula for the area and the centroid, and the same kind of sum gives the polar moment ∫Vi∥q∥2dq\int_{V_i} \lVert q \rVert^2 dq, from which the cost of the cell follows. All robots read the positions at the start of the step and move together. The implementation clips with all other robots, which gives the same cell; a real robot clips only with its Voronoi neighbors, the robots joined to it in the Delaunay triangulation.

Example

Three robots on a segment. Let QQ be the thin strip [0,1]×[0,0.1][0, 1] \times [0, 0.1], k=1k = 1, and the robots at x=0.1x = 0.1, 0.20.2 and 0.90.9 on the middle line. The borders of the cells are the midpoints 0.150.15 and 0.550.55, so the cells are [0,0.15][0, 0.15], [0.15,0.55][0.15, 0.55] and [0.55,1][0.55, 1], with centroids 0.0750.075, 0.350.35 and 0.7750.775. The robots move there. In the next step the borders are 0.21250.2125 and 0.56250.5625, and the robots move to 0.106250.10625, 0.38750.3875 and 0.781250.78125. They converge to 1/61/6, 1/21/2 and 5/65/6, where each robot is at the middle of a cell of length 1/31/3.

Four robots in a square. Let QQ be the unit square, ϕ=1\phi = 1, k=1k = 1, and the robots start crowded in one corner.

step robot 1 robot 2 robot 3 robot 4 cost HH
0 (0.1, 0.1) (0.3, 0.2) (0.2, 0.4) (0.4, 0.4) 0.15792
1 (0.1054, 0.1229) (0.4614, 0.123) (0.1491, 0.6404) (0.6737, 0.5696) 0.06414
2 (0.1402, 0.1903) (0.5833, 0.1641) (0.2117, 0.7026) (0.7306, 0.6291) 0.04946
3 (0.1785, 0.2253) (0.6576, 0.194) (0.2425, 0.7295) (0.751, 0.6776) 0.04417
5 (0.2229, 0.2483) (0.7203, 0.229) (0.2569, 0.7482) (0.7578, 0.7264) 0.04194
10 (0.2474, 0.251) (0.7473, 0.2482) (0.252, 0.751) (0.752, 0.7482) 0.04167
20 (0.25, 0.25) (0.75, 0.25) (0.25, 0.75) (0.75, 0.75) 0.04167

At step 0 robot 4 owns the cell of area 0.59440.5944, most of the square, and its centroid (0.6737,0.5696)(0.6737, 0.5696) pulls it far out. The cost falls in every step, and the robots end at the centers of the four squares of side 1/21/2. Each small square adds 14⋅1/4+1/412=196\frac14 \cdot \frac{1/4 + 1/4}{12} = \frac{1}{96} to the cost, so the final cost is 1/24≈0.041671/24 \approx 0.04167. The largest distance from a robot to its centroid is about 1.6⋅10−51.6 \cdot 10^{-5} after 20 steps and 1.4⋅10−121.4 \cdot 10^{-12} after 60 steps.

A critical point that is not the best. Two robots in the unit square at (1/3,2/3)(1/3, 2/3) and (2/3,1/3)(2/3, 1/3) have the diagonal as the border of their cells, and each robot is at the centroid of its triangle. So they never move, and the cost is 1/9≈0.11111/9 \approx 0.1111. The two halves of the square with robots at (0.25,0.5)(0.25, 0.5) and (0.75,0.5)(0.75, 0.5) cost only 5/48≈0.10425/48 \approx 0.1042. If one robot starts 10−610^{-6} away from the diagonal configuration, the error grows, and the robots end at two halves of the square. The diagonal configuration is a saddle of HH.

Correctness

The proof uses two facts. For fixed robots, the Voronoi cells are the best way to divide QQ, because each point goes to its nearest robot. For fixed cells, the parallel axis identity ∫Wi∥q−p∥2=Ji+Mi∥p−Ci∥2\int_{W_i} \lVert q - p \rVert^2 = J_i + M_i \lVert p - C_i \rVert^2 shows that the best point for a cell is its centroid. A step first keeps the cells and moves each robot to pi+k(Ci−pi)p_i + k(C_i - p_i), which cuts the cost by k(2−k)∑iMi∥pi−Ci∥2k(2 - k) \sum_i M_i \lVert p_i - C_i \rVert^2, and then switching to the new Voronoi cells does not raise the cost. Summed over the steps, ∑iMi∥pi−Ci∥2→0\sum_i M_i \lVert p_i - C_i \rVert^2 \to 0. Cortés et al. (2004) used the LaSalle invariance principle to conclude that the robots converge to the set of centroidal Voronoi configurations, and showed that the gradient of HH is 2Mi(pi−Ci)2 M_i (p_i - C_i), so the law is a gradient descent with a step that depends on the robot.

Proof: The centroid step never increases the coverage cost, and the robots approach the set of centroidal Voronoi configurationsfull

Let Q⊂R2Q \subset \mathbb{R}^2 be a convex polygon with nonempty interior, and let ϕ≥0\phi \ge 0 be an integrable density on QQ; the implementation uses ϕ=1\phi = 1. For distinct points P=(p1,…,pr)P = (p_1, \dots, p_r) in QQ and a partition W=(W1,…,Wr)W = (W_1, \dots, W_r) of QQ into measurable sets, let

H(P,W)=∑i=1r∫Wi∥q−pi∥2ϕ(q) dq,H(P)=H(P,V(P)),H(P, W) = \sum_{i=1}^{r} \int_{W_i} \lVert q - p_i \rVert^2 \phi(q)\, dq, \qquad H(P) = H(P, V(P)),

where V(P)V(P) is the Voronoi partition, Vi={q∈Q:∥q−pi∥≤∥q−pj∥ for all j}V_i = \{ q \in Q : \lVert q - p_i \rVert \le \lVert q - p_j \rVert \text{ for all } j \}. For a set WiW_i with mass Mi=∫Wiϕ>0M_i = \int_{W_i} \phi > 0 the centroid is Ci=1Mi∫Wiqϕ(q) dqC_i = \frac{1}{M_i} \int_{W_i} q \phi(q)\, dq. Line numbers refer to the pseudocode on the distributed Lloyd coverage algorithm page. One step is pi′=pi+k(Ci−pi)p_i' = p_i + k (C_i - p_i) with CiC_i the centroid of ViV_i and a gain 0<k<20 < k < 2; the page uses 0<k≤10 < k \le 1.

Lemma 1 (the cell is computed exactly). Lines L3 to L5 return ViV_i.

Proof. ∥q−pi∥≤∥q−pj∥\lVert q - p_i \rVert \le \lVert q - p_j \rVert is equivalent, after squaring and cancelling ∥q∥2\lVert q \rVert^2, to (pj−pi)⋅q≤12(∥pj∥2−∥pi∥2)(p_j - p_i) \cdot q \le \frac12 (\lVert p_j \rVert^2 - \lVert p_i \rVert^2), a closed half-plane. So ViV_i is QQ intersected with r−1r - 1 half-planes. Clipping a convex polygon with a half-plane gives the convex polygon of their intersection, and the order of the clips does not matter. □\square

Lemma 2 (parallel axis identity). For a set WiW_i with mass Mi>0M_i > 0 and centroid CiC_i, and any point pp,

∫Wi∥q−p∥2ϕ(q) dq=∫Wi∥q−Ci∥2ϕ(q) dq+Mi∥p−Ci∥2.\int_{W_i} \lVert q - p \rVert^2 \phi(q)\, dq = \int_{W_i} \lVert q - C_i \rVert^2 \phi(q)\, dq + M_i \lVert p - C_i \rVert^2.

Proof. Write q−p=(q−Ci)+(Ci−p)q - p = (q - C_i) + (C_i - p) and expand the square. The cross term is 2(Ci−p)⋅∫Wi(q−Ci)ϕ(q) dq=2(Ci−p)⋅(MiCi−MiCi)=02 (C_i - p) \cdot \int_{W_i} (q - C_i) \phi(q)\, dq = 2 (C_i - p) \cdot (M_i C_i - M_i C_i) = 0. □\square

The implementation uses this identity with p=0p = 0 to compute the cost of a cell from its area, its centroid and its polar moment ∫∥q∥2dq\int \lVert q \rVert^2 dq, which the shoelace formulas give exactly.

Lemma 3 (the best partition for fixed points). For fixed PP and every partition WW, H(P,V(P))≤H(P,W)H(P, V(P)) \le H(P, W).

Proof. For each q∈Qq \in Q, the term of H(P,W)H(P, W) at qq is ∥q−pi∥2ϕ(q)\lVert q - p_i \rVert^2 \phi(q) for the ii with q∈Wiq \in W_i, and the Voronoi partition takes the smallest of these values. The boundaries of the cells have measure zero, so ties do not matter. Integrate over QQ. □\square

Lemma 4 (the best points for a fixed partition). For a fixed partition WW with all Mi>0M_i > 0, H(P,W)=∑iJi+∑iMi∥pi−Ci∥2H(P, W) = \sum_i J_i + \sum_i M_i \lVert p_i - C_i \rVert^2, where Ji=∫Wi∥q−Ci∥2ϕJ_i = \int_{W_i} \lVert q - C_i \rVert^2 \phi does not depend on PP. So H(⋅,W)H(\cdot, W) is smallest exactly when pi=Cip_i = C_i for all ii.

Proof. Apply Lemma 2 to each cell and add. □\square

Lemma 5 (robots stay in QQ and stay distinct). If ϕ=1\phi = 1, the points pi′p_i' lie in QQ, and for 0<k≤10 < k \le 1 they are distinct.

Proof. CiC_i is the centroid of the convex set Vi⊆QV_i \subseteq Q, so Ci∈ViC_i \in V_i, and pi∈Vip_i \in V_i. For 0<k≤10 < k \le 1 the point pi′p_i' is a convex combination of the two, so it is in Vi⊆QV_i \subseteq Q. The centroid of a convex polygon with nonempty interior is an interior point of it, and ViV_i has nonempty interior because pip_i is strictly nearer to itself than to any other robot. A point of the half-open segment from a point of a convex set to an interior point of it is an interior point, so pi′p_i' is in the interior of ViV_i. The interiors of two Voronoi cells do not meet, so pi′≠pj′p_i' \ne p_j'. □\square

Theorem 1 (sufficient decrease). Let ϕ=1\phi = 1 and 0<k≤10 < k \le 1. Then

H(P′)≤H(P)−k(2−k)∑i=1rMi∥pi−Ci∥2,H(P') \le H(P) - k (2 - k) \sum_{i=1}^{r} M_i \lVert p_i - C_i \rVert^2,

with MiM_i and CiC_i taken for the cells of PP. In particular H(P′)≤H(P)H(P') \le H(P), with equality only when every robot is at the centroid of its cell.

Proof. Let W=V(P)W = V(P). By Lemma 5 the new points are distinct and in QQ. By Lemma 3, H(P′)=H(P′,V(P′))≤H(P′,W)H(P') = H(P', V(P')) \le H(P', W). By Lemma 4, H(P′,W)=∑iJi+∑iMi∥pi′−Ci∥2H(P', W) = \sum_i J_i + \sum_i M_i \lVert p_i' - C_i \rVert^2, and pi′−Ci=(1−k)(pi−Ci)p_i' - C_i = (1 - k)(p_i - C_i). Also H(P)=H(P,W)=∑iJi+∑iMi∥pi−Ci∥2H(P) = H(P, W) = \sum_i J_i + \sum_i M_i \lVert p_i - C_i \rVert^2. Subtract and use 1−(1−k)2=k(2−k)1 - (1 - k)^2 = k (2 - k). Every Mi>0M_i > 0, so the decrease is zero only when pi=Cip_i = C_i for all ii. □\square

Theorem 2 (the centroid gap goes to zero). Let ϕ=1\phi = 1, 0<k≤10 < k \le 1, and let P(0),P(1),…P(0), P(1), \dots be the steps of the algorithm. Then ∑t≥0∑iMi(t)∥pi(t)−Ci(t)∥2≤H(P(0))/(k(2−k))\sum_{t \ge 0} \sum_i M_i(t) \lVert p_i(t) - C_i(t) \rVert^2 \le H(P(0)) / (k (2 - k)), so ∑iMi(t)∥pi(t)−Ci(t)∥2→0\sum_i M_i(t) \lVert p_i(t) - C_i(t) \rVert^2 \to 0.

Proof. Add the inequality of Theorem 1 for t=0,…,T−1t = 0, \dots, T - 1. The sum telescopes to H(P(0))−H(P(T))H(P(0)) - H(P(T)), which is at most H(P(0))H(P(0)) because H≥0H \ge 0. A series of nonnegative terms with bounded partial sums has terms that go to zero. ■\blacksquare

What is not proved here. Theorem 2 bounds the gap weighted by the masses. To conclude that every limit point of the robots is a centroidal Voronoi configuration one needs that no cell mass goes to zero and that the centroids depend continuously on the points; this is the convergence result of Cortés, Martínez, Karatas and Bullo (2004), proved there with the LaSalle invariance principle for the continuous flow p˙i=−k(pi−Ci)\dot p_i = -k (p_i - C_i) and for the discrete step. The formula ∂H/∂pi=2Mi(pi−Ci)\partial H / \partial p_i = 2 M_i (p_i - C_i) for the gradient of H(P)H(P), which shows that the centroid step is a step against the gradient, is also from that paper and from Du, Faber and Gunzburger (1999); it is not proved here. The theorems give no rate, and the limit can be a saddle of HH and not the global minimum.

Complexity

  • Per robot and step. Each clip in line L5 costs time linear in the size of the current cell, at most n+rn + r vertices, so a robot that clips with all others uses O(r(n+r))O(r (n + r)) time in the real RAM model. A robot that knows its did_i Voronoi neighbors uses O(di(n+di))O(d_i (n + d_i)) time.
  • Per step. The implementation computes all cells in O(r2(n+r))O(r^2 (n + r)) time. One Voronoi diagram for all robots, clipped to QQ, gives all cells in O(rlog⁡r+nr)O(r \log r + n r) time.
  • Number of steps. The proof gives no rate. Martínez, Bullo, Cortés and Frazzoli (2007) study the number of rounds of deployment laws of this kind. On the examples above about 20 steps reach a gap of 10−510^{-5}.
  • Space. O(n+r)O(n + r) per cell.

Properties

  • Distributed. A robot needs only the positions of its Voronoi neighbors, whose number is less than 6 on average in the plane, and not the number of robots.
  • Monotone. The cost never increases.
  • Local, not global. The limit is a critical point of HH. It can be a saddle or a local minimum that is not the global minimum.
  • Stays in the region. For 0<k≤10 < k \le 1 every robot stays in its own cell, so the robots stay in QQ and never collide.
  • Deterministic. The same start gives the same run.

Variants and improvements

  • Continuous time. The flow p˙i=−k(pi−Ci)\dot p_i = -k (p_i - C_i) is the original form, with the same cost decrease and the same limit set.
  • Nonuniform density. With a density ϕ\phi the cells are the same, but the mass and the centroid are weighted by ϕ\phi, and the robots gather where ϕ\phi is large.
  • Limited range. Robots that sense only within a radius use the part of the cell within that radius, which gives a related cost with the same structure and needs only robots within twice that radius.
  • Other costs. Sensors of different quality lead to power diagrams instead of Voronoi cells. Nonconvex regions and unknown densities need other cells or adaptive laws.

When to use it

Use it to spread a team of robots or sensors over a known convex region, so that the expected distance from an event to the nearest robot is small, and when each robot can talk to the robots near it. Use coverage path planning instead when one robot must sweep every point of the region, and the Laplacian consensus protocol when the robots must gather and not spread.

Pitfalls

  • Saddles and local minima. The limit depends on the start. Symmetric starts, such as robots on a line or on the diagonal of a square, stay symmetric in exact arithmetic and stop at a saddle. In floating point the rounding error can grow away from such a saddle, so runs from the same start can end at different configurations.
  • Gain. For k>1k > 1 a robot can leave its cell, and for k≥2k \ge 2 the cost can increase. The proof needs 0<k<20 < k < 2, and the simple argument that robots stay apart needs k≤1k \le 1.
  • Nonconvex regions. The centroid of a cell in a nonconvex region can lie outside the region or behind a wall, so the law needs changes there.
  • Neighbor discovery. Clipping with too few robots gives a cell that is too large. A robot must know every Voronoi neighbor, which can be far away when the robots are sparse.

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.

cortes_coverage_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cortes-coverage-algorithm/. The authors are listed in prov/CV7WDC.jsonl.

"""Distributed Lloyd coverage algorithm (Cortes, Martinez, Karatas and Bullo).

Robots p_1..p_r lie in a convex polygon Q with uniform density. Each robot
computes its Voronoi cell inside Q, the centroid C_i of the cell, and moves
by p_i <- p_i + k (C_i - p_i) with a gain 0 < k <= 1 (k = 1 is Lloyd's step).
The coverage cost H(P) = sum_i integral over V_i of |q - p_i|^2 dq never
increases.
"""

from typing import Sequence

Point = tuple[float, float]
Polygon = list[Point]


def clip(poly: Sequence[Point], a: Point, b: float, eps: float = 1e-14) -> Polygon:
    """Part of a convex polygon where a . x <= b (Sutherland-Hodgman, one half-plane)."""
    out: Polygon = []
    n = len(poly)
    for idx in range(n):
        p, q = poly[idx], poly[(idx + 1) % n]
        fp = a[0] * p[0] + a[1] * p[1] - b
        fq = a[0] * q[0] + a[1] * q[1] - b
        if fp <= eps:
            out.append(p)
        if (fp < -eps and fq > eps) or (fp > eps and fq < -eps):
            s = fp / (fp - fq)
            out.append((p[0] + s * (q[0] - p[0]), p[1] + s * (q[1] - p[1])))
    return out


def voronoi_cell(i: int, pts: Sequence[Point], region: Sequence[Point]) -> Polygon:
    """Voronoi cell of robot i inside the convex polygon region."""
    pi = pts[i]
    cell: Polygon = list(region)  # @line L3
    for j, pj in enumerate(pts):  # @line L4
        if j != i and cell:
            a = (pj[0] - pi[0], pj[1] - pi[1])
            b = (pj[0] ** 2 + pj[1] ** 2 - pi[0] ** 2 - pi[1] ** 2) / 2
            cell = clip(cell, a, b)  # @line L5
    return cell


def moments(poly: Sequence[Point]) -> tuple[float, float, float, float]:
    """Area M, centroid (cx, cy) and polar moment J = integral |q|^2 dq of a polygon."""
    a = sx = sy = jj = 0.0
    n = len(poly)
    for idx in range(n):
        x0, y0 = poly[idx]
        x1, y1 = poly[(idx + 1) % n]
        cr = x0 * y1 - x1 * y0
        a += cr
        sx += (x0 + x1) * cr
        sy += (y0 + y1) * cr
        jj += (x0 * x0 + x0 * x1 + x1 * x1 + y0 * y0 + y0 * y1 + y1 * y1) * cr
    a /= 2
    if a <= 0:
        return 0.0, 0.0, 0.0, 0.0
    return a, sx / (6 * a), sy / (6 * a), jj / 12


def cell_data(pts: Sequence[Point], region: Sequence[Point]):
    """For each robot: (mass M_i, centroid C_i, cost of the cell around p_i)."""
    res = []
    for i, p in enumerate(pts):
        m, cx, cy, j = moments(voronoi_cell(i, pts, region))  # @line L6
        cost = j - 2 * m * (p[0] * cx + p[1] * cy) + m * (p[0] ** 2 + p[1] ** 2)
        res.append((m, (cx, cy) if m > 0 else p, cost))
    return res


def coverage_cost(pts: Sequence[Point], region: Sequence[Point]) -> float:
    """H(P) = sum_i integral over V_i of |q - p_i|^2 dq (uniform density)."""
    return sum(c for _, _, c in cell_data(pts, region))


def coverage_step(pts: Sequence[Point], region: Sequence[Point], k: float = 1.0) -> list[Point]:
    """One synchronous step: every robot moves the fraction k toward its centroid."""
    new = []
    for p, (_, (cx, cy), _) in zip(pts, cell_data(pts, region)):  # @line L2
        new.append((p[0] + k * (cx - p[0]), p[1] + k * (cy - p[1])))  # @line L7
    return new


def run(pts: Sequence[Point], region: Sequence[Point], k: float = 1.0, steps: int = 100) -> list[Point]:
    cur = [tuple(map(float, p)) for p in pts]
    for _ in range(steps):  # @line L1
        cur = coverage_step(cur, region, k)
    return cur  # @line L8


def centroid_gap(pts: Sequence[Point], region: Sequence[Point]) -> float:
    """max_i |p_i - C_i|, zero exactly at a centroidal Voronoi configuration."""
    return max(((p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2) ** 0.5
               for p, (_, c, _) in zip(pts, cell_data(pts, region)))
test_cortes_coverage_algorithm.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/cortes-coverage-algorithm/. The authors are listed in prov/CV7WDC.jsonl.

import math
import random

from cortes_coverage_algorithm import (
    cell_data,
    centroid_gap,
    coverage_cost,
    coverage_step,
    moments,
    run,
    voronoi_cell,
)

SQUARE = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
PENTAGON = [(0.0, 0.0), (2.0, 0.0), (2.5, 1.2), (1.0, 2.0), (-0.4, 1.1)]


def grid_cost(pts, n=200):
    """Midpoint rule for the cost on the unit square."""
    h = 1.0 / n
    tot = 0.0
    for a in range(n):
        x = (a + 0.5) * h
        for b in range(n):
            y = (b + 0.5) * h
            tot += min((x - p[0]) ** 2 + (y - p[1]) ** 2 for p in pts)
    return tot * h * h


def test_moments_of_simple_shapes() -> None:
    m, cx, cy, j = moments(SQUARE)
    assert (m, cx, cy) == (1.0, 0.5, 0.5)
    assert abs(j - 2 / 3) < 1e-15
    m, cx, cy, _ = moments([(0.0, 0.0), (3.0, 0.0), (0.0, 3.0)])
    assert abs(m - 4.5) < 1e-12 and abs(cx - 1) < 1e-12 and abs(cy - 1) < 1e-12


def test_cells_partition_the_region() -> None:
    rng = random.Random(1)
    region_area = moments(PENTAGON)[0]
    for _ in range(30):
        pts = [(rng.uniform(-0.4, 2.5), rng.uniform(0, 2)) for _ in range(rng.randrange(1, 9))]
        cells = [voronoi_cell(i, pts, PENTAGON) for i in range(len(pts))]
        assert abs(sum(moments(c)[0] for c in cells) - region_area) < 1e-9
        for c, p in zip(cells, pts):
            for v in c:
                d = math.dist(v, p)
                assert all(math.dist(v, q) >= d - 1e-9 for q in pts)


STRIP = [(0.0, 0.0), (1.0, 0.0), (1.0, 0.1), (0.0, 0.1)]


def test_one_dimensional_example() -> None:
    pts = [(0.1, 0.05), (0.2, 0.05), (0.9, 0.05)]
    data = cell_data(pts, STRIP)
    assert [round(m, 12) for m, _, _ in data] == [0.015, 0.04, 0.045]
    assert [round(c[0], 12) for _, c, _ in data] == [0.075, 0.35, 0.775]
    two = coverage_step(coverage_step(pts, STRIP), STRIP)
    assert [round(p[0], 12) for p in two] == [0.10625, 0.3875, 0.78125]
    out = run(pts, STRIP, 1.0, 300)
    for p, x in zip(out, [1 / 6, 1 / 2, 5 / 6]):
        assert abs(p[0] - x) < 1e-9 and abs(p[1] - 0.05) < 1e-12


def test_line_in_square_is_a_saddle() -> None:
    line = [(1 / 6, 0.5), (0.5, 0.5), (5 / 6, 0.5)]
    assert centroid_gap(line, SQUARE) < 1e-14
    assert abs(coverage_cost(line, SQUARE) - 5 / 54) < 1e-14
    out = run([(1 / 6, 0.5), (0.5, 0.5 - 1e-6), (5 / 6, 0.5)], SQUARE, 1.0, 200)
    assert centroid_gap(out, SQUARE) < 1e-9
    assert coverage_cost(out, SQUARE) < 0.067


def test_cost_against_known_values_and_grid() -> None:
    assert abs(coverage_cost([(0.5, 0.5)], SQUARE) - 1 / 6) < 1e-14
    assert abs(coverage_cost([(0.25, 0.5), (0.75, 0.5)], SQUARE) - 5 / 48) < 1e-14
    assert abs(coverage_cost([(1 / 3, 2 / 3), (2 / 3, 1 / 3)], SQUARE) - 1 / 9) < 1e-14
    rng = random.Random(2)
    pts = [(rng.random(), rng.random()) for _ in range(4)]
    assert abs(coverage_cost(pts, SQUARE) - grid_cost(pts)) < 1e-4


def test_cost_never_increases_and_decrease_bound() -> None:
    rng = random.Random(3)
    for k in (0.3, 0.7, 1.0):
        pts = [(rng.uniform(0, 2), rng.uniform(0, 1.5)) for _ in range(6)]
        for _ in range(25):
            data = cell_data(pts, PENTAGON)
            before = sum(c for _, _, c in data)
            gap = sum(m * math.dist(p, c) ** 2 for p, (m, c, _) in zip(pts, data))
            pts = coverage_step(pts, PENTAGON, k)
            after = coverage_cost(pts, PENTAGON)
            assert after <= before - k * (2 - k) * gap + 1e-12


def test_robots_stay_inside_and_distinct() -> None:
    rng = random.Random(4)
    pts = [(rng.uniform(0, 2), rng.uniform(0, 1.5)) for _ in range(7)]
    for _ in range(30):
        pts = coverage_step(pts, PENTAGON, 0.5)
        for p in pts:
            assert moments(voronoi_cell(0, [p], PENTAGON))[0] > 0
        assert min(math.dist(a, b) for i, a in enumerate(pts) for b in pts[i + 1:]) > 1e-6


def test_converges_to_centroidal_configuration() -> None:
    rng = random.Random(5)
    pts = [(rng.random(), rng.random()) for _ in range(5)]
    out = run(pts, SQUARE, 1.0, 400)
    assert centroid_gap(out, SQUARE) < 1e-6


def test_diagonal_critical_point_is_fixed_but_not_optimal() -> None:
    diag = [(1 / 3, 2 / 3), (2 / 3, 1 / 3)]
    assert centroid_gap(diag, SQUARE) < 1e-14
    halves = [(0.25, 0.5), (0.75, 0.5)]
    assert centroid_gap(halves, SQUARE) < 1e-14
    assert coverage_cost(halves, SQUARE) < coverage_cost(diag, SQUARE)
    assert run(diag, SQUARE, 1.0, 50) == diag
    out = run([(1 / 3 + 1e-6, 2 / 3), (2 / 3, 1 / 3)], SQUARE, 1.0, 200)
    assert abs(coverage_cost(out, SQUARE) - 5 / 48) < 1e-12
    assert centroid_gap(out, SQUARE) < 1e-9

History

Lloyd described the iteration in 1957 at Bell Labs for the design of quantizers, and it was published in 1982. Du, Faber and Gunzburger (1999) surveyed centroidal Voronoi tessellations and Lloyd's method. Cortés, Martínez, Karatas and Bullo (2004) turned the iteration into a control law for mobile sensing networks, and proved convergence with an invariance principle. The book of Bullo, Cortés and Martínez (2009) treats deployment in its own chapter.

References

  1. Jorge Cortes, Sonia Martinez, Timur Karatas and Francesco Bullo, Coverage control for mobile sensing networks, IEEE Transactions on Robotics and Automation 20(2), 2004, pages 243 to 255 (the cost, its gradient, the continuous and discrete laws, and convergence to centroidal Voronoi configurations)
  2. Stuart P. Lloyd, Least squares quantization in PCM, IEEE Transactions on Information Theory 28(2), 1982, the iteration that alternates nearest cells and centroids
  3. Qiang Du, Vance Faber and Max Gunzburger, Centroidal Voronoi tessellations, applications and algorithms, SIAM Review 41(4), 1999, pages 637 to 676 (centroidal Voronoi tessellations as critical points of the energy, and Lloyd's method)
  4. Sonia Martinez, Francesco Bullo, Jorge Cortes and Emilio Frazzoli, On synchronous robotic networks, Part II, Time complexity of rendezvous and deployment algorithms, IEEE Transactions on Automatic Control 52(12), 2007, pages 2214 to 2226 (the number of rounds of deployment algorithms)
  5. Francesco Bullo, Jorge Cortes and Sonia Martinez, Distributed Control of Robotic Networks, Princeton University Press, 2009, Chapter 5, Deployment

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_robot
  • 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