Source code for pyboxbuilder.box.validation

# SPDX-License-Identifier: Apache-2.0
"""Pre-CSG geometric invariant validation (FR-092 / SC-092).

Enforces physical and geometric invariants on a :class:`ResolvedBoxSpec` before
invoking PythonSCAD / Manifold boolean operations. Catching impossible envelopes,
degenerate thicknesses, and negative clearances here prevents downstream kernel
faults, unprintable solids, or obscure geometry solver errors.
"""

from __future__ import annotations

import math
from typing import TYPE_CHECKING

from pyboxbuilder.enums import (
    CatchType,
    DispenserExtractionMode,
    DrawerHandleStyle,
    HingeCatchType,
    InterlockType,
    LatchAxis,
    MagnetType,
    PatternType,
    StackableMode,
    StackableShape,
)

if TYPE_CHECKING:
    from pyboxbuilder.box.spec import ResolvedBoxSpec

MIN_PRINTABLE_WALL_MM = 0.8
"""Minimum printable wall thickness on standard 0.4mm nozzle FDM printers."""

MIN_PRINTABLE_FLOOR_MM = 0.8
"""Minimum printable base floor thickness."""

MIN_CLEARANCE_MARGIN_MM = 1.0
"""Minimum internal clearance margin required beyond outer walls."""


class GeometryValidationError(ValueError):
    """Raised when a box configuration violates physical or geometric invariants (FR-092)."""

    def __init__(
        self,
        label: str,
        invariant: str,
        message: str,
        guidance: str | None = None,
    ) -> None:
        self.label = label
        self.invariant = invariant
        self.guidance = guidance
        full_message = f"Geometric validation failed for box '{label}' [{invariant}]: {message}"
        if guidance:
            full_message += f" Remediation: {guidance}"
        super().__init__(full_message)


[docs] class GeometryValidator: """Validates physical and geometric invariants on a ResolvedBoxSpec prior to CSG evaluation."""
[docs] @classmethod def validate(cls, spec: ResolvedBoxSpec) -> None: """Validate all physical invariants on the resolved specification. Args: spec: The frozen :class:`ResolvedBoxSpec` to validate. Raises: GeometryValidationError: If any physical invariant is violated. """ cls._validate_envelope_positivity(spec) cls._validate_material_thicknesses(spec) cls._validate_envelope_sanity(spec) cls._validate_clearances(spec) cls._validate_closure_bounds(spec) cls._validate_stackable_bounds(spec) cls._validate_interlock_bounds(spec) cls._validate_enum_invariants(spec)
@classmethod def _validate_envelope_positivity(cls, spec: ResolvedBoxSpec) -> None: for dim, name in ( (spec.width, "width"), (spec.length, "length"), (spec.height, "height"), ): if not isinstance(dim, (int, float)) or math.isnan(dim) or math.isinf(dim) or dim <= 0.0: raise GeometryValidationError( label=spec.label, invariant="positive_finite_envelope", message=f"{name} must be a positive finite float, got {dim}.", guidance=f"Set a positive {name} value in builder or container layout.", ) @classmethod def _validate_material_thicknesses(cls, spec: ResolvedBoxSpec) -> None: if spec.wall_thickness < MIN_PRINTABLE_WALL_MM: raise GeometryValidationError( label=spec.label, invariant="min_wall_thickness", message=( f"Wall thickness {spec.wall_thickness}mm is below the minimum printable " f"threshold ({MIN_PRINTABLE_WALL_MM}mm)." ), guidance=f"Increase wall_thickness to at least {MIN_PRINTABLE_WALL_MM}mm (recommended >= 1.2mm).", ) if spec.floor_thickness < MIN_PRINTABLE_FLOOR_MM: raise GeometryValidationError( label=spec.label, invariant="min_floor_thickness", message=( f"Floor thickness {spec.floor_thickness}mm is below the minimum printable " f"threshold ({MIN_PRINTABLE_FLOOR_MM}mm)." ), guidance=f"Increase floor_thickness to at least {MIN_PRINTABLE_FLOOR_MM}mm (recommended >= 1.6mm).", ) if spec.lid_thickness < 0.0: raise GeometryValidationError( label=spec.label, invariant="non_negative_lid_thickness", message=f"Lid thickness cannot be negative, got {spec.lid_thickness}mm.", guidance="Set lid_thickness to 0.0 for lidless boxes or > 0.0 for lidded boxes.", ) @classmethod def _validate_envelope_sanity(cls, spec: ResolvedBoxSpec) -> None: min_width = 2 * spec.wall_thickness + MIN_CLEARANCE_MARGIN_MM if spec.width < min_width: raise GeometryValidationError( label=spec.label, invariant="envelope_width_sanity", message=( f"Box width ({spec.width:.2f}mm) is too small to accommodate two walls of " f"{spec.wall_thickness:.2f}mm plus interior clearance (minimum {min_width:.2f}mm)." ), guidance=f"Increase width to >= {min_width:.2f}mm or reduce wall_thickness.", ) min_length = 2 * spec.wall_thickness + MIN_CLEARANCE_MARGIN_MM if spec.length < min_length: raise GeometryValidationError( label=spec.label, invariant="envelope_length_sanity", message=( f"Box length ({spec.length:.2f}mm) is too small to accommodate two walls of " f"{spec.wall_thickness:.2f}mm plus interior clearance (minimum {min_length:.2f}mm)." ), guidance=f"Increase length to >= {min_length:.2f}mm or reduce wall_thickness.", ) min_height = spec.floor_thickness + spec.lid_thickness if spec.height <= min_height: raise GeometryValidationError( label=spec.label, invariant="envelope_height_sanity", message=( f"Box height ({spec.height:.2f}mm) must be strictly greater than the sum of floor " f"({spec.floor_thickness:.2f}mm) and lid ({spec.lid_thickness:.2f}mm) thicknesses " f"({min_height:.2f}mm)." ), guidance=f"Increase height to > {min_height:.2f}mm.", ) @classmethod def _validate_clearances(cls, spec: ResolvedBoxSpec) -> None: for clearance, name in ( (spec.size_spacing, "size_spacing"), (spec.sliding_slack, "sliding_slack"), (spec.cap_slack, "cap_slack"), (spec.slip_slack, "slip_slack"), ): if clearance < 0.0: raise GeometryValidationError( label=spec.label, invariant="non_negative_clearance", message=f"Clearance parameter '{name}' cannot be negative, got {clearance}mm.", guidance=f"Set '{name}' to a non-negative clearance (e.g. 0.1 to 0.3mm).", ) @classmethod def _validate_closure_bounds(cls, spec: ResolvedBoxSpec) -> None: if ( spec.catch_radius is not None and spec.catch_radius > 0.0 and spec.catch_radius >= spec.wall_thickness ): raise GeometryValidationError( label=spec.label, invariant="catch_radius_fits_wall", message=( f"Catch radius ({spec.catch_radius:.2f}mm) must be strictly less than " f"wall thickness ({spec.wall_thickness:.2f}mm)." ), guidance=f"Reduce catch_radius to < {spec.wall_thickness:.2f}mm or increase wall_thickness.", ) if ( spec.catch_size is not None and spec.catch_size > 0.0 and spec.resolved_catch_type(CatchType.BUMP) != CatchType.MAGNET and spec.catch_size >= spec.wall_thickness ): raise GeometryValidationError( label=spec.label, invariant="catch_size_fits_wall", message=( f"Catch size ({spec.catch_size:.2f}mm) must be strictly less than " f"wall thickness ({spec.wall_thickness:.2f}mm)." ), guidance=f"Reduce catch_size to < {spec.wall_thickness:.2f}mm or increase wall_thickness.", ) if ( spec.catch_size is not None and spec.catch_size > 0.0 and spec.resolved_catch_type(CatchType.BUMP) == CatchType.MAGNET and spec.catch_size >= min(spec.width, spec.length) / 2.0 ): raise GeometryValidationError( label=spec.label, invariant="catch_size_fits_wall", message=( f"Magnet catch diameter ({spec.catch_size:.2f}mm) must be strictly less than " f"half the box footprint ({min(spec.width, spec.length) / 2.0:.2f}mm)." ), guidance="Reduce catch_size or increase box dimensions.", ) if spec.inset > 0.0: interior_depth = spec.height - spec.floor_thickness if spec.inset >= interior_depth: raise GeometryValidationError( label=spec.label, invariant="inset_depth_fits_box", message=( f"Inset depth ({spec.inset:.2f}mm) exceeds available box interior depth " f"({interior_depth:.2f}mm)." ), guidance="Reduce inset or increase box height.", ) pip_w = getattr(spec, "pip_bridge_width", None) if pip_w is not None and pip_w < 0.4: raise GeometryValidationError( label=spec.label, invariant="pip_bridge_width_min", message=( f"Print-in-place hinge bridge width ({pip_w:.2f}mm) must be " f"at least 0.40mm to ensure printable 3D bridging." ), guidance="Set pip_bridge_width to >= 0.40mm.", ) @classmethod def _validate_stackable_bounds(cls, spec: ResolvedBoxSpec) -> None: if spec.stackable is None: return from pyboxbuilder.enums import StackableMode if spec.stackable in ( StackableMode.FEET, StackableMode.INDENTS, StackableMode.PYRAMID, StackableMode.PYRAMIDS, StackableMode.PATTERN, StackableMode.PERIMETER, ): foot_size = spec.stackable_foot_size or max(6.0, spec.wall_thickness * 2.5) min_span = min(spec.width, spec.length) if foot_size >= min_span / 2.0: raise GeometryValidationError( label=spec.label, invariant="stackable_foot_size_fits_footprint", message=( f"Stackable foot size ({foot_size:.2f}mm) must be strictly less than " f"half the minimum box span ({min_span / 2.0:.2f}mm)." ), guidance="Reduce stackable_foot_size or increase box width/length.", ) if spec.stackable_foot_height <= 0.0: raise GeometryValidationError( label=spec.label, invariant="positive_stackable_foot_height", message=f"Stackable foot height must be positive, got {spec.stackable_foot_height}mm.", guidance="Set stackable_foot_height to a positive value (e.g. 1.6mm).", ) if isinstance(spec.stackable_pyramid_count, int) and spec.stackable_pyramid_count < 1: raise GeometryValidationError( label=spec.label, invariant="positive_stackable_pyramid_count", message=f"Stackable pyramid count must be >= 1, got {spec.stackable_pyramid_count}.", guidance="Set stackable_pyramid_count to a positive integer (e.g. 1, 2, or 3).", ) if isinstance(spec.stackable_pyramid_count, tuple) and any( isinstance(x, int) and x < 0 for x in spec.stackable_pyramid_count ): raise GeometryValidationError( label=spec.label, invariant="positive_stackable_pyramid_count", message=f"Stackable pyramid count entries must be >= 0, got {spec.stackable_pyramid_count}.", guidance="Use positive integer counts per corner or axis.", ) @classmethod def _validate_interlock_bounds(cls, spec: ResolvedBoxSpec) -> None: if spec.polygon_sides is not None and spec.polygon_sides < 3: raise GeometryValidationError( label=spec.label, invariant="min_polygon_sides", message=f"Regular polygon must have at least 3 sides, got {spec.polygon_sides}.", guidance="Set polygon_sides to 3 (triangle), 4 (square), 6 (hexagon), or higher.", ) if spec.interlock_type is not None and spec.interlock_clearance < 0.0: raise GeometryValidationError( label=spec.label, invariant="non_negative_interlock_clearance", message=f"Interlock clearance must be non-negative, got {spec.interlock_clearance}mm.", guidance="Set interlock_clearance to a non-negative value (e.g. 0.15mm).", ) if spec.interlock_type is InterlockType.DOVETAIL: dt_depth = 3.0 if isinstance(spec.interlock_size, (int, float)): dt_depth = float(spec.interlock_size) elif isinstance(spec.interlock_size, (tuple, list)) and len(spec.interlock_size) >= 1: dt_depth = float(spec.interlock_size[0]) if spec.wall_thickness <= dt_depth: raise GeometryValidationError( label=spec.label, invariant="dovetail_depth_fits_wall", message=( f"Wall thickness ({spec.wall_thickness:.2f}mm) must be strictly greater than " f"dovetail depth ({dt_depth:.2f}mm) to prevent piercing through the wall into the interior." ), guidance=( f"Increase wall_thickness to > {dt_depth:.2f}mm (e.g. wall_thickness=4.0) " f"or reduce dovetail depth (interlock_size) to < {spec.wall_thickness:.2f}mm." ), ) @classmethod def _validate_enum_invariants(cls, spec: ResolvedBoxSpec) -> None: """Validate that all categorical configuration options are strict instances of Python Enum (FR-106).""" categorical_fields = ( (spec.catch_type, CatchType, "catch_type", True), (spec.hinge_catch_type, HingeCatchType, "hinge_catch_type", True), (spec.interlock_type, InterlockType, "interlock_type", True), (spec.magnet_type, MagnetType, "magnet_type", True), (spec.stackable, StackableMode, "stackable", True), (spec.stackable_shape, StackableShape, "stackable_shape", True), (spec.stackable_pattern, PatternType, "stackable_pattern", True), (spec.dispenser_mode, DispenserExtractionMode, "dispenser_mode", False), (spec.drawer_handle_style, DrawerHandleStyle, "drawer_handle_style", False), (spec.latch_axis, LatchAxis, "latch_axis", False), ) for val, enum_cls, name, allow_none in categorical_fields: if val is None: if not allow_none: raise GeometryValidationError( label=spec.label, invariant="enum_invariant", message=f"Field '{name}' must not be None; expected {enum_cls.__name__} enum.", guidance=f"Set {name} to a valid {enum_cls.__name__} member.", ) continue if not isinstance(val, enum_cls): raise GeometryValidationError( label=spec.label, invariant="enum_invariant", message=( f"Field '{name}' must be an instance of {enum_cls.__name__} enum, " f"got {type(val).__name__} ({val!r})." ), guidance=( f"Use {enum_cls.__name__}.{val.upper() if isinstance(val, str) else 'MEMBER'} " "instead of raw strings." ), )