Repository navigation
Octree-informed structured mesh; meshing and simulation for octree models #28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
javoha
wants to merge
18
commits into
main
Choose a base branch
from
jvh_dev_octree_mesh
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
80b01c2
Add an octree-informed structured mesh component
javoha a95a3b6
Run SfePy on the octree-informed mesh
javoha 05169a6
Compute the SfePy fault zone from the fault surfaces
javoha 164d204
Merge jvh_dev_octrees_dc (with main) into jvh_dev_octree_mesh
javoha 3477407
Let the Workbench read the octree-informed mesh component's signature
javoha 70f73cb
Merge branch 'jvh_dev_octrees_dc' into jvh_dev_octree_mesh
javoha 482cc14
Merge branch 'jvh_dev_octrees_dc' into jvh_dev_octree_mesh
javoha 1d91131
Merge branch 'jvh_dev_octrees_dc' into jvh_dev_octree_mesh
javoha 889a3b0
Merge branch 'jvh_dev_octrees_dc' into jvh_dev_octree_mesh
javoha 46559b7
Merge branch 'jvh_dev_octrees_dc' into jvh_dev_octree_mesh
javoha 8abe53b
Merge main into jvh_dev_octree_mesh
javoha 0814f42
Octree-informed mesh: colour and sidebar position from the palette
javoha 85e4290
GOLEM: accept the octree-informed structured mesh
javoha 2f2d8c2
Unstructured mesh: accept structural models on an OctreeGrid
javoha 2dfb107
Merge remote-tracking branch 'origin/main' into jvh_dev_octree_mesh
javoha 0f92057
Octree models: example sections in model 1 and 2, manuals
javoha 48bec39
Meshing manual: trade-offs of the octree-informed mesh
javoha dc5cc50
Meshing manual: octree-informed trade-offs as requested in review
javoha File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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" | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
|
|
||||||
| MeshTypeType = typing.Annotated[ | ||||||
| MeshType, | ||||||
| AnnotatedScriptType( | ||||||
| name="MeshType", | ||||||
| identifier="MeshTypeType", | ||||||
| controlled="Select|implicit|structured|unstructured", | ||||||
| controlled="Select|implicit|structured|unstructured|octree_informed", | ||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
| color=palette.PARAMETER, | ||||||
| ), | ||||||
| ] | ||||||
|
|
||||||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.