Algorithm Search⌘K

Algorithmresearch

Connected Fermat spiral toolpath

Also called Fermat spiral infill.

Zhao and coauthors' fill that covers a layer with Fermat spirals joined into one continuous path, which avoids the many starts and stops of contour filling.

Time
O(n) worst
Space
O(n) extra
Where
n = number of contours of the rectangle
Properties
deterministicexactiterative
Origin
Haisen Zhao, Fanglin Gu, Qi Xing Huang, Jorge Garcia, Yong Chen, Changhe Tu, Bedrich Benes, Hao Zhang, Daniel Cohen Or, Baoquan Chen, 2016

A connected Fermat spiral toolpath fills one layer of a printed part with a single continuous path. Zhao and coauthors (2016) built it from the iso-contours of the distance to the boundary, the same curves that a contour-parallel toolpath prints as separate closed loops. A Fermat spiral links every second contour into an inward spiral and the other contours into an outward spiral, and joins the two at the center. Both ends of the path then lie on the outer contour, next to each other, so the spiral of one region can be linked to the spirals of the regions around it. A contour fill with nn loops needs nn starts and stops of the nozzle. A Fermat spiral needs one. This page gives the construction on a rectangle, with exact offsets, and proves that the path is simple, stays inside, and covers the rectangle. The general method of the paper, for any region, is described in words only.

In plain words

Draw nested rectangles inside a rectangle, one bead width apart. A printer could print each one as a closed loop, but then it must stop, lift, move and start again for every loop, and each start leaves a mark.

Instead, cut every loop open at one place on its bottom side. Join loop 1 to loop 3, loop 3 to loop 5, and so on, with short vertical pieces that pass through the cuts of the loops in between. This gives a spiral that goes in. Join loops 2, 4, 6 in the same way. That spiral comes back out. Connect the two spirals at the middle. The nozzle now goes in along one spiral and comes out along the other, and it ends right next to where it started.

The problem

The input is a rectangle [0,W]×[0,H][0, W] \times [0, H] with W≥HW \ge H and a bead width w>0w > 0. The output is a path for the nozzle, a polyline. A good fill path is simple (it does not cross or touch itself), stays at least w/2w/2 from the boundary so that the bead stays inside, and leaves no gap and no overlap between beads. A fill path for a region in a layer is a case of toolpath planning.

The contours are the curves at distance di=(i−12) wd_i = (i - \tfrac12)\,w from the boundary, for i=1,…,ni = 1, \dots, n, where nn is the number of such ii with di<H/2d_i < H/2. In a rectangle, the contour at distance dd is the rectangle [d,W−d]×[d,H−d][d, W - d] \times [d, H - d]. With a square bead of side ww centered on the path, contour ii covers the frame of points whose distance to the boundary is between (i−1)w(i - 1)w and iwiw.

The algorithm

Let XX be the abscissa of the links. Write cj=X−jwc_j = X - jw. Contour ii is cut open on its bottom side between cic_i and ci−2c_{i-2}, a gap of length 2w2w, except the innermost contour, which has the gap from cn−1c_{n-1} to cn−2c_{n-2}.

  1. FERMAT-RECTANGLE(W, H, w, X)
  2. 1n ← number of i ≥ 1 with (i − 1/2)w < H/2
  3. 2if n < 2 or not (2n − 3/2)w < X < W − 3w/2 then fail
  4. 3for i ← 1 to n do
  5. 4d ← (i − 1/2)w
  6. 5s ← (c_(i−2), d) ▷ start of the open contour
  7. 6e ← (c_i, d) if i < n, else (c_(n−1), d) ▷ end of the open contour
  8. 7R_i ← s, (W − d, d), (W − d, H − d), (d, H − d), (d, d), e
  9. 8A ← R_1 R_3 R_5 ... ▷ the inward spiral
  10. 9B ← R_2 R_4 R_6 ... ▷ the outward spiral, before reversal
  11. 10P ← A followed by B reversed ▷ the segment between them is the center join
  12. 11append (X, w/2) to P ▷ the exit, back to contour 1
  13. 12return P

Each open contour RiR_i goes counterclockwise from its start ss to its end ee. In line L8, the end (ci,di)(c_i, d_i) of RiR_i and the start (ci,di+2)(c_i, d_{i+2}) of Ri+2R_{i+2} have the same abscissa, so consecutive contours of AA are joined by a vertical link at x=cix = c_i of length 2w2w. That link crosses the bottom side of contour i+1i + 1 at cic_i, which is the middle of the gap of contour i+1i + 1. Line L9 does the same for the even contours. Line L10 joins the last points of AA and BB, which are the ends of contours n−1n - 1 and nn and lie on the vertical line x=cn−1x = c_{n-1}. Line L11 adds a last vertical piece from the start of contour 2 down through the gap of contour 1.

The bounds of line L2 make every piece fit. The end of contour nn must lie right of its left side, cn−1>dnc_{n-1} > d_n, which is X>(2n−32)wX > (2n - \tfrac32)w. The start of each contour must lie left of its right side, ci−2<W−dic_{i-2} < W - d_i, which is X<W−32wX < W - \tfrac32 w for every ii. A valid XX exists if and only if W>2nwW > 2nw. A square with W=H=2nwW = H = 2nw has no valid XX in this form. The code of this page rejects it.

Example

Take W=6W = 6, H=4H = 4, w=1w = 1 and X=72X = \tfrac72. Line L1 gives n=2n = 2 (with d1=12d_1 = \tfrac12 and d2=32<2d_2 = \tfrac32 < 2), and line L2 needs 52<X<92\tfrac52 < X < \tfrac92.

line value
L5 to L7, i=1i = 1 R1R_1: (92,12)(\tfrac92, \tfrac12), (112,12)(\tfrac{11}2, \tfrac12), (112,72)(\tfrac{11}2, \tfrac72), (12,72)(\tfrac12, \tfrac72), (12,12)(\tfrac12, \tfrac12), (52,12)(\tfrac52, \tfrac12)
L5 to L7, i=2i = 2 R2R_2: (72,32)(\tfrac72, \tfrac32), (92,32)(\tfrac92, \tfrac32), (92,52)(\tfrac92, \tfrac52), (32,52)(\tfrac32, \tfrac52), (32,32)(\tfrac32, \tfrac32), (52,32)(\tfrac52, \tfrac32)
L8, L9 A=R1A = R_1, B=R2B = R_2
L10 R1R_1, then (52,32)(\tfrac52, \tfrac32), (32,32)(\tfrac32, \tfrac32), (32,52)(\tfrac32, \tfrac52), (92,52)(\tfrac92, \tfrac52), (92,32)(\tfrac92, \tfrac32), (72,32)(\tfrac72, \tfrac32)
L11 (72,12)(\tfrac72, \tfrac12)

The path has 13 points and length 23. It starts at (92,12)(\tfrac92, \tfrac12) and ends at (72,12)(\tfrac72, \tfrac12), one bead width to the left. The center join is the segment from (52,12)(\tfrac52, \tfrac12) up to (52,32)(\tfrac52, \tfrac32). A square bead of side 1 along the path covers area 23⋅1+1=24=WH23 \cdot 1 + 1 = 24 = W H, and the covered region is the whole rectangle, so there is no gap and no overlap. Printed as two closed contour loops, the same layer needs two starts. Printed as this path, it needs one.

For W=10W = 10, H=7H = 7 and w=1w = 1, line L1 gives n=3n = 3. The path has length 65, and the beads leave a strip of area (10−6)(7−6)=4(10 - 6)(7 - 6) = 4 at the center uncovered, because the height is not an even multiple of ww. A contour fill with the same contours leaves the same strip.

Correctness

Four facts hold for every input that passes line L2. The full proof is below.

  • Simple. Every segment is horizontal or vertical. The contours are nested rectangles ww apart. A vertical link at cic_i spans the heights did_i to di+2d_{i+2}, and so it meets only contours ii, i+1i + 1 and i+2i + 2. It meets contour i+1i + 1 inside its gap, because ci−1>ci>ci+1c_{i-1} > c_i > c_{i+1}. The links are at different abscissas c1,…,cn−2c_1, \dots, c_{n-2}, the center join is at cn−1c_{n-1}, and the exit is at c0c_0, inside the gap of contour 1. So no two segments meet except consecutive ones at their shared point.
  • Inside. Every point has both coordinates at least w/2w/2 from the boundary, so a bead of width ww stays inside the rectangle.
  • Ends on the boundary. The path starts at (c−1,w/2)(c_{-1}, w/2) and ends at (c0,w/2)(c_0, w/2), both on contour 1, at distance ww.
  • Coverage. The square beads cover the whole rectangle except the core of points at distance more than nwnw from the boundary, which has area (W−2nw) max⁡(0,H−2nw)(W - 2nw)\,\max(0, H - 2nw). The gap of contour ii is filled by the link at ci−1c_{i-1} for 2≤i≤n−12 \le i \le n - 1, by the exit for i=1i = 1, and needs nothing for i=ni = n, because its length is ww.

The length is L=2n(W+H)−4wn2−wL = 2n(W + H) - 4wn^2 - w: the perimeters of the contours, minus the gaps, plus the links, the join and the exit. If H=2nwH = 2nw, the bead area Lw+w2Lw + w^2 equals WHWH, and the beads cover the rectangle with no overlap. If H<2nwH < 2nw, the two long sides of contour nn are closer than ww, and the beads there overlap. These are properties of the construction on this page, proved for rectangles. This page makes no coverage claim for general regions.

Proof: The Fermat spiral of a rectangle is a simple path inside it that covers all but the corefull

Claim. Let W≥H>0W \ge H > 0 and w>0w > 0, let n≥2n \ge 2 be the number of i≥1i \ge 1 with di=(i−12)w<H/2d_i = (i - \tfrac12)w < H/2, and let (2n−32)w<X<W−32w(2n - \tfrac32)w < X < W - \tfrac32 w. Write cj=X−jwc_j = X - jw. Then FERMAT-RECTANGLE(W,H,w,X)(W, H, w, X) stops and returns a polyline PP with these properties:

  1. every segment of PP is horizontal or vertical and has positive length, and two segments of PP meet only if they are consecutive, and then only at their shared point;
  2. every point of PP lies in [w/2,W−w/2]×[w/2,H−w/2][w/2, W - w/2] \times [w/2, H - w/2];
  3. PP starts at (c−1,w/2)(c_{-1}, w/2) and ends at (c0,w/2)(c_0, w/2);
  4. the union of the closed squares of side ww centered at the points of PP is the set of points of the rectangle at distance at most nwnw from its boundary, where the distance is δ(x,y)=min⁡(x,y,W−x,H−y)\delta(x, y) = \min(x, y, W - x, H - y).

Termination is clear: the loop of line L3 runs nn times, and every other line does a fixed amount of work.

Step 0 (two inequalities). For 1≤i≤n1 \le i \le n: cmin⁡(i,n−1)>dic_{\min(i, n-1)} > d_i, because cmin⁡(i,n−1)−di≥cn−1−dn=X−(2n−32)w>0c_{\min(i,n-1)} - d_i \ge c_{n-1} - d_n = X - (2n - \tfrac32)w > 0 (the left side decreases in ii for i≤n−1i \le n-1, and for i=ni = n it is exactly cn−1−dnc_{n-1} - d_n). And ci−2<W−dic_{i-2} < W - d_i, because W−di−ci−2=W−X−32w>0W - d_i - c_{i-2} = W - X - \tfrac32 w > 0. Also dn<H/2d_n < H/2 gives di<H−did_i < H - d_i for all i≤ni \le n, and W≥HW \ge H gives di<W−did_i < W - d_i.

Step 1 (the pieces). Let QiQ_i be the rectangle [di,W−di]×[di,H−di][d_i, W - d_i] \times [d_i, H - d_i], contour ii. By Step 0 it is not degenerate. The open contour RiR_i of line L7 is QiQ_i without the open interval Gi=(ei,si)G_i = (e_i, s_i) of its bottom side, where si=ci−2s_i = c_{i-2}, ei=cie_i = c_i for i<ni < n and en=cn−1e_n = c_{n-1}. By Step 0, di<ei<si<W−did_i < e_i < s_i < W - d_i, so GiG_i lies strictly inside the bottom side, and the five segments of RiR_i have positive length. The other segments of PP are:

  • the links of lines L8 and L9: for 1≤i≤n−21 \le i \le n - 2, the vertical segment ViV_i at x=cix = c_i from y=diy = d_i (the end of RiR_i) to y=di+2y = d_{i+2} (the start of Ri+2R_{i+2});
  • the center join JJ at x=cn−1x = c_{n-1} from dn−1d_{n-1} to dnd_n: the last point of AA and the last point of BB are the ends en−1=(cn−1,dn−1)e_{n-1} = (c_{n-1}, d_{n-1}) and en=(cn−1,dn)e_n = (c_{n-1}, d_n), in some order;
  • the exit EE at x=c0x = c_0 from y=d2y = d_2 (the start s2s_2 of R2R_2, which is the last point of BB reversed) to y=d1=w/2y = d_1 = w/2.

So PP is the chain R1,V1,R3,V3,…R_1, V_1, R_3, V_3, \dots, then JJ, then the even contours in reverse with their links, then EE. Every segment is horizontal or vertical with positive length.

Step 2 (simple). The rectangles QiQ_i are nested and disjoint: Qi+1Q_{i+1} lies in the interior of QiQ_i, since di+1=di+wd_{i+1} = d_i + w. So two different contours never meet. A vertical segment at abscissa xx with heights in [di,di+2][d_i, d_{i+2}] meets only QiQ_i, Qi+1Q_{i+1} and Qi+2Q_{i+2}, and it meets QjQ_j only where it crosses or touches the bottom side y=djy = d_j, provided di+2<x<W−di+2d_{i+2} < x < W - d_{i+2}. This holds for the link ViV_i at x=cix = c_i, i≤n−2i \le n - 2: ci+di+2=X+32w<Wc_i + d_{i+2} = X + \tfrac32 w < W and ci−di+2≥cn−2−dn=X−(2n−52)w>0c_i - d_{i+2} \ge c_{n-2} - d_n = X - (2n - \tfrac52)w > 0. It holds for JJ (contours n−1n - 1 and nn): cn−1+dn=X+12w<Wc_{n-1} + d_n = X + \tfrac12 w < W and cn−1>dnc_{n-1} > d_n by Step 0. It holds for EE (contours 1 and 2): c0+d2=X+32w<Wc_0 + d_2 = X + \tfrac32 w < W and c0>cn−1>dn≥d2c_0 > c_{n-1} > d_n \ge d_2.

  • ViV_i meets RiR_i only at its lower end and Ri+2R_{i+2} only at its upper end. It crosses the line y=di+1y = d_{i+1} at x=cix = c_i, and ci+1<ci<ci−1c_{i+1} < c_i < c_{i-1}, so the crossing point lies in the gap Gi+1=(ci+1,ci−1)G_{i+1} = (c_{i+1}, c_{i-1}) if i+1<ni + 1 < n, or in Gn=(cn−1,cn−2)G_n = (c_{n-1}, c_{n-2}) if i+1=ni + 1 = n. So ViV_i does not meet Ri+1R_{i+1}.
  • JJ spans [dn−1,dn][d_{n-1}, d_n] and meets only Rn−1R_{n-1} and RnR_n, at its ends.
  • EE spans [d1,d2][d_1, d_2]. It meets R2R_2 only at s2s_2. At y=d1y = d_1 its point (c0,d1)(c_0, d_1) lies in G1=(c1,c−1)G_1 = (c_1, c_{-1}), so it does not meet R1R_1.
  • Two of these vertical segments have different abscissas c1,…,cn−2c_1, \dots, c_{n-2}, cn−1c_{n-1} and c0c_0, so they are disjoint.

Within one RiR_i, the five segments form a rectangle minus a gap, so only consecutive ones meet, at corners, and the first and the last do not meet because GiG_i is not empty. A link meets the segments of RiR_i and Ri+2R_{i+2} only at the shared end points. This proves part 1.

Step 3 (inside, ends). Every point of PP lies on some QiQ_i, and Qi⊆[d1,W−d1]×[d1,H−d1]Q_i \subseteq [d_1, W - d_1] \times [d_1, H - d_1] with d1=w/2d_1 = w/2. The first point of PP is s1=(c−1,d1)s_1 = (c_{-1}, d_1) and the last is (c0,w/2)(c_0, w/2). This proves parts 2 and 3.

Step 4 (coverage). For a set SS, let S+S^+ be the union of the closed squares of side ww centered at the points of SS, which is the set of points at L∞L_\infty distance at most w/2w/2 from SS. For a rectangle, Qi+Q_i^+ is the closed frame Fi={(i−1)w≤δ≤iw}F_i = \{(i - 1)w \le \delta \le iw\}. Every segment of PP lies on some QiQ_i or between two of them, so P+⊆⋃iFi={δ≤nw}P^+ \subseteq \bigcup_i F_i = \{\delta \le nw\}.

For the other inclusion, fix ii and a point q∈Fiq \in F_i. If qq is within L∞L_\infty distance w/2w/2 of a point of RiR_i, it is covered. Otherwise its nearest points on QiQ_i lie in the gap, and so qq lies in the box [ei+w/2,si−w/2]×[(i−1)w,iw][e_i + w/2, s_i - w/2] \times [(i-1)w, iw]. For i=ni = n the gap has length cn−2−cn−1=wc_{n-2} - c_{n-1} = w, so this box is the single segment x=cn−1+w/2x = c_{n-1} + w/2, and its points are at distance exactly w/2w/2 from both ends of RnR_n, so they are covered. For i<ni < n the box is [ci−1−w/2,ci−1+w/2]×[(i−1)w,iw][c_{i-1} - w/2, c_{i-1} + w/2] \times [(i-1)w, iw]. If 2≤i≤n−12 \le i \le n - 1, the link Vi−1V_{i-1} at x=ci−1x = c_{i-1} spans the heights di−1d_{i-1} to di+1d_{i+1}, so its square bead covers the heights (i−2)w(i - 2)w to (i+1)w(i + 1)w and the abscissas of the box. If i=1i = 1, the exit EE at x=c0x = c_0 spans d1d_1 to d2d_2, and its bead covers the heights 00 to 2w2w. So Fi⊆P+F_i \subseteq P^+ for every ii, and P+={δ≤nw}P^+ = \{\delta \le nw\}.

The core {δ>nw}\{\delta > nw\} is the open rectangle (nw,W−nw)×(nw,H−nw)(nw, W - nw) \times (nw, H - nw), of area (W−2nw)max⁡(0,H−2nw)(W - 2nw)\max(0, H - 2nw); note W>2nwW > 2nw follows from the bounds on XX. This proves part 4. ■\blacksquare

Complexity

The path has 6n+16n + 1 points, and each is found in O(1)O(1) time, so the time and the extra space are O(n)O(n), with n<H/(2w)+12n < H/(2w) + \tfrac12. The tests check simplicity by comparing all pairs of segments, which is O(n2)O(n^2) and is not part of the algorithm.

For a general region, the cost of the method of Zhao and coauthors is dominated by the computation of the iso-contours of the distance field and by the smoothing and optimization steps. The paper does not state a single bound for the whole pipeline, and this page does not give one.

Properties

  • One path. The layer is printed with one start and one stop, against one per contour for a contour fill.
  • Spacing. Two parallel passes side by side are ww apart, except the two long sides of the innermost contour, which are H−2dnH - 2d_n apart. The tests check this on squares and rectangles. The proof page does not prove it.
  • Both ends outside. The two ends lie on the outer contour, one bead width apart. A spiral can be opened there and spliced into a neighbor path.
  • Follows the boundary. Like a contour fill, every pass is parallel to the boundary, so the outer surface is printed by a contour, not by the ends of raster lines.
  • Few sharp turns on smooth regions. On a smooth region, the spirals turn as gently as the contours. On a rectangle, the corners stay.
  • Exact. With rational input, every point is rational, and every claim above is checked exactly.

Variants and improvements

  • General regions. For a region with holes or several lobes, the contours of the distance field change topology: a contour splits into two, or two merge. Zhao and coauthors split the region at these events into spiralable parts, each with nested contours, fill each part with a Fermat spiral, and connect the spirals into one path by a traversal of the tree of parts. Each connection opens a spiral at its two ends on the boundary and routes it through the neighbor. This page does not implement that pipeline.
  • Smoothing. The paper smooths the path and adjusts the spacing to reduce sharp turns and gaps between beads. Those steps are not part of this page.
  • Single spiral. A plain spiral links contour ii to contour i+1i + 1 and ends at the center. It is also one path, but its end is inside, so it cannot be linked to a neighbor without a jump.
  • Other fills. A direction-parallel toolpath uses parallel lines joined end to end. It is simpler and gives the same pattern in every region, but it meets the boundary at the end of every line. See infill pattern for the sparse fills used inside parts.

When to use it

Use a connected Fermat spiral when the number of starts and stops matters, for example on extrusion printers where each start and stop leaves a mark or a weak spot, and when the fill should follow the boundary. Use a raster fill when the region is very thin or very complex, or when the slicer must be simple and fast. The claims of the paper about print quality are measured on test prints. The claims on this page are proved for rectangles only.

Pitfalls

  • Spacing near the links. The pieces next to the links are short when XX is close to a bound of line L2. A piece of length much less than ww makes a tight U-turn, where real beads overlap. Choose XX near the middle of the interval.
  • Even and odd heights. If HH is not an even multiple of ww, the center has a gap or an overlap. Adjust ww slightly, as the paper adjusts the spacing, or accept the error.
  • Squares. A square of side aa works in this form only if 2nw<a≤(2n+1)w2nw < a \le (2n + 1)w, for example a=7a = 7 or a=9a = 9 with w=1w = 1. A square of side 2nw2nw has no valid link position. Use a different place for the links, or change ww slightly.
  • The exit fills a gap. Contour 1 has a gap of 2w2w, and only the exit passes through it. If the exit is left out, a square of side ww next to the start stays empty.
  • Floating-point offsets. For general regions, offsets in floating point can make two contours touch or cross. Snap the result and check for self-intersection.

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.

fermat_spiral_toolpath.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fermat-spiral-toolpath/. The authors are listed in prov/RPHNQ4.jsonl.

"""A connected Fermat spiral on an axis-aligned rectangle, with exact offsets.

This is the basic step of Zhao et al. (2016) on the simplest region. The
iso-contours of the distance to the boundary at spacing w are the rectangles
inset by d_i = (i - 1/2) w. Each contour is cut open on its bottom edge. The
odd contours are linked into one inward spiral, the even contours into a
second one, and the two spirals are joined at the center. The result is one
path that goes in and comes out again, and both of its ends lie on the outer
contour, at distance w from each other.

The general pipeline of the paper (contours of a distance field on any region,
the split into spiralable parts, and the linking of many spirals into one
path) is not implemented here.

Coordinates are int or Fraction, so every test on the result is exact.
"""

from fractions import Fraction


def ring_count(height, w):
    """Number of contours i >= 1 with (i - 1/2) w < height / 2."""
    half = Fraction(height) / 2
    n = 0
    while (n + Fraction(1, 2)) * w < half:
        n += 1
    return n


def link_range(width, height, w):
    """The open interval of link abscissas X that give a valid path."""
    width, height, w = Fraction(width), Fraction(height), Fraction(w)
    n = ring_count(height, w)
    return n, (2 * n - Fraction(3, 2)) * w, width - Fraction(3, 2) * w


def fermat_rectangle(width, height, w, x_link=None):
    """Return the path as a list of (x, y) points.

    The rectangle is [0, width] x [0, height] with width >= height, and w is
    the spacing. x_link is the abscissa X of the links. It must satisfy
    (2n - 3/2) w < X < width - 3w/2. The default is the midpoint.
    Raises ValueError if no valid path of this form exists.
    """
    width, height, w = Fraction(width), Fraction(height), Fraction(w)
    if height > width:
        raise ValueError("expects width >= height; swap the axes")
    n, lo, hi = link_range(width, height, w)  # @line L1
    if x_link is None:
        x_link = (lo + hi) / 2
    x_link = Fraction(x_link)
    if n < 2 or not lo < x_link < hi:  # @line L2
        raise ValueError("the rectangle is too small or too narrow for this spacing")
    rings = []
    for i in range(1, n + 1):  # @line L3
        d = (i - Fraction(1, 2)) * w  # @line L4
        s = (x_link - (i - 2) * w, d)  # @line L5
        e = (x_link - min(i, n - 1) * w, d)  # @line L6
        rings.append([s, (width - d, d), (width - d, height - d), (d, height - d), (d, d), e])  # @line L7
    odd = [p for ring in rings[0::2] for p in ring]  # @line L8
    even = [p for ring in rings[1::2] for p in ring]  # @line L9
    path = odd + even[::-1]  # @line L10
    path.append((x_link, w / 2))  # the exit: back down to contour 1  # @line L11
    return path  # @line L12


def segments(path):
    return [(path[i], path[i + 1]) for i in range(len(path) - 1)]


def length(path):
    """Length of the path. Every segment is axis-parallel."""
    return sum(abs(b[0] - a[0]) + abs(b[1] - a[1]) for a, b in segments(path))


if __name__ == "__main__":
    p = fermat_rectangle(6, 4, 1, Fraction(7, 2))
    print(" ".join("(%s, %s)" % (x, y) for x, y in p))
    print("length", length(p))
test_fermat_spiral_toolpath.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fermat-spiral-toolpath/. The authors are listed in prov/RPHNQ4.jsonl.

import random
from fractions import Fraction as F

import pytest

from fermat_spiral_toolpath import fermat_rectangle, length, link_range, ring_count, segments


def box(seg):
    (x0, y0), (x1, y1) = seg
    return min(x0, x1), min(y0, y1), max(x0, x1), max(y0, y1)


def meet(a, b):
    """Intersection of two axis-parallel segments as a box, or None."""
    a, b = box(a), box(b)
    lo_x, lo_y, hi_x, hi_y = max(a[0], b[0]), max(a[1], b[1]), min(a[2], b[2]), min(a[3], b[3])
    if lo_x > hi_x or lo_y > hi_y:
        return None
    return lo_x, lo_y, hi_x, hi_y


def union_area(rects):
    """Exact area of a union of boxes by coordinate compression (brute force)."""
    xs = sorted({r[0] for r in rects} | {r[2] for r in rects})
    ys = sorted({r[1] for r in rects} | {r[3] for r in rects})
    total = F(0)
    for i in range(len(xs) - 1):
        cx = (xs[i] + xs[i + 1]) / 2
        col = [r for r in rects if r[0] < cx < r[2]]
        for j in range(len(ys) - 1):
            cy = (ys[j] + ys[j + 1]) / 2
            if any(r[1] < cy < r[3] for r in col):
                total += (xs[i + 1] - xs[i]) * (ys[j + 1] - ys[j])
    return total


def bead(path, w):
    """The square bead of side w swept along each segment."""
    h = w / 2
    return [(b[0] - h, b[1] - h, b[2] + h, b[3] + h) for b in map(box, segments(path))]


def random_case(rng):
    w = F(rng.choice([1, 1, 2, 3]), rng.choice([1, 2]))
    height = w * F(rng.randint(31, 130), 10)  # height > 3w, so n >= 2
    n = ring_count(height, w)
    width = max(height, 2 * n * w) + w * F(rng.randint(1, 60), 10)
    n, lo, hi = link_range(width, height, w)
    x = lo + (hi - lo) * F(rng.randint(1, 99), 100)
    return width, height, w, x


def check_simple(path):
    seg = segments(path)
    for i, a in enumerate(seg):
        assert a[0] != a[1] and (a[0][0] == a[1][0] or a[0][1] == a[1][1])  # nonzero, axis-parallel
        for j in range(i + 1, len(seg)):
            m = meet(a, seg[j])
            if j == i + 1:
                assert m == (a[1][0], a[1][1], a[1][0], a[1][1])  # only the shared vertex
            else:
                assert m is None


def test_page_example():
    p = fermat_rectangle(6, 4, 1, F(7, 2))
    h = F(1, 2)
    want = [(9 * h, h), (11 * h, h), (11 * h, 7 * h), (h, 7 * h), (h, h), (5 * h, h),
            (5 * h, 3 * h), (3 * h, 3 * h), (3 * h, 5 * h), (9 * h, 5 * h), (9 * h, 3 * h), (7 * h, 3 * h), (7 * h, h)]
    assert p == want
    assert length(p) == 23
    assert union_area(bead(p, F(1))) == 24  # covers the whole 6 x 4 rectangle


def test_simple_inside_and_ends_on_the_boundary():
    rng = random.Random(4)
    for _ in range(150):
        width, height, w, x = random_case(rng)
        p = fermat_rectangle(width, height, w, x)
        check_simple(p)
        assert all(w / 2 <= px <= width - w / 2 and w / 2 <= py <= height - w / 2 for px, py in p)
        (sx, sy), (ex, ey) = p[0], p[-1]
        assert sy == ey == w / 2 and sx - ex == w  # both ends on contour 1, side by side


def test_length_formula():
    rng = random.Random(5)
    for _ in range(150):
        width, height, w, x = random_case(rng)
        n = ring_count(height, w)
        assert length(fermat_rectangle(width, height, w, x)) == 2 * n * (width + height) - 4 * w * n * n - w


def test_coverage_and_overlap():
    rng = random.Random(6)
    exact = 0
    for _ in range(60):
        width, height, w, x = random_case(rng)
        if rng.random() < 0.3:  # make the height an even multiple of w
            height = 2 * w * rng.randint(2, 6)
            width = max(width, height + w)
            n, lo, hi = link_range(width, height, w)
            x = (lo + hi) / 2
        p = fermat_rectangle(width, height, w, x)
        n = ring_count(height, w)
        covered = union_area(bead(p, w))
        core = (width - 2 * n * w) * max(F(0), height - 2 * n * w)
        assert covered == width * height - core
        material = length(p) * w + w * w
        assert material >= covered
        if height == 2 * n * w:
            exact += 1
            assert covered == material == width * height  # no gap and no overlap
    assert exact > 5


def parallel_gap(a, b):
    """Distance of two parallel segments whose projections overlap with positive length, else None."""
    (ax0, ay0), (ax1, ay1) = a
    (bx0, by0), (bx1, by1) = b
    if ay0 == ay1 and by0 == by1:
        if min(max(ax0, ax1), max(bx0, bx1)) > max(min(ax0, ax1), min(bx0, bx1)):
            return abs(ay0 - by0)
    if ax0 == ax1 and bx0 == bx1:
        if min(max(ay0, ay1), max(by0, by1)) > max(min(ay0, ay1), min(by0, by1)):
            return abs(ax0 - bx0)
    return None


def test_spacing_of_passes_on_squares_and_rectangles():
    rng = random.Random(8)
    cases = [(F(7), F(7), F(1)), (F(21, 2), F(21, 2), F(1)), (F(9), F(9), F(1))]
    cases += [random_case(rng)[:3] for _ in range(40)]
    for width, height, w in cases:
        p = fermat_rectangle(width, height, w)
        seg = segments(p)
        gaps = [parallel_gap(seg[i], seg[j]) for i in range(len(seg)) for j in range(i + 1, len(seg))]
        n = ring_count(height, w)
        inner = height - (2 * n - 1) * w  # distance of the long sides of the innermost contour
        assert min(g for g in gaps if g is not None) == min(w, inner)


def test_feasibility_interval():
    rng = random.Random(7)
    for _ in range(60):
        width, height, w, _ = random_case(rng)
        n, lo, hi = link_range(width, height, w)
        for bad in (lo, hi, lo - w / 7, hi + w / 7):
            with pytest.raises(ValueError):
                fermat_rectangle(width, height, w, bad)
        check_simple(fermat_rectangle(width, height, w, lo + (hi - lo) / 1000))
        check_simple(fermat_rectangle(width, height, w, hi - (hi - lo) / 1000))
    with pytest.raises(ValueError):
        fermat_rectangle(6, 6, 1)  # n = 3 needs width > 6
    with pytest.raises(ValueError):
        fermat_rectangle(10, 2, 1)  # one contour only
    check_simple(fermat_rectangle(7, 6, 1))


def test_without_the_bounds_the_path_breaks():
    # At X = hi the first piece of each contour has length zero.
    width, height, w = F(10), F(7), F(1)
    n, lo, hi = link_range(width, height, w)
    p = fermat_rectangle(width, height, w, hi - F(1, 10 ** 6))
    assert min(abs(b[0] - a[0]) + abs(b[1] - a[1]) for a, b in segments(p)) == F(1, 10 ** 6)

History

Zhao, Gu, Huang, Garcia, Chen, Tu, Benes, Zhang, Cohen-Or and Chen presented connected Fermat spirals for layered fabrication at SIGGRAPH 2016, in ACM Transactions on Graphics. The name comes from the Fermat spiral r2=a2θr^2 = a^2 \theta, which has two arms that wind into the center and meet there. Earlier fill paths for printing and for pocket milling were contour loops or zigzag lines.

References

  1. Haisen Zhao, Fanglin Gu, Qi-Xing Huang, Jorge Garcia, Yong Chen, Changhe Tu, Bedrich Benes, Hao Zhang, Daniel Cohen-Or and Baoquan Chen, Connected Fermat spirals for layered fabrication, ACM Transactions on Graphics 35(4), Article 100, 2016, the construction of a Fermat spiral from the iso-contours of a spiralable region, and the connection of the spirals of all regions into one path
  2. Ian Gibson, David Rosen, Brent Stucker and Mahyar Khorasani, Additive Manufacturing Technologies, 3rd edition, Springer, 2021, the discussion of contour and raster fill paths for extrusion processes

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
  • at least three sources
  • a scene preset for the example