Algorithm Search⌘K

Algorithmcore

Set membership classification

Also called point membership classification, Tilove classification.

Classifies a point, a curve or a surface against a CSG solid as in, on or out by classifying it at the leaves and combining the results up the tree.

Time
O(m + L^2) worst
Space
O(L) extra
Where
L = the number of primitives in the tree; m = the number of edges of all primitives
Properties
deterministicofflinerecursive
Origin
Robert B. Tilove, 1980

Set membership classification splits a candidate set SS, such as a point, a segment or a face, into the part inside a solid XX, the part on its boundary and the part outside. For a solid given by a CSG tree, it classifies SS against each primitive and then combines the results up the tree with the rules of the regularized set operations. Where SS lies on the boundary of two primitives, the three classes are not enough, and the algorithm combines neighborhoods instead. Tilove defined it in 1980, and it is the basic query of CSG modelers: boundary evaluation, ray casting and interference tests all reduce to it.

In plain words

A CSG solid is a recipe: take this box, add that cylinder, cut out this hole. To test a point, you ask each basic shape first. Then you go up the recipe: a point inside one of two added shapes is inside their sum, a point inside the cut is outside, and so on.

The hard case is a point on the skin of two shapes. Two boxes side by side share a wall. A point on that wall is on the skin of each box, but it is inside the joined solid. So "on the skin" is not enough information. The method keeps, for each such point, a small picture of which directions around it lead into the shape. To join two shapes it joins their pictures. The point is inside if every direction leads in, outside if none does, and on the skin otherwise.

The problem

Let X⊆E3X \subseteq E^3 be an r-set and SS a candidate set. The classification of SS against XX is the triple

Sin⁡X=S∩int⁡X,Son⁡X=S∩∂X,Sout⁡X=S∖X.S \operatorname{in} X = S \cap \operatorname{int} X, \qquad S \operatorname{on} X = S \cap \partial X, \qquad S \operatorname{out} X = S \setminus X.

The three parts are disjoint and their union is SS. Tilove regularizes each part in the topology of SS, so that a segment is split into segments and isolated points are dropped. For a single point pp the answer is one of IN, ON and OUT. This is point membership classification. In this page XX is given by a CSG tree whose leaves are primitives and whose inner nodes are ∪∗\cup^*, ∩∗\cap^* and −∗-^*.

The classes of SS against AA and BB almost determine the class against A∪∗BA \cup^* B: IN against either child gives IN, and OUT against both gives OUT. The rule fails when SS is ON against both. Two squares that share an edge have a union in which the shared edge is IN. Two squares that overlap have a union in which the common part of their boundaries is ON. Intersection and difference have the same gap. The fix is the neighborhood.

Neighborhood. In the plane, the neighborhood of pp in XX is the set of directions dd with p+εd∈int⁡Xp + \varepsilon d \in \operatorname{int} X for all small ε>0\varepsilon > 0. Near pp the boundary lines of the primitives through pp cut the disk into open sectors, so the neighborhood is a union of open sectors. It is stored as the list of breakpoint directions, sorted by angle, and one label per sector: in or out. For a point inside a polygon edge the neighborhood is a half-disk, and at a vertex it is a wedge. In space the neighborhood is a set of regions on a small sphere: a half-ball on a face, a wedge on an edge and a cone at a vertex.

The algorithm

  1. CLASSIFY(p, T) ▷ the neighborhood of p in the solid of T
  2. 1if T is a primitive then
  3. 2return LEAF-NEIGHBORHOOD(p, T)
  4. 3N1 ← CLASSIFY(p, T.left), N2 ← CLASSIFY(p, T.right)
  5. 4return COMBINE(N1, N2, T.op)
  6. COMBINE(N1, N2, op)
  7. 5D ← the breakpoints of N1 and N2, sorted by angle, one per direction
  8. 6for each sector σ between consecutive directions of D do
  9. 7d ← a direction strictly inside σ
  10. 8label(σ) ← op(d ∈ N1, d ∈ N2)
  11. 9remove each breakpoint with equal labels on both sides, return (D, labels)
  12. PMC(p, T) ▷ point membership classification
  13. 10N ← CLASSIFY(p, T)
  14. 11if every sector of N is in then return IN
  15. 12if no sector of N is in then return OUT
  16. 13return ON

LEAF-NEIGHBORHOOD for a convex polygon evaluates the sign of each edge line at pp with the orientation test. If one sign is negative, pp is outside and the neighborhood is empty. If all are positive, it is the full disk. Otherwise the edges with sign 00 pass through pp: their directions ±e\pm e are the breakpoints, and a sector is in when its sample direction is on the inner side of each such edge. A convex polygon has at most two edges through pp, so a leaf has at most four breakpoints.

Line L7 picks the sample for the sector from uu counterclockwise to vv. It is u+vu + v when the sector is less than a half turn, uu turned by a quarter turn when it is exactly a half turn, and −(u+v)-(u + v) when it is more. With rational breakpoints the sample is rational, so every test is exact.

Segments and faces. To classify a segment, split it at its crossings with the edge lines of all primitives. On each open piece, every primitive gives the same neighborhood at every point, so one point of the piece classifies it, and so does each split point. Tilove merges the sorted piece lists of the two children at each node instead, which gives the same parts. In space the same scheme splits a face along its intersection curves with the other faces.

Example

Let Q1=[0,2]×[0,2]Q_1 = [0, 2] \times [0, 2], Q2=[2,4]×[0,2]Q_2 = [2, 4] \times [0, 2] and the triangle RR with vertices (1,1)(1, 1), (3,1)(3, 1) and (2,3)(2, 3). The solid is X=(Q1∪∗Q2)−∗RX = (Q_1 \cup^* Q_2) -^* R. Classify p=(2,1)p = (2, 1). It lies on the shared edge of the squares and on the bottom edge of the triangle.

node breakpoints in sectors class of pp
Q1Q_1 up, down the left half ON
Q2Q_2 up, down the right half ON
Q1∪∗Q2Q_1 \cup^* Q_2 none the whole disk IN
RR right, left the upper half ON
XX right, left the lower half ON

At the union node, line L5 gives the two breakpoints up and down, line L8 labels both half-disks in, and line L9 removes both breakpoints. So the shared edge vanishes, and the union is IN at pp even though both children say ON. The difference keeps the lower half-disk, so pp is on the boundary of XX, where the bottom of the triangle cuts into the rectangle.

Other points: (2,1/2)(2, 1/2) is IN (the shared edge below the triangle is not boundary), (2,2)(2, 2) is OUT (it is inside RR), (1,1)(1, 1) is ON (a corner of the notch), and (2,3)(2, 3) is OUT.

Now classify the segment from (2,−1)(2, -1) to (2,3)(2, 3), which runs up the shared edge, with parameter t∈[0,1]t \in [0, 1]. It is OUT for t<1/4t < 1/4, ON at t=1/4t = 1/4 (the point (2,0)(2, 0)), IN for 1/4<t<1/21/4 < t < 1/2, ON at t=1/2t = 1/2 (the point (2,1)(2, 1)), and OUT for t>1/2t > 1/2, where it is inside the triangle or above the rectangle. A classifier with only three classes at the leaves would report the part from (2,0)(2, 0) to (2,1)(2, 1) as ON, because it is on the boundary of both squares.

Correctness

Fix pp and let Λ\Lambda be the finite set of edge lines of all primitives that pass through pp. For a small enough ε\varepsilon, the disk of radius ε\varepsilon around pp meets no other edge line, so each open sector of the disk cut by Λ\Lambda lies wholly inside or wholly outside each primitive. On such a sector the regularized result equals the plain set formula of the tree (fact 7 of regularized set operations). COMBINE evaluates that formula at one direction of each sector, so by induction on the tree CLASSIFY returns the exact neighborhood. A closed regular set is the closure of its interior, so pp is in its interior exactly when all sectors are in, and outside it exactly when none is. The full proof gives the details.

Proof: Point membership classification with neighborhoods is exactfull

Let TT be a CSG tree in the plane whose leaves are convex polygons P1,…,PLP_1, \ldots, P_L, each a closed regular set, and whose inner nodes are ∪∗\cup^*, ∩∗\cap^* and −∗-^*. Write XTX_T for the set of the tree. For a node TT let ΦT\Phi_T be the plain set formula of its subtree, with ∪\cup, ∩\cap and ∖\setminus in place of the regularized operations, and with each leaf PiP_i replaced by its interior. Fix a point pp.

Lemma 1 (local sectors). Let Λ\Lambda be the set of edge lines of the leaves that pass through pp, and DD the set of the 2∣Λ∣2|\Lambda| directions along them. There is ε>0\varepsilon > 0 such that, for each open sector σ\sigma between consecutive directions of DD (the whole punctured disk if DD is empty), the set Cσ={p+td:d∈σ,0<t<ε}C_\sigma = \{p + t d : d \in \sigma, 0 < t < \varepsilon\} lies in int⁡Pi\operatorname{int} P_i or in E2∖PiE^2 \setminus P_i, for each ii.

Proof. Each edge line not through pp has a positive distance from pp. Let ε\varepsilon be less than the least of these distances. Then no edge line other than those of Λ\Lambda meets the disk UU of radius ε\varepsilon around pp. The set CσC_\sigma is connected and meets no edge line, so each edge expression orient⁡(a,b,x)\operatorname{orient}(a, b, x) has a constant nonzero sign on CσC_\sigma. A point of the plane is in int⁡Pi\operatorname{int} P_i exactly when all edge expressions of PiP_i are positive, and outside PiP_i when one is negative. So CσC_\sigma is wholly in int⁡Pi\operatorname{int} P_i or wholly outside PiP_i. □\square

Call the true neighborhood of pp in a closed regular set YY the set of σ\sigma with Cσ⊆int⁡YC_\sigma \subseteq \operatorname{int} Y.

Lemma 2 (the formula on a sector). For each node TT and each sector σ\sigma, Cσ⊆int⁡XTC_\sigma \subseteq \operatorname{int} X_T if Cσ⊆ΦTC_\sigma \subseteq \Phi_T, and Cσ∩XT=∅C_\sigma \cap X_T = \emptyset otherwise.

Proof. Write C=CσC = C_\sigma; it is open. We show by induction on TT that XT∩CX_T \cap C is CC or empty, and that it is CC exactly when C⊆ΦTC \subseteq \Phi_T. By Lemma 1, ΦT∩C\Phi_T \cap C is CC or empty for every node. For a leaf, Lemma 1 gives C⊆int⁡Pi=ΦTC \subseteq \operatorname{int} P_i = \Phi_T or C∩Pi=∅C \cap P_i = \emptyset. For an inner node, XT=r(Y)X_T = r(Y) with Y=Xleft∘XrightY = X_{\text{left}} \circ X_{\text{right}} for the plain operation ∘\circ. By the induction hypothesis, Y∩CY \cap C is CC or empty, and it is CC exactly when the plain operation of the two truth values is true, that is, when C⊆ΦTC \subseteq \Phi_T. If Y∩C=CY \cap C = C, then C⊆int⁡Y⊆r(Y)C \subseteq \operatorname{int} Y \subseteq r(Y), because CC is open. If Y∩C=∅Y \cap C = \emptyset, then int⁡Y∩C=∅\operatorname{int} Y \cap C = \emptyset, and since CC is open, cl⁡(int⁡Y)∩C=∅\operatorname{cl}(\operatorname{int} Y) \cap C = \emptyset. In the first case C⊆XTC \subseteq X_T and CC is open, so C⊆int⁡XTC \subseteq \operatorname{int} X_T. □\square

Lemma 3 (leaves). LEAF-NEIGHBORHOOD(p,Pi)(p, P_i) returns a list of breakpoints and labels such that a direction dd in a sector σ\sigma of DD is labeled in exactly when Cσ⊆int⁡PiC_\sigma \subseteq \operatorname{int} P_i.

Proof. If an edge expression of PiP_i is negative at pp, it stays negative on UU, so every CσC_\sigma is outside PiP_i, and the empty neighborhood is right. If all are positive, every CσC_\sigma is inside, and the full disk is right. Otherwise let E0E_0 be the edges whose lines pass through pp. For x=p+tdx = p + t d, the expression of an edge (a,b)(a, b) with e=b−ae = b - a through pp equals t⋅cross⁡(e,d)t \cdot \operatorname{cross}(e, d), and the other expressions are positive on UU. So Cσ⊆int⁡PiC_\sigma \subseteq \operatorname{int} P_i exactly when cross⁡(e,d)>0\operatorname{cross}(e, d) > 0 for all e∈E0e \in E_0, at any d∈σd \in \sigma. The breakpoints ±e\pm e of the leaf are a subset of DD, so each sector of DD lies in one sector of the leaf, and the leaf labels its sectors with this test at a sample direction. □\square

Lemma 4 (sample directions). For breakpoints u≠vu \ne v consecutive in counterclockwise order, the direction ss of line L7 lies strictly inside the open sector from uu to vv.

Proof. If cross⁡(u,v)>0\operatorname{cross}(u, v) > 0, the sector is less than a half turn, and cross⁡(u,u+v)=cross⁡(u,v)>0\operatorname{cross}(u, u + v) = \operatorname{cross}(u, v) > 0 and cross⁡(u+v,v)=cross⁡(u,v)>0\operatorname{cross}(u + v, v) = \operatorname{cross}(u, v) > 0, so u+vu + v is inside. If cross⁡(u,v)=0\operatorname{cross}(u, v) = 0 and u,vu, v point opposite ways, the sector is the half-plane to the left of uu, and cross⁡(u,u⊥)=∣u∣2>0\operatorname{cross}(u, u^\perp) = |u|^2 > 0 for u⊥=(−uy,ux)u^\perp = (-u_y, u_x). If cross⁡(u,v)<0\operatorname{cross}(u, v) < 0, the sector is more than a half turn, and its complement, the sector from vv to uu, is less than a half turn and contains u+vu + v by the first case. So −(u+v)-(u + v), which is opposite to a direction strictly inside a sector of less than a half turn, is not in the closed complement, and it lies in the sector from uu to vv. If there is a single breakpoint uu, the sector is the full turn without uu, and −u-u is in it. □\square

Theorem. For every node TT, CLASSIFY(p,T)(p, T) returns breakpoints and labels such that each dd in a sector σ\sigma of DD is labeled in exactly when Cσ⊆int⁡XTC_\sigma \subseteq \operatorname{int} X_T. PMC(p,T)(p, T) returns IN when p∈int⁡XTp \in \operatorname{int} X_T, OUT when p∉XTp \notin X_T, and ON when p∈∂XTp \in \partial X_T.

Proof. By induction on the tree. For a leaf, lines L1 and L2 and Lemma 3 give the claim. For an inner node with operation ∘\circ, the induction hypothesis holds for both children. Line L5 takes the union of their breakpoints, which is a subset of DD, so each sector of DD lies in one sector τ\tau of the merged list. By Lemma 4 the sample of line L7 is in τ\tau, so by the hypothesis line L8 sets the label of τ\tau to [Cσ⊆int⁡Xleft]∘[Cσ⊆int⁡Xright][C_\sigma \subseteq \operatorname{int} X_{\text{left}}] \circ [C_\sigma \subseteq \operatorname{int} X_{\text{right}}] for each sector σ⊆τ\sigma \subseteq \tau of DD. By Lemma 2 applied to the children, Cσ⊆int⁡XleftC_\sigma \subseteq \operatorname{int} X_{\text{left}} exactly when Cσ⊆ΦleftC_\sigma \subseteq \Phi_{\text{left}}, and the same for the right child. So the label is the truth of Cσ⊆ΦTC_\sigma \subseteq \Phi_T, which by Lemma 2 is the truth of Cσ⊆int⁡XTC_\sigma \subseteq \operatorname{int} X_T. Line L9 removes only breakpoints with equal labels on both sides, which does not change the label of any direction.

For PMC, let NN be the neighborhood of the root. If all labels are in, then U∖Λ⊆XTU \setminus \Lambda \subseteq X_T. The set XTX_T is closed and U∖ΛU \setminus \Lambda is dense in UU, so U⊆XTU \subseteq X_T and p∈int⁡XTp \in \operatorname{int} X_T. If no label is in, then by Lemma 2 every CσC_\sigma misses XTX_T, so XT∩U⊆ΛX_T \cap U \subseteq \Lambda. A closed regular set is the closure of its interior, and an open set inside the finite union of lines Λ\Lambda is empty, so int⁡XT∩U=∅\operatorname{int} X_T \cap U = \emptyset and p∉cl⁡(int⁡XT)=XTp \notin \operatorname{cl}(\operatorname{int} X_T) = X_T. If some labels are in and some are out, then pp is a limit of points of int⁡XT\operatorname{int} X_T, so p∈XTp \in X_T, and also a limit of points outside XTX_T, so p∉int⁡XTp \notin \operatorname{int} X_T. So p∈∂XTp \in \partial X_T. ■\blacksquare

Termination. CLASSIFY calls itself once on each child, so it visits each node of the finite tree once. Each COMBINE loops once over a finite list of breakpoints.

Segments. For a segment from aa to bb, let t0=0<t1<⋯<tk=1t_0 = 0 < t_1 < \cdots < t_k = 1 be its parameters at the crossings with the edge lines of all leaves. On an open piece (tj,tj+1)(t_j, t_{j+1}) every edge expression has a constant sign or is zero all along, so the leaf neighborhoods of its points are the same, and by the theorem so is the class against XTX_T. So the class of one point of each piece and the classes of the split points give the exact classification of the segment.

Complexity

The costs are in the real RAM with exact predicates. Let the tree have LL primitives with mm edges in all.

  • Leaves. LEAF-NEIGHBORHOOD costs O(k)O(k) for a polygon of kk edges, so O(m)O(m) for all leaves.
  • Inner nodes. A node has at most as many breakpoints as its leaves together, so at most 4L4L. With a linear merge of the two sorted lists in line L5 and a joint scan in line L8, each of the L−1L - 1 inner nodes costs O(L)O(L). The total is O(m+L2)O(m + L^2) for a point.
  • Easy points. If pp lies on no edge line, every neighborhood is the full or the empty disk, and the cost is O(m)O(m).
  • Segments. A segment has O(m)O(m) split points. Merging the sorted piece lists up the tree costs O(Lm)O(L m) after the leaves, plus O(mlog⁡m)O(m \log m) to sort the crossings.

Real modelers prune the tree with a bounding box per subtree: a point outside the box of a subtree is OUT for that subtree with no further work.

Properties

  • Exact under exact predicates. All branches use the signs of 2×22 \times 2 determinants of rational data, so with exact arithmetic the class is right for every input, including points at vertices and on shared edges.
  • Regularized by construction. The class depends only on the interiors of the primitives near pp, so it is the class against the regularized result and never against a dangling edge.
  • General primitives. Any primitive with a neighborhood oracle works. Non-convex polygons, disks and, in space, half-spaces and quadrics fit the same scheme.

Variants and improvements

  • Point membership for a B-rep. For a solid given by its boundary, there is no tree. Cast a ray and count crossings (point in polygon in the plane), or use the generalized winding number for a surface with gaps.
  • Neighborhoods in space. Requicha and Voelcker (1985) describe the neighborhoods of points on faces, edges and vertices that the boundary evaluation of PADL-2 used. Vertex neighborhood classification uses the same idea on B-reps.
  • Rays. Classifying a ray is the one-dimensional case, where the neighborhoods are intervals. That is CSG ray casting.
  • Interference. Two solids interfere when A∩∗BA \cap^* B is not empty. A modeler tests this by classifying faces of one solid against the other, and it needs the neighborhoods for solids that only touch, where the regularized intersection is empty.

When to use it

Use it in a CSG modeler for every query that needs the solid itself: point tests, rendering by rays, boundary evaluation, interference and mass properties by sampling. Use the three-class rules alone when the inputs are in general position, and keep neighborhoods for the case where a candidate lies on two boundaries at once. For a solid stored only as a B-rep, use a ray or winding number test instead.

Pitfalls

  • Classes in place of neighborhoods. If line L2 returns only IN, ON or OUT, a node must guess the result of ON against ON. For two squares that share an edge it then reports the shared edge as ON, and boundary evaluation keeps a face inside the solid. Line L2 must return the sectors, and line L8 must combine sectors.
  • The sample of a wide sector. If line L7 always takes u+vu + v, then for a sector of more than a half turn the sample lies in the opposite sector, and the labels are swapped. Use −(u+v)-(u + v) there, and a quarter turn of uu for an exact half turn.
  • Duplicate directions. Line L5 must merge breakpoints that point the same way, such as (1,0)(1, 0) and (2,0)(2, 0). If both stay, the sector between them is empty, and line L7 returns a sample from the wrong side.
  • Rounded predicates. In floating point, a point computed as an intersection is a little off the edge line, so LEAF-NEIGHBORHOOD misses a tight edge and returns the full or the empty disk. The class is then IN or OUT where it should be ON. See the geometric robustness problem. Use exact or filtered predicates, as in exact geometric computation.

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.

set_membership_classification.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/set-membership-classification/. The authors are listed in prov/E1CR69.jsonl.

"""Tilove's set membership classification in the plane, with exact neighborhoods.

A solid is a CSG tree. A leaf is a convex polygon, given by its vertices in
counterclockwise order. An inner node is a tuple (op, left, right) with op in
"union", "intersection" and "difference"; the operations are the regularized
ones. Coordinates are int or Fraction, and every test is exact.

A neighborhood of a point p is a pair (dirs, labels). dirs is a list of
directions sorted by angle, and labels[i] tells whether the open sector from
dirs[i] counterclockwise to dirs[i + 1] lies inside the solid near p. With no
directions, labels has one entry for the whole disk around p.
"""

from fractions import Fraction
from functools import cmp_to_key
from typing import Sequence, Union

Num = Union[int, Fraction]
Vec = tuple[Num, Num]
Polygon = Sequence[Vec]
Tree = Union[Polygon, tuple]
Neighborhood = tuple[list[Vec], list[bool]]

IN, ON, OUT = "in", "on", "out"
OPS = {
    "union": lambda a, b: a or b,
    "intersection": lambda a, b: a and b,
    "difference": lambda a, b: a and not b,
}


def cross(u: Vec, v: Vec) -> Num:
    return u[0] * v[1] - u[1] * v[0]


def _upper(d: Vec) -> bool:
    return d[1] > 0 or (d[1] == 0 and d[0] > 0)


def _angle_cmp(u: Vec, v: Vec) -> int:
    hu, hv = _upper(u), _upper(v)
    if hu != hv:
        return -1 if hu else 1
    c = cross(u, v)
    return -1 if c > 0 else (1 if c < 0 else 0)


def _same_dir(u: Vec, v: Vec) -> bool:
    return cross(u, v) == 0 and u[0] * v[0] + u[1] * v[1] > 0


def sector_sample(u: Vec, v: Vec) -> Vec:
    """A direction strictly inside the open sector from u counterclockwise to v."""
    c = cross(u, v)
    if _same_dir(u, v):
        return (-u[0], -u[1])  # the sector is the full turn minus one ray
    if c > 0:
        return (u[0] + v[0], u[1] + v[1])
    if c == 0:
        return (-u[1], u[0])  # a half turn: rotate u by a quarter turn
    return (-(u[0] + v[0]), -(u[1] + v[1]))


def contains(nb: Neighborhood, d: Vec) -> bool:
    """Is the direction d, which is not a breakpoint, in an inside sector?"""
    dirs, labels = nb
    if not dirs:
        return labels[0]
    k = len(dirs)
    if k == 1:
        return labels[0]
    for i in range(k):
        u, v = dirs[i], dirs[(i + 1) % k]
        cu, cv, cuv = cross(u, d), cross(d, v), cross(u, v)
        inside = (cu > 0 and cv > 0) if cuv > 0 else (cu > 0 or cv > 0) if cuv < 0 else cu > 0
        if inside:
            return labels[i]
    raise ValueError("direction is a breakpoint")


def _simplify(dirs: list[Vec], labels: list[bool]) -> Neighborhood:
    """Remove the breakpoints that have the same label on both sides."""
    if len(set(labels)) <= 1:
        return [], [labels[0] if labels else False]
    k = len(dirs)
    keep = [i for i in range(k) if labels[i - 1] != labels[i]]
    return [dirs[i] for i in keep], [labels[i] for i in keep]


def leaf_neighborhood(p: Vec, poly: Polygon) -> Neighborhood:
    """The neighborhood of p in a convex polygon given counterclockwise."""
    k = len(poly)
    tight: list[Vec] = []
    for i in range(k):
        a, b = poly[i], poly[(i + 1) % k]
        e = (b[0] - a[0], b[1] - a[1])
        s = cross(e, (p[0] - a[0], p[1] - a[1]))
        if s < 0:
            return [], [False]  # strictly outside one edge line
        if s == 0:
            tight.append(e)
    if not tight:
        return [], [True]  # strictly inside
    dirs: list[Vec] = []
    for e in tight:
        for d in (e, (-e[0], -e[1])):
            if not any(_same_dir(d, x) for x in dirs):
                dirs.append(d)
    dirs.sort(key=cmp_to_key(_angle_cmp))
    labels = []
    for i in range(len(dirs)):
        w = sector_sample(dirs[i], dirs[(i + 1) % len(dirs)])
        labels.append(all(cross(e, w) > 0 for e in tight))
    return _simplify(dirs, labels)


def combine(n1: Neighborhood, n2: Neighborhood, op: str) -> Neighborhood:
    """The neighborhood in (A op B) from the neighborhoods in A and B."""
    f = OPS[op]
    dirs: list[Vec] = []
    for d in n1[0] + n2[0]:  # @line L5
        if not any(_same_dir(d, x) for x in dirs):
            dirs.append(d)
    dirs.sort(key=cmp_to_key(_angle_cmp))
    if not dirs:
        return [], [f(n1[1][0], n2[1][0])]
    labels = []
    for i in range(len(dirs)):  # @line L6
        w = sector_sample(dirs[i], dirs[(i + 1) % len(dirs)])  # @line L7
        labels.append(f(contains(n1, w), contains(n2, w)))  # @line L8
    return _simplify(dirs, labels)  # @line L9


def classify_neighborhood(p: Vec, tree: Tree) -> Neighborhood:
    """The neighborhood of p in the solid of the tree. Cost: O(size of the tree times the breakpoints)."""
    if not (isinstance(tree, tuple) and tree and isinstance(tree[0], str)):  # @line L1
        return leaf_neighborhood(p, tree)  # @line L2
    op, left, right = tree
    nl, nr = classify_neighborhood(p, left), classify_neighborhood(p, right)  # @line L3
    return combine(nl, nr, op)  # @line L4


def classify_point(p: Vec, tree: Tree) -> str:
    """Point membership classification: IN, ON or OUT of the regularized solid."""
    dirs, labels = classify_neighborhood(p, tree)  # @line L10
    if all(labels):  # @line L11
        return IN
    if not any(labels):  # @line L12
        return OUT
    return ON  # @line L13


def _leaves(tree: Tree) -> list[Polygon]:
    if isinstance(tree, tuple) and tree and isinstance(tree[0], str):
        return _leaves(tree[1]) + _leaves(tree[2])
    return [tree]


Pieces = list[tuple[Fraction, Fraction, str]]


def classify_segment(a: Vec, b: Vec, tree: Tree) -> Pieces:
    """Classify the segment from a to b (a != b) against the solid.

    The segment is split at the crossings with the edge lines of all leaves.
    On each open piece every leaf neighborhood is constant, so one point of the
    piece gives its class. Returns pieces (t0, t1, class) in the parameter t of
    a + t (b - a), in order: a piece with t0 == t1 is a single point, the
    others are open intervals. Points with the same class as both neighbors
    are merged away. Cost: O(m) point classifications for m edges in all.
    """
    ts = {Fraction(0), Fraction(1)}
    d = (b[0] - a[0], b[1] - a[1])
    for poly in _leaves(tree):  # the breakpoints of each leaf: crossings with its edge lines
        k = len(poly)
        for i in range(k):
            u, v = poly[i], poly[(i + 1) % k]
            e = (v[0] - u[0], v[1] - u[1])
            den = cross(e, d)
            if den != 0:
                t = Fraction(cross(e, (u[0] - a[0], u[1] - a[1])), den)
                if 0 < t < 1:
                    ts.add(t)
    ts_sorted = sorted(ts)
    point_at = lambda t: (a[0] + t * d[0], a[1] + t * d[1])
    points = [(t, t, classify_point(point_at(t), tree)) for t in ts_sorted]
    opens = [(t0, t1, classify_point(point_at((t0 + t1) / 2), tree))
             for t0, t1 in zip(ts_sorted, ts_sorted[1:])]
    out: Pieces = [points[0]]
    cur = opens[0]
    for pt, nxt in zip(points[1:-1], opens[1:]):
        if cur[2] == pt[2] == nxt[2]:
            cur = (cur[0], nxt[1], cur[2])  # drop the point and join the two intervals
        else:
            out.extend([cur, pt])
            cur = nxt
    out.extend([cur, points[-1]])
    return out


def segment_class_at(pieces: Pieces, t: Fraction) -> str:
    """The class of the point with parameter t, read from the output of classify_segment."""
    for t0, t1, c in pieces:
        if t0 == t1 == t or t0 < t < t1:
            return c
    raise ValueError("t is outside [0, 1]")
test_set_membership_classification.py 179 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/set-membership-classification/. The authors are listed in prov/E1CR69.jsonl.

import random
import unittest
from fractions import Fraction
from math import gcd

from set_membership_classification import (
    IN, ON, OUT, classify_neighborhood, classify_point, classify_segment, cross, segment_class_at,
)

DIRS = [(x, y) for x in range(-8, 9) for y in range(-8, 9) if gcd(x, y) == 1]


def is_tree_node(t):
    return isinstance(t, tuple) and t and isinstance(t[0], str)


def strictly_inside(p, poly):
    k = len(poly)
    return all(cross((poly[(i + 1) % k][0] - poly[i][0], poly[(i + 1) % k][1] - poly[i][1]),
                     (p[0] - poly[i][0], p[1] - poly[i][1])) > 0 for i in range(k))


def formula(p, tree):
    """The plain set formula, valid at a point that lies on no leaf boundary."""
    if not is_tree_node(tree):
        return strictly_inside(p, tree)
    op, l, r = tree
    a, b = formula(p, l), formula(p, r)
    return {"union": a or b, "intersection": a and b, "difference": a and not b}[op]


def edge_dirs_through(p, tree):
    if is_tree_node(tree):
        return edge_dirs_through(p, tree[1]) + edge_dirs_through(p, tree[2])
    out = []
    k = len(tree)
    for i in range(k):
        a, b = tree[i], tree[(i + 1) % k]
        e = (b[0] - a[0], b[1] - a[1])
        if cross(e, (p[0] - a[0], p[1] - a[1])) == 0:
            out.append(e)
    return out


def scale(tree, s):
    if is_tree_node(tree):
        return (tree[0], scale(tree[1], s), scale(tree[2], s))
    return [(int(x * s), int(y * s)) for x, y in tree]


def brute_classify(p, tree):
    """Sample points at distance about 1/10^6 in many directions and evaluate the plain formula.

    All edge vectors have coordinates of at most 8 in absolute value, so every
    open sector between two edge lines through p contains one of DIRS. The work
    is done in integers, scaled by s.
    """
    lines = edge_dirs_through(p, tree)
    if not lines:
        return IN if formula(p, tree) else OUT
    s = Fraction(p[0]).denominator * Fraction(p[1]).denominator * 10 ** 6
    big = scale(tree, s)
    q = (int(p[0] * s), int(p[1] * s))
    seen = set()
    for w in DIRS:
        if any(cross(e, w) == 0 for e in lines):
            continue
        seen.add(formula((q[0] + w[0], q[1] + w[1]), big))
        if len(seen) == 2:
            return ON
    return IN if seen == {True} else OUT


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


def random_convex(rng):
    while True:
        if rng.random() < 0.4:
            x0, y0 = rng.randint(0, 3), rng.randint(0, 3)
            x1, y1 = x0 + rng.randint(1, 2), y0 + rng.randint(1, 2)
            return [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
        h = hull([(rng.randint(0, 4), rng.randint(0, 4)) for _ in range(rng.randint(3, 6))])
        if len(h) >= 3:
            return h


def random_tree(rng, depth):
    if depth == 0 or rng.random() < 0.3:
        return random_convex(rng)
    op = rng.choice(["union", "union", "intersection", "difference"])
    return (op, random_tree(rng, depth - 1), random_tree(rng, depth - 1))


def half_point(rng):
    return (Fraction(rng.randint(0, 9), 2), Fraction(rng.randint(0, 9), 2))


SQ1 = [(0, 0), (2, 0), (2, 2), (0, 2)]
SQ2 = [(2, 0), (4, 0), (4, 2), (2, 2)]
TRI = [(1, 1), (3, 1), (2, 3)]


class TestSetMembership(unittest.TestCase):
    def test_worked_example(self):
        tree = ("difference", ("union", SQ1, SQ2), TRI)
        self.assertEqual(classify_point((2, 1), ("union", SQ1, SQ2)), IN)
        self.assertEqual(classify_point((2, 0), ("union", SQ1, SQ2)), ON)
        self.assertEqual(classify_point((2, 1), ("intersection", SQ1, SQ2)), OUT)
        self.assertEqual(classify_point((2, 1), tree), ON)
        self.assertEqual(classify_point((2, 2), tree), OUT)
        self.assertEqual(classify_point((2, Fraction(1, 2)), tree), IN)
        self.assertEqual(classify_point((Fraction(1, 2), Fraction(1, 2)), tree), IN)
        self.assertEqual(classify_point((2, 3), tree), OUT)
        nb = classify_neighborhood((2, 1), tree)
        self.assertEqual(nb, ([(2, 0), (-2, 0)], [False, True]))

    def test_touching_squares(self):
        self.assertEqual(classify_point((2, 1), ("intersection", SQ1, SQ2)), OUT)
        self.assertEqual(classify_point((2, 1), ("difference", SQ1, SQ2)), ON)
        self.assertEqual(classify_point((1, 1), ("difference", SQ1, SQ1)), OUT)

    def test_segment_example(self):
        tree = ("difference", ("union", SQ1, SQ2), TRI)
        pieces = classify_segment((0, 1), (4, 1), tree)
        q, h = Fraction(1, 4), Fraction(3, 4)
        self.assertEqual(pieces, [(0, 0, ON), (0, q, IN), (q, q, ON), (q, h, ON), (h, h, ON),
                                  (h, 1, IN), (1, 1, ON)])

    def test_random_points(self):
        rng = random.Random(1980)
        count = 0
        for _ in range(300):
            tree = random_tree(rng, 3)
            for _ in range(4):
                p = half_point(rng)
                self.assertEqual(classify_point(p, tree), brute_classify(p, tree), (p, tree))
                count += 1
        self.assertGreaterEqual(count, 1000)

    def test_random_segments(self):
        rng = random.Random(874)
        for _ in range(120):
            tree = random_tree(rng, 2)
            a, b = half_point(rng), half_point(rng)
            if a == b:
                continue
            pieces = classify_segment(a, b, tree)
            for k in range(17):
                t = Fraction(k, 16)
                p = (a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1]))
                self.assertEqual(segment_class_at(pieces, t), brute_classify(p, tree))
            for t0, t1, c in pieces:
                if t0 < t1:
                    m = (t0 + t1) / 2
                    p = (a[0] + m * (b[0] - a[0]), a[1] + m * (b[1] - a[1]))
                    self.assertEqual(c, brute_classify(p, tree))


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

History

Tilove gave the definition and the combine rules in 1980, as part of the work on the PADL modelers in the Production Automation Project at the University of Rochester. Requicha surveyed the CSG representation and its algorithms in the same year. Requicha and Voelcker (1985) described how classification with neighborhoods drives boundary evaluation and the merging of boundaries.

References

  1. Robert B. Tilove, Set membership classification, a unified approach to geometric intersection problems, IEEE Transactions on Computers C-29(10), 874 to 883, 1980, the whole paper (the definition of the classification, the combine rules for the regularized operations, and the neighborhoods for the on parts)
  2. Aristides A. G. Requicha and Herbert B. Voelcker, Boolean operations in solid modeling, boundary evaluation and merging algorithms, Proceedings of the IEEE 73(1), 30 to 44, 1985, the sections on set membership classification and on neighborhoods
  3. Aristides A. G. Requicha, Representations for rigid solids, theory, methods, and systems, ACM Computing Surveys 12(4), 437 to 464, 1980, the sections on CSG and on the algorithms that use it

Where this leads

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