Algorithm Search⌘K

Algorithmcore

Boustrophedon cell decomposition

Also called boustrophedon coverage.

Splits free space into cells at critical points of a sweep line and covers each cell by back and forth lanes.

Time
O(n log^2 n + m log n) worst
Space
O(n + m) extra
Where
m = the number of lanes; n = the number of obstacle vertices
Properties
deterministicexactofflinenot randomized
Origin
Howie Choset, Philippe Pignon, 1998

The boustrophedon cell decomposition splits the free part of a known planar region into cells that a robot can cover with simple back and forth lanes, like an ox plowing a field (the Greek word means "as the ox turns"). A vertical line sweeps across the region. At each position, the free part of the line is a set of intervals. The number of intervals changes only at a few critical points: where an obstacle begins, one interval splits into two, and where an obstacle ends, two intervals merge into one. Each interval traces a cell between two critical points. Inside a cell, the robot moves up and down along lanes spaced by its tool width; the cells are then visited one by one along their adjacency graph. Howie Choset and Philippe Pignon introduced it for coverage path planning as a coarser version of the trapezoidal decomposition: it cuts only where the connectivity of the sweep line changes, not at every vertex, so it has fewer cells and fewer turns.

In plain words

Think of mowing a lawn that has some flower beds in it. The easiest way to mow is in long straight strips, up and down, moving over by one mower width each time. That works until a flower bed splits a strip in two. So you divide the lawn into pieces where this happens: one piece before the flower bed, one piece above it, one piece below it, and one piece after it. Each piece can be mowed in plain strips with no surprises.

The method finds those pieces by sliding a line across the lawn and watching where it gets split or joined. Then it mows the pieces one after another.

The problem

Input. A rectangle [0,W]×[0,H][0, W] \times [0, H] and kk disjoint convex polygons inside it, with nn vertices in total, given with exact rational coordinates; and a tool width w>0w > 0. In general position: each polygon has one leftmost and one rightmost vertex, and no two of these share an xx. Arithmetic on the coordinates costs one step, as in the real RAM.

Output. A set of cells whose interiors are disjoint and whose union is the free space; the adjacency graph of the cells; and a coverage path made of vertical lane segments, such that every free point is at horizontal distance at most w/2w/2 from a lane of its own cell.

How it differs from close pages. The trapezoidal decomposition cuts at every vertex, which gives trapezoids for point location and cell decomposition planners; the boustrophedon decomposition merges trapezoids into cells that one back and forth pattern covers. Convex decomposition also splits a region, but into convex pieces, and has no notion of a sweep. Frontier-based exploration works on an unknown map; this method needs the whole map in advance.

The algorithm

  1. BOUSTROPHEDON(W, H, obstacles, w)
  2. 1events ← the leftmost and the rightmost vertex of each obstacle, sorted by x
  3. 2open one cell for the whole slice at x = 0; active ← no obstacles
  4. 3for each event (x, o):
  5. 4if x is the leftmost vertex of o: close the cell that contains the vertex; open a cell below o and a cell above o; link both to the closed cell; insert o into active
  6. 5else: close the cells just below and just above o; open one cell that spans both; link it to both; remove o from active
  7. 6close every open cell at x = W
  8. 7order ← the cells in depth-first order of the adjacency graph, from the first cell
  9. 8in each cell of order: cover it with ⌈(x1 - x0)/w⌉ evenly spaced vertical lanes, alternately up and down

The sweep line keeps the active obstacles in their order from bottom to top; disjoint convex obstacles never cross, so this order changes only at events. The gap between two consecutive active obstacles, or between an obstacle and the bottom or top of the rectangle, is one open cell. Line L4 finds the gap that contains the new vertex by comparing it with the active obstacles at that xx. A cell's walls may bend at vertices of the obstacles between its two events; the cell does not split there, because the slice stays one interval. That is the difference from the trapezoidal decomposition.

Line L8 uses ⌈(x1−x0)/w⌉\lceil(x_1 - x_0)/w\rceil lanes at the centers of equal strips, so each lane is at most ww from the next and the end lanes are at most w/2w/2 from the ends of the cell. Each lane runs from the lower wall to the upper wall of the cell at its xx.

Example

The region is 10×610 \times 6, with a diamond obstacle with vertices (3,3)(3, 3), (5,1)(5, 1), (7,3)(7, 3) and (5,5)(5, 5). The events are the IN event at x=3x = 3 and the OUT event at x=7x = 7.

Cell xx range Lower wall Upper wall Area Lanes for w=1w = 1
0 0 to 3 bottom top 18 3
1 3 to 7 bottom diamond, lower edges 8 4
2 3 to 7 diamond, upper edges top 8 4
3 7 to 10 bottom top 18 3

The areas add up to 60−8=5260 - 8 = 52, the area of the free space. The vertex (5,1)(5, 1) bends the upper wall of cell 1, but the slice stays one interval, so cell 1 is not cut there. A trapezoidal decomposition would cut at x=5x = 5 too and give 6 cells. The adjacency graph is a 4-cycle: 0 is linked to 1 and 2, and both are linked to 3. Depth-first order from cell 0 is 0, 1, 3, 2: the robot covers the left part, the part below the diamond, the right part, and then the part above, which it reaches from cell 3. The lanes of cell 1 are at x=3.5,4.5,5.5,6.5x = 3.5, 4.5, 5.5, 6.5, from y=0y = 0 up to 2.5,1.5,1.5,2.52.5, 1.5, 1.5, 2.5.

Correctness

The proof shows that the cells partition the free space, that each cell is bounded by two walls that do not cross, that the adjacency graph is connected, and that kk obstacles in general position give exactly 1+3k1 + 3k cells: each IN event closes one cell and opens two, and each OUT event closes two and opens one. It also shows that every free point is within horizontal distance w/2w/2 of a lane of its cell. The tests check the partition on random points of random scenes in exact rational arithmetic, the total area against the shoelace formula, the cell count, that linked cells share a boundary segment, and the spacing of the lanes.

Proof: The boustrophedon cells partition the free space and the lanes cover each cellfull

Line numbers refer to the pseudocode on the boustrophedon cell decomposition page. The region is the rectangle R=[0,W]×[0,H]R = [0, W] \times [0, H], and the obstacles O1,…,OkO_1, \dots, O_k are disjoint closed convex polygons in the interior of RR. The free space is F=R∖⋃jOjF = R \setminus \bigcup_j O_j. General position: each obstacle has one leftmost vertex and one rightmost vertex, and the 2k2k event abscissas are distinct. For an obstacle OO and an xx in its xx-range, write O(x)=[ℓO(x),uO(x)]O(x) = [\ell_O(x), u_O(x)] for its slice on the vertical line at xx. A cell CC with abscissas x0<x1x_0 < x_1 and walls ff and gg is the open set {(x,y):x0<x<x1, f(x)<y<g(x)}\{(x, y) : x_0 < x < x_1,\ f(x) < y < g(x)\}, where ff is 00 or uOu_O for an obstacle OO, and gg is HH or ℓO\ell_O.

Lemma 1 (the order of the obstacles is fixed between events). If the xx-ranges of two obstacles AA and BB share an open interval II, then either uA(x)<ℓB(x)u_A(x) < \ell_B(x) for all xx in II, or uB(x)<ℓA(x)u_B(x) < \ell_A(x) for all xx in II.

Proof. AA and BB are disjoint compact convex sets, so a line LL strictly separates them. If LL were vertical, at x=cx = c, then one xx-range would be in x<cx < c and the other in x>cx > c, and the ranges would not share an open interval. So LL is the graph of an affine function hh, with, say, AA below and BB above. Then uA(x)<h(x)<ℓB(x)u_A(x) < h(x) < \ell_B(x) for every xx in II. □\square

So, on each open interval between two consecutive events, the active obstacles have a fixed order from bottom to top, and their slices are disjoint closed intervals in that order. Write the boundaries in order as b0=0,O(1),…,O(a),ba+1=Hb_0 = 0, O_{(1)}, \dots, O_{(a)}, b_{a+1} = H. The free slice at such an xx is the union of the a+1a + 1 open gaps between consecutive boundaries (the lower end of a gap is 00 or uu of the obstacle below, the upper end is HH or ℓ\ell of the obstacle above), together with the boundary points of the slices, which are a finite set on each line.

Lemma 2 (the sweep invariant). After line L2 and after each event of lines L4 and L5, let ee be the last event abscissa (e=0e = 0 after L2) and let e′e' be the next one (e′=We' = W after the last event). Then active lists the obstacles whose xx-range contains (e,e′)(e, e'), in order from bottom to top, and gaps lists a+1a + 1 open cells, with x0≤ex_0 \le e, such that the ii-th cell has the walls of the ii-th gap. Each of these cells has x0x_0 set and x1x_1 not yet set, and every other cell has x1≤ex_1 \le e.

Proof. By induction on the events. After line L2, no obstacle is active, since all obstacles lie in the interior of RR, and the one cell has walls 00 and HH.

IN event of OO at x=ex = e, with leftmost vertex v=(e,yv)v = (e, y_v). The point vv is on the boundary of OO, so it is not in another obstacle, and it is not on the boundary of RR. By Lemma 1 and the induction hypothesis, the active obstacles at ee have disjoint slices in their order, and yvy_v lies in none of them. So yvy_v lies in exactly one gap: the one with index pp equal to the number of active obstacles with u(e)<yvu(e) < y_v, which line L4 computes. For xx slightly larger than ee, the slice of OO is a short interval near yvy_v, inside gap pp. So gap pp splits into the gap from its old lower wall to ℓO\ell_O and the gap from uOu_O to its old upper wall. Line L4 sets x1=ex_1 = e on the old cell, opens these two cells, inserts OO at index pp in active, and replaces the old cell by the two new cells in gaps. The invariant holds again.

OUT event of OO at x=ex = e. OO is active at index pp. Gap pp lies just below OO and gap p+1p + 1 just above it. For xx slightly larger than ee, OO is gone, and these two gaps become one gap from the lower wall of gap pp to the upper wall of gap p+1p + 1. Line L5 closes both cells at ee, opens the merged cell, and replaces the two cells by it. The invariant holds again. □\square

Theorem 1 (partition). The cells are open, pairwise disjoint, and contained in FF. Every point of FF outside a finite union of vertical segments and obstacle edges is in exactly one cell. So the closures of the cells cover FF, and the areas of the cells add up to the area of FF.

Proof. Take (x,y)(x, y) with xx not an event abscissa and yy not on a slice boundary. Let e<x<e′e < x < e' for consecutive events ee and e′e'. By Lemma 2, the cells with x0<x<x1x_0 < x < x_1 are exactly the cells in gaps during (e,e′)(e, e'): the cells opened later have x0≥e′x_0 \ge e', and the cells closed earlier have x1≤ex_1 \le e. Line L6 closes the last cells at WW. The open intervals of these cells at xx are the gaps, which are disjoint, and their union is the free slice minus the boundary points. So (x,y)(x, y) is in exactly one cell if it is free, and in no cell if it is in an obstacle. The excluded points are on the 2k2k event lines and on the obstacle edges, which have area zero. □\square

Theorem 2 (the count and the graph). There are exactly 1+3k1 + 3k cells and 4k4k adjacency edges. The adjacency graph is connected, and two linked cells share a boundary segment of positive length on a vertical line.

Proof. Line L2 opens one cell. Each IN event opens two cells and adds two edges, and each OUT event opens one cell and adds two edges. There are kk events of each kind, so there are 1+2k+k1 + 2k + k cells and 4k4k edges. The two edges of an event join a new cell to a cell opened earlier, and no edge is added twice, since each new cell is linked only at its own event. By induction on the order in which the cells are opened, each cell is joined to cell 0. So the depth-first search of line L7 reaches every cell.

At an IN event at x=ex = e, the old cell's interval at ee is (f(e),g(e))(f(e), g(e)) with f(e)<yv<g(e)f(e) < y_v < g(e). The slice of OO at ee is the point yvy_v, so the new cells have the intervals (f(e),yv)(f(e), y_v) and (yv,g(e))(y_v, g(e)) at ee, and each shares a segment of positive length with the old cell. At an OUT event, the same holds with the rightmost vertex of OO and the merged cell. □\square

Theorem 3 (the lanes). For a cell with width s=x1−x0s = x_1 - x_0 and a tool width w>0w > 0, line L8 makes m=max⁡(1,⌈s/w⌉)m = \max(1, \lceil s/w \rceil) lanes at xi=x0+(2i+1)s/(2m)x_i = x_0 + (2i + 1)s/(2m) for i=0,…,m−1i = 0, \dots, m - 1. Each lane is a nonempty vertical segment inside the closure of the cell, and every xx in [x0,x1][x_0, x_1] is within w/2w/2 of some xix_i.

Proof. Since m≥s/wm \ge s/w, the gap between consecutive lanes is s/m≤ws/m \le w, and the first and last lanes are s/(2m)≤w/2s/(2m) \le w/2 from x0x_0 and x1x_1. Each xix_i lies strictly between x0x_0 and x1x_1, where the interval of the cell is open and nonempty by Lemma 2, so the lane from f(xi)f(x_i) to g(xi)g(x_i) has positive length. The coverage path runs lane ii upward when ii is even and downward when ii is odd, so consecutive lanes of a cell join at the same wall. □\square

Remarks. Theorem 3 bounds the horizontal distance from a free point to the line of a lane. It does not say that the tool, a segment of width ww swept along the lane, covers every point: next to a slanted wall, the lane at xix_i may end before the wall at xx is reached, which leaves a thin wedge. General position is used in Lemma 1 (no shared event abscissa) and in Lemma 2 (one leftmost and one rightmost vertex). The code does not use a balanced tree. Each event scans the active list and slices each active obstacle, so the decomposition takes O(klog⁡k+kn)O(k \log k + kn) steps. The tests check Theorem 1 on 150 random points in each of 12 random scenes, with exact fractions and with points kept off the event lines, and they check the areas against the shoelace formula. They also check the counts of Theorem 2 and the shared segments. Theorem 3 is checked on 8 scenes with three tool widths.

Complexity

  • Time. Sorting the 2k2k events costs O(klog⁡k)O(k \log k). With the active obstacles in a balanced search tree, each event makes O(log⁡k)O(\log k) comparisons, and each comparison evaluates a chain of an obstacle at xx by binary search in O(log⁡n)O(\log n). The decomposition takes O(n+klog⁡klog⁡n)O(n + k \log k \log n), which is O(nlog⁡2n)O(n \log^2 n), and each of the mm lanes needs two chain evaluations, O(log⁡n)O(\log n) each. The code uses lists and linear scans instead, so it takes O(kn+mn)O(kn + mn), which is enough for a few hundred vertices.
  • Space. O(n)O(n) for the obstacles, the cells and the graph, and O(m)O(m) for the path.

Properties

  • Complete coverage. For a tool of width ww that moves along the lanes, every free point is within w/2w/2 horizontally of a lane of its cell. Near a slanted wall, the tool may miss a thin sliver at the end of a lane, which practical planners cover by a pass along the wall.
  • Few cells. 1+3k1 + 3k cells for kk convex obstacles, independent of the number of vertices. The trapezoidal decomposition has a cell count that grows with the number of vertices.
  • Exact. With rational input, the decomposition, the areas and the lanes are exact.
  • Direction matters. The number of turns, and so the time of the coverage, depends on the sweep direction. Turning the sweep to follow the longest dimension of the region usually reduces the turns.

Variants and improvements

  • Morse decompositions. Acar, Choset and others generalized the critical points to those of a Morse function: a circle that grows from a point gives spiral coverage, and other functions give other patterns.
  • Nonconvex obstacles. A nonconvex obstacle has more IN and OUT events: every vertex where the slice splits or merges is critical, not only the leftmost and rightmost ones.
  • Online coverage. The robot can detect the critical points with its sensors while it covers an unknown region, and build the adjacency graph as it goes.
  • Better cell order. Ordering the cells is a kind of traveling salesman problem on the adjacency graph; depth-first order is simple, but a tour that also chooses the start corner of each cell is shorter.

When to use it

Use the boustrophedon decomposition when the map is known, the obstacles are polygons, and the robot covers with a tool of fixed width: floor cleaning, lawn mowing, painting, field work and seabed or aerial surveys. When the map is a grid, a grid-based method or a spanning-tree coverage is often simpler. When the map is unknown, use an online coverage method, or explore first.

Pitfalls

  • Degenerate input. Vertical edges at the leftmost or rightmost point, or two events at the same xx, need extra care: merge the events, or perturb the input.
  • Lane ends near slanted walls. A lane that ends where the wall is steep leaves a thin wedge uncovered next to the wall. Add a pass along the boundary.
  • Too narrow cells. A cell narrower than the tool still gets one lane; the tool may not fit. Inflate the obstacles by half the tool width first, as in the configuration space.
  • Travel between cells. Depth-first order can send the robot back through covered cells. Count that travel in the path length.

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.

boustrophedon_cell_decomposition.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boustrophedon-cell-decomposition/. The authors are listed in prov/E8C6B2.jsonl.

"""Boustrophedon cell decomposition (Choset and Pignon 1998) and the coverage path.

The region is the rectangle [0, W] x [0, H] minus disjoint convex polygonal obstacles in
its interior. Coordinates are Fractions (or ints), so all tests are exact. General
position: each obstacle has a unique leftmost and a unique rightmost vertex, and no two
obstacles share the x of such a vertex.

A vertical line sweeps from left to right. Between critical points, the slice of free
space is a fixed number of intervals; each interval traces one cell. At the leftmost
vertex of an obstacle (an IN event) one interval splits into two; at the rightmost
vertex (an OUT event) two intervals merge into one. Each cell is then covered by
vertical lanes, up and down, and the cells are visited in depth-first order.
"""

from fractions import Fraction
import math


def polygon_slice(poly, x):
    """(ylo, yhi) of a convex polygon on the vertical line at x, or None if it misses."""
    ys = []
    m = len(poly)
    for i in range(m):
        (ax, ay), (bx, by) = poly[i], poly[(i + 1) % m]
        if ax == bx:
            if ax == x:
                ys += [ay, by]
        elif min(ax, bx) <= x <= max(ax, bx):
            ys.append(ay + (by - ay) * (x - ax) / (bx - ax))
    return (min(ys), max(ys)) if ys else None


class Cell:
    """A cell between x0 and x1. low and high are obstacle indices, or None for the
    bottom (y = 0) and top (y = H) of the rectangle."""

    def __init__(self, cid, x0, low, high):
        self.id, self.x0, self.x1, self.low, self.high = cid, x0, None, low, high

    def __repr__(self):
        return f"Cell({self.id}, {self.x0}..{self.x1}, low={self.low}, high={self.high})"


def floor_y(cell, obstacles, x):
    """The y of the lower wall of the cell at x."""
    return Fraction(0) if cell.low is None else polygon_slice(obstacles[cell.low], x)[1]


def ceil_y(cell, obstacles, x, height):
    """The y of the upper wall of the cell at x."""
    return Fraction(height) if cell.high is None else polygon_slice(obstacles[cell.high], x)[0]


def decompose(width, height, obstacles):
    """Returns (cells, adjacency): a list of Cells and a dict from cell id to a set of ids."""
    events = []
    for k, poly in enumerate(obstacles):
        xs = [p[0] for p in poly]
        events.append((min(xs), 0, k))  # IN
        events.append((max(xs), 1, k))  # OUT
    events.sort()  # @line L1
    cells, adj = [], {}

    def open_cell(x, low, high):
        c = Cell(len(cells), x, low, high)
        cells.append(c)
        adj[c.id] = set()
        return c

    def link(a, b):
        adj[a.id].add(b.id)
        adj[b.id].add(a.id)

    active = []  # obstacles crossing the sweep line, from bottom to top
    gaps = [open_cell(Fraction(0), None, None)]  # @line L2
    for x, kind, k in events:  # @line L3
        poly = obstacles[k]
        if kind == 0:  # @line L4
            yv = next(p[1] for p in poly if p[0] == x)
            pos = sum(1 for j in active if polygon_slice(obstacles[j], x)[1] < yv)
            old = gaps[pos]
            old.x1 = x
            below, above = open_cell(x, old.low, k), open_cell(x, k, old.high)
            link(old, below)
            link(old, above)
            active.insert(pos, k)
            gaps[pos:pos + 1] = [below, above]  # @line L4
        else:  # @line L5
            pos = active.index(k)
            below, above = gaps[pos], gaps[pos + 1]
            below.x1 = above.x1 = x
            merged = open_cell(x, below.low, above.high)
            link(below, merged)
            link(above, merged)
            del active[pos]
            gaps[pos:pos + 2] = [merged]  # @line L5
    for c in gaps:  # @line L6
        c.x1 = Fraction(width)
    return cells, adj


def cell_area(cell, obstacles, height):
    """Exact area: the height of the cell is linear between vertex abscissas."""
    xs = {cell.x0, cell.x1}
    for k in (cell.low, cell.high):
        if k is not None:
            xs |= {p[0] for p in obstacles[k] if cell.x0 < p[0] < cell.x1}
    xs = sorted(xs)
    gap = [ceil_y(cell, obstacles, x, height) - floor_y(cell, obstacles, x) for x in xs]
    return sum((xs[i + 1] - xs[i]) * (gap[i] + gap[i + 1]) / 2 for i in range(len(xs) - 1))


def locate(cells, obstacles, height, x, y):
    """The ids of the cells whose interior contains (x, y) (one for a free point off the event lines)."""
    return [c.id for c in cells
            if c.x0 < x < c.x1 and floor_y(c, obstacles, x) < y < ceil_y(c, obstacles, x, height)]


def dfs_order(adj, start=0):
    """Cells in the order a depth-first search first reaches them, smallest id first."""
    order, seen, stack = [], set(), [start]
    while stack:
        c = stack.pop()
        if c in seen:
            continue
        seen.add(c)
        order.append(c)
        stack.extend(sorted(adj[c] - seen, reverse=True))
    return order  # @line L7


def lanes(cell, obstacles, height, w):
    """ceil(width / w) evenly spaced vertical lanes; returns (x, ylo, yhi) for each, bottom-up."""
    span = cell.x1 - cell.x0
    m = max(1, math.ceil(span / w))
    out = []
    for i in range(m):
        x = cell.x0 + (2 * i + 1) * span / (2 * m)  # @line L8
        out.append((x, floor_y(cell, obstacles, x), ceil_y(cell, obstacles, x, height)))
    return out


def coverage_path(cells, adj, obstacles, height, w):
    """The lane segments in visiting order, alternating up and down inside each cell."""
    path = []
    for cid in dfs_order(adj):
        for i, (x, lo, hi) in enumerate(lanes(cells[cid], obstacles, height, w)):
            path.append(((x, lo), (x, hi)) if i % 2 == 0 else ((x, hi), (x, lo)))  # @line L8
    return path
test_boustrophedon_cell_decomposition.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boustrophedon-cell-decomposition/. The authors are listed in prov/E8C6B2.jsonl.

import math
import random
from fractions import Fraction

from boustrophedon_cell_decomposition import (
    cell_area,
    ceil_y,
    coverage_path,
    decompose,
    dfs_order,
    floor_y,
    lanes,
    locate,
    polygon_slice,
)

W, H = 20, 12


def hull(points):
    pts = sorted(set(points))

    def cross(o, a, b):
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

    lower, upper = [], []
    for p in pts:
        while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
            lower.pop()
        lower.append(p)
    for p in reversed(pts):
        while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
            upper.pop()
        upper.append(p)
    return lower[:-1] + upper[:-1]


def shoelace(poly):
    m = len(poly)
    return abs(sum(poly[i][0] * poly[(i + 1) % m][1] - poly[(i + 1) % m][0] * poly[i][1] for i in range(m))) / 2


def random_obstacles(rng, k):
    """k disjoint convex polygons in general position inside the rectangle."""
    while True:
        discs, polys = [], []
        for _ in range(200):
            if len(polys) == k:
                break
            r = rng.uniform(0.6, 2.0)
            cx, cy = rng.uniform(r + 0.5, W - r - 0.5), rng.uniform(r + 0.5, H - r - 0.5)
            if any(math.hypot(cx - a, cy - b) < r + s + 0.3 for a, b, s in discs):
                continue
            pts = []
            for _ in range(rng.randint(3, 6)):
                t = rng.uniform(0, 2 * math.pi)
                pts.append((Fraction(round((cx + r * math.cos(t)) * 1000), 1000),
                            Fraction(round((cy + r * math.sin(t)) * 1000), 1000)))
            poly = hull(pts)
            xs = sorted(p[0] for p in poly)
            if len(poly) < 3 or xs[0] == xs[1] or xs[-1] == xs[-2]:
                continue
            discs.append((cx, cy, r))
            polys.append(poly)
        ends = [x for p in polys for x in (min(q[0] for q in p), max(q[0] for q in p))]
        if len(polys) == k and len(set(ends)) == len(ends):
            return polys


def inside(poly, x, y):
    s = polygon_slice(poly, x)
    return s is not None and s[0] <= y <= s[1]


def test_example_diamond():
    diamond = [(3, 3), (5, 1), (7, 3), (5, 5)]
    obstacles = [[(Fraction(a), Fraction(b)) for a, b in diamond]]
    cells, adj = decompose(10, 6, obstacles)
    assert len(cells) == 4
    assert [cell_area(c, obstacles, 6) for c in cells] == [18, 8, 8, 18]
    assert adj == {0: {1, 2}, 1: {0, 3}, 2: {0, 3}, 3: {1, 2}}
    assert dfs_order(adj) == [0, 1, 3, 2]
    assert sum(len(lanes(c, obstacles, 6, 1)) for c in cells) == 14
    # Lanes of the cell below the diamond: x = 3.5, 4.5, 5.5, 6.5, from y = 0 to the lower edge.
    assert lanes(cells[1], obstacles, 6, 1) == [(Fraction(7, 2), 0, Fraction(5, 2)), (Fraction(9, 2), 0, Fraction(3, 2)),
                                                (Fraction(11, 2), 0, Fraction(3, 2)), (Fraction(13, 2), 0, Fraction(5, 2))]


def test_cells_partition_the_free_space():
    rng = random.Random(41)
    for trial in range(12):
        k = rng.randint(0, 5)
        obstacles = random_obstacles(rng, k)
        cells, adj = decompose(W, H, obstacles)
        assert len(cells) == 1 + 3 * k
        free_area = W * H - sum(shoelace(p) for p in obstacles)
        assert sum(cell_area(c, obstacles, H) for c in cells) == free_area
        for _ in range(150):
            x = Fraction(rng.randrange(1, 10 ** 6 * W), 10 ** 6) + Fraction(1, 7 * 10 ** 7)
            y = Fraction(rng.randrange(1, 10 ** 6 * H), 10 ** 6) + Fraction(1, 11 * 10 ** 7)
            blocked = any(inside(p, x, y) for p in obstacles)
            assert len(locate(cells, obstacles, H, x, y)) == (0 if blocked else 1)


def test_adjacency_graph():
    rng = random.Random(42)
    for trial in range(12):
        k = rng.randint(1, 5)
        obstacles = random_obstacles(rng, k)
        cells, adj = decompose(W, H, obstacles)
        assert sum(len(v) for v in adj.values()) == 2 * 4 * k
        assert sorted(dfs_order(adj)) == list(range(len(cells)))
        for a in adj:
            for b in adj[a]:
                ca, cb = cells[a], cells[b]
                if ca.x1 != cb.x0:
                    ca, cb = cb, ca
                x = ca.x1
                assert x == cb.x0
                lo = max(floor_y(ca, obstacles, x), floor_y(cb, obstacles, x))
                hi = min(ceil_y(ca, obstacles, x, H), ceil_y(cb, obstacles, x, H))
                assert hi > lo


def test_lanes_cover_each_cell_within_half_a_width():
    rng = random.Random(43)
    for trial in range(8):
        obstacles = random_obstacles(rng, rng.randint(1, 4))
        cells, adj = decompose(W, H, obstacles)
        w = Fraction(rng.choice([1, 2, 3]), 2)
        path = coverage_path(cells, adj, obstacles, H, w)
        assert len(path) == sum(max(1, math.ceil((c.x1 - c.x0) / w)) for c in cells)
        for c in cells:
            xs = [ln[0] for ln in lanes(c, obstacles, H, w)]
            assert xs[0] - c.x0 <= w / 2 and c.x1 - xs[-1] <= w / 2
            assert all(b - a <= w for a, b in zip(xs, xs[1:]))
            for x, lo, hi in lanes(c, obstacles, H, w):
                assert lo < hi and not any(inside(p, x, (lo + hi) / 2) for p in obstacles)
        # Inside each cell, in visiting order, the lanes alternate up and down.
        i = 0
        for cid in dfs_order(adj):
            for j in range(len(lanes(cells[cid], obstacles, H, w))):
                (x0, y0), (x1, y1) = path[i]
                assert x0 == x1 and (y1 > y0) == (j % 2 == 0)
                i += 1
        assert i == len(path)

History

The trapezoidal decomposition, used in motion planning since the 1980s, cuts the free space at every vertex. Choset and Pignon presented the boustrophedon cellular decomposition at the Field and Service Robotics conference in 1997, published in 1998: cut only at the critical points where the sweep line's free part splits or merges, and cover each cell by back and forth motion. Choset described it again in Autonomous Robots in 2000. Later work generalized the critical points through Morse functions, and the survey of Galceran and Carreras lists it among the main exact cellular decompositions for coverage.

References

  1. Coverage path planning: the boustrophedon cellular decomposition, Field and Service Robotics, edited by A. Zelinsky, Springer, 1998, pp. 203-209, the whole paper (the decomposition at the points where the slice changes connectivity, and the coverage of each cell by back and forth motion)
  2. Coverage of known spaces: the boustrophedon cellular decomposition, Autonomous Robots 9(3), pp. 247-253, the whole paper
  3. A survey on coverage path planning for robotics, Robotics and Autonomous Systems 61(12), pp. 1258-1276, the part on exact cellular decompositions

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.worst
  • 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