polyfoammesh.core.gmsh_wrapper

GMSH Python API wrapper — CAD analysis, surface mesh, volume mesh.

GMSH runs natively on Windows (no WSL). It uses OpenCASCADE to read STEP files directly, compute curvature and proximity fields, and generate high-quality surface and volume meshes.

Integration with cfMesh:
GMSH_HYBRID → GMSH analyses CAD + generates surface STL with

curvature-aware refinement → cfMesh fills volume

GMSH_DIRECT → GMSH generates tetrahedral mesh + BL → meshio

converts to OpenFOAM polyMesh

Requirements:

pip install gmsh meshio

Module Attributes

GMSH_ROBUST_OPT_ENV_VAR

Set by GmshVolumeWorker on a signature-triggered robust retry only.

GMSH_MANUAL_EQUIV_ENV_VAR

Set by GmshVolumeWorker on its last-ditch adaptive-off attempt.

Functions

apply_solution_size_field(gmsh_mod, ...[, ...])

Install a solution-derived target-cell-size field as background sizing.

compute_bl_stack(first_layer, growth_ratio, ...)

Total boundary-layer thickness: h1 * (r^n - 1) / (r - 1).

compute_bl_wall_size_floor(first_layer, ...)

Wall-cell size floor that lets the requested BL stack physically fit.

compute_sizing(filepath[, detail, user_lc])

Open a STEP/STP file in GMSH and compute curvature + proximity.

count_msh_element_types(msh_path)

Count 3D/2D element types in a GMSH MSH 2.2 file, by type code.

derive_manual_equivalent_sizes(volume_m3, ...)

Explicit (max_cell, min_cell) in metres whose volume-estimated tet count matches target_cells — the Phase D adaptive-off fallback sizing.

from_step(filepath)

Open a STEP file in GMSH, return physical surface names.

generate_surface_stl(filepath, output_stl[, ...])

Generate a curvature-adapted surface STL using GMSH.

generate_volume_mesh(filepath, output_msh[, ...])

Generate a full tetrahedral volume mesh using GMSH (direct flow).

gmsh_baked_bl_enabled()

True when POLYFOAMMESH_GMSH_BL is set to a truthy value.

gmsh_shutdown()

Finalize GMSH.

prepare_foamy_hex_mesh(filepath, case_dir[, ...])

Set up a foamyHexMesh case: a curvature-aware STL surface (same generator as the hybrid GMSH+cfMesh flow) plus a self-contained foamyHexMeshDict, ready for OFConfig.build_foamy_hex_mesh_cmd() to run via WSL.

surface_resolution_multiplier(surface_resolution)

Map the GUI Surface resolution preset (or an explicit float) to a multiplier on the curvature angular-error constant (_SURFACE_RESOLUTION_MULT).

Classes

GmshSizing([min_curvature_radius, ...])

Structured sizing information computed by GMSH for a CAD geometry.

polyfoammesh.core.gmsh_wrapper.surface_resolution_multiplier(surface_resolution)[source]

Map the GUI Surface resolution preset (or an explicit float) to a multiplier on the curvature angular-error constant (_SURFACE_RESOLUTION_MULT).

"Medium" (the default) returns exactly 1.0, so the historical behaviour is reproduced bit-for-bit when the control is left alone. Unknown values also fall back to 1.0 rather than silently coarsening/refining.

Return type:

float

polyfoammesh.core.gmsh_wrapper.compute_bl_stack(first_layer, growth_ratio, n_layers)[source]

Total boundary-layer thickness: h1 * (r^n - 1) / (r - 1).

first_layer is the ABSOLUTE first-layer height (metres), growth_ratio the layer-to-layer expansion, n_layers the count. Returns 0.0 for a disabled/degenerate stack (never raises).

Return type:

float

Parameters:
polyfoammesh.core.gmsh_wrapper.compute_bl_wall_size_floor(first_layer, growth_ratio, n_layers, max_extent)[source]

Wall-cell size floor that lets the requested BL stack physically fit.

stack / _BL_CELLS_ACROSS_STACK, capped at _BL_FLOOR_MAX_EXTENT_FRACTION * max_extent so the coupling can never ask for absurdly fine cells on a large part. Returns 0.0 (off) when the stack is disabled/degenerate or the geometry extent is unknown.

Return type:

float

Parameters:
polyfoammesh.core.gmsh_wrapper.gmsh_baked_bl_enabled()[source]

True when POLYFOAMMESH_GMSH_BL is set to a truthy value.

Default OFF so the historical pure-tet GMSH output is byte-identical.

Return type:

bool

polyfoammesh.core.gmsh_wrapper.count_msh_element_types(msh_path)[source]

Count 3D/2D element types in a GMSH MSH 2.2 file, by type code.

MSH 2.2 type codes: 1=line, 2=triangle, 3=quad, 4=tet, 5=hex, 6=prism, 7=pyramid. A pure-tet GMSH volume mesh returns {4: n}; a GMSH-baked boundary layer adds {6: n_prism} (and {3: ...} boundary quads). Pure parser (no gmsh import), so it is safe to call from tests and from a post-mesh probe.

Return type:

dict[int, int]

Parameters:

msh_path (Path | str)

class polyfoammesh.core.gmsh_wrapper.GmshSizing(min_curvature_radius=1.0, min_proximity=1.0, max_extent=1.0, suggested_surface_size=0.05, suggested_volume_size=0.1, patch_sizes=<factory>, n_physical_groups=0)[source]

Bases: object

Structured sizing information computed by GMSH for a CAD geometry.

Parameters:
min_curvature_radius: float = 1.0
min_proximity: float = 1.0
max_extent: float = 1.0
suggested_surface_size: float = 0.05
suggested_volume_size: float = 0.1
patch_sizes: dict[str, float]
n_physical_groups: int = 0
polyfoammesh.core.gmsh_wrapper.gmsh_shutdown()[source]

Finalize GMSH. Call once at app exit.

polyfoammesh.core.gmsh_wrapper.from_step(filepath)[source]

Open a STEP file in GMSH, return physical surface names.

Uses OpenCASCADE kernel. Returns the list of patch names found (physical groups), ready to be mapped to inlet/outlet/wall.

Return type:

list[str]

Parameters:

filepath (Path | str)

polyfoammesh.core.gmsh_wrapper.compute_sizing(filepath, detail='medium', user_lc=None)[source]

Open a STEP/STP file in GMSH and compute curvature + proximity.

Parameters:
  • filepath (Path | str) – Path to STEP file.

  • detail (str) – ‘coarse’ | ‘medium’ | ‘fine’ — controls how aggressively small features are resolved.

  • user_lc (float | None) – Optional override for the global element size.

Return type:

GmshSizing

Returns:

GmshSizing with min curvature radius, min proximity, and suggested per-patch surface/volume sizes.

polyfoammesh.core.gmsh_wrapper.generate_surface_stl(filepath, output_stl, detail='medium', user_lc=None)[source]

Generate a curvature-adapted surface STL using GMSH.

This is the hybrid flow:
  1. GMSH opens CAD (STEP)

  2. Computes curvature-aware sizing field

  3. Generates 2D surface mesh (triangles)

  4. Exports as ASCII STL → can be read by cfMesh for volume fill

Return type:

list[str]

Returns:

List of patch names found in the STL (suitable for inlet/outlet/wall mapping).

Parameters:
polyfoammesh.core.gmsh_wrapper.prepare_foamy_hex_mesh(filepath, case_dir, detail='medium')[source]

Set up a foamyHexMesh case: a curvature-aware STL surface (same generator as the hybrid GMSH+cfMesh flow) plus a self-contained foamyHexMeshDict, ready for OFConfig.build_foamy_hex_mesh_cmd() to run via WSL.

foamyHexMesh is OpenFOAM’s native conformal-Voronoi mesher — it builds genuine polyhedra directly from the surface geometry, with no tet-mesh + dual-conversion step at all. Investigated as the alternative to polyDualMesh’s face-orientation defect after confirming that defect survives every tet-generation strategy tried (curvature/feature-size sizing, gap-aware refinement, budget-driven sizing, both HXT and classic Delaunay algorithms) — it’s a limitation of polyDualMesh’s dual construction itself on complex real-world CAD, not of input tet mesh quality, so no amount of tet tuning was ever going to fix it.

locationInMesh — a point foamyHexMesh needs inside the volume to be meshed — is computed as the CAD volume’s own center of mass (gmsh.model.occ.getCenterOfMass), not guessed or asked of the user: for the tube/duct-like flow volumes this app targets (the STEP geometry defines the fluid passage directly, confirmed by every watertight-volume check so far), center of mass reliably falls inside the solid.

Return type:

dict

Parameters:
polyfoammesh.core.gmsh_wrapper.apply_solution_size_field(gmsh_mod, size_field_file, existing_bg_field=None)[source]

Install a solution-derived target-cell-size field as background sizing.

size_field_file is a GMSH Structured field file (text format) written by core.solution_adaptive.write_structured_size_field — a regular lattice of target cell sizes sampled from a CFD solution’s refinement indicator. Unlike the refinement_zones ball primitives, this is a genuinely spatially-continuous field: GMSH trilinearly interpolates it, so a refined region can follow the actual shape of a shear layer or a contraction instead of being approximated by axis-aligned spheres.

Two things this deliberately does NOT do the obvious way:

  1. It MIN-combines with existing_bg_field rather than calling setAsBackgroundMesh() on its own. Calling it directly would replace the geometry-adaptive field (curvature/small-feature/gap sizing) outright — which is exactly what the older refinement_zones block does, and why zones silently coarsen everything the geometry sizing had refined. Min-combining means the solution field can only ever ASK FOR SMALLER cells than geometry already demanded, never larger, which is the correct semantics for a refinement indicator.

  2. It lowers Mesh.CharacteristicLengthMin to the field’s own minimum. Verified directly against GMSH 4.15.2: that option is a hard floor applied AFTER the background field is evaluated — a probe box meshed with a background field asking for 0.02 produced 27,263 nodes with the floor at 0, and 443 nodes with the floor left at the field’s coarse value 0.15. Without this line the whole refinement request is silently clamped away and the “refined” mesh comes back essentially unchanged.

Returns a dict with the field’s min/max target size and the tag installed.

Return type:

dict

Parameters:
  • size_field_file (Path | str)

  • existing_bg_field (int | None)

polyfoammesh.core.gmsh_wrapper.GMSH_ROBUST_OPT_ENV_VAR = 'POLYFOAMMESH_GMSH_ROBUST_OPT'

Set by GmshVolumeWorker on a signature-triggered robust retry only. Enables the 2D optimizer inside robust mode (normally hard-off) — see _resolve_optimize for the measured justification.

polyfoammesh.core.gmsh_wrapper.GMSH_MANUAL_EQUIV_ENV_VAR = 'POLYFOAMMESH_GMSH_MANUAL_EQUIV'

Set by GmshVolumeWorker on its last-ditch adaptive-off attempt. Makes the wrapper derive explicit sizes from the cell target instead of adaptive sizing — see derive_manual_equivalent_sizes.

polyfoammesh.core.gmsh_wrapper.derive_manual_equivalent_sizes(volume_m3, target_cells)[source]

Explicit (max_cell, min_cell) in metres whose volume-estimated tet count matches target_cells — the Phase D adaptive-off fallback sizing.

The wrapper’s own cell-count estimate is est = vol / lc**3 (see the explicit-size budget guard in generate_volume_mesh); inverting it gives

max_cell = (vol / target_cells) ** (1/3)

which reproduces the Phase A manual baseline exactly: on the mm-declared venturi.step (bbox volume ~5.4e-12 m^3, target 200 000) it yields max_cell = 3.0e-6 m, the value that converged there. The min cell is 0.2 * max_cell — the same ratio the explicit-size path applies when the caller’s min is not finer, giving feature/curvature refinement inside the bulk without changing the target’s order of magnitude. Kept a pure, dependency-free function so the formula is unit-testable.

Return type:

tuple[float, float]

Parameters:
polyfoammesh.core.gmsh_wrapper.generate_volume_mesh(filepath, output_msh, detail='medium', user_lc=None, n_layers=0, bl_thickness=None, bl_expansion=1.2, refinement_zones=None, min_cell_size=None, max_cells_override=None, size_field_file=None, surface_resolution='medium', bl_wall_size_floor=0.0)[source]

Generate a full tetrahedral volume mesh using GMSH (direct flow).

This is the direct flow — no cfMesh needed. The mesh includes boundary layers if requested.

Steps:
  1. Open CAD (STEP)

  2. Compute size field

  3. Generate 3D tetrahedral mesh with optional BL

  4. Export as MSH (.msh)

  5. Convert to OpenFOAM polyMesh via meshio

Parameters:
  • size_field_file (Path | str | None) – optional GMSH Structured field file holding a solution-derived target cell size lattice (see apply_solution_size_field). Min-combined with whatever geometry-based sizing this function set up, so it can only refine further, never coarsen. This is the re-meshing hook for solution-adaptive refinement.

  • filepath (Path | str)

  • output_msh (Path | str)

  • detail (str)

  • user_lc (float | None)

  • n_layers (int)

  • bl_thickness (float | None)

  • bl_expansion (float)

  • refinement_zones (list[dict] | None)

  • min_cell_size (float | None)

  • max_cells_override (int | None)

  • surface_resolution (str | float)

  • bl_wall_size_floor (float)

Return type:

tuple[Path, list[str]]

Returns:

(path_to_msh, list_of_patch_names)