Skip to content

Commit f6e60eb

Browse files
committed
feat: add Form Line constraint type for tangent/strike and interface data
Adds a new "Form Line" digitised-data type: a line can constrain a model either as a strike/tangent constraint (using each vertex's local tangent direction, with an optional low-weight dip magnitude) or as an interface constraint sharing an unknown common value, without needing a value attribute field.
1 parent d3a020f commit f6e60eb

3 files changed

Lines changed: 252 additions & 5 deletions

File tree

‎loopstructural/gui/modelling/geological_model_tab/layer_selection_table.py‎

Lines changed: 101 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
from qgis.core import QgsMapLayerProxyModel
22
from qgis.gui import QgsFieldComboBox, QgsMapLayerComboBox
33
from qgis.PyQt.QtWidgets import (
4+
QCheckBox,
45
QComboBox,
56
QDialog,
67
QDialogButtonBox,
8+
QDoubleSpinBox,
9+
QFormLayout,
710
QHBoxLayout,
811
QLabel,
912
QPushButton,
@@ -436,6 +439,8 @@ def _setup_type_specific_fields(self, layout):
436439
self._setup_value_fields(layout)
437440
elif self.layer_type == "Inequality":
438441
self._setup_inequality_fields(layout)
442+
elif self.layer_type == "Form Line":
443+
self._setup_form_line_fields(layout)
439444

440445
def _setup_orientation_fields(self, layout):
441446
"""Setup fields for orientation data type."""
@@ -505,6 +510,85 @@ def _setup_value_fields(self, layout):
505510

506511
self.field_combos = {'value_field': self.value_field_combo}
507512

513+
def _setup_form_line_fields(self, layout):
514+
"""Setup fields for form line data type.
515+
516+
A form line has no attribute field to pick -- its geometry *is* the
517+
constraint. The only choice is what the line means to the scalar
518+
field: that it's constant (but unknown) along the line, or that the
519+
line marks the local strike direction of the field.
520+
521+
"Constrain Strike" can optionally add a dip magnitude too (e.g. an
522+
axial surface known to dip ~60 degrees). This is added as a
523+
low-weight constraint alongside the (hard) per-vertex strike from
524+
the line, rather than replacing it: the line's own direction is a
525+
precisely known fact, but the dip is usually only a rough regional
526+
estimate, and digitising direction leaves which way the surface
527+
dips ambiguous -- "Reverse dip direction" flips between the two
528+
mirror-image planes that share the same strike and dip magnitude.
529+
"""
530+
field_layout = QHBoxLayout()
531+
532+
constraint_label = QLabel("Constraint:")
533+
self.constraint_combo = QComboBox()
534+
self.constraint_combo.addItems(["Constant Value", "Constrain Strike"])
535+
if self.existing_data.get('form_line_constraint') == 'strike':
536+
self.constraint_combo.setCurrentText("Constrain Strike")
537+
538+
field_layout.addWidget(constraint_label)
539+
field_layout.addWidget(self.constraint_combo)
540+
layout.addLayout(field_layout)
541+
542+
self.dip_group = QWidget()
543+
dip_layout = QFormLayout(self.dip_group)
544+
545+
self.constrain_dip_checkbox = QCheckBox("Also constrain dip (weak)")
546+
self.constrain_dip_checkbox.setChecked(
547+
self.existing_data.get('form_line_dip') is not None
548+
)
549+
dip_layout.addRow(self.constrain_dip_checkbox)
550+
551+
self.dip_spin = QDoubleSpinBox()
552+
self.dip_spin.setRange(0, 90)
553+
self.dip_spin.setValue(self.existing_data.get('form_line_dip') or 60.0)
554+
dip_layout.addRow("Dip", self.dip_spin)
555+
556+
self.reverse_dip_checkbox = QCheckBox("Reverse dip direction")
557+
self.reverse_dip_checkbox.setChecked(
558+
bool(self.existing_data.get('form_line_reverse_dip', False))
559+
)
560+
dip_layout.addRow(self.reverse_dip_checkbox)
561+
562+
self.dip_weight_spin = QDoubleSpinBox()
563+
self.dip_weight_spin.setRange(0.001, 1.0)
564+
self.dip_weight_spin.setSingleStep(0.01)
565+
self.dip_weight_spin.setDecimals(3)
566+
self.dip_weight_spin.setValue(self.existing_data.get('form_line_dip_weight', 0.1))
567+
dip_layout.addRow("Weight", self.dip_weight_spin)
568+
569+
self.dip_spin.setEnabled(self.constrain_dip_checkbox.isChecked())
570+
self.reverse_dip_checkbox.setEnabled(self.constrain_dip_checkbox.isChecked())
571+
self.dip_weight_spin.setEnabled(self.constrain_dip_checkbox.isChecked())
572+
self.constrain_dip_checkbox.toggled.connect(self.dip_spin.setEnabled)
573+
self.constrain_dip_checkbox.toggled.connect(self.reverse_dip_checkbox.setEnabled)
574+
self.constrain_dip_checkbox.toggled.connect(self.dip_weight_spin.setEnabled)
575+
576+
layout.addWidget(self.dip_group)
577+
578+
def update_dip_visibility(text):
579+
self.dip_group.setVisible(text == "Constrain Strike")
580+
581+
self.constraint_combo.currentTextChanged.connect(update_dip_visibility)
582+
update_dip_visibility(self.constraint_combo.currentText())
583+
584+
self.field_combos = {
585+
'constraint_combo': self.constraint_combo,
586+
'constrain_dip_checkbox': self.constrain_dip_checkbox,
587+
'dip_spin': self.dip_spin,
588+
'reverse_dip_checkbox': self.reverse_dip_checkbox,
589+
'dip_weight_spin': self.dip_weight_spin,
590+
}
591+
508592
def _setup_inequality_fields(self, layout):
509593
"""Setup fields for inequality data type."""
510594
field_layout = QHBoxLayout()
@@ -542,7 +626,10 @@ def _validate_layer_selection(self):
542626
return False
543627

544628
layer_name = self.layer_combo.currentLayer().name()
545-
if layer_name in self.data_manager.feature_data.get(self.feature_name, {}):
629+
is_layer_being_edited = layer_name == self.existing_data.get('layer_name')
630+
if not is_layer_being_edited and layer_name in self.data_manager.feature_data.get(
631+
self.feature_name, {}
632+
):
546633
self.data_manager.logger("Layer already selected.", log_level=2)
547634
self.button_box.button(QDialogButtonBox.Ok).setEnabled(False)
548635
return False
@@ -586,6 +673,19 @@ def _on_accepted(self):
586673
self.layer_data['lower_field'] = self.field_combos['lower_field'].currentField()
587674
self.layer_data['upper_field'] = self.field_combos['upper_field'].currentField()
588675

676+
elif self.layer_type == "Form Line":
677+
constraint_text = self.field_combos['constraint_combo'].currentText()
678+
is_strike = constraint_text == "Constrain Strike"
679+
self.layer_data['form_line_constraint'] = 'strike' if is_strike else 'value'
680+
if is_strike and self.field_combos['constrain_dip_checkbox'].isChecked():
681+
self.layer_data['form_line_dip'] = self.field_combos['dip_spin'].value()
682+
self.layer_data['form_line_reverse_dip'] = self.field_combos[
683+
'reverse_dip_checkbox'
684+
].isChecked()
685+
self.layer_data['form_line_dip_weight'] = self.field_combos[
686+
'dip_weight_spin'
687+
].value()
688+
589689
self.accept()
590690

591691
def get_layer_data(self):

‎loopstructural/main/model_manager.py‎

Lines changed: 76 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,38 @@ def __call__(self, line: gpd.GeoDataFrame, dem: Callable, use_z: bool) -> pd.Dat
100100
return df
101101

102102

103+
def _form_line_tangent_vectors(df: pd.DataFrame) -> np.ndarray:
104+
"""Per-vertex unit tangent (tx, ty, tz) along each digitised line in `df`.
105+
106+
Points are grouped by `feature_id` (one group per digitised line, in the
107+
vertex order `AllSampler` walks each geometry's coords) and the local
108+
tangent at each vertex is a central difference against its neighbours,
109+
falling back to a forward/backward difference at each line's two ends --
110+
the same construction used for fault traces in
111+
`GeologicalModelManager._extend_fault_trace_to_domain`, generalised to 3D
112+
and without the bounding-box extension (which is fault-specific).
113+
114+
A line with a single vertex has no direction, so its row is left as NaN.
115+
"""
116+
xyz = df[['X', 'Y', 'Z']].to_numpy(dtype=float)
117+
tangents = np.full((len(df), 3), np.nan)
118+
for _, group_index in df.groupby('feature_id', sort=False).groups.items():
119+
pos = df.index.get_indexer(group_index)
120+
pts = xyz[pos]
121+
n = len(pts)
122+
if n < 2:
123+
continue
124+
t = np.zeros((n, 3))
125+
t[0] = pts[1] - pts[0]
126+
t[-1] = pts[-1] - pts[-2]
127+
if n > 2:
128+
t[1:-1] = pts[2:] - pts[:-2]
129+
norm = np.linalg.norm(t, axis=1, keepdims=True)
130+
norm[norm < 1e-9] = np.nan
131+
tangents[pos] = t / norm
132+
return tangents
133+
134+
103135
class GeologicalModelManager(Observable):
104136
"""This class manages the geological model and assembles it from the data provided by the data manager.
105137
It is responsible for updating the model with faults, stratigraphy, and other geological features.
@@ -1424,8 +1456,9 @@ def add_foliation(
14241456
data : dict
14251457
Mapping of layer identifiers to dicts describing each layer. Each
14261458
layer dict must include a 'type' key (one of 'Orientation',
1427-
'Formline', 'Value', 'Inequality') and the fields required by that
1428-
type (e.g. 'strike_field', 'dip_field', 'value_field', ...).
1459+
'Form Line', 'Value', 'Inequality') and the fields required by
1460+
that type (e.g. 'strike_field', 'dip_field', 'value_field',
1461+
'form_line_constraint', ...).
14291462
folded_feature_name : str or None
14301463
Optional name of a feature to which the foliation should be
14311464
associated/converted (currently unused in this helper).
@@ -1443,15 +1476,54 @@ def add_foliation(
14431476
# for z
14441477
dfs = []
14451478
kwargs = {}
1479+
interface_offset = 0
14461480
for layer_data in data.values():
1481+
if layer_data.get('processed'):
1482+
# auto-synced rows from the map2loop workflow (type values
1483+
# like 'Contact (auto)') aren't meant for this manual path
1484+
continue
14471485
if layer_data['type'] == 'Orientation':
14481486
df = sampler(layer_data['df'], self.dem_function, use_z_coordinate)
14491487
df['strike'] = df[layer_data['strike_field']]
1488+
if layer_data.get('orientation_format') == 'Dip Direction':
1489+
df['strike'] = df['strike'] - 90
14501490
df['dip'] = df[layer_data['dip_field']]
14511491
df['feature_name'] = name
14521492
dfs.append(df[['X', 'Y', 'Z', 'strike', 'dip', 'feature_name']])
1453-
elif layer_data['type'] == 'Formline':
1454-
pass
1493+
elif layer_data['type'] == 'Form Line':
1494+
df = sampler(layer_data['df'], self.dem_function, use_z_coordinate)
1495+
df['feature_name'] = name
1496+
if layer_data.get('form_line_constraint') == 'strike':
1497+
df[['tx', 'ty', 'tz']] = _form_line_tangent_vectors(df)
1498+
df = df.dropna(subset=['tx', 'ty', 'tz'])
1499+
dfs.append(df[['X', 'Y', 'Z', 'tx', 'ty', 'tz', 'feature_name']])
1500+
dip = layer_data.get('form_line_dip')
1501+
if dip is not None and not df.empty:
1502+
# The line's own direction is a precisely known hard
1503+
# fact (the tangent constraint above), but a fixed
1504+
# dip magnitude is usually only a rough regional
1505+
# estimate -- so it's added as a *low-weight*
1506+
# constraint that nudges the field towards that dip
1507+
# rather than rigidly enforcing it at every vertex.
1508+
strike = np.degrees(np.arctan2(df['tx'], df['ty'])) % 360
1509+
if layer_data.get('form_line_reverse_dip'):
1510+
# A form line's strike is only known up to 180
1511+
# degrees (it depends on digitising direction),
1512+
# and unlike the tangent-only constraint above,
1513+
# a fixed dip *magnitude* makes that ambiguity
1514+
# matter: the two mirror-image planes sharing
1515+
# this strike and dip differ by 180 degrees of
1516+
# strike.
1517+
strike = (strike + 180) % 360
1518+
dip_df = df[['X', 'Y', 'Z', 'feature_name']].copy()
1519+
dip_df['strike'] = strike
1520+
dip_df['dip'] = dip
1521+
dip_df['w'] = layer_data.get('form_line_dip_weight', 0.1)
1522+
dfs.append(dip_df[['X', 'Y', 'Z', 'strike', 'dip', 'w', 'feature_name']])
1523+
else:
1524+
df['interface'] = df['feature_id'].astype(float) + interface_offset
1525+
interface_offset += df['feature_id'].nunique()
1526+
dfs.append(df[['X', 'Y', 'Z', 'interface', 'feature_name']])
14551527
elif layer_data['type'] == 'Value':
14561528
df = sampler(layer_data['df'], self.dem_function, use_z_coordinate)
14571529
df['val'] = df[layer_data['value_field']]
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
"""Pytest tests for the `_form_line_tangent_vectors` helper.
2+
3+
Like AllSampler, this only operates on a plain pandas DataFrame, but it
4+
lives in model_manager.py, which imports LoopStructural/QGIS at module
5+
level, so this test can only run where those are installed (hence
6+
tests/qgis/ rather than tests/unit/).
7+
"""
8+
9+
import numpy as np
10+
import pandas as pd
11+
12+
from loopstructural.main.model_manager import _form_line_tangent_vectors
13+
14+
15+
def _line_df(points, feature_id=0):
16+
return pd.DataFrame(
17+
{
18+
'X': [p[0] for p in points],
19+
'Y': [p[1] for p in points],
20+
'Z': [p[2] for p in points],
21+
'feature_id': [feature_id] * len(points),
22+
}
23+
)
24+
25+
26+
class TestFormLineTangentVectors:
27+
def test_straight_line_gives_constant_unit_tangent(self):
28+
df = _line_df([(0, 0, 0), (1, 0, 0), (2, 0, 0), (3, 0, 0)])
29+
30+
tangents = _form_line_tangent_vectors(df)
31+
32+
expected = np.tile([1.0, 0.0, 0.0], (4, 1))
33+
np.testing.assert_allclose(tangents, expected, atol=1e-12)
34+
35+
def test_interior_point_uses_central_difference(self):
36+
# An L-shaped bend: the interior point's tangent should be the
37+
# (normalised) average direction of the two adjacent segments,
38+
# not either segment alone.
39+
df = _line_df([(0, 0, 0), (1, 0, 0), (1, 1, 0)])
40+
41+
tangents = _form_line_tangent_vectors(df)
42+
43+
raw = np.array([1.0, 1.0, 0.0])
44+
expected_interior = raw / np.linalg.norm(raw)
45+
np.testing.assert_allclose(tangents[0], [1.0, 0.0, 0.0], atol=1e-12)
46+
np.testing.assert_allclose(tangents[1], expected_interior, atol=1e-12)
47+
np.testing.assert_allclose(tangents[2], [0.0, 1.0, 0.0], atol=1e-12)
48+
49+
def test_single_point_line_is_nan(self):
50+
df = _line_df([(0, 0, 0)])
51+
52+
tangents = _form_line_tangent_vectors(df)
53+
54+
assert np.all(np.isnan(tangents))
55+
56+
def test_multiple_lines_are_independent(self):
57+
df = pd.concat(
58+
[
59+
_line_df([(0, 0, 0), (1, 0, 0)], feature_id=0),
60+
_line_df([(5, 5, 0), (5, 6, 0)], feature_id=1),
61+
],
62+
ignore_index=True,
63+
)
64+
65+
tangents = _form_line_tangent_vectors(df)
66+
67+
np.testing.assert_allclose(tangents[0:2], np.tile([1.0, 0.0, 0.0], (2, 1)), atol=1e-12)
68+
np.testing.assert_allclose(tangents[2:4], np.tile([0.0, 1.0, 0.0], (2, 1)), atol=1e-12)
69+
70+
def test_coincident_points_give_nan_tangent(self):
71+
df = _line_df([(0, 0, 0), (0, 0, 0)])
72+
73+
tangents = _form_line_tangent_vectors(df)
74+
75+
assert np.all(np.isnan(tangents))

0 commit comments

Comments
 (0)