Skip to content

Commit 8cb3dd9

Browse files
committed
fix: give the new contacts to the thickness step of a build
- When the contacts and the thicknesses are calculated together, the thickness calculation uses the new contacts, not the out-of-date layer. - The background thread does not change the data manager. finish() puts the contacts into the model on the GUI thread. - Read the inputs with basal_contacts_inputs() and thickness_inputs() without arguments. #134 changed these functions, so the build failed. - qgsLayerToGeoDataFrame accepts a GeoDataFrame. - Add unit tests for the order and for the thread rule.
1 parent 6c546f7 commit 8cb3dd9

3 files changed

Lines changed: 184 additions & 22 deletions

File tree

‎loopstructural/main/derived_refresh.py‎

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ class DerivedRefresh:
6060
6161
Make the object on the GUI thread (it reads the layers and the settings).
6262
Call `run` on the background thread. Call `finish` on the GUI thread.
63+
`run` does not change the data manager. `finish` puts the results in it.
6364
"""
6465

6566
def __init__(self, data_manager, model_manager, names=None):
@@ -90,13 +91,7 @@ def _read_contacts_job(self):
9091
else dm.get_layer_role(layer_roles.FAULT_TRACES)
9192
)
9293
unit_field = dm.get_layer_role(layer_roles.GEOLOGY_UNIT_FIELD)
93-
inputs = dm.basal_contacts_inputs(
94-
geology=geology,
95-
unit_field=unit_field,
96-
faults=faults,
97-
ignore_units=settings.get('ignore_units', []),
98-
override_units=settings.get('basal_override_units', []),
99-
)
94+
inputs = dm.basal_contacts_inputs()
10095
_check_contacts_inputs(inputs)
10196
target_crs = dm.get_model_crs()
10297
if target_crs is None or not target_crs.isValid():
@@ -157,14 +152,7 @@ def layer(key, role=None):
157152
contacts_layer = dm.get_layer_role(layer_roles.BASAL_CONTACTS)
158153
elif settings.get('basal_contacts_layer'):
159154
contacts_layer = dm.find_layer_by_name(settings['basal_contacts_layer'])
160-
inputs = dm.thickness_inputs(
161-
geology=geology,
162-
unit_field=unit_field,
163-
contacts_layer=contacts_layer,
164-
calculator_type=calculator_type,
165-
structure=structure,
166-
cross_sections=cross_sections,
167-
)
155+
inputs = dm.thickness_inputs()
168156
orientation_types = ("Dip Direction", "Strike")
169157
index = settings.get('orientation_type_index', 0)
170158
orientation_type = orientation_types[index] if 0 <= index < len(orientation_types) else None
@@ -234,15 +222,16 @@ def _run_contacts(self, updater):
234222
"column. Check the unit name field and the order of the column."
235223
)
236224
self._contacts_result = contacts
237-
# The model reads the contacts directly. The project layer is only for display.
238-
self.data_manager.update_stratigraphy(
239-
basal_contacts=contacts, unit_name_field=BASAL_CONTACT_UNIT_FIELD
240-
)
241225

242226
def _run_thickness(self, updater):
243227
from .m2l_api import calculate_thickness
244228

245-
result = calculate_thickness(updater=updater, **self._thickness['params'])
229+
params = dict(self._thickness['params'])
230+
if self._contacts_result is not None:
231+
# The contacts of this refresh, not the out-of-date project layer
232+
params['basal_contacts'] = self._contacts_result
233+
params['basal_contacts_unit_name'] = None
234+
result = calculate_thickness(updater=updater, **params)
246235
if not isinstance(result, dict) or result.get('thicknesses') is None:
247236
raise DerivedRefreshError("The thickness calculation gave no result.")
248237
self._thickness_result = result
@@ -260,6 +249,10 @@ def finish(self):
260249
dm = self.data_manager
261250
skipped = []
262251
if self._contacts_result is not None:
252+
# The model reads the contacts directly. The project layer is only for display.
253+
dm.update_stratigraphy(
254+
basal_contacts=self._contacts_result, unit_name_field=BASAL_CONTACT_UNIT_FIELD
255+
)
263256
self._update_contacts_layer(self._contacts_result)
264257
dm.derived.record(derived_data.BASAL_CONTACTS, inputs=self._contacts['inputs'])
265258
if self._thickness_result is not None:

‎loopstructural/main/vectorLayerWrapper/_geometry.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ def qgsLayerToGeoDataFrame(layer, target_crs=None) -> Optional[gpd.GeoDataFrame]
4545
4646
Parameters
4747
----------
48-
layer : QgsVectorLayer
49-
The vector layer to convert
48+
layer : QgsVectorLayer or gpd.GeoDataFrame
49+
The vector layer to convert. A GeoDataFrame is returned as a copy.
5050
target_crs : QgsCoordinateReferenceSystem, optional
5151
If provided, all geometries will be transformed to this CRS.
5252
If None, the layer's source CRS is used.
@@ -58,6 +58,11 @@ def qgsLayerToGeoDataFrame(layer, target_crs=None) -> Optional[gpd.GeoDataFrame]
5858
"""
5959
if layer is None:
6060
return None
61+
if isinstance(layer, gpd.GeoDataFrame):
62+
gdf = layer.copy()
63+
if target_crs is not None and target_crs.isValid() and gdf.crs is not None:
64+
gdf = gdf.to_crs(target_crs.authid())
65+
return gdf
6166

6267
features = layer.getFeatures()
6368
fields = layer.fields()

‎tests/unit/test_derived_refresh.py‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
"""Pytest tests for the refresh of the derived data before a build.
2+
3+
`loopstructural.main.derived_refresh` imports `m2l_api` only when it
4+
calculates, so the tests put a fake `m2l_api` in `sys.modules` and run in the
5+
fast tests/unit/ job.
6+
"""
7+
8+
import sys
9+
from types import ModuleType, SimpleNamespace
10+
11+
import pandas as pd
12+
import pytest
13+
14+
from loopstructural.main import derived_data, layer_roles
15+
from loopstructural.main.derived_refresh import BASAL_CONTACT_UNIT_FIELD, DerivedRefresh
16+
17+
UNITS = ['young', 'old']
18+
19+
20+
class FakeLayer:
21+
def __init__(self, name):
22+
self._name = name
23+
24+
def name(self):
25+
return self._name
26+
27+
28+
class FakeDerived:
29+
def __init__(self):
30+
self.recorded = []
31+
32+
def record(self, name, inputs):
33+
self.recorded.append((name, inputs))
34+
35+
36+
class FakeDataManager:
37+
def __init__(self):
38+
self.layer_roles = SimpleNamespace(contacts_source=layer_roles.CONTACTS_FROM_GEOLOGY)
39+
self.derived = FakeDerived()
40+
self.old_contacts = FakeLayer('Basal contacts')
41+
self.roles = {
42+
layer_roles.GEOLOGY: FakeLayer('geology'),
43+
layer_roles.GEOLOGY_UNIT_FIELD: 'UNITNAME',
44+
layer_roles.BASAL_CONTACTS: self.old_contacts,
45+
}
46+
self.settings = {
47+
'basal_contacts_widget': {},
48+
'thickness_calculator_widget': {
49+
'calculator_type': 'InterpolatedStructure',
50+
'basal_contacts_layer': 'Basal contacts',
51+
'basal_unit_field': 'basal_unit',
52+
},
53+
}
54+
self.stratigraphy_updates = []
55+
self.applied = []
56+
57+
def get_widget_settings(self, name, default=None):
58+
return self.settings.get(name, default)
59+
60+
def get_layer_role(self, role):
61+
return self.roles.get(role)
62+
63+
def find_layer_by_name(self, name):
64+
return self.old_contacts if name == 'Basal contacts' else FakeLayer(name)
65+
66+
def basal_contacts_inputs(self):
67+
return {'geology': 'geology', 'unit_field': 'UNITNAME', 'unit_order': UNITS}
68+
69+
def thickness_inputs(self):
70+
return {'contacts': 'calculated', 'unit_order': UNITS}
71+
72+
def get_model_crs(self):
73+
return SimpleNamespace(isValid=lambda: True)
74+
75+
def get_stratigraphic_unit_names(self):
76+
return list(UNITS)
77+
78+
def get_stratigraphic_unit_colours(self):
79+
return {}
80+
81+
def update_stratigraphy(self, basal_contacts=None, unit_name_field=None):
82+
self.stratigraphy_updates.append((basal_contacts, unit_name_field))
83+
84+
def apply_calculated_thicknesses(self, values):
85+
self.applied.append(values)
86+
return values, []
87+
88+
89+
@pytest.fixture
90+
def contacts():
91+
return pd.DataFrame({BASAL_CONTACT_UNIT_FIELD: ['young'], 'X': [1.0]})
92+
93+
94+
@pytest.fixture
95+
def m2l_api(monkeypatch, contacts):
96+
"""A fake `m2l_api` that records the calls."""
97+
module = ModuleType('loopstructural.main.m2l_api')
98+
module.calls = []
99+
100+
def extract_basal_contacts(updater=None, **params):
101+
module.calls.append(('contacts', params))
102+
return {'basal_contacts': contacts}
103+
104+
def calculate_thickness(updater=None, **params):
105+
module.calls.append(('thickness', params))
106+
return {'thicknesses': pd.DataFrame({'name': ['young'], 'ThicknessMedian': [10.0]})}
107+
108+
module.extract_basal_contacts = extract_basal_contacts
109+
module.calculate_thickness = calculate_thickness
110+
monkeypatch.setitem(sys.modules, 'loopstructural.main.m2l_api', module)
111+
return module
112+
113+
114+
@pytest.fixture
115+
def dm():
116+
return FakeDataManager()
117+
118+
119+
def _refresh(dm, names):
120+
refresh = DerivedRefresh(dm, None, names)
121+
refresh._update_contacts_layer = lambda contacts: None
122+
return refresh
123+
124+
125+
BOTH = [derived_data.BASAL_CONTACTS, derived_data.THICKNESS]
126+
127+
128+
class TestRefreshOrder:
129+
def test_the_inputs_are_read_from_the_data_manager(self, dm, m2l_api):
130+
refresh = _refresh(dm, BOTH)
131+
assert refresh._contacts['inputs'] == dm.basal_contacts_inputs()
132+
assert refresh._thickness['inputs'] == dm.thickness_inputs()
133+
134+
def test_the_thickness_uses_the_new_contacts_not_the_old_layer(self, dm, m2l_api, contacts):
135+
_refresh(dm, BOTH).run()
136+
assert [name for name, _params in m2l_api.calls] == ['contacts', 'thickness']
137+
params = m2l_api.calls[1][1]
138+
assert params['basal_contacts'] is contacts
139+
assert params['basal_contacts'] is not dm.old_contacts
140+
assert params['basal_contacts_unit_name'] is None
141+
142+
def test_the_thickness_alone_uses_the_contacts_layer(self, dm, m2l_api):
143+
_refresh(dm, [derived_data.THICKNESS]).run()
144+
params = m2l_api.calls[0][1]
145+
assert params['basal_contacts'] is dm.old_contacts
146+
assert params['basal_contacts_unit_name'] == 'basal_unit'
147+
148+
149+
class TestThreads:
150+
def test_run_does_not_change_the_data_manager(self, dm, m2l_api):
151+
_refresh(dm, BOTH).run()
152+
assert dm.stratigraphy_updates == []
153+
assert dm.applied == []
154+
assert dm.derived.recorded == []
155+
156+
def test_finish_puts_the_contacts_in_the_model_and_records_the_inputs(
157+
self, dm, m2l_api, contacts
158+
):
159+
refresh = _refresh(dm, BOTH)
160+
refresh.run()
161+
refresh.finish()
162+
assert dm.stratigraphy_updates == [(contacts, BASAL_CONTACT_UNIT_FIELD)]
163+
assert dm.applied == [{'young': 10.0}]
164+
assert [name for name, _inputs in dm.derived.recorded] == BOTH

0 commit comments

Comments
 (0)