Algorithm Search⌘K

Data structureadvanced

Nef polyhedron

Also called Nef polyhedra, selective Nef complex.

A point set built from finitely many half-spaces by Boolean operations, closed also under interior, closure and boundary, and stored exactly by Hachenberger and Kettner's selective Nef complex.

Time
O(n^3) worst
Space
O(n^3) extra
Where
n = the number of distinct lines or planes that bound the set

A Nef polyhedron in Rd\mathbb{R}^d is a set that can be built from finitely many open half-spaces by complement and intersection, and so also by union and difference. Walter Nef introduced these sets in 1978. They contain far more than solids. A Nef polyhedron may be open, closed or neither, and it may have dangling faces, isolated edges and points, and cuts inside it. Nef polyhedra are closed under all Boolean operations and under interior, closure, boundary and regularization. This is not true of the r-sets of classical solid modeling, which need regularized operations to stay closed. The usual representation is selective: take the arrangement of all bounding hyperplanes, and mark each of its faces as in or out. Hachenberger, Kettner and Mehlhorn built the three-dimensional version, the selective Nef complex, with exact arithmetic, and it is the basis of exact Boolean operations and Minkowski sums of polyhedra in CGAL. This page gives the data structure in the plane, where the faces are vertices, edges and cells of a line arrangement, and the closure results with proofs.

In plain words

Draw a few straight lines across a sheet of paper. They cut it into pieces: points where lines cross, bits of lines between crossings, and open regions between the lines. Now colour some of the pieces. Any set you can make from half-planes by "and", "or" and "not" is exactly such a colouring, for some lines.

That gives a simple way to store the set: the lines, and a yes or no for every piece. To combine two sets, draw both sets of lines, so the pieces get smaller, and colour each small piece by the rule. To find the inside of a set, keep a coloured piece only if all pieces that touch it are coloured too. To find the closure, add every piece that touches a coloured one.

The abstract type

A Nef polygon (the case d=2d = 2) is a subset of the plane with these operations:

  • Build an open or closed half-plane {ax+by+c>0}\{a x + b y + c > 0\} or {ax+by+c≥0}\{a x + b y + c \ge 0\}, the empty set or the whole plane.
  • Booleans: union, intersection, difference, symmetric difference and complement, with no regularization.
  • Topology: interior, closure, boundary and regularization cl⁡(int⁡(⋅))\operatorname{cl}(\operatorname{int}(\cdot)).
  • Queries: does the set contain a point pp; is it empty; how many marked vertices, edges and cells does it have.
  • Simplify: drop the lines on which the set does not depend.

The values are the sets, not their descriptions: two formulas that give the same set give equal Nef polygons, and emptiness of the symmetric difference tests this.

Representation

Let HH be a finite set of lines, each in a canonical form ax+by+c=0a x + b y + c = 0 with the first nonzero coefficient of (a,b)(a, b) equal to 1. The sign vector of a point pp is σ(p)=(sign⁡(aipx+bipy+ci))i∈H\sigma(p) = (\operatorname{sign}(a_i p_x + b_i p_y + c_i))_{i \in H}. The faces of the arrangement of HH are the classes of points with equal sign vectors: vertices, open edges and open cells, of dimension 0, 1 and 2 by the number of zero signs. A face gg is above a face ff when f⊆cl⁡(g)f \subseteq \operatorname{cl}(g) and f≠gf \ne g; the faces above ff are its star. In sign vectors, gg is above ff exactly when gg agrees with ff wherever ff is nonzero.

A Nef polygon is stored as the pair (H,M)(H, M), where MM is the set of marked faces, given by their sign vectors. The arrangement keeps, for each face, its dimension and its star. The code builds them from the lines. Each pair of lines that cross gives a vertex. The vertices on each line, sorted along it, cut it into edges. Each edge has two cells, its sign vector with the zero for its line replaced by +1+1 and by −1-1. The star of an edge is its two cells. The star of a vertex is the edges that end at it and their cells.

Operations

  1. CONTAINS(A, p)
  2. 1return σ_A(p) ∈ A.marks ▷ O(n) sign tests
  3. COMBINE(A, B, op) ▷ op is and, or, minus or xor
  4. 2H ← A.lines ∪ B.lines, as canonical lines
  5. 3build the arrangement of H: its faces, their dimensions and stars
  6. 4for each face f of the arrangement do
  7. 5f_A ← f restricted to A.lines; f_B ← f restricted to B.lines
  8. 6mark f if op(f_A ∈ A.marks, f_B ∈ B.marks)
  9. 7return (H, marks)
  10. INTERIOR(A)
  11. 8return the marked faces f whose whole star is marked
  12. CLOSURE(A)
  13. 9return the faces f that are marked or have a marked face in their star
  14. BOUNDARY(A)
  15. 10return CLOSURE(A) minus INTERIOR(A)

Complement flips every mark on the same arrangement. A half-plane is built on the arrangement of its one line: two cells and the line itself, which is marked when the half-plane is closed. Regularization is CLOSURE(INTERIOR(A)).

Simplify. Line ii can be dropped when the mark of every face depends only on its signs on the other lines, that is, when the set is a union of faces of the coarser arrangement. The code drops such lines one at a time, rebuilding the arrangement after each.

Example

Take the closed square [0,2]2[0,2]^2, the segment from (2,1)(2,1) to (3,1)(3,1) and the point (4,4)(4,4), each built as an intersection of four closed half-planes, and let SS be their union. Its arrangement has the 8 lines x=0,2,3,4x = 0, 2, 3, 4 and y=0,1,2,4y = 0, 1, 2, 4, with 16 vertices, 40 edges and 25 cells. The line y=1y = 1 runs through the square, so the square is two cells, the edge between them and the six vertices and six edges around them.

set marked vertices marked edges marked cells lines after simplify
SS 8 8 2 8
int⁡S\operatorname{int} S 0 1 2 4 (the open square: 0, 0, 1)
cl⁡S\operatorname{cl} S 8 8 2 8 (it is SS, which is closed)
∂S\partial S 8 7 0 8
cl⁡int⁡S\operatorname{cl} \operatorname{int} S 6 7 2 4 (the closed square: 4, 4, 1)
complement of SS 8 32 23 8

The interior of SS keeps the inner edge on y=1y = 1, since both cells beside it are marked, and drops the segment and the point, whose stars are not marked. Regularization removes the segment and the point and gives back the square, which is the r-set that a classical modeler would keep. A Nef polygon keeps all three parts. Every line of SS is needed: x=3x = 3 and y=1y = 1 for the segment, x=4x = 4 and y=4y = 4 for the point.

A second example shows why r-sets need regularized operations. The closed half-planes x≥0x \ge 0 and x≤0x \le 0 are both r-sets, but their intersection is the line x=0x = 0: one marked edge and no cells. It is a Nef polygon, but not an r-set, and its regularization is empty.

Correctness

The three facts below are proved in the proof file.

  1. Every Nef polygon is a finite union of faces of a line arrangement, and every such union is a Nef polygon. A half-plane is a union of faces of the arrangement of its line. Unions of faces of a fixed arrangement are closed under complement and intersection, and a finer arrangement refines every face of a coarser one. Conversely, each face is an intersection of open half-planes and lines, and a line is the complement of the union of two open half-planes.
  2. The topological operations depend only on the star. Every point pp of a face ff has a neighbourhood that meets exactly ff and the faces of its star. So pp is interior to a union of faces SS exactly when ff and its whole star are in SS, and in the closure exactly when ff or a face of its star is in SS. Lines L8 and L9 compute this, and the results are again unions of faces, so Nef polygons are closed under interior, closure, boundary and regularization.
  3. Booleans are exact on the common refinement. Each face of the arrangement of HA∪HBH_A \cup H_B lies inside the face of AA's arrangement with the restricted sign vector, so line L6 marks the face exactly when its points satisfy the Boolean rule.

By contrast, the r-sets, the closed regular sets with S=cl⁡int⁡SS = \operatorname{cl}\operatorname{int} S, are not closed under intersection, as the example of the line shows, and not under complement, since the complement of a closed set is open. The regularized operations A∩∗B=cl⁡int⁡(A∩B)A \cap^* B = \operatorname{cl}\operatorname{int}(A \cap B) fix this, and Nef polygons give them by line L8, then line L9.

The tests check the code against the defining formulas. A random formula over 1 to 16 half-planes with integer coefficients in [−3,3][-3, 3], open or closed, combined by and, or, minus, xor and not, is evaluated at every grid point with denominator 2 in [−3,3]2[-3, 3]^2 and at every crossing of two of its lines. The answer is compared with the Nef polygon's CONTAINS. Interior, closure and boundary are checked the same way against an independent oracle. The oracle evaluates the formula at pp and at p+εdp + \varepsilon d for a fixed set of directions dd that has a direction in every wedge between two possible lines, with ε\varepsilon small enough that no other line is crossed. Nested topological operators shrink ε\varepsilon by a factor of 100 per level. The tests also check cl⁡cl⁡=cl⁡\operatorname{cl}\operatorname{cl} = \operatorname{cl}, int⁡int⁡=int⁡\operatorname{int}\operatorname{int} = \operatorname{int}, cl⁡(∁S)=∁int⁡S\operatorname{cl}(\complement S) = \complement\operatorname{int} S and ∂S=cl⁡S∩cl⁡∁S\partial S = \operatorname{cl} S \cap \operatorname{cl}\complement S, that regularization is idempotent, and that simplification keeps the set.

Proof: Nef polygons are the unions of arrangement faces, are closed under Booleans and the topological operations, and the stored operations are exactfull

We use the notation and the pseudocode of the page. A Nef polygon is a subset of R2\mathbb{R}^2 obtained from finitely many open half-planes {ax+by+c>0}\{a x + b y + c > 0\} by complement and intersection. Union and difference follow by De Morgan's laws. For a finite set HH of distinct lines, A(H)\mathcal{A}(H) is its arrangement, whose faces are the classes of equal sign vectors, and a union of faces of A(H)\mathcal{A}(H) is a set ⋃f∈Mf\bigcup_{f \in M} f for some set MM of faces.

Lemma 1 (faces are convex and the sign vector order is the closure order). Each face of A(H)\mathcal{A}(H) is a nonempty convex set, relatively open, of dimension 2 minus the rank of the lines on which it lies: a cell, an open edge or a vertex. For faces f≠gf \ne g, f⊆cl⁡(g)f \subseteq \operatorname{cl}(g) exactly when gi=fig_i = f_i for every ii with fi≠0f_i \ne 0.

Proof. A face is the solution set of finitely many strict and non-strict linear constraints si(aix+biy+ci)>0s_i (a_i x + b_i y + c_i) > 0 or =0= 0, so it is convex. It is relatively open in the affine set cut out by its equations. If f⊆cl⁡(g)f \subseteq \operatorname{cl}(g) and fi≠0f_i \ne 0, then a point of ff has a neighbourhood where line ii has the constant sign fif_i, and this neighbourhood meets gg, so gi=fig_i = f_i. Conversely, suppose gg agrees with ff where ff is nonzero. Take p∈fp \in f and q∈gq \in g. For t∈(0,1]t \in (0, 1], the point p+t(q−p)p + t(q - p) has sign gig_i on every line: if fi=gi≠0f_i = g_i \ne 0, both ends have that sign; if fi=0f_i = 0, the value is tt times its value at qq. So the half-open segment lies in gg and p∈cl⁡(g)p \in \operatorname{cl}(g). Since ff is convex and every point of it is in cl⁡(g)\operatorname{cl}(g), f⊆cl⁡(g)f \subseteq \operatorname{cl}(g). □\square

Lemma 2 (local structure). Let pp be a point of the face ff. There is a disc UU around pp such that the faces that meet UU are exactly ff and the faces of its star, the faces gg with f⊆cl⁡(g)f \subseteq \operatorname{cl}(g).

Proof. Let UU be a disc around pp that meets no line through which pp does not pass. On UU every line with fi≠0f_i \ne 0 keeps the sign fif_i, so every face that meets UU agrees with ff where ff is nonzero, and it is ff or in its star by Lemma 1. Conversely, every face gg of the star has pp in its closure (by the segment of the proof of Lemma 1), so it meets UU. □\square

Theorem 1 (Nef polygons are the unions of faces). A set is a Nef polygon exactly when it is a union of faces of A(H)\mathcal{A}(H) for some finite HH.

Proof. A Nef polygon is built from open half-planes with lines in some finite set HH. An open half-plane over a line of HH is the union of the faces with sign +1+1 on that line. Unions of faces of a fixed arrangement are closed under complement (take the other faces) and intersection (take the common faces), because the faces partition the plane. So every Nef polygon over HH is a union of faces of A(H)\mathcal{A}(H). Conversely, a face with sign vector ss is the intersection, over ii, of the open half-plane {si(aix+biy+ci)>0}\{s_i (a_i x + b_i y + c_i) > 0\} if si≠0s_i \neq 0, and of the line ii if si=0s_i = 0. A line is the complement of the union of its two open half-planes. So a face is a Nef polygon, and so is a finite union of faces. □\square

Theorem 2 (closure under the topological operations). If SS is a union of faces of A(H)\mathcal{A}(H), then so are int⁡S\operatorname{int} S, cl⁡S\operatorname{cl} S, ∂S\partial S and cl⁡int⁡S\operatorname{cl}\operatorname{int} S. A face ff is in int⁡S\operatorname{int} S exactly when ff and its whole star are in SS, and in cl⁡S\operatorname{cl} S exactly when ff or some face of its star is in SS. So Nef polygons are closed under interior, closure, boundary and regularization.

Proof. Let p∈fp \in f and UU as in Lemma 2. If ff and its star are in SS, then U⊆SU \subseteq S, so p∈int⁡Sp \in \operatorname{int} S. If some face of the star or ff is not in SS, then every disc around pp, shrunk inside UU, meets that face (by Lemma 2 applied to smaller discs), so p∉int⁡Sp \notin \operatorname{int} S. The closure is the complement of the interior of the complement, which gives the second rule. Both rules depend only on ff, so the results are unions of faces. The boundary is cl⁡S∖int⁡S\operatorname{cl} S \setminus \operatorname{int} S, and regularization composes the two. Theorem 1 turns these unions back into Nef polygons. □\square

Lemma 3 (the arrangement in the code). The constructor of Arrangement lists every face of A(H)\mathcal{A}(H) once, and up[f] is exactly the star of ff.

Proof. If HH is empty there is one face, the plane, with an empty star. Otherwise, every vertex lies on two lines that are not parallel and is found as their crossing. On line ii, the vertices sorted by the parameter p⋅(−bi,ai)p \cdot (-b_i, a_i) cut the line into open segments and two rays, or leave it whole if there are none. A segment between consecutive vertices crosses no other line, so it is one edge, and its midpoint, a point beyond each end, or any point of a line without vertices, gives its sign vector. Each edge has exactly one zero, since distinct canonical lines meet in at most one point, which would be a vertex. Every cell has an edge on its boundary, since HH is not empty and the cell is not the plane. The cells beside an edge on line ii are the sign vectors of the edge with ±1\pm 1 at ii. Both are realized by points near the middle of the edge, so every cell is listed. For the star: by Lemma 1, the faces above an edge ee are the two cells beside it. The faces above a vertex vv are the edges whose closure contains vv, which are the edges with vv as an endpoint, and the cells whose closure contains vv. Such a cell is a convex region with vv on its boundary, so it is a wedge between two consecutive lines through vv near vv, and its boundary contains an edge that ends at vv. So it is a cell of one of those edges. □\square

Theorem 3 (the operations are exact). CONTAINS, COMBINE, INTERIOR, CLOSURE, BOUNDARY, the complement and simplify return the stated sets, and all of them terminate.

Proof. CONTAINS: pp lies in the face with sign vector σ(p)\sigma(p), which is marked exactly when that face is in the set. COMBINE: by canonical forms, HA∪HBH_A \cup H_B has no duplicates, and for a face ff of the merged arrangement, every point of ff has the sign vector fAf_A on the lines of AA, so ff lies inside the face fAf_A of A(HA)\mathcal{A}(H_A), and f⊆Af \subseteq A exactly when fAf_A is marked. The same holds for BB. So line L6 marks ff exactly when f⊆op⁡(A,B)f \subseteq \operatorname{op}(A, B), and since the faces partition the plane, the result is op⁡(A,B)\operatorname{op}(A, B). Complement: the faces partition the plane. Lines L8 to L10: Theorem 2 with Lemma 3. simplify: if the mark of every face depends only on its signs off line ii, then the set is the union of the faces of A(H∖{i})\mathcal{A}(H \setminus \{i\}) that are projections of marked faces, since each face of the coarse arrangement is the union of the fine faces that project to it. So dropping line ii keeps the set. Each round removes a line, so there are at most ∣H∣|H| rounds. Every loop runs over a finite list. □\square

Corollary (r-sets need regularization). The r-sets, the closed regular sets S=cl⁡int⁡SS = \operatorname{cl}\operatorname{int} S, are not closed under intersection or complement. The closed half-planes {x≥0}\{x \ge 0\} and {x≤0}\{x \le 0\} are r-sets, but their intersection is the line x=0x = 0, whose interior is empty, so cl⁡int⁡\operatorname{cl}\operatorname{int} of it is empty and not the line. The complement of a nonempty bounded r-set is open and not closed, so not an r-set. The regularized operations A∩∗B=cl⁡int⁡(A∩B)A \cap^* B = \operatorname{cl}\operatorname{int}(A \cap B) and ∁∗A=cl⁡(∁A)\complement^* A = \operatorname{cl}(\complement A) return r-sets, because cl⁡int⁡\operatorname{cl}\operatorname{int} is idempotent. On one side, int⁡X\operatorname{int} X is an open subset of cl⁡int⁡X\operatorname{cl}\operatorname{int} X, so int⁡X⊆int⁡cl⁡int⁡X\operatorname{int} X \subseteq \operatorname{int}\operatorname{cl}\operatorname{int} X, and taking closures gives cl⁡int⁡X⊆cl⁡int⁡cl⁡int⁡X\operatorname{cl}\operatorname{int} X \subseteq \operatorname{cl}\operatorname{int}\operatorname{cl}\operatorname{int} X. On the other, int⁡cl⁡int⁡X⊆cl⁡int⁡X\operatorname{int}\operatorname{cl}\operatorname{int} X \subseteq \operatorname{cl}\operatorname{int} X, and taking closures gives cl⁡int⁡cl⁡int⁡X⊆cl⁡int⁡X\operatorname{cl}\operatorname{int}\operatorname{cl}\operatorname{int} X \subseteq \operatorname{cl}\operatorname{int} X. Nef polygons need no regularization, since by Theorems 1 and 2 each plain operation already returns a Nef polygon.

Complexity

The following is proved for the plane code, where nn is the number of distinct lines:

  • An arrangement of nn lines has at most (n2)\binom{n}{2} vertices, n2n^2 edges and (n2)+n+1\binom{n}{2} + n + 1 cells, so O(n2)O(n^2) faces. Each sign vector has nn entries, so the representation takes O(n3)O(n^3) space, and building the arrangement takes O(n3)O(n^3) time, plus O(n2log⁡n)O(n^2 \log n) for sorting the vertices along the lines.
  • CONTAINS takes O(n)O(n) time. A Boolean operation on sets with nAn_A and nBn_B lines takes O((nA+nB)3)O((n_A + n_B)^3) time. Complement, interior, closure and boundary take time linear in the total size of the stars, which is O(n2)O(n^2), times O(n)O(n) for hashing a sign vector.
  • Simplification tries each line and rebuilds the arrangement after each drop, so it takes O(n4)O(n^4) time.

A plane map, a doubly connected edge list with a mark on each vertex, edge and face, stores the same thing in O(n2)O(n^2) space and overlays two maps in O((N+k)log⁡N)O((N + k) \log N) time for maps of total size NN with kk crossings. In three dimensions, the selective Nef complex of a polyhedron with NN vertices, edges and faces is built and combined in time that depends on the overlay of the local sphere maps and on the number of crossings. Hachenberger, Kettner and Mehlhorn measured the running times of their implementation on large models; this page states no worst-case bound for it.

Variants

  • Selective Nef complex (three dimensions). Hachenberger, Kettner and Mehlhorn store a cell complex of vertices, edges, facets and volumes, each with a mark. Each vertex has a sphere map: the intersection of the set with a small sphere around the vertex. It is a Nef polygon on the sphere, made of points (edges leaving the vertex), arcs (facets) and regions (volumes), each with a mark. Booleans overlay the sphere maps at every vertex of both inputs and at new vertices where edges cross faces, combine the marks, and then simplify by removing the parts that do not change the set. The local picture at a vertex is what Nef called the local pyramid.
  • Plane maps. In the plane the same idea is a plane map with marks, the two-dimensional structure on which the three-dimensional one is built.
  • Without the arrangement. A set can also be kept as a Boolean formula over half-spaces, a CSG tree without regularization. Membership is then easy, but equality, emptiness and the topological operations need the arrangement.
  • Selective geometric complexes. The SGC of Rossignac and O'Connor uses the same in-or-out marks on the cells of a complex, with curved cells and any dimension, but without the half-space generation of Nef sets.
  • Regularized subsets. A modeler that needs only solids can apply regularization after every operation and store the result as a B-rep, which is smaller. The Nef structure is then used only where the exactness or the lower-dimensional parts matter.

When to use it

Use Nef polyhedra when the Boolean operations must be exact and must handle every degenerate case: touching faces, coplanar faces, edges that meet in a point, sets that pinch to a line. This is the case in robust Minkowski sums, in configuration spaces, and in geometric software where a wrong answer is worse than a slow one. Use them also when the lower-dimensional parts are part of the model, such as cuts, sheets and wires in a non-manifold model, or when the topological operations are needed. For everyday solid modeling with curved surfaces and tolerances, a B-rep kernel with regularized operations is faster and smaller. The Nef structure is limited to linear geometry.

Pitfalls

  • The same line twice. If x≥0x \ge 0 and −x≤0-x \le 0 give two different line records, the arrangement has a duplicate line, and the faces are counted twice. Bring every line to a canonical form, as the code does, before merging line sets.
  • Floating-point coefficients. A sign vector is only meaningful if every sign is exact. With floating-point arithmetic, a point near a crossing gets inconsistent signs, and two faces that should be equal differ. Use rational or integer coefficients, or an exact predicate kernel such as the orientation test with exact arithmetic.
  • Forgetting the lower-dimensional faces. A Boolean operation that marks only cells computes the regularized result, not the Nef result. The edges and vertices must be marked too.
  • Growth of the arrangement. Every operation adds the lines of both inputs, and the arrangement grows quadratically in their number. Simplify after operations, or the size grows with the length of the modeling history and not with the complexity of the set.
  • Unbounded sets. Nef polyhedra include unbounded sets such as half-planes. A modeler that expects bounded solids must check boundedness, or intersect with a big box.

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.

nef_polyhedron.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nef-polyhedron/. The authors are listed in prov/Q616YB.jsonl.

"""Nef polygons: plane sets built from half-planes by Boolean operations.

A Nef polygon over a finite set of lines is a union of faces of the line
arrangement: vertices, open edges and open cells. A face is named by its
sign vector, the signs of a x + b y + c at its points for every line, and
the set is stored as the set of marked sign vectors. This is the selective
idea behind the plane maps of Seel and the selective Nef complexes of
Hachenberger and Kettner, without their geometric maps: the faces here are
found from the lines, and the incidences come with them.

Booleans overlay the two arrangements and combine the marks. Interior,
closure and boundary look at the star of each face: the faces whose closure
contains it. All arithmetic is exact with Fraction.

Precondition: lines have rational coefficients and (a, b) != (0, 0).
Cost: an arrangement of n lines has O(n^2) faces and is built in O(n^3)
time, since each sign vector has n entries. A Boolean operation builds the
arrangement of the union of the two line sets, so it takes O((n1 + n2)^3).
Interior, closure and boundary take time linear in the total size of the
stars, O(n^3) in all. Point membership takes O(n).
"""

from __future__ import annotations

from fractions import Fraction
from typing import Callable, Iterable, Sequence

Line = tuple[Fraction, Fraction, Fraction]
Point = tuple[Fraction, Fraction]
SV = tuple[int, ...]


def sign(v: Fraction) -> int:
    return (v > 0) - (v < 0)


def canonical(a, b, c) -> tuple[Line, int]:
    """Scale a x + b y + c so that its first nonzero coefficient of (a, b)
    is 1. Returns the line and the sign of the factor removed."""
    a, b, c = Fraction(a), Fraction(b), Fraction(c)
    k = a if a != 0 else b
    if k == 0:
        raise ValueError("not a line")
    return (a / k, b / k, c / k), sign(k)


def side(line: Line, p: Point) -> int:
    return sign(line[0] * p[0] + line[1] * p[1] + line[2])


class Arrangement:
    """The faces of the arrangement of distinct lines, by sign vector, with
    their dimension and the set of faces above each one (its star)."""

    def __init__(self, lines: Sequence[Line]):
        self.lines: list[Line] = list(lines)
        self.index = {l: i for i, l in enumerate(self.lines)}
        self.dim: dict[SV, int] = {}
        self.up: dict[SV, set[SV]] = {}
        n = len(self.lines)
        if n == 0:
            self.dim[()] = 2
            self.up[()] = set()
            return
        on_line: list[list[Point]] = [[] for _ in range(n)]
        for i in range(n):
            for j in range(i + 1, n):
                p = self._meet(self.lines[i], self.lines[j])
                if p is not None:
                    on_line[i].append(p)
                    on_line[j].append(p)
        for i, (a, b, c) in enumerate(self.lines):
            d = (-b, a)
            vs = sorted(set(on_line[i]), key=lambda p: p[0] * d[0] + p[1] * d[1])
            if vs:
                reps = [(vs[0][0] - d[0], vs[0][1] - d[1], None, vs[0])]
                reps += [((u[0] + w[0]) / 2, (u[1] + w[1]) / 2, u, w) for u, w in zip(vs, vs[1:])]
                reps.append((vs[-1][0] + d[0], vs[-1][1] + d[1], vs[-1], None))
            else:
                p0 = (Fraction(0), -c / b) if b != 0 else (-c / a, Fraction(0))
                reps = [(p0[0], p0[1], None, None)]
            for x, y, u, w in reps:
                e = self.sv((x, y))
                cells = [e[:i] + (s,) + e[i + 1:] for s in (1, -1)]
                self.dim[e] = 1
                self.up.setdefault(e, set()).update(cells)
                for f in cells:
                    self.dim[f] = 2
                    self.up.setdefault(f, set())
                for v in (u, w):
                    if v is not None:
                        vv = self.sv(v)
                        self.dim[vv] = 0
                        self.up.setdefault(vv, set()).update([e] + cells)

    @staticmethod
    def _meet(l1: Line, l2: Line) -> Point | None:
        det = l1[0] * l2[1] - l1[1] * l2[0]
        if det == 0:
            return None
        return ((l1[1] * l2[2] - l1[2] * l2[1]) / det, (l1[2] * l2[0] - l1[0] * l2[2]) / det)

    def sv(self, p: Point) -> SV:
        return tuple(side(l, p) for l in self.lines)

    def faces(self) -> list[SV]:
        return sorted(self.dim)


class NefPolygon:
    """A Nef polygon: an arrangement and the set of its marked faces."""

    def __init__(self, arr: Arrangement, marks: Iterable[SV]):
        self.arr = arr
        self.marks = frozenset(marks)

    # construction
    @staticmethod
    def halfplane(a, b, c, closed: bool) -> "NefPolygon":
        """{(x, y) : a x + b y + c > 0}, or >= 0 when closed."""
        line, s = canonical(a, b, c)
        arr = Arrangement([line])
        return NefPolygon(arr, [f for f in arr.faces() if s * f[0] > 0 or (closed and f[0] == 0)])

    @staticmethod
    def empty() -> "NefPolygon":
        return NefPolygon(Arrangement([]), [])

    @staticmethod
    def plane() -> "NefPolygon":
        return NefPolygon(Arrangement([]), [()])

    # queries
    def contains(self, p: Sequence) -> bool:
        return self.arr.sv((Fraction(p[0]), Fraction(p[1]))) in self.marks  # @line L1

    def is_empty(self) -> bool:
        return not self.marks

    # Boolean operations
    def _combine(self, other: "NefPolygon", op: Callable[[bool, bool], bool]) -> "NefPolygon":
        lines = list(dict.fromkeys(self.arr.lines + other.arr.lines))  # @line L2
        arr = Arrangement(lines)  # @line L3
        ia = [arr.index[l] for l in self.arr.lines]
        ib = [arr.index[l] for l in other.arr.lines]
        marks = []
        for f in arr.faces():  # @line L4
            fa = tuple(f[k] for k in ia)  # @line L5
            fb = tuple(f[k] for k in ib)
            if op(fa in self.marks, fb in other.marks):  # @line L6
                marks.append(f)
        return NefPolygon(arr, marks)  # @line L7

    def __or__(self, other):
        return self._combine(other, lambda x, y: x or y)

    def __and__(self, other):
        return self._combine(other, lambda x, y: x and y)

    def __sub__(self, other):
        return self._combine(other, lambda x, y: x and not y)

    def __xor__(self, other):
        return self._combine(other, lambda x, y: x != y)

    def complement(self) -> "NefPolygon":
        return NefPolygon(self.arr, [f for f in self.arr.faces() if f not in self.marks])

    # topological operations
    def interior(self) -> "NefPolygon":
        m = self.marks
        return NefPolygon(self.arr, [f for f in m if self.arr.up[f] <= m])  # @line L8

    def closure(self) -> "NefPolygon":
        m = self.marks
        return NefPolygon(self.arr, [f for f in self.arr.faces()
                                     if f in m or any(g in m for g in self.arr.up[f])])  # @line L9

    def boundary(self) -> "NefPolygon":
        return self.closure() - self.interior()  # @line L10

    def regularization(self) -> "NefPolygon":
        return self.interior().closure()

    def simplify(self) -> "NefPolygon":
        """Drop lines on which the set does not depend: line i goes when the
        mark of every face is a function of its signs on the other lines."""
        cur = self
        changed = True
        while changed:
            changed = False
            for i in range(len(cur.arr.lines)):
                seen: dict[SV, bool] = {}
                ok = True
                for f in cur.arr.faces():
                    g = f[:i] + f[i + 1:]
                    if seen.setdefault(g, f in cur.marks) != (f in cur.marks):
                        ok = False
                        break
                if ok:
                    arr = Arrangement(cur.arr.lines[:i] + cur.arr.lines[i + 1:])
                    cur = NefPolygon(arr, [g for g, mk in seen.items() if mk])
                    changed = True
                    break
        return cur

    def count_by_dimension(self) -> tuple[int, int, int]:
        c = [0, 0, 0]
        for f in self.marks:
            c[self.arr.dim[f]] += 1
        return (c[0], c[1], c[2])
test_nef_polyhedron.py 204 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nef-polyhedron/. The authors are listed in prov/Q616YB.jsonl.

import random
import unittest
from fractions import Fraction as Fr
from math import atan2, gcd

from nef_polyhedron import NefPolygon

# Directions for the neighbourhood oracle: every primitive vector with
# entries in [-3, 3], which contains the direction of every line with such
# coefficients, and the sum of each pair of neighbours in angular order,
# which lies strictly inside every wedge between two such lines.
S3 = sorted({(x, y) for x in range(-3, 4) for y in range(-3, 4) if (x, y) != (0, 0) and gcd(x, y) == 1},
            key=lambda d: atan2(d[1], d[0]))
DIRS = [(0, 0)] + S3 + [(S3[i][0] + S3[(i + 1) % len(S3)][0], S3[i][1] + S3[(i + 1) % len(S3)][1])
                        for i in range(len(S3))]
EPS0 = Fr(1, 1000)


def ev(node, p, eps=EPS0):
    """Evaluate a formula at p straight from its definition. A topological
    operator looks at p and at p + eps d for every d in DIRS; eps is small
    enough that these points see every face around p and no other."""
    k = node[0]
    if k == "h":
        _, a, b, c, closed = node
        v = a * p[0] + b * p[1] + c
        return v >= 0 if closed else v > 0
    if k == "not":
        return not ev(node[1], p, eps)
    if k in ("and", "or", "minus", "xor"):
        x, y = ev(node[1], p, eps), ev(node[2], p, eps)
        return {"and": x and y, "or": x or y, "minus": x and not y, "xor": x != y}[k]
    near = [ev(node[1], (p[0] + eps * d[0], p[1] + eps * d[1]), eps / 100) for d in DIRS]
    if k == "int":
        return all(near)
    if k == "cl":
        return any(near)
    if k == "bd":
        return any(near) and not all(near)
    raise ValueError(k)


def build(node):
    k = node[0]
    if k == "h":
        return NefPolygon.halfplane(*node[1:])
    if k == "not":
        return build(node[1]).complement()
    if k in ("and", "or", "minus", "xor"):
        a, b = build(node[1]), build(node[2])
        return {"and": a & b, "or": a | b, "minus": a - b, "xor": a ^ b}[k]
    a = build(node[1])
    return {"int": a.interior(), "cl": a.closure(), "bd": a.boundary()}[k]


def random_halfplane(rng):
    while True:
        a, b = rng.randint(-3, 3), rng.randint(-3, 3)
        if (a, b) != (0, 0):
            return ("h", a, b, rng.randint(-3, 3), rng.random() < 0.5)


def random_formula(rng, depth, topo):
    if depth == 0 or rng.random() < 0.25:
        return random_halfplane(rng)
    r = rng.random()
    if topo and r < 0.3:
        return (rng.choice(["int", "cl", "bd"]), random_formula(rng, depth - 1, False))
    if r < 0.4:
        return ("not", random_formula(rng, depth - 1, topo))
    return (rng.choice(["and", "or", "minus", "xor"]), random_formula(rng, depth - 1, topo),
            random_formula(rng, depth - 1, topo))


def halfplanes(node, out):
    if node[0] == "h":
        out.append(node)
    else:
        for c in node[1:]:
            halfplanes(c, out)
    return out


def sample_points(node):
    """Grid points with denominator 2 and every crossing of two lines."""
    pts = [(Fr(x, 2), Fr(y, 2)) for x in range(-6, 7) for y in range(-6, 7)]
    hs = halfplanes(node, [])
    for i in range(len(hs)):
        for j in range(i + 1, len(hs)):
            a1, b1, c1 = hs[i][1:4]
            a2, b2, c2 = hs[j][1:4]
            det = a1 * b2 - a2 * b1
            if det != 0:
                pts.append((Fr(b1 * c2 - c1 * b2, det), Fr(c1 * a2 - a1 * c2, det)))
    return pts


class TestHandCases(unittest.TestCase):
    def test_touching_halfplanes_meet_in_a_line(self):
        a = NefPolygon.halfplane(1, 0, 0, True)    # x >= 0
        b = NefPolygon.halfplane(-1, 0, 0, True)   # x <= 0
        s = a & b
        self.assertEqual(s.count_by_dimension(), (0, 1, 0))
        self.assertTrue(s.contains((0, 5)))
        self.assertTrue(s.regularization().is_empty())

    def test_square_with_a_dangling_edge_and_a_point(self):
        sq = (NefPolygon.halfplane(1, 0, 0, True) & NefPolygon.halfplane(-1, 0, 2, True)
              & NefPolygon.halfplane(0, 1, 0, True) & NefPolygon.halfplane(0, -1, 2, True))
        # the segment y = 1, 2 <= x <= 3
        seg = (NefPolygon.halfplane(0, 1, -1, True) & NefPolygon.halfplane(0, -1, 1, True)
               & NefPolygon.halfplane(1, 0, -2, True) & NefPolygon.halfplane(-1, 0, 3, True))
        # the point (4, 4)
        pt = (NefPolygon.halfplane(1, 0, -4, True) & NefPolygon.halfplane(-1, 0, 4, True)
              & NefPolygon.halfplane(0, 1, -4, True) & NefPolygon.halfplane(0, -1, 4, True))
        s = sq | seg | pt
        for q, want in [((1, 1), True), ((Fr(5, 2), 1), True), ((4, 4), True), ((3, 2), False)]:
            self.assertEqual(s.contains(q), want)
        r = s.regularization()
        self.assertFalse(r.contains((Fr(5, 2), 1)))
        self.assertFalse(r.contains((4, 4)))
        self.assertTrue(r.contains((2, 2)))
        self.assertTrue(s.boundary().contains((Fr(5, 2), 1)))
        # all 8 lines x = 0, 2, 3, 4 and y = 0, 1, 2, 4 carry some boundary
        self.assertEqual(len(s.simplify().arr.lines), 8)
        # the regularized set needs only the 4 lines of the square
        self.assertEqual(len(r.simplify().arr.lines), 4)

    def test_open_square_minus_its_diagonal(self):
        sq = (NefPolygon.halfplane(1, 0, 0, False) & NefPolygon.halfplane(-1, 0, 1, False)
              & NefPolygon.halfplane(0, 1, 0, False) & NefPolygon.halfplane(0, -1, 1, False))
        diag = NefPolygon.halfplane(1, -1, 0, True) & NefPolygon.halfplane(-1, 1, 0, True)
        s = sq - diag
        self.assertEqual(s.count_by_dimension(), (0, 0, 2))
        self.assertFalse(s.contains((Fr(1, 2), Fr(1, 2))))
        self.assertTrue(s.closure().contains((Fr(1, 2), Fr(1, 2))))
        self.assertTrue((s.regularization() ^ sq.closure()).is_empty())


class TestAgainstFormula(unittest.TestCase):
    def test_boolean_formulas(self):
        rng = random.Random(1)
        checked = 0
        for _ in range(80):
            f = random_formula(rng, 4, False)
            s = build(f)
            for p in sample_points(f):
                self.assertEqual(s.contains(p), ev(f, p), (f, p))
                checked += 1
        self.assertGreater(checked, 500)

    def test_topological_operators(self):
        rng = random.Random(2)
        checked = 0
        for _ in range(40):
            f = (rng.choice(["int", "cl", "bd"]), random_formula(rng, 3, False))
            s = build(f)
            pts = sample_points(f)
            for p in rng.sample(pts, min(25, len(pts))):
                self.assertEqual(s.contains(p), ev(f, p), (f, p))
                checked += 1
        self.assertGreater(checked, 500)

    def test_nested_formulas(self):
        rng = random.Random(3)
        for _ in range(25):
            f = random_formula(rng, 4, True)
            s = build(f)
            pts = sample_points(f)
            for p in rng.sample(pts, min(15, len(pts))):
                self.assertEqual(s.contains(p), ev(f, p), (f, p))


class TestIdentities(unittest.TestCase):
    def test_closure_identities(self):
        rng = random.Random(4)
        for _ in range(60):
            s = build(random_formula(rng, 4, False))
            c, i = s.closure(), s.interior()
            self.assertTrue((c.closure() ^ c).is_empty())
            self.assertTrue((i.interior() ^ i).is_empty())
            self.assertTrue((s.complement().closure() ^ i.complement()).is_empty())
            self.assertTrue((s.boundary() ^ (c & s.complement().closure())).is_empty())
            self.assertTrue((s - c).is_empty() and (i - s).is_empty())
            r = s.regularization()
            self.assertTrue((r.regularization() ^ r).is_empty())

    def test_simplify_keeps_the_set(self):
        rng = random.Random(5)
        for _ in range(60):
            f = random_formula(rng, 4, False)
            s = build(f)
            t = s.simplify()
            self.assertLessEqual(len(t.arr.lines), len(s.arr.lines))
            self.assertTrue((s ^ t).is_empty())
            for p in sample_points(f)[::7]:
                self.assertEqual(t.contains(p), ev(f, p))


if __name__ == "__main__":
    unittest.main()

History

Walter Nef defined the polyhedra generated by half-spaces in a 1978 book, as a basis for computer graphics, and showed their closure under the Boolean and topological operations. The theory was developed further by Hanspeter Bieri and Nef in the 1980s. Rossignac and Requicha argued in 1991 for non-regularized sets in solid modeling, and the selective geometric complex of Rossignac and O'Connor (1989) gave a general structure with in-or-out marks on cells. Michael Seel implemented planar Nef polyhedra in CGAL with plane maps. Peter Hachenberger, Lutz Kettner and Kurt Mehlhorn extended this to three dimensions with the selective Nef complex and published the data structure, the algorithms and experiments in 2007. CGAL's exact Boolean operations and Minkowski sums of polyhedra use it.

References

  1. Walter Nef, Beiträge zur Theorie der Polyeder, mit Anwendungen in der Computergraphik, Herbert Lang, Bern, 1978, the definition of polyhedra as the sets generated by finitely many open half-spaces under complement and intersection, and their closure under the topological operations
  2. Peter Hachenberger, Lutz Kettner and Kurt Mehlhorn, Boolean operations on 3D selective Nef complexes, data structure, algorithms, optimized implementation and experiments, Computational Geometry 38(1-2), 64 to 99, 2007, the selective Nef complex with sphere maps at the vertices, Boolean operations by overlay, selection and simplification, and the experiments with exact arithmetic
  3. Jarek R. Rossignac and Aristides A. G. Requicha, Constructive non-regularized geometry, Computer-Aided Design 23(1), 21 to 32, 1991, the case for non-regularized sets in solid modeling and Boolean operations that keep lower-dimensional parts

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)
WritingW4 complete
  • a review of the text: no review record reviews/Q616YB/text.yaml