polyfoammesh.core.geometry
Functions
|
Per-patch thickness sampling, then aggregated. |
|
Approximate a GMSH-style continuous local-sizing field for cfMesh using many small, growth-rate-graded |
|
RAM-aware cell-count ceiling for cfMesh/cartesianMesh — the equivalent of |
|
Pre-flight check: do the patches together bound a closed volume? |
|
|
|
|
|
Coarsen |
|
Return the maximum dimension of the geometry bounding box. |
|
Return (dx, dy, dz) of the geometry bounding box. |
|
Estimate cell size needed to resolve surface curvature. |
|
Compute per-patch cell sizes + boundary refinement parameters. |
|
Return the summed volume of all patch meshes. |
|
|
|
Estimate the final cell count before meshing. |
|
Geometry-aware cell-count estimate: near-wall refinement + bulk core. |
|
|
|
|
|
Load STEP or STL, returning a list of trimesh meshes (one per patch/solid). |
|
|
|
Load an STL file as a list of trimesh meshes (one per solid). |
|
Like |
|
Multiply all vertex coordinates in-place by factor. |
|
Snap a cell size to the nearest cfMesh octree level. |
|
Split mesh into surface patches by feature (dihedral) angle. |
|
Split a single-patch STL mesh into inlet/outlet/wall patches. |
|
Feature-aware cell size suggestion. |
|
|
|
Convert a CAD unit string to a scale factor (CAD unit → metres). |
|
Clamp cell sizes relative to the bounding box to avoid degenerate meshes. |
Classes
- 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.
- polyfoammesh.core.geometry.compute_bbox_dim(meshes)[source]
Return the maximum dimension of the geometry bounding box.
- polyfoammesh.core.geometry.compute_bbox_full(meshes)[source]
Return (dx, dy, dz) of the geometry bounding box.
- polyfoammesh.core.geometry.analyze_local_thickness(meshes, samples=192, seed=12648430)[source]
Per-patch thickness sampling, then aggregated.
- Return type:
- Parameters:
- Algorithm:
For each patch, allocate samples proportional to area (with a floor so small patches are never starved).
Sample thickness within each patch.
- 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_thicknessonly ever needed global percentiles (p1, p5, …), so_sample_thickness_one_meshdiscards WHERE each thickness was measured. A per-point sizing field (seegmsh_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
meshencloses 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 thismeshis 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) intests/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.
- 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).
- 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_curvaturecells across the minimum radius of curvature. ReturnsNonewhen no curved surfaces are detected (shape is entirely flat-faceted).
- polyfoammesh.core.geometry.compute_patch_cell_sizes(meshes, detail='medium', seed=12648430)[source]
Compute per-patch cell sizes + boundary refinement parameters.
- Return type:
- 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
objectRefinementsboxes.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 ownthroat_detector.detect_refinement_regionsonly 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:Sample local passage thickness across the whole surface (the same ray-cast
sample_thickness_fieldGMSH’s own passage- thickness field and this session’s feature-aware minCellSize already use — validated, not the throat_detector’s former from-scratch reimplementation).Convert each sample to a target cell size (thickness / cells_across, clamped to [global_max_cell/20, global_max_cell]).
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.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_boxescaps 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.
- 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:
- 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).
- polyfoammesh.core.geometry.scale_meshes(meshes, factor)[source]
Multiply all vertex coordinates in-place by factor. Returns the input list.
- 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_budgetfor the tet/GMSH path, which had NO counterpart on the cfMesh side (validate_cell_sizesonly ever clamped against the bounding box, never against the machine’s actual RAM). Without this, a user requesting a finemaxCellSizeon 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
.wslconfigsets), 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.
- polyfoammesh.core.geometry.coarsen_for_ram_budget(max_cell, domain_volume, max_cells_override=None)[source]
Coarsen
max_cellsodomain_volume / max_cell**3stays withincfmesh_cell_budget()— the RAM safety net, standalone so callers that already have their own bbox clamp (or none at all, likemeshdict_gen.write_meshdictreading a surface STL directly) can apply just this check withoutvalidate_cell_sizes’s bbox/2 clamp running a second time on top of whatever the caller already did.Returns (safe_max, warnings) —
safe_maxis unchanged when the estimate is already within budget.
- 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 coarsensmax_cellfurther if it would exceedcfmesh_cell_budget(max_cells_override)— the RAM safety net the bbox-only clamp below never provided. Skipped (no-op) whendomain_volumeis 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.
- 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^kfor integer k. A size that is not exactlyroot_size / 2^kis 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:
- Return type:
- Returns:
(effective_size, level)whereeffective_sizeis the size that cfMesh actually uses, andlevelis 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.
- 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.
- 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_countdivides 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:
- 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**3core: 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_sizesempty/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(shape, inlet_axis='Z', strategy='auto', custom_tags=None)[source]
- polyfoammesh.core.geometry.tessellate_patches(patches, tolerance=0.01, angle_tolerance=0.1)[source]
- polyfoammesh.core.geometry.load_and_tessellate(filepath, tolerance=0.01, angle_tolerance=0.1)[source]
- 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).
- 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_degare 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.
- 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_degare merged into one patch. A smaller angle therefore produces more, smaller patches. The resulting submeshes are namedsurface_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).