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
Set by GmshVolumeWorker on a signature-triggered robust retry only. |
|
Set by GmshVolumeWorker on its last-ditch adaptive-off attempt. |
Functions
|
Install a solution-derived target-cell-size field as background sizing. |
|
Total boundary-layer thickness: |
|
Wall-cell size floor that lets the requested BL stack physically fit. |
|
Open a STEP/STP file in GMSH and compute curvature + proximity. |
|
Count 3D/2D element types in a GMSH MSH 2.2 file, by type code. |
|
Explicit |
|
Open a STEP file in GMSH, return physical surface names. |
|
Generate a curvature-adapted surface STL using GMSH. |
|
Generate a full tetrahedral volume mesh using GMSH (direct flow). |
True when |
|
Finalize GMSH. |
|
|
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. |
|
Map the GUI |
Classes
|
Structured sizing information computed by GMSH for a CAD geometry. |
- polyfoammesh.core.gmsh_wrapper.surface_resolution_multiplier(surface_resolution)[source]
Map the GUI
Surface resolutionpreset (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:
- 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_layeris the ABSOLUTE first-layer height (metres),growth_ratiothe layer-to-layer expansion,n_layersthe count. Returns 0.0 for a disabled/degenerate stack (never raises).
- 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_extentso 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.
- polyfoammesh.core.gmsh_wrapper.gmsh_baked_bl_enabled()[source]
True when
POLYFOAMMESH_GMSH_BLis set to a truthy value.Default OFF so the historical pure-tet GMSH output is byte-identical.
- Return type:
- 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.
- 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:
objectStructured sizing information computed by GMSH for a CAD geometry.
- Parameters:
- 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.
- 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:
- Return type:
- 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:
GMSH opens CAD (STEP)
Computes curvature-aware sizing field
Generates 2D surface mesh (triangles)
Exports as ASCII STL → can be read by cfMesh for volume fill
- 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.
- 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
Structuredfield file (text format) written bycore.solution_adaptive.write_structured_size_field— a regular lattice of target cell sizes sampled from a CFD solution’s refinement indicator. Unlike therefinement_zonesball 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:
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_zonesblock 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.It lowers
Mesh.CharacteristicLengthMinto 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.
- 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_optimizefor 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 ingenerate_volume_mesh); inverting it givesmax_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 is0.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.
- 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:
Open CAD (STEP)
Compute size field
Generate 3D tetrahedral mesh with optional BL
Export as MSH (.msh)
Convert to OpenFOAM polyMesh via meshio
- Parameters:
size_field_file (
Path|str|None) – optional GMSHStructuredfield file holding a solution-derived target cell size lattice (seeapply_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.detail (str)
user_lc (float | None)
n_layers (int)
bl_thickness (float | None)
bl_expansion (float)
min_cell_size (float | None)
max_cells_override (int | None)
bl_wall_size_floor (float)
- Return type:
- Returns:
(path_to_msh, list_of_patch_names)