|
| 1 | +"""Input and output validation for the xeltofab mesh transform.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from typing import TYPE_CHECKING |
| 6 | +import warnings |
| 7 | + |
| 8 | +import numpy as np |
| 9 | +import numpy.typing as npt |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from xeltofab import PipelineState |
| 13 | + |
| 14 | + |
| 15 | +def validate_input(design: npt.NDArray) -> npt.NDArray: |
| 16 | + """Validate and sanitize a density-field design array. |
| 17 | +
|
| 18 | + Args: |
| 19 | + design: A numpy array representing a density field. |
| 20 | +
|
| 21 | + Returns: |
| 22 | + The (possibly clipped) design array. |
| 23 | +
|
| 24 | + Raises: |
| 25 | + TypeError: If *design* is not a numpy array. |
| 26 | + ValueError: If *design* is not 2-D or 3-D. |
| 27 | + """ |
| 28 | + if not isinstance(design, np.ndarray): |
| 29 | + msg = f"design must be a numpy ndarray, got {type(design).__name__}" |
| 30 | + raise TypeError(msg) |
| 31 | + |
| 32 | + if not np.issubdtype(design.dtype, np.floating) and not np.issubdtype(design.dtype, np.integer): |
| 33 | + msg = f"design must have a numeric dtype, got {design.dtype}" |
| 34 | + raise TypeError(msg) |
| 35 | + |
| 36 | + if design.size == 0: |
| 37 | + msg = f"design must be non-empty, got shape {design.shape}" |
| 38 | + raise ValueError(msg) |
| 39 | + |
| 40 | + if design.ndim not in (2, 3): |
| 41 | + msg = f"design must be 2-D or 3-D, got {design.ndim}-D with shape {design.shape}" |
| 42 | + raise ValueError(msg) |
| 43 | + |
| 44 | + # Single pass: min/max propagate NaN, so NaN detection comes for free. |
| 45 | + vmin, vmax = float(design.min()), float(design.max()) |
| 46 | + if np.isnan(vmin) or np.isnan(vmax) or np.isinf(vmin) or np.isinf(vmax): |
| 47 | + msg = "design contains non-finite values (NaN or Inf)" |
| 48 | + raise ValueError(msg) |
| 49 | + |
| 50 | + if vmin < 0.0 or vmax > 1.0: |
| 51 | + warnings.warn( |
| 52 | + f"Design values outside [0, 1] (min={vmin:.4f}, max={vmax:.4f}). Clipping.", |
| 53 | + stacklevel=3, |
| 54 | + ) |
| 55 | + design = np.clip(design, 0.0, 1.0) |
| 56 | + |
| 57 | + return design |
| 58 | + |
| 59 | + |
| 60 | +def validate_output( |
| 61 | + state: PipelineState, |
| 62 | + input_volume_fraction: float, |
| 63 | + tolerance: float, |
| 64 | +) -> list[str]: |
| 65 | + """Run post-pipeline validation checks. |
| 66 | +
|
| 67 | + Args: |
| 68 | + state: A ``xeltofab.PipelineState`` instance. |
| 69 | + input_volume_fraction: Volume fraction of the input design (``np.mean(design)``). |
| 70 | + tolerance: Maximum allowed absolute deviation in volume fraction. |
| 71 | +
|
| 72 | + Returns: |
| 73 | + A list of warning messages (empty if all checks pass). |
| 74 | +
|
| 75 | + Raises: |
| 76 | + RuntimeError: If the pipeline produced no mesh (3-D) or no contours (2-D). |
| 77 | + """ |
| 78 | + warnings_list: list[str] = [] |
| 79 | + |
| 80 | + ndim: int = getattr(state, "ndim", 0) |
| 81 | + |
| 82 | + if ndim == 3: # noqa: PLR2004 |
| 83 | + vertices = getattr(state, "vertices", None) |
| 84 | + faces = getattr(state, "faces", None) |
| 85 | + if vertices is None or faces is None: |
| 86 | + msg = "3-D pipeline produced no mesh (vertices or faces are None)." |
| 87 | + raise RuntimeError(msg) |
| 88 | + elif ndim == 2: # noqa: PLR2004 |
| 89 | + contours = getattr(state, "contours", None) |
| 90 | + if contours is None or len(contours) == 0: |
| 91 | + msg = "2-D pipeline produced no contours." |
| 92 | + raise RuntimeError(msg) |
| 93 | + else: |
| 94 | + msg = f"Unsupported or missing 'ndim' in pipeline state: {ndim!r}. Expected 2 or 3." |
| 95 | + raise RuntimeError(msg) |
| 96 | + |
| 97 | + output_vf = getattr(state, "volume_fraction", None) |
| 98 | + if output_vf is not None: |
| 99 | + delta = abs(input_volume_fraction - output_vf) |
| 100 | + if delta > tolerance: |
| 101 | + warnings_list.append( |
| 102 | + f"Volume fraction changed by {delta:.4f} " |
| 103 | + f"(input={input_volume_fraction:.4f}, output={output_vf:.4f}, " |
| 104 | + f"tolerance={tolerance:.4f})." |
| 105 | + ) |
| 106 | + |
| 107 | + for msg in warnings_list: |
| 108 | + warnings.warn(msg, stacklevel=3) |
| 109 | + |
| 110 | + return warnings_list |
0 commit comments