Skip to content

Commit 2f55f97

Browse files
committed
feat: add basal contact override functionality to handle full boundaries
1 parent c5a63fa commit 2f55f97

5 files changed

Lines changed: 203 additions & 16 deletions

File tree

‎loopstructural/gui/map2loop_tools/basal_contacts_widget.py‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,8 @@ def _restore_selection(self):
161161
self.faultsLayerComboBox.setLayer(layer)
162162
if field := settings.get('unit_name_field'):
163163
self.unitNameFieldComboBox.setField(field)
164+
if units := settings.get('basal_override_units'):
165+
self.basalOverrideUnitsLineEdit.setText(', '.join(units))
164166

165167
def _persist_selection(self):
166168
"""Persist current selections into data manager."""
@@ -178,6 +180,7 @@ def _persist_selection(self):
178180
else None
179181
),
180182
'unit_name_field': self.unitNameFieldComboBox.currentField(),
183+
'basal_override_units': self._units_from_line_edit(self.basalOverrideUnitsLineEdit),
181184
}
182185
self.data_manager.set_widget_settings('basal_contacts_widget', settings)
183186

@@ -309,6 +312,11 @@ def _on_extractor_error(self, traceback_text):
309312
QMessageBox.critical(self, "Error", f"An error occurred: {summary}")
310313
self.task_failed.emit()
311314

315+
@staticmethod
316+
def _units_from_line_edit(line_edit):
317+
"""Return the unit names in a comma-separated line edit."""
318+
return [unit.strip() for unit in line_edit.text().split(',') if unit.strip()]
319+
312320
def get_parameters(self):
313321
"""Get current widget parameters.
314322
@@ -317,17 +325,15 @@ def get_parameters(self):
317325
dict
318326
Dictionary of current widget parameters.
319327
"""
320-
ignore_units = []
321-
if self.ignoreUnitsLineEdit.text().strip():
322-
ignore_units = [
323-
unit.strip() for unit in self.ignoreUnitsLineEdit.text().split(',') if unit.strip()
324-
]
328+
ignore_units = self._units_from_line_edit(self.ignoreUnitsLineEdit)
329+
basal_override_units = self._units_from_line_edit(self.basalOverrideUnitsLineEdit)
325330

326331
return {
327332
'geology_layer': self.geologyLayerComboBox.currentLayer(),
328333
'unit_name_field': self.unitNameFieldComboBox.currentField(),
329334
'faults_layer': self.faultsLayerComboBox.currentLayer(),
330335
'ignore_units': ignore_units,
336+
'basal_override_units': basal_override_units,
331337
'all_contacts': self.allContactsCheckBox.isChecked(),
332338
}
333339

@@ -345,6 +351,8 @@ def set_parameters(self, params):
345351
self.faultsLayerComboBox.setLayer(params['faults_layer'])
346352
if params.get('ignore_units'):
347353
self.ignoreUnitsLineEdit.setText(', '.join(params['ignore_units']))
354+
if params.get('basal_override_units'):
355+
self.basalOverrideUnitsLineEdit.setText(', '.join(params['basal_override_units']))
348356
if 'all_contacts' in params:
349357
self.allContactsCheckBox.setChecked(params['all_contacts'])
350358

@@ -361,11 +369,8 @@ def _make_extract_contacts_target(self):
361369
`extract_basal_contacts()`; anything that touches the project or
362370
shows UI happens afterwards, in `_on_extractor_finished`.
363371
"""
364-
ignore_units = []
365-
if self.ignoreUnitsLineEdit.text().strip():
366-
ignore_units = [
367-
unit.strip() for unit in self.ignoreUnitsLineEdit.text().split(',') if unit.strip()
368-
]
372+
ignore_units = self._units_from_line_edit(self.ignoreUnitsLineEdit)
373+
basal_override_units = self._units_from_line_edit(self.basalOverrideUnitsLineEdit)
369374
geology = self.geologyLayerComboBox.currentLayer()
370375
unit_name_field = self.unitNameFieldComboBox.currentField()
371376
faults = self.faultsLayerComboBox.currentLayer()
@@ -423,6 +428,7 @@ def _is_null_like(v):
423428
debug_manager=self._debug,
424429
target_crs=target_crs,
425430
unit_colours=unit_colours,
431+
basal_override_units=basal_override_units,
426432
)
427433
return result, all_contacts
428434

‎loopstructural/gui/map2loop_tools/basal_contacts_widget.ui‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,30 @@
6868
</widget>
6969
</item>
7070
<item row="4" column="0">
71+
<widget class="QLabel" name="basalOverrideUnitsLabel">
72+
<property name="text">
73+
<string>Basal Contact Overrides:</string>
74+
</property>
75+
</widget>
76+
</item>
77+
<item row="4" column="1">
78+
<widget class="QLineEdit" name="basalOverrideUnitsLineEdit">
79+
<property name="placeholderText">
80+
<string>Comma-separated list of units (e.g. cover, intrusions)</string>
81+
</property>
82+
<property name="toolTip">
83+
<string>The basal contact of each of these units is its full boundary with all other units. The stratigraphic order is not used for these units.</string>
84+
</property>
85+
</widget>
86+
</item>
87+
<item row="5" column="0">
7188
<widget class="QLabel" name="contactTypeLabel">
7289
<property name="text">
7390
<string>Contact Type:</string>
7491
</property>
7592
</widget>
7693
</item>
77-
<item row="4" column="1">
94+
<item row="5" column="1">
7895
<widget class="QCheckBox" name="allContactsCheckBox">
7996
<property name="text">
8097
<string>Extract All Contacts (not just basal)</string>

‎loopstructural/main/m2l_api.py‎

Lines changed: 88 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,69 @@ def orient_order_by_structure(
182182
return agree, disagree
183183

184184

185+
def split_override_contacts(contacts, override_units, stratigraphic_order):
186+
"""Take the contacts of the override units out of the contacts.
187+
188+
The basal contact of an override unit (for example cover or an intrusion)
189+
is its full boundary with all other units. It does not come from the
190+
stratigraphic order. Thus each contact that touches an override unit is
191+
a basal contact of that unit, and it is not given to the other unit.
192+
193+
Parameters
194+
----------
195+
contacts : GeoDataFrame
196+
All contacts, with 'UNITNAME_1' and 'UNITNAME_2' columns.
197+
override_units : list
198+
Names of the override units.
199+
stratigraphic_order : list
200+
Unit names, youngest first. If a contact is between two override
201+
units, it is the basal contact of the younger unit. A unit that is
202+
not in this list is younger than the units that are.
203+
204+
Returns
205+
-------
206+
tuple(GeoDataFrame, GeoDataFrame)
207+
(the contacts that do not touch an override unit, the basal contacts
208+
of the override units with 'ID', 'basal_unit', 'type' and 'geometry'
209+
columns, as map2loop gives them)
210+
"""
211+
import shapely
212+
213+
override_units = [str(unit).strip() for unit in override_units or [] if unit is not None]
214+
override_units = [unit for unit in override_units if unit]
215+
columns = ['ID', 'basal_unit', 'type', 'geometry']
216+
if contacts is None:
217+
return contacts, pd.DataFrame(columns=columns)
218+
if not override_units or len(contacts) == 0:
219+
return contacts, contacts.iloc[0:0].reindex(columns=columns)
220+
221+
unit_1 = contacts['UNITNAME_1'].astype(str).str.strip()
222+
unit_2 = contacts['UNITNAME_2'].astype(str).str.strip()
223+
touches = unit_1.isin(override_units) | unit_2.isin(override_units)
224+
remaining = contacts[~touches].reset_index(drop=True)
225+
overridden = contacts[touches].reset_index(drop=True)
226+
227+
order = [str(name).strip() for name in stratigraphic_order if name is not None]
228+
229+
def age_rank(unit):
230+
return order.index(unit) if unit in order else -1
231+
232+
def owner(row):
233+
a = str(row['UNITNAME_1']).strip()
234+
b = str(row['UNITNAME_2']).strip()
235+
if a in override_units and b in override_units:
236+
return a if age_rank(a) <= age_rank(b) else b
237+
return a if a in override_units else b
238+
239+
overridden['basal_unit'] = [owner(row) for _, row in overridden.iterrows()]
240+
overridden['ID'] = [age_rank(unit) for unit in overridden['basal_unit']]
241+
overridden['type'] = 'BASAL'
242+
overridden['geometry'] = [
243+
shapely.line_merge(shapely.snap(geo, geo, 1)) for geo in overridden['geometry']
244+
]
245+
return remaining, overridden[columns]
246+
247+
185248
def extract_basal_contacts(
186249
geology,
187250
stratigraphic_order,
@@ -193,6 +256,7 @@ def extract_basal_contacts(
193256
debug_manager=None,
194257
target_crs=None,
195258
unit_colours=None,
259+
basal_override_units=None,
196260
):
197261
"""Extract basal contacts from geological data.
198262
@@ -221,6 +285,11 @@ def extract_basal_contacts(
221285
Mapping of unit name to colour. When given, a 'colour' column is
222286
added to the returned basal contacts, looked up by the 'basal_unit'
223287
each contact was extracted for.
288+
basal_override_units : list, optional
289+
Names of units (for example cover or an intrusion) whose basal contact
290+
is their full boundary with all other units, not the contacts that the
291+
stratigraphic order gives. These units do not have to be in the
292+
stratigraphic column. See split_override_contacts.
224293
225294
Returns
226295
-------
@@ -259,7 +328,12 @@ def extract_basal_contacts(
259328
str(name).strip() for name in stratigraphic_order if name is not None
260329
}
261330
ignored_names = {str(unit).strip() for unit in ignore_units if unit is not None}
262-
missing_from_column = sorted(geology_unit_names - stratigraphic_names - ignored_names)
331+
override_names = {
332+
str(unit).strip() for unit in basal_override_units or [] if unit is not None
333+
}
334+
missing_from_column = sorted(
335+
geology_unit_names - stratigraphic_names - ignored_names - override_names
336+
)
263337
if missing_from_column:
264338
message = (
265339
"The geology layer has unit(s) with no entry in the stratigraphic column: "
@@ -278,6 +352,7 @@ def extract_basal_contacts(
278352
"ignore_units": ignore_units,
279353
"unit_name_field": unit_name_field,
280354
"all_contacts": all_contacts,
355+
"basal_override_units": basal_override_units,
281356
"geology": geology,
282357
"faults": faults,
283358
},
@@ -304,14 +379,22 @@ def extract_basal_contacts(
304379

305380
try:
306381
all_contacts_result = contact_extractor.extract_all_contacts()
382+
column_contacts, override_contacts = split_override_contacts(
383+
all_contacts_result, basal_override_units, stratigraphic_order
384+
)
307385
# map2loop raises if a contact has a unit that is not in the column,
308386
# so give it only the contacts between units that are in the column.
309387
column_units = [name for name in stratigraphic_order if name is not None]
310-
contact_extractor.contacts = all_contacts_result[
311-
all_contacts_result['UNITNAME_1'].isin(column_units)
312-
& all_contacts_result['UNITNAME_2'].isin(column_units)
388+
contact_extractor.contacts = column_contacts[
389+
column_contacts['UNITNAME_1'].isin(column_units)
390+
& column_contacts['UNITNAME_2'].isin(column_units)
313391
].reset_index(drop=True)
314-
basal_contacts = contact_extractor.extract_basal_contacts(column_units)
392+
if len(contact_extractor.contacts) > 0:
393+
basal_contacts = contact_extractor.extract_basal_contacts(column_units)
394+
else:
395+
basal_contacts = override_contacts.iloc[0:0]
396+
if len(override_contacts) > 0:
397+
basal_contacts = pd.concat([basal_contacts, override_contacts], ignore_index=True)
315398
logger.debug(
316399
"Extracted contacts: all=%s basal=%s",
317400
all_contacts_result.shape,

‎loopstructural/processing/algorithms/extract_basal_contacts.py‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class BasalContactsAlgorithm(QgsProcessingAlgorithm):
4040
INPUT_FAULTS = 'FAULTS'
4141
INPUT_STRATI_COLUMN = 'STRATIGRAPHIC_COLUMN'
4242
INPUT_IGNORE_UNITS = 'IGNORE_UNITS'
43+
INPUT_BASAL_OVERRIDE_UNITS = 'BASAL_OVERRIDE_UNITS'
4344
OUTPUT = "BASAL_CONTACTS"
4445
ALL_CONTACTS = "ALL_CONTACTS"
4546

@@ -107,6 +108,15 @@ def initAlgorithm(self, config: Optional[dict[str, Any]] = None) -> None:
107108
)
108109
)
109110

111+
self.addParameter(
112+
QgsProcessingParameterMatrix(
113+
self.INPUT_BASAL_OVERRIDE_UNITS,
114+
"Basal contact override unit(s) (full boundary is the basal contact)",
115+
headers=["Unit"],
116+
optional=True,
117+
)
118+
)
119+
110120
self.addParameter(
111121
QgsProcessingParameterFeatureSink(
112122
self.OUTPUT,
@@ -136,6 +146,13 @@ def processAlgorithm(
136146
strati_order = []
137147
unit_colours = None
138148
ignore_units = self.parameterAsMatrix(parameters, self.INPUT_IGNORE_UNITS, context)
149+
basal_override_units = [
150+
str(unit).strip()
151+
for unit in self.parameterAsMatrix(
152+
parameters, self.INPUT_BASAL_OVERRIDE_UNITS, context
153+
)
154+
if unit is not None and str(unit).strip()
155+
]
139156

140157
if isinstance(strati_column, QgsProcessingParameterMapLayer):
141158
raise QgsProcessingException("Invalid stratigraphic column layer")
@@ -173,6 +190,7 @@ def processAlgorithm(
173190
updater=feedback.pushInfo,
174191
target_crs=geology.crs() if geology else None,
175192
unit_colours=unit_colours,
193+
basal_override_units=basal_override_units,
176194
)
177195
basal_contacts = result['basal_contacts']
178196
all_contacts = result['all_contacts']

‎tests/qgis/test_basal_contacts.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import unittest
22
from pathlib import Path
33
from qgis.core import (
4+
QgsFeature,
5+
QgsGeometry,
46
QgsVectorLayer,
57
QgsProcessingContext,
68
QgsProcessingFeedback,
@@ -9,6 +11,7 @@
911
QgsApplication,
1012
)
1113
from qgis.testing import start_app
14+
from loopstructural.main.m2l_api import extract_basal_contacts
1215
from loopstructural.processing.algorithms.extract_basal_contacts import BasalContactsAlgorithm
1316
from loopstructural.processing.provider import Map2LoopProvider
1417

@@ -150,5 +153,65 @@ def tearDownClass(cls):
150153
pass
151154

152155

156+
class TestBasalContactOverrides(unittest.TestCase):
157+
"""Units in basal_override_units get their full boundary as basal contact."""
158+
159+
@classmethod
160+
def setUpClass(cls):
161+
cls.qgs = start_app()
162+
163+
def _geology(self):
164+
# A, B and C are layers from top to bottom (0 <= x <= 100). D is
165+
# a unit on the right side (100 <= x <= 150) that touches all three.
166+
layer = QgsVectorLayer("Polygon?crs=EPSG:28350&field=unitname:string", "geology", "memory")
167+
polygons = {
168+
'A': "POLYGON((0 200, 100 200, 100 300, 0 300, 0 200))",
169+
'B': "POLYGON((0 100, 100 100, 100 200, 0 200, 0 100))",
170+
'C': "POLYGON((0 0, 100 0, 100 100, 0 100, 0 0))",
171+
'D': "POLYGON((100 0, 150 0, 150 300, 100 300, 100 0))",
172+
}
173+
features = []
174+
for name, wkt in polygons.items():
175+
feature = QgsFeature(layer.fields())
176+
feature.setAttribute('unitname', name)
177+
feature.setGeometry(QgsGeometry.fromWkt(wkt))
178+
features.append(feature)
179+
layer.dataProvider().addFeatures(features)
180+
return layer
181+
182+
def _extract(self, order, overrides=None):
183+
return extract_basal_contacts(
184+
geology=self._geology(),
185+
stratigraphic_order=order,
186+
ignore_units=[],
187+
unit_name_field='unitname',
188+
basal_override_units=overrides,
189+
)['basal_contacts']
190+
191+
def _length(self, contacts, unit):
192+
return contacts[contacts['basal_unit'] == unit].geometry.length.sum()
193+
194+
def test_cover_not_in_column(self):
195+
contacts = self._extract(['A', 'B', 'C'])
196+
self.assertNotIn('D', set(contacts['basal_unit']))
197+
198+
contacts = self._extract(['A', 'B', 'C'], overrides=['D'])
199+
self.assertAlmostEqual(self._length(contacts, 'D'), 300, delta=10)
200+
self.assertTrue((contacts[contacts['basal_unit'] == 'D']['type'] == 'BASAL').all())
201+
# the other units keep their basal contacts
202+
self.assertAlmostEqual(self._length(contacts, 'A'), 100, delta=5)
203+
self.assertAlmostEqual(self._length(contacts, 'B'), 100, delta=5)
204+
205+
def test_intrusion_in_column(self):
206+
# without the override, the contact of D with the younger unit A
207+
# is given to A
208+
contacts = self._extract(['A', 'D', 'B', 'C'])
209+
self.assertLess(self._length(contacts, 'D'), 250)
210+
211+
contacts = self._extract(['A', 'D', 'B', 'C'], overrides=['D'])
212+
self.assertAlmostEqual(self._length(contacts, 'D'), 300, delta=10)
213+
self.assertAlmostEqual(self._length(contacts, 'A'), 100, delta=5)
214+
215+
153216
if __name__ == '__main__':
154217
unittest.main()

0 commit comments

Comments
 (0)