"""Polyhedral conversion via cfMesh polyDualMesh.
Runs cfMesh's ``polyDualMesh`` over the whole hex-dominant mesh,
converting every cell to an arbitrary polyhedron (a dual-mesh
operation). Despite the historical "Mosaic" name, this is NOT a
Star-CCM+ Mosaic-style mesher: there is no hex core, no conformal
polyhedral transition cap layer and no interface detection — the
entire mesh is converted in place.
Pipeline:
1. Count hex cells before conversion
2. polyDualMesh 90 -overwrite over the whole mesh
3. Count poly cells after conversion
4. Estimate a volume-ratio proxy (checkMesh max/min volume, else heuristic)
"""
from __future__ import annotations
import logging
import re
import subprocess
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from polyfoammesh.config import OFConfig
from polyfoammesh.core.validation import validate_case_dir
from polyfoammesh.octopoda_local import octo
logger = logging.getLogger(__name__)
# Maximum acceptable volume ratio at hex→poly transition
MAX_VOLUME_RATIO = 10.0
# Regex per OpenFOAM float (scientific notation support)
_OF_FLOAT_RE = re.compile(r"[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?")
[docs]
@dataclass
class MosaicParams:
"""Parameters controlling the polyDualMesh conversion."""
n_smoothing_iterations: int = 3
volume_ratio_target: float = 8.0
preserve_original: bool = True
poly_dual_aggregation: bool = True
[docs]
@dataclass
class MosaicResult:
success: bool = False
case_dir: str = ""
hex_cells: int = 0
poly_cells: int = 0
cell_reduction_pct: float = 0.0
volume_ratio: float = 0.0
warnings: list[str] = field(default_factory=list)
errors: list[str] = field(default_factory=list)
wall_time_seconds: float = 0.0
[docs]
class MosaicEngine:
"""PolyDualMesh conversion engine (historically named "Mosaic").
Converts the whole hex-dominant mesh to polyhedral via cfMesh's
polyDualMesh. The "Mosaic" name is historical — this is not a
Star-CCM+ Mosaic-style mesher.
Usage::
me = MosaicEngine(of_config)
me.set_case_dir("path/to/case")
result = me.run()
"""
def __init__(self, of_config: OFConfig | None = None) -> None:
self._of_config = of_config or OFConfig()
self._case_dir: Path | None = None
self._params = MosaicParams()
self._result = MosaicResult()
[docs]
def set_case_dir(self, case_dir: Path | str) -> None:
result = validate_case_dir(case_dir)
if not result.valid:
raise ValueError(result.message)
self._case_dir = Path(case_dir)
[docs]
def set_params(self, params: MosaicParams) -> None:
self._params = params
[docs]
def run(self) -> MosaicResult:
"""Execute the polyDualMesh conversion.
Steps:
1. Run polyDualMesh on the hex-dominant mesh
2. Parse cell count before/after
3. Estimate a volume-ratio proxy
"""
start = datetime.now()
self._result = MosaicResult()
octo.log_event("mosaic", "workflow_start", {"case_dir": str(self._case_dir)})
try:
if not self._case_dir:
raise RuntimeError("No case directory. Call set_case_dir() first.")
# Count hex cells before conversion
self._result.hex_cells = self._count_cells("hex")
# Run polyDualMesh conversion
self._step_poly_conversion()
# Count poly cells after
self._result.poly_cells = self._count_cells("poly")
if self._result.hex_cells > 0:
reduction = (
1 - self._result.poly_cells / self._result.hex_cells
) * 100
self._result.cell_reduction_pct = round(reduction, 1)
# Estimate volume ratio
self._result.volume_ratio = self._estimate_volume_ratio()
self._result.success = True
octo.log_event("mosaic", "workflow_complete", {
"hex_cells": self._result.hex_cells,
"poly_cells": self._result.poly_cells,
"reduction_pct": self._result.cell_reduction_pct,
})
except Exception as exc:
self._result.errors.append(str(exc))
logger.exception("Mosaic conversion failed")
octo.log_event("mosaic", "workflow_failed", {"error": str(exc)})
elapsed = (datetime.now() - start).total_seconds()
self._result.wall_time_seconds = elapsed
return self._result
def _step_poly_conversion(self) -> None:
"""Run polyDualMesh via WSL2.
Uses featureAngle=90 (measured best: -10% max skewness vs 45).
polyDualMesh uses -overwrite to modify constant/polyMesh in-place.
"""
if not self._case_dir:
return
linux_case_raw = self._of_config.wsl_linux_case_path(self._case_dir)
env_q = self._of_config._quoted_linux_path(self._of_config.env_script)
cmd = self._of_config._build_wsl_cmd(
f"source {env_q} 2>/dev/null; "
f"cd {linux_case_raw} && "
f"polyDualMesh 90 -overwrite 2>&1 | tail -15"
)
logger.info("Running polyDualMesh (mosaic, featureAngle=90)...")
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
if result.returncode != 0:
raise RuntimeError(
f"polyDualMesh failed (exit {result.returncode}):\n{result.stderr[-300:]}"
)
self._result.poly_cells = self._count_cells("poly")
logger.info("polyDualMesh conversion OK")
def _count_cells(self, stage: str = "hex") -> int:
"""Count cells in the polyMesh.
*stage* is unused: both "hex" (pre-conversion) and "poly"
(post-conversion) read the same constant/polyMesh/owner, since
polyDualMesh -overwrite modifies it in place — run() calls this
before and after _step_poly_conversion() to get each stage's real
count from the file as it stood at that point in time.
"""
if not self._case_dir:
return 0
from polyfoammesh.core.boundary_reader import count_cells
return count_cells(self._case_dir)
def _estimate_volume_ratio(self) -> float:
"""Estimate a cell volume-ratio proxy.
Uses the ratio of max to min cell volume from checkMesh output
when available, otherwise a heuristic based on cell counts.
"""
if not self._case_dir:
return 0.0
poly_points = self._case_dir / "constant" / "polyMesh" / "points"
if not poly_points.exists():
return 0.0
# Check for checkMesh log with volume statistics
log = self._case_dir / "log.checkMesh"
if log.exists():
text = log.read_text(encoding="utf-8", errors="replace")
m = re.search(rf"Min volume = ({_OF_FLOAT_RE.pattern}).*?Max volume = ({_OF_FLOAT_RE.pattern})", text, re.DOTALL)
if m:
min_v = abs(float(m.group(1)))
max_v = abs(float(m.group(2)))
if min_v > 0:
return round(max_v / min_v, 1)
if self._result.poly_cells > 0 and self._result.hex_cells > 0:
ratio = self._result.hex_cells / max(self._result.poly_cells, 1)
return round(ratio * 1.5, 1)
return 0.0
[docs]
def volume_ratio_acceptable(self) -> bool:
"""Check if the volume ratio meets the MAX_VOLUME_RATIO threshold."""
return self._result.volume_ratio <= MAX_VOLUME_RATIO