polyfoammesh.core.geometry

Functions

analyze_local_thickness(meshes[, samples, seed])

Per-patch thickness sampling, then aggregated.

build_graded_refinement_boxes(meshes[, ...])

Approximate a GMSH-style continuous local-sizing field for cfMesh using many small, growth-rate-graded objectRefinements boxes.

cfmesh_cell_budget([max_cells_override, ...])

RAM-aware cell-count ceiling for cfMesh/cartesianMesh — the equivalent of gmsh_wrapper._hardware_budget for the tet/GMSH path, which had NO counterpart on the cfMesh side (validate_cell_sizes only ever clamped against the bounding box, never against the machine's actual RAM).

check_watertight(meshes)

Pre-flight check: do the patches together bound a closed volume?

classify_faces(shape[, inlet_axis, ...])

classify_faces_auto(shape[, inlet_axis, tol])

coarsen_for_ram_budget(max_cell, domain_volume)

Coarsen max_cell so domain_volume / max_cell**3 stays within cfmesh_cell_budget() — the RAM safety net, standalone so callers that already have their own bbox clamp (or none at all, like meshdict_gen.write_meshdict reading a surface STL directly) can apply just this check without validate_cell_sizes's bbox/2 clamp running a second time on top of whatever the caller already did.

compute_bbox_dim(meshes)

Return the maximum dimension of the geometry bounding box.

compute_bbox_full(meshes)

Return (dx, dy, dz) of the geometry bounding box.

compute_curvature_sizing(meshes[, ...])

Estimate cell size needed to resolve surface curvature.

compute_patch_cell_sizes(meshes[, detail, seed])

Compute per-patch cell sizes + boundary refinement parameters.

compute_volume(meshes)

Return the summed volume of all patch meshes.

create_test_cylinder([radius, height])

estimate_cell_count(volume, max_cell, min_cell)

Estimate the final cell count before meshing.

estimate_cell_count_geometric(meshes, ...[, ...])

Geometry-aware cell-count estimate: near-wall refinement + bulk core.

height_scale(shape)

load_and_tessellate(filepath[, tolerance, ...])

load_geometry(filepath)

Load STEP or STL, returning a list of trimesh meshes (one per patch/solid).

load_step(filepath)

load_stl(filepath)

Load an STL file as a list of trimesh meshes (one per solid).

sample_thickness_field(mesh, n_samples, bbox_max)

Like _sample_thickness_one_mesh, but returns (points, thickness) pairs instead of a flat list of values.

scale_meshes(meshes, factor)

Multiply all vertex coordinates in-place by factor.

snap_to_octree_level(cell_size, bbox_dim[, ...])

Snap a cell size to the nearest cfMesh octree level.

split_mesh_by_angle(mesh[, angle_deg])

Split mesh into surface patches by feature (dihedral) angle.

split_single_stl_patch(mesh[, angle_deg, ...])

Split a single-patch STL mesh into inlet/outlet/wall patches.

suggest_cell_sizes([meshes, detail, ...])

Feature-aware cell size suggestion.

tessellate_patches(patches[, tolerance, ...])

unit_to_scale(unit)

Convert a CAD unit string to a scale factor (CAD unit → metres).

validate_cell_sizes(bbox_max_dim, max_cell, ...)

Clamp cell sizes relative to the bounding box to avoid degenerate meshes.

Classes

AnalysisResult

class polyfoammesh.core.geometry.AnalysisResult[source]

Bases: TypedDict

p1: float
p5: float
p10: float
p25: float
p50: float
p75: float
n_samples: int
min_thickness: float
bbox: tuple[float, float, float]
polyfoammesh.core.geometry.create_test_cylinder(radius=1.0, height=2.0)[source]
Return type:

Workplane

Parameters:
polyfoammesh.core.geometry.load_step(filepath)[source]
Return type:

Shape

Parameters:

filepath (Path | str)

polyfoammesh.core.geometry.load_stl(filepath)[source]

Load an STL file as a list of trimesh meshes (one per solid).

ASCII STL: split on solid NAME / endsolid NAME blocks so each named solid becomes its own patch (preserves multi-body geometry). Binary STL: trimesh loads it as a single mesh; we still wrap it as a one-element list with the patch name derived from the filename stem.

Return type:

list[Trimesh]

Parameters:

filepath (Path | str)

polyfoammesh.core.geometry.compute_bbox_dim(meshes)[source]

Return the maximum dimension of the geometry bounding box.

Return type:

float

Parameters:

meshes (list[Trimesh])

polyfoammesh.core.geometry.compute_bbox_full(meshes)[source]

Return (dx, dy, dz) of the geometry bounding box.

Return type:

tuple[float, float, float]

Parameters:

meshes (list[Trimesh])

polyfoammesh.core.geometry.analyze_local_thickness(meshes, samples=192, seed=12648430)[source]

Per-patch thickness sampling, then aggregated.

Return type:

AnalysisResult

Parameters:
Algorithm:
  1. For each patch, allocate samples proportional to area (with a floor so small patches are never starved).

  2. Sample thickness within each patch.

  3. Aggregate per-patch percentiles using a stratified rule:

    p_global[k] = sum over patches of (area_patch / area_total) * p_patch[k]

    This way, a small-area constriction (with small p10) actually pulls down the global p10 — even if its sample count is small.

Why this matters: cfMesh real cases often have one big patch (e.g. a tube wall) and one small patch (e.g. a constriction). With a naive global percentiles, the constriction’s small values get drowned in the tube’s large values.

polyfoammesh.core.geometry.sample_thickness_field(mesh, n_samples, bbox_max, seed=12648430, timeout_s=20.0)[source]

Like _sample_thickness_one_mesh, but returns (points, thickness) pairs instead of a flat list of values.

analyze_local_thickness only ever needed global percentiles (p1, p5, …), so _sample_thickness_one_mesh discards WHERE each thickness was measured. A per-point sizing field (see gmsh_wrapper._configure_passage_thickness_field) needs exactly that spatial correspondence — a passage is narrow at a specific location, not “somewhere on the part” — so this is a separate function rather than a change to the existing one, to avoid touching the already-used, already-correct percentile path.

The measurement itself is the width of the volume mesh encloses at each sample point (cast a ray along the inward normal, first hit wins; falls back to the outward direction if the inward ray misses, e.g. a sample near a convex corner). For a CFD case this mesh is normally the fluid domain’s boundary, so “thickness” here IS the local width of the flow passage — verified end-to-end on a properly multi-ring venturi (wide-narrow-wide, throat at the midpoint) in tests/test_passage_thickness_field.py: reports ~1.99 at the wide ends against a true 2.0 diameter, decreasing smoothly toward the throat — a genuinely LOCAL field, not a per-body statistic.

timeout_s: this function is called from multiple places (GMSH’s passage-thickness field, the feature-aware minCellSize slider, throat_detector) on whatever geometry the user loaded, some of which can be large/complex CAD parts far more expensive to ray-cast than any of this function’s own test fixtures. Ray-casting stops taking on new batches once the deadline passes and returns whatever was measured so far (never raises, never blocks past the deadline) — a real user reported cartesianMesh becoming unusably slow / hanging on a real geometry after a caller of this function started running it more than once per meshing pass with no time bound at all.

Return type:

tuple[ndarray, ndarray]

Parameters:
polyfoammesh.core.geometry.check_watertight(meshes)[source]

Pre-flight check: do the patches together bound a closed volume?

cfMesh needs a closed domain. Handed an open surface it does not fail — it happily produces a small nonsense mesh that leaks into the surroundings, so the user only discovers the problem much later (or never). Catching it here turns a silent bad result into an early, actionable message.

Returns (is_watertight, n_open_boundary_edges, human_readable_message).

Return type:

tuple[bool, int, str]

Parameters:

meshes (list[Trimesh])

polyfoammesh.core.geometry.compute_curvature_sizing(meshes, cells_per_curvature=8, bbox_max=1.0)[source]

Estimate cell size needed to resolve surface curvature.

Uses face adjacency dihedral angles to detect curved regions (1-30°) and derives a cell size that puts cells_per_curvature cells across the minimum radius of curvature. Returns None when no curved surfaces are detected (shape is entirely flat-faceted).

Return type:

float | None

Parameters:
polyfoammesh.core.geometry.compute_patch_cell_sizes(meshes, detail='medium', seed=12648430)[source]

Compute per-patch cell sizes + boundary refinement parameters.

Return type:

tuple[dict[str, float], float | None, float | None]

Parameters:

For each mesh patch, samples its local thickness and derives a cell size that resolves it. Returns:

  • patch_cell_sizes: {name: cell_size} — only for patches whose suggested size is SMALLER than the global max.

  • boundary_cell_size: suggested cell size near walls (None if boundary refinement not needed).

  • boundary_refinement_thickness: distance (m) for boundary refinement (None if not needed).

polyfoammesh.core.geometry.build_graded_refinement_boxes(meshes, detail='medium', global_max_cell=0.05, cells_across=8, growth_rate=1.2, max_boxes=200, seed=12648430)[source]

Approximate a GMSH-style continuous local-sizing field for cfMesh using many small, growth-rate-graded objectRefinements boxes.

cfMesh/cartesianMesh has no equivalent of GMSH’s setSizeCallback — a continuous, point-by-point size field with smooth grading between fine and coarse regions. Its only real refinement tool is a handful of discrete zones (objectRefinements), and this project’s own throat_detector.detect_refinement_regions only ever emits the few “significant minima” it finds (2-3 zones, typically), leaving everything else at the uniform global size — good enough to flag an obvious narrow gap, not a substitute for a graded field. This builds a MUCH denser approximation instead:

  1. Sample local passage thickness across the whole surface (the same ray-cast sample_thickness_field GMSH’s own passage- thickness field and this session’s feature-aware minCellSize already use — validated, not the throat_detector’s former from-scratch reimplementation).

  2. Convert each sample to a target cell size (thickness / cells_across, clamped to [global_max_cell/20, global_max_cell]).

  3. Growth-rate relax the target sizes across ALL samples (same eikonal/Dijkstra propagation GMSH’s own curvature field uses, gmsh_wrapper._relax_size_field_growth_rate) — this is what gives a SMOOTH transition between a fine throat and the coarse bulk instead of a hard step at a zone boundary.

  4. Voxelize the relaxed field into a coarse 3D grid and emit one box per occupied voxel whose target size is meaningfully finer than the global max — a discretized, graded approximation of the continuous field, using cfMesh’s only real primitive.

max_boxes caps the voxel count (a very large objectRefinements block would bloat meshDict and slow cfMesh’s own zone lookup) — the voxel grid is coarsened until the box count fits.

Returns a list of box dicts (schema matching meshdict_gen.build_object_refinements’s box form: xmin/xmax/ ymin/ymax/zmin/zmax/cell_size). Empty list (never raises) when there is nothing to refine or sampling fails.

Return type:

list[dict]

Parameters:
polyfoammesh.core.geometry.suggest_cell_sizes(meshes=None, detail='medium', bbox_max_dim=None)[source]

Feature-aware cell size suggestion.

Parameters:
  • meshes (list[Trimesh] | None) – list of trimesh patches. If provided, used to sample local thickness and pick cell sizes that respect small features. If None, falls back to the old bbox-based algorithm.

  • detail (str) – ‘coarse’ | ‘medium’ | ‘fine’ — controls how aggressively the algorithm resolves small features.

  • bbox_max_dim (float | None) – explicit bbox max (required if meshes is None).

Return type:

tuple[float, float]

Returns:

(max_cell_size, min_cell_size) in metres.

polyfoammesh.core.geometry.unit_to_scale(unit)[source]

Convert a CAD unit string to a scale factor (CAD unit → metres).

Return type:

float

Parameters:

unit (str)

polyfoammesh.core.geometry.scale_meshes(meshes, factor)[source]

Multiply all vertex coordinates in-place by factor. Returns the input list.

Return type:

list[Trimesh]

Parameters:
polyfoammesh.core.geometry.cfmesh_cell_budget(max_cells_override=None, parallel_cores=1)[source]

RAM-aware cell-count ceiling for cfMesh/cartesianMesh — the equivalent of gmsh_wrapper._hardware_budget for the tet/GMSH path, which had NO counterpart on the cfMesh side (validate_cell_sizes only ever clamped against the bounding box, never against the machine’s actual RAM). Without this, a user requesting a fine maxCellSize on a large domain can ask cfMesh for a mesh that doesn’t fit in memory with no warning until the process is killed or thrashes the machine.

Bytes-per-cell: cartesianMesh’s own reference numbers put a real 14.5M-cell mesh at ~11 GB peak, i.e. ~760 bytes/cell — used here directly rather than guessed, the same way GMSH’s own bytes/cell was re-derived from first principles instead of an old, much too pessimistic constant (see _hardware_budget’s comment).

Same floor logic as the GMSH budget: the ceiling is max(50% of currently-free RAM, 25% of total RAM), so a machine that’s merely busy right now (browser open, previous mesh still in the viewer) doesn’t silently get a much coarser budget than the same idle machine would.

cartesianMesh actually RUNS inside the WSL2 VM, not on the Windows host — and WSL2 defaults to a memory cap of its own (50% of host RAM, or whatever .wslconfig sets), independent of the host’s real total. Capping only against the HOST’S RAM can let a request through that the host has room for but the WSL2 VM does not — measured live: a 32 GB host with WSL2 capped at ~15 GB total / ~9 GB available let an 8-11M cell request past a host-only budget, which then failed inside WSL2 during parallel decomposition/reconstruction. The smaller of the host-based and WSL-based budgets wins. WSL’s own per-rank decomposition/reconstruction overhead on TOP of the base mesh size (each of N ranks holds a partition, then reconstructParMesh briefly needs the full mesh again) is NOT separately modeled here — this budget bounds the base mesh, not the transient peak a highly-parallel run adds on top of it.

Return type:

dict

Parameters:
  • max_cells_override (int | None)

  • parallel_cores (int)

polyfoammesh.core.geometry.coarsen_for_ram_budget(max_cell, domain_volume, max_cells_override=None)[source]

Coarsen max_cell so domain_volume / max_cell**3 stays within cfmesh_cell_budget() — the RAM safety net, standalone so callers that already have their own bbox clamp (or none at all, like meshdict_gen.write_meshdict reading a surface STL directly) can apply just this check without validate_cell_sizes’s bbox/2 clamp running a second time on top of whatever the caller already did.

Returns (safe_max, warnings) — safe_max is unchanged when the estimate is already within budget.

Return type:

tuple[float, list[str]]

Parameters:
  • max_cell (float)

  • domain_volume (float)

  • max_cells_override (int | None)

polyfoammesh.core.geometry.validate_cell_sizes(bbox_max_dim, max_cell, min_cell, domain_volume=None, max_cells_override=None)[source]

Clamp cell sizes relative to the bounding box to avoid degenerate meshes.

domain_volume (bbox dx*dy*dz, or the true enclosed volume if known): when given, additionally estimates the cell count cfMesh would produce (domain_volume / max_cell**3) and coarsens max_cell further if it would exceed cfmesh_cell_budget(max_cells_override) — the RAM safety net the bbox-only clamp below never provided. Skipped (no-op) when domain_volume is not supplied, so existing callers that don’t pass it keep their exact previous behaviour.

Returns (safe_max, safe_min, warnings). Raises ValueError if clamping produces non-positive values.

Return type:

tuple[float, float, list[str]]

Parameters:
  • bbox_max_dim (float)

  • max_cell (float)

  • min_cell (float)

  • domain_volume (float | None)

  • max_cells_override (int | None)

polyfoammesh.core.geometry.snap_to_octree_level(cell_size, bbox_dim, ratio_max=1.5)[source]

Snap a cell size to the nearest cfMesh octree level.

cfMesh uses an octree where the root box covers the geometry with some padding. Cell sizes are root_size / 2^k for integer k. A size that is not exactly root_size / 2^k is silently rounded to the nearest valid level, so the requested size is not what the user gets.

This function estimates the root box size as bbox_dim * ratio_max (empirical default 1.5) and returns the closest valid size and its octree level.

Parameters:
  • cell_size (float) – Desired cell size in metres.

  • bbox_dim (float) – Maximum bounding-box dimension of the geometry.

  • ratio_max (float) – Factor to estimate root box size (empirical, default 1.5 based on cfMesh v2512 behaviour).

Return type:

tuple[float, int]

Returns:

(effective_size, level) where effective_size is the size that cfMesh actually uses, and level is the octree level (>= 1).

polyfoammesh.core.geometry.compute_volume(meshes)[source]

Return the summed volume of all patch meshes.

trimesh may emit warnings for non-watertight meshes; those are logged at debug level and skipped. The result is clamped to >= 0.

Return type:

float

Parameters:

meshes (list[Trimesh])

polyfoammesh.core.geometry.estimate_cell_count(volume, max_cell, min_cell)[source]

Estimate the final cell count before meshing.

Returns (low, nominal, high) with a +/-40%% margin around the nominal estimate based on the average cell size. A floor of 100 is enforced on all three values.

Return type:

tuple[int, int, int]

Parameters:
polyfoammesh.core.geometry.estimate_cell_count_geometric(meshes, volume, core_cell, patch_sizes=None)[source]

Geometry-aware cell-count estimate: near-wall refinement + bulk core.

estimate_cell_count divides the WHOLE volume by one average cell size, which is blind to local refinement: a small-area, finely-sized patch (e.g. a 0.04 m wall on a 3 m bbox) occupies a tiny fraction of the volume by geometry but a huge fraction of the CELLS, because cells there are tiny. That mismatch was the source of >10x estimate errors (documented at the call site in main_window.py: 19K estimated vs 2.3M actual on exactly this pattern).

Return type:

tuple[int, int, int]

Parameters:

Two-zone model instead, using the real per-patch surface area (already computed from the loaded trimesh patches, no extra meshing pass needed):

  • near-wall shell per patch: a slab of thickness _SHELL_DEPTH_CELLS * local_cell_size, volume = area * thickness, cells = shell_volume / local_cell_size**3

  • core: whatever volume is left over (>= 0), cells = core_volume / core_cell**3

Falls back to the plain volume/core_cell**3 estimate when there is no per-patch sizing information (patch_sizes empty/None) — same behaviour as before for geometries without local refinement.

Returns (low, nominal, high) with a +/-20%% margin (tighter than the +/-40%% blind estimate, since this one is grounded in real surface area rather than a single global average).

polyfoammesh.core.geometry.classify_faces_auto(shape, inlet_axis='Z', tol=0.01)[source]
Return type:

list[tuple[str, list[Face]]]

Parameters:
  • shape (Shape)

  • inlet_axis (str)

  • tol (float)

polyfoammesh.core.geometry.classify_faces(shape, inlet_axis='Z', strategy='auto', custom_tags=None)[source]
Return type:

list[tuple[str, list[Face]]]

Parameters:
  • shape (Shape)

  • inlet_axis (str)

  • strategy (str)

  • custom_tags (dict[int, str] | None)

polyfoammesh.core.geometry.height_scale(shape)[source]
Return type:

float

Parameters:

shape (Shape)

polyfoammesh.core.geometry.tessellate_patches(patches, tolerance=0.01, angle_tolerance=0.1)[source]
Return type:

list[Trimesh]

Parameters:
polyfoammesh.core.geometry.load_and_tessellate(filepath, tolerance=0.01, angle_tolerance=0.1)[source]
Return type:

list[Trimesh]

Parameters:
polyfoammesh.core.geometry.load_geometry(filepath)[source]

Load STEP or STL, returning a list of trimesh meshes (one per patch/solid).

STEP → classify_faces → tessellate_patches (existing flow). STL → load_stl (multi-solid aware, ASCII or binary).

Return type:

list[Trimesh]

Parameters:

filepath (Path | str)

polyfoammesh.core.geometry.split_single_stl_patch(mesh, angle_deg=40.0, axis_tol=0.05, pos_tol=0.02)[source]

Split a single-patch STL mesh into inlet/outlet/wall patches.

Mirrors the STEP auto-classification: components of faces joined by dihedral angles below angle_deg are grouped; a component whose area-weighted normal is (nearly) perpendicular to an axis AND whose centroid sits at that axis’ bbox extreme becomes a cap (inlet at the min end, outlet at the max end); everything else is ‘wall’.

Never raises and never renames when not confident: with fewer than two detected caps the original mesh is returned unchanged.

Return type:

list[Trimesh]

Parameters:
polyfoammesh.core.geometry.split_mesh_by_angle(mesh, angle_deg=30.0)[source]

Split mesh into surface patches by feature (dihedral) angle.

BaramMesh-style: faces joined by a dihedral angle smaller than angle_deg are merged into one patch. A smaller angle therefore produces more, smaller patches. The resulting submeshes are named surface_1, surface_2, … (1-based), ordered by component area descending so patch numbering is stable and meaningful.

Never raises: returns [mesh] unchanged when there is at most one component, or on any failure (the caller can always fall back to the original single patch).

Return type:

list[Trimesh]

Parameters:
  • mesh (Trimesh)

  • angle_deg (float)