Skip to content

Applications

Experimental applications compose BRepAX geometry evaluation with host-side CAD preparation. Their individual contracts define differentiation and input scope.

STEP through-hole editing

prepare_hole_edit recognizes cylindrical through-holes in a supplied B-Rep. It can edit selected radii and centers without reconstructing the stock's modeling history. The JAX model holds the exact volume, surface-area and first-moment laws of the holes, so it needs no mesh; the host rebuild method produces a new OCCT shape for further use or STEP export.

import equinox as eqx
import jax
import jax.numpy as jnp

from brepax.experimental.applications.hole_edit import prepare_hole_edit
from brepax.io.step import read_step

jax.config.update("jax_enable_x64", True)
shape = read_step("part.step")
all_holes = prepare_hole_edit(shape)
# Select one hole by its input face ID; other features remain fixed.
face_id = all_holes.holes[0].face_id
edit = prepare_hole_edit(shape, [face_id])
model = edit.model
radii = (model.reference_radii + model.upper_radii) / 2
assert bool(eqx.filter_jit(model.is_valid)(radii))
volume, derivative = jax.jit(jax.value_and_grad(model.volume))(radii)
areas = jax.jit(jax.vmap(model.surface_area))(
    jnp.stack([model.reference_radii, radii])
)
edited_shape = edit.rebuild(radii)

Center motion uses an optional second argument, center_shifts, with one world-coordinate displacement vector per selected hole. It is measured from the original center in input CAD units. The hole axis stays fixed; shifts must be perpendicular to it. Omitting the argument preserves radius-only behavior. For the Z-axis holes in the fixture below:

shifts = jnp.array([[0.2, -0.1, 0.0]])
assert bool(eqx.filter_jit(model.is_valid)(radii, shifts))
center = model.center_of_mass(radii, shifts)
center_jacobian = jax.jit(jax.jacrev(model.center_of_mass, argnums=1))(radii, shifts)
edited_shape = edit.rebuild(radii, shifts)

For a reproducible repository example, use tests/fixtures/box_with_holes.step as part.step. Its radius-4 through-hole can be selected and changed to 4.4; the other radius-3 hole remains unchanged. The tests also cover rectangular and round stocks, nonintersecting orthogonal holes, regenerated placements, STEP roundtrips, and independent CAD finite-difference references.

Contract and limits

  • Input must contain one valid outward-oriented solid. Editable holes need a complete empty cylindrical bore, two perpendicular outward-facing planar ends, and clearance from other boundaries. Blind, oblique, intersecting and near-boundary holes are rejected, as are holes with other material resting on an opening's plane, which filling that opening would join. Material inside a bore has to cross that plane, however thin it is. A cylindrical wall split into several faces, such as a STEP exporter's two half-cylinder faces or a coplanar seam splitting it axially, is rejected by default too; pass merge_same_domain=True to unify same-domain faces/edges before recognition and recover such holes. Unsupported inward cylinders appear in edit.rejected; an explicit selection of an unsupported face raises ValueError. A counterbore shoulder is not a valid end for its larger cylinder; the smaller bore through the remaining slab can still qualify independently.
  • merge_same_domain=True renumbers face IDs to the unified working solid: edit.holes, edit.rejected, and any face_ids passed in refer to that unified shape, not the original input. Discover IDs by preparing once without face_ids, then select by preparing again with the same merge_same_domain value and those IDs. rebuild starts from the unified working solid, but its Boolean operations can change the face partition: discover face IDs again from the rebuilt solid before selecting faces on it. The default, False, keeps the original input's face IDs and partition unchanged.
  • Radii, center shifts, hole metadata, returned points and metrics use the input CAD's units. A fixed CadFrame normalizes host preparation and numerical evaluation. By default, the input bounding box is centered and its largest extent becomes 40 working units. No physical unit is inferred from a numeric coordinate.
  • Preparation requires JAX x64. Recognition and CAD rebuilding run outside jit, vmap and differentiation. Geometry/metric methods support all three; the Boolean validity predicate supports jit/vmap. Keep the prepared model fixed when differentiating with respect to radii or shifts. For direct compilation of a bound model method, use eqx.filter_jit(model.volume); bare jax.jit(model.volume) can fail because the bound Equinox model contains unhashable arrays. Alternatively, JIT a function taking the model as a PyTree argument. Compositions such as the value_and_grad example above also work.
  • Radius bounds are [0.5*r0, r0 + clearance - margin], where margin is 30 CAD tolerances (contact_margin). Center shifts and radius growth share that range: the reach norm(shift) + max(radius-r0, 0) must not exceed clearance - margin, even when shrinking a hole. Two selected holes must also keep margin between them, so the sum of their reaches must not exceed their distance less margin: upper_radii holds one hole at a time, and all holes at their upper radii are generally invalid together. Halfway to those limits, all holes are valid together. Axial shifts are invalid beyond roundoff (64 * x64_epsilon * r0); the residual is projected out. Invalid edits return NaN metrics under JAX; rebuild raises. Gradients at invalid inputs are undefined.
  • The range is where the laws stay true, not where a part stays sound: a wall can come down to margin. State the distance you need, through ligament_bounds or hole_ligament_constraints.
  • Volume and area are rigid-motion invariant; their radius gradients are too. Under positive length scaling s, values scale by s**3 and s**2, and radius gradients by s**2 and s. Centers transform as points; center radius derivatives rotate as vectors and are unchanged by unit scaling. Rotate center shifts with the geometry. Scalar shift gradients rotate as vectors and scale like radius gradients. The center-of-mass shift Jacobian transforms as R @ J @ R.T and is unchanged by unit scaling. These Jacobians describe transverse motion, with zero axial component; they do not authorize editing the hole depth or orientation.
  • Volume, area and first moment follow the laws of isolated complete cylinders with planar ends, from reference measures integrated adaptively to 1e-9 relative. They hold up to the CAD tolerance of the prepared solid and do not differentiate OCCT reconstruction. Rebuild and independently check CAD before accepting an optimized design.
  • Face IDs apply only to the prepared input. Reconstruction unifies connected same-domain faces and edges to remove fill seams; unselected geometry stays fixed, but its face partition can change. Do not assume that Boolean output or a STEP roundtrip preserves face IDs.

See ADR-0021 for the scope decision.

Remaining distances and caller responses

HoleEditModel.ligament_bounds gives a lower bound on each edited hole's distance to every other boundary face except its own end faces. An edited wall lies within abs(r - r0) + norm(s) of the wall it replaces, so the distances measured at recognition can fall by at most that travel, and by both travels between two selected holes. The bound applies to every recognized hole, is reached when a hole grows toward a radially closest feature, and is conservative otherwise. It is a distance between faces, not a part-wide wall thickness.

Volume, area, center of mass and these bounds compose with a response you define, such as a stress surrogate fitted to hole size and ligament:

def response(radii):
    ligaments = model.ligament_bounds(radii)
    return model.volume(radii) / 1e4 + jnp.sum(1 / ligaments**2)

gradient = jax.grad(response)(radii)

This gradient describes the exact laws, and on a plate it matched finite differences through rebuilt CAD. A search using it has no certificate: rebuild its result and check it. Avoid constraining a part-wide minimum wall thickness through the frozen mesh below. Measured on six imported parts, its hard minimum had a zero gradient on three, and remeshing could move its value by more than a small edit did.

Inverse editing

The regression example also imports a four-hole STEP plate, selects three noncollinear holes, fits their radii to independently generated CAD volume and in-plane center-of-mass targets, and validates the rebuilt STEP while preserving the fourth hole. Its Newton iteration checks the Jacobian rank and edit bounds; it is a reproducible example, not a general-purpose optimizer API.

Another regression solves a selected hole's radius and two transverse center coordinates from independent CAD volume and in-plane center-of-mass targets, then checks the rebuilt STEP and the unchanged neighboring hole. Moving an isolated hole at fixed radius leaves volume and area unchanged; those two measurements alone cannot determine a center position.

Choose enough independent target measurements. For four coplanar equal-height holes, volume and even the full 3D center of mass need not determine all four radii uniquely. A small residual of the laws also does not certify the CAD: check the rebuilt part.

brepax.experimental.applications.hole_edit

Experimental fixed-topology radius and center editing of STEP through-holes.

Host preparation and reconstruction use OCCT. The array model holds the exact volume, surface-area and first-moment laws of the represented holes, so it needs no mesh; responses without a law belong to the optional frozen mesh of :mod:brepax.experimental.applications.hole_mesh. Nothing traces through feature recognition, Boolean rebuilding or topology changes.

PreparedHoleEdit dataclass

Host result with selected holes, rejected candidates, frame and JAX model.

holes are ordered like the radius vector; explicit face selections preserve caller order, otherwise original face order is used. Unselected features remain fixed. Host CAD objects never enter the JAX model.

rebuild(radii, center_shifts=None)

Rebuild isolated holes in OCCT and restore external coordinates.

This host operation is not differentiable. Raises ValueError for an invalid radius/shift vector and RuntimeError for reconstruction failure or disagreement with isolated-hole volume, area or center of mass. When whole-solid OCCT properties disagree, the removed and added regions must still match the edit and stay beside the edited bores. Input CAD remains owned by the caller; each reconstruction uses an owned copy. Only holes whose radius differs from its reference or whose center moves are filled and cut again; the others keep their imported faces, since a STEP hole wall may deviate from its ideal cylinder within the CAD tolerance. Same-domain faces/edges are unified, so unselected geometry is preserved but original face partitions and IDs are not.

HoleEditModel

Bases: Module

Exact laws of isolated holes; differentiate radii and shifts directly.

Each method accepts external-unit radii and optional center_shifts with shape (selected holes, 3). Shifts are world-coordinate vectors from the original centers, perpendicular to the fixed hole axes. Omission means zero shift. Axial components exceeding 64x64_epsilonreference_radius are invalid; roundoff-sized components are projected out. Shift Jacobians are tangent derivatives, with zero axial component, not axial edit support.

Within the bounds, with t = r - r0, a hole of height h changes the volume by -pi*h*t*(2*r0 + t), the surface area by 2*pi*h*t - 2*pi*t*(2*r0 + t), and the first moment by -pi*h*(t*(2*r0 + t)*c + r**2*s) for center c and transverse shift s. The laws hold exactly for holes recognized as complete cylinders with planar ends, up to the CAD tolerance of the prepared solid. The reference measures come from adaptive OCCT integration to 1e-9 relative.

Geometry and metric methods support jit, vmap and parameter differentiation; the Boolean validity predicate supports jit/vmap. Lengths are in the input CAD's units. Scalar measures and their radius derivatives are invariant under rigid placement. Rotate shifts along with the CAD: scalar shift gradients rotate as vectors, while the center-of-mass shift Jacobian transforms as RJR.T. Under positive unit scaling s, volume/area scale by s3/s2 and length gradients by s**2/s. Center-of-mass length Jacobians do not scale. Centers transform as points.

lower_radii/upper_radii bound radii one hole at a time: an upper radius stops contact_margin short of the nearest feature, with the other holes unedited. Each hole's reach, its shift magnitude plus positive radius growth, must not exceed upper_radii - reference_radii, including when shrinking the hole. Two selected holes must also keep contact_margin between them, so their reaches must sum to at most their distance less that margin, and all holes at their upper radii are generally invalid together. Invalid edits produce NaN measures; derivatives there are undefined.

This range only keeps the laws true. A wall this thin is rarely a design you want: state the distance to keep with ligament_bounds, or with :func:~brepax.experimental.applications.dimension_query.hole_ligament_constraints.

fixed_clearance is each hole's distance to every boundary face other than its end faces and the selected holes, hole_clearance its distance to each selected hole (infinite on the diagonal). Both are in input units; ligament_bounds uses them.

center_of_mass(radii, center_shifts=None)

Uniform-density center of mass in external coordinates.

is_valid(radii, center_shifts=None)

Check radius bounds, the reach of each hole and pair, and transversality.

ligament_bounds(radii, center_shifts=None)

Lower bound on each edited hole's distance to the rest of the boundary.

A point of an edited wall lies within abs(r - r0) + norm(s) of the wall it replaces, so by the triangle inequality the distance to any boundary face other than the hole's own end faces falls by at most that travel, and to another selected hole by at most both travels. This holds for every recognized hole, whatever the neighboring surfaces are.

The bound is reached when the hole only grows and the closest feature lies radially, and is conservative otherwise: shrinking counts as travel because a feature beyond the hole's opening can come closer. It is the distance between faces, not a part-wide wall thickness: it says nothing about features the selected holes do not face. NaN for invalid edits.

shift_lengths(shifts)

Transverse shift magnitudes, differentiable at the zero-shift default.

shifts_or_zero(center_shifts)

Return validated shifts, with zeros when they are omitted.

surface_area(radii, center_shifts=None)

Solid surface area in input length units squared.

transverse(shifts)

Project shifts onto the planes perpendicular to the hole axes.

volume(radii, center_shifts=None)

Solid volume in input length units cubed.

ThroughHole dataclass

Recognized hole in input units; face IDs belong to the prepared input only.

base is one axis endpoint, axis a unit direction toward the other, and clearance the distance from the cylinder to other boundary faces, excluding its two planar end faces. boundary_distances keeps that distance per face as (face_id, distance), so its minimum is clearance. No identity persistence is promised after Boolean rebuilding or STEP serialization.

RejectedHole dataclass

An inward cylindrical face excluded from the editable feature set.

prepare_hole_edit(shape, face_ids=None, *, frame=None, merge_same_domain=False)

Prepare bounded edits of full cylindrical through-holes in one solid.

Accepts a B-Rep returned by read_step; does not assume a stock primitive or a construction history. Each selected inward cylinder must be complete, with two perpendicular planar ends and sufficient clearance. Blind, oblique, intersecting and near-boundary holes are unsupported, as are holes with other material resting on an opening's plane. A cylindrical wall split into several faces, e.g. a STEP exporter's two half-cylinder faces or a coplanar seam splitting it axially, is also unsupported by default; see merge_same_domain. Rejected inward cylinders are reported; an explicit selection of one raises.

frame maps input units to working coordinates; by default the bounding box is centered and its largest extent becomes 40 working units. It is frozen during editing. Preparation requires JAX x64; it never changes the global JAX precision setting. Input CAD is copied. No mesh is built; see :func:~brepax.experimental.applications.hole_mesh.prepare_hole_mesh for responses without an exact law.

merge_same_domain unifies coincident same-domain faces and edges of the working solid with OCCT ShapeUpgrade_UnifySameDomain before recognition, so a cylindrical wall split as described above can still be recognized as one complete hole. It also merges any other same-domain faces/edges in the solid, so the input's face partition is not preserved: when True, every returned face_id (selected, rejected, or passed in face_ids) refers to the unified working solid, not the original input. To select specific holes, call prepare_hole_edit once with merge_same_domain=True and no face_ids to read their face_id from the result, then again with those IDs and the same merge_same_domain=True; the unification is deterministic for a given input shape, so the IDs line up. rebuild starts from that unified working solid; its result can have a different face partition, so take face IDs from the rebuilt solid itself. Default is False: face IDs and geometry are unaffected.

Radius bounds are [0.5*r0, r0 + clearance - margin], with a margin of 30 CAD tolerances. Optional transverse center shifts share the growth budget: the reach norm(shift) + max(radius-r0, 0) must not exceed clearance - margin, and two selected holes must not reach further than their distance less the margin between them. Inside this range the laws hold, however thin the remaining walls are; HoleEditModel.ligament_bounds bounds those walls. These are local edits, not a topology-changing CAD kernel.

Raises ValueError for invalid CAD, unsupported selections, or no supported holes. OCCT extraction failures propagate. When merge_same_domain is True, a failed or geometry-changing unification also raises ValueError or RuntimeError.

Example

import jax from brepax.io.step import read_step jax.config.update("jax_enable_x64", True) edit = prepare_hole_edit(read_step("plate_with_holes.step")) radii = (edit.model.reference_radii + edit.model.upper_radii) / 2 assert bool(edit.model.is_valid(radii)) volume, gradient = jax.jit(jax.value_and_grad(edit.model.volume))(radii) edited_cad = edit.rebuild(radii)

To move a hole, pass center_shifts in external units to the model and rebuild. For a selected Z-axis hole, jnp.array([[0.1, 0.0, 0.0]]) moves its center in X; check the combined budget with is_valid first.

Frozen mesh for responses without a law

prepare_hole_mesh builds the watertight triangulation of a prepared edit and moves it with the same radii and shifts. Use it for responses with no exact law, such as metrics evaluated on triangles. Volume, area and center of mass are also available on the mesh for comparing discretizations, and are less accurate than the laws above.

from brepax.experimental.applications.hole_mesh import prepare_hole_mesh

mesh = prepare_hole_mesh(edit, deflection=0.0001)
assert bool(mesh.is_valid(radii))
triangles = eqx.filter_jit(mesh.triangles)(radii)
  • deflection is in working units, not the original STEP units.
  • Gradients describe the frozen mesh with coupled boundary motion. They do not differentiate remeshing, and refining deflection changes their error. Fresh meshing may change discretization error, so compare within an accuracy budget rather than demanding identical triangulations.
  • mesh.is_valid also rejects collapsed or locally reversed triangles. This limits the mesh only: edit.rebuild does not consult it, so an edit the mesh refuses can still rebuild. Because the planar boundary moves only within 0.4*clearance of the hole, growing further can reverse triangles there. It is not a general self-intersection certificate.
  • Preparation can fail where the edit itself is fine, for example when incident faces disagree by more than twice the CAD tolerance.

brepax.experimental.applications.hole_mesh

Frozen watertight mesh moved by through-hole edits, for responses without a law.

Volume, surface area and first moment of a hole edit have exact laws in :class:~brepax.experimental.applications.hole_edit.HoleEditModel. This layer is for responses that have none, such as metrics evaluated on triangles. Its derivatives are derivatives of the frozen discretization, which limits accuracy and can restrict the usable radii; neither affects the prepared edit or its rebuild.

HoleMeshModel

Bases: Module

Pure array mesh; differentiate radii and shifts with the mesh frozen.

Parameters are those of edit: external-unit radii and optional world-coordinate center_shifts. Cylinder samples and neighboring planar samples move together, tapering to zero before another feature, so the mesh stays connected. Methods support jit, vmap and parameter differentiation; the Boolean validity predicate supports jit/vmap.

is_valid adds to the edit bounds a check that no triangle collapses or reverses. It rejects edits of this mesh only: a rejected edit can still rebuild, and the check is not a general self-intersection test. Planar samples move only within 0.4*clearance of a hole, so growth past that can reverse triangles there, inside the range of the edit itself. Invalid edits produce NaN triangles; derivatives there are undefined. Values and gradients carry discretization error and depend on the deflection.

center_of_mass(radii, center_shifts=None)

Uniform-density mesh center of mass in external coordinates.

is_valid(radii, center_shifts=None)

Check the edit bounds and the mesh orientation.

surface_area(radii, center_shifts=None)

Mesh surface area in input length units squared.

triangles(radii, center_shifts=None)

Return external-coordinate triangles, or NaNs for invalid edits.

volume(radii, center_shifts=None)

Signed mesh volume in input length units cubed.

working_triangles(radii, center_shifts=None)

Return normalized triangles; both parameters still use input units.

prepare_hole_mesh(edit, *, deflection=0.001)

Build the frozen watertight mesh of a prepared hole edit.

deflection is an absolute WORKING-unit meshing tolerance, finite and positive. Meshing accuracy is not certified.

Raises ValueError for an invalid deflection, a mesh that cannot be welded into a closed oriented surface, incident faces whose mesh nodes disagree by more than twice the shape's CAD tolerance (WatertightMesh.max_gap), or degenerate reference geometry. Unsupported surface evaluators raise NotImplementedError. The prepared edit stays usable after any of these.

Example

import jax from brepax.experimental.applications.hole_edit import prepare_hole_edit from brepax.io.step import read_step jax.config.update("jax_enable_x64", True) edit = prepare_hole_edit(read_step("plate_with_holes.step")) mesh = prepare_hole_mesh(edit, deflection=0.0005) triangles = mesh.triangles(edit.model.reference_radii)

STEP planar face offsets

recognize_face_offsets finds planar faces of a supplied B-Rep that can move along their outward normals, and prepare_face_offset turns selected faces into a JAX model of exact volume and center-of-mass laws. The host rebuild method sweeps each face by its offset, fuses or cuts the swept prism in OCCT, and validates the result against the same laws.

import jax
import jax.numpy as jnp

from brepax.experimental.applications.face_offset import (
    prepare_face_offset,
    recognize_face_offsets,
)
from brepax.io.step import read_step

jax.config.update("jax_enable_x64", True)
shape = read_step("part.step")
faces, rejected = recognize_face_offsets(shape)
face = faces[0]
edit = prepare_face_offset(shape, [face.face_id])
offsets = jnp.array([face.upper / 2])
volume, gradient = jax.value_and_grad(edit.model.volume)(offsets)
center = edit.model.center_of_mass(offsets)
edited_shape = edit.rebuild(offsets)

Contract and limits

  • A face qualifies when it is planar with a single boundary loop and every neighbor is a perpendicular plane or a cylinder whose axis runs along the face normal. Faces with inner loops, drafted or filleted neighbors, and other neighbor types are reported in rejected with a reason.
  • Each face gets a closed interval [lower, upper] (input units, positive outward) that ends before the first event: the swept face meeting other material, leaving the solid, or running past the far end of a neighbor. Intervals come from bounding boxes of OCCT Boolean results, so they can only be shorter than the true range, and they keep a margin of 10 CAD tolerances. Travel is capped at twice the part size. A face whose Boolean already disagrees with the law at a tiny offset is rejected.
  • Within the intervals, volume is V0 + sum(area * offset) and each face adds area * offset * (centroid + normal * offset / 2) to the first moment. These laws are exact for the represented faces; outside the intervals the model returns NaN and rebuild raises. Model methods support jit, vmap and differentiation.
  • Selected faces must be independent: not adjacent, and with disjoint boxes around their full swept ranges. Coupled moves, such as two faces sharing an edge, are out of scope.
  • rebuild checks whole-solid volume and first moment first. If those miss the law, a box around each swept slab decides: inside it, the change must match the law within the CAD tolerance; outside it, volume and first moment may change by at most 1e-7 relative. A Boolean can rebuild faces far from the edit, so the edited CAD can differ there by that much. Same-domain faces of the result are unified, so face IDs change.
  • Recognition sweeps and probes every candidate in OCCT and can take seconds per face on large parts. frame and merge_same_domain behave as in prepare_hole_edit.

See ADR-0023 for the scope decision.

brepax.experimental.applications.face_offset

Offset planar faces of an imported solid along their outward normals.

A recognized face moves as a rigid plane between conservative event bounds. Within those bounds the volume and first moment are exact polynomials in the offsets, and each edit can be rebuilt and validated in OCCT. Topology changes, drafted or filleted neighbors, and faces with inner loops are out of scope.

PreparedFaceOffset dataclass

Host result with the selected faces, the frame and the JAX model.

faces are ordered like the offset vector and use input units.

rebuild(offsets)

Rebuild the offsets in OCCT and restore external coordinates.

This host operation is not differentiable. Raises ValueError for an invalid offset vector and RuntimeError when OCCT fails or the result disagrees with the slab law. Same-domain faces of the result are unified, so face IDs of the rebuilt solid differ from the input's.

FaceOffsetModel

Bases: Module

Exact volume and first-moment laws of independent planar face offsets.

Each method takes offsets in input length units, one per selected face, positive outward. Within lower <= offsets <= upper the volume is V0 + sum(area * offset) and the first moment adds area * offset * (centroid + normal * offset / 2) per face; these hold exactly for the represented faces, up to the CAD tolerance of the prepared solid. Outside the bounds the methods return NaN. Methods support jit, vmap and differentiation; the validity predicate supports jit and vmap. Under positive unit scaling s, volume scales by s**3 and its offset gradient by s**2.

center_of_mass(offsets)

Uniform-density center of mass in external coordinates.

is_valid(offsets)

Check that every offset is finite and inside its interval.

volume(offsets)

Solid volume in input length units cubed.

PlanarFace dataclass

A planar face that can move along its outward normal.

Lengths are in the units of the shape the record was made from. lower <= 0 <= upper bound the offset; area, centroid and perimeter describe the face before the move.

RejectedFace dataclass

recognize_face_offsets(shape, *, frame=None, merge_same_domain=False)

Find the planar faces of one solid that can be offset.

Returns recognized faces in input units and rejected planar faces with a reason; non-planar faces are reported as "not planar". Recognition sweeps and probes each candidate in OCCT and can take seconds per face on large parts. frame and merge_same_domain behave as in :func:prepare_face_offset, and face IDs refer to the same solid.

prepare_face_offset(shape, face_ids, *, frame=None, merge_same_domain=False)

Prepare offsets of selected planar faces of one solid.

Accepts a B-Rep returned by read_step. Each selected face must be planar with one boundary loop, and every neighbor must be a perpendicular plane or a cylinder whose axis runs along the face normal. Each face gets a closed offset interval that ends before the first event: the swept face meeting other material, leaving the solid, or running past the end of a neighbor. Intervals are derived conservatively from bounding boxes of OCCT Boolean results, keep a margin of 10 CAD tolerances, and are capped at twice the part size. A face whose Boolean already disagrees with the law at a tiny offset is rejected.

Selected faces must be pairwise independent: not adjacent, and with disjoint boxes around their full swept ranges. Offsets of such faces add up exactly; coupled moves are out of scope.

frame and merge_same_domain behave as in prepare_hole_edit: with merge_same_domain=True, face IDs refer to the unified working solid, so take them from :func:recognize_face_offsets with the same setting. Requires JAX x64.

Raises ValueError for invalid CAD, duplicate or unsupported selections, or interacting faces.

Example

import jax from brepax.io.step import read_step jax.config.update("jax_enable_x64", True) shape = read_step("bracket.step") faces, _ = recognize_face_offsets(shape) edit = prepare_face_offset(shape, [faces[0].face_id]) offsets = jax.numpy.array([faces[0].upper / 2]) volume, gradient = jax.value_and_grad(edit.model.volume)(offsets) edited_cad = edit.rebuild(offsets)

Certified minimal dimension changes

minimal_volume_change asks for the cheapest weighted change of dimension handles that brings the volume change into a band. It returns a rechecked witness, a proof that no handle values in the box reach the band, or an explicitly unresolved result. Handles come from prepared through-holes (radius) and planar faces (offset).

import jax
import jax.numpy as jnp

from brepax.experimental.applications.dimension_query import (
    face_offset_laws,
    minimal_volume_change,
)
from brepax.experimental.applications.face_offset import (
    prepare_face_offset,
    recognize_face_offsets,
)
from brepax.io.step import read_step

jax.config.update("jax_enable_x64", True)
shape = read_step("part.step")
faces, _ = recognize_face_offsets(shape)
edit = prepare_face_offset(shape, [faces[0].face_id, faces[1].face_id])
volume = float(edit.model.volume(jnp.zeros(2)))
result = minimal_volume_change(
    face_offset_laws(edit), (-0.02 * volume, -0.015 * volume)
)
if result.status == "optimal_within_tolerance":
    edited_shape = edit.rebuild(jnp.array(result.values))

Holes and minimum ligaments

hole_ligament_constraints gives the radius laws together with a TravelLimit for each pair of selected holes that could otherwise meet. Pass both: radius intervals alone admit holes that would touch. Without a minimum, the allowed values are the radii is_valid accepts, so walls can come down to the contact margin. With minimum_ligament, each radius interval also narrows by its distance to fixed faces, and any allowed values keep ligament_bounds at or above it:

from brepax.experimental.applications.dimension_query import (
    hole_ligament_constraints,
    minimal_volume_change,
)
from brepax.experimental.applications.hole_edit import prepare_hole_edit

edit = prepare_hole_edit(shape)
laws, limits = hole_ligament_constraints(edit, minimum_ligament=3.0)
result = minimal_volume_change(
    laws, (-0.02 * volume, -0.015 * volume), travel_limits=limits
)

Infeasibility then concerns the bound, which can be stricter than the geometry where a hole shrinks or moves. Without a minimum, shrinking a hole does not count as travel, because it cannot bring two holes into contact. Minimum-edge-distance rules stated as a fixed length fit this form. Rules stated along a load direction need that direction, which a B-Rep does not carry, and are not represented.

Contract and limits

  • Each handle contributes an exact univariate law: area * offset for a face and -pi * height * (r**2 - r0**2) for a hole radius. The coefficients are the prepared measurements, converted exactly to rationals; pi is enclosed between rationals 1e-40 apart. Results certify this represented model, not the source CAD; rebuild and validate a witness before using it.
  • The cost is sum(weight * abs(value - reference)), with every handle kept in its prepared interval. Laws must be monotone on their intervals.
  • optimal_within_tolerance: values is a float vector whose volume change, evaluated exactly for every pi in the enclosure, lies in the band, and lower_bound bounds the cost of every handle vector in the box that satisfies travel_limits and reaches the band. Lower bounds come from exact convex hulls of each handle's (volume, cost) curve.
  • infeasible: no handle values in the box that satisfy travel_limits reach the band. reachable encloses the range of the volume change over the box, exact up to the pi enclosure, and ignores travel limits.
  • unresolved: the node budget ran out. lower_bound still holds, and values is the best witness found, if any.
  • A minimal witness usually lies on an edge of the band. The rebuilt CAD matches the law only within the rebuild's validation bound, which grows with the CAD tolerance, so its measured volume can fall just outside the band. On occt_linkrods (tolerance 3.3e-3), a hole witness on the band edge rebuilt just outside it. When the rebuilt part itself must be in the band, query a band narrowed by that allowance.
  • Volume and hole ligaments are constrained. Center-of-mass targets, hole center shifts and handles of different prepared edits rebuilt together are not supported yet.

brepax.experimental.applications.dimension_query

Certified minimal changes of dimension handles that reach a volume band.

Each handle contributes an exact univariate volume law in its own value. Holes contribute -pi * height * (r**2 - r0**2) and planar faces area * offset. Because the laws add up, the reachable volume over the handle box is exact, and the cheapest weighted change reaching a band is found by branch and bound with exact rational lower bounds. The certificate applies to the represented laws, whose coefficients are the prepared measurements; only a validated rebuild connects a witness to edited CAD.

DimensionQueryResult dataclass

Outcome of :func:minimal_volume_change.

optimal_within_tolerance: values reach the band for every value of pi in the enclosure, and no handle values in the box reach it with a weighted change below lower_bound, which is within tolerance of change. infeasible: no handle values in the box satisfying the travel limits reach the band. reachable is the exact range of the volume change over the box, widened by the pi enclosure and ignoring travel limits. unresolved: the node budget ran out; values is the best witness found, if any, and lower_bound still bounds every solution.

DimensionLaw dataclass

Exact volume contribution of one handle as a function of its value.

The contribution is r(x) - r(x0) + pi * (q(x) - q(x0)) with r and q given by rational and pi_coefficients (constant, linear, quadratic). It must be monotone on [lower, upper]. Lengths and volumes use the input CAD's units; weight scales the cost weight * abs(x - reference).

TravelLimit dataclass

Limit on the summed absolute change of two handles named by label.

abs(x - reference) of first plus that of second must not exceed limit. Two edited holes keep a ligament this way, because their walls approach by at most their combined travel. With increases_only, a handle below its reference counts as no travel: two holes cannot touch by shrinking.

minimal_volume_change(laws, volume_change, *, travel_limits=(), tolerance=None, max_nodes=10000)

Find the cheapest weighted change of handle values reaching a volume band.

volume_change is the band [low, high] for the summed volume contributions, in input units cubed. The cost is sum(weight * abs(x - reference)) over handles, each kept in its [lower, upper]. A witness is a float vector checked exactly against the band for every pi in the enclosure. Lower bounds come from exact convex hulls of each handle's (volume, cost) curve, so the returned lower bound holds for every handle vector in the box. tolerance is the accepted absolute gap between witness cost and lower bound; it defaults to 1e-9 times the total weighted interval width.

travel_limits couple pairs of handles. A witness satisfies them exactly, and lower bounds and infeasibility hold over the handle vectors that do. Closing the gap on an active limit takes more nodes, so it can end unresolved within max_nodes.

A minimal witness usually lies on an edge of the band, and rebuilt CAD matches the law only within its validation bound; narrow the band by that allowance when the rebuilt part itself must lie in it.

Raises ValueError for an empty or inverted band, a law that is not monotone on its interval, a reference outside its interval, or a travel limit that is negative, names one handle twice, or names a label that does not identify exactly one law.

face_offset_laws(edit, weights=None)

Volume laws area * offset of a prepared face offset, in input units.

hole_ligament_constraints(edit, minimum_ligament=None, weights=None)

Hole radius laws and travel limits for :func:minimal_volume_change.

Radius intervals alone admit holes that would meet, so pass both results. Each pair of selected holes that could otherwise come too close gets a :class:TravelLimit.

By default the allowed values are exactly the radii is_valid accepts: they keep the laws true, with walls down to the model's contact_margin. Shrinking a hole is then free, since it cannot bring two holes into contact.

With minimum_ligament, in input units, any allowed values also keep the ligament bound at or above it in exact arithmetic; evaluating HoleEditModel.ligament_bounds in floats can round it by an ulp. Each radius interval narrows by its distance to fixed faces, and shrinking counts as travel, as it does in that bound. Infeasibility then concerns the bound, which is conservative except where a hole grows toward a radially closest feature.

Raises ValueError for a negative minimum, or one a hole's bound already violates at its reference radius.

Circular cut crossing a plate edge

brepax.experimental.contact evaluates the remaining volume of a rectangular plate after a perpendicular circular through-cut, including the transition from an enclosed hole to an open notch. It integrates the analytic boundary and differentiates that same continuous volume. It does not accept arbitrary STEP input or rebuild a solid; the imported-hole API above retains its clearance constraints.

Use a source checkout containing this experimental module for the example and benchmark below.

import jax
import jax.numpy as jnp

from brepax.experimental.contact import plate_with_hole_volume

jax.config.update("jax_enable_x64", True)
center = jnp.array([1.5, 0.2])
half_extents = jnp.array([3.0, 2.0])
height = jnp.array(2.0)

def volume(radius):
    return plate_with_hole_volume(center, radius, half_extents, height)

# First contact is at radius 1.5; 1.7 opens the right edge.
value, derivative = jax.jit(jax.value_and_grad(volume))(jnp.array(1.7))

Use one length unit and local plate coordinates. All parameters support first derivatives; exact contact can have a smooth volume even when the solid's boundary pinches and its mesh is not closed. Moving a fully enclosed hole's center at fixed radius correctly has zero volume derivative. See ADR-0022 for the scope, numerical limitations, and comparison requirements.

Run the independent geometry and estimator comparison from a checkout:

uv run --group benchmark python -m benchmarks.contact_transition.run --cad --output /tmp/contact.json

The output retains failed cases, all declared smoothing choices, finite-difference steps, fresh OCCT and mesh checks, and synchronized execution costs. Ordinary AD of the same analytic primal is included. These bounded comparisons do not establish a general advantage over ordinary AD or arbitrary CAD support.

brepax.experimental.contact

Analytic area and first shape derivatives for a circular cut in a rectangle.

This limited experiment uses Green's theorem and boundary flux, not a sampled indicator or a correction to a future contact event. It does not edit a B-Rep.

circle_rectangle_intersection_area(center, radius, half_extents)

Area of a disk intersected with a centered, axis-aligned rectangle.

All inputs use one length unit. center is in the rectangle's local frame; radius and both half_extents must be positive and finite. Invalid numerical inputs return NaN for the value and first derivatives. Use floating JAX arrays of matching dtype; x64 is recommended near contact.

Supports jit, vmap, JVP and reverse-mode first derivatives in all arguments, including at circle/edge and circle/corner contacts (C1). The custom JVP integrates normal boundary velocity for the same continuous area as the primal. It avoids differentiating singular arc endpoints whose contributions cancel and arbitrary AD conventions at tied sorted endpoints. Only first derivatives are part of this contract; second derivatives may not exist at contact.

Scaling all lengths by s>0 scales area by s**2 and length derivatives by s. The local frame must move with the rectangle under rigid transformations. Tiny remaining areas and extreme radius/rectangle ratios can lose relative floating-point accuracy; this is not a general robust Boolean kernel.

Example::

area = circle_rectangle_intersection_area(
    jnp.array([1.5, 0.2]), jnp.array(1.8), jnp.array([3.0, 2.0])
)

plate_with_hole_volume(center, radius, half_extents, height)

Remaining volume after a perpendicular circular through-cut in a plate.

The stock is [-bx,bx] x [-by,by] x [0,height]; the cutter spans its full height. The cut may open through edges or corners, unlike bounded fixed-topology hole editing. This function evaluates a scalar; it does not regenerate CAD or accept arbitrary STEP geometry.

Inputs are floating JAX arrays in one length unit. Positive finite sizes are required; invalid inputs produce NaN values and first derivatives. First differentiation in all arguments and JAX transformations follow circle_rectangle_intersection_area. Volume scales as length cubed and length derivatives as length squared. Interior center motion correctly has zero volume derivative. Near total stock removal, subtraction limits relative accuracy of the remaining volume.

Example::

radius = jnp.array(1.8)
objective = lambda r: plate_with_hole_volume(
    jnp.array([1.5, 0.2]), r, jnp.array([3.0, 2.0]), jnp.array(2.0)
)
volume, dvolume_dr = jax.value_and_grad(objective)(radius)

Opposing planar face contact

brepax.experimental.planar_contact evaluates how intersection volume starts changing when two solids move from a known opposing planar contact. It takes a convex contact polygon and a translation/rotation direction. Unlike the circular-cut example, this is a one-sided directional response, generally nonlinear in direction, with no single gradient representing every motion.

import jax
import jax.numpy as jnp

from brepax.experimental.planar_contact import (
    planar_contact_volume_direction,
    prepare_planar_contact_patch,
)

jax.config.update("jax_enable_x64", True)
patch = prepare_planar_contact_patch(
    [[-1, -1], [1, -1], [1, 1], [-1, 1]],
    origin=[0, 0, 0], basis=[[1, 0], [0, 1], [0, 0]],
)
tilts = jnp.array([[1.0, 0, 0], [-1.0, 0, 0]])
response = jax.jit(jax.vmap(
    lambda omega: planar_contact_volume_direction(
        patch, jnp.zeros(3), omega, jnp.zeros(3)
    )
))(tilts)
# Both tilts create overlap: response == [1, 1].

The plane normal is the cross product of the basis columns, outward from the fixed solid. Inputs use one length unit; translation is length per unit of the dimensionless path parameter and rotation is radians per unit parameter. Transform both velocities and the pivot with the geometry under proper rigid motion. Scaling lengths and translation by s scales the response by s**3. Changing the pivot requires the compensating translation documented by the API. Preparation is host-only and requires x64; queries support jit and vmap with a fixed polygon size. Differentiating a response query does not produce the gradient of Boolean volume at contact.

For actual CAD inputs, prepare_planar_contact_reference in brepax.experimental.planar_contact_cad takes two solids and explicit face IDs. It checks finite convex polyhedra with straight-edged, single-wire planar faces and unique opposing supports. Its required mode distinguishes "zero_residual" from "projected_nominal". Both return a nominal support polygon, with the source gaps, normal residuals, and tolerances retained in prepared.diagnostics; neither certifies exact source contact nor repairs the solids. Even a positive gap below OCCT tolerance changes the derivative. Curved or holed faces, initial overlap, additional contact patches, and general nonconvex CAD are outside this selected-face preparation contract. The collection API below handles the separate case of explicitly supplied convex cells.

Run the grouped estimator comparison and fresh CAD direction-selection example:

uv run --group benchmark python -m benchmarks.face_contact.run --output /tmp/face-contact.json

The same finite motion candidates and action step are evaluated with actual CAD volumes. Results include calibration choices, five geometry-group splits, ablations, setup/runtime costs, and unsupported or unresolved cases. A good infinitesimal direction does not certify a finite edit; tiny CAD wedges can fall below OCCT resolution. This experiment does not add a generic optimizer, contact detector, or arbitrary STEP topology-editing API. See ADR-0022 for the decision and the directional derivation.

brepax.experimental.planar_contact

One-sided volume responses from supplied opposing planar contact patches.

This is a nonlinear function of a supplied rigid-motion direction, not a custom JVP of Boolean volume or a detector of contact in arbitrary geometry.

PlanarContactPatch

Bases: Module

Convex contact polygon in an oriented orthonormal plane frame.

Create with :func:prepare_planar_contact_patch outside JAX tracing. vertices are counterclockwise local coordinates without a repeated closing vertex. origin + basis @ vertex gives a world point; the cross product of the basis columns points outward from the fixed solid toward the moving solid. Geometry uses a single length unit.

The record contains no solids and cannot certify contact or isolation. Keep it fixed when querying motions. Polygon size is static under JIT; vmap over directions does not require padding or changing this size.

PlanarContactSet

Bases: Module

Packed contact triangles with a fixed capacity and padding mask.

Create with :func:prepare_planar_contact_set outside JAX tracing. Each active row stores one triangle in a patch's local plane coordinates, together with that plane's origin and oriented orthonormal basis. Keeping local coordinates avoids constructing large world-space triangle vertices. The leading dimension is static under JIT; inactive rows contribute zero.

This record carries supplied geometry, not proof that its patches form a complete, nonoverlapping physical contact set. Keep it fixed when querying motion directions. Its arrays are not a differentiable CAD construction.

prepare_planar_contact_patch(vertices, *, origin, basis)

Validate a convex local polygon and its world frame on the host.

Requires JAX x64. Raises ValueError for nonfinite/malformed inputs, repeated edges, nonpositive area, nonconvexity, or a nonorthonormal frame. Polygon half-plane checks reject negative orientations, including those within roundoff: accepting an uncertain negative sign can admit a thin self-crossing polygon. This conservative check may reject nearly collinear input after a coordinate transform. Frame checks use 64 float64 epsilons as a dimensionless roundoff allowance. This checks represented geometry, not the existence of a physical contact. No vertex is snapped or removed. Near-degenerate or extremely large local coordinates can lose precision and should be recentered by the caller.

planar_contact_volume_direction(patch, linear_velocity, angular_velocity, pivot)

Positive one-sided derivative of intersection volume at planar contact.

The initial interiors must be disjoint, with one isolated opposing contact polygon and positive solid thickness on both sides. For the moving body's path pivot + exp(t*[angular_velocity]_cross) @ (x-pivot) + t*linear_velocity, this returns the integral of max(-normal dot (linear_velocity + angular_velocity cross (x-pivot)), 0). It measures the limit as t decreases to zero from above. A positive gap, existing overlap, or an omitted positive-area contact changes that target.

Supports jit and vmap over supplied finite directions with a fixed patch. This map is nonlinear in direction; it is not an ordinary JVP of volume. Differentiating this function would differentiate the response model, not the underlying Boolean volume. No derivative of this response map is part of the contract. Invalid motion components return NaN.

With dimensionless t, linear velocity uses length units, angular velocity radians, and the result volume units. Proper rigid transformations must also transform the frame, pivot, and both velocities. Scaling all lengths and linear velocity by s>0 scales the result by s**3. Changing pivot to p' requires v' = v + angular_velocity cross (p'-pivot) for the same instantaneous motion direction (finite paths can differ at second order). For rigid bodies, union and fixed-minus-moving volume responses have the opposite sign. Finite edits still require an independent volume check.

Uses exact affine integration over a triangle fan in float64. Very small caps, extreme scales, or cancellation in the represented velocity field can lose relative accuracy; no arbitrary-precision guarantee is made.

Example::

jax.config.update("jax_enable_x64", True)
patch = prepare_planar_contact_patch(
    [[-1, -1], [1, -1], [1, 1], [-1, 1]],
    origin=[0, 0, 0], basis=[[1, 0], [0, 1], [0, 0]],
)
# Opposite tilts both create overlap: each response is 1.
value = jax.jit(planar_contact_volume_direction)(
    patch, jnp.zeros(3), jnp.array([1.0, 0, 0]), jnp.zeros(3)
)

prepare_planar_contact_set(patches, *, capacity=None)

Validate and pack supplied patches into masked triangle arrays.

Requires JAX x64 and validates each patch using :func:prepare_planar_contact_patch. capacity counts triangles, not patches. Its default is the sum of len(vertices)-2 over the patches; a larger capacity pads with inactive rows. An empty input is allowed and has zero default capacity. Raises ValueError for a negative/noninteger capacity, insufficient capacity, or an invalid patch.

Patch interiors must be disjoint as surface regions and the collection must include every positive-area contact relevant to the requested volume response. These geometric conditions are the caller's responsibility: this function neither detects overlaps nor removes duplicates. Repeating a patch counts its contribution twice. Edge-sharing partitions are valid. All patches must use one length unit and outward normals from the same fixed body toward the same moving body.

planar_contact_set_volume_direction(contacts, linear_velocity, angular_velocity, pivot)

Sum positive one-sided overlap responses over supplied contact patches.

Every active triangle integrates the positive normal approach speed for the common rigid motion specified by linear_velocity, angular_velocity and pivot. For two finite polyhedral bodies with initially disjoint interiors, this is the intersection-volume derivative when the supplied patches cover all positive-area opposing contacts once and the solids have positive thickness there. Contacts may share edges. Omitted or duplicated patches invalidate the full-body interpretation. Gapped, edge-only and point-only polyhedral contacts contribute no first order volume, but can contribute to a finite edit. A zero response is not a collision-free certificate; independently check every finite edit.

Supports jit and vmap over directions and equally padded sets. Empty sets return zero for finite motions. Nonfinite motion or pivot components return NaN, including for an empty set. Uses the same stable affine triangle integration as :func:planar_contact_volume_direction, with the same floating-point limits. Accumulation over many triangles can introduce additional summation error.

Units, rigid covariance, cubic length scaling and compensated-pivot laws match :func:planar_contact_volume_direction. This is a nonlinear map of the supplied direction, not an ordinary JVP. No derivative of this map or of the packed geometry is part of the contract.

Example::

unit_square = [[0, 0], [1, 0], [1, 1], [0, 1]]
floor = prepare_planar_contact_patch(
    unit_square, origin=[0, 0, 0], basis=[[1, 0], [0, 1], [0, 0]]
)
wall = prepare_planar_contact_patch(
    unit_square, origin=[0, 0, 0], basis=[[0, 0], [1, 0], [0, 1]]
)
contacts = prepare_planar_contact_set((floor, wall), capacity=8)
# Into both walls: each unit-area patch contributes one.
response = planar_contact_set_volume_direction(
    contacts, jnp.array([-1.0, 0, -1]), jnp.zeros(3), jnp.zeros(3)
)  # 2.0

brepax.experimental.planar_contact_cad

Host preparation of a nominal contact patch from selected planar CAD faces.

This module prepares a planar contact model, not an exact-contact certificate or a repaired B-Rep. Source gaps and numerical residuals remain visible.

PreparedPlanarContact dataclass

Numerical reference patch and host-only source diagnostics.

PlanarContactDiagnostics dataclass

Source-CAD evidence, in input length units unless dimensionless.

plane_distance_range contains signed moving-vertex distances from the fixed plane, whose outward normal points towards the moving solid. signed_plane_gap uses the underlying plane origins. With imperfect opposition there is no single gap, so both quantities are retained. Normal residual is dimensionless. Bounds concern floating-point geometric consistency and never replace a nonzero gap by exact source contact.

prepare_planar_contact_reference(fixed_shape, moving_shape, *, fixed_face_id, moving_face_id, mode)

Prepare explicitly selected convex support polygons on the fixed plane.

Both inputs must be valid finite convex polyhedral solids with planar, convex, single-wire faces and straight edges. Face IDs index the current TopExp_Explorer(shape, TopAbs_FACE) order; rebuilding CAD can change IDs. The selected faces must oppose, be the unique faces on their support planes, and have positive-area overlap after projection. Whole-solid checks exclude competing contacts outside this convex supporting model.

mode is required. "zero_residual" rejects every computed nonzero plane or normal-opposition residual. "projected_nominal" permits only roundoff-sized residuals and explicitly projects the moving support polygon onto the fixed plane. Both return the projected support-polygon reference, not a repaired solid or a certified derivative of the original CAD. Even a positive source gap below either OCCT tolerance or roundoff has a different contact derivative; inspect the returned diagnostics and establish actual contact independently before applying the reference law to source CAD.

Lengths retain input units; linear velocities and pivots passed to the evaluator must use these units. Preparation requires JAX x64 and runs on the host. The resulting patch supports the numerical evaluator's JAX transformations. Rigid placement and positive unit scaling preserve the reference geometry up to extraction roundoff. Extreme origin/feature conditioning can fail the consistency checks instead of being snapped.

Raises ValueError for unsupported geometry, selection, residuals, or mode. No contact search, face healing, or original-solid modification occurs.

Example, given two known contacting boxes and their selected face IDs::

prepared = prepare_planar_contact_reference(
    fixed, moving, fixed_face_id=5, moving_face_id=4,
    mode="zero_residual",
)
rate = planar_contact_volume_direction(
    prepared.patch, velocity, angular_velocity, pivot,
)

Multiple contacts from convex cells

prepare_planar_contact_set_reference accepts finite lists of convex polyhedral CAD cells for the fixed and moving bodies. The moving cells share one rigid motion. It checks every within-body and cross-body pair; same-body cell interiors must be disjoint, and initial cross-body overlap is rejected. All positive-area contacts contribute to the packed response. Positive gaps and edge/point contacts remain in the inventory even though their first-order volume response is zero. Shared patch edges are allowed; duplicate cells are not.

For example, a cube approaching the floor and wall of an L-shaped stock has two unit-area contact patches:

import jax
import jax.numpy as jnp

from brepax._occt.backend import BRepPrimAPI_MakeBox, gp_Pnt
from brepax.experimental.planar_contact import planar_contact_set_volume_direction
from brepax.experimental.planar_contact_collection_cad import (
    prepare_planar_contact_set_reference,
)

jax.config.update("jax_enable_x64", True)
fixed = [
    BRepPrimAPI_MakeBox(gp_Pnt(-1, 0, -1), 2, 1, 1).Shape(),
    BRepPrimAPI_MakeBox(gp_Pnt(-1, 0, 0), 1, 1, 1).Shape(),
]
moving = [BRepPrimAPI_MakeBox(gp_Pnt(0, 0, 0), 1, 1, 1).Shape()]
prepared = prepare_planar_contact_set_reference(
    fixed, moving, mode="zero_residual"
)
response = planar_contact_set_volume_direction(
    prepared.contact_set,
    jnp.array([-1.0, 0, -1]), jnp.zeros(3), jnp.zeros(3),
)  # 2.0; the finite overlap is 2*t - t**2 for small positive t.

Preparation requires JAX x64. The packed set supports jit and vmap, with optional triangle capacity and masks when preparing sets directly. Direct numerical preparation only packages the supplied patches; it cannot establish contact completeness or absence of duplicates.

The CAD collection uses represented vertex hulls for pair classification and retains source-plane residuals for its nominal contact polygons. Neither is a certificate for exact source-CAD contact. Unlike selected-face counterfactual projection, this collection never promotes a positive represented gap or interior overlap into touching: gaps stay separated and overlaps are rejected. "projected_nominal" only permits the bounded face-residual preparation after the represented pair is touching. Source faces must own the exact represented support vertices and resolve the same support plane and normal; an unresolved thin patch is rejected rather than replaced by another nearby face. Rotating and re-extracting adjacent cells can introduce tiny represented overlaps and cause conservative rejection. Preparing an explicit design in its working frame and then transforming the contact model is a distinct route; finite CAD must still be checked after actual placement.

The bounded cutter/socket example selects both a direction and a finite amount, then executes an actual stock-minus-cutter Boolean edit:

uv run --group benchmark python -m benchmarks.multi_contact.run \
  --output /tmp/multi-contact.json --step-output /tmp/cutter-edit.step

The report compares target-removal error and fixed-step material removal, including single-patch ablations, sampled estimators, actual CAD differences, and scanning the same finite candidates. It keeps preparation, compilation, query and Boolean costs separate. Common/Cut volume balance and valid shapes check the executed action; they do not imply that a requested target volume was achieved exactly. First-order selection can miss a better finite action. The demonstration STEP assigns millimetres to its generated working lengths and is read back to verify volume and validity; it does not infer input units.

The single-contact benchmark also records three CAD resolution routes: raw external construction, reconstruction from trusted dimensions in an explicit fixed CadFrame, and transformation of an already-built B-Rep. Reconstruction can resolve a small design feature without resolving uncertainty in imported source CAD. A coordinate transform also transforms stored tolerances and is not a substitute for constructing the design in suitable working units.

brepax.experimental.planar_contact_collection_cad

Exhaustive contact preparation for two explicit convex-cell collections.

Cell-pair predicates use convex hulls of represented CAD vertex coordinates. The returned face patches use the selected-face nominal reference contract; neither reference certifies exact contact of the original CAD surfaces.

PreparedPlanarContactSet dataclass

Complete pair inventory and projected patches for represented cells.

Completeness covers the supplied cells only. It does not establish that they form a decomposition of some separately supplied CAD object. Face projection residuals remain visible in patch_sources. Distinct patches may share edges; same-body represented interiors have been checked not to overlap. Empty and lower-dimensional inventories legitimately have zero first-order response, but still require finite-edit CAD verification.

ContactPreparationError

Bases: ValueError

Rejected pair with retained evidence; no partial contact set is returned.

prepare_planar_contact_set_reference(fixed_cells, moving_cells, *, mode)

Prepare all planar contacts between two explicit convex-cell bodies.

Each input cell must satisfy the selected-face preparation's finite convex polyhedral contract. Empty sequences are allowed. The caller supplies the decomposition: this function neither decomposes nonconvex STEP solids nor proves equality to another whole-body shape.

Extraction runs once per cell. Exact integer predicates classify the convex hulls of the binary64 topological vertex coordinates, testing face normals and every nonparallel edge-cross-edge axis without an angular cutoff. Same-body and cross-body interior overlap is rejected even when smaller than OCCT tolerances. Every positive represented gap remains separated, including sub-tolerance gaps. Edge and point contacts remain in the inventory with zero first-order contribution.

Required mode controls face preparation only after represented face contact is established. Each exposed topological vertex set must map uniquely to one source face; its normal and plane must resolve the exact represented support within the stated roundoff bounds. An unresolved small patch cannot fall back to some other nearby source-face pair. zero_residual requires computed-zero plane/opposition residuals. projected_nominal permits roundoff-sized face residuals using the existing projected-support-polygon reference. Unlike the explicitly selected single-patch API, this collection API never projects a represented positive gap or overlap into contact.

Neither mode certifies contact of the source CAD surfaces. Their trimmed planes may differ from the vertex hulls within extraction roundoff; face diagnostics preserve this distinction. A common CAD transform can turn a nominally touching partition into slightly overlapping represented hulls, which is conservatively rejected. Preparing known design-frame cells and transforming the numerical model is a separate operation, not an automatic fallback or proof about transformed source CAD.

Lengths and tolerances use input units. JAX x64 is required. This host-side exhaustive procedure targets small cell collections: hull construction enumerates vertex triples and has O(n**4) worst-case cost per cell. The returned packed set supports the numerical evaluator's jit/vmap contract. No finite collision-free step or Boolean result follows from a zero rate; independently verify every finite edit, including edge/point contacts.

Raises ValueError for unsupported cells, mode or precision, and ContactPreparationError with pair evidence for overlap or unresolved source-face preparation. No partial set or modified CAD is returned.

Example, for a cutter touching a floor and a side wall::

prepared = prepare_planar_contact_set_reference(
    (floor, wall), (cutter,), mode="zero_residual",
)
rate = planar_contact_set_volume_direction(
    prepared.contact_set, velocity, angular_velocity, pivot,
)
# Inspect prepared.cell_pairs and independently verify the finite Cut.

Preserving a supplied placement

brepax.experimental.planar_contact_placement keeps local geometry and a common frame instead of baking a transformation into every vertex. With the local cells from the preceding example:

from brepax.experimental.planar_contact_placement import (
    placed_planar_contact_set_volume_direction,
    prepare_placed_planar_contact_set_reference,
)

placed = prepare_placed_planar_contact_set_reference(
    fixed, moving, rotation=jnp.eye(3), origin=(2, -1, 3),
    length_scale=0.001, mode="zero_residual",
)
rate = placed_planar_contact_set_volume_direction(
    placed.model, jnp.array([-0.001, 0, -0.001]),
    jnp.zeros(3), jnp.array([2.0, -1, 3]),
)  # 2e-9 in world volume units per dimensionless time.

The convention is world = origin + length_scale * rotation @ local. World velocities and pivot are pulled back to the local frame. Diagnostics in local_reference retain local units. A genuine shared proper-rigid top-level OCCT Location can instead be supplied through prepare_located_planar_contact_set_reference; different Location datum chains, reflections and scaled source Locations are rejected. Nested source geometry is preserved. Explicit numerical length scaling remains available separately.

This preserves supplied provenance; it cannot reconstruct a lost frame from flattened STEP vertices. Positive local gaps remain gaps and initial overlap is rejected. original_cad_contact_certified remains false. The response supports jit and vmap over motion directions, not differentiation of the prepared geometry or frame. Finite edits still require actual CAD validation.

brepax.experimental.planar_contact_placement

Preserve supplied local contact geometry under a common world placement.

A placed model refers to the supplied local geometry and its explicit frame. It does not repair, reclassify, or certify a separately flattened world B-Rep.

PlacedPlanarContactSet

Bases: Module

Fixed local contact model with world = origin + scale * R @ local.

Create with :func:place_planar_contact_set. rotation is proper and length_scale gives world length units per local length unit. The model keeps local support coordinates instead of rounding every CAD vertex into world coordinates. Geometry and placement stay fixed during motion queries; differentiating either record is outside the contract.

PreparedPlacedPlanarContactSet dataclass

Placed numerical model and the unmodified local preparation evidence.

All dimensional pair/source diagnostics in local_reference retain local units. provenance distinguishes explicitly supplied local cells from cells whose common top-level CAD Location was retained and removed exactly. Neither provenance proves contact of the original CAD surfaces or of a separately supplied flattened world-coordinate B-Rep.

place_planar_contact_set(local, *, rotation, origin, length_scale=1.0)

Attach an explicit similarity to an already prepared local contact set.

Host validation requires x64, finite origin, a proper orthogonal rotation within 64 binary64 epsilons, and a positive scale whose square is a finite normal binary64 value. The matrix is validated without projection or repair. No geometry, pair relation, or source diagnostic is recomputed. Input arrays are copied; later host mutation does not change the model.

A gap or overlap in the supplied local geometry remains that relation. Supplying the old construction frame beside a flattened B-Rep does not undo its rounded vertex coordinates: prepare the preserved local cells.

placed_planar_contact_set_volume_direction(model, linear_velocity, angular_velocity, pivot)

Return one-sided volume rate for a world-coordinate instantaneous motion.

Linear velocity and pivot use world length units; angular velocity uses radians per dimensionless time. The result is world volume per time. JIT and vmap over supplied directions are supported. Like the local evaluator, this nonlinear response is not an ordinary Boolean-volume JVP.

The pullback is s**3 D(R.T v/s, R.T omega, R.T(p-origin)/s). Positive homogeneity gives the equivalent area-scaled evaluation below, avoiding unnecessary overflow in the cubic multiplier or linear-velocity division. Remaining intermediate overflow and unresolvable world-coordinate differences are not repaired. Keep the pivot near the geometry; a distant origin cannot restore information already rounded out of the supplied pivot.

Compensating a changed pivot preserves this instantaneous response. It does not assert equivalence of finite paths using linearly translated rotations. Zero response does not certify a collision-free finite move.

prepare_placed_planar_contact_set_reference(fixed_local_cells, moving_local_cells, *, rotation, origin, length_scale=1.0, mode)

Prepare preserved local CAD cells and retain their explicit shared frame.

Local cells follow prepare_planar_contact_set_reference unchanged: same-body or initial cross-body overlap is rejected; positive gaps and lower-dimensional contacts remain in the inventory. The caller supplies the local geometry and the frame; this function does not infer either from transformed world geometry. Every finite edit still needs CAD validation.

Example, with existing local stock/cutter cells and a supplied rotation::

prepared = prepare_placed_planar_contact_set_reference(
    stock_cells, cutter_cells, rotation=rotation, origin=(2, -1, 3),
    length_scale=0.001, mode="zero_residual",
)
rate = placed_planar_contact_set_volume_direction(
    prepared.model, world_velocity, world_angular_velocity, world_pivot,
)
# Pair/source diagnostics remain in prepared.local_reference's units.

prepare_located_planar_contact_set_reference(fixed_cells, moving_cells, *, mode)

Use a genuinely shared top-level proper-rigid OCCT Location as provenance.

Every supplied cell must have the same Location datum chain, as compared by OCCT IsEqual. Independently created equal matrices are insufficient. Reflections and nonunit scales beyond frame roundoff are rejected; use explicit local cells and numeric unit metadata for scaled models. At least one non-null cell is required to supply the frame.

Removing this top-level Location leaves the local TShape, orientation and nested geometry unchanged. No inverse transform is baked into vertices. The frame is read from the retained Location, never from a guessed placement or a geometry fit. This is not a general assembly-frame recovery procedure.

An identity Location is allowed and does not recover lost provenance: a flattened input is classified using its existing coordinates and may reject exactly as before. Failures retain the local preparation's pair evidence. The returned model does not certify original source-CAD contact.

Finite polyhedral translation

brepax.experimental.polyhedral_translation prepares the complete finite overlap-volume profile along a prescribed translation. Inputs are convex-cell vertex arrays, not CAD solids. Each body's cell interiors must be disjoint, and the bodies must have no initial interior overlap. Preparation computes rational event times and cubic coefficients from the represented geometry; the JAX evaluator uses floating coefficients. It does not fit CAD samples.

Vertices, velocity components and max_step also accept fractions.Fraction, int, or a decimal or rational str such as "1.2", parsed without binary64 rounding. Rounded decimal dimensions can split a knot that coincides by design into two exact times a few ULP apart. Adjacent pieces with an exactly identical total polynomial are coalesced before packing, so such a split disappears when the total volume does not change across it; distinct events that cannot be packed still raise "no resolvable float64 chamber".

from itertools import product

import jax
import numpy as np

from brepax.experimental.polyhedral_translation import (
    polyhedral_translation_slope,
    polyhedral_translation_volume,
    prepare_polyhedral_translation,
)

jax.config.update("jax_enable_x64", True)
box = np.array(list(product((0.0, 1.0), repeat=3)))
path = prepare_polyhedral_translation(
    [box], [box + (1, 1, 0)], (-1, -1, 0), max_step=2.0,
)
value = jax.jit(polyhedral_translation_volume)(path.profile, 0.25)  # 0.0625
left = polyhedral_translation_slope(path.profile, 1.0, side="left")  # 2
right = polyhedral_translation_slope(path.profile, 1.0, side="right")  # -2

This edge-contact example has zero initial slope, grows quadratically, and then loses overlap after the event at step one. Values have cubic length units; step is dimensionless. jit, vmap over steps and ordinary step AD inside open event intervals are supported. At events use explicit one-sided slopes; geometry and direction differentiation are outside the contract.

The profile's floating thresholds round rational event times upward for binary64 query classification. A threshold need not equal the exact event: path.events retains its rational time and exact left/right slope limits. path.events and path.exact_knots omit coalesced knots. A remaining knot can still be combinatorial for one cell pair when the total volume also changes there. Distinct events without a resolvable floating interval and overflowing or underflowing coefficients are rejected. Out-of-range queries, and slope requests from a side outside the prepared interval, return NaN. Preparation is intended for small convex cells and can be expensive. It does not support rotation or certify that a separate CAD model matches the represented hulls.

uv run --group benchmark python -m benchmarks.multi_contact.translation \
  --output /tmp/translation.json --step-output /tmp/translation-edit.step

The benchmark compares independent interval/section references and actual CAD, checks event slopes, and executes a target-volume Cut on a known monotone translation interval. A separate rotating-prism control shows why the initial velocity field cannot determine higher-order finite terms. See the derivation and path limits.

brepax.experimental.polyhedral_translation

Finite translation-volume profiles for explicit convex-cell bodies.

Host preparation uses exact rational geometry of represented vertices, taken from either binary64 coordinates or exact rational/decimal-string input. The numerical profile supports JAX step queries. This is neither an importer nor a general Boolean JVP: cells and velocity remain fixed after preparation.

PolyhedralTranslationProfile

Bases: Module

Static piece arrays for a fixed pure-translation path.

Create with :func:prepare_polyhedral_translation outside tracing. thresholds round exact event times upward for correct binary64 query classification; they are not generally the actual event times. The mask identifies exactly representable knots. Coefficients use the represented origins and widths, not the unrounded rational event coordinates.

Only the scalar step is an intended differentiation variable. Ordinary AD is supported inside open event chambers, not at a derivative jump. Use the explicit slope query or host event limits at chamber boundaries.

PreparedPolyhedralTranslation dataclass

Exact model diagnostics plus the rounded numerical evaluator.

This certifies only the supplied vertex-hull model. It does not establish correspondence to separately supplied CAD or identify every knot as a physical contact event. Knots between pieces with an exactly identical total polynomial are coalesced; other combinatorial knots can remain.

TranslationEvent dataclass

Exact step and one-sided volume/step limits at an internal chamber knot.

prepare_polyhedral_translation(fixed_cells, moving_cells, velocity, *, max_step)

Prepare exact finite overlap along moving + step * velocity.

Each nonempty body is a list of bounded convex cells. A cell is a float64 array of shape (N, 3) or a nested sequence of exact coordinates. Every hull must have positive volume; same-body interiors and initial cross-body interiors must be disjoint. Face, edge, point contact and positive gaps are retained. max_step is finite and positive. Step is dimensionless; vertices and velocity share a length unit, and output has its cube as the volume unit.

Vertices, velocity components and max_step accept Fraction, int or a decimal/rational str such as "1.2", parsed without binary64 rounding; a plain float keeps its binary64 value. Binary64 rounding of decimal dimensions can split a knot that coincides by design into two exact times too close to pack. Adjacent pieces with an exactly identical total polynomial are coalesced, which removes such a split when the total volume does not change across it; otherwise exact input is needed.

Preparation enumerates exact hull facets and triple-plane intersections; it is intended for small cells, not large meshes. No volume measurements are fitted. No new contacts are omitted within the prepared interval. Rational event times and one-sided limits remain in the host record. Numerically unresolvable intervals or overflowing/underflowing coefficients raise ValueError instead of merging two knots with distinct total polynomials or snapping geometry.

Exact global rigid coordinate changes preserve volume; scaling geometry and velocity by s scales volume and step derivatives by s**3. Independently rounding transformed vertices can change the represented contact state and cause preparation to reject; this law does not certify such rounded inputs or CAD import tolerances. Host preparation does not support shape/velocity AD.

Example::

from itertools import product
import jax
import numpy as np

jax.config.update("jax_enable_x64", True)
box = np.array(list(product((0., 1.), repeat=3)))
prepared = prepare_polyhedral_translation(
    [box], [box + (1., 1., 0.)], (-1., -1., 0.), max_step=2.
)
# Edge contact has zero initial slope but positive finite overlap.
volume = polyhedral_translation_volume(prepared.profile, 0.25)  # 0.0625

Exact-decimal example, placing a design coincidence at one exact knot instead of relying on coalescing a redundant sliver between two knots that binary64 vertices would place a few ULP apart::

from fractions import Fraction
from itertools import product

def box(lo, hi):
    return [tuple(c) for c in product(*zip(lo, hi))]

fixed = [
    box((0, 0, 0), (1, 1, "0.2")),
    box((0, 0, "0.2"), (1, 1, "1.0")),
]
cutter = box(("0.3", "0.3", "1.2"), ("0.7", "0.7", "2.0"))
prepared = prepare_polyhedral_translation(
    fixed, [cutter], (0, 0, Fraction(-1)), max_step="1.5"
)

polyhedral_translation_volume(profile, step)

Evaluate finite overlap, returning NaN outside the prepared interval.

Supports jit/vmap and ordinary step differentiation inside open chambers. The value is continuous at events; its derivative need not be. This evaluates the fixed represented model, not a rebuilt CAD solid.

polyhedral_translation_slope(profile, step, *, side='right')

Return the specified one-sided volume/step derivative.

side is static under jit. At a nonrepresentable rational event, a rounded-up threshold lies strictly after it: both sides there use the following chamber. Exact event limits are in the host events record. Missing interval sides (left at zero, right at max_step), nonfinite steps and out-of-range steps return NaN. Derivatives of this slope are not part of the contract.

Target positions and reachable volume

brepax.experimental.polyhedral_targets uses the retained exact polynomials to find target-volume positions over the entire prepared translation path. It handles multiple roots, roots at extrema, and constant solution intervals. These are host queries; they do not differentiate the root-selection operation.

from itertools import product

import jax
import numpy as np

from brepax.experimental.polyhedral_targets import (
    polyhedral_translation_range,
    polyhedral_translation_targets,
)
from brepax.experimental.polyhedral_translation import prepare_polyhedral_translation

jax.config.update("jax_enable_x64", True)
box = np.array(list(product((0.0, 1.0), repeat=3)))
path = prepare_polyhedral_translation(
    [box], [box + (1, 1, 0)], (-1, -1, 0), max_step=2.0,
)
solutions = polyhedral_translation_targets(
    path, 0.25, step_tolerance=1e-12, volume_tolerance=1e-12,
)
steps = [root.step for root in solutions.roots]  # [0.5, 1.5]
volume_range = polyhedral_translation_range(
    path, step_tolerance=1e-12, volume_tolerance=1e-12,
)
# The maximum volume enclosure is exactly [1, 1].

unreachable means no exact solution exists on this represented path. unresolved means exact solutions exist but some cannot be returned as distinct floating actions meeting the requested tolerances or refinement cap. exact_reachable records existence separately. Root records retain rational isolating bounds and the exact model residual at each proposed float step; constant solution intervals are returned separately. Inspect these outcomes before choosing a position, and verify the actual CAD edit independently.

Exact unreachability does not exclude an edit within a nonzero application error allowance. Root existence, numerical root resolution, and acceptance of an independently checked CAD residual are separate decisions.

Step tolerance is absolute and dimensionless. Volume tolerance has cubic length units and must scale with the target when changing units. A floating target denotes that exact binary64 value; use fractions.Fraction for another exact rational target. Volume-range enclosures are conservative when their refinement is unresolved. They can be computed once for repeated targets; the target solver decides existence directly from the polynomials.

brepax.experimental.polyhedral_targets

Host target inversion and range bounds for exact finite translation profiles.

Existence is decided using rational polynomials, not rounded JAX coefficients or sampled brackets. Float actions are approximate and have separately checked step and volume errors. These results concern the represented vertex-hull path; an actual CAD edit still requires independent validation.

TranslationTargetRoot dataclass

An exact root enclosure and an independently assessed binary64 action.

root_count counts distinct roots, not multiplicity. For a nonpoint unresolved cluster it counts roots strictly between the bounds; endpoint roots appear separately. A resolved nonpoint interval has nonroot endpoints and contains exactly one root. volume_residual is the exact represented path value at step minus the target, not a JAX or source-CAD error bound.

TranslationTargetInterval dataclass

A closed solution interval, with its earliest binary64 member if one exists.

TranslationTargetResult dataclass

Complete exact root inventory, including unresolved numerical actions.

unreachable means no exact solution on the supplied represented path. unresolved means exact solutions exist but one or more cannot be returned as distinct float actions meeting the requested tolerances/refinement cap. This does not certify the correspondence or accuracy of source CAD.

TranslationRangeCandidate dataclass

Knot, stationary-root bracket, or constant interval enclosing extrema.

volume_bounds encloses all values on [lower, upper]. A candidate need not be a local extremum; every global extremum is covered by one.

TranslationVolumeRange dataclass

Rational enclosures of the minimum and maximum on the prepared path.

Each pair brackets one extremal value. Refinement failure leaves conservative enclosures and resolved=False; target existence is assessed separately by :func:polyhedral_translation_targets, without relying on these bounds.

polyhedral_translation_targets(prepared, target, *, step_tolerance, volume_tolerance, max_refinements=128)

Find every target-volume location on a prepared finite translation path.

This host-only query uses the original rational cubics and counts repeated roots once. It retains constant solution intervals and does not assume a monotone path. A float target denotes its exact binary64 value; pass a Fraction for an exact rational target.

step_tolerance is a positive absolute dimensionless position bound; volume_tolerance is a nonnegative absolute error in volume units. Both bounds must hold for a resolved float action. Scale the volume tolerance and target by s**3 when scaling geometry and velocity by s. Preparation's exact-coordinate invariance and rounded-input limitations still apply.

max_refinements caps bisection depth per root interval, not wall time. Existence remains exact when refinement or float separation fails. No derivative of this host selection operation is provided. In particular, target roots at extrema or events need their own sensitivity contract.

Example::

result = polyhedral_translation_targets(
    prepared, 0.2, step_tolerance=1e-12, volume_tolerance=1e-12
)
if result.status == "reachable":
    steps = [root.step for root in result.roots]
    # Validate the chosen step with the actual CAD before editing.

polyhedral_translation_range(prepared, *, step_tolerance, volume_tolerance, max_refinements=128)

Enclose the full attainable volume range without CAD or grid sampling.

Examine every rational knot and every root of each derivative quadratic. step_tolerance bounds stationary-root bracket widths, while volume_tolerance bounds their volume-enclosure widths. Units and limits match :func:polyhedral_translation_targets. A failed refinement retains conservative range bounds; it does not establish target infeasibility.

Compute once for repeated target queries on the same prepared geometry and direction. Returned extrema refer only to this complete represented path.

Design sensitivities along a translation path

brepax.experimental.polyhedral_parameter prepares an affine family of convex vertex cells with fixed facet normals and one or two dimensionless design parameters. Unlike a fixed translation profile, its traced volume evaluation changes the geometry with those parameters. Translation velocity stays fixed.

The following example changes the initial gap and the stock extrusion height. At the reference design the target has two positions; the first is a simple root whose sensitivity can be evaluated inside its event interval.

from itertools import product

import jax
import numpy as np

from brepax.experimental.polyhedral_parameter import (
    AffinePolyhedralCell,
    polyhedral_parameter_position_sensitivity,
    prepare_polyhedral_parameter,
    specialize_polyhedral_parameter,
)
from brepax.experimental.polyhedral_targets import polyhedral_translation_targets

jax.config.update("jax_enable_x64", True)
stock = np.array([
    (x, y, z) for z in (0.0, 1.0)
    for x, y in ((0.0, 0.0), (1.0, 0.0), (1.0, 1.0))
])
stock_changes = np.zeros((2, 6, 3))
stock_changes[1, 3:, 2] = 1.0
tool = np.array(list(product((-0.375, -0.125), (-0.5, 1.5), (-0.5, 1.5))))
tool_changes = np.zeros((2, 8, 3))
tool_changes[0, :, 0] = -1.0
design = prepare_polyhedral_parameter(
    [AffinePolyhedralCell(stock, stock_changes)],
    [AffinePolyhedralCell(tool, tool_changes)],
    (1.0, 0.0, 0.0), max_step=1.5,
)
theta = np.zeros(2)
path = specialize_polyhedral_parameter(design, theta)
solutions = polyhedral_translation_targets(
    path, 15 / 128, step_tolerance=1e-12, volume_tolerance=1e-12,
)
steps = [root.step for root in solutions.roots]  # [23/32, 5/4]
sensitivity = jax.jit(polyhedral_parameter_position_sensitivity)(
    design.model, 23 / 32, theta,
)  # [1, -15/32]: fixed physical target, dimensionless design parameters.

An AffinePolyhedralCell has vertices (N, 3) and parameter displacements (P, N, 3). Its vertex map is affine in theta; vertices, displacement coefficients and velocity share a length unit. Preparation checks the fixed facet-normal assumption and derives sufficient strict linear conditions on theta. These preserve cell validity, disjoint interiors and event ordering; they need not describe the largest valid region. Conflicting event-order changes at the reference design are rejected even if volume itself is smooth.

polyhedral_parameter_volume supports jit, vmap and first-order JVP/reverse derivatives in step and design parameters inside resolved open intervals. Its custom JVP uses the physical derivative polynomials, avoiding cancellation from differentiating rounded moving normalization anchors. Prepared model coefficients are not differentiation variables; higher derivatives are outside the contract. It returns NaN near moving events or parameter boundaries and when value/derivative cancellation or numerical range is unresolved. This can include a mathematically smooth stationary point. That is a limitation of the numerical derivative chart, not a claim that physical volume is undefined. Host specialization checks exact parameter conditions and creates a complete fixed-parameter translation profile with the existing boundary-value, one-sided-slope and target-query contracts. Specialization evaluates the affine represented family; independently rounded new vertices or rebuilt CAD can differ from that model.

The position-sensitivity query computes the local volume-level-set derivative; it does not verify a target residual or select a root. Check the root first. Zero or unresolved slope, event boundaries and branch changes require separate treatment. Supply target_parameter_gradient when the target itself changes with the design. For fixed dimensionless parameters, scaling all lengths by s scales volume and its parameter derivatives by s**3; convert physical length sensitivities by the chain rule. Retain independent CAD validation.

uv run --group benchmark python -m benchmarks.multi_contact.parametric \
  --output /tmp/parametric.json

This benchmark compares finite-profile inversion, first-order proposals and CAD-only search on the same supplied translation paths and ranges. It checks root inventories and path-unreachable targets against independent prism sections, evaluates design sensitivities, and validates actual rebuilt CAD edits. Parameter-volume differences rebuild CAD directly; position differences use specialized roots checked against independent section solutions and rebuilt CAD residuals. Failures and unsupported cases remain in the results. Timings include preparation and attempted CAD operations, but share one process and JAX caches; they are diagnostics rather than isolated cold-start comparisons.

brepax.experimental.polyhedral_parameter

Local design sensitivities for fixed-normal polyhedral translation paths.

Host preparation certifies an open parameter region for represented vertex families. Within that region, JAX differentiates the changing volume rather than a frozen set of polynomial coefficients. Events and their ordering remain explicit; neither this chart nor its derivatives certify original CAD input.

AffinePolyhedralCell dataclass

Bounded convex cell with affine vertex displacements.

vertices has shape (N, 3); parameter_displacements has shape (P, N, 3), with P equal to one or two. At dimensionless parameters theta, vertex i is vertices[i] + sum(theta[p] * displacements[p, i]). Vertices and displacements use the same length unit. Preparation checks fixed facet normals and derives a conservative open validity region.

PolyhedralParameterModel

Bases: Module

Packed changing-volume chart, evaluated only inside resolved chambers.

Prepare on the host with :func:prepare_polyhedral_parameter. Floating event positions are rounded values, not exact contact classifications. Strict guards with roundoff bands reject uncertain parameter/chamber boundaries; use host specialization for exact model event diagnostics.

ParameterTranslationEvent dataclass

Affine combinatorial event; not necessarily a physical contact event.

Its exact step is reference_step + parameter_gradient dot theta. The derivative is valid only in the prepared open parameter region.

PreparedPolyhedralParameter dataclass

Exact parameter certificates and their conservative numerical evaluator.

Each parameter_constraints row is (constant, parameter coefficients) and must be strictly positive. These sufficient conditions need not be the largest valid region. The reference is theta=0. Event-order ties with different affine expressions are unsupported, even if volume is smooth.

prepare_polyhedral_parameter(fixed_cells, moving_cells, velocity, *, max_step)

Prepare a local design chart for a specified finite translation.

Each cell is a bounded, positive-volume vertex hull. Parameters are dimensionless and reference theta=0; there must be one or two shared parameters. Vertex displacements must preserve facet normals exactly for the represented inputs. Same-body interiors and initial cross-body interiors remain disjoint under the returned linear validity conditions. A nonregular reference, including an event tie that splits with theta, raises ValueError. This rejects some otherwise valid volume families.

The moving body follows vertex(theta) + step * velocity for 0 <= step <= max_step. Step is dimensionless; velocity uses the vertex length unit. Geometry and velocity are host inputs; t and theta are the differentiation variables. Preparation enumerates plane triples and is intended for small cells. No CAD observations are fitted.

First JAX derivatives are supported in strict, numerically resolved open chambers. Values at or near a changing event are NaN in that evaluator; specialize on the host for a complete fixed-parameter profile and one-sided slopes. A custom JVP uses exact-derived physical derivative polynomials to avoid cancellation in the moving normalization's floating chain rule. Prepared model arrays are explicitly frozen; only step and theta are differentiated. This separates discrete chart selection from changing-geometry evaluation. Neither an uncertain floating guard nor a source-CAD contact is certified.

Exact global rigid frame changes preserve values and step/parameter derivatives. Scaling vertices, displacements and velocity by s scales all those quantities by s**3, keeping dimensionless theta and step fixed. Independently rounded transformed inputs can change validity or reject. A derivative with respect to a physical length parameter instead has the corresponding chain-rule units.

Example::

from itertools import product
import jax
import numpy as np

jax.config.update("jax_enable_x64", True)
box = np.array(list(product((0., 1.), repeat=3)))
fixed = AffinePolyhedralCell(box, np.zeros((1, 8, 3)))
shift = np.tile(np.array([1., 0., 0.]), (1, 8, 1))
moving = AffinePolyhedralCell(box + (2., 0., 0.), shift)
prepared = prepare_polyhedral_parameter(
    [fixed], [moving], (-1., 0., 0.), max_step=4.
)
# Initial gap grows by theta; the interior overlap is step - 1 - theta.
volume = polyhedral_parameter_volume(prepared.model, 1.5, np.array([0.1]))

specialize_polyhedral_parameter(prepared, parameters)

Substitute theta exactly, yielding an ordinary finite translation profile.

Supplied finite float64 theta values are interpreted as exact rationals. Strict validity guards are checked on the host; invalid parameters raise ValueError. This uses the prepared affine family, not newly rounded vertex coordinates. Existing profile packing may reject unresolved events or underflow. The result supports the usual value, slope and target queries.

polyhedral_parameter_volume(model, step, parameters)

Evaluate volume with live step and design parameters in an open chamber.

Supports jit, vmap and first JVP/reverse derivatives in step and theta. A custom JVP evaluates exact-derived derivatives of the same volume; it avoids cancellation in a floating moving-origin chain rule. Model arrays are frozen, and higher derivatives are outside the contract. Strict linear guards and conservative roundoff bands reject uncertain classification. At/near events, outside the parameter region or step interval, or when a required nonzero value/derivative monomial underflows, or cancellation prevents resolving a value/derivative sum, value and intended derivatives are NaN. This includes some valid interior stationary points. Subnormal query inputs also reject because XLA may flush them before arithmetic. Packing/evaluation is floating arithmetic, not an exact volume oracle. Use :func:specialize_polyhedral_parameter for boundary values and slopes.

polyhedral_parameter_events(model, parameters)

Return rounded affine knots, including zero and max_step.

Supports jit/vmap and parameter AD inside the resolved parameter region. These rounded positions are not exact event classifications. Invalid or roundoff-ambiguous parameters return NaNs; host specialization retains the exact rational event positions. Some knots may be combinatorial only.

polyhedral_parameter_position_sensitivity(model, step, parameters, *, target_parameter_gradient=None)

Differentiate a local volume level set through the supplied position.

Returns (target_parameter_gradient - dV/dtheta) / (dV/dstep). The default holds the physical volume target fixed; an explicit target gradient uses volume per dimensionless parameter. This is not a root finder or a check that step attains a requested target. Verify the root residual separately. The selected root branch must be simple and inside a resolved chamber. Invalid queries, unresolved/zero slopes, and underflow of a nonzero target difference or resulting ratio return NaNs. Equal represented target and volume derivatives retain zero sensitivity. No derivative at extrema, event boundaries or switching between root branches is promised.

One supplied event-order boundary

brepax.experimental.polyhedral_boundary handles one supplied exchange at theta=0 for a single affine design parameter. It requires fixed facet normals and translation velocity, valid bounded cells, disjoint same-body interiors, and no initial cross-body overlap throughout its certified region.

from fractions import Fraction
from itertools import product

import jax
import numpy as np

from brepax.experimental.polyhedral_boundary import (
    polyhedral_event_boundary_response,
    prepare_polyhedral_event_boundary,
    specialize_polyhedral_event_boundary,
)
from brepax.experimental.polyhedral_parameter import AffinePolyhedralCell
from brepax.experimental.polyhedral_targets import polyhedral_translation_targets

jax.config.update("jax_enable_x64", True)
stock = np.array(list(product((0.0, 1.0), repeat=3)))
tool = np.array(list(product((-1.5, -0.5), (-1.0, 2.0), (-1.0, 2.0))))
changes = np.zeros((1, 8, 3))
changes[0, tool[:, 0] == -1.5, 0] = -1.0
boundary = prepare_polyhedral_event_boundary(
    [AffinePolyhedralCell(stock, np.zeros((1, 8, 3)))],
    [AffinePolyhedralCell(tool, changes)], (1.0, 0.0, 0.0),
    max_step=3, parameter_radius=Fraction(1, 8),
)
response = polyhedral_event_boundary_response(boundary, Fraction(3, 2))
# Signed left/right theta derivatives are 1 and 0; no ordinary theta derivative.
path = specialize_polyhedral_event_boundary(boundary, Fraction(1, 8))
solutions = polyhedral_translation_targets(
    path, 1, step_tolerance=1e-12, volume_tolerance=1e-12,
)
# Full-volume solutions form the interval [3/2, 13/8].

parameter_radius selects reference points at -radius and +radius; it is not a tolerance, finite-difference step, or claimed validity bound. Inspect parameter_interval: its outer endpoints are open, zero is included, and None denotes an unbounded endpoint. Preparation rejects references that do not certify exactly one isolated pair of events with the same surrounding inventory. The returned events are stable affine labels, not chronological positions on both sides.

The response query evaluates (step, theta=0) along epsilon * (step_direction, parameter_direction) as epsilon decreases to zero from above. Results are exact Fraction values. The signed left parameter derivative is the negative of the response in direction (0,-1). ordinary_parameter_derivative returns their common value when they agree, or None otherwise; it is not a joint differentiability certificate. Directions exiting the supplied translation interval or inconsistent tangent limits reject.

Preparation and responses are host operations, without jit, vmap or boundary AD. Specialization requires JAX x64 and retains the existing profile packing/target-query limits. All queries preserve supplied Fraction scalars; float scalars denote their exact binary64 values. With dimensionless step and design parameter, scaling geometry, displacement coefficients and velocity by s > 0 scales volume and directional responses by s**3. Exact rigid coordinate changes preserve them; independently rounded inputs can change the certificate. See the directional derivation.

uv run --group benchmark python -m benchmarks.multi_contact.event_boundary \
  --output /tmp/event-boundary.json

For each supplied design dimension, this bounded comparison finds a target position along a prescribed translation path. It compares reuse of a boundary model, rebuilding the exact fixed-dimension profile, and CAD-only search at the same requested accuracy; it does not search for the smallest dimension change. Boolean operations use disposable copies of both inputs so repeated observations preserve source topology and tolerances; copying time is included in CAD cost. Exact target existence and meeting the CAD residual allowance are reported separately. Failed probes and model/source disagreements remain visible even when a selected edit passes its final CAD checks.

brepax.experimental.polyhedral_boundary

Host queries across one supplied polyhedral event-order boundary.

PreparedPolyhedralEventBoundary dataclass

Exact host certificate for an exchange supplied at theta=0.

parameter_interval is open at each finite outer endpoint and includes zero. None denotes an unbounded endpoint. events labels the two affine event functions; their tuple order is not chronological on both sides. No original-CAD contact or rounded transformed input is certified.

PolyhedralBoundaryResponse dataclass

Exact volume and first responses at fixed reference parameter theta=0.

directional_derivative is the right derivative along the supplied (step_direction, parameter_direction), generally nonlinear in direction. The left parameter derivative is the quotient as theta approaches zero from below: it is the negative of the response to direction (0,-1). All fields use volume units per dimensionless step/parameter as applicable.

ordinary_parameter_derivative property

Scalar theta derivative at fixed step, not joint differentiability.

prepare_polyhedral_event_boundary(fixed_cells, moving_cells, velocity, *, max_step, parameter_radius)

Certify two adjacent charts at one supplied event exchange at theta=0.

Cells use one dimensionless affine design parameter, fixed facet normals and fixed translation velocity. Geometry, displacements and velocity share length units; step is dimensionless on [0,max_step]. Positive cell volume, disjoint same-body interiors and initially disjoint cross-body interiors must have strict validity certificates across the returned parameter region.

parameter_radius is a positive exact reference-center choice: prepare regular charts at its negative and positive values. It is not a tolerance, finite-difference increment or claimed domain radius. This function does not discover a boundary or search for suitable centers. Their certified open regions must adjoin at zero, with the same affine event inventory and exactly one isolated pair of distinct event functions meeting inside the path. Other event ties, static feasibility changes, or invalid geometry raise ValueError, even for some physically valid families.

Vertices and displacements denote represented float64 coordinates; centers and queries preserve supplied Fraction values. Rebased cells/planes are exact, without rebuilding rounded center coordinates. Polynomial closures must agree with the fixed-reference geometry. No observations are fitted. This host preparation and its response query are not JAX transformations. Global exact rigid transforms preserve values and responses; scaling all length inputs by s multiplies them by s**3. Independently rounded inputs can change the certificate. The implementation is intended for small cells.

Example::

from fractions import Fraction
from itertools import product
import numpy as np

stock = np.array(list(product((0., 1.), repeat=3)))
cutter = np.array(list(product((-1.5, -.5), (-1., 2.), (-1., 2.))))
shift = np.zeros((1, 8, 3))
shift[0, cutter[:, 0] == -1.5, 0] = -1.
prepared = prepare_polyhedral_event_boundary(
    [AffinePolyhedralCell(stock, np.zeros((1, 8, 3)))],
    [AffinePolyhedralCell(cutter, shift)], (1., 0., 0.),
    max_step=3., parameter_radius=Fraction(1, 8),
)
response = polyhedral_event_boundary_response(prepared, Fraction(3, 2))
assert response.left_parameter_derivative == 1
assert response.right_parameter_derivative == 0

specialize_polyhedral_event_boundary(prepared, parameter)

Build the ordinary finite profile at any certified theta, including zero.

Fraction parameters retain their exact values; floats denote their exact binary64 values. Outer domain endpoints reject. The existing profile uses JAX x64 and may reject unresolved float event packing or coefficient range. Its usual target/range queries apply, including empty, singleton and interval target solution sets. No derivative of target selection is added.

polyhedral_event_boundary_response(prepared, step, *, step_direction=0, parameter_direction=1)

Return exact one-sided volume responses at (step,theta=0).

Direction means (step,theta)=(step,0)+epsilon*(step_direction, parameter_direction) for epsilon approaching zero from above. Tangent event rays require agreement of all incident polynomial limits; directions exiting the translation interval raise ValueError. The direction map can be nonlinear; this is not a JVP, JAX gradient, or derivative of a root set. No higher derivative or general boundary discovery is provided.

brepax.experimental.polyhedral_design.polyhedral_design_target searches a closed parameter interval inside a prepared event-boundary certificate or an automatically continued domain. It chooses a parameter and translation step that meet the target-volume allowance, while bounding how much the absolute change from an initial parameter could still improve. It does not assume a monotone volume or connected feasible set.

Using boundary from the example above:

from brepax.experimental.polyhedral_design import polyhedral_design_target

result = polyhedral_design_target(
    boundary, 1,
    parameter_bounds=(Fraction(-1, 4), Fraction(1, 4)),
    initial_parameter=Fraction(-1, 8),
    parameter_tolerance=1e-4,
    step_tolerance=1e-10,
    volume_tolerance=1e-8,
    max_boxes=256,
)
if result.witness is not None:
    theta, step = result.witness.parameter, result.witness.step
    # Validate this numerical design and edit against actual rebuilt CAD.

For a supplied event-boundary certificate, the parameter bounds must lie strictly inside its open outer endpoints. For continuation, they must lie inside the requested closed preparation window; unconfirmed parts remain in the objective lower bound. Scalar floats denote exact binary64 inputs; use Fraction when an exact rational target or bound matters. volume_tolerance defines the allowed absolute volume residual. status="optimal_within_tolerance" certifies that the gap between the returned change and the best possible change is at most parameter_tolerance; an unresolved result may have a larger gap or no witness. step_tolerance instead controls numerical target-position refinement.

The returned witness is checked at its actual binary64 parameter and step. Its objective supplies an upper bound; unresolved parameter intervals supply a lower bound. A witness can remain useful when the optimality gap is unresolved. An infeasible result requires excluding the entire requested interval; merely finding no witness is not enough. Exact target reachability is distinct from meeting the volume allowance. Isolated feasible points, numerical packing limits and refinement caps can prevent resolution.

This host operation uses the existing x64 profile specialization and its packing limits; it is not a traced optimizer and supplies no selection gradient. The objective measures distance in the supplied parameter coordinate; rescaling that coordinate also rescales the objective and parameter tolerance. With dimensionless parameter and step, rigid coordinate changes preserve feasibility and optimal objective values. Scaling geometry, affine displacements and velocity by s requires target and volume tolerance to scale by s**3. Exact represented-coordinate laws do not certify separately rounded geometry or the accuracy of an OCCT edit. See the bound derivation.

uv run --group benchmark python -m benchmarks.multi_contact.design_search \
  --output /tmp/design-search.json

The bounded comparison searches the design dimension as well as translation. It compares the certified model with complete fixed-profile rebuilding and adaptive CAD observations, with whole-task Boolean and cooperative wall limits. Reports retain proposed model witnesses even when CAD rejects them, independent optimality enclosures, every measured probe, and fresh final Common/Cut checks. The model's optimality certificate and CAD validity are separate findings; sampled baselines do not claim global infeasibility. These constructed tasks are mechanism checks, not evidence of generalization or runtime superiority.

brepax.experimental.polyhedral_design

Bounded design search over certified polyhedral parameter regions.

DesignTargetWitness dataclass

An executable binary64 pair, checked in exact represented-model arithmetic.

DesignTargetResult dataclass

A bounded search certificate, not a complete design-feasibility atlas.

The lower objective bound concerns continuous real parameter/step pairs in the queried closed domain and volume band. The upper bound belongs to the returned binary64 witness, whose volume and residual are exact rational model values. infeasible excludes the entire continuous domain; unresolved retains regions not excluded within the search budget. No status certifies source CAD, an exact central-target root, or a gradient.

optimality_gap property

Certified objective gap when an executable witness is available.

DesignQueryFailure dataclass

A valid exact parameter whose existing numerical profile could not be packed.

polyhedral_design_target(prepared, target, *, parameter_bounds, initial_parameter, parameter_tolerance, step_tolerance, volume_tolerance, max_boxes=256, max_refinements=128)

Minimize design change while finding a target-volume translation action.

For a supplied event boundary, search a finite closed parameter interval strictly inside its open certificate. For automatic continuation, search inside its requested closed domain, retaining uncovered regions. The objective is abs(theta-initial_parameter); the constraint is abs(V(step,theta)-target) <= volume_tolerance. This volume tolerance defines a feasible band, unlike the exact-existence semantics of polyhedral_translation_targets. Both returned coordinates are binary64 values, rechecked as exact rationals against the original band and domain.

Parameters and step are dimensionless; target/tolerance have volume units. Scale both by s**3 when scaling geometry, displacements, and velocity by s. Exact coordinate-frame laws and represented-input limitations of the prepared model apply. This host query is neither JAX-transformable nor a derivative of target selection, and retains existing JAX x64/profile packing requirements. Failed numerical packing remains explicitly recorded.

parameter_tolerance is the allowed objective gap for an optimal_within_tolerance result. step_tolerance controls candidate-root refinement, not a separate feasibility constraint. max_boxes caps examined design intervals and isolated points across all charts; max_refinements caps each existing root-isolation path. Initial candidate queries at domain/chart endpoints are additional work, reported by point_queries. Preparation has its own chart/attempt limits. Fixed range tolerances can leave bound floors; isolated feasible points, unavailable float actions, or exhausted budgets may remain unresolved. No finite-completeness guarantee is made.

Every uncovered region, including an isolated boundary point, contributes its distance from the initial parameter to the global objective lower bound. Incomplete coverage can still certify a gap if all uncovered regions are sufficiently far away; it cannot establish global infeasibility. remaining_intervals contains conservative closed envelopes of regions not excluded, including uncovered ones. Exact coverage membership and stop reasons remain on the prepared continuation, separately from this status.

Example::

result = polyhedral_design_target(
    boundary, 0.2, parameter_bounds=(-0.1, 0.1),
    initial_parameter=0.08, parameter_tolerance=1e-4,
    step_tolerance=1e-10, volume_tolerance=1e-8,
)
if result.witness is not None:
    # Independently validate this model action with the actual CAD.
    theta, step = result.witness.parameter, result.witness.step

Automatic event continuation

brepax.experimental.polyhedral_continuation starts from an ordinary design parameter and discovers isolated exchanges of translation-event order. It retains the same explicit convex cells, one affine design parameter, fixed facet normals and fixed translation velocity as the local parameter model. It does not require event positions or trial radii from the caller.

Using stock, tool, and changes from the event-boundary example above:

from brepax.experimental.polyhedral_continuation import prepare_polyhedral_continuation

coverage = prepare_polyhedral_continuation(
    [AffinePolyhedralCell(stock, np.zeros((1, 8, 3)))],
    [AffinePolyhedralCell(tool, changes)], (1.0, 0.0, 0.0),
    max_step=3,
    parameter_bounds=(Fraction(-1, 4), Fraction(1, 4)),
    seed_parameter=Fraction(-1, 8),
    max_charts=8,
    max_center_trials=8,
)
result = polyhedral_design_target(
    coverage, 1,
    parameter_bounds=coverage.parameter_bounds,
    initial_parameter=Fraction(-1, 8),
    parameter_tolerance=1e-4,
    step_tolerance=1e-10,
    volume_tolerance=1e-8,
)

The original cells at parameter zero must admit fixed-normal preparation, and the seed must admit a regular local chart. A nonregular seed, an unsupported frontier, exhausted chart/refinement budgets, or an event at the requested window endpoint can leave an interval or singleton unconfirmed. This is not a claim that the geometry is invalid or the target unreachable. Preparation retains open chart intervals, separately certified event points, and failure reasons. Exact rational rebasing preserves the original family, including at non-binary event positions; it does not round the shape to create a new family.

The design query uses a single interval budget across the covered regions and retains uncovered regions in its global objective lower bound. A distant unconfirmed region can coexist with optimal_within_tolerance; it cannot be silently dropped to declare whole-window infeasibility. The returned numerical parameter and step are rechecked against the original global model.

Exact volume laws apply on jointly certified inputs, but the current selection of sufficient separating certificates can change the covered region after a coordinate rotation. Coverage, resource-limited status, and the choice among equal-cost numerical edits are not promised to be equivariant. Simultaneous event exchanges, general geometric changes, arbitrary STEP decomposition and gradients of the selected design remain outside this contract. See the continuation argument.

uv run --group benchmark python -m benchmarks.multi_contact.continuation \
  --output /tmp/continuation.json

The comparison uses stepped and oblique geometry mechanisms, with separate unsupported-frontier controls. It supplies no event locations to the automatic method. Reports distinguish the first completed Common observation meeting the volume band, retrospective qualification against the independent design optimum, and fresh final Cut validation. The automatic query finishes before its first CAD observation; no internal candidate is assigned an earlier observation time. Preparation and all attempted operations are charged. These constructed tasks do not establish generalization or a runtime advantage.

brepax.experimental.polyhedral_continuation

Bounded automatic continuation for one affine polyhedral design parameter.

PreparedPolyhedralContinuation dataclass

Covered charts and explicit uncertainty on a closed design window.

A gap is unconfirmed coverage, not invalid geometry or target infeasibility. Boundary parameters are included only after both adjoining chart closures agree with an independently assembled exact fixed-parameter profile.

attempts property

Every seed, trial center and unresolved frontier observation.

boundary_parameters property

Automatically discovered and certified isolated exchange parameters.

chart_count property

Number of accepted regular charts, including the seed when available.

uncovered property

Unconfirmed portions of the query window, retaining endpoint membership.

prepare_polyhedral_continuation(fixed_cells, moving_cells, velocity, *, max_step, parameter_bounds, seed_parameter, max_charts=8, max_center_trials=8)

Discover isolated event exchanges from a regular seed, within a budget.

Supply original float64 vertex cells with one affine, dimensionless design parameter, fixed facet normals and fixed translation velocity. The seed is an ordinary design parameter, not a supplied event or a finite-difference radius. Original cells at theta=0 must admit fixed-normal cell preparation; a nonzero seed does not bypass a nonregular original cell reference. Exact affine guard roots propose frontiers; each accepted transition has one isolated event pair, unchanged event inventory, valid non-event guards and equal exact closures. No rounded rebased vertices are substituted.

The finite closed window must contain the seed. max_charts caps accepted charts including the seed; max_center_trials caps exact rational side centers per frontier. Failed trials remain in attempts. Malformed arrays, nonfinite scalars and invalid bounds/budgets raise ValueError. A family whose seed or next chart cannot be certified instead leaves explicit gaps. No seed search, simultaneous-event handling, or alternative separator search is performed. An event at a window endpoint may remain an uncovered point.

Cell coordinates, displacements and velocity have length units; translation step and parameter are dimensionless. Exact frame changes preserve volume on jointly certified parameters; scaling all lengths by s scales it by s**3. The sufficient separator chosen by existing preparation can depend on the frame: coverage and resolution status are not promised equivariant. Rounded input, source CAD and geometric invalidity are not certified. This host preparation has no JAX transformation or completeness guarantee; specialization retains existing JAX x64 and numerical packing requirements.

Example::

prepared = prepare_polyhedral_continuation(
    fixed_cells, moving_cells, (1, 0, 0), max_step=4,
    parameter_bounds=(-0.05, 0.6), seed_parameter=0,
)
if not prepared.uncovered:
    path = specialize_polyhedral_continuation(prepared, 0.5)
    # Existing exact target/range queries apply to this model path.

specialize_polyhedral_continuation(prepared, parameter)

Specialize only a certified parameter; unresolved coverage raises ValueError.

Fraction values retain the original affine family exactly. Existing translation-profile packing may reject unresolved float64 event chambers or coefficient scales even when the host parameter is certified.

Selecting finite edits with a CAD budget

uv run --group benchmark python -m benchmarks.multi_contact.selection \
  --output /tmp/finite-selection.json

This benchmark compares analytical candidate ordering and CAD confirmation with CAD-only adaptive selection. Its separate amount-refinement panel uses bounded proposals and only returns observed actions. It promises neither monotonic volume along arbitrary motion nor target reachability. A negative error difference relative to the fixed candidate grid is possible when a refined amount improves on every grid action.

Fresh synthetic geometry groups and five grouped train/test partitions keep calibration apart from each evaluated shape; repeated targets are not independent shapes. Reports retain failed or unsupported inputs and targets exceeding a known total-material bound. Probe attempts and final independent Common/Cut checks have separate costs. Cached replay timings do not establish end-to-end speed superiority. The experimental comparison is not a general optimizer API or evidence for arbitrary STEP inputs.

Other experimental applications

brepax.experimental.applications.mold_direction

Mold pull-direction optimization via differentiable undercut analysis.

Given a shape defined by its SDF, estimates the volume of material that would prevent mold removal in a given pull direction. The undercut criterion is SDF-based: a surface point is undercut when its outward normal opposes the pull direction (dot(normal, direction) < 0).

Both the undercut volume and the optimization loop are fully differentiable, enabling gradient-based search over the unit sphere S^2.

MoldDirectionResult dataclass

Result of mold direction optimization.

Attributes:

Name Type Description
direction Float[Array, 3]

Optimized pull direction (unit vector).

trajectory Float[Array, 'n 3']

Direction at each step, shape (steps+1, 3).

losses list[float]

Undercut volume at each step.

converged bool

Whether loss change dropped below tolerance.

optimize_mold_direction(shape_sdf, initial_direction, *, lo, hi, resolution=64, steps=100, lr=0.01, tol=1e-06)

Find the mold pull direction that minimizes undercut volume.

Uses projected gradient descent on S^2: after each gradient step the direction vector is re-normalized to the unit sphere.

Parameters:

Name Type Description Default
shape_sdf Callable[[Float[Array, 3]], Float[Array, '']]

Signed distance function for a single query point.

required
initial_direction Float[Array, 3]

Starting pull direction (will be normalized).

required
lo Float[Array, 3]

Lower corner of the evaluation domain.

required
hi Float[Array, 3]

Upper corner of the evaluation domain.

required
resolution int

Grid resolution per axis.

64
steps int

Maximum optimization steps.

100
lr float

Learning rate for gradient descent.

0.01
tol float

Convergence tolerance on absolute loss change.

1e-06

Returns:

Type Description
MoldDirectionResult

MoldDirectionResult with optimized direction and diagnostics.

Examples:

>>> import jax.numpy as jnp
>>> from brepax.primitives import Box
>>> box = Box(
...     center=jnp.array([0.0, 0.0, 0.0]),
...     half_extents=jnp.array([1.0, 1.0, 0.5]),
... )
>>> result = optimize_mold_direction(
...     box.sdf,
...     jnp.array([1.0, 1.0, 1.0]),
...     lo=jnp.array([-2.0, -2.0, -2.0]),
...     hi=jnp.array([2.0, 2.0, 2.0]),
...     resolution=32,
...     steps=50,
... )

undercut_volume(shape_sdf, direction, *, lo, hi, resolution=64)

Estimate undercut volume for a mold pull direction.

Undercut is defined as the set of interior points whose SDF spatial gradient (outward normal) opposes the pull direction. Both the interior membership and the undercut condition are smoothed with sigmoid indicators scaled by the grid cell width, ensuring the estimate improves with resolution.

Normals are estimated via central finite differences to avoid NaN gradients at degenerate SDF points (cylinder axis, box center, etc.).

Parameters:

Name Type Description Default
shape_sdf Callable[[Float[Array, 3]], Float[Array, '']]

Signed distance function for a single query point. Must accept shape (3,) and return scalar.

required
direction Float[Array, 3]

Unit pull direction on S^2.

required
lo Float[Array, 3]

Lower corner of the evaluation domain.

required
hi Float[Array, 3]

Upper corner of the evaluation domain.

required
resolution int

Grid resolution per axis.

64

Returns:

Type Description
Float[Array, '']

Scalar estimated undercut volume.

Examples:

>>> import jax.numpy as jnp
>>> from brepax.primitives import Box
>>> box = Box(
...     center=jnp.array([0.0, 0.0, 0.0]),
...     half_extents=jnp.array([1.0, 1.0, 0.5]),
... )
>>> vol = undercut_volume(
...     box.sdf,
...     jnp.array([0.0, 0.0, 1.0]),
...     lo=jnp.array([-2.0, -2.0, -2.0]),
...     hi=jnp.array([2.0, 2.0, 2.0]),
...     resolution=32,
... )

brepax.experimental.applications.cad_frame.CadFrame dataclass

Fixed host metadata with x_external = origin + length_scale * x_work.

length_scale is external length units per working length unit. Choose it once from a reference design size, before constructing CAD, and keep it fixed throughout editing. For a 40 mm reference expressed in metres, use length_scale=0.001 to work at size 40. origin is in external units. Directions/rotations are unchanged by this positive uniform scale; any rigid rotation belongs to the supplied geometry model.

Array conversions support JIT, vmap and differentiation when this frame is captured as fixed metadata. A degree-k scalar scales by sk and its gradient with respect to external lengths by s(k-1). The frame itself is not a differentiable model. Prefer x64 for CAD accuracy.

Normalize design dimensions and dimensional meshing/smoothing tolerances BEFORE OCCT construction. This does not infer STEP units, repair existing B-Reps, or guarantee CAD accuracy at arbitrary scales. Output transforms retain OCCT's tolerance semantics; they do not tighten tolerances.

Example

import jax import jax.numpy as jnp frame = CadFrame(0.001, (1.0, 2.0, 3.0)) def sphere_volume(radius): ... r = frame.working_lengths(radius) ... return frame.external_measure(4 * jnp.pi * r**3 / 3, 3) derivative = jax.jit(jax.grad(sphere_volume))(jnp.array(0.003))

external_measure(value, length_power)

Restore a length, area or volume; JAX propagates the unit chain rule.

external_points(points)

Restore point positions; evaluate scalar metrics before this step.

restore_shape(working_shape)

Copy a working B-Rep into external coordinates on the host.

Does not copy triangulations. Raises ValueError for null input and RuntimeError if OCCT returns an invalid result. This is an output conversion, not a traced operation or a mesh-to-CAD reconstruction.

working_lengths(lengths)

Convert external lengths (including deflections) to working units.