Algorithm Search⌘K

Data structureintro

Spatial occupancy enumeration

Also called voxel representation, exhaustive enumeration of solids.

Represents a solid by the set of cells of a regular 3D grid that it fills. Booleans on cells are exact, but the shape is only approximated and the memory grows as n³.

Time
O(m) area · booleanO(1) classifyO(m D) to_octree
Space
Θ(n^3) bit_arrayΘ(m) cell_set
Where
D = the depth of the octree, log₂ n; m = the number of filled cells; n = the number of cells along each side of the grid

Spatial occupancy enumeration stores a solid as a list of cells. Cut space into a regular grid of equal cubes, the voxels, and keep the cubes that the solid fills. The stored solid is the union of these closed cubes. This union is always a valid solid, an r-set, and the Boolean operations become set operations on the lists of cells: a cell is in the union, intersection or difference exactly when the operation says so for the two lists. This is the regularized operation, with no extra step. Point tests, volume and surface area are as simple. The price is that most solids are not unions of grid cubes, so the cells only approximate them, and the memory grows with the cube of the resolution. Requicha named the scheme in his survey of 1980, and Meagher's octree encoding of 1982 made it smaller.

In plain words

Build the shape from small equal cubes, like a toy made of building blocks of one size on a fixed grid. To store it, list the grid places that hold a block.

To join two shapes, keep each place that holds a block in either list. To find their common part, keep only the places in both lists. To cut one shape out of another, remove from the first list each place that the second list also has. These rules never make a thin skin or a loose line, because every result is again a set of whole blocks.

The problem is the grid. A sphere or a sloped face becomes a staircase. To make the steps smaller, you need more blocks, and halving the size of the block makes eight times as many. A tree that groups large empty and full regions, the octree, saves much of this memory.

The abstract type

Fix the grid of unit cubes c(i,j,k)=[i,i+1]×[j,j+1]×[k,k+1]c(i, j, k) = [i, i + 1] \times [j, j + 1] \times [k, k + 1] for integers i,j,ki, j, k; another grid step hh is a scaling of this one. A voxel set VV is a finite set of integer triples, and it stands for the solid [V]=⋃c∈Vc(c)[V] = \bigcup_{c \in V} c(c).

  • SAMPLE(S,box)\mathrm{SAMPLE}(S, box): the set of cells of boxbox whose centres lie in the solid SS. This is one common way to make VV from a CAD model, a scan or a medical image.
  • UNION(V,W)\mathrm{UNION}(V, W), INTERSECTION(V,W)\mathrm{INTERSECTION}(V, W) and DIFFERENCE(V,W)\mathrm{DIFFERENCE}(V, W): the voxel sets of [V]∪∗[W][V] \cup^* [W], [V]∩∗[W][V] \cap^* [W] and [V]−∗[W][V] -^* [W].
  • CLASSIFY(V,p)\mathrm{CLASSIFY}(V, p): IN, ON or OUT, as pp is in the interior of [V][V], on its boundary or outside it.
  • VOLUME(V)\mathrm{VOLUME}(V) and AREA(V)\mathrm{AREA}(V): the volume and the boundary area of [V][V].
  • OCTREE(V)\mathrm{OCTREE}(V) and its inverse: the octree of VV inside a cube of side 2D2^D, and back.

Representation

Three forms are common, and they store the same set.

form storage membership test good for
bit array n3n^3 bits for the box of n×n×nn \times n \times n cells one index computation dense data in a fixed box, as from a scanner
set of cells one integer triple per filled cell, in a hash table one hash look up, expected O(1)O(1) sparse sets and unbounded space
octree one node per block of the tree, each leaf EMPTY or FULL a walk of O(D)O(D) steps solids with large uniform regions

The code of this page uses the set of cells, so all costs on it are expected costs under hashing. The point pp and the corners of the cells are exact rationals and integers, so every test is exact.

Operations

  1. CLASSIFY(V, p) ▷ IN, ON or OUT for the closed union [V]
  2. 1for j ← 1 to 3: R_j ← {⌊p_j⌋ − 1, ⌊p_j⌋} if p_j is an integer, else {⌊p_j⌋}
  3. 2k ← the number of cells c ∈ R₁ × R₂ × R₃ with c ∈ V
  4. 3if k = 0 then return OUT
  5. 4if k = |R₁ × R₂ × R₃| then return IN
  6. 5return ON
  7. BOOLEAN(V, W, op) ▷ op is or, and, or and-not
  8. 6return {c ∈ V ∪ W : op(c ∈ V, c ∈ W)}
  9. OCTREE(C, corner, s) ▷ C: the cells of V in the cube of side s at corner
  10. 7if C = ∅ then return EMPTY
  11. 8if |C| = s³ then return FULL
  12. 9split C among the 8 cubes of side s/2 and return a node with their 8 OCTREE results

Line L1 finds the cells that contain pp. On an axis where pjp_j is not an integer, only the cell ⌊pj⌋\lfloor p_j \rfloor covers it; where pjp_j is an integer, pp lies on a grid plane and both neighbour cells touch it. So pp is in 1, 2, 4 or 8 closed cells, as it is inside a cell, on a face, on an edge or at a corner. If none of them is in VV, the point is outside; if all of them are, a small ball around pp is filled and pp is inside; otherwise it is on the boundary.

Line L6 is the whole Boolean operation. UNION takes or, INTERSECTION takes and, and DIFFERENCE takes "in VV and not in WW".

The volume of [V][V] is the number of cells. The area is the number of pairs of a cell in VV and one of its six face neighbours not in VV: each such pair is one unit square of the boundary.

To combine two octrees of the same cube, walk them together. Where both nodes are leaves, apply op to their two values. Where one is a leaf, treat it as eight equal children. If all eight results are EMPTY, or all are FULL, return one leaf. This walk visits each node of each input tree at most once.

Example

Take two boxes, one cell thick in zz. AA fills the cells with 0≤i≤20 \le i \le 2 and 0≤j≤10 \le j \le 1, so [A]=[0,3]×[0,2]×[0,1][A] = [0, 3] \times [0, 2] \times [0, 1], and BB fills those with 2≤i≤32 \le i \le 3 and 0≤j≤10 \le j \le 1, so [B]=[2,4]×[0,2]×[0,1][B] = [2, 4] \times [0, 2] \times [0, 1]. They overlap in the column i=2i = 2.

result cells volume area
AA 6 6 22
BB 4 4 16
A∪∗BA \cup^* B 8 8 28
A∩∗BA \cap^* B the 2 cells with i=2i = 2 2 10
A−∗BA -^* B the 4 cells with i≤1i \le 1 4 16

The check vol(A∪∗B)+vol(A∩∗B)=8+2=6+4\mathrm{vol}(A \cup^* B) + \mathrm{vol}(A \cap^* B) = 8 + 2 = 6 + 4 holds. Now classify some points against A−∗B=[0,2]×[0,2]×[0,1]A -^* B = [0, 2] \times [0, 2] \times [0, 1].

point pp cells around pp (L1) cells in A−∗BA -^* B class
(1,1,12)(1, 1, \tfrac12) 4 cells with i,j∈{0,1}i, j \in \{0, 1\} 4 IN
(2,1,12)(2, 1, \tfrac12) 4 cells with i∈{1,2}i \in \{1, 2\}, j∈{0,1}j \in \{0, 1\} 2 ON
(52,1,12)(\tfrac52, 1, \tfrac12) 2 cells with i=2i = 2 0 OUT
(0,0,0)(0, 0, 0) 8 cells around the corner 1 ON

The point (2,1,12)(2, 1, \tfrac12) is the reason for regularization. It lies in the closed box [B][B], so the ordinary difference [A]∖[B][A] \setminus [B] does not contain it, and that set has no face at x=2x = 2. It is not closed. The cell rule keeps the face, and CLASSIFY reports ON.

The octree of A∪∗BA \cup^* B in the cube [0,4)3[0, 4)^3 has depth 2. The root has 8 children of side 2. The two children at z∈[0,2)z \in [0, 2) and y∈[0,2)y \in [0, 2) hold 4 of their 8 cells each, so they are split into 8 unit leaves, 4 FULL and 4 EMPTY. The other 6 children are EMPTY leaves. So the tree has 1+8+16=251 + 8 + 16 = 25 nodes for 8 cells: for a solid this thin, the tree is larger than the list.

Correctness

The proof page shows four facts. First, for any finite VV the set [V][V] is closed and regular, so it is an r-set. Second, the set operations on cells give exactly the regularized operations: off the grid planes a point is in one open cell, and the regularized result is the closure of its interior, which these points decide. Third, CLASSIFY is exact, because the cells found in L1 cover a ball around pp and the open part of each one comes as close to pp as we like. Fourth, the area count is the area of the boundary, because a point inside a grid square is on the boundary exactly when one of the two cells beside it is in VV.

The proof page also proves the error of SAMPLE: a cell that does not meet the boundary of SS is kept exactly when it lies in SS. So SS and [SAMPLE(S)][\mathrm{SAMPLE}(S)] differ only inside cells that the boundary of SS crosses, and with grid step hh every point of the difference is within 3 h\sqrt3\,h of the boundary of SS.

The tests compare the operations with a brute force built only on ordinary point membership in the operands, by a scan over their cells. For random voxel sets, every point of the half-integer grid is classified both by CLASSIFY on the result and by the operation applied to the operands at the eight points p+s/4p + s/4, s∈{−1,+1}3s \in \{-1, +1\}^3, which lie inside cells. Points with denominator 7 are on no grid plane, and there CLASSIFY must agree with the ordinary formula. The tests also check the area against a count of ON square centres, the volume identity above, the sampling error on a ball, and the octree round trip and octree Booleans against the cell sets.

Proof: Set operations on grid cells are the regularized set operations, and CLASSIFY, AREA and OCTREE are exactfull

We use the pseudocode of the page. For an integer triple cc write cˉ=∏j[cj,cj+1]\bar c = \prod_j [c_j, c_j + 1] for the closed cell and c˚=∏j(cj,cj+1)\mathring c = \prod_j (c_j, c_j + 1) for the open cell. For a finite set VV of triples, [V]=⋃c∈Vcˉ[V] = \bigcup_{c \in V} \bar c. Let GG be the union of the grid planes xj=tx_j = t with tt an integer. Two facts about cells are used throughout. (a) A point not in GG lies in exactly one open cell and in no other closed cell. (b) An open cell c˚\mathring c meets the closed cell dˉ\bar d only if d=cd = c, and every point of cˉ\bar c is a limit of points of c˚\mathring c.

Lemma 1 ([V][V] is an r-set). For finite VV, [V][V] is bounded, closed and regular, [V]=cl⁡(int⁡[V])[V] = \operatorname{cl}(\operatorname{int}[V]), and semianalytic.

Proof. A finite union of closed bounded boxes is closed and bounded, and it is a finite Boolean combination of the halfspaces xj≥tx_j \ge t, so it is semianalytic. Each box is regular, cˉ=cl⁡c˚\bar c = \operatorname{cl} \mathring c, so [V]=⋃ccl⁡c˚=cl⁡⋃cc˚⊆cl⁡(int⁡[V])⊆[V][V] = \bigcup_c \operatorname{cl} \mathring c = \operatorname{cl} \bigcup_c \mathring c \subseteq \operatorname{cl}(\operatorname{int}[V]) \subseteq [V], where the last step uses that [V][V] is closed. □\square

Lemma 2 (BOOLEAN). For op one of or, and, and-not, let ⊗\otimes be the matching set operation and ⊗∗\otimes^* its regularized form, X⊗∗Y=cl⁡(int⁡(X⊗Y))X \otimes^* Y = \operatorname{cl}(\operatorname{int}(X \otimes Y)). Then line L6 returns U={c:op(c∈V,c∈W)}U = \{c : \mathrm{op}(c \in V, c \in W)\} and [U]=[V]⊗∗[W][U] = [V] \otimes^* [W].

Proof. Line L6 tests every cell of V∪WV \cup W; a cell in neither set fails op for all three choices, so the result is UU. Let X=[V]⊗[W]X = [V] \otimes [W]. For a point x∉Gx \notin G in the open cell c˚\mathring c, fact (a) gives x∈[V]x \in [V] exactly when c∈Vc \in V, and the same for WW, so x∈Xx \in X exactly when c∈Uc \in U. So X∖G=⋃c∈Uc˚X \setminus G = \bigcup_{c \in U} \mathring c. This set is open, so it lies in int⁡X\operatorname{int} X, and its closure [U][U] lies in cl⁡(int⁡X)\operatorname{cl}(\operatorname{int} X). Conversely, int⁡X\operatorname{int} X is open and GG is closed with empty interior, so int⁡X∖G\operatorname{int} X \setminus G is dense in int⁡X\operatorname{int} X. It lies in X∖G⊆[U]X \setminus G \subseteq [U], which is closed, so cl⁡(int⁡X)⊆[U]\operatorname{cl}(\operatorname{int} X) \subseteq [U]. □\square

Lemma 3 (CLASSIFY). Line L1 makes R=R1×R2×R3R = R_1 \times R_2 \times R_3 the set of cells cc with p∈cˉp \in \bar c, and CLASSIFY returns IN if p∈int⁡[V]p \in \operatorname{int}[V], ON if p∈∂[V]p \in \partial [V] and OUT if p∉[V]p \notin [V].

Proof. The point pp is in cˉ\bar c exactly when cj≤pj≤cj+1c_j \le p_j \le c_j + 1 for each jj, that is when cj=⌊pj⌋c_j = \lfloor p_j \rfloor, or pjp_j is an integer and cj=pj−1c_j = p_j - 1. This is L1. The cells that do not contain pp are closed, and only finitely many of them lie within distance 1 of pp, so there is a ball BB around pp that meets no cell outside RR. Every point of space lies in some closed cell, so B⊆⋃c∈RcˉB \subseteq \bigcup_{c \in R} \bar c. If k=0k = 0, no cell of VV contains pp, and p∉[V]p \notin [V]. If every cell of RR is in VV, then B⊆[V]B \subseteq [V] and p∈int⁡[V]p \in \operatorname{int}[V]. Otherwise some c∈Rc \in R is in VV and some d∈Rd \in R is not. Then p∈cˉ⊆[V]p \in \bar c \subseteq [V]. By fact (b), pp is a limit of points of d˚\mathring d, and d˚\mathring d is disjoint from every cell of VV, so pp is a limit of points outside [V][V] and is on the boundary. Lines L3 to L5 return these three answers. □\square

Lemma 4 (VOLUME and AREA). The volume of [V][V] is ∣V∣|V|, and the area of ∂[V]\partial [V] is the number of pairs (c,d)(c, d) with c∈Vc \in V, d∉Vd \notin V and dd a face neighbour of cc.

Proof. The open cells are disjoint and the rest of [V][V] lies in GG, which has volume 0, so the volume is ∣V∣|V|. By Lemma 3, a point pp that is in GG on exactly one grid plane lies in exactly two cells cc and dd, face neighbours with the common square σ\sigma in that plane, and p∈∂[V]p \in \partial[V] exactly when one of them is in VV and the other is not. The points on two or more grid planes lie on the grid lines, which have area 0, and the points off GG are not on the boundary. So ∂[V]\partial[V] is, up to a set of area 0, the union of the unit squares σ\sigma between such pairs. Each such square has area 1 and is counted once, from the side of the cell in VV. □\square

Lemma 5 (OCTREE). For a set CC of cells inside the cube QQ of side s=2ds = 2^d at cornercorner, OCTREE(CC, cornercorner, ss) stops, and it returns a tree whose FULL leaves cover exactly the cells of CC, in which no internal node has eight children that are all EMPTY or all FULL. The joint walk of two such trees returns the tree of the same kind for C1⊗C2C_1 \otimes C_2.

Proof. By induction on dd. Lines L7 and L8 return a correct leaf when CC is empty or is every cell of QQ; when d=0d = 0 the cube has one cell, so one of the two holds. Otherwise CC is mixed, and L9 splits it among the eight subcubes of side 2d−12^{d-1}, each cell going to the one subcube that contains it; the induction hypothesis gives correct children, and the node is mixed, so it is not one leaf. The depth falls by one per call, so the recursion stops. For the walk, a leaf of value vv on a cube stands for the same cells as eight leaves of value vv on its subcubes, so expanding a leaf does not change the set, and op applied to two leaves is op applied to every cell of their cube. By induction the eight results are correct, and replacing eight equal leaves by one keeps the set and the reduced form. A reduced tree is unique for its set, since L7 and L8 decide each node from the set alone, so the walk returns the same tree as OCTREE of the result. □\square

Lemma 6 (the error of SAMPLE). Let SS be a closed set and V={c:the centre of c is in S}V = \{c : \text{the centre of } c \text{ is in } S\}. If cˉ\bar c does not meet ∂S\partial S, then c∈Vc \in V exactly when cˉ⊆S\bar c \subseteq S. So S△[V]S \mathbin{\triangle} [V] lies in the union of the cells that meet ∂S\partial S.

Proof. Space is the disjoint union of int⁡S\operatorname{int} S, ∂S\partial S and the open set outside SS. If cˉ\bar c misses ∂S\partial S, then it is the union of its two disjoint relatively open parts in int⁡S\operatorname{int} S and outside SS. A cube is connected, so one part is empty, and the centre decides which one. A point of S△[V]S \mathbin{\triangle} [V] in a cell cˉ\bar c that misses ∂S\partial S would contradict this. □\square

Lemma 7 (the area on a convex solid). If SS is convex, then every grid line parallel to an axis meets the cells of VV in one run, so AREA(VV) is twice the number of such lines that meet VV.

Proof. The centres on one line that lie in SS are the centres in the segment where the line meets SS, a convex set, so they are consecutive. A run gives exactly two boundary squares across that line, one at each end, and every boundary square is the end of a run on the line through the two cells beside it. □\square

For a ball of radius rr in unit cells, the lines parallel to one axis that meet VV number πr2+O(r)\pi r^2 + O(r): a line through a point of the disk at distance at most r−1r - 1 from the centre meets a chord longer than 2, so it holds a centre, and the lattice points of a disk of radius rr number πr2+O(r)\pi r^2 + O(r). So AREA(VV) =6πr2+O(r)= 6 \pi r^2 + O(r), while the sphere has area 4πr24 \pi r^2.

Theorem. BOOLEAN returns the voxel sets of the regularized union, intersection and difference; CLASSIFY, VOLUME and AREA return the class of a point, the volume and the boundary area of [V][V]; OCTREE and the joint walk return the reduced octree of their set. Each operation stops: BOOLEAN, CLASSIFY and AREA after a finite loop over at most ∣V∣+∣W∣|V| + |W| cells, 8 cells and 6∣V∣6|V| pairs, OCTREE after d+1d + 1 levels of calls.

Proof. Lemmas 1 to 5 give the results, and the loops and the recursion are bounded as stated. □\square

The tests check Lemma 2 and Lemma 3 together against ordinary point membership: at a point pp of the half-integer grid, each point p+s/4p + s/4 with s∈{−1,+1}3s \in \{-1, +1\}^3 lies in one open cell, so by the proof of Lemma 2 the ordinary result there agrees with the regularized one, and by Lemma 3 pp is IN, ON or OUT as these eight points are all, some or none in it. They check Lemma 4 by counting the square centres that CLASSIFY puts ON, Lemmas 6 and 7 on a sampled ball, and Lemma 5 by round trips and Booleans on random octrees. ■\blacksquare

Complexity

With a hash table, CLASSIFY makes at most 8 look ups, so it takes expected O(1)O(1) time. BOOLEAN looks at each cell of VV and WW once, so it takes expected O(m)O(m) time for m=∣V∣+∣W∣m = |V| + |W|. VOLUME is O(1)O(1) if the count is stored, and AREA is O(m)O(m), six look ups per cell. The set of cells takes Θ(m)\Theta(m) space. The bit array takes Θ(n3)\Theta(n^3) bits whatever the solid, and its Booleans take O(n3/w)O(n^3 / w) word operations on a machine with words of ww bits.

OCTREE splits the cells once per level, so it takes O(mD)O(m D) time, and each level has at most mm nonempty nodes, so the tree has O(mD)O(m D) nodes. The joint walk of two octrees takes time linear in the sum of their sizes, because each call pairs a node position that is present in at least one of the two trees.

The real cost is the resolution. A part of 1 m at a cell of 1 mm needs 10910^9 cells, 125 MB as bits, and a cell of 0.5 mm needs 8 times more. The octree helps because its size follows the boundary, not the volume. For a region quadtree, Hunter and Steiglitz proved a bound of O(p+D)O(p + D) nodes for a region of perimeter pp; for a ball the octree size here grows by about 4 when the radius doubles, while the box of cells grows by 8. These ball figures are measured, not proved:

radius rr cells in the sample octree nodes cells in the cube (2r)3(2r)^3 AREA 4πr24 \pi r^2
4 280 457 512 312 201
8 2176 1737 4096 1248 804
16 17256 6985 32768 4872 3217
32 137376 29065 262144 19368 12868

Variants

  • Octree. Meagher's octree encoding groups each uniform block of 2k×2k×2k2^k \times 2^k \times 2^k cells into one leaf. Booleans walk the two trees together, and a rotation by a multiple of 90°90° about an axis permutes the children.
  • Linear octree. Store only the FULL leaves, each as its Morton code and its level, in sorted order, as Gargantini did for the linear quadtree.
  • Run lengths. Store each grid line as the list of runs of filled cells, as in run-length encoding. The Boolean operations merge the runs line by line.
  • Cell decomposition. Requicha's more general scheme glues cells of different shapes, such as tetrahedra or curved bricks, that meet only on their faces. Finite element meshes are decompositions of this kind.
  • Values in the cells. Store a density, a material or a signed distance per cell instead of one bit. Marching cubes then makes a smooth surface between the samples, and TSDF fusion builds such grids from depth images.
  • Two dimensions. The same scheme on pixels gives the binary image and the region quadtree.

When to use it

Use a voxel set when the data comes as samples on a grid, as from CT and MRI scans, when the shape is noisy or very complex and its exact faces do not matter, or when an algorithm needs many fast point tests and Booleans of the same size, as in the simulation of machining, the slicing for 3D printing or the planning of paths. A B-rep or a CSG tree is better for a precise CAD part with flat and curved faces: it is exact, it is small, and it can be moved by any rigid motion. A voxel set is exact only for solids that are unions of grid cubes.

Pitfalls

  • Resolution. Halving the cell multiplies the memory of a dense grid by 8. Choose the cell from the smallest feature that must survive, and prefer an octree or a sparse set when most cells are empty or full.
  • Thin features vanish. SAMPLE keeps a cell by its centre, so a wall or a rod thinner than one cell can disappear or break into parts. Sampling by "the cell meets SS" keeps them, but the result is larger than SS.
  • The area is wrong in the limit. AREA counts the steps of the staircase, and on a slope the steps do not get flatter when the cells get smaller. For a convex solid each grid line that meets the sample gives exactly 2 boundary squares, so the area tends to the sum of the areas of the shadows in the three axis directions, counted twice. For a ball of radius rr this is 6πr26 \pi r^2, 1.5 times the true 4πr24 \pi r^2, as the table shows. Use the cells for volume, and fit a surface, for example by marching cubes, for area.
  • Motions. Only translations by whole cells and the 24 rotations of the cube are exact. Any other motion must sample the moved solid again, and the errors grow with each step.
  • Different grids. Booleans are exact only when both operands use the same grid. Two grids with different steps or origins must be sampled onto one first.
  • Non-manifold results. Two cells that meet only along an edge or at a corner give a valid r-set whose boundary is not a manifold. A manifold B-rep made from the cells must treat these edges and vertices with care.

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.

spatial_occupancy_enumeration.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spatial-occupancy-enumeration/. The authors are listed in prov/F2JK2W.jsonl.

"""Spatial occupancy enumeration: a solid as a set of closed unit cells.

The cell (i, j, k) is the closed cube [i, i+1] x [j, j+1] x [k, k+1], and a
voxel set V stands for the union of its cells. Such a union is always a closed
regular set, and the set operations on the cells are the regularized set
operations on the solids. All tests are exact on integer and Fraction points.

The octree functions convert a voxel set inside the cube [0, 2^d)^3 to an
octree and back, and combine two octrees with a Boolean operation.
"""

from __future__ import annotations

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

Cell = tuple[int, int, int]
IN, ON, OUT = "in", "on", "out"
EMPTY, FULL = "E", "F"
Octree = Union[str, tuple]  # EMPTY, FULL, or a tuple of 8 children

NEIGHBOURS = ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1))
UNION = lambda a, b: a or b  # noqa: E731
INTERSECTION = lambda a, b: a and b  # noqa: E731
DIFFERENCE = lambda a, b: a and not b  # noqa: E731


class VoxelSet:
    def __init__(self, cells: Iterable[Cell] = ()) -> None:
        self.cells: set[Cell] = {tuple(c) for c in cells}  # type: ignore[misc]

    @staticmethod
    def from_membership(inside: Callable[[tuple], bool], lo: Sequence[int], hi: Sequence[int]) -> "VoxelSet":
        """Sample a solid at the centre of each cell of the box [lo, hi)."""
        h = Fraction(1, 2)
        return VoxelSet(c for c in itertools.product(*(range(lo[j], hi[j]) for j in range(3)))
                        if inside((c[0] + h, c[1] + h, c[2] + h)))

    def __eq__(self, other: object) -> bool:
        return isinstance(other, VoxelSet) and self.cells == other.cells

    def __len__(self) -> int:
        return len(self.cells)

    # ----- the regularized operations are the set operations on cells -----

    def boolean(self, other: "VoxelSet", op: Callable[[bool, bool], bool]) -> "VoxelSet":
        return VoxelSet(c for c in self.cells | other.cells
                        if op(c in self.cells, c in other.cells))  # @line L6

    def union(self, other: "VoxelSet") -> "VoxelSet":
        return self.boolean(other, UNION)

    def intersection(self, other: "VoxelSet") -> "VoxelSet":
        return self.boolean(other, INTERSECTION)

    def difference(self, other: "VoxelSet") -> "VoxelSet":
        return self.boolean(other, DIFFERENCE)

    # ----- queries -----

    def classify(self, p: Sequence) -> str:
        """IN, ON or OUT for the closed union of the cells."""
        ranges = []
        for x in p:  # @line L1
            f = int(x // 1)
            ranges.append((f - 1, f) if x == f else (f,))
        around = list(itertools.product(*ranges))
        k = sum(1 for c in around if c in self.cells)  # @line L2
        if k == 0:  # @line L3
            return OUT
        if k == len(around):  # @line L4
            return IN
        return ON  # @line L5

    def volume(self) -> int:
        return len(self.cells)

    def area(self) -> int:
        """The number of unit squares between a cell of V and a cell not in V."""
        return sum(1 for c in self.cells for d in NEIGHBOURS
                   if (c[0] + d[0], c[1] + d[1], c[2] + d[2]) not in self.cells)


# ----- octrees -----

def to_octree(v: VoxelSet, depth: int) -> Octree:
    """The octree of v inside the cube [0, 2^depth)^3; cells outside it are an error."""
    side = 1 << depth
    for c in v.cells:
        if not all(0 <= x < side for x in c):
            raise ValueError("a cell is outside the cube of the octree")
    return _build(list(v.cells), (0, 0, 0), side)


def _child_corner(corner: Cell, half: int, i: int) -> Cell:
    return tuple(corner[j] + half * (i >> j & 1) for j in range(3))  # type: ignore[return-value]


def _build(cells: list[Cell], corner: Cell, side: int) -> Octree:
    if not cells:  # @line L7
        return EMPTY
    if len(cells) == side ** 3:  # @line L8
        return FULL
    half = side // 2  # @line L9
    parts: list[list[Cell]] = [[] for _ in range(8)]
    for c in cells:
        parts[sum(1 << j for j in range(3) if c[j] >= corner[j] + half)].append(c)
    return tuple(_build(parts[i], _child_corner(corner, half, i), half) for i in range(8))


def from_octree(t: Octree, depth: int) -> VoxelSet:
    out: set[Cell] = set()

    def walk(t: Octree, corner: Cell, side: int) -> None:
        if t == EMPTY:
            return
        if t == FULL:
            out.update(itertools.product(*(range(corner[j], corner[j] + side) for j in range(3))))
            return
        half = side // 2
        for i in range(8):
            walk(t[i], _child_corner(corner, half, i), half)

    walk(t, (0, 0, 0), 1 << depth)
    return VoxelSet(out)


def octree_boolean(a: Octree, b: Octree, op: Callable[[bool, bool], bool]) -> Octree:
    """Combine two octrees of the same cube in time linear in their sizes."""
    if isinstance(a, str) and isinstance(b, str):
        return FULL if op(a == FULL, b == FULL) else EMPTY
    ka = a if isinstance(a, tuple) else (a,) * 8
    kb = b if isinstance(b, tuple) else (b,) * 8
    kids = tuple(octree_boolean(x, y, op) for x, y in zip(ka, kb))
    if all(k == EMPTY for k in kids):
        return EMPTY
    if all(k == FULL for k in kids):
        return FULL
    return kids


def octree_size(t: Octree) -> int:
    return 1 if isinstance(t, str) else 1 + sum(octree_size(k) for k in t)
test_spatial_occupancy_enumeration.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spatial-occupancy-enumeration/. The authors are listed in prov/F2JK2W.jsonl.

import itertools
import random
import unittest
from fractions import Fraction

from spatial_occupancy_enumeration import (
    DIFFERENCE, EMPTY, FULL, IN, INTERSECTION, ON, OUT, UNION, VoxelSet,
    from_octree, octree_boolean, octree_size, to_octree,
)

QUARTER = Fraction(1, 4)
OCTANTS = list(itertools.product((-1, 1), repeat=3))
OPS = {"union": UNION, "intersection": INTERSECTION, "difference": DIFFERENCE}


def contains(cells, p, scale=1):
    """Ordinary point membership of p / scale in the closed union of the cells,
    by a scan. With integer p and scale the test is integer arithmetic."""
    return any(all(scale * c[j] <= p[j] <= scale * (c[j] + 1) for j in range(3)) for c in cells)


def brute_classify(a, b, op, p):
    """The class of p against the regularized result of op on the solids a and b,
    from ordinary point membership in a and b only. p is on the half-integer grid,
    so each point p + s/4 is on no grid plane: it is interior to one cell, and the
    ordinary result there agrees with its interior (and so with the regularized
    result) near p. p is in the closure of each of the eight open octants. The
    points are scaled by 4 so that the scan uses integers."""
    k = 0
    for s in OCTANTS:
        q = tuple(int(4 * p[j]) + s[j] for j in range(3))
        k += bool(op(contains(a, q, 4), contains(b, q, 4)))
    return OUT if k == 0 else IN if k == 8 else ON


def random_set(rng, n, density):
    return VoxelSet(c for c in itertools.product(range(n), repeat=3) if rng.random() < density)


def box(lo, hi):
    return VoxelSet(itertools.product(*(range(lo[j], hi[j]) for j in range(3))))


class VoxelTests(unittest.TestCase):
    def test_box_measures(self):
        b = box((0, 0, 0), (3, 4, 5))
        self.assertEqual(b.volume(), 60)
        self.assertEqual(b.area(), 2 * (12 + 20 + 15))
        self.assertEqual(b.classify((0, 0, 0)), ON)
        self.assertEqual(b.classify((1, 1, 1)), IN)
        self.assertEqual(b.classify((3, 2, 2)), ON)
        self.assertEqual(b.classify((Fraction(7, 2), 2, 2)), OUT)

    def test_regularized_on_shared_faces(self):
        a = box((0, 0, 0), (2, 2, 2))
        b = box((2, 0, 0), (4, 2, 2))
        self.assertTrue(contains(a.cells, (2, 1, 1)) and contains(b.cells, (2, 1, 1)))
        self.assertEqual(len(a.intersection(b)), 0)  # no dangling face
        d = a.difference(box((1, 0, 0), (3, 2, 2)))
        self.assertEqual(d.classify((1, 1, 1)), ON)  # the face x = 1 is kept
        u = a.union(b)
        self.assertEqual(u.classify((2, 1, 1)), IN)  # the shared face is now interior
        self.assertEqual(u.area(), a.area() + b.area() - 2 * 4)

    def test_operations_against_point_membership(self):
        rng = random.Random(1982)
        on_seen = 0
        for trial in range(12):
            a = random_set(rng, 4, 0.45)
            b = random_set(rng, 4, 0.45)
            for name, op in OPS.items():
                r = a.boolean(b, op)
                self.assertEqual(r, getattr(a, name)(b))
                for _ in range(300):
                    p = tuple(Fraction(rng.randrange(-1, 10), 2) for _ in range(3))
                    got = r.classify(p)
                    self.assertEqual(got, brute_classify(a.cells, b.cells, op, p), (trial, name, p))
                    on_seen += got == ON
                for _ in range(40):  # points on no grid plane: the ordinary formula
                    p = tuple(Fraction(rng.randrange(0, 35), 7) for _ in range(3))
                    if any(x.denominator == 1 for x in p):
                        continue
                    want = op(contains(a.cells, p), contains(b.cells, p))
                    self.assertEqual(r.classify(p) == IN, want)
                    self.assertNotEqual(r.classify(p), ON)
        self.assertGreater(on_seen, 1000)

    def test_area_and_volume(self):
        rng = random.Random(7)
        for _ in range(30):
            a = random_set(rng, 4, 0.5)
            b = random_set(rng, 4, 0.5)
            self.assertEqual(a.union(b).volume() + a.intersection(b).volume(), a.volume() + b.volume())
            # brute force area: the unit squares of the grid whose centre is ON
            squares = 0
            for axis in range(3):
                for c in itertools.product(range(-1, 6), repeat=3):
                    centre = tuple(Fraction(c[j]) if j == axis else c[j] + Fraction(1, 2) for j in range(3))
                    squares += a.classify(centre) == ON
            self.assertEqual(a.area(), squares)

    def test_sampling_a_solid(self):
        r = 6
        ball = VoxelSet.from_membership(lambda p: sum((x - r) ** 2 for x in p) <= r * r, (0, 0, 0), (2 * r, 2 * r, 2 * r))
        self.assertEqual(ball.classify((r, r, r)), IN)
        self.assertEqual(ball.volume(), len([c for c in itertools.product(range(2 * r), repeat=3)
                                             if sum((x + Fraction(1, 2) - r) ** 2 for x in c) <= r * r]))
        # The error is only in cells that meet the boundary sphere: a cell wholly
        # inside the ball is kept and a cell wholly outside it is dropped.
        for c in itertools.product(range(-1, 2 * r + 1), repeat=3):
            far = sum(max((x - r) ** 2, (x + 1 - r) ** 2) for x in c)
            near = sum((max(x, min(r, x + 1)) - r) ** 2 for x in c)  # the nearest point of the cell
            if far <= r * r:
                self.assertIn(c, ball.cells)
            if near > r * r:
                self.assertNotIn(c, ball.cells)
        self.assertEqual(from_octree(to_octree(ball, 4), 4), ball)
        # The ball is convex, so each grid line meets the sample in one run of
        # cells, and the area is twice the number of lines that meet it.
        lines = {(a, tuple(c[j] for j in range(3) if j != a)) for c in ball.cells for a in range(3)}
        self.assertEqual(ball.area(), 2 * len(lines))

    def test_octree_round_trip_and_booleans(self):
        rng = random.Random(1980)
        self.assertEqual(to_octree(box((0, 0, 0), (8, 8, 8)), 3), FULL)
        self.assertEqual(to_octree(VoxelSet(), 3), EMPTY)
        with self.assertRaises(ValueError):
            to_octree(VoxelSet([(8, 0, 0)]), 3)
        for _ in range(40):
            lo = [rng.randrange(0, 8) for _ in range(3)]
            hi = [rng.randrange(x + 1, 9) for x in lo]
            a = box(lo, hi).union(random_set(rng, 8, 0.05))
            b = random_set(rng, 8, rng.choice((0.1, 0.5, 0.9)))
            ta, tb = to_octree(a, 3), to_octree(b, 3)
            self.assertEqual(from_octree(ta, 3), a)
            self.assertEqual(from_octree(tb, 3), b)
            for op in OPS.values():
                t = octree_boolean(ta, tb, op)
                self.assertEqual(from_octree(t, 3), a.boolean(b, op))
                self.assertEqual(t, to_octree(a.boolean(b, op), 3))  # the result is reduced
            self.assertLessEqual(octree_size(ta), 1 + 8 + 64 + 512)


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

History

Arrays of volume samples came from medical imaging and image processing in the 1970s. In 1980 Requicha's survey put solids on a formal basis and listed spatial occupancy enumeration among the representation schemes, as an unambiguous and unique scheme whose domain is limited to unions of grid cells; he also named the more general cell decompositions. In the same year Jackins and Tanimoto described oct-trees for three-dimensional objects, after the quadtrees of images, and Meagher's report of 1980 and paper of 1982 developed octree encoding for solid modeling, with Booleans, motions and display that work on the tree. Mäntylä's book of 1988 treats exhaustive enumeration and octrees together as decomposition models.

References

  1. Aristides A. G. Requicha, Representations for rigid solids, theory, methods, and systems, ACM Computing Surveys 12(4), 437 to 464, 1980, the section on representation schemes, where spatial occupancy enumeration and cell decomposition are two of the schemes, with their domain, validity, unambiguity and uniqueness
  2. Donald Meagher, Geometric modeling using octree encoding, Computer Graphics and Image Processing 19(2), 129 to 147, 1982, the octree encoding of solids, its size, and the Boolean operations, motions and display on it
  3. Chris L. Jackins and Steven L. Tanimoto, Oct-trees and their use in representing three-dimensional objects, Computer Graphics and Image Processing 14(3), 1980, the oct-tree as the three-dimensional form of the region quadtree, and its construction from a voxel array
  4. Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, the chapter on decomposition models, with exhaustive enumeration, octrees and cell decompositions
  5. Gregory M. Hunter and Kenneth Steiglitz, Operations on images using quad trees, IEEE Transactions on Pattern Analysis and Machine Intelligence 1(2), 1979, pp. 145 to 153, the bound on the number of nodes of a quadtree by the perimeter of the region

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.area
  • a full proof of time.boolean
  • a full proof of time.classify
  • a full proof of time.to_octree
  • a full proof of space.bit_array
  • a full proof of space.cell_set
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/F2JK2W/text.yaml