Skip to content
Open
37 changes: 23 additions & 14 deletions LoopStructural/modelling/features/_geological_feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,29 +242,36 @@ def evaluate_gradient(
# generate a regular tetrahedron for each point
# we will then move these points by the fault and then recalculate the gradient.
# this should work...
resolved = False
tetrahedron = regular_tetraherdron_for_points(pos, element_scale_parameter)
# A fault that the block names has no jump, so a tetrahedron may cross it.
jumping = [f for f in faults if not block or f.name not in block]

while not resolved:
resolved = True
def straddles(tet):
out = np.zeros(tet.shape[0], dtype=bool)
for f in jumping:
side = (
f[0]
.evaluate_value(
tetrahedron.reshape(-1, 3), fillnan='nearest', **block_kwargs(block)
tet.reshape(-1, 3), fillnan='nearest', **block_kwargs(block)
)
.reshape(tetrahedron.shape[0], 4)
.reshape(tet.shape[0], 4)
)
flag = np.logical_or(np.all(side > 0, axis=1), np.all(side < 0, axis=1))
if np.any(~flag):
logger.warning(
f"Points are too close to fault {f[0].name}. Refining the tetrahedron"
)
element_scale_parameter *= 0.5
tetrahedron = regular_tetraherdron_for_points(pos, element_scale_parameter)
resolved = False
out |= ~np.logical_or(np.all(side > 0, axis=1), np.all(side < 0, axis=1))
return out

# Make smaller only the tetrahedra that cross a fault, at most 10 times.
straddle = straddles(tetrahedron)
for _ in range(10):
if not np.any(straddle):
break
logger.warning(
f"{np.sum(straddle)} points are too close to a fault. Refining the tetrahedron"
)
element_scale_parameter *= 0.5
tetrahedron[straddle] = regular_tetraherdron_for_points(
pos[straddle], element_scale_parameter
)
straddle[straddle] = straddles(tetrahedron[straddle])

tetrahedron_faulted = self._apply_faults(
np.array(tetrahedron.reshape(-1, 3)), block=block, restored_through=restored_through
Expand All @@ -273,7 +280,9 @@ def evaluate_gradient(
values = self.interpolator.evaluate_value(tetrahedron_faulted.reshape(-1, 3)).reshape(
(-1, 4)
)
v[mask, :] = gradient_from_tetrahedron(tetrahedron[mask, :, :], values[mask])
# A point on a fault has no single gradient (the field jumps there), so it stays NaN.
ok = np.logical_and(mask, ~straddle)
v[ok, :] = gradient_from_tetrahedron(tetrahedron[ok, :, :], values[ok])

return v
pos = self._apply_faults(pos, block=block, restored_through=restored_through)
Expand Down
17 changes: 12 additions & 5 deletions LoopStructural/modelling/features/builders/_fault_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,9 @@ def create_data_from_geometry(
fault_dip_anisotropy : float, default=1.0
Anisotropy factor for the fault dip.
fault_pitch : float, optional
Pitch angle of the fault.
Angle in degrees, in the fault plane, of the slip vector from the strike
direction (down_dip x normal). 90 gives the down-dip slip vector, which
with a positive displacement is a reverse fault.
"""
# Suspend automatic rebuilds while we populate internal attributes to avoid recursion
self._fault_buffer = fault_buffer
Expand Down Expand Up @@ -372,10 +374,15 @@ def create_data_from_geometry(
fault_normal_vector = np.array(fault_normal_vector)

if fault_pitch is not None:
rotation_matrix = rotation(fault_normal_vector[None, :], np.array([fault_pitch]))
fault_slip_vector = np.einsum(
"ijk,ik->ij", rotation_matrix, fault_normal_vector[None, :]
)[0]
# Pitch is the angle in the fault plane from strike; 90 is down-dip.
normal = fault_normal_vector / np.linalg.norm(fault_normal_vector)
down_dip = np.array([0.0, 0.0, -1.0]) + normal[2] * normal
if np.linalg.norm(down_dip) < 1e-12:
raise ValueError("fault_pitch needs a fault plane that is not horizontal")
down_dip /= np.linalg.norm(down_dip)
strike = np.cross(down_dip, normal)
rotation_matrix = rotation(normal[None, :], np.array([fault_pitch]))
fault_slip_vector = np.einsum("ijk,ik->ij", rotation_matrix, strike[None, :])[0]

if fault_slip_vector is None:
if (
Expand Down
9 changes: 3 additions & 6 deletions LoopStructural/modelling/features/fault/_fault_segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,12 @@ def faultfunction(self):

@faultfunction.setter
def faultfunction(self, value):
if callable(value):
self._faultfunction = value
if issubclass(FaultDisplacement, type(value)):
self._faultfunction = value

elif isinstance(value, str) and value == "BaseFault":
if isinstance(value, str) and value == "BaseFault":
self._faultfunction = BaseFault().fault_displacement
elif isinstance(value, str) and value == "BaseFault3D":
self._faultfunction = BaseFault3D().fault_displacement
elif callable(value):
self._faultfunction = value
else:
raise ValueError("Fault function must be a function or BaseFault")

Expand Down
4 changes: 3 additions & 1 deletion LoopStructural/modelling/features/fold/_foldframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,12 @@ def calculate_fold_axis_rotation(self, feature_builder, fold_axis=None):
# project s0 onto axis plane B X A X B
projected_l1 = np.cross(s1g, np.cross(l1, s1g, axisa=1, axisb=1), axisa=1, axisb=1)
projected_s1gyg = np.cross(s1g, np.cross(s1gyg, s1g, axisa=1, axisb=1), axisa=1, axisb=1)
projected_l1 /= np.linalg.norm(projected_l1, axis=1)[:, None]
projected_s1gyg /= np.linalg.norm(projected_s1gyg, axis=1)[:, None]

# einsum dot product
far = np.einsum("ij,ij->i", projected_l1, projected_s1gyg)
far = np.rad2deg(np.arccos(far))
far = np.rad2deg(np.arccos(np.clip(far, -1.0, 1.0)))
# scalar triple product
# np.einsum("ij,ij->i", np.cross(l1, s1gyg, axisa=1, axisb=1), s1g)
# check bounds
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def fit(self, params: dict | None = None) -> bool:
calculate_wavelength=params.get("calculate_wavelength", True),
),
)
mask = np.logical_or(
mask = np.logical_and(
~np.isnan(self.fold_frame_coordinate), ~np.isnan(self.rotation_angle)
)
logger.info(f"Percentage of points not used {np.sum(~mask)/len(mask)*100}")
Expand Down
1 change: 1 addition & 0 deletions tests/unit/modelling/test_fault_block_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,4 @@ def test_displaced_fault_block_frame_equals_the_frame_on_its_side(displaced):
inside = side * young_gx > 1e-6
block_gx = old.evaluate_frame_value(pts, block={"young": side})
np.testing.assert_array_equal(block_gx[inside], gx[inside])

90 changes: 90 additions & 0 deletions tests/unit/modelling/test_fold_fault_audit_fixes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
"""Regression tests for fold and fault audit fixes."""

from types import SimpleNamespace

import numpy as np
import pandas as pd
import pytest

from LoopStructural import GeologicalModel
from LoopStructural.modelling.features.fault import FaultSegment
from LoopStructural.modelling.features.fold import FoldFrame
from LoopStructural.modelling.features.fold.fold_function._fourier_series_fold_rotation_angle import (
FourierSeriesFoldRotationAngleProfile,
)


class _PlaneFeature:
def __init__(self, gradient):
self.gradient = np.array(gradient, dtype=float)

def evaluate_value(self, points):
return points @ self.gradient

def evaluate_gradient(self, points):
return np.tile(self.gradient, (points.shape[0], 1))


@pytest.mark.parametrize("limb", [0.0, 45.0, 70.0])
def test_fold_axis_rotation_not_biased_by_limb_dip(limb):
theta, phi = np.deg2rad(60.0), np.deg2rad(limb)
lineation = [np.sin(theta) * np.cos(phi), np.cos(theta) * np.cos(phi), np.sin(phi)]
builder = SimpleNamespace(
get_gradient_constraints=lambda: np.zeros((0, 6)),
get_norm_constraints=lambda: np.array([[0.0, 0.0, 0.0, *lineation]]),
)
frame = SimpleNamespace(features=[_PlaneFeature([0, 0, 1]), _PlaneFeature([0, 1, 0])])
far, _ = FoldFrame.calculate_fold_axis_rotation(frame, builder)
np.testing.assert_allclose(far, [60.0 - 90.0], atol=1e-8)


def test_fold_profile_fit_ignores_one_nan_row():
s = np.linspace(0, 1000, 50)
angle = 20 + 30 * np.cos(2 * np.pi / 500 * s)
angle[10] = np.nan
profile = FourierSeriesFoldRotationAngleProfile(angle, s)
assert profile.fit(params={"guess": [0, 1, 1, 500]})


def _fault_model(**kwargs):
model = GeologicalModel([0, 0, 0], [1, 1, 1])
model.data = pd.DataFrame(
[
[0.5, 0.5, 0.5, 1, 0, 0, 0, "fault", 0],
[0.5, 0.5, 0.5, 0, 0, 1, 1, "fault", 0],
[0.5, 0.5, 0.5, 0, 1, 0, 2, "fault", 0],
[0.2, 0.5, 0.5, 0, 0, 1, 0, "strati", 0.5],
[0.8, 0.5, 0.5, 0, 0, 1, 0, "strati", 0.5],
],
columns=["X", "Y", "Z", "nx", "ny", "nz", "coord", "feature_name", "val"],
)
fault = model.create_and_add_fault("fault", 0.1, nelements=1e3, **kwargs)
return model, fault


def test_fault_pitch_rotates_strike_in_fault_plane():
# The plane dips 45 degrees to +x: strike is along y, down-dip is (1, 0, -1).
normal = np.array([1.0, 0.0, 1.0]) / np.sqrt(2)
_, fault = _fault_model(fault_normal_vector=normal, fault_pitch=90)
down_dip = np.array([1.0, 0.0, -1.0]) / np.sqrt(2)
np.testing.assert_allclose(fault.builder.fault_slip_vector, down_dip, atol=1e-8)
_, fault = _fault_model(fault_normal_vector=normal, fault_pitch=0)
np.testing.assert_allclose(np.abs(fault.builder.fault_slip_vector), [0, 1, 0], atol=1e-8)


def test_faulted_gradient_on_fault_is_nan_and_finishes():
model, _ = _fault_model()
strati = model.create_and_add_foliation("strati", nelements=1e3)
points = np.array([[0.5, 0.5, 0.5], [0.2, 0.5, 0.5]])
g = strati.evaluate_gradient(points)
assert np.all(np.isnan(g[0]))
assert np.all(np.isfinite(g[1]))


def test_faultfunction_setter_accepts_callable_rejects_object():
segment = FaultSegment.__new__(FaultSegment)
segment.faultfunction = lambda x: x
assert callable(segment.faultfunction)
segment.faultfunction = "BaseFault"
with pytest.raises(ValueError):
segment.faultfunction = object()
Loading