Skip to content

Commit 5cd2a60

Browse files
committed
fix: use one geology source in the thickness algorithm
The algorithm now uses the geology feature source for the units, the bounding box and the basal contact extraction. Thus "selected features only" applies to all of them, and an input that is not a map layer works. Add an optional faults input. The faults are used when the algorithm extracts the basal contacts from the geology. Show an error if the extraction finds no basal contacts. Add tests for basal contacts from the geology layer and from the selected features only.
1 parent 7ed4ab6 commit 5cd2a60

2 files changed

Lines changed: 191 additions & 16 deletions

File tree

‎loopstructural/processing/algorithms/thickness_calculator.py‎

Lines changed: 43 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ class ThicknessCalculatorAlgorithm(QgsProcessingAlgorithm):
5353
INPUT_MAX_LINE_LENGTH = 'MAX_LINE_LENGTH'
5454
INPUT_STRATI_COLUMN = 'STRATIGRAPHIC_COLUMN'
5555
INPUT_BASAL_CONTACTS = 'BASAL_CONTACTS'
56+
INPUT_FAULTS = 'FAULTS'
5657
INPUT_STRUCTURE_DATA = 'STRUCTURE_DATA'
5758
INPUT_DIPDIR_FIELD = 'DIPDIR_FIELD'
5859
INPUT_DIP_FIELD = 'DIP_FIELD'
@@ -145,6 +146,16 @@ def initAlgorithm(self, config: Optional[dict[str, Any]] = None) -> None:
145146
[QgsProcessing.SourceType.TypeVectorPolygon],
146147
)
147148
)
149+
# Faults are only used when the basal contacts are extracted from the
150+
# geology layer.
151+
self.addParameter(
152+
QgsProcessingParameterFeatureSource(
153+
self.INPUT_FAULTS,
154+
"Faults (optional, used to extract basal contacts)",
155+
[QgsProcessing.SourceType.TypeVectorLine],
156+
optional=True,
157+
)
158+
)
148159

149160
self.addParameter(
150161
QgsProcessingParameterField(
@@ -251,7 +262,10 @@ def processAlgorithm(
251262
bounding_box_type = self.parameterAsEnum(parameters, self.INPUT_BOUNDING_BOX_TYPE, context)
252263
max_line_length = self.parameterAsSource(parameters, self.INPUT_MAX_LINE_LENGTH, context)
253264
basal_contacts = self.parameterAsSource(parameters, self.INPUT_BASAL_CONTACTS, context)
254-
geology_data = self.parameterAsSource(parameters, self.INPUT_GEOLOGY, context)
265+
geology_source = self.parameterAsSource(parameters, self.INPUT_GEOLOGY, context)
266+
if geology_source is None:
267+
raise QgsProcessingException(self.invalidSourceError(parameters, self.INPUT_GEOLOGY))
268+
faults_source = self.parameterAsSource(parameters, self.INPUT_FAULTS, context)
255269
structure_data = self.parameterAsSource(parameters, self.INPUT_STRUCTURE_DATA, context)
256270
orientation_type = self.parameterAsEnum(parameters, self.INPUT_ORIENTATION_TYPE, context)
257271
is_strike = orientation_type == 1
@@ -262,15 +276,19 @@ def processAlgorithm(
262276

263277
sampled_contacts = self.parameterAsSource(parameters, self.INPUT_SAMPLED_CONTACTS, context)
264278
unit_name_field = self.parameterAsString(parameters, self.INPUT_UNIT_NAME_FIELD, context)
265-
geology_layer = self.parameterAsVectorLayer(parameters, self.INPUT_GEOLOGY, context)
279+
# Use the geology source for the units, the bounding box and the basal
280+
# contacts. The source follows "selected features only", and it is
281+
# also correct when the input is not a map layer.
282+
units = qgsLayerToDataFrame(geology_source)
283+
geology_data = qgsLayerToGeoDataFrame(geology_source)
266284

267285
if bounding_box_type == 0:
268-
extent = geology_layer.extent()
286+
minx, miny, maxx, maxy = geology_data.total_bounds
269287
bounding_box = {
270-
'minx': extent.xMinimum(),
271-
'miny': extent.yMinimum(),
272-
'maxx': extent.xMaximum(),
273-
'maxy': extent.yMaximum(),
288+
'minx': minx,
289+
'miny': miny,
290+
'maxx': maxx,
291+
'maxy': maxy,
274292
}
275293
feedback.pushInfo("Using bounding box from geology layer")
276294
else:
@@ -314,21 +332,30 @@ def processAlgorithm(
314332
strati_column_settings = QgsSettings()
315333
strati_column_settings.setValue('m2l/strati_column', matrix)
316334
# convert layers to dataframe or geodataframe
317-
units = qgsLayerToDataFrame(geology_data)
318-
geology_data = qgsLayerToGeoDataFrame(geology_data)
319335
if basal_contacts is not None:
320336
basal_contacts = qgsLayerToGeoDataFrame(basal_contacts)
321337
else:
322338
feedback.pushInfo(
323339
"No basal contacts layer supplied; extracting basal contacts from geology layer..."
324340
)
325-
basal_contacts = extract_basal_contacts(
326-
geology=geology_layer,
327-
stratigraphic_order=stratigraphic_order,
328-
unit_name_field=unit_name_field,
329-
updater=feedback.pushInfo,
330-
target_crs=geology_layer.crs() if geology_layer else None,
331-
)['basal_contacts']
341+
# Reproject the faults to the CRS of the geology, so that the two
342+
# layers align.
343+
try:
344+
basal_contacts = extract_basal_contacts(
345+
geology=geology_source,
346+
stratigraphic_order=stratigraphic_order,
347+
faults=faults_source,
348+
unit_name_field=unit_name_field,
349+
updater=feedback.pushInfo,
350+
target_crs=geology_source.sourceCrs(),
351+
)['basal_contacts']
352+
except Exception as err:
353+
raise QgsProcessingException(str(err)) from err
354+
if basal_contacts.empty:
355+
raise QgsProcessingException(
356+
"No basal contacts were found in the geology layer. Make sure that "
357+
"the units in the stratigraphic column are in the geology layer."
358+
)
332359
structure_data = qgsLayerToDataFrame(structure_data)
333360
rename_map = {}
334361
missing_fields = []
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
"""The thickness calculator algorithm extracts basal contacts from geology.
2+
3+
When no basal contacts layer is given, the algorithm gets the basal contacts
4+
from the geology layer and the stratigraphic column. The map2loop calculator
5+
is replaced with a fake, so these tests examine only the data that the
6+
algorithm gives to it.
7+
"""
8+
9+
import unittest
10+
from unittest.mock import patch
11+
12+
import pandas as pd
13+
from qgis.core import (
14+
QgsFeature,
15+
QgsGeometry,
16+
QgsProcessing,
17+
QgsProcessingContext,
18+
QgsProcessingFeatureSourceDefinition,
19+
QgsProcessingFeedback,
20+
QgsProject,
21+
QgsVectorLayer,
22+
)
23+
from qgis.testing import start_app
24+
25+
from loopstructural.processing.algorithms.thickness_calculator import (
26+
ThicknessCalculatorAlgorithm,
27+
)
28+
29+
MODULE = 'loopstructural.processing.algorithms.thickness_calculator'
30+
31+
32+
class FakeCalculator:
33+
"""Keep the arguments of compute and return a thickness for each unit."""
34+
35+
calls = []
36+
37+
def __init__(self, **kwargs):
38+
self.kwargs = kwargs
39+
40+
def compute(self, units, stratigraphic_order, basal_contacts, *args):
41+
FakeCalculator.calls.append({'kwargs': self.kwargs, 'basal_contacts': basal_contacts})
42+
return pd.DataFrame(
43+
{
44+
'name': list(units['name']),
45+
'ThicknessMean': 1.0,
46+
'ThicknessMedian': 1.0,
47+
'ThicknessStdDev': 0.0,
48+
}
49+
)
50+
51+
52+
class TestThicknessFromGeology(unittest.TestCase):
53+
54+
@classmethod
55+
def setUpClass(cls):
56+
cls.qgs = start_app()
57+
58+
def setUp(self):
59+
FakeCalculator.calls = []
60+
self.geology = self._geology()
61+
QgsProject.instance().addMapLayer(self.geology)
62+
63+
def tearDown(self):
64+
QgsProject.instance().removeMapLayer(self.geology.id())
65+
66+
def _geology(self):
67+
# Two blocks of the layers A, B and C (top to bottom). The first block
68+
# is at 0 <= x <= 100 and the second block is at 1000 <= x <= 1100.
69+
layer = QgsVectorLayer("Polygon?crs=EPSG:28350&field=unitname:string", "geology", "memory")
70+
features = []
71+
for x0 in (0, 1000):
72+
x1 = x0 + 100
73+
for name, (y0, y1) in {'A': (200, 300), 'B': (100, 200), 'C': (0, 100)}.items():
74+
feature = QgsFeature(layer.fields())
75+
feature.setAttribute('unitname', name)
76+
feature.setGeometry(
77+
QgsGeometry.fromWkt(
78+
f"POLYGON(({x0} {y0}, {x1} {y0}, {x1} {y1}, {x0} {y1}, {x0} {y0}))"
79+
)
80+
)
81+
features.append(feature)
82+
layer.dataProvider().addFeatures(features)
83+
return layer
84+
85+
def _points(self, fields, values):
86+
layer = QgsVectorLayer(f"Point?crs=EPSG:28350&{fields}", "points", "memory")
87+
features = []
88+
for x, y, attributes in values:
89+
feature = QgsFeature(layer.fields())
90+
feature.setAttributes(attributes)
91+
feature.setGeometry(QgsGeometry.fromWkt(f"POINT({x} {y})"))
92+
features.append(feature)
93+
layer.dataProvider().addFeatures(features)
94+
return layer
95+
96+
def _run(self, geology):
97+
structure = self._points("field=DIPDIR:double&field=DIP:double", [(50, 150, [90.0, 10.0])])
98+
sampled_contacts = self._points("field=unit:string", [(50, 200, ['A'])])
99+
algorithm = ThicknessCalculatorAlgorithm()
100+
algorithm.initAlgorithm()
101+
parameters = {
102+
'THICKNESS_CALCULATOR_TYPE': 0,
103+
'BOUNDING_BOX_TYPE': 0,
104+
'MAX_LINE_LENGTH': 1000,
105+
'GEOLOGY': geology,
106+
'UNIT_NAME_FIELD': 'unitname',
107+
'STRATIGRAPHIC_COLUMN': ['A', 'B', 'C'],
108+
'SAMPLED_CONTACTS': sampled_contacts,
109+
'STRUCTURE_DATA': structure,
110+
'ORIENTATION_TYPE': 0,
111+
'DIPDIR_FIELD': 'DIPDIR',
112+
'DIP_FIELD': 'DIP',
113+
'THICKNESS': QgsProcessing.TEMPORARY_OUTPUT,
114+
}
115+
context = QgsProcessingContext()
116+
context.setProject(QgsProject.instance())
117+
with patch(f'{MODULE}.InterpolatedStructure', FakeCalculator):
118+
algorithm.processAlgorithm(parameters, context, QgsProcessingFeedback())
119+
self.assertEqual(len(FakeCalculator.calls), 1)
120+
return FakeCalculator.calls[0]
121+
122+
def _length(self, contacts, unit):
123+
return contacts[contacts['basal_unit'] == unit].geometry.length.sum()
124+
125+
def test_contacts_from_geology_layer(self):
126+
call = self._run(self.geology)
127+
contacts = call['basal_contacts']
128+
self.assertFalse(contacts.empty)
129+
# Each block has one contact of 100 m for A (on B) and for B (on C).
130+
self.assertAlmostEqual(self._length(contacts, 'A'), 200, delta=5)
131+
self.assertAlmostEqual(self._length(contacts, 'B'), 200, delta=5)
132+
self.assertAlmostEqual(call['kwargs']['bounding_box']['maxx'], 1100)
133+
134+
def test_contacts_from_selected_features_only(self):
135+
# Select only the first block.
136+
self.geology.selectByExpression('x(centroid($geometry)) < 500')
137+
self.assertEqual(self.geology.selectedFeatureCount(), 3)
138+
call = self._run(QgsProcessingFeatureSourceDefinition(self.geology.id(), True))
139+
contacts = call['basal_contacts']
140+
self.assertFalse(contacts.empty)
141+
self.assertLessEqual(contacts.total_bounds[2], 100 + 1e-6)
142+
self.assertAlmostEqual(self._length(contacts, 'A'), 100, delta=5)
143+
self.assertAlmostEqual(self._length(contacts, 'B'), 100, delta=5)
144+
self.assertAlmostEqual(call['kwargs']['bounding_box']['maxx'], 100)
145+
146+
147+
if __name__ == '__main__':
148+
unittest.main()

0 commit comments

Comments
 (0)