Repository navigation
Conversation
Create Octree-Informed Structured Mesh builds a rectilinear hexahedral mesh for a structural model computed on an OctreeGrid: n_x * n_y * n_z cells like a regular grid, but each axis spaced by equidistributing alpha * (share of max-level octree cells per slab) + (1 - alpha) * uniform, with cells at least one finest octree cell and neighbour ratios up to max_growth. Each cell takes the lithology of the octree cell at its center (look-up, no interpolation). octree_informed_edges returns the coordinate lists (e.g. MOOSE CartesianMeshGenerator dx). pre_check_octree_grid refuses models on a RegularGrid or not computed. New MeshType.OCTREE_INFORMED; the Exodus exporter takes its hexahedral path for it. The SfePy builder does not support it yet. Co-Authored-By: Claude Opus 5.5
MESH_TYPE_CODES maps MeshType.OCTREE_INFORMED to "imp": hexahedra with block ids take the implicit mesh's export and run path. Fault zones are voxel-based (a trace in the shape of a regular lith_block), so compute_fault_zone_cell_mask now refuses structural models on an OctreeGrid with a clear message instead of failing inside. Tests: octree fixtures (model 1, 16^3) and the octree-informed mesh; builder accepts it, fault zones are refused, a real SfePy run on it. Co-Authored-By: Claude Opus 5.5
compute_fault_zone_cell_mask now selects the mesh cells whose centroid lies within fault_zone_n_voxels + 0.5 structural grid cells of a fault's UNMASKED surface mesh (VTK point-to-surface distance, per axis in cells of the structural grid; finest cells on an OctreeGrid), keeping the fault_activity rule via each cell's block id. It works for structural models on both grids and every mesh type, replacing the voxel trace (fault_trace_on_grid, binary dilation, nearest-voxel look-up), which only worked on a RegularGrid. For a fault parallel to a grid plane the zone is the voxel version's; oblique faults are no longer widened by the voxel staircase (model 2's pinned counts 764 / 596 become 658 / 504). Octree models no longer refuse fault zones. Co-Authored-By: Claude Opus 5.5
Co-Authored-By: Claude Opus 5.5
octree_informed.py was the only module with a @wbgeo_component that used 'from __future__ import annotations'. That turns every annotation into a string, which the DSL rejects (test_component_signatures failed for all six parameters and the return type), so the component would not have registered in the Workbench. Co-Authored-By: Claude Opus 5.5
Brings in main with MR !46 (GOLEM). Conflicts from the SfePy renames (SfepyHydrothermalProblemBuilder, SfepyCustomBuilder, sfepy_model_builder): kept the geometric fault zone docstrings and counts (658/504) with the new names, kept both sides of the octree and export/petsc tests; the octree SfePy tests use linear_solver="iterative" (default is now petsc). Co-Authored-By: Claude Opus 5.5
Conflicts resolved by keeping both sides: the octree_informed mesh type together with the palette colour of MeshTypeType, and the octree imports together with the palette import in the SfePy builder. Co-Authored-By: Claude Opus 5.5
main now requires palette constants and a positionInGroup for every component (tests/test_workbench_palette.py): MESH colour like the other meshers, position 960 right below Create Structured Implicit Mesh. Co-Authored-By: Claude Opus 5.5
The octree-informed mesh is exported like the implicit mesh (hexahedra, one block per lithology, no boundary blocks), which the GOLEM builders already handle; it only had to be added to GOLEM_SUPPORTED_MESH_TYPES. The error messages now list the accepted types from that set. Tests (model 1 on an octree): the generated hydrothermal problem accepts the mesh and passes validate_golem_input, all blocks are material blocks, the temperature gradient is anchored to the mesh nodes, the custom builder accepts it, and the Exodus export has one hexahedral block per mesh block. Checked with a real GOLEM run in Docker (model 1, octree max level 4, 4,096 hexahedra, 3 steps, 67 s): pressure and temperature within the boundary values except a ~1 K temperature overshoot in the thermal boundary layer below the top, where the octree-informed cells are coarsest (110-144 m); the implicit mesh (62.5 m) has none. Co-Authored-By: Claude Opus 5.5
The unstructured mesher takes its surfaces from the extended masked meshes, which exist on both grids. Only the lithology lookup and the cell size read the regular grid layout: - build_grid_litho samples the octree lithology exactly at the finest cell centres (to_regular), so the table matches a RegularGrid at the finest resolution - the piece-area threshold and the B-spline step use the finest octree cell size pre_check_regular_grid stays on the implicit and the structured explicit mesh; its message now points to the two meshers that accept octree models. Check on model 2 (1 fault, 2 groups, 40x16x16 finest cells): octree and equivalent regular grid give the same 5 volumes, tetra counts within 3 %, the same element quality and lithology purity. Co-Authored-By: Claude Opus 5.5
- Model 1 and model 2 examples: new optional section 5 (commented out) runs the model on an Octree Grid: structural (and fault) model, octree-informed structured mesh, unstructured mesh, SfePy run on the octree-informed mesh. Both sections were run uncommented (model 2's SfePy run with linear_solver="direct"; "iterative" does not converge with the fault zone's permeability contrast, noted in the example). - Meshing manual: new step 4 for Create Octree-Informed Structured Mesh (method, parameters, when it pays off, limits); unstructured mesh on octree models; red connection for the implicit and structured mesh; Exodus type and mesh_type in the output. - Simulation manual: octree-informed mesh for SfePy and GOLEM; fault zone width in finest cells on an Octree Grid. - Structural modeling manual: meshing options for octree models, pointer to the example sections. Co-Authored-By: Claude Opus 5.5
| 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 |
There was a problem hiding this comment.
# VTK/meshio HEX8 corner ordering, identical to _rectilinear_hexahedra.
_HEX8_OFFSETS = np.array([
[0, 0, 0], [1, 0, 0], [1, 1, 0], [0, 1, 0],
[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1],
], dtype=np.int64)
def _octree_leaf_hexahedra(grid: OctreeGrid, cells: OctreeCells):
"""Convert stored leaves to HEX8 using integer finest-grid coordinates.
Supports level-local ijk and finest-grid lower-corner ijk. The existing
locate method is used to verify the indexing convention against leaf IDs.
Assumes a complete dyadic leaf partition of the rectangular grid extent.
"""
finest = np.asarray(grid.finest_resolution, dtype=np.int64)
extent = np.asarray(grid.extent, dtype=np.float64).reshape(3, 2)
low, high = extent[:, 0], extent[:, 1]
levels = np.asarray(cells.level, dtype=np.int64).reshape(-1)
ijk = np.asarray(cells.ijk, dtype=np.int64)
if (finest.shape != (3,) or np.any(finest <= 0) or
np.any(high <= low) or not np.all(np.isfinite(extent))):
raise ValueError('Invalid octree grid extent or resolution.')
if (ijk.shape != (len(levels), 3) or not len(levels) or
np.any(levels < 0) or np.any(levels > grid.max_level) or
grid.max_level > 60):
raise ValueError('Invalid octree leaf indices or levels.')
stride = np.left_shift(np.int64(1), grid.max_level - levels)
h = (high - low) / finest
if sum(int(s)**3 for s in stride) != int(finest[0])*int(finest[1])*int(finest[2]):
raise ValueError('Stored cells do not have the volume of a complete leaf partition.')
valid = []
for lower in (ijk * stride[:, None], ijk):
upper = lower + stride[:, None]
if (np.any(lower < 0) or np.any(upper > finest) or
np.any(lower % stride[:, None])):
continue
centers = low + (lower + 0.5 * stride[:, None]) * h
located = np.asarray(cells.locate(grid, centers)).reshape(-1)
if np.array_equal(located, np.arange(len(levels))):
if not any(np.array_equal(lower, other) for other in valid):
valid.append(lower)
if len(valid) != 1:
raise ValueError('Cannot uniquely verify octree ijk convention using cells.locate(). '
'Inspect OctreeCells before exporting.')
corners = valid[0][:, None, :] + stride[:, None, None] * _HEX8_OFFSETS[None, :, :]
# Deduplicate exactly on the integer lattice, not by floating-point tolerance.
lattice, inverse = np.unique(corners.reshape(-1, 3), axis=0, return_inverse=True)
nodes = low + lattice * h
nodes = np.where(lattice == finest, high, nodes)
return nodes, inverse.reshape(-1, 8).astype(np.int64)
@wbgeo_component(
description='Converts octree leaves directly to locally refined hexahedra (non-conforming)',
title='Create Octree-Preserving Mesh',
color=palette.MESH,
border_color=palette.BORDER,
group='Meshing',
positionInGroup=961,
identifier='wbgeo::meshing_create_octree_preserving_mesh',
return_name='Mesh',
input_checks=[pre_check_octree_grid],
)
def create_octree_preserving_mesh(geomodel_result: StructuralModelResults) -> MeshResults:
"""One HEX8 per stored octree leaf; original lithology and refinement.
WARNING: coarse/fine interfaces may contain hanging nodes. This function
does not balance the tree or generate solver constraints. Do not treat
this mesh as a conforming FEM mesh without further processing.
"""
pre_check_octree_grid(geomodel_result)
frame = geomodel_result.structural_frame
grid = frame.grid
mesh_type = getattr(MeshType, 'OCTREE_PRESERVING', None)
if mesh_type is None:
raise ValueError('Add OCTREE_PRESERVING to MeshType in core.object_components '
'and register it with your plotting/export dispatch as needed.')
nodes, hexahedra = _octree_leaf_hexahedra(grid, frame.cells)
block = np.asarray(frame.lith_block).reshape(-1).astype(np.int64)
levels = np.asarray(frame.cells.level).reshape(-1).astype(np.int64)
if len(block) != len(hexahedra):
raise ValueError('Expected one lithology ID per octree leaf.')
elements = []
block_ids = []
octree_levels = []
for block_id in np.unique(block):
mask = block == block_id
elements.append(meshio.CellBlock('hexahedron', hexahedra[mask]))
block_ids.append(block[mask])
octree_levels.append(levels[mask])
point_sets = build_point_sets(
classify_boundary_nodes(nodes, np.asarray(grid.extent)), len(nodes))
return MeshResults(
nodes=nodes,
elements=elements,
cell_data={'block_id': block_ids, 'octree_level': octree_levels},
point_sets=point_sets,
mesh_type=mesh_type,
)
| name="MeshType", | ||
| identifier="MeshTypeType", | ||
| controlled="Select|implicit|structured|unstructured", | ||
| controlled="Select|implicit|structured|unstructured|octree_informed", |
There was a problem hiding this comment.
| controlled="Select|implicit|structured|unstructured|octree_informed", | |
| controlled="Select|implicit|structured|unstructured|octree_informed|octree_preserving", |
| IMPLICIT = "implicit" | ||
| STRUCTURED = "structured" | ||
| UNSTRUCTURED = "unstructured" | ||
| OCTREE_INFORMED = "octree_informed" |
There was a problem hiding this comment.
| OCTREE_INFORMED = "octree_informed" | |
| OCTREE_PRESERVING = "octree_preserving" |
|
Hi @baes2021, Thanks a lot for the thorough review and for testing it with your own mesh. Comparing the meshes like this is really helpful. Let me first go back a step to why we added the octree, since that matters for how we mesh it. Why (adaptive) octree grids for structural modeling On a regular grid, the interpolator is evaluated in every cell, even far away from any boundary, where the lithology doesn't change. The octree refines only where something happens (contacts, erosion surfaces, faults) and Grid vs mesh Just a small side note, but I think we should be careful to keep the two apart in this discussion, because the octree shows up in both and it's easy to mix them. The octree is the structural model's grid: cells of different sizes side by side are fine there, since each cell only stores a value. Using it as a simulation mesh is a different question, because there the elements have to be conforming. So I'd see the octree as something that informs meshing, not as a mesh itself. (Same as Regular grid --> Implicit structured mesh) The octree-informed mesh I agree that the octree-informed mesh is quite close to the implicit mesh; with On merging it into Create Implicit Structured Mesh: I'd like that too in principle, but it's tricky in the Workbench right now. The component would have to recognise whether the structural model comes from a regular or an octree grid and change its options accordingly ( The octree-preserving mesh The problem is that it isn't conforming: where a large octree cell touches smaller ones, the corners of the small cells (hanging nodes) sit on the large cell's face, and the large cell doesn't know about them. Your docstring points this out as well. The tricky part is that the solvers don't complain: the mesh has the same format as the implicit mesh, so SfePy reads and runs it, but the results are wrong. A quick check on model 1 on an octree (32³ finest cells), all units with the same properties, heat conduction between fixed top and bottom temperatures, where the exact solution is a straight line in z:
I'd expect the same for GOLEM, since MOOSE reads the Exodus file the same way. That said, I think the idea is worth following up, and we could add the octree-preserving mesh in a separate PR if you think it's useful, once the hanging nodes are dealt with. A good starting point already exists on the structural side: the Octree Grid has an optional 2:1 balancing ( For this PR I'd keep the octree-informed mesh as it is unless you stringly disagree ;) |
@javoha let me chime in on the simulator side. I think we should separate the issue here. Having whatever flavor of octree-mesh as input into a simulator (here the main issue is on preserving geometric conformity) and whether or not the mesh is good enough to guarantee numerical convergence. As you pointed out the current PR should only tackle the first point. The latter is more a matter that should be on the user/expert side. This said, I agree with @baes2021 in that we should work on an implementation that is boundary conforming as much as possible, and her first comment might help to streamline activities here. The question is whether or not we can rely on internal refinement with a grading metric inside the octree mesh in order to alleviate having contrasting volume neighboring elements (question is whether this is enough to guarantee numerical convergence of a solution, but this is relative to the application). We can think (@baes2021) to add this additional stage of internal and local refinement as an intermediate stage in the meshing workflow (similar to what we already have for the other mesh-types), but we would need to discuss and agree what topological information to use to inform the refinement/smoothing. I am also fine to move this into an independent thread/issue. Let me know, |
|
Thanks @mcacace , I agree: this PR only covers the first point (a mesh the simulators can take), and how good the mesh needs to be is a separate, application-dependent question. One small addition, just so we keep the two apart: the 9.3 K in the check above isn't a convergence or quality effect but a conformity one. The exact solution is linear, so any conforming hex mesh reproduces it exactly, however coarse or graded. Grading (2:1, which the octree already offers via I fully agree that a mesh following the geological boundaries more closely is worth working towards, and that @baes2021's octree-preserving mesh is a good starting point. Can you open an issue for it (octree-preserving mesh made and link it here, so we can continue the discussion there and keep this PR to the octree-informed mesh. Does that work for both of you? |
Will do |
|
Following @mcacace's suggestion, I will explore the octree-preserved mesh in a separate issue. |
Short list after the method description, as requested in the review of #28: structured mesh as the main advantage (conforming, same convention as the implicit mesh, works with SfePy and GOLEM), layer boundaries approximated as staircases (alpha trade-off, unstructured mesh for boundary-following meshes), refinement along whole slabs where it may not be needed. Co-Authored-By: Claude Opus 5.5
Thanks @baes2021 ! I added a short trade-offs list to the meshing manual (48bec39): structured mesh as the main advantage, layer boundaries as staircases (and the alpha trade-off), and refinement along whole slabs. |
Review comment on 48bec39: drop the sentence on SfePy/GOLEM, surface meshing and edge coordinates from the structured-mesh point, and replace the refinement point with the reviewer's text ("an octree structural model" -> "the adaptive octree grid of a structural model"). The cell count is fixed by n_cells_x/y/z, so "increasing the total element count" became "for a given number of cells fewer of them end up near the features". Co-Authored-By: Claude Opus 5.5
|
Replying to your comment on 48bec39: thanks @baes2021, I applied your changes in the manual (dc5cc50), with "the adaptive octree grid of a structural model" instead of "an octree structural model", to keep grid and model apart, and one small correction: the number of cells is fixed by One small thought, just for perspective: most of the points in the list are not specific to the octree-informed mesh but come with any structured (tensor-product) hexahedral mesh, including our implicit structured mesh: layer boundaries become staircases, and any refinement runs along whole rows, columns and layers. The implicit mesh is the extreme case of that, since it is uniform everywhere. The octree-informed mesh doesn't add these limitations; at the same number of cells it only moves cells towards the structures (and with Happy to leave the list as it is now, though; it's useful information for users either way. |
|
I agree that the implicit structured mesh has the same limitations. My point, however, is that users might expect the octree-informed mesh to better resolve geological boundaries and reduce the staircase effect. This is not necessarily the case because the octree-informed mesh does not fully preserve the local refinement of the original octree grid, where finer cells are concentrated around geological boundaries. Therefore, users looking at the octree structural modelling results might expect a similar level of boundary resolution in the resulting simulation mesh, which is not necessarily achieved. I think we can leave the manual as it is now, with the current modifications. Later, when we introduce another octree-based meshing approach, we can revisit the manual and better explain the differences, advantages, and limitations of each approach. |
Fair point and agreed! |



Summary
Meshing and simulation for structural models computed on an Octree Grid. Until now every mesher refused octree models. With this PR:
Related: #5 (the geometric fault zone here is groundwork for damage zones; it will change once damage zones become part of the structural model).
Meshing changes (please review: @baes2021)
1. New component: Create Octree-Informed Structured Mesh (
core/meshing_components/implicit/octree_informed.py, identifierwbgeo::meshing_create_octree_informed_structured_mesh, Meshing group, position 960)n_cells_x * n_cells_y * n_cells_zcells on three coordinate lists, like a regular grid but with its own non-uniform spacing per axis.alpha * density + (1 - alpha) * uniform, so cells are finewhere the octree is refined (contacts, erosion boundaries, faults) and coarse elsewhere.
max_growth.n_cells_x/y/z(0 = half the finest resolution),alpha(0.7; 0 gives a uniform grid),max_growth(1.3).MeshResultswith hexahedra grouped by lithology (cell_data["block_id"]), boundary point sets (reusesbuild_point_sets/classify_boundary_nodesfrom the unstructured mesher), newMeshType.OCTREE_INFORMED(also added to the Workbench dropdown string).
pre_check_octree_grid(new, inpre_checks.py): only accepts models on an Octree Grid that have been computed.OCTREE_INFORMEDto the hexahedral path of the implicit mesh (Exo_format.py, one line).2. Unstructured mesher accepts octree models (
explicit/unstructured/structural_surfaces.py,mesh_data.py)extended_maskedmeshes, which exist on both grids. Only two places read the regular grid layout:build_grid_litho: on an Octree Grid the lithology is sampled exactly at the centres of the finest cells (to_regular), so the table looks like the one of a Regular Grid at the finest resolution._cell_spacing).pre_check_regular_gridremoved fromcreate_unstructured_mesh_dataonly.assignment.
3. Implicit and structured explicit mesh stay blocked
pre_check_regular_gridstays on both; only its docstring and message changed. Why we did not port them:hexahedral mesh of an octree model is already available: the octree-informed mesh with
alpha = 0.a port (and it only supports unfaulted models).
In the Workbench the block works as intended: dragging a connection from a computed octree structural model to either of the two meshers turns it red, and the pre-check message tells the user to use "Create Octree-Informed
Structured Mesh" or "Create Unstructured Explicit Mesh". The check also runs at the start of execution, so it cannot be bypassed.
Simulation changes
OCTREE_INFORMEDruns through the hexahedral path of the implicit mesh (MESH_TYPE_CODES).OCTREE_INFORMEDadded toGOLEM_SUPPORTED_MESH_TYPES; the error messages list the supported types from that set.compute_fault_zone_cell_masknow selects the cells whose centroid lies withinfault_zone_n_voxels + 0.5structural grid cells of the fault's unmasked surface (VTK exactdistance, per axis in structural cells, finest cells on an octree), with the same
fault_activityrule as before. This replaces the voxel version (fault_trace_on_grid), which only worked on a Regular Grid.Evaluation: octree-informed vs uniform mesh
SfePy on three models (horizontal layers, layers dipping 30°, model 2 with fault), conduction and coupled flow, strong property contrasts between units. Temperature error (RMS, K) against a uniform reference at the finest
octree resolution, at equal cell count:
along an axis (exact for horizontal layers; a tensor-product mesh cannot follow dipping boundaries).
alpha = 0.7was the best of the tested values (0, 0.7, 1).Compatibility
plane the zone is unchanged. Pinned test counts for model 2 (30 x 15 x 15) changed from 764/596 to 658/504 cells.
MeshTypegains a value.Known issue (not caused by this PR)
With coupled flow, SfePy temperatures can exceed the boundary values on coarse meshes (e.g. 67 °C at a 60 °C boundary). This happens equally on the implicit mesh from a Regular Grid, so it is not specific to the octree mesh;
most likely the advection term without stabilization. GOLEM showed a ~1 K overshoot in the same situation. To be tracked in a separate issue.
Tests
tests/tests_meshing_components/implicit/test_octree_informed_mesh.py(pre-check, rectilinear grid with the octree's lithology, finer cells at interfaces within the size and growth limits,alpha = 0uniform,parameter checks, Exodus export); unstructured octree test and updated refusal tests in
test_pre_checks.py; SfePy run, builder and fault-zone tests on octree fixtures; GOLEM builder and Exodus export tests forOCTREE_INFORMED.mainmerged): 1322 passed, 1 skipped.Examples and manuals
Both sections were run uncommented. For model 2 without PETSc,
linear_solver="direct"converges (about 15 minutes);"iterative"does not, because of the fault zone's permeability contrast (noted in the example).mesh_typein the output.