mirror of
https://gitlab.com/pamhyr/pamhyr2.git
synced 2026-10-30 03:20:41 +01:00
Compare commits
168
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9e5153d63d | ||
|
|
797de09683 | ||
|
|
ef10588880 | ||
|
|
c2a8e17bf3 | ||
|
|
03979a8bea | ||
|
|
a4eee962f7 | ||
|
|
d8d1b4cd1f | ||
|
|
cdeca8a2e8 | ||
|
|
4d9c4cb5d0 | ||
|
|
618477b384 | ||
|
|
70a26d0036 | ||
|
|
c3afc4dd58 | ||
|
|
ef72e41b14 | ||
|
|
be7b5b892a | ||
|
|
5f64362f65 | ||
|
|
357b39758c | ||
|
|
a2f215984b | ||
|
|
b1cf45497b | ||
|
|
ee416e1059 | ||
|
|
3fee3b0bb3 | ||
|
|
a06c2eaa7e | ||
|
|
4e767d86d6 | ||
|
|
f43d108871 | ||
|
|
33a2107876 | ||
|
|
7103fdcb46 | ||
|
|
ace85ccb40 | ||
|
|
ec81a998cb | ||
|
|
a18accb404 | ||
|
|
657f54ff91 | ||
|
|
bf2d3ae7a9 | ||
|
|
656b337499 | ||
|
|
ed2ed0ac2a | ||
|
|
d2f03415c8 | ||
|
|
69371b5949 | ||
|
|
bbd8f7f832 | ||
|
|
ab95f06700 | ||
|
|
2a699f46ca | ||
|
|
17792ec995 | ||
|
|
33ad91d1a6 | ||
|
|
7d2ef35128 | ||
|
|
40b48a2080 | ||
|
|
7eb39e5896 | ||
|
|
28cc88b4b8 | ||
|
|
c9925cd03c | ||
|
|
40f9465929 | ||
|
|
359805b713 | ||
|
|
31565b9170 | ||
|
|
9c2a0541df | ||
|
|
38d7d587fa | ||
|
|
f19ab9455a | ||
|
|
cadffe40d6 | ||
|
|
5a195e2822 | ||
|
|
63592b91a9 | ||
|
|
88345c58a7 | ||
|
|
7124b2b61c | ||
|
|
f93e6a7d7c | ||
|
|
5d46401b85 | ||
|
|
97867080d9 | ||
|
|
93a4b44143 | ||
|
|
5e3e5628d2 | ||
|
|
bddaad0193 | ||
|
|
4a6349cd9c | ||
|
|
e9c998fec8 | ||
|
|
290b8918fc | ||
|
|
0e6de5d0f0 | ||
|
|
98d30a326e | ||
|
|
5f64499984 | ||
|
|
6e32c740ae | ||
|
|
e0721715d0 | ||
|
|
10edc00973 | ||
|
|
f8829ce82c | ||
|
|
ac91b712a3 | ||
|
|
4bccbbac33 | ||
|
|
5c8b7290ba | ||
|
|
288713ce5b | ||
|
|
ff3b5a320c | ||
|
|
49eb28056e | ||
|
|
ddb682dff6 | ||
|
|
a2e0f6a517 | ||
|
|
7356e5dd30 | ||
|
|
933c6c1952 | ||
|
|
d8fd4488e2 | ||
|
|
89c6e8bb29 | ||
|
|
d4c596a6fe | ||
|
|
fef2a2e979 | ||
|
|
f001dffb68 | ||
|
|
2818644b7f | ||
|
|
86d93fd702 | ||
|
|
593cc0c91b | ||
|
|
d15fa684b7 | ||
|
|
9879094661 | ||
|
|
5ce5478bf4 | ||
|
|
5fb36e7fbe | ||
|
|
0dbea26a2e | ||
|
|
b0e0dc75f1 | ||
|
|
318f6a4668 | ||
|
|
fdb5cd23e7 | ||
|
|
e064c1aee5 | ||
|
|
32a316589b | ||
|
|
d4bc9bdf75 | ||
|
|
3325ba935b | ||
|
|
345f24996f | ||
|
|
e0bc481ae2 | ||
|
|
4040b2456c | ||
|
|
8e77d31a5a | ||
|
|
081e6e7322 | ||
|
|
6e029beafc | ||
|
|
f5a7cd5984 | ||
|
|
d4d5e26a2b | ||
|
|
92990948ad | ||
|
|
a0d8b9ea43 | ||
|
|
d97620ad56 | ||
|
|
bf6d40f398 | ||
|
|
6d4dc3a22b | ||
|
|
74d23386a7 | ||
|
|
03299db99a | ||
|
|
a0886d900e | ||
|
|
9f46bcd853 | ||
|
|
97fe038d9b | ||
|
|
bcc9dd1a0d | ||
|
|
fc40552d68 | ||
|
|
f41050fe5c | ||
|
|
97f487c0af | ||
|
|
499e16975f | ||
|
|
75f3c07cd9 | ||
|
|
71914fdf57 | ||
|
|
58e3da8942 | ||
|
|
2d7409debb | ||
|
|
b7c3793a66 | ||
|
|
92fb653676 | ||
|
|
2498466a51 | ||
|
|
ef36eba039 | ||
|
|
c40e28ed0f | ||
|
|
b21846a513 | ||
|
|
3532f75c2b | ||
|
|
6c59919972 | ||
|
|
77d56b8bec | ||
|
|
7ef7bc13dc | ||
|
|
a1d85274b9 | ||
|
|
e7b9bc92a2 | ||
|
|
7d8e414fe2 | ||
|
|
476bcc9c55 | ||
|
|
ae006f52f4 | ||
|
|
3583a93ae0 | ||
|
|
212a00a43c | ||
|
|
e5dbba362a | ||
|
|
bdc09addfa | ||
|
|
51b3987a4a | ||
|
|
e7290fa81b | ||
|
|
b5432498c6 | ||
|
|
807592eab2 | ||
|
|
394c0779fc | ||
|
|
5b3f777100 | ||
|
|
8b36905842 | ||
|
|
b203e8e062 | ||
|
|
4d4df1bde2 | ||
|
|
876780a349 | ||
|
|
3b83377f3c | ||
|
|
e64c45b621 | ||
|
|
70dae9ab1b | ||
|
|
0bb3c5bc65 | ||
|
|
54f5c7c548 | ||
|
|
56217186ff | ||
|
|
82fb2bcc48 | ||
|
|
6dc42b637a | ||
|
|
e6d12713e3 | ||
|
|
9456cf32fc | ||
|
|
9b1fb4e7d2 |
No files matched your search
@@ -44,6 +44,7 @@ __old__
|
||||
mage8/
|
||||
adists/
|
||||
rubarbe/
|
||||
rubar/
|
||||
|
||||
linux/
|
||||
windows/
|
||||
|
||||
@@ -1069,6 +1069,12 @@ gitlab-ci.
|
||||
sudo python3 -m pip install pyinstaller
|
||||
#+end_src
|
||||
|
||||
In addition, you must install Glab[fn:glab] to allow the runner to
|
||||
proceed with the publication.
|
||||
|
||||
[fn:glab] The Gitlab cli releases page:
|
||||
https://gitlab.com/gitlab-org/cli/-/releases
|
||||
|
||||
*** Windows (Wine) {{{windows}}}
|
||||
|
||||
The ci-runner environment for Wine need at least wine version 8, let
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 30 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 127 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
@@ -4,7 +4,7 @@ PyQt5-sip==12.18.0
|
||||
PyQtWebEngine==5.15.6
|
||||
QScintilla>=2.14.1
|
||||
pyqtgraph>=0.12.1
|
||||
matplotlib==3.8.3
|
||||
matplotlib==3.10.8
|
||||
numpy>=1.24.2
|
||||
colorama>=0.4.3
|
||||
pyinstaller>=5.11.0
|
||||
@@ -14,3 +14,4 @@ platformdirs>=4.2.0
|
||||
pyshp>=2.3.1
|
||||
rasterio==1.3.11
|
||||
#fortranformat==2.0.3
|
||||
psutil>=7.2.2
|
||||
+1
-1
@@ -20,4 +20,4 @@
|
||||
"python-pyqtgraph" "python-qscintilla"
|
||||
"python-numpy@1" "python-shapely" "python-pyshp"
|
||||
"python-matplotlib" "python-colorama"
|
||||
"python-rasterio"))
|
||||
"python-rasterio" "python-psutil"))
|
||||
+2
-2
@@ -4,7 +4,7 @@ PyQt5-sip==12.18.0
|
||||
#PyQtWebEngine==5.15.6
|
||||
QScintilla>=2.14.1
|
||||
pyqtgraph>=0.12.1
|
||||
matplotlib==3.8.3
|
||||
matplotlib==3.10.8
|
||||
numpy>=1.24.2
|
||||
colorama>=0.4.3
|
||||
pyinstaller>=5.11.0
|
||||
@@ -14,4 +14,4 @@ platformdirs>=4.2.0
|
||||
pyshp>=2.3.1
|
||||
rasterio==1.3.11
|
||||
#fortranformat==2.0.3
|
||||
|
||||
psutil>=7.2.2
|
||||
@@ -254,3 +254,46 @@ for each reach"
|
||||
return False
|
||||
|
||||
return ok
|
||||
|
||||
|
||||
class MageLateralSolidChecker(AbstractModelChecker):
|
||||
"""Mage has no solid lateral contribution (notice: only upstream
|
||||
solid discharges, QSO): the solid ones are not exported (LAT holds
|
||||
liquid discharges only). Non blocking warning"""
|
||||
|
||||
def __init__(self, version="mage8"):
|
||||
super(MageLateralSolidChecker, self).__init__()
|
||||
|
||||
self._name = _translate(
|
||||
"Checker", "Mage solid lateral contributions checker")
|
||||
self._description = _translate(
|
||||
"Checker",
|
||||
"Check if the study has solid lateral contributions, which "
|
||||
"Mage does not take into account"
|
||||
)
|
||||
self._solver = version
|
||||
self._modules = Modules.LATERAL_CONTRIBUTION
|
||||
|
||||
def run(self, study):
|
||||
if not self.basic_check(study):
|
||||
return False
|
||||
|
||||
edges = study.river.enable_edges()
|
||||
names = [
|
||||
lc.name
|
||||
for lc in study.river.lateral_contribution.get_tab("solid")
|
||||
if not lc.is_deleted() and lc.reach in edges and len(lc) > 0
|
||||
]
|
||||
|
||||
if len(names) == 0:
|
||||
self._status = STATUS.OK
|
||||
self._summary = "ok"
|
||||
return True
|
||||
|
||||
self._status = STATUS.WARNING
|
||||
self._summary = _translate(
|
||||
"Checker",
|
||||
"Solid lateral contributions not taken into account by Mage: "
|
||||
"{names}"
|
||||
).format(names=", ".join(names))
|
||||
return False
|
||||
@@ -0,0 +1,255 @@
|
||||
# RubarBE.py -- Pamhyr RubarBE checkers
|
||||
# Copyright (C) 2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""RubarBE checkers. Each one runs a step of the checks of the RubarBE
|
||||
export (Solver/RubarBE.py), without writing any file, so that they
|
||||
always give the messages of the export: an error where the export would
|
||||
be cancelled, a warning for the data it ignores (empty boundary
|
||||
conditions, lateral contributions not read, solid lateral contributions
|
||||
without liquid one, structures without RubarBE equivalent...)."""
|
||||
|
||||
import logging
|
||||
|
||||
from PyQt5.QtCore import QCoreApplication
|
||||
|
||||
from Modules import Modules
|
||||
from tools import logger_exception
|
||||
|
||||
from Checker.Checker import AbstractModelChecker, STATUS
|
||||
|
||||
_translate = QCoreApplication.translate
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class RubarBEChecker(AbstractModelChecker):
|
||||
"""Base class: _check(solver, study, context, warnings) runs the
|
||||
export step, raising RubarExportError (error) or appending to
|
||||
warnings (warning). Steps that need the reach are not run when the
|
||||
study has not a single valid reach: RubarBEReachChecker reports it"""
|
||||
|
||||
_needs_reach = True
|
||||
|
||||
def __init__(self, name, description, modules, version="rubarbe"):
|
||||
super(RubarBEChecker, self).__init__()
|
||||
|
||||
self._name = name
|
||||
self._description = description
|
||||
self._solver = version
|
||||
self._modules = modules
|
||||
|
||||
@staticmethod
|
||||
def _context(solver, study):
|
||||
# Read the parameters without creating them (get_params would
|
||||
# add default ones to the study)
|
||||
river = study.river
|
||||
if solver.type in river._parameters:
|
||||
values = solver._parameter_values(study)
|
||||
else:
|
||||
values = {k: str(v).strip()
|
||||
for k, v in solver.default_parameters()}
|
||||
|
||||
return {
|
||||
"values": values,
|
||||
"trased": values.get("rubarbe_trased", "n").lower()
|
||||
in ("y", "o"),
|
||||
}
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
raise NotImplementedError
|
||||
|
||||
def run(self, study):
|
||||
from Solver.RubarBE import RubarBE, RubarExportError
|
||||
|
||||
if not self.basic_check(study):
|
||||
return False
|
||||
|
||||
solver = RubarBE("checker")
|
||||
warnings = []
|
||||
try:
|
||||
context = self._context(solver, study)
|
||||
if self._needs_reach:
|
||||
try:
|
||||
edge, profiles = solver._single_reach(study.river)
|
||||
except RubarExportError:
|
||||
self._status = STATUS.OK
|
||||
self._summary = "ok"
|
||||
return True
|
||||
context["hydraulics"] = {
|
||||
"edge": edge,
|
||||
"profiles": profiles,
|
||||
"tinit": solver._seconds(
|
||||
context["values"].get("rubarbe_tinit", "0")),
|
||||
"warnings": warnings,
|
||||
}
|
||||
self._check(solver, study, context, warnings)
|
||||
except (RubarExportError, ValueError) as error:
|
||||
self._status = STATUS.ERROR
|
||||
self._summary = str(error)
|
||||
return False
|
||||
except Exception as error:
|
||||
# Never stop the checker thread
|
||||
logger_exception(error)
|
||||
self._status = STATUS.UNKNOWN
|
||||
self._summary = str(error)
|
||||
return False
|
||||
|
||||
if warnings:
|
||||
self._status = STATUS.WARNING
|
||||
self._summary = " | ".join(warnings)
|
||||
return False
|
||||
|
||||
self._status = STATUS.OK
|
||||
self._summary = "ok"
|
||||
return True
|
||||
|
||||
|
||||
class RubarBEReachChecker(RubarBEChecker):
|
||||
_needs_reach = False
|
||||
|
||||
def __init__(self, version="rubarbe"):
|
||||
super(RubarBEReachChecker, self).__init__(
|
||||
_translate("Checker", "RubarBE reach checker"),
|
||||
_translate(
|
||||
"Checker",
|
||||
"Check that the study has a single enabled reach, with at "
|
||||
"least two profiles of increasing rk"
|
||||
),
|
||||
Modules.GEOMETRY, version,
|
||||
)
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
solver._single_reach(study.river)
|
||||
|
||||
|
||||
class RubarBEGeometryChecker(RubarBEChecker):
|
||||
def __init__(self, version="rubarbe"):
|
||||
super(RubarBEGeometryChecker, self).__init__(
|
||||
_translate("Checker", "RubarBE geometry and sediment checker"),
|
||||
_translate(
|
||||
"Checker",
|
||||
"Check the main channel and active bed limits of the "
|
||||
"profiles and, with sediment transport, their sediment "
|
||||
"layers"
|
||||
),
|
||||
# Rerun on changes of the geometry, which impact the sediment
|
||||
# layers
|
||||
Modules.SEDIMENT_LAYER, version,
|
||||
)
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
solver._geometry_data(context["hydraulics"]["edge"],
|
||||
context["trased"])
|
||||
|
||||
|
||||
class RubarBEBoundaryChecker(RubarBEChecker):
|
||||
def __init__(self, version="rubarbe"):
|
||||
super(RubarBEBoundaryChecker, self).__init__(
|
||||
_translate("Checker", "RubarBE boundary conditions checker"),
|
||||
_translate(
|
||||
"Checker",
|
||||
"Check the liquid and solid boundary conditions used by "
|
||||
"the boundary settings of the solver parameters"
|
||||
),
|
||||
Modules.BOUNDARY_CONDITION, version,
|
||||
)
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
values = context["values"]
|
||||
edge = context["hydraulics"]["edge"]
|
||||
solver._check_regime(values)
|
||||
solver._check_boundaries(study.river, edge, values, warnings)
|
||||
solver._solid_boundary(study.river, edge, values,
|
||||
context["trased"], warnings)
|
||||
|
||||
|
||||
class RubarBEFrictionChecker(RubarBEChecker):
|
||||
def __init__(self, version="rubarbe"):
|
||||
super(RubarBEFrictionChecker, self).__init__(
|
||||
_translate("Checker", "RubarBE friction checker"),
|
||||
_translate("Checker", "Check that the reach has frictions"),
|
||||
Modules.FRICTION, version,
|
||||
)
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
solver._interpolated_frictions(context["hydraulics"]["edge"])
|
||||
|
||||
|
||||
class RubarBEInitialConditionsChecker(RubarBEChecker):
|
||||
def __init__(self, version="rubarbe"):
|
||||
super(RubarBEInitialConditionsChecker, self).__init__(
|
||||
_translate("Checker", "RubarBE initial conditions checker"),
|
||||
_translate(
|
||||
"Checker", "Check the initial conditions of the reach"),
|
||||
Modules.INITIAL_CONDITION, version,
|
||||
)
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
solver._initial_conditions(study.river,
|
||||
context["hydraulics"]["edge"])
|
||||
|
||||
|
||||
class RubarBELateralChecker(RubarBEChecker):
|
||||
def __init__(self, version="rubarbe"):
|
||||
super(RubarBELateralChecker, self).__init__(
|
||||
_translate("Checker", "RubarBE lateral contributions checker"),
|
||||
_translate(
|
||||
"Checker",
|
||||
"Check the lateral contributions: read only with lateral "
|
||||
"overflows, solid ones attached to the liquid contribution "
|
||||
"of the same sections"
|
||||
),
|
||||
Modules.LATERAL_CONTRIBUTION, version,
|
||||
)
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
solver._lateral_data(study.river, context["hydraulics"],
|
||||
context["values"], context["trased"], warnings)
|
||||
|
||||
|
||||
class RubarBEStructureChecker(RubarBEChecker):
|
||||
def __init__(self, version="rubarbe"):
|
||||
super(RubarBEStructureChecker, self).__init__(
|
||||
_translate("Checker", "RubarBE hydraulic structures checker"),
|
||||
_translate(
|
||||
"Checker",
|
||||
"Check the hydraulic structures: weirs and rectangular and "
|
||||
"circular orifices only"
|
||||
),
|
||||
Modules.HYDRAULIC_STRUCTURES, version,
|
||||
)
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
solver._structure_data(study.river, context["hydraulics"], warnings)
|
||||
|
||||
|
||||
class RubarBESavesChecker(RubarBEChecker):
|
||||
def __init__(self, version="rubarbe"):
|
||||
super(RubarBESavesChecker, self).__init__(
|
||||
_translate("Checker", "RubarBE saves checker"),
|
||||
_translate(
|
||||
"Checker",
|
||||
"Check the save abscissas (ABSHYD) and times (TNPROF) of "
|
||||
"the solver parameters"
|
||||
),
|
||||
# The solver parameters have no module: rerun on any change
|
||||
Modules.NONE, version,
|
||||
)
|
||||
|
||||
def _check(self, solver, study, context, warnings):
|
||||
solver._save_data(context["values"], context["hydraulics"])
|
||||
+97
-61
@@ -172,8 +172,8 @@ class InternalMeshing(AMeshingTool):
|
||||
|
||||
ltot1 = 0.0
|
||||
ltot2 = 0.0
|
||||
alpha = []
|
||||
beta = []
|
||||
alpha = [0.0]
|
||||
beta = [0.0]
|
||||
# remove names
|
||||
sect2.points[start2].name = ''
|
||||
sect2.points[end2].name = ''
|
||||
@@ -196,67 +196,38 @@ class InternalMeshing(AMeshingTool):
|
||||
else: # regular case
|
||||
alpha = list(map(lambda x: x/ltot1, alpha)) # target ratios
|
||||
beta = list(map(lambda x: x/ltot2, beta)) # current ratios
|
||||
for i in range(len1 - len2):
|
||||
beta.append(1.0)
|
||||
beta.append(0.0) # beta[-1]
|
||||
# loop on the points to insert
|
||||
for k in range(len1-len2):
|
||||
trouve = False
|
||||
for j0 in range(len2):
|
||||
if trouve:
|
||||
break
|
||||
undeplus = True
|
||||
for j1 in range(j0, len2):
|
||||
if undeplus:
|
||||
if beta[j1] <= alpha[j1]:
|
||||
undeplus = False
|
||||
break
|
||||
if undeplus:
|
||||
if j0 == len2:
|
||||
trouve = True
|
||||
else:
|
||||
j1 = j0+1
|
||||
if beta[j0]-alpha[j0] > alpha[j1]-beta[j0]:
|
||||
trouve = True
|
||||
match = self._match_indices(alpha, beta)
|
||||
|
||||
if trouve:
|
||||
len2 += 1
|
||||
for i in reversed(range(j0, len2)):
|
||||
beta[i+1] = beta[i]
|
||||
if (beta[j0] == beta[j0-1]):
|
||||
# rien
|
||||
pass
|
||||
else:
|
||||
ratio = (alpha[j0] - beta[j0-1]) \
|
||||
/ (beta[j0] - beta[j0-1])
|
||||
if ratio < 0.0:
|
||||
logger.warning(f"ratio négatif {ratio}")
|
||||
# on double le point a gauche
|
||||
p = sect2.point(start2+j0-1).copy()
|
||||
sect2.insert_point(start2+j0-1, p)
|
||||
sect2.point(start2+j0-1).name = ''
|
||||
beta[j0] = beta[j0-1]
|
||||
else:
|
||||
p = sect2.point(start2+j0).copy()
|
||||
sect2.insert_point(start2+j0, p)
|
||||
sect2.point(start2+j0+1).name = ''
|
||||
sect2.point(start2+j0+1).x = \
|
||||
(1.0-ratio) * sect2.point(start2+j0).x + \
|
||||
ratio * sect2.point(start2+j0+2).x
|
||||
sect2.point(start2+j0+1).y = \
|
||||
(1.0-ratio) * sect2.point(start2+j0).y + \
|
||||
ratio * sect2.point(start2+j0+2).y
|
||||
sect2.point(start2+j0+1).z = \
|
||||
(1.0-ratio) * sect2.point(start2+j0).z + \
|
||||
ratio * sect2.point(start2+j0+2).z
|
||||
beta[j0] = (1.-ratio)*beta[j0-1] \
|
||||
+ ratio*beta[j0+1]
|
||||
insertions_per_segment = [] # liste de (index, [points])
|
||||
for j in range(len2):
|
||||
i_start = match[j]
|
||||
i_end = match[j + 1]
|
||||
q_start = sect2.point(start2 + j)
|
||||
q_end = sect2.point(start2 + j + 1)
|
||||
|
||||
new_points = []
|
||||
if i_end - i_start > 1:
|
||||
u_start, u_end = alpha[i_start], alpha[i_end]
|
||||
span = u_end - u_start
|
||||
for k in range(i_start + 1, i_end):
|
||||
ratio = (alpha[k] - u_start) / span # dans [0,1]
|
||||
p = q_start.copy()
|
||||
p.name = ''
|
||||
p.x = (1.0-ratio) * q_start.x + ratio * q_end.x
|
||||
p.y = (1.0-ratio) * q_start.y + ratio * q_end.y
|
||||
p.z = (1.0-ratio) * q_start.z + ratio * q_end.z
|
||||
new_points.append(p)
|
||||
|
||||
# à insérer après l'indice j
|
||||
insertions_per_segment.append((j, new_points))
|
||||
|
||||
# Insertion en ordre décroissant de j
|
||||
# pour ne pas perturber les indices
|
||||
for j, new_points in reversed(insertions_per_segment):
|
||||
for offset, p in enumerate(new_points):
|
||||
sect2.insert_point(start2 + j + 1 + offset, p)
|
||||
len2 += 1
|
||||
|
||||
if len1 > len2:
|
||||
for i in range(len1 - len2):
|
||||
p = sect2.point(start2+len2).copy()
|
||||
sect2.insert_point(start2+len2, p)
|
||||
sect2.point(start2+len2).name = ''
|
||||
if tag1 != "un":
|
||||
sect2.point(start2).name = tag1
|
||||
if tag2 != "np":
|
||||
@@ -264,6 +235,71 @@ class InternalMeshing(AMeshingTool):
|
||||
|
||||
sect2.modified()
|
||||
|
||||
def _match_indices(self, u_ref, v_target):
|
||||
# appariement optimal (ordre croissant) par programmation dynamique
|
||||
"""
|
||||
Trouve, pour chaque v_target[j], un indice i_j dans u_ref tel que
|
||||
i_0 < i_1 < ... < i_{m-1} et
|
||||
Sum |u_ref[i_j] - v_target[j]| soit minimal.
|
||||
|
||||
Retourne la liste des indices i_j (longueur m),
|
||||
avec i_0 = 0 et i_{m-1} = n-1 imposés
|
||||
(les extrémités se correspondent forcément).
|
||||
|
||||
"""
|
||||
n = len(u_ref)
|
||||
m = len(v_target)
|
||||
|
||||
# Les extrémités sont fixées.
|
||||
fixed_first, fixed_last = 0, n - 1
|
||||
|
||||
# DP sur les indices disponibles entre fixed_first+1 et fixed_last-1
|
||||
# dp[j][i] = coût minimal pour apparier v_target[1..j] aux indices
|
||||
# se terminant à l'indice i (i croissant strict), j de 1 à m-2.
|
||||
if m == 2:
|
||||
return [fixed_first, fixed_last]
|
||||
|
||||
# indices internes possibles
|
||||
candidates = list(range(fixed_first + 1, fixed_last))
|
||||
inner_targets = v_target[1:-1] # cibles internes (j = 1..m-2)
|
||||
|
||||
INF = float("inf")
|
||||
# dp[j] : dict indice_candidat -> (coût_min, provenance)
|
||||
dp = [{} for _ in range(len(inner_targets))]
|
||||
|
||||
for j, vt in enumerate(inner_targets):
|
||||
for idx_pos, i in enumerate(candidates):
|
||||
cost_here = abs(u_ref[i] - vt)
|
||||
if j == 0:
|
||||
# doit être > fixed_first
|
||||
dp[j][i] = (cost_here, fixed_first)
|
||||
else:
|
||||
best = (INF, None)
|
||||
for i_prev in candidates[:idx_pos]:
|
||||
if i_prev in dp[j - 1]:
|
||||
c = dp[j - 1][i_prev][0] + cost_here
|
||||
if c < best[0]:
|
||||
best = (c, i_prev)
|
||||
if best[1] is not None:
|
||||
dp[j][i] = best
|
||||
|
||||
# Reconstruction : on part du dernier niveau, on choisit le
|
||||
# meilleur indice tel que la suite jusqu'à fixed_last
|
||||
# reste croissante et valide.
|
||||
last_level = dp[-1]
|
||||
valid = {i: c for i, c in last_level.items() if i < fixed_last}
|
||||
if not valid:
|
||||
raise RuntimeError("Alignement impossible avec ces données.")
|
||||
best_i = min(valid, key=lambda i: valid[i][0])
|
||||
|
||||
chain = [best_i]
|
||||
for j in range(len(inner_targets) - 1, 0, -1):
|
||||
prev_i = dp[j][chain[-1]][1]
|
||||
chain.append(prev_i)
|
||||
chain.reverse()
|
||||
|
||||
return [fixed_first] + chain + [fixed_last]
|
||||
|
||||
def update_rk(self, reach, begin_rk, end_rk,
|
||||
step: float = 50,
|
||||
limites=[-1, -1],
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
# Distribution.py -- Pamhyr
|
||||
# Copyright (C) 2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import struct
|
||||
import logging
|
||||
import itertools
|
||||
import numpy as np
|
||||
|
||||
from tools import logger_exception
|
||||
|
||||
from Model.Except import NotImplementedMethodeError
|
||||
from Model.Tools.PamhyrDB import SQLSubModel
|
||||
from Model.Scenario import Scenario
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class Distribution(SQLSubModel):
|
||||
_sub_classes = []
|
||||
|
||||
def __init__(self, id: int = -1,
|
||||
name: str = "", script: str = "",
|
||||
status=None):
|
||||
super(Distribution, self).__init__(
|
||||
id=id, status=status,
|
||||
owner_scenario=0
|
||||
)
|
||||
|
||||
self._name = name
|
||||
self._type = "generic"
|
||||
self._script = script
|
||||
self._labels = []
|
||||
self._default_values = []
|
||||
self._params_checkers = []
|
||||
self._params_tips = []
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name
|
||||
|
||||
@property
|
||||
def labels(self):
|
||||
return self._labels
|
||||
|
||||
@property
|
||||
def default_values(self):
|
||||
return self._default_values
|
||||
|
||||
@classmethod
|
||||
def _db_create(cls, execute, ext=""):
|
||||
execute(f"""
|
||||
CREATE TABLE ensemble_distribution{ext} (
|
||||
{cls.create_db_add_pamhyr_id()},
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
name TEXT NOT NULL,
|
||||
script TEXT NOT NULL,
|
||||
PRIMARY KEY(pamhyr_id)
|
||||
)
|
||||
""")
|
||||
|
||||
if ext == "_tmp":
|
||||
return True
|
||||
|
||||
return cls._create_submodel(execute)
|
||||
|
||||
@classmethod
|
||||
def _db_update(cls, execute, version, data=None):
|
||||
major, minor, release = version.strip().split(".")
|
||||
if major == "0" and int(minor) < 2:
|
||||
cls._db_create(execute)
|
||||
elif major == "0" and int(minor) == 2:
|
||||
if int(release) < 8:
|
||||
cls._db_create(execute)
|
||||
|
||||
return cls._update_submodel(execute, version, data)
|
||||
|
||||
@classmethod
|
||||
def _db_load(cls, execute, data=None):
|
||||
new = []
|
||||
scenario = data["scenario"]
|
||||
loaded = data['loaded_pid']
|
||||
|
||||
table = execute(
|
||||
"SELECT pamhyr_id, deleted, name, script " +
|
||||
"FROM ensemble_distribution " +
|
||||
f"WHERE pamhyr_id NOT IN ({', '.join(map(str, loaded))})"
|
||||
)
|
||||
|
||||
for row in table:
|
||||
it = iter(row)
|
||||
|
||||
id = next(it)
|
||||
deleted = (next(it) == 1)
|
||||
name = next(it)
|
||||
script = next(it)
|
||||
|
||||
new_distribution = cls(
|
||||
id, name=name, script=script,
|
||||
status=data["status"]
|
||||
)
|
||||
if deleted:
|
||||
new_distribution.set_as_deleted()
|
||||
|
||||
loaded.add(id)
|
||||
new.append(new_distribution)
|
||||
|
||||
return new
|
||||
|
||||
def _db_save(self, execute, data=None):
|
||||
# Only save custom distribution
|
||||
if self._type != "custom":
|
||||
return True
|
||||
|
||||
if not self.must_be_saved():
|
||||
return True
|
||||
|
||||
execute(
|
||||
"INSERT INTO " +
|
||||
"ensemble_distribution(pamhyr_id, deleted, " +
|
||||
" name, script) " +
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
self.pamhyr_id, self.is_deleted(),
|
||||
self._name, self._script
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def _data_traversal(self,
|
||||
predicate=lambda obj, data: True,
|
||||
modifier=lambda obj, data: None,
|
||||
data={}):
|
||||
if predicate(self, data):
|
||||
modifier(self, data)
|
||||
|
||||
def is_valid_parameters(self, parameters):
|
||||
valid = True
|
||||
tips = []
|
||||
|
||||
for i, checker in enumerate(self._params_checkers):
|
||||
ok = checker(parameters)
|
||||
if not ok:
|
||||
tips.append(self._params_tips[i])
|
||||
valid = False
|
||||
|
||||
return (valid, tips)
|
||||
|
||||
def check_params(self, params):
|
||||
return True
|
||||
|
||||
def random(self, r):
|
||||
raise NotImplementedMethodeError(cls, cls._load)
|
||||
|
||||
|
||||
###############################
|
||||
# DISTRIBUTION IMPLEMENTATION #
|
||||
###############################
|
||||
|
||||
class Uniform(Distribution):
|
||||
_sub_classes = []
|
||||
|
||||
def __init__(self, id: int = -1,
|
||||
name: str = "uniform", script: str = "",
|
||||
status=None):
|
||||
super(Uniform, self).__init__(
|
||||
id=id, status=status,
|
||||
name=name, script=script
|
||||
)
|
||||
|
||||
self._labels = ["low", "high"]
|
||||
self._default_values = [20.0, 40.0]
|
||||
self._params_checkers = [self.check_params, self.check_params]
|
||||
self._params_tips = ["uniform_low_tips", "uniform_high_tips"]
|
||||
|
||||
def check_params(self, params):
|
||||
return (params[0] < params[1])
|
||||
|
||||
def random(self, params, nb):
|
||||
lst = params.copy()
|
||||
lst.append(nb)
|
||||
|
||||
return np.random.uniform(*lst)
|
||||
|
||||
|
||||
class Normal(Distribution):
|
||||
_sub_classes = []
|
||||
|
||||
def __init__(self, id: int = -1,
|
||||
name: str = "normal", script: str = "",
|
||||
status=None):
|
||||
super(Normal, self).__init__(
|
||||
id=id, status=status,
|
||||
name=name, script=script
|
||||
)
|
||||
|
||||
self._labels = ["loc", "scale"]
|
||||
self._default_values = [30.0, 5.0]
|
||||
self._params_checkers = [self.check_params, self.check_scale]
|
||||
self._params_tips = ["normal_loc_tips", "normal_scale_tips"]
|
||||
|
||||
def check_scale(self, params):
|
||||
return 0 <= params[1]
|
||||
|
||||
def random(self, params, nb):
|
||||
lst = params.copy()
|
||||
lst.append(nb)
|
||||
|
||||
return np.random.normal(*lst)
|
||||
|
||||
|
||||
class Binomial(Distribution):
|
||||
_sub_classes = []
|
||||
|
||||
def __init__(self, id: int = -1,
|
||||
name: str = "binomial", script: str = "",
|
||||
status=None):
|
||||
super(Binomial, self).__init__(
|
||||
id=id, status=status,
|
||||
name=name, script=script
|
||||
)
|
||||
|
||||
self._labels = ["binomial_n", "binomial_p"]
|
||||
self._default_values = [100.0, 0.3]
|
||||
self._params_checkers = [self.check_n, self.check_p]
|
||||
self._params_tips = ["binomial_n_tips", "binomial_p_tips"]
|
||||
|
||||
def check_n(self, params):
|
||||
n = params[0]
|
||||
return (0 <= n) and (n == round(n))
|
||||
|
||||
def check_p(self, params):
|
||||
p = params[1]
|
||||
return 0 <= p <= 1
|
||||
|
||||
def random(self, params, nb):
|
||||
lst = params.copy()
|
||||
lst.append(nb)
|
||||
|
||||
return np.random.binomial(*lst)
|
||||
|
||||
|
||||
class Poisson(Distribution):
|
||||
_sub_classes = []
|
||||
|
||||
def __init__(self, id: int = -1,
|
||||
name: str = "poisson", script: str = "",
|
||||
status=None):
|
||||
super(Poisson, self).__init__(
|
||||
id=id, status=status,
|
||||
name=name, script=script
|
||||
)
|
||||
|
||||
self._labels = ["poisson_lam"]
|
||||
self._default_values = [5.0]
|
||||
self._params_checkers = [self.check_lam]
|
||||
self._params_tips = ["poisson_lam_tips"]
|
||||
|
||||
def check_lam(self, params):
|
||||
lam = params[0]
|
||||
return 0 <= lam
|
||||
|
||||
def random(self, params, nb):
|
||||
lst = params.copy()
|
||||
lst.append(nb)
|
||||
|
||||
return np.random.poisson(*lst)
|
||||
|
||||
|
||||
class Custom(Distribution):
|
||||
_sub_classes = []
|
||||
|
||||
def __init__(self, id: int = -1,
|
||||
name: str = "", script: str = "",
|
||||
status=None):
|
||||
super(Custom, self).__init__(
|
||||
id=id, status=status,
|
||||
name=name, script=script
|
||||
)
|
||||
|
||||
self._labels = ["custom"]
|
||||
self._type = "custom"
|
||||
self._default_values = [""]
|
||||
self._params_checkers = [self.check_params]
|
||||
self._params_tips = ["custom_params_tips"]
|
||||
|
||||
def random(self, params, nb):
|
||||
try:
|
||||
# Run script to (re)define the sample distribution
|
||||
f = eval(self._script)
|
||||
return f(params, nb)
|
||||
except Exception as e:
|
||||
logger_exception(e)
|
||||
return None # TODO: Raise helpful exception
|
||||
@@ -0,0 +1,62 @@
|
||||
# DistributionList.py -- Pamhyr
|
||||
# Copyright (C) 2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from tools import trace, timer
|
||||
|
||||
from Model.Tools.PamhyrListExt import PamhyrModelList
|
||||
from Model.Ensembles.Distribution import *
|
||||
|
||||
|
||||
class DistributionList(PamhyrModelList):
|
||||
_sub_classes = [Distribution]
|
||||
|
||||
@classmethod
|
||||
def _db_load(cls, execute, data=None):
|
||||
new = cls(status=data['status'])
|
||||
|
||||
# Default distributions
|
||||
d = {"status": data['status']}
|
||||
new._lst = [
|
||||
Uniform(**d),
|
||||
Normal(**d),
|
||||
Binomial(**d),
|
||||
Poisson(**d),
|
||||
]
|
||||
|
||||
# DB custom distributions
|
||||
new._lst += Distribution._db_load(
|
||||
execute, data
|
||||
)
|
||||
|
||||
return new
|
||||
|
||||
def _db_save(self, execute, data={}):
|
||||
execute(
|
||||
"DELETE FROM ensemble_distribution"
|
||||
)
|
||||
|
||||
for fun in self._lst:
|
||||
fun._db_save(execute, data)
|
||||
|
||||
return True
|
||||
|
||||
def new(self, index):
|
||||
r = Custom(status=self._status)
|
||||
self._lst.insert(index, r)
|
||||
self._status.modified()
|
||||
return r
|
||||
@@ -0,0 +1,279 @@
|
||||
# Ensemble.py -- Pamhyr
|
||||
# Copyright (C) 2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import struct
|
||||
import logging
|
||||
import itertools
|
||||
|
||||
import numpy as np
|
||||
|
||||
from Model.Tools.PamhyrDB import SQLSubModel
|
||||
from Model.Scenario import Scenario
|
||||
from Model.Ensembles.Distribution import Uniform
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class Ensemble(SQLSubModel):
|
||||
_sub_classes = []
|
||||
|
||||
def __init__(self, id: int = -1, name: str = "",
|
||||
distribution=None, params=[0., 100.],
|
||||
data_type=None, target_data=None,
|
||||
status=None, owner_scenario=-1):
|
||||
super(Ensemble, self).__init__(
|
||||
id=id, status=status,
|
||||
owner_scenario=owner_scenario
|
||||
)
|
||||
|
||||
self._name = name
|
||||
self._data_type = data_type
|
||||
self._distribution = distribution
|
||||
self._params = params
|
||||
self._target_data = target_data
|
||||
|
||||
@classmethod
|
||||
def _db_create(cls, execute, ext=""):
|
||||
execute(f"""
|
||||
CREATE TABLE ensemble{ext} (
|
||||
{cls.create_db_add_pamhyr_id()},
|
||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
name TEXT NOT NULL,
|
||||
type VARCHAR(8) NOT NULL,
|
||||
distribution INTEGER NOT NULL,
|
||||
distribution_name VARCHAR(32) NOT NULL,
|
||||
params BLOB NOT NULL,
|
||||
params_len INTEGER NOT NULL,
|
||||
data_pid INTEGER NOT NULL,
|
||||
{Scenario.create_db_add_scenario()},
|
||||
{Scenario.create_db_add_scenario_fk()},
|
||||
PRIMARY KEY(pamhyr_id, scenario)
|
||||
)
|
||||
""")
|
||||
|
||||
if ext == "_tmp":
|
||||
return True
|
||||
|
||||
return cls._create_submodel(execute)
|
||||
|
||||
@classmethod
|
||||
def _db_update(cls, execute, version, data=None):
|
||||
major, minor, release = version.strip().split(".")
|
||||
if major == "0" and int(minor) < 2:
|
||||
cls._db_create(execute)
|
||||
elif major == "0" and int(minor) == 2:
|
||||
if int(release) < 8:
|
||||
cls._db_create(execute)
|
||||
|
||||
return cls._update_submodel(execute, version, data)
|
||||
|
||||
@classmethod
|
||||
def _db_load(cls, execute, data=None):
|
||||
new = []
|
||||
scenario = data["scenario"]
|
||||
distributions = data["ens_distributions"]
|
||||
stricklers = data["stricklers"]
|
||||
loaded = data['loaded_pid']
|
||||
|
||||
table = execute(
|
||||
"SELECT pamhyr_id, deleted, name, type, " +
|
||||
"distribution, distribution_name, params, params_len, data_pid, " +
|
||||
"scenario " +
|
||||
"FROM ensemble " +
|
||||
f"WHERE scenario = {scenario.id} " +
|
||||
f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))})"
|
||||
)
|
||||
|
||||
for row in table:
|
||||
it = iter(row)
|
||||
|
||||
id = next(it)
|
||||
deleted = (next(it) == 1)
|
||||
name = next(it)
|
||||
data_type = next(it)
|
||||
fid = next(it)
|
||||
fname = next(it)
|
||||
params = next(it)
|
||||
params_len = next(it)
|
||||
data_pid = next(it)
|
||||
owner_scenario = next(it)
|
||||
|
||||
def fn(f): return f._name == fname
|
||||
if fid != -1:
|
||||
def fn(f): return f._pamhyr_id == fid
|
||||
|
||||
distribution = next(
|
||||
filter(fn, distributions.lst),
|
||||
None
|
||||
)
|
||||
|
||||
target_data = next(
|
||||
filter(
|
||||
lambda s: s._pamhyr_id == data_pid,
|
||||
stricklers.lst
|
||||
),
|
||||
None
|
||||
)
|
||||
|
||||
rdata = list(cls._decode_params(params, params_len))
|
||||
|
||||
new_ensemble = cls(
|
||||
id, name=name,
|
||||
distribution=distribution,
|
||||
params=rdata,
|
||||
data_type=data_type,
|
||||
target_data=target_data,
|
||||
status=data["status"],
|
||||
owner_scenario=owner_scenario
|
||||
)
|
||||
if deleted:
|
||||
new_ensemble.set_as_deleted()
|
||||
|
||||
loaded.add(id)
|
||||
new.append(new_ensemble)
|
||||
|
||||
return new
|
||||
|
||||
def _db_save(self, execute, data=None):
|
||||
if not self.must_be_saved():
|
||||
return True
|
||||
|
||||
execute(
|
||||
"DELETE FROM ensemble " +
|
||||
f"WHERE pamhyr_id = {self.pamhyr_id} " +
|
||||
f"AND scenario = {self._status.scenario_id}"
|
||||
)
|
||||
|
||||
bparams, length = self._encode_params()
|
||||
|
||||
if self._distribution is None:
|
||||
fid = -1
|
||||
fname = "NULL"
|
||||
else:
|
||||
fid = self._distribution._pamhyr_id
|
||||
fname = self._distribution._name
|
||||
|
||||
if self._distribution._type == "generic":
|
||||
fid = -1
|
||||
|
||||
data_pid = -1
|
||||
if self._target_data is not None:
|
||||
data_pid = self._target_data._pamhyr_id
|
||||
|
||||
execute(
|
||||
"INSERT INTO " +
|
||||
"ensemble(pamhyr_id, deleted, name, type, " +
|
||||
" distribution, distribution_name, params, params_len, " +
|
||||
" data_pid, scenario) " +
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
self.pamhyr_id, self.is_deleted(),
|
||||
self._name, self._data_type,
|
||||
fid, fname, bparams, length,
|
||||
data_pid, self._status.scenario_id
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def _encode_params(self):
|
||||
length = len(self._params)
|
||||
data_format = ">" + ''.join(itertools.repeat("d", length))
|
||||
|
||||
return struct.pack(data_format, *self._params), length
|
||||
|
||||
@classmethod
|
||||
def _decode_params(cls, bparams, length):
|
||||
data_format = ">" + ''.join(itertools.repeat("d", length))
|
||||
|
||||
return struct.unpack(data_format, bparams)
|
||||
|
||||
def random(self, nb):
|
||||
return np.nditer(
|
||||
self._distribution.random(
|
||||
self._params, nb
|
||||
)
|
||||
)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
return self._name
|
||||
|
||||
@name.setter
|
||||
def name(self, name):
|
||||
self._name = name
|
||||
self._status.modified()
|
||||
|
||||
@property
|
||||
def distribution(self):
|
||||
return self._distribution
|
||||
|
||||
@distribution.setter
|
||||
def distribution(self, distribution):
|
||||
self._distribution = distribution
|
||||
self._status.modified()
|
||||
|
||||
@property
|
||||
def params(self):
|
||||
return self._params
|
||||
|
||||
@params.setter
|
||||
def params(self, params):
|
||||
self._params = params
|
||||
self._status.modified()
|
||||
|
||||
@property
|
||||
def data_type(self):
|
||||
return self._data_type
|
||||
|
||||
@data_type.setter
|
||||
def data_type(self, data_type):
|
||||
self._data_type = data_type
|
||||
self._status.modified()
|
||||
|
||||
@property
|
||||
def target_data(self):
|
||||
return self._target_data
|
||||
|
||||
@target_data.setter
|
||||
def target_data(self, target_data):
|
||||
self._target_data = target_data
|
||||
self._status.modified()
|
||||
|
||||
def get_data_dict(self, use_ids=False):
|
||||
target_data = self.target_data
|
||||
distribution = self.distribution
|
||||
|
||||
if use_ids:
|
||||
if self.target_data:
|
||||
target_data = self.target_data.pamhyr_id
|
||||
if self.distribution:
|
||||
distribution = self.distribution.name
|
||||
|
||||
return {
|
||||
"name": self.name,
|
||||
"data_type": self.data_type,
|
||||
"target_data": target_data,
|
||||
"distribution": distribution,
|
||||
"params": self.params,
|
||||
}
|
||||
|
||||
def set_data_dict(self, data):
|
||||
self.name = data["name"]
|
||||
self.data_type = data["data_type"]
|
||||
self.target_data = data["target_data"]
|
||||
self.distribution = data["distribution"]
|
||||
self.params = data["params"]
|
||||
@@ -0,0 +1,62 @@
|
||||
# EnsembleList.py -- Pamhyr
|
||||
# Copyright (C) 2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from tools import trace, timer
|
||||
|
||||
from Model.Tools.PamhyrListExt import PamhyrModelList
|
||||
from Model.Ensembles.Ensemble import Ensemble
|
||||
|
||||
|
||||
class EnsembleList(PamhyrModelList):
|
||||
_sub_classes = [Ensemble]
|
||||
|
||||
@classmethod
|
||||
def _db_load(cls, execute, data=None):
|
||||
new = cls(status=data['status'])
|
||||
|
||||
new._lst = Ensemble._db_load(
|
||||
execute, data
|
||||
)
|
||||
|
||||
return new
|
||||
|
||||
def _db_save(self, execute, data=None):
|
||||
execute(
|
||||
"DELETE FROM ensemble " +
|
||||
f"WHERE scenario = {self._status.scenario_id}"
|
||||
)
|
||||
|
||||
for ens in self._lst:
|
||||
ens._db_save(execute, data=data)
|
||||
|
||||
return True
|
||||
|
||||
def new(self, index):
|
||||
r = Ensemble(status=self._status)
|
||||
self._lst.insert(index, r)
|
||||
self._status.modified()
|
||||
return r
|
||||
|
||||
def new_with_data(self, index, data):
|
||||
r = Ensemble(status=self._status)
|
||||
|
||||
r.set_data_dict(data)
|
||||
|
||||
self._lst.insert(index, r)
|
||||
self._status.modified()
|
||||
return r
|
||||
@@ -55,8 +55,11 @@ class Point(SQLSubModel):
|
||||
|
||||
@name.setter
|
||||
def name(self, name):
|
||||
changed = self._name != name
|
||||
self._name = name
|
||||
self.modified()
|
||||
if changed and self._profile is not None:
|
||||
self._profile.content_modified()
|
||||
|
||||
def is_named(self):
|
||||
"""
|
||||
|
||||
@@ -95,12 +95,11 @@ class PointXYZ(Point):
|
||||
"ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE"
|
||||
)
|
||||
|
||||
if major == "0" and minor == "2":
|
||||
if int(release) < 5:
|
||||
execute(
|
||||
"CREATE INDEX idx_point " +
|
||||
"ON geometry_pointXYZ(profile, scenario);"
|
||||
)
|
||||
# Try to create index at each update
|
||||
execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_point " +
|
||||
"ON geometry_pointXYZ(profile, scenario);"
|
||||
)
|
||||
|
||||
return cls._update_submodel(execute, version, data)
|
||||
|
||||
@@ -329,8 +328,11 @@ class PointXYZ(Point):
|
||||
|
||||
@x.setter
|
||||
def x(self, value):
|
||||
changed = self._x != float(value)
|
||||
self._x = float(value)
|
||||
self.modified()
|
||||
if changed and self._profile is not None:
|
||||
self._profile.content_modified()
|
||||
|
||||
@property
|
||||
def y(self):
|
||||
@@ -338,8 +340,11 @@ class PointXYZ(Point):
|
||||
|
||||
@y.setter
|
||||
def y(self, value):
|
||||
changed = self._y != float(value)
|
||||
self._y = float(value)
|
||||
self.modified()
|
||||
if changed and self._profile is not None:
|
||||
self._profile.content_modified()
|
||||
|
||||
@property
|
||||
def z(self):
|
||||
@@ -347,8 +352,11 @@ class PointXYZ(Point):
|
||||
|
||||
@z.setter
|
||||
def z(self, value):
|
||||
changed = self._z != float(value)
|
||||
self._z = float(value)
|
||||
self.modified()
|
||||
if changed and self._profile is not None:
|
||||
self._profile.content_modified()
|
||||
|
||||
def shift(self, x, y, z):
|
||||
self.x += x
|
||||
|
||||
@@ -47,6 +47,8 @@ class Profile(object):
|
||||
self._sl = None
|
||||
|
||||
self._points: List[Point] = []
|
||||
self._modification_count = 0
|
||||
self._old_interpolated = ""
|
||||
|
||||
self._profile_type = _type
|
||||
|
||||
@@ -160,8 +162,13 @@ class Profile(object):
|
||||
|
||||
@rk.setter
|
||||
def rk(self, value: float):
|
||||
self._rk = float(value)
|
||||
self.modified()
|
||||
value = float(value)
|
||||
changed = value != self._rk
|
||||
self._rk = value
|
||||
if changed:
|
||||
self.content_modified()
|
||||
else:
|
||||
self.modified()
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -173,8 +180,13 @@ class Profile(object):
|
||||
|
||||
@name.setter
|
||||
def name(self, value: str):
|
||||
self._name = value.strip()
|
||||
self.modified()
|
||||
value = value.strip()
|
||||
changed = value != self._name
|
||||
self._name = value
|
||||
if changed:
|
||||
self.content_modified()
|
||||
else:
|
||||
self.modified()
|
||||
|
||||
@property
|
||||
def sl(self):
|
||||
@@ -217,6 +229,38 @@ class Profile(object):
|
||||
return [point for point in self.points
|
||||
if point.is_named()]
|
||||
|
||||
@property
|
||||
def modification_count(self):
|
||||
"""Content revision for this session; not stored in the database."""
|
||||
return self._modification_count
|
||||
|
||||
def increase_modification_count(self):
|
||||
"""Increase content revision for this session;
|
||||
not stored in the database."""
|
||||
self._modification_count += 1
|
||||
|
||||
def decrease_modification_count(self):
|
||||
"""Decrease content revision for this session;
|
||||
not stored in the database."""
|
||||
self._modification_count -= 1
|
||||
|
||||
@property
|
||||
def old_interpolated(self):
|
||||
"""Old interpolated value for this session;
|
||||
not stored in the database."""
|
||||
return self._old_interpolated
|
||||
|
||||
@old_interpolated.setter
|
||||
def old_interpolated(self, value):
|
||||
self._old_interpolated = value
|
||||
|
||||
def content_modified(self):
|
||||
"""An edited profile is no longer an interpolation result."""
|
||||
# self._modification_count += 1
|
||||
if hasattr(self, "_interpolated"):
|
||||
self._interpolated = False
|
||||
self.modified()
|
||||
|
||||
def insert_point(self, index: int, point: Point):
|
||||
"""Insert point at index.
|
||||
|
||||
@@ -232,7 +276,7 @@ class Profile(object):
|
||||
else:
|
||||
self._points.insert(index, point)
|
||||
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
def delete_i(self, indexes: list):
|
||||
list(
|
||||
@@ -245,7 +289,7 @@ class Profile(object):
|
||||
)
|
||||
)
|
||||
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
def delete_points(self, points):
|
||||
"""Delete some elements in profile list
|
||||
@@ -262,7 +306,7 @@ class Profile(object):
|
||||
points
|
||||
)
|
||||
)
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
# Move
|
||||
|
||||
@@ -272,7 +316,7 @@ class Profile(object):
|
||||
|
||||
p = self._points
|
||||
p[index], p[next] = p[next], p[index]
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
def move_down_point(self, index: int):
|
||||
if index >= 0:
|
||||
@@ -280,7 +324,7 @@ class Profile(object):
|
||||
|
||||
p = self._points
|
||||
p[index], p[prev] = p[prev], p[index]
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
# Sort
|
||||
|
||||
@@ -297,7 +341,7 @@ class Profile(object):
|
||||
key=predicate,
|
||||
reverse=is_reversed
|
||||
)
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
@timer
|
||||
def sort_with_indexes(self, indexes: list):
|
||||
@@ -313,12 +357,12 @@ class Profile(object):
|
||||
)
|
||||
)
|
||||
)
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
@timer
|
||||
def reverse(self):
|
||||
self._points.reverse()
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
# Sediment Layers
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import queue
|
||||
import types
|
||||
import random
|
||||
import logging
|
||||
import numpy as np
|
||||
@@ -39,9 +40,9 @@ logger = logging.getLogger()
|
||||
|
||||
@dataclass
|
||||
class Tabulation:
|
||||
z: np.array([])
|
||||
A: np.array([])
|
||||
L: np.array([])
|
||||
z: np.ndarray
|
||||
A: np.ndarray
|
||||
L: np.ndarray
|
||||
|
||||
|
||||
class ProfileXYZ(Profile, SQLSubModel):
|
||||
@@ -158,7 +159,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
||||
)
|
||||
|
||||
if major == "0" and int(minor) <= 2:
|
||||
if int(release) < 9:
|
||||
if int(release) < 10:
|
||||
execute(
|
||||
"ALTER TABLE geometry_profileXYZ " +
|
||||
"ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT TRUE"
|
||||
@@ -559,7 +560,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
||||
)
|
||||
self._points.append(pt)
|
||||
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
def get_point_i(self, index: int) -> PointXYZ:
|
||||
"""Get point at index.
|
||||
@@ -624,7 +625,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
||||
)
|
||||
self.points.append(point_xyz)
|
||||
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
def insert(self, index: int):
|
||||
"""Insert a new point at index.
|
||||
@@ -643,7 +644,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
||||
point = PointXYZ(x=x, y=y, z=z, profile=self, status=self._status)
|
||||
self._points.insert(index, point)
|
||||
|
||||
self.modified()
|
||||
self.content_modified()
|
||||
|
||||
return point
|
||||
|
||||
@@ -842,7 +843,11 @@ class ProfileXYZ(Profile, SQLSubModel):
|
||||
return poly
|
||||
|
||||
def wet_points(self, z):
|
||||
left, right = self.get_water_limits(z)
|
||||
limits = self.get_water_limits(z)
|
||||
|
||||
if isinstance(limits, types.GeneratorType):
|
||||
limits = next(limits)
|
||||
left, right = limits
|
||||
|
||||
points = list(filter(lambda p: p.z < z, self._points))
|
||||
points = [left] + points + [right]
|
||||
@@ -862,6 +867,13 @@ class ProfileXYZ(Profile, SQLSubModel):
|
||||
|
||||
return n_zones
|
||||
|
||||
def froude(self, z, v):
|
||||
return v / np.sqrt(
|
||||
9.81 * (
|
||||
self.wet_area(z) / self.wet_width(z)
|
||||
)
|
||||
)
|
||||
|
||||
@timer
|
||||
def get_all_water_limits_ac(self, z):
|
||||
"""
|
||||
@@ -1172,8 +1184,9 @@ class ProfileXYZ(Profile, SQLSubModel):
|
||||
interpolated=self.interpolated)
|
||||
|
||||
for i, k in enumerate(self.points):
|
||||
p.insert_point(i, k.copy())
|
||||
p.insert_point(i, k.cloned_for(p))
|
||||
|
||||
p._interpolated = self.interpolated
|
||||
return p
|
||||
|
||||
def purge_aligned_points(self):
|
||||
|
||||
@@ -224,6 +224,9 @@ class LateralContribution(SQLSubModel):
|
||||
self._header = []
|
||||
self._types = [float, float]
|
||||
|
||||
self._d50 = 0.002
|
||||
self._sigma = 1.0
|
||||
|
||||
@classmethod
|
||||
def _db_create(cls, execute, ext=""):
|
||||
execute(f"""
|
||||
@@ -236,6 +239,8 @@ class LateralContribution(SQLSubModel):
|
||||
reach INTEGER,
|
||||
begin_section INTEGER,
|
||||
end_section INTEGER,
|
||||
d50 REAL DEFAULT 0.002,
|
||||
sigma REAL DEFAULT 1,
|
||||
{Scenario.create_db_add_scenario()},
|
||||
{Scenario.create_db_add_scenario_fk()},
|
||||
FOREIGN KEY(reach) REFERENCES river_reach(pamhyr_id),
|
||||
@@ -286,8 +291,32 @@ class LateralContribution(SQLSubModel):
|
||||
"ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE"
|
||||
)
|
||||
|
||||
if major == "0" and (int(minor) < 2 or
|
||||
(minor == "2" and int(release) < 11)):
|
||||
cls._db_update_to_0_2_11(execute)
|
||||
|
||||
return cls._update_submodel(execute, version, data)
|
||||
|
||||
@classmethod
|
||||
def _db_update_to_0_2_11(cls, execute):
|
||||
# The table may already have been recreated with these columns
|
||||
# by _db_update_to_0_2_0
|
||||
columns = [
|
||||
row[0] for row in execute(
|
||||
"SELECT name FROM pragma_table_info('lateral_contribution')"
|
||||
)
|
||||
]
|
||||
if "d50" not in columns:
|
||||
execute(
|
||||
"ALTER TABLE lateral_contribution " +
|
||||
"ADD COLUMN d50 REAL DEFAULT 0.002"
|
||||
)
|
||||
if "sigma" not in columns:
|
||||
execute(
|
||||
"ALTER TABLE lateral_contribution " +
|
||||
"ADD COLUMN sigma REAL DEFAULT 1"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _db_update_to_0_2_0(cls, execute, data):
|
||||
table = "lateral_contribution"
|
||||
@@ -339,7 +368,7 @@ class LateralContribution(SQLSubModel):
|
||||
|
||||
table = execute(
|
||||
"SELECT pamhyr_id, deleted, name, type, " +
|
||||
"reach, begin_section, end_section, scenario " +
|
||||
"reach, begin_section, end_section, d50, sigma, scenario " +
|
||||
"FROM lateral_contribution " +
|
||||
f"WHERE tab = '{tab}'" +
|
||||
f"AND scenario = {scenario.id} " +
|
||||
@@ -356,6 +385,8 @@ class LateralContribution(SQLSubModel):
|
||||
reach = next(it)
|
||||
b_section = next(it)
|
||||
e_section = next(it)
|
||||
d50 = next(it)
|
||||
sigma = next(it)
|
||||
owner_scenario = next(it)
|
||||
|
||||
ctor = cls._get_ctor_from_type(t)
|
||||
@@ -367,6 +398,10 @@ class LateralContribution(SQLSubModel):
|
||||
lc.reach = None
|
||||
lc._begin_section = None
|
||||
lc._end_section = None
|
||||
if d50 is not None:
|
||||
lc._d50 = float(d50)
|
||||
if sigma is not None:
|
||||
lc._sigma = float(sigma)
|
||||
|
||||
if row[3] != -1:
|
||||
lc.reach = next(
|
||||
@@ -426,12 +461,13 @@ class LateralContribution(SQLSubModel):
|
||||
"INSERT INTO " +
|
||||
"lateral_contribution(" +
|
||||
"pamhyr_id, deleted, name, type, tab, " +
|
||||
"reach, begin_section, end_section, scenario) " +
|
||||
"reach, begin_section, end_section, d50, sigma, scenario) " +
|
||||
"VALUES (" +
|
||||
f"{self.id}, {self._db_format(self.is_deleted())}, " +
|
||||
f"'{self._db_format(self._name)}', " +
|
||||
f"'{self._db_format(self._type)}', '{tab}', {reach}, " +
|
||||
f"{begin_section}, {end_section}, " +
|
||||
f"{self._d50}, {self._sigma}, " +
|
||||
f"{self._status.scenario_id}" +
|
||||
")"
|
||||
)
|
||||
@@ -523,10 +559,30 @@ class LateralContribution(SQLSubModel):
|
||||
new._reach = reach
|
||||
new._begin_section = begin_section
|
||||
new._end_section = end_section
|
||||
new._d50 = self._d50
|
||||
new._sigma = self._sigma
|
||||
new._data = [data.cloned() for data in self.data]
|
||||
new.modified()
|
||||
return new
|
||||
|
||||
@property
|
||||
def d50(self):
|
||||
return self._d50
|
||||
|
||||
@d50.setter
|
||||
def d50(self, value):
|
||||
self._d50 = float(value)
|
||||
self.modified()
|
||||
|
||||
@property
|
||||
def sigma(self):
|
||||
return self._sigma
|
||||
|
||||
@sigma.setter
|
||||
def sigma(self, value):
|
||||
self._sigma = float(value)
|
||||
self.modified()
|
||||
|
||||
@property
|
||||
def begin_rk(self):
|
||||
if self._begin_section is None:
|
||||
|
||||
@@ -272,9 +272,9 @@ class TableData(SQLSubModel):
|
||||
|
||||
if len(shape) == 2:
|
||||
shape_x, shape_y = shape
|
||||
elif len(shape == 1):
|
||||
elif len(shape) == 1:
|
||||
shape_x, = shape
|
||||
elif len(shape == 3):
|
||||
elif len(shape) == 3:
|
||||
shape_x, shape_y, shape_z = shape
|
||||
else:
|
||||
logger.error(
|
||||
@@ -326,14 +326,14 @@ class TableData(SQLSubModel):
|
||||
if isinstance(key, tuple):
|
||||
return self._data[key[0], key[1]]
|
||||
|
||||
self._date[key]
|
||||
self._data[key]
|
||||
|
||||
|
||||
class Results(SQLSubModel):
|
||||
_sub_classes = [River, TableData, AdditionalData]
|
||||
|
||||
def __init__(self, id=-1, study=None, solver=None,
|
||||
repertory="", name="0"):
|
||||
repertory="", name="0", is_ensemble=False):
|
||||
super(Results, self).__init__(
|
||||
id=id, status=study.status,
|
||||
owner_scenario=study.status.scenario.id
|
||||
@@ -341,11 +341,14 @@ class Results(SQLSubModel):
|
||||
|
||||
self._name = name
|
||||
self._study = study
|
||||
self._river = River(self._study, self)
|
||||
# Solver readers add their own reaches; ensembles need them upfront.
|
||||
self._river = River(self._study, self, init=is_ensemble)
|
||||
|
||||
self._solver = solver
|
||||
self._repertory = repertory
|
||||
|
||||
self._is_ensemble = is_ensemble
|
||||
|
||||
self._meta_data = {
|
||||
# Keep results creation date
|
||||
"creation_date": datetime.now(),
|
||||
@@ -359,6 +362,9 @@ class Results(SQLSubModel):
|
||||
if solver is not None:
|
||||
self.set("solver_type", solver._type)
|
||||
|
||||
def is_ensemble(self):
|
||||
return self._is_ensemble
|
||||
|
||||
@property
|
||||
def date(self):
|
||||
date = self._meta_data["creation_date"]
|
||||
@@ -426,9 +432,11 @@ class Results(SQLSubModel):
|
||||
solver_name TEXT NOT NULL,
|
||||
solver_type TEXT NOT NULL,
|
||||
study_revision INTEGER NOT NULL,
|
||||
creation_data DATE NOT NULL,
|
||||
creation_date DATE NOT NULL,
|
||||
nb_timestamps INTEGER NOT NULL,
|
||||
timestamps BLOB NOT NULL,
|
||||
seed INTEGER,
|
||||
number_of_run INTEGER,
|
||||
{Scenario.create_db_add_scenario()},
|
||||
{Scenario.create_db_add_scenario_fk()},
|
||||
PRIMARY KEY(pamhyr_id, scenario)
|
||||
@@ -454,6 +462,21 @@ class Results(SQLSubModel):
|
||||
cls._db_create(execute)
|
||||
create = True
|
||||
|
||||
if major == "0" and int(minor) <= 2:
|
||||
if int(release) < 9 and not create:
|
||||
execute(
|
||||
"ALTER TABLE results ADD COLUMN " +
|
||||
"seed INTEGER"
|
||||
)
|
||||
execute(
|
||||
"ALTER TABLE results ADD COLUMN " +
|
||||
"number_of_run INTEGER"
|
||||
)
|
||||
execute(
|
||||
"ALTER TABLE results RENAME COLUMN " +
|
||||
"creation_data TO creation_date"
|
||||
)
|
||||
|
||||
return cls._update_submodel(execute, version, data)
|
||||
|
||||
@classmethod
|
||||
@@ -466,7 +489,9 @@ class Results(SQLSubModel):
|
||||
|
||||
table = execute(
|
||||
"SELECT pamhyr_id, solver_name, solver_type, " +
|
||||
"study_revision, creation_data, nb_timestamps, timestamps, " +
|
||||
"study_revision, creation_date, " +
|
||||
"seed, number_of_run, " +
|
||||
"nb_timestamps, timestamps, " +
|
||||
"scenario " +
|
||||
"FROM results " +
|
||||
f"WHERE scenario = {scenario.id}"
|
||||
@@ -486,6 +511,8 @@ class Results(SQLSubModel):
|
||||
solver_type = next(it)
|
||||
revision = next(it)
|
||||
creation_date = next(it)
|
||||
seed = next(it)
|
||||
number_of_run = next(it)
|
||||
nb_timestamps = next(it)
|
||||
timestamps_bytes = next(it)
|
||||
owner_scenario = next(it)
|
||||
@@ -496,6 +523,9 @@ class Results(SQLSubModel):
|
||||
new_results.set("solver_type", solver_type)
|
||||
new_results.set("study_revision", revision)
|
||||
new_results.set("creation_date", creation_date)
|
||||
if seed is not None:
|
||||
new_results.set("seed", seed)
|
||||
new_results.set("number_of_run", number_of_run)
|
||||
|
||||
data["result_pid"] = pid
|
||||
data["result"] = new_results
|
||||
@@ -588,15 +618,25 @@ class Results(SQLSubModel):
|
||||
ts = sorted(self.get("timestamps"))
|
||||
sf = ">" + ''.join(itertools.repeat("d", len(ts)))
|
||||
|
||||
if "seed" in self._meta_data:
|
||||
seed = int(self.get("seed"))
|
||||
number_of_run = int(self.get("number_of_run"))
|
||||
else:
|
||||
seed = None
|
||||
number_of_run = None
|
||||
|
||||
execute(
|
||||
"INSERT INTO " +
|
||||
"results (pamhyr_id, solver_name, solver_type, " +
|
||||
"study_revision, creation_data, " +
|
||||
"study_revision, creation_date, " +
|
||||
"seed, number_of_run, " +
|
||||
"nb_timestamps, timestamps, " +
|
||||
"scenario) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
"scenario) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
self._pamhyr_id, solver_name, solver_type,
|
||||
self._status.version, self.get("creation_date"),
|
||||
len(ts), struct.pack(sf, *ts), self._owner_scenario
|
||||
seed, number_of_run,
|
||||
len(ts), struct.pack(sf, *ts),
|
||||
self._owner_scenario
|
||||
)
|
||||
|
||||
data["result"] = self._pamhyr_id
|
||||
|
||||
@@ -104,7 +104,10 @@ class Profile(SQLSubModel):
|
||||
return any(map(lambda ts: "sl" in self._data[ts], self._data))
|
||||
|
||||
def has_bedload(self):
|
||||
return any(map(lambda ts: "sl" in self._data[ts], self._data))
|
||||
# Sediment layers (Mage) or bed level of the section (RubarBE)
|
||||
return any(map(lambda ts: ("sl" in self._data[ts] or
|
||||
"zfd" in self._data[ts]),
|
||||
self._data))
|
||||
|
||||
@classmethod
|
||||
def _db_create(cls, execute, ext=""):
|
||||
@@ -403,7 +406,7 @@ class Reach(SQLSubModel):
|
||||
class River(SQLSubModel):
|
||||
_sub_classes = [Reach]
|
||||
|
||||
def __init__(self, study, parent):
|
||||
def __init__(self, study, parent, init=True):
|
||||
super(River, self).__init__(
|
||||
id=-1, status=study.status,
|
||||
owner_scenario=study.status.scenario.id
|
||||
@@ -414,6 +417,9 @@ class River(SQLSubModel):
|
||||
|
||||
# Dict with timestamps as key
|
||||
self._reachs = []
|
||||
if init:
|
||||
for i, _ in enumerate(self._study.river.enable_edges()):
|
||||
self.add(i)
|
||||
|
||||
def __len__(self):
|
||||
return len(self._reachs)
|
||||
@@ -453,7 +459,7 @@ class River(SQLSubModel):
|
||||
|
||||
reach.update_water_limits(
|
||||
timestamp,
|
||||
data[ind[0]:ind[1]]
|
||||
data[ind[0]:ind[1] + 1]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
@@ -469,7 +475,7 @@ class River(SQLSubModel):
|
||||
study = data["study"]
|
||||
parent = data["parent"]
|
||||
|
||||
new_river = cls(study, parent)
|
||||
new_river = cls(study, parent, init=False)
|
||||
|
||||
for reach in study.river.reachs():
|
||||
data["reach"] = reach.reach
|
||||
|
||||
+10
-1
@@ -69,6 +69,7 @@ from Model.WeatherParameters.WeatherParametersList \
|
||||
import WeatherParametersList
|
||||
|
||||
from Model.GeoTIFF.GeoTIFFList import GeoTIFFList
|
||||
from Model.Ensembles.EnsembleList import EnsembleList
|
||||
from Model.Results.Results import Results
|
||||
|
||||
logger = logging.getLogger()
|
||||
@@ -487,6 +488,7 @@ class River(Graph):
|
||||
BoundaryConditionsTemperatureList,
|
||||
WeatherParametersList,
|
||||
GeoTIFFList,
|
||||
EnsembleList,
|
||||
Results
|
||||
]
|
||||
|
||||
@@ -532,6 +534,9 @@ class River(Graph):
|
||||
|
||||
self._geotiff = GeoTIFFList(status=self._status)
|
||||
|
||||
# Scenario ensemble
|
||||
self._ensembles = EnsembleList(status=self._status)
|
||||
|
||||
self._results = {}
|
||||
|
||||
@classmethod
|
||||
@@ -650,6 +655,8 @@ class River(Graph):
|
||||
|
||||
new._geotiff = GeoTIFFList._db_load(execute, data)
|
||||
|
||||
new._ensembles = EnsembleList._db_load(execute, data)
|
||||
|
||||
return new
|
||||
|
||||
def _db_load_results(self, execute, data=None):
|
||||
@@ -688,6 +695,8 @@ class River(Graph):
|
||||
|
||||
objs.append(self._geotiff)
|
||||
|
||||
objs.append(self._ensembles)
|
||||
|
||||
for solv_type in self.results:
|
||||
objs.append(self.results[solv_type])
|
||||
|
||||
@@ -766,7 +775,7 @@ class River(Graph):
|
||||
self._InitialConditionsTemperature,
|
||||
self._BoundaryConditionsTemperature,
|
||||
self._WeatherParameters,
|
||||
self._geotiff,
|
||||
self._geotiff, self._ensembles,
|
||||
]
|
||||
|
||||
for solver in self._parameters:
|
||||
|
||||
+29
-12
@@ -58,6 +58,7 @@ class Scenario(SQLSubModel):
|
||||
"initial_conditions_temperature",
|
||||
"initial_conditions_temperature_spec",
|
||||
"weather_parameters", "weather_parameters_data",
|
||||
"ensemble",
|
||||
]
|
||||
|
||||
related_tables = tables_with_deleted_column + [
|
||||
@@ -72,6 +73,7 @@ class Scenario(SQLSubModel):
|
||||
name: str = "",
|
||||
description: str = "",
|
||||
x: int = 1000.0, y: int = 1000.0,
|
||||
is_ensemble: bool = False,
|
||||
revision: int = 0,
|
||||
parent=None):
|
||||
super(Scenario, self).__init__()
|
||||
@@ -81,6 +83,7 @@ class Scenario(SQLSubModel):
|
||||
self._x, self._y = x, y
|
||||
self._name = name
|
||||
self._description = description
|
||||
self._is_ensemble = is_ensemble
|
||||
self._revision = revision
|
||||
self._parent = parent
|
||||
|
||||
@@ -103,6 +106,7 @@ class Scenario(SQLSubModel):
|
||||
y REAL NOT NULL DEFAULT 1000,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT NOT NULL,
|
||||
is_ensemble BOOL DEFAULT FALSE,
|
||||
revision INTEGER NOT NULL,
|
||||
parent_id INTEGER REFERENCES scenario(id)
|
||||
)
|
||||
@@ -138,6 +142,13 @@ class Scenario(SQLSubModel):
|
||||
cls._db_create(execute)
|
||||
cls._db_add_default(execute)
|
||||
|
||||
if major == "0" and int(minor) == 2:
|
||||
if int(release) < 8:
|
||||
execute(
|
||||
f"ALTER TABLE scenario " +
|
||||
"ADD COLUMN is_ensemble BOOL DEFAULT FALSE"
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
@@ -158,7 +169,8 @@ class Scenario(SQLSubModel):
|
||||
scenarios = {}
|
||||
|
||||
table = execute(
|
||||
"SELECT id, x, y, name, description, revision, parent_id " +
|
||||
"SELECT id, x, y, name, description, " +
|
||||
" is_ensemble, revision, parent_id " +
|
||||
"FROM scenario " +
|
||||
"ORDER BY id ASC"
|
||||
)
|
||||
@@ -170,6 +182,7 @@ class Scenario(SQLSubModel):
|
||||
x, y = next(it), next(it)
|
||||
name = next(it)
|
||||
desc = next(it)
|
||||
is_ens = next(it)
|
||||
revi = next(it)
|
||||
parent = next(it)
|
||||
|
||||
@@ -179,7 +192,9 @@ class Scenario(SQLSubModel):
|
||||
new = cls(
|
||||
id=id, x=x, y=y,
|
||||
name=name, description=desc,
|
||||
revision=revi, parent=parent
|
||||
is_ensemble=is_ens,
|
||||
revision=revi,
|
||||
parent=parent
|
||||
)
|
||||
scenarios[id] = new
|
||||
|
||||
@@ -189,21 +204,18 @@ class Scenario(SQLSubModel):
|
||||
if self.is_deleted():
|
||||
return self.drop_all(execute)
|
||||
|
||||
parent = 'NULL'
|
||||
parent = None
|
||||
if self.parent is not None:
|
||||
parent = self.parent._id
|
||||
|
||||
execute(
|
||||
"INSERT OR REPLACE INTO " +
|
||||
"scenario(id, x, y, name, description, revision, parent_id) " +
|
||||
"VALUES (" +
|
||||
f"{self._id}, " +
|
||||
f"{self.x}, {self.y}, " +
|
||||
f"'{self._db_format(self.name)}', " +
|
||||
f"'{self._db_format(self.description)}', " +
|
||||
f"{self._revision}, " +
|
||||
f"{parent}" +
|
||||
")"
|
||||
"scenario(id, x, y, name, description, " +
|
||||
" is_ensemble, revision, parent_id) " +
|
||||
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
self._id, self.x, self.y,
|
||||
self.name, self.description, self._is_ensemble,
|
||||
self._revision, parent
|
||||
)
|
||||
|
||||
return True
|
||||
@@ -328,6 +340,9 @@ class Scenario(SQLSubModel):
|
||||
def parent(self):
|
||||
return self._parent
|
||||
|
||||
def is_ensemble(self):
|
||||
return self._is_ensemble
|
||||
|
||||
def set_pos(self, x, y):
|
||||
self._x = x
|
||||
self._y = y
|
||||
@@ -345,6 +360,8 @@ class Scenario(SQLSubModel):
|
||||
return self.name
|
||||
if key == "description":
|
||||
return self.description
|
||||
if key == "is_ensemble":
|
||||
return self.is_ensemble()
|
||||
if key == "parent":
|
||||
return self.parent
|
||||
|
||||
|
||||
@@ -57,8 +57,11 @@ class Scenarios(PamhyrModelDict):
|
||||
|
||||
return None
|
||||
|
||||
def new(self, parent):
|
||||
new = Scenario(parent=parent)
|
||||
def new(self, parent, is_ensemble=False):
|
||||
new = Scenario(
|
||||
parent=parent,
|
||||
is_ensemble=is_ensemble
|
||||
)
|
||||
self.set(new._id, new)
|
||||
return new
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
from copy import copy
|
||||
from tools import trace, timer
|
||||
from Solver.Solvers import solver_type_list
|
||||
from Solver.RubarBE import Rubar3
|
||||
|
||||
from Model.Scenario import Scenario
|
||||
from Model.Tools.PamhyrDB import SQLSubModel
|
||||
@@ -296,14 +297,20 @@ class SolverParametersList(PamhyrModelList):
|
||||
scenario = data["scenario"]
|
||||
loaded = data['loaded_pid']
|
||||
|
||||
solvers = execute("SELECT DISTINCT solver FROM solver_parameter")
|
||||
solvers = [
|
||||
row[0] for row in
|
||||
execute("SELECT DISTINCT solver FROM solver_parameter")
|
||||
]
|
||||
new = {}
|
||||
|
||||
if scenario is None:
|
||||
return new
|
||||
|
||||
for solver in solvers:
|
||||
solver = solver[0]
|
||||
if solver == "rubar3" and "rubarbe" not in solvers:
|
||||
new["rubarbe"] = cls._db_load_rubar3(execute, data)
|
||||
continue
|
||||
|
||||
if solver not in solver_type_list:
|
||||
continue
|
||||
|
||||
@@ -315,10 +322,44 @@ class SolverParametersList(PamhyrModelList):
|
||||
|
||||
n._lst = list(map(lambda t: t[1], sorted(lst)))
|
||||
|
||||
# Parameters added to the solver after the study was saved
|
||||
names = {p.name for p in n._lst}
|
||||
n._lst += [
|
||||
Parameter(name=name, value=value, status=status)
|
||||
for name, value in st.default_parameters()
|
||||
if name not in names
|
||||
]
|
||||
|
||||
new[solver] = n
|
||||
|
||||
return new
|
||||
|
||||
@classmethod
|
||||
def _db_load_rubar3(cls, execute, data):
|
||||
"""Rubar3 is no longer offered: RubarBE, its generic version,
|
||||
takes the parameters of a Rubar3 study (same rubarbe_* keys,
|
||||
RubarBE reads them the same way). Missing parameters take the
|
||||
Rubar3 defaults (no sediment transport), so that the
|
||||
computation is unchanged. New parameters (new ids): saved as
|
||||
RubarBE ones with the study, the Rubar3 rows are then ignored"""
|
||||
status = data["status"]
|
||||
n = cls(solver_type=solver_type_list["rubarbe"], status=status)
|
||||
|
||||
data['solver'] = "rubar3"
|
||||
lst = Parameter._db_load(execute, data)
|
||||
|
||||
n._lst = [
|
||||
Parameter(name=p.name, value=p.value, status=status)
|
||||
for _, p in sorted(lst, key=lambda t: t[0])
|
||||
]
|
||||
names = {p.name for p in n._lst}
|
||||
n._lst += [
|
||||
Parameter(name=name, value=value, status=status)
|
||||
for name, value in Rubar3.default_parameters()
|
||||
if name not in names
|
||||
]
|
||||
return n
|
||||
|
||||
def _db_save(self, execute, data=None):
|
||||
t = self._solver._type
|
||||
execute(
|
||||
|
||||
+84
-7
@@ -21,7 +21,7 @@ import shutil
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from tools import timer, timestamp
|
||||
from tools import timer, timestamp, parse_datetime
|
||||
from functools import reduce
|
||||
|
||||
from Model.Tools.PamhyrListExt import PamhyrModelList
|
||||
@@ -32,7 +32,9 @@ from Model.Scenario import Scenario
|
||||
from Model.Status import StudyStatus
|
||||
from Model.Except import NotImplementedMethodeError
|
||||
from Model.River import River
|
||||
from Model.TimeShift import shift_river_times, shift_database_times
|
||||
from Model.Geometry.Reach import Reach
|
||||
from Model.Ensembles.DistributionList import DistributionList
|
||||
from Model.HydraulicStructures.HydraulicStructures import (
|
||||
HydraulicStructure
|
||||
)
|
||||
@@ -46,10 +48,11 @@ logger = logging.getLogger()
|
||||
|
||||
|
||||
class Study(SQLModel):
|
||||
_version = "0.2.10"
|
||||
_version = "0.2.11"
|
||||
|
||||
_sub_classes = [
|
||||
Scenario,
|
||||
DistributionList,
|
||||
River,
|
||||
]
|
||||
|
||||
@@ -72,6 +75,7 @@ class Study(SQLModel):
|
||||
self.description = ""
|
||||
# Time system
|
||||
self._time_system = "time"
|
||||
self._pending_time_offset = 0.0
|
||||
self._date = datetime.fromtimestamp(0)
|
||||
|
||||
if init_new:
|
||||
@@ -84,6 +88,9 @@ class Study(SQLModel):
|
||||
self.scenarios = Scenarios(status=self.status)
|
||||
self.scenarios[0] = s0
|
||||
self.status.scenario = s0
|
||||
|
||||
self._ens_distributions = DistributionList(status=self.status)
|
||||
|
||||
self._river = River(status=self.status)
|
||||
else:
|
||||
self._init_db_file(filename, is_new=False)
|
||||
@@ -198,6 +205,16 @@ class Study(SQLModel):
|
||||
self._date = date
|
||||
self.status.modified()
|
||||
|
||||
def change_start_date(self, date, preserve_dates=False):
|
||||
"""Change the origin, optionally preserving series calendar dates."""
|
||||
new_date = parse_datetime(date)
|
||||
offset = (parse_datetime(self.date) - new_date).total_seconds()
|
||||
if preserve_dates and offset:
|
||||
shift_river_times(self.river, offset)
|
||||
self._pending_time_offset += offset
|
||||
self._river_scenario_cache.clear()
|
||||
self.use_date(new_date)
|
||||
|
||||
@property
|
||||
def date(self):
|
||||
return self._date
|
||||
@@ -217,8 +234,7 @@ class Study(SQLModel):
|
||||
me.name = name
|
||||
me.description = description
|
||||
if date is not None:
|
||||
me.use_date()
|
||||
me.date = date
|
||||
me.use_date(date)
|
||||
return me
|
||||
|
||||
@classmethod
|
||||
@@ -395,12 +411,19 @@ class Study(SQLModel):
|
||||
lambda a, s: a or (s.parent is scenario),
|
||||
new.scenarios.lst,
|
||||
False
|
||||
):
|
||||
) or scenario.is_ensemble():
|
||||
new.status.set_as_read_only()
|
||||
|
||||
data["scenario"] = scenario
|
||||
data["loaded_pid"] = set()
|
||||
|
||||
# Get ensemble distribution
|
||||
new._ens_distributions = DistributionList._db_load(
|
||||
sql_exec, data=data
|
||||
)
|
||||
|
||||
data["ens_distributions"] = new._ens_distributions
|
||||
|
||||
# Load river data
|
||||
new._river = River._db_load(
|
||||
sql_exec, data=data
|
||||
@@ -461,8 +484,38 @@ class Study(SQLModel):
|
||||
)
|
||||
progress()
|
||||
|
||||
if self._pending_time_offset:
|
||||
self._db.execute('SAVEPOINT shift_time_origin')
|
||||
try:
|
||||
shift_database_times(self._db, self._pending_time_offset)
|
||||
self._db.execute('RELEASE SAVEPOINT shift_time_origin')
|
||||
except Exception:
|
||||
self._db.execute('ROLLBACK TO SAVEPOINT shift_time_origin')
|
||||
self._db.execute('RELEASE SAVEPOINT shift_time_origin')
|
||||
raise
|
||||
self._pending_time_offset = 0.0
|
||||
|
||||
if self.status.scenario.is_ensemble():
|
||||
lst = [
|
||||
self.scenarios, self._ens_distributions,
|
||||
self._river._ensembles,
|
||||
]
|
||||
for solv in self._river._results:
|
||||
lst.append(self._river._results[solv])
|
||||
|
||||
self._save_submodel(
|
||||
lst, data=progress
|
||||
)
|
||||
progress()
|
||||
self.commit()
|
||||
|
||||
return
|
||||
|
||||
self._save_submodel(
|
||||
[self.scenarios, self._river],
|
||||
[
|
||||
self.scenarios, self._ens_distributions,
|
||||
self._river
|
||||
],
|
||||
data=progress
|
||||
)
|
||||
|
||||
@@ -580,7 +633,8 @@ class Study(SQLModel):
|
||||
data = {
|
||||
"status": self.status,
|
||||
"loaded_pid": set(),
|
||||
"scenario": scenario
|
||||
"scenario": scenario,
|
||||
"ens_distributions": self._ens_distributions,
|
||||
}
|
||||
|
||||
self.status.start_loading()
|
||||
@@ -595,6 +649,9 @@ class Study(SQLModel):
|
||||
self.status.stop_loading()
|
||||
self.status.scenario = old_scenario
|
||||
|
||||
if self._pending_time_offset:
|
||||
shift_river_times(river, self._pending_time_offset)
|
||||
|
||||
# FIXME: Disable scenario cache to save memory usage
|
||||
# self._river_scenario_cache[scenario] = river
|
||||
|
||||
@@ -654,6 +711,7 @@ class Study(SQLModel):
|
||||
self.status.scenario.y + 100)
|
||||
|
||||
new.name = self.status.scenario.name + " (copy)"
|
||||
new.is_ensemble = self.status.scenario.is_ensemble
|
||||
|
||||
self.status.scenario = new
|
||||
self.river._data_traversal(
|
||||
@@ -665,6 +723,25 @@ class Study(SQLModel):
|
||||
self.status.set_as_editable()
|
||||
return new
|
||||
|
||||
def create_ensemble_scenario(self, pos=None, switch=True):
|
||||
new = self.scenarios.new(
|
||||
self.status.scenario,
|
||||
is_ensemble=True
|
||||
)
|
||||
|
||||
new.name = self.status.scenario.name + " (ensemble)"
|
||||
if pos is not None:
|
||||
new.set_pos(pos.x(), pos.y())
|
||||
else:
|
||||
new.set_pos(self.status.scenario.x + 100,
|
||||
self.status.scenario.y)
|
||||
|
||||
if switch:
|
||||
self.status.scenario = new
|
||||
|
||||
self.status.set_as_read_only()
|
||||
return new
|
||||
|
||||
@property
|
||||
def results(self):
|
||||
return self._river.results
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Shift temporal series when preserving calendar dates across a new origin."""
|
||||
from Model.BoundaryCondition.BoundaryCondition import BoundaryCondition
|
||||
from Model.LateralContribution.LateralContribution import LateralContribution
|
||||
from Model.WeatherParameters.WeatherParameters import WeatherParameters
|
||||
from Model.BoundaryConditionsAdisTS.BoundaryConditionAdisTS import (
|
||||
BoundaryConditionAdisTS
|
||||
)
|
||||
from Model.LateralContributionsAdisTS.LateralContributionAdisTS import (
|
||||
LateralContributionAdisTS
|
||||
)
|
||||
from Model.BoundaryConditionsTemperature.BoundaryConditionTemperature import (
|
||||
BoundaryConditionTemperature
|
||||
)
|
||||
|
||||
|
||||
def shift_river_times(river, offset):
|
||||
changes = []
|
||||
seen = set()
|
||||
|
||||
def collect(obj, data):
|
||||
temporal = isinstance(obj, (
|
||||
BoundaryConditionAdisTS,
|
||||
LateralContributionAdisTS,
|
||||
BoundaryConditionTemperature
|
||||
))
|
||||
if isinstance(obj, (
|
||||
BoundaryCondition, LateralContribution, WeatherParameters
|
||||
)):
|
||||
temporal = bool(obj.header) and obj.header[0] == 'time'
|
||||
if temporal:
|
||||
for point in obj._data:
|
||||
if id(point) not in seen:
|
||||
changes.append((point, float(point[0]) + offset))
|
||||
seen.add(id(point))
|
||||
|
||||
river._data_traversal(modifier=collect)
|
||||
for point, value in changes:
|
||||
# This is a global change of origin, not a scenario-specific edit.
|
||||
point[0] = value
|
||||
|
||||
|
||||
def shift_database_times(connection, offset):
|
||||
tables = [
|
||||
(
|
||||
'boundary_condition_data', 'boundary_condition',
|
||||
'bc', BoundaryCondition
|
||||
),
|
||||
(
|
||||
'lateral_contribution_data', 'lateral_contribution',
|
||||
'lc', LateralContribution
|
||||
),
|
||||
(
|
||||
'weather_parameters_data', 'weather_parameters',
|
||||
'wp', WeatherParameters
|
||||
),
|
||||
('boundary_condition_data_adists', None, None, None),
|
||||
('lateral_contribution_data_adists', None, None, None),
|
||||
('boundary_condition_data_temperature', None, None, None),
|
||||
]
|
||||
for table, parent, fk, model in tables:
|
||||
if model is None:
|
||||
rows = connection.execute(
|
||||
f'SELECT rowid, data0 FROM {table}'
|
||||
).fetchall()
|
||||
else:
|
||||
rows = []
|
||||
for kind, in connection.execute(
|
||||
f'SELECT DISTINCT type FROM {parent}'
|
||||
):
|
||||
headers = model._get_ctor_from_type(kind)().header
|
||||
if not headers or headers[0] != 'time':
|
||||
continue
|
||||
rows.extend(connection.execute(
|
||||
f'SELECT d.rowid, d.data0 FROM {table} d JOIN {parent} p '
|
||||
f'ON p.pamhyr_id=d.{fk} AND p.scenario=d.scenario '
|
||||
f'WHERE p.type=?',
|
||||
(kind,)
|
||||
).fetchall())
|
||||
connection.executemany(
|
||||
f'UPDATE {table} SET data0=? WHERE rowid=?',
|
||||
[(float(value) + offset, rowid) for rowid, value in rows]
|
||||
)
|
||||
@@ -185,6 +185,13 @@ class SQLSubModel(PamhyrID):
|
||||
else:
|
||||
self._owner_scenario = owner_scenario
|
||||
|
||||
def __str__(self):
|
||||
t = type(self)
|
||||
return (
|
||||
f"'{t.__module__}.{t.__name__}" +
|
||||
f"@{self._pamhyr_id}.{self._owner_scenario}'"
|
||||
)
|
||||
|
||||
def must_be_saved(self):
|
||||
"""Return True if this object MUST be save in the save file.
|
||||
|
||||
|
||||
@@ -341,7 +341,7 @@ class WeatherParameters(SQLSubModel):
|
||||
created = False
|
||||
|
||||
if major == "0" and (int(minor) < 2 or
|
||||
(int(minor) == 2 and int(release) <= 7)):
|
||||
(int(minor) == 2 and int(release) < 10)):
|
||||
if not cls.is_table_exists(execute, "air_temperature"):
|
||||
cls._db_create(execute)
|
||||
created = True
|
||||
|
||||
+6
-1
@@ -25,6 +25,7 @@ from PyQt5.QtCore import QProcess
|
||||
|
||||
from Scripts.AScript import AScript
|
||||
from Model.Study import Study
|
||||
from View.RunSolver.Translate import RunSolverTranslate
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
@@ -89,12 +90,16 @@ class ScriptRun(AScript):
|
||||
|
||||
# Export and Run
|
||||
logger.info(f"~Export~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
||||
solver.export(study, workdir, qlog=self._q)
|
||||
ok = solver.export(study, workdir, qlog=self._q)
|
||||
|
||||
while self._q.qsize() != 0:
|
||||
s = self._q.get()
|
||||
logger.info(s)
|
||||
|
||||
if not ok:
|
||||
logger.warning(RunSolverTranslate()["export_failed"])
|
||||
return
|
||||
|
||||
if command == "run":
|
||||
logger.info(f"~Run~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
||||
solver.run(
|
||||
|
||||
@@ -19,8 +19,9 @@
|
||||
import os
|
||||
import logging
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from tools import timer, parse_command_line, get_version, logger_exception
|
||||
from tools import parse_datetime
|
||||
|
||||
try:
|
||||
# Installation allow Unix-like signal
|
||||
@@ -158,11 +159,15 @@ class CommandLineSolver(AbstractSolver):
|
||||
txt = add_file.text
|
||||
txt = txt.replace("@version", get_version())
|
||||
txt = txt.replace("@date", datetime.now().isoformat(sep=" "))
|
||||
txt = self._prepare_additional_file_text(add_file.path, txt)
|
||||
|
||||
f.write(txt)
|
||||
|
||||
return files
|
||||
|
||||
def _prepare_additional_file_text(self, path, text):
|
||||
return text
|
||||
|
||||
def export_study_description(self, study, repertory, qlog, name="0"):
|
||||
files = []
|
||||
|
||||
|
||||
+276
-12
@@ -28,6 +28,7 @@ from tools import timer, trace, logger_exception
|
||||
from Solver.CommandLine import CommandLineSolver
|
||||
from Checker.Mage import (
|
||||
MageNetworkGraphChecker, MageGeometryGuideLineChecker,
|
||||
MageLateralSolidChecker,
|
||||
)
|
||||
|
||||
from Model.Results.Results import Results
|
||||
@@ -106,6 +107,7 @@ class Mage(CommandLineSolver):
|
||||
MageNetworkGraphChecker(connectivity=True, version=cls._type),
|
||||
MageNetworkGraphChecker(connectivity=False, version=cls._type),
|
||||
MageGeometryGuideLineChecker(version=cls._type),
|
||||
MageLateralSolidChecker(version=cls._type),
|
||||
]
|
||||
|
||||
return lst
|
||||
@@ -303,7 +305,7 @@ class Mage(CommandLineSolver):
|
||||
# Point line
|
||||
wfile.write(f"{x} {y} {z} {n} {sediment}\n")
|
||||
|
||||
def _export_BC(self, t, bounds, repertory, qlog, name="0"):
|
||||
def _export_BC(self, study, t, bounds, repertory, qlog, name="0"):
|
||||
files = []
|
||||
|
||||
if len(bounds) == 0:
|
||||
@@ -333,7 +335,7 @@ class Mage(CommandLineSolver):
|
||||
v1 = d[1]
|
||||
|
||||
if t in ["HYD", "LIM"]:
|
||||
v0 /= 60 # Convert first column to minute
|
||||
v0 /= 60 # Convert first column to minutes
|
||||
|
||||
f.write(f"{v0:9} {v1:9} \n")
|
||||
|
||||
@@ -365,10 +367,17 @@ class Mage(CommandLineSolver):
|
||||
elif bound.bctype == "SL":
|
||||
QSO.append(bound)
|
||||
|
||||
files = files + self._export_BC("AVA", AVA, repertory, qlog, name=name)
|
||||
files = files + self._export_BC("HYD", HYD, repertory, qlog, name=name)
|
||||
files = files + self._export_BC("LIM", LIM, repertory, qlog, name=name)
|
||||
files = files + self._export_QSO(QSO, repertory, qlog, name=name)
|
||||
files = files + self._export_BC(
|
||||
study, "AVA", AVA, repertory, qlog, name=name
|
||||
)
|
||||
files = files + self._export_BC(
|
||||
study, "HYD", HYD, repertory, qlog, name=name
|
||||
)
|
||||
files = files + self._export_BC(
|
||||
study, "LIM", LIM, repertory, qlog, name=name
|
||||
)
|
||||
files = files + self._export_QSO(study, QSO, repertory,
|
||||
qlog, name=name)
|
||||
|
||||
return files
|
||||
|
||||
@@ -384,7 +393,7 @@ class Mage(CommandLineSolver):
|
||||
qlog.put(f"Export LAT file")
|
||||
files.append(f"{name}.LAT")
|
||||
|
||||
for tab in ["liquid", "solid", "suspenssion"]:
|
||||
for tab in ["liquid"]:
|
||||
for lateral in lst.get_tab(tab):
|
||||
self._export_LC(study, lateral, f, qlog)
|
||||
|
||||
@@ -422,10 +431,11 @@ class Mage(CommandLineSolver):
|
||||
if d.is_deleted():
|
||||
continue
|
||||
|
||||
time = d[0]
|
||||
if lateral.lctype in ["EV"]:
|
||||
f.write(f"{d[0]:10.3f}{-d[1]:10.3f}\n")
|
||||
f.write(f"{time:10.3f}{-d[1]:10.3f}\n")
|
||||
else:
|
||||
f.write(f"{d[0]:10.3f}{d[1]:10.3f}\n")
|
||||
f.write(f"{time:10.3f}{d[1]:10.3f}\n")
|
||||
|
||||
def _export_RUG(self, study, repertory, qlog, name="0"):
|
||||
files = []
|
||||
@@ -686,6 +696,23 @@ class Mage(CommandLineSolver):
|
||||
|
||||
return res
|
||||
|
||||
def _prepare_additional_file_text(self, path, text):
|
||||
if os.path.splitext(path)[1].lower() != ".var":
|
||||
return text
|
||||
|
||||
lines = []
|
||||
for line in text.splitlines(keepends=True):
|
||||
stripped = line.lstrip()
|
||||
fields = stripped.split()
|
||||
if stripped.startswith("$"):
|
||||
# MAGE only recognizes rule markers in the first column.
|
||||
line = stripped
|
||||
elif (not stripped.startswith("*") and len(fields) >= 2
|
||||
and fields[1] == "W2Z"):
|
||||
line = "$ " + stripped
|
||||
lines.append(line)
|
||||
return "".join(lines)
|
||||
|
||||
def _export_VAR(self, study, repertory, qlog, name="0"):
|
||||
files = []
|
||||
|
||||
@@ -736,9 +763,11 @@ class Mage(CommandLineSolver):
|
||||
name = bhs.name
|
||||
if name == "":
|
||||
name = f"HS_{bhs.id:>3}".replace(" ", "0")
|
||||
else:
|
||||
name = name.replace(" ", "_")
|
||||
|
||||
f.write(
|
||||
f"${name} clapet"
|
||||
f"${name} clapet\n"
|
||||
)
|
||||
return files
|
||||
|
||||
@@ -964,7 +993,7 @@ class Mage8(Mage):
|
||||
|
||||
return files
|
||||
|
||||
def _export_QSO(self, bounds, repertory, qlog, name="0"):
|
||||
def _export_QSO(self, study, bounds, repertory, qlog, name="0"):
|
||||
files = []
|
||||
|
||||
if len(bounds) == 0:
|
||||
@@ -994,7 +1023,8 @@ class Mage8(Mage):
|
||||
|
||||
# Data
|
||||
for d in bound.data:
|
||||
f.write(f"{d[0]/60:10.3f}{d[1]:10.3f}\n")
|
||||
time = d[0] / 60
|
||||
f.write(f"{time:10.3f}{d[1]:10.3f}\n")
|
||||
|
||||
return files
|
||||
|
||||
@@ -1035,6 +1065,75 @@ class Mage8(Mage):
|
||||
logger_exception(e)
|
||||
return False
|
||||
|
||||
def export_ensemble_variation(self, study, repertory,
|
||||
qlog=None, name="0",
|
||||
samples=None):
|
||||
self._study = study
|
||||
name = study.name.replace(" ", "_")
|
||||
|
||||
var_samples = self._export_ensemble_RUG(
|
||||
study, repertory,
|
||||
qlog, name=name,
|
||||
samples=samples,
|
||||
)
|
||||
|
||||
return var_samples
|
||||
|
||||
def _export_ensemble_RUG(self, study, repertory,
|
||||
qlog, name="0",
|
||||
samples={}):
|
||||
files = []
|
||||
var_samples = []
|
||||
|
||||
for ens in samples:
|
||||
if ens.target_data is None:
|
||||
continue
|
||||
|
||||
x = next(samples[ens])
|
||||
var_samples.append(x)
|
||||
|
||||
qlog.put(f"*** Variation " +
|
||||
f"'{ens.target_data}' - {ens.data_type} x {x}")
|
||||
|
||||
if ens.data_type == "strickler_minor":
|
||||
ens.target_data.minor = x
|
||||
elif ens.data_type == "strickler_medium":
|
||||
ens.target_data.medium = x
|
||||
|
||||
if qlog is not None:
|
||||
qlog.put("Export variation of RUG file")
|
||||
|
||||
# Write header
|
||||
with mage_file_open(os.path.join(repertory, f"{name}.RUG"), "w+") as f:
|
||||
files.append(f"{name}.RUG")
|
||||
|
||||
edges = study.river.enable_edges()
|
||||
|
||||
id = 1
|
||||
for edge in edges:
|
||||
frictions = edge.frictions
|
||||
|
||||
for friction in frictions.frictions:
|
||||
if friction.begin_strickler is None:
|
||||
continue
|
||||
|
||||
if friction.is_deleted():
|
||||
continue
|
||||
|
||||
num = f"{id:>3}"
|
||||
brk = f"{friction.begin_rk:>10.3f}"
|
||||
erk = f"{friction.end_rk:>10.3f}"
|
||||
|
||||
strickler = friction.begin_strickler
|
||||
coef_1 = f"{strickler.minor:>10.3f}"
|
||||
coef_2 = f"{strickler.medium:>10.3f}"
|
||||
|
||||
f.write(f"K{num} {brk}{erk}{coef_1}{coef_2}\n")
|
||||
|
||||
id += 1
|
||||
|
||||
return var_samples
|
||||
|
||||
###########
|
||||
# RESULTS #
|
||||
###########
|
||||
@@ -1465,6 +1564,171 @@ class Mage8(Mage):
|
||||
|
||||
return results
|
||||
|
||||
@timer
|
||||
def read_ensemble_bin(self, study, fname, tables, run_number, qlog=None):
|
||||
logger.info(f"read_ensemble_bin: Start reading '{fname}' ...")
|
||||
start = time.time()
|
||||
|
||||
with mage_file_open(fname, "r") as f:
|
||||
def newline(): return np.fromfile(f, dtype=np.int32, count=1)
|
||||
def endline(): return np.fromfile(f, dtype=np.int32, count=1)
|
||||
|
||||
def read_int(size): return np.fromfile(
|
||||
f, dtype=np.int32, count=size)
|
||||
|
||||
def read_float(size): return np.fromfile(
|
||||
f, dtype=np.float32, count=size)
|
||||
|
||||
def read_float64(size): return np.fromfile(
|
||||
f, dtype=np.float64, count=size)
|
||||
|
||||
# Meta data (1st line)
|
||||
newline()
|
||||
data = read_int(3)
|
||||
|
||||
nb_reach = data[0]
|
||||
nb_profile = data[1]
|
||||
mage_version = data[2]
|
||||
|
||||
if mage_version <= 80:
|
||||
msg = (
|
||||
"Read BIN files: " +
|
||||
f"Possible incompatible mage version '{mage_version}', " +
|
||||
"please check your solver configuration..."
|
||||
)
|
||||
logger.warning(msg)
|
||||
|
||||
if qlog is not None:
|
||||
qlog.put("[WARNING] " + msg)
|
||||
|
||||
endline()
|
||||
|
||||
# Reach information (2nd line)
|
||||
newline()
|
||||
_ = read_int(2*nb_reach)
|
||||
endline()
|
||||
|
||||
# X (3rd line)
|
||||
newline()
|
||||
_ = read_float(nb_profile)
|
||||
endline()
|
||||
|
||||
# Z and Y (4th line)
|
||||
newline()
|
||||
_ = read_float(3*nb_profile)
|
||||
endline()
|
||||
|
||||
# Data
|
||||
newline()
|
||||
|
||||
ts = set()
|
||||
|
||||
tmp_table = {}
|
||||
end = False
|
||||
while not end:
|
||||
n = read_int(1)[0]
|
||||
timestamp = read_float64(1)[0]
|
||||
key = bytearray(
|
||||
np.fromfile(
|
||||
f, dtype=np.byte, count=1
|
||||
)
|
||||
).decode()
|
||||
data = read_float(n)
|
||||
|
||||
if key not in tmp_table:
|
||||
tmp_table[key] = []
|
||||
|
||||
tmp_table[key].append(data)
|
||||
|
||||
ts.add(timestamp)
|
||||
|
||||
endline()
|
||||
end = newline().size <= 0
|
||||
|
||||
table = {}
|
||||
for k in tmp_table:
|
||||
table[k] = np.array(tmp_table[k])
|
||||
|
||||
self.read_ensemble_bin_agregate_data(
|
||||
table, tables, run_number
|
||||
)
|
||||
|
||||
tables["timestamps"] = ts
|
||||
|
||||
logger.info(f"reading time: '{time.time() - start}'")
|
||||
|
||||
def read_ensemble_bin_agregate_data(self, tables, res, run_number):
|
||||
z = tables["Z"]
|
||||
q = tables["Q"]
|
||||
|
||||
if "z_mean" not in res:
|
||||
res["z_mean"] = z
|
||||
res["q_mean"] = q
|
||||
|
||||
res["z_tmp_M2"] = np.zeros(z.shape)
|
||||
res["q_tmp_M2"] = np.zeros(q.shape)
|
||||
|
||||
res["z_std_derivation"] = np.zeros(z.shape)
|
||||
res["q_std_derivation"] = np.zeros(q.shape)
|
||||
|
||||
res["z_min"] = z
|
||||
res["z_max"] = z
|
||||
|
||||
res["q_min"] = q
|
||||
res["q_max"] = q
|
||||
else:
|
||||
# Get mean results for Z and Q
|
||||
n = run_number
|
||||
for x, txt in [(z, "z"), (q, "q")]:
|
||||
t_mean = f"{txt}_mean"
|
||||
t_M2 = f"{txt}_tmp_M2"
|
||||
t_std_deriv = f"{txt}_std_derivation"
|
||||
|
||||
delta = x - res[t_mean]
|
||||
|
||||
res[t_mean] += delta / n
|
||||
|
||||
delta_2 = x - res[t_mean]
|
||||
|
||||
res[t_M2] += delta * delta_2
|
||||
res[t_std_deriv] = np.sqrt(res[t_M2] / n)
|
||||
|
||||
# Z and Q min max values
|
||||
res["z_min"] = np.minimum(z, res["z_min"])
|
||||
res["z_max"] = np.maximum(z, res["z_max"])
|
||||
res["q_min"] = np.minimum(q, res["q_min"])
|
||||
res["q_max"] = np.maximum(q, res["q_max"])
|
||||
|
||||
@timer
|
||||
def results_ensemble(self, study, repertory,
|
||||
tables, run_number,
|
||||
qlog=None, name=None):
|
||||
self._study = study
|
||||
if name is None:
|
||||
name = study.name.replace(" ", "_")
|
||||
|
||||
fname = os.path.join(repertory, f"{name}.BIN".replace(" ", "_"))
|
||||
if not os.path.isfile(fname):
|
||||
logger.info(f"Result file {name}.BIN does not exist")
|
||||
return None
|
||||
try:
|
||||
self.read_ensemble_bin(study, fname, tables, run_number, qlog)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to read results")
|
||||
logger_exception(e)
|
||||
return None
|
||||
|
||||
return True
|
||||
|
||||
def get_ensemble_empty_results(self, study, repertory, name=None):
|
||||
return Results(
|
||||
study=study,
|
||||
solver=self,
|
||||
repertory=repertory,
|
||||
name=name,
|
||||
is_ensemble=True,
|
||||
)
|
||||
|
||||
|
||||
class MageFake7(Mage8):
|
||||
_type = "mage_fake7"
|
||||
|
||||
+1388
-389
File diff suppressed because it is too large.
Load diff
@@ -35,8 +35,7 @@ solver_long_name = {
|
||||
# "mage_fake7": "Mage fake v7",
|
||||
"adistswc": "Adis-TS_WC",
|
||||
"adisttwc": "Adis-TT_WC",
|
||||
# "rubarbe": "RubarBE",
|
||||
"rubar3": "Rubar3",
|
||||
"rubarbe": "RubarBE",
|
||||
}
|
||||
|
||||
solver_type_list = {
|
||||
@@ -46,6 +45,5 @@ solver_type_list = {
|
||||
# "mage_fake7": MageFake7,
|
||||
"adistswc": AdisTSwc,
|
||||
"adisttwc": AdisTTwc,
|
||||
# "rubarbe": RubarBE,
|
||||
"rubar3": Rubar3,
|
||||
"rubarbe": RubarBE,
|
||||
}
|
||||
@@ -94,11 +94,12 @@ class TableModel(PamhyrTableModel):
|
||||
v = v.replace(',', '.')
|
||||
value = f"{float(v):.4f}"
|
||||
elif self._data.header[column] == "time":
|
||||
if self._opt_data == "time":
|
||||
if self.time_system == "time":
|
||||
value = timestamp_to_old_pamhyr_date(int(v))
|
||||
else:
|
||||
value = format_datetime(
|
||||
datetime(1970, 1, 1) + timedelta(seconds=float(v))
|
||||
parse_datetime(self.start_date)
|
||||
+ timedelta(seconds=float(v))
|
||||
)
|
||||
else:
|
||||
value = f"{v}"
|
||||
@@ -117,8 +118,8 @@ class TableModel(PamhyrTableModel):
|
||||
|
||||
try:
|
||||
if (self._data.header[column] == "time"
|
||||
and self._opt_data == "date"):
|
||||
value = self.date_to_timestamp(value)
|
||||
and self.time_system == "date"):
|
||||
value = self.date_to_elapsed_seconds(value)
|
||||
|
||||
row = self.get_true_data_row(row)
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
import logging
|
||||
|
||||
from Modules import Modules
|
||||
|
||||
from tools import timer, trace
|
||||
|
||||
from numpy import sqrt
|
||||
@@ -174,7 +176,7 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
||||
data=self._data,
|
||||
undo=self._undo_stack,
|
||||
opt_data=self._study.time_system,
|
||||
start_date=self._study.date
|
||||
study=self._study
|
||||
)
|
||||
|
||||
table.setModel(self._table)
|
||||
@@ -186,7 +188,10 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
||||
self.canvas = MplCanvas(width=5, height=4, dpi=100)
|
||||
self.canvas.setObjectName("canvas")
|
||||
self.toolbar = PamhyrPlotToolbar(
|
||||
self.canvas, self
|
||||
self.canvas, self, items=[
|
||||
"home", "move", "zoom", "save",
|
||||
"iso", "back/forward"
|
||||
]
|
||||
)
|
||||
self.verticalLayout.addWidget(self.toolbar)
|
||||
self.verticalLayout.addWidget(self.canvas)
|
||||
@@ -262,6 +267,11 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
||||
self._d50sigma.set_d50(self._data.d50)
|
||||
self._d50sigma.set_sigma(self._data.sigma)
|
||||
|
||||
def _propagated_update(self, key=Modules(0)):
|
||||
if Modules.STUDY in key:
|
||||
self._table.layoutChanged.emit()
|
||||
self.plot.update()
|
||||
|
||||
def update(self):
|
||||
self.plot.update()
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ class DelCommand(QUndoCommand):
|
||||
self._bcs.insert(self._tab, row, el)
|
||||
|
||||
def redo(self):
|
||||
self._bcs.delete_i(self._tab, self._rows)
|
||||
self._bcs.delete(self._tab, [el for _, el in self._bc])
|
||||
|
||||
|
||||
class SortCommand(QUndoCommand):
|
||||
|
||||
@@ -21,6 +21,7 @@ import traceback
|
||||
|
||||
from datetime import date, time, datetime, timedelta
|
||||
|
||||
from tools import parse_datetime
|
||||
from tools import (
|
||||
trace, timer,
|
||||
timestamp_to_old_pamhyr_date,
|
||||
@@ -84,11 +85,12 @@ class TableModel(PamhyrTableModel):
|
||||
if self._data._types[column] == float:
|
||||
value = f"{v:.4f}"
|
||||
elif self._data.header[column] == "time":
|
||||
if self._opt_data == "time":
|
||||
if self.time_system == "time":
|
||||
value = timestamp_to_old_pamhyr_date(int(v))
|
||||
else:
|
||||
value = format_datetime(
|
||||
datetime(1970, 1, 1) + timedelta(seconds=float(v))
|
||||
parse_datetime(self.start_date)
|
||||
+ timedelta(seconds=float(v))
|
||||
)
|
||||
else:
|
||||
value = f"{v}"
|
||||
@@ -107,8 +109,8 @@ class TableModel(PamhyrTableModel):
|
||||
|
||||
try:
|
||||
if (self._data.header[column] == "time"
|
||||
and self._opt_data == "date"):
|
||||
value = self.date_to_timestamp(value)
|
||||
and self.time_system == "date"):
|
||||
value = self.date_to_elapsed_seconds(value)
|
||||
|
||||
row = self.get_true_data_row(row)
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
import logging
|
||||
|
||||
from Modules import Modules
|
||||
|
||||
from tools import timer, trace
|
||||
|
||||
from View.Tools.PamhyrWindow import PamhyrWindow
|
||||
@@ -129,7 +131,7 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
||||
data=self._data,
|
||||
undo=self._undo_stack,
|
||||
opt_data=self._study.time_system,
|
||||
start_date=self._study.date
|
||||
study=self._study
|
||||
)
|
||||
|
||||
table.setModel(self._table)
|
||||
@@ -162,6 +164,11 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
||||
self.find(QAction, "action_sort").triggered.connect(self.sort)
|
||||
self._table.dataChanged.connect(self.update)
|
||||
|
||||
def _propagated_update(self, key=Modules(0)):
|
||||
if Modules.STUDY in key:
|
||||
self._table.layoutChanged.emit()
|
||||
self.plot.update()
|
||||
|
||||
def update(self):
|
||||
self.plot.update()
|
||||
self.plot.fit_to_data()
|
||||
|
||||
@@ -21,6 +21,7 @@ import traceback
|
||||
|
||||
from datetime import date, time, datetime, timedelta
|
||||
|
||||
from tools import parse_datetime
|
||||
from tools import (
|
||||
trace, timer,
|
||||
timestamp_to_old_pamhyr_date,
|
||||
@@ -84,11 +85,12 @@ class TableModel(PamhyrTableModel):
|
||||
if self._data._types[column] == float:
|
||||
value = f"{v:.2f}"
|
||||
elif self._data.header[column] == "time":
|
||||
if self._opt_data == "time":
|
||||
if self.time_system == "time":
|
||||
value = timestamp_to_old_pamhyr_date(int(v))
|
||||
else:
|
||||
value = format_datetime(
|
||||
datetime(1970, 1, 1) + timedelta(seconds=float(v))
|
||||
parse_datetime(self.start_date)
|
||||
+ timedelta(seconds=float(v))
|
||||
)
|
||||
else:
|
||||
value = f"{v}"
|
||||
@@ -107,8 +109,8 @@ class TableModel(PamhyrTableModel):
|
||||
|
||||
try:
|
||||
if (self._data.header[column] == "time"
|
||||
and self._opt_data == "date"):
|
||||
value = self.date_to_timestamp(value)
|
||||
and self.time_system == "date"):
|
||||
value = self.date_to_elapsed_seconds(value)
|
||||
|
||||
row = self.get_true_data_row(row)
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
import logging
|
||||
|
||||
from Modules import Modules
|
||||
|
||||
from tools import timer, trace
|
||||
|
||||
from View.Tools.PamhyrWindow import PamhyrWindow
|
||||
@@ -118,7 +120,7 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
||||
data=self._data,
|
||||
undo=self._undo_stack,
|
||||
opt_data=self._study.time_system,
|
||||
start_date=self._study.date
|
||||
study=self._study
|
||||
)
|
||||
|
||||
table.setModel(self._table)
|
||||
@@ -151,6 +153,11 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
||||
self.find(QAction, "action_sort").triggered.connect(self.sort)
|
||||
self._table.dataChanged.connect(self.update)
|
||||
|
||||
def _propagated_update(self, key=Modules(0)):
|
||||
if Modules.STUDY in key:
|
||||
self._table.layoutChanged.emit()
|
||||
self.plot.update()
|
||||
|
||||
def update(self):
|
||||
self.plot.update()
|
||||
self.plot.fit_to_data()
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import psutil
|
||||
import logging
|
||||
import traceback
|
||||
|
||||
@@ -120,7 +122,10 @@ class TimerWindow(PamhyrWindow):
|
||||
parent=parent
|
||||
)
|
||||
|
||||
self._process = psutil.Process(os.getpid())
|
||||
|
||||
self.setup_table()
|
||||
self.setup_label()
|
||||
self.setup_alarm()
|
||||
self.setup_connections()
|
||||
|
||||
@@ -136,6 +141,15 @@ class TimerWindow(PamhyrWindow):
|
||||
data=None,
|
||||
)
|
||||
|
||||
def setup_label(self):
|
||||
label = self.find(QLabel, "label")
|
||||
label.setText(
|
||||
f" Memory usage:\t" +
|
||||
"<b>" +
|
||||
f"{self._process.memory_info().rss / (1000 * 1000):.3f}" +
|
||||
"</b> MB"
|
||||
)
|
||||
|
||||
def setup_alarm(self):
|
||||
self._alarm = QTimer()
|
||||
self._alarm.start(2000)
|
||||
@@ -148,6 +162,7 @@ class TimerWindow(PamhyrWindow):
|
||||
|
||||
def update(self):
|
||||
self._table.update_lst()
|
||||
self.setup_label()
|
||||
|
||||
# def reset(self):
|
||||
# self._table.reset_timers()
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
# Translate.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from PyQt5.QtCore import QCoreApplication
|
||||
|
||||
from View.Ensembles.Translate import EnsemblesTranslate
|
||||
|
||||
_translate = QCoreApplication.translate
|
||||
|
||||
|
||||
class EnsembleEditTranslate(EnsemblesTranslate):
|
||||
def __init__(self):
|
||||
super(EnsembleEditTranslate, self).__init__()
|
||||
|
||||
self._dict["binomial_n"] = _translate("Ensemble", "n")
|
||||
self._dict["binomial_p"] = _translate("Ensemble", "p")
|
||||
|
||||
self._dict["poisson_lam"] = _translate("Ensemble", "Lam")
|
||||
|
||||
self._dict["checker_failed_title"] = _translate(
|
||||
"Ensemble",
|
||||
"Invalid parameter"
|
||||
)
|
||||
self._dict["checker_failed_text"] = _translate(
|
||||
"Ensemble",
|
||||
"This parameter is not valid for selected distribution: "
|
||||
)
|
||||
|
||||
uniform = _translate(
|
||||
"Ensemble", "(High - Low) must be non-negative."
|
||||
)
|
||||
self._dict["uniform_low_tips"] = uniform
|
||||
self._dict["uniform_high_tips"] = uniform
|
||||
|
||||
self._dict["normal_scale_tips"] = _translate(
|
||||
"Ensemble", "Scale must be non-negative."
|
||||
)
|
||||
|
||||
self._dict["binomial_n_tips"] = _translate(
|
||||
"Ensemble", "N must be non-negative and must be an integers."
|
||||
)
|
||||
|
||||
self._dict["binomial_p_tips"] = _translate(
|
||||
"Ensemble", "P must be >= 0 and <=1."
|
||||
)
|
||||
|
||||
self._dict["poisson_lam_tips"] = _translate(
|
||||
"Ensemble", "Lam must be >= 0."
|
||||
)
|
||||
@@ -0,0 +1,320 @@
|
||||
# Window.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
|
||||
from tools import trace, timer, logger_exception
|
||||
|
||||
from View.Tools.PamhyrWindow import PamhyrWindow, PamhyrDialog
|
||||
from View.Tools.PamhyrWidget import PamhyrWidget
|
||||
from View.Tools.PamhyrTree import (
|
||||
PamhyrModelItem, PamhyrModelListItem,
|
||||
)
|
||||
|
||||
from PyQt5.QtGui import (
|
||||
QKeySequence,
|
||||
)
|
||||
|
||||
from PyQt5 import QtWidgets
|
||||
from PyQt5.QtCore import (
|
||||
Qt, QVariant, QAbstractTableModel,
|
||||
QCoreApplication, QModelIndex, pyqtSlot,
|
||||
QRect, QSettings,
|
||||
)
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialogButtonBox, QPushButton, QLineEdit,
|
||||
QFileDialog, QTableView, QAbstractItemView,
|
||||
QUndoStack, QShortcut, QAction, QItemDelegate,
|
||||
QComboBox, QVBoxLayout, QHeaderView, QTabWidget,
|
||||
QGroupBox, QTreeWidget,
|
||||
)
|
||||
|
||||
from View.Ensembles.Edit.Translate import EnsembleEditTranslate
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class StricklersCoefModelItem(PamhyrModelItem):
|
||||
def get_value(self):
|
||||
return (self._data, self.parent()._data)
|
||||
|
||||
|
||||
class StricklersModelItem(PamhyrModelItem):
|
||||
def __init__(self, data=None, trad=None, parent=None):
|
||||
super(StricklersModelItem, self).__init__(
|
||||
data=data, trad=trad, parent=parent,
|
||||
)
|
||||
|
||||
def _setup_children(self):
|
||||
for coef in ["strickler_minor", "strickler_medium"]:
|
||||
self.addChild(
|
||||
StricklersCoefModelItem(data=coef, parent=self)
|
||||
)
|
||||
|
||||
def get_value(self):
|
||||
return self._data
|
||||
|
||||
|
||||
class EnsembleEditDialog(PamhyrDialog):
|
||||
_pamhyr_ui = "EnsembleEditDialog"
|
||||
_pamhyr_name = "Parameters"
|
||||
|
||||
def __init__(self, study=None, ensemble=None,
|
||||
parent=None):
|
||||
trad = EnsembleEditTranslate()
|
||||
|
||||
super(EnsembleEditDialog, self).__init__(
|
||||
title=trad[self._pamhyr_name],
|
||||
trad=trad,
|
||||
options=[],
|
||||
parent=parent
|
||||
)
|
||||
|
||||
self._study = study
|
||||
self._ensemble = ensemble
|
||||
self._target_data = None
|
||||
|
||||
self._tree = self.find(QTreeWidget, "treeWidget_target_data")
|
||||
self._tg_group_box = self.find(QGroupBox, "groupBox_target_data")
|
||||
|
||||
self._init_tree()
|
||||
self._init_default_values()
|
||||
self._init_connection()
|
||||
|
||||
def _init_tree(self):
|
||||
self._tree.setColumnCount(1)
|
||||
self._tree.setHeaderLabels(["Name"])
|
||||
|
||||
stricklers = PamhyrModelListItem(
|
||||
name="Stricklers",
|
||||
lst=self._study.river.stricklers,
|
||||
child_item_ctor=StricklersModelItem,
|
||||
parent=self._tree
|
||||
)
|
||||
|
||||
self._target_data = (
|
||||
self._ensemble.data_type,
|
||||
self._ensemble.target_data
|
||||
)
|
||||
|
||||
self._tg_group_box.setTitle(
|
||||
self._format_target_data(self._target_data)
|
||||
)
|
||||
|
||||
item = stricklers.find_item_by_value(self._target_data)
|
||||
if item:
|
||||
self._tree.setCurrentItem(item)
|
||||
|
||||
def _init_default_values(self):
|
||||
self.set_line_edit_text("lineEdit_name", self._ensemble.name)
|
||||
|
||||
self.combobox_add_items(
|
||||
"comboBox_distribution",
|
||||
[self._trad["not_defined"]] +
|
||||
list(
|
||||
map(
|
||||
lambda d: d.name,
|
||||
self._study._ens_distributions.lst
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
self._params_widget = None
|
||||
if self._ensemble.distribution is not None:
|
||||
self.set_combobox_text("comboBox_distribution",
|
||||
self._ensemble.distribution.name)
|
||||
|
||||
self._set_widget(self._ensemble.distribution)
|
||||
|
||||
def _init_connection(self):
|
||||
self.find(QComboBox, "comboBox_distribution")\
|
||||
.currentTextChanged.connect(self.update_distribution)
|
||||
|
||||
self._tree.itemClicked.connect(self._tree_item_select)
|
||||
|
||||
def _tree_item_select(self, item):
|
||||
if type(item) is StricklersCoefModelItem:
|
||||
self._target_data = item.get_value()
|
||||
|
||||
self._tg_group_box.setTitle(
|
||||
self._format_target_data(self._target_data)
|
||||
)
|
||||
|
||||
def _format_target_data(self, data):
|
||||
return f" Selection: {str(data[1])}, {data[0]}"
|
||||
|
||||
def update_distribution(self, txt):
|
||||
# txt = self.get_combobox_text("comboBox_distribution")
|
||||
distribution = next(
|
||||
filter(
|
||||
lambda d: d.name == txt,
|
||||
self._study._ens_distributions.lst
|
||||
),
|
||||
None
|
||||
)
|
||||
|
||||
self._set_widget(distribution)
|
||||
|
||||
def _set_widget(self, distribution):
|
||||
box = self.find(QGroupBox, "groupBox_params")
|
||||
vbox = self.find(QVBoxLayout, "verticalLayout_params")
|
||||
|
||||
if self._params_widget is not None:
|
||||
vbox.removeWidget(self._params_widget)
|
||||
self._params_widget.setParent(None)
|
||||
|
||||
if distribution is None:
|
||||
return
|
||||
|
||||
size = len(distribution._labels)
|
||||
if size == 1:
|
||||
self._params_widget = Ensemble1ParamsWidget(
|
||||
ensemble=self._ensemble,
|
||||
distribution=distribution,
|
||||
trad=self._trad, parent=box,
|
||||
)
|
||||
vbox.addWidget(self._params_widget)
|
||||
elif size == 2:
|
||||
self._params_widget = Ensemble2ParamsWidget(
|
||||
ensemble=self._ensemble,
|
||||
distribution=distribution,
|
||||
trad=self._trad, parent=box,
|
||||
)
|
||||
vbox.addWidget(self._params_widget)
|
||||
else:
|
||||
self._params_widget = None
|
||||
|
||||
@property
|
||||
def values(self):
|
||||
return self._values
|
||||
|
||||
def accept(self):
|
||||
txt = self.get_combobox_text("comboBox_distribution")
|
||||
distribution = next(
|
||||
filter(
|
||||
lambda d: d.name == txt,
|
||||
self._study._ens_distributions.lst
|
||||
),
|
||||
None
|
||||
)
|
||||
parameters = self._params_widget.values
|
||||
|
||||
if distribution is not None:
|
||||
ok, tips = distribution.is_valid_parameters(parameters)
|
||||
if not ok:
|
||||
self.message_box(
|
||||
text=self._trad["checker_failed_text"],
|
||||
informative_text="\n".join(
|
||||
map(lambda t: " - " + self._trad[t], tips)
|
||||
),
|
||||
window_title=self._trad["checker_failed_title"],
|
||||
)
|
||||
return
|
||||
|
||||
self._values = {
|
||||
"name": self.get_line_edit_text("lineEdit_name"),
|
||||
"data_type": self._target_data[0],
|
||||
"target_data": self._target_data[1],
|
||||
"distribution": distribution,
|
||||
"params": parameters,
|
||||
}
|
||||
|
||||
super().accept()
|
||||
|
||||
def reject(self):
|
||||
self.close()
|
||||
|
||||
|
||||
class Ensemble1ParamsWidget(PamhyrWidget):
|
||||
_pamhyr_ui = "Ensemble1ParamsWidget"
|
||||
_pamhyr_name = "Parameters"
|
||||
|
||||
def __init__(self, ensemble=None,
|
||||
distribution=None,
|
||||
trad=None, parent=None):
|
||||
super(Ensemble1ParamsWidget, self).__init__(
|
||||
parent=parent
|
||||
)
|
||||
self._trad = trad
|
||||
|
||||
self._ensemble = ensemble
|
||||
self._distribution = distribution
|
||||
self._labels = distribution.labels
|
||||
|
||||
self._init_default_labels()
|
||||
self._init_default_values()
|
||||
|
||||
def _init_default_labels(self):
|
||||
self.set_label_text("label_0", self._trad[self._labels[0]])
|
||||
|
||||
def _init_default_values(self):
|
||||
self._values = self._ensemble.params
|
||||
if len(self._values) != 1:
|
||||
self._values = self._distribution.default_values.copy()
|
||||
|
||||
self.set_double_spin_box("doubleSpinBox_0", self._values[0])
|
||||
|
||||
@property
|
||||
def values(self):
|
||||
self._values = [
|
||||
self.get_double_spin_box("doubleSpinBox_0"),
|
||||
]
|
||||
|
||||
return self._values
|
||||
|
||||
|
||||
class Ensemble2ParamsWidget(PamhyrWidget):
|
||||
_pamhyr_ui = "Ensemble2ParamsWidget"
|
||||
_pamhyr_name = "Parameters"
|
||||
|
||||
def __init__(self, ensemble=None,
|
||||
distribution=None,
|
||||
trad=None, parent=None):
|
||||
super(Ensemble2ParamsWidget, self).__init__(
|
||||
parent=parent
|
||||
)
|
||||
self._trad = trad
|
||||
|
||||
self._ensemble = ensemble
|
||||
self._distribution = distribution
|
||||
self._labels = distribution.labels
|
||||
|
||||
self._init_default_labels()
|
||||
self._init_default_values()
|
||||
|
||||
def _init_default_labels(self):
|
||||
self.set_label_text("label_0", self._trad[self._labels[0]])
|
||||
self.set_label_text("label_1", self._trad[self._labels[1]])
|
||||
|
||||
def _init_default_values(self):
|
||||
self._values = self._ensemble.params
|
||||
if len(self._values) != 2:
|
||||
self._values = self._distribution.default_values.copy()
|
||||
|
||||
self.set_double_spin_box("doubleSpinBox_0", self._values[0])
|
||||
self.set_double_spin_box("doubleSpinBox_1", self._values[1])
|
||||
|
||||
@property
|
||||
def values(self):
|
||||
self._values = [
|
||||
self.get_double_spin_box("doubleSpinBox_0"),
|
||||
self.get_double_spin_box("doubleSpinBox_1")
|
||||
]
|
||||
|
||||
return self._values
|
||||
@@ -0,0 +1,268 @@
|
||||
# Table.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
import traceback
|
||||
|
||||
from tools import trace, timer
|
||||
|
||||
from PyQt5.QtCore import (
|
||||
Qt, QVariant, QAbstractTableModel,
|
||||
QCoreApplication, QModelIndex, pyqtSlot,
|
||||
QRect,
|
||||
)
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialogButtonBox, QPushButton, QLineEdit,
|
||||
QFileDialog, QTableView, QAbstractItemView,
|
||||
QUndoStack, QShortcut, QAction, QItemDelegate,
|
||||
QComboBox,
|
||||
)
|
||||
|
||||
from View.Ensembles.UndoCommand import (
|
||||
SetNameCommand, SetTypeCommand, SetDataCommand,
|
||||
SetDistributionCommand,
|
||||
AddCommand, DelCommand,
|
||||
)
|
||||
|
||||
from View.Tools.PamhyrTable import PamhyrTableModel
|
||||
|
||||
from View.Ensembles.Translate import *
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
_translate = QCoreApplication.translate
|
||||
|
||||
|
||||
class ComboBoxDelegate(QItemDelegate):
|
||||
def __init__(self, data=None, study=None,
|
||||
mode="stricklers", trad=None, parent=None):
|
||||
super(ComboBoxDelegate, self).__init__(parent)
|
||||
|
||||
self._data = data
|
||||
self._study = study
|
||||
self._trad = trad
|
||||
self._mode = mode
|
||||
|
||||
def createEditor(self, parent, option, index):
|
||||
self.editor = QComboBox(parent)
|
||||
|
||||
if self._mode == "data_type":
|
||||
self.editor.addItems(
|
||||
[
|
||||
self._trad["not_defined"],
|
||||
self._trad["strickler_minor"],
|
||||
self._trad["strickler_medium"],
|
||||
]
|
||||
)
|
||||
elif self._mode == "stricklers":
|
||||
used = list(
|
||||
map(
|
||||
lambda e: (e.data_type, e._target_data),
|
||||
self._data.lst
|
||||
)
|
||||
)
|
||||
current = self._data.get(index.row())
|
||||
|
||||
self.editor.addItems(
|
||||
[self._trad["not_defined"]] +
|
||||
list(
|
||||
map(
|
||||
lambda s: str(s),
|
||||
filter(
|
||||
# Exclude target data already used for
|
||||
# this data type
|
||||
lambda s: (
|
||||
current.target_data == s or
|
||||
(current.data_type, s) not in used
|
||||
),
|
||||
self._study.river.stricklers.stricklers
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
elif self._mode == "distribution":
|
||||
self.editor.addItems(
|
||||
[self._trad["not_defined"]] +
|
||||
list(
|
||||
map(
|
||||
lambda f: f.name,
|
||||
self._study._ens_distributions.lst
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
self.editor.setCurrentText(index.data(Qt.DisplayRole))
|
||||
return self.editor
|
||||
|
||||
def setEditorData(self, editor, index):
|
||||
value = index.data(Qt.DisplayRole)
|
||||
self.editor.currentTextChanged.connect(self.currentItemChanged)
|
||||
|
||||
def setModelData(self, editor, model, index):
|
||||
text = str(editor.currentText())
|
||||
|
||||
if self._mode == "data_type":
|
||||
value = next(
|
||||
filter(
|
||||
lambda x: self._trad[x] == text,
|
||||
["strickler_minor", "strickler_medium"],
|
||||
),
|
||||
""
|
||||
)
|
||||
elif self._mode == "stricklers":
|
||||
value = next(
|
||||
filter(
|
||||
lambda s: str(s) == text,
|
||||
self._study.river.stricklers.stricklers
|
||||
),
|
||||
None
|
||||
)
|
||||
elif self._mode == "distribution":
|
||||
value = next(
|
||||
filter(
|
||||
lambda f: f.name == text,
|
||||
self._study._ens_distributions.lst
|
||||
),
|
||||
None
|
||||
)
|
||||
else:
|
||||
value = text
|
||||
|
||||
model.setData(index, value)
|
||||
|
||||
editor.close()
|
||||
editor.deleteLater()
|
||||
|
||||
def updateEditorGeometry(self, editor, option, index):
|
||||
r = QRect(option.rect)
|
||||
if self.editor.windowFlags() & Qt.Popup:
|
||||
if editor.parent() is not None:
|
||||
r.setTopLeft(self.editor.parent().mapToGlobal(r.topLeft()))
|
||||
editor.setGeometry(r)
|
||||
|
||||
@pyqtSlot()
|
||||
def currentItemChanged(self):
|
||||
self.commitData.emit(self.sender())
|
||||
|
||||
|
||||
class EnsembleTableModel(PamhyrTableModel):
|
||||
def _setup_lst(self):
|
||||
self._lst = self._data
|
||||
self._study = self._opt_data
|
||||
|
||||
def data(self, index, role):
|
||||
if role != Qt.ItemDataRole.DisplayRole:
|
||||
return QVariant()
|
||||
|
||||
row = index.row()
|
||||
column = index.column()
|
||||
|
||||
if self._headers[column] == "name":
|
||||
return self._lst.get(row).name
|
||||
elif self._headers[column] == "type":
|
||||
return self._trad[self._lst.get(row).data_type]
|
||||
elif self._headers[column] == "target_data":
|
||||
value = self._lst.get(row).target_data
|
||||
if value is None:
|
||||
return self._trad["not_defined"]
|
||||
return str(value)
|
||||
elif self._headers[column] == "distribution":
|
||||
value = self._lst.get(row).distribution
|
||||
if value is None:
|
||||
return self._trad["not_defined"]
|
||||
return value.name
|
||||
elif self._headers[column] == "parameters":
|
||||
value = self._lst.get(row).params
|
||||
return str(value)
|
||||
|
||||
return QVariant()
|
||||
|
||||
def setData(self, index, value, role=Qt.EditRole):
|
||||
if not index.isValid() or role != Qt.EditRole:
|
||||
return False
|
||||
|
||||
if self.is_same_data(index, value):
|
||||
return False
|
||||
|
||||
row = index.row()
|
||||
column = index.column()
|
||||
|
||||
try:
|
||||
if self._headers[column] == "name":
|
||||
self._undo.push(
|
||||
SetNameCommand(
|
||||
self._lst, row, value
|
||||
)
|
||||
)
|
||||
elif self._headers[column] == "type":
|
||||
self._undo.push(
|
||||
SetTypeCommand(
|
||||
self._lst, row, value
|
||||
)
|
||||
)
|
||||
elif self._headers[column] == "target_data":
|
||||
self._undo.push(
|
||||
SetDataCommand(
|
||||
self._lst, row, value
|
||||
)
|
||||
)
|
||||
elif self._headers[column] == "distribution":
|
||||
self._undo.push(
|
||||
SetDistributionCommand(
|
||||
self._lst, row, value
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logger.info(e)
|
||||
logger.debug(traceback.format_exc())
|
||||
|
||||
self.dataChanged.emit(index, index)
|
||||
return True
|
||||
|
||||
def add(self, row, parent=QModelIndex()):
|
||||
self.beginInsertRows(parent, row, row - 1)
|
||||
|
||||
self._undo.push(
|
||||
AddCommand(
|
||||
self._lst, row,
|
||||
)
|
||||
)
|
||||
|
||||
self.endInsertRows()
|
||||
self.layoutChanged.emit()
|
||||
|
||||
def delete(self, rows, parent=QModelIndex()):
|
||||
self.beginRemoveRows(parent, rows[0], rows[-1])
|
||||
|
||||
self._undo.push(
|
||||
DelCommand(
|
||||
self._lst, rows
|
||||
)
|
||||
)
|
||||
|
||||
self.endRemoveRows()
|
||||
self.layoutChanged.emit()
|
||||
|
||||
def undo(self):
|
||||
self._undo.undo()
|
||||
self.layoutChanged.emit()
|
||||
|
||||
def redo(self):
|
||||
self._undo.redo()
|
||||
self.layoutChanged.emit()
|
||||
@@ -0,0 +1,50 @@
|
||||
# Translate.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from PyQt5.QtCore import QCoreApplication
|
||||
|
||||
from View.Translate import MainTranslate
|
||||
|
||||
_translate = QCoreApplication.translate
|
||||
|
||||
|
||||
class EnsemblesTranslate(MainTranslate):
|
||||
def __init__(self):
|
||||
super(EnsemblesTranslate, self).__init__()
|
||||
|
||||
self._dict["Ensembles"] = _translate(
|
||||
"Ensembles", "Ensembles"
|
||||
)
|
||||
|
||||
self._dict["ensemble"] = _translate(
|
||||
"Ensembles", "Ensembles scenario"
|
||||
)
|
||||
self._dict["strickler_minor"] = _translate(
|
||||
"Ensembles", "Stricklers minor"
|
||||
)
|
||||
self._dict["strickler_medium"] = _translate(
|
||||
"Ensembles", "Stricklers medium"
|
||||
)
|
||||
|
||||
self._sub_dict["table_headers"] = {
|
||||
"name": self._dict["name"],
|
||||
"type": _translate("Ensembles", "Type"),
|
||||
"target_data": _translate("Ensembles", "Target data"),
|
||||
"distribution": _translate("Ensembles", "Distribution"),
|
||||
"parameters": _translate("Ensembles", "Parameters"),
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
# UndoCommand.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from copy import deepcopy
|
||||
from tools import trace, timer
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QMessageBox, QUndoCommand, QUndoStack,
|
||||
)
|
||||
|
||||
from Model.Friction.Friction import Friction
|
||||
from Model.Friction.FrictionList import FrictionList
|
||||
|
||||
|
||||
class SetNameCommand(QUndoCommand):
|
||||
def __init__(self, ensembles, index, new_value):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._ensembles = ensembles
|
||||
self._index = index
|
||||
self._old = self._ensembles.get(self._index).name
|
||||
self._new = str(new_value)
|
||||
|
||||
def undo(self):
|
||||
self._ensembles.get(self._index).name = self._old
|
||||
|
||||
def redo(self):
|
||||
self._ensembles.get(self._index).name = self._new
|
||||
|
||||
|
||||
class SetTypeCommand(QUndoCommand):
|
||||
def __init__(self, ensembles, index, new_value):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._ensembles = ensembles
|
||||
self._index = index
|
||||
self._old = self._ensembles.get(self._index)\
|
||||
.data_type
|
||||
self._new = new_value
|
||||
|
||||
def undo(self):
|
||||
self._ensembles.get(self._index).data_type = self._old
|
||||
|
||||
def redo(self):
|
||||
self._ensembles.get(self._index).data_type = self._new
|
||||
|
||||
|
||||
class SetDataCommand(QUndoCommand):
|
||||
def __init__(self, ensembles, index, data):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._ensembles = ensembles
|
||||
self._index = index
|
||||
self._old = self._ensembles.get(self._index)\
|
||||
.target_data
|
||||
self._new = data
|
||||
|
||||
def undo(self):
|
||||
self._ensembles.get(self._index).target_data = self._old
|
||||
|
||||
def redo(self):
|
||||
self._ensembles.get(self._index).target_data = self._new
|
||||
|
||||
|
||||
class SetDistributionCommand(QUndoCommand):
|
||||
def __init__(self, ensembles, index, distribution):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._ensembles = ensembles
|
||||
self._index = index
|
||||
self._old = self._ensembles.get(self._index).distribution
|
||||
self._old_params = self._ensembles.get(self._index).params
|
||||
self._new = distribution
|
||||
|
||||
def undo(self):
|
||||
self._ensembles.get(self._index).distribution = self._old
|
||||
self._ensembles.get(self._index).params = self._old_params
|
||||
|
||||
def redo(self):
|
||||
self._ensembles.get(self._index).distribution = self._new
|
||||
if self._new is not None:
|
||||
self._ensembles.get(self._index).params = self._new.default_values
|
||||
|
||||
|
||||
class AddCommand(QUndoCommand):
|
||||
def __init__(self, ensembles, index):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._ensembles = ensembles
|
||||
self._index = index
|
||||
self._new = None
|
||||
|
||||
def undo(self):
|
||||
self._ensembles.delete_i([self._index])
|
||||
|
||||
def redo(self):
|
||||
if self._new is None:
|
||||
self._new = self._ensembles.new(self._index)
|
||||
else:
|
||||
self._ensembles.insert(self._index, self._new)
|
||||
|
||||
|
||||
class ImportCommand(QUndoCommand):
|
||||
def __init__(self, ensembles, data, index):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._ensembles = ensembles
|
||||
self._index = index
|
||||
self._data = data
|
||||
self._news = None
|
||||
|
||||
def undo(self):
|
||||
for new in self._news:
|
||||
new.set_as_deleted()
|
||||
|
||||
def redo(self):
|
||||
if self._news is None:
|
||||
self._news = list(
|
||||
map(
|
||||
lambda d: self._ensembles.new_with_data(
|
||||
self._index, d
|
||||
),
|
||||
self._data,
|
||||
)
|
||||
)
|
||||
else:
|
||||
for new in self._news:
|
||||
new.set_as_not_deleted()
|
||||
|
||||
|
||||
class DelCommand(QUndoCommand):
|
||||
def __init__(self, ensembles, rows):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._ensembles = ensembles
|
||||
self._rows = rows
|
||||
|
||||
self._friction = []
|
||||
for row in rows:
|
||||
self._friction.append((row, self._ensembles.get(row)))
|
||||
self._friction.sort()
|
||||
|
||||
def undo(self):
|
||||
for row, el in self._friction:
|
||||
self._ensembles.insert(row, el)
|
||||
|
||||
def redo(self):
|
||||
self._ensembles.delete_i(self._rows)
|
||||
|
||||
|
||||
class SetAllCommand(QUndoCommand):
|
||||
def __init__(self, ensemble, data):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._ensemble = ensemble
|
||||
self._old = self._ensemble.get_data_dict()
|
||||
self._new = data
|
||||
|
||||
def undo(self):
|
||||
self._ensemble.set_data_dict(self._old)
|
||||
|
||||
def redo(self):
|
||||
self._ensemble.set_data_dict(self._new)
|
||||
@@ -0,0 +1,280 @@
|
||||
# Window.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
import json
|
||||
|
||||
from tools import trace, timer, logger_exception
|
||||
|
||||
from View.Tools.PamhyrWindow import PamhyrWindow, PamhyrDialog
|
||||
|
||||
from PyQt5.QtGui import (
|
||||
QKeySequence,
|
||||
)
|
||||
|
||||
from PyQt5 import QtWidgets
|
||||
from PyQt5.QtCore import (
|
||||
Qt, QVariant, QAbstractTableModel,
|
||||
QCoreApplication, QModelIndex, pyqtSlot,
|
||||
QRect, QSettings,
|
||||
)
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialogButtonBox, QPushButton, QLineEdit,
|
||||
QFileDialog, QTableView, QAbstractItemView,
|
||||
QUndoStack, QShortcut, QAction, QItemDelegate,
|
||||
QComboBox, QVBoxLayout, QHeaderView, QTabWidget,
|
||||
)
|
||||
|
||||
from Modules import Modules
|
||||
|
||||
from View.Ensembles.Edit.Window import EnsembleEditDialog
|
||||
from View.Ensembles.Table import (
|
||||
EnsembleTableModel, ComboBoxDelegate
|
||||
)
|
||||
from View.Ensembles.Translate import EnsemblesTranslate
|
||||
from View.Ensembles.UndoCommand import SetAllCommand, ImportCommand
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class EnsemblesWindow(PamhyrWindow):
|
||||
_pamhyr_ui = "Ensembles"
|
||||
_pamhyr_name = "Ensembles"
|
||||
|
||||
def __init__(self, ensembles=None,
|
||||
study=None, config=None,
|
||||
parent=None):
|
||||
trad = EnsemblesTranslate()
|
||||
|
||||
self._ensembles = ensembles
|
||||
|
||||
name = (
|
||||
trad[self._pamhyr_name] + " - " +
|
||||
study.name
|
||||
)
|
||||
|
||||
super(EnsemblesWindow, self).__init__(
|
||||
title=name,
|
||||
study=study,
|
||||
config=config,
|
||||
trad=trad,
|
||||
parent=parent
|
||||
)
|
||||
|
||||
self.setup_table()
|
||||
self.setup_connections()
|
||||
|
||||
def setup_table_delegate(self):
|
||||
self._delegate_stricklers = ComboBoxDelegate(
|
||||
data=self._ensembles,
|
||||
study=self._study,
|
||||
mode="stricklers",
|
||||
trad=self._trad,
|
||||
parent=self
|
||||
)
|
||||
|
||||
self._delegate_data_type = ComboBoxDelegate(
|
||||
data=self._ensembles,
|
||||
study=self._study,
|
||||
mode="data_type",
|
||||
trad=self._trad,
|
||||
parent=self
|
||||
)
|
||||
|
||||
self._delegate_distribution = ComboBoxDelegate(
|
||||
data=self._ensembles,
|
||||
study=self._study,
|
||||
mode="distribution",
|
||||
trad=self._trad,
|
||||
parent=self
|
||||
)
|
||||
|
||||
return {
|
||||
"type": self._delegate_data_type,
|
||||
"target_data": self._delegate_stricklers,
|
||||
"distribution": self._delegate_distribution,
|
||||
}
|
||||
|
||||
def setup_table(self):
|
||||
self._table = {}
|
||||
|
||||
delegates = self.setup_table_delegate()
|
||||
|
||||
editable_headers = [
|
||||
"name",
|
||||
]
|
||||
|
||||
table = self.find(QTableView, f"tableView")
|
||||
self._table = EnsembleTableModel(
|
||||
table_view=table,
|
||||
table_headers=self._trad.get_dict("table_headers"),
|
||||
editable_headers=editable_headers,
|
||||
delegates=delegates,
|
||||
data=self._ensembles,
|
||||
trad=self._trad,
|
||||
undo=self._undo_stack,
|
||||
opt_data=self._study
|
||||
)
|
||||
|
||||
table.setModel(self._table)
|
||||
table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
||||
table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
|
||||
table.setAlternatingRowColors(True)
|
||||
|
||||
def setup_connections(self):
|
||||
self.find(QAction, "action_add").triggered.connect(self.add)
|
||||
self.find(QAction, "action_del").triggered.connect(self.delete)
|
||||
self.find(QAction, "action_edit").triggered.connect(self.edit)
|
||||
self.find(QAction, "action_export").triggered.connect(
|
||||
self.export_to_json
|
||||
)
|
||||
self.find(QAction, "action_import").triggered.connect(
|
||||
self.import_from_json
|
||||
)
|
||||
|
||||
table = self.find(QTableView, f"tableView")
|
||||
table.selectionModel()\
|
||||
.selectionChanged\
|
||||
.connect(self.update)
|
||||
|
||||
self._table.dataChanged\
|
||||
.connect(self.update)
|
||||
|
||||
def index_selected_rows(self):
|
||||
table = self.find(QTableView, f"tableView")
|
||||
return list(
|
||||
# Delete duplicate
|
||||
set(
|
||||
map(
|
||||
lambda i: i.row(),
|
||||
table.selectedIndexes()
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
def add(self):
|
||||
rows = self.index_selected_rows()
|
||||
if len(self._ensembles) == 0 or len(rows) == 0:
|
||||
self._table.add(0)
|
||||
else:
|
||||
self._table.add(rows[0])
|
||||
|
||||
def delete(self):
|
||||
rows = self.index_selected_rows()
|
||||
if len(rows) == 0:
|
||||
return
|
||||
|
||||
self._table.delete(rows)
|
||||
|
||||
def _undo(self):
|
||||
self._table.undo()
|
||||
|
||||
def _redo(self):
|
||||
self._table.redo()
|
||||
|
||||
def edit(self):
|
||||
rows = self.index_selected_rows()
|
||||
|
||||
for row in rows:
|
||||
try:
|
||||
ens = self._ensembles.get(row)
|
||||
dlg = EnsembleEditDialog(
|
||||
study=self._study,
|
||||
ensemble=ens,
|
||||
parent=self
|
||||
)
|
||||
|
||||
if dlg.exec():
|
||||
self._undo_stack.push(
|
||||
SetAllCommand(
|
||||
ens, dlg.values
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
logger_exception(e)
|
||||
return
|
||||
|
||||
def export_to_json(self):
|
||||
ens = []
|
||||
for e in self._ensembles.lst:
|
||||
ens.append(e.get_data_dict(use_ids=True))
|
||||
|
||||
data = {"ensembles": ens}
|
||||
|
||||
def aux(filename):
|
||||
with open(filename[0], 'w') as f:
|
||||
f.write(json.dumps(data))
|
||||
|
||||
self.file_dialog(
|
||||
select_file=None,
|
||||
callback=aux,
|
||||
default_suffix='.json',
|
||||
file_filter=[self._trad["file_json"]]
|
||||
)
|
||||
|
||||
def import_from_json(self):
|
||||
def aux(filename):
|
||||
with open(filename[0], 'r') as f:
|
||||
return json.load(f)
|
||||
|
||||
data = self.file_dialog(
|
||||
select_file=None,
|
||||
callback=aux,
|
||||
default_suffix='.json',
|
||||
file_filter=[self._trad["file_json"]]
|
||||
)
|
||||
|
||||
dtarget = dict(
|
||||
map(
|
||||
lambda s: (s.pamhyr_id, s),
|
||||
self._study.river.stricklers.stricklers
|
||||
)
|
||||
)
|
||||
|
||||
ddistr = dict(
|
||||
map(
|
||||
lambda d: (d.name, d),
|
||||
self._study._ens_distributions.lst
|
||||
)
|
||||
)
|
||||
|
||||
def update(d, values):
|
||||
d.update(values)
|
||||
return d
|
||||
|
||||
updated = list(
|
||||
map(
|
||||
lambda d: update(
|
||||
d, {"target_data": dtarget[d["target_data"]]}
|
||||
),
|
||||
map(
|
||||
lambda d: update(
|
||||
d, {"distribution": ddistr[d["distribution"]]}
|
||||
),
|
||||
data["ensembles"]
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
self._undo_stack.push(
|
||||
ImportCommand(
|
||||
self._ensembles, updated, 0
|
||||
)
|
||||
)
|
||||
self._table.update()
|
||||
@@ -105,9 +105,19 @@ class ComboBoxDelegate(QItemDelegate):
|
||||
strickler
|
||||
)
|
||||
elif self._mode == "rk":
|
||||
self.editor.addItems(
|
||||
list(map(str, self._data.reach.get_rk()))
|
||||
)
|
||||
if self._data is None:
|
||||
self.editor.addItems(
|
||||
["-"]
|
||||
)
|
||||
else:
|
||||
self.editor.addItems(
|
||||
list(
|
||||
map(
|
||||
lambda p: p.display_name(),
|
||||
self._data.reach.profiles
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
self.editor.setCurrentText(str(index.data(Qt.DisplayRole)))
|
||||
return self.editor
|
||||
|
||||
@@ -112,7 +112,7 @@ class PlotAC(PamhyrPlot):
|
||||
profile_id = 0
|
||||
|
||||
profile = self.data.profile(profile_id)
|
||||
if profile is None:
|
||||
if profile is None or self._parent.tableView.isRowHidden(profile_id):
|
||||
return
|
||||
|
||||
station = profile.get_station()
|
||||
@@ -192,21 +192,24 @@ class PlotAC(PamhyrPlot):
|
||||
self.plot_selected.set_data([], [])
|
||||
self.next_plot_selected.set_data([], [])
|
||||
|
||||
if 0 <= previous_id < self.data.number_profiles:
|
||||
if (0 <= previous_id < self.data.number_profiles
|
||||
and not self._parent.tableView.isRowHidden(previous_id)):
|
||||
self.previous_plot_selected.set_data(
|
||||
self.data.profile(previous_id).get_station(),
|
||||
self.data.profile(previous_id).z()
|
||||
)
|
||||
self.previous_plot_selected.set_visible(True)
|
||||
|
||||
if 0 <= profile_id < self.data.number_profiles:
|
||||
if (0 <= profile_id < self.data.number_profiles
|
||||
and not self._parent.tableView.isRowHidden(profile_id)):
|
||||
self.plot_selected.set_data(
|
||||
self.data.profile(profile_id).get_station(),
|
||||
self.data.profile(profile_id).z()
|
||||
)
|
||||
self.plot_selected.set_visible(True)
|
||||
|
||||
if 0 <= next_id < self.data.number_profiles:
|
||||
if (0 <= next_id < self.data.number_profiles
|
||||
and not self._parent.tableView.isRowHidden(next_id)):
|
||||
self.next_plot_selected.set_data(
|
||||
self.data.profile(next_id).get_station(),
|
||||
self.data.profile(next_id).z()
|
||||
|
||||
@@ -20,6 +20,7 @@ import logging
|
||||
|
||||
from tools import timer
|
||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
||||
from matplotlib.backend_bases import MouseButton
|
||||
from PyQt5.QtWidgets import QApplication
|
||||
from PyQt5.QtCore import (
|
||||
Qt, QItemSelectionModel,
|
||||
@@ -64,7 +65,7 @@ class PlotRKZ(PamhyrPlot):
|
||||
def onpick(self, event):
|
||||
if event.mouseevent.inaxes != self.canvas.axes:
|
||||
return
|
||||
if event.mouseevent.button.value != 1:
|
||||
if event.mouseevent.button != MouseButton.LEFT:
|
||||
return
|
||||
|
||||
modifiers = QApplication.keyboardModifiers()
|
||||
@@ -110,9 +111,9 @@ class PlotRKZ(PamhyrPlot):
|
||||
def _closest_rk(self, event):
|
||||
|
||||
s = event.artist.get_segments()
|
||||
x = [i[0, 0] for i in s]
|
||||
mx = event.mouseevent.xdata
|
||||
points = enumerate(x)
|
||||
points = [(i, segment[0, 0]) for i, segment in enumerate(s)
|
||||
if len(segment)]
|
||||
|
||||
def dist_mouse(point):
|
||||
x = point[1]
|
||||
@@ -136,6 +137,7 @@ class PlotRKZ(PamhyrPlot):
|
||||
if len(ind) == 0:
|
||||
return
|
||||
|
||||
ind = [i for i in ind if not self._table.isRowHidden(i)]
|
||||
for i in ind:
|
||||
index.append(QItemSelectionRange(self._table.model().index(i, 0)))
|
||||
|
||||
@@ -150,18 +152,7 @@ class PlotRKZ(PamhyrPlot):
|
||||
self._table.scrollTo(self._table.model().index(ind[-1], 0))
|
||||
|
||||
def _select_range_in_table(self, ind1, ind2):
|
||||
if self._table is not None:
|
||||
self._table.setFocus()
|
||||
selection = self._table.selectionModel()
|
||||
index = QItemSelection(self._table.model().index(ind1, 0),
|
||||
self._table.model().index(ind2, 0))
|
||||
selection.select(
|
||||
index,
|
||||
QItemSelectionModel.Rows |
|
||||
QItemSelectionModel.ClearAndSelect |
|
||||
QItemSelectionModel.Select
|
||||
)
|
||||
self._table.scrollTo(self._table.model().index(ind2, 0))
|
||||
self._select_in_table(list(range(ind1, ind2 + 1)))
|
||||
|
||||
@timer
|
||||
def redraw(self, data):
|
||||
@@ -213,13 +204,23 @@ class PlotRKZ(PamhyrPlot):
|
||||
picker=10,
|
||||
)
|
||||
|
||||
if self._table is not None:
|
||||
segments = self.line_rk_zmin_zmax.get_segments()
|
||||
self.line_rk_zmin_zmax.set_segments([
|
||||
segment[:0] if self._table.isRowHidden(row) else segment
|
||||
for row, segment in enumerate(segments)
|
||||
])
|
||||
|
||||
def color_highlight(self):
|
||||
rows = sorted(list(
|
||||
set(
|
||||
(i.row() for i in self.parent.tableView.selectedIndexes())
|
||||
)
|
||||
))
|
||||
colors = [self.color_plot for row in range(len(self._data))]
|
||||
colors = [
|
||||
"darkorange" if profile.interpolated else self.color_plot
|
||||
for profile in self._data.profiles
|
||||
]
|
||||
style = ["-" for row in range(len(self._data))]
|
||||
if len(rows) > 0:
|
||||
for row in rows:
|
||||
|
||||
+14
-16
@@ -18,6 +18,7 @@
|
||||
|
||||
from tools import timer, trace
|
||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
||||
from matplotlib.backend_bases import MouseButton
|
||||
from matplotlib import collections
|
||||
import numpy as np
|
||||
|
||||
@@ -60,7 +61,7 @@ class PlotXY(PamhyrPlot):
|
||||
def onpick(self, event):
|
||||
if event.mouseevent.inaxes != self.canvas.axes:
|
||||
return
|
||||
if event.mouseevent.button.value != 1:
|
||||
if event.mouseevent.button != MouseButton.LEFT:
|
||||
return
|
||||
|
||||
modifiers = QApplication.keyboardModifiers()
|
||||
@@ -136,6 +137,7 @@ class PlotXY(PamhyrPlot):
|
||||
index = QItemSelection()
|
||||
if len(ind) == 0:
|
||||
return
|
||||
ind = [i for i in ind if not self._table.isRowHidden(i)]
|
||||
for i in ind:
|
||||
index.append(QItemSelectionRange(self._table.model().index(i, 0)))
|
||||
selection.select(
|
||||
@@ -149,18 +151,7 @@ class PlotXY(PamhyrPlot):
|
||||
self._table.scrollTo(self._table.model().index(ind[-1], 0))
|
||||
|
||||
def _select_range_in_table(self, ind1, ind2):
|
||||
if self._table is not None:
|
||||
self._table.setFocus()
|
||||
selection = self._table.selectionModel()
|
||||
index = QItemSelection(self._table.model().index(ind1, 0),
|
||||
self._table.model().index(ind2, 0))
|
||||
selection.select(
|
||||
index,
|
||||
QItemSelectionModel.Rows |
|
||||
QItemSelectionModel.ClearAndSelect |
|
||||
QItemSelectionModel.Select
|
||||
)
|
||||
self._table.scrollTo(self._table.model().index(ind2, 0))
|
||||
self._select_in_table(list(range(ind1, ind2 + 1)))
|
||||
|
||||
@timer
|
||||
def redraw(self, data):
|
||||
@@ -189,8 +180,12 @@ class PlotXY(PamhyrPlot):
|
||||
|
||||
def draw_xy(self):
|
||||
self.line_xy = []
|
||||
for xy in zip(self.data.get_x(), self.data.get_y()):
|
||||
self.line_xy.append(np.column_stack(xy))
|
||||
for row, profile in enumerate(self.data.profiles):
|
||||
hidden = self._table is not None and self._table.isRowHidden(row)
|
||||
self.line_xy.append(
|
||||
np.empty((0, 2)) if hidden or len(profile) == 0
|
||||
else np.column_stack((profile.x(), profile.y()))
|
||||
)
|
||||
|
||||
self._colors, self._style = self.color_highlight()
|
||||
self.line_xy_collection = collections.LineCollection(
|
||||
@@ -207,7 +202,10 @@ class PlotXY(PamhyrPlot):
|
||||
(i.row() for i in self.parent.tableView.selectedIndexes())
|
||||
)
|
||||
))
|
||||
colors = [self.color_plot for row in range(len(self._data))]
|
||||
colors = [
|
||||
"darkorange" if profile.interpolated else self.color_plot
|
||||
for profile in self._data.profiles
|
||||
]
|
||||
style = ["-" for row in range(len(self._data))]
|
||||
if len(rows) > 0:
|
||||
for row in rows:
|
||||
|
||||
@@ -22,6 +22,7 @@ from math import dist, sqrt
|
||||
|
||||
from tools import timer, trace
|
||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
||||
from matplotlib.backend_bases import MouseButton
|
||||
|
||||
from PyQt5.QtCore import (
|
||||
Qt, QCoreApplication, QItemSelectionModel,
|
||||
@@ -111,7 +112,7 @@ class Plot(PamhyrPlot):
|
||||
def onpick(self, event):
|
||||
if event.mouseevent.inaxes != self.canvas.axes:
|
||||
return
|
||||
if event.mouseevent.button.value != 1:
|
||||
if event.mouseevent.button != MouseButton.LEFT:
|
||||
return
|
||||
|
||||
modifiers = QApplication.keyboardModifiers()
|
||||
@@ -126,11 +127,11 @@ class Plot(PamhyrPlot):
|
||||
def onclick(self, event):
|
||||
if event.inaxes != self.canvas.axes:
|
||||
return
|
||||
if event.button.value == 1:
|
||||
if event.button not in (MouseButton.MIDDLE, MouseButton.RIGHT):
|
||||
return
|
||||
|
||||
z = self._get_z_from_click(event)
|
||||
if z < self.data.z_min() or event.button.value == 2:
|
||||
if z < self.data.z_min() or event.button == MouseButton.MIDDLE:
|
||||
self.highlight = None
|
||||
self.draw_highligth()
|
||||
self.update_idle()
|
||||
|
||||
@@ -37,6 +37,11 @@ class SetDataCommand(QUndoCommand):
|
||||
self._index = index
|
||||
self._old = old_value
|
||||
self._new = self.type(new_value)
|
||||
if self._profile.old_interpolated == "":
|
||||
if self._profile.interpolated:
|
||||
self._profile.old_interpolated = "interpolated"
|
||||
else:
|
||||
self._profile.old_interpolated = "not_interpolated"
|
||||
|
||||
|
||||
class SetXCommand(SetDataCommand):
|
||||
@@ -46,10 +51,19 @@ class SetXCommand(SetDataCommand):
|
||||
|
||||
def undo(self):
|
||||
self._profile.point(self._index).x = self._old
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
self._profile.point(self._index).x = self._new
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -60,10 +74,19 @@ class SetYCommand(SetDataCommand):
|
||||
|
||||
def undo(self):
|
||||
self._profile.point(self._index).y = self._old
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
self._profile.point(self._index).y = self._new
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -74,10 +97,19 @@ class SetZCommand(SetDataCommand):
|
||||
|
||||
def undo(self):
|
||||
self._profile.point(self._index).z = self._old
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
self._profile.point(self._index).z = self._new
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -89,9 +121,20 @@ class SetNameCommand(SetDataCommand):
|
||||
|
||||
def undo(self):
|
||||
self._profile.point(self._index).name = self._old
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
self._profile.point(self._index).name = self._new
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
class AddCommand(QUndoCommand):
|
||||
@@ -104,6 +147,13 @@ class AddCommand(QUndoCommand):
|
||||
|
||||
def undo(self):
|
||||
self._profile.delete_i([self._index])
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
@@ -111,7 +161,8 @@ class AddCommand(QUndoCommand):
|
||||
self._point = self._profile.insert(self._index)
|
||||
else:
|
||||
self._profile.insert_point(self._index, self._point)
|
||||
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -125,10 +176,19 @@ class DelCommand(QUndoCommand):
|
||||
def undo(self):
|
||||
for point in self._points:
|
||||
point.set_as_not_deleted()
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
self._profile.delete_points(self._points)
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -153,10 +213,19 @@ class SortCommand(QUndoCommand):
|
||||
|
||||
def undo(self):
|
||||
self._profile.sort_with_indexes(self._indexes)
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
self._profile.sort(self._column, self._reverse)
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -173,6 +242,13 @@ class MoveCommand(QUndoCommand):
|
||||
self._profile.move_up_point(self._i)
|
||||
else:
|
||||
self._profile.move_down_point(self._i)
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
@@ -180,6 +256,8 @@ class MoveCommand(QUndoCommand):
|
||||
self._profile.move_up_point(self._i)
|
||||
else:
|
||||
self._profile.move_down_point(self._i)
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.interpolated = False
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -191,10 +269,19 @@ class ReverseCommand(QUndoCommand):
|
||||
|
||||
def undo(self):
|
||||
self._profile.reverse()
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
self._profile.reverse()
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -209,10 +296,19 @@ class PurgeCommand(QUndoCommand):
|
||||
def undo(self):
|
||||
for point in self._deleted:
|
||||
point.set_as_not_deleted()
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
self._deleted = self._profile.purge(self._np_purge)
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
|
||||
|
||||
@@ -228,9 +324,18 @@ class PasteCommand(QUndoCommand):
|
||||
|
||||
def undo(self):
|
||||
self._profile.delete_points(self._points)
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
self._profile.modified()
|
||||
|
||||
def redo(self):
|
||||
for point in self._points:
|
||||
self._profile.insert_point(self._row, point)
|
||||
self._profile.interpolated = False
|
||||
self._profile.increase_modification_count()
|
||||
self._profile.modified()
|
||||
@@ -45,6 +45,9 @@ class GeometryTranslate(MainTranslate):
|
||||
self._dict["cross_sections"] = _translate("Geometry", "cross-sections")
|
||||
self._dict["profile"] = _translate("Geometry", "cross-section")
|
||||
self._dict["profiles"] = _translate("Geometry", "cross-sections")
|
||||
self._dict["show_interpolated_profiles"] = _translate(
|
||||
"Geometry", "Show interpolated profiles"
|
||||
)
|
||||
self._dict["cross_section_enabled_count"] = _translate(
|
||||
"Geometry", "Cross-section enabled ({count} disabled)"
|
||||
)
|
||||
|
||||
@@ -41,6 +41,7 @@ class SetDataCommand(QUndoCommand):
|
||||
self._index = index
|
||||
self._old = old_value
|
||||
self._new = self.type(new_value)
|
||||
self._profile = self._reach.profile(self._index)
|
||||
|
||||
|
||||
class SetNameCommand(SetDataCommand):
|
||||
@@ -48,24 +49,52 @@ class SetNameCommand(SetDataCommand):
|
||||
self.type = str
|
||||
super(SetNameCommand, self).__init__(
|
||||
reach, index, old_value, new_value)
|
||||
if self._profile.old_interpolated == "":
|
||||
if self._profile.interpolated:
|
||||
self._profile.old_interpolated = "interpolated"
|
||||
else:
|
||||
self._profile.old_interpolated = "not_interpolated"
|
||||
|
||||
def undo(self):
|
||||
self._reach.profile(self._index).name = self._old
|
||||
self._profile.name = self._old
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
|
||||
def redo(self):
|
||||
self._reach.profile(self._index).name = self._new
|
||||
# Name setter will automatically update the interpolated attribute
|
||||
self._profile.name = self._new
|
||||
self._profile.increase_modification_count()
|
||||
|
||||
|
||||
class SetRKCommand(SetDataCommand):
|
||||
def __init__(self, reach, index, old_value, new_value):
|
||||
self.type = float
|
||||
super(SetRKCommand, self).__init__(reach, index, old_value, new_value)
|
||||
if self._profile.old_interpolated == "":
|
||||
if self._profile.interpolated:
|
||||
self._profile.old_interpolated = "interpolated"
|
||||
else:
|
||||
self._profile.old_interpolated = "not_interpolated"
|
||||
|
||||
def undo(self):
|
||||
self._reach.profile(self._index).rk = self._old
|
||||
self._profile.rk = self._old
|
||||
self._profile.decrease_modification_count()
|
||||
if self._profile.modification_count == 0:
|
||||
if self._profile.old_interpolated == "interpolated":
|
||||
self._profile.interpolated = True
|
||||
else:
|
||||
self._profile.interpolated = False
|
||||
self._profile.old_interpolated = ""
|
||||
|
||||
def redo(self):
|
||||
self._reach.profile(self._index).rk = self._new
|
||||
# RK setter will automatically update the interpolated attribute
|
||||
self._profile.rk = self._new
|
||||
self._profile.increase_modification_count()
|
||||
|
||||
|
||||
class SetEnabledCommand(QUndoCommand):
|
||||
|
||||
@@ -127,6 +127,9 @@ class GeometryWindow(PamhyrWindow):
|
||||
table.setAlternatingRowColors(True)
|
||||
|
||||
def setup_checkbox(self):
|
||||
self.find(QCheckBox, "checkBox_show_interpolated").setText(
|
||||
self._trad["show_interpolated_profiles"]
|
||||
)
|
||||
self._checkbox = self.find(QCheckBox, "checkBox_enabled")
|
||||
self._set_checkbox_state()
|
||||
|
||||
@@ -197,6 +200,18 @@ class GeometryWindow(PamhyrWindow):
|
||||
self._status_label.setText(txt)
|
||||
|
||||
def setup_connections(self):
|
||||
self.find(QCheckBox, "checkBox_show_interpolated").toggled.connect(
|
||||
self.update_interpolated_profiles_visibility
|
||||
)
|
||||
self.find(QCheckBox, "checkBox_show_interpolated").toggled.connect(
|
||||
self.update_redraw
|
||||
)
|
||||
self._table.modelReset.connect(
|
||||
self.update_interpolated_profiles_visibility)
|
||||
self._table.rowsInserted.connect(
|
||||
self.update_interpolated_profiles_visibility)
|
||||
self._table.rowsRemoved.connect(
|
||||
self.update_interpolated_profiles_visibility)
|
||||
if self._study.is_read_only():
|
||||
actions = {
|
||||
"action_export": self.export_to_file,
|
||||
@@ -237,6 +252,24 @@ class GeometryWindow(PamhyrWindow):
|
||||
def update(self):
|
||||
self._update()
|
||||
|
||||
def update_interpolated_profiles_visibility(self):
|
||||
show_interpolated = self.find(
|
||||
QCheckBox, "checkBox_show_interpolated"
|
||||
).isChecked()
|
||||
selection = self.tableView.selectionModel()
|
||||
for row in range(self._table.rowCount()):
|
||||
hidden = not show_interpolated \
|
||||
and self._reach.profile(row).interpolated
|
||||
self.tableView.setRowHidden(row, hidden)
|
||||
if hidden:
|
||||
selection.select(
|
||||
self._table.index(row, 0),
|
||||
QItemSelectionModel.Deselect | QItemSelectionModel.Rows
|
||||
)
|
||||
if selection.currentIndex().row() == row:
|
||||
selection.setCurrentIndex(QModelIndex(),
|
||||
QItemSelectionModel.NoUpdate)
|
||||
|
||||
def update_redraw(self):
|
||||
self._update(redraw=True)
|
||||
|
||||
@@ -248,6 +281,7 @@ class GeometryWindow(PamhyrWindow):
|
||||
self.find(QAction, "action_meshing").setEnabled(enabled)
|
||||
|
||||
def _update(self, redraw=False, propagate=True):
|
||||
self.update_interpolated_profiles_visibility()
|
||||
self.update_meshing_action()
|
||||
|
||||
if redraw:
|
||||
@@ -498,6 +532,7 @@ class GeometryWindow(PamhyrWindow):
|
||||
data=self._reach,
|
||||
trad=self._trad,
|
||||
toolbar=self._toolbar_ac,
|
||||
parent=self,
|
||||
)
|
||||
self._plot_ac.draw()
|
||||
|
||||
|
||||
@@ -42,7 +42,7 @@ class PlotAC(PamhyrPlot):
|
||||
self._isometric_axis = False
|
||||
|
||||
self._auto_relim_update = True
|
||||
self._autoscale_update = False
|
||||
self._autoscale_update = True
|
||||
|
||||
@property
|
||||
def river(self):
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
from tools import timer
|
||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
||||
from matplotlib.backend_bases import MouseButton
|
||||
|
||||
from PyQt5.QtCore import (
|
||||
QCoreApplication, Qt,
|
||||
@@ -30,6 +31,14 @@ _translate = QCoreApplication.translate
|
||||
|
||||
|
||||
class PlotRKC(PamhyrPlot):
|
||||
# Class attributes: PlotRKZ (frictions) does not call this __init__
|
||||
_selected = None # Selected hydraulic structure, in blue
|
||||
profile = None
|
||||
line_rk_zmin = None
|
||||
line_rk_zmin_zmax = None
|
||||
hs_vlines = None
|
||||
_hs_drawn = [] # Structures of hs_vlines, in order
|
||||
|
||||
def __init__(self, canvas=None, trad=None, toolbar=None,
|
||||
river=None, reach=None, profile=None,
|
||||
parent=None):
|
||||
@@ -133,19 +142,14 @@ class PlotRKC(PamhyrPlot):
|
||||
vymin = []
|
||||
vymax = []
|
||||
self.anotate_lst = []
|
||||
self._hs_drawn = []
|
||||
hs_color = []
|
||||
index = self.parent.tableView.selectedIndexes()
|
||||
for i, hs in enumerate(lhs):
|
||||
for hs in lhs:
|
||||
section = hs.input_section
|
||||
if section is None:
|
||||
continue
|
||||
|
||||
if i == index[0].row():
|
||||
color = "blue"
|
||||
elif hs.enabled:
|
||||
color = "red"
|
||||
else:
|
||||
color = "darkgrey"
|
||||
color = self._hs_color(hs)
|
||||
|
||||
x = section.rk
|
||||
if x is not None:
|
||||
@@ -163,6 +167,7 @@ class PlotRKC(PamhyrPlot):
|
||||
vymin.append(min(z_min))
|
||||
vymax.append(max(z_max))
|
||||
hs_color.append(color)
|
||||
self._hs_drawn.append(hs)
|
||||
|
||||
self.hs_vlines = self.canvas.axes.vlines(
|
||||
x=vx, ymin=vymin, ymax=vymax,
|
||||
@@ -171,6 +176,28 @@ class PlotRKC(PamhyrPlot):
|
||||
color=hs_color,
|
||||
)
|
||||
|
||||
def _hs_color(self, hs):
|
||||
if hs is self._selected:
|
||||
return "blue"
|
||||
if hs.enabled:
|
||||
return "red"
|
||||
return "darkgrey"
|
||||
|
||||
def set_selected(self, hs):
|
||||
"""Draw the selected structure in blue, without redrawing the
|
||||
plot (the view is kept)"""
|
||||
self._selected = hs
|
||||
if self.hs_vlines is None:
|
||||
return
|
||||
|
||||
colors = [self._hs_color(h) for h in self._hs_drawn]
|
||||
if colors:
|
||||
self.hs_vlines.set_color(colors)
|
||||
for annotation, color in zip(self.anotate_lst, colors):
|
||||
annotation.set_color(color)
|
||||
|
||||
self.canvas.figure.canvas.draw_idle()
|
||||
|
||||
def color_highlight(self, highlight):
|
||||
|
||||
reach = self._current_reach
|
||||
@@ -243,7 +270,7 @@ class PlotRKC(PamhyrPlot):
|
||||
def onpick(self, event):
|
||||
if event.mouseevent.inaxes != self.canvas.axes:
|
||||
return
|
||||
if event.mouseevent.button.value != 1:
|
||||
if event.mouseevent.button != MouseButton.LEFT:
|
||||
return
|
||||
|
||||
modifiers = QApplication.keyboardModifiers()
|
||||
@@ -254,7 +281,8 @@ class PlotRKC(PamhyrPlot):
|
||||
|
||||
closest = self._closest_profile(event)
|
||||
index = self.parent.tableView.selectedIndexes()
|
||||
if self.parent._table is not None:
|
||||
# Moves the selected structure: nothing to do without selection
|
||||
if self.parent._table is not None and len(index) > 2:
|
||||
self.parent._table.setData(index[2], closest)
|
||||
|
||||
return
|
||||
|
||||
@@ -130,11 +130,13 @@ class HydraulicStructuresWindow(PamhyrWindow):
|
||||
self._checkbox = self.find(QCheckBox, f"checkBox")
|
||||
self._set_checkbox_state()
|
||||
|
||||
_toolbar_items = ["home", "move", "zoom", "save", "iso", "back/forward"]
|
||||
|
||||
def setup_plots(self):
|
||||
self.canvas = MplCanvas(width=5, height=4, dpi=100)
|
||||
self.canvas.setObjectName("canvas")
|
||||
self.toolbar = PamhyrPlotToolbar(
|
||||
self.canvas, self
|
||||
self.canvas, self, items=self._toolbar_items
|
||||
)
|
||||
self.plot_layout = self.find(QVBoxLayout, "verticalLayout")
|
||||
self.plot_layout.addWidget(self.toolbar)
|
||||
@@ -143,7 +145,7 @@ class HydraulicStructuresWindow(PamhyrWindow):
|
||||
self.plot_rkc = PlotRKC(
|
||||
canvas=self.canvas,
|
||||
river=self._study.river,
|
||||
reach=None,
|
||||
reach=self._displayed_reach(None),
|
||||
profile=None,
|
||||
trad=self._trad,
|
||||
toolbar=self.toolbar,
|
||||
@@ -154,7 +156,7 @@ class HydraulicStructuresWindow(PamhyrWindow):
|
||||
self.canvas_2 = MplCanvas(width=5, height=4, dpi=100)
|
||||
self.canvas_2.setObjectName("canvas_2")
|
||||
self.toolbar_2 = PamhyrPlotToolbar(
|
||||
self.canvas_2, self
|
||||
self.canvas_2, self, items=self._toolbar_items
|
||||
)
|
||||
self.plot_layout_2 = self.find(QVBoxLayout, "verticalLayout_2")
|
||||
self.plot_layout_2.addWidget(self.toolbar_2)
|
||||
@@ -183,7 +185,7 @@ class HydraulicStructuresWindow(PamhyrWindow):
|
||||
table = self.find(QTableView, "tableView")
|
||||
table.selectionModel()\
|
||||
.selectionChanged\
|
||||
.connect(self.update)
|
||||
.connect(self.update_selection)
|
||||
|
||||
self._table.dataChanged.connect(self.update)
|
||||
self._table.layoutChanged.connect(self.update)
|
||||
@@ -283,10 +285,17 @@ class HydraulicStructuresWindow(PamhyrWindow):
|
||||
)
|
||||
|
||||
def update(self):
|
||||
"""Data changed: plots redrawn, fitted to their data"""
|
||||
self._set_checkbox_state()
|
||||
self._update_clear_plot()
|
||||
self._update_plots(redraw=True)
|
||||
|
||||
def _update_clear_plot(self):
|
||||
def update_selection(self):
|
||||
"""Selection changed: the selected structure is drawn in blue,
|
||||
the view is kept (unless its reach is another one)"""
|
||||
self._set_checkbox_state()
|
||||
self._update_plots(redraw=False)
|
||||
|
||||
def _selected_structure(self):
|
||||
rows = self.index_selected_rows()
|
||||
|
||||
if (len(rows) == 0 or
|
||||
|
||||
@@ -384,9 +384,19 @@ class InitialConditionTableModel(PamhyrTableModel):
|
||||
self.layoutChanged.emit()
|
||||
|
||||
def generate(self, generator, param, option):
|
||||
self.layoutAboutToBeChanged.emit()
|
||||
|
||||
self._undo.beginMacro(f"generate {generator}")
|
||||
self._undo.push(
|
||||
GenerateCommand(
|
||||
self._lst, generator, param, option
|
||||
)
|
||||
)
|
||||
self._undo.push(
|
||||
SortCommand(
|
||||
self._lst, False
|
||||
)
|
||||
)
|
||||
self._undo.endMacro()
|
||||
|
||||
self.layoutChanged.emit()
|
||||
@@ -100,15 +100,19 @@ class SortCommand(QUndoCommand):
|
||||
self._indexes = None
|
||||
|
||||
def undo(self):
|
||||
ll = self._ics.data
|
||||
order = {
|
||||
id(x): self._indexes[i]
|
||||
for i, x in enumerate(self._ics.data)
|
||||
}
|
||||
self._ics.sort(
|
||||
key=lambda x: self._indexes[ll.index(x)]
|
||||
key=lambda x: order.get(id(x), len(order))
|
||||
)
|
||||
|
||||
def redo(self):
|
||||
self._ics.sort(
|
||||
reverse=self._reverse,
|
||||
key=lambda x: x["rk"].rk
|
||||
key=lambda x: ((x["rk"] is None),
|
||||
0.0 if x["rk"] is None else x["rk"].rk)
|
||||
)
|
||||
if self._indexes is None:
|
||||
self._indexes = list(
|
||||
@@ -182,11 +186,19 @@ class GenerateCommand(QUndoCommand):
|
||||
self._ics = ics
|
||||
self._param = param
|
||||
self._option = option
|
||||
self._copy = self._ics.data
|
||||
# All the rows, with their deleted flag: the generation marks the
|
||||
# previous rows as deleted (clear_data)
|
||||
self._copy = list(self._ics._data)
|
||||
self._deleted = [d.is_deleted() for d in self._copy]
|
||||
self._generator = generator
|
||||
|
||||
def undo(self):
|
||||
self._ics.data = self._copy
|
||||
for data, deleted in zip(self._copy, self._deleted):
|
||||
if deleted:
|
||||
data.set_as_deleted()
|
||||
else:
|
||||
data.set_as_not_deleted()
|
||||
self._ics.data = list(self._copy)
|
||||
|
||||
def redo(self):
|
||||
if self._generator == "growing":
|
||||
|
||||
@@ -20,6 +20,7 @@ import logging
|
||||
import traceback
|
||||
from datetime import date, time, datetime, timedelta
|
||||
|
||||
from tools import parse_datetime
|
||||
from tools import (
|
||||
trace, timer,
|
||||
timestamp_to_old_pamhyr_date,
|
||||
@@ -73,11 +74,12 @@ class TableModel(PamhyrTableModel):
|
||||
if self._data.get_type_column(column) == float:
|
||||
value = f"{v:.4f}"
|
||||
elif self._data.header[column] == "time":
|
||||
if self._opt_data == "time":
|
||||
if self.time_system == "time":
|
||||
value = timestamp_to_old_pamhyr_date(int(v))
|
||||
else:
|
||||
value = format_datetime(
|
||||
datetime(1970, 1, 1) + timedelta(seconds=float(v))
|
||||
parse_datetime(self.start_date)
|
||||
+ timedelta(seconds=float(v))
|
||||
)
|
||||
else:
|
||||
value = f"{v}"
|
||||
@@ -96,8 +98,8 @@ class TableModel(PamhyrTableModel):
|
||||
|
||||
try:
|
||||
if (self._data.header[column] == "time"
|
||||
and self._opt_data == "date"):
|
||||
value = self.date_to_timestamp(value)
|
||||
and self.time_system == "date"):
|
||||
value = self.date_to_elapsed_seconds(value)
|
||||
|
||||
self._undo.push(
|
||||
SetDataCommand(
|
||||
|
||||
@@ -44,6 +44,22 @@ class SetDataCommand(QUndoCommand):
|
||||
self._data._set_i_c_v(self._index, self._column, self._new)
|
||||
|
||||
|
||||
class SetMetaDataCommand(QUndoCommand):
|
||||
def __init__(self, data, column, new_value):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._data = data
|
||||
self._column = column
|
||||
self._old = getattr(self._data, self._column)
|
||||
self._new = float(new_value)
|
||||
|
||||
def undo(self):
|
||||
setattr(self._data, self._column, self._old)
|
||||
|
||||
def redo(self):
|
||||
setattr(self._data, self._column, self._new)
|
||||
|
||||
|
||||
class AddCommand(QUndoCommand):
|
||||
def __init__(self, data, index):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
@@ -25,6 +25,8 @@ from PyQt5.QtGui import (
|
||||
QKeySequence,
|
||||
)
|
||||
|
||||
from Modules import Modules
|
||||
|
||||
from PyQt5.QtCore import (
|
||||
Qt, QVariant, QAbstractTableModel, QCoreApplication,
|
||||
)
|
||||
@@ -33,7 +35,7 @@ from PyQt5.QtWidgets import (
|
||||
QDialogButtonBox, QPushButton, QLineEdit,
|
||||
QFileDialog, QTableView, QAbstractItemView,
|
||||
QUndoStack, QShortcut, QAction, QItemDelegate,
|
||||
QHeaderView,
|
||||
QHeaderView, QVBoxLayout,
|
||||
)
|
||||
|
||||
from View.Tools.Plot.PamhyrCanvas import MplCanvas
|
||||
@@ -42,6 +44,8 @@ from View.Tools.Plot.PamhyrToolbar import PamhyrPlotToolbar
|
||||
from View.LateralContribution.Edit.translate import LCETranslate
|
||||
from View.LateralContribution.Edit.Table import TableModel
|
||||
from View.LateralContribution.Edit.Plot import Plot
|
||||
from View.LateralContribution.Edit.UndoCommand import SetMetaDataCommand
|
||||
from View.BoundaryCondition.Edit.Window import WD50Sigma
|
||||
|
||||
_translate = QCoreApplication.translate
|
||||
|
||||
@@ -52,10 +56,15 @@ class EditLateralContributionWindow(PamhyrWindow):
|
||||
|
||||
def __init__(self, data=None,
|
||||
study=None, config=None,
|
||||
parent=None):
|
||||
tab="liquid", parent=None):
|
||||
self._data = data
|
||||
# Grain size of the sediment brought: solid contributions only
|
||||
self._is_solid = tab == "solid"
|
||||
|
||||
trad = LCETranslate()
|
||||
if self._is_solid:
|
||||
trad.get_dict("table_headers")["discharge"] = \
|
||||
trad["solid_discharge"]
|
||||
name = trad[self._pamhyr_name]
|
||||
if self._data is not None:
|
||||
edge_name = (self._data.reach.name if self._data.reach is not None
|
||||
@@ -79,6 +88,7 @@ class EditLateralContributionWindow(PamhyrWindow):
|
||||
|
||||
self.setup_table()
|
||||
self.setup_plot()
|
||||
self.setup_d50sigma()
|
||||
self.setup_connections()
|
||||
|
||||
def setup_table(self):
|
||||
@@ -110,7 +120,7 @@ class EditLateralContributionWindow(PamhyrWindow):
|
||||
undo=self._undo_stack,
|
||||
trad=self._trad,
|
||||
opt_data=self._study.time_system,
|
||||
start_date=self._study.date
|
||||
study=self._study
|
||||
)
|
||||
|
||||
table.setModel(self._table)
|
||||
@@ -137,7 +147,18 @@ class EditLateralContributionWindow(PamhyrWindow):
|
||||
)
|
||||
self.plot.draw()
|
||||
|
||||
def setup_d50sigma(self):
|
||||
if not self._is_solid:
|
||||
return
|
||||
|
||||
layout = self.find(QVBoxLayout, "verticalLayout_table")
|
||||
self._d50sigma = WD50Sigma(parent=self)
|
||||
layout.addWidget(self._d50sigma)
|
||||
self.widget_update()
|
||||
|
||||
def setup_connections(self):
|
||||
self._undo_stack.indexChanged.connect(self._propagate_lateral_update)
|
||||
|
||||
if self._study.is_editable():
|
||||
self.find(QAction, "action_add").triggered.connect(self.add)
|
||||
self.find(QAction, "action_del").triggered.connect(self.delete)
|
||||
@@ -146,6 +167,38 @@ class EditLateralContributionWindow(PamhyrWindow):
|
||||
self._table.dataChanged.connect(self.update)
|
||||
self._table.layoutChanged.connect(self.update)
|
||||
|
||||
if self._is_solid:
|
||||
if self._study.is_editable():
|
||||
self._d50sigma.d50Changed.connect(self.d50_changed)
|
||||
self._d50sigma.sigmaChanged.connect(self.sigma_changed)
|
||||
else:
|
||||
self._d50sigma.setEnabled(False)
|
||||
|
||||
def _propagate_lateral_update(self, index=None):
|
||||
# Every change of the lateral contributions goes through the undo
|
||||
# stack (push, undo, redo): the main window then reruns their
|
||||
# checkers
|
||||
self._propagate_update(key=Modules.LATERAL_CONTRIBUTION)
|
||||
|
||||
def d50_changed(self, value):
|
||||
self._undo_stack.push(SetMetaDataCommand(self._data, "d50", value))
|
||||
|
||||
def sigma_changed(self, value):
|
||||
self._undo_stack.push(
|
||||
SetMetaDataCommand(self._data, "sigma", value)
|
||||
)
|
||||
|
||||
def widget_update(self):
|
||||
if self._is_solid:
|
||||
self._d50sigma.set_d50(self._data.d50)
|
||||
self._d50sigma.set_sigma(self._data.sigma)
|
||||
|
||||
def _propagated_update(self, key=Modules(0)):
|
||||
if Modules.STUDY in key:
|
||||
self._table.layoutChanged.emit()
|
||||
self.plot.update()
|
||||
self.widget_update()
|
||||
|
||||
def update(self):
|
||||
self.plot.update()
|
||||
self.plot.fit_to_data()
|
||||
@@ -228,7 +281,9 @@ class EditLateralContributionWindow(PamhyrWindow):
|
||||
def _undo(self):
|
||||
self._table.undo()
|
||||
self.plot.update()
|
||||
self.widget_update()
|
||||
|
||||
def _redo(self):
|
||||
self._table.redo()
|
||||
self.plot.update()
|
||||
self.widget_update()
|
||||
@@ -39,3 +39,7 @@ class LCETranslate(LCTranslate):
|
||||
"discharge": self._dict["unit_discharge"],
|
||||
"z": self._dict["unit_elevation"],
|
||||
}
|
||||
# Discharge column of a solid contribution
|
||||
self._dict["solid_discharge"] = _translate(
|
||||
"LateralContribution", "Solid discharge (kg/s)"
|
||||
)
|
||||
@@ -20,6 +20,7 @@ import logging
|
||||
|
||||
from tools import trace, timer
|
||||
|
||||
from Modules import Modules
|
||||
from View.Tools.PamhyrWindow import PamhyrWindow
|
||||
|
||||
from PyQt5 import QtWidgets
|
||||
@@ -67,6 +68,7 @@ logger = logging.getLogger()
|
||||
class LateralContributionWindow(PamhyrWindow):
|
||||
_pamhyr_ui = "LateralContributions"
|
||||
_pamhyr_name = "Lateral contribution"
|
||||
_tabs = ["liquid", "solid"]
|
||||
|
||||
def __init__(self, study=None, config=None, parent=None):
|
||||
trad = LCTranslate()
|
||||
@@ -96,7 +98,7 @@ class LateralContributionWindow(PamhyrWindow):
|
||||
else:
|
||||
editable_headers = []
|
||||
|
||||
for t in ["liquid", "solid", "suspenssion"]:
|
||||
for t in self._tabs:
|
||||
self._delegate_type = ComboBoxDelegate(
|
||||
data=self._study.river,
|
||||
mode="type",
|
||||
@@ -158,6 +160,8 @@ class LateralContributionWindow(PamhyrWindow):
|
||||
)
|
||||
|
||||
def setup_connections(self):
|
||||
self._undo_stack.indexChanged.connect(self._propagate_lateral_update)
|
||||
|
||||
if self._study.is_editable():
|
||||
self.find(QAction, "action_import").triggered.connect(
|
||||
self.import_from_file)
|
||||
@@ -168,7 +172,7 @@ class LateralContributionWindow(PamhyrWindow):
|
||||
self.find(QAction, "action_edit").triggered.connect(self.edit)
|
||||
self.tabs.currentChanged.connect(self._set_current_reach)
|
||||
|
||||
for t in ["liquid", "solid", "suspenssion"]:
|
||||
for t in self._tabs:
|
||||
table = self.find(QTableView, f"tableView_{t}")
|
||||
table.selectionModel()\
|
||||
.selectionChanged\
|
||||
@@ -177,6 +181,12 @@ class LateralContributionWindow(PamhyrWindow):
|
||||
self._table[t].dataChanged\
|
||||
.connect(self._set_current_reach)
|
||||
|
||||
def _propagate_lateral_update(self, index=None):
|
||||
# Every change of the lateral contributions goes through the undo
|
||||
# stack (push, undo, redo): the main window then reruns their
|
||||
# checkers
|
||||
self._propagate_update(key=Modules.LATERAL_CONTRIBUTION)
|
||||
|
||||
def current_tab(self):
|
||||
return self.find(QTabWidget, "tabWidget")\
|
||||
.currentWidget()\
|
||||
@@ -303,6 +313,7 @@ class LateralContributionWindow(PamhyrWindow):
|
||||
win = EditLateralContributionWindow(
|
||||
data=data,
|
||||
study=self._study,
|
||||
tab=tab,
|
||||
parent=self
|
||||
)
|
||||
win.show()
|
||||
|
||||
@@ -20,6 +20,7 @@ import logging
|
||||
import traceback
|
||||
from datetime import date, time, datetime, timedelta
|
||||
|
||||
from tools import parse_datetime
|
||||
from tools import (
|
||||
trace, timer,
|
||||
timestamp_to_old_pamhyr_date,
|
||||
@@ -87,11 +88,12 @@ class TableModel(PamhyrTableModel):
|
||||
if self._data._types[column] == float:
|
||||
value = f"{v:.4f}"
|
||||
elif self._data.header[column] == "time":
|
||||
if self._opt_data == "time":
|
||||
if self.time_system == "time":
|
||||
value = timestamp_to_old_pamhyr_date_adists(int(v))
|
||||
else:
|
||||
value = format_datetime(
|
||||
datetime(1970, 1, 1) + timedelta(seconds=float(v))
|
||||
parse_datetime(self.start_date)
|
||||
+ timedelta(seconds=float(v))
|
||||
)
|
||||
else:
|
||||
value = f"{v}"
|
||||
@@ -110,8 +112,8 @@ class TableModel(PamhyrTableModel):
|
||||
|
||||
try:
|
||||
if (self._data.header[column] == "time"
|
||||
and self._opt_data == "date"):
|
||||
value = self.date_to_timestamp(value)
|
||||
and self.time_system == "date"):
|
||||
value = self.date_to_elapsed_seconds(value)
|
||||
|
||||
row = self.get_true_data_row(row)
|
||||
|
||||
|
||||
@@ -29,6 +29,8 @@ from PyQt5.QtCore import (
|
||||
Qt, QVariant, QAbstractTableModel, QCoreApplication,
|
||||
)
|
||||
|
||||
from Modules import Modules
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialogButtonBox, QPushButton, QLineEdit,
|
||||
QFileDialog, QTableView, QAbstractItemView,
|
||||
@@ -132,7 +134,7 @@ class EditLateralContributionAdisTSWindow(PamhyrWindow):
|
||||
undo=self._undo_stack,
|
||||
trad=self._trad,
|
||||
opt_data=self._study.time_system,
|
||||
start_date=self._study.date
|
||||
study=self._study
|
||||
)
|
||||
|
||||
table.setModel(self._table)
|
||||
@@ -166,6 +168,11 @@ class EditLateralContributionAdisTSWindow(PamhyrWindow):
|
||||
|
||||
self._table.dataChanged.connect(self.update)
|
||||
|
||||
def _propagated_update(self, key=Modules(0)):
|
||||
if Modules.STUDY in key:
|
||||
self._table.layoutChanged.emit()
|
||||
self.plot.update()
|
||||
|
||||
def update(self):
|
||||
self.plot.update()
|
||||
self.plot.fit_to_data()
|
||||
|
||||
+148
-35
@@ -30,7 +30,7 @@ from platformdirs import user_cache_dir
|
||||
|
||||
from Solver.AdisTS import AdisTS
|
||||
from Solver.Mage import Mage8
|
||||
from Solver.RubarBE import Rubar3
|
||||
from Solver.RubarBE import RubarBE
|
||||
from tools import logger_exception, pamhyr_db_need_update, timer
|
||||
|
||||
from PyQt5 import QtGui
|
||||
@@ -61,11 +61,13 @@ from View.WaitingDialog import WaitingDialog
|
||||
|
||||
from View.MainWindowTabInfo import WidgetInfo
|
||||
from View.MainWindowTabChecker import WidgetChecker
|
||||
from View.MainWindowTabGraph import WidgetGraph
|
||||
|
||||
from View.Configure.Window import ConfigureWindow
|
||||
from View.Study.Window import NewStudyWindow
|
||||
from View.About.Window import AboutWindow
|
||||
from View.Scenarios.Window import ScenariosWindow
|
||||
from View.Ensembles.Window import EnsemblesWindow
|
||||
from View.Network.Window import NetworkWindow
|
||||
from View.Geometry.Window import GeometryWindow
|
||||
from View.BoundaryCondition.Window import BoundaryConditionWindow
|
||||
@@ -82,11 +84,14 @@ from View.GeoTIFF.Window import GeoTIFFListWindow
|
||||
from View.REPLines.Window import REPLineListWindow
|
||||
from View.SolverParameters.Window import SolverParametersWindow
|
||||
from View.RunSolver.Window import (
|
||||
EnsembleRunNumberDialog,
|
||||
SelectSolverWindow,
|
||||
SolverLogWindow,
|
||||
SolverLogEnsWindow,
|
||||
)
|
||||
|
||||
from View.Results.Window import ResultsWindow
|
||||
|
||||
from View.Results.Window import ResultsWindow, ResultsEnsembleWindow
|
||||
from View.Results.CompareDialog import (
|
||||
CompareScenariosWindow
|
||||
)
|
||||
@@ -235,6 +240,7 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
|
||||
def setup_tab(self):
|
||||
self.setup_tab_info()
|
||||
self.setup_tab_graph()
|
||||
self.setup_tab_checker()
|
||||
|
||||
def setup_tab_info(self):
|
||||
@@ -261,6 +267,19 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
self._trad["tab_checker_name"]
|
||||
)
|
||||
|
||||
def setup_tab_graph(self):
|
||||
tab_widget = self.findChild(QTabWidget, "tabWidget")
|
||||
|
||||
self._tab_widget_graph = WidgetGraph(
|
||||
study=self._study, trad=self._trad, parent=self
|
||||
)
|
||||
|
||||
tab_widget.insertTab(
|
||||
0, self._tab_widget_graph,
|
||||
self._trad["tab_graph_name"]
|
||||
)
|
||||
tab_widget.setCurrentWidget(self._tab_widget_graph)
|
||||
|
||||
def enable_actions(self, action: str, enable: bool):
|
||||
"""Enable of disable an action componant
|
||||
|
||||
@@ -545,6 +564,7 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
self._do_propagate_update_rec(window, keys)
|
||||
|
||||
self._tab_widget_checker.update(modules=keys)
|
||||
self._tab_widget_graph.update()
|
||||
|
||||
def _do_propagate_update_info_tab(self, keys):
|
||||
modules = Modules.modelling_list()
|
||||
@@ -570,6 +590,10 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
self._tab_widget_info.study = self._study
|
||||
self._tab_widget_info.update()
|
||||
|
||||
if self._tab_widget_graph.study != self._study:
|
||||
self._tab_widget_graph.study = self._study
|
||||
self._tab_widget_graph.update()
|
||||
|
||||
if self._tab_widget_checker.study != self._study:
|
||||
self._tab_widget_checker.study = self._study
|
||||
self._tab_widget_checker.update(modules=Modules.STUDY)
|
||||
@@ -898,13 +922,32 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
# MSG AND DIALOG #
|
||||
##################
|
||||
|
||||
def msg_select_reach(self):
|
||||
self.message_box(
|
||||
window_title=self._trad["Warning"],
|
||||
text=self._trad["mb_select_reach_title"],
|
||||
informative_text=self._trad["mb_select_reach_msg"]
|
||||
def ensure_current_reach(self):
|
||||
"""Offer a reach selection when needed;
|
||||
return False on cancellation."""
|
||||
if self._study is None:
|
||||
return False
|
||||
river = self._study.river
|
||||
if river.has_current_reach():
|
||||
return True
|
||||
edges = list(river.edges())
|
||||
if not edges:
|
||||
QMessageBox.information(
|
||||
self, self._trad["Select reach"], self._trad["no_reach"]
|
||||
)
|
||||
return False
|
||||
labels = [f"{edge.name or self._trad['reach']} (#{edge.id})"
|
||||
for edge in edges]
|
||||
selected, accepted = QInputDialog.getItem(
|
||||
self, self._trad["Select reach"],
|
||||
self._trad["reach"] + ":", labels, 0, False
|
||||
)
|
||||
self.open_network()
|
||||
if not accepted:
|
||||
return False
|
||||
river.set_current_reach(edges[labels.index(selected)])
|
||||
self._tab_widget_graph.update()
|
||||
self._propagate_update(key=Modules.NETWORK)
|
||||
return True
|
||||
|
||||
def dialog_reopen_study(self):
|
||||
dlg = QMessageBox(self)
|
||||
@@ -1287,6 +1330,9 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
return
|
||||
|
||||
self.network = NetworkWindow(study=self._study, parent=self)
|
||||
self.network.networkChanged.connect(
|
||||
self._tab_widget_graph.update, Qt.QueuedConnection
|
||||
)
|
||||
self.network.show()
|
||||
|
||||
def open_scenarios(self):
|
||||
@@ -1297,6 +1343,7 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
"""
|
||||
if self._study is None:
|
||||
return
|
||||
|
||||
if self._study.filename is None or self._study.filename == "":
|
||||
self.message_box(
|
||||
window_title=self._trad["Warning"],
|
||||
@@ -1330,13 +1377,36 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
self.scenarios = ScenariosWindow(study=self._study, parent=self)
|
||||
self.scenarios.show()
|
||||
|
||||
def open_ensemble_scenario(self):
|
||||
"""Open ensemble scenario window
|
||||
|
||||
Returns:
|
||||
Nothing
|
||||
"""
|
||||
if self._study is None:
|
||||
return
|
||||
|
||||
if self.sub_window_exists(
|
||||
EnsemblesWindow,
|
||||
data=[self._study, self.conf]
|
||||
):
|
||||
return
|
||||
|
||||
ensemble = EnsemblesWindow(
|
||||
ensembles=self._study.river._ensembles,
|
||||
study=self._study,
|
||||
config=self.conf,
|
||||
parent=self
|
||||
)
|
||||
ensemble.show()
|
||||
|
||||
def open_geometry(self):
|
||||
"""Open geometry window
|
||||
|
||||
Returns:
|
||||
Nothing
|
||||
"""
|
||||
if (self._study is not None and self._study.river.has_current_reach()):
|
||||
if self.ensure_current_reach():
|
||||
reach = self._study.river.current_reach().reach
|
||||
|
||||
if self.sub_window_exists(
|
||||
@@ -1356,9 +1426,7 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
)
|
||||
geometry.show()
|
||||
return geometry
|
||||
else:
|
||||
self.msg_select_reach()
|
||||
return None
|
||||
return None
|
||||
|
||||
def open_meshing(self):
|
||||
"""Open the current reach geometry and its meshing dialog."""
|
||||
@@ -1441,27 +1509,24 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
strick.show()
|
||||
|
||||
def open_frictions(self):
|
||||
if self._study is not None:
|
||||
if self._study.river.has_current_reach():
|
||||
reach = self._study.river.current_reach()
|
||||
if self.ensure_current_reach():
|
||||
reach = self._study.river.current_reach()
|
||||
|
||||
if self.sub_window_exists(
|
||||
FrictionsWindow,
|
||||
data=[self._study, self.conf, reach]
|
||||
):
|
||||
return
|
||||
if self.sub_window_exists(
|
||||
FrictionsWindow,
|
||||
data=[self._study, self.conf, reach]
|
||||
):
|
||||
return
|
||||
|
||||
frictions = FrictionsWindow(
|
||||
study=self._study,
|
||||
config=self.conf,
|
||||
parent=self
|
||||
)
|
||||
frictions.show()
|
||||
else:
|
||||
self.msg_select_reach()
|
||||
frictions = FrictionsWindow(
|
||||
study=self._study,
|
||||
config=self.conf,
|
||||
parent=self
|
||||
)
|
||||
frictions.show()
|
||||
|
||||
def open_initial_conditions(self):
|
||||
if self._study.river.has_current_reach():
|
||||
if self.ensure_current_reach():
|
||||
reach = self._study.river.current_reach()
|
||||
|
||||
if self.sub_window_exists(
|
||||
@@ -1477,8 +1542,6 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
parent=self
|
||||
)
|
||||
initial.show()
|
||||
else:
|
||||
self.msg_select_reach()
|
||||
|
||||
def open_additional_files(self):
|
||||
if self._study is not None:
|
||||
@@ -1552,8 +1615,7 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
)
|
||||
return
|
||||
|
||||
if not self._study.river.has_current_reach():
|
||||
self.msg_select_reach()
|
||||
if not self.ensure_current_reach():
|
||||
return
|
||||
|
||||
reach = self._study.river.current_reach().reach
|
||||
@@ -1694,6 +1756,9 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
sol.show()
|
||||
|
||||
def solver_log(self, solver):
|
||||
if self._study.status.scenario.is_ensemble():
|
||||
return self._solver_log_ensemble(solver)
|
||||
|
||||
sol = SolverLogWindow(
|
||||
study=self._study,
|
||||
config=self.conf,
|
||||
@@ -1702,6 +1767,28 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
)
|
||||
sol.show()
|
||||
|
||||
def _solver_log_ensemble(self, solver):
|
||||
run_number = 1
|
||||
|
||||
dlg = EnsembleRunNumberDialog(
|
||||
trad=self._trad,
|
||||
parent=self
|
||||
)
|
||||
if dlg.exec():
|
||||
function = dlg.function
|
||||
number_of_run = dlg.number
|
||||
seed = dlg.seed
|
||||
|
||||
sol = SolverLogEnsWindow(
|
||||
number_of_run=number_of_run,
|
||||
seed=seed, function=function,
|
||||
study=self._study,
|
||||
config=self.conf,
|
||||
solver=solver,
|
||||
parent=self
|
||||
)
|
||||
sol.show()
|
||||
|
||||
def msg_box_results_continue(self):
|
||||
dlg = QMessageBox(self)
|
||||
|
||||
@@ -1778,6 +1865,12 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
if not self.msg_box_results_continue():
|
||||
return
|
||||
|
||||
if self._study.status.scenario.is_ensemble():
|
||||
self.open_solver_ens_results_window(solver, results)
|
||||
else:
|
||||
self.open_solver_results_window(solver, results)
|
||||
|
||||
def open_solver_results_window(self, solver, results):
|
||||
# Windows already opened
|
||||
if self.sub_window_exists(
|
||||
ResultsWindow,
|
||||
@@ -1797,6 +1890,26 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
)
|
||||
res.show()
|
||||
|
||||
def open_solver_ens_results_window(self, solver, results):
|
||||
# Windows already opened
|
||||
if self.sub_window_exists(
|
||||
ResultsEnsembleWindow,
|
||||
data=[
|
||||
self._study,
|
||||
None, # No config,
|
||||
results._solver,
|
||||
results._repertory,
|
||||
results._name]
|
||||
):
|
||||
return
|
||||
|
||||
res = ResultsEnsembleWindow(
|
||||
study=self._study,
|
||||
results=[results],
|
||||
parent=self
|
||||
)
|
||||
res.show()
|
||||
|
||||
def msg_open_results_no_results(self):
|
||||
self.message_box(
|
||||
window_title=self._trad["Warning"],
|
||||
@@ -1969,7 +2082,7 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
dialog.setFileMode(QFileDialog.FileMode.ExistingFile)
|
||||
dialog.setDefaultSuffix(".BIN")
|
||||
# dialog.setFilter(dialog.filter() | QtCore.QDir.Hidden)
|
||||
dialog.setNameFilters(['Mage (*.BIN)', 'Rubar3 (profil.*)'])
|
||||
dialog.setNameFilters(['Mage (*.BIN)', 'RubarBE (profil.*)'])
|
||||
|
||||
if self._study.filename is not None:
|
||||
if self._last_solver is None:
|
||||
@@ -1989,7 +2102,7 @@ class ApplicationWindow(QMainWindow, ListedSubWindow, WindowToolKit):
|
||||
if ".BIN" in file_name[0]:
|
||||
solver = Mage8("Mage8")
|
||||
else:
|
||||
solver = Rubar3("Rubar3")
|
||||
solver = RubarBE("RubarBE")
|
||||
|
||||
self.open_solver_results(
|
||||
solver,
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
# MainWindowTabGraph.py -- Pamhyr
|
||||
# Copyright (C) 2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from View.Tools.Plot.PamhyrCanvas import MplCanvas
|
||||
from View.Tools.Plot.PamhyrToolbar import PamhyrPlotToolbar
|
||||
from View.PlotXY import PlotXY
|
||||
from View.Network.GraphWidget import GraphWidget
|
||||
|
||||
from PyQt5.QtCore import Qt
|
||||
from PyQt5.QtWidgets import (
|
||||
QWidget, QGroupBox, QLabel, QHBoxLayout, QVBoxLayout, QSplitter,
|
||||
)
|
||||
|
||||
|
||||
class WidgetGraph(QWidget):
|
||||
"""Read-only network graph displayed in the main window."""
|
||||
|
||||
def __init__(self, study=None, trad=None, parent=None):
|
||||
super(WidgetGraph, self).__init__(parent)
|
||||
|
||||
self._study = study
|
||||
self._trad = trad
|
||||
self._plot_river = None
|
||||
|
||||
layout = QHBoxLayout(self)
|
||||
self._splitter = QSplitter(Qt.Horizontal, self)
|
||||
self._splitter.setChildrenCollapsible(False)
|
||||
layout.addWidget(self._splitter)
|
||||
self._graph_widget = None
|
||||
|
||||
self._graph_group = QGroupBox(
|
||||
self._trad["graph_network_title"], self
|
||||
)
|
||||
self._graph_layout = QVBoxLayout(self._graph_group)
|
||||
|
||||
self._graph_title = QLabel(self._graph_group)
|
||||
self._graph_title.setTextFormat(Qt.PlainText)
|
||||
self._graph_title.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
|
||||
self._graph_title.setWordWrap(True)
|
||||
self._graph_layout.addWidget(self._graph_title)
|
||||
self._update_graph_title()
|
||||
self._splitter.addWidget(self._graph_group)
|
||||
|
||||
self.canvas = MplCanvas(width=5, height=4, dpi=100)
|
||||
self.canvas.setObjectName("canvas_graph")
|
||||
self.toolbar = PamhyrPlotToolbar(
|
||||
self.canvas, self,
|
||||
items=["home", "zoom", "save", "iso", "back/forward", "move"]
|
||||
)
|
||||
self._plot_group = QGroupBox(
|
||||
self._trad["graph_geographic_title"], self
|
||||
)
|
||||
self._plot_layout = QVBoxLayout(self._plot_group)
|
||||
self._plot_layout.addWidget(self.toolbar)
|
||||
self._plot_layout.addWidget(self.canvas, 1)
|
||||
self._splitter.addWidget(self._plot_group)
|
||||
self._splitter.setStretchFactor(0, 1)
|
||||
self._splitter.setStretchFactor(1, 1)
|
||||
self._splitter.setSizes([1000, 1000])
|
||||
|
||||
self.plot = PlotXY(
|
||||
canvas=self.canvas,
|
||||
data=None,
|
||||
trad=self._trad,
|
||||
toolbar=self.toolbar,
|
||||
parent=self
|
||||
)
|
||||
|
||||
@property
|
||||
def study(self):
|
||||
return self._study
|
||||
|
||||
@study.setter
|
||||
def study(self, study):
|
||||
self._study = study
|
||||
self._update_graph_title()
|
||||
|
||||
def _update_graph_title(self):
|
||||
self._graph_title.setText(
|
||||
self._study.name if self._study is not None else ""
|
||||
)
|
||||
|
||||
def update(self):
|
||||
river = self._study.river if self._study is not None else None
|
||||
view = None
|
||||
if river is not None and river is self._plot_river:
|
||||
axes = self.canvas.axes
|
||||
if axes.has_data():
|
||||
view = (axes.get_xlim(), axes.get_ylim(),
|
||||
axes.get_aspect(), axes.get_adjustable())
|
||||
|
||||
self._update_graph_title()
|
||||
if (self._graph_widget is not None
|
||||
and (self._study is None
|
||||
or self._graph_widget.graph is not self._study.river)):
|
||||
self._graph_layout.removeWidget(self._graph_widget)
|
||||
self._graph_widget.deleteLater()
|
||||
self._graph_widget = None
|
||||
|
||||
if self._study is not None and self._graph_widget is None:
|
||||
self._graph_widget = GraphWidget(
|
||||
self._study.river,
|
||||
parent=self,
|
||||
only_display=True,
|
||||
trad=self._trad,
|
||||
)
|
||||
self._graph_layout.addWidget(self._graph_widget, 1)
|
||||
elif self._graph_widget is not None:
|
||||
self._graph_widget.display_update()
|
||||
|
||||
data = None
|
||||
geotiff = None
|
||||
if self._study is not None:
|
||||
data = self._study.river.enable_edges()
|
||||
geotiff = self._study.river.geotiff
|
||||
|
||||
self.plot = PlotXY(
|
||||
canvas=self.canvas,
|
||||
data=data,
|
||||
geotiff=geotiff,
|
||||
trad=self._trad,
|
||||
toolbar=self.toolbar,
|
||||
parent=self
|
||||
)
|
||||
self.plot.update()
|
||||
self._plot_river = river
|
||||
if view is not None:
|
||||
x_limits, y_limits, aspect, adjustable = view
|
||||
self.canvas.axes.set_aspect(aspect, adjustable=adjustable)
|
||||
self.canvas.axes.set_xlim(x_limits)
|
||||
self.canvas.axes.set_ylim(y_limits)
|
||||
self.canvas.draw_idle()
|
||||
@@ -448,6 +448,7 @@ class NewEdgeLine(QGraphicsItem):
|
||||
class GraphWidget(QGraphicsView):
|
||||
changeEdge = pyqtSignal(object)
|
||||
changeNode = pyqtSignal(object)
|
||||
currentEdgeChanged = pyqtSignal()
|
||||
|
||||
def __init__(self, graph, parent=None,
|
||||
min_size=(400, 400), max_size=None,
|
||||
@@ -476,6 +477,7 @@ class GraphWidget(QGraphicsView):
|
||||
self.m_origin_x = 0.0
|
||||
self.m_origin_y = 0.0
|
||||
self.clicked = False
|
||||
self._panning = False
|
||||
|
||||
self.setup_scene(min_size, max_size, size)
|
||||
|
||||
@@ -491,8 +493,8 @@ class GraphWidget(QGraphicsView):
|
||||
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
|
||||
self.setResizeAnchor(QGraphicsView.AnchorViewCenter)
|
||||
|
||||
self.scale(1, 1)
|
||||
self.previousScale = 1
|
||||
self.scale(0.7, 0.7)
|
||||
self.previousScale = 0.7
|
||||
self.centerOn(1000.0, 1000.0)
|
||||
|
||||
if min_size:
|
||||
@@ -667,6 +669,13 @@ class GraphWidget(QGraphicsView):
|
||||
Returns:
|
||||
Nothing
|
||||
"""
|
||||
# Scene items are destroyed by clear(); do not retain hover/selection
|
||||
# references to them when refreshing another view of the same graph.
|
||||
self._selected_item = None
|
||||
self._selected_new_edge_src_node = None
|
||||
self._current_edge = None
|
||||
self._current_moved_node = None
|
||||
self.tmp_line = None
|
||||
self.scene().clear()
|
||||
self.create_items()
|
||||
|
||||
@@ -875,6 +884,9 @@ class GraphWidget(QGraphicsView):
|
||||
|
||||
if previous_edge:
|
||||
previous_edge.update()
|
||||
edge.update()
|
||||
if previous_edge is not edge:
|
||||
self.currentEdgeChanged.emit()
|
||||
except Exception as e:
|
||||
logger.warning(str(e))
|
||||
|
||||
@@ -937,6 +949,8 @@ class GraphWidget(QGraphicsView):
|
||||
|
||||
def mousePressEvent(self, event):
|
||||
if self._only_display:
|
||||
if event.button() == Qt.LeftButton:
|
||||
self._start_pan(event)
|
||||
return
|
||||
|
||||
if event.button() == Qt.RightButton \
|
||||
@@ -959,6 +973,12 @@ class GraphWidget(QGraphicsView):
|
||||
self._selected_new_edge_src_node = None
|
||||
|
||||
items = self.items(event.pos())
|
||||
if event.button() == Qt.LeftButton and not any(
|
||||
isinstance(item, (NodeItem, EdgeItem, NodeText))
|
||||
for item in items
|
||||
):
|
||||
self._start_pan(event)
|
||||
return
|
||||
if items and type(items[0]) is EdgeItem:
|
||||
edge = items[0]
|
||||
if edge:
|
||||
@@ -1007,7 +1027,10 @@ class GraphWidget(QGraphicsView):
|
||||
def mouseReleaseEvent(self, event):
|
||||
self.clicked = False
|
||||
|
||||
if self._only_display:
|
||||
if self._panning or self._only_display:
|
||||
self._panning = False
|
||||
self.viewport().unsetCursor()
|
||||
event.accept()
|
||||
return
|
||||
|
||||
locked = self.graph._status.is_read_only()
|
||||
@@ -1029,7 +1052,28 @@ class GraphWidget(QGraphicsView):
|
||||
self.update()
|
||||
super(GraphWidget, self).mouseReleaseEvent(event)
|
||||
|
||||
def _start_pan(self, event):
|
||||
self.clicked = True
|
||||
self._panning = True
|
||||
self.m_origin_x = event.x()
|
||||
self.m_origin_y = event.y()
|
||||
self.viewport().setCursor(Qt.ClosedHandCursor)
|
||||
event.accept()
|
||||
|
||||
def mouseMoveEvent(self, event):
|
||||
if self._panning or self._only_display:
|
||||
if self._panning and event.buttons() & Qt.LeftButton:
|
||||
dx = event.x() - self.m_origin_x
|
||||
dy = event.y() - self.m_origin_y
|
||||
horizontal = self.horizontalScrollBar()
|
||||
vertical = self.verticalScrollBar()
|
||||
horizontal.setValue(horizontal.value() - dx)
|
||||
vertical.setValue(vertical.value() - dy)
|
||||
self.m_origin_x = event.x()
|
||||
self.m_origin_y = event.y()
|
||||
event.accept()
|
||||
return
|
||||
|
||||
pos = self.mapToScene(event.pos())
|
||||
locked = self.graph._status.is_read_only()
|
||||
|
||||
@@ -1061,20 +1105,6 @@ class GraphWidget(QGraphicsView):
|
||||
|
||||
# If state is "move"
|
||||
if self._state == "move":
|
||||
# Move on scene
|
||||
if not self.selected_item():
|
||||
if event.buttons() & Qt.LeftButton:
|
||||
old_p = self.mapToScene(
|
||||
int(self.m_origin_x), int(self.m_origin_y)
|
||||
)
|
||||
new_p = self.mapToScene(event.pos())
|
||||
translation = new_p - old_p
|
||||
|
||||
self.translate(translation.x(), translation.y())
|
||||
|
||||
self.m_origin_x = event.x()
|
||||
self.m_origin_y = event.y()
|
||||
|
||||
# Propagate event
|
||||
self.update()
|
||||
super(GraphWidget, self).mouseMoveEvent(event)
|
||||
|
||||
@@ -64,7 +64,17 @@ class SelectProfileDialog(PamhyrDialog):
|
||||
|
||||
self._reach = reach
|
||||
self._profile = None
|
||||
self._profiles = self._reach.reach.enabled_profiles
|
||||
self._profiles = list(self._reach.reach.profiles)
|
||||
structure_profiles = [
|
||||
structure.input_section
|
||||
for structure in study.river.hydraulic_structures.lst
|
||||
if structure.input_reach is reach and not structure.is_deleted()
|
||||
]
|
||||
self._selectable_indices = [
|
||||
index for index, profile in enumerate(self._profiles)
|
||||
if 0 < index < len(self._profiles) - 1
|
||||
and profile not in structure_profiles
|
||||
]
|
||||
|
||||
self.setup_combobox()
|
||||
|
||||
@@ -74,19 +84,28 @@ class SelectProfileDialog(PamhyrDialog):
|
||||
list(
|
||||
map(
|
||||
lambda p: p.display_name(),
|
||||
self._reach.reach.profiles[1:-1]
|
||||
self._profiles
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
if len(self._profiles) == 0:
|
||||
self.find(QDialogButtonBox, "buttonBox")\
|
||||
.button(QDialogButtonBox.Ok)\
|
||||
.setEnabled(False)
|
||||
combobox = self.find(QComboBox, "comboBox")
|
||||
for index in range(len(self._profiles)):
|
||||
if index not in self._selectable_indices:
|
||||
item = combobox.model().item(index)
|
||||
item.setFlags(item.flags() &
|
||||
~(Qt.ItemIsEnabled | Qt.ItemIsSelectable))
|
||||
|
||||
combobox.setCurrentIndex(
|
||||
self._selectable_indices[0] if self._selectable_indices else -1
|
||||
)
|
||||
self.find(QDialogButtonBox, "buttonBox")\
|
||||
.button(QDialogButtonBox.Ok)\
|
||||
.setEnabled(bool(self._selectable_indices))
|
||||
|
||||
def accept(self):
|
||||
index = self.find(QComboBox, "comboBox").currentIndex()
|
||||
if not 0 <= index < len(self._profiles):
|
||||
if index not in self._selectable_indices:
|
||||
return
|
||||
|
||||
self._profile = self._profiles[index]
|
||||
|
||||
@@ -58,6 +58,8 @@ _translate = QCoreApplication.translate
|
||||
|
||||
|
||||
class NetworkWindow(PamhyrWindow):
|
||||
networkChanged = pyqtSignal()
|
||||
|
||||
_pamhyr_ui = "Network"
|
||||
_pamhyr_name = "River network"
|
||||
|
||||
@@ -140,6 +142,8 @@ class NetworkWindow(PamhyrWindow):
|
||||
self._graph_layout.addWidget(self._graph_widget)
|
||||
|
||||
def setup_connections(self):
|
||||
self._undo_stack.indexChanged.connect(self.networkChanged)
|
||||
self._graph_widget.currentEdgeChanged.connect(self.networkChanged)
|
||||
self._nodes_model.dataChanged.connect(self.update)
|
||||
self._reachs_model.dataChanged.connect(
|
||||
self._graph_widget.display_update)
|
||||
|
||||
@@ -26,10 +26,13 @@ from View.Results.translate import ResultsTranslate
|
||||
|
||||
|
||||
class CustomExportDialog(PamhyrDialog):
|
||||
_pamhyr_ui = "CustomExportAdisDialog"
|
||||
_pamhyr_name = "Custom Plot Selection"
|
||||
_pamhyr_ui = "CustomExportDialog"
|
||||
_pamhyr_name = "Custom Export"
|
||||
|
||||
def __init__(self, parent=None):
|
||||
def __init__(self,
|
||||
tag_x="values_x",
|
||||
tag_y="values_y",
|
||||
parent=None):
|
||||
trad = ResultsTranslate()
|
||||
super(CustomExportDialog, self).__init__(
|
||||
title=trad[self._pamhyr_name],
|
||||
@@ -38,8 +41,8 @@ class CustomExportDialog(PamhyrDialog):
|
||||
parent=parent
|
||||
)
|
||||
|
||||
self._available_values_x = self._trad.get_dict("values_x")
|
||||
self._available_values_y = self._trad.get_dict("values_y")
|
||||
self._available_values_x = self._trad.get_dict(tag_x)
|
||||
self._available_values_y = self._trad.get_dict(tag_y)
|
||||
|
||||
self.setup_radio_buttons_x()
|
||||
self.setup_radio_buttons_res()
|
||||
@@ -66,8 +69,8 @@ class CustomExportDialog(PamhyrDialog):
|
||||
|
||||
def setup_radio_buttons_res(self):
|
||||
self._radio2 = []
|
||||
layout = self.find(QVBoxLayout, "verticalLayout_pol")
|
||||
label = self.find(QLabel, "label_3")
|
||||
layout = self.find(QVBoxLayout, "verticalLayout_solv")
|
||||
label = self.find(QLabel, "label_solv")
|
||||
label.setText(self._trad["solver"])
|
||||
|
||||
for solver in self.parent._solvers:
|
||||
@@ -89,7 +92,7 @@ class CustomExportDialog(PamhyrDialog):
|
||||
layout.addStretch()
|
||||
|
||||
def setup_label(self):
|
||||
self._label = self.find(QLabel, "label_4")
|
||||
self._label = self.find(QLabel, "label_data")
|
||||
self._label.setFrameStyle(QFrame.StyledPanel)
|
||||
self._label.setStyleSheet('background-color: white')
|
||||
self.set_label()
|
||||
@@ -163,6 +166,15 @@ class CustomExportDialog(PamhyrDialog):
|
||||
res = i
|
||||
break
|
||||
|
||||
self.value = x, y, self._envelop.isChecked(), res
|
||||
self.value = (x, y, self._envelop.isChecked(), res)
|
||||
|
||||
super().accept()
|
||||
|
||||
|
||||
class CustomExportEnsembleDialog(CustomExportDialog):
|
||||
def __init__(self, parent=None):
|
||||
super(CustomExportEnsembleDialog, self).__init__(
|
||||
tag_x="values_x_ens",
|
||||
tag_y="values_y_ens",
|
||||
parent=parent
|
||||
)
|
||||
@@ -286,6 +286,10 @@ class PlotAC(PamhyrPlot):
|
||||
initial_z = np.asarray(profile.geometry.z(), dtype=float)
|
||||
result = self.results[self._current_res_id]
|
||||
|
||||
bed = self._get_bed_from_sections(profile, result, initial_z)
|
||||
if bed is not None:
|
||||
return bed
|
||||
|
||||
try:
|
||||
sediment_timestamps = sorted(result.get("sediment_timestamps"))
|
||||
except (KeyError, TypeError):
|
||||
@@ -324,6 +328,38 @@ class PlotAC(PamhyrPlot):
|
||||
|
||||
return initial_z
|
||||
|
||||
def _get_bed_from_sections(self, profile, result, initial_z):
|
||||
"""Bed of the solvers that give the bed level of each section at
|
||||
each time ('zfd') and exact sections at some times
|
||||
('bed_sections', RubarBE): the last exact section before the
|
||||
current time, or the study geometry, with its moving points
|
||||
('bed_points') shifted by the change of the bed level since then.
|
||||
None for the other results"""
|
||||
try:
|
||||
sections = result.get("bed_sections")
|
||||
moving = result.get("bed_points")[profile.global_index]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
current = profile.get_ts_key(self._current_timestamp, "zfd")
|
||||
if current is None:
|
||||
return None
|
||||
|
||||
index = profile.global_index
|
||||
saved = [ts for ts in sorted(sections)
|
||||
if ts <= self._current_timestamp and index in sections[ts]]
|
||||
if saved:
|
||||
base_timestamp = saved[-1]
|
||||
base = np.asarray(sections[base_timestamp][index], dtype=float)
|
||||
else:
|
||||
base_timestamp = min(result.get("timestamps"))
|
||||
base = initial_z
|
||||
|
||||
level = profile.get_ts_key(base_timestamp, "zfd")
|
||||
if level is None or len(base) != len(moving):
|
||||
return None
|
||||
return base + np.where(moving, current - level, 0.0)
|
||||
|
||||
def _get_wet_mask(self, profile, elevation):
|
||||
result = self.results[self._current_res_id]
|
||||
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
# PlotHEnsemble.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
|
||||
from functools import reduce
|
||||
from datetime import datetime
|
||||
|
||||
from tools import timer, trace, logger_exception
|
||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
||||
|
||||
from PyQt5.QtCore import (
|
||||
QCoreApplication
|
||||
)
|
||||
|
||||
_translate = QCoreApplication.translate
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class PlotHEnsemble(PamhyrPlot):
|
||||
def __init__(self, canvas=None, trad=None, toolbar=None,
|
||||
results=None, reach_id=0, profile_id=[0], res_id=[0],
|
||||
parent=None):
|
||||
super(PlotHEnsemble, self).__init__(
|
||||
canvas=canvas,
|
||||
trad=trad,
|
||||
data=results,
|
||||
toolbar=toolbar,
|
||||
parent=parent
|
||||
)
|
||||
|
||||
self._mode = "time"
|
||||
|
||||
self._parent = parent
|
||||
self._current_reach_id = reach_id
|
||||
self._current_profile_id = profile_id
|
||||
self._current_res_id = res_id
|
||||
self._timestamps = parent._timestamps
|
||||
self._current_timestamp = max(self._timestamps)
|
||||
|
||||
self.label_x = self._trad["unit_time_s"]
|
||||
self.label_y = self._trad["unit_discharge"]
|
||||
|
||||
self.label_discharge = _translate("Results", "Cross-section discharge")
|
||||
self.label_discharge_max = _translate("Results", "Max discharge")
|
||||
self.label_timestamp = _translate("Results", "Current timestamp")
|
||||
|
||||
self._isometric_axis = False
|
||||
|
||||
# self._auto_relim_update = False
|
||||
# self._autoscale_update = False
|
||||
|
||||
self._line_max = []
|
||||
self._line = []
|
||||
self._add_data_lines = []
|
||||
|
||||
@property
|
||||
def results(self):
|
||||
return self.data
|
||||
|
||||
@results.setter
|
||||
def results(self, results):
|
||||
self.data = results
|
||||
self._current_timestamp = max(self._timestamps)
|
||||
|
||||
@timer
|
||||
def draw(self, highlight=None):
|
||||
self.canvas.axes.cla()
|
||||
self.canvas.axes.grid(color='grey', linestyle='--', linewidth=0.5)
|
||||
|
||||
if self.results is None:
|
||||
return
|
||||
|
||||
if len(self._current_res_id) < 1:
|
||||
return
|
||||
|
||||
for res_id in self._current_res_id:
|
||||
if self.results[res_id] is None:
|
||||
continue
|
||||
|
||||
results = self.results[res_id]
|
||||
reach = results.river.reach(self._current_reach_id)
|
||||
|
||||
if reach.geometry.number_profiles == 0:
|
||||
self._init = False
|
||||
return
|
||||
|
||||
self.draw_data(res_id)
|
||||
self.draw_data_std_derivation(res_id)
|
||||
|
||||
self.canvas.axes.set_xlabel(
|
||||
self._trad["unit_time_s"],
|
||||
color='black', fontsize=10
|
||||
)
|
||||
|
||||
self.canvas.axes.set_ylabel(
|
||||
self._trad["unit_discharge"],
|
||||
color='black', fontsize=10
|
||||
)
|
||||
|
||||
self.set_ticks_time_formater()
|
||||
|
||||
self.draw_additional_data(0)
|
||||
|
||||
self.enable_legend()
|
||||
|
||||
self.canvas.draw_idle()
|
||||
self.update_idle()
|
||||
|
||||
self.draw_current()
|
||||
self._init = True
|
||||
|
||||
@timer
|
||||
def draw_data(self, res_id):
|
||||
results = self.results[res_id]
|
||||
reach = results.river.reach(self._current_reach_id)
|
||||
|
||||
colors = [
|
||||
("q_min", self.color_plot_ensemble_min),
|
||||
("q_mean", self.color_plot_ensemble_mean),
|
||||
("q_max", self.color_plot_ensemble_max),
|
||||
]
|
||||
|
||||
for t, c in colors:
|
||||
q = results.get("table")[t]
|
||||
profile = reach.profile(self._current_profile_id[0])
|
||||
|
||||
x = self._timestamps
|
||||
y = q[:, profile.global_index]
|
||||
# y = profile.get_key("Q")
|
||||
|
||||
if res_id == 2:
|
||||
label = f"Δ {self.label_discharge} {t} {profile.name}"
|
||||
else:
|
||||
label = f"{self.label_discharge} {t} {profile.name}"
|
||||
|
||||
line, = self.canvas.axes.plot(
|
||||
x, y,
|
||||
label=label,
|
||||
color=c,
|
||||
# linestyle=self.linestyle[i % len(self.linestyle)],
|
||||
**self.plot_default_kargs
|
||||
)
|
||||
|
||||
self._line.append(line)
|
||||
|
||||
@timer
|
||||
def draw_data_std_derivation(self, res_id):
|
||||
results = self.results[res_id]
|
||||
reach = results.river.reach(self._current_reach_id)
|
||||
|
||||
q = results.get("table")["q_mean"]
|
||||
std_deriv = results.get("table")["q_std_derivation"]
|
||||
profile = reach.profile(self._current_profile_id[0])
|
||||
|
||||
x = self._timestamps
|
||||
y = q[:, profile.global_index]
|
||||
std = std_deriv[:, profile.global_index]
|
||||
|
||||
y_b = y - std
|
||||
y_t = y + std
|
||||
|
||||
plot = self.canvas.axes.fill_between(
|
||||
x, y_b, y_t,
|
||||
label=f"Standard derivation {profile.name}",
|
||||
color=self.color_plot_ensemble_std_deriv,
|
||||
alpha=0.3,
|
||||
)
|
||||
|
||||
def draw_additional_data(self, res_id):
|
||||
results = self.results[res_id]
|
||||
|
||||
self._add_data_lines = []
|
||||
|
||||
for data in results.get("additional_data"):
|
||||
data = data._data
|
||||
x, y = data['x'], data['y']
|
||||
legend = data['legend']
|
||||
unit = data['unit']
|
||||
|
||||
if data['type_x'] == 'time' and data['type_y'] == 'discharge':
|
||||
line, = self.canvas.axes.plot(
|
||||
x, y, marker="+",
|
||||
label=legend + ' ' + unit
|
||||
)
|
||||
|
||||
self._add_data_lines.append(line)
|
||||
|
||||
self.enable_legend()
|
||||
self.canvas.draw_idle()
|
||||
|
||||
def draw_current(self):
|
||||
self._current, = self.canvas.axes.plot(
|
||||
[self._current_timestamp, self._current_timestamp],
|
||||
self.canvas.axes.get_ylim(),
|
||||
# label=self.label_timestamp,
|
||||
color="grey",
|
||||
linestyle="dashed",
|
||||
lw=1.,
|
||||
)
|
||||
|
||||
def set_reach(self, reach_id):
|
||||
self._current_reach_id = reach_id
|
||||
self._current_profile_id = [0]
|
||||
self.draw()
|
||||
|
||||
def set_profile(self, profile_id):
|
||||
self._current_profile_id = profile_id
|
||||
# self.update()
|
||||
self.draw()
|
||||
|
||||
def set_result(self, res_id):
|
||||
self._current_res_id = res_id
|
||||
self.draw()
|
||||
|
||||
def set_timestamp(self, timestamp):
|
||||
self._current_timestamp = timestamp
|
||||
self.update_current()
|
||||
self.update_idle()
|
||||
|
||||
def update(self):
|
||||
if not self._init:
|
||||
self.draw()
|
||||
|
||||
self.update_current()
|
||||
self.update_idle()
|
||||
|
||||
def update_additional_data(self):
|
||||
self.draw_additional_data(0)
|
||||
self.update_idle()
|
||||
|
||||
def update_all(self):
|
||||
self._current_reach_id = self._parent._get_current_reach()
|
||||
self._current_profile_id = self._parent._get_current_profiles_list()
|
||||
self._current_res_id = self._parent._get_current_results()
|
||||
self._current_timestamp = self._parent._get_current_timestamp()
|
||||
self._init = False
|
||||
self.update()
|
||||
|
||||
def update_current(self):
|
||||
y = self._current.get_ydata()
|
||||
self._current.set_data(
|
||||
[self._current_timestamp, self._current_timestamp],
|
||||
y
|
||||
)
|
||||
+10
-36
@@ -124,12 +124,8 @@ class PlotRKC(PamhyrPlot):
|
||||
table = results.get("table")["zfd"]
|
||||
ts = results.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
zfd = list(
|
||||
map(
|
||||
lambda p: table[ts, p.global_index],
|
||||
reach.profiles
|
||||
)
|
||||
)
|
||||
gi_0, gi_1 = reach.global_index
|
||||
zfd = table[ts, gi_0:gi_1 + 1]
|
||||
|
||||
self.line_bottom, = self.canvas.axes.plot(
|
||||
rk, zfd,
|
||||
@@ -189,14 +185,8 @@ class PlotRKC(PamhyrPlot):
|
||||
table = result.get("table")["Z"]
|
||||
ts = result.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
water_z = list(
|
||||
map(
|
||||
lambda p: table[
|
||||
ts, p.global_index
|
||||
],
|
||||
reach.profiles
|
||||
)
|
||||
)
|
||||
gi_0, gi_1 = reach.global_index
|
||||
water_z = table[ts, gi_0:gi_1 + 1]
|
||||
|
||||
self.water = self.canvas.axes.plot(
|
||||
rk, water_z,
|
||||
@@ -219,16 +209,8 @@ class PlotRKC(PamhyrPlot):
|
||||
table = result.get("table")["Z"]
|
||||
ts = result.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
water_z = list(
|
||||
map(
|
||||
lambda p: np.max(
|
||||
table[
|
||||
:, p.global_index
|
||||
]
|
||||
),
|
||||
reach.profiles
|
||||
)
|
||||
)
|
||||
gi_0, gi_1 = reach.global_index
|
||||
water_z = table[ts, gi_0:gi_1 + 1]
|
||||
|
||||
self.canvas.axes.plot(
|
||||
rk, water_z, lw=1.,
|
||||
@@ -361,14 +343,8 @@ class PlotRKC(PamhyrPlot):
|
||||
table = result.get("table")["Z"]
|
||||
ts = result.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
water_z = list(
|
||||
map(
|
||||
lambda p: table[
|
||||
ts, p.global_index
|
||||
],
|
||||
reach.profiles
|
||||
)
|
||||
)
|
||||
gi_0, gi_1 = reach.global_index
|
||||
water_z = table[ts, gi_0:gi_1 + 1]
|
||||
|
||||
self.water[0].set_data(
|
||||
rk, water_z
|
||||
@@ -411,10 +387,8 @@ class PlotRKC(PamhyrPlot):
|
||||
table = results.get("table")["zfd"]
|
||||
ts = results.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
zfd = list(map(
|
||||
lambda p: table[ts, p.global_index],
|
||||
reach.profiles
|
||||
))
|
||||
gi_0, gi_1 = reach.global_index
|
||||
zfd = table[ts, gi_0:gi_1 + 1]
|
||||
|
||||
self.line_bottom.remove()
|
||||
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
# PlotRKCEnsemble.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
import numpy as np
|
||||
|
||||
from functools import reduce
|
||||
|
||||
from tools import timer
|
||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
||||
|
||||
from PyQt5.QtCore import (
|
||||
QCoreApplication
|
||||
)
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class PlotRKCEnsemble(PamhyrPlot):
|
||||
def __init__(self, canvas=None, trad=None, toolbar=None,
|
||||
results=None, reach_id=0, profile_id=0,
|
||||
parent=None):
|
||||
super(PlotRKCEnsemble, self).__init__(
|
||||
canvas=canvas,
|
||||
trad=trad,
|
||||
data=results,
|
||||
toolbar=toolbar,
|
||||
parent=parent
|
||||
)
|
||||
|
||||
self._parent = parent
|
||||
self._current_reach_id = reach_id
|
||||
self._current_profile_id = profile_id
|
||||
self._timestamps = parent._timestamps
|
||||
self._current_timestamp = max(self._timestamps)
|
||||
|
||||
self.label_x = self._trad["unit_rk"]
|
||||
self.label_y = self._trad["unit_elevation"]
|
||||
|
||||
self.label_bottom = self._trad["label_bottom"]
|
||||
self.label_water = self._trad["label_water"]
|
||||
self.label_water_mean = self._trad["label_water_mean"]
|
||||
self.label_water_min = self._trad["label_water_min"]
|
||||
self.label_water_max = self._trad["label_water_max"]
|
||||
|
||||
self.water = []
|
||||
|
||||
self._isometric_axis = False
|
||||
|
||||
self._auto_relim_update = True
|
||||
self._autoscale_update = False
|
||||
|
||||
@property
|
||||
def results(self):
|
||||
return self.data
|
||||
|
||||
@results.setter
|
||||
def results(self, results):
|
||||
self.data = results
|
||||
self._current_timestamp = max(self._timestamps)
|
||||
|
||||
@timer
|
||||
def draw(self, highlight=None):
|
||||
self.init_axes()
|
||||
|
||||
if self.results is None:
|
||||
return
|
||||
|
||||
if self.results[0] is None:
|
||||
return
|
||||
|
||||
results = self.results[0]
|
||||
reach = results.river.reach(self._current_reach_id)
|
||||
|
||||
self.draw_bottom(reach)
|
||||
self.draw_std_derivation(reach)
|
||||
self.draw_water_elevation(reach)
|
||||
self.draw_current(reach)
|
||||
self.draw_profiles_hs(reach)
|
||||
|
||||
self.enable_legend()
|
||||
|
||||
self.idle()
|
||||
self._init = True
|
||||
|
||||
def draw_bottom(self, reach):
|
||||
self.draw_bottom_geometry(reach)
|
||||
|
||||
def draw_profiles_hs(self, reach):
|
||||
results = self.results[0]
|
||||
lhs = filter(
|
||||
lambda hs: hs._input_reach.reach is reach.geometry,
|
||||
filter(
|
||||
lambda hs: hs._input_reach is not None,
|
||||
results.study.river.hydraulic_structures.lst
|
||||
)
|
||||
)
|
||||
|
||||
for hs in lhs:
|
||||
x = hs.input_section.rk
|
||||
z_min = reach.geometry.get_z_min()
|
||||
z_max = reach.geometry.get_z_max()
|
||||
|
||||
self.canvas.axes.plot(
|
||||
[x, x],
|
||||
[min(z_min), max(z_max)],
|
||||
linestyle="--",
|
||||
lw=1.,
|
||||
color=self.color_plot_previous,
|
||||
)
|
||||
|
||||
self.canvas.axes.annotate(
|
||||
" > " + hs.name,
|
||||
(x, max(z_max)),
|
||||
horizontalalignment='left',
|
||||
verticalalignment='top',
|
||||
annotation_clip=True,
|
||||
fontsize=9, color=self.color_plot_previous,
|
||||
)
|
||||
|
||||
def draw_bottom_geometry(self, reach):
|
||||
rk = reach.geometry.get_rk()
|
||||
z_min = reach.geometry.get_z_min()
|
||||
z_max = reach.geometry.get_z_max()
|
||||
|
||||
self.line_rk_zmin = self.canvas.axes.plot(
|
||||
rk, z_min,
|
||||
color=self.color_plot_river_bottom,
|
||||
lw=1.
|
||||
)
|
||||
|
||||
self._river_bottom = z_min
|
||||
|
||||
def draw_water_elevation(self, reach):
|
||||
if len(reach.geometry.profiles) != 0:
|
||||
result = self.results[0]
|
||||
rk = reach.geometry.get_rk()
|
||||
|
||||
self.water = []
|
||||
|
||||
colors = [
|
||||
("z_min", self.color_plot_ensemble_min),
|
||||
("z_mean", self.color_plot_ensemble_mean),
|
||||
("z_max", self.color_plot_ensemble_max),
|
||||
]
|
||||
|
||||
for t, color in colors:
|
||||
table = result.get("table")[t]
|
||||
ts = result.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
gi_0, gi_1 = reach.global_index
|
||||
water_z = table[ts, gi_0:gi_1 + 1]
|
||||
|
||||
plot, = self.canvas.axes.plot(
|
||||
rk, water_z,
|
||||
lw=1., color=color,
|
||||
label=f"Elevation: {t} (m)",
|
||||
)
|
||||
|
||||
self.water.append(plot)
|
||||
|
||||
def draw_std_derivation(self, reach):
|
||||
if len(reach.geometry.profiles) != 0:
|
||||
result = self.results[0]
|
||||
rk = reach.geometry.get_rk()
|
||||
z_min = reach.geometry.get_z_min()
|
||||
|
||||
color = self.color_plot_ensemble_std_deriv
|
||||
|
||||
table = result.get("table")["z_mean"]
|
||||
std_deriv = result.get("table")["z_std_derivation"]
|
||||
|
||||
ts = result.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
gi_0, gi_1 = reach.global_index
|
||||
|
||||
water_z = table[ts, gi_0:gi_1 + 1]
|
||||
std = std_deriv[ts, gi_0:gi_1 + 1]
|
||||
|
||||
water_z_b = water_z - std
|
||||
water_z_t = water_z + std
|
||||
|
||||
plot = self.canvas.axes.fill_between(
|
||||
rk, water_z_b, water_z_t,
|
||||
lw=1., color=color, alpha=0.3,
|
||||
label=f"Standard derivation",
|
||||
)
|
||||
|
||||
self.water_std_deriv = plot
|
||||
|
||||
def draw_additional_data(self):
|
||||
results = self.results[0]
|
||||
|
||||
self._add_data_lines = []
|
||||
|
||||
for data in results.get("additional_data"):
|
||||
data = data._data
|
||||
|
||||
tx, ty = data['type_x'], data['type_y']
|
||||
x, y = data['x'], data['y']
|
||||
legend = data['legend']
|
||||
unit = data['unit']
|
||||
|
||||
if tx == 'water_elevation' and ty == 'time':
|
||||
line, = self.canvas.axes.plot(
|
||||
x, y, marker="+",
|
||||
label=legend + ' ' + unit
|
||||
)
|
||||
|
||||
self._add_data_lines.append(line)
|
||||
|
||||
self.canvas.draw_idle()
|
||||
|
||||
def draw_current(self, reach):
|
||||
rk = reach.geometry.get_rk()
|
||||
z_min = reach.geometry.get_z_min()
|
||||
z_max = reach.geometry.get_z_max()
|
||||
|
||||
self.profile, = self.canvas.axes.plot(
|
||||
[
|
||||
rk[self._current_profile_id],
|
||||
rk[self._current_profile_id]
|
||||
],
|
||||
[
|
||||
z_max[self._current_profile_id],
|
||||
z_min[self._current_profile_id]
|
||||
],
|
||||
color=self.color_plot,
|
||||
lw=1.
|
||||
)
|
||||
|
||||
def is_overflow_point(self, profile, point):
|
||||
left_limit = profile.geometry.point(0)
|
||||
right_limit = profile.geometry.point(
|
||||
profile.geometry.number_points - 1
|
||||
)
|
||||
|
||||
return (
|
||||
point == left_limit
|
||||
or point == right_limit
|
||||
)
|
||||
|
||||
def set_reach(self, reach_id):
|
||||
self._current_reach_id = reach_id
|
||||
self._current_profile_id = 0
|
||||
self.draw()
|
||||
|
||||
def set_profile(self, profile_id):
|
||||
self._current_profile_id = profile_id
|
||||
self.update_current()
|
||||
|
||||
def set_timestamp(self, timestamp):
|
||||
self._current_timestamp = timestamp
|
||||
self.update()
|
||||
|
||||
def update(self):
|
||||
if not self._init:
|
||||
self.draw()
|
||||
|
||||
results = self.results[0]
|
||||
reach = results.river.reach(self._current_reach_id)
|
||||
|
||||
self.update_water_elevation()
|
||||
self.update_std_derivation()
|
||||
|
||||
self.update_idle()
|
||||
|
||||
def update_all(self):
|
||||
self._current_reach_id = self._parent._get_current_reach()
|
||||
self._current_profile_id = self._parent._get_current_profile()
|
||||
self._current_timestamp = self._parent._get_current_timestamp()
|
||||
self._init = False
|
||||
self.update()
|
||||
|
||||
def update_water_elevation(self):
|
||||
result = self.results[0]
|
||||
reach = result.river.reach(self._current_reach_id)
|
||||
rk = reach.geometry.get_rk()
|
||||
z_min = reach.geometry.get_z_min()
|
||||
table = result.get("table")["z_mean"]
|
||||
ts = result.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
gi_0, gi_1 = reach.global_index
|
||||
water_z = table[ts, gi_0:gi_1 + 1]
|
||||
|
||||
colors = [
|
||||
(0, "z_min", self.color_plot_ensemble_min),
|
||||
(1, "z_mean", self.color_plot_ensemble_mean),
|
||||
(2, "z_max", self.color_plot_ensemble_max),
|
||||
]
|
||||
|
||||
for i, t, color in colors:
|
||||
table = result.get("table")[t]
|
||||
ts = result.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
gi_0, gi_1 = reach.global_index
|
||||
water_z = table[ts, gi_0:gi_1 + 1]
|
||||
|
||||
self.water[i].set_data(rk, water_z)
|
||||
|
||||
def update_std_derivation(self):
|
||||
result = self.results[0]
|
||||
reach = result.river.reach(self._current_reach_id)
|
||||
|
||||
rk = reach.geometry.get_rk()
|
||||
|
||||
table = result.get("table")["z_mean"]
|
||||
std_deriv = result.get("table")["z_std_derivation"]
|
||||
|
||||
ts = result.get_timestamp_id(self._current_timestamp)
|
||||
|
||||
gi_0, gi_1 = reach.global_index
|
||||
|
||||
water_z = table[ts, gi_0:gi_1 + 1]
|
||||
std = std_deriv[ts, gi_0:gi_1 + 1]
|
||||
|
||||
water_z_b = water_z - std
|
||||
water_z_t = water_z + std
|
||||
|
||||
self.water_std_deriv.set_data(rk, water_z_b, water_z_t)
|
||||
|
||||
def update_additional_data(self):
|
||||
self.draw_additional_data()
|
||||
self.update_idle()
|
||||
|
||||
def update_current(self):
|
||||
results = self.results[0]
|
||||
reach = results.river.reach(self._current_reach_id)
|
||||
rk = reach.geometry.get_rk()
|
||||
z_min = reach.geometry.get_z_min()
|
||||
z_max = reach.geometry.get_z_max()
|
||||
cid = self._current_profile_id
|
||||
|
||||
self.profile.set_data(
|
||||
[rk[cid], rk[cid]],
|
||||
[z_max[cid], z_min[cid]]
|
||||
)
|
||||
|
||||
self.canvas.figure.canvas.draw_idle()
|
||||
self.update_idle()
|
||||
@@ -24,6 +24,7 @@ import numpy as np
|
||||
|
||||
from tools import timer, trace, logger_exception
|
||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
||||
from matplotlib.backend_bases import MouseButton
|
||||
from matplotlib import collections
|
||||
|
||||
from PyQt5.QtCore import (
|
||||
@@ -89,7 +90,7 @@ class PlotXY(PamhyrPlot):
|
||||
def onpick(self, event):
|
||||
if event.mouseevent.inaxes != self.canvas.axes:
|
||||
return
|
||||
if event.mouseevent.button.value != 1:
|
||||
if event.mouseevent.button != MouseButton.LEFT:
|
||||
return
|
||||
|
||||
modifiers = QApplication.keyboardModifiers()
|
||||
|
||||
@@ -61,6 +61,8 @@ class TableModel(PamhyrTableModel):
|
||||
# _river.reach(0).profiles))
|
||||
elif self._opt_data == "solver":
|
||||
self._lst = self._parent._solvers
|
||||
elif self._opt_data == "runs":
|
||||
self._lst = self._data[0].get("table")["samples"]
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
self._timestamp = max(kwargs["parent"]._timestamps)
|
||||
@@ -93,6 +95,10 @@ class TableModel(PamhyrTableModel):
|
||||
if v is None:
|
||||
v = self._data[0].solver_name
|
||||
return str(v)
|
||||
elif self._opt_data == "runs":
|
||||
if self._headers[column] == "runs":
|
||||
p = self._lst[row, :]
|
||||
return f"{row}: {p}"
|
||||
elif self._opt_data == "raw_data":
|
||||
table = self._data[0].get("table")
|
||||
ts = self._data[0].get_timestamp_id(self._timestamp)
|
||||
|
||||
+679
-378
File diff suppressed because it is too large.
Load diff
@@ -44,6 +44,7 @@ class ResultsTranslate(MainTranslate):
|
||||
|
||||
self._dict['envelop'] = _translate("Results", "Envelop")
|
||||
self._dict['solver'] = _translate("Results", "Solver")
|
||||
self._dict['runs'] = _translate("Results", "Runs")
|
||||
|
||||
self._dict['x'] = _translate("Results", "X (m)")
|
||||
self._dict["temperature_map"] = _translate(
|
||||
@@ -55,10 +56,20 @@ class ResultsTranslate(MainTranslate):
|
||||
|
||||
self._dict['label_bottom'] = _translate("Results", "Bottom")
|
||||
self._dict['label_water'] = _translate("Results", "Water elevation")
|
||||
|
||||
self._dict['label_water_min'] = _translate(
|
||||
"Results",
|
||||
"Min water elevation"
|
||||
)
|
||||
self._dict['label_water_mean'] = _translate(
|
||||
"Results",
|
||||
"Mean water elevation"
|
||||
)
|
||||
self._dict['label_water_max'] = _translate(
|
||||
"Results",
|
||||
"Max water elevation"
|
||||
)
|
||||
|
||||
self._dict["ImageCoordinates"] = _translate(
|
||||
"Results", "Image coordinates"
|
||||
)
|
||||
@@ -87,6 +98,10 @@ class ResultsTranslate(MainTranslate):
|
||||
"solver": self._dict['solver'],
|
||||
}
|
||||
|
||||
self._sub_dict["table_headers_runs"] = {
|
||||
"runs": self._dict['runs'],
|
||||
}
|
||||
|
||||
self._sub_dict["table_headers_pollutants"] = {
|
||||
"name": _translate("Results", "Pollutant name"),
|
||||
}
|
||||
@@ -121,6 +136,25 @@ class ResultsTranslate(MainTranslate):
|
||||
"wet_area": self._dict["unit_wet_area"],
|
||||
}
|
||||
|
||||
self._sub_dict["values_x_ens"] = {
|
||||
"rk": self._dict["unit_rk"],
|
||||
"time": self._dict["unit_time_s"],
|
||||
}
|
||||
|
||||
self._sub_dict["values_y_ens"] = {
|
||||
"z_mean": self._dict["unit_mean_water_elevation"],
|
||||
"q_mean": self._dict["unit_mean_discharge"],
|
||||
"z_standard_derivation": self._dict["unit_std_deriv_elevation"],
|
||||
"q_standard_derivation": self._dict["unit_std_deriv_discharge"],
|
||||
}
|
||||
|
||||
self._sub_dict["values_y_envelop_ens"] = {
|
||||
"z_min": self._dict["unit_min_water_elevation"],
|
||||
"z_max": self._dict["unit_max_water_elevation"],
|
||||
"q_min": self._dict["unit_min_discharge"],
|
||||
"q_max": self._dict["unit_max_discharge"],
|
||||
}
|
||||
|
||||
if self.pollutants is not None:
|
||||
self._sub_dict["table_headers_raw_data"] = {
|
||||
"name": _translate("Results", "Profile"),
|
||||
@@ -151,7 +185,7 @@ class ResultsTranslate(MainTranslate):
|
||||
"max_velocity": self._dict["unit_max_velocity"],
|
||||
"min_depth": self._dict["unit_min_depth"],
|
||||
"max_depth": self._dict["unit_max_depth"],
|
||||
}
|
||||
}
|
||||
|
||||
self._sub_dict["values_y_pol"] = {
|
||||
"unit_C": self._dict["unit_concentration"],
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
# Translate.py -- Pamhyr
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
from PyQt5.QtCore import QCoreApplication
|
||||
|
||||
from View.Tools.PamhyrTranslate import PamhyrTranslate
|
||||
|
||||
_translate = QCoreApplication.translate
|
||||
|
||||
|
||||
class RunSolverTranslate(PamhyrTranslate):
|
||||
def __init__(self):
|
||||
super(RunSolverTranslate, self).__init__()
|
||||
|
||||
self._dict["invalid_options"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {key}: expected three digits, each 1 or 2, "
|
||||
"Select valid options in the parameters (tab Solid Transport)."
|
||||
)
|
||||
self._dict["unsupported_transport_law"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {key}: unsupported transport law {value!r}. "
|
||||
"Please choose another transport law from the list."
|
||||
)
|
||||
self._dict["warning"] = _translate("Solver", "Warning: {message}")
|
||||
self._dict["incompatible_upstream_boundary"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: REGIME=1 is incompatible with CONDAM=0. "
|
||||
"A reflecting upstream boundary cannot impose the water depth."
|
||||
)
|
||||
self._dict["missing_tcadim"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {key}: the selected transport law and options "
|
||||
"use a dimensionless critical stress given by the user. "
|
||||
"Fill it in the parameters (tab Solid Transport)."
|
||||
)
|
||||
self._dict["solid_boundary_downstream"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: solid boundary condition {name} at node "
|
||||
"{node}: RubarBE only reads a solid boundary condition at the "
|
||||
"upstream node. Remove it."
|
||||
)
|
||||
self._dict["solid_boundary_too_long"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: solid boundary condition {name} at node "
|
||||
"{node} has {count} points, RubarBE accepts at most {maximum}."
|
||||
)
|
||||
self._dict["save_list_invalid"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {key}: '{value}' is not a valid value. "
|
||||
"Separate the values with spaces or semicolons, use a dot as "
|
||||
"decimal separator, and give the times in seconds or "
|
||||
"days:hours:minutes:seconds."
|
||||
)
|
||||
self._dict["save_list_too_long"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {key} has {count} values, RubarBE accepts "
|
||||
"at most {maximum}."
|
||||
)
|
||||
self._dict["save_list_required"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {flag} is enabled but {key} is empty. Fill "
|
||||
"it in the solver parameters (tab Saves), or disable {flag}."
|
||||
)
|
||||
self._dict["abshyd_outside"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: rubarbe_abshyd: abscissa {rk} is outside "
|
||||
"reach {reach}, whose sections go from {first} to {last}."
|
||||
)
|
||||
self._dict["tnprof_outside"] = _translate(
|
||||
"Solver",
|
||||
"rubarbe_tnprof: times {times} s are outside the computation, "
|
||||
"from {tinit} s to {tmax} s. RubarBE saves the earlier ones at "
|
||||
"the first time steps and never reaches the later ones."
|
||||
)
|
||||
self._dict["solid_boundary_invalid"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: solid boundary condition {name} at node "
|
||||
"{node} must have D50 > 0 m and sigma >= 1 (1 for a uniform "
|
||||
"sediment)."
|
||||
)
|
||||
self._dict["multireach_unsupported"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: the Rubar export supports a single reach, "
|
||||
"{count} enabled reaches found."
|
||||
)
|
||||
self._dict["not_enough_profiles"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: reach {reach} needs at least two profiles."
|
||||
)
|
||||
self._dict["rk_not_increasing"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: the profiles of reach {reach} must have "
|
||||
"strictly increasing rk. Sort the profiles of the geometry."
|
||||
)
|
||||
self._dict["boundary_code_unsupported"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {key}={value} is not supported by the Rubar "
|
||||
"export (single reach)."
|
||||
)
|
||||
self._dict["boundary_missing"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {setting} requires a {kind} boundary "
|
||||
"condition at node {node}."
|
||||
)
|
||||
self._dict["boundary_unexpected"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: boundary condition {name} ({kind}) at node "
|
||||
"{node} is not used with {setting}. Remove it or change the "
|
||||
"boundary settings in the solver parameters."
|
||||
)
|
||||
self._dict["boundary_ambiguous"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: several {kind} boundary conditions at node "
|
||||
"{node}."
|
||||
)
|
||||
self._dict["structure_section"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: the section of hydraulic structure {name} is "
|
||||
"not a profile of reach {reach}."
|
||||
)
|
||||
self._dict["structure_empty_ignored"] = _translate(
|
||||
"Solver",
|
||||
"Hydraulic structure {name} has no enabled basic structure "
|
||||
"that RubarBE takes into account: it is ignored."
|
||||
)
|
||||
self._dict["structure_too_many"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: hydraulic structure {name} has {count} "
|
||||
"enabled basic structures, RubarBE accepts at most {maximum}."
|
||||
)
|
||||
self._dict["structure_too_many_structures"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {count} hydraulic structures, RubarBE accepts "
|
||||
"at most {maximum}."
|
||||
)
|
||||
self._dict["structure_same_section"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: hydraulic structures {first} and {second} are "
|
||||
"on the same section (rk {rk}). Put their basic structures in a "
|
||||
"single hydraulic structure."
|
||||
)
|
||||
self._dict["structure_type_ignored"] = _translate(
|
||||
"Solver",
|
||||
"Basic structure {name} of type {type} has no RubarBE "
|
||||
"equivalent: it is not taken into account. RubarBE accepts "
|
||||
"discharge weirs (S1), rectangular orifices (OR) and circular "
|
||||
"orifices (OC)."
|
||||
)
|
||||
self._dict["structure_maximal_loading"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: rectangular orifice {name}: RubarBE has no "
|
||||
"maximal loading elevation. Leave it at 9999.999."
|
||||
)
|
||||
self._dict["structure_siltation"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: circular orifice {name}: RubarBE has no "
|
||||
"siltation height. Set it to 0."
|
||||
)
|
||||
self._dict["structure_invalid"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: basic structure {name} must have a width (or "
|
||||
"diameter) > 0 and a discharge coefficient > 0."
|
||||
)
|
||||
self._dict["structure_loading_below"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: basic structure {name}: the loading elevation "
|
||||
"must be above the weir elevation."
|
||||
)
|
||||
self._dict["structure_format"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: a value of basic structure {name} does not fit "
|
||||
"the 10 columns of RubarBE (3 decimals)."
|
||||
)
|
||||
self._dict["lateral_empty_ignored"] = _translate(
|
||||
"Solver",
|
||||
"Lateral contribution {name} on reach {reach} has no value: it "
|
||||
"is ignored."
|
||||
)
|
||||
self._dict["lateral_solid_no_transport"] = _translate(
|
||||
"Solver",
|
||||
"Solid lateral contribution {name} on reach {reach} is not taken "
|
||||
"into account: sediment transport (rubarbe_trased) is disabled "
|
||||
"in the solver parameters."
|
||||
)
|
||||
self._dict["lateral_solid_unmatched"] = _translate(
|
||||
"Solver",
|
||||
"Solid lateral contribution {name} on reach {reach} is not taken "
|
||||
"into account: RubarBE brings sediment only with water, and no "
|
||||
"liquid lateral contribution has the same sections."
|
||||
)
|
||||
self._dict["lateral_solid_unisol"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: solid lateral contribution {name} on reach "
|
||||
"{reach} gives a solid discharge in kg/s, but the solver "
|
||||
"parameters set the solid unit (rubarbe_sediment_unisol) to a "
|
||||
"concentration. Set it to a mass discharge (kg/s)."
|
||||
)
|
||||
self._dict["lateral_solid_invalid"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: solid lateral contribution {name} on reach "
|
||||
"{reach} must have D50 > 0 m and sigma >= 1 (1 for a uniform "
|
||||
"sediment)."
|
||||
)
|
||||
self._dict["lateral_solid_conflict"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: solid lateral contributions {names} on reach "
|
||||
"{reach} are attached to the same liquid contribution {liquid} "
|
||||
"but have different D50 or sigma. RubarBE accepts a single "
|
||||
"grain size per inflow."
|
||||
)
|
||||
self._dict["lateral_iodev_disabled"] = _translate(
|
||||
"Solver",
|
||||
"Lateral contribution {name} on reach {reach} is not taken into "
|
||||
"account: lateral overflows (rubarbe_iodev) are disabled in the "
|
||||
"solver parameters."
|
||||
)
|
||||
self._dict["lateral_type_unsupported"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: lateral contribution {name} on reach {reach} "
|
||||
"has no type. Choose a type (lateral sources, rain or "
|
||||
"evaporation)."
|
||||
)
|
||||
self._dict["lateral_sections"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: the sections of lateral contribution {name} "
|
||||
"are not profiles of reach {reach}."
|
||||
)
|
||||
self._dict["lateral_not_sorted"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: the times of lateral contribution {name} on "
|
||||
"reach {reach} must be increasing."
|
||||
)
|
||||
self._dict["lateral_overlap"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: lateral contributions {first} and {second} "
|
||||
"on reach {reach} overlap, which RubarBE does not accept. Merge "
|
||||
"them or move one of them."
|
||||
)
|
||||
self._dict["lateral_too_long"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: the lateral contributions give {count} values "
|
||||
"(number of points times number of cells of their zone), "
|
||||
"RubarBE accepts at most {maximum}."
|
||||
)
|
||||
self._dict["boundary_empty_ignored"] = _translate(
|
||||
"Solver",
|
||||
"Boundary condition {name} at node {node} has no value: it is "
|
||||
"ignored."
|
||||
)
|
||||
self._dict["boundary_missing_empty"] = _translate(
|
||||
"Solver",
|
||||
"Empty boundary condition(s) ignored: {names}."
|
||||
)
|
||||
self._dict["boundary_not_sorted"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: the times of boundary condition {name} at "
|
||||
"node {node} must be increasing."
|
||||
)
|
||||
self._dict["upstream_level_unsupported"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: {setting} imposes an upstream water level, "
|
||||
"which the current RubarBE version reads but does not use in "
|
||||
"the computation. Choose another upstream boundary setting."
|
||||
)
|
||||
self._dict["missing_friction"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: no friction defined on reach {reach}."
|
||||
)
|
||||
self._dict["missing_initial_conditions"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: no initial condition defined on reach "
|
||||
"{reach}."
|
||||
)
|
||||
self._dict["discharge_out_of_range"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: initial discharges of reach {reach} must be "
|
||||
"greater than -500 m3/s."
|
||||
)
|
||||
self._dict["duplicate_point_name"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: several points are named '{name}' in "
|
||||
"profile {profile} of reach {reach}."
|
||||
)
|
||||
self._dict["main_channel"] = _translate("Solver", "main channel")
|
||||
self._dict["active_bed"] = _translate("Solver", "active bed")
|
||||
self._dict["bed_limits_invalid"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: in profile {profile} of reach {reach}, the "
|
||||
"{bed} limits (points '{left}' and '{right}', or the profile "
|
||||
"ends) must be ordered from left to right with at least one "
|
||||
"point between them."
|
||||
)
|
||||
self._dict["missing_sediment_layers"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: point {point} of profile {profile} of reach "
|
||||
"{reach} has no sediment layer, which the sediment transport "
|
||||
"requires."
|
||||
)
|
||||
self._dict["invalid_sediment_layer"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: layer '{layer}' of sediment layers '{sl}' "
|
||||
"(profile {profile} of reach {reach}) must have a thickness "
|
||||
">= 0, D50 > 0 m, sigma >= 1 (1 for a uniform sediment) and a "
|
||||
"critical constraint >= 0 Pa."
|
||||
)
|
||||
self._dict["too_many_compartments"] = _translate(
|
||||
"Solver",
|
||||
"Export cancelled: sediment layers '{sl}' (profile {profile} of "
|
||||
"reach {reach}) give {count} compartments, RubarBE accepts at "
|
||||
"most {maximum}. A non erodible compartment is added under an "
|
||||
"erodible last layer."
|
||||
)
|
||||
self._dict["export_failed"] = _translate(
|
||||
"Solver", "Export failed; task cancelled"
|
||||
)
|
||||
@@ -20,6 +20,8 @@ import os
|
||||
import logging
|
||||
import tempfile
|
||||
|
||||
import numpy as np
|
||||
|
||||
from queue import Queue
|
||||
from tools import trace, timer, logger_exception
|
||||
|
||||
@@ -40,7 +42,7 @@ from PyQt5.QtWidgets import (
|
||||
QFileDialog, QTableView, QAbstractItemView,
|
||||
QUndoStack, QShortcut, QAction, QItemDelegate,
|
||||
QComboBox, QVBoxLayout, QHeaderView, QTabWidget,
|
||||
QTextEdit,
|
||||
QTextEdit, QProgressBar, QCheckBox,
|
||||
)
|
||||
|
||||
from View.RunSolver.Log.Window import SolverLogFileWindow
|
||||
@@ -57,6 +59,63 @@ _translate = QCoreApplication.translate
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class EnsembleRunNumberDialog(PamhyrDialog):
|
||||
_pamhyr_ui = "EnsembleRunNumberDialog"
|
||||
_pamhyr_name = "EnsembleRunNumber"
|
||||
|
||||
def __init__(self, trad=None, parent=None):
|
||||
super(EnsembleRunNumberDialog, self).__init__(
|
||||
title=trad[self._pamhyr_name],
|
||||
trad=trad,
|
||||
options=[],
|
||||
parent=parent
|
||||
)
|
||||
|
||||
self._function = "Random"
|
||||
self._number = 100
|
||||
self._seed = -1
|
||||
|
||||
self._init_default_values()
|
||||
self._init_connection()
|
||||
|
||||
def _init_default_values(self):
|
||||
self.combobox_add_items("comboBox", ["Random"])
|
||||
self.set_combobox_text("comboBox", "Random")
|
||||
|
||||
self.set_spin_box("spinBox", 100)
|
||||
|
||||
def _init_connection(self):
|
||||
self._checkbox = self.find(QCheckBox, f"checkBox")
|
||||
self._checkbox.clicked.connect(self._set_random_seed_spin_box_state)
|
||||
|
||||
def _set_random_seed_spin_box_state(self):
|
||||
self.set_spin_box_enable("spinBox_seed", self._checkbox.isChecked())
|
||||
|
||||
@property
|
||||
def number(self):
|
||||
return self._number
|
||||
|
||||
@property
|
||||
def seed(self):
|
||||
return self._seed
|
||||
|
||||
@property
|
||||
def function(self):
|
||||
return self._function
|
||||
|
||||
def accept(self):
|
||||
self._function = self.get_combobox_text("comboBox")
|
||||
self._number = self.get_spin_box("spinBox")
|
||||
|
||||
if self._checkbox.isChecked():
|
||||
self._seed = self.get_spin_box("spinBox_seed")
|
||||
|
||||
super().accept()
|
||||
|
||||
def reject(self):
|
||||
self.close()
|
||||
|
||||
|
||||
class SelectSolverWindow(PamhyrDialog):
|
||||
_pamhyr_ui = "SelectSolver"
|
||||
_pamhyr_name = "Select solver"
|
||||
@@ -427,3 +486,233 @@ class SolverLogWindow(PamhyrWindow):
|
||||
parent=self,
|
||||
)
|
||||
log.show()
|
||||
|
||||
|
||||
class SolverLogEnsWindow(SolverLogWindow):
|
||||
_pamhyr_ui = "SolverLogEnsemble"
|
||||
_pamhyr_name = "Solver Log Ensemble"
|
||||
|
||||
def __init__(self, number_of_run=100,
|
||||
seed=-1, function="Random",
|
||||
study=None, config=None,
|
||||
solver=None, parent=None):
|
||||
self._number_of_run = number_of_run
|
||||
self._last_run = 0
|
||||
|
||||
if seed != -1:
|
||||
np.random.seed(seed)
|
||||
|
||||
self._seed = np.random.get_state()[1][0]
|
||||
logger.info(
|
||||
"solver: Set ensemble with " +
|
||||
f"{number_of_run} {function} and " +
|
||||
f"{self._seed} as random seed"
|
||||
)
|
||||
|
||||
self._samples = {}
|
||||
for ens in study.river._ensembles.lst:
|
||||
if ens.distribution is None:
|
||||
continue
|
||||
|
||||
self._samples[ens] = ens.random(self._number_of_run)
|
||||
|
||||
self._results = None
|
||||
self._run_samples = []
|
||||
self._results_tables = {}
|
||||
|
||||
super(SolverLogEnsWindow, self).__init__(
|
||||
solver=solver,
|
||||
study=study,
|
||||
config=config,
|
||||
parent=parent,
|
||||
)
|
||||
|
||||
def setup_connections(self):
|
||||
self.setup_progress_bar()
|
||||
|
||||
super(SolverLogEnsWindow, self).setup_connections()
|
||||
|
||||
def setup_progress_bar(self):
|
||||
self._progress_bar = self.find(QProgressBar, "progressBar")
|
||||
self._progress_bar.setRange(0, self._number_of_run)
|
||||
self._progress_bar.setValue(0)
|
||||
|
||||
def _log_int(self, int_code, color=None):
|
||||
logger.info(f"solver: Returns {int_code}")
|
||||
color = "blue" if int_code == 0 else "red"
|
||||
|
||||
self.find(QTextEdit, "textEdit")\
|
||||
.append(
|
||||
f"<font color=\"{color}\">" +
|
||||
f" *** Finished with code {int_code}" +
|
||||
"</font>"
|
||||
)
|
||||
|
||||
self.statusbar.showMessage(
|
||||
("Done" if int_code == 0 else "Failed")
|
||||
+ f" #{self._last_run}",
|
||||
3000
|
||||
)
|
||||
|
||||
self._solver.results_ensemble(
|
||||
self._study, self._workdir,
|
||||
self._results_tables,
|
||||
self._last_run,
|
||||
qlog=self._output,
|
||||
)
|
||||
|
||||
if self._last_run < self._number_of_run:
|
||||
self.next()
|
||||
else:
|
||||
self._results = self.fill_results_from_tables()
|
||||
self._parent.set_results(self._solver, self._results)
|
||||
|
||||
self._progress_bar.setValue(self._last_run)
|
||||
|
||||
def fill_results_from_tables(self):
|
||||
tables = self._results_tables
|
||||
results = self._solver.get_ensemble_empty_results(
|
||||
self._study, self._workdir
|
||||
)
|
||||
|
||||
table = {}
|
||||
|
||||
for key in ["z", "q"]:
|
||||
for func in ["min", "mean", "max", "std_derivation"]:
|
||||
name = f"{key}_{func}"
|
||||
table[name] = results.new_table_data(name, tables[name])
|
||||
|
||||
table["samples"] = results.new_table_data(
|
||||
"samples", np.array(self._run_samples)
|
||||
)
|
||||
results.set("number_of_run", self._number_of_run)
|
||||
results.set("seed", self._seed) # Keep random seed
|
||||
|
||||
results.set("table", table)
|
||||
|
||||
# Compute global index for reaches and profiles
|
||||
gi = 0
|
||||
for reach in results.river.reachs:
|
||||
gi_start = gi
|
||||
|
||||
for profile in reach.profiles:
|
||||
gi += 1
|
||||
|
||||
reach.set_global_index(range(gi_start, gi))
|
||||
|
||||
# Compute timestamps index table
|
||||
ts = tables["timestamps"]
|
||||
ts_index = {}
|
||||
for i, t in enumerate(sorted(ts)):
|
||||
ts_index[t] = i
|
||||
|
||||
results.set("timestamps", ts)
|
||||
results.set_timestamp_index(ts_index)
|
||||
|
||||
return results
|
||||
|
||||
def next(self):
|
||||
self._process = self.new_process(self._parent)
|
||||
|
||||
self._log(f" *** Run #{self._last_run}", color="blue")
|
||||
|
||||
if self._solver._type in ["mage8"]:
|
||||
samples = self._solver.export_ensemble_variation(
|
||||
self._study, self._workdir, qlog=self._output,
|
||||
samples=self._samples,
|
||||
)
|
||||
else:
|
||||
samples = self.ensemble_variation()
|
||||
self._solver.export(
|
||||
self._study, self._workdir, qlog=self._output
|
||||
)
|
||||
|
||||
# Keep samples generators results
|
||||
self._run_samples.append(samples)
|
||||
|
||||
self._solver.run(
|
||||
self._study,
|
||||
process=self._process,
|
||||
output_queue=self._output
|
||||
)
|
||||
|
||||
self.set_running_button_status()
|
||||
|
||||
self._last_run += 1
|
||||
self._progress_bar.setValue(self._last_run - 1)
|
||||
|
||||
def ensemble_variation(self):
|
||||
samples = []
|
||||
|
||||
for ens in self._samples:
|
||||
if ens.target_data is None:
|
||||
continue
|
||||
|
||||
x = next(self._samples[ens])
|
||||
samples.append(x)
|
||||
|
||||
self._log(f"*** Variation #{self._last_run} " +
|
||||
f"'{ens.target_data}' - {ens.data_type} x {x}",
|
||||
color="blue")
|
||||
|
||||
if ens.data_type == "strickler_minor":
|
||||
ens.target_data.minor = x
|
||||
elif ens.data_type == "strickler_medium":
|
||||
ens.target_data.medium = x
|
||||
|
||||
return samples
|
||||
|
||||
def run(self):
|
||||
self._log(f" *** Run solver {self._solver.name}", color="blue")
|
||||
self.next()
|
||||
|
||||
def start(self):
|
||||
if self._solver.is_stoped():
|
||||
self._log(f" *** Export study {self._solver.name}", color="blue")
|
||||
|
||||
ok = self._solver.export(
|
||||
self._study, self._workdir, qlog=self._output
|
||||
)
|
||||
|
||||
if not ok:
|
||||
self._log(f" *** Failed to export", color="red")
|
||||
self.update()
|
||||
return
|
||||
else:
|
||||
self.update()
|
||||
self._process = self.new_process(self._parent)
|
||||
|
||||
self._log(" *** Start", color="blue")
|
||||
self._results = None
|
||||
|
||||
self.next()
|
||||
|
||||
def set_running_button_status(self):
|
||||
self.find(QAction, "action_start").setEnabled(False)
|
||||
if _signal:
|
||||
self.find(QAction, "action_pause").setEnabled(True)
|
||||
else:
|
||||
self.find(QAction, "action_pause").setEnabled(False)
|
||||
self.find(QAction, "action_stop").setEnabled(True)
|
||||
self.find(QAction, "action_log_file").setEnabled(False)
|
||||
self.find(QAction, "action_results").setEnabled(False)
|
||||
|
||||
def stop(self):
|
||||
self._log(" *** Stop", color="blue")
|
||||
self._solver.kill()
|
||||
|
||||
self.find(QAction, "action_start").setEnabled(True)
|
||||
self.find(QAction, "action_pause").setEnabled(False)
|
||||
self.find(QAction, "action_stop").setEnabled(False)
|
||||
self.find(QAction, "action_results").setEnabled(True)
|
||||
if self._solver.log_file() != "":
|
||||
self.find(QAction, "action_log_file").setEnabled(True)
|
||||
|
||||
def results(self):
|
||||
if self._results is None:
|
||||
return
|
||||
|
||||
self._parent.set_results(self._solver, self._results)
|
||||
self._parent.open_solver_results(self._solver, self._results)
|
||||
|
||||
self._solver.has_results_loaded()
|
||||
@@ -47,11 +47,19 @@ class AbstractMenu(object):
|
||||
|
||||
class DefaultMenu(AbstractMenu):
|
||||
def run(self):
|
||||
current_scenario = self._graph.status.scenario
|
||||
|
||||
if current_scenario.is_ensemble():
|
||||
return
|
||||
|
||||
add_node = self._menu.addAction(self._trad["menu_add_scenario"])
|
||||
ensemble = self._menu.addAction(self._trad["menu_ens_scenario"])
|
||||
|
||||
action = self._exec()
|
||||
if action == add_node:
|
||||
self._parent.new_scenario(self._pos)
|
||||
if action == ensemble:
|
||||
self._parent.create_new_ensemble_scenario(self._pos)
|
||||
|
||||
|
||||
class ScenarioMenu(AbstractMenu):
|
||||
@@ -61,9 +69,13 @@ class ScenarioMenu(AbstractMenu):
|
||||
|
||||
current_scenario = item.graph._study.status.scenario.id
|
||||
|
||||
select = self._menu.addAction(self._trad["menu_select_scenario"])
|
||||
select = None
|
||||
duplicate = None
|
||||
delete = None
|
||||
edit_ens = None
|
||||
|
||||
if len(scenarios) > 1:
|
||||
select = self._menu.addAction(self._trad["menu_select_scenario"])
|
||||
|
||||
if item.scenario.id != 0:
|
||||
if scenarios.is_leaf(item.scenario):
|
||||
@@ -74,6 +86,11 @@ class ScenarioMenu(AbstractMenu):
|
||||
self._trad["menu_dup_scenario"]
|
||||
)
|
||||
|
||||
if item.scenario.is_ensemble():
|
||||
edit_ens = self._menu.addAction(
|
||||
self._trad["menu_edit_ens_scenario"]
|
||||
)
|
||||
|
||||
action = self._exec()
|
||||
if action is None:
|
||||
return
|
||||
@@ -83,3 +100,5 @@ class ScenarioMenu(AbstractMenu):
|
||||
self._parent.delete_scenario(item)
|
||||
elif action == duplicate:
|
||||
self._parent.duplicate_scenario(item)
|
||||
elif action == edit_ens:
|
||||
self._parent.edit_ensemble_scenario(item)
|
||||
@@ -100,7 +100,11 @@ class ScenarioItem(QGraphicsTextItem):
|
||||
)
|
||||
)
|
||||
painter.setBrush(QBrush(color))
|
||||
painter.drawEllipse(self.boundingRect())
|
||||
|
||||
if self.scenario.is_ensemble():
|
||||
painter.drawRect(self.boundingRect())
|
||||
else:
|
||||
painter.drawEllipse(self.boundingRect())
|
||||
|
||||
super(ScenarioItem, self).paint(painter, option, widget)
|
||||
|
||||
@@ -526,6 +530,51 @@ class GraphWidget(QGraphicsView):
|
||||
self.exec_with_waiting_window(fn, "duplicate_scenario")
|
||||
self.changeScenario.emit(self.sender())
|
||||
|
||||
def create_ensemble_scenario(self, item):
|
||||
must_save = self.dialog_save()
|
||||
if must_save == "Cancel":
|
||||
return
|
||||
|
||||
def fn():
|
||||
self._close_other_window()
|
||||
|
||||
if must_save == "Save":
|
||||
self._study.save()
|
||||
|
||||
self._undo.push(
|
||||
CreateEnsembleScenarioCommand(
|
||||
self._study,
|
||||
)
|
||||
)
|
||||
|
||||
self.exec_with_waiting_window(fn, "create_ensemble_scenario")
|
||||
self.changeScenario.emit(self.sender())
|
||||
|
||||
def create_new_ensemble_scenario(self, pos):
|
||||
must_save = self.dialog_save()
|
||||
if must_save == "Cancel":
|
||||
return
|
||||
|
||||
def fn():
|
||||
self._close_other_window()
|
||||
|
||||
if must_save == "Save":
|
||||
self._study.save()
|
||||
|
||||
self._undo.push(
|
||||
CreateEnsembleScenarioCommand(
|
||||
self._study, pos=pos,
|
||||
)
|
||||
)
|
||||
|
||||
self.exec_with_waiting_window(fn, "create_ensemble_scenario")
|
||||
self.changeScenario.emit(self.sender())
|
||||
|
||||
def edit_ensemble_scenario(self, item):
|
||||
self.parent\
|
||||
.parent\
|
||||
.open_ensemble_scenario()
|
||||
|
||||
def _close_other_window(self):
|
||||
self.parent\
|
||||
.parent\
|
||||
|
||||
@@ -98,6 +98,26 @@ class DuplicateScenariosCommand(QUndoCommand):
|
||||
self._study.reload_from_scenario(self._new)
|
||||
|
||||
|
||||
class CreateEnsembleScenarioCommand(QUndoCommand):
|
||||
def __init__(self, study, pos=None):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
self._study = study
|
||||
self._new = None
|
||||
self._pos = pos
|
||||
|
||||
def undo(self):
|
||||
self._study.scenarios.delete(self._new.id)
|
||||
self._study.reload_from_scenario(self._new.parent)
|
||||
|
||||
def redo(self):
|
||||
if self._new is None:
|
||||
self._new = self._study.create_ensemble_scenario(self._pos)
|
||||
else:
|
||||
self._new.set_as_not_deleted()
|
||||
self._study.reload_from_scenario(self._new)
|
||||
|
||||
|
||||
class SetCommand(QUndoCommand):
|
||||
def __init__(self, scenario, column, new_value):
|
||||
QUndoCommand.__init__(self)
|
||||
|
||||
@@ -43,6 +43,12 @@ class ScenariosTranslate(MainTranslate):
|
||||
self._dict["menu_dup_scenario"] = _translate(
|
||||
"Scenarios", "Duplicate this scenario"
|
||||
)
|
||||
self._dict["menu_ens_scenario"] = _translate(
|
||||
"Scenarios", "Create ensemble scenario from current scenario"
|
||||
)
|
||||
self._dict["menu_edit_ens_scenario"] = _translate(
|
||||
"Scenarios", "Edit this ensemble scenario"
|
||||
)
|
||||
|
||||
self._sub_dict["table_headers_scenarios"] = {
|
||||
# "id": self._dict['id'],
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Rubar parameter descriptions (notice sections 3.1, 3.10 and annex 1).
|
||||
|
||||
Keys and values keep their historical database representation.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal, DecimalException, InvalidOperation
|
||||
|
||||
from Solver.RubarBE import Rubar3
|
||||
|
||||
|
||||
GROUPS = ('Temps et calcul', 'Hydraulique', 'Transport solide',
|
||||
'Évolution du fond', 'Sauvegardes')
|
||||
YES_NO = {'y': 'Oui', 'n': 'Non'}
|
||||
ON_OFF = {'1': 'Oui', '0': 'Non'}
|
||||
LAWS = {
|
||||
'1': 'Meyer-Peter et Müller', '2': 'Engelund et Hansen', '3': 'Bagnold',
|
||||
'8': 'Ackers et White (1973)', '9': 'Smart et Jaeggi', '10': 'van Rijn',
|
||||
'11': 'Rickenmann', '12': 'Camenen et Larson', '13': 'Schoklitsch',
|
||||
'14': 'Sato, Hikkawa et Ashida', '15': 'Recking et al. (2008)',
|
||||
'16': 'Brownlie', '17': 'Laursen', '18': 'Ackers et White (1990)',
|
||||
'19': 'Karim', '20': 'Karim et Kennedy', '21': 'Yang et Lim (2003)',
|
||||
'22': 'Yang (1984)', '23': 'Yang (1979)', '24': 'Yang (1973)',
|
||||
'25': 'van Rijn (1984) — suspension', '26': 'van Rijn (1984) — charriage',
|
||||
'27': 'Recking et al. (2016)', '28': 'Piton et al. (2017)',
|
||||
'29': 'Lefort (2007)', '30': 'Lefort (2015)',
|
||||
}
|
||||
OPTION_CHOICES = (
|
||||
('Correction de pente',
|
||||
{'1': 'Correction d’Ikeda', '2': 'Sans correction'},
|
||||
'Permet d\'introduire que la répartition de la contrainte critique dans '
|
||||
'une section en travers est influencée par la pente transversale'),
|
||||
('Seuil critique', {'1': 'Fourni par l’utilisateur',
|
||||
'2': 'Calculé par le diagramme de Shields'},
|
||||
'Permet de choisir pour certaines formules de capacité, entre un seuil '
|
||||
'critique fourni par l’utilisateur ou '
|
||||
'un seuil critique calculé par le diagramme de Shields.'),
|
||||
('Contrainte utilisée', {'1': 'Contrainte efficace',
|
||||
'2': 'Contrainte non réduite'},
|
||||
'Permet de choisir pour certaines formules de capacité, entre la '
|
||||
'contrainte efficace calculée ou la contrainte non réduite.'),
|
||||
)
|
||||
|
||||
|
||||
# Choices read by RubarBE 2021 but never used by its computation: the
|
||||
# upstream level of HAMONT (rubar_init.f90). The export refuses them.
|
||||
UNSUPPORTED_CHOICES = {
|
||||
('rubarbe_condam', '2'): 'La version actuelle de RubarBE ne prend pas '
|
||||
'en compte la cote amont imposée.',
|
||||
('rubarbe_regime', '1'): 'La version actuelle de RubarBE ne prend pas '
|
||||
'en compte le tirant d’eau amont imposé.',
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Field:
|
||||
key: str
|
||||
group: int
|
||||
label: str
|
||||
help: str
|
||||
kind: str = 'real'
|
||||
choices: dict = None
|
||||
minimum: float = 0
|
||||
maximum: float = None
|
||||
positive: bool = False
|
||||
optional: bool = False
|
||||
|
||||
|
||||
def fields():
|
||||
"""Describe historical Rubar fields without changing their defaults."""
|
||||
result = []
|
||||
|
||||
def add(key, group, label, help, **kwargs):
|
||||
result.append(Field('rubarbe_' + key, group, label, help, **kwargs))
|
||||
|
||||
def choice(key, group, label, help, choices):
|
||||
add(key, group, label, help, kind='choice', choices=choices)
|
||||
|
||||
add('cfl', 0, 'Nombre de Courant (CFL)',
|
||||
'Limite supérieure du nombre de Courant, afin d\'assurer la stabilité '
|
||||
'du schéma numérique ; comprise entre 0 et 1.',
|
||||
positive=True, maximum=1)
|
||||
for key, label, help in (
|
||||
('tinit', 'Début du calcul',
|
||||
'Doit correspondre aux conditions initiales.'),
|
||||
('tmax', 'Fin du calcul', 'Doit être postérieure au début du calcul.'),
|
||||
):
|
||||
add(key, 0, label + ' (j:h:min:s ou s)', help, kind='time')
|
||||
choice('iopdt', 0, 'Gestion du pas de temps',
|
||||
'En mode mixte, le pas reste fixe jusqu’à la date de bascule.',
|
||||
{'y': 'Automatique', 'n': 'Fixe',
|
||||
'm': 'Mixte : fixe puis automatique'})
|
||||
add('dt', 0, 'Pas de temps initial ou fixe (s)',
|
||||
'Premier pas en mode automatique, pas demandé en mode fixe.',
|
||||
positive=True)
|
||||
add('tiopdt', 0, 'Fin de la période à pas fixe' + ' (j:h:min:s ou s)',
|
||||
'Utilisée uniquement avec un pas de temps mixte.', kind='time')
|
||||
choice('rep', 0, 'Reprendre un calcul',
|
||||
'Nécessite les fichiers de reprise du calcul précédent.', YES_NO)
|
||||
|
||||
choice('condam', 1, 'Condition à la limite amont',
|
||||
'Le choix doit correspondre aux données de la limite amont. '
|
||||
'La cote imposée n’est pas prise en compte par la version '
|
||||
'actuelle de RubarBE.',
|
||||
{'0': 'Réflexion', '1': 'Débit imposé Q(t)',
|
||||
'2': 'Cote imposée Z(t)', '4': 'Confluence'})
|
||||
choice('condav', 1, 'Condition à la limite aval',
|
||||
'Le choix doit correspondre aux données de la limite aval.',
|
||||
{'0': 'Sortie libre', '1': 'Courbe de tarage Q(Z)',
|
||||
'2': 'Réflexion',
|
||||
'3': 'Cote imposée Z(t)', '4': 'Confluence / défluence',
|
||||
'5': 'Régime uniforme', '7': 'Régime critique'})
|
||||
choice('regime', 1, 'Imposer aussi le tirant d’eau amont',
|
||||
'Complète le débit imposé ; non pris en compte par la version '
|
||||
'actuelle de RubarBE.',
|
||||
ON_OFF)
|
||||
choice('iodev', 1, 'Déversement latéral',
|
||||
'Nécessite les données de déversements latéraux.',
|
||||
YES_NO)
|
||||
for key, label, help in (
|
||||
('iodebord', 'Formule Debord',
|
||||
'Oui: utilise la formule Debord pour les lits composés.\nNon:'
|
||||
' pas de perte de charge complémentaire entre lit mineur et moyen.'),
|
||||
('iostockage', 'Stockage dans le lit majeur',
|
||||
'Traite le lit majeur sous la berge la plus basse comme zone '
|
||||
'de stockage.'),
|
||||
):
|
||||
choice(key, 1, label, help, YES_NO)
|
||||
choice('optfpc', 1, 'Calcul du frottement',
|
||||
'Strickler fourni ou frottement calculé à partir des sédiments.',
|
||||
{'0': 'Coefficients de Strickler fournis', '1': 'Brownlie (1983)',
|
||||
'2': 'Griffith (1981) - pour un fond mobile', '3': 'Karim (1995)',
|
||||
'4': 'Wu et Wang (1999)', '5': 'Yu et Lim (2003)',
|
||||
'6': 'Recking et al. (2008)', '7': 'Garde et Raju (1966)'})
|
||||
for key, label in (
|
||||
('ros', 'Masse volumique des sédiments (kg/m³)'),
|
||||
('dm', 'Diamètre médian des sédiments (m)'),
|
||||
('segma', 'Étendue granulométrique des sédiments (—)'),
|
||||
):
|
||||
add(key, 1, label,
|
||||
'Utilisé pour le frottement calculé sans transport solide '
|
||||
'(disponible uniquement si le transport solide est désactivé '
|
||||
'et que le calcul du frottement se fait avec les sédiments).',
|
||||
positive=True)
|
||||
|
||||
choice('trased', 2, 'Activer le transport solide',
|
||||
'Fonction de RubarBE. L’évolution du fond se règle séparément.',
|
||||
YES_NO)
|
||||
add('sediment_ros', 2, 'Masse volumique des sédiments (kg/m³)',
|
||||
'Masse volumique des grains.', positive=True)
|
||||
add('sediment_por', 2, 'Porosité des sédiments (—)',
|
||||
'Fraction du volume occupée par les vides : de 0 inclus à 1 exclu.',
|
||||
positive=True, maximum=1)
|
||||
choice('sediment_opts', 2, 'Loi de capacité solide',
|
||||
'Formule de capacité solide ; choisir selon le domaine '
|
||||
'physique.',
|
||||
LAWS)
|
||||
choice('sediment_unisol', 2, 'Unité des débits ou concentrations solides',
|
||||
'Unité des débits ou concentrations solides.',
|
||||
{'1': 'Débit massique (kg/s)', '2': 'Concentration (kg/m³)'})
|
||||
choice('sediment_odchar', 2, 'Distance de chargement',
|
||||
'Option de calcul de la ditance de chargement.',
|
||||
{'0': 'Distance constante', '1': 'Loi de Han', '2': 'Wu et Wang'})
|
||||
add('sediment_dcharg', 2, 'Distance de chargement constante (m)',
|
||||
'Utilisée uniquement si la distance de chargement est constante.')
|
||||
add('sediment_halfa', 2, 'Paramètre alpha de Han (m)',
|
||||
'Utilisé uniquement avec la loi de chargement de Han.')
|
||||
add('sediment_option', 2, 'Calcul de la contrainte critique',
|
||||
'Trois choix indépendants, enregistrés ensemble dans OPTION.',
|
||||
kind='options')
|
||||
add('sediment_tcadim', 2, 'Seuil critique adimensionnel (—)',
|
||||
'Contrainte critique adimensionnelle (TCADIM) fournie par '
|
||||
'l’utilisateur, par exemple 0,047 pour Meyer-Peter et Müller ou 0,15 '
|
||||
'pour Recking et al. (2008). Utilisée lorsque le seuil n’est pas '
|
||||
'calculé par le diagramme de Shields et que la loi en a besoin.',
|
||||
positive=True, optional=True)
|
||||
add('sediment_visc', 2, 'Viscosité cinématique de l’eau (m²/s)',
|
||||
'Viscosité cinématique de l’eau, variable avec la température. '
|
||||
'À 15 °C : environ 1,30 × 10⁻⁶ m²/s.', positive=True)
|
||||
choice('sediment_choixc', 2, 'Calcul de la contrainte hydrodynamique de '
|
||||
'cisaillement',
|
||||
'MPC : méthode des perpendiculaires confondues (notice §8.5).',
|
||||
{'1': 'MPC', '2': 'Répartition uniforme',
|
||||
'3': 'MPC — pente moyenne sur 3 segments',
|
||||
'4': 'MPC — moyenne sur 3 segments',
|
||||
'5': 'MPC — moyenne sur une distance de périmètre de '
|
||||
'longueur égale à la hauteur d’eau',
|
||||
'6': 'MPC — proportionnelle au diamètre de la couche '
|
||||
'puissance 1/3',
|
||||
'7': 'MPC — proportionnelle au Strickler puissance −3/2',
|
||||
'8': 'MPC — proportionnelle à la hauteur d’eau'})
|
||||
choice('sediment_capsol', 2, 'Calcul de la capacité solide',
|
||||
'Les méthodes 2 et 3 nécessitent une répartition MPC.',
|
||||
{'1': 'Contrainte moyenne, largeur active imposée',
|
||||
'2': 'Contrainte moyenne, largeur active calculée',
|
||||
'3': 'Répartition locale des contraintes'})
|
||||
add('sediment_mult_1', 2, 'Multiplicateur de la capacité de chariage (—)',
|
||||
'1 conserve la capacité calculée par la loi choisie.')
|
||||
|
||||
choice('sediment_defond', 3, 'Faire évoluer la géométrie du lit',
|
||||
'Le transport solide peut être calculé sans déformation du lit.',
|
||||
ON_OFF)
|
||||
choice('sediment_demix', 3, 'Activer le démixage',
|
||||
'Option pour le demixage de deux compartiments sédimentaires.',
|
||||
ON_OFF)
|
||||
for key, label in (
|
||||
('dchard', 'Distance de chargement pour le diamètre de sédiment (m)'),
|
||||
('dchars', 'Distance de chargement de l’étendue granulométrique des '
|
||||
'sédiments (m)'),
|
||||
):
|
||||
add('sediment_' + key, 3, label,
|
||||
'Utilisée uniquement lorsque le démixage est activé.')
|
||||
choice('sediment_typdef', 3, 'Actualisation de la masse active',
|
||||
'Actualise la masse active après une variation relative de 10⁻ⁿ.',
|
||||
{'0': 'À chaque pas', '1': 'Variation de 10 %',
|
||||
'2': 'Variation de 1 %', '3': 'Variation de 0,1 %',
|
||||
'4': 'Variation de 0,01 %'})
|
||||
choice('sediment_depot', 3, 'Méthode d\'application du dépôt',
|
||||
'Méthodes de déformation de la section décrites au §8.5.3.',
|
||||
{'1': 'Couches horizontales',
|
||||
'2': 'Uniforme sur le périmètre mouillé',
|
||||
'3': 'Inverse de la contrainte locale (1/τ)',
|
||||
'4': 'Selon le seuil critique — tout le lit actif mouillé',
|
||||
'5': 'Selon le seuil critique — une partie du lit actif mouillé',
|
||||
'6': 'Méthode 6 — fonction des contraintes (notice §8.5.3)',
|
||||
'7': 'Méthode 7 — fonction des contraintes (notice §8.5.3)',
|
||||
'8': 'Méthode 8 — code cité dans l’annexe 1'})
|
||||
choice('sediment_varcons', 3, 'Grandeurs conservées après déformation',
|
||||
'Les autres grandeurs hydrauliques sont recalculées.',
|
||||
{'1': 'Section mouillée et débit', '2': 'Niveau d’eau et débit',
|
||||
'3': 'Niveau d’eau et vitesse'})
|
||||
add('sediment_bmiu', 3, 'Tangente de l’angle de frottement interne (—)',
|
||||
'Saisir tan(angle), et non l’angle en degrés, de la valeur moyenne '
|
||||
'de la tangente de l\'angle de frottement interne de sédiments.',
|
||||
positive=True)
|
||||
for i, label in enumerate((
|
||||
'Épaisseur de couche active : multiplicateur du d84',
|
||||
'Épaisseur de fines infiltrantes : multiplicateur du d16',
|
||||
'Coefficient de mélange des couches superficielles',
|
||||
'Coefficient de création d’une couche de dépôt',
|
||||
), 2):
|
||||
add(f'sediment_mult_{i}', 3, label + ' (—)',
|
||||
'Facultatif : laisser vide pour utiliser le comportement '
|
||||
'du solveur.',
|
||||
optional=True)
|
||||
|
||||
for key, label, help in (
|
||||
('ts', 'Instant de sauvegarde pour reprise',
|
||||
'Écrit les fichiers de reprise lorsque cet instant est dépassé.'),
|
||||
('dtsauv', 'Intervalle de sauvegarde des profils',
|
||||
'0 demande une sauvegarde à chaque pas de calcul.'),
|
||||
('psave', 'Intervalle de sauvegarde des hydrogrammes',
|
||||
'0 demande une sauvegarde à chaque pas de calcul.'),
|
||||
):
|
||||
add(key, 4, label + ' (j:h:min:s ou s)', help, kind='time')
|
||||
for i, label in enumerate((
|
||||
'Fichiers de reprise', 'Hydrogrammes aux abscisses choisies',
|
||||
'Enveloppes des résultats', 'Profils aux instants choisis',
|
||||
'Profils à intervalle fixe', 'Temps de dépassement des débits',
|
||||
), 1):
|
||||
choice(f'tf_{i}', 4, label,
|
||||
'Les abscisses ou instants demandés '
|
||||
'doivent être définis dans les données correspondantes.',
|
||||
YES_NO)
|
||||
add('abshyd', 4, 'Abscisses des hydrogrammes (m)',
|
||||
'Abscisses (PK) où sont enregistrés hydrogrammes et limnigrammes '
|
||||
'au pas de sauvegarde des hydrogrammes, séparées par des espaces '
|
||||
'ou des points-virgules ; 100 au plus. Nécessaires si '
|
||||
'« Hydrogrammes aux abscisses choisies » vaut Oui.',
|
||||
kind='rk_list')
|
||||
add('tnprof', 4, 'Instants de sauvegarde des profils (j:h:min:s ou s)',
|
||||
'Instants séparés par des espaces ou des points-virgules ; 100 au '
|
||||
'plus. Nécessaires si « Profils aux instants choisis » vaut Oui ; '
|
||||
'les sorties complémentaires sont aussi écrites à ces instants.',
|
||||
kind='time_list')
|
||||
for i in range(1, 4):
|
||||
add(f'fdeb{i}', 4, f'Seuil de débit du front {i} (m³/s)',
|
||||
'Débit pour lequel à chaque abscisse, est enregistré le temps '
|
||||
'de premier dépassement (fichier TRAJEC si demandé).',
|
||||
positive=True)
|
||||
choice('iovis', 4, 'Sorties complémentaires',
|
||||
'Largeurs et sorties complémentaires hydrauliques et '
|
||||
'sédimentaires.',
|
||||
YES_NO)
|
||||
return {field.key: field for field in result}
|
||||
|
||||
|
||||
FIELDS = fields()
|
||||
|
||||
|
||||
def canonical(field, value):
|
||||
value = str(value).strip()
|
||||
if field.choices and 'y' in field.choices:
|
||||
aliases = {'o': 'y', 'y': 'y', 'n': 'n', 'm': 'm'}
|
||||
return aliases.get(value.lower(), value)
|
||||
return value
|
||||
|
||||
|
||||
def validate(field, value):
|
||||
"""Return a storage value or raise a user-facing validation error."""
|
||||
value = canonical(field, value)
|
||||
if field.kind == 'choice':
|
||||
if value not in field.choices:
|
||||
raise ValueError('Choisissez une valeur dans la liste.')
|
||||
return value
|
||||
if field.kind == 'options':
|
||||
if len(value) != 3 or any(c not in '12' for c in value):
|
||||
raise ValueError('Renseignez les trois choix de contrainte.')
|
||||
return value
|
||||
if field.kind == 'text':
|
||||
return value
|
||||
if field.kind in ('rk_list', 'time_list'):
|
||||
try:
|
||||
numbers = Rubar3.save_list(value, field.kind == 'time_list')
|
||||
except ValueError as error:
|
||||
raise ValueError(
|
||||
f'Valeur non reconnue : {error}. Séparez les valeurs par '
|
||||
'des espaces ou des points-virgules, avec un point pour '
|
||||
'les décimales.') from None
|
||||
if len(numbers) > Rubar3._max_saves:
|
||||
raise ValueError(f'{Rubar3._max_saves} valeurs au plus '
|
||||
'(limite de RubarBE).')
|
||||
return value
|
||||
if not value and field.optional:
|
||||
return value
|
||||
value = value.replace(',', '.').replace('d', 'E').replace('D', 'E')
|
||||
try:
|
||||
if field.kind == 'time' and ':' in value:
|
||||
parts = value.split(':')
|
||||
valid = all(p.isascii() and p.isdigit() for p in parts)
|
||||
if len(parts) != 4 or not valid:
|
||||
raise ValueError(
|
||||
'Utilisez j:h:min:s ou un nombre de secondes.')
|
||||
number = sum(Decimal(p) * factor for p, factor in
|
||||
zip(parts, (86400, 3600, 60, 1)))
|
||||
else:
|
||||
number = Decimal(value)
|
||||
except InvalidOperation:
|
||||
raise ValueError('Saisissez un nombre fini.') from None
|
||||
if not number.is_finite():
|
||||
raise ValueError('Saisissez un nombre fini.')
|
||||
if number < field.minimum or (field.positive and number == 0):
|
||||
raise ValueError('La valeur doit être strictement positive.'
|
||||
if field.positive else
|
||||
'La valeur doit être positive ou nulle.')
|
||||
if field.maximum is not None and number > field.maximum:
|
||||
raise ValueError(f'La valeur ne doit pas dépasser {field.maximum}.')
|
||||
if field.key == 'rubarbe_sediment_por' and number >= 1:
|
||||
raise ValueError('La porosité doit être inférieure à 1.')
|
||||
scientific = not field.key.startswith('rubarbe_sediment_')
|
||||
try:
|
||||
Rubar3._real(str(number), field.key, scientific=scientific)
|
||||
except (ValueError, DecimalException, OverflowError):
|
||||
raise ValueError(
|
||||
'Valeur trop longue ou hors plage pour le format du solveur '
|
||||
'(12 colonnes).' if scientific else
|
||||
'Valeur trop précise ou hors plage pour le format du solveur '
|
||||
'(10 colonnes).') from None
|
||||
return value
|
||||
|
||||
|
||||
def active(field, values):
|
||||
"""Dependencies only disable editing; stored values are never erased."""
|
||||
key = field.key.removeprefix('rubarbe_')
|
||||
transport = values.get('rubarbe_trased', 'n').lower() in ('y', 'o')
|
||||
if key.startswith('sediment_') and not transport:
|
||||
return False
|
||||
if key == 'tiopdt':
|
||||
return values.get('rubarbe_iopdt', '').lower() == 'm'
|
||||
if key == 'sediment_tcadim':
|
||||
return Rubar3.tcadim_required(
|
||||
values.get('rubarbe_sediment_opts', ''),
|
||||
values.get('rubarbe_sediment_option', ''))
|
||||
if key in ('ros', 'dm', 'segma'):
|
||||
return (not transport and
|
||||
values.get('rubarbe_optfpc', '0') not in ('', '0'))
|
||||
dependencies = {
|
||||
'sediment_dcharg': ('sediment_odchar', ('0',)),
|
||||
'sediment_halfa': ('sediment_odchar', ('1',)),
|
||||
'sediment_dchard': ('sediment_demix', ('1',)),
|
||||
'sediment_dchars': ('sediment_demix', ('1',)),
|
||||
'sediment_varcons': ('sediment_defond', ('1',)),
|
||||
'sediment_depot': ('sediment_defond', ('1',)),
|
||||
}
|
||||
if key in dependencies:
|
||||
source, accepted = dependencies[key]
|
||||
return values.get('rubarbe_' + source) in accepted
|
||||
if key.startswith('fdeb'):
|
||||
return values.get('rubarbe_tf_6', 'n').lower() in ('y', 'o')
|
||||
|
||||
def enabled(flag):
|
||||
return values.get('rubarbe_' + flag, 'n').lower() in ('y', 'o')
|
||||
|
||||
if key == 'abshyd':
|
||||
return enabled('tf_2')
|
||||
if key == 'tnprof':
|
||||
return enabled('tf_4') or enabled('iovis')
|
||||
return True
|
||||
@@ -0,0 +1,376 @@
|
||||
"""Grouped Rubar parameter editor, backed by the existing parameter list."""
|
||||
|
||||
from functools import partial
|
||||
|
||||
from PyQt5.QtCore import QCoreApplication, QEvent, Qt
|
||||
from PyQt5.QtGui import QKeySequence
|
||||
from PyQt5.QtWidgets import (
|
||||
QComboBox, QFormLayout, QLabel, QLineEdit, QScrollArea,
|
||||
QSizePolicy, QTabWidget, QVBoxLayout, QWidget,
|
||||
)
|
||||
|
||||
from View.SolverParameters.RubarFields import (
|
||||
FIELDS, GROUPS, OPTION_CHOICES, UNSUPPORTED_CHOICES, Field, active,
|
||||
canonical, validate,
|
||||
)
|
||||
from View.SolverParameters.UndoCommand import SetCommand
|
||||
|
||||
|
||||
def tr(text):
|
||||
return QCoreApplication.translate('RubarParameters', text)
|
||||
|
||||
|
||||
class RubarForm(QWidget):
|
||||
def __init__(self, parameters, undo, editable=True, parent=None):
|
||||
super().__init__(parent)
|
||||
self.parameters = parameters
|
||||
self.stack = undo
|
||||
self.editable = editable
|
||||
self.editors = {}
|
||||
self.labels = {}
|
||||
self.errors = {}
|
||||
self.descriptions = dict(FIELDS)
|
||||
self.indices = {p.name: i for i, p in enumerate(parameters.parameters)}
|
||||
self._refreshing = False
|
||||
self._options_pending = False
|
||||
layout = QVBoxLayout(self)
|
||||
intro = QLabel(tr('Les valeurs valides sont appliquées à l’étude. '
|
||||
'Pensez à enregistrer l’étude pour les conserver.'))
|
||||
intro.setWordWrap(True)
|
||||
layout.addWidget(intro)
|
||||
self.notice = QLabel()
|
||||
self.notice.setWordWrap(True)
|
||||
self.notice.setTextFormat(Qt.PlainText)
|
||||
layout.addWidget(self.notice)
|
||||
self.tabs = QTabWidget()
|
||||
layout.addWidget(self.tabs)
|
||||
forms = []
|
||||
for group in GROUPS:
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
|
||||
form.setRowWrapPolicy(QFormLayout.WrapLongRows)
|
||||
form.setVerticalSpacing(12)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setWidget(page)
|
||||
self.tabs.addTab(scroll, tr(group))
|
||||
forms.append(form)
|
||||
# Metadata order is stable even when stored parameter order changes.
|
||||
keys = [key for key in FIELDS if key in self.indices]
|
||||
keys += [key for key in self.indices if key not in FIELDS]
|
||||
for key in keys:
|
||||
field = self.descriptions.setdefault(key, Field(
|
||||
key, 0, key, 'Paramètre supplémentaire conservé tel quel.',
|
||||
kind='text'))
|
||||
self._add_field(field, forms[field.group])
|
||||
self.help = QLabel(tr(
|
||||
'Sélectionnez un réglage pour afficher son aide.'))
|
||||
self.help.setWordWrap(True)
|
||||
self.help.setTextFormat(Qt.PlainText)
|
||||
self.help.setMinimumHeight(60)
|
||||
layout.addWidget(self.help)
|
||||
self.stack.indexChanged.connect(self.refresh)
|
||||
self.refresh()
|
||||
|
||||
def _add_field(self, field, form):
|
||||
key = field.key
|
||||
container = QWidget()
|
||||
box = QVBoxLayout(container)
|
||||
box.setContentsMargins(0, 0, 0, 0)
|
||||
if field.kind == 'options':
|
||||
editor = QWidget()
|
||||
subform = QFormLayout(editor)
|
||||
subform.setContentsMargins(0, 0, 0, 0)
|
||||
self.option_editors = []
|
||||
for title, choices, tooltip in OPTION_CHOICES:
|
||||
combo = QComboBox()
|
||||
combo.setSizeAdjustPolicy(
|
||||
QComboBox.AdjustToMinimumContentsLengthWithIcon)
|
||||
combo.addItem(tr('À renseigner'), None)
|
||||
for value, label in choices.items():
|
||||
combo.addItem(tr(label), value)
|
||||
combo.currentIndexChanged.connect(self._commit_options)
|
||||
combo.setProperty('parameter', key)
|
||||
combo.installEventFilter(self)
|
||||
combo.setToolTip(tr(tooltip) + '\n' + key)
|
||||
subform.addRow(tr(title), combo)
|
||||
self.option_editors.append(combo)
|
||||
elif field.kind == 'choice':
|
||||
editor = QComboBox()
|
||||
editor.setSizeAdjustPolicy(
|
||||
QComboBox.AdjustToMinimumContentsLengthWithIcon)
|
||||
for value, label in field.choices.items():
|
||||
editor.addItem(tr(label), value)
|
||||
editor.currentIndexChanged.connect(
|
||||
partial(self._choice_changed, key))
|
||||
else:
|
||||
editor = QLineEdit()
|
||||
editor.setPlaceholderText(tr('Valeur du solveur') if field.optional
|
||||
else tr('Saisir une valeur'))
|
||||
editor.textEdited.connect(partial(self._check_draft, key))
|
||||
editor.editingFinished.connect(partial(self._finish_text, key))
|
||||
editor.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
|
||||
editor.setObjectName(key)
|
||||
editor.setProperty('parameter', key)
|
||||
editor.installEventFilter(self)
|
||||
editor.setToolTip(
|
||||
tr(field.help) + '\n' + key + '\nNotice §3.1 / §3.10')
|
||||
box.addWidget(editor)
|
||||
error = QLabel()
|
||||
error.setWordWrap(True)
|
||||
error.setTextFormat(Qt.PlainText)
|
||||
error.setStyleSheet('color: #b42318;')
|
||||
box.addWidget(error)
|
||||
label = QLabel(tr(field.label))
|
||||
label.setWordWrap(True)
|
||||
label.setFixedWidth(310)
|
||||
label.setMinimumHeight(label.heightForWidth(310))
|
||||
label.setBuddy(editor)
|
||||
label.setToolTip(editor.toolTip())
|
||||
form.addRow(label, container)
|
||||
self.editors[key] = editor
|
||||
self.labels[key] = label
|
||||
self.errors[key] = error
|
||||
|
||||
def eventFilter(self, watched, event):
|
||||
if event.type() in (QEvent.FocusIn, QEvent.Enter):
|
||||
key = watched.property('parameter')
|
||||
if key:
|
||||
field = self.descriptions[key]
|
||||
self.help.setText(tr(field.help) + '\n' + key)
|
||||
# Use the model undo stack even inside a line editor.
|
||||
if event.type() in (QEvent.ShortcutOverride, QEvent.KeyPress):
|
||||
if (event.matches(QKeySequence.Undo) or
|
||||
event.matches(QKeySequence.Redo)):
|
||||
if event.type() == QEvent.KeyPress:
|
||||
if event.matches(QKeySequence.Undo):
|
||||
self.undo()
|
||||
else:
|
||||
self.redo()
|
||||
event.accept()
|
||||
return True
|
||||
return super().eventFilter(watched, event)
|
||||
|
||||
def values(self):
|
||||
return {p.name: str(p.value) for p in self.parameters.parameters}
|
||||
|
||||
def _error(self, key, message):
|
||||
self.errors[key].setText(message)
|
||||
self.errors[key].setVisible(bool(message))
|
||||
self.editors[key].setStyleSheet(
|
||||
'QLineEdit { border: 1px solid #b42318; }' if message else '')
|
||||
|
||||
def _validated(self, key, value):
|
||||
try:
|
||||
value = validate(self.descriptions[key], value)
|
||||
except ValueError as error:
|
||||
self._error(key, tr(str(error)) + tr(' Valeur non enregistrée.'))
|
||||
return None
|
||||
self._error(key, '')
|
||||
return value
|
||||
|
||||
def _check_draft(self, key, value):
|
||||
self._validated(key, value)
|
||||
|
||||
def _finish_text(self, key):
|
||||
editor = self.editors[key]
|
||||
if editor.isModified():
|
||||
if self.commit(key, editor.text()):
|
||||
editor.setModified(False)
|
||||
|
||||
def _choice_changed(self, key, index):
|
||||
if not self._refreshing:
|
||||
value = self.editors[key].itemData(index)
|
||||
if value is not None:
|
||||
self.commit(key, value)
|
||||
|
||||
def _commit_options(self):
|
||||
if self._refreshing:
|
||||
return
|
||||
values = [combo.currentData() for combo in self.option_editors]
|
||||
key = 'rubarbe_sediment_option'
|
||||
if any(value is None for value in values):
|
||||
self._options_pending = True
|
||||
self._error(key, tr(
|
||||
'Renseignez les trois choix. Valeur non enregistrée.'))
|
||||
else:
|
||||
self._options_pending = False
|
||||
self.commit(key, ''.join(values))
|
||||
|
||||
def apply_pending(self):
|
||||
"""Commit focused text before Ctrl+S; leave invalid drafts visible."""
|
||||
values = self.values()
|
||||
if (values.get('rubarbe_condam') == '0' and
|
||||
values.get('rubarbe_regime') == '1'):
|
||||
self.tabs.setCurrentIndex(1)
|
||||
self.editors['rubarbe_condam'].setFocus()
|
||||
return False
|
||||
for key, editor in self.editors.items():
|
||||
if (isinstance(editor, QLineEdit) and editor.isModified() and
|
||||
active(self.descriptions[key], self.values())):
|
||||
if not self.commit(key, editor.text()):
|
||||
self.tabs.setCurrentIndex(self.descriptions[key].group)
|
||||
editor.setFocus()
|
||||
return False
|
||||
if (self._options_pending and
|
||||
active(FIELDS['rubarbe_sediment_option'], self.values())):
|
||||
self.tabs.setCurrentIndex(2)
|
||||
self.option_editors[0].setFocus()
|
||||
return False
|
||||
return True
|
||||
|
||||
def commit(self, key, value):
|
||||
field = self.descriptions[key]
|
||||
if not self.editable or not active(field, self.values()):
|
||||
return False
|
||||
value = self._validated(key, value)
|
||||
if value is None:
|
||||
return False
|
||||
values = self.values()
|
||||
values[key] = value
|
||||
if (key in ('rubarbe_condam', 'rubarbe_regime') and
|
||||
values.get('rubarbe_condam') == '0' and
|
||||
values.get('rubarbe_regime') == '1'):
|
||||
self.refresh()
|
||||
return False
|
||||
if isinstance(self.editors[key], QLineEdit):
|
||||
self.editors[key].setModified(False)
|
||||
if self.values()[key] != value:
|
||||
self.stack.push(SetCommand(self.parameters, self.indices[key],
|
||||
'value', value))
|
||||
elif isinstance(self.editors[key], QLineEdit):
|
||||
self.editors[key].setText(value)
|
||||
return True
|
||||
|
||||
def refresh(self, *args):
|
||||
self._refreshing = True
|
||||
values = self.values()
|
||||
for key, editor in self.editors.items():
|
||||
field = self.descriptions[key]
|
||||
value = canonical(field, values[key])
|
||||
enabled = active(field, values)
|
||||
editor.setEnabled(self.editable and enabled)
|
||||
self.labels[key].setEnabled(enabled)
|
||||
if isinstance(editor, QLineEdit) and editor.isModified():
|
||||
self._validated(key, editor.text())
|
||||
continue
|
||||
if field.kind == 'options' and self._options_pending:
|
||||
self.errors[key].setVisible(enabled)
|
||||
continue
|
||||
if field.kind == 'options':
|
||||
valid = len(value) == 3 and all(c in '12' for c in value)
|
||||
for i, combo in enumerate(self.option_editors):
|
||||
index = combo.findData(value[i]) if valid else 0
|
||||
combo.setCurrentIndex(index)
|
||||
elif isinstance(editor, QComboBox):
|
||||
# Display unknown historical values without replacing them.
|
||||
for i in reversed(range(editor.count())):
|
||||
if editor.itemData(i) is None:
|
||||
editor.removeItem(i)
|
||||
index = editor.findData(value)
|
||||
if index < 0:
|
||||
editor.addItem(tr('Valeur non reconnue : ') + value, None)
|
||||
index = editor.count() - 1
|
||||
editor.setCurrentIndex(index)
|
||||
else:
|
||||
editor.setText(values[key])
|
||||
try:
|
||||
validate(field, values[key])
|
||||
self._error(key, '')
|
||||
except ValueError as error:
|
||||
self._error(key, tr('Valeur enregistrée à vérifier : ') +
|
||||
values[key] + ' — ' + tr(str(error)))
|
||||
self.errors[key].setVisible(
|
||||
enabled and bool(self.errors[key].text()))
|
||||
self._update_context(values)
|
||||
for key, forbidden, blocked in (
|
||||
('rubarbe_regime', '1', values.get('rubarbe_condam') == '0'),
|
||||
('rubarbe_condam', '0', values.get('rubarbe_regime') == '1'),
|
||||
):
|
||||
editor = self.editors.get(key)
|
||||
if editor is None:
|
||||
continue
|
||||
index = editor.findData(forbidden)
|
||||
if index >= 0:
|
||||
editor.model().item(index).setEnabled(not blocked)
|
||||
# Unsupported choices stay visible, so a stored value is still
|
||||
# displayed, but cannot be selected anymore
|
||||
for (key, value), reason in UNSUPPORTED_CHOICES.items():
|
||||
editor = self.editors.get(key)
|
||||
index = editor.findData(value) if editor is not None else -1
|
||||
if index >= 0:
|
||||
item = editor.model().item(index)
|
||||
item.setEnabled(False)
|
||||
item.setToolTip(tr(reason))
|
||||
self._refreshing = False
|
||||
|
||||
def _update_context(self, values):
|
||||
warnings = []
|
||||
if not self.editable:
|
||||
warnings.append(tr('Étude en lecture seule.'))
|
||||
transport = values.get('rubarbe_trased', '').lower() in ('y', 'o')
|
||||
if not transport:
|
||||
warnings.append(tr('Transport solide désactivé : les réglages '
|
||||
'sédimentaires sont conservés mais inactifs.'))
|
||||
elif (values.get('rubarbe_sediment_capsol') in ('2', '3') and
|
||||
values.get('rubarbe_sediment_choixc') == '2'):
|
||||
warnings.append(tr(
|
||||
'La capacité solide choisie nécessite une méthode MPC ; '
|
||||
'la répartition uniforme est incompatible.'))
|
||||
if (values.get('rubarbe_condam') == '0' and
|
||||
values.get('rubarbe_regime') == '1'):
|
||||
warnings.append(tr('Une limite amont réfléchissante ne permet pas '
|
||||
'd’imposer aussi le tirant d’eau.'))
|
||||
for (key, value), reason in UNSUPPORTED_CHOICES.items():
|
||||
if values.get(key) == value:
|
||||
warnings.append(tr(reason) + tr(
|
||||
' Le calcul sera refusé : choisissez un autre réglage '
|
||||
'de la limite amont.'))
|
||||
try:
|
||||
from tools import old_pamhyr_date_to_timestamp
|
||||
|
||||
def seconds(value):
|
||||
return (old_pamhyr_date_to_timestamp(value) if ':' in value
|
||||
else float(value.replace(',', '.')))
|
||||
|
||||
start = seconds(values['rubarbe_tinit'])
|
||||
if seconds(values['rubarbe_tmax']) <= start:
|
||||
warnings.append(tr('La fin du calcul doit suivre son début.'))
|
||||
except (KeyError, ValueError):
|
||||
pass
|
||||
if transport:
|
||||
try:
|
||||
if float(values.get('rubarbe_sediment_visc', '0')) > 0.001:
|
||||
warnings.append(tr(
|
||||
'Viscosité élevée pour de l’eau : vérifiez la valeur. '
|
||||
'Le seuil critique adimensionnel se saisit dans son '
|
||||
'propre champ.'))
|
||||
except ValueError:
|
||||
pass
|
||||
if (FIELDS['rubarbe_sediment_tcadim'].key in self.editors and
|
||||
active(FIELDS['rubarbe_sediment_tcadim'], values) and
|
||||
not values.get('rubarbe_sediment_tcadim', '').strip()):
|
||||
warnings.append(tr(
|
||||
'La loi et les options choisies utilisent un seuil '
|
||||
'critique adimensionnel : renseignez-le.'))
|
||||
self.notice.setText('\n'.join(warnings))
|
||||
self.notice.setVisible(bool(warnings))
|
||||
|
||||
def undo(self):
|
||||
if self.editable:
|
||||
self._options_pending = False
|
||||
for editor in self.editors.values():
|
||||
if isinstance(editor, QLineEdit):
|
||||
editor.setModified(False)
|
||||
self.stack.undo()
|
||||
self.refresh()
|
||||
|
||||
def redo(self):
|
||||
if self.editable:
|
||||
self._options_pending = False
|
||||
for editor in self.editors.values():
|
||||
if isinstance(editor, QLineEdit):
|
||||
editor.setModified(False)
|
||||
self.stack.redo()
|
||||
self.refresh()
|
||||
@@ -42,6 +42,7 @@ from PyQt5.QtWidgets import (
|
||||
|
||||
from View.SolverParameters.UndoCommand import *
|
||||
from View.SolverParameters.Table import TableModel, ValueDelegate
|
||||
from View.SolverParameters.RubarForm import RubarForm
|
||||
from View.SolverParameters.translate import ParamTranslate
|
||||
|
||||
from Solver.Solvers import solver_long_name, solver_type_list
|
||||
@@ -62,7 +63,7 @@ class SolverParametersWindow(PamhyrWindow):
|
||||
title=name,
|
||||
study=study,
|
||||
config=config,
|
||||
options=['copy'],
|
||||
options=['undo', 'copy'],
|
||||
trad=trad,
|
||||
parent=parent
|
||||
)
|
||||
@@ -88,6 +89,15 @@ class SolverParametersWindow(PamhyrWindow):
|
||||
editable_headers = []
|
||||
|
||||
for st in solver_type_list:
|
||||
if st in ('rubar3', 'rubarbe'):
|
||||
widget = RubarForm(
|
||||
self._study.river.get_params(st), self._undo_stack[st],
|
||||
editable=self._study.is_editable(),
|
||||
)
|
||||
widget.setObjectName(f"tab_{st}")
|
||||
self._table[st] = widget
|
||||
self._tab_widget.addTab(widget, solver_long_name[st])
|
||||
continue
|
||||
# Create widgets
|
||||
widget = QWidget()
|
||||
grid = QGridLayout()
|
||||
@@ -135,8 +145,19 @@ class SolverParametersWindow(PamhyrWindow):
|
||||
tab = self.current_tab()
|
||||
self._table[tab].redo()
|
||||
|
||||
def _save(self, source):
|
||||
for editor in self._table.values():
|
||||
if isinstance(editor, RubarForm) and not editor.apply_pending():
|
||||
self._tab_widget.setCurrentWidget(editor)
|
||||
return
|
||||
return super()._save(source)
|
||||
|
||||
def _copy(self):
|
||||
logger.info("TODO: copy")
|
||||
editor = self.focusWidget()
|
||||
if isinstance(editor, QLineEdit):
|
||||
editor.copy()
|
||||
|
||||
def _paste(self):
|
||||
logger.info("TODO: paste")
|
||||
editor = self.focusWidget()
|
||||
if isinstance(editor, QLineEdit) and self._study.is_editable():
|
||||
editor.paste()
|
||||
@@ -19,7 +19,7 @@
|
||||
import logging
|
||||
|
||||
from datetime import datetime
|
||||
from tools import get_user_name
|
||||
from tools import get_user_name, parse_datetime, format_datetime
|
||||
|
||||
from Modules import Modules
|
||||
from Model.Study import Study
|
||||
@@ -34,7 +34,7 @@ from PyQt5.QtGui import (
|
||||
from PyQt5.QtWidgets import (
|
||||
QRadioButton, QLabel, QDateTimeEdit,
|
||||
QTextEdit, QPlainTextEdit, QTextBrowser,
|
||||
QPushButton,
|
||||
QPushButton, QMessageBox,
|
||||
)
|
||||
|
||||
_translate = QCoreApplication.translate
|
||||
@@ -155,7 +155,80 @@ All right reserved.
|
||||
self.find(QLabel, "label_date").setEnabled(True)
|
||||
self.find(QDateTimeEdit, "dateTimeEdit_date").setEnabled(True)
|
||||
|
||||
def _close_study_editors(self):
|
||||
def close_children(parent):
|
||||
for _, window in list(parent.sub_win_list):
|
||||
if window is self:
|
||||
continue
|
||||
if not close_children(window):
|
||||
return False
|
||||
if not window.close():
|
||||
return False
|
||||
undo = getattr(window, "_undo_stack", None)
|
||||
if undo is not None:
|
||||
undo.clear()
|
||||
window.deleteLater()
|
||||
return True
|
||||
|
||||
return close_children(self.parent)
|
||||
|
||||
def accept(self):
|
||||
preserve_dates = False
|
||||
if (
|
||||
self._study is not None
|
||||
and self._study.time_system == "date"
|
||||
and self.get_radio_button("radioButton_date")
|
||||
):
|
||||
old_date = parse_datetime(self._study.date)
|
||||
new_date = parse_datetime(
|
||||
self.get_datetime_edit("dateTimeEdit_date")
|
||||
)
|
||||
if new_date != old_date:
|
||||
dialog = QMessageBox(self)
|
||||
dialog.setWindowTitle(_translate(
|
||||
"Study", "Change simulation start date?"
|
||||
))
|
||||
dialog.setText(_translate(
|
||||
"Study", "How should the data dates change?"
|
||||
))
|
||||
dialog.setInformativeText(_translate(
|
||||
"Study",
|
||||
"Previous start: {old}\nNew start: {new}\n\n"
|
||||
"Shift dates: keep elapsed simulation times unchanged.\n"
|
||||
"Keep dates: adjust elapsed times so calendar dates "
|
||||
"stay unchanged."
|
||||
).format(
|
||||
old=format_datetime(old_date),
|
||||
new=format_datetime(new_date)
|
||||
))
|
||||
shift = dialog.addButton(
|
||||
_translate("Study", "Shift dates"),
|
||||
QMessageBox.AcceptRole
|
||||
)
|
||||
keep = dialog.addButton(
|
||||
_translate("Study", "Keep dates"),
|
||||
QMessageBox.ActionRole
|
||||
)
|
||||
cancel = dialog.addButton(QMessageBox.Cancel)
|
||||
dialog.setDefaultButton(cancel)
|
||||
dialog.exec()
|
||||
if dialog.clickedButton() not in (shift, keep):
|
||||
return
|
||||
preserve_dates = dialog.clickedButton() is keep
|
||||
|
||||
if self._study is not None:
|
||||
date_mode = self.get_radio_button("radioButton_date")
|
||||
mode_changed = date_mode != (self._study.time_system == "date")
|
||||
date_changed = date_mode and (
|
||||
parse_datetime(self.get_datetime_edit("dateTimeEdit_date"))
|
||||
!= parse_datetime(self._study.date)
|
||||
)
|
||||
if (
|
||||
(mode_changed or date_changed)
|
||||
and not self._close_study_editors()
|
||||
):
|
||||
return
|
||||
|
||||
name = self.get_line_edit_text("lineEdit_name")
|
||||
description = self.get_plaintext_edit_text("plainTextEdit_description")
|
||||
|
||||
@@ -172,7 +245,9 @@ All right reserved.
|
||||
self._study.description = description
|
||||
if self.get_radio_button("radioButton_date"):
|
||||
date = self.get_datetime_edit("dateTimeEdit_date")
|
||||
self._study.use_date(date)
|
||||
self._study.change_start_date(
|
||||
date, preserve_dates=preserve_dates
|
||||
)
|
||||
else:
|
||||
self._study.use_time()
|
||||
|
||||
|
||||
@@ -107,7 +107,7 @@ class WindowToolKit(object):
|
||||
|
||||
dialog = QFileDialog(self, options=options)
|
||||
|
||||
if select_file == "Existing_file":
|
||||
if select_file == "ExistingFile":
|
||||
mode = QFileDialog.FileMode.ExistingFile
|
||||
elif select_file == "Directory":
|
||||
mode = QFileDialog.FileMode.Directory
|
||||
@@ -390,6 +390,18 @@ class ASubWindowFeatures(object):
|
||||
"""
|
||||
return self.find(QSpinBox, name).value()
|
||||
|
||||
def set_spin_box_enable(self, name: str, value: bool):
|
||||
"""Set status of spinbox component
|
||||
|
||||
Args:
|
||||
name: The spinbox component name
|
||||
value: The boolean value
|
||||
|
||||
Returns:
|
||||
Nothing
|
||||
"""
|
||||
self.find(QSpinBox, name).setEnabled(value)
|
||||
|
||||
def set_double_spin_box(self, name: str, value: int):
|
||||
"""Set value of spinbox component
|
||||
|
||||
|
||||
@@ -42,6 +42,12 @@ class PamhyrPlot(APlot):
|
||||
color_plot_river_bottom = "grey"
|
||||
color_plot_river_water = "blue"
|
||||
color_plot_river_water_zone = "skyblue"
|
||||
|
||||
color_plot_ensemble_min = "green"
|
||||
color_plot_ensemble_mean = "black"
|
||||
color_plot_ensemble_max = "red"
|
||||
color_plot_ensemble_std_deriv = "black"
|
||||
|
||||
colors = list(mplcolors.TABLEAU_COLORS)
|
||||
linestyle = ['solid', 'dashed', 'dashdot', 'dotted']
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
import logging
|
||||
import traceback
|
||||
from datetime import timezone
|
||||
|
||||
from tools import trace, timer, parse_datetime
|
||||
|
||||
@@ -63,8 +62,22 @@ class PamhyrTextDelegate(QStyledItemDelegate):
|
||||
|
||||
|
||||
class PamhyrTableModel(QAbstractTableModel):
|
||||
def date_to_timestamp(self, value):
|
||||
"""Convert an accepted calendar date to its raw UTC timestamp."""
|
||||
@property
|
||||
def time_system(self):
|
||||
return (
|
||||
self._study.time_system
|
||||
if self._study is not None else self._opt_data
|
||||
)
|
||||
|
||||
@property
|
||||
def start_date(self):
|
||||
return (
|
||||
self._study.date
|
||||
if self._study is not None else self._start_date
|
||||
)
|
||||
|
||||
def date_to_elapsed_seconds(self, value):
|
||||
"""Convert an accepted calendar date to elapsed simulation seconds."""
|
||||
try:
|
||||
entered_date = parse_datetime(value)
|
||||
except ValueError as error:
|
||||
@@ -82,7 +95,7 @@ class PamhyrTableModel(QAbstractTableModel):
|
||||
)
|
||||
raise error
|
||||
|
||||
return entered_date.replace(tzinfo=timezone.utc).timestamp()
|
||||
return (entered_date - parse_datetime(self.start_date)).total_seconds()
|
||||
|
||||
def _setup_delegates(self):
|
||||
if self._table_view is None:
|
||||
@@ -111,7 +124,7 @@ class PamhyrTableModel(QAbstractTableModel):
|
||||
opt_data=None,
|
||||
options=["rows_selection"],
|
||||
parent=None,
|
||||
start_date=None):
|
||||
start_date=None, study=None):
|
||||
super(PamhyrTableModel, self).__init__()
|
||||
|
||||
self._table_view = table_view
|
||||
@@ -129,6 +142,7 @@ class PamhyrTableModel(QAbstractTableModel):
|
||||
self._undo = undo
|
||||
self._lst = []
|
||||
self._start_date = start_date
|
||||
self._study = study
|
||||
|
||||
self._setup_delegates()
|
||||
self._setup_lst()
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
# PamhyrTree.py -- Pamhyr abstract table model
|
||||
# Copyright (C) 2023-2026 INRAE
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, either version 3 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import logging
|
||||
import traceback
|
||||
|
||||
from tools import trace, timer
|
||||
|
||||
from Model.Except import NotImplementedMethodeError
|
||||
|
||||
from PyQt5.QtCore import (
|
||||
Qt, QVariant, QAbstractItemModel,
|
||||
QCoreApplication, QModelIndex, pyqtSlot,
|
||||
)
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QTreeWidget, QTreeWidgetItem,
|
||||
)
|
||||
|
||||
logger = logging.getLogger()
|
||||
|
||||
|
||||
class PamhyrModelItem(QTreeWidgetItem):
|
||||
def __init__(self, data=None, trad=None, parent=None):
|
||||
self._data = data
|
||||
self._name = self._get_name()
|
||||
|
||||
super(PamhyrModelItem, self).__init__(
|
||||
parent, [self._name],
|
||||
)
|
||||
|
||||
self._setup_children()
|
||||
|
||||
def _get_name(self):
|
||||
return str(self._data)
|
||||
|
||||
def _setup_children(self):
|
||||
return
|
||||
|
||||
def get_value(self):
|
||||
return self._data
|
||||
|
||||
def find_item_by_value(self, data):
|
||||
if self.get_value() == data:
|
||||
return self
|
||||
|
||||
for i in range(self.childCount()):
|
||||
item = self.child(i)
|
||||
if item.get_value() == data:
|
||||
return item
|
||||
|
||||
found = item.find_item_by_value(data)
|
||||
if found:
|
||||
return found
|
||||
|
||||
return None
|
||||
|
||||
|
||||
class PamhyrModelListItem(QTreeWidgetItem):
|
||||
def __init__(self, name=None, lst=None,
|
||||
child_item_ctor=PamhyrModelItem,
|
||||
trad=None, parent=None):
|
||||
super(PamhyrModelListItem, self).__init__(
|
||||
parent, [name],
|
||||
)
|
||||
|
||||
self._name = name
|
||||
self._lst = lst
|
||||
self._trad = trad
|
||||
self._child_item_ctor = child_item_ctor
|
||||
|
||||
self._setup_children()
|
||||
|
||||
def _setup_children(self):
|
||||
for el in self._lst.lst:
|
||||
self.addChild(
|
||||
self._child_item_ctor(
|
||||
data=el, trad=self._trad, parent=self
|
||||
)
|
||||
)
|
||||
|
||||
def get_value(self):
|
||||
return None
|
||||
|
||||
def find_item_by_value(self, data):
|
||||
if self.get_value() == data:
|
||||
return self
|
||||
|
||||
for i in range(self.childCount()):
|
||||
item = self.child(i)
|
||||
if item.get_value() == data:
|
||||
return item
|
||||
|
||||
found = item.find_item_by_value(data)
|
||||
if found:
|
||||
return found
|
||||
|
||||
return None
|
||||
+36
-8
@@ -40,6 +40,12 @@ class CommonWordTranslate(PamhyrTranslate):
|
||||
self._dict["time"] = _translate("CommonWord", "Time")
|
||||
self._dict["date"] = _translate("CommonWord", "Date")
|
||||
|
||||
self._dict["low"] = _translate("CommonWord", "Low")
|
||||
self._dict["high"] = _translate("CommonWord", "High")
|
||||
|
||||
self._dict["loc"] = _translate("CommonWord", "Loc")
|
||||
self._dict["scale"] = _translate("CommonWord", "Scale")
|
||||
|
||||
self._dict["reach"] = _translate("CommonWord", "Reach")
|
||||
self._dict["reaches"] = _translate("CommonWord", "Reaches")
|
||||
self._dict["Select reach"] = _translate("CommonWord", "Select reach")
|
||||
@@ -65,6 +71,9 @@ class CommonWordTranslate(PamhyrTranslate):
|
||||
self._dict["file_csv"] = _translate(
|
||||
"CommonWord", "CSV file (*.csv)"
|
||||
)
|
||||
self._dict["file_json"] = _translate(
|
||||
"CommonWord", "JSON file (*.json)"
|
||||
)
|
||||
|
||||
|
||||
class UnitTranslate(CommonWordTranslate):
|
||||
@@ -103,6 +112,12 @@ class UnitTranslate(CommonWordTranslate):
|
||||
self._dict["unit_water_elevation"] = _translate(
|
||||
"Unit", "Water Elevation (m)"
|
||||
)
|
||||
self._dict["unit_mean_water_elevation"] = _translate(
|
||||
"Unit", "Mean water elevation (m)"
|
||||
)
|
||||
self._dict["unit_std_deriv_elevation"] = _translate(
|
||||
"Unit", "Elevation standard derivation (m)"
|
||||
)
|
||||
self._dict["unit_water_elevation_envelop"] = _translate(
|
||||
"Unit", "Water Elevation Envelop (m)"
|
||||
)
|
||||
@@ -122,8 +137,16 @@ class UnitTranslate(CommonWordTranslate):
|
||||
self._dict["unit_min_velocity"] = _translate(
|
||||
"Unit", "Min Velocity (m/s)"
|
||||
)
|
||||
self._dict["unit_discharge"] = _translate(
|
||||
"Unit", "Discharge") + f" (m³/s)"
|
||||
self._dict["unit_discharge"] = (
|
||||
_translate("Unit", "Discharge") + f" (m³/s)"
|
||||
)
|
||||
self._dict["unit_mean_discharge"] = (
|
||||
_translate("Unit", "Mean discharge") + f" (m³/s)"
|
||||
)
|
||||
self._dict["unit_std_deriv_discharge"] = (
|
||||
_translate("Unit", "Discharge standard derivation")
|
||||
+ f" (m³/s)"
|
||||
)
|
||||
self._dict["unit_discharge_envelop"] = _translate(
|
||||
"Unit", "Discharge Envelop") + " (m³/s)"
|
||||
self._dict["unit_max_discharge"] = _translate(
|
||||
@@ -175,6 +198,15 @@ class MainTranslate(UnitTranslate):
|
||||
self._dict["tab_checker_name"] = _translate(
|
||||
"MainWindow", "Checks"
|
||||
)
|
||||
self._dict["tab_graph_name"] = _translate(
|
||||
"MainWindow", "Graph"
|
||||
)
|
||||
self._dict["graph_network_title"] = _translate(
|
||||
"MainWindow", "Hydrographic network"
|
||||
)
|
||||
self._dict["graph_geographic_title"] = _translate(
|
||||
"MainWindow", "Geographic view"
|
||||
)
|
||||
|
||||
self._dict["open_debug"] = _translate(
|
||||
"MainWindow", "Open debug window"
|
||||
@@ -200,13 +232,9 @@ class MainTranslate(UnitTranslate):
|
||||
self._dict["Warning"] = _translate(
|
||||
"MainWindow", "Warning"
|
||||
)
|
||||
self._dict["mb_select_reach_title"] = _translate(
|
||||
"MainWindow", "Please select a reach"
|
||||
)
|
||||
self._dict["mb_select_reach_msg"] = _translate(
|
||||
self._dict["no_reach"] = _translate(
|
||||
"MainWindow",
|
||||
"This edition window need a reach selected "
|
||||
"into the river network to work on it"
|
||||
"Create a reach in the network before opening this window."
|
||||
)
|
||||
|
||||
self._dict["mb_last_open_title"] = _translate(
|
||||
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user