Core Module

The core module contains the main data structures and high-level APIs for PolytopAX.

ConvexHull Class

class polytopax.ConvexHull(vertices: ~jax.Array, faces: ~jax.Array | None = None, algorithm_info: dict[str, ~typing.Any] = <factory>)[source]

Bases: object

JAX-compatible ConvexHull class with object-oriented API.

This class provides a high-level interface for convex hull operations, including geometric queries, property computation, and transformations. It is designed to be compatible with JAX transformations (jit, grad, vmap).

vertices

Hull vertex coordinates with shape (n_vertices, dim)

Type:

jax.Array

faces

Face composition with shape (n_faces, vertices_per_face) [optional]

Type:

jax.Array | None

algorithm_info

Metadata about the computation algorithm

Type:

dict[str, Any]

_volume_cache

Cached volume value for performance

Type:

float | None

_surface_area_cache

Cached surface area value for performance

Type:

float | jax.Array | None

_centroid_cache

Cached centroid value for performance

Type:

jax.Array | None

Example

>>> import jax.numpy as jnp
>>> from polytopax import ConvexHull
>>> points = jnp.array([[0, 0], [1, 0], [0, 1], [1, 1]])
>>> hull = ConvexHull.from_points(points)
>>> print(f"Volume: {hull.volume():.4f}")
>>> print(f"Centroid: {hull.centroid()}")

Methods

from_points(points[, algorithm])

Create ConvexHull from point cloud.

from_dict(data)

Create ConvexHull from dictionary representation.

to_dict()

Convert hull to dictionary representation.

volume([method])

Compute hull volume (with caching).

surface_area()

Compute hull surface area (with caching).

centroid()

Compute hull centroid (with caching).

diameter()

Compute hull diameter (maximum distance between vertices).

bounding_box()

Compute axis-aligned bounding box.

contains(point[, tolerance])

Test if point is inside hull.

distance_to(point)

Compute distance from point to hull.

is_degenerate([tolerance])

Check if hull is degenerate (lower-dimensional).

vertices_array()

Get vertices as JAX array.

summary()

Get summary statistics of the hull.

scale(factor)

Scale the convex hull (Phase 2 implementation).

translate(vector)

Translate the convex hull (Phase 2 implementation).

rotate(angle[, axis])

Rotate the convex hull (Phase 2 implementation).

vertices: Array
faces: Array | None = None
algorithm_info: dict[str, Any]
__post_init__()[source]

Post-initialization processing.

classmethod from_points(points: Array, algorithm: str = 'approximate', **kwargs) ConvexHull[source]

Create ConvexHull from point cloud.

Parameters:
  • points – Input point cloud with shape (n_points, dim)

  • algorithm – Hull computation algorithm (“approximate”)

  • **kwargs – Algorithm-specific parameters

Returns:

ConvexHull instance

Example

>>> points = jnp.random.normal(jax.random.PRNGKey(0), (50, 3))
>>> hull = ConvexHull.from_points(points, n_directions=100)
property n_vertices: int

Number of hull vertices.

property dimension: int

Spatial dimension.

volume(method: str = 'simplex_decomposition') float | Array[source]

Compute hull volume (with caching).

Parameters:

method – Volume computation method

Returns:

Volume of the convex hull

surface_area() float | Array[source]

Compute hull surface area (with caching).

Returns:

Surface area of the convex hull

contains(point: Array, tolerance: float = 1e-08) bool[source]

Test if point is inside hull.

Parameters:
  • point – Point to test with shape (dim,)

  • tolerance – Numerical tolerance

Returns:

True if point is inside or on boundary

distance_to(point: Array) float[source]

Compute distance from point to hull.

Parameters:

point – Point with shape (dim,)

Returns:

Signed distance (positive=outside, negative=inside)

centroid() Array[source]

Compute hull centroid (with caching).

Returns:

Centroid coordinates

bounding_box() tuple[Array, Array][source]

Compute axis-aligned bounding box.

Returns:

Tuple of (min_coords, max_coords)

diameter() float[source]

Compute hull diameter (maximum distance between vertices).

Returns:

Maximum distance between any two vertices

is_degenerate(tolerance: float = 1e-10) bool[source]

Check if hull is degenerate (lower-dimensional).

Parameters:

tolerance – Tolerance for degeneracy detection

Returns:

True if hull is degenerate

summary() dict[str, Any][source]

Get summary statistics of the hull.

Returns:

Dictionary containing various hull properties

vertices_array() Array[source]

Get vertices as JAX array.

Returns:

Vertex coordinates array

to_dict() dict[str, Any][source]

Convert hull to dictionary representation.

Returns:

Dictionary representation suitable for serialization

classmethod from_dict(data: dict[str, Any]) ConvexHull[source]

Create ConvexHull from dictionary representation.

Parameters:

data – Dictionary containing hull data

Returns:

ConvexHull instance

__repr__() str[source]

String representation of ConvexHull.

__str__() str[source]

Human-readable string representation.

scale(factor: float | Array) ConvexHull[source]

Scale the convex hull (Phase 2 implementation).

Parameters:

factor – Scaling factor (scalar or per-dimension)

Returns:

New scaled ConvexHull instance

translate(vector: Array) ConvexHull[source]

Translate the convex hull (Phase 2 implementation).

Parameters:

vector – Translation vector

Returns:

New translated ConvexHull instance

rotate(angle: float, axis: Array | None = None) ConvexHull[source]

Rotate the convex hull (Phase 2 implementation).

Parameters:
  • angle – Rotation angle (radians)

  • axis – Rotation axis (3D only)

Returns:

New rotated ConvexHull instance

__init__(vertices: ~jax.Array, faces: ~jax.Array | None = None, algorithm_info: dict[str, ~typing.Any] = <factory>) None

Main Functions

Convex hull computation functions - unified interface.

polytopax.core.hull.approximate_convex_hull(points: Array, n_directions: int = 100, method: str = 'uniform', random_seed: int = 0) tuple[Array, Array][source]

Differentiable approximate convex hull computation.

This function maintains backward compatibility with the original API while forwarding to the new implementation.

Parameters:
  • points – Point cloud with shape […, n_points, dim]

  • n_directions – Number of sampling directions

  • method – Sampling strategy (‘uniform’, ‘adaptive’, ‘icosphere’)

  • random_seed – Random seed

Returns:

Tuple of (hull_points, hull_indices)

Note

This function is maintained for backward compatibility. For new code, consider using the unified convex_hull() function or the algorithms.approximation module directly.

polytopax.core.hull.convex_hull(points: Array, algorithm: str = 'approximate', **kwargs) Array[source]

Compute convex hull of a set of points.

This is the main unified interface for convex hull computation. It supports multiple algorithms and provides a consistent API.

Parameters:
  • points – Input points array with shape (…, n_points, dimension)

  • algorithm – Algorithm to use: - “approximate”: Differentiable approximate hull (default) - “quickhull”: Exact Quickhull algorithm (Phase 2) - “graham_scan”: 2D Graham scan algorithm (Phase 2)

  • **kwargs – Algorithm-specific parameters passed to the underlying function

Returns:

Array of convex hull vertices

Example

>>> import jax.numpy as jnp
>>> points = jnp.array([[0, 0], [1, 0], [0, 1], [1, 1]])
>>> hull_vertices = convex_hull(points, algorithm="approximate")
>>> print(hull_vertices.shape)  # (n_hull_vertices, 2)
Algorithm-specific parameters:
For algorithm=”approximate”:
  • n_directions (int): Number of sampling directions (default: 100)

  • method (str): Sampling method (“uniform”, “icosphere”, “adaptive”)

  • temperature (float): Softmax temperature for differentiability

  • random_key (Array): JAX random key

polytopax.core.hull.distance_to_hull(point: Array, hull_vertices: Array) Array

Compute distance from point to convex hull.

Parameters:
  • point – Point with shape (…, dim)

  • hull_vertices – Hull vertices with shape (…, n_vertices, dim)

Returns:

  • Positive: point is outside hull

  • Zero: point is on boundary

  • Negative: point is inside hull

Return type:

Signed distance to hull

polytopax.core.hull.hull_surface_area(vertices: Array, faces: Array | None = None) Array

Compute surface area of convex hull.

Parameters:
  • vertices – Hull vertices with shape (…, n_vertices, dim)

  • faces – Face vertex indices with shape (…, n_faces, vertices_per_face) If None, faces will be computed automatically

Returns:

Surface area (sum of face areas)

polytopax.core.hull.hull_volume(vertices: Array, method: str = 'simplex_decomposition') Array

Compute volume of convex hull (differentiable).

Parameters:
  • vertices – Hull vertices with shape (…, n_vertices, dim)

  • method – Volume computation method - “simplex_decomposition”: Decompose into simplices - “shoelace”: Shoelace formula (2D only) - “divergence_theorem”: Use divergence theorem (3D only) - “monte_carlo”: Monte Carlo estimation - “multi_method”: Consensus across multiple methods

Returns:

Volume of the convex hull (d-dimensional measure)

Note

For d-dimensional space, volume is the d-dimensional measure. For 2D, this is area; for 3D, this is volume; etc.

polytopax.core.hull.point_in_hull(point: Array, hull_vertices: Array, tolerance: float = 1e-08, method: str = 'halfspace') Array

Test if point is inside convex hull.

Determines whether a point lies inside, on the boundary, or outside of the convex hull defined by the given vertices.

Parameters:
  • point – Point to test with shape (…, dim)

  • hull_vertices – Hull vertices with shape (…, n_vertices, dim)

  • tolerance – Numerical tolerance for boundary detection

  • method – Algorithm to use (“halfspace”, “linear_programming”, “barycentric”)

Returns:

Boolean array indicating inclusion (True = inside or on boundary)

Algorithm (linear_programming method):

A point p is inside the convex hull if it can be expressed as: p = sum(λᵢ * vᵢ) where sum(λᵢ) = 1 and λᵢ >= 0

This is solved as a linear programming problem: minimize 0 subject to: sum(λᵢ * vᵢ) = p

sum(λᵢ) = 1 λᵢ >= 0

Utilities

Core utility functions for PolytopAX.

polytopax.core.utils.validate_point_cloud(points: Array) Array[source]

Validate point cloud shape and numerical validity.

Parameters:

points – Input point cloud with shape (…, n_points, dim)

Returns:

Validated point cloud

Raises:

ValueError – Invalid shape or numerical values

polytopax.core.utils.generate_direction_vectors(dimension: int, n_directions: int, method: Literal['uniform', 'icosphere', 'adaptive'] = 'uniform', random_key: Array | None = None) Array[source]

Generate direction vectors for sampling.

Parameters:
  • dimension – Spatial dimension

  • n_directions – Number of directions to generate

  • method – Sampling strategy - “uniform”: Uniform distribution on sphere - “icosphere”: Icosahedral subdivision (3D only) - “adaptive”: Locally adaptive density sampling

  • random_key – JAX random key (required for “uniform” and “adaptive”)

Returns:

Normalized direction vector set with shape (n_directions, dimension)

Raises:

ValueError – Invalid parameters or unsupported combinations

polytopax.core.utils.robust_orientation_test(points: Array, tolerance: float = 1e-12) Array[source]

Robust geometric orientation test.

Implements numerically stable orientation tests for geometric predicates. Based on Shewchuk (1997) adaptive precision predicates concepts.

Parameters:
  • points – Points to test with shape (…, n_points, dim)

  • tolerance – Numerical tolerance for degeneracy detection

Returns:

Orientation indicators

Note

This is a simplified implementation. Full robust predicates would require adaptive precision arithmetic.

polytopax.core.utils.compute_simplex_volume(vertices: Array) Array[source]

Compute volume of simplex defined by vertices.

Parameters:

vertices – Simplex vertices with shape (…, n_vertices, dim) where n_vertices = dim + 1 for full-dimensional simplex

Returns:

Volume of the simplex

polytopax.core.utils.project_to_simplex(point: Array, vertices: Array) tuple[Array, Array][source]

Project point onto simplex defined by vertices.

Parameters:
  • point – Point to project with shape (…, dim)

  • vertices – Simplex vertices with shape (…, n_vertices, dim)

Returns:

Tuple of (projected_point, barycentric_coordinates)

polytopax.core.utils.remove_duplicate_points(points: Array, tolerance: float = 1e-10) tuple[Array, Array][source]

Remove duplicate points within tolerance.

Parameters:
  • points – Point cloud with shape (…, n_points, dim)

  • tolerance – Distance tolerance for considering points duplicate

Returns:

Tuple of (unique_points, unique_indices)

polytopax.core.utils.scale_to_unit_ball(points: Array) tuple[Array, tuple[Array, float]][source]

Scale point cloud to fit in unit ball.

Parameters:

points – Point cloud with shape (…, n_points, dim)

Returns:

Tuple of (scaled_points, (center, scale_factor))

polytopax.core.utils.unscale_from_unit_ball(points: Array, transform_params: tuple[Array, float]) Array[source]

Reverse scaling from unit ball.

Parameters:
  • points – Scaled point cloud

  • transform_params – (center, scale_factor) from scale_to_unit_ball

Returns:

Original scale point cloud

Type Definitions

The core module defines several type aliases for better code documentation:

polytopax.core.utils.PointCloud = Array

Array base class for JAX

jax.Array is the public interface for instance checks and type annotation of JAX arrays and tracers. Its main applications are in instance checks and type annotations; for example:

x = jnp.arange(5)
isinstance(x, jax.Array)  # returns True both inside and outside traced functions.

def f(x: Array) -> Array:  # type annotations are valid for traced and non-traced types.
  return x

jax.Array should not be used directly for creation of arrays; instead you should use array creation routines offered in jax.numpy, such as jax.numpy.array(), jax.numpy.zeros(), jax.numpy.ones(), jax.numpy.full(), jax.numpy.arange(), etc.

Point cloud array with shape (…, n_points, dimension)

polytopax.core.utils.HullVertices = Array

Array base class for JAX

jax.Array is the public interface for instance checks and type annotation of JAX arrays and tracers. Its main applications are in instance checks and type annotations; for example:

x = jnp.arange(5)
isinstance(x, jax.Array)  # returns True both inside and outside traced functions.

def f(x: Array) -> Array:  # type annotations are valid for traced and non-traced types.
  return x

jax.Array should not be used directly for creation of arrays; instead you should use array creation routines offered in jax.numpy, such as jax.numpy.array(), jax.numpy.zeros(), jax.numpy.ones(), jax.numpy.full(), jax.numpy.arange(), etc.

Hull vertices array with shape (n_vertices, dimension)

polytopax.core.utils.DirectionVectors = Array

Array base class for JAX

jax.Array is the public interface for instance checks and type annotation of JAX arrays and tracers. Its main applications are in instance checks and type annotations; for example:

x = jnp.arange(5)
isinstance(x, jax.Array)  # returns True both inside and outside traced functions.

def f(x: Array) -> Array:  # type annotations are valid for traced and non-traced types.
  return x

jax.Array should not be used directly for creation of arrays; instead you should use array creation routines offered in jax.numpy, such as jax.numpy.array(), jax.numpy.zeros(), jax.numpy.ones(), jax.numpy.full(), jax.numpy.arange(), etc.

Direction vectors array with shape (n_directions, dimension)

polytopax.core.utils.SamplingMethod

Direction vector sampling method specification alias of Literal[‘uniform’, ‘icosphere’, ‘adaptive’]

alias of Literal[‘uniform’, ‘icosphere’, ‘adaptive’]