Skip to content

Commit a74e867

Browse files
authored
feat: use the native solver of LoopStructural when it is installed (#148)
* feat: use the native solver of LoopStructural when it is installed - New setting Solver: Native (the default) or Default. With Native, and when loop-interpolation-core is installed, the interpolators get solver='native'. Without the core, the plugin uses the default solver. - The native solver also solves the inequality constraints, so ADMM is not set for them when native is used. - A feature that the native solver cannot solve (for example a fold or a region mask) is built again with the default solver (cg, or ADMM for inequalities). The plugin uses the default solver for that feature from then on, and writes one log message. * build: require LoopStructural[native] 1.11 and fix the pin bump workflow - LoopStructural 1.11.0 allows loop-interpolation 0.2, which has the native solver. Require LoopStructural[native]~=1.11.0 in the three requirement files. - The pin bump workflow read the key "LoopStructural" from the release manifest, but the key of the root package is ".", so it always stopped. It also did not update loopstructural/requirements.txt (the file that qpip reads) and did not match a pin with an extra. * feat: fall back to the default solver for each coordinate, not each feature The coordinates 1 and 2 of a fault frame have orthogonal rows that the native core cannot read, so all the faults used cg. Now the plugin finds the coordinates that the core refuses (with the support check of loop-interpolation), solves only those with the default solver, and keeps native for the others. It records the coordinates, so the next build does not try native for them again. If the check finds no coordinate, the full feature uses the default solver, as before. The tests for the ADMM solver of inequality rows now turn the native core off, because with it the native solver solves the inequalities. * fix: give the native solver the iteration limit of cg, and fall back when it does not converge The native core stops after 5 000 iterations by default; cg allows 10 x the number of nodes. On a large grid the native solve stopped before it converged. loop-interpolation then keeps the old field, which had the size of the old grid, so the surfaces failed ("cannot assign 51000 values to array of shape 87232"). - Before each solve, give each native builder maxiter = 10 x its number of nodes. - After the build, a coordinate whose native solve did not converge is solved again with the default solver, and uses it from then on. The native limit is not given to the default solver.
1 parent eb2e059 commit a74e867

12 files changed

Lines changed: 605 additions & 19 deletions

File tree

‎.github/workflows/bump-loopstructural-pin.yml‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@ jobs:
2222
# plus loop_common/loop_interpolation sub-packages), so `releases/latest`
2323
# can return whichever component's release was published last, not
2424
# necessarily the LoopStructural package. Read the manifest instead —
25-
# it maps package name to version unambiguously.
26-
latest=$(curl -fsS https://raw.githubusercontent.com/Loop3D/LoopStructural/master/.release-please-manifest.json | jq -r '.["LoopStructural"] // empty')
25+
# it maps package path to version unambiguously. LoopStructural is the
26+
# root package, so its key is ".".
27+
latest=$(curl -fsS https://raw.githubusercontent.com/Loop3D/LoopStructural/master/.release-please-manifest.json | jq -r '.["."] // empty')
2728
if ! [[ "$latest" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
2829
echo "::error::Could not read a valid LoopStructural version from the release manifest (got '${latest}')."
2930
exit 1
@@ -36,11 +37,13 @@ jobs:
3637
latest="${{ steps.latest.outputs.version }}"
3738
latest_minor="${latest%.*}"
3839
changed=0
39-
for f in requirements/embedded.txt requirements/testing.txt; do
40-
current=$(grep -oP 'LoopStructural~=\K[0-9]+\.[0-9]+\.[0-9]+' "$f")
40+
# loopstructural/requirements.txt is the file that QGIS (qpip) reads.
41+
# The pin can have an extra, for example LoopStructural[native]~=1.11.0.
42+
for f in loopstructural/requirements.txt requirements/embedded.txt requirements/testing.txt; do
43+
current=$(grep -oP 'LoopStructural(\[[^]]*\])?~=\K[0-9]+\.[0-9]+\.[0-9]+' "$f")
4144
current_minor="${current%.*}"
4245
if [ "$latest_minor" != "$current_minor" ]; then
43-
sed -i "s/LoopStructural~=[0-9.]\+/LoopStructural~=${latest}/" "$f"
46+
sed -i -E "s/(LoopStructural(\[[^]]*\])?)~=[0-9.]+/\1~=${latest}/" "$f"
4447
changed=1
4548
fi
4649
done
@@ -54,8 +57,8 @@ jobs:
5457
title: "Bump LoopStructural pin to ${{ steps.latest.outputs.version }}"
5558
body: |
5659
LoopStructural released a new minor version (${{ steps.latest.outputs.version }}).
57-
This bumps the `~=` pin in `requirements/embedded.txt` and
58-
`requirements/testing.txt` accordingly.
60+
This bumps the `~=` pin in `loopstructural/requirements.txt`,
61+
`requirements/embedded.txt` and `requirements/testing.txt` accordingly.
5962
6063
Verify the `qgis-compat` CI job passes before merging.
6164
branch: bump-loopstructural-pin

‎loopstructural/gui/dlg_settings.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
from qgis.PyQt import uic
1515
from qgis.PyQt.QtCore import QUrl
1616
from qgis.PyQt.QtGui import QDesktopServices, QIcon
17+
from qgis.PyQt.QtWidgets import QComboBox, QLabel
1718

1819
# project
1920
from loopstructural.__about__ import (
@@ -23,6 +24,7 @@
2324
__uri_tracker__,
2425
__version__,
2526
)
27+
from loopstructural.main import solver_choice
2628
from loopstructural.toolbelt import PlgLogger, PlgOptionsManager
2729
from loopstructural.toolbelt.preferences import PlgSettingsStructure
2830

@@ -84,6 +86,7 @@ def __init__(self, parent):
8486
self.n_elements_auto_check_box.toggled.connect(
8587
lambda checked: self.n_elements_spin_box.setEnabled(not checked)
8688
)
89+
self._add_solver_combo()
8790

8891
# load previously saved settings
8992
self.load_settings()
@@ -100,6 +103,7 @@ def apply(self):
100103
settings.interpolator_npw = self.npw_spin_box.value()
101104
settings.interpolator_cpw = self.cpw_spin_box.value()
102105
settings.interpolator_regularisation = self.regularisation_spin_box.value()
106+
settings.interpolator_solver = self.solver_combo.currentData()
103107
settings.version = __version__
104108
debug_dir_text = (
105109
self.le_debug_directory.text() if hasattr(self, "le_debug_directory") else ""
@@ -131,9 +135,31 @@ def load_settings(self):
131135
self.regularisation_spin_box.setValue(settings.interpolator_regularisation)
132136
self.cpw_spin_box.setValue(settings.interpolator_cpw)
133137
self.npw_spin_box.setValue(settings.interpolator_npw)
138+
index = self.solver_combo.findData(settings.interpolator_solver)
139+
self.solver_combo.setCurrentIndex(max(index, 0))
134140
if hasattr(self, "le_debug_directory"):
135141
self.le_debug_directory.setText(settings.debug_directory or "")
136142

143+
def _add_solver_combo(self):
144+
"""Add the choice of the solver below the number of elements."""
145+
self.solver_combo = QComboBox(self)
146+
for choice in solver_choice.CHOICES:
147+
self.solver_combo.addItem(solver_choice.LABELS[choice], choice)
148+
if solver_choice.native_available():
149+
tooltip = (
150+
"The native solver is much faster. A feature that it cannot solve "
151+
"(for example a fold) is solved with the default solver."
152+
)
153+
else:
154+
tooltip = (
155+
"The native solver is not installed, so the default solver is used. "
156+
"Install it with: pip install loopstructural[native]"
157+
)
158+
self.solver_combo.setToolTip(tooltip)
159+
row = self.gridLayout_solver.rowCount()
160+
self.gridLayout_solver.addWidget(QLabel("Solver", self), row, 0)
161+
self.gridLayout_solver.addWidget(self.solver_combo, row, 1)
162+
137163
def reset_settings(self):
138164
"""Reset settings in the UI and persisted settings to plugin defaults."""
139165
default_settings = PlgSettingsStructure()

‎loopstructural/main/model_manager.py‎

Lines changed: 123 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
from LoopStructural import GeologicalModel
3030
from loopstructural.toolbelt.preferences import PlgOptionsManager
3131

32-
from ..main import constraints, parametric_fault
32+
from ..main import constraints, parametric_fault, solver_choice
3333
from ..main.data_types import FaultEntry, StratigraphyEntry
3434
from ..main.helpers import qgisAttributeIsNone
3535
from ..main.interpolation_size import DataSummary, suggest_nelements, summarise_data
@@ -248,6 +248,14 @@ def __init__(self, debug_manager=None):
248248
self.nelements_used: Dict[str, tuple] = {}
249249
# feature name -> DataSummary of the data of the last build
250250
self._data_summaries: Dict[str, DataSummary] = {}
251+
# features that the native solver could not solve; they use the
252+
# default solver (see `_solve_feature`)
253+
self._native_failed: Set[str] = set()
254+
# feature name -> indexes of the builders (coordinates) that use the
255+
# default solver because the native solver could not solve them
256+
self._native_fallbacks: Dict[str, Set[int]] = {}
257+
# features with constraints that need an inequality solver
258+
self._needs_inequalities: Set[str] = set()
251259

252260
@property
253261
def uses_map_data(self) -> bool:
@@ -325,6 +333,9 @@ def reset(self):
325333
self.nelements_overrides = {}
326334
self.nelements_used = {}
327335
self._data_summaries = {}
336+
self._native_failed = set()
337+
self._native_fallbacks = {}
338+
self._needs_inequalities = set()
328339
self.dem_function = lambda x, y: 0
329340
self._topology_dirty = False
330341
self._data_dirty = False
@@ -1015,12 +1026,117 @@ def interpolator_arguments(self, name, data) -> dict:
10151026
else:
10161027
nelements, automatic = self.default_nelements(name)
10171028
self.nelements_used[name] = (nelements, automatic)
1018-
return {
1029+
arguments = {
10191030
'nelements': nelements,
10201031
'npw': settings.interpolator_npw,
10211032
'cpw': settings.interpolator_cpw,
10221033
'regularisation': settings.interpolator_regularisation,
10231034
}
1035+
if self._use_native(name):
1036+
arguments['solver'] = solver_choice.NATIVE
1037+
return arguments
1038+
1039+
def _use_native(self, name) -> bool:
1040+
"""Return True if the feature `name` uses the native solver.
1041+
1042+
Not for a feature that the native solver could not solve before, see
1043+
`_solve_feature`.
1044+
"""
1045+
if name in self._native_failed:
1046+
return False
1047+
settings = PlgOptionsManager.get_plg_settings()
1048+
return solver_choice.use_native(settings.interpolator_solver)
1049+
1050+
def _inequality_solver(self, name, solver):
1051+
"""Return the solver to pass for a constraint type that needs `solver` (or None).
1052+
1053+
The native solver also solves the inequality constraints, so with it
1054+
`interpolator_arguments` gives the solver and this returns None.
1055+
"""
1056+
if not solver:
1057+
return None
1058+
self._needs_inequalities.add(name)
1059+
return None if self._use_native(name) else solver
1060+
1061+
def _solve_feature(self, feature, rebuild=True):
1062+
"""Build `feature`. A coordinate that the native solver cannot solve is
1063+
built with the default solver, and uses it from now on.
1064+
1065+
Each coordinate of a structural frame has its own builder. For a fault,
1066+
the coordinates 1 and 2 have orthogonal rows that the native core cannot
1067+
read, but the coordinate 0 can use it. If the check of loop-interpolation
1068+
finds no coordinate, the full feature uses the default solver.
1069+
1070+
A native solve that does not converge is also solved again with the
1071+
default solver: loop-interpolation then keeps the old field, which can
1072+
have the size of an old grid.
1073+
1074+
`rebuild` builds the feature again; otherwise only if it is out of date.
1075+
"""
1076+
name = feature.name
1077+
builders = solver_choice.builders(feature)
1078+
fallback = solver_choice.fallback_solver(name in self._needs_inequalities)
1079+
# the coordinates that failed in an earlier build
1080+
for index in self._native_fallbacks.get(name, ()):
1081+
if index < len(builders):
1082+
self._set_fallback(builders[index], fallback)
1083+
self._set_native_limits(builders)
1084+
build = feature.builder.update if rebuild else feature.builder.up_to_date
1085+
# one coordinate (or more) changes to the fallback at each attempt
1086+
for _attempt in range(len(builders) + 1):
1087+
try:
1088+
build()
1089+
break
1090+
except solver_choice.NATIVE_ERRORS as error:
1091+
if not solver_choice.uses_native(feature):
1092+
raise
1093+
failed = solver_choice.unsupported_builders(builders)
1094+
if not failed:
1095+
self._native_failed.add(name)
1096+
failed = list(range(len(builders)))
1097+
self._use_fallback(name, builders, failed, fallback, f"not supported ({error})")
1098+
# the coordinates that are built already stay as they are
1099+
build = feature.builder.up_to_date
1100+
else:
1101+
build()
1102+
unconverged = solver_choice.unconverged_builders(builders)
1103+
if unconverged:
1104+
self._use_fallback(name, builders, unconverged, fallback, "did not converge")
1105+
feature.builder.up_to_date()
1106+
1107+
@staticmethod
1108+
def _set_fallback(builder, fallback):
1109+
# the native iteration limit is not for the other solvers
1110+
builder.update_build_arguments({'solver': fallback, 'solver_kwargs': {}})
1111+
1112+
@staticmethod
1113+
def _set_native_limits(builders):
1114+
"""Give each native builder the iteration limit of its grid.
1115+
1116+
Only a change of the limit marks the builder out of date.
1117+
"""
1118+
for builder in builders:
1119+
if (builder.build_arguments or {}).get('solver') != solver_choice.NATIVE:
1120+
continue
1121+
limits = solver_choice.native_solver_kwargs(builder)
1122+
if limits and builder.build_arguments.get('solver_kwargs') != limits:
1123+
builder.update_build_arguments({'solver_kwargs': limits})
1124+
1125+
def _use_fallback(self, name, builders, indexes, fallback, reason):
1126+
"""Solve the builders `indexes` of the feature `name` with `fallback` from now on."""
1127+
self._native_fallbacks.setdefault(name, set()).update(indexes)
1128+
if self._debug_manager is not None:
1129+
which = (
1130+
f"the coordinates {sorted(indexes)} of '{name}'"
1131+
if len(builders) > 1
1132+
else f"'{name}'"
1133+
)
1134+
self._debug_manager.log(
1135+
f"Native solver, {which}: {reason}. Solved with '{fallback}'.",
1136+
log_level=1,
1137+
)
1138+
for index in indexes:
1139+
self._set_fallback(builders[index], fallback)
10241140

10251141
def default_nelements(self, name) -> tuple:
10261142
"""Return (number of elements, True if automatic) for the feature
@@ -1238,7 +1354,7 @@ def _extra_kwargs(self, name) -> dict:
12381354
return {}
12391355
kwargs = {}
12401356
for layer_data in spec['data'].values():
1241-
solver = constraints.solver_for(layer_data.get('type'))
1357+
solver = self._inequality_solver(name, constraints.solver_for(layer_data.get('type')))
12421358
if solver:
12431359
kwargs['solver'] = solver
12441360
return kwargs
@@ -1941,7 +2057,7 @@ def update_feature(self, feature_name: str):
19412057
raise ValueError(f"Feature '{feature_name}' not found in the model.")
19422058
# Allow UI to react to a feature update
19432059
self._emit('model_update_started')
1944-
feature.builder.update()
2060+
self._solve_feature(feature)
19452061
# Notify observers and include feature name for interested listeners
19462062
self._emit('feature_updated', feature_name)
19472063
self._emit('model_update_finished')
@@ -2003,7 +2119,7 @@ def update_all_features(
20032119
feature = self.model.get_feature_by_name(feature_name)
20042120
if feature is not None:
20052121
self._report_progress(f"Solving '{feature_name}'")
2006-
feature.builder.update()
2122+
self._solve_feature(feature)
20072123
finally:
20082124
self._progress_callback = None
20092125
else:
@@ -2020,7 +2136,7 @@ def update_all_features(
20202136
for f in self.model.features:
20212137
if not f.name.startswith('__'):
20222138
self._report_progress(f"Solving '{f.name}'")
2023-
f.builder.up_to_date()
2139+
self._solve_feature(f, rebuild=False)
20242140
finally:
20252141
self._progress_callback = None
20262142
if dbg is not None:
@@ -2300,7 +2416,7 @@ def _foliation_data(
23002416
dfs.append(constraints.add_weight(rows, df, layer_data))
23012417
else:
23022418
dfs.append(constraints.constraint_rows(df, layer_data, name))
2303-
solver = constraints.solver_for(layer_type)
2419+
solver = self._inequality_solver(name, constraints.solver_for(layer_type))
23042420
if solver:
23052421
kwargs['solver'] = solver
23062422
except Exception as e:

0 commit comments

Comments
 (0)