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
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
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 for integers ; another grid step is a scaling of this one. A voxel set is a finite set of integer triples, and it stands for the solid .
- : the set of cells of whose centres lie in the solid . This is one common way to make from a CAD model, a scan or a medical image.
- , and : the voxel sets of , and .
- : IN, ON or OUT, as is in the interior of , on its boundary or outside it.
- and : the volume and the boundary area of .
- and its inverse: the octree of inside a cube of side , and back.
Representation
Three forms are common, and they store the same set.
| form | storage | membership test | good for |
|---|---|---|---|
| bit array | bits for the box of 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 | sparse sets and unbounded space |
| octree | one node per block of the tree, each leaf EMPTY or FULL | a walk of 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 and the corners of the cells are exact rationals and integers, so every test is exact.
Operations
CLASSIFY(V, p) ▷ IN, ON or OUT for the closed union [V]- 1
for j ← 1 to 3: R_j ← {⌊p_j⌋ − 1, ⌊p_j⌋} if p_j is an integer, else {⌊p_j⌋} - 2
k ← the number of cells c ∈ R₁ × R₂ × R₃ with c ∈ V - 3
if k = 0 then return OUT - 4
if k = |R₁ × R₂ × R₃| then return IN - 5
return ON BOOLEAN(V, W, op) ▷ op is or, and, or and-not- 6
return {c ∈ V ∪ W : op(c ∈ V, c ∈ W)} OCTREE(C, corner, s) ▷ C: the cells of V in the cube of side s at corner- 7
if C = ∅ then return EMPTY - 8
if |C| = s³ then return FULL - 9
split 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 . On an axis where is not an integer, only the cell covers it; where is an integer, lies on a grid plane and both neighbour cells touch it. So 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 , the point is outside; if all of them are, a small ball around is filled and 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 and not in ".
The volume of is the number of cells. The area is the number of pairs of a cell in and one of its six face neighbours not in : 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 . fills the cells with and , so , and fills those with and , so . They overlap in the column .
| result | cells | volume | area |
|---|---|---|---|
| 6 | 6 | 22 | |
| 4 | 4 | 16 | |
| 8 | 8 | 28 | |
| the 2 cells with | 2 | 10 | |
| the 4 cells with | 4 | 16 |
The check holds. Now classify some points against .
| point | cells around (L1) | cells in | class |
|---|---|---|---|
| 4 cells with | 4 | IN | |
| 4 cells with , | 2 | ON | |
| 2 cells with | 0 | OUT | |
| 8 cells around the corner | 1 | ON |
The point is the reason for regularization. It lies in the closed box , so the ordinary difference does not contain it, and that set has no face at . It is not closed. The cell rule keeps the face, and CLASSIFY reports ON.
The octree of in the cube has depth 2. The root has 8 children of side 2. The two children at and 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 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 the set 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 and the open part of each one comes as close to 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 .
The proof page also proves the error of SAMPLE: a cell that does not meet the boundary of is kept exactly when it lies in . So and differ only inside cells that the boundary of crosses, and with grid step every point of the difference is within of the boundary of .
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 , , 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 write for the closed cell and for the open cell. For a finite set of triples, . Let be the union of the grid planes with an integer. Two facts about cells are used throughout. (a) A point not in lies in exactly one open cell and in no other closed cell. (b) An open cell meets the closed cell only if , and every point of is a limit of points of .
Lemma 1 ( is an r-set). For finite , is bounded, closed and regular, , and semianalytic.
Proof. A finite union of closed bounded boxes is closed and bounded, and it is a finite Boolean combination of the halfspaces , so it is semianalytic. Each box is regular, , so , where the last step uses that is closed.
Lemma 2 (BOOLEAN). For op one of or, and, and-not, let be the matching set operation and its regularized form, . Then line L6 returns and .
Proof. Line L6 tests every cell of ; a cell in neither set fails op for all three choices, so the result is . Let . For a point in the open cell , fact (a) gives exactly when , and the same for , so exactly when . So . This set is open, so it lies in , and its closure lies in . Conversely, is open and is closed with empty interior, so is dense in . It lies in , which is closed, so .
Lemma 3 (CLASSIFY). Line L1 makes the set of cells with , and CLASSIFY returns IN if , ON if and OUT if .
Proof. The point is in exactly when for each , that is when , or is an integer and . This is L1. The cells that do not contain are closed, and only finitely many of them lie within distance 1 of , so there is a ball around that meets no cell outside . Every point of space lies in some closed cell, so . If , no cell of contains , and . If every cell of is in , then and . Otherwise some is in and some is not. Then . By fact (b), is a limit of points of , and is disjoint from every cell of , so is a limit of points outside and is on the boundary. Lines L3 to L5 return these three answers.
Lemma 4 (VOLUME and AREA). The volume of is , and the area of is the number of pairs with , and a face neighbour of .
Proof. The open cells are disjoint and the rest of lies in , which has volume 0, so the volume is . By Lemma 3, a point that is in on exactly one grid plane lies in exactly two cells and , face neighbours with the common square in that plane, and exactly when one of them is in 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 are not on the boundary. So is, up to a set of area 0, the union of the unit squares between such pairs. Each such square has area 1 and is counted once, from the side of the cell in .
Lemma 5 (OCTREE). For a set of cells inside the cube of side at , OCTREE(, , ) stops, and it returns a tree whose FULL leaves cover exactly the cells of , 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 .
Proof. By induction on . Lines L7 and L8 return a correct leaf when is empty or is every cell of ; when the cube has one cell, so one of the two holds. Otherwise is mixed, and L9 splits it among the eight subcubes of side , 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 on a cube stands for the same cells as eight leaves of value 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.
Lemma 6 (the error of SAMPLE). Let be a closed set and . If does not meet , then exactly when . So lies in the union of the cells that meet .
Proof. Space is the disjoint union of , and the open set outside . If misses , then it is the union of its two disjoint relatively open parts in and outside . A cube is connected, so one part is empty, and the centre decides which one. A point of in a cell that misses would contradict this.
Lemma 7 (the area on a convex solid). If is convex, then every grid line parallel to an axis meets the cells of in one run, so AREA() is twice the number of such lines that meet .
Proof. The centres on one line that lie in are the centres in the segment where the line meets , 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.
For a ball of radius in unit cells, the lines parallel to one axis that meet number : a line through a point of the disk at distance at most from the centre meets a chord longer than 2, so it holds a centre, and the lattice points of a disk of radius number . So AREA() , while the sphere has area .
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 ; 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 cells, 8 cells and pairs, OCTREE after levels of calls.
Proof. Lemmas 1 to 5 give the results, and the loops and the recursion are bounded as stated.
The tests check Lemma 2 and Lemma 3 together against ordinary point membership: at a point of the half-integer grid, each point with 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 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.
Complexity
With a hash table, CLASSIFY makes at most 8 look ups, so it takes expected time. BOOLEAN looks at each cell of and once, so it takes expected time for . VOLUME is if the count is stored, and AREA is , six look ups per cell. The set of cells takes space. The bit array takes bits whatever the solid, and its Booleans take word operations on a machine with words of bits.
OCTREE splits the cells once per level, so it takes time, and each level has at most nonempty nodes, so the tree has 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 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 nodes for a region of perimeter ; 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 | cells in the sample | octree nodes | cells in the cube | AREA | |
|---|---|---|---|---|---|
| 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 cells into one leaf. Booleans walk the two trees together, and a rotation by a multiple of 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 " keeps them, but the result is larger than .
- 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 this is , 1.5 times the true , 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.
# 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
- 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
- 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
- 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
- Martti Mäntylä, An Introduction to Solid Modeling, Computer Science Press, 1988, the chapter on decomposition models, with exhaustive enumeration, octrees and cell decompositions
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag F2JK2W Edit this page History Report an error Markdown