diff --git a/core/meshing_components/explicit/unstructured/mesh_data.py b/core/meshing_components/explicit/unstructured/mesh_data.py index 317ba94d..9cc74349 100644 --- a/core/meshing_components/explicit/unstructured/mesh_data.py +++ b/core/meshing_components/explicit/unstructured/mesh_data.py @@ -17,7 +17,6 @@ from numpy.typing import NDArray from core.object_components import StructuralModelResults, ExtentData from core.object_components import MeshResults, MeshType -from core.meshing_components.pre_checks import pre_check_regular_grid from core.meshing_components.explicit.unstructured.create_grid_fragment_surface import create_surface_grid, import_surfaces, fragment_surfaces from core.meshing_components.explicit.unstructured.structural_surfaces import build_grid_litho, import_structural_surfaces from core.meshing_components.explicit.unstructured.domain_geometry import ( @@ -2592,7 +2591,6 @@ class CSVSurfaceModelResults: positionInGroup=990, identifier='create_unstructured_mesh_data', # a unique identifier return_name='Mesh', # the name for the returned-port - input_checks=[pre_check_regular_grid], ) # inputs are handled via the method signature def create_unstructured_mesh_data( geomodel_result: typing.Union[StructuralModelResults, CSVSurfaceModelResults], @@ -2669,12 +2667,10 @@ def create_unstructured_mesh_data( Returns: MeshResults: An instance of the MeshResults class. - Raises: - ValueError: geomodel_result's structural model is on an OctreeGrid. + Structural models on a RegularGrid and on an OctreeGrid are both supported: + the surfaces come from the extended masked meshes, and the lithology of the + volumes is looked up on the structural grid (the finest octree cells). """ - # Pre-checks can be ignored/skipped by a caller (see docs/developers/components.md), - # so also enforced here. - pre_check_regular_grid(geomodel_result) # normalize diff --git a/core/meshing_components/explicit/unstructured/structural_surfaces.py b/core/meshing_components/explicit/unstructured/structural_surfaces.py index 433b46eb..0e3ac6e3 100644 --- a/core/meshing_components/explicit/unstructured/structural_surfaces.py +++ b/core/meshing_components/explicit/unstructured/structural_surfaces.py @@ -26,6 +26,7 @@ from scipy.spatial import ConvexHull, cKDTree from core.object_components import StructuralModelResults +from core.structural_modeling_components.structural_objects.grids.grid_classes import OctreeGrid, to_regular logger = logging.getLogger(__name__) @@ -71,10 +72,19 @@ class SurfacePiece: faces: NDArray[np.int64] +def _cell_spacing(grid) -> NDArray[np.float64]: + """Size of the structural grid cells as (dx, dy, dz): the finest cells on an OctreeGrid.""" + return np.asarray(grid.finest_spacing if isinstance(grid, OctreeGrid) else grid.spacing, dtype=float) + + def build_grid_litho(geomodel_result: StructuralModelResults) -> pd.DataFrame: """ Lithology of every structural grid cell, used to assign lithologies to the mesh volumes. + On an OctreeGrid the lithology is sampled exactly at the centres of the finest + cells (each octree cell covers whole finest cells), so the table looks like the + one of a RegularGrid at the finest resolution. + Args: geomodel_result: Structural model result. @@ -82,10 +92,17 @@ def build_grid_litho(geomodel_result: StructuralModelResults) -> pd.DataFrame: DataFrame with columns ``x``, ``y``, ``z`` (cell centres) and ``lithology``. """ frame = geomodel_result.structural_frame - # grid_coordinates is (N, 3); lith_block is (nx, ny, nz) -- flatten to (N,). + grid = frame.grid + if isinstance(grid, OctreeGrid): + coordinates = grid.equivalent_regular_grid().grid_coordinates + lithology = to_regular(grid, frame.cells, frame.lith_block).flatten() + else: + # grid_coordinates is (N, 3); lith_block is (nx, ny, nz) -- flatten to (N,). + coordinates = grid.grid_coordinates + lithology = frame.lith_block.flatten() return pd.concat([ - pd.DataFrame(frame.grid.grid_coordinates, columns=["x", "y", "z"]), - pd.DataFrame(frame.lith_block.flatten(), columns=["lithology"]), + pd.DataFrame(coordinates, columns=["x", "y", "z"]), + pd.DataFrame(lithology, columns=["lithology"]), ], axis=1) @@ -132,7 +149,7 @@ def collect_surface_pieces(geomodel_result: StructuralModelResults) -> List[Surf structural model was computed with an older version. """ frame = geomodel_result.structural_frame - spacing = np.asarray(frame.grid.spacing, dtype=float) + spacing = _cell_spacing(frame.grid) min_area = _MIN_PIECE_AREA_CELLS * float(np.sort(spacing)[:2].prod()) sources: List[Tuple[str, bool, object]] = [ @@ -352,7 +369,7 @@ def import_structural_surfaces(geomodel_result: StructuralModelResults) -> Tuple reference_surface_indices: Fault pieces as {label: position in ``surfaces``}; used by ``fragment_surfaces`` for fault physical groups and fault refinement. """ - spacing = np.asarray(geomodel_result.structural_frame.grid.spacing, dtype=float) + spacing = _cell_spacing(geomodel_result.structural_frame.grid) cell = float(spacing.min()) step = _BSPLINE_STEP_CELLS * float(spacing.max()) diff --git a/core/meshing_components/implicit/octree_informed.py b/core/meshing_components/implicit/octree_informed.py new file mode 100644 index 00000000..e53514da --- /dev/null +++ b/core/meshing_components/implicit/octree_informed.py @@ -0,0 +1,202 @@ +""" +Octree-informed structured mesh: a rectilinear hexahedral mesh whose cell sizes +follow the octree of a structural model. + +The cells are laid out like a regular grid (``n_x * n_y * n_z`` hexahedra on +three coordinate lists), but each axis has its own non-uniform spacing: fine +where the octree is refined to its max level (contacts, erosion boundaries, +faults), coarse elsewhere. Along each axis: + + 1) Interface density: the share of the max-level cells of the stored octree + in each slab of finest cells. + 2) Node positions by equidistribution of ``w = alpha * density + (1 - alpha) * uniform``: + every cell holds the same share of ``w``. + 3) Cell sizes limited to at least one finest octree cell and to a growth + factor between neighbours of at most ``max_growth``. + +Each cell takes the lithology of the octree cell at its center (a look-up in +the stored result, no interpolation). The coordinate lists are what +structured mesh generators take as spacing lists (e.g. MOOSE's +``CartesianMeshGenerator`` ``dx``/``ix``): ``np.diff`` of the edges. +""" + +from typing import List, Tuple + +import meshio +import numpy as np +import numpy.typing as npt +from py_api_wbgeo.nodesapi import wbgeo_component +from core import workbench_palette as palette + +from core.meshing_components.explicit.unstructured.mesh_data import build_point_sets, classify_boundary_nodes +from core.meshing_components.pre_checks import pre_check_octree_grid +from core.object_components import MeshResults, MeshType, StructuralModelResults +from core.structural_modeling_components.structural_objects.grids.grid_classes import OctreeCells, OctreeGrid + +FloatArray = npt.NDArray[np.float64] + +# Iterations of the size limiting (minimum size, growth factor, total length); +# it converges in a few for any reachable target. +_SPACING_ITERATIONS: int = 200 + + +@wbgeo_component( + description='Provides a structured hexahedral mesh whose cell sizes follow the octree of the structural model', + title='Create Octree-Informed Structured Mesh', + color=palette.MESH, + border_color=palette.BORDER, + group='Meshing', + positionInGroup=960, + identifier='wbgeo::meshing_create_octree_informed_structured_mesh', + return_name='Mesh', + input_checks=[pre_check_octree_grid], +) +def create_octree_informed_structured_mesh( + geomodel_result: StructuralModelResults, + n_cells_x: int = 0, + n_cells_y: int = 0, + n_cells_z: int = 0, + alpha: float = 0.7, + max_growth: float = 1.3, +) -> MeshResults: + """ + Create a rectilinear hexahedral mesh with cell sizes informed by the octree. + + Args: + geomodel_result: A structural model computed on an OctreeGrid. + n_cells_x: Cells along x; 0 for half the finest octree resolution. At + most the finest resolution (cells are at least one finest cell). + n_cells_y: Cells along y, as ``n_cells_x``. + n_cells_z: Cells along z, as ``n_cells_x``. + alpha: Weight of the interface density against a uniform spacing, + in ``[0, 1]``: 0 gives a uniform grid, 1 follows the density only. + max_growth: Largest size ratio of neighbouring cells along an axis (>= 1). + + Returns: + MeshResults with hexahedra grouped by lithology id (``cell_data["block_id"]``), + boundary point sets, and ``mesh_type`` OCTREE_INFORMED. + + Raises: + ValueError: The model is not on an OctreeGrid or not computed, or a + parameter is out of range. + """ + # Pre-checks can be skipped by a caller, so also enforced here. + pre_check_octree_grid(geomodel_result) + frame = geomodel_result.structural_frame + grid = frame.grid + edges = octree_informed_edges(grid, frame.cells, (n_cells_x, n_cells_y, n_cells_z), alpha, max_growth) + + # Lithology of the octree cell at each mesh cell's center. + centers = [0.5 * (e[:-1] + e[1:]) for e in edges] + cx, cy, cz = np.meshgrid(*centers, indexing="ij") + points_c = np.column_stack([cx.ravel(), cy.ravel(), cz.ravel()]) + block = np.asarray(frame.lith_block)[frame.cells.locate(grid, points_c)].astype(np.int64) # (n_x*n_y*n_z,) + + nodes, hexahedra = _rectilinear_hexahedra(edges) + cells: List[meshio.CellBlock] = [] + block_ids: List[np.ndarray] = [] + for block_id in np.unique(block): + members = hexahedra[block == block_id] + cells.append(meshio.CellBlock("hexahedron", members)) + block_ids.append(np.full(len(members), block_id, dtype=np.int64)) + + extent_mesh = np.array([edges[0][0], edges[0][-1], edges[1][0], edges[1][-1], edges[2][0], edges[2][-1]]) + point_sets = build_point_sets(classify_boundary_nodes(nodes, extent_mesh), len(nodes)) + return MeshResults( + nodes=nodes, + elements=cells, + cell_data={"block_id": block_ids}, + point_sets=point_sets, + mesh_type=MeshType.OCTREE_INFORMED, + ) + + +def octree_informed_edges( + grid: OctreeGrid, + cells: OctreeCells, + n_cells: Tuple[int, int, int], + alpha: float = 0.7, + max_growth: float = 1.3, +) -> Tuple[FloatArray, FloatArray, FloatArray]: + """ + Cell edge coordinates along x, y and z from the octree's interface density. + + Args: + grid: The octree grid. + cells: The stored cells of a structural model on it. + n_cells: Cells per axis; 0 for half the finest resolution. + alpha: Weight of the interface density against a uniform spacing, in ``[0, 1]``. + max_growth: Largest size ratio of neighbouring cells (>= 1). + + Returns: + Three increasing coordinate arrays, ``n + 1`` edges each, from the + extent's lower to its upper bound. + """ + if not 0.0 <= alpha <= 1.0: + raise ValueError(f"alpha must lie in [0, 1], got {alpha}.") + if max_growth < 1.0: + raise ValueError(f"max_growth must be at least 1, got {max_growth}.") + finest = np.asarray(grid.finest_resolution, dtype=np.int64) + fine = np.asarray(cells.level) == grid.max_level + edges = [] + for axis in range(3): + n_finest = int(finest[axis]) + n = int(n_cells[axis]) or max(1, n_finest // 2) + if not 1 <= n <= n_finest: + raise ValueError(f"Cells along axis {'xyz'[axis]} must lie in [1, {n_finest}] " + f"(the finest octree resolution), got {n}.") + counts = np.bincount(np.asarray(cells.ijk)[fine, axis], minlength=n_finest).astype(np.float64) + density = counts / counts.sum() if counts.sum() > 0 else np.full(n_finest, 1.0 / n_finest) + weight = alpha * density + (1.0 - alpha) / n_finest + low, high = grid.extent[2 * axis], grid.extent[2 * axis + 1] + sizes = _equidistributed_sizes(weight, n, (high - low) / n_finest, max_growth) + edges.append(low + np.concatenate([[0.0], np.cumsum(sizes)])) + edges[-1][-1] = high # exact upper bound despite rounding + return edges[0], edges[1], edges[2] + + +def _equidistributed_sizes(weight: FloatArray, n: int, h: float, max_growth: float) -> FloatArray: + """ + ``n`` cell sizes over ``len(weight)`` slabs of size ``h``, each holding an + equal share of ``weight`` (piecewise constant per slab), then limited to at + least ``h`` and a neighbour ratio of at most ``max_growth``, summing to the + axis length. + """ + length = h * weight.size + cumulative = np.concatenate([[0.0], np.cumsum(weight)]) + slab_edges = np.arange(weight.size + 1) * h + nodes = np.interp(np.linspace(0.0, cumulative[-1], n + 1), cumulative, slab_edges) + sizes = np.diff(nodes) + for _ in range(_SPACING_ITERATIONS): + before = sizes.copy() + sizes = np.maximum(sizes, h) + for k in range(1, n): # small cells next to large ones grow + sizes[k] = max(sizes[k], sizes[k - 1] / max_growth) + for k in range(n - 2, -1, -1): + sizes[k] = max(sizes[k], sizes[k + 1] / max_growth) + sizes *= length / sizes.sum() + if np.allclose(sizes, before, rtol=1e-12, atol=0.0): + break + return sizes + + +def _rectilinear_hexahedra(edges: Tuple[FloatArray, FloatArray, FloatArray]) -> Tuple[FloatArray, np.ndarray]: + """ + Nodes and hexahedra of the rectilinear grid on the edge coordinates. + + Node ``(i, j, k)`` has index ``(i * (ny + 1) + j) * (nz + 1) + k``; hexahedra + in cell order ``(i, j, k)``, corners as in the implicit structured mesh. + """ + nx, ny, nz = (len(e) - 1 for e in edges) + gx, gy, gz = np.meshgrid(*edges, indexing="ij") + nodes = np.column_stack([gx.ravel(), gy.ravel(), gz.ravel()]).astype(np.float64) + + def node(i, j, k): + return (i * (ny + 1) + j) * (nz + 1) + k + + i, j, k = (a.ravel() for a in np.meshgrid(np.arange(nx), np.arange(ny), np.arange(nz), indexing="ij")) + hexahedra = np.column_stack([ + node(i, j, k), node(i + 1, j, k), node(i + 1, j + 1, k), node(i, j + 1, k), + node(i, j, k + 1), node(i + 1, j, k + 1), node(i + 1, j + 1, k + 1), node(i, j + 1, k + 1), + ]).astype(np.int64) + return nodes, hexahedra diff --git a/core/meshing_components/mesh_format/exodus/Exo_format.py b/core/meshing_components/mesh_format/exodus/Exo_format.py index 1f1d061c..b260eb96 100644 --- a/core/meshing_components/mesh_format/exodus/Exo_format.py +++ b/core/meshing_components/mesh_format/exodus/Exo_format.py @@ -33,6 +33,7 @@ class MeshType(StrEnum): ObjectMeshType.IMPLICIT: MeshType.IMPLICIT, ObjectMeshType.STRUCTURED: MeshType.STRUCTURED, ObjectMeshType.UNSTRUCTURED: MeshType.UNSTRUCTURED, + ObjectMeshType.OCTREE_INFORMED: MeshType.IMPLICIT, # hexahedra with block ids, like the implicit mesh } diff --git a/core/meshing_components/pre_checks.py b/core/meshing_components/pre_checks.py index 384f3d25..2145110b 100644 --- a/core/meshing_components/pre_checks.py +++ b/core/meshing_components/pre_checks.py @@ -8,21 +8,39 @@ def pre_check_regular_grid(geomodel_result: StructuralModelResults) -> None: """ - Pre-check: meshing needs a structural model computed on a RegularGrid. + Pre-check for the implicit and the structured mesh: they need a structural + model computed on a RegularGrid. - The meshing components read the regular grid's layout (resolution, grid - coordinates, a lithology block per voxel, marching-cubes surfaces whose - vertices lie on the grid lines), which a model on an OctreeGrid doesn't - have. Raises to block the connection rather than fail somewhere inside the - mesher or, for the structured mesh, silently build an oversized mesh. - - Other geology inputs (the unstructured mesher also takes surfaces read - from CSV files) have no grid, so there is nothing to check. + Both read the regular grid's layout: the implicit mesh one hexahedron per + voxel of the lithology block, the structured mesh the marching-cubes surfaces + whose vertices lie on the grid lines. A model on an OctreeGrid has neither + (one hexahedron per octree cell would not be a conforming mesh). Raises to + block the connection rather than fail somewhere inside the mesher or, for + the structured mesh, silently build an oversized mesh. The unstructured mesh + and the octree-informed structured mesh accept octree models. """ if not isinstance(geomodel_result, StructuralModelResults): return if isinstance(geomodel_result.structural_frame.grid, OctreeGrid): raise ValueError( - "Meshing does not support structural models computed on an OctreeGrid yet. " - "Compute the structural model on a RegularGrid for meshing." + "This mesh needs a structural model computed on a RegularGrid. For a model on an " + "OctreeGrid, use 'Create Octree-Informed Structured Mesh' or 'Create Unstructured " + "Explicit Mesh'." + ) + + +def pre_check_octree_grid(geomodel_result: StructuralModelResults) -> None: + """ + Pre-check: the octree-informed mesh needs a structural model computed on an OctreeGrid. + + Its cell spacing comes from where the octree is refined, which a model on a + RegularGrid doesn't have. Raises to block the connection. + """ + frame = geomodel_result.structural_frame + if not isinstance(frame.grid, OctreeGrid): + raise ValueError( + "The octree-informed mesh needs a structural model computed on an OctreeGrid. " + "Use the other meshing components for models on a RegularGrid." ) + if frame.cells is None or frame.lith_block is None: + raise ValueError("The structural model has not been computed yet (no octree cells or lithology).") diff --git a/core/object_components.py b/core/object_components.py index 1dcbcc4f..482b70c8 100644 --- a/core/object_components.py +++ b/core/object_components.py @@ -158,9 +158,10 @@ class FaultModelResults: class MeshType(StrEnum): """ - Which meshing component produced a MeshResults -- the three mesh - generation approaches available (create_implicit_structured_mesh, - create_structured_mesh_data, create_unstructured_mesh_data). Set + Which meshing component produced a MeshResults -- the mesh generation + approaches available (create_implicit_structured_mesh, + create_structured_mesh_data, create_unstructured_mesh_data, and + create_octree_informed_structured_mesh for models on an OctreeGrid). Set automatically by each of those on the MeshResults they return, so downstream consumers (e.g. SfepyHydrothermalProblemBuilder) can read a mesh's own provenance instead of requiring it to be passed separately @@ -169,13 +170,14 @@ class MeshType(StrEnum): IMPLICIT = "implicit" STRUCTURED = "structured" UNSTRUCTURED = "unstructured" + OCTREE_INFORMED = "octree_informed" MeshTypeType = typing.Annotated[ MeshType, AnnotatedScriptType( name="MeshType", identifier="MeshTypeType", - controlled="Select|implicit|structured|unstructured", + controlled="Select|implicit|structured|unstructured|octree_informed", color=palette.PARAMETER, ), ] diff --git a/core/simulation_components/simulation_packages/golem/golem_model_builder.py b/core/simulation_components/simulation_packages/golem/golem_model_builder.py index 5dc68bd6..c7809b2a 100644 --- a/core/simulation_components/simulation_packages/golem/golem_model_builder.py +++ b/core/simulation_components/simulation_packages/golem/golem_model_builder.py @@ -34,13 +34,21 @@ ) from core import workbench_palette as palette -#: Mesh types GOLEM builders accept (the single place to extend, e.g. for octree meshes). +#: Mesh types GOLEM builders accept (the single place to extend). The +#: octree-informed mesh is exported like the implicit mesh (hexahedra, one +#: block per lithology, no boundary blocks). GOLEM_SUPPORTED_MESH_TYPES = frozenset({ MeshType.IMPLICIT, MeshType.STRUCTURED, MeshType.UNSTRUCTURED, + MeshType.OCTREE_INFORMED, }) + +def _supported_mesh_types_text() -> str: + """The accepted mesh types for error messages, e.g. 'implicit, octree_informed, ...'.""" + return ", ".join(sorted(t.value for t in GOLEM_SUPPORTED_MESH_TYPES)) + class GolemFaultProperties(RockUnitProperties): """Properties placed directly on a 2D fault element block.""" name: str = "fault" @@ -157,8 +165,8 @@ def __post_init__(self) -> None: for mesh in (self.mesh_results, self.mesh1, self.mesh2): if mesh is not None and mesh.mesh_type not in GOLEM_SUPPORTED_MESH_TYPES: raise ValueError( - "Custom GOLEM input requires implicit, structured, or " - f"unstructured WBGeo meshes; got {mesh.mesh_type!r}." + f"Custom GOLEM input requires a WBGeo mesh of type " + f"{_supported_mesh_types_text()}; got {mesh.mesh_type!r}." ) def referenced_meshes(self): @@ -344,9 +352,8 @@ class GolemHydrothermalProblemBuilder: def __post_init__(self) -> None: if self.mesh_results.mesh_type not in GOLEM_SUPPORTED_MESH_TYPES: raise ValueError( - "GOLEM requires mesh_results.mesh_type to be IMPLICIT, " - "STRUCTURED or UNSTRUCTURED; got " - f"{self.mesh_results.mesh_type!r}." + f"GOLEM requires a mesh of type {_supported_mesh_types_text()}; " + f"got {self.mesh_results.mesh_type!r}." ) if self.num_steps < 1: raise ValueError("num_steps must be >= 1") diff --git a/core/simulation_components/simulation_packages/sfepy/sfepy_model_builder.py b/core/simulation_components/simulation_packages/sfepy/sfepy_model_builder.py index 0b990c36..a326a08a 100644 --- a/core/simulation_components/simulation_packages/sfepy/sfepy_model_builder.py +++ b/core/simulation_components/simulation_packages/sfepy/sfepy_model_builder.py @@ -39,11 +39,11 @@ import pyvista as pv from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator from pydantic.dataclasses import dataclass -from scipy.ndimage import binary_dilation -from scipy.spatial import cKDTree from py_api_wbgeo.nodesapi import wbgeo_type from core.object_components import MeshResults, StructuralModelResults, SimulationResults, MeshType +from core.structural_modeling_components.structural_objects.grids.grid_classes import OctreeGrid +from core.structural_modeling_components.structural_objects.structural_objects import FaultMeshType from core import workbench_palette as palette logger = logging.getLogger(__name__) @@ -202,6 +202,8 @@ def effective_heat_capacity(self, fluid: FluidProperties) -> float: MeshType.IMPLICIT: "imp", MeshType.STRUCTURED: "str", MeshType.UNSTRUCTURED: "unstr", + # Hexahedra with block ids, like the implicit mesh: same export and run path. + MeshType.OCTREE_INFORMED: "imp", } @@ -219,7 +221,8 @@ def check_mesh_has_known_type(mesh_results: MeshResults) -> None: raise ValueError( "mesh_results.mesh_type is None -- SfepyHydrothermalProblemBuilder needs to know " "which meshing component produced this mesh (create_implicit_structured_mesh, " - "create_structured_mesh_data, or create_unstructured_mesh_data), which normally " + "create_structured_mesh_data, create_unstructured_mesh_data or " + "create_octree_informed_structured_mesh), which normally " "set this automatically. If mesh_results was constructed manually (e.g. in a " "test), set mesh_type explicitly to one of MeshType's members." ) @@ -418,58 +421,40 @@ def lithology_to_group_idx(geomodel_result: StructuralModelResults) -> Dict[int, return mapping -def fault_trace_on_grid(fault, active_mask: np.ndarray) -> np.ndarray: - """ - Boolean array, same shape as the structural model's lith_block, - marking grid cells adjacent to `fault`'s zero-crossing surface -- - i.e. where `fault.get_domain_mask()` (the "which side" mask, already - computed as scalar_field > scalar_value when the fault frame was - built) flips between one neighboring cell and the next along any - axis -- AND restricted to `active_mask` (see - compute_fault_zone_cell_mask()): the structural modeling component - supports *finite* faults that don't cut every stratigraphic group - (model9 is the clearest example; even model2's single fault could be - set to only affect its older group via set_fault_activity_by_index()). - Without this restriction, cells in a group the fault doesn't - actually reach would still show a "crossing" here -- get_domain_mask() - is a purely geometric quantity (scalar_field > scalar_value) that - doesn't know about fault_activity at all, only - effective_domain_components_for_group() (general.py) applies that - during the real lith_block computation, merging the fault's domains - back together (no real offset) for inactive groups. - """ - domain_mask = fault.get_domain_mask() - crossing = np.zeros(domain_mask.shape, dtype=bool) - for axis in range(domain_mask.ndim): - diff = np.diff(domain_mask, axis=axis) - idx_lo = [slice(None)] * domain_mask.ndim - idx_hi = [slice(None)] * domain_mask.ndim - idx_lo[axis] = slice(0, -1) - idx_hi[axis] = slice(1, None) - crossing[tuple(idx_lo)] |= diff - crossing[tuple(idx_hi)] |= diff - return crossing & active_mask - - def compute_fault_zone_cell_mask( mesh_results: MeshResults, geomodel_result: StructuralModelResults, fault_zone_n_voxels: int = 1, ) -> Optional[np.ndarray]: """ Boolean array, one entry per mesh cell (concatenated in - mesh_results.elements block order), True where that cell falls within - fault_zone_n_voxels of any fault's trace. None if there are no faults - in this structural model at all, or if the resulting mask is empty - (e.g. fault_zone_n_voxels too small relative to mesh resolution, or - fault_activity restricts every fault away from every group) -- both - logged as a warning rather than an error, since a caller's config - might be reused across faulted/unfaulted models. + mesh_results.elements block order), True where that cell lies in the + damage zone of a fault: its centroid within ``fault_zone_n_voxels + 0.5`` + structural grid cells of the fault's UNMASKED surface mesh. + + Geometric, from the faults' surface meshes, so it works for structural + models on a RegularGrid and an OctreeGrid and for every mesh type. The + distance is VTK's exact point-to-surface distance, measured per axis in + cells of the structural grid (finest cells on an OctreeGrid). The half + cell makes the zone of a fault parallel to a grid plane exactly the one + of the former voxel version (the voxel layers on both sides of the + surface, dilated by fault_zone_n_voxels); unlike that version, an oblique + fault's zone is not widened by the voxel staircase. + + A fault only counts for cells in groups it affects (fault_activity, 0 = + youngest group; basement, unknown and non-volume blocks always count): + the structural modeling component supports faults that don't cut every + group (e.g. model9), and the cells of a group the fault doesn't reach + must stay out of its zone. + + None if there are no faults in this structural model at all, or if the + resulting mask is empty (e.g. fault_activity restricts every fault away + from every group) -- both logged as a warning rather than an error, + since a caller's config might be reused across faulted/unfaulted models. Standalone module-level function (not just a method on SfepyHydrothermalProblemBuilder) so it's reusable by any caller wanting the same "damage zone" cell selection without SfepyHydrothermalProblemBuilder's - other machinery (rock-unit enumeration, auto-generated materials, - etc.) -- e.g. SfepyCustomBuilder, which only needs the cell selection - itself and leaves what to *do* with it entirely to the custom file. + other machinery -- e.g. SfepyCustomBuilder, which only needs the cell + selection itself and leaves what to *do* with it to the custom file. """ frame = geomodel_result.structural_frame fault_frame = getattr(frame, "fault_frame", None) @@ -479,47 +464,45 @@ def compute_fault_zone_cell_mask( "faults (structural_frame.fault_frame is empty/None) -- ignoring." ) return None + grid = frame.grid + cell_size = np.asarray(grid.finest_spacing if isinstance(grid, OctreeGrid) else grid.spacing, dtype=np.float64) - # Per-voxel group index, in fault_activity's convention (0 = - # youngest group; basement gets a sentinel index one past the last - # real group, so `group_idx >= youngest_idx` is always True for it - # regardless of youngest_idx -- basement sits below/outside every - # group, so any fault reaching this deep affects it unconditionally). - lith_to_group = lithology_to_group_idx(geomodel_result) + # Cell centroids (in structural-cell units) and each cell's group, in + # fault_activity's convention (0 = youngest; basement, unknown and + # non-volume blocks get the sentinel n_groups: always affected). n_groups = len(frame.structural_groups) - group_idx_grid = np.full(frame.lith_block.shape, n_groups, dtype=int) - for lith_id, group_idx in lith_to_group.items(): - group_idx_grid[frame.lith_block == lith_id] = group_idx + lith_to_group = lithology_to_group_idx(geomodel_result) + block_ids = (mesh_results.cell_data or {}).get("block_id") + centroids, cell_groups = [], [] + for i, block in enumerate(mesh_results.elements): + centroids.append(np.asarray(mesh_results.nodes)[block.data].mean(axis=1)) + lith = np.asarray(block_ids[i]) if block_ids is not None else np.full(len(block.data), -1) + cell_groups.append(np.array([lith_to_group.get(int(l), n_groups) for l in lith], dtype=int)) + if not centroids: + return None + centroids = np.concatenate(centroids) / cell_size + cell_groups = np.concatenate(cell_groups) fault_activity = frame.fault_activity or {} - combined_trace = np.zeros(frame.lith_block.shape, dtype=bool) + cell_mask = np.zeros(len(centroids), dtype=bool) for fault in fault_frame.fault_elements: - # Same default (0 = fully active) set_fault_frame() uses when - # fault_activity isn't explicitly restricted. - youngest_idx = fault_activity.get(fault.name, 0) - active_mask = group_idx_grid >= youngest_idx - combined_trace |= fault_trace_on_grid(fault, active_mask) - - if fault_zone_n_voxels > 0: - combined_trace = binary_dilation(combined_trace, iterations=fault_zone_n_voxels) - - tree = cKDTree(frame.grid.grid_coordinates) - flat_trace = combined_trace.ravel() - - cell_mask_chunks = [] - for block in mesh_results.elements: - centroids = mesh_results.nodes[block.data].mean(axis=1) - _, idx = tree.query(centroids) - cell_mask_chunks.append(flat_trace[idx]) - cell_mask = np.concatenate(cell_mask_chunks) if cell_mask_chunks else np.array([], dtype=bool) + vertices = fault.vertices.get(FaultMeshType.UNMASKED) + faces = fault.edges.get(FaultMeshType.UNMASKED) + if vertices is None or faces is None or len(vertices) == 0 or len(faces) == 0: + continue + active = cell_groups >= fault_activity.get(fault.name, 0) # groups the fault affects + if not active.any(): + continue + faces = np.asarray(faces, dtype=np.int64).reshape(-1, 3) + surface = pv.PolyData(np.asarray(vertices, dtype=np.float64) / cell_size, + np.column_stack([np.full(len(faces), 3), faces]).ravel()) + distance = np.abs(pv.PolyData(centroids[active]).compute_implicit_distance(surface)["implicit_distance"]) + cell_mask[np.flatnonzero(active)[distance <= fault_zone_n_voxels + 0.5]] = True if not cell_mask.any(): logger.warning( "fault_zone_n_voxels was given but no mesh cells fell within " - "fault_zone_n_voxels=%d of any *active* fault trace -- ignoring (try a " - "larger fault_zone_n_voxels, check the mesh actually resolves this model's " - "faults, or check fault_activity isn't restricting every fault away from " - "every group it's meshed in).", + "fault_zone_n_voxels=%d of any *active* fault surface -- ignoring.", fault_zone_n_voxels, ) return None @@ -605,10 +588,10 @@ class SfepyHydrothermalProblemBuilder: explicitly meshes fault surfaces, and SfePy itself has no fault/interface element either (only per-region material constants, same as lithology already uses) -- so this represents a fault as a "damage zone" band of cells - straddling its trace (`fault_zone_n_voxels` grid cells wide, computed on - the *structural model's* grid via each fault's `get_domain_mask()`, - then resampled to mesh cells the same way lithology is resampled for - unstructured meshes), a standard, simpler proxy for fault hydraulics + around its surface (mesh cells whose centroid lies within + `fault_zone_n_voxels + 0.5` cells of the *structural model's* grid from + the fault's surface mesh, see compute_fault_zone_cell_mask -- works on + both grids and every mesh type), a standard, simpler proxy for fault hydraulics (gouge seal or fracture-enhanced conduit) than an exact geometric split. All faults in the structural model are combined into one shared "fault zone" material region (`Omega_fault`) -- not per-fault -- deliberately @@ -693,8 +676,8 @@ def __post_init__(self): # aren't tagged anywhere on MeshResults for the mesh types that # actually work here (implicit/structured only carry lith_block). # So instead of a geometrically-exact fault surface, this treats a - # fault as a "damage zone" band of cells straddling its trace - # (n_voxels wide, on the *structural model's* grid) and gives them + # fault as a "damage zone" band of cells around its surface + # (n_voxels of the *structural model's* grid either side) and gives them # their own separate material -- a standard, simpler proxy for # fault-zone hydraulics (gouge seal or fracture-enhanced conduit) # than an exact geometric split, and the only mesh-type-agnostic @@ -753,9 +736,6 @@ def _map_mat_id_to_lithology(self) -> Dict[int, int]: def _lithology_to_group_idx(self) -> Dict[int, int]: return lithology_to_group_idx(self.geomodel_result) - def _fault_trace_on_grid(self, fault, active_mask: np.ndarray) -> np.ndarray: - return fault_trace_on_grid(fault, active_mask) - def _compute_fault_zone_cell_mask(self) -> Optional[np.ndarray]: return compute_fault_zone_cell_mask(self.mesh_results, self.geomodel_result, self.fault_zone_n_voxels) @@ -1331,8 +1311,8 @@ class SfepyCustomBuilder: fault_zone_n_voxels: optional opt-in for a "damage zone" cell selection, the same mechanism SfepyHydrothermalProblemBuilder uses (see - compute_fault_zone_cell_mask) -- a band of cells straddling each - active fault's trace gets reassigned its own group id + compute_fault_zone_cell_mask) -- a band of cells around each + active fault's surface gets reassigned its own group id (self.fault_group_id), referenceable from the custom file as 'cells of group {fault_group_id}' (e.g. as its own 'Omega_fault' region). Unlike SfepyHydrothermalProblemBuilder, no material/equation is diff --git a/docs/components/meshing/Manual_meshing.md b/docs/components/meshing/Manual_meshing.md index 9a77fc0c..29bd69cb 100644 --- a/docs/components/meshing/Manual_meshing.md +++ b/docs/components/meshing/Manual_meshing.md @@ -13,7 +13,9 @@ treatment of faults, stratigraphic boundaries, and unconformities. The Workbench addresses this with two complementary approaches --- **explicit** meshing (structured and unstructured) and **implicit** meshing --- that turn structural model output into water-tight 3D meshes -for geoscientific simulation. The Workbench focuses on 3D models +for geoscientific simulation. For structural models computed on an +**Octree Grid**, a third approach, the **octree-informed structured +mesh**, uses the octree's refinement to place the cells. The Workbench focuses on 3D models throughout, to better capture the Earth's three-dimensional structure, so all meshing methods produce 3D meshes. @@ -23,11 +25,14 @@ so all meshing methods produce 3D meshes. > These features are not yet implemented for structured or implicit > meshing. -> **Note:** All meshing methods need a structural model computed on a -> **Regular Grid**. A structural model computed on an **Octree Grid** +> **Note:** A structural model computed on an **Octree Grid** > (see the [structural modeling manual](../structural_modeling/Manual_structural_modeling.md)) -> is refused with an error when it is connected to a meshing component. -> Meshing from octree models is planned. +> can be meshed with **Create Unstructured Explicit Mesh** and with +> **Create Octree-Informed Structured Mesh** (see +> [step 4](#4-octree-informed-structured-mesh)). The implicit and the +> structured explicit mesh need a model computed on a **Regular Grid**: in +> the Workbench, the connection turns red with a message that points to +> the two meshers that accept octree models. ------------------------------------------------------------------------ @@ -56,9 +61,10 @@ and processing requirements. ## Workflow -Steps 1--3 are alternative meshing methods --- pick the one that fits -your model, rather than running them in sequence. Step 4 (export) -applies to the result of whichever method was used. +Steps 1--4 are alternative meshing methods --- pick the one that fits +your model, rather than running them in sequence. Step 4 only works for +models computed on an Octree Grid. Step 5 (export) applies to the result +of whichever method was used. ### 1. Explicit structured mesh @@ -150,6 +156,12 @@ requirements than structured meshing. This is the only meshing method that supports embedding engineering objects and faults. +It works for structural models computed on a Regular Grid and on an +Octree Grid, with the same parameters: the surfaces come from the +`extended_masked` surface meshes, which both grids provide, and the +lithology of each volume is looked up in the structural model (on an +Octree Grid, at the resolution of the finest octree cells). + #### Engineering objects All engineering objects below are optional, loaded from CSV files, and @@ -826,12 +838,108 @@ mesh_implicit_structured = create_implicit_structured_mesh( ) ``` -### 4. Export the mesh +### 4. Octree-informed structured mesh + +> **Workbench component:** `Create Octree-Informed Structured Mesh` + +A structured hexahedral mesh for structural models computed on an +**Octree Grid**. The cells are laid out like a regular grid +(`n_cells_x * n_cells_y * n_cells_z` hexahedra in rows, columns and +layers), but the spacing along each axis follows the octree: cells are +small where the octree is refined to its maximum level (contacts, +unconformities, faults) and large elsewhere. Each cell takes the +lithology of the octree cell at its centre, so the mesh needs no +interpolation and no surface meshing, and it is fast to build. + +How the spacing is found, per axis: + +1. For each slab of finest octree cells along the axis, the share of + cells that are refined to the maximum level gives an interface + density. +2. The cell edges are placed so that every cell holds the same share of + `alpha * density + (1 - alpha) * uniform`. +3. Cells are at least one finest octree cell wide, and neighbouring + cells differ in size by at most `max_growth`. + +Because the spacing is set per axis, a refined zone always spans the +whole model along the other two axes (a fine layer of cells around a +horizontal contact, a fine column of cells around a vertical fault). The +mesh therefore pays off most for models whose structures are unevenly +distributed along the axes, such as faulted models. For simple layered +models it is about as accurate as a uniform mesh with the same number of +cells. The refinement follows the geology only, not physical features +such as thermal boundary layers. + +Trade-offs at a glance: + +- **Structured mesh (the main advantage):** the cells are hexahedra in + rows, columns and layers that share whole faces with their + neighbours, exactly as in the implicit mesh. +- **Layer boundaries are approximated, not followed:** each cell takes + the lithology at its centre, so boundaries become staircases along + the cell faces, as in the implicit mesh. Finer cells near a boundary + make the steps smaller, but dipping or curved boundaries are never + followed exactly. A high `alpha` concentrates cells at the + interfaces and coarsens the rest of the model, which can place some + boundaries worse than a uniform mesh does; `alpha = 0.7` was the best + compromise in our tests. For a mesh that follows the boundaries, use + the unstructured mesh, which also accepts octree models. +- **Unnecessary refinement due to global axis-wise subdivision:** + unlike the adaptive octree grid of a structural model, where + refinement is localized around geological contacts and faults, the + octree-informed structured mesh propagates refinement along entire + coordinate planes. Consequently, cells are refined even in regions + far from geological features, so for a given number of cells fewer + of them end up near the features, without necessarily improving + local accuracy. + This limitation is particularly pronounced for localized, inclined, + or irregular geological structures. + +The inputs are: + +- **`geomodel_result`**: A structural model computed on an Octree + Grid. A model on a Regular Grid is refused (use the other meshing + methods for it). +- **`n_cells_x`**, **`n_cells_y`**, **`n_cells_z`** *(optional)*: The + number of cells along each axis. `0` (the default) uses half the + finest octree resolution along that axis; the maximum is the finest + resolution, since a cell is at least one finest octree cell. +- **`alpha`** *(optional)*: How strongly the spacing follows the + octree, between `0` and `1`. `0` gives a uniform grid, `1` follows + the interface density only. Default `0.7`. +- **`max_growth`** *(optional)*: The largest size ratio of neighbouring + cells along an axis (at least `1`). Smaller values give a gentler + grading. Default `1.3`. + +The output is a structured 3D hexahedral mesh with mesh type +`octree_informed`. Both simulators accept it, SfePy and GOLEM, in the +same way as the implicit mesh. + +Example call in the codebase: + +``` python +mesh_octree_informed = create_octree_informed_structured_mesh( + geomodel_result=structural_model_result_octree, + n_cells_x=0, + n_cells_y=0, + n_cells_z=0, + alpha=0.7, + max_growth=1.3, +) +``` + +The edge coordinates per axis are available from +`octree_informed_edges(grid, cells, (n_cells_x, n_cells_y, n_cells_z), alpha, max_growth)`, +e.g. as spacing lists (`numpy.diff` of the edges) for other structured +mesh generators. Section 5 of the model 1 and model 2 example scripts +shows the whole workflow on an Octree Grid. + +### 5. Export the mesh > **Workbench component:** `Export Mesh` The Workbench provides a unified export interface for meshes generated -by any of the three methods above. Meshes can be exported to **Exodus**, +by any of the four methods above. Meshes can be exported to **Exodus**, **Gmsh**, **Abaqus**, **Ansys**, **FeFlow**, **STL**, **VTK**, **VTU**, and **VTM** formats --- in the visual interface (visual DSL), `Export Mesh` exposes all of these through a single format selector. @@ -864,8 +972,9 @@ buf = export_mesh_results_to_exodus(mesh_unstructured_with_objects, type="unstr" ``` Here, `type` is `"unstr"`, `"str"`, or `"imp"` depending on which of the -three meshing methods produced the mesh, ensuring correct formatting -during export. +meshing methods produced the mesh, ensuring correct formatting during +export. The octree-informed structured mesh uses `"imp"`, like the +implicit mesh. ------------------------------------------------------------------------ @@ -903,8 +1012,8 @@ plot_mesh_3d(mesh_unstructured_with_objects, structural_model_result, style="sur ## Output > **Workbench:** The `Mesh` output port of `Create Structured Explicit Mesh`, -> `Create Unstructured Explicit Mesh`, or `Create Structured Implicit Mesh` -> carries the result. It can be connected directly to `Export Mesh` +> `Create Unstructured Explicit Mesh`, `Create Structured Implicit Mesh`, +> or `Create Octree-Informed Structured Mesh` carries the result. It can be connected directly to `Export Mesh` > for export, or inspected in-place using `Plot Mesh in 3D`. Each meshing method returns a `MeshResults` object: @@ -915,6 +1024,10 @@ Each meshing method returns a `MeshResults` object: - **`cell_data`** *(optional)* --- per-cell data arrays aligned with `elements`, such as material/lithology IDs. - **`point_sets`** *(optional)* --- per-node data arrays. +- **`mesh_type`** *(optional)* --- which meshing method produced the + mesh: `implicit`, `structured`, `unstructured` or `octree_informed`. + The simulation components read it to choose the matching export and + run path. - **`mesh`** --- a PyVista `MultiBlock` view of the same data, built on first access. Block 0 is the basement (lithology 0); subsequent blocks follow oldest to youngest. diff --git a/docs/components/simulation/Manual_simulation.md b/docs/components/simulation/Manual_simulation.md index 9d900298..6e77559a 100644 --- a/docs/components/simulation/Manual_simulation.md +++ b/docs/components/simulation/Manual_simulation.md @@ -144,7 +144,8 @@ The component accepts the following parameters: `options`) instead of treating them as ordinary lithology. Has no effect if the structural model has no faults. Default `False`. - **`fault_zone_n_voxels`** *(optional)*: Width of the fault damage - zone, in structural-grid voxels. Default `1`. + zone, in structural-grid cells (the finest cells on an Octree Grid). + Default `1`. - **`p_top`**, **`p_bottom`** *(optional)*: Pressure boundary values at the model top/bottom, in Pa. Default `p_top=0.0`, `p_bottom=1e6`. - **`t_top`**, **`t_bottom`** *(optional)*: Temperature boundary @@ -169,8 +170,8 @@ The component accepts the following parameters: In the codebase, the mesh and structural model are provided through two additional parameters: -- **`mesh_results`**: The mesh to solve on (implicit, structured, or - unstructured). +- **`mesh_results`**: The mesh to solve on (implicit, structured, + unstructured, or octree-informed structured). - **`geomodel_result`**: The structural model. Example call in the codebase: @@ -241,7 +242,8 @@ the structural model used to generate that mesh. The component accepts the following parameters: - **`input_file`**: Path to a complete SfePy input file (`.py`). - **`fault_zone_n_voxels`** *(optional)*: If set, gives cells within - this many structural-grid voxels of any active fault's trace their + this many structural-grid cells (finest cells on an Octree Grid) of + any active fault's surface their own region id --- the same damage-zone cell selection `Build SfePy Hydrothermal Problem` uses, referenceable from the custom file as `cells of group N`. @@ -314,8 +316,8 @@ Important inputs and controls in Workbench include: In the codebase, the mesh and structural model are provided through two additional parameters: -- **`mesh_results`**: Mesh used by GOLEM (implicit, structured, or - unstructured). +- **`mesh_results`**: Mesh used by GOLEM (implicit, structured, + unstructured, or octree-informed structured). - **`geomodel_result`**: Structural model. In the codebase, the properties configured through **`options`** in the Workbench are provided through three separate parameters: diff --git a/docs/components/structural_modeling/Manual_structural_modeling.md b/docs/components/structural_modeling/Manual_structural_modeling.md index d5de3207..ed82dd0d 100644 --- a/docs/components/structural_modeling/Manual_structural_modeling.md +++ b/docs/components/structural_modeling/Manual_structural_modeling.md @@ -63,7 +63,7 @@ from core.structural_modeling_components.structural_objects.grids.grid_classes i grid = OctreeGrid(extent=(0, 2500, 0, 1000, 0, 1000), base_resolution=(10, 4, 4), max_level=4) ``` -The rest of the workflow is the same as with a Regular Grid. +The rest of the workflow is the same as with a Regular Grid. For meshing, use the unstructured explicit mesh or the octree-informed structured mesh (see the [meshing manual](../meshing/Manual_meshing.md)). Section 5 of the model 1 and model 2 example scripts runs the whole workflow on an Octree Grid, from the structural model to the simulation. ### 2. Load input data @@ -406,7 +406,7 @@ plot_fault_model_2D(fault_model_result.fault_frame, axis="y", index=15) - **Fault surface meshes** — `masked`, `unmasked`, `extended` and `extended_masked` meshes for each fault element. The fault's `extended_masked` mesh is cut at the base of all groups younger than the youngest group the fault offsets, and reaches about one grid cell beyond it. - **All intermediate results** — scalar values per element, age masks per group, and the fault domain map are stored on the structural frame within the result object and can be accessed programmatically for further analysis or visualisation. -The `StructuralModelResults` object is the direct input to the meshing components. The meshing components currently need a structural model computed on a Regular Grid and refuse a model computed on an Octree Grid (see the [meshing manual](../meshing/Manual_meshing.md)). +The `StructuralModelResults` object is the direct input to the meshing components. A model computed on an Octree Grid can be meshed with the unstructured explicit mesh and the octree-informed structured mesh; the implicit and the structured explicit mesh need a Regular Grid (see the [meshing manual](../meshing/Manual_meshing.md)). ### Save, load and export diff --git a/examples/synthetic_examples/model1/WBGeo1.0_model1.py b/examples/synthetic_examples/model1/WBGeo1.0_model1.py index c7fe206d..66786637 100644 --- a/examples/synthetic_examples/model1/WBGeo1.0_model1.py +++ b/examples/synthetic_examples/model1/WBGeo1.0_model1.py @@ -19,6 +19,10 @@ 4. Alternative: simulation with SfePy (optional) 4.1 Generated hydrothermal problem 4.2 Custom input file + 5. Alternative: the model on an Octree Grid (optional) + 5.1 Octree structural model + 5.2 Meshing the octree model (octree-informed structured and explicit unstructured mesh) + 5.3 Simulation on the octree-informed mesh """ # Uncomment the two lines below to enable detailed log output from all WBGeo components. @@ -29,7 +33,7 @@ import pandas as pd import os -from core.structural_modeling_components.structural_objects.grids.grid_classes import RegularGrid +from core.structural_modeling_components.structural_objects.grids.grid_classes import RegularGrid, OctreeGrid from core.object_components import InputData_StructuralElements from core.structural_modeling_components import general @@ -46,6 +50,7 @@ ExtraPlaneRefinement, GeneralRefinement) from core.meshing_components.meshing_visualization.meshing_visualization import plot_mesh_3d from core.meshing_components.implicit.export_implicit import create_implicit_structured_mesh +from core.meshing_components.implicit.octree_informed import create_octree_informed_structured_mesh from core.meshing_components.mesh_format.mesh_export import ( export_mesh_results_to_exodus, export_mesh_results_to_vtu, export_mesh_results_to_vtk, export_mesh_results_to_feflow, @@ -486,3 +491,86 @@ # print("SfepyCustomBuilder T mean:", custom_data_by_time.node_data_by_time[custom_final_time]["T"].mean()) # plot_variable_at_a_time(custom_data_by_time, "T", time=custom_final_time, cmap="coolwarm", show_edges=True) # plot_cross_section_2D(custom_data_by_time, "T", origin=(500, 500, 500), normal=(0, 1, 0), cmap="coolwarm") + +# ============================================================================== +#%% 5. Alternative: the model on an Octree Grid (optional) +# ============================================================================== + +# The same model on an adaptive OctreeGrid instead of a RegularGrid. The extent is split into +# base blocks (level 0), and cells are halved down to max_level where the model changes (here +# around the two surfaces). Finest cells: base_resolution * 2**max_level, here 64 x 64 x 64 +# (about 15.6 m). Octree models can be meshed with the octree-informed structured mesh and the +# explicit unstructured mesh; the implicit and the explicit structured mesh need a RegularGrid. +# Uncomment the section to run it. It reuses the input data of section 1.1 and the rock and +# fluid properties of section 3.1. + +#%% 5.1 Octree structural model + +# Create an octree grid with the same extent +# grid_octree = OctreeGrid( +# extent=(0, 1000, 0, 1000, 0, 1000), +# base_resolution=(2, 2, 2), # base blocks of 500 m +# max_level=5, +# ) + +# Build and compute the structural model on it (surfaces by dual contouring) +# frame_octree = general.build_structural_frame(input_data_elements=data_elements, grid=grid_octree) +# structural_model_result_octree = general.compute_structural_model( +# frame_octree, +# extract_meshes=True, +# verbose=True, +# ) + +# Octree cells of the structural model per level +# structural_model_result_octree.structural_frame.detailed_report() + +# Plot the results; show_grid=True draws the outlines of the octree cells the section cuts +# plot_structural_model_2D(structural_model_result_octree.structural_frame, show_grid=True) +# plot_structural_model_3D(structural_model_result_octree.structural_frame, show_surface_meshes=True) + +#%% 5.2 Meshing the octree model + +# Octree-informed structured mesh: hexahedra laid out like a regular grid (n_x * n_y * n_z cells), +# but each axis is spaced by the octree: fine where the octree is refined, coarse elsewhere. +# n_cells_x/y/z: cells per axis, 0 = half the finest octree resolution (here 32 x 32 x 32) +# alpha: 0 = uniform grid, 1 = follow the octree refinement only +# max_growth: largest size ratio of neighbouring cells along an axis +# mesh_octree_informed = create_octree_informed_structured_mesh( +# geomodel_result=structural_model_result_octree, +# n_cells_x=0, +# n_cells_y=0, +# n_cells_z=0, +# alpha=0.7, +# max_growth=1.3, +# ) + +# Explicit unstructured mesh, the same call as for the RegularGrid model in section 2 +# mesh_explicit_unstructured_octree = create_unstructured_mesh_data( +# geomodel_result=structural_model_result_octree, +# mesh_size=30, +# curve_mesh_size=5, +# ) + +# Plot the meshes +# plot_mesh_3d(mesh_octree_informed, structural_model_result_octree, show_plotter=True) +# plot_mesh_3d(mesh_explicit_unstructured_octree, structural_model_result_octree, show_plotter=True) + +#%% 5.3 Simulation on the octree-informed mesh + +# SfePy as in section 4.1 (see the note on linear_solver there); GOLEM takes the mesh the same way +# (mesh_results=mesh_octree_informed in GolemHydrothermalProblemBuilder, section 3.2) +# builder_octree = SfepyHydrothermalProblemBuilder( +# mesh_results=mesh_octree_informed, +# geomodel_result=structural_model_result_octree, +# rock_properties=rock_properties, +# fluid=fluid, +# include_flow=True, +# end_time=5e11, +# num_steps=3, +# ) +# data_by_time_octree = run_simulation_sfepy(builder_octree, stream_output=True) + +# Plot the simulation results +# final_time_octree = max(data_by_time_octree.nodes_by_time.keys()) +# plot_variable_at_a_time(data_by_time_octree, "T", time=final_time_octree, cmap="coolwarm", show_edges=True) +# plot_cross_section_2D(data_by_time_octree, "T", origin=(500, 500, 500), normal=(0, 1, 0), cmap="coolwarm") diff --git a/examples/synthetic_examples/model2/WBGeo1.0_model2.py b/examples/synthetic_examples/model2/WBGeo1.0_model2.py index f160540e..c7d3a827 100644 --- a/examples/synthetic_examples/model2/WBGeo1.0_model2.py +++ b/examples/synthetic_examples/model2/WBGeo1.0_model2.py @@ -22,6 +22,10 @@ 4. Alternative: simulation with SfePy (optional) 4.1 Generated hydrothermal problem 4.2 Custom input file + 5. Alternative: the model on an Octree Grid (optional) + 5.1 Octree fault and structural model + 5.2 Meshing the octree model (octree-informed structured and explicit unstructured mesh) + 5.3 Simulation on the octree-informed mesh """ # Uncomment the two lines below to enable detailed log output from all WBGeo components. @@ -33,7 +37,7 @@ import os import tempfile -from core.structural_modeling_components.structural_objects.grids.grid_classes import RegularGrid +from core.structural_modeling_components.structural_objects.grids.grid_classes import RegularGrid, OctreeGrid from core.structural_modeling_components.structural_model_file import save_structural_model, load_structural_model from core.structural_modeling_components.structural_model_export import export_structural_model @@ -52,6 +56,7 @@ ExtraPlaneRefinement, GeneralRefinement) from core.meshing_components.meshing_visualization.meshing_visualization import plot_mesh_3d from core.meshing_components.implicit.export_implicit import create_implicit_structured_mesh +from core.meshing_components.implicit.octree_informed import create_octree_informed_structured_mesh from core.meshing_components.mesh_format.mesh_export import ( export_mesh_results_to_exodus, export_mesh_results_to_vtu, export_mesh_results_to_vtk, export_mesh_results_to_feflow, @@ -561,3 +566,99 @@ # custom_final_time = max(custom_data_by_time.nodes_by_time.keys()) # plot_variable_at_a_time(custom_data_by_time, "T", time=custom_final_time, cmap="coolwarm", show_edges=False) # plot_cross_section_2D(custom_data_by_time, "T", origin=(1250, 500, 500), normal=(0, 1, 0), cmap="coolwarm") + +# ============================================================================== +#%% 5. Alternative: the model on an Octree Grid (optional) +# ============================================================================== + +# The same model on an adaptive OctreeGrid instead of a RegularGrid. The extent is split into +# base blocks (level 0), and cells are halved down to max_level where the model changes (here +# around the surfaces, the unconformity and the fault). Finest cells: base_resolution * 2**max_level, +# here 160 x 64 x 64 (about 15.6 m). Octree models can be meshed with the octree-informed +# structured mesh and the explicit unstructured mesh; the implicit and the explicit structured +# mesh need a RegularGrid. +# Uncomment the section to run it. It reuses the input data of sections 1.1 and 1.4 and the +# rock, fault and fluid properties of section 3.1. + +#%% 5.1 Octree fault and structural model + +# Create an octree grid with the same extent +# grid_octree = OctreeGrid( +# extent=(0, 2500, 0, 1000, 0, 1000), +# base_resolution=(5, 2, 2), # base blocks of 500 m +# max_level=5, +# ) + +# Fault model on the octree (refined to max_level along the fault) +# fault_frame_octree = general_faults.build_fault_frame(input_data_fault_elements=data_faults, grid=grid_octree) +# fault_model_result_octree = general_faults.compute_fault_domains(fault_frame_octree) + +# Structural model on the same octree, with the octree fault model +# frame_octree = general.build_structural_frame(input_data_elements=data_elements, +# grid=grid_octree, +# fault_model_results=fault_model_result_octree +# ) +# structural_model_result_octree = general.compute_structural_model( +# frame_octree, +# extract_meshes=True, +# verbose=True, +# ) + +# Octree cells of the structural model per level +# structural_model_result_octree.structural_frame.detailed_report() + +# Plot the results; show_grid=True draws the outlines of the octree cells the section cuts +# plot_structural_model_2D(structural_model_result_octree.structural_frame, show_grid=True) +# plot_structural_model_3D(structural_model_result_octree.structural_frame, show_surface_meshes=True) + +#%% 5.2 Meshing the octree model + +# Octree-informed structured mesh: hexahedra laid out like a regular grid (n_x * n_y * n_z cells), +# but each axis is spaced by the octree: fine where the octree is refined, coarse elsewhere. +# n_cells_x/y/z: cells per axis, 0 = half the finest octree resolution (here 80 x 32 x 32) +# alpha: 0 = uniform grid, 1 = follow the octree refinement only +# max_growth: largest size ratio of neighbouring cells along an axis +# mesh_octree_informed = create_octree_informed_structured_mesh( +# geomodel_result=structural_model_result_octree, +# n_cells_x=0, +# n_cells_y=0, +# n_cells_z=0, +# alpha=0.7, +# max_growth=1.3, +# ) + +# Explicit unstructured mesh, the same call as for the RegularGrid model in section 2 +# mesh_explicit_unstructured_octree = create_unstructured_mesh_data( +# geomodel_result=structural_model_result_octree, +# tolerance=50, +# mesh_size=50, +# curve_mesh_size=5, +# ) + +# Plot the meshes +# plot_mesh_3d(mesh_octree_informed, structural_model_result_octree, show_plotter=True) +# plot_mesh_3d(mesh_explicit_unstructured_octree, structural_model_result_octree, show_plotter=True) + +#%% 5.3 Simulation on the octree-informed mesh + +# SfePy as in section 4.1, with the fault damage zone; GOLEM takes the mesh the same way +# (mesh_results=mesh_octree_informed in GolemHydrothermalProblemBuilder, section 3.2). +# Without petsc4py (see section 4), pass linear_solver="direct": it converges here but takes about +# 15 minutes; "iterative" does not converge because of the fault zone's strong permeability contrast. +# builder_octree = SfepyHydrothermalProblemBuilder( +# mesh_results=mesh_octree_informed, +# geomodel_result=structural_model_result_octree, +# rock_properties=rock_properties, +# fluid=fluid, +# include_flow=True, +# fault_zone_properties=fault_zone_properties, +# fault_zone_n_voxels=1, +# end_time=5.0e11, +# num_steps=3, +# ) +# data_by_time_octree = run_simulation_sfepy(builder_octree, stream_output=True) + +# Plot the simulation results. normal=(0, 1, 0) cuts across the fault, which doesn't change along y. +# final_time_octree = max(data_by_time_octree.nodes_by_time.keys()) +# plot_variable_at_a_time(data_by_time_octree, "T", time=final_time_octree, cmap="coolwarm", show_edges=True) +# plot_cross_section_2D(data_by_time_octree, "T", origin=(1250, 500, 500), normal=(0, 1, 0), cmap="coolwarm") diff --git a/tests/tests_meshing_components/implicit/test_octree_informed_mesh.py b/tests/tests_meshing_components/implicit/test_octree_informed_mesh.py new file mode 100644 index 00000000..aff9d644 --- /dev/null +++ b/tests/tests_meshing_components/implicit/test_octree_informed_mesh.py @@ -0,0 +1,101 @@ +""" +Octree-informed structured mesh: a rectilinear hexahedral mesh with cell sizes from the octree. +""" +from __future__ import annotations + +import warnings + +import numpy as np +import pandas as pd +import pytest + +from core.meshing_components.implicit.octree_informed import ( + create_octree_informed_structured_mesh, + octree_informed_edges, +) +from core.meshing_components.mesh_format.exodus.Exo_format import exodus_type_for, export_mesh_results_to_exodus +from core.meshing_components.pre_checks import pre_check_octree_grid +from core.object_components import InputData_StructuralElements, MeshType, StructuralModelResults +from core.structural_modeling_components import general +from core.structural_modeling_components.structural_objects.grids.grid_classes import OctreeGrid + +INTERFACE_Z = 0.53 # the upper of two horizontal surfaces + + +def _layers() -> InputData_StructuralElements: + xs = np.linspace(0.05, 0.95, 5) + rows = [{"X": float(x), "Y": float(y), "Z": z, "formation": name} + for name, z in (("top", INTERFACE_Z), ("bottom", 0.21)) for x in xs for y in xs] + return InputData_StructuralElements( + name="layers", mapping_object={"Series": ("top", "bottom")}, surface_points=pd.DataFrame(rows), + orientations=pd.DataFrame([dict(r, G_x=0.0, G_y=0.0, G_z=1.0) for r in rows])) + + +def _compute(grid) -> StructuralModelResults: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + frame = general.build_structural_frame(input_data_elements=_layers(), grid=grid) + return general.compute_structural_model(frame, extract_meshes=False, verbose=False) + + +@pytest.fixture(scope="module") +def octree_result() -> StructuralModelResults: + return _compute(OctreeGrid(extent=(0.0, 1.0, 0.0, 1.0, 0.0, 1.0), base_resolution=(2, 2, 2), max_level=3)) + + +def test_only_models_on_a_computed_octree_are_accepted(octree_result): + grid = octree_result.structural_frame.grid + with pytest.raises(ValueError, match="needs a structural model computed on an OctreeGrid"): + pre_check_octree_grid(_compute(grid.equivalent_regular_grid())) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + uncomputed = StructuralModelResults( + structural_frame=general.build_structural_frame(input_data_elements=_layers(), grid=grid)) + with pytest.raises(ValueError, match="not been computed"): + create_octree_informed_structured_mesh(uncomputed) + + +def test_the_mesh_is_a_rectilinear_grid_with_the_octrees_lithology(octree_result): + frame = octree_result.structural_frame + mesh = create_octree_informed_structured_mesh(octree_result, n_cells_x=6, n_cells_y=5, n_cells_z=8) + assert mesh.mesh_type == MeshType.OCTREE_INFORMED + assert len(mesh.nodes) == 7 * 6 * 9 + hexahedra = np.concatenate([block.data for block in mesh.elements]) + block_ids = np.concatenate(mesh.cell_data["block_id"]) + assert hexahedra.shape == (6 * 5 * 8, 8) + # Each block's cells carry the lithology of the octree cell at their center. + centers = mesh.nodes[hexahedra].mean(axis=1) + np.testing.assert_array_equal(block_ids, np.asarray(frame.lith_block)[frame.cells.locate(frame.grid, centers)]) + assert set(mesh.point_sets) == {"left", "right", "front", "back", "bottom", "top"} + + +def test_cells_are_finer_at_the_interface_within_size_and_growth_limits(octree_result): + frame = octree_result.structural_frame + h = frame.grid.finest_spacing[2] + ex, ey, ez = octree_informed_edges(frame.grid, frame.cells, (0, 0, 8), alpha=0.9, max_growth=1.5) + sizes = np.diff(ez) + assert ez[0] == 0.0 and ez[-1] == 1.0 and np.all(sizes >= h - 1e-12) + assert np.max(np.maximum(sizes[1:] / sizes[:-1], sizes[:-1] / sizes[1:])) <= 1.5 + 1e-9 + at_interface = np.searchsorted(ez, INTERFACE_Z) - 1 + assert sizes[at_interface] < 1.0 / 8 # finer than uniform at the interface + assert sizes.max() > 1.0 / 8 # coarser elsewhere + # Horizontal layers: no density along x and y, so those stay uniform. + np.testing.assert_allclose(np.diff(ex), 1.0 / len(np.diff(ex))) + + +def test_alpha_zero_gives_a_uniform_grid_and_bad_parameters_are_refused(octree_result): + frame = octree_result.structural_frame + for edges in octree_informed_edges(frame.grid, frame.cells, (4, 4, 4), alpha=0.0): + np.testing.assert_allclose(np.diff(edges), 0.25) + with pytest.raises(ValueError, match="alpha"): + octree_informed_edges(frame.grid, frame.cells, (4, 4, 4), alpha=1.5) + with pytest.raises(ValueError, match="max_growth"): + octree_informed_edges(frame.grid, frame.cells, (4, 4, 4), max_growth=0.5) + with pytest.raises(ValueError, match="must lie in"): + octree_informed_edges(frame.grid, frame.cells, (4, 4, 17)) # finer than the finest cells + + +def test_exodus_export_takes_the_hexahedral_path(octree_result): + mesh = create_octree_informed_structured_mesh(octree_result, n_cells_x=4, n_cells_y=4, n_cells_z=4) + assert exodus_type_for(mesh).value == "imp" + assert len(export_mesh_results_to_exodus(mesh, type=exodus_type_for(mesh)).getvalue()) > 0 diff --git a/tests/tests_meshing_components/test_pre_checks.py b/tests/tests_meshing_components/test_pre_checks.py index 57a0c62c..f6eac4fe 100644 --- a/tests/tests_meshing_components/test_pre_checks.py +++ b/tests/tests_meshing_components/test_pre_checks.py @@ -1,6 +1,7 @@ """ -The meshing components refuse structural models computed on an OctreeGrid -(pre_check_regular_grid), both as a pre-check and inside the component. +The implicit and structured meshing components refuse structural models computed +on an OctreeGrid (pre_check_regular_grid), both as a pre-check and inside the +component. The unstructured mesher accepts them. """ from __future__ import annotations @@ -51,9 +52,22 @@ def test_the_pre_check_refuses_an_octree_model_only(results): @pytest.mark.parametrize("component, kwargs", [ (create_structured_mesh_data, {"refinement_data": [2, 2]}), - (create_unstructured_mesh_data, {}), (create_implicit_structured_mesh, {}), -], ids=["structured", "unstructured", "implicit"]) +], ids=["structured", "implicit"]) def test_meshing_components_refuse_an_octree_model(results, component, kwargs): with pytest.raises(ValueError, match="OctreeGrid"): component(geomodel_result=results[0], **kwargs) + + +def _tetra_counts(mesh) -> list[int]: + return [len(block.data) for block in mesh.elements if block.type == "tetra"] + + +def test_the_unstructured_mesher_accepts_an_octree_model(results): + """Octree and equivalent regular grid give the same volumes and similar meshes.""" + octree, regular = results + meshes = [create_unstructured_mesh_data(geomodel_result=result, mesh_size=0.1, curve_mesh_size=0.05) + for result in (octree, regular)] + octree_counts, regular_counts = (_tetra_counts(mesh) for mesh in meshes) + assert len(octree_counts) == len(regular_counts) == 3 + assert sum(octree_counts) == pytest.approx(sum(regular_counts), rel=0.1) diff --git a/tests/tests_simulation_components/conftest.py b/tests/tests_simulation_components/conftest.py index 3f8a283e..a4f59a77 100644 --- a/tests/tests_simulation_components/conftest.py +++ b/tests/tests_simulation_components/conftest.py @@ -5,8 +5,9 @@ from core.object_components import InputData_StructuralElements, InputData_FaultElements from core.structural_modeling_components import general, general_faults -from core.structural_modeling_components.structural_objects.grids.grid_classes import RegularGrid +from core.structural_modeling_components.structural_objects.grids.grid_classes import OctreeGrid, RegularGrid from core.meshing_components.implicit.export_implicit import create_implicit_structured_mesh +from core.meshing_components.implicit.octree_informed import create_octree_informed_structured_mesh REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) MODEL1_DATA_DIR = os.path.join(REPO_ROOT, "examples/synthetic_examples/model1/input_data/geological_data") @@ -33,7 +34,7 @@ def model1_implicit_mesh(model1_structural_result): return create_implicit_structured_mesh(geomodel_result=model1_structural_result) -def _build_model2_structural_result(*, restrict_fault_to_older_group: bool = False): +def _build_model2_structural_result(*, restrict_fault_to_older_group: bool = False, grid=None): """Small (30x15x15), faulted structural model (1 fault, 2 stratigraphic groups). restrict_fault_to_older_group must be applied (via set_fault_activity_by_group) @@ -41,7 +42,8 @@ def _build_model2_structural_result(*, restrict_fault_to_older_group: bool = Fal takes effect in the real lith_block (domain merging), not just the raw fault_activity dict -- see SfepyHydrothermalProblemBuilder's class docstring. """ - grid = RegularGrid(extent=(0, 2500, 0, 1000, 0, 1000), resolution=(30, 15, 15)) + if grid is None: + grid = RegularGrid(extent=(0, 2500, 0, 1000, 0, 1000), resolution=(30, 15, 15)) data_faults = InputData_FaultElements( name="Faults_Model_2", fault_surface_points=pd.read_csv(os.path.join(MODEL2_DATA_DIR, "model2_surface_points_df.csv")), @@ -86,3 +88,37 @@ def model2_implicit_mesh(model2_faulted_structural_result): @pytest.fixture(scope="module") def model2_implicit_mesh_restricted_activity(model2_faulted_structural_result_restricted_activity): return create_implicit_structured_mesh(geomodel_result=model2_faulted_structural_result_restricted_activity) + + +@pytest.fixture(scope="module") +def model1_octree_structural_result(): + """Model 1 on a small OctreeGrid (16^3 finest cells), fault-free (basement + rock1/rock2).""" + grid = OctreeGrid(extent=(0, 1000, 0, 1000, 0, 1000), base_resolution=(2, 2, 2), max_level=3) + data_elements = InputData_StructuralElements( + name="Model_1", + mapping_object={"Strat_Series1": ("rock2", "rock1")}, + surface_points=pd.read_csv(os.path.join(MODEL1_DATA_DIR, "model1_surface_points_df.csv")), + orientations=pd.read_csv(os.path.join(MODEL1_DATA_DIR, "model1_orientations_df.csv")), + ) + frame = general.build_structural_frame(input_data_elements=data_elements, grid=grid) + return general.compute_structural_model(frame, extract_meshes=False, verbose=False) + + +@pytest.fixture(scope="module") +def model1_octree_informed_mesh(model1_octree_structural_result): + """Octree-informed structured mesh of model1_octree_structural_result (6 x 6 x 6 hexahedra).""" + return create_octree_informed_structured_mesh(model1_octree_structural_result, n_cells_x=6, n_cells_y=6, + n_cells_z=6) + + +@pytest.fixture(scope="module") +def model2_octree_structural_result(): + """Model 2 (1 fault, 2 groups) on a small OctreeGrid (20 x 8 x 8 finest cells).""" + return _build_model2_structural_result( + grid=OctreeGrid(extent=(0, 2500, 0, 1000, 0, 1000), base_resolution=(5, 2, 2), max_level=2)) + + +@pytest.fixture(scope="module") +def model2_octree_informed_mesh(model2_octree_structural_result): + """Octree-informed structured mesh of model2_octree_structural_result (half the finest resolution).""" + return create_octree_informed_structured_mesh(model2_octree_structural_result) diff --git a/tests/tests_simulation_components/test_custom_sfepy_builder.py b/tests/tests_simulation_components/test_custom_sfepy_builder.py index 55b8449e..3e3cb170 100644 --- a/tests/tests_simulation_components/test_custom_sfepy_builder.py +++ b/tests/tests_simulation_components/test_custom_sfepy_builder.py @@ -133,7 +133,7 @@ def test_fault_zone_detected_on_faulted_model(model2_implicit_mesh, model2_fault fault_zone_n_voxels=1, ) assert builder.fault_zone_cell_mask is not None - assert int(builder.fault_zone_cell_mask.sum()) == 764 # same pinned regression number as SfepyHydrothermalProblemBuilder + assert int(builder.fault_zone_cell_mask.sum()) == 658 # same pinned regression number as SfepyHydrothermalProblemBuilder assert builder.fault_group_id == len(model2_implicit_mesh.elements) diff --git a/tests/tests_simulation_components/test_golem_model_builder.py b/tests/tests_simulation_components/test_golem_model_builder.py index 278fad3d..5a198bf5 100644 --- a/tests/tests_simulation_components/test_golem_model_builder.py +++ b/tests/tests_simulation_components/test_golem_model_builder.py @@ -124,7 +124,7 @@ def test_custom_golem_builder_rejects_unknown_mesh_type(model1_implicit_mesh): "[]\n" "[Outputs]\n[]\n" ) - with pytest.raises(ValueError, match="implicit, structured, or unstructured"): + with pytest.raises(ValueError, match="implicit, octree_informed, structured, unstructured"): GolemCustomBuilder(input_file_contents=content, mesh_results=mesh) @@ -622,3 +622,52 @@ def test_hydrothermal_unstructured_gradient_keeps_structural_extent( extent = model1_structural_result.structural_frame.grid.extent assert builder.z_bottom == pytest.approx(extent[4]) assert builder.z_top == pytest.approx(extent[5]) + + +# ----------------------------------------------------------------------------- +# Octree-informed structured mesh (hexahedra, one block per lithology, like the +# implicit mesh) +# ----------------------------------------------------------------------------- + +def test_hydrothermal_builder_accepts_octree_informed_mesh( + model1_octree_informed_mesh, model1_octree_structural_result, tmp_path +): + mesh = model1_octree_informed_mesh + builder = GolemHydrothermalProblemBuilder( + mesh_results=mesh, geomodel_result=model1_octree_structural_result, num_steps=1, + ) + # All element blocks are material blocks (no trailing boundary blocks). + assert builder.material_block_count == len(mesh.elements) + assert builder.volume_blocks == list(range(len(mesh.elements))) + # The temperature gradient is anchored to the mesh nodes. + nodes = np.asarray(mesh.nodes, dtype=float) + assert builder.z_bottom == pytest.approx(nodes[:, 2].min()) + assert builder.z_top == pytest.approx(nodes[:, 2].max()) + + path = tmp_path / "octree.i" + builder.build_input_file(str(path)) + validate_golem_input(path.read_text(), mesh, mesh.mesh_type) + + +def test_custom_golem_builder_accepts_octree_informed_mesh(model1_octree_informed_mesh): + builder = GolemCustomBuilder( + input_file_contents=_custom_golem_input("${GOLEM_MESH_FILE}"), + mesh_results=model1_octree_informed_mesh, + ) + assert builder.referenced_meshes() == {"${GOLEM_MESH_FILE}": model1_octree_informed_mesh} + + +def test_octree_informed_mesh_exports_to_exodus_for_golem(model1_octree_informed_mesh, tmp_path): + """GOLEM writes its mesh with exodus_type_for(): the octree-informed mesh takes the + implicit path, with one hexahedral element block per mesh block.""" + import meshio + from core.meshing_components.mesh_format.exodus.Exo_format import ( + MeshType as ExodusMeshType, exodus_type_for, export_mesh_results_to_exodus, + ) + mesh = model1_octree_informed_mesh + assert exodus_type_for(mesh) == ExodusMeshType.IMPLICIT + path = tmp_path / "octree.e" + path.write_bytes(export_mesh_results_to_exodus(mesh, type=exodus_type_for(mesh)).getvalue()) + exported = meshio.read(path) + assert [block.type for block in exported.cells] == ["hexahedron"] * len(mesh.elements) + assert sum(len(block.data) for block in exported.cells) == sum(len(b.data) for b in mesh.elements) diff --git a/tests/tests_simulation_components/test_hydrothermal_builder.py b/tests/tests_simulation_components/test_hydrothermal_builder.py index f50ee720..19b70da8 100644 --- a/tests/tests_simulation_components/test_hydrothermal_builder.py +++ b/tests/tests_simulation_components/test_hydrothermal_builder.py @@ -481,7 +481,7 @@ def test_standalone_fault_zone_functions_match_builder(model2_implicit_mesh, mod mask = compute_fault_zone_cell_mask(model2_implicit_mesh, model2_faulted_structural_result, 1) assert mask is not None - assert int(mask.sum()) == int(builder.fault_zone_cell_mask.sum()) == 764 # pinned regression number + assert int(mask.sum()) == int(builder.fault_zone_cell_mask.sum()) == 658 # pinned regression number def test_fault_zone_none_on_fault_free_model(model1_implicit_mesh, model1_structural_result): @@ -504,7 +504,8 @@ def test_fault_zone_respects_restricted_fault_activity( must exclude the younger group's cells from the fault zone -- this was a real bug in an earlier version (raw get_domain_mask() ignored fault_activity entirely). Cross-checks the two known-good cell counts at - this exact fixture resolution (30x15x15): 764 fully-active, 596 restricted. + this exact fixture resolution (30x15x15): 658 fully-active, 504 restricted + (geometric zone; the former voxel version gave 764 / 596). """ full_builder = SfepyHydrothermalProblemBuilder( mesh_results=model2_implicit_mesh, geomodel_result=model2_faulted_structural_result, @@ -512,7 +513,7 @@ def test_fault_zone_respects_restricted_fault_activity( linear_solver="iterative", ) full_count = int(full_builder.fault_zone_cell_mask.sum()) - assert full_count == 764 + assert full_count == 658 restricted_builder = SfepyHydrothermalProblemBuilder( mesh_results=model2_implicit_mesh_restricted_activity, @@ -521,7 +522,7 @@ def test_fault_zone_respects_restricted_fault_activity( linear_solver="iterative", ) restricted_count = int(restricted_builder.fault_zone_cell_mask.sum()) - assert restricted_count == 596 + assert restricted_count == 504 assert restricted_count < full_count @@ -567,6 +568,52 @@ def test_fault_zone_pressure_input_file_includes_fault_material( assert "dw_diffusion.i.Omega_fault(m_fault.perm_over_mu, q, p)" in content +# --------------------------------------------------------------------------- +# Octree-informed structured mesh (structural model on an OctreeGrid) +# --------------------------------------------------------------------------- + +def test_octree_informed_mesh_takes_the_implicit_hexahedral_path(model1_octree_structural_result, + model1_octree_informed_mesh): + from core.simulation_components.simulation_packages.sfepy.sfepy_model_builder import MESH_TYPE_CODES + assert model1_octree_informed_mesh.mesh_type == MeshType.OCTREE_INFORMED + assert MESH_TYPE_CODES[MeshType.OCTREE_INFORMED] == "imp" + builder = SfepyHydrothermalProblemBuilder(mesh_results=model1_octree_informed_mesh, + geomodel_result=model1_octree_structural_result, + rock_properties={}, fluid=FluidProperties(), include_flow=False, num_steps=1, linear_solver="iterative") + assert builder.fault_zone_cell_mask is None + assert len(builder.compute_cell_materials()) == 6 * 6 * 6 + + +def test_fault_zone_on_an_octree_model(model2_octree_structural_result, model2_octree_informed_mesh): + """The geometric fault zone works on an OctreeGrid model and the octree-informed mesh.""" + builder = SfepyHydrothermalProblemBuilder(mesh_results=model2_octree_informed_mesh, + geomodel_result=model2_octree_structural_result, rock_properties={}, + fluid=FluidProperties(), include_flow=False, num_steps=1, linear_solver="iterative", + fault_zone_properties=_FAULT_ZONE_PROPS, fault_zone_n_voxels=1) + mask = builder.fault_zone_cell_mask + assert mask is not None and 0 < mask.sum() < len(mask) + assert (builder.compute_cell_materials() == _FAULT_ZONE_PROPS.name).sum() == mask.sum() + + +def test_fault_zone_is_the_band_within_n_plus_half_cells_of_the_fault_surface( + model2_implicit_mesh, model2_faulted_structural_result): + """Geometric definition: centroid within fault_zone_n_voxels + 0.5 grid cells of the fault surface.""" + import pyvista as pv + from core.structural_modeling_components.structural_objects.structural_objects import FaultMeshType + frame = model2_faulted_structural_result.structural_frame + h = np.asarray(frame.grid.spacing, dtype=float) + fault = frame.fault_frame.fault_elements[0] + faces = np.asarray(fault.edges[FaultMeshType.UNMASKED]).reshape(-1, 3) + surface = pv.PolyData(np.asarray(fault.vertices[FaultMeshType.UNMASKED]) / h, + np.column_stack([np.full(len(faces), 3), faces]).ravel()) + centroids = np.concatenate([model2_implicit_mesh.nodes[b.data].mean(axis=1) for b in model2_implicit_mesh.elements]) + distance = np.abs(pv.PolyData(centroids / h).compute_implicit_distance(surface)["implicit_distance"]) + one = compute_fault_zone_cell_mask(model2_implicit_mesh, model2_faulted_structural_result, 1) + two = compute_fault_zone_cell_mask(model2_implicit_mesh, model2_faulted_structural_result, 2) + np.testing.assert_array_equal(one, distance <= 1.5) # the single fault affects every group here + assert np.all(two[one]) and two.sum() > one.sum() + + def test_petsc_solver_fails_early_when_petsc4py_missing( monkeypatch, model1_implicit_mesh, model1_structural_result, ): diff --git a/tests/tests_simulation_components/test_hydrothermal_run.py b/tests/tests_simulation_components/test_hydrothermal_run.py index 5e721491..7579c6c1 100644 --- a/tests/tests_simulation_components/test_hydrothermal_run.py +++ b/tests/tests_simulation_components/test_hydrothermal_run.py @@ -571,6 +571,22 @@ def test_run_simulation_sfepy_custom_builder_fault_zone_end_to_end( assert float(T.mean()) == pytest.approx(35.0, abs=1e-6) +def test_sfepy_runs_on_an_octree_informed_mesh(model1_octree_structural_result, model1_octree_informed_mesh): + """A real (small) conduction run on the octree-informed mesh: hexahedra, temperatures within the BCs.""" + from core.simulation_components.simulation_packages.sfepy.sfepy_model_builder import ( + FluidProperties, SfepyHydrothermalProblemBuilder) + builder = SfepyHydrothermalProblemBuilder(mesh_results=model1_octree_informed_mesh, + geomodel_result=model1_octree_structural_result, rock_properties={}, + fluid=FluidProperties(), include_flow=False, num_steps=1, linear_solver="iterative") + result = run_simulation_sfepy(builder) + final = max(result.node_data_by_time) + temperature = np.asarray(result.node_data_by_time[final]["T"]) + assert np.isfinite(temperature).all() + t0 = np.asarray(result.node_data_by_time[min(result.node_data_by_time)]["T"]) + assert t0.min() - 1e-6 <= temperature.min() and temperature.max() <= t0.max() + 1e-6 + assert set(np.unique(result.celltypes_by_time[final]).tolist()) == {12} # VTK hexahedra + + def _tetra_result(solver): """Two tetrahedra in two blocks, two time steps, with every optional field filled.""" sim = SimulationResults(solver=solver, block_names={1: "rock1", 2: "rock2"})