mirror of
https://gitlab.com/pamhyr/pamhyr2.git
synced 2026-10-30 03:20:41 +01:00
Compare commits
97
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7eb39e5896 | ||
|
|
28cc88b4b8 | ||
|
|
c9925cd03c | ||
|
|
40f9465929 | ||
|
|
359805b713 | ||
|
|
31565b9170 | ||
|
|
9c2a0541df | ||
|
|
38d7d587fa | ||
|
|
f19ab9455a | ||
|
|
cadffe40d6 | ||
|
|
5a195e2822 | ||
|
|
63592b91a9 | ||
|
|
88345c58a7 | ||
|
|
7124b2b61c | ||
|
|
f93e6a7d7c | ||
|
|
5d46401b85 | ||
|
|
97867080d9 | ||
|
|
93a4b44143 | ||
|
|
5e3e5628d2 | ||
|
|
4a6349cd9c | ||
|
|
e9c998fec8 | ||
|
|
290b8918fc | ||
|
|
0e6de5d0f0 | ||
|
|
98d30a326e | ||
|
|
5f64499984 | ||
|
|
6e32c740ae | ||
|
|
e0721715d0 | ||
|
|
10edc00973 | ||
|
|
f8829ce82c | ||
|
|
ac91b712a3 | ||
|
|
4bccbbac33 | ||
|
|
5c8b7290ba | ||
|
|
288713ce5b | ||
|
|
ff3b5a320c | ||
|
|
a2e0f6a517 | ||
|
|
7356e5dd30 | ||
|
|
933c6c1952 | ||
|
|
d8fd4488e2 | ||
|
|
fef2a2e979 | ||
|
|
f001dffb68 | ||
|
|
2818644b7f | ||
|
|
86d93fd702 | ||
|
|
593cc0c91b | ||
|
|
32a316589b | ||
|
|
d4bc9bdf75 | ||
|
|
3325ba935b | ||
|
|
345f24996f | ||
|
|
4040b2456c | ||
|
|
8e77d31a5a | ||
|
|
6e029beafc | ||
|
|
f5a7cd5984 | ||
|
|
d4d5e26a2b | ||
|
|
92990948ad | ||
|
|
bf6d40f398 | ||
|
|
03299db99a | ||
|
|
a0886d900e | ||
|
|
97fe038d9b | ||
|
|
58e3da8942 | ||
|
|
b7c3793a66 | ||
|
|
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
@@ -1069,6 +1069,12 @@ gitlab-ci.
|
|||||||
sudo python3 -m pip install pyinstaller
|
sudo python3 -m pip install pyinstaller
|
||||||
#+end_src
|
#+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}}}
|
*** Windows (Wine) {{{windows}}}
|
||||||
|
|
||||||
The ci-runner environment for Wine need at least wine version 8, let
|
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
|
PyQtWebEngine==5.15.6
|
||||||
QScintilla>=2.14.1
|
QScintilla>=2.14.1
|
||||||
pyqtgraph>=0.12.1
|
pyqtgraph>=0.12.1
|
||||||
matplotlib==3.8.3
|
matplotlib==3.10.8
|
||||||
numpy>=1.24.2
|
numpy>=1.24.2
|
||||||
colorama>=0.4.3
|
colorama>=0.4.3
|
||||||
pyinstaller>=5.11.0
|
pyinstaller>=5.11.0
|
||||||
@@ -14,3 +14,4 @@ platformdirs>=4.2.0
|
|||||||
pyshp>=2.3.1
|
pyshp>=2.3.1
|
||||||
rasterio==1.3.11
|
rasterio==1.3.11
|
||||||
#fortranformat==2.0.3
|
#fortranformat==2.0.3
|
||||||
|
psutil>=7.2.2
|
||||||
+1
-1
@@ -20,4 +20,4 @@
|
|||||||
"python-pyqtgraph" "python-qscintilla"
|
"python-pyqtgraph" "python-qscintilla"
|
||||||
"python-numpy@1" "python-shapely" "python-pyshp"
|
"python-numpy@1" "python-shapely" "python-pyshp"
|
||||||
"python-matplotlib" "python-colorama"
|
"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
|
#PyQtWebEngine==5.15.6
|
||||||
QScintilla>=2.14.1
|
QScintilla>=2.14.1
|
||||||
pyqtgraph>=0.12.1
|
pyqtgraph>=0.12.1
|
||||||
matplotlib==3.8.3
|
matplotlib==3.10.8
|
||||||
numpy>=1.24.2
|
numpy>=1.24.2
|
||||||
colorama>=0.4.3
|
colorama>=0.4.3
|
||||||
pyinstaller>=5.11.0
|
pyinstaller>=5.11.0
|
||||||
@@ -14,4 +14,4 @@ platformdirs>=4.2.0
|
|||||||
pyshp>=2.3.1
|
pyshp>=2.3.1
|
||||||
rasterio==1.3.11
|
rasterio==1.3.11
|
||||||
#fortranformat==2.0.3
|
#fortranformat==2.0.3
|
||||||
|
psutil>=7.2.2
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
# Adists.py -- Pamhyr study checkers
|
||||||
|
# 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 time
|
||||||
|
import logging
|
||||||
|
from functools import reduce
|
||||||
|
|
||||||
|
from PyQt5.QtCore import QCoreApplication
|
||||||
|
|
||||||
|
from Modules import Modules
|
||||||
|
from Checker.Checker import AbstractModelChecker, STATUS
|
||||||
|
|
||||||
|
_translate = QCoreApplication.translate
|
||||||
|
|
||||||
|
logger = logging.getLogger()
|
||||||
|
|
||||||
|
|
||||||
|
class AdistsOutputRKChecker(AbstractModelChecker):
|
||||||
|
def __init__(self):
|
||||||
|
super(AdistsOutputRKChecker, self).__init__()
|
||||||
|
|
||||||
|
self._name = _translate("Checker", "AdisTS output RK checker")
|
||||||
|
self._description = _translate(
|
||||||
|
"Checker", "Check output RK"
|
||||||
|
)
|
||||||
|
self._modules = Modules.OUTPUT_RK
|
||||||
|
|
||||||
|
def run(self, study):
|
||||||
|
ok = True
|
||||||
|
nerror = 0
|
||||||
|
self._summary = "ok"
|
||||||
|
self._status = STATUS.OK
|
||||||
|
|
||||||
|
if not self.basic_check(study):
|
||||||
|
return False
|
||||||
|
|
||||||
|
return ok
|
||||||
+2
-5
@@ -229,11 +229,7 @@ for each reach"
|
|||||||
gls = []
|
gls = []
|
||||||
|
|
||||||
for edge in edges:
|
for edge in edges:
|
||||||
profiles = edge.reach.enabled_profiles
|
comp, incomp = edge.reach.compute_guidelines()
|
||||||
comp, incomp = edge.reach.compute_guidelines(
|
|
||||||
profiles=profiles,
|
|
||||||
update_cache=False
|
|
||||||
)
|
|
||||||
if len(incomp) != 0:
|
if len(incomp) != 0:
|
||||||
self._status = STATUS.WARNING
|
self._status = STATUS.WARNING
|
||||||
self._summary = "incomplete_guideline"
|
self._summary = "incomplete_guideline"
|
||||||
@@ -241,6 +237,7 @@ for each reach"
|
|||||||
|
|
||||||
gls.append(comp)
|
gls.append(comp)
|
||||||
|
|
||||||
|
profiles = edge.reach.profiles
|
||||||
for profile in profiles:
|
for profile in profiles:
|
||||||
if not profile.has_standard_named_points():
|
if not profile.has_standard_named_points():
|
||||||
self._status = STATUS.WARNING
|
self._status = STATUS.WARNING
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ class StudyGeometryChecker(AbstractModelChecker):
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
for edge in edges:
|
for edge in edges:
|
||||||
if len(edge.reach.enabled_profiles) < 2:
|
if len(edge.reach.profiles) < 2:
|
||||||
summary = "no_geometry_defined"
|
summary = "no_geometry_defined"
|
||||||
status = STATUS.ERROR
|
status = STATUS.ERROR
|
||||||
ok = False
|
ok = False
|
||||||
@@ -132,12 +132,8 @@ class StudyInitialConditionsChecker(AbstractModelChecker):
|
|||||||
return ok
|
return ok
|
||||||
|
|
||||||
ic = river.initial_conditions[reach]
|
ic = river.initial_conditions[reach]
|
||||||
enabled_profiles = set(reach.enabled_profiles)
|
len_ic = len(ic)
|
||||||
len_ic = sum(
|
len_reach = len(reach)
|
||||||
data["section"] in enabled_profiles
|
|
||||||
for data in ic.data
|
|
||||||
)
|
|
||||||
len_reach = len(enabled_profiles)
|
|
||||||
|
|
||||||
if len_ic < len_reach:
|
if len_ic < len_reach:
|
||||||
self._summary = "initial_condition_missing_profile"
|
self._summary = "initial_condition_missing_profile"
|
||||||
|
|||||||
+62
-112
@@ -57,13 +57,6 @@ class InternalMeshing(AMeshingTool):
|
|||||||
|
|
||||||
# we never modify original profiles, we work on the copies
|
# we never modify original profiles, we work on the copies
|
||||||
m_profiles = self.st_to_m(profiles, guide_list)
|
m_profiles = self.st_to_m(profiles, guide_list)
|
||||||
|
|
||||||
# Adapt the spacing to the kilometre-point direction. The value from
|
|
||||||
# the dialog is a distance, so only its magnitude is significant.
|
|
||||||
step = self.signed_step(
|
|
||||||
step, m_profiles[0].rk, m_profiles[-1].rk
|
|
||||||
)
|
|
||||||
|
|
||||||
new_profiles = self.interpolate_transversal_step(m_profiles, step)
|
new_profiles = self.interpolate_transversal_step(m_profiles, step)
|
||||||
|
|
||||||
for new_profiles2 in new_profiles:
|
for new_profiles2 in new_profiles:
|
||||||
@@ -72,12 +65,6 @@ class InternalMeshing(AMeshingTool):
|
|||||||
|
|
||||||
return new_profiles
|
return new_profiles
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def signed_step(step, begin_rk, end_rk):
|
|
||||||
if end_rk < begin_rk:
|
|
||||||
return -abs(step)
|
|
||||||
return abs(step)
|
|
||||||
|
|
||||||
def st_to_m(self, profiles, guide_list):
|
def st_to_m(self, profiles, guide_list):
|
||||||
guide_list = ["un"] + guide_list + ["np"]
|
guide_list = ["un"] + guide_list + ["np"]
|
||||||
max_values = [0] * (len(guide_list) - 1)
|
max_values = [0] * (len(guide_list) - 1)
|
||||||
@@ -137,11 +124,10 @@ class InternalMeshing(AMeshingTool):
|
|||||||
p.points[k].z = pt1[k].z + \
|
p.points[k].z = pt1[k].z + \
|
||||||
dj*(pt2[k].z -
|
dj*(pt2[k].z -
|
||||||
pt1[k].z)
|
pt1[k].z)
|
||||||
p.rk = round(profiles[i].rk +
|
p.rk = profiles[i].rk + \
|
||||||
dj*(profiles[i+1].rk -
|
dj*(profiles[i+1].rk -
|
||||||
profiles[i].rk), 2)
|
profiles[i].rk)
|
||||||
p.name = f'interpol{p.rk}'
|
p.name = f'interpol{p.rk}'
|
||||||
p.interpolated = True
|
|
||||||
new_profiles2.append(p)
|
new_profiles2.append(p)
|
||||||
new_profiles.append(new_profiles2)
|
new_profiles.append(new_profiles2)
|
||||||
|
|
||||||
@@ -172,8 +158,8 @@ class InternalMeshing(AMeshingTool):
|
|||||||
|
|
||||||
ltot1 = 0.0
|
ltot1 = 0.0
|
||||||
ltot2 = 0.0
|
ltot2 = 0.0
|
||||||
alpha = [0.0]
|
alpha = []
|
||||||
beta = [0.0]
|
beta = []
|
||||||
# remove names
|
# remove names
|
||||||
sect2.points[start2].name = ''
|
sect2.points[start2].name = ''
|
||||||
sect2.points[end2].name = ''
|
sect2.points[end2].name = ''
|
||||||
@@ -196,38 +182,67 @@ class InternalMeshing(AMeshingTool):
|
|||||||
else: # regular case
|
else: # regular case
|
||||||
alpha = list(map(lambda x: x/ltot1, alpha)) # target ratios
|
alpha = list(map(lambda x: x/ltot1, alpha)) # target ratios
|
||||||
beta = list(map(lambda x: x/ltot2, beta)) # current ratios
|
beta = list(map(lambda x: x/ltot2, beta)) # current ratios
|
||||||
match = self._match_indices(alpha, beta)
|
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
|
||||||
|
|
||||||
insertions_per_segment = [] # liste de (index, [points])
|
if trouve:
|
||||||
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
|
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]
|
||||||
|
|
||||||
|
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":
|
if tag1 != "un":
|
||||||
sect2.point(start2).name = tag1
|
sect2.point(start2).name = tag1
|
||||||
if tag2 != "np":
|
if tag2 != "np":
|
||||||
@@ -235,71 +250,6 @@ class InternalMeshing(AMeshingTool):
|
|||||||
|
|
||||||
sect2.modified()
|
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,
|
def update_rk(self, reach, begin_rk, end_rk,
|
||||||
step: float = 50,
|
step: float = 50,
|
||||||
limites=[-1, -1],
|
limites=[-1, -1],
|
||||||
|
|||||||
@@ -531,7 +531,7 @@ class BoundaryConditionAdisTS(SQLSubModel):
|
|||||||
new_0 = self._types[0](data[0].replace(",", "."))
|
new_0 = self._types[0](data[0].replace(",", "."))
|
||||||
new_1 = self._types[1](data[1].replace(",", "."))
|
new_1 = self._types[1](data[1].replace(",", "."))
|
||||||
|
|
||||||
return Data(new_0, new_1, types=self._types, status=self._status)
|
return (new_0, new_1)
|
||||||
|
|
||||||
def add(self, index: int):
|
def add(self, index: int):
|
||||||
value = Data(
|
value = Data(
|
||||||
@@ -543,9 +543,6 @@ class BoundaryConditionAdisTS(SQLSubModel):
|
|||||||
return value
|
return value
|
||||||
|
|
||||||
def insert(self, index: int, value):
|
def insert(self, index: int, value):
|
||||||
if value in self._data:
|
|
||||||
value.set_as_not_deleted()
|
|
||||||
else:
|
|
||||||
self._data.insert(index, value)
|
self._data.insert(index, value)
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
|
|||||||
@@ -1,481 +0,0 @@
|
|||||||
# BoundaryConditionsTemperature.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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,
|
|
||||||
old_pamhyr_date_to_timestamp,
|
|
||||||
date_iso_to_timestamp,
|
|
||||||
date_dmy_to_timestamp,
|
|
||||||
)
|
|
||||||
|
|
||||||
from Model.Tools.PamhyrDB import SQLSubModel
|
|
||||||
from Model.Except import NotImplementedMethodeError
|
|
||||||
from Model.Scenario import Scenario
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class Data(SQLSubModel):
|
|
||||||
_sub_classes = []
|
|
||||||
|
|
||||||
def __init__(self,
|
|
||||||
data0, data1,
|
|
||||||
id: int = -1,
|
|
||||||
types=[float, float],
|
|
||||||
status=None,
|
|
||||||
owner_scenario=-1):
|
|
||||||
super(Data, self).__init__(
|
|
||||||
id=id, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._types = types
|
|
||||||
self._data = [data0, data1]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_create(cls, execute, ext=""):
|
|
||||||
execute(f"""
|
|
||||||
CREATE TABLE boundary_condition_data_temperature{ext}(
|
|
||||||
{cls.create_db_add_pamhyr_id()},
|
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
data0 TEXT NOT NULL,
|
|
||||||
data1 TEXT NOT NULL,
|
|
||||||
bca INTEGER,
|
|
||||||
{Scenario.create_db_add_scenario()},
|
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
|
||||||
FOREIGN KEY(bca)
|
|
||||||
REFERENCES boundary_condition_temperature(pamhyr_id)
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_update(cls, execute, version, data=None):
|
|
||||||
major, minor, release = version.strip().split(".")
|
|
||||||
created = False
|
|
||||||
if major == "0" and minor == "0":
|
|
||||||
if int(release) < 11:
|
|
||||||
cls._db_create(execute)
|
|
||||||
created = True
|
|
||||||
|
|
||||||
if major == "0" and (int(minor) < 2 or
|
|
||||||
(int(minor) == 2 and int(release) <= 7)):
|
|
||||||
if not cls.is_table_exists(execute,
|
|
||||||
"boundary_condition_data_temperature"):
|
|
||||||
cls._db_create(execute)
|
|
||||||
created = True
|
|
||||||
|
|
||||||
if not created:
|
|
||||||
return cls._update_submodel(execute, version, data)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_load(cls, execute, data=None):
|
|
||||||
new = []
|
|
||||||
status = data['status']
|
|
||||||
scenario = data["scenario"]
|
|
||||||
loaded = data['loaded_pid']
|
|
||||||
|
|
||||||
if scenario is None:
|
|
||||||
return new
|
|
||||||
|
|
||||||
bca = data["bca"]
|
|
||||||
|
|
||||||
table = execute(
|
|
||||||
"SELECT pamhyr_id, deleted, data0, data1, scenario FROM " +
|
|
||||||
"boundary_condition_data_temperature " +
|
|
||||||
f"WHERE scenario = {scenario.id} " +
|
|
||||||
# f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))}) " +
|
|
||||||
f"AND bca = {bca.id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
if table is not None:
|
|
||||||
for row in table:
|
|
||||||
it = iter(row)
|
|
||||||
|
|
||||||
pid = next(it)
|
|
||||||
deleted = (next(it) == 1)
|
|
||||||
data0 = next(it)
|
|
||||||
data1 = next(it)
|
|
||||||
owner_scenario = next(it)
|
|
||||||
|
|
||||||
bc = cls(
|
|
||||||
data0, data1,
|
|
||||||
id=pid,
|
|
||||||
status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
if deleted:
|
|
||||||
bc.set_as_deleted()
|
|
||||||
|
|
||||||
loaded.add(pid)
|
|
||||||
new.append(bc)
|
|
||||||
|
|
||||||
data["scenario"] = scenario.parent
|
|
||||||
new += cls._db_load(execute, data)
|
|
||||||
data["scenario"] = scenario
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
|
||||||
if not self.must_be_saved():
|
|
||||||
return True
|
|
||||||
|
|
||||||
bca = data["bca"]
|
|
||||||
|
|
||||||
data0 = self._db_format(self._data[0])
|
|
||||||
data1 = self._db_format(self._data[1])
|
|
||||||
|
|
||||||
execute(
|
|
||||||
"INSERT INTO " +
|
|
||||||
"boundary_condition_data_temperature(" +
|
|
||||||
"pamhyr_id, deleted, data0, data1, bca, scenario) " +
|
|
||||||
f"VALUES ({self.id}, {self._db_format(self.is_deleted())}, " +
|
|
||||||
f"'{data0}', {data1}, {bca.id}, " +
|
|
||||||
f"{self._status.scenario_id})"
|
|
||||||
)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
def __getitem__(self, key):
|
|
||||||
return self._types[key](self._data[key])
|
|
||||||
|
|
||||||
def __setitem__(self, key, value):
|
|
||||||
self._data[key] = self._types[key](value)
|
|
||||||
|
|
||||||
|
|
||||||
class BoundaryConditionTemperature(SQLSubModel):
|
|
||||||
_sub_classes = [Data]
|
|
||||||
|
|
||||||
def __init__(self, id: int = -1, status=None, owner_scenario=-1):
|
|
||||||
super(BoundaryConditionTemperature, self).__init__(
|
|
||||||
id=id, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._status = status
|
|
||||||
|
|
||||||
self._name = ""
|
|
||||||
self._node = None
|
|
||||||
self._data = []
|
|
||||||
self._header = []
|
|
||||||
self._types = [self.time_convert, float]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_create(cls, execute, ext=""):
|
|
||||||
execute(f"""
|
|
||||||
CREATE TABLE boundary_condition_temperature{ext}(
|
|
||||||
{cls.create_db_add_pamhyr_id()},
|
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
node INTEGER,
|
|
||||||
{Scenario.create_db_add_scenario()},
|
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
|
||||||
FOREIGN KEY(node) REFERENCES river_node(pamhyr_id)
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
|
|
||||||
if ext != "":
|
|
||||||
return True
|
|
||||||
|
|
||||||
return cls._create_submodel(execute)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_update(cls, execute, version, data=None):
|
|
||||||
major, minor, release = version.strip().split(".")
|
|
||||||
created = False
|
|
||||||
|
|
||||||
if major == "0" and (int(minor) < 2 or (
|
|
||||||
int(minor) == 2 and int(release) <= 7)):
|
|
||||||
if not cls.is_table_exists(execute,
|
|
||||||
"boundary_condition_temperature"):
|
|
||||||
cls._db_create(execute)
|
|
||||||
created = True
|
|
||||||
|
|
||||||
if not created:
|
|
||||||
return cls._update_submodel(execute, version, data)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_load(cls, execute, data=None):
|
|
||||||
new = []
|
|
||||||
status = data['status']
|
|
||||||
nodes = data['nodes']
|
|
||||||
scenario = data["scenario"]
|
|
||||||
loaded = data['loaded_pid']
|
|
||||||
|
|
||||||
if scenario is None:
|
|
||||||
return new
|
|
||||||
|
|
||||||
sql = (
|
|
||||||
"SELECT pamhyr_id, deleted, name, node, scenario "
|
|
||||||
"FROM boundary_condition_temperature " +
|
|
||||||
f"WHERE scenario = {scenario.id} "
|
|
||||||
)
|
|
||||||
|
|
||||||
table = execute(sql)
|
|
||||||
|
|
||||||
if table is not None:
|
|
||||||
for row in table:
|
|
||||||
it = iter(row)
|
|
||||||
|
|
||||||
pid = next(it)
|
|
||||||
deleted = (next(it) == 1)
|
|
||||||
bc_name = next(it)
|
|
||||||
node = next(it)
|
|
||||||
owner_scenario = next(it)
|
|
||||||
|
|
||||||
bc = cls(
|
|
||||||
id=pid,
|
|
||||||
status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
if deleted:
|
|
||||||
bc.set_as_deleted()
|
|
||||||
|
|
||||||
bc.name = bc_name
|
|
||||||
|
|
||||||
bc.node = None
|
|
||||||
if node != -1:
|
|
||||||
tmp = next(
|
|
||||||
filter(
|
|
||||||
lambda n: n.id == node, nodes
|
|
||||||
),
|
|
||||||
None
|
|
||||||
)
|
|
||||||
if tmp is not None:
|
|
||||||
bc.node = tmp.id
|
|
||||||
else:
|
|
||||||
bc.node = -1
|
|
||||||
|
|
||||||
data["bca"] = bc
|
|
||||||
bc._data = Data._db_load(execute, data=data)
|
|
||||||
|
|
||||||
loaded.add(pid)
|
|
||||||
new.append(bc)
|
|
||||||
|
|
||||||
data["scenario"] = scenario.parent
|
|
||||||
new += cls._db_load(execute, data)
|
|
||||||
data["scenario"] = scenario
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
|
||||||
if not self.must_be_saved():
|
|
||||||
return True
|
|
||||||
|
|
||||||
execute(
|
|
||||||
"DELETE FROM boundary_condition_temperature " +
|
|
||||||
f"WHERE pamhyr_id = {self.id} " +
|
|
||||||
f"AND scenario = {self._status.scenario_id} "
|
|
||||||
)
|
|
||||||
execute(
|
|
||||||
"DELETE FROM boundary_condition_data_temperature " +
|
|
||||||
f"WHERE bca = {self.id} " +
|
|
||||||
f"AND scenario = {self._status.scenario_id} "
|
|
||||||
)
|
|
||||||
|
|
||||||
node = -1
|
|
||||||
if self._node is not None:
|
|
||||||
node = self._node
|
|
||||||
|
|
||||||
execute(
|
|
||||||
"INSERT INTO " +
|
|
||||||
"boundary_condition_temperature(" +
|
|
||||||
"pamhyr_id, deleted, name, " +
|
|
||||||
"node, scenario) " +
|
|
||||||
"VALUES (" +
|
|
||||||
f"{self.id}, {self._db_format(self.is_deleted())}, " +
|
|
||||||
f"'{self._db_format(self._name)}', {node}, " +
|
|
||||||
f"{self._status.scenario_id}" +
|
|
||||||
")"
|
|
||||||
)
|
|
||||||
|
|
||||||
data["bca"] = self
|
|
||||||
|
|
||||||
ind = 0
|
|
||||||
for d in self._data:
|
|
||||||
data["ind"] = ind
|
|
||||||
|
|
||||||
d._db_save(execute, data)
|
|
||||||
|
|
||||||
ind += 1
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
def _data_traversal(self,
|
|
||||||
predicate=lambda obj, data: True,
|
|
||||||
modifier=lambda obj, data: None,
|
|
||||||
data={}):
|
|
||||||
if predicate(self, data):
|
|
||||||
modifier(self, data)
|
|
||||||
|
|
||||||
for d in self._data:
|
|
||||||
d._data_traversal(predicate, modifier, data)
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
return len(
|
|
||||||
list(
|
|
||||||
filter(
|
|
||||||
lambda el: el is not None and not el.is_deleted(),
|
|
||||||
self._data
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def time_convert(cls, data):
|
|
||||||
if type(data) is str:
|
|
||||||
if data.count("-") == 2:
|
|
||||||
return date_iso_to_timestamp(data)
|
|
||||||
if data.count("/") == 2:
|
|
||||||
return date_dmy_to_timestamp(data)
|
|
||||||
if data.count(":") == 3:
|
|
||||||
return old_pamhyr_date_to_timestamp(data)
|
|
||||||
if data.count(":") == 2:
|
|
||||||
return old_pamhyr_date_to_timestamp("00:" + data)
|
|
||||||
if data.count(".") == 1:
|
|
||||||
return round(float(data))
|
|
||||||
|
|
||||||
return int(data)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def name(self):
|
|
||||||
return self._name
|
|
||||||
|
|
||||||
@name.setter
|
|
||||||
def name(self, name):
|
|
||||||
self._name = name
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def node(self):
|
|
||||||
return self._node
|
|
||||||
|
|
||||||
@node.setter
|
|
||||||
def node(self, node):
|
|
||||||
self._node = node
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def header(self):
|
|
||||||
return self._header.copy()
|
|
||||||
|
|
||||||
@header.setter
|
|
||||||
def header(self, header):
|
|
||||||
self._header = header
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def data(self):
|
|
||||||
return list(
|
|
||||||
filter(
|
|
||||||
lambda el: el is not None and not el.is_deleted(),
|
|
||||||
self._data
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def _default_0(self):
|
|
||||||
return self._types[0](0)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def _default_1(self):
|
|
||||||
return self._types[1](0.0)
|
|
||||||
|
|
||||||
def new_from_data(self, header, data):
|
|
||||||
new_0 = self._default_0
|
|
||||||
new_1 = self._default_1
|
|
||||||
|
|
||||||
if len(header) != 0:
|
|
||||||
for i in [0, 1]:
|
|
||||||
for j in range(len(header)):
|
|
||||||
if self._header[i] == header[j]:
|
|
||||||
if i == 0:
|
|
||||||
new_0 = self._types[i](data[j].replace(",", "."))
|
|
||||||
else:
|
|
||||||
new_1 = self._types[i](data[j].replace(",", "."))
|
|
||||||
else:
|
|
||||||
new_0 = self._types[0](data[0].replace(",", "."))
|
|
||||||
new_1 = self._types[1](data[1].replace(",", "."))
|
|
||||||
|
|
||||||
return Data(new_0, new_1, types=self._types, status=self._status)
|
|
||||||
|
|
||||||
def add(self, index: int):
|
|
||||||
value = Data(
|
|
||||||
self._default_0, self._default_1,
|
|
||||||
status=self._status
|
|
||||||
)
|
|
||||||
self._data.insert(index, value)
|
|
||||||
self.modified()
|
|
||||||
return value
|
|
||||||
|
|
||||||
def insert(self, index: int, value):
|
|
||||||
if value in self._data:
|
|
||||||
value.set_as_not_deleted()
|
|
||||||
else:
|
|
||||||
self._data.insert(index, value)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def delete_i(self, indexes):
|
|
||||||
list(
|
|
||||||
map(
|
|
||||||
lambda e: e[1].set_as_deleted(),
|
|
||||||
filter(
|
|
||||||
lambda e: e[0] in indexes,
|
|
||||||
enumerate(self.data)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def sort(self, _reverse=False, key=None):
|
|
||||||
if key is None:
|
|
||||||
self._data.sort(reverse=_reverse)
|
|
||||||
else:
|
|
||||||
self._data.sort(reverse=_reverse, key=key)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def index(self, bc):
|
|
||||||
self._data.index(bc)
|
|
||||||
|
|
||||||
def get_i(self, index):
|
|
||||||
return self.data[index]
|
|
||||||
|
|
||||||
def get_range(self, _range):
|
|
||||||
lst = []
|
|
||||||
for r in _range:
|
|
||||||
lst.append(r)
|
|
||||||
return lst
|
|
||||||
|
|
||||||
def _set_i_c_v(self, index, column, value):
|
|
||||||
v = self._data[index]
|
|
||||||
v[column] = self._types[column](value)
|
|
||||||
self._data[index] = v
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def set_i_0(self, index: int, value):
|
|
||||||
self._set_i_c_v(index, 0, value)
|
|
||||||
|
|
||||||
def set_i_1(self, index: int, value):
|
|
||||||
self._set_i_c_v(index, 1, value)
|
|
||||||
@@ -275,44 +275,3 @@ class D90AdisTS(SQLSubModel):
|
|||||||
x.set_as_not_deleted()
|
x.set_as_not_deleted()
|
||||||
|
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
split_rk = profile.rk
|
|
||||||
reach_rks = reach.reach.get_rk()
|
|
||||||
if len(reach_rks) == 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
parts = [
|
|
||||||
(reach1.id, min(reach_rks), split_rk),
|
|
||||||
(reach2.id, split_rk, max(reach_rks)),
|
|
||||||
]
|
|
||||||
specifications = [
|
|
||||||
specification
|
|
||||||
for specification in self._data
|
|
||||||
if (not specification.is_deleted() and
|
|
||||||
specification.reach == reach.id)
|
|
||||||
]
|
|
||||||
|
|
||||||
for specification in specifications:
|
|
||||||
begin = specification.start_rk
|
|
||||||
end = specification.end_rk
|
|
||||||
if begin is None or end is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
lower, upper = sorted((begin, end))
|
|
||||||
reverse = begin > end
|
|
||||||
|
|
||||||
for new_reach, part_lower, part_upper in parts:
|
|
||||||
clipped_lower = max(lower, part_lower)
|
|
||||||
clipped_upper = min(upper, part_upper)
|
|
||||||
if clipped_lower >= clipped_upper:
|
|
||||||
continue
|
|
||||||
|
|
||||||
start_rk = clipped_upper if reverse else clipped_lower
|
|
||||||
end_rk = clipped_lower if reverse else clipped_upper
|
|
||||||
self._data.append(specification.cloned_for(
|
|
||||||
new_reach, start_rk, end_rk
|
|
||||||
))
|
|
||||||
|
|
||||||
if len(specifications) != 0:
|
|
||||||
self.modified()
|
|
||||||
@@ -61,10 +61,6 @@ class D90AdisTSList(PamhyrModelList):
|
|||||||
self._status.modified()
|
self._status.modified()
|
||||||
return n
|
return n
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
for d90 in self.lst:
|
|
||||||
d90.split_reach(reach, profile, reach1, reach2)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def D90_AdisTS_List(self):
|
def D90_AdisTS_List(self):
|
||||||
return self.lst
|
return self.lst
|
||||||
@@ -261,13 +261,3 @@ class D90AdisTSSpec(SQLSubModel):
|
|||||||
def enabled(self, enabled):
|
def enabled(self, enabled):
|
||||||
self._enabled = enabled
|
self._enabled = enabled
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
def cloned_for(self, reach, start_rk, end_rk):
|
|
||||||
new = D90AdisTSSpec(name=self._name_section, status=self._status)
|
|
||||||
new._reach = reach
|
|
||||||
new._start_rk = start_rk
|
|
||||||
new._end_rk = end_rk
|
|
||||||
new._d90 = self._d90
|
|
||||||
new._enabled = self._enabled
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
@@ -329,44 +329,3 @@ class DIFAdisTS(SQLSubModel):
|
|||||||
x.set_as_not_deleted()
|
x.set_as_not_deleted()
|
||||||
|
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
split_rk = profile.rk
|
|
||||||
reach_rks = reach.reach.get_rk()
|
|
||||||
if len(reach_rks) == 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
parts = [
|
|
||||||
(reach1.id, min(reach_rks), split_rk),
|
|
||||||
(reach2.id, split_rk, max(reach_rks)),
|
|
||||||
]
|
|
||||||
specifications = [
|
|
||||||
specification
|
|
||||||
for specification in self._data
|
|
||||||
if (not specification.is_deleted() and
|
|
||||||
specification.reach == reach.id)
|
|
||||||
]
|
|
||||||
|
|
||||||
for specification in specifications:
|
|
||||||
begin = specification.start_rk
|
|
||||||
end = specification.end_rk
|
|
||||||
if begin is None or end is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
lower, upper = sorted((begin, end))
|
|
||||||
reverse = begin > end
|
|
||||||
|
|
||||||
for new_reach, part_lower, part_upper in parts:
|
|
||||||
clipped_lower = max(lower, part_lower)
|
|
||||||
clipped_upper = min(upper, part_upper)
|
|
||||||
if clipped_lower >= clipped_upper:
|
|
||||||
continue
|
|
||||||
|
|
||||||
start_rk = clipped_upper if reverse else clipped_lower
|
|
||||||
end_rk = clipped_lower if reverse else clipped_upper
|
|
||||||
self._data.append(specification.cloned_for(
|
|
||||||
new_reach, start_rk, end_rk
|
|
||||||
))
|
|
||||||
|
|
||||||
if len(specifications) != 0:
|
|
||||||
self.modified()
|
|
||||||
@@ -61,10 +61,6 @@ class DIFAdisTSList(PamhyrModelList):
|
|||||||
self._status.modified()
|
self._status.modified()
|
||||||
return n
|
return n
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
for dif in self.lst:
|
|
||||||
dif.split_reach(reach, profile, reach1, reach2)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def DIF_AdisTS_List(self):
|
def DIF_AdisTS_List(self):
|
||||||
return self.lst
|
return self.lst
|
||||||
@@ -293,15 +293,3 @@ class DIFAdisTSSpec(SQLSubModel):
|
|||||||
def enabled(self, enabled):
|
def enabled(self, enabled):
|
||||||
self._enabled = enabled
|
self._enabled = enabled
|
||||||
self._status.modified()
|
self._status.modified()
|
||||||
|
|
||||||
def cloned_for(self, reach, start_rk, end_rk):
|
|
||||||
new = DIFAdisTSSpec(method=self._method, status=self._status)
|
|
||||||
new._reach = reach
|
|
||||||
new._start_rk = start_rk
|
|
||||||
new._end_rk = end_rk
|
|
||||||
new._dif = self._dif
|
|
||||||
new._b = self._b
|
|
||||||
new._c = self._c
|
|
||||||
new._enabled = self._enabled
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
@@ -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"]
|
||||||
+19
-30
@@ -1,5 +1,5 @@
|
|||||||
# InitialConditionsTemperatureList.py -- Pamhyr
|
# EnsembleList.py -- Pamhyr
|
||||||
# Copyright (C) 2023-2025 INRAE
|
# Copyright (C) 2026 INRAE
|
||||||
#
|
#
|
||||||
# This program is free software: you can redistribute it and/or modify
|
# 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
|
# it under the terms of the GNU General Public License as published by
|
||||||
@@ -16,27 +16,20 @@
|
|||||||
|
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
from copy import copy
|
|
||||||
from tools import trace, timer
|
from tools import trace, timer
|
||||||
|
|
||||||
from Model.Tools.PamhyrListExt import PamhyrModelList
|
from Model.Tools.PamhyrListExt import PamhyrModelList
|
||||||
from Model.InitialConditionsTemperature.InitialConditionsTemperature \
|
from Model.Ensembles.Ensemble import Ensemble
|
||||||
import InitialConditionsTemperature
|
|
||||||
|
|
||||||
|
|
||||||
class InitialConditionsTemperatureList(PamhyrModelList):
|
class EnsembleList(PamhyrModelList):
|
||||||
_sub_classes = [
|
_sub_classes = [Ensemble]
|
||||||
InitialConditionsTemperature,
|
|
||||||
]
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _db_load(cls, execute, data=None):
|
def _db_load(cls, execute, data=None):
|
||||||
new = cls(status=data['status'])
|
new = cls(status=data['status'])
|
||||||
|
|
||||||
if data is None:
|
new._lst = Ensemble._db_load(
|
||||||
data = {}
|
|
||||||
|
|
||||||
new._lst = InitialConditionsTemperature._db_load(
|
|
||||||
execute, data
|
execute, data
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -44,30 +37,26 @@ class InitialConditionsTemperatureList(PamhyrModelList):
|
|||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
def _db_save(self, execute, data=None):
|
||||||
execute(
|
execute(
|
||||||
"DELETE FROM initial_conditions_temperature " +
|
"DELETE FROM ensemble " +
|
||||||
f"WHERE scenario = {self._status.scenario_id}"
|
f"WHERE scenario = {self._status.scenario_id}"
|
||||||
)
|
)
|
||||||
|
|
||||||
if data is None:
|
for ens in self._lst:
|
||||||
data = {}
|
ens._db_save(execute, data=data)
|
||||||
|
|
||||||
for ic in self._lst:
|
|
||||||
ic._db_save(execute, data=data)
|
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def new(self, index):
|
def new(self, index):
|
||||||
n = InitialConditionsTemperature(status=self._status)
|
r = Ensemble(status=self._status)
|
||||||
self._lst.insert(index, n)
|
self._lst.insert(index, r)
|
||||||
self._status.modified()
|
self._status.modified()
|
||||||
return n
|
return r
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
def new_with_data(self, index, data):
|
||||||
for initial_condition in self.lst:
|
r = Ensemble(status=self._status)
|
||||||
initial_condition.split_reach(
|
|
||||||
reach, profile, reach1, reach2
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
r.set_data_dict(data)
|
||||||
def Initial_Conditions_List(self):
|
|
||||||
return self.lst
|
self._lst.insert(index, r)
|
||||||
|
self._status.modified()
|
||||||
|
return r
|
||||||
@@ -109,22 +109,16 @@ class FrictionList(PamhyrModelList):
|
|||||||
((999 ** 100), -(999 ** 100))
|
((999 ** 100), -(999 ** 100))
|
||||||
)
|
)
|
||||||
|
|
||||||
for friction in self.lst:
|
frictions = list(
|
||||||
lower, upper = sorted((friction.begin_rk, friction.end_rk))
|
filter(
|
||||||
clipped_lower = max(lower, rk_min)
|
lambda f: ((rk_min <= f.begin_rk <= rk_max) or
|
||||||
clipped_upper = min(upper, rk_max)
|
(rk_min <= f.end_rk <= rk_max)),
|
||||||
if clipped_lower >= clipped_upper:
|
self._lst))
|
||||||
continue
|
|
||||||
|
|
||||||
|
for ind, friction in enumerate(frictions):
|
||||||
n = friction.cloned_for(reach)
|
n = friction.cloned_for(reach)
|
||||||
if friction.begin_rk > friction.end_rk:
|
|
||||||
n.begin_rk = clipped_upper
|
|
||||||
n.end_rk = clipped_lower
|
|
||||||
else:
|
|
||||||
n.begin_rk = clipped_lower
|
|
||||||
n.end_rk = clipped_upper
|
|
||||||
|
|
||||||
new._lst.append(n)
|
new._lst.insert(ind, n)
|
||||||
new._status.modified()
|
new._status.modified()
|
||||||
|
|
||||||
return new
|
return new
|
||||||
@@ -55,11 +55,8 @@ class Point(SQLSubModel):
|
|||||||
|
|
||||||
@name.setter
|
@name.setter
|
||||||
def name(self, name):
|
def name(self, name):
|
||||||
changed = self._name != name
|
|
||||||
self._name = name
|
self._name = name
|
||||||
self.modified()
|
self.modified()
|
||||||
if changed and self._profile is not None:
|
|
||||||
self._profile.content_modified()
|
|
||||||
|
|
||||||
def is_named(self):
|
def is_named(self):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -328,11 +328,8 @@ class PointXYZ(Point):
|
|||||||
|
|
||||||
@x.setter
|
@x.setter
|
||||||
def x(self, value):
|
def x(self, value):
|
||||||
changed = self._x != float(value)
|
|
||||||
self._x = float(value)
|
self._x = float(value)
|
||||||
self.modified()
|
self.modified()
|
||||||
if changed and self._profile is not None:
|
|
||||||
self._profile.content_modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def y(self):
|
def y(self):
|
||||||
@@ -340,11 +337,8 @@ class PointXYZ(Point):
|
|||||||
|
|
||||||
@y.setter
|
@y.setter
|
||||||
def y(self, value):
|
def y(self, value):
|
||||||
changed = self._y != float(value)
|
|
||||||
self._y = float(value)
|
self._y = float(value)
|
||||||
self.modified()
|
self.modified()
|
||||||
if changed and self._profile is not None:
|
|
||||||
self._profile.content_modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def z(self):
|
def z(self):
|
||||||
@@ -352,11 +346,8 @@ class PointXYZ(Point):
|
|||||||
|
|
||||||
@z.setter
|
@z.setter
|
||||||
def z(self, value):
|
def z(self, value):
|
||||||
changed = self._z != float(value)
|
|
||||||
self._z = float(value)
|
self._z = float(value)
|
||||||
self.modified()
|
self.modified()
|
||||||
if changed and self._profile is not None:
|
|
||||||
self._profile.content_modified()
|
|
||||||
|
|
||||||
def shift(self, x, y, z):
|
def shift(self, x, y, z):
|
||||||
self.x += x
|
self.x += x
|
||||||
|
|||||||
@@ -47,8 +47,6 @@ class Profile(object):
|
|||||||
self._sl = None
|
self._sl = None
|
||||||
|
|
||||||
self._points: List[Point] = []
|
self._points: List[Point] = []
|
||||||
self._modification_count = 0
|
|
||||||
self._old_interpolated = ""
|
|
||||||
|
|
||||||
self._profile_type = _type
|
self._profile_type = _type
|
||||||
|
|
||||||
@@ -162,12 +160,7 @@ class Profile(object):
|
|||||||
|
|
||||||
@rk.setter
|
@rk.setter
|
||||||
def rk(self, value: float):
|
def rk(self, value: float):
|
||||||
value = float(value)
|
self._rk = float(value)
|
||||||
changed = value != self._rk
|
|
||||||
self._rk = value
|
|
||||||
if changed:
|
|
||||||
self.content_modified()
|
|
||||||
else:
|
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -180,12 +173,7 @@ class Profile(object):
|
|||||||
|
|
||||||
@name.setter
|
@name.setter
|
||||||
def name(self, value: str):
|
def name(self, value: str):
|
||||||
value = value.strip()
|
self._name = value.strip()
|
||||||
changed = value != self._name
|
|
||||||
self._name = value
|
|
||||||
if changed:
|
|
||||||
self.content_modified()
|
|
||||||
else:
|
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -229,38 +217,6 @@ class Profile(object):
|
|||||||
return [point for point in self.points
|
return [point for point in self.points
|
||||||
if point.is_named()]
|
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):
|
def insert_point(self, index: int, point: Point):
|
||||||
"""Insert point at index.
|
"""Insert point at index.
|
||||||
|
|
||||||
@@ -276,7 +232,7 @@ class Profile(object):
|
|||||||
else:
|
else:
|
||||||
self._points.insert(index, point)
|
self._points.insert(index, point)
|
||||||
|
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
def delete_i(self, indexes: list):
|
def delete_i(self, indexes: list):
|
||||||
list(
|
list(
|
||||||
@@ -289,7 +245,7 @@ class Profile(object):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
def delete_points(self, points):
|
def delete_points(self, points):
|
||||||
"""Delete some elements in profile list
|
"""Delete some elements in profile list
|
||||||
@@ -306,7 +262,7 @@ class Profile(object):
|
|||||||
points
|
points
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
# Move
|
# Move
|
||||||
|
|
||||||
@@ -316,7 +272,7 @@ class Profile(object):
|
|||||||
|
|
||||||
p = self._points
|
p = self._points
|
||||||
p[index], p[next] = p[next], p[index]
|
p[index], p[next] = p[next], p[index]
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
def move_down_point(self, index: int):
|
def move_down_point(self, index: int):
|
||||||
if index >= 0:
|
if index >= 0:
|
||||||
@@ -324,7 +280,7 @@ class Profile(object):
|
|||||||
|
|
||||||
p = self._points
|
p = self._points
|
||||||
p[index], p[prev] = p[prev], p[index]
|
p[index], p[prev] = p[prev], p[index]
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
# Sort
|
# Sort
|
||||||
|
|
||||||
@@ -341,7 +297,7 @@ class Profile(object):
|
|||||||
key=predicate,
|
key=predicate,
|
||||||
reverse=is_reversed
|
reverse=is_reversed
|
||||||
)
|
)
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
@timer
|
@timer
|
||||||
def sort_with_indexes(self, indexes: list):
|
def sort_with_indexes(self, indexes: list):
|
||||||
@@ -357,12 +313,12 @@ class Profile(object):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
@timer
|
@timer
|
||||||
def reverse(self):
|
def reverse(self):
|
||||||
self._points.reverse()
|
self._points.reverse()
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
# Sediment Layers
|
# Sediment Layers
|
||||||
|
|
||||||
|
|||||||
@@ -58,8 +58,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
num=0,
|
num=0,
|
||||||
nb_point: int = 0,
|
nb_point: int = 0,
|
||||||
code1: int = 0, code2: int = 0,
|
code1: int = 0, code2: int = 0,
|
||||||
status=None, owner_scenario=-1,
|
status=None, owner_scenario=-1):
|
||||||
enabled=True, interpolated=False):
|
|
||||||
"""ProfileXYZ constructor
|
"""ProfileXYZ constructor
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
@@ -91,8 +90,6 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
self.time_l = 0.0
|
self.time_l = 0.0
|
||||||
self._station = []
|
self._station = []
|
||||||
self.station_up_to_date = False
|
self.station_up_to_date = False
|
||||||
self._enabled = bool(enabled)
|
|
||||||
self._interpolated = bool(interpolated)
|
|
||||||
|
|
||||||
self._get_water_limits_cache = {}
|
self._get_water_limits_cache = {}
|
||||||
self._get_water_limits_ac_cache = {}
|
self._get_water_limits_ac_cache = {}
|
||||||
@@ -111,8 +108,6 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
code1 INTEGER NOT NULL,
|
code1 INTEGER NOT NULL,
|
||||||
code2 INTEGER NOT NULL,
|
code2 INTEGER NOT NULL,
|
||||||
sl INTEGER,
|
sl INTEGER,
|
||||||
enabled BOOLEAN NOT NULL DEFAULT TRUE,
|
|
||||||
interpolated BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
{Scenario.create_db_add_scenario()},
|
{Scenario.create_db_add_scenario()},
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
{Scenario.create_db_add_scenario_fk()},
|
||||||
FOREIGN KEY(reach) REFERENCES river_reach(pamhyr_id),
|
FOREIGN KEY(reach) REFERENCES river_reach(pamhyr_id),
|
||||||
@@ -157,27 +152,6 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
"ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE"
|
"ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE"
|
||||||
)
|
)
|
||||||
|
|
||||||
if major == "0" and int(minor) <= 2:
|
|
||||||
if int(release) < 9:
|
|
||||||
execute(
|
|
||||||
"ALTER TABLE geometry_profileXYZ " +
|
|
||||||
"ADD COLUMN enabled BOOLEAN NOT NULL DEFAULT TRUE"
|
|
||||||
)
|
|
||||||
|
|
||||||
if major == "0" and (int(minor) < 2 or
|
|
||||||
(minor == "2" and int(release) < 10)):
|
|
||||||
if minor != "0":
|
|
||||||
execute(
|
|
||||||
"ALTER TABLE geometry_profileXYZ " +
|
|
||||||
"ADD COLUMN interpolated BOOLEAN NOT NULL DEFAULT FALSE"
|
|
||||||
)
|
|
||||||
execute(
|
|
||||||
"UPDATE geometry_profileXYZ " +
|
|
||||||
"SET interpolated = CASE " +
|
|
||||||
"WHEN LOWER(name) LIKE 'interpol%' THEN TRUE " +
|
|
||||||
"ELSE FALSE END"
|
|
||||||
)
|
|
||||||
|
|
||||||
return cls._update_submodel(execute, version, data)
|
return cls._update_submodel(execute, version, data)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -263,7 +237,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
|
|
||||||
table = execute(
|
table = execute(
|
||||||
"SELECT pamhyr_id, ind, deleted, name, rk, num, " +
|
"SELECT pamhyr_id, ind, deleted, name, rk, num, " +
|
||||||
"code1, code2, sl, scenario, enabled, interpolated " +
|
"code1, code2, sl, scenario " +
|
||||||
"FROM geometry_profileXYZ " +
|
"FROM geometry_profileXYZ " +
|
||||||
f"WHERE reach = {reach.id} " +
|
f"WHERE reach = {reach.id} " +
|
||||||
f"AND scenario = {scenario.id} " +
|
f"AND scenario = {scenario.id} " +
|
||||||
@@ -284,8 +258,6 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
code2 = next(it)
|
code2 = next(it)
|
||||||
sl = next(it)
|
sl = next(it)
|
||||||
owner_scenario = next(it)
|
owner_scenario = next(it)
|
||||||
enabled = (next(it) == 1)
|
|
||||||
interpolated = (next(it) == 1)
|
|
||||||
|
|
||||||
profile = cls(
|
profile = cls(
|
||||||
id=pid, ind=ind, num=num,
|
id=pid, ind=ind, num=num,
|
||||||
@@ -293,9 +265,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
code1=code1, code2=code2,
|
code1=code1, code2=code2,
|
||||||
reach=reach,
|
reach=reach,
|
||||||
status=status,
|
status=status,
|
||||||
owner_scenario=owner_scenario,
|
owner_scenario=owner_scenario
|
||||||
enabled=enabled,
|
|
||||||
interpolated=interpolated
|
|
||||||
)
|
)
|
||||||
if deleted:
|
if deleted:
|
||||||
profile.set_as_deleted()
|
profile.set_as_deleted()
|
||||||
@@ -348,14 +318,12 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
execute(
|
execute(
|
||||||
"INSERT OR REPLACE INTO " +
|
"INSERT OR REPLACE INTO " +
|
||||||
"geometry_profileXYZ(pamhyr_id, deleted, ind, name, reach, " +
|
"geometry_profileXYZ(pamhyr_id, deleted, ind, name, reach, " +
|
||||||
"rk, num, code1, code2, sl, scenario, enabled, interpolated) " +
|
"rk, num, code1, code2, sl, scenario) " +
|
||||||
"VALUES (" +
|
"VALUES (" +
|
||||||
f"{self.pamhyr_id}, {self._db_format(self.is_deleted())}, " +
|
f"{self.pamhyr_id}, {self._db_format(self.is_deleted())}, " +
|
||||||
f"{ind}, '{self._db_format(self._name)}', " +
|
f"{ind}, '{self._db_format(self._name)}', " +
|
||||||
f"{self.reach.pamhyr_id}, {self.rk}, {self.num}, " +
|
f"{self.reach.pamhyr_id}, {self.rk}, {self.num}, " +
|
||||||
f"{self.code1}, {self.code1}, {sl}, {self._status.scenario_id}, " +
|
f"{self.code1}, {self.code1}, {sl}, {self._status.scenario_id}" +
|
||||||
f"{self._db_format(self._enabled)}, " +
|
|
||||||
f"{self._db_format(self._interpolated)}" +
|
|
||||||
")"
|
")"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -422,9 +390,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
name=self.name,
|
name=self.name,
|
||||||
rk=self.rk,
|
rk=self.rk,
|
||||||
reach=self.reach,
|
reach=self.reach,
|
||||||
status=self._status,
|
status=self._status
|
||||||
enabled=self.is_enabled,
|
|
||||||
interpolated=self.interpolated
|
|
||||||
)
|
)
|
||||||
if self.is_deleted():
|
if self.is_deleted():
|
||||||
new_p.set_as_deleted()
|
new_p.set_as_deleted()
|
||||||
@@ -444,9 +410,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
name=self.name,
|
name=self.name,
|
||||||
rk=self.rk,
|
rk=self.rk,
|
||||||
reach=new_reach,
|
reach=new_reach,
|
||||||
status=self._status,
|
status=self._status
|
||||||
enabled=self.is_enabled,
|
|
||||||
interpolated=self.interpolated
|
|
||||||
)
|
)
|
||||||
if self.is_deleted():
|
if self.is_deleted():
|
||||||
new_p.set_as_deleted()
|
new_p.set_as_deleted()
|
||||||
@@ -559,7 +523,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
)
|
)
|
||||||
self._points.append(pt)
|
self._points.append(pt)
|
||||||
|
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
def get_point_i(self, index: int) -> PointXYZ:
|
def get_point_i(self, index: int) -> PointXYZ:
|
||||||
"""Get point at index.
|
"""Get point at index.
|
||||||
@@ -624,7 +588,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
)
|
)
|
||||||
self.points.append(point_xyz)
|
self.points.append(point_xyz)
|
||||||
|
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
def insert(self, index: int):
|
def insert(self, index: int):
|
||||||
"""Insert a new point at index.
|
"""Insert a new point at index.
|
||||||
@@ -643,7 +607,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
point = PointXYZ(x=x, y=y, z=z, profile=self, status=self._status)
|
point = PointXYZ(x=x, y=y, z=z, profile=self, status=self._status)
|
||||||
self._points.insert(index, point)
|
self._points.insert(index, point)
|
||||||
|
|
||||||
self.content_modified()
|
self.modified()
|
||||||
|
|
||||||
return point
|
return point
|
||||||
|
|
||||||
@@ -862,6 +826,13 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
|
|
||||||
return n_zones
|
return n_zones
|
||||||
|
|
||||||
|
def froude(self, z, v):
|
||||||
|
return v / np.sqrt(
|
||||||
|
9.81 * (
|
||||||
|
self.wet_area(z) / self.wet_width(z)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
@timer
|
@timer
|
||||||
def get_all_water_limits_ac(self, z):
|
def get_all_water_limits_ac(self, z):
|
||||||
"""
|
"""
|
||||||
@@ -1003,7 +974,7 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
Projection of the points of the profile on a plane.
|
Projection of the points of the profile on a plane.
|
||||||
"""
|
"""
|
||||||
if self.nb_points < 2:
|
if self.nb_points < 2:
|
||||||
return [0.0] * self.nb_points
|
return [0.0]
|
||||||
else:
|
else:
|
||||||
if self.station_up_to_date:
|
if self.station_up_to_date:
|
||||||
return self._station
|
return self._station
|
||||||
@@ -1167,14 +1138,11 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
p = ProfileXYZ(name=self.name,
|
p = ProfileXYZ(name=self.name,
|
||||||
rk=self.rk,
|
rk=self.rk,
|
||||||
reach=self.reach,
|
reach=self.reach,
|
||||||
status=self._status,
|
status=self._status)
|
||||||
enabled=self.is_enabled,
|
|
||||||
interpolated=self.interpolated)
|
|
||||||
|
|
||||||
for i, k in enumerate(self.points):
|
for i, k in enumerate(self.points):
|
||||||
p.insert_point(i, k.cloned_for(p))
|
p.insert_point(i, k.copy())
|
||||||
|
|
||||||
p._interpolated = self.interpolated
|
|
||||||
return p
|
return p
|
||||||
|
|
||||||
def purge_aligned_points(self):
|
def purge_aligned_points(self):
|
||||||
@@ -1204,25 +1172,3 @@ class ProfileXYZ(Profile, SQLSubModel):
|
|||||||
break
|
break
|
||||||
self._points = points
|
self._points = points
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
@property
|
|
||||||
def is_enabled(self):
|
|
||||||
return self._enabled
|
|
||||||
|
|
||||||
@property
|
|
||||||
def enabled(self):
|
|
||||||
return self._enabled
|
|
||||||
|
|
||||||
@enabled.setter
|
|
||||||
def enabled(self, value):
|
|
||||||
self._enabled = bool(value)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def interpolated(self):
|
|
||||||
return self._interpolated
|
|
||||||
|
|
||||||
@interpolated.setter
|
|
||||||
def interpolated(self, value):
|
|
||||||
self._interpolated = bool(value)
|
|
||||||
self.modified()
|
|
||||||
@@ -80,13 +80,11 @@ class Reach(SQLSubModel):
|
|||||||
@classmethod
|
@classmethod
|
||||||
def _db_load(cls, execute, data=None):
|
def _db_load(cls, execute, data=None):
|
||||||
new = cls(status=data["status"], parent=data["reach"])
|
new = cls(status=data["status"], parent=data["reach"])
|
||||||
profile_data = data.copy()
|
|
||||||
profile_data["reach"] = new
|
|
||||||
|
|
||||||
new._profiles = sorted(
|
new._profiles = sorted(
|
||||||
ProfileXYZ._db_load(
|
ProfileXYZ._db_load(
|
||||||
execute,
|
execute,
|
||||||
data=profile_data
|
data=data.copy()
|
||||||
),
|
),
|
||||||
key=lambda p: p._db_ind
|
key=lambda p: p._db_ind
|
||||||
)
|
)
|
||||||
@@ -159,14 +157,6 @@ class Reach(SQLSubModel):
|
|||||||
def profiles(self, profiles):
|
def profiles(self, profiles):
|
||||||
self._profiles = profiles
|
self._profiles = profiles
|
||||||
|
|
||||||
@property
|
|
||||||
def enabled_profiles(self):
|
|
||||||
return list(filter(lambda p: p.is_enabled, self.profiles))
|
|
||||||
|
|
||||||
@property
|
|
||||||
def number_enabled_profiles(self):
|
|
||||||
return len(self.enabled_profiles)
|
|
||||||
|
|
||||||
def get_profiles_from_rk(self, rk):
|
def get_profiles_from_rk(self, rk):
|
||||||
return list(
|
return list(
|
||||||
filter(
|
filter(
|
||||||
@@ -377,28 +367,6 @@ class Reach(SQLSubModel):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
def get_z_min_enabled_profiles(self):
|
|
||||||
return list(
|
|
||||||
map(
|
|
||||||
lambda profile: profile.z_min(),
|
|
||||||
filter(
|
|
||||||
lambda profile: len(profile) > 0 and profile.is_enabled,
|
|
||||||
self.profiles
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_z_max_enabled_profiles(self):
|
|
||||||
return list(
|
|
||||||
map(
|
|
||||||
lambda profile: profile.z_max(),
|
|
||||||
filter(
|
|
||||||
lambda profile: len(profile) > 0 and profile.is_enabled,
|
|
||||||
self.profiles
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_rk(self):
|
def get_rk(self):
|
||||||
"""List of profiles rk
|
"""List of profiles rk
|
||||||
|
|
||||||
@@ -407,17 +375,6 @@ class Reach(SQLSubModel):
|
|||||||
"""
|
"""
|
||||||
return [profile.rk for profile in self.profiles]
|
return [profile.rk for profile in self.profiles]
|
||||||
|
|
||||||
def get_rk_enabled_profiles(self):
|
|
||||||
return list(
|
|
||||||
map(
|
|
||||||
lambda profile: profile.rk,
|
|
||||||
filter(
|
|
||||||
lambda profile: len(profile) > 0 and profile.is_enabled,
|
|
||||||
self.profiles
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_rk_complete_profiles(self):
|
def get_rk_complete_profiles(self):
|
||||||
return list(
|
return list(
|
||||||
map(
|
map(
|
||||||
@@ -529,22 +486,14 @@ class Reach(SQLSubModel):
|
|||||||
)
|
)
|
||||||
|
|
||||||
@timer
|
@timer
|
||||||
def compute_guidelines(self, profiles=None, update_cache=True):
|
def compute_guidelines(self):
|
||||||
"""Compute reach guidelines
|
"""Compute reach guidelines
|
||||||
|
|
||||||
Args:
|
|
||||||
profiles: Profiles used to compute the guidelines. If omitted,
|
|
||||||
all non-deleted profiles of the reach are used.
|
|
||||||
update_cache: Whether to update the reach guidelines cache.
|
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Tuple of complete and incomplete guidelines name.
|
Tuple of complete and incomplete guidelines name.
|
||||||
"""
|
"""
|
||||||
if profiles is None:
|
|
||||||
profiles = self.profiles
|
|
||||||
|
|
||||||
# Get all point contained into a guideline
|
# Get all point contained into a guideline
|
||||||
named_points = [profile.named_points() for profile in profiles]
|
named_points = [profile.named_points() for profile in self.profiles]
|
||||||
points_name = list(
|
points_name = list(
|
||||||
map(
|
map(
|
||||||
lambda lst: list(map(lambda p: p.name, lst)),
|
lambda lst: list(map(lambda p: p.name, lst)),
|
||||||
@@ -575,13 +524,11 @@ class Reach(SQLSubModel):
|
|||||||
|
|
||||||
complete = guide_set - incomplete
|
complete = guide_set - incomplete
|
||||||
|
|
||||||
if update_cache:
|
|
||||||
# Compute guideline and put data in cache
|
# Compute guideline and put data in cache
|
||||||
self._compute_guidelines_cache(
|
self._compute_guidelines_cache(guide_set, named_points,
|
||||||
guide_set, named_points, complete, incomplete
|
complete, incomplete)
|
||||||
)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
|
self.modified()
|
||||||
return (complete, incomplete)
|
return (complete, incomplete)
|
||||||
|
|
||||||
def _map_guidelines_points(self, func, full=False):
|
def _map_guidelines_points(self, func, full=False):
|
||||||
@@ -805,11 +752,8 @@ class Reach(SQLSubModel):
|
|||||||
list_profile.append(list_point_profile)
|
list_profile.append(list_point_profile)
|
||||||
list_point_profile = []
|
list_point_profile = []
|
||||||
else:
|
else:
|
||||||
# MAGE-8 ST files can append hydraulic data
|
line.append("")
|
||||||
# after the regular x, y, z and point-name
|
list_point_profile.append(line[:3])
|
||||||
# fields. ProfileXYZ still expects exactly
|
|
||||||
# those first four fields.
|
|
||||||
list_point_profile.append(line[:4])
|
|
||||||
else:
|
else:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|||||||
@@ -277,10 +277,3 @@ class BasicHS(SQLSubModel):
|
|||||||
|
|
||||||
def convert(self, new_type):
|
def convert(self, new_type):
|
||||||
return new_type(id=self.id, name=self.name, status=self._status)
|
return new_type(id=self.id, name=self.name, status=self._status)
|
||||||
|
|
||||||
def cloned(self):
|
|
||||||
new = type(self)(name=self._name, status=self._status)
|
|
||||||
new._enabled = self._enabled
|
|
||||||
new._data = [value.cloned() for value in self._data]
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
@@ -208,11 +208,3 @@ class BHSValue(SQLSubModel):
|
|||||||
def value(self, value):
|
def value(self, value):
|
||||||
self._value = self._type(value)
|
self._value = self._type(value)
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
def cloned(self):
|
|
||||||
return BHSValue(
|
|
||||||
name=self._name,
|
|
||||||
type=self._type,
|
|
||||||
value=self._value,
|
|
||||||
status=self._status
|
|
||||||
)
|
|
||||||
@@ -47,7 +47,9 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
|
|
||||||
self._name = name
|
self._name = name
|
||||||
self._input_section = None
|
self._input_section = None
|
||||||
|
self._output_section = None
|
||||||
self._input_reach = None
|
self._input_reach = None
|
||||||
|
self._output_reach = None
|
||||||
self._enabled = True
|
self._enabled = True
|
||||||
self._data = []
|
self._data = []
|
||||||
|
|
||||||
@@ -60,12 +62,17 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
enabled BOOLEAN NOT NULL,
|
enabled BOOLEAN NOT NULL,
|
||||||
input_reach INTEGER,
|
input_reach INTEGER,
|
||||||
|
output_reach INTEGER,
|
||||||
input_section INTEGER,
|
input_section INTEGER,
|
||||||
|
output_section INTEGER,
|
||||||
{Scenario.create_db_add_scenario()},
|
{Scenario.create_db_add_scenario()},
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
{Scenario.create_db_add_scenario_fk()},
|
||||||
FOREIGN KEY(input_reach) REFERENCES river_reach(pamhyr_id),
|
FOREIGN KEY(input_reach) REFERENCES river_reach(pamhyr_id),
|
||||||
|
FOREIGN KEY(output_reach) REFERENCES river_reach(pamhyr_id),
|
||||||
FOREIGN KEY(input_section)
|
FOREIGN KEY(input_section)
|
||||||
REFERENCES geometry_profileXYZ(pamhyr_id),
|
REFERENCES geometry_profileXYZ(pamhyr_id),
|
||||||
|
FOREIGN KEY(output_section)
|
||||||
|
REFERENCES geometry_profileXYZ(pamhyr_id),
|
||||||
PRIMARY KEY(pamhyr_id, scenario)
|
PRIMARY KEY(pamhyr_id, scenario)
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
@@ -85,10 +92,11 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
return True
|
return True
|
||||||
|
|
||||||
if rl < 11:
|
if rl < 11:
|
||||||
|
for v in ["input", "output"]:
|
||||||
execute(
|
execute(
|
||||||
"""
|
f"""
|
||||||
ALTER TABLE hydraulic_structures
|
ALTER TABLE hydraulic_structures
|
||||||
RENAME COLUMN input_kp TO input_rk
|
RENAME COLUMN {v}_kp TO {v}_rk
|
||||||
"""
|
"""
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -104,28 +112,8 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
"ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE"
|
"ADD COLUMN deleted BOOLEAN NOT NULL DEFAULT FALSE"
|
||||||
)
|
)
|
||||||
|
|
||||||
if major == "0" and (int(minor) < 2 or
|
|
||||||
(minor == "2" and rl < 10)):
|
|
||||||
cls._db_update_to_0_2_10(execute)
|
|
||||||
|
|
||||||
return cls._update_submodel(execute, version, data)
|
return cls._update_submodel(execute, version, data)
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_update_to_0_2_10(cls, execute):
|
|
||||||
table = "hydraulic_structures"
|
|
||||||
cls._db_create(execute, ext="_tmp")
|
|
||||||
|
|
||||||
execute(
|
|
||||||
f"INSERT INTO {table}_tmp " +
|
|
||||||
"(pamhyr_id, deleted, name, enabled, input_section, " +
|
|
||||||
"input_reach, scenario) " +
|
|
||||||
"SELECT pamhyr_id, deleted, name, enabled, input_section, " +
|
|
||||||
f"input_reach, scenario FROM {table}"
|
|
||||||
)
|
|
||||||
|
|
||||||
execute(f"DROP TABLE {table}")
|
|
||||||
execute(f"ALTER TABLE {table}_tmp RENAME TO {table}")
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _db_update_to_0_2_0(cls, execute, data):
|
def _db_update_to_0_2_0(cls, execute, data):
|
||||||
table = "hydraulic_structures"
|
table = "hydraulic_structures"
|
||||||
@@ -143,10 +131,11 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
|
|
||||||
execute(
|
execute(
|
||||||
f"INSERT INTO {table}_tmp " +
|
f"INSERT INTO {table}_tmp " +
|
||||||
"(pamhyr_id, name, enabled, input_section, " +
|
"(pamhyr_id, name, enabled, input_section, output_section, " +
|
||||||
"input_reach, scenario) " +
|
"input_reach, output_reach, scenario) " +
|
||||||
"SELECT pamhyr_id, name, enabled, " +
|
"SELECT pamhyr_id, name, enabled, " +
|
||||||
"input_section, input_reach, scenario " +
|
"input_section, output_section, " +
|
||||||
|
"input_reach, output_reach, scenario " +
|
||||||
f"FROM {table}"
|
f"FROM {table}"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -156,36 +145,42 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
@classmethod
|
@classmethod
|
||||||
def _db_update_to_0_2_0_set_reach_pid(cls, execute, table, reachs):
|
def _db_update_to_0_2_0_set_reach_pid(cls, execute, table, reachs):
|
||||||
els = execute(
|
els = execute(
|
||||||
f"SELECT pamhyr_id, input_reach FROM {table}"
|
f"SELECT pamhyr_id, input_reach, output_reach FROM {table}"
|
||||||
)
|
)
|
||||||
|
|
||||||
for row in els:
|
for row in els:
|
||||||
it = iter(row)
|
it = iter(row)
|
||||||
pid = next(it)
|
pid = next(it)
|
||||||
in_reach_id = next(it)
|
in_reach_id = next(it)
|
||||||
|
out_reach_id = next(it)
|
||||||
|
|
||||||
if in_reach_id == -1:
|
if in_reach_id == -1:
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if out_reach_id == -1:
|
||||||
|
out_reach_id = in_reach_id
|
||||||
|
|
||||||
execute(
|
execute(
|
||||||
f"UPDATE {table} " +
|
f"UPDATE {table} " +
|
||||||
f"SET input_reach = {reachs[in_reach_id]} " +
|
f"SET input_reach = {reachs[in_reach_id]}, " +
|
||||||
|
f"output_reach = {reachs[out_reach_id]} " +
|
||||||
f"WHERE pamhyr_id = {pid}"
|
f"WHERE pamhyr_id = {pid}"
|
||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _db_update_to_0_1_1(cls, execute, data,
|
def _db_update_to_0_1_1(cls, execute, data,
|
||||||
origin_version="0.1.0"):
|
origin_version="0.1.0"):
|
||||||
|
for v in ["input", "output"]:
|
||||||
execute(
|
execute(
|
||||||
"ALTER TABLE hydraulic_structures " +
|
"ALTER TABLE hydraulic_structures " +
|
||||||
"ADD COLUMN input_section INTEGER"
|
f"ADD COLUMN {v}_section INTEGER"
|
||||||
)
|
)
|
||||||
|
|
||||||
cls._db_update_to_0_1_1_assoc_section_from_rk(
|
cls._db_update_to_0_1_1_assoc_section_from_rk(
|
||||||
execute, "hydraulic_structures",
|
execute, "hydraulic_structures",
|
||||||
reach_column="input_reach",
|
reach_column=f"{v}_reach",
|
||||||
rk_column="input_rk",
|
rk_column=f"{v}_rk",
|
||||||
section_column="input_section",
|
section_column=f"{v}_section",
|
||||||
origin_version=origin_version
|
origin_version=origin_version
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -201,7 +196,8 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
|
|
||||||
table = execute(
|
table = execute(
|
||||||
"SELECT pamhyr_id, deleted, name, enabled, " +
|
"SELECT pamhyr_id, deleted, name, enabled, " +
|
||||||
"input_section, input_reach, scenario " +
|
"input_section, output_section, " +
|
||||||
|
"input_reach, output_reach, scenario " +
|
||||||
"FROM hydraulic_structures " +
|
"FROM hydraulic_structures " +
|
||||||
f"WHERE scenario = {scenario.id} " +
|
f"WHERE scenario = {scenario.id} " +
|
||||||
f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))})"
|
f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))})"
|
||||||
@@ -231,7 +227,12 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
input_section_id = (
|
input_section_id = (
|
||||||
-1 if input_section_id is None else input_section_id
|
-1 if input_section_id is None else input_section_id
|
||||||
)
|
)
|
||||||
|
output_section_id = next(it)
|
||||||
|
output_section_id = (
|
||||||
|
-1 if output_section_id is None else output_section_id
|
||||||
|
)
|
||||||
input_reach_id = next(it)
|
input_reach_id = next(it)
|
||||||
|
output_reach_id = next(it)
|
||||||
owner_scenario = next(it)
|
owner_scenario = next(it)
|
||||||
|
|
||||||
hs = cls(
|
hs = cls(
|
||||||
@@ -242,19 +243,27 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
hs.set_as_deleted()
|
hs.set_as_deleted()
|
||||||
|
|
||||||
hs.enabled = enabled
|
hs.enabled = enabled
|
||||||
hs.input_reach = reduce(
|
hs.input_reach, hs.output_reach = reduce(
|
||||||
lambda acc, n: n if n.pamhyr_id == input_reach_id else acc,
|
lambda acc, n: (
|
||||||
|
n if n.pamhyr_id == input_reach_id else acc[0],
|
||||||
|
n if n.pamhyr_id == output_reach_id else acc[1]
|
||||||
|
),
|
||||||
data["edges"],
|
data["edges"],
|
||||||
None
|
[None, None]
|
||||||
)
|
)
|
||||||
sections = []
|
sections = []
|
||||||
if hs.input_reach is not None:
|
if hs.input_reach is not None:
|
||||||
sections += hs.input_reach.reach.profiles
|
sections += hs.input_reach.reach.profiles
|
||||||
|
if hs.output_reach is not None:
|
||||||
|
sections += hs.output_reach.reach.profiles
|
||||||
|
|
||||||
hs.input_section = reduce(
|
hs.input_section, hs.output_section = reduce(
|
||||||
lambda acc, s: s if s.pamhyr_id == input_section_id else acc,
|
lambda acc, s: (
|
||||||
|
s if s.pamhyr_id == input_section_id else acc[0],
|
||||||
|
s if s.pamhyr_id == output_section_id else acc[1]
|
||||||
|
),
|
||||||
sections,
|
sections,
|
||||||
None
|
[None, None]
|
||||||
)
|
)
|
||||||
|
|
||||||
loaded.add(hs_id)
|
loaded.add(hs_id)
|
||||||
@@ -278,15 +287,24 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
if self._input_reach is not None:
|
if self._input_reach is not None:
|
||||||
input_reach_id = self._input_reach.pamhyr_id
|
input_reach_id = self._input_reach.pamhyr_id
|
||||||
|
|
||||||
|
output_reach_id = -1
|
||||||
|
if self._output_reach is not None:
|
||||||
|
output_reach_id = self._output_reach.pamhyr_id
|
||||||
|
|
||||||
input_section = 'NULL'
|
input_section = 'NULL'
|
||||||
if self.input_section is not None:
|
if self.input_section is not None:
|
||||||
input_section = self.input_section.pamhyr_id
|
input_section = self.input_section.pamhyr_id
|
||||||
|
|
||||||
|
output_section = 'NULL'
|
||||||
|
if self.output_section is not None:
|
||||||
|
output_section = self.output_section.pamhyr_id
|
||||||
|
|
||||||
execute(
|
execute(
|
||||||
"INSERT INTO " +
|
"INSERT INTO " +
|
||||||
"hydraulic_structures(" +
|
"hydraulic_structures(" +
|
||||||
" pamhyr_id, deleted, name, enabled, " +
|
" pamhyr_id, deleted, name, enabled, " +
|
||||||
" input_section, input_reach, " +
|
" input_section, output_section, " +
|
||||||
|
" input_reach, output_reach, " +
|
||||||
" scenario" +
|
" scenario" +
|
||||||
") " +
|
") " +
|
||||||
"VALUES (" +
|
"VALUES (" +
|
||||||
@@ -294,7 +312,8 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
f"{self._db_format(self.is_deleted())}, " +
|
f"{self._db_format(self.is_deleted())}, " +
|
||||||
f"'{self._db_format(self._name)}', " +
|
f"'{self._db_format(self._name)}', " +
|
||||||
f"{self._db_format(self.enabled)}, " +
|
f"{self._db_format(self.enabled)}, " +
|
||||||
f"{input_section}, {input_reach_id}, " +
|
f"{input_section}, {output_section}, " +
|
||||||
|
f"{input_reach_id}, {output_reach_id}, " +
|
||||||
f"{self._status.scenario_id}"
|
f"{self._status.scenario_id}"
|
||||||
")"
|
")"
|
||||||
)
|
)
|
||||||
@@ -352,6 +371,13 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
|
|
||||||
return self._input_section
|
return self._input_section
|
||||||
|
|
||||||
|
@property
|
||||||
|
def output_rk(self):
|
||||||
|
if self._output_section is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
return self._output_section
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def input_section(self):
|
def input_section(self):
|
||||||
return self._input_section
|
return self._input_section
|
||||||
@@ -361,6 +387,15 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
self._input_section = input_section
|
self._input_section = input_section
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def output_section(self):
|
||||||
|
return self._output_section
|
||||||
|
|
||||||
|
@output_section.setter
|
||||||
|
def output_section(self, output_section):
|
||||||
|
self._output_section = output_section
|
||||||
|
self.modified()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def enabled(self):
|
def enabled(self):
|
||||||
return self._enabled
|
return self._enabled
|
||||||
@@ -379,19 +414,19 @@ class HydraulicStructure(SQLSubModel):
|
|||||||
self._input_reach = input_reach
|
self._input_reach = input_reach
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def output_reach(self):
|
||||||
|
return self._output_reach
|
||||||
|
|
||||||
|
@output_reach.setter
|
||||||
|
def output_reach(self, output_reach):
|
||||||
|
self._output_reach = output_reach
|
||||||
|
self.modified()
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def basic_structures(self):
|
def basic_structures(self):
|
||||||
return self.lst.copy()
|
return self.lst.copy()
|
||||||
|
|
||||||
def cloned_for(self, input_reach, input_section):
|
|
||||||
new = HydraulicStructure(name=self._name, status=self._status)
|
|
||||||
new._enabled = self._enabled
|
|
||||||
new._input_reach = input_reach
|
|
||||||
new._input_section = input_section
|
|
||||||
new._data = [structure.cloned() for structure in self.lst]
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
|
|
||||||
def basic_structure(self, index: int):
|
def basic_structure(self, index: int):
|
||||||
if len(self._data) == 0:
|
if len(self._data) == 0:
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -61,64 +61,6 @@ class HydraulicStructureList(PamhyrModelList):
|
|||||||
self.modified()
|
self.modified()
|
||||||
return n
|
return n
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
profiles = reach.reach.profiles
|
|
||||||
split_index = profiles.index(profile)
|
|
||||||
sections1 = dict(zip(
|
|
||||||
profiles[:split_index + 1],
|
|
||||||
reach1.reach.profiles
|
|
||||||
))
|
|
||||||
sections2 = dict(zip(
|
|
||||||
profiles[split_index:],
|
|
||||||
reach2.reach.profiles
|
|
||||||
))
|
|
||||||
|
|
||||||
def split_endpoint(endpoint_reach, section):
|
|
||||||
if endpoint_reach is not reach:
|
|
||||||
return endpoint_reach, section
|
|
||||||
if section not in profiles:
|
|
||||||
return endpoint_reach, section
|
|
||||||
|
|
||||||
index = profiles.index(section)
|
|
||||||
if index < split_index:
|
|
||||||
return reach1, sections1[section]
|
|
||||||
return reach2, sections2[section]
|
|
||||||
|
|
||||||
structures = [
|
|
||||||
structure
|
|
||||||
for structure in self.lst
|
|
||||||
if structure.input_reach is reach
|
|
||||||
]
|
|
||||||
|
|
||||||
for structure in structures:
|
|
||||||
input_reach, input_section = split_endpoint(
|
|
||||||
structure.input_reach,
|
|
||||||
structure.input_section
|
|
||||||
)
|
|
||||||
self._lst.append(structure.cloned_for(
|
|
||||||
input_reach,
|
|
||||||
input_section
|
|
||||||
))
|
|
||||||
|
|
||||||
if len(structures) != 0:
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def enabled_reaches_list(self):
|
|
||||||
return [
|
|
||||||
structure
|
|
||||||
for structure in self.lst
|
|
||||||
if (structure.input_reach is None or
|
|
||||||
(not structure.input_reach.is_deleted() and
|
|
||||||
structure.input_reach.is_enable()))
|
|
||||||
]
|
|
||||||
|
|
||||||
def get_for_enabled_reaches(self, index):
|
|
||||||
structures = self.enabled_reaches_list
|
|
||||||
if not 0 <= index < len(structures):
|
|
||||||
return None
|
|
||||||
return structures[index]
|
|
||||||
|
|
||||||
def __copy__(self):
|
def __copy__(self):
|
||||||
new = HydraulicStructureList()
|
new = HydraulicStructureList()
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,6 @@
|
|||||||
import logging
|
import logging
|
||||||
|
|
||||||
from copy import copy, deepcopy
|
from copy import copy, deepcopy
|
||||||
from math import isclose
|
|
||||||
from tools import trace, timer
|
from tools import trace, timer
|
||||||
from functools import reduce
|
from functools import reduce
|
||||||
from numpy import interp
|
from numpy import interp
|
||||||
@@ -257,17 +256,6 @@ class Data(SQLSubModel):
|
|||||||
)
|
)
|
||||||
return new
|
return new
|
||||||
|
|
||||||
def cloned_for(self, reach, section):
|
|
||||||
return Data(
|
|
||||||
name=self._name,
|
|
||||||
comment=self._comment,
|
|
||||||
section=section,
|
|
||||||
discharge=self._discharge,
|
|
||||||
height=self._height,
|
|
||||||
reach=reach,
|
|
||||||
status=self._status,
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def name(self):
|
def name(self):
|
||||||
return self._name
|
return self._name
|
||||||
@@ -440,28 +428,15 @@ class InitialConditions(SQLSubModel):
|
|||||||
|
|
||||||
def new_from_data(self, rk, discharge, elevation):
|
def new_from_data(self, rk, discharge, elevation):
|
||||||
n = Data(reach=self._reach, status=self._status)
|
n = Data(reach=self._reach, status=self._status)
|
||||||
# Values read from Mage INI files are strings, whereas profile RK
|
|
||||||
# values are stored as floats. Normalize the imported value before
|
|
||||||
# looking up its associated profile.
|
|
||||||
rk = float(rk)
|
|
||||||
|
|
||||||
section = reduce(
|
section = reduce(
|
||||||
lambda acc, s: (
|
lambda acc, s: (
|
||||||
# Mage INI files store RK values with two decimal places.
|
s if s.rk == rk else acc
|
||||||
# Allow for the rounding introduced by that format.
|
|
||||||
s if isclose(s.rk, rk, rel_tol=0.0, abs_tol=0.0051)
|
|
||||||
else acc
|
|
||||||
),
|
),
|
||||||
self._reach.reach.profiles,
|
self._reach.reach.profiles,
|
||||||
None
|
None
|
||||||
)
|
)
|
||||||
|
|
||||||
if section is None:
|
|
||||||
raise ValueError(
|
|
||||||
f"No profile with RK {rk} exists in reach "
|
|
||||||
f"{self._reach.name}"
|
|
||||||
)
|
|
||||||
|
|
||||||
n['section'] = section
|
n['section'] = section
|
||||||
n['discharge'] = discharge
|
n['discharge'] = discharge
|
||||||
n['elevation'] = elevation
|
n['elevation'] = elevation
|
||||||
@@ -530,20 +505,6 @@ class InitialConditions(SQLSubModel):
|
|||||||
for data in self._data:
|
for data in self._data:
|
||||||
data.set_as_deleted()
|
data.set_as_deleted()
|
||||||
|
|
||||||
def _splited_for(self, reach, sections):
|
|
||||||
new = InitialConditions(reach=reach, status=self._status)
|
|
||||||
|
|
||||||
new._data = [
|
|
||||||
data.cloned_for(reach, sections[data["section"]])
|
|
||||||
for data in self.data
|
|
||||||
if data["section"] in sections
|
|
||||||
]
|
|
||||||
|
|
||||||
if len(new._data) != 0:
|
|
||||||
new.modified()
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def generate_growing_constant_depth(self, height: float,
|
def generate_growing_constant_depth(self, height: float,
|
||||||
compute_discharge: bool):
|
compute_discharge: bool):
|
||||||
profiles = self._reach.reach.profiles.copy()
|
profiles = self._reach.reach.profiles.copy()
|
||||||
|
|||||||
@@ -88,28 +88,3 @@ class InitialConditionsDict(PamhyrModelDict):
|
|||||||
new = InitialConditions(reach=reach, status=self._status)
|
new = InitialConditions(reach=reach, status=self._status)
|
||||||
self.set(reach, new)
|
self.set(reach, new)
|
||||||
return new
|
return new
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
if reach not in self._dict:
|
|
||||||
return
|
|
||||||
|
|
||||||
profiles = reach.reach.profiles
|
|
||||||
split_index = profiles.index(profile)
|
|
||||||
|
|
||||||
sections1 = dict(zip(
|
|
||||||
profiles[:split_index + 1],
|
|
||||||
reach1.reach.profiles
|
|
||||||
))
|
|
||||||
sections2 = dict(zip(
|
|
||||||
profiles[split_index:],
|
|
||||||
reach2.reach.profiles
|
|
||||||
))
|
|
||||||
|
|
||||||
self.set(
|
|
||||||
reach1,
|
|
||||||
self._dict[reach]._splited_for(reach1, sections1)
|
|
||||||
)
|
|
||||||
self.set(
|
|
||||||
reach2,
|
|
||||||
self._dict[reach]._splited_for(reach2, sections2)
|
|
||||||
)
|
|
||||||
@@ -359,60 +359,3 @@ class InitialConditionsAdisTS(SQLSubModel):
|
|||||||
x.set_as_not_deleted()
|
x.set_as_not_deleted()
|
||||||
|
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
split_rk = profile.rk
|
|
||||||
reach_rks = reach.reach.get_rk()
|
|
||||||
if len(reach_rks) == 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
lower_reach_rk = min(reach_rks)
|
|
||||||
upper_reach_rk = max(reach_rks)
|
|
||||||
parts = [
|
|
||||||
(reach1.id, lower_reach_rk, split_rk),
|
|
||||||
(reach2.id, split_rk, upper_reach_rk),
|
|
||||||
]
|
|
||||||
specifications = [
|
|
||||||
specification
|
|
||||||
for specification in self._data
|
|
||||||
if (not specification.is_deleted() and
|
|
||||||
specification.reach == reach.id)
|
|
||||||
]
|
|
||||||
|
|
||||||
for specification in specifications:
|
|
||||||
begin = specification.start_rk
|
|
||||||
end = specification.end_rk
|
|
||||||
if begin is None or end is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
lower, upper = sorted((begin, end))
|
|
||||||
reverse = begin > end
|
|
||||||
|
|
||||||
for new_reach, part_lower, part_upper in parts:
|
|
||||||
clipped_lower = max(lower, part_lower)
|
|
||||||
clipped_upper = min(upper, part_upper)
|
|
||||||
if clipped_lower >= clipped_upper:
|
|
||||||
continue
|
|
||||||
|
|
||||||
start_rk = clipped_upper if reverse else clipped_lower
|
|
||||||
end_rk = clipped_lower if reverse else clipped_upper
|
|
||||||
self._data.append(specification.cloned_for(
|
|
||||||
new_reach, start_rk, end_rk
|
|
||||||
))
|
|
||||||
|
|
||||||
if len(specifications) != 0:
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def get_specs_for_enabled_reaches(self, reaches):
|
|
||||||
enabled_reaches = {
|
|
||||||
reach.id
|
|
||||||
for reach in reaches
|
|
||||||
if not reach.is_deleted() and reach.is_enable()
|
|
||||||
}
|
|
||||||
return [
|
|
||||||
specification
|
|
||||||
for specification in self._data
|
|
||||||
if (not specification.is_deleted() and
|
|
||||||
(specification.reach in (None, -1) or
|
|
||||||
specification.reach in enabled_reaches))
|
|
||||||
]
|
|
||||||
@@ -62,12 +62,6 @@ class InitialConditionsAdisTSList(PamhyrModelList):
|
|||||||
self._status.modified()
|
self._status.modified()
|
||||||
return n
|
return n
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
for initial_condition in self.lst:
|
|
||||||
initial_condition.split_reach(
|
|
||||||
reach, profile, reach1, reach2
|
|
||||||
)
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def Initial_Conditions_List(self):
|
def Initial_Conditions_List(self):
|
||||||
return self.lst
|
return self.lst
|
||||||
@@ -31,12 +31,10 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
_sub_classes = []
|
_sub_classes = []
|
||||||
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
def __init__(self, id: int = -1, name: str = "",
|
||||||
status=None, owner_scenario=-1):
|
status=None, owner_scenario=None):
|
||||||
super(ICAdisTSSpec, self).__init__(
|
super(ICAdisTSSpec, self).__init__()
|
||||||
id=id,
|
|
||||||
status=status,
|
self._status = status
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._name_section = name
|
self._name_section = name
|
||||||
self._reach = None
|
self._reach = None
|
||||||
@@ -192,7 +190,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
new_spec.rate = rate
|
new_spec.rate = rate
|
||||||
new_spec.enabled = enabled
|
new_spec.enabled = enabled
|
||||||
|
|
||||||
loaded.add(id)
|
# loaded.add(pid)
|
||||||
new.append(new_spec)
|
new.append(new_spec)
|
||||||
|
|
||||||
data["scenario"] = scenario.parent
|
data["scenario"] = scenario.parent
|
||||||
@@ -236,8 +234,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@name.setter
|
@name.setter
|
||||||
def name(self, name):
|
def name(self, name):
|
||||||
self._name_section = name
|
self._name_section = name
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def reach(self):
|
def reach(self):
|
||||||
@@ -246,8 +243,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@reach.setter
|
@reach.setter
|
||||||
def reach(self, reach):
|
def reach(self, reach):
|
||||||
self._reach = reach
|
self._reach = reach
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def start_rk(self):
|
def start_rk(self):
|
||||||
@@ -256,8 +252,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@start_rk.setter
|
@start_rk.setter
|
||||||
def start_rk(self, start_rk):
|
def start_rk(self, start_rk):
|
||||||
self._start_rk = start_rk
|
self._start_rk = start_rk
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def end_rk(self):
|
def end_rk(self):
|
||||||
@@ -266,8 +261,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@end_rk.setter
|
@end_rk.setter
|
||||||
def end_rk(self, end_rk):
|
def end_rk(self, end_rk):
|
||||||
self._end_rk = end_rk
|
self._end_rk = end_rk
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def concentration(self):
|
def concentration(self):
|
||||||
@@ -276,8 +270,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@concentration.setter
|
@concentration.setter
|
||||||
def concentration(self, concentration):
|
def concentration(self, concentration):
|
||||||
self._concentration = concentration
|
self._concentration = concentration
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def eg(self):
|
def eg(self):
|
||||||
@@ -286,8 +279,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@eg.setter
|
@eg.setter
|
||||||
def eg(self, eg):
|
def eg(self, eg):
|
||||||
self._eg = eg
|
self._eg = eg
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def em(self):
|
def em(self):
|
||||||
@@ -296,8 +288,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@em.setter
|
@em.setter
|
||||||
def em(self, em):
|
def em(self, em):
|
||||||
self._em = em
|
self._em = em
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def ed(self):
|
def ed(self):
|
||||||
@@ -306,8 +297,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@ed.setter
|
@ed.setter
|
||||||
def ed(self, ed):
|
def ed(self, ed):
|
||||||
self._ed = ed
|
self._ed = ed
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def rate(self):
|
def rate(self):
|
||||||
@@ -316,8 +306,7 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@rate.setter
|
@rate.setter
|
||||||
def rate(self, rate):
|
def rate(self, rate):
|
||||||
self._rate = rate
|
self._rate = rate
|
||||||
self.modified()
|
self._status.modified()
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def enabled(self):
|
def enabled(self):
|
||||||
@@ -326,18 +315,4 @@ class ICAdisTSSpec(SQLSubModel):
|
|||||||
@enabled.setter
|
@enabled.setter
|
||||||
def enabled(self, enabled):
|
def enabled(self, enabled):
|
||||||
self._enabled = enabled
|
self._enabled = enabled
|
||||||
self.modified()
|
self._status.modified()
|
||||||
|
|
||||||
def cloned_for(self, reach, start_rk, end_rk):
|
|
||||||
new = ICAdisTSSpec(name=self._name_section, status=self._status)
|
|
||||||
new._reach = reach
|
|
||||||
new._start_rk = start_rk
|
|
||||||
new._end_rk = end_rk
|
|
||||||
new._concentration = self._concentration
|
|
||||||
new._eg = self._eg
|
|
||||||
new._em = self._em
|
|
||||||
new._ed = self._ed
|
|
||||||
new._rate = self._rate
|
|
||||||
new._enabled = self._enabled
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
@@ -1,272 +0,0 @@
|
|||||||
# InitialConditionsTemperature.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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 tools import trace, timer, old_pamhyr_date_to_timestamp
|
|
||||||
|
|
||||||
from Model.Tools.PamhyrDB import SQLSubModel
|
|
||||||
from Model.Except import NotImplementedMethodeError
|
|
||||||
from Model.Scenario import Scenario
|
|
||||||
|
|
||||||
from Model.InitialConditionsTemperature.InitialConditionsTemperatureSpec \
|
|
||||||
import ICTemperatureSpec
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class InitialConditionsTemperature(SQLSubModel):
|
|
||||||
_sub_classes = [
|
|
||||||
ICTemperatureSpec,
|
|
||||||
]
|
|
||||||
|
|
||||||
def __init__(self, id: int = -1, name: str = "default",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(InitialConditionsTemperature, self).__init__(
|
|
||||||
id=id, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
self._status = status
|
|
||||||
|
|
||||||
self._name = name
|
|
||||||
self._temperature = None
|
|
||||||
self._data = []
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_create(cls, execute, ext=""):
|
|
||||||
execute(f"""
|
|
||||||
CREATE TABLE initial_conditions_temperature{ext}(
|
|
||||||
{cls.create_db_add_pamhyr_id()},
|
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
temperature REAL NOT NULL,
|
|
||||||
{Scenario.create_db_add_scenario()},
|
|
||||||
{Scenario.create_db_add_scenario_fk()}
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
|
|
||||||
return cls._create_submodel(execute)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_update(cls, execute, version, data=None):
|
|
||||||
major, minor, release = version.strip().split(".")
|
|
||||||
|
|
||||||
if major == "0":
|
|
||||||
if int(minor) < 2 or (int(minor) == 2 and int(release) <= 7):
|
|
||||||
table_name = "initial_conditions_temperature"
|
|
||||||
if not cls.is_table_exists(execute, table_name):
|
|
||||||
cls._db_create(execute)
|
|
||||||
|
|
||||||
return cls._update_submodel(execute, version, data)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_load(cls, execute, data=None):
|
|
||||||
new = []
|
|
||||||
status = data['status']
|
|
||||||
scenario = data["scenario"]
|
|
||||||
loaded = data['loaded_pid']
|
|
||||||
|
|
||||||
if scenario is None:
|
|
||||||
return new
|
|
||||||
|
|
||||||
table = execute(
|
|
||||||
"SELECT pamhyr_id, deleted, " +
|
|
||||||
"name, temperature, scenario " +
|
|
||||||
"FROM initial_conditions_temperature " +
|
|
||||||
f"WHERE scenario = {scenario.id} " +
|
|
||||||
f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))})"
|
|
||||||
)
|
|
||||||
|
|
||||||
if table is not None:
|
|
||||||
for row in table:
|
|
||||||
it = iter(row)
|
|
||||||
|
|
||||||
pid = next(it)
|
|
||||||
deleted = (next(it) == 1)
|
|
||||||
name = next(it)
|
|
||||||
temperature = next(it)
|
|
||||||
owner_scenario = next(it)
|
|
||||||
|
|
||||||
ic = cls(
|
|
||||||
id=pid,
|
|
||||||
name=name,
|
|
||||||
status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
if deleted:
|
|
||||||
ic.set_as_deleted()
|
|
||||||
|
|
||||||
ic.temperature = temperature
|
|
||||||
|
|
||||||
data['ic_default_id'] = pid
|
|
||||||
ic._data = ICTemperatureSpec._db_load(execute, data)
|
|
||||||
|
|
||||||
loaded.add(pid)
|
|
||||||
new.append(ic)
|
|
||||||
|
|
||||||
data["scenario"] = scenario.parent
|
|
||||||
new += cls._db_load(execute, data)
|
|
||||||
data["scenario"] = scenario
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
|
||||||
if not self.must_be_saved():
|
|
||||||
return True
|
|
||||||
|
|
||||||
execute(
|
|
||||||
"DELETE FROM initial_conditions_temperature " +
|
|
||||||
f"WHERE pamhyr_id = {self.id} " +
|
|
||||||
f"AND scenario = {self._status.scenario_id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
temperature = self._temperature if \
|
|
||||||
self._temperature is not None else 0.0
|
|
||||||
|
|
||||||
sql = (
|
|
||||||
"INSERT INTO " +
|
|
||||||
"initial_conditions_temperature(" +
|
|
||||||
"pamhyr_id, deleted, name, temperature, " +
|
|
||||||
"scenario" +
|
|
||||||
") " +
|
|
||||||
"VALUES (" +
|
|
||||||
f"{self.id}, {self.is_deleted()}, " +
|
|
||||||
f"'{self._db_format(self._name)}', " +
|
|
||||||
f"{temperature}, {self._status.scenario_id}" +
|
|
||||||
")"
|
|
||||||
)
|
|
||||||
|
|
||||||
execute(sql)
|
|
||||||
|
|
||||||
data['ic_default_id'] = self.id
|
|
||||||
execute(
|
|
||||||
"DELETE FROM initial_conditions_temperature_spec " +
|
|
||||||
f"WHERE ic_default = {self.id} " +
|
|
||||||
f"AND scenario = {self._status.scenario_id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
for ic_spec in self._data:
|
|
||||||
ic_spec._db_save(execute, data)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
return len(self.data)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def data(self):
|
|
||||||
return list(filter(lambda item: not item.is_deleted(), self._data))
|
|
||||||
|
|
||||||
@property
|
|
||||||
def name(self):
|
|
||||||
return self._name
|
|
||||||
|
|
||||||
@name.setter
|
|
||||||
def name(self, name):
|
|
||||||
self._name = name
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def temperature(self):
|
|
||||||
return self._temperature
|
|
||||||
|
|
||||||
@temperature.setter
|
|
||||||
def temperature(self, temperature):
|
|
||||||
self._temperature = temperature
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def new(self, index):
|
|
||||||
n = ICTemperatureSpec(status=self._status)
|
|
||||||
self._data.insert(index, n)
|
|
||||||
self.modified()
|
|
||||||
return n
|
|
||||||
|
|
||||||
def delete(self, data):
|
|
||||||
list(
|
|
||||||
map(
|
|
||||||
lambda x: x.set_as_deleted(),
|
|
||||||
data
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def delete_i(self, indexes):
|
|
||||||
list(
|
|
||||||
map(
|
|
||||||
lambda e: e[1].set_as_deleted(),
|
|
||||||
filter(
|
|
||||||
lambda e: e[0] in indexes,
|
|
||||||
enumerate(self._data)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def insert(self, index, data):
|
|
||||||
if data in self._data:
|
|
||||||
self.undelete([data])
|
|
||||||
else:
|
|
||||||
self._data.insert(index, data)
|
|
||||||
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def undelete(self, lst):
|
|
||||||
for x in lst:
|
|
||||||
x.set_as_not_deleted()
|
|
||||||
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
parts = []
|
|
||||||
for new_reach in (reach1, reach2):
|
|
||||||
rks = new_reach.reach.get_rk()
|
|
||||||
if rks:
|
|
||||||
parts.append((new_reach.id, min(rks), max(rks)))
|
|
||||||
|
|
||||||
specifications = [
|
|
||||||
specification
|
|
||||||
for specification in self._data
|
|
||||||
if (not specification.is_deleted() and
|
|
||||||
specification.reach == reach.id)
|
|
||||||
]
|
|
||||||
clones = []
|
|
||||||
|
|
||||||
for specification in specifications:
|
|
||||||
begin = specification.start_rk
|
|
||||||
end = specification.end_rk
|
|
||||||
if begin is None or end is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
lower, upper = sorted((begin, end))
|
|
||||||
reverse = begin > end
|
|
||||||
for new_reach, part_lower, part_upper in parts:
|
|
||||||
clipped_lower = max(lower, part_lower)
|
|
||||||
clipped_upper = min(upper, part_upper)
|
|
||||||
if clipped_lower >= clipped_upper:
|
|
||||||
continue
|
|
||||||
|
|
||||||
start_rk = clipped_upper if reverse else clipped_lower
|
|
||||||
end_rk = clipped_lower if reverse else clipped_upper
|
|
||||||
clones.append(specification.cloned_for(
|
|
||||||
new_reach, start_rk, end_rk
|
|
||||||
))
|
|
||||||
|
|
||||||
if clones:
|
|
||||||
self._data.extend(clones)
|
|
||||||
self.modified()
|
|
||||||
@@ -1,215 +0,0 @@
|
|||||||
# InitialConditionsAdisTSSpec.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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
|
|
||||||
|
|
||||||
from Model.Tools.PamhyrDB import SQLSubModel
|
|
||||||
from Model.Except import NotImplementedMethodeError
|
|
||||||
from Model.Scenario import Scenario
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class ICTemperatureSpec(SQLSubModel):
|
|
||||||
_sub_classes = []
|
|
||||||
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(ICTemperatureSpec, self).__init__(
|
|
||||||
id=id, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._name_section = name
|
|
||||||
self._reach = None
|
|
||||||
self._start_rk = None
|
|
||||||
self._end_rk = None
|
|
||||||
self._temperature = None
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_create(cls, execute, ext=""):
|
|
||||||
execute(f"""
|
|
||||||
CREATE TABLE initial_conditions_temperature_spec{ext}(
|
|
||||||
{cls.create_db_add_pamhyr_id()},
|
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
ic_default INTEGER NOT NULL,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
reach INTEGER NOT NULL,
|
|
||||||
start_rk REAL NOT NULL,
|
|
||||||
end_rk REAL NOT NULL,
|
|
||||||
temperature REAL NOT NULL,
|
|
||||||
{Scenario.create_db_add_scenario()},
|
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
|
||||||
FOREIGN KEY(ic_default)
|
|
||||||
REFERENCES initial_conditions_temperature(pamhyr_id),
|
|
||||||
FOREIGN KEY(reach) REFERENCES river_reach(pamhyr_id)
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
|
|
||||||
return cls._create_submodel(execute)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_update(cls, execute, version, data=None):
|
|
||||||
major, minor, release = version.strip().split(".")
|
|
||||||
|
|
||||||
if major == "0":
|
|
||||||
if int(minor) < 2 or (int(minor) == 2 and int(release) <= 7):
|
|
||||||
table_name = "initial_conditions_temperature_spec"
|
|
||||||
if not cls.is_table_exists(execute, table_name):
|
|
||||||
cls._db_create(execute)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_load(cls, execute, data=None):
|
|
||||||
new = []
|
|
||||||
status = data['status']
|
|
||||||
reachs = data["edges"]
|
|
||||||
scenario = data["scenario"]
|
|
||||||
loaded = data['loaded_pid']
|
|
||||||
|
|
||||||
if scenario is None:
|
|
||||||
return new
|
|
||||||
|
|
||||||
table = execute(
|
|
||||||
"SELECT pamhyr_id, deleted, name, reach, start_rk, end_rk, " +
|
|
||||||
"temperature, scenario " +
|
|
||||||
"FROM initial_conditions_temperature_spec " +
|
|
||||||
f"WHERE ic_default = {data['ic_default_id']} " +
|
|
||||||
f"AND scenario = {scenario.id} " +
|
|
||||||
f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))}) "
|
|
||||||
)
|
|
||||||
|
|
||||||
if table is not None:
|
|
||||||
for row in table:
|
|
||||||
it = iter(row)
|
|
||||||
|
|
||||||
id = next(it)
|
|
||||||
deleted = (next(it) == 1)
|
|
||||||
name = next(it)
|
|
||||||
reach = next(it)
|
|
||||||
start_rk = next(it)
|
|
||||||
end_rk = next(it)
|
|
||||||
temperature = next(it)
|
|
||||||
owner_scenario = next(it)
|
|
||||||
|
|
||||||
new_spec = cls(
|
|
||||||
id=id, name=name,
|
|
||||||
status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
if deleted:
|
|
||||||
new_spec.set_as_deleted()
|
|
||||||
|
|
||||||
new_spec.reach = reach
|
|
||||||
new_spec.start_rk = start_rk
|
|
||||||
new_spec.end_rk = end_rk
|
|
||||||
new_spec.temperature = temperature
|
|
||||||
|
|
||||||
loaded.add(id)
|
|
||||||
new.append(new_spec)
|
|
||||||
|
|
||||||
data["scenario"] = scenario.parent
|
|
||||||
new += cls._db_load(execute, data)
|
|
||||||
data["scenario"] = scenario
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
|
||||||
if not self.must_be_saved():
|
|
||||||
return True
|
|
||||||
|
|
||||||
ic_default = data['ic_default_id']
|
|
||||||
|
|
||||||
sql = (
|
|
||||||
"INSERT INTO " +
|
|
||||||
"initial_conditions_temperature_spec(pamhyr_id, deleted, " +
|
|
||||||
"ic_default, name, reach, " +
|
|
||||||
"start_rk, end_rk, temperature, scenario) " +
|
|
||||||
"VALUES (" +
|
|
||||||
f"{self.id}, {self._db_format(self.is_deleted())}, " +
|
|
||||||
f"{ic_default}, " +
|
|
||||||
f"'{self._db_format(self._name_section)}', " +
|
|
||||||
f"{self._reach}, " +
|
|
||||||
f"{self._start_rk}, {self._end_rk}, " +
|
|
||||||
f"{self._temperature}, " +
|
|
||||||
f"{self._status.scenario_id}" +
|
|
||||||
")"
|
|
||||||
)
|
|
||||||
execute(sql)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
@property
|
|
||||||
def name(self):
|
|
||||||
return self._name_section
|
|
||||||
|
|
||||||
@name.setter
|
|
||||||
def name(self, name):
|
|
||||||
self._name_section = name
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def reach(self):
|
|
||||||
return self._reach
|
|
||||||
|
|
||||||
@reach.setter
|
|
||||||
def reach(self, reach):
|
|
||||||
self._reach = reach
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def start_rk(self):
|
|
||||||
return self._start_rk
|
|
||||||
|
|
||||||
@start_rk.setter
|
|
||||||
def start_rk(self, start_rk):
|
|
||||||
self._start_rk = start_rk
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def end_rk(self):
|
|
||||||
return self._end_rk
|
|
||||||
|
|
||||||
@end_rk.setter
|
|
||||||
def end_rk(self, end_rk):
|
|
||||||
self._end_rk = end_rk
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def temperature(self):
|
|
||||||
return self._temperature
|
|
||||||
|
|
||||||
@temperature.setter
|
|
||||||
def temperature(self, temperature):
|
|
||||||
self._temperature = temperature
|
|
||||||
self._status.modified()
|
|
||||||
|
|
||||||
def cloned_for(self, reach, start_rk, end_rk):
|
|
||||||
new = ICTemperatureSpec(
|
|
||||||
name=self._name_section,
|
|
||||||
status=self._status
|
|
||||||
)
|
|
||||||
new._reach = reach
|
|
||||||
new._start_rk = start_rk
|
|
||||||
new._end_rk = end_rk
|
|
||||||
new._temperature = self._temperature
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
@@ -196,13 +196,6 @@ class Data(SQLSubModel):
|
|||||||
def __setitem__(self, key, value):
|
def __setitem__(self, key, value):
|
||||||
self._data[key] = self._types[key](value)
|
self._data[key] = self._types[key](value)
|
||||||
|
|
||||||
def cloned(self):
|
|
||||||
return Data(
|
|
||||||
self[0], self[1],
|
|
||||||
types=self._types,
|
|
||||||
status=self._status
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class LateralContribution(SQLSubModel):
|
class LateralContribution(SQLSubModel):
|
||||||
_sub_classes = [Data]
|
_sub_classes = [Data]
|
||||||
@@ -518,15 +511,6 @@ class LateralContribution(SQLSubModel):
|
|||||||
def has_reach(self):
|
def has_reach(self):
|
||||||
return self._reach is not None
|
return self._reach is not None
|
||||||
|
|
||||||
def cloned_for(self, reach, begin_section, end_section):
|
|
||||||
new = type(self)(name=self._name, status=self._status)
|
|
||||||
new._reach = reach
|
|
||||||
new._begin_section = begin_section
|
|
||||||
new._end_section = end_section
|
|
||||||
new._data = [data.cloned() for data in self.data]
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def begin_rk(self):
|
def begin_rk(self):
|
||||||
if self._begin_section is None:
|
if self._begin_section is None:
|
||||||
|
|||||||
@@ -71,89 +71,6 @@ class LateralContributionList(PamhyrModelListWithTab):
|
|||||||
self._status.modified()
|
self._status.modified()
|
||||||
return n
|
return n
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
profiles = reach.reach.profiles
|
|
||||||
split_index = profiles.index(profile)
|
|
||||||
|
|
||||||
parts = [
|
|
||||||
(
|
|
||||||
reach1,
|
|
||||||
0,
|
|
||||||
split_index,
|
|
||||||
dict(zip(
|
|
||||||
profiles[:split_index + 1],
|
|
||||||
reach1.reach.profiles
|
|
||||||
))
|
|
||||||
),
|
|
||||||
(
|
|
||||||
reach2,
|
|
||||||
split_index,
|
|
||||||
len(profiles) - 1,
|
|
||||||
dict(zip(
|
|
||||||
profiles[split_index:],
|
|
||||||
reach2.reach.profiles
|
|
||||||
))
|
|
||||||
),
|
|
||||||
]
|
|
||||||
|
|
||||||
for tab in self._tabs:
|
|
||||||
contributions = [
|
|
||||||
contribution
|
|
||||||
for contribution in self.get_tab(tab)
|
|
||||||
if contribution.reach is reach
|
|
||||||
]
|
|
||||||
|
|
||||||
for contribution in contributions:
|
|
||||||
if (contribution.begin_section not in profiles or
|
|
||||||
contribution.end_section not in profiles):
|
|
||||||
continue
|
|
||||||
|
|
||||||
begin = profiles.index(contribution.begin_section)
|
|
||||||
end = profiles.index(contribution.end_section)
|
|
||||||
lower, upper = sorted((begin, end))
|
|
||||||
reverse = begin > end
|
|
||||||
clones = []
|
|
||||||
|
|
||||||
for new_reach, part_lower, part_upper, sections in parts:
|
|
||||||
clipped_lower = max(lower, part_lower)
|
|
||||||
clipped_upper = min(upper, part_upper)
|
|
||||||
if clipped_lower >= clipped_upper:
|
|
||||||
continue
|
|
||||||
|
|
||||||
begin_index = (
|
|
||||||
clipped_upper if reverse else clipped_lower
|
|
||||||
)
|
|
||||||
end_index = (
|
|
||||||
clipped_lower if reverse else clipped_upper
|
|
||||||
)
|
|
||||||
clones.append(contribution.cloned_for(
|
|
||||||
new_reach,
|
|
||||||
sections[profiles[begin_index]],
|
|
||||||
sections[profiles[end_index]]
|
|
||||||
))
|
|
||||||
|
|
||||||
if len(clones) == 0:
|
|
||||||
continue
|
|
||||||
|
|
||||||
self._tabs[tab].extend(clones)
|
|
||||||
|
|
||||||
self._status.modified()
|
|
||||||
|
|
||||||
def get_tab_for_enabled_reaches(self, tab):
|
|
||||||
return [
|
|
||||||
contribution
|
|
||||||
for contribution in self.get_tab(tab)
|
|
||||||
if (contribution.reach is None or
|
|
||||||
(not contribution.reach.is_deleted() and
|
|
||||||
contribution.reach.is_enable()))
|
|
||||||
]
|
|
||||||
|
|
||||||
def get_for_enabled_reaches(self, tab, index):
|
|
||||||
contributions = self.get_tab_for_enabled_reaches(tab)
|
|
||||||
if not 0 <= index < len(contributions):
|
|
||||||
return None
|
|
||||||
return contributions[index]
|
|
||||||
|
|
||||||
def __copy__(self):
|
def __copy__(self):
|
||||||
new = LateralContributionList()
|
new = LateralContributionList()
|
||||||
|
|
||||||
|
|||||||
@@ -192,13 +192,6 @@ class Data(SQLSubModel):
|
|||||||
def __setitem__(self, key, value):
|
def __setitem__(self, key, value):
|
||||||
self._data[key] = self._types[key](value)
|
self._data[key] = self._types[key](value)
|
||||||
|
|
||||||
def cloned(self):
|
|
||||||
return Data(
|
|
||||||
self[0], self[1],
|
|
||||||
types=self._types,
|
|
||||||
status=self._status
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class LateralContributionAdisTS(SQLSubModel):
|
class LateralContributionAdisTS(SQLSubModel):
|
||||||
_sub_classes = [Data]
|
_sub_classes = [Data]
|
||||||
@@ -484,18 +477,6 @@ class LateralContributionAdisTS(SQLSubModel):
|
|||||||
self._end_rk = end_rk
|
self._end_rk = end_rk
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|
||||||
def cloned_for(self, reach, begin_rk, end_rk):
|
|
||||||
new = LateralContributionAdisTS(
|
|
||||||
pollutant=self._pollutant,
|
|
||||||
status=self._status
|
|
||||||
)
|
|
||||||
new._reach = reach
|
|
||||||
new._begin_rk = begin_rk
|
|
||||||
new._end_rk = end_rk
|
|
||||||
new._data = [data.cloned() for data in self.data]
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def _default_0(self):
|
def _default_0(self):
|
||||||
return self._types[0](0)
|
return self._types[0](0)
|
||||||
|
|||||||
@@ -68,46 +68,6 @@ class LateralContributionsAdisTSList(PamhyrModelList):
|
|||||||
self._status.modified()
|
self._status.modified()
|
||||||
return n
|
return n
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
parts = []
|
|
||||||
for new_reach in (reach1, reach2):
|
|
||||||
rks = new_reach.reach.get_rk()
|
|
||||||
if len(rks) == 0:
|
|
||||||
continue
|
|
||||||
parts.append((new_reach.id, min(rks), max(rks)))
|
|
||||||
|
|
||||||
contributions = [
|
|
||||||
contribution
|
|
||||||
for contribution in self.lst
|
|
||||||
if contribution.reach == reach.id
|
|
||||||
]
|
|
||||||
clones = []
|
|
||||||
|
|
||||||
for contribution in contributions:
|
|
||||||
begin = contribution.begin_rk
|
|
||||||
end = contribution.end_rk
|
|
||||||
if begin is None or end is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
lower, upper = sorted((begin, end))
|
|
||||||
reverse = begin > end
|
|
||||||
|
|
||||||
for new_reach, part_lower, part_upper in parts:
|
|
||||||
clipped_lower = max(lower, part_lower)
|
|
||||||
clipped_upper = min(upper, part_upper)
|
|
||||||
if clipped_lower >= clipped_upper:
|
|
||||||
continue
|
|
||||||
|
|
||||||
begin_rk = clipped_upper if reverse else clipped_lower
|
|
||||||
end_rk = clipped_lower if reverse else clipped_upper
|
|
||||||
clones.append(contribution.cloned_for(
|
|
||||||
new_reach, begin_rk, end_rk
|
|
||||||
))
|
|
||||||
|
|
||||||
if len(clones) != 0:
|
|
||||||
self._lst.extend(clones)
|
|
||||||
self._status.modified()
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def Lat_Cont_List(self):
|
def Lat_Cont_List(self):
|
||||||
return self.lst
|
return self.lst
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
# OutputRKAdists.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,
|
||||||
|
old_pamhyr_date_to_timestamp,
|
||||||
|
date_iso_to_timestamp,
|
||||||
|
date_dmy_to_timestamp,
|
||||||
|
)
|
||||||
|
|
||||||
|
from Model.Tools.PamhyrDB import SQLSubModel
|
||||||
|
from Model.Except import NotImplementedMethodeError
|
||||||
|
from Model.Scenario import Scenario
|
||||||
|
|
||||||
|
logger = logging.getLogger()
|
||||||
|
|
||||||
|
|
||||||
|
class OutputRKAdists(SQLSubModel):
|
||||||
|
_sub_classes = []
|
||||||
|
|
||||||
|
def __init__(self, id: int = -1, reach=None,
|
||||||
|
rk=None, title: str = "", status=None,
|
||||||
|
owner_scenario=-1):
|
||||||
|
super(OutputRKAdists, self).__init__(
|
||||||
|
id=id, status=status,
|
||||||
|
owner_scenario=owner_scenario
|
||||||
|
)
|
||||||
|
|
||||||
|
self._reach = reach
|
||||||
|
self._rk = rk
|
||||||
|
self._title = str(title)
|
||||||
|
self._enabled = True
|
||||||
|
|
||||||
|
@property
|
||||||
|
def reach(self):
|
||||||
|
return self._reach
|
||||||
|
|
||||||
|
@reach.setter
|
||||||
|
def reach(self, reach_id):
|
||||||
|
self._reach = reach_id
|
||||||
|
self._status.modified()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def rk(self):
|
||||||
|
return self._rk
|
||||||
|
|
||||||
|
@rk.setter
|
||||||
|
def rk(self, profile_id):
|
||||||
|
self._rk = profile_id
|
||||||
|
self._status.modified()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def title(self):
|
||||||
|
return self._title
|
||||||
|
|
||||||
|
@title.setter
|
||||||
|
def title(self, title):
|
||||||
|
self._title = title
|
||||||
|
self._status.modified()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _db_create(cls, execute, ext=""):
|
||||||
|
execute(f"""
|
||||||
|
CREATE TABLE output_rk_adists{ext}(
|
||||||
|
{cls.create_db_add_pamhyr_id()},
|
||||||
|
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
reach INTEGER NOT NULL,
|
||||||
|
rk REAL NOT NULL,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
{Scenario.create_db_add_scenario()},
|
||||||
|
{Scenario.create_db_add_scenario_fk()},
|
||||||
|
FOREIGN KEY(reach) REFERENCES river_reach(id)
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
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:
|
||||||
|
if cls.is_table_exists(execute, "OutputRKAdists"):
|
||||||
|
cls._db_update_to_0_2_0(execute, data)
|
||||||
|
else:
|
||||||
|
cls._db_create(execute)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _db_update_to_0_2_0(cls, execute, data):
|
||||||
|
table = "OutputRKAdists"
|
||||||
|
table_new = "output_rk_adists"
|
||||||
|
reachs = data['id2pid']['river_reach']
|
||||||
|
|
||||||
|
cls.update_db_add_pamhyr_id(execute, table, data)
|
||||||
|
Scenario.update_db_add_scenario(execute, table)
|
||||||
|
|
||||||
|
cls._db_create(execute, ext="_tmp")
|
||||||
|
|
||||||
|
execute(
|
||||||
|
f"INSERT INTO {table_new}_tmp " +
|
||||||
|
"(pamhyr_id, reach, rk, title, scenario) " +
|
||||||
|
"SELECT pamhyr_id, reach, rk, title, scenario " +
|
||||||
|
f"FROM {table}"
|
||||||
|
)
|
||||||
|
|
||||||
|
execute(f"DROP TABLE {table}")
|
||||||
|
execute(f"ALTER TABLE {table_new}_tmp RENAME TO {table_new}")
|
||||||
|
|
||||||
|
cls._db_update_to_0_2_0_set_reach_pid(execute, table_new, reachs)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _db_load(cls, execute, data=None):
|
||||||
|
new = []
|
||||||
|
status = data['status']
|
||||||
|
scenario = data["scenario"]
|
||||||
|
loaded = data['loaded_pid']
|
||||||
|
|
||||||
|
# reach = data["reach"]
|
||||||
|
# profile = data["profile"]
|
||||||
|
|
||||||
|
if scenario is None:
|
||||||
|
return new
|
||||||
|
|
||||||
|
table = execute(
|
||||||
|
"SELECT pamhyr_id, deleted, reach, rk, title, scenario " +
|
||||||
|
f"FROM output_rk_adists"
|
||||||
|
)
|
||||||
|
|
||||||
|
if table is not None:
|
||||||
|
for row in table:
|
||||||
|
it = iter(row)
|
||||||
|
|
||||||
|
pid = next(it)
|
||||||
|
deleted = (next(it) == 1)
|
||||||
|
id_reach = next(it)
|
||||||
|
id_rk = next(it)
|
||||||
|
title = next(it)
|
||||||
|
owner_scenario = next(it)
|
||||||
|
|
||||||
|
new_output = cls(
|
||||||
|
id=pid, reach=id_reach,
|
||||||
|
rk=id_rk, title=title,
|
||||||
|
status=status,
|
||||||
|
owner_scenario=owner_scenario,
|
||||||
|
)
|
||||||
|
if deleted:
|
||||||
|
new_output.set_as_deleted()
|
||||||
|
|
||||||
|
loaded.add(pid)
|
||||||
|
new.append(new_output)
|
||||||
|
|
||||||
|
data["scenario"] = scenario.parent
|
||||||
|
new += cls._db_load(execute, data)
|
||||||
|
data["scenario"] = scenario
|
||||||
|
|
||||||
|
return new
|
||||||
|
|
||||||
|
def _db_save(self, execute, data=None):
|
||||||
|
if not self.must_be_saved():
|
||||||
|
return True
|
||||||
|
|
||||||
|
execute(
|
||||||
|
"DELETE FROM output_rk_adists " +
|
||||||
|
f"WHERE pamhyr_id = {self.id} " +
|
||||||
|
f"AND scenario = {self._status.scenario_id} "
|
||||||
|
)
|
||||||
|
|
||||||
|
execute(
|
||||||
|
"INSERT INTO " +
|
||||||
|
"output_rk_adists(pamhyr_id, deleted, " +
|
||||||
|
"reach, rk, title, scenario) " +
|
||||||
|
"VALUES (" +
|
||||||
|
f"{self.id}, {self._db_format(self.is_deleted())}, " +
|
||||||
|
f"{self._reach}, {self._rk}, " +
|
||||||
|
f"'{self._db_format(self._title)}', " +
|
||||||
|
f"{self._status.scenario_id}" +
|
||||||
|
")"
|
||||||
|
)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
@property
|
||||||
|
def enabled(self):
|
||||||
|
return self._enabled
|
||||||
|
|
||||||
|
@enabled.setter
|
||||||
|
def enabled(self, enabled):
|
||||||
|
self._enabled = enabled
|
||||||
|
self._status.modified()
|
||||||
+20
-32
@@ -1,5 +1,5 @@
|
|||||||
# BoundaryConditionsTemperatureList.py -- Pamhyr
|
# OutputRKListAdists.py -- Pamhyr
|
||||||
# Copyright (C) 2023-2025 INRAE
|
# Copyright (C) 2024-2025 INRAE
|
||||||
#
|
#
|
||||||
# This program is free software: you can redistribute it and/or modify
|
# 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
|
# it under the terms of the GNU General Public License as published by
|
||||||
@@ -16,56 +16,44 @@
|
|||||||
|
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
from copy import copy
|
|
||||||
from tools import trace, timer
|
from tools import trace, timer
|
||||||
|
|
||||||
from Model.Tools.PamhyrListExt import PamhyrModelList
|
|
||||||
from Model.Except import NotImplementedMethodeError
|
from Model.Except import NotImplementedMethodeError
|
||||||
|
from Model.Tools.PamhyrListExt import PamhyrModelList
|
||||||
from Model.BoundaryConditionsTemperature.BoundaryConditionTemperature \
|
from Model.OutputRKAdists.OutputRKAdists import OutputRKAdists
|
||||||
import BoundaryConditionTemperature
|
|
||||||
|
|
||||||
|
|
||||||
class BoundaryConditionsTemperatureList(PamhyrModelList):
|
class OutputRKAdistsList(PamhyrModelList):
|
||||||
_sub_classes = [
|
_sub_classes = [OutputRKAdists]
|
||||||
BoundaryConditionTemperature,
|
|
||||||
]
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _db_load(cls, execute, data=None):
|
def _db_load(cls, execute, data=None):
|
||||||
new = cls(status=data['status'])
|
new = cls(status=data["status"])
|
||||||
|
|
||||||
if data is None:
|
new._lst = OutputRKAdists._db_load(execute, data)
|
||||||
data = {}
|
|
||||||
|
|
||||||
new._lst = BoundaryConditionTemperature._db_load(execute, data)
|
|
||||||
|
|
||||||
return new
|
return new
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
def _db_save(self, execute, data=None):
|
||||||
|
ok = True
|
||||||
|
|
||||||
|
# Delete previous data
|
||||||
execute(
|
execute(
|
||||||
"DELETE FROM boundary_condition_temperature " +
|
"DELETE FROM output_rk_adists " +
|
||||||
f"WHERE scenario = {self._status.scenario_id}"
|
|
||||||
)
|
|
||||||
execute(
|
|
||||||
"DELETE FROM boundary_condition_data_temperature " +
|
|
||||||
f"WHERE scenario = {self._status.scenario_id}"
|
f"WHERE scenario = {self._status.scenario_id}"
|
||||||
)
|
)
|
||||||
|
|
||||||
if data is None:
|
for sl in self._lst:
|
||||||
data = {}
|
ok &= sl._db_save(execute, data)
|
||||||
|
|
||||||
for bca in self._lst:
|
return ok
|
||||||
bca._db_save(execute, data=data)
|
|
||||||
|
|
||||||
return True
|
@property
|
||||||
|
def OutputRK_List(self):
|
||||||
|
return self.lst
|
||||||
|
|
||||||
def new(self, index):
|
def new(self, lst, index):
|
||||||
n = BoundaryConditionTemperature(status=self._status)
|
n = OutputRKAdists(status=self._status)
|
||||||
self._lst.insert(index, n)
|
self._lst.insert(index, n)
|
||||||
self._status.modified()
|
self._status.modified()
|
||||||
return n
|
return n
|
||||||
|
|
||||||
@property
|
|
||||||
def BCs_Temperature_List(self):
|
|
||||||
return self.lst
|
|
||||||
@@ -202,8 +202,13 @@ class TableData(SQLSubModel):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _db_update(cls, execute, version, data=None):
|
def _db_update(cls, execute, version, data=None):
|
||||||
if not cls.is_table_exists(execute, "results_table_data"):
|
major, minor, release = version.strip().split(".")
|
||||||
|
create = False
|
||||||
|
|
||||||
|
if major == "0" and int(minor) == 2:
|
||||||
|
if int(release) < 7 and not create:
|
||||||
cls._db_create(execute)
|
cls._db_create(execute)
|
||||||
|
create = True
|
||||||
|
|
||||||
return cls._update_submodel(execute, version, data)
|
return cls._update_submodel(execute, version, data)
|
||||||
|
|
||||||
@@ -272,9 +277,9 @@ class TableData(SQLSubModel):
|
|||||||
|
|
||||||
if len(shape) == 2:
|
if len(shape) == 2:
|
||||||
shape_x, shape_y = shape
|
shape_x, shape_y = shape
|
||||||
elif len(shape == 1):
|
elif len(shape) == 1:
|
||||||
shape_x, = shape
|
shape_x, = shape
|
||||||
elif len(shape == 3):
|
elif len(shape) == 3:
|
||||||
shape_x, shape_y, shape_z = shape
|
shape_x, shape_y, shape_z = shape
|
||||||
else:
|
else:
|
||||||
logger.error(
|
logger.error(
|
||||||
@@ -326,14 +331,14 @@ class TableData(SQLSubModel):
|
|||||||
if isinstance(key, tuple):
|
if isinstance(key, tuple):
|
||||||
return self._data[key[0], key[1]]
|
return self._data[key[0], key[1]]
|
||||||
|
|
||||||
self._date[key]
|
self._data[key]
|
||||||
|
|
||||||
|
|
||||||
class Results(SQLSubModel):
|
class Results(SQLSubModel):
|
||||||
_sub_classes = [River, TableData, AdditionalData]
|
_sub_classes = [River, TableData, AdditionalData]
|
||||||
|
|
||||||
def __init__(self, id=-1, study=None, solver=None,
|
def __init__(self, id=-1, study=None, solver=None,
|
||||||
repertory="", name="0"):
|
repertory="", name="0", is_ensemble=False):
|
||||||
super(Results, self).__init__(
|
super(Results, self).__init__(
|
||||||
id=id, status=study.status,
|
id=id, status=study.status,
|
||||||
owner_scenario=study.status.scenario.id
|
owner_scenario=study.status.scenario.id
|
||||||
@@ -346,6 +351,8 @@ class Results(SQLSubModel):
|
|||||||
self._solver = solver
|
self._solver = solver
|
||||||
self._repertory = repertory
|
self._repertory = repertory
|
||||||
|
|
||||||
|
self._is_ensemble = is_ensemble
|
||||||
|
|
||||||
self._meta_data = {
|
self._meta_data = {
|
||||||
# Keep results creation date
|
# Keep results creation date
|
||||||
"creation_date": datetime.now(),
|
"creation_date": datetime.now(),
|
||||||
@@ -359,6 +366,9 @@ class Results(SQLSubModel):
|
|||||||
if solver is not None:
|
if solver is not None:
|
||||||
self.set("solver_type", solver._type)
|
self.set("solver_type", solver._type)
|
||||||
|
|
||||||
|
def is_ensemble(self):
|
||||||
|
return self._is_ensemble
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def date(self):
|
def date(self):
|
||||||
date = self._meta_data["creation_date"]
|
date = self._meta_data["creation_date"]
|
||||||
@@ -426,9 +436,11 @@ class Results(SQLSubModel):
|
|||||||
solver_name TEXT NOT NULL,
|
solver_name TEXT NOT NULL,
|
||||||
solver_type TEXT NOT NULL,
|
solver_type TEXT NOT NULL,
|
||||||
study_revision INTEGER NOT NULL,
|
study_revision INTEGER NOT NULL,
|
||||||
creation_data DATE NOT NULL,
|
creation_date DATE NOT NULL,
|
||||||
nb_timestamps INTEGER NOT NULL,
|
nb_timestamps INTEGER NOT NULL,
|
||||||
timestamps BLOB NOT NULL,
|
timestamps BLOB NOT NULL,
|
||||||
|
seed INTEGER,
|
||||||
|
number_of_run INTEGER,
|
||||||
{Scenario.create_db_add_scenario()},
|
{Scenario.create_db_add_scenario()},
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
{Scenario.create_db_add_scenario_fk()},
|
||||||
PRIMARY KEY(pamhyr_id, scenario)
|
PRIMARY KEY(pamhyr_id, scenario)
|
||||||
@@ -454,6 +466,21 @@ class Results(SQLSubModel):
|
|||||||
cls._db_create(execute)
|
cls._db_create(execute)
|
||||||
create = True
|
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)
|
return cls._update_submodel(execute, version, data)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -466,7 +493,9 @@ class Results(SQLSubModel):
|
|||||||
|
|
||||||
table = execute(
|
table = execute(
|
||||||
"SELECT pamhyr_id, solver_name, solver_type, " +
|
"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 " +
|
"scenario " +
|
||||||
"FROM results " +
|
"FROM results " +
|
||||||
f"WHERE scenario = {scenario.id}"
|
f"WHERE scenario = {scenario.id}"
|
||||||
@@ -486,6 +515,8 @@ class Results(SQLSubModel):
|
|||||||
solver_type = next(it)
|
solver_type = next(it)
|
||||||
revision = next(it)
|
revision = next(it)
|
||||||
creation_date = next(it)
|
creation_date = next(it)
|
||||||
|
seed = next(it)
|
||||||
|
number_of_run = next(it)
|
||||||
nb_timestamps = next(it)
|
nb_timestamps = next(it)
|
||||||
timestamps_bytes = next(it)
|
timestamps_bytes = next(it)
|
||||||
owner_scenario = next(it)
|
owner_scenario = next(it)
|
||||||
@@ -496,6 +527,9 @@ class Results(SQLSubModel):
|
|||||||
new_results.set("solver_type", solver_type)
|
new_results.set("solver_type", solver_type)
|
||||||
new_results.set("study_revision", revision)
|
new_results.set("study_revision", revision)
|
||||||
new_results.set("creation_date", creation_date)
|
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_pid"] = pid
|
||||||
data["result"] = new_results
|
data["result"] = new_results
|
||||||
@@ -522,7 +556,7 @@ class Results(SQLSubModel):
|
|||||||
i = 0
|
i = 0
|
||||||
for reach in new_results._river.reachs:
|
for reach in new_results._river.reachs:
|
||||||
nb = len(reach.profiles)
|
nb = len(reach.profiles)
|
||||||
reach.set_global_index(range(i, i + nb))
|
reach.set_global_index(range(i, i + nb + 1))
|
||||||
i += nb
|
i += nb
|
||||||
|
|
||||||
if "Z" in table_data:
|
if "Z" in table_data:
|
||||||
@@ -588,15 +622,25 @@ class Results(SQLSubModel):
|
|||||||
ts = sorted(self.get("timestamps"))
|
ts = sorted(self.get("timestamps"))
|
||||||
sf = ">" + ''.join(itertools.repeat("d", len(ts)))
|
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(
|
execute(
|
||||||
"INSERT INTO " +
|
"INSERT INTO " +
|
||||||
"results (pamhyr_id, solver_name, solver_type, " +
|
"results (pamhyr_id, solver_name, solver_type, " +
|
||||||
"study_revision, creation_data, " +
|
"study_revision, creation_date, " +
|
||||||
|
"seed, number_of_run, " +
|
||||||
"nb_timestamps, timestamps, " +
|
"nb_timestamps, timestamps, " +
|
||||||
"scenario) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
"scenario) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
self._pamhyr_id, solver_name, solver_type,
|
self._pamhyr_id, solver_name, solver_type,
|
||||||
self._status.version, self.get("creation_date"),
|
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
|
data["result"] = self._pamhyr_id
|
||||||
|
|||||||
@@ -154,7 +154,6 @@ class Profile(SQLSubModel):
|
|||||||
"len_data, data, scenario " +
|
"len_data, data, scenario " +
|
||||||
"FROM results_data " +
|
"FROM results_data " +
|
||||||
f"WHERE scenario = {scenario.id} " +
|
f"WHERE scenario = {scenario.id} " +
|
||||||
f"AND result = {data['result_pid']} " +
|
|
||||||
f"AND reach = {reach.pamhyr_id} " +
|
f"AND reach = {reach.pamhyr_id} " +
|
||||||
f"AND section = {profile.pamhyr_id}"
|
f"AND section = {profile.pamhyr_id}"
|
||||||
)
|
)
|
||||||
@@ -277,7 +276,7 @@ class Profile(SQLSubModel):
|
|||||||
class Reach(SQLSubModel):
|
class Reach(SQLSubModel):
|
||||||
_sub_classes = [Profile]
|
_sub_classes = [Profile]
|
||||||
|
|
||||||
def __init__(self, reach, study, parent, with_init=True, profiles=None):
|
def __init__(self, reach, study, parent, with_init=True):
|
||||||
super(Reach, self).__init__(
|
super(Reach, self).__init__(
|
||||||
id=-1, status=study.status,
|
id=-1, status=study.status,
|
||||||
owner_scenario=study.status.scenario.id
|
owner_scenario=study.status.scenario.id
|
||||||
@@ -288,12 +287,10 @@ class Reach(SQLSubModel):
|
|||||||
self._reach = reach # Source reach in the study
|
self._reach = reach # Source reach in the study
|
||||||
self._profiles = []
|
self._profiles = []
|
||||||
if with_init:
|
if with_init:
|
||||||
if profiles is None:
|
|
||||||
profiles = reach.profiles
|
|
||||||
self._profiles = list(
|
self._profiles = list(
|
||||||
map(
|
map(
|
||||||
lambda p: Profile(p, self._study, self._parent),
|
lambda p: Profile(p, self._study, self._parent),
|
||||||
profiles
|
reach.profiles
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -382,14 +379,7 @@ class Reach(SQLSubModel):
|
|||||||
|
|
||||||
for i, profile in enumerate(reach.profiles):
|
for i, profile in enumerate(reach.profiles):
|
||||||
data["profile"] = profile
|
data["profile"] = profile
|
||||||
result_profile = Profile._db_load(execute, data)
|
new_reach._profiles += [Profile._db_load(execute, data)]
|
||||||
if len(result_profile) > 0:
|
|
||||||
new_reach._profiles.append(result_profile)
|
|
||||||
|
|
||||||
new_reach._profile_mask = [
|
|
||||||
profile.name[0:8] != 'interpol'
|
|
||||||
for profile in new_reach._profiles
|
|
||||||
]
|
|
||||||
|
|
||||||
return new_reach
|
return new_reach
|
||||||
|
|
||||||
@@ -403,7 +393,7 @@ class Reach(SQLSubModel):
|
|||||||
class River(SQLSubModel):
|
class River(SQLSubModel):
|
||||||
_sub_classes = [Reach]
|
_sub_classes = [Reach]
|
||||||
|
|
||||||
def __init__(self, study, parent):
|
def __init__(self, study, parent, init=True):
|
||||||
super(River, self).__init__(
|
super(River, self).__init__(
|
||||||
id=-1, status=study.status,
|
id=-1, status=study.status,
|
||||||
owner_scenario=study.status.scenario.id
|
owner_scenario=study.status.scenario.id
|
||||||
@@ -414,6 +404,9 @@ class River(SQLSubModel):
|
|||||||
|
|
||||||
# Dict with timestamps as key
|
# Dict with timestamps as key
|
||||||
self._reachs = []
|
self._reachs = []
|
||||||
|
if init:
|
||||||
|
for i, _ in enumerate(self._study.river.enable_edges()):
|
||||||
|
self.add(i)
|
||||||
|
|
||||||
def __len__(self):
|
def __len__(self):
|
||||||
return len(self._reachs)
|
return len(self._reachs)
|
||||||
@@ -428,13 +421,10 @@ class River(SQLSubModel):
|
|||||||
def has_reach(self, id):
|
def has_reach(self, id):
|
||||||
return 0 <= id < len(self._reachs)
|
return 0 <= id < len(self._reachs)
|
||||||
|
|
||||||
def add(self, reach_id, profiles=None):
|
def add(self, reach_id):
|
||||||
reachs = self._study.river.enable_edges()
|
reachs = self._study.river.enable_edges()
|
||||||
|
|
||||||
new = Reach(
|
new = Reach(reachs[reach_id].reach, self._study, self._parent)
|
||||||
reachs[reach_id].reach, self._study, self._parent,
|
|
||||||
profiles=profiles
|
|
||||||
)
|
|
||||||
|
|
||||||
self._reachs.append(new)
|
self._reachs.append(new)
|
||||||
return new
|
return new
|
||||||
@@ -469,13 +459,13 @@ class River(SQLSubModel):
|
|||||||
study = data["study"]
|
study = data["study"]
|
||||||
parent = data["parent"]
|
parent = data["parent"]
|
||||||
|
|
||||||
new_river = cls(study, parent)
|
new_river = cls(study, parent, init=False)
|
||||||
|
|
||||||
for reach in study.river.reachs():
|
for reach in study.river.reachs():
|
||||||
data["reach"] = reach.reach
|
data["reach"] = reach.reach
|
||||||
result_reach = Reach._db_load(execute, data)
|
new_river._reachs.append(
|
||||||
if len(result_reach) > 0:
|
Reach._db_load(execute, data)
|
||||||
new_river._reachs.append(result_reach)
|
)
|
||||||
|
|
||||||
return new_river
|
return new_river
|
||||||
|
|
||||||
|
|||||||
@@ -64,15 +64,13 @@ class Profile(object):
|
|||||||
|
|
||||||
|
|
||||||
class Reach(object):
|
class Reach(object):
|
||||||
def __init__(self, reach, study, profiles=None):
|
def __init__(self, reach, study):
|
||||||
self._study = study
|
self._study = study
|
||||||
self._reach = reach # Source reach in the study
|
self._reach = reach # Source reach in the study
|
||||||
if profiles is None:
|
|
||||||
profiles = reach.profiles
|
|
||||||
self._profiles = list(
|
self._profiles = list(
|
||||||
map(
|
map(
|
||||||
lambda p: Profile(p, self._study),
|
lambda p: Profile(p, self._study),
|
||||||
profiles
|
reach.profiles
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -91,10 +89,6 @@ class Reach(object):
|
|||||||
def profiles(self):
|
def profiles(self):
|
||||||
return self._profiles.copy()
|
return self._profiles.copy()
|
||||||
|
|
||||||
def get_rk(self):
|
|
||||||
"""Return the PK values for profiles present in the results."""
|
|
||||||
return [profile.rk for profile in self._profiles]
|
|
||||||
|
|
||||||
def profile(self, id):
|
def profile(self, id):
|
||||||
return self._profiles[id]
|
return self._profiles[id]
|
||||||
|
|
||||||
@@ -125,10 +119,10 @@ class River(object):
|
|||||||
def has_reach(self, id):
|
def has_reach(self, id):
|
||||||
return 0 <= id < len(self._reachs)
|
return 0 <= id < len(self._reachs)
|
||||||
|
|
||||||
def add(self, reach_id, profiles=None):
|
def add(self, reach_id):
|
||||||
reachs = self._study.river.enable_edges()
|
reachs = self._study.river.enable_edges()
|
||||||
|
|
||||||
new = Reach(reachs[reach_id].reach, self._study, profiles=profiles)
|
new = Reach(reachs[reach_id].reach, self._study)
|
||||||
|
|
||||||
self._reachs.append(new)
|
self._reachs.append(new)
|
||||||
return new
|
return new
|
||||||
|
|||||||
+23
-131
@@ -49,6 +49,7 @@ from Model.REPLine.REPLineList import REPLineList
|
|||||||
|
|
||||||
from Solver.Solvers import solver_type_list
|
from Solver.Solvers import solver_type_list
|
||||||
|
|
||||||
|
from Model.OutputRKAdists.OutputRKListAdists import OutputRKAdistsList
|
||||||
from Model.Pollutants.PollutantsList import PollutantsList
|
from Model.Pollutants.PollutantsList import PollutantsList
|
||||||
from Model.InitialConditionsAdisTS.InitialConditionsAdisTSList \
|
from Model.InitialConditionsAdisTS.InitialConditionsAdisTSList \
|
||||||
import InitialConditionsAdisTSList
|
import InitialConditionsAdisTSList
|
||||||
@@ -58,17 +59,8 @@ from Model.LateralContributionsAdisTS.LateralContributionsAdisTSList \
|
|||||||
import LateralContributionsAdisTSList
|
import LateralContributionsAdisTSList
|
||||||
from Model.D90AdisTS.D90AdisTSList import D90AdisTSList
|
from Model.D90AdisTS.D90AdisTSList import D90AdisTSList
|
||||||
from Model.DIFAdisTS.DIFAdisTSList import DIFAdisTSList
|
from Model.DIFAdisTS.DIFAdisTSList import DIFAdisTSList
|
||||||
|
|
||||||
from Model.InitialConditionsTemperature.InitialConditionsTemperatureList \
|
|
||||||
import InitialConditionsTemperatureList
|
|
||||||
|
|
||||||
from Model.BoundaryConditionsTemperature.BoundaryConditionsTemperatureList \
|
|
||||||
import BoundaryConditionsTemperatureList
|
|
||||||
|
|
||||||
from Model.WeatherParameters.WeatherParametersList \
|
|
||||||
import WeatherParametersList
|
|
||||||
|
|
||||||
from Model.GeoTIFF.GeoTIFFList import GeoTIFFList
|
from Model.GeoTIFF.GeoTIFFList import GeoTIFFList
|
||||||
|
from Model.Ensembles.EnsembleList import EnsembleList
|
||||||
from Model.Results.Results import Results
|
from Model.Results.Results import Results
|
||||||
|
|
||||||
logger = logging.getLogger()
|
logger = logging.getLogger()
|
||||||
@@ -477,16 +469,15 @@ class River(Graph):
|
|||||||
HydraulicStructureList,
|
HydraulicStructureList,
|
||||||
AddFileList,
|
AddFileList,
|
||||||
REPLineList,
|
REPLineList,
|
||||||
|
OutputRKAdistsList,
|
||||||
PollutantsList,
|
PollutantsList,
|
||||||
InitialConditionsAdisTSList,
|
InitialConditionsAdisTSList,
|
||||||
BoundaryConditionsAdisTSList,
|
BoundaryConditionsAdisTSList,
|
||||||
LateralContributionsAdisTSList,
|
LateralContributionsAdisTSList,
|
||||||
D90AdisTSList,
|
D90AdisTSList,
|
||||||
DIFAdisTSList,
|
DIFAdisTSList,
|
||||||
InitialConditionsTemperatureList,
|
|
||||||
BoundaryConditionsTemperatureList,
|
|
||||||
WeatherParametersList,
|
|
||||||
GeoTIFFList,
|
GeoTIFFList,
|
||||||
|
EnsembleList,
|
||||||
Results
|
Results
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -513,6 +504,7 @@ class River(Graph):
|
|||||||
)
|
)
|
||||||
self._additional_files = AddFileList(status=self._status)
|
self._additional_files = AddFileList(status=self._status)
|
||||||
self._rep_lines = REPLineList(status=self._status)
|
self._rep_lines = REPLineList(status=self._status)
|
||||||
|
self._Output_rk_adists = OutputRKAdistsList(status=self._status)
|
||||||
self._Pollutants = PollutantsList(status=self._status)
|
self._Pollutants = PollutantsList(status=self._status)
|
||||||
self._InitialConditionsAdisTS = InitialConditionsAdisTSList(
|
self._InitialConditionsAdisTS = InitialConditionsAdisTSList(
|
||||||
status=self._status)
|
status=self._status)
|
||||||
@@ -522,16 +514,12 @@ class River(Graph):
|
|||||||
status=self._status)
|
status=self._status)
|
||||||
self._D90AdisTS = D90AdisTSList(status=self._status)
|
self._D90AdisTS = D90AdisTSList(status=self._status)
|
||||||
self._DIFAdisTS = DIFAdisTSList(status=self._status)
|
self._DIFAdisTS = DIFAdisTSList(status=self._status)
|
||||||
self._InitialConditionsTemperature = (
|
|
||||||
InitialConditionsTemperatureList(status=self._status)
|
|
||||||
)
|
|
||||||
self._BoundaryConditionsTemperature = (
|
|
||||||
BoundaryConditionsTemperatureList(status=self._status)
|
|
||||||
)
|
|
||||||
self._WeatherParameters = (WeatherParametersList(status=self._status))
|
|
||||||
|
|
||||||
self._geotiff = GeoTIFFList(status=self._status)
|
self._geotiff = GeoTIFFList(status=self._status)
|
||||||
|
|
||||||
|
# Scenario ensemble
|
||||||
|
self._ensembles = EnsembleList(status=self._status)
|
||||||
|
|
||||||
self._results = {}
|
self._results = {}
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -627,6 +615,10 @@ class River(Graph):
|
|||||||
|
|
||||||
new._Pollutants = PollutantsList._db_load(execute, data)
|
new._Pollutants = PollutantsList._db_load(execute, data)
|
||||||
|
|
||||||
|
new._Output_rk_adists = OutputRKAdistsList._db_load(
|
||||||
|
execute, data
|
||||||
|
)
|
||||||
|
|
||||||
new._InitialConditionsAdisTS = InitialConditionsAdisTSList._db_load(
|
new._InitialConditionsAdisTS = InitialConditionsAdisTSList._db_load(
|
||||||
execute, data)
|
execute, data)
|
||||||
|
|
||||||
@@ -640,16 +632,10 @@ class River(Graph):
|
|||||||
|
|
||||||
new._DIFAdisTS = DIFAdisTSList._db_load(execute, data)
|
new._DIFAdisTS = DIFAdisTSList._db_load(execute, data)
|
||||||
|
|
||||||
new._InitialConditionsTemperature = \
|
|
||||||
InitialConditionsTemperatureList._db_load(execute, data)
|
|
||||||
|
|
||||||
new._BoundaryConditionsTemperature = \
|
|
||||||
BoundaryConditionsTemperatureList._db_load(execute, data)
|
|
||||||
|
|
||||||
new._WeatherParameters = WeatherParametersList._db_load(execute, data)
|
|
||||||
|
|
||||||
new._geotiff = GeoTIFFList._db_load(execute, data)
|
new._geotiff = GeoTIFFList._db_load(execute, data)
|
||||||
|
|
||||||
|
new._ensembles = EnsembleList._db_load(execute, data)
|
||||||
|
|
||||||
return new
|
return new
|
||||||
|
|
||||||
def _db_load_results(self, execute, data=None):
|
def _db_load_results(self, execute, data=None):
|
||||||
@@ -675,6 +661,7 @@ class River(Graph):
|
|||||||
for solver in self._parameters:
|
for solver in self._parameters:
|
||||||
objs.append(self._parameters[solver])
|
objs.append(self._parameters[solver])
|
||||||
|
|
||||||
|
objs.append(self._Output_rk_adists)
|
||||||
objs.append(self._Pollutants)
|
objs.append(self._Pollutants)
|
||||||
objs.append(self._InitialConditionsAdisTS)
|
objs.append(self._InitialConditionsAdisTS)
|
||||||
objs.append(self._BoundaryConditionsAdisTS)
|
objs.append(self._BoundaryConditionsAdisTS)
|
||||||
@@ -682,12 +669,10 @@ class River(Graph):
|
|||||||
objs.append(self._D90AdisTS)
|
objs.append(self._D90AdisTS)
|
||||||
objs.append(self._DIFAdisTS)
|
objs.append(self._DIFAdisTS)
|
||||||
|
|
||||||
objs.append(self._InitialConditionsTemperature)
|
|
||||||
objs.append(self._BoundaryConditionsTemperature)
|
|
||||||
objs.append(self._WeatherParameters)
|
|
||||||
|
|
||||||
objs.append(self._geotiff)
|
objs.append(self._geotiff)
|
||||||
|
|
||||||
|
objs.append(self._ensembles)
|
||||||
|
|
||||||
for solv_type in self.results:
|
for solv_type in self.results:
|
||||||
objs.append(self.results[solv_type])
|
objs.append(self.results[solv_type])
|
||||||
|
|
||||||
@@ -758,15 +743,13 @@ class River(Graph):
|
|||||||
self._hydraulic_structures,
|
self._hydraulic_structures,
|
||||||
self._additional_files,
|
self._additional_files,
|
||||||
self._rep_lines,
|
self._rep_lines,
|
||||||
|
self._Output_rk_adists,
|
||||||
self._Pollutants,
|
self._Pollutants,
|
||||||
self._InitialConditionsAdisTS,
|
self._InitialConditionsAdisTS,
|
||||||
self._BoundaryConditionsAdisTS,
|
self._BoundaryConditionsAdisTS,
|
||||||
self._LateralContributionsAdisTS,
|
self._LateralContributionsAdisTS,
|
||||||
self._D90AdisTS, self._DIFAdisTS,
|
self._D90AdisTS, self._DIFAdisTS,
|
||||||
self._InitialConditionsTemperature,
|
self._geotiff, self._ensembles,
|
||||||
self._BoundaryConditionsTemperature,
|
|
||||||
self._WeatherParameters,
|
|
||||||
self._geotiff,
|
|
||||||
]
|
]
|
||||||
|
|
||||||
for solver in self._parameters:
|
for solver in self._parameters:
|
||||||
@@ -871,6 +854,10 @@ Last export at: @date."""
|
|||||||
def parameters(self):
|
def parameters(self):
|
||||||
return self._parameters
|
return self._parameters
|
||||||
|
|
||||||
|
@property
|
||||||
|
def Output_rk_adists(self):
|
||||||
|
return self._Output_rk_adists
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def Pollutants(self):
|
def Pollutants(self):
|
||||||
return self._Pollutants
|
return self._Pollutants
|
||||||
@@ -895,67 +882,6 @@ Last export at: @date."""
|
|||||||
def dif_adists(self):
|
def dif_adists(self):
|
||||||
return self._DIFAdisTS
|
return self._DIFAdisTS
|
||||||
|
|
||||||
@property
|
|
||||||
def ic_temperature(self):
|
|
||||||
return self._InitialConditionsTemperature
|
|
||||||
|
|
||||||
@property
|
|
||||||
def boundary_conditions_temperature(self):
|
|
||||||
return self._BoundaryConditionsTemperature
|
|
||||||
|
|
||||||
@property
|
|
||||||
def weather_parameters(self):
|
|
||||||
return self._WeatherParameters
|
|
||||||
|
|
||||||
def profile_dependencies(self, profile):
|
|
||||||
"""Return model data which directly reference *profile*.
|
|
||||||
|
|
||||||
PK-based intervals are deliberately not included: only explicit
|
|
||||||
references to the profile object prevent it from being disabled.
|
|
||||||
"""
|
|
||||||
dependencies = []
|
|
||||||
|
|
||||||
def add(kind, item, association):
|
|
||||||
dependencies.append({
|
|
||||||
"kind": kind,
|
|
||||||
"item": item,
|
|
||||||
"association": association,
|
|
||||||
})
|
|
||||||
|
|
||||||
for structure in self._hydraulic_structures.lst:
|
|
||||||
if structure.input_section is profile:
|
|
||||||
add("hydraulic_structure", structure, "")
|
|
||||||
|
|
||||||
for tab in self._lateral_contribution._tabs_list:
|
|
||||||
for contribution in self._lateral_contribution.get_tab(tab):
|
|
||||||
if contribution.begin_section is profile:
|
|
||||||
add("lateral_contribution", contribution, "begin_section")
|
|
||||||
if contribution.end_section is profile:
|
|
||||||
add("lateral_contribution", contribution, "end_section")
|
|
||||||
|
|
||||||
for parameter in self._WeatherParameters.lst:
|
|
||||||
if parameter.begin_section is profile:
|
|
||||||
add("weather_parameter", parameter, "begin_section")
|
|
||||||
if parameter.end_section is profile:
|
|
||||||
add("weather_parameter", parameter, "end_section")
|
|
||||||
|
|
||||||
reach_id = profile.reach.pamhyr_id
|
|
||||||
for initial_condition in self._InitialConditionsTemperature.lst:
|
|
||||||
for specification in initial_condition.data:
|
|
||||||
same_reach = specification.reach == reach_id
|
|
||||||
same_rk = (
|
|
||||||
specification.start_rk == profile.rk or
|
|
||||||
specification.end_rk == profile.rk
|
|
||||||
)
|
|
||||||
if same_reach and same_rk:
|
|
||||||
add(
|
|
||||||
"initial_condition_temperature",
|
|
||||||
specification,
|
|
||||||
"cross_section_pk",
|
|
||||||
)
|
|
||||||
|
|
||||||
return dependencies
|
|
||||||
|
|
||||||
def get_params(self, solver):
|
def get_params(self, solver):
|
||||||
if solver in self._parameters:
|
if solver in self._parameters:
|
||||||
return self._parameters[solver]
|
return self._parameters[solver]
|
||||||
@@ -1012,12 +938,6 @@ Last export at: @date."""
|
|||||||
self._results[solv_type] = results
|
self._results[solv_type] = results
|
||||||
|
|
||||||
def _split_reach(self, reach, profile):
|
def _split_reach(self, reach, profile):
|
||||||
profiles = reach.reach.profiles
|
|
||||||
if not profiles or profile not in profiles[1:-1]:
|
|
||||||
raise ValueError(
|
|
||||||
"A reach cannot be split at its first or last profile"
|
|
||||||
)
|
|
||||||
|
|
||||||
node1 = reach.node1
|
node1 = reach.node1
|
||||||
node2 = reach.node2
|
node2 = reach.node2
|
||||||
|
|
||||||
@@ -1034,32 +954,4 @@ Last export at: @date."""
|
|||||||
self._add_edge(r1)
|
self._add_edge(r1)
|
||||||
self._add_edge(r2)
|
self._add_edge(r2)
|
||||||
|
|
||||||
self._initial_conditions.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
self._lateral_contribution.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
self._hydraulic_structures.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
self._InitialConditionsAdisTS.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
self._LateralContributionsAdisTS.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
self._InitialConditionsTemperature.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
self._WeatherParameters.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
self._D90AdisTS.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
self._DIFAdisTS.split_reach(
|
|
||||||
reach, profile, r1, r2
|
|
||||||
)
|
|
||||||
|
|
||||||
return r1, r2
|
return r1, r2
|
||||||
+37
-22
@@ -32,6 +32,7 @@ class Scenario(SQLSubModel):
|
|||||||
|
|
||||||
tables_with_deleted_column = [
|
tables_with_deleted_column = [
|
||||||
# Adists
|
# Adists
|
||||||
|
"output_rk_adists",
|
||||||
"boundary_condition_adists", "boundary_condition_data_adists",
|
"boundary_condition_adists", "boundary_condition_data_adists",
|
||||||
"lateral_contribution_adists", "lateral_contribution_data_adists",
|
"lateral_contribution_adists", "lateral_contribution_data_adists",
|
||||||
"initial_conditions_adists", "initial_conditions_adists_spec",
|
"initial_conditions_adists", "initial_conditions_adists_spec",
|
||||||
@@ -52,12 +53,7 @@ class Scenario(SQLSubModel):
|
|||||||
"geometry_pointXYZ", "geometry_profileXYZ",
|
"geometry_pointXYZ", "geometry_profileXYZ",
|
||||||
"river_reach", "river_node",
|
"river_reach", "river_node",
|
||||||
"geotiff", "reservoir", "reservoir_data",
|
"geotiff", "reservoir", "reservoir_data",
|
||||||
# Temperature
|
"ensemble",
|
||||||
"boundary_condition_temperature",
|
|
||||||
"boundary_condition_data_temperature",
|
|
||||||
"initial_conditions_temperature",
|
|
||||||
"initial_conditions_temperature_spec",
|
|
||||||
"weather_parameters", "weather_parameters_data",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
related_tables = tables_with_deleted_column + [
|
related_tables = tables_with_deleted_column + [
|
||||||
@@ -72,6 +68,7 @@ class Scenario(SQLSubModel):
|
|||||||
name: str = "",
|
name: str = "",
|
||||||
description: str = "",
|
description: str = "",
|
||||||
x: int = 1000.0, y: int = 1000.0,
|
x: int = 1000.0, y: int = 1000.0,
|
||||||
|
is_ensemble: bool = False,
|
||||||
revision: int = 0,
|
revision: int = 0,
|
||||||
parent=None):
|
parent=None):
|
||||||
super(Scenario, self).__init__()
|
super(Scenario, self).__init__()
|
||||||
@@ -81,6 +78,7 @@ class Scenario(SQLSubModel):
|
|||||||
self._x, self._y = x, y
|
self._x, self._y = x, y
|
||||||
self._name = name
|
self._name = name
|
||||||
self._description = description
|
self._description = description
|
||||||
|
self._is_ensemble = is_ensemble
|
||||||
self._revision = revision
|
self._revision = revision
|
||||||
self._parent = parent
|
self._parent = parent
|
||||||
|
|
||||||
@@ -103,6 +101,7 @@ class Scenario(SQLSubModel):
|
|||||||
y REAL NOT NULL DEFAULT 1000,
|
y REAL NOT NULL DEFAULT 1000,
|
||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
description TEXT NOT NULL,
|
description TEXT NOT NULL,
|
||||||
|
is_ensemble BOOL DEFAULT FALSE,
|
||||||
revision INTEGER NOT NULL,
|
revision INTEGER NOT NULL,
|
||||||
parent_id INTEGER REFERENCES scenario(id)
|
parent_id INTEGER REFERENCES scenario(id)
|
||||||
)
|
)
|
||||||
@@ -138,6 +137,13 @@ class Scenario(SQLSubModel):
|
|||||||
cls._db_create(execute)
|
cls._db_create(execute)
|
||||||
cls._db_add_default(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
|
return True
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -158,7 +164,8 @@ class Scenario(SQLSubModel):
|
|||||||
scenarios = {}
|
scenarios = {}
|
||||||
|
|
||||||
table = execute(
|
table = execute(
|
||||||
"SELECT id, x, y, name, description, revision, parent_id " +
|
"SELECT id, x, y, name, description, " +
|
||||||
|
" is_ensemble, revision, parent_id " +
|
||||||
"FROM scenario " +
|
"FROM scenario " +
|
||||||
"ORDER BY id ASC"
|
"ORDER BY id ASC"
|
||||||
)
|
)
|
||||||
@@ -170,6 +177,7 @@ class Scenario(SQLSubModel):
|
|||||||
x, y = next(it), next(it)
|
x, y = next(it), next(it)
|
||||||
name = next(it)
|
name = next(it)
|
||||||
desc = next(it)
|
desc = next(it)
|
||||||
|
is_ens = next(it)
|
||||||
revi = next(it)
|
revi = next(it)
|
||||||
parent = next(it)
|
parent = next(it)
|
||||||
|
|
||||||
@@ -179,7 +187,9 @@ class Scenario(SQLSubModel):
|
|||||||
new = cls(
|
new = cls(
|
||||||
id=id, x=x, y=y,
|
id=id, x=x, y=y,
|
||||||
name=name, description=desc,
|
name=name, description=desc,
|
||||||
revision=revi, parent=parent
|
is_ensemble=is_ens,
|
||||||
|
revision=revi,
|
||||||
|
parent=parent
|
||||||
)
|
)
|
||||||
scenarios[id] = new
|
scenarios[id] = new
|
||||||
|
|
||||||
@@ -189,21 +199,18 @@ class Scenario(SQLSubModel):
|
|||||||
if self.is_deleted():
|
if self.is_deleted():
|
||||||
return self.drop_all(execute)
|
return self.drop_all(execute)
|
||||||
|
|
||||||
parent = 'NULL'
|
parent = None
|
||||||
if self.parent is not None:
|
if self.parent is not None:
|
||||||
parent = self.parent._id
|
parent = self.parent._id
|
||||||
|
|
||||||
execute(
|
execute(
|
||||||
"INSERT OR REPLACE INTO " +
|
"INSERT OR REPLACE INTO " +
|
||||||
"scenario(id, x, y, name, description, revision, parent_id) " +
|
"scenario(id, x, y, name, description, " +
|
||||||
"VALUES (" +
|
" is_ensemble, revision, parent_id) " +
|
||||||
f"{self._id}, " +
|
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||||
f"{self.x}, {self.y}, " +
|
self._id, self.x, self.y,
|
||||||
f"'{self._db_format(self.name)}', " +
|
self.name, self.description, self._is_ensemble,
|
||||||
f"'{self._db_format(self.description)}', " +
|
self._revision, parent
|
||||||
f"{self._revision}, " +
|
|
||||||
f"{parent}" +
|
|
||||||
")"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
@@ -328,6 +335,9 @@ class Scenario(SQLSubModel):
|
|||||||
def parent(self):
|
def parent(self):
|
||||||
return self._parent
|
return self._parent
|
||||||
|
|
||||||
|
def is_ensemble(self):
|
||||||
|
return self._is_ensemble
|
||||||
|
|
||||||
def set_pos(self, x, y):
|
def set_pos(self, x, y):
|
||||||
self._x = x
|
self._x = x
|
||||||
self._y = y
|
self._y = y
|
||||||
@@ -345,14 +355,19 @@ class Scenario(SQLSubModel):
|
|||||||
return self.name
|
return self.name
|
||||||
if key == "description":
|
if key == "description":
|
||||||
return self.description
|
return self.description
|
||||||
|
if key == "is_ensemble":
|
||||||
|
return self.is_ensemble()
|
||||||
if key == "parent":
|
if key == "parent":
|
||||||
return self.parent
|
return self.parent
|
||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def workdir(self):
|
def workdir(self):
|
||||||
current = "scenario_" + str(self.id)
|
srep = ""
|
||||||
if self.parent is None or self.parent.id == 0:
|
if self.id != 0:
|
||||||
return current
|
srep = os.path.join(
|
||||||
|
self.parent.workdir(),
|
||||||
|
"scenario_" + str(self.id)
|
||||||
|
)
|
||||||
|
|
||||||
return os.path.join(self.parent.workdir(), current)
|
return srep
|
||||||
@@ -57,8 +57,11 @@ class Scenarios(PamhyrModelDict):
|
|||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def new(self, parent):
|
def new(self, parent, is_ensemble=False):
|
||||||
new = Scenario(parent=parent)
|
new = Scenario(
|
||||||
|
parent=parent,
|
||||||
|
is_ensemble=is_ensemble
|
||||||
|
)
|
||||||
self.set(new._id, new)
|
self.set(new._id, new)
|
||||||
return new
|
return new
|
||||||
|
|
||||||
|
|||||||
@@ -216,9 +216,6 @@ class Parameter(SQLSubModel):
|
|||||||
return new
|
return new
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
def _db_save(self, execute, data=None):
|
||||||
if not self.must_be_saved():
|
|
||||||
return True
|
|
||||||
|
|
||||||
ind = data["ind"]
|
ind = data["ind"]
|
||||||
solver = data["solver"]
|
solver = data["solver"]
|
||||||
|
|
||||||
|
|||||||
@@ -60,12 +60,9 @@ class StricklersList(PamhyrModelList):
|
|||||||
return self.lst
|
return self.lst
|
||||||
|
|
||||||
def new(self, index):
|
def new(self, index):
|
||||||
owner_scenario = (
|
|
||||||
self._status.scenario_id if self._status is not None else -1
|
|
||||||
)
|
|
||||||
s = Stricklers(
|
s = Stricklers(
|
||||||
status=self._status,
|
status=self._status,
|
||||||
owner_scenario=owner_scenario
|
owner_scenario=self._status.scenario_id
|
||||||
)
|
)
|
||||||
self.insert(index, s)
|
self.insert(index, s)
|
||||||
self.modified()
|
self.modified()
|
||||||
|
|||||||
+60
-40
@@ -21,7 +21,7 @@ import shutil
|
|||||||
import logging
|
import logging
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from tools import timer, timestamp, parse_datetime
|
from tools import timer, timestamp
|
||||||
from functools import reduce
|
from functools import reduce
|
||||||
|
|
||||||
from Model.Tools.PamhyrListExt import PamhyrModelList
|
from Model.Tools.PamhyrListExt import PamhyrModelList
|
||||||
@@ -32,8 +32,8 @@ from Model.Scenario import Scenario
|
|||||||
from Model.Status import StudyStatus
|
from Model.Status import StudyStatus
|
||||||
from Model.Except import NotImplementedMethodeError
|
from Model.Except import NotImplementedMethodeError
|
||||||
from Model.River import River
|
from Model.River import River
|
||||||
from Model.TimeShift import shift_river_times, shift_database_times
|
|
||||||
from Model.Geometry.Reach import Reach
|
from Model.Geometry.Reach import Reach
|
||||||
|
from Model.Ensembles.DistributionList import DistributionList
|
||||||
from Model.HydraulicStructures.HydraulicStructures import (
|
from Model.HydraulicStructures.HydraulicStructures import (
|
||||||
HydraulicStructure
|
HydraulicStructure
|
||||||
)
|
)
|
||||||
@@ -47,10 +47,11 @@ logger = logging.getLogger()
|
|||||||
|
|
||||||
|
|
||||||
class Study(SQLModel):
|
class Study(SQLModel):
|
||||||
_version = "0.2.10"
|
_version = "0.2.9"
|
||||||
|
|
||||||
_sub_classes = [
|
_sub_classes = [
|
||||||
Scenario,
|
Scenario,
|
||||||
|
DistributionList,
|
||||||
River,
|
River,
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -73,7 +74,6 @@ class Study(SQLModel):
|
|||||||
self.description = ""
|
self.description = ""
|
||||||
# Time system
|
# Time system
|
||||||
self._time_system = "time"
|
self._time_system = "time"
|
||||||
self._pending_time_offset = 0.0
|
|
||||||
self._date = datetime.fromtimestamp(0)
|
self._date = datetime.fromtimestamp(0)
|
||||||
|
|
||||||
if init_new:
|
if init_new:
|
||||||
@@ -86,6 +86,9 @@ class Study(SQLModel):
|
|||||||
self.scenarios = Scenarios(status=self.status)
|
self.scenarios = Scenarios(status=self.status)
|
||||||
self.scenarios[0] = s0
|
self.scenarios[0] = s0
|
||||||
self.status.scenario = s0
|
self.status.scenario = s0
|
||||||
|
|
||||||
|
self._ens_distributions = DistributionList(status=self.status)
|
||||||
|
|
||||||
self._river = River(status=self.status)
|
self._river = River(status=self.status)
|
||||||
else:
|
else:
|
||||||
self._init_db_file(filename, is_new=False)
|
self._init_db_file(filename, is_new=False)
|
||||||
@@ -200,16 +203,6 @@ class Study(SQLModel):
|
|||||||
self._date = date
|
self._date = date
|
||||||
self.status.modified()
|
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
|
@property
|
||||||
def date(self):
|
def date(self):
|
||||||
return self._date
|
return self._date
|
||||||
@@ -229,7 +222,8 @@ class Study(SQLModel):
|
|||||||
me.name = name
|
me.name = name
|
||||||
me.description = description
|
me.description = description
|
||||||
if date is not None:
|
if date is not None:
|
||||||
me.use_date(date)
|
me.use_date()
|
||||||
|
me.date = date
|
||||||
return me
|
return me
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
@@ -301,14 +295,7 @@ class Study(SQLModel):
|
|||||||
if major == "0" and int(minor) < 2:
|
if major == "0" and int(minor) < 2:
|
||||||
self._add_into_info_if_not_exists('current_scenario', '0')
|
self._add_into_info_if_not_exists('current_scenario', '0')
|
||||||
|
|
||||||
needs_foreign_keys_disabled = (
|
if major == "0" and int(minor) < 2:
|
||||||
major == "0" and (
|
|
||||||
int(minor) < 2 or
|
|
||||||
(minor == "2" and int(release) < 10)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
if needs_foreign_keys_disabled:
|
|
||||||
# Need to temporary disable the sqlite foreign keys
|
# Need to temporary disable the sqlite foreign keys
|
||||||
# checking to update db dans change the table id fk to
|
# checking to update db dans change the table id fk to
|
||||||
# table pamhyr_id fk
|
# table pamhyr_id fk
|
||||||
@@ -318,7 +305,7 @@ class Study(SQLModel):
|
|||||||
|
|
||||||
ok = self._update_submodel(version[0], data={})
|
ok = self._update_submodel(version[0], data={})
|
||||||
|
|
||||||
if needs_foreign_keys_disabled:
|
if major == "0" and int(minor) < 2:
|
||||||
# Reactivate foreign keys checking
|
# Reactivate foreign keys checking
|
||||||
self.execute(
|
self.execute(
|
||||||
"PRAGMA foreign_keys = ON;"
|
"PRAGMA foreign_keys = ON;"
|
||||||
@@ -406,12 +393,19 @@ class Study(SQLModel):
|
|||||||
lambda a, s: a or (s.parent is scenario),
|
lambda a, s: a or (s.parent is scenario),
|
||||||
new.scenarios.lst,
|
new.scenarios.lst,
|
||||||
False
|
False
|
||||||
):
|
) or scenario.is_ensemble():
|
||||||
new.status.set_as_read_only()
|
new.status.set_as_read_only()
|
||||||
|
|
||||||
data["scenario"] = scenario
|
data["scenario"] = scenario
|
||||||
data["loaded_pid"] = set()
|
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
|
# Load river data
|
||||||
new._river = River._db_load(
|
new._river = River._db_load(
|
||||||
sql_exec, data=data
|
sql_exec, data=data
|
||||||
@@ -472,19 +466,27 @@ class Study(SQLModel):
|
|||||||
)
|
)
|
||||||
progress()
|
progress()
|
||||||
|
|
||||||
if self._pending_time_offset:
|
if self.status.scenario.is_ensemble():
|
||||||
self._db.execute('SAVEPOINT shift_time_origin')
|
lst = [
|
||||||
try:
|
self.scenarios, self._ens_distributions,
|
||||||
shift_database_times(self._db, self._pending_time_offset)
|
self._river._ensembles,
|
||||||
self._db.execute('RELEASE SAVEPOINT shift_time_origin')
|
]
|
||||||
except Exception:
|
for solv in self._river._results:
|
||||||
self._db.execute('ROLLBACK TO SAVEPOINT shift_time_origin')
|
lst.append(self._river._results[solv])
|
||||||
self._db.execute('RELEASE SAVEPOINT shift_time_origin')
|
|
||||||
raise
|
|
||||||
self._pending_time_offset = 0.0
|
|
||||||
|
|
||||||
self._save_submodel(
|
self._save_submodel(
|
||||||
[self.scenarios, self._river],
|
lst, data=progress
|
||||||
|
)
|
||||||
|
progress()
|
||||||
|
self.commit()
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
self._save_submodel(
|
||||||
|
[
|
||||||
|
self.scenarios, self._ens_distributions,
|
||||||
|
self._river
|
||||||
|
],
|
||||||
data=progress
|
data=progress
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -602,7 +604,8 @@ class Study(SQLModel):
|
|||||||
data = {
|
data = {
|
||||||
"status": self.status,
|
"status": self.status,
|
||||||
"loaded_pid": set(),
|
"loaded_pid": set(),
|
||||||
"scenario": scenario
|
"scenario": scenario,
|
||||||
|
"ens_distributions": self._ens_distributions,
|
||||||
}
|
}
|
||||||
|
|
||||||
self.status.start_loading()
|
self.status.start_loading()
|
||||||
@@ -617,9 +620,6 @@ class Study(SQLModel):
|
|||||||
self.status.stop_loading()
|
self.status.stop_loading()
|
||||||
self.status.scenario = old_scenario
|
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
|
# FIXME: Disable scenario cache to save memory usage
|
||||||
# self._river_scenario_cache[scenario] = river
|
# self._river_scenario_cache[scenario] = river
|
||||||
|
|
||||||
@@ -679,6 +679,7 @@ class Study(SQLModel):
|
|||||||
self.status.scenario.y + 100)
|
self.status.scenario.y + 100)
|
||||||
|
|
||||||
new.name = self.status.scenario.name + " (copy)"
|
new.name = self.status.scenario.name + " (copy)"
|
||||||
|
new.is_ensemble = self.status.scenario.is_ensemble
|
||||||
|
|
||||||
self.status.scenario = new
|
self.status.scenario = new
|
||||||
self.river._data_traversal(
|
self.river._data_traversal(
|
||||||
@@ -690,6 +691,25 @@ class Study(SQLModel):
|
|||||||
self.status.set_as_editable()
|
self.status.set_as_editable()
|
||||||
return new
|
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
|
@property
|
||||||
def results(self):
|
def results(self):
|
||||||
return self._river.results
|
return self._river.results
|
||||||
|
|||||||
@@ -1,82 +0,0 @@
|
|||||||
"""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:
|
else:
|
||||||
self._owner_scenario = owner_scenario
|
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):
|
def must_be_saved(self):
|
||||||
"""Return True if this object MUST be save in the save file.
|
"""Return True if this object MUST be save in the save file.
|
||||||
|
|
||||||
|
|||||||
@@ -1,775 +0,0 @@
|
|||||||
# WeatherParameters.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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,
|
|
||||||
old_pamhyr_date_to_timestamp,
|
|
||||||
date_iso_to_timestamp,
|
|
||||||
date_dmy_to_timestamp,
|
|
||||||
)
|
|
||||||
|
|
||||||
from Model.Tools.PamhyrDB import SQLSubModel
|
|
||||||
from Model.Except import NotImplementedMethodeError
|
|
||||||
from Model.Scenario import Scenario
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class Data(SQLSubModel):
|
|
||||||
_sub_classes = []
|
|
||||||
|
|
||||||
def __init__(self,
|
|
||||||
data0, data1,
|
|
||||||
id: int = -1,
|
|
||||||
types=[float, float],
|
|
||||||
status=None,
|
|
||||||
owner_scenario=-1):
|
|
||||||
super(Data, self).__init__(
|
|
||||||
id=id, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._types = types
|
|
||||||
self._data = [data0, data1]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_create(cls, execute, ext=""):
|
|
||||||
execute(f"""
|
|
||||||
CREATE TABLE weather_parameters_data{ext} (
|
|
||||||
{cls.create_db_add_pamhyr_id()},
|
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
ind INTEGER NOT NULL,
|
|
||||||
data0 TEXT NOT NULL,
|
|
||||||
data1 TEXT NOT NULL,
|
|
||||||
wp INTEGER,
|
|
||||||
{Scenario.create_db_add_scenario()},
|
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
|
||||||
FOREIGN KEY(wp) REFERENCES weather_parameters(pamhyr_id),
|
|
||||||
PRIMARY KEY(pamhyr_id, scenario)
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
|
|
||||||
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 or
|
|
||||||
(int(minor) == 2 and int(release) <= 7)):
|
|
||||||
if not cls.is_table_exists(execute, "air_temperature_data"):
|
|
||||||
cls._db_create(execute)
|
|
||||||
|
|
||||||
return cls._update_submodel(execute, version, data)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_load(cls, execute, data=None):
|
|
||||||
new = []
|
|
||||||
wp = data["wp"]
|
|
||||||
status = data['status']
|
|
||||||
scenario = data["scenario"]
|
|
||||||
loaded = data['loaded_pid']
|
|
||||||
|
|
||||||
if scenario is None:
|
|
||||||
return new
|
|
||||||
|
|
||||||
values = execute(
|
|
||||||
"SELECT pamhyr_id, deleted, " +
|
|
||||||
"data0, data1, scenario " +
|
|
||||||
"FROM weather_parameters_data " +
|
|
||||||
f"WHERE wp = {wp._pamhyr_id} " +
|
|
||||||
f"AND scenario = {scenario.id} " +
|
|
||||||
f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))}) " +
|
|
||||||
"ORDER BY ind ASC"
|
|
||||||
)
|
|
||||||
|
|
||||||
for v in values:
|
|
||||||
it = iter(v)
|
|
||||||
|
|
||||||
pid = next(it)
|
|
||||||
deleted = next(it)
|
|
||||||
data0 = wp._types[0](next(it))
|
|
||||||
data1 = wp._types[1](next(it))
|
|
||||||
owner_scenario = next(it)
|
|
||||||
|
|
||||||
nd = cls(
|
|
||||||
data0, data1,
|
|
||||||
id=pid,
|
|
||||||
types=wp._types,
|
|
||||||
status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
if deleted:
|
|
||||||
nd.set_as_deleted()
|
|
||||||
|
|
||||||
loaded.add(pid)
|
|
||||||
new.append(nd)
|
|
||||||
|
|
||||||
data["scenario"] = scenario.parent
|
|
||||||
new += cls._db_load(execute, data)
|
|
||||||
data["scenario"] = scenario
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
|
||||||
pid = self._pamhyr_id
|
|
||||||
ind = data["ind"]
|
|
||||||
data0 = self._db_format(str(self[0]))
|
|
||||||
data1 = self._db_format(str(self[1]))
|
|
||||||
wp = data["wp"]
|
|
||||||
|
|
||||||
execute(
|
|
||||||
"INSERT INTO " +
|
|
||||||
"weather_parameters_data (pamhyr_id, deleted, ind, " +
|
|
||||||
"data0, data1, wp, scenario) " +
|
|
||||||
f"VALUES ({pid}, {self._db_format(self.is_deleted())}, " +
|
|
||||||
f"{ind}, '{self._db_format(data0)}', {self._db_format(data1)}, " +
|
|
||||||
f"{wp._pamhyr_id}, {self._status.scenario_id}" +
|
|
||||||
")"
|
|
||||||
)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
def __getitem__(self, key):
|
|
||||||
return self._types[key](self._data[key])
|
|
||||||
|
|
||||||
def __setitem__(self, key, value):
|
|
||||||
self._data[key] = self._types[key](value)
|
|
||||||
|
|
||||||
def cloned(self):
|
|
||||||
return Data(
|
|
||||||
self[0], self[1],
|
|
||||||
types=self._types,
|
|
||||||
status=self._status
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class WeatherParametersDefault(SQLSubModel):
|
|
||||||
def __init__(self, type: str, value: float = 0.0,
|
|
||||||
id: int = -1, status=None, owner_scenario=-1):
|
|
||||||
super(WeatherParametersDefault, self).__init__(
|
|
||||||
id=id, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = type
|
|
||||||
self._value = float(value)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_load(cls, execute, data=None):
|
|
||||||
new = []
|
|
||||||
status = data['status']
|
|
||||||
scenario = data["scenario"]
|
|
||||||
loaded = data['loaded_pid']
|
|
||||||
|
|
||||||
if scenario is None:
|
|
||||||
return new
|
|
||||||
|
|
||||||
table = execute(
|
|
||||||
"SELECT pamhyr_id, type, value, scenario " +
|
|
||||||
"FROM weather_parameters_default " +
|
|
||||||
f"WHERE scenario = {scenario.id} " +
|
|
||||||
f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))}) "
|
|
||||||
)
|
|
||||||
|
|
||||||
for row in table:
|
|
||||||
it = iter(row)
|
|
||||||
|
|
||||||
pid = next(it)
|
|
||||||
type = next(it)
|
|
||||||
value = next(it)
|
|
||||||
owner_scenario = next(it)
|
|
||||||
|
|
||||||
wp_default = cls(
|
|
||||||
type=type,
|
|
||||||
value=value,
|
|
||||||
id=pid,
|
|
||||||
status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
loaded.add(pid)
|
|
||||||
new.append(wp_default)
|
|
||||||
|
|
||||||
data["scenario"] = scenario.parent
|
|
||||||
new += cls._db_load(execute, data)
|
|
||||||
data["scenario"] = scenario
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
|
||||||
if not self.must_be_saved():
|
|
||||||
return True
|
|
||||||
|
|
||||||
execute(
|
|
||||||
"INSERT INTO " +
|
|
||||||
"weather_parameters_default(" +
|
|
||||||
"pamhyr_id, type, value, scenario) " +
|
|
||||||
"VALUES (" +
|
|
||||||
f"{self.id}, '{self._db_format(self._type)}', {self._value}, " +
|
|
||||||
f"{self._status.scenario_id}" +
|
|
||||||
")"
|
|
||||||
)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
@property
|
|
||||||
def type(self):
|
|
||||||
return self._type
|
|
||||||
|
|
||||||
@property
|
|
||||||
def value(self):
|
|
||||||
return self._value
|
|
||||||
|
|
||||||
@value.setter
|
|
||||||
def value(self, value):
|
|
||||||
self._value = float(value)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
|
|
||||||
class WeatherParameters(SQLSubModel):
|
|
||||||
_sub_classes = [Data]
|
|
||||||
|
|
||||||
def __init__(self, id: int = -1,
|
|
||||||
name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(WeatherParameters, self).__init__(
|
|
||||||
id=id, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._name = name
|
|
||||||
self._type = ""
|
|
||||||
self._reach = None
|
|
||||||
self._begin_section = None
|
|
||||||
self._end_section = None
|
|
||||||
self._data = []
|
|
||||||
self._header = []
|
|
||||||
self._types = [float, float]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_create(cls, execute, ext=""):
|
|
||||||
execute(f"""
|
|
||||||
CREATE TABLE weather_parameters{ext}(
|
|
||||||
{cls.create_db_add_pamhyr_id()},
|
|
||||||
deleted BOOLEAN NOT NULL DEFAULT FALSE,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
type TEXT NOT NULL,
|
|
||||||
reach INTEGER,
|
|
||||||
begin_section INTEGER,
|
|
||||||
end_section INTEGER,
|
|
||||||
{Scenario.create_db_add_scenario()},
|
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
|
||||||
FOREIGN KEY(reach) REFERENCES river_reach(pamhyr_id),
|
|
||||||
FOREIGN KEY(begin_section)
|
|
||||||
REFERENCES geometry_profileXYZ(pamhyr_id),
|
|
||||||
FOREIGN KEY(end_section)
|
|
||||||
REFERENCES geometry_profileXYZ(pamhyr_id),
|
|
||||||
PRIMARY KEY(pamhyr_id, scenario)
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
|
|
||||||
execute(f"""
|
|
||||||
CREATE TABLE weather_parameters_default{ext}(
|
|
||||||
{cls.create_db_add_pamhyr_id()},
|
|
||||||
type TEXT NOT NULL,
|
|
||||||
value FLOAT 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 _get_ctor_from_type(cls, t):
|
|
||||||
from Model.WeatherParameters.WeatherParametersTypes import (
|
|
||||||
NotDefined, WeatherParam, AirTemperature, SpecificHumidity,
|
|
||||||
GlobalRadiation, ReferenceWindSpeed, GroundwaterTemperature,
|
|
||||||
GroundwaterFlowRate, Albedo, ShadingCoefficient, CloudCoverFraction
|
|
||||||
)
|
|
||||||
|
|
||||||
res = NotDefined
|
|
||||||
if t == "WP":
|
|
||||||
res = WeatherParam
|
|
||||||
elif t == "AT":
|
|
||||||
res = AirTemperature
|
|
||||||
elif t == "SH":
|
|
||||||
res = SpecificHumidity
|
|
||||||
elif t == "GR":
|
|
||||||
res = GlobalRadiation
|
|
||||||
elif t == "RWS":
|
|
||||||
res = ReferenceWindSpeed
|
|
||||||
elif t == "GT":
|
|
||||||
res = GroundwaterTemperature
|
|
||||||
elif t == "GFR":
|
|
||||||
res = GroundwaterFlowRate
|
|
||||||
elif t == "ALB":
|
|
||||||
res = Albedo
|
|
||||||
elif t == "SC":
|
|
||||||
res = ShadingCoefficient
|
|
||||||
elif t == "CCF":
|
|
||||||
res = CloudCoverFraction
|
|
||||||
else:
|
|
||||||
res = NotDefined
|
|
||||||
return res
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_update(cls, execute, version, data=None):
|
|
||||||
major, minor, release = version.strip().split(".")
|
|
||||||
created = False
|
|
||||||
|
|
||||||
if major == "0" and (int(minor) < 2 or
|
|
||||||
(int(minor) == 2 and int(release) <= 7)):
|
|
||||||
if not cls.is_table_exists(execute, "air_temperature"):
|
|
||||||
cls._db_create(execute)
|
|
||||||
created = True
|
|
||||||
|
|
||||||
if not cls.is_table_exists(execute, "weather_parameters_default"):
|
|
||||||
execute(f"""
|
|
||||||
CREATE TABLE weather_parameters_default(
|
|
||||||
{cls.create_db_add_pamhyr_id()},
|
|
||||||
type TEXT NOT NULL,
|
|
||||||
value FLOAT NOT NULL,
|
|
||||||
{Scenario.create_db_add_scenario()},
|
|
||||||
{Scenario.create_db_add_scenario_fk()},
|
|
||||||
primary KEY(pamhyr_id, scenario)
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
|
|
||||||
if not created:
|
|
||||||
return cls._update_submodel(execute, version, data)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_load(cls, execute, data=None):
|
|
||||||
new = []
|
|
||||||
status = data['status']
|
|
||||||
edges = data["edges"]
|
|
||||||
scenario = data["scenario"]
|
|
||||||
loaded = data['loaded_pid']
|
|
||||||
|
|
||||||
if scenario is None:
|
|
||||||
return new
|
|
||||||
|
|
||||||
table = execute(
|
|
||||||
"SELECT pamhyr_id, deleted, name, type, " +
|
|
||||||
"reach, begin_section, end_section, scenario " +
|
|
||||||
"FROM weather_parameters " +
|
|
||||||
f"WHERE scenario = {scenario.id} " +
|
|
||||||
f"AND pamhyr_id NOT IN ({', '.join(map(str, loaded))}) "
|
|
||||||
)
|
|
||||||
|
|
||||||
for row in table:
|
|
||||||
it = iter(row)
|
|
||||||
|
|
||||||
pid = next(it)
|
|
||||||
deleted = next(it)
|
|
||||||
name = next(it)
|
|
||||||
t = next(it)
|
|
||||||
reach = next(it)
|
|
||||||
b_section = next(it)
|
|
||||||
e_section = next(it)
|
|
||||||
owner_scenario = next(it)
|
|
||||||
|
|
||||||
ctor = cls._get_ctor_from_type(t)
|
|
||||||
wp = ctor(
|
|
||||||
id=pid, name=name,
|
|
||||||
status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
wp.reach = None
|
|
||||||
wp._begin_section = None
|
|
||||||
wp._end_section = None
|
|
||||||
|
|
||||||
if reach not in (-1, None):
|
|
||||||
wp.reach = next(
|
|
||||||
(edge for edge in edges if edge.id == reach), None
|
|
||||||
)
|
|
||||||
profiles = (
|
|
||||||
wp.reach.reach.profiles
|
|
||||||
if wp.reach is not None else []
|
|
||||||
)
|
|
||||||
wp._begin_section = next(
|
|
||||||
(profile for profile in profiles
|
|
||||||
if profile.id == b_section), None
|
|
||||||
)
|
|
||||||
wp._end_section = next(
|
|
||||||
(profile for profile in profiles
|
|
||||||
if profile.id == e_section), None
|
|
||||||
)
|
|
||||||
|
|
||||||
data["wp"] = wp
|
|
||||||
wp._data = Data._db_load(execute, data=data)
|
|
||||||
|
|
||||||
loaded.add(pid)
|
|
||||||
new.append(wp)
|
|
||||||
|
|
||||||
data["scenario"] = scenario.parent
|
|
||||||
new += cls._db_load(execute, data)
|
|
||||||
data["scenario"] = scenario
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
|
||||||
if not self.must_be_saved():
|
|
||||||
return True
|
|
||||||
|
|
||||||
data["wp"] = self
|
|
||||||
|
|
||||||
execute(
|
|
||||||
"DELETE FROM weather_parameters_data " +
|
|
||||||
f"WHERE wp = {self._pamhyr_id} " +
|
|
||||||
f"AND scenario = {self._status.scenario_id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
reach = None
|
|
||||||
begin_section = None
|
|
||||||
end_section = None
|
|
||||||
|
|
||||||
if self._reach is not None:
|
|
||||||
reach = self._reach._pamhyr_id
|
|
||||||
begin_section = self._begin_section._pamhyr_id
|
|
||||||
end_section = self._end_section._pamhyr_id
|
|
||||||
|
|
||||||
execute(
|
|
||||||
"INSERT INTO " +
|
|
||||||
"weather_parameters(" +
|
|
||||||
"pamhyr_id, deleted, name, type, " +
|
|
||||||
"reach, begin_section, end_section, scenario) " +
|
|
||||||
"VALUES (" +
|
|
||||||
f"{self.id}, {self._db_format(self.is_deleted())}, " +
|
|
||||||
f"'{self._db_format(self._name)}', " +
|
|
||||||
f"'{self._db_format(self._type)}', {reach}, " +
|
|
||||||
f"{begin_section}, {end_section}, " +
|
|
||||||
f"{self._status.scenario_id}" +
|
|
||||||
")"
|
|
||||||
)
|
|
||||||
|
|
||||||
ind = 0
|
|
||||||
for d in self._data:
|
|
||||||
data["ind"] = ind
|
|
||||||
|
|
||||||
d._db_save(execute, data)
|
|
||||||
|
|
||||||
ind += 1
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
def _data_traversal(self,
|
|
||||||
predicate=lambda obj, data: True,
|
|
||||||
modifier=lambda obj, data: None,
|
|
||||||
data={}):
|
|
||||||
if predicate(self, data):
|
|
||||||
modifier(self, data)
|
|
||||||
|
|
||||||
for d in self._data:
|
|
||||||
d._data_traversal(predicate, modifier, data)
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
return len(
|
|
||||||
list(
|
|
||||||
filter(
|
|
||||||
lambda el: not el.is_deleted(),
|
|
||||||
self._data
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def compatibility(cls):
|
|
||||||
return ["liquid", "solid", "suspenssion"]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def time_convert(cls, data):
|
|
||||||
if type(data) is str:
|
|
||||||
if data.count("-") == 2:
|
|
||||||
return date_iso_to_timestamp(data)
|
|
||||||
if data.count("/") == 2:
|
|
||||||
return date_dmy_to_timestamp(data)
|
|
||||||
if data.count(":") == 3:
|
|
||||||
return old_pamhyr_date_to_timestamp(data)
|
|
||||||
if data.count(":") == 2:
|
|
||||||
return old_pamhyr_date_to_timestamp("00:" + data)
|
|
||||||
if data.count(".") == 1:
|
|
||||||
return round(float(data))
|
|
||||||
|
|
||||||
return int(data)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def name(self):
|
|
||||||
if self._name == "":
|
|
||||||
return f"LC #{self.id}"
|
|
||||||
|
|
||||||
return self._name
|
|
||||||
|
|
||||||
@name.setter
|
|
||||||
def name(self, name):
|
|
||||||
self._name = name
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def type(self):
|
|
||||||
return self._type
|
|
||||||
|
|
||||||
@property
|
|
||||||
def reach(self):
|
|
||||||
return self._reach
|
|
||||||
|
|
||||||
@reach.setter
|
|
||||||
def reach(self, reach):
|
|
||||||
self._reach = reach
|
|
||||||
self._begin_section = None
|
|
||||||
self._end_section = None
|
|
||||||
|
|
||||||
if reach is not None:
|
|
||||||
profiles = reach.reach.profiles
|
|
||||||
if profiles:
|
|
||||||
self._begin_section = profiles[0]
|
|
||||||
self._end_section = profiles[-1]
|
|
||||||
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def has_reach(self):
|
|
||||||
return self._reach is not None
|
|
||||||
|
|
||||||
@property
|
|
||||||
def begin_rk(self):
|
|
||||||
if self._begin_section is None:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
return self._begin_section.rk
|
|
||||||
|
|
||||||
@property
|
|
||||||
def begin_section(self):
|
|
||||||
return self._begin_section
|
|
||||||
|
|
||||||
@begin_section.setter
|
|
||||||
def begin_section(self, section):
|
|
||||||
self._begin_section = section
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def end_rk(self):
|
|
||||||
if self._end_section is None:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
return self._end_section.rk
|
|
||||||
|
|
||||||
@property
|
|
||||||
def end_section(self):
|
|
||||||
return self._end_section
|
|
||||||
|
|
||||||
@end_section.setter
|
|
||||||
def end_section(self, section):
|
|
||||||
self._end_section = section
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def cloned_for(self, reach, begin_section, end_section):
|
|
||||||
new = type(self)(name=self._name, status=self._status)
|
|
||||||
new._reach = reach
|
|
||||||
new._begin_section = begin_section
|
|
||||||
new._end_section = end_section
|
|
||||||
new._data = [data.cloned() for data in self.data]
|
|
||||||
new.modified()
|
|
||||||
return new
|
|
||||||
|
|
||||||
@property
|
|
||||||
def header(self):
|
|
||||||
return self._header.copy()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def data(self):
|
|
||||||
return list(
|
|
||||||
filter(
|
|
||||||
lambda el: not el.is_deleted(),
|
|
||||||
self._data
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_type_column(self, column):
|
|
||||||
if 0 <= column < 2:
|
|
||||||
return self._types[column]
|
|
||||||
return None
|
|
||||||
|
|
||||||
@property
|
|
||||||
def _default_0(self):
|
|
||||||
return self._types[0](0)
|
|
||||||
|
|
||||||
@property
|
|
||||||
def _default_1(self):
|
|
||||||
return self._types[1](0.0)
|
|
||||||
|
|
||||||
def is_define(self):
|
|
||||||
return self._data is not None
|
|
||||||
|
|
||||||
def new_from_data(self, header, data):
|
|
||||||
new_0 = self._default_0
|
|
||||||
new_1 = self._default_1
|
|
||||||
|
|
||||||
def convert(column, value, default):
|
|
||||||
if value.strip() == "":
|
|
||||||
return default
|
|
||||||
return self._types[column](value.replace(",", "."))
|
|
||||||
|
|
||||||
if len(header) != 0:
|
|
||||||
for i in [0, 1]:
|
|
||||||
for j in range(len(header)):
|
|
||||||
if self._header[i] == header[j] and j < len(data):
|
|
||||||
if i == 0:
|
|
||||||
new_0 = convert(i, data[j], new_0)
|
|
||||||
else:
|
|
||||||
new_1 = convert(i, data[j], new_1)
|
|
||||||
else:
|
|
||||||
if len(data) > 0:
|
|
||||||
new_0 = convert(0, data[0], new_0)
|
|
||||||
if len(data) > 1:
|
|
||||||
new_1 = convert(1, data[1], new_1)
|
|
||||||
|
|
||||||
return Data(new_0, new_1, status=self._status)
|
|
||||||
|
|
||||||
def add(self, index: int):
|
|
||||||
value = Data(self._default_0, self._default_1, status=self._status)
|
|
||||||
self.insert(index, value)
|
|
||||||
return value
|
|
||||||
|
|
||||||
def insert(self, index: int, value):
|
|
||||||
visible_data = self.data
|
|
||||||
if index < len(visible_data):
|
|
||||||
index = self._data.index(visible_data[index])
|
|
||||||
else:
|
|
||||||
index = len(self._data)
|
|
||||||
self._data.insert(index, value)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def set_data_value(self, value, column, data):
|
|
||||||
value[column] = self._types[column](data)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def set_deleted(self, values, deleted):
|
|
||||||
for value in values:
|
|
||||||
if deleted:
|
|
||||||
value.set_as_deleted()
|
|
||||||
else:
|
|
||||||
value.set_as_not_deleted()
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def reorder(self, values):
|
|
||||||
values = iter(values)
|
|
||||||
self._data = [
|
|
||||||
value if value.is_deleted() else next(values)
|
|
||||||
for value in self._data
|
|
||||||
]
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def delete_i(self, indexes):
|
|
||||||
self._data = list(
|
|
||||||
map(
|
|
||||||
lambda e: e[1],
|
|
||||||
filter(
|
|
||||||
lambda e: e[0] not in indexes,
|
|
||||||
enumerate(self.data)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def set_as_deleted_i(self, indexes):
|
|
||||||
for i in indexes:
|
|
||||||
self._data[i].set_as_deleted()
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def set_as_not_deleted_i(self, indexes):
|
|
||||||
for i in indexes:
|
|
||||||
self._data[i].set_as_not_deleted()
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def delete(self, els):
|
|
||||||
self._data = list(
|
|
||||||
filter(
|
|
||||||
lambda e: e not in els,
|
|
||||||
self.data
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def sort(self, _reverse=False, key=None):
|
|
||||||
if key is None:
|
|
||||||
self._data.sort(reverse=_reverse)
|
|
||||||
else:
|
|
||||||
self._data.sort(reverse=_reverse, key=key)
|
|
||||||
self.modified()
|
|
||||||
|
|
||||||
def get_i(self, index):
|
|
||||||
return self.data[index]
|
|
||||||
|
|
||||||
def get_range(self, _range):
|
|
||||||
lst = []
|
|
||||||
for r in _range:
|
|
||||||
lst.append(r)
|
|
||||||
return lst
|
|
||||||
|
|
||||||
def _set_i_c_v(self, index, column, value):
|
|
||||||
self.set_data_value(self.get_i(index), column, value)
|
|
||||||
|
|
||||||
def set_i_0(self, index: int, value):
|
|
||||||
self._set_i_c_v(index, 0, value)
|
|
||||||
|
|
||||||
def set_i_1(self, index: int, value):
|
|
||||||
self._set_i_c_v(index, 1, value)
|
|
||||||
|
|
||||||
@timer
|
|
||||||
def convert(self, cls):
|
|
||||||
new = cls(name=self.name, status=self._status)
|
|
||||||
new.reach = self.reach
|
|
||||||
new.begin_section = self.begin_section
|
|
||||||
new.end_section = self.end_section
|
|
||||||
|
|
||||||
for i, _ in enumerate(self.data):
|
|
||||||
new.add(i)
|
|
||||||
|
|
||||||
for i in [0, 1]:
|
|
||||||
for j in [0, 1]:
|
|
||||||
if self._header[i] == new.header[j]:
|
|
||||||
for ind, v in self.data:
|
|
||||||
try:
|
|
||||||
new._set_i_c_v(ind, j, v[i])
|
|
||||||
except Exception as e:
|
|
||||||
logger.info(e)
|
|
||||||
|
|
||||||
self.modified()
|
|
||||||
return new
|
|
||||||
|
|
||||||
def move_up(self, index):
|
|
||||||
if 0 < index < len(self):
|
|
||||||
data = self.data
|
|
||||||
data[index - 1], data[index] = data[index], data[index - 1]
|
|
||||||
self.reorder(data)
|
|
||||||
|
|
||||||
def move_down(self, index):
|
|
||||||
if 0 <= index < len(self) - 1:
|
|
||||||
data = self.data
|
|
||||||
data[index], data[index + 1] = data[index + 1], data[index]
|
|
||||||
self.reorder(data)
|
|
||||||
@@ -1,234 +0,0 @@
|
|||||||
# WeatherParametersList.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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 copy
|
|
||||||
from tools import trace, timer
|
|
||||||
|
|
||||||
from Model.Tools.PamhyrListExt import PamhyrModelList
|
|
||||||
from Model.Except import NotImplementedMethodeError
|
|
||||||
|
|
||||||
from Model.WeatherParameters.WeatherParameters import (
|
|
||||||
WeatherParameters,
|
|
||||||
WeatherParametersDefault,
|
|
||||||
)
|
|
||||||
from Model.WeatherParameters.WeatherParametersTypes import (
|
|
||||||
NotDefined, WeatherParam, AirTemperature, SpecificHumidity,
|
|
||||||
GlobalRadiation, ReferenceWindSpeed, GroundwaterTemperature,
|
|
||||||
GroundwaterFlowRate, Albedo, ShadingCoefficient, CloudCoverFraction
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class WeatherParametersList(PamhyrModelList):
|
|
||||||
_sub_classes = [
|
|
||||||
WeatherParameters,
|
|
||||||
]
|
|
||||||
_default_types = [
|
|
||||||
"AT", "SH", "GR", "RWS", "GT", "GFR", "ALB", "SC", "CCF"
|
|
||||||
]
|
|
||||||
_default_values = {
|
|
||||||
"AT": 20.0,
|
|
||||||
"SH": 0.001,
|
|
||||||
"GR": 10.0,
|
|
||||||
"RWS": 1.0,
|
|
||||||
"GT": 0.0,
|
|
||||||
"GFR": 0.0,
|
|
||||||
"ALB": 0.06,
|
|
||||||
"SC": 0.15,
|
|
||||||
"CCF": 0.5,
|
|
||||||
}
|
|
||||||
|
|
||||||
def __init__(self, status=None):
|
|
||||||
super(WeatherParametersList, self).__init__(status=status)
|
|
||||||
self._default = []
|
|
||||||
self._init_missing_default_values()
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def _db_load(cls, execute, data=None):
|
|
||||||
new = cls(status=data['status'])
|
|
||||||
|
|
||||||
if data is None:
|
|
||||||
data = {}
|
|
||||||
|
|
||||||
new._lst = WeatherParameters._db_load(
|
|
||||||
execute, data
|
|
||||||
)
|
|
||||||
|
|
||||||
data['loaded_pid'] = set()
|
|
||||||
new._default = WeatherParametersDefault._db_load(
|
|
||||||
execute, data
|
|
||||||
)
|
|
||||||
new._init_missing_default_values()
|
|
||||||
new._sort_default_values()
|
|
||||||
|
|
||||||
return new
|
|
||||||
|
|
||||||
def _db_save(self, execute, data=None):
|
|
||||||
execute(
|
|
||||||
"DELETE FROM weather_parameters " +
|
|
||||||
f"WHERE scenario = {self._status.scenario_id}"
|
|
||||||
)
|
|
||||||
execute(
|
|
||||||
"DELETE FROM weather_parameters_data " +
|
|
||||||
f"WHERE scenario = {self._status.scenario_id}"
|
|
||||||
)
|
|
||||||
execute(
|
|
||||||
"DELETE FROM weather_parameters_default " +
|
|
||||||
f"WHERE scenario = {self._status.scenario_id}"
|
|
||||||
)
|
|
||||||
|
|
||||||
if data is None:
|
|
||||||
data = {}
|
|
||||||
|
|
||||||
for wp in self._lst:
|
|
||||||
wp._db_save(execute, data=data)
|
|
||||||
|
|
||||||
for wp_default in self._default:
|
|
||||||
wp_default._db_save(execute, data=data)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
def _data_traversal(self,
|
|
||||||
predicate=lambda obj, data: True,
|
|
||||||
modifier=lambda obj, data: None,
|
|
||||||
data={}):
|
|
||||||
if predicate(self, data):
|
|
||||||
modifier(self, data)
|
|
||||||
|
|
||||||
for el in self._lst:
|
|
||||||
el._data_traversal(predicate, modifier, data)
|
|
||||||
|
|
||||||
for el in self._default:
|
|
||||||
el._data_traversal(predicate, modifier, data)
|
|
||||||
|
|
||||||
def _init_missing_default_values(self):
|
|
||||||
existing = [wp_default.type for wp_default in self.default]
|
|
||||||
for type in self._default_types:
|
|
||||||
if type not in existing:
|
|
||||||
self._default.append(
|
|
||||||
WeatherParametersDefault(
|
|
||||||
type=type,
|
|
||||||
value=self._default_values[type],
|
|
||||||
status=self._status,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
self._sort_default_values()
|
|
||||||
|
|
||||||
def _sort_default_values(self):
|
|
||||||
self._default.sort(
|
|
||||||
key=lambda wp_default: self._default_types.index(wp_default.type)
|
|
||||||
if wp_default.type in self._default_types
|
|
||||||
else len(self._default_types)
|
|
||||||
)
|
|
||||||
|
|
||||||
def new(self, index, type="ND"):
|
|
||||||
if type == "AT":
|
|
||||||
n = AirTemperature(status=self._status)
|
|
||||||
elif type == "SH":
|
|
||||||
n = SpecificHumidity(status=self._status)
|
|
||||||
elif type == "GR":
|
|
||||||
n = GlobalRadiation(status=self._status)
|
|
||||||
elif type == "RWS":
|
|
||||||
n = ReferenceWindSpeed(status=self._status)
|
|
||||||
elif type == "GT":
|
|
||||||
n = GroundwaterTemperature(status=self._status)
|
|
||||||
elif type == "GFR":
|
|
||||||
n = GroundwaterFlowRate(status=self._status)
|
|
||||||
elif type == "ALB":
|
|
||||||
n = Albedo(status=self._status)
|
|
||||||
elif type == "SC":
|
|
||||||
n = ShadingCoefficient(status=self._status)
|
|
||||||
elif type == "CCF":
|
|
||||||
n = CloudCoverFraction(status=self._status)
|
|
||||||
else:
|
|
||||||
n = NotDefined(status=self._status)
|
|
||||||
self._lst.insert(index, n)
|
|
||||||
self._status.modified()
|
|
||||||
return n
|
|
||||||
|
|
||||||
def split_reach(self, reach, profile, reach1, reach2):
|
|
||||||
profiles = reach.reach.profiles
|
|
||||||
split_index = profiles.index(profile)
|
|
||||||
parts = [
|
|
||||||
(
|
|
||||||
reach1,
|
|
||||||
0,
|
|
||||||
split_index,
|
|
||||||
dict(zip(
|
|
||||||
profiles[:split_index + 1],
|
|
||||||
reach1.reach.profiles
|
|
||||||
))
|
|
||||||
),
|
|
||||||
(
|
|
||||||
reach2,
|
|
||||||
split_index,
|
|
||||||
len(profiles) - 1,
|
|
||||||
dict(zip(
|
|
||||||
profiles[split_index:],
|
|
||||||
reach2.reach.profiles
|
|
||||||
))
|
|
||||||
),
|
|
||||||
]
|
|
||||||
weather_parameters = [
|
|
||||||
weather_parameter
|
|
||||||
for weather_parameter in self.lst
|
|
||||||
if weather_parameter.reach is reach
|
|
||||||
]
|
|
||||||
clones = []
|
|
||||||
|
|
||||||
for weather_parameter in weather_parameters:
|
|
||||||
if (weather_parameter.begin_section not in profiles or
|
|
||||||
weather_parameter.end_section not in profiles):
|
|
||||||
continue
|
|
||||||
|
|
||||||
begin = profiles.index(weather_parameter.begin_section)
|
|
||||||
end = profiles.index(weather_parameter.end_section)
|
|
||||||
lower, upper = sorted((begin, end))
|
|
||||||
reverse = begin > end
|
|
||||||
|
|
||||||
for new_reach, part_lower, part_upper, sections in parts:
|
|
||||||
clipped_lower = max(lower, part_lower)
|
|
||||||
clipped_upper = min(upper, part_upper)
|
|
||||||
if clipped_lower >= clipped_upper:
|
|
||||||
continue
|
|
||||||
|
|
||||||
begin_index = clipped_upper if reverse else clipped_lower
|
|
||||||
end_index = clipped_lower if reverse else clipped_upper
|
|
||||||
clones.append(weather_parameter.cloned_for(
|
|
||||||
new_reach,
|
|
||||||
sections[profiles[begin_index]],
|
|
||||||
sections[profiles[end_index]]
|
|
||||||
))
|
|
||||||
|
|
||||||
if clones:
|
|
||||||
self._lst.extend(clones)
|
|
||||||
self._status.modified()
|
|
||||||
|
|
||||||
@property
|
|
||||||
def Weather_Parameters_List(self):
|
|
||||||
return self.lst
|
|
||||||
|
|
||||||
@property
|
|
||||||
def default(self):
|
|
||||||
return self._default.copy()
|
|
||||||
|
|
||||||
def default_for_type(self, type):
|
|
||||||
for wp_default in self.default:
|
|
||||||
if wp_default.type == type:
|
|
||||||
return wp_default
|
|
||||||
return None
|
|
||||||
@@ -1,171 +0,0 @@
|
|||||||
# LateralContributionTypes.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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 Model.Except import NotImplementedMethodeError
|
|
||||||
|
|
||||||
from Model.WeatherParameters.WeatherParameters import WeatherParameters
|
|
||||||
|
|
||||||
|
|
||||||
class NotDefined(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(NotDefined, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "ND"
|
|
||||||
self._header = ["x", "y"]
|
|
||||||
|
|
||||||
@property
|
|
||||||
def _default_0(self):
|
|
||||||
return 0.0
|
|
||||||
|
|
||||||
|
|
||||||
class WeatherParam(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(WeatherParam, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "WP"
|
|
||||||
self._header = ["time", "value"]
|
|
||||||
self._types = [WeatherParam.time_convert, float]
|
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def compatibility(cls):
|
|
||||||
return ["liquid"]
|
|
||||||
|
|
||||||
|
|
||||||
class AirTemperature(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(AirTemperature, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "AT"
|
|
||||||
self._header = ["time", "temperature"]
|
|
||||||
self._types = [AirTemperature.time_convert, float]
|
|
||||||
|
|
||||||
|
|
||||||
class SpecificHumidity(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(SpecificHumidity, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "SH"
|
|
||||||
self._header = ["time", "humidity"]
|
|
||||||
self._types = [SpecificHumidity.time_convert, float]
|
|
||||||
|
|
||||||
|
|
||||||
class GlobalRadiation(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(GlobalRadiation, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "GR"
|
|
||||||
self._header = ["time", "radiation"]
|
|
||||||
self._types = [GlobalRadiation.time_convert, float]
|
|
||||||
|
|
||||||
|
|
||||||
class ReferenceWindSpeed(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(ReferenceWindSpeed, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "RWS"
|
|
||||||
self._header = ["time", "wind speed"]
|
|
||||||
self._types = [ReferenceWindSpeed.time_convert, float]
|
|
||||||
|
|
||||||
|
|
||||||
class GroundwaterTemperature(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(GroundwaterTemperature, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "GT"
|
|
||||||
self._header = ["time", "temperature"]
|
|
||||||
self._types = [GroundwaterTemperature.time_convert, float]
|
|
||||||
|
|
||||||
|
|
||||||
class GroundwaterFlowRate(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(GroundwaterFlowRate, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "GFR"
|
|
||||||
self._header = ["time", "discharge"]
|
|
||||||
self._types = [GroundwaterFlowRate.time_convert, float]
|
|
||||||
|
|
||||||
|
|
||||||
class Albedo(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(Albedo, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "ALB"
|
|
||||||
self._header = ["time", "albedo"]
|
|
||||||
self._types = [Albedo.time_convert, float]
|
|
||||||
|
|
||||||
|
|
||||||
class ShadingCoefficient(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(ShadingCoefficient, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "SC"
|
|
||||||
self._header = ["time", "shading coefficient"]
|
|
||||||
self._types = [ShadingCoefficient.time_convert, float]
|
|
||||||
|
|
||||||
|
|
||||||
class CloudCoverFraction(WeatherParameters):
|
|
||||||
def __init__(self, id: int = -1, name: str = "",
|
|
||||||
status=None, owner_scenario=-1):
|
|
||||||
super(CloudCoverFraction, self).__init__(
|
|
||||||
id=id, name=name, status=status,
|
|
||||||
owner_scenario=owner_scenario
|
|
||||||
)
|
|
||||||
|
|
||||||
self._type = "CCF"
|
|
||||||
self._header = ["time", "cloud cover fraction"]
|
|
||||||
self._types = [CloudCoverFraction.time_convert, float]
|
|
||||||
@@ -23,8 +23,6 @@ import tempfile
|
|||||||
from Model.Status import StudyStatus
|
from Model.Status import StudyStatus
|
||||||
from Model.Study import Study
|
from Model.Study import Study
|
||||||
from Model.River import River
|
from Model.River import River
|
||||||
from Model.LateralContribution.LateralContributionTypes import LateralContrib
|
|
||||||
from Model.HydraulicStructures.Basic.Types import DischargeWeir
|
|
||||||
|
|
||||||
|
|
||||||
class StudyTestCase(unittest.TestCase):
|
class StudyTestCase(unittest.TestCase):
|
||||||
@@ -64,31 +62,6 @@ class StudyTestCase(unittest.TestCase):
|
|||||||
study = Study.new("foo", "bar")
|
study = Study.new("foo", "bar")
|
||||||
self.assertNotEqual(study.river, None)
|
self.assertNotEqual(study.river, None)
|
||||||
|
|
||||||
def test_save_open_study_weather_parameters_default(self):
|
|
||||||
study = Study.new("foo", "bar")
|
|
||||||
defaults = study.river.weather_parameters.default
|
|
||||||
|
|
||||||
self.assertEqual(len(defaults), 9)
|
|
||||||
self.assertEqual(
|
|
||||||
[default.value for default in defaults],
|
|
||||||
[20.0, 0.001, 10.0, 1.0, 0.0, 0.0, 0.06, 0.15, 0.5]
|
|
||||||
)
|
|
||||||
defaults[0].value = 12.5
|
|
||||||
|
|
||||||
dir = tempfile.mkdtemp()
|
|
||||||
f = os.path.join(dir, "foo.pamhyr")
|
|
||||||
|
|
||||||
study.filename = f
|
|
||||||
study.save()
|
|
||||||
study.close()
|
|
||||||
|
|
||||||
study = Study.open(f)
|
|
||||||
defaults = study.river.weather_parameters.default
|
|
||||||
|
|
||||||
self.assertEqual(len(defaults), 9)
|
|
||||||
self.assertEqual(defaults[0].type, "AT")
|
|
||||||
self.assertEqual(defaults[0].value, 12.5)
|
|
||||||
|
|
||||||
|
|
||||||
class StudyScenarioTestCase(unittest.TestCase):
|
class StudyScenarioTestCase(unittest.TestCase):
|
||||||
def test_create_study(self):
|
def test_create_study(self):
|
||||||
@@ -289,89 +262,3 @@ class RiverTestCase(unittest.TestCase):
|
|||||||
edges = river.edges()
|
edges = river.edges()
|
||||||
self.assertEqual(edges[0], e0)
|
self.assertEqual(edges[0], e0)
|
||||||
self.assertEqual(edges[1], e1)
|
self.assertEqual(edges[1], e1)
|
||||||
|
|
||||||
def test_split_reach_splits_initial_conditions(self):
|
|
||||||
status = StudyStatus()
|
|
||||||
river = River(status=status)
|
|
||||||
node1 = river.add_node()
|
|
||||||
node2 = river.add_node(x=40.0)
|
|
||||||
reach = river.add_edge(node1, node2)
|
|
||||||
|
|
||||||
profiles = []
|
|
||||||
for index in range(5):
|
|
||||||
profile = reach.reach.insert(index)
|
|
||||||
profile.rk = index * 10.0
|
|
||||||
profile.insert(0)
|
|
||||||
profiles.append(profile)
|
|
||||||
|
|
||||||
initial_conditions = river.initial_conditions.get(reach)
|
|
||||||
for index, profile in enumerate(profiles):
|
|
||||||
data = initial_conditions.new_from_data(
|
|
||||||
profile.rk,
|
|
||||||
discharge=100.0 + index,
|
|
||||||
elevation=10.0 + index,
|
|
||||||
)
|
|
||||||
initial_conditions.insert(index, data)
|
|
||||||
|
|
||||||
reach1, reach2 = river._split_reach(reach, profiles[2])
|
|
||||||
conditions1 = river.initial_conditions.get(reach1).data
|
|
||||||
conditions2 = river.initial_conditions.get(reach2).data
|
|
||||||
|
|
||||||
self.assertEqual(
|
|
||||||
[data["discharge"] for data in conditions1],
|
|
||||||
[100.0, 101.0, 102.0]
|
|
||||||
)
|
|
||||||
self.assertEqual(
|
|
||||||
[data["discharge"] for data in conditions2],
|
|
||||||
[102.0, 103.0, 104.0]
|
|
||||||
)
|
|
||||||
self.assertEqual(
|
|
||||||
[data["section"] for data in conditions1],
|
|
||||||
reach1.reach.profiles
|
|
||||||
)
|
|
||||||
self.assertEqual(
|
|
||||||
[data["section"] for data in conditions2],
|
|
||||||
reach2.reach.profiles
|
|
||||||
)
|
|
||||||
self.assertTrue(all(
|
|
||||||
data._reach is reach1 for data in conditions1
|
|
||||||
))
|
|
||||||
self.assertTrue(all(
|
|
||||||
data._reach is reach2 for data in conditions2
|
|
||||||
))
|
|
||||||
|
|
||||||
def test_split_reach_keeps_partial_initial_conditions_in_scope(self):
|
|
||||||
status = StudyStatus()
|
|
||||||
river = River(status=status)
|
|
||||||
node1 = river.add_node()
|
|
||||||
node2 = river.add_node(x=40.0)
|
|
||||||
reach = river.add_edge(node1, node2)
|
|
||||||
|
|
||||||
profiles = []
|
|
||||||
for index in range(5):
|
|
||||||
profile = reach.reach.insert(index)
|
|
||||||
profile.rk = index * 10.0
|
|
||||||
profile.insert(0)
|
|
||||||
profiles.append(profile)
|
|
||||||
|
|
||||||
initial_conditions = river.initial_conditions.get(reach)
|
|
||||||
for index in (1, 3):
|
|
||||||
data = initial_conditions.new_from_data(
|
|
||||||
profiles[index].rk,
|
|
||||||
discharge=100.0 + index,
|
|
||||||
elevation=10.0 + index,
|
|
||||||
)
|
|
||||||
initial_conditions.insert(len(initial_conditions.data), data)
|
|
||||||
|
|
||||||
reach1, reach2 = river._split_reach(reach, profiles[2])
|
|
||||||
|
|
||||||
self.assertEqual(
|
|
||||||
[data["discharge"]
|
|
||||||
for data in river.initial_conditions.get(reach1).data],
|
|
||||||
[101.0]
|
|
||||||
)
|
|
||||||
self.assertEqual(
|
|
||||||
[data["discharge"]
|
|
||||||
for data in river.initial_conditions.get(reach2).data],
|
|
||||||
[103.0]
|
|
||||||
)
|
|
||||||
@@ -55,6 +55,7 @@ class Modules(IterableFlag):
|
|||||||
RESERVOIR = auto()
|
RESERVOIR = auto()
|
||||||
SEDIMENT_LAYER = auto()
|
SEDIMENT_LAYER = auto()
|
||||||
ADDITIONAL_FILES = auto()
|
ADDITIONAL_FILES = auto()
|
||||||
|
OUTPUT_RK = auto()
|
||||||
GEOTIFF = auto()
|
GEOTIFF = auto()
|
||||||
|
|
||||||
# Results
|
# Results
|
||||||
@@ -80,6 +81,7 @@ class Modules(IterableFlag):
|
|||||||
cls.ADDITIONAL_FILES,
|
cls.ADDITIONAL_FILES,
|
||||||
cls.RESULTS,
|
cls.RESULTS,
|
||||||
cls.WINDOW_LIST,
|
cls.WINDOW_LIST,
|
||||||
|
cls.OUTPUT_RK,
|
||||||
cls.GEOTIFF
|
cls.GEOTIFF
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
+2
-8
@@ -25,7 +25,6 @@ from PyQt5.QtCore import QProcess
|
|||||||
|
|
||||||
from Scripts.AScript import AScript
|
from Scripts.AScript import AScript
|
||||||
from Model.Study import Study
|
from Model.Study import Study
|
||||||
from View.RunSolver.Translate import RunSolverTranslate
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
logger = logging.getLogger()
|
||||||
|
|
||||||
@@ -76,8 +75,7 @@ class ScriptRun(AScript):
|
|||||||
os.path.dirname(study.filename),
|
os.path.dirname(study.filename),
|
||||||
"_PAMHYR_",
|
"_PAMHYR_",
|
||||||
study.name.replace(" ", "_"),
|
study.name.replace(" ", "_"),
|
||||||
solver.name.replace(" ", "_"),
|
solver.name.replace(" ", "_")
|
||||||
study.status.scenario.workdir(),
|
|
||||||
)
|
)
|
||||||
os.makedirs(workdir, exist_ok=True)
|
os.makedirs(workdir, exist_ok=True)
|
||||||
logger.info(f"Set working dir to {workdir}")
|
logger.info(f"Set working dir to {workdir}")
|
||||||
@@ -90,16 +88,12 @@ class ScriptRun(AScript):
|
|||||||
|
|
||||||
# Export and Run
|
# Export and Run
|
||||||
logger.info(f"~Export~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
logger.info(f"~Export~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
||||||
ok = solver.export(study, workdir, qlog=self._q)
|
solver.export(study, workdir, qlog=self._q)
|
||||||
|
|
||||||
while self._q.qsize() != 0:
|
while self._q.qsize() != 0:
|
||||||
s = self._q.get()
|
s = self._q.get()
|
||||||
logger.info(s)
|
logger.info(s)
|
||||||
|
|
||||||
if not ok:
|
|
||||||
logger.warning(RunSolverTranslate()["export_failed"])
|
|
||||||
return
|
|
||||||
|
|
||||||
if command == "run":
|
if command == "run":
|
||||||
logger.info(f"~Run~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
logger.info(f"~Run~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
|
||||||
solver.run(
|
solver.run(
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ class AbstractSolver(object):
|
|||||||
def default_parameters(cls):
|
def default_parameters(cls):
|
||||||
lst = [
|
lst = [
|
||||||
("all_init_time", "000:00:00:00"),
|
("all_init_time", "000:00:00:00"),
|
||||||
("all_final_time", "10:00:00:00"),
|
("all_final_time", "999:99:00:00"),
|
||||||
("all_timestep", "300.0"),
|
("all_timestep", "300.0"),
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
+60
-83
@@ -35,6 +35,10 @@ from Solver.CommandLine import CommandLineSolver
|
|||||||
from Model.Results.ResultsAdisTS import Results
|
from Model.Results.ResultsAdisTS import Results
|
||||||
from Model.Results.River.River import River, Reach, Profile
|
from Model.Results.River.River import River, Reach, Profile
|
||||||
|
|
||||||
|
from Checker.Adists import (
|
||||||
|
AdistsOutputRKChecker,
|
||||||
|
)
|
||||||
|
|
||||||
from itertools import chain
|
from itertools import chain
|
||||||
|
|
||||||
logger = logging.getLogger()
|
logger = logging.getLogger()
|
||||||
@@ -86,7 +90,11 @@ class AdisTS(CommandLineSolver):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def checkers(cls):
|
def checkers(cls):
|
||||||
return []
|
lst = [
|
||||||
|
AdistsOutputRKChecker(),
|
||||||
|
]
|
||||||
|
|
||||||
|
return lst
|
||||||
|
|
||||||
##########
|
##########
|
||||||
# Export #
|
# Export #
|
||||||
@@ -109,6 +117,9 @@ class AdisTS(CommandLineSolver):
|
|||||||
_nodes_names = {}
|
_nodes_names = {}
|
||||||
_nodes_views = set()
|
_nodes_views = set()
|
||||||
|
|
||||||
|
def get_reach_name(self, reach):
|
||||||
|
return f"Reach_{reach.pamhyr_id:>3}".replace(" ", "0")
|
||||||
|
|
||||||
def get_node_name(self, node):
|
def get_node_name(self, node):
|
||||||
"""Generate a 3 char name for node
|
"""Generate a 3 char name for node
|
||||||
|
|
||||||
@@ -171,7 +182,7 @@ class AdisTS(CommandLineSolver):
|
|||||||
# Write header
|
# Write header
|
||||||
edges = study.river.enable_edges()
|
edges = study.river.enable_edges()
|
||||||
for edge in edges:
|
for edge in edges:
|
||||||
name = self.get_reach_name(edge)
|
name = f"Reach_{edge.id + 1:>3}".replace(" ", "0")
|
||||||
|
|
||||||
with adists_file_open(
|
with adists_file_open(
|
||||||
os.path.join(repertory, "net", f"{name}.ST"),
|
os.path.join(repertory, "net", f"{name}.ST"),
|
||||||
@@ -180,7 +191,7 @@ class AdisTS(CommandLineSolver):
|
|||||||
files.append(str(os.path.join("net", f"{name}.ST")))
|
files.append(str(os.path.join("net", f"{name}.ST")))
|
||||||
|
|
||||||
cnt_num = 1
|
cnt_num = 1
|
||||||
for profile in edge.reach.enabled_profiles:
|
for profile in edge.reach.profiles:
|
||||||
self._export_ST_profile_header(
|
self._export_ST_profile_header(
|
||||||
f, files, profile, cnt_num
|
f, files, profile, cnt_num
|
||||||
)
|
)
|
||||||
@@ -266,7 +277,7 @@ class AdisTS(CommandLineSolver):
|
|||||||
edges = study.river.enable_edges()
|
edges = study.river.enable_edges()
|
||||||
|
|
||||||
for e in edges:
|
for e in edges:
|
||||||
name = self.get_reach_name(e)
|
name = f"Reach_{e.id + 1:>3}".replace(" ", "0")
|
||||||
id = name
|
id = name
|
||||||
|
|
||||||
n1 = f"{self.get_node_name(e.node1):3}".replace(" ", "x")
|
n1 = f"{self.get_node_name(e.node1):3}".replace(" ", "x")
|
||||||
@@ -335,7 +346,7 @@ class AdisTS(CommandLineSolver):
|
|||||||
|
|
||||||
return coeff.minor, coeff.medium
|
return coeff.minor, coeff.medium
|
||||||
|
|
||||||
for j, profile in enumerate(edge.reach.enabled_profiles):
|
for j, profile in enumerate(edge.reach.profiles):
|
||||||
coef_min, coef_moy = get_stricklers_from_rk(profile.rk,
|
coef_min, coef_moy = get_stricklers_from_rk(profile.rk,
|
||||||
lst)
|
lst)
|
||||||
f.write(
|
f.write(
|
||||||
@@ -355,19 +366,13 @@ class AdisTS(CommandLineSolver):
|
|||||||
if qlog is not None:
|
if qlog is not None:
|
||||||
qlog.put("Export REP file")
|
qlog.put("Export REP file")
|
||||||
|
|
||||||
mage_path = (mage_rep if os.path.isabs(mage_rep) else os.path.join(
|
|
||||||
os.path.abspath(os.path.join(repertory, os.pardir)),
|
|
||||||
mage_rep,
|
|
||||||
))
|
|
||||||
relative_mage_path = os.path.relpath(mage_path, repertory)
|
|
||||||
|
|
||||||
# Write header
|
# Write header
|
||||||
with adists_file_open(
|
with adists_file_open(
|
||||||
os.path.join(
|
os.path.join(
|
||||||
repertory, f"{name}.REP"
|
repertory, f"{name}.REP"
|
||||||
), "w+"
|
), "w+"
|
||||||
) as f:
|
) as f:
|
||||||
path = os.path.join(relative_mage_path, name)
|
path = os.path.join("..", mage_rep, name)
|
||||||
f.write(f"NET {name}.NET\n")
|
f.write(f"NET {name}.NET\n")
|
||||||
f.write(f"REP {path}.REP\n")
|
f.write(f"REP {path}.REP\n")
|
||||||
|
|
||||||
@@ -382,7 +387,9 @@ class AdisTS(CommandLineSolver):
|
|||||||
|
|
||||||
# fake mage_fin.ini:
|
# fake mage_fin.ini:
|
||||||
|
|
||||||
self._export_fake_INI(study, mage_path,
|
path_mage = os.path.join(os.path.abspath(
|
||||||
|
os.path.join(repertory, os.pardir)), mage_rep)
|
||||||
|
self._export_fake_INI(study, path_mage,
|
||||||
qlog, name=name)
|
qlog, name=name)
|
||||||
|
|
||||||
# path_mage_net = os.path.join(os.path.abspath(
|
# path_mage_net = os.path.join(os.path.abspath(
|
||||||
@@ -408,41 +415,6 @@ class AdisTS(CommandLineSolver):
|
|||||||
# RESULTS #
|
# RESULTS #
|
||||||
###########
|
###########
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _remove_temperature_results(repertory):
|
|
||||||
"""Remove temperature outputs generated but unused by AdisTS."""
|
|
||||||
results_directory = os.path.join(repertory, "resultats")
|
|
||||||
if not os.path.isdir(results_directory):
|
|
||||||
results_directory = repertory
|
|
||||||
|
|
||||||
if not os.path.isdir(results_directory):
|
|
||||||
return
|
|
||||||
|
|
||||||
for filename in os.listdir(results_directory):
|
|
||||||
if not (filename.startswith("TEM.") or
|
|
||||||
filename.startswith("TEM_")):
|
|
||||||
continue
|
|
||||||
|
|
||||||
filepath = os.path.join(results_directory, filename)
|
|
||||||
if os.path.isfile(filepath):
|
|
||||||
try:
|
|
||||||
os.remove(filepath)
|
|
||||||
logger.debug(
|
|
||||||
f"Removed unused AdisTS result '{filepath}'"
|
|
||||||
)
|
|
||||||
except OSError as error:
|
|
||||||
logger.warning(
|
|
||||||
f"Unable to remove AdisTS result '{filepath}': "
|
|
||||||
f"{error}"
|
|
||||||
)
|
|
||||||
|
|
||||||
def run_output_data_fomater(self, study):
|
|
||||||
# AdisTS generates temperature results that are not used by the solver,
|
|
||||||
# but they are still present in the output directory.
|
|
||||||
# Remove them to avoid confusion.
|
|
||||||
self._remove_temperature_results(self._process.workingDirectory())
|
|
||||||
return super(AdisTS, self).run_output_data_fomater(study)
|
|
||||||
|
|
||||||
def read_bin(self, study, repertory, results, qlog=None, name="0"):
|
def read_bin(self, study, repertory, results, qlog=None, name="0"):
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -481,8 +453,7 @@ class AdisTS(CommandLineSolver):
|
|||||||
_nodes_views = set()
|
_nodes_views = set()
|
||||||
|
|
||||||
def get_reach_name(self, reach):
|
def get_reach_name(self, reach):
|
||||||
index = self._study.river.get_edge_id(reach) + 1
|
return f"Reach_{reach.pamhyr_id:>3}".replace(" ", "0")
|
||||||
return f"Reach_{index:03d}"
|
|
||||||
|
|
||||||
#################################
|
#################################
|
||||||
# Adis-TS in weak coupling mode #
|
# Adis-TS in weak coupling mode #
|
||||||
@@ -536,13 +507,12 @@ class AdisTSwc(AdisTS):
|
|||||||
study, pollutant._data, f, qlog
|
study, pollutant._data, f, qlog
|
||||||
)
|
)
|
||||||
|
|
||||||
POL_ICs = next((
|
POL_ICs = next(filter(
|
||||||
ic for ic in
|
lambda ic: ic.pollutant == pollutant.id,
|
||||||
study.river.ic_adists.Initial_Conditions_List
|
study.river.ic_adists.Initial_Conditions_List
|
||||||
if ic.pollutant == pollutant.id
|
))
|
||||||
), None)
|
|
||||||
|
|
||||||
if POL_ICs is not None and POL_ICs.concentration is not None:
|
if POL_ICs.concentration is not None:
|
||||||
f.write(f"file_ini = {name}.INI\n")
|
f.write(f"file_ini = {name}.INI\n")
|
||||||
self._export_ICs_AdisTS(
|
self._export_ICs_AdisTS(
|
||||||
study, repertory, POL_ICs, qlog, name
|
study, repertory, POL_ICs, qlog, name
|
||||||
@@ -582,18 +552,15 @@ class AdisTSwc(AdisTS):
|
|||||||
os.path.join(repertory, f"{POL_name}.ALD"), "w+"
|
os.path.join(repertory, f"{POL_name}.ALD"), "w+"
|
||||||
) as f:
|
) as f:
|
||||||
for LC in POL_LC:
|
for LC in POL_LC:
|
||||||
reach = next((
|
reach = next(filter(
|
||||||
edge for edge in study.river.enable_edges()
|
lambda edge: edge.id == LC.edge, study.river.enable_edges()
|
||||||
if edge.id == LC.reach
|
)) # .name
|
||||||
), None)
|
|
||||||
if reach is None:
|
|
||||||
continue
|
|
||||||
reach_name = self.get_reach_name(reach)
|
reach_name = self.get_reach_name(reach)
|
||||||
f.write(f"${reach_name} {LC.begin_rk} {LC.end_rk}\n")
|
f.write(f"${reach_name} {LC.begin_rk} {LC.end_rk}\n")
|
||||||
f.write(f"*temps |débit massique (kg/s)\n")
|
f.write(f"*temps |débit massique (kg/s)\n")
|
||||||
f.write(f"*---------++++++++++\n")
|
f.write(f"*---------++++++++++\n")
|
||||||
|
|
||||||
for LC_data in LC.data:
|
for LC_data in LC._data:
|
||||||
tmp = timestamp_to_old_pamhyr_date_adists(int(LC_data[0]))
|
tmp = timestamp_to_old_pamhyr_date_adists(int(LC_data[0]))
|
||||||
f.write(" ".join((f"{tmp}",
|
f.write(" ".join((f"{tmp}",
|
||||||
f"{LC_data[1]}\n")))
|
f"{LC_data[1]}\n")))
|
||||||
@@ -610,10 +577,9 @@ class AdisTSwc(AdisTS):
|
|||||||
repertory, f"{POL_name}.CDT"), "w+"
|
repertory, f"{POL_name}.CDT"), "w+"
|
||||||
) as f:
|
) as f:
|
||||||
for BC in POL_BC:
|
for BC in POL_BC:
|
||||||
node = next((node for node in study.river.nodes()
|
node = next(filter(
|
||||||
if node.id == BC.node), None)
|
lambda x: x.id == BC.node, study.river._nodes
|
||||||
if node is None:
|
))
|
||||||
continue
|
|
||||||
f.write(f"${self.get_node_name(node)}\n")
|
f.write(f"${self.get_node_name(node)}\n")
|
||||||
|
|
||||||
if BC.type == "Concentration":
|
if BC.type == "Concentration":
|
||||||
@@ -625,7 +591,7 @@ class AdisTSwc(AdisTS):
|
|||||||
f.write(f"*JJ:HH:MM | (kg/s)\n")
|
f.write(f"*JJ:HH:MM | (kg/s)\n")
|
||||||
f.write(f"*---------++++++++++\n")
|
f.write(f"*---------++++++++++\n")
|
||||||
|
|
||||||
for BC_data in BC.data:
|
for BC_data in BC._data:
|
||||||
tmp = timestamp_to_old_pamhyr_date_adists(int(BC_data[0]))
|
tmp = timestamp_to_old_pamhyr_date_adists(int(BC_data[0]))
|
||||||
f.write(" ".join((f"{tmp}",
|
f.write(" ".join((f"{tmp}",
|
||||||
f"{BC_data[1]}\n")))
|
f"{BC_data[1]}\n")))
|
||||||
@@ -659,9 +625,6 @@ class AdisTSwc(AdisTS):
|
|||||||
|
|
||||||
edges = study.river.enable_edges()
|
edges = study.river.enable_edges()
|
||||||
for ic_spec in pol_ics_spec_data:
|
for ic_spec in pol_ics_spec_data:
|
||||||
if ic_spec.is_deleted():
|
|
||||||
continue
|
|
||||||
|
|
||||||
id_reach = ic_spec.reach
|
id_reach = ic_spec.reach
|
||||||
reach = next((x for x in edges if x.id == id_reach), None)
|
reach = next((x for x in edges if x.id == id_reach), None)
|
||||||
if reach is None:
|
if reach is None:
|
||||||
@@ -685,9 +648,7 @@ class AdisTSwc(AdisTS):
|
|||||||
list_characteristics = ["type", "diametre", "rho", "porosity",
|
list_characteristics = ["type", "diametre", "rho", "porosity",
|
||||||
"cdc_riv", "cdc_cas", "apd", "ac", "bc"]
|
"cdc_riv", "cdc_cas", "apd", "ac", "bc"]
|
||||||
|
|
||||||
pol_data = [data for data in pol_data if not data.is_deleted()]
|
if len(list_characteristics) <= (len(pol_data[0])):
|
||||||
|
|
||||||
if pol_data and len(list_characteristics) <= len(pol_data[0]):
|
|
||||||
for i in range(len(list_characteristics)):
|
for i in range(len(list_characteristics)):
|
||||||
f.write(f"{list_characteristics[i]} = {pol_data[0][i]}\n")
|
f.write(f"{list_characteristics[i]} = {pol_data[0][i]}\n")
|
||||||
|
|
||||||
@@ -716,9 +677,6 @@ class AdisTSwc(AdisTS):
|
|||||||
def _export_d90_spec(self, study, d90_spec_data, f, qlog, name="0"):
|
def _export_d90_spec(self, study, d90_spec_data, f, qlog, name="0"):
|
||||||
|
|
||||||
for d90_spec in d90_spec_data:
|
for d90_spec in d90_spec_data:
|
||||||
if d90_spec.is_deleted():
|
|
||||||
continue
|
|
||||||
|
|
||||||
if (d90_spec.name is None
|
if (d90_spec.name is None
|
||||||
or d90_spec.reach is None
|
or d90_spec.reach is None
|
||||||
or d90_spec.start_rk is None
|
or d90_spec.start_rk is None
|
||||||
@@ -778,9 +736,6 @@ class AdisTSwc(AdisTS):
|
|||||||
def _export_dif_spec(self, study, dif_spec_data, f, qlog, name="0"):
|
def _export_dif_spec(self, study, dif_spec_data, f, qlog, name="0"):
|
||||||
|
|
||||||
for dif_spec in dif_spec_data:
|
for dif_spec in dif_spec_data:
|
||||||
if dif_spec.is_deleted():
|
|
||||||
continue
|
|
||||||
|
|
||||||
if (dif_spec.reach is None
|
if (dif_spec.reach is None
|
||||||
or dif_spec.start_rk is None
|
or dif_spec.start_rk is None
|
||||||
or dif_spec.end_rk is None
|
or dif_spec.end_rk is None
|
||||||
@@ -848,8 +803,33 @@ class AdisTSwc(AdisTS):
|
|||||||
if name != "command_line_arguments":
|
if name != "command_line_arguments":
|
||||||
f.write(f"{dict_names[name]} = {value}\n")
|
f.write(f"{dict_names[name]} = {value}\n")
|
||||||
|
|
||||||
|
outputrks = study.river.Output_rk_adists.OutputRK_List
|
||||||
|
|
||||||
|
for outputrk in outputrks:
|
||||||
|
self._export_outputrk(study, outputrk, f, qlog)
|
||||||
|
|
||||||
return files
|
return files
|
||||||
|
|
||||||
|
def _export_outputrk(self, study, outputrk, f, qlog, name="0"):
|
||||||
|
if (outputrk.reach is None
|
||||||
|
or outputrk.rk is None
|
||||||
|
or outputrk.title is None):
|
||||||
|
return
|
||||||
|
|
||||||
|
edges = study.river.enable_edges()
|
||||||
|
|
||||||
|
id_edges = list(map(lambda x: x.id, edges))
|
||||||
|
|
||||||
|
id_reach = outputrk.reach
|
||||||
|
reach = next((x for x in edges if x.id == id_reach), None)
|
||||||
|
rk = outputrk.rk
|
||||||
|
title = outputrk.title
|
||||||
|
|
||||||
|
if reach is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
f.write(f"output = {study.river.get_edge_id(reach)+1} {rk} {title}\n")
|
||||||
|
|
||||||
@timer
|
@timer
|
||||||
def read_bin(self, study, repertory, results, qlog=None, name="0"):
|
def read_bin(self, study, repertory, results, qlog=None, name="0"):
|
||||||
|
|
||||||
@@ -896,10 +876,7 @@ class AdisTSwc(AdisTS):
|
|||||||
|
|
||||||
for i in range(ibmax):
|
for i in range(ibmax):
|
||||||
# Add results reach to reach list
|
# Add results reach to reach list
|
||||||
geometry_reach = study.river.enable_edges()[i].reach
|
r = results.river.add(i)
|
||||||
r = results.river.add(
|
|
||||||
i, profiles=geometry_reach.enabled_profiles
|
|
||||||
)
|
|
||||||
reachs.append(r)
|
reachs.append(r)
|
||||||
|
|
||||||
is1[i] = data[2 * i] - 1 # first section of reach i
|
is1[i] = data[2 * i] - 1 # first section of reach i
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -19,9 +19,8 @@
|
|||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime
|
||||||
from tools import timer, parse_command_line, get_version, logger_exception
|
from tools import timer, parse_command_line, get_version, logger_exception
|
||||||
from tools import parse_datetime
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
# Installation allow Unix-like signal
|
# Installation allow Unix-like signal
|
||||||
@@ -159,15 +158,11 @@ class CommandLineSolver(AbstractSolver):
|
|||||||
txt = add_file.text
|
txt = add_file.text
|
||||||
txt = txt.replace("@version", get_version())
|
txt = txt.replace("@version", get_version())
|
||||||
txt = txt.replace("@date", datetime.now().isoformat(sep=" "))
|
txt = txt.replace("@date", datetime.now().isoformat(sep=" "))
|
||||||
txt = self._prepare_additional_file_text(add_file.path, txt)
|
|
||||||
|
|
||||||
f.write(txt)
|
f.write(txt)
|
||||||
|
|
||||||
return files
|
return files
|
||||||
|
|
||||||
def _prepare_additional_file_text(self, path, text):
|
|
||||||
return text
|
|
||||||
|
|
||||||
def export_study_description(self, study, repertory, qlog, name="0"):
|
def export_study_description(self, study, repertory, qlog, name="0"):
|
||||||
files = []
|
files = []
|
||||||
|
|
||||||
|
|||||||
+257
-65
@@ -65,8 +65,6 @@ class Mage(CommandLineSolver):
|
|||||||
self._cmd_solver = "@path @input -o @output"
|
self._cmd_solver = "@path @input -o @output"
|
||||||
self._cmd_output = ""
|
self._cmd_output = ""
|
||||||
|
|
||||||
self._reset_node_names()
|
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def default_parameters(cls):
|
def default_parameters(cls):
|
||||||
lst = super(Mage, cls).default_parameters()
|
lst = super(Mage, cls).default_parameters()
|
||||||
@@ -127,15 +125,12 @@ class Mage(CommandLineSolver):
|
|||||||
|
|
||||||
_l_alph = len(_alph)
|
_l_alph = len(_alph)
|
||||||
|
|
||||||
def _reset_node_names(self):
|
_nodes_cnt = 0
|
||||||
"""Reset the node-name registry for a new export."""
|
_nodes_names = {}
|
||||||
self._nodes_cnt = 0
|
_nodes_views = set()
|
||||||
self._nodes_names = {}
|
|
||||||
self._nodes_views = set()
|
|
||||||
|
|
||||||
def get_reach_name(self, reach):
|
def get_reach_name(self, reach):
|
||||||
index = self._study.river.get_edge_id(reach) + 1
|
return f"Reach_{reach.pamhyr_id:>3}".replace(" ", "0")
|
||||||
return f"Reach_{index:03d}"
|
|
||||||
|
|
||||||
def get_node_name(self, node):
|
def get_node_name(self, node):
|
||||||
"""Generate a 3 char name for node
|
"""Generate a 3 char name for node
|
||||||
@@ -215,7 +210,7 @@ class Mage(CommandLineSolver):
|
|||||||
# Write header
|
# Write header
|
||||||
edges = study.river.enable_edges()
|
edges = study.river.enable_edges()
|
||||||
for edge in edges:
|
for edge in edges:
|
||||||
name = self.get_reach_name(edge)
|
name = f"Reach_{edge.pamhyr_id:>3}".replace(" ", "0")
|
||||||
|
|
||||||
with mage_file_open(
|
with mage_file_open(
|
||||||
os.path.join(repertory, "net", f"{name}.ST"),
|
os.path.join(repertory, "net", f"{name}.ST"),
|
||||||
@@ -224,7 +219,7 @@ class Mage(CommandLineSolver):
|
|||||||
files.append(str(os.path.join("net", f"{name}.ST")))
|
files.append(str(os.path.join("net", f"{name}.ST")))
|
||||||
|
|
||||||
cnt_num = 1
|
cnt_num = 1
|
||||||
for profile in edge.reach.enabled_profiles:
|
for profile in edge.reach.profiles:
|
||||||
self._export_ST_profile_header(
|
self._export_ST_profile_header(
|
||||||
f, files, profile, cnt_num
|
f, files, profile, cnt_num
|
||||||
)
|
)
|
||||||
@@ -303,7 +298,7 @@ class Mage(CommandLineSolver):
|
|||||||
# Point line
|
# Point line
|
||||||
wfile.write(f"{x} {y} {z} {n} {sediment}\n")
|
wfile.write(f"{x} {y} {z} {n} {sediment}\n")
|
||||||
|
|
||||||
def _export_BC(self, study, t, bounds, repertory, qlog, name="0"):
|
def _export_BC(self, t, bounds, repertory, qlog, name="0"):
|
||||||
files = []
|
files = []
|
||||||
|
|
||||||
if len(bounds) == 0:
|
if len(bounds) == 0:
|
||||||
@@ -333,7 +328,7 @@ class Mage(CommandLineSolver):
|
|||||||
v1 = d[1]
|
v1 = d[1]
|
||||||
|
|
||||||
if t in ["HYD", "LIM"]:
|
if t in ["HYD", "LIM"]:
|
||||||
v0 /= 60 # Convert first column to minutes
|
v0 /= 60 # Convert first column to minute
|
||||||
|
|
||||||
f.write(f"{v0:9} {v1:9} \n")
|
f.write(f"{v0:9} {v1:9} \n")
|
||||||
|
|
||||||
@@ -365,17 +360,10 @@ class Mage(CommandLineSolver):
|
|||||||
elif bound.bctype == "SL":
|
elif bound.bctype == "SL":
|
||||||
QSO.append(bound)
|
QSO.append(bound)
|
||||||
|
|
||||||
files = files + self._export_BC(
|
files = files + self._export_BC("AVA", AVA, repertory, qlog, name=name)
|
||||||
study, "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_BC(
|
files = files + self._export_QSO(QSO, repertory, qlog, name=name)
|
||||||
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
|
return files
|
||||||
|
|
||||||
@@ -429,11 +417,10 @@ class Mage(CommandLineSolver):
|
|||||||
if d.is_deleted():
|
if d.is_deleted():
|
||||||
continue
|
continue
|
||||||
|
|
||||||
time = d[0]
|
|
||||||
if lateral.lctype in ["EV"]:
|
if lateral.lctype in ["EV"]:
|
||||||
f.write(f"{time:10.3f}{-d[1]:10.3f}\n")
|
f.write(f"{d[0]:10.3f}{-d[1]:10.3f}\n")
|
||||||
else:
|
else:
|
||||||
f.write(f"{time:10.3f}{d[1]:10.3f}\n")
|
f.write(f"{d[0]:10.3f}{d[1]:10.3f}\n")
|
||||||
|
|
||||||
def _export_RUG(self, study, repertory, qlog, name="0"):
|
def _export_RUG(self, study, repertory, qlog, name="0"):
|
||||||
files = []
|
files = []
|
||||||
@@ -497,12 +484,7 @@ class Mage(CommandLineSolver):
|
|||||||
if cond.is_deleted():
|
if cond.is_deleted():
|
||||||
continue
|
continue
|
||||||
|
|
||||||
enabled_profiles = set(reach.reach.enabled_profiles)
|
data = cond.data
|
||||||
data = [
|
|
||||||
item for item in cond.data
|
|
||||||
if not item.is_deleted()
|
|
||||||
and item["section"] in enabled_profiles
|
|
||||||
]
|
|
||||||
if len(data) == 0:
|
if len(data) == 0:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
@@ -510,6 +492,9 @@ class Mage(CommandLineSolver):
|
|||||||
|
|
||||||
id_sec = 1
|
id_sec = 1
|
||||||
for d in data:
|
for d in data:
|
||||||
|
if d.is_deleted():
|
||||||
|
continue
|
||||||
|
|
||||||
IR = f"{id}"
|
IR = f"{id}"
|
||||||
IS = f"{id_sec}"
|
IS = f"{id_sec}"
|
||||||
discharge = f"{d['discharge']:>10.5f}"
|
discharge = f"{d['discharge']:>10.5f}"
|
||||||
@@ -694,23 +679,6 @@ class Mage(CommandLineSolver):
|
|||||||
|
|
||||||
return res
|
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"):
|
def _export_VAR(self, study, repertory, qlog, name="0"):
|
||||||
files = []
|
files = []
|
||||||
|
|
||||||
@@ -761,11 +729,9 @@ class Mage(CommandLineSolver):
|
|||||||
name = bhs.name
|
name = bhs.name
|
||||||
if name == "":
|
if name == "":
|
||||||
name = f"HS_{bhs.id:>3}".replace(" ", "0")
|
name = f"HS_{bhs.id:>3}".replace(" ", "0")
|
||||||
else:
|
|
||||||
name = name.replace(" ", "_")
|
|
||||||
|
|
||||||
f.write(
|
f.write(
|
||||||
f"${name} clapet\n"
|
f"${name} clapet"
|
||||||
)
|
)
|
||||||
return files
|
return files
|
||||||
|
|
||||||
@@ -991,7 +957,7 @@ class Mage8(Mage):
|
|||||||
|
|
||||||
return files
|
return files
|
||||||
|
|
||||||
def _export_QSO(self, study, bounds, repertory, qlog, name="0"):
|
def _export_QSO(self, bounds, repertory, qlog, name="0"):
|
||||||
files = []
|
files = []
|
||||||
|
|
||||||
if len(bounds) == 0:
|
if len(bounds) == 0:
|
||||||
@@ -1021,8 +987,7 @@ class Mage8(Mage):
|
|||||||
|
|
||||||
# Data
|
# Data
|
||||||
for d in bound.data:
|
for d in bound.data:
|
||||||
time = d[0] / 60
|
f.write(f"{d[0]/60:10.3f}{d[1]:10.3f}\n")
|
||||||
f.write(f"{time:10.3f}{d[1]:10.3f}\n")
|
|
||||||
|
|
||||||
return files
|
return files
|
||||||
|
|
||||||
@@ -1039,7 +1004,6 @@ class Mage8(Mage):
|
|||||||
@timer
|
@timer
|
||||||
def export(self, study, repertory, qlog=None, name="0"):
|
def export(self, study, repertory, qlog=None, name="0"):
|
||||||
self._study = study
|
self._study = study
|
||||||
self._reset_node_names()
|
|
||||||
name = study.name.replace(" ", "_")
|
name = study.name.replace(" ", "_")
|
||||||
|
|
||||||
# Define GRA file name
|
# Define GRA file name
|
||||||
@@ -1063,6 +1027,75 @@ class Mage8(Mage):
|
|||||||
logger_exception(e)
|
logger_exception(e)
|
||||||
return False
|
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 #
|
# RESULTS #
|
||||||
###########
|
###########
|
||||||
@@ -1127,10 +1160,7 @@ class Mage8(Mage):
|
|||||||
|
|
||||||
for i in range(nb_reach):
|
for i in range(nb_reach):
|
||||||
# Add results reach to reach list
|
# Add results reach to reach list
|
||||||
geometry_reach = study.river.enable_edges()[i].reach
|
r = results.river.reach(i)
|
||||||
r = results.river.add(
|
|
||||||
i, profiles=geometry_reach.enabled_profiles
|
|
||||||
)
|
|
||||||
reachs.append(r)
|
reachs.append(r)
|
||||||
|
|
||||||
# ID of first and last reach profiles
|
# ID of first and last reach profiles
|
||||||
@@ -1435,10 +1465,7 @@ class Mage8(Mage):
|
|||||||
zfd_lst = []
|
zfd_lst = []
|
||||||
|
|
||||||
for r in reachs:
|
for r in reachs:
|
||||||
z_min = [
|
z_min = r.geometry.get_z_min()
|
||||||
profile.geometry.z_min()
|
|
||||||
for profile in r.profiles
|
|
||||||
]
|
|
||||||
sls = map(
|
sls = map(
|
||||||
lambda p: p.get_ts_key(ts_list[0], "sl")[0],
|
lambda p: p.get_ts_key(ts_list[0], "sl")[0],
|
||||||
r.profiles
|
r.profiles
|
||||||
@@ -1493,6 +1520,171 @@ class Mage8(Mage):
|
|||||||
|
|
||||||
return results
|
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):
|
class MageFake7(Mage8):
|
||||||
_type = "mage_fake7"
|
_type = "mage_fake7"
|
||||||
|
|||||||
+106
-261
@@ -18,14 +18,11 @@
|
|||||||
|
|
||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
import math
|
|
||||||
from decimal import Decimal, InvalidOperation, localcontext
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
from tools import timer, trace, old_pamhyr_date_to_timestamp, logger_exception
|
from tools import timer, trace, old_pamhyr_date_to_timestamp, logger_exception
|
||||||
|
|
||||||
from Solver.CommandLine import CommandLineSolver
|
from Solver.CommandLine import CommandLineSolver
|
||||||
from View.RunSolver.Translate import RunSolverTranslate
|
|
||||||
|
|
||||||
from Model.Results.Results import Results
|
from Model.Results.Results import Results
|
||||||
from Model.Results.River.River import River, Reach, Profile
|
from Model.Results.River.River import River, Reach, Profile
|
||||||
@@ -47,7 +44,7 @@ class Rubar3(CommandLineSolver):
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def default_parameters(cls):
|
def default_parameters(cls):
|
||||||
# Keep historical rubarbe_* keys for existing Rubar3 studies.
|
# lst = super(Rubar3, cls).default_parameters()
|
||||||
|
|
||||||
lst = [
|
lst = [
|
||||||
("rubarbe_cfl", "0.50000E+00"),
|
("rubarbe_cfl", "0.50000E+00"),
|
||||||
@@ -55,13 +52,13 @@ class Rubar3(CommandLineSolver):
|
|||||||
("rubarbe_condav", "3"),
|
("rubarbe_condav", "3"),
|
||||||
("rubarbe_regime", "0"),
|
("rubarbe_regime", "0"),
|
||||||
("rubarbe_iodev", "n"),
|
("rubarbe_iodev", "n"),
|
||||||
("rubarbe_iodebord", "o"),
|
("rubarbe_iodebord", ""),
|
||||||
("rubarbe_iostockage", "o"),
|
("rubarbe_iostockage", ""),
|
||||||
("rubarbe_iopdt", "y"),
|
("rubarbe_iopdt", "y"),
|
||||||
("rubarbe_iovis", "n"),
|
("rubarbe_iovis", "n"),
|
||||||
("rubarbe_rep", "n"),
|
("rubarbe_rep", "n"),
|
||||||
("rubarbe_tinit", "000:00:00:00"),
|
("rubarbe_tinit", "000:00:00:00"),
|
||||||
("rubarbe_tmax", "001:00:00:00"), # 1 day
|
("rubarbe_tmax", "000:01:00:00"), # 1 day
|
||||||
("rubarbe_tiopdt", "000:00:00:00"),
|
("rubarbe_tiopdt", "000:00:00:00"),
|
||||||
("rubarbe_dt", "5.0"),
|
("rubarbe_dt", "5.0"),
|
||||||
("rubarbe_ts", "999:99:99:00"),
|
("rubarbe_ts", "999:99:99:00"),
|
||||||
@@ -92,8 +89,8 @@ class Rubar3(CommandLineSolver):
|
|||||||
("rubarbe_sediment_mult_3", ""),
|
("rubarbe_sediment_mult_3", ""),
|
||||||
("rubarbe_sediment_mult_4", ""),
|
("rubarbe_sediment_mult_4", ""),
|
||||||
("rubarbe_sediment_mult_5", ""),
|
("rubarbe_sediment_mult_5", ""),
|
||||||
("rubarbe_sediment_visc", "1.3E-06"),
|
("rubarbe_sediment_visc", "0.047"),
|
||||||
("rubarbe_sediment_opts", "3"),
|
("rubarbe_sediment_opts", "6"),
|
||||||
("rubarbe_sediment_odchar", "0"),
|
("rubarbe_sediment_odchar", "0"),
|
||||||
("rubarbe_sediment_unisol", "1"),
|
("rubarbe_sediment_unisol", "1"),
|
||||||
("rubarbe_sediment_typdef", "3"),
|
("rubarbe_sediment_typdef", "3"),
|
||||||
@@ -143,34 +140,8 @@ class Rubar3(CommandLineSolver):
|
|||||||
self._study = study
|
self._study = study
|
||||||
name = study.name.replace(" ", "_")
|
name = study.name.replace(" ", "_")
|
||||||
|
|
||||||
values = self._parameter_values(study)
|
|
||||||
if (values.get("rubarbe_regime") == "1" and
|
|
||||||
values.get("rubarbe_condam") == "0"):
|
|
||||||
trad = RunSolverTranslate()
|
|
||||||
message = trad["incompatible_upstream_boundary"]
|
|
||||||
logger.warning(message)
|
|
||||||
if qlog is not None:
|
|
||||||
qlog.put(trad["warning"].format(message=message))
|
|
||||||
return False
|
|
||||||
|
|
||||||
trased = self._parameter_flag(study, "trased") == "O"
|
|
||||||
if trased:
|
|
||||||
# Notice §3.6: HYDROS is required at each upstream boundary
|
|
||||||
missing = self._reaches_without_solid_boundary(study)
|
|
||||||
if missing:
|
|
||||||
trad = RunSolverTranslate()
|
|
||||||
message = trad["missing_solid_boundary"].format(
|
|
||||||
reaches=", ".join(missing)
|
|
||||||
)
|
|
||||||
logger.warning(message)
|
|
||||||
if qlog is not None:
|
|
||||||
qlog.put(trad["warning"].format(message=message))
|
|
||||||
return False
|
|
||||||
|
|
||||||
self._export_donnee(study, repertory, qlog, name=name)
|
self._export_donnee(study, repertory, qlog, name=name)
|
||||||
if trased:
|
self._export_ts(study, repertory, qlog, name=name)
|
||||||
if not self._export_ts(study, repertory, qlog, name=name):
|
|
||||||
return False
|
|
||||||
self._export_geomac_i(study, repertory, qlog, name=name)
|
self._export_geomac_i(study, repertory, qlog, name=name)
|
||||||
self._export_mail(study, repertory, qlog, name=name)
|
self._export_mail(study, repertory, qlog, name=name)
|
||||||
self._export_devers(study, repertory, qlog, name=name)
|
self._export_devers(study, repertory, qlog, name=name)
|
||||||
@@ -182,205 +153,108 @@ class Rubar3(CommandLineSolver):
|
|||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# Notice Rubar3/RubarBE, annex 1: records are positional, not keyed.
|
def _export_donnee(self, study, repertory, qlog, name="0"):
|
||||||
# Each record starts with an A50 label, including records of integers.
|
|
||||||
_donnee_fields = (
|
|
||||||
("cfl", "real"),
|
|
||||||
("condam", "integer"), ("condav", "integer"),
|
|
||||||
("regime", "integer"), ("iodev", "flags"),
|
|
||||||
("iopdt", "flag"), ("iovis", "flag"), ("rep", "flag"),
|
|
||||||
("tinit", "time"), ("tmax", "time"), ("tiopdt", "time"),
|
|
||||||
("dt", "real"), ("ts", "time"), ("dtsauv", "time"),
|
|
||||||
("psave", "time"), ("fdeb1", "real"), ("fdeb2", "real"),
|
|
||||||
("fdeb3", "real"),
|
|
||||||
("tf_1", "flag"), ("tf_2", "flag"), ("tf_3", "flag"),
|
|
||||||
("tf_4", "flag"), ("tf_5", "flag"), ("tf_6", "flag"),
|
|
||||||
("trased", "flag"),
|
|
||||||
)
|
|
||||||
_ts_fields = (
|
|
||||||
("ros", "real"), ("por", "real"), ("dcharg", "real"),
|
|
||||||
("halfa", "real"), ("mult_1", "multipliers"),
|
|
||||||
("visc", "real"), ("opts", "law"), ("odchar", "integer"),
|
|
||||||
("unisol", "integer"), ("typdef", "integer"),
|
|
||||||
("depot", "depot"), ("choixc", "integer"),
|
|
||||||
("option", "options"), ("capsol", "integer"),
|
|
||||||
("bmiu", "real"), ("demix", "integer"),
|
|
||||||
("defond", "integer"), ("varcons", "integer"),
|
|
||||||
)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _reaches_without_solid_boundary(study):
|
|
||||||
river = study.river
|
|
||||||
solid = [
|
|
||||||
bc for bc in river.boundary_condition.get_tab("solid")
|
|
||||||
if not bc.is_deleted() and bc.bctype == "SL" and len(bc) > 0
|
|
||||||
]
|
|
||||||
|
|
||||||
return [
|
|
||||||
edge.name for edge in river.enable_edges()
|
|
||||||
if river.is_upstream_node(edge.node1)
|
|
||||||
and not any(bc.node == edge.node1 for bc in solid)
|
|
||||||
]
|
|
||||||
|
|
||||||
def _parameter_values(self, study):
|
|
||||||
return {p.name: str(p.value).strip()
|
|
||||||
for p in study.river.get_params(self.type).parameters}
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _required(values, key):
|
|
||||||
value = values.get(key, "")
|
|
||||||
if not value:
|
|
||||||
raise ValueError(f"Missing Rubar parameter: {key}")
|
|
||||||
return value
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _flag(value, key, mixed=False):
|
|
||||||
result = value.upper()
|
|
||||||
if result == "Y":
|
|
||||||
result = "O"
|
|
||||||
if result not in (("O", "N", "M") if mixed else ("O", "N")):
|
|
||||||
raise ValueError(f"{key}: expected O/Y or N" +
|
|
||||||
(" or M" if mixed else ""))
|
|
||||||
return result
|
|
||||||
|
|
||||||
def _parameter_flag(self, study, suffix):
|
|
||||||
key = "rubarbe_" + suffix
|
|
||||||
return self._flag(self._required(self._parameter_values(study), key),
|
|
||||||
key)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _integer(value, key, width=1):
|
|
||||||
if not value.isascii() or not value.isdigit() or len(value) > width:
|
|
||||||
raise ValueError(f"{key}: expected an integer in {width} columns")
|
|
||||||
return value.rjust(width)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _real(value, key, scientific=False):
|
|
||||||
try:
|
|
||||||
number = Decimal(value.replace("d", "E").replace("D", "E"))
|
|
||||||
except InvalidOperation:
|
|
||||||
raise ValueError(f"{key}: invalid real value {value!r}") from None
|
|
||||||
if not number.is_finite():
|
|
||||||
raise ValueError(f"{key}: expected a finite real value")
|
|
||||||
if scientific:
|
|
||||||
# DONNEE: E12.5. Reject overflow instead of shifting columns.
|
|
||||||
floating = float(number)
|
|
||||||
if not math.isfinite(floating) or (number and floating == 0):
|
|
||||||
raise ValueError(f"{key}: real value outside E12.5 range")
|
|
||||||
result = f"{floating:12.5E}"
|
|
||||||
width = 12
|
|
||||||
else:
|
|
||||||
# TS: F10.0 input accepts an explicit decimal point/exponent.
|
|
||||||
# Preserve the value exactly; do not round porosity etc. to int.
|
|
||||||
with localcontext() as context:
|
|
||||||
context.prec = max(28, len(number.as_tuple().digits))
|
|
||||||
number = number.normalize()
|
|
||||||
result = str(number).upper()
|
|
||||||
if len(result) > 10:
|
|
||||||
result = format(number, "E")
|
|
||||||
width = 10
|
|
||||||
if len(result) > width:
|
|
||||||
raise ValueError(f"{key}: value {value!r} exceeds {width} columns")
|
|
||||||
return result.rjust(width)
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _write_parameters(repertory, filename, lines):
|
|
||||||
# Validate all records before opening/truncating the destination.
|
|
||||||
path = os.path.join(repertory, filename)
|
|
||||||
with open(path, "w", encoding="ascii") as f:
|
|
||||||
f.writelines(lines)
|
|
||||||
|
|
||||||
def _export_donnee(self, study, repertory, qlog=None, name="0"):
|
|
||||||
values = self._parameter_values(study)
|
|
||||||
fields = list(self._donnee_fields)
|
|
||||||
# The diagnostic transport-capacity extension is optional as a block.
|
|
||||||
if values.get("rubarbe_optfpc", ""):
|
|
||||||
fields += [("optfpc", "integer"), ("ros", "real"),
|
|
||||||
("dm", "real"), ("segma", "real")]
|
|
||||||
elif any(values.get("rubarbe_" + key, "")
|
|
||||||
for key in ("ros", "dm", "segma")):
|
|
||||||
raise ValueError("rubarbe_optfpc: required before ROS/DM/SEGMA")
|
|
||||||
lines = []
|
|
||||||
for suffix, kind in fields:
|
|
||||||
key = "rubarbe_" + suffix
|
|
||||||
value = self._required(values, key)
|
|
||||||
if kind == "integer":
|
|
||||||
result = self._integer(value, key)
|
|
||||||
elif kind in ("flag", "flags"):
|
|
||||||
result = self._flag(value, key, mixed=suffix == "iopdt")
|
|
||||||
if kind == "flags":
|
|
||||||
# Missing optional flags mean O (notice section 3.1).
|
|
||||||
# Write both explicitly so STOCKAGE cannot shift left.
|
|
||||||
for extra in ("iodebord", "iostockage"):
|
|
||||||
extra_key = "rubarbe_" + extra
|
|
||||||
result += self._flag(values.get(extra_key) or "O",
|
|
||||||
extra_key)
|
|
||||||
else:
|
|
||||||
if kind == "time" and ":" in value:
|
|
||||||
parts = value.split(":")
|
|
||||||
if len(parts) != 4 or not all(p.isdigit() for p in parts):
|
|
||||||
raise ValueError(
|
|
||||||
f"{key}: expected days:hours:minutes:seconds")
|
|
||||||
value = str(old_pamhyr_date_to_timestamp(value))
|
|
||||||
result = self._real(value, key, scientific=True)
|
|
||||||
lines.append(f"{key:<50}{result}\n")
|
|
||||||
if qlog is not None:
|
if qlog is not None:
|
||||||
qlog.put("Export DONNEE file")
|
qlog.put("Export DONNEE file")
|
||||||
self._write_parameters(repertory, f"donnee.{name}", lines)
|
|
||||||
|
|
||||||
def _export_ts(self, study, repertory, qlog=None, name="0"):
|
with open(
|
||||||
trad = RunSolverTranslate()
|
os.path.join(
|
||||||
values = self._parameter_values(study)
|
repertory, f"donnee.{name}"
|
||||||
prefix = "rubarbe_sediment_"
|
), "w+"
|
||||||
fields = list(self._ts_fields)
|
) as f:
|
||||||
demix = self._required(values, prefix + "demix")
|
params = filter(
|
||||||
if demix not in ("0", "1"):
|
lambda p: "rubarbe_sediment_" not in p.name,
|
||||||
raise ValueError(f"{prefix}demix: expected 0 or 1")
|
study.river.get_params(self._type).parameters
|
||||||
if demix == "1":
|
)
|
||||||
fields += [("dchard", "real"), ("dchars", "real")]
|
|
||||||
lines = []
|
it = iter(params)
|
||||||
for suffix, kind in fields:
|
|
||||||
key = prefix + suffix
|
param = next(it, None)
|
||||||
value = self._required(values, key)
|
while param is not None:
|
||||||
if kind == "real":
|
name = param.name
|
||||||
result = self._real(value, key)
|
value = param.value
|
||||||
elif kind == "multipliers":
|
|
||||||
result = self._real(value, key)
|
if "all_" in name:
|
||||||
extras = [values.get(prefix + f"mult_{i}", "")
|
continue
|
||||||
for i in range(2, 6)]
|
|
||||||
# Preserve empty interior F10.0 fields; omit trailing fields
|
if value != "":
|
||||||
# to retain the solver's defaults for optional coefficients.
|
# Value format
|
||||||
while extras and not extras[-1]:
|
if value.count(':') == 3:
|
||||||
extras.pop()
|
value = old_pamhyr_date_to_timestamp(value)
|
||||||
for i, extra in enumerate(extras, 2):
|
value = f"{value:>12.5e}".upper()
|
||||||
result += (self._real(extra, prefix + f"mult_{i}")
|
|
||||||
if extra else " " * 10)
|
if value.count('.') == 1:
|
||||||
elif kind == "options":
|
value = f"{float(value):>12.5e}".upper()
|
||||||
if len(value) != 3 or any(c not in "12" for c in value):
|
|
||||||
message = trad["invalid_options"].format(key=key)
|
if value == "y" or value == "n":
|
||||||
logger.warning(message)
|
value = "O" if value == "y" else "N"
|
||||||
if qlog is not None:
|
|
||||||
qlog.put(trad["warning"].format(message=message))
|
# Write value
|
||||||
return False
|
f.write(f"{name:<50}{value}")
|
||||||
result = value
|
|
||||||
elif kind == "law":
|
# Add values of 'rubarbe_iodebord' and
|
||||||
# Notice section 3.10 / 8.7: 4--7 are not listed.
|
# 'rubarbe_iostockage'
|
||||||
if value not in {str(i) for i in [1, 2, 3, *range(8, 31)]}:
|
if name == "rubarbe_iodev":
|
||||||
message = trad["unsupported_transport_law"].format(
|
v2 = next(it).value
|
||||||
key=key, value=value)
|
v3 = next(it).value
|
||||||
logger.warning(message)
|
|
||||||
if qlog is not None:
|
# f.write(f"{v2}{v3}")
|
||||||
qlog.put(trad["warning"].format(message=message))
|
|
||||||
return False
|
# New line
|
||||||
result = self._integer(value, key, width=2)
|
f.write(f"\n")
|
||||||
else:
|
|
||||||
result = self._integer(value, key,
|
param = next(it, None)
|
||||||
width=10 if kind == "depot" else 1)
|
|
||||||
lines.append(f"{key:<50}{result}\n")
|
def _export_ts(self, study, repertory, qlog, name="0"):
|
||||||
if qlog is not None:
|
if qlog is not None:
|
||||||
qlog.put("Export TS file")
|
qlog.put("Export TS file")
|
||||||
self._write_parameters(repertory, f"ts.{name}", lines)
|
|
||||||
return True
|
with open(
|
||||||
|
os.path.join(
|
||||||
|
repertory, f"ts.{name}"
|
||||||
|
), "w+"
|
||||||
|
) as f:
|
||||||
|
def float_format(string):
|
||||||
|
if "." in string:
|
||||||
|
return f"{float(string):>10.0f}"
|
||||||
|
return ""
|
||||||
|
|
||||||
|
params = filter(
|
||||||
|
lambda p: "rubarbe_sediment_" in p.name,
|
||||||
|
study.river.get_params(self.type).parameters
|
||||||
|
)
|
||||||
|
it = iter(params)
|
||||||
|
|
||||||
|
line = 0
|
||||||
|
while line < 20:
|
||||||
|
param = next(it)
|
||||||
|
name = param.name
|
||||||
|
value = param.value
|
||||||
|
|
||||||
|
if value != "":
|
||||||
|
# Value format
|
||||||
|
if value.count('.') == 1:
|
||||||
|
value = f"{float_format(value)}"
|
||||||
|
else:
|
||||||
|
value = f"{value:>10}"
|
||||||
|
|
||||||
|
# Write value
|
||||||
|
f.write(f"{name:<50}{value}")
|
||||||
|
|
||||||
|
# Add values of 'rubarbe_iodebord' and
|
||||||
|
# 'rubarbe_iostockage'
|
||||||
|
if name == "rubarbe_sediment_mult_1":
|
||||||
|
m2 = f"{float_format(next(it).value)}"
|
||||||
|
m3 = f"{float_format(next(it).value)}"
|
||||||
|
m4 = f"{float_format(next(it).value)}"
|
||||||
|
m5 = f"{float_format(next(it).value)}"
|
||||||
|
|
||||||
|
f.write(f"{m2}{m3}{m4}{m5}")
|
||||||
|
|
||||||
|
# New line
|
||||||
|
f.write(f"\n")
|
||||||
|
|
||||||
|
line += 1
|
||||||
|
|
||||||
def _export_geomac_i(self, study, repertory, qlog, name="0"):
|
def _export_geomac_i(self, study, repertory, qlog, name="0"):
|
||||||
if qlog is not None:
|
if qlog is not None:
|
||||||
@@ -742,7 +616,6 @@ class Rubar3(CommandLineSolver):
|
|||||||
)).value
|
)).value
|
||||||
if timestamp.count(':') == 3:
|
if timestamp.count(':') == 3:
|
||||||
timestamp = old_pamhyr_date_to_timestamp(timestamp)
|
timestamp = old_pamhyr_date_to_timestamp(timestamp)
|
||||||
timestamp = float(timestamp)
|
|
||||||
ts.add(timestamp)
|
ts.add(timestamp)
|
||||||
|
|
||||||
# add initial condition
|
# add initial condition
|
||||||
@@ -763,7 +636,8 @@ class Rubar3(CommandLineSolver):
|
|||||||
while True:
|
while True:
|
||||||
line = f.readline()
|
line = f.readline()
|
||||||
if line == "":
|
if line == "":
|
||||||
break
|
results.set("timestamps", ts)
|
||||||
|
return
|
||||||
|
|
||||||
timestamp = float(line)
|
timestamp = float(line)
|
||||||
ts.add(timestamp)
|
ts.add(timestamp)
|
||||||
@@ -797,24 +671,6 @@ class Rubar3(CommandLineSolver):
|
|||||||
h, s, q, z = read_data_line(f)
|
h, s, q, z = read_data_line(f)
|
||||||
set_and_compute_limites(reach, ind, z+h, q, s)
|
set_and_compute_limites(reach, ind, z+h, q, s)
|
||||||
|
|
||||||
# Tables and plots use timestamp rows and global profile columns.
|
|
||||||
timestamps = sorted(ts)
|
|
||||||
profiles = []
|
|
||||||
for reach, _ in reachs:
|
|
||||||
offset = len(profiles)
|
|
||||||
profiles.extend(reach.profiles)
|
|
||||||
reach.set_global_index(range(offset, len(profiles)))
|
|
||||||
|
|
||||||
results.set("timestamps", timestamps)
|
|
||||||
results.compute_timestamp_index()
|
|
||||||
results.set("table", {
|
|
||||||
key: np.array([
|
|
||||||
[profile.get_ts_key(t, key) for profile in profiles]
|
|
||||||
for t in timestamps
|
|
||||||
], dtype=float)
|
|
||||||
for key in ("Z", "Q", "V")
|
|
||||||
})
|
|
||||||
|
|
||||||
@timer
|
@timer
|
||||||
def write_bin(self, study, fname, results, qlog=None, name="0"):
|
def write_bin(self, study, fname, results, qlog=None, name="0"):
|
||||||
logger.info(f"write_bin: Start writing '{fname}' ...")
|
logger.info(f"write_bin: Start writing '{fname}' ...")
|
||||||
@@ -944,14 +800,3 @@ class RubarBE(Rubar3):
|
|||||||
self._cmd_input = ""
|
self._cmd_input = ""
|
||||||
self._cmd_solver = "@path @args @input"
|
self._cmd_solver = "@path @args @input"
|
||||||
self._cmd_output = ""
|
self._cmd_output = ""
|
||||||
|
|
||||||
@classmethod
|
|
||||||
def default_parameters(cls):
|
|
||||||
# New BE studies evolve the bed. Keep Rubar3 defaults unchanged.
|
|
||||||
overrides = {
|
|
||||||
"rubarbe_trased": "y",
|
|
||||||
"rubarbe_sediment_opts": "1", # Meyer-Peter and Mueller
|
|
||||||
"rubarbe_sediment_option": "212", # no Ikeda, given Shields, total
|
|
||||||
}
|
|
||||||
return [(key, overrides.get(key, value))
|
|
||||||
for key, value in super().default_parameters()]
|
|
||||||
@@ -23,7 +23,6 @@ from Solver.Mage import (
|
|||||||
Mage7, Mage8, MageFake7,
|
Mage7, Mage8, MageFake7,
|
||||||
)
|
)
|
||||||
from Solver.AdisTS import AdisTSwc
|
from Solver.AdisTS import AdisTSwc
|
||||||
from Solver.AdisTT import AdisTTwc
|
|
||||||
from Solver.RubarBE import Rubar3, RubarBE
|
from Solver.RubarBE import Rubar3, RubarBE
|
||||||
|
|
||||||
_translate = QCoreApplication.translate
|
_translate = QCoreApplication.translate
|
||||||
@@ -34,8 +33,7 @@ solver_long_name = {
|
|||||||
"mage8": "Mage v8",
|
"mage8": "Mage v8",
|
||||||
# "mage_fake7": "Mage fake v7",
|
# "mage_fake7": "Mage fake v7",
|
||||||
"adistswc": "Adis-TS_WC",
|
"adistswc": "Adis-TS_WC",
|
||||||
"adisttwc": "Adis-TT_WC",
|
# "rubarbe": "RubarBE",
|
||||||
"rubarbe": "RubarBE",
|
|
||||||
"rubar3": "Rubar3",
|
"rubar3": "Rubar3",
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,7 +43,6 @@ solver_type_list = {
|
|||||||
"mage8": Mage8,
|
"mage8": Mage8,
|
||||||
# "mage_fake7": MageFake7,
|
# "mage_fake7": MageFake7,
|
||||||
"adistswc": AdisTSwc,
|
"adistswc": AdisTSwc,
|
||||||
"adisttwc": AdisTTwc,
|
# "rubarbe": RubarBE,
|
||||||
"rubarbe": RubarBE,
|
|
||||||
"rubar3": Rubar3,
|
"rubar3": Rubar3,
|
||||||
}
|
}
|
||||||
@@ -54,7 +54,7 @@ class Plot(PamhyrPlot):
|
|||||||
self._isometric_axis = False
|
self._isometric_axis = False
|
||||||
|
|
||||||
self._auto_relim_update = True
|
self._auto_relim_update = True
|
||||||
self._autoscale_update = True
|
self._autoscale_update = False
|
||||||
|
|
||||||
def custom_ticks(self):
|
def custom_ticks(self):
|
||||||
if self.data.header[0] != "time":
|
if self.data.header[0] != "time":
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ from datetime import date, time, datetime, timedelta
|
|||||||
from tools import (
|
from tools import (
|
||||||
trace, timer,
|
trace, timer,
|
||||||
timestamp_to_old_pamhyr_date,
|
timestamp_to_old_pamhyr_date,
|
||||||
old_pamhyr_date_to_timestamp, format_datetime, parse_datetime
|
old_pamhyr_date_to_timestamp
|
||||||
)
|
)
|
||||||
|
|
||||||
from View.Tools.PamhyrTable import PamhyrTableModel
|
from View.Tools.PamhyrTable import PamhyrTableModel
|
||||||
@@ -94,13 +94,10 @@ class TableModel(PamhyrTableModel):
|
|||||||
v = v.replace(',', '.')
|
v = v.replace(',', '.')
|
||||||
value = f"{float(v):.4f}"
|
value = f"{float(v):.4f}"
|
||||||
elif self._data.header[column] == "time":
|
elif self._data.header[column] == "time":
|
||||||
if self.time_system == "time":
|
if self._opt_data == "time":
|
||||||
value = timestamp_to_old_pamhyr_date(int(v))
|
value = timestamp_to_old_pamhyr_date(int(v))
|
||||||
else:
|
else:
|
||||||
value = format_datetime(
|
value = str(datetime.fromtimestamp(v))
|
||||||
parse_datetime(self.start_date)
|
|
||||||
+ timedelta(seconds=float(v))
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
value = f"{v}"
|
value = f"{v}"
|
||||||
|
|
||||||
@@ -117,10 +114,6 @@ class TableModel(PamhyrTableModel):
|
|||||||
column = index.column()
|
column = index.column()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if (self._data.header[column] == "time"
|
|
||||||
and self.time_system == "date"):
|
|
||||||
value = self.date_to_elapsed_seconds(value)
|
|
||||||
|
|
||||||
row = self.get_true_data_row(row)
|
row = self.get_true_data_row(row)
|
||||||
|
|
||||||
self._undo.push(
|
self._undo.push(
|
||||||
@@ -150,43 +143,21 @@ class TableModel(PamhyrTableModel):
|
|||||||
self.update()
|
self.update()
|
||||||
|
|
||||||
def delete(self, rows, parent=QModelIndex()):
|
def delete(self, rows, parent=QModelIndex()):
|
||||||
if not rows:
|
self.beginRemoveRows(parent, rows[0], rows[-1])
|
||||||
return
|
|
||||||
|
|
||||||
rows = sorted(set(rows))
|
rows = list(map(
|
||||||
rows = [
|
lambda r: self.get_true_data_row(r),
|
||||||
self.get_true_data_row(row)
|
rows))
|
||||||
for row in rows
|
|
||||||
]
|
|
||||||
|
|
||||||
# A multiple selection may contain non-contiguous rows. A model reset
|
|
||||||
# accurately represents this atomic undo command, unlike one
|
|
||||||
# beginRemoveRows() call spanning rows that are not all removed.
|
|
||||||
self.beginResetModel()
|
|
||||||
try:
|
|
||||||
self._undo.push(
|
self._undo.push(
|
||||||
DelCommand(
|
DelCommand(
|
||||||
self._data, rows
|
self._data, rows
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
finally:
|
|
||||||
self.endResetModel()
|
self.endRemoveRows()
|
||||||
self.update()
|
self.update()
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
self.beginResetModel()
|
|
||||||
try:
|
|
||||||
self._undo.undo()
|
|
||||||
finally:
|
|
||||||
self.endResetModel()
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
self.beginResetModel()
|
|
||||||
try:
|
|
||||||
self._undo.redo()
|
|
||||||
finally:
|
|
||||||
self.endResetModel()
|
|
||||||
|
|
||||||
def sort(self, _reverse, parent=QModelIndex()):
|
def sort(self, _reverse, parent=QModelIndex()):
|
||||||
self.layoutAboutToBeChanged.emit()
|
self.layoutAboutToBeChanged.emit()
|
||||||
|
|
||||||
@@ -239,18 +210,17 @@ class TableModel(PamhyrTableModel):
|
|||||||
if len(data) == 0:
|
if len(data) == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
|
||||||
rows = [self._data.new_from_data(header, d) for d in data]
|
|
||||||
except (ValueError, TypeError, IndexError) as error:
|
|
||||||
logger.warning(error)
|
|
||||||
return False
|
|
||||||
|
|
||||||
self.layoutAboutToBeChanged.emit()
|
self.layoutAboutToBeChanged.emit()
|
||||||
|
|
||||||
self._undo.push(
|
self._undo.push(
|
||||||
PasteCommand(
|
PasteCommand(
|
||||||
self._data, row,
|
self._data, row,
|
||||||
rows
|
list(
|
||||||
|
map(
|
||||||
|
lambda d: self._data.new_from_data(header, d),
|
||||||
|
data
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -97,11 +97,12 @@ class DelCommand(QUndoCommand):
|
|||||||
QUndoCommand.__init__(self)
|
QUndoCommand.__init__(self)
|
||||||
|
|
||||||
self._data = data
|
self._data = data
|
||||||
self._rows = sorted(set(rows))
|
self._rows = rows
|
||||||
self._bc = [
|
|
||||||
self._data.get_i(row)
|
self._bc = []
|
||||||
for row in self._rows
|
for row in rows:
|
||||||
]
|
self._bc.append(self._data.get_i(row))
|
||||||
|
self._bc.sort()
|
||||||
|
|
||||||
def undo(self):
|
def undo(self):
|
||||||
for el in self._bc:
|
for el in self._bc:
|
||||||
@@ -119,17 +120,13 @@ class SortCommand(QUndoCommand):
|
|||||||
self._data = data
|
self._data = data
|
||||||
self._reverse = _reverse
|
self._reverse = _reverse
|
||||||
|
|
||||||
# Keep the order of the complete underlying list, including soft
|
self._old = self._data.data
|
||||||
# deleted items. ``data`` only exposes visible items and therefore
|
self._indexes = None
|
||||||
# cannot reliably restore a sort after a delete/undelete operation.
|
|
||||||
self._old_positions = {
|
|
||||||
id(item): index
|
|
||||||
for index, item in enumerate(self._data._data)
|
|
||||||
}
|
|
||||||
|
|
||||||
def undo(self):
|
def undo(self):
|
||||||
|
ll = self._data.data
|
||||||
self._data.sort(
|
self._data.sort(
|
||||||
key=lambda item: self._old_positions[id(item)]
|
key=lambda x: self._indexes[ll.index(x)]
|
||||||
)
|
)
|
||||||
|
|
||||||
def redo(self):
|
def redo(self):
|
||||||
@@ -137,6 +134,14 @@ class SortCommand(QUndoCommand):
|
|||||||
_reverse=self._reverse,
|
_reverse=self._reverse,
|
||||||
key=lambda x: x[0]
|
key=lambda x: x[0]
|
||||||
)
|
)
|
||||||
|
if self._indexes is None:
|
||||||
|
self._indexes = list(
|
||||||
|
map(
|
||||||
|
lambda p: self._old.index(p),
|
||||||
|
self._data.data
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._old = None
|
||||||
|
|
||||||
|
|
||||||
class MoveCommand(QUndoCommand):
|
class MoveCommand(QUndoCommand):
|
||||||
|
|||||||
@@ -18,8 +18,6 @@
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from Modules import Modules
|
|
||||||
|
|
||||||
from tools import timer, trace
|
from tools import timer, trace
|
||||||
|
|
||||||
from numpy import sqrt
|
from numpy import sqrt
|
||||||
@@ -175,8 +173,7 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
|||||||
},
|
},
|
||||||
data=self._data,
|
data=self._data,
|
||||||
undo=self._undo_stack,
|
undo=self._undo_stack,
|
||||||
opt_data=self._study.time_system,
|
opt_data=self._study.time_system
|
||||||
study=self._study
|
|
||||||
)
|
)
|
||||||
|
|
||||||
table.setModel(self._table)
|
table.setModel(self._table)
|
||||||
@@ -264,11 +261,6 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
|||||||
self._d50sigma.set_d50(self._data.d50)
|
self._d50sigma.set_d50(self._data.d50)
|
||||||
self._d50sigma.set_sigma(self._data.sigma)
|
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):
|
def update(self):
|
||||||
self.plot.update()
|
self.plot.update()
|
||||||
|
|
||||||
|
|||||||
@@ -124,7 +124,7 @@ class DelCommand(QUndoCommand):
|
|||||||
self._bcs.insert(self._tab, row, el)
|
self._bcs.insert(self._tab, row, el)
|
||||||
|
|
||||||
def redo(self):
|
def redo(self):
|
||||||
self._bcs.delete(self._tab, [el for _, el in self._bc])
|
self._bcs.delete_i(self._tab, self._rows)
|
||||||
|
|
||||||
|
|
||||||
class SortCommand(QUndoCommand):
|
class SortCommand(QUndoCommand):
|
||||||
|
|||||||
@@ -21,11 +21,10 @@ import traceback
|
|||||||
|
|
||||||
from datetime import date, time, datetime, timedelta
|
from datetime import date, time, datetime, timedelta
|
||||||
|
|
||||||
from tools import parse_datetime
|
|
||||||
from tools import (
|
from tools import (
|
||||||
trace, timer,
|
trace, timer,
|
||||||
timestamp_to_old_pamhyr_date,
|
timestamp_to_old_pamhyr_date,
|
||||||
old_pamhyr_date_to_timestamp, format_datetime
|
old_pamhyr_date_to_timestamp
|
||||||
)
|
)
|
||||||
|
|
||||||
from View.Tools.PamhyrTable import PamhyrTableModel
|
from View.Tools.PamhyrTable import PamhyrTableModel
|
||||||
@@ -85,13 +84,10 @@ class TableModel(PamhyrTableModel):
|
|||||||
if self._data._types[column] == float:
|
if self._data._types[column] == float:
|
||||||
value = f"{v:.4f}"
|
value = f"{v:.4f}"
|
||||||
elif self._data.header[column] == "time":
|
elif self._data.header[column] == "time":
|
||||||
if self.time_system == "time":
|
if self._opt_data == "time":
|
||||||
value = timestamp_to_old_pamhyr_date(int(v))
|
value = timestamp_to_old_pamhyr_date(int(v))
|
||||||
else:
|
else:
|
||||||
value = format_datetime(
|
value = str(datetime.fromtimestamp(v))
|
||||||
parse_datetime(self.start_date)
|
|
||||||
+ timedelta(seconds=float(v))
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
value = f"{v}"
|
value = f"{v}"
|
||||||
|
|
||||||
@@ -108,10 +104,6 @@ class TableModel(PamhyrTableModel):
|
|||||||
column = index.column()
|
column = index.column()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if (self._data.header[column] == "time"
|
|
||||||
and self.time_system == "date"):
|
|
||||||
value = self.date_to_elapsed_seconds(value)
|
|
||||||
|
|
||||||
row = self.get_true_data_row(row)
|
row = self.get_true_data_row(row)
|
||||||
|
|
||||||
self._undo.push(
|
self._undo.push(
|
||||||
@@ -171,18 +163,17 @@ class TableModel(PamhyrTableModel):
|
|||||||
if len(data) == 0:
|
if len(data) == 0:
|
||||||
return
|
return
|
||||||
|
|
||||||
try:
|
|
||||||
rows = [self._data.new_from_data(header, d) for d in data]
|
|
||||||
except (ValueError, TypeError, IndexError) as error:
|
|
||||||
logger.warning(error)
|
|
||||||
return False
|
|
||||||
|
|
||||||
self.layoutAboutToBeChanged.emit()
|
self.layoutAboutToBeChanged.emit()
|
||||||
|
|
||||||
self._undo.push(
|
self._undo.push(
|
||||||
PasteCommand(
|
PasteCommand(
|
||||||
self._data, row,
|
self._data, row,
|
||||||
rows
|
list(
|
||||||
|
map(
|
||||||
|
lambda d: self._data.new_from_data(header, d),
|
||||||
|
data
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -18,8 +18,6 @@
|
|||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
from Modules import Modules
|
|
||||||
|
|
||||||
from tools import timer, trace
|
from tools import timer, trace
|
||||||
|
|
||||||
from View.Tools.PamhyrWindow import PamhyrWindow
|
from View.Tools.PamhyrWindow import PamhyrWindow
|
||||||
@@ -66,22 +64,14 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
|||||||
name = trad[self._pamhyr_name]
|
name = trad[self._pamhyr_name]
|
||||||
|
|
||||||
if self._data is not None:
|
if self._data is not None:
|
||||||
pollutant_name = next(
|
|
||||||
(
|
|
||||||
pollutant.name
|
|
||||||
for pollutant in study.river.Pollutants.Pollutants_List
|
|
||||||
if pollutant.id == self._data.pollutant
|
|
||||||
),
|
|
||||||
None
|
|
||||||
)
|
|
||||||
n = self._data.node
|
n = self._data.node
|
||||||
node_name = next(filter(
|
node_name = next(filter(
|
||||||
lambda x: x.id == n, study.river._nodes
|
lambda x: x.id == n, study.river._nodes
|
||||||
)).name
|
)).name
|
||||||
name += f" - {study.name}"
|
name += (
|
||||||
if pollutant_name is not None:
|
f" - {study.name} " +
|
||||||
name += f" - {pollutant_name}"
|
f"({node_name})"
|
||||||
name += f" ({node_name})"
|
)
|
||||||
|
|
||||||
super(EditBoundaryConditionWindow, self).__init__(
|
super(EditBoundaryConditionWindow, self).__init__(
|
||||||
title=name,
|
title=name,
|
||||||
@@ -130,8 +120,7 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
|||||||
},
|
},
|
||||||
data=self._data,
|
data=self._data,
|
||||||
undo=self._undo_stack,
|
undo=self._undo_stack,
|
||||||
opt_data=self._study.time_system,
|
opt_data=self._study.time_system
|
||||||
study=self._study
|
|
||||||
)
|
)
|
||||||
|
|
||||||
table.setModel(self._table)
|
table.setModel(self._table)
|
||||||
@@ -164,14 +153,8 @@ class EditBoundaryConditionWindow(PamhyrWindow):
|
|||||||
self.find(QAction, "action_sort").triggered.connect(self.sort)
|
self.find(QAction, "action_sort").triggered.connect(self.sort)
|
||||||
self._table.dataChanged.connect(self.update)
|
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):
|
def update(self):
|
||||||
self.plot.update()
|
self.plot.update()
|
||||||
self.plot.fit_to_data()
|
|
||||||
|
|
||||||
def index_selected_row(self):
|
def index_selected_row(self):
|
||||||
table = self.find(QTableView, "tableView")
|
table = self.find(QTableView, "tableView")
|
||||||
|
|||||||
@@ -1,105 +0,0 @@
|
|||||||
# Plot.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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 datetime import datetime
|
|
||||||
|
|
||||||
from tools import timer, trace
|
|
||||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
|
||||||
|
|
||||||
from PyQt5.QtCore import (
|
|
||||||
QCoreApplication
|
|
||||||
)
|
|
||||||
|
|
||||||
_translate = QCoreApplication.translate
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class Plot(PamhyrPlot):
|
|
||||||
def __init__(self, mode="time", data=None,
|
|
||||||
trad=None, canvas=None, toolbar=None,
|
|
||||||
parent=None):
|
|
||||||
super(Plot, self).__init__(
|
|
||||||
canvas=canvas,
|
|
||||||
trad=trad,
|
|
||||||
data=data,
|
|
||||||
toolbar=toolbar,
|
|
||||||
parent=parent
|
|
||||||
)
|
|
||||||
|
|
||||||
self._table_headers = self._trad.get_dict("table_headers")
|
|
||||||
|
|
||||||
header = self.data.header
|
|
||||||
|
|
||||||
self.label_x = self._table_headers[header[0]]
|
|
||||||
self.label_y = self._table_headers[header[1]]
|
|
||||||
|
|
||||||
self._mode = mode
|
|
||||||
self._isometric_axis = False
|
|
||||||
|
|
||||||
self._auto_relim_update = True
|
|
||||||
self._autoscale_update = False
|
|
||||||
|
|
||||||
def custom_ticks(self):
|
|
||||||
if self.data.header[0] != "time":
|
|
||||||
return
|
|
||||||
|
|
||||||
self.set_ticks_time_formater()
|
|
||||||
|
|
||||||
@timer
|
|
||||||
def draw(self):
|
|
||||||
self.init_axes()
|
|
||||||
|
|
||||||
if len(self.data) == 0:
|
|
||||||
self._init = False
|
|
||||||
return
|
|
||||||
|
|
||||||
self.draw_data()
|
|
||||||
self.custom_ticks()
|
|
||||||
|
|
||||||
self.idle()
|
|
||||||
self._init = True
|
|
||||||
|
|
||||||
def draw_data(self):
|
|
||||||
# Plot data
|
|
||||||
x = list(map(lambda v: v[0], self.data.data))
|
|
||||||
y = list(map(lambda v: v[1], self.data.data))
|
|
||||||
|
|
||||||
self._line, = self.canvas.axes.plot(
|
|
||||||
x, y,
|
|
||||||
color=self.color_plot,
|
|
||||||
**self.plot_default_kargs
|
|
||||||
)
|
|
||||||
|
|
||||||
@timer
|
|
||||||
def update(self, ind=None):
|
|
||||||
if not self._init:
|
|
||||||
self.draw()
|
|
||||||
return
|
|
||||||
|
|
||||||
self.update_data()
|
|
||||||
|
|
||||||
self.update_idle()
|
|
||||||
|
|
||||||
def update_data(self):
|
|
||||||
x = list(map(lambda v: v[0], self.data.data))
|
|
||||||
y = list(map(lambda v: v[1], self.data.data))
|
|
||||||
|
|
||||||
self._line.set_data(x, y)
|
|
||||||
@@ -1,194 +0,0 @@
|
|||||||
# Table.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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 datetime import date, time, datetime, timedelta
|
|
||||||
|
|
||||||
from tools import parse_datetime
|
|
||||||
from tools import (
|
|
||||||
trace, timer,
|
|
||||||
timestamp_to_old_pamhyr_date,
|
|
||||||
old_pamhyr_date_to_timestamp, format_datetime
|
|
||||||
)
|
|
||||||
|
|
||||||
from View.Tools.PamhyrTable import PamhyrTableModel
|
|
||||||
|
|
||||||
from PyQt5.QtCore import (
|
|
||||||
Qt, QVariant, QAbstractTableModel,
|
|
||||||
QCoreApplication, QModelIndex, pyqtSlot,
|
|
||||||
QRect, QTime, QDateTime,
|
|
||||||
)
|
|
||||||
|
|
||||||
from PyQt5.QtWidgets import (
|
|
||||||
QTableView, QAbstractItemView, QSpinBox,
|
|
||||||
QTimeEdit, QDateTimeEdit, QItemDelegate,
|
|
||||||
)
|
|
||||||
|
|
||||||
from View.BoundaryConditionsTemperature.Edit.UndoCommand import (
|
|
||||||
AddCommand, DelCommand, SetDataCommand, PasteCommand, SortCommand,
|
|
||||||
)
|
|
||||||
|
|
||||||
_translate = QCoreApplication.translate
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class TableModel(PamhyrTableModel):
|
|
||||||
def get_true_data_row(self, row):
|
|
||||||
if len(self._data.data) > 0:
|
|
||||||
bc = self._data.data[row]
|
|
||||||
else:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
return next(
|
|
||||||
map(
|
|
||||||
lambda e: e[0],
|
|
||||||
filter(
|
|
||||||
lambda e: e[1] == bc,
|
|
||||||
enumerate(self._data._data)
|
|
||||||
)
|
|
||||||
), 0
|
|
||||||
)
|
|
||||||
|
|
||||||
def data(self, index, role):
|
|
||||||
if role == Qt.TextAlignmentRole:
|
|
||||||
return Qt.AlignHCenter | Qt.AlignVCenter
|
|
||||||
|
|
||||||
if role != Qt.ItemDataRole.DisplayRole:
|
|
||||||
return QVariant()
|
|
||||||
|
|
||||||
row = index.row()
|
|
||||||
column = index.column()
|
|
||||||
|
|
||||||
value = QVariant()
|
|
||||||
|
|
||||||
if 0 <= column < 2:
|
|
||||||
row = self.get_true_data_row(row)
|
|
||||||
v = self._data._data[row][column]
|
|
||||||
if self._data._types[column] == float:
|
|
||||||
value = f"{v:.2f}"
|
|
||||||
elif self._data.header[column] == "time":
|
|
||||||
if self.time_system == "time":
|
|
||||||
value = timestamp_to_old_pamhyr_date(int(v))
|
|
||||||
else:
|
|
||||||
value = format_datetime(
|
|
||||||
parse_datetime(self.start_date)
|
|
||||||
+ timedelta(seconds=float(v))
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
value = f"{v}"
|
|
||||||
|
|
||||||
return value
|
|
||||||
|
|
||||||
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._data.header[column] == "time"
|
|
||||||
and self.time_system == "date"):
|
|
||||||
value = self.date_to_elapsed_seconds(value)
|
|
||||||
|
|
||||||
row = self.get_true_data_row(row)
|
|
||||||
|
|
||||||
self._undo.push(
|
|
||||||
SetDataCommand(
|
|
||||||
self._data, row, column, 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._data, row
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
self.endInsertRows()
|
|
||||||
self.layoutChanged.emit()
|
|
||||||
|
|
||||||
def delete(self, rows, parent=QModelIndex()):
|
|
||||||
self.beginRemoveRows(parent, rows[0], rows[-1])
|
|
||||||
_rows = list(
|
|
||||||
map(
|
|
||||||
lambda r: self.get_true_data_row(r),
|
|
||||||
rows
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self._undo.push(
|
|
||||||
DelCommand(
|
|
||||||
self._data, _rows
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
self.endRemoveRows()
|
|
||||||
self.layoutChanged.emit()
|
|
||||||
|
|
||||||
def sort(self, _reverse, parent=QModelIndex()):
|
|
||||||
self.layoutAboutToBeChanged.emit()
|
|
||||||
|
|
||||||
self._undo.push(
|
|
||||||
SortCommand(
|
|
||||||
self._data, _reverse
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
self.layoutAboutToBeChanged.emit()
|
|
||||||
self.update()
|
|
||||||
|
|
||||||
def paste(self, row, header, data):
|
|
||||||
if len(data) == 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
try:
|
|
||||||
rows = [self._data.new_from_data(header, d) for d in data]
|
|
||||||
except (ValueError, TypeError, IndexError) as error:
|
|
||||||
logger.warning(error)
|
|
||||||
return False
|
|
||||||
|
|
||||||
self.layoutAboutToBeChanged.emit()
|
|
||||||
|
|
||||||
self._undo.push(
|
|
||||||
PasteCommand(
|
|
||||||
self._data, row,
|
|
||||||
rows
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
self.layoutAboutToBeChanged.emit()
|
|
||||||
self.update()
|
|
||||||
|
|
||||||
def update(self):
|
|
||||||
# self.auto_sort()
|
|
||||||
self.layoutChanged.emit()
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
# UndoCommand.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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 copy import deepcopy
|
|
||||||
from tools import trace, timer
|
|
||||||
|
|
||||||
from PyQt5.QtWidgets import (
|
|
||||||
QMessageBox, QUndoCommand, QUndoStack,
|
|
||||||
)
|
|
||||||
|
|
||||||
from Model.BoundaryConditionsTemperature.BoundaryConditionTemperature \
|
|
||||||
import BoundaryConditionTemperature
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class SetDataCommand(QUndoCommand):
|
|
||||||
def __init__(self, data, index, column, new_value):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._data = data
|
|
||||||
self._index = index
|
|
||||||
self._column = column
|
|
||||||
self._old = self._data.get_i(self._index)[self._column]
|
|
||||||
self._new = new_value
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
self._data._set_i_c_v(self._index, self._column, self._old)
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
self._data._set_i_c_v(self._index, self._column, self._new)
|
|
||||||
|
|
||||||
|
|
||||||
class AddCommand(QUndoCommand):
|
|
||||||
def __init__(self, data, index):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._data = data
|
|
||||||
self._index = index
|
|
||||||
self._new = None
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
del self._data._data[self._index]
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
if self._new is None:
|
|
||||||
self._new = self._data.add(self._index)
|
|
||||||
else:
|
|
||||||
self._data.insert(self._index, self._new)
|
|
||||||
|
|
||||||
|
|
||||||
class DelCommand(QUndoCommand):
|
|
||||||
def __init__(self, data, rows):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._data = data
|
|
||||||
self._rows = rows
|
|
||||||
|
|
||||||
self._bc = []
|
|
||||||
for row in rows:
|
|
||||||
self._bc.append((row, self._data._data[row]))
|
|
||||||
self._bc.sort()
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
for row, el in self._bc:
|
|
||||||
el.set_as_not_deleted()
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
for row, el in self._bc:
|
|
||||||
el.set_as_deleted()
|
|
||||||
|
|
||||||
|
|
||||||
class PasteCommand(QUndoCommand):
|
|
||||||
def __init__(self, data, row, bcs):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._data = data
|
|
||||||
self._row = row
|
|
||||||
self._bcs = bcs
|
|
||||||
self._bcs.reverse()
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
self._data.delete_i(
|
|
||||||
range(self._row, self._row + len(self._bcs))
|
|
||||||
)
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
for bc in self._bcs:
|
|
||||||
self._data.insert(self._row, bc)
|
|
||||||
|
|
||||||
|
|
||||||
class SortCommand(QUndoCommand):
|
|
||||||
def __init__(self, data, _reverse):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._data = data
|
|
||||||
self._reverse = _reverse
|
|
||||||
|
|
||||||
self._old = self._data.data
|
|
||||||
self._indexes = None
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
ll = self._data.data
|
|
||||||
self._data.sort(
|
|
||||||
key=lambda x: self._indexes[ll.index(x)]
|
|
||||||
)
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
self._data.sort(
|
|
||||||
_reverse=self._reverse,
|
|
||||||
key=lambda x: x[0]
|
|
||||||
)
|
|
||||||
if self._indexes is None:
|
|
||||||
self._indexes = list(
|
|
||||||
map(
|
|
||||||
lambda p: self._old.index(p),
|
|
||||||
self._data.data
|
|
||||||
)
|
|
||||||
)
|
|
||||||
self._old = None
|
|
||||||
@@ -1,238 +0,0 @@
|
|||||||
# Window.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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 Modules import Modules
|
|
||||||
|
|
||||||
from tools import timer, trace
|
|
||||||
|
|
||||||
from View.Tools.PamhyrWindow import PamhyrWindow
|
|
||||||
from View.Tools.PamhyrWidget import PamhyrWidget
|
|
||||||
from View.Tools.PamhyrDelegate import PamhyrExTimeDelegate
|
|
||||||
|
|
||||||
from PyQt5.QtGui import (
|
|
||||||
QKeySequence,
|
|
||||||
)
|
|
||||||
|
|
||||||
from PyQt5 import QtCore
|
|
||||||
from PyQt5.QtCore import (
|
|
||||||
Qt, QVariant, QAbstractTableModel, QCoreApplication,
|
|
||||||
pyqtSlot, pyqtSignal,
|
|
||||||
)
|
|
||||||
|
|
||||||
from PyQt5.QtWidgets import (
|
|
||||||
QDialogButtonBox, QPushButton, QLineEdit,
|
|
||||||
QFileDialog, QTableView, QAbstractItemView,
|
|
||||||
QUndoStack, QShortcut, QAction, QItemDelegate,
|
|
||||||
QHeaderView, QDoubleSpinBox, QVBoxLayout,
|
|
||||||
)
|
|
||||||
|
|
||||||
from View.Tools.Plot.PamhyrCanvas import MplCanvas
|
|
||||||
from View.Tools.Plot.PamhyrToolbar import PamhyrPlotToolbar
|
|
||||||
|
|
||||||
from View.BoundaryConditionsTemperature.Edit.translate import BCETranslate
|
|
||||||
from View.BoundaryConditionsTemperature.Edit.Table import TableModel
|
|
||||||
from View.BoundaryConditionsTemperature.Edit.Plot import Plot
|
|
||||||
|
|
||||||
_translate = QCoreApplication.translate
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class EditBoundaryConditionWindow(PamhyrWindow):
|
|
||||||
_pamhyr_ui = "EditBoundaryConditionsTemperature"
|
|
||||||
_pamhyr_name = "Edit Boundary Conditions Temperature"
|
|
||||||
|
|
||||||
def __init__(self, data=None, study=None, config=None, parent=None):
|
|
||||||
self._data = data
|
|
||||||
trad = BCETranslate()
|
|
||||||
|
|
||||||
name = trad[self._pamhyr_name]
|
|
||||||
|
|
||||||
if self._data is not None:
|
|
||||||
n = self._data.node
|
|
||||||
node_name = next(filter(
|
|
||||||
lambda x: x.id == n, study.river._nodes
|
|
||||||
)).name
|
|
||||||
name += (
|
|
||||||
f" - {study.name} " +
|
|
||||||
f"({node_name})"
|
|
||||||
)
|
|
||||||
|
|
||||||
super(EditBoundaryConditionWindow, self).__init__(
|
|
||||||
title=name,
|
|
||||||
study=study,
|
|
||||||
config=config,
|
|
||||||
trad=trad,
|
|
||||||
parent=parent
|
|
||||||
)
|
|
||||||
|
|
||||||
self._hash_data.append(data)
|
|
||||||
|
|
||||||
self.setup_table()
|
|
||||||
self.setup_plot()
|
|
||||||
self.setup_connections()
|
|
||||||
|
|
||||||
def setup_table(self):
|
|
||||||
table_headers = self._trad.get_dict("table_headers")
|
|
||||||
|
|
||||||
if self._study.is_editable():
|
|
||||||
editable_headers = self._trad.get_dict("table_headers")
|
|
||||||
else:
|
|
||||||
editable_headers = []
|
|
||||||
|
|
||||||
self._data.header = ["time", "temperature"]
|
|
||||||
|
|
||||||
headers = {}
|
|
||||||
for h in self._data.header:
|
|
||||||
headers[h] = table_headers[h]
|
|
||||||
|
|
||||||
self._delegate_time = PamhyrExTimeDelegate(
|
|
||||||
data=self._data,
|
|
||||||
mode=self._study.time_system,
|
|
||||||
parent=self
|
|
||||||
)
|
|
||||||
|
|
||||||
table = self.find(QTableView, "tableView")
|
|
||||||
self._table = TableModel(
|
|
||||||
table_view=table,
|
|
||||||
table_headers=headers,
|
|
||||||
editable_headers=editable_headers,
|
|
||||||
delegates={
|
|
||||||
# "time": self._delegate_time,
|
|
||||||
},
|
|
||||||
data=self._data,
|
|
||||||
undo=self._undo_stack,
|
|
||||||
opt_data=self._study.time_system,
|
|
||||||
study=self._study
|
|
||||||
)
|
|
||||||
|
|
||||||
table.setModel(self._table)
|
|
||||||
table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
|
||||||
table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
|
|
||||||
table.setAlternatingRowColors(True)
|
|
||||||
|
|
||||||
def setup_plot(self):
|
|
||||||
self.canvas = MplCanvas(width=5, height=4, dpi=100)
|
|
||||||
self.canvas.setObjectName("canvas")
|
|
||||||
self.toolbar = PamhyrPlotToolbar(
|
|
||||||
self.canvas, self
|
|
||||||
)
|
|
||||||
self.verticalLayout.addWidget(self.toolbar)
|
|
||||||
self.verticalLayout.addWidget(self.canvas)
|
|
||||||
|
|
||||||
self.plot = Plot(
|
|
||||||
canvas=self.canvas,
|
|
||||||
data=self._data,
|
|
||||||
mode=self._study.time_system,
|
|
||||||
trad=self._trad,
|
|
||||||
toolbar=self.toolbar,
|
|
||||||
)
|
|
||||||
self.plot.draw()
|
|
||||||
|
|
||||||
def setup_connections(self):
|
|
||||||
if self._study.is_editable():
|
|
||||||
self.find(QAction, "action_add").triggered.connect(self.add)
|
|
||||||
self.find(QAction, "action_del").triggered.connect(self.delete)
|
|
||||||
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()
|
|
||||||
|
|
||||||
def index_selected_row(self):
|
|
||||||
table = self.find(QTableView, "tableView")
|
|
||||||
return table.selectionModel()\
|
|
||||||
.selectedRows()[0]\
|
|
||||||
.row()
|
|
||||||
|
|
||||||
def index_selected_rows(self):
|
|
||||||
table = self.find(QTableView, "tableView")
|
|
||||||
return list(
|
|
||||||
# Delete duplicate
|
|
||||||
set(
|
|
||||||
map(
|
|
||||||
lambda i: i.row(),
|
|
||||||
table.selectedIndexes()
|
|
||||||
)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
def add(self):
|
|
||||||
rows = self.index_selected_rows()
|
|
||||||
if len(self._data) == 0 or len(rows) == 0:
|
|
||||||
self._table.add(0)
|
|
||||||
else:
|
|
||||||
self._table.add(rows[0])
|
|
||||||
|
|
||||||
self.plot.update()
|
|
||||||
|
|
||||||
def delete(self):
|
|
||||||
rows = self.index_selected_rows()
|
|
||||||
if len(rows) == 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
self._table.delete(rows)
|
|
||||||
self.plot.update()
|
|
||||||
|
|
||||||
def sort(self):
|
|
||||||
self._table.sort(False)
|
|
||||||
self.plot.update()
|
|
||||||
|
|
||||||
def _copy(self):
|
|
||||||
rows = self.index_selected_rows()
|
|
||||||
|
|
||||||
table = []
|
|
||||||
table.append(self._data.header)
|
|
||||||
|
|
||||||
data = self._data.data
|
|
||||||
for row in rows:
|
|
||||||
table.append(list(data[row]))
|
|
||||||
|
|
||||||
self.copyTableIntoClipboard(table)
|
|
||||||
|
|
||||||
def _paste(self):
|
|
||||||
header, data = self.parseClipboardTable()
|
|
||||||
|
|
||||||
logger.debug(f"paste: h:{header}, d:{data}")
|
|
||||||
|
|
||||||
if len(data) == 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
row = 0
|
|
||||||
rows = self.index_selected_rows()
|
|
||||||
if len(rows) != 0:
|
|
||||||
row = rows[0]
|
|
||||||
|
|
||||||
self._table.paste(row, header, data)
|
|
||||||
self.plot.update()
|
|
||||||
|
|
||||||
def _undo(self):
|
|
||||||
self._table.undo()
|
|
||||||
self.plot.update()
|
|
||||||
|
|
||||||
def _redo(self):
|
|
||||||
self._table.redo()
|
|
||||||
self.plot.update()
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
# UndoCommand.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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.BoundaryConditionsTemperature.BoundaryConditionTemperature \
|
|
||||||
import BoundaryConditionTemperature
|
|
||||||
from Model.BoundaryConditionsTemperature.BoundaryConditionsTemperatureList \
|
|
||||||
import BoundaryConditionsTemperatureList
|
|
||||||
|
|
||||||
|
|
||||||
class SetNodeCommand(QUndoCommand):
|
|
||||||
def __init__(self, bcs, index, node):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._bcs = bcs
|
|
||||||
self._index = index
|
|
||||||
self._old = self._bcs.get(self._index).node
|
|
||||||
self._new = node.id if node is not None else None
|
|
||||||
self._previous = next(
|
|
||||||
(
|
|
||||||
bc for i, bc in enumerate(self._bcs.lst)
|
|
||||||
if i != self._index and bc.node == self._new
|
|
||||||
),
|
|
||||||
None
|
|
||||||
)
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
self._bcs.get(self._index).node = self._old
|
|
||||||
if self._previous is not None:
|
|
||||||
self._previous.node = self._new
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
self._bcs.get(self._index).node = self._new
|
|
||||||
if self._previous is not None:
|
|
||||||
self._previous.node = None
|
|
||||||
|
|
||||||
|
|
||||||
class SetNameCommand(QUndoCommand):
|
|
||||||
def __init__(self, bcs, index, name):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._bcs = bcs
|
|
||||||
self._index = index
|
|
||||||
self._name = name
|
|
||||||
self._old = self._bcs.get(self._index).name
|
|
||||||
self._new = self._name
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
self._bcs.get(self._index).name = self._old
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
self._bcs.get(self._index).name = self._new
|
|
||||||
|
|
||||||
|
|
||||||
class AddCommand(QUndoCommand):
|
|
||||||
def __init__(self, bcs, index):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._bcs = bcs
|
|
||||||
self._index = index
|
|
||||||
self._new = None
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
self._bcs.delete_i([self._index])
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
if self._new is None:
|
|
||||||
self._new = self._bcs.new(self._index)
|
|
||||||
else:
|
|
||||||
self._bcs.insert(self._index, self._new)
|
|
||||||
|
|
||||||
|
|
||||||
class DelCommand(QUndoCommand):
|
|
||||||
def __init__(self, bcs, rows):
|
|
||||||
QUndoCommand.__init__(self)
|
|
||||||
|
|
||||||
self._bcs = bcs
|
|
||||||
self._rows = rows
|
|
||||||
|
|
||||||
self._bc = []
|
|
||||||
for row in rows:
|
|
||||||
self._bc.append((row, self._bcs._lst[row]))
|
|
||||||
self._bc.sort()
|
|
||||||
|
|
||||||
def undo(self):
|
|
||||||
for row, el in self._bc:
|
|
||||||
self._bcs.insert(row, el)
|
|
||||||
|
|
||||||
def redo(self):
|
|
||||||
self._bcs.delete_i(self._rows)
|
|
||||||
@@ -1,192 +0,0 @@
|
|||||||
# Window.py -- Pamhyr
|
|
||||||
# Copyright (C) 2023-2025 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
|
|
||||||
|
|
||||||
from PyQt5.QtGui import (
|
|
||||||
QKeySequence,
|
|
||||||
)
|
|
||||||
|
|
||||||
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, QVBoxLayout, QHeaderView, QTabWidget,
|
|
||||||
QWidget,
|
|
||||||
)
|
|
||||||
|
|
||||||
from View.BoundaryConditionsTemperature.Table import (
|
|
||||||
TableModel, ComboBoxDelegate
|
|
||||||
)
|
|
||||||
|
|
||||||
from View.Network.GraphWidget import GraphWidget
|
|
||||||
from View.BoundaryConditionsTemperature.translate import BCTemperatureTranslate
|
|
||||||
from View.BoundaryConditionsTemperature.Edit.Window \
|
|
||||||
import EditBoundaryConditionWindow
|
|
||||||
|
|
||||||
_translate = QCoreApplication.translate
|
|
||||||
|
|
||||||
logger = logging.getLogger()
|
|
||||||
|
|
||||||
|
|
||||||
class BoundaryConditionsTemperatureWindow(PamhyrWindow):
|
|
||||||
_pamhyr_ui = "BoundaryConditionsTemperature"
|
|
||||||
_pamhyr_name = "Boundary conditions temperature"
|
|
||||||
|
|
||||||
def __init__(self, data=None, study=None,
|
|
||||||
config=None, parent=None):
|
|
||||||
self._data = data
|
|
||||||
trad = BCTemperatureTranslate()
|
|
||||||
|
|
||||||
name = (
|
|
||||||
trad[self._pamhyr_name] +
|
|
||||||
" - " + study.name
|
|
||||||
)
|
|
||||||
|
|
||||||
super(BoundaryConditionsTemperatureWindow, self).__init__(
|
|
||||||
title=name,
|
|
||||||
study=study,
|
|
||||||
config=config,
|
|
||||||
trad=trad,
|
|
||||||
parent=parent
|
|
||||||
)
|
|
||||||
|
|
||||||
self._bcs = self._study.river.boundary_conditions_temperature
|
|
||||||
|
|
||||||
self.setup_graph()
|
|
||||||
self.setup_table()
|
|
||||||
self.setup_connections()
|
|
||||||
|
|
||||||
def setup_table(self):
|
|
||||||
self._delegate_node = ComboBoxDelegate(
|
|
||||||
trad=self._trad,
|
|
||||||
data=self._study.river,
|
|
||||||
mode="node",
|
|
||||||
parent=self
|
|
||||||
)
|
|
||||||
|
|
||||||
if self._study.is_editable():
|
|
||||||
editable_headers = self._trad.get_dict("table_headers")
|
|
||||||
else:
|
|
||||||
editable_headers = []
|
|
||||||
|
|
||||||
table = self.find(QTableView, f"tableView")
|
|
||||||
self._table = TableModel(
|
|
||||||
table_view=table,
|
|
||||||
table_headers=self._trad.get_dict("table_headers"),
|
|
||||||
editable_headers=editable_headers,
|
|
||||||
delegates={
|
|
||||||
"node": self._delegate_node,
|
|
||||||
},
|
|
||||||
trad=self._trad,
|
|
||||||
bc_list=self._study.river.boundary_conditions_temperature,
|
|
||||||
undo=self._undo_stack,
|
|
||||||
data=self._study.river
|
|
||||||
)
|
|
||||||
table.setModel(self._table)
|
|
||||||
table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
|
||||||
table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
|
|
||||||
table.setAlternatingRowColors(True)
|
|
||||||
|
|
||||||
def setup_graph(self):
|
|
||||||
self.graph_widget = GraphWidget(
|
|
||||||
self._study.river,
|
|
||||||
min_size=None, size=(200, 200),
|
|
||||||
only_display=True,
|
|
||||||
parent=self
|
|
||||||
)
|
|
||||||
self.graph_layout = self.find(QVBoxLayout, "verticalLayout")
|
|
||||||
self.graph_layout.addWidget(self.graph_widget)
|
|
||||||
|
|
||||||
def setup_connections(self):
|
|
||||||
if self._study.is_editable():
|
|
||||||
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)
|
|
||||||
|
|
||||||
def index_selected_row(self):
|
|
||||||
table = self.find(QTableView, f"tableView")
|
|
||||||
return table.selectionModel()\
|
|
||||||
.selectedRows()[0]\
|
|
||||||
.row()
|
|
||||||
|
|
||||||
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):
|
|
||||||
self._table.add(self._table.rowCount())
|
|
||||||
|
|
||||||
def delete(self):
|
|
||||||
rows = self.index_selected_rows()
|
|
||||||
if len(rows) == 0:
|
|
||||||
return
|
|
||||||
|
|
||||||
self._table.delete(rows)
|
|
||||||
|
|
||||||
def _copy(self):
|
|
||||||
logger.info("TODO: copy")
|
|
||||||
|
|
||||||
def _paste(self):
|
|
||||||
logger.info("TODO: paste")
|
|
||||||
|
|
||||||
def _undo(self):
|
|
||||||
self._table.undo()
|
|
||||||
|
|
||||||
def _redo(self):
|
|
||||||
self._table.redo()
|
|
||||||
|
|
||||||
def edit(self):
|
|
||||||
rows = self.index_selected_rows()
|
|
||||||
for row in rows:
|
|
||||||
data = self._table.get(row)
|
|
||||||
|
|
||||||
if data.node is None:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if self.sub_window_exists(
|
|
||||||
EditBoundaryConditionWindow,
|
|
||||||
data=[self._study, None, data]
|
|
||||||
):
|
|
||||||
continue
|
|
||||||
|
|
||||||
win = EditBoundaryConditionWindow(
|
|
||||||
data=data,
|
|
||||||
study=self._study,
|
|
||||||
parent=self
|
|
||||||
)
|
|
||||||
win.show()
|
|
||||||
@@ -53,13 +53,12 @@ class CheckListWindowAdisTS(PamhyrWindow):
|
|||||||
|
|
||||||
def __init__(self, autorun: bool = True,
|
def __init__(self, autorun: bool = True,
|
||||||
study=None, config=None,
|
study=None, config=None,
|
||||||
solver=None, parent=None, mage_rep=None, mode="adists"):
|
solver=None, parent=None, mage_rep=None):
|
||||||
trad = CheckListTranslate()
|
trad = CheckListTranslate()
|
||||||
|
|
||||||
self._autorun = autorun
|
self._autorun = autorun
|
||||||
self._solver = solver
|
self._solver = solver
|
||||||
self._mage_rep = mage_rep
|
self._mage_rep = mage_rep
|
||||||
self._mode = mode
|
|
||||||
|
|
||||||
name = trad[self._pamhyr_name] + " - " + study.name
|
name = trad[self._pamhyr_name] + " - " + study.name
|
||||||
|
|
||||||
@@ -74,8 +73,6 @@ class CheckListWindowAdisTS(PamhyrWindow):
|
|||||||
|
|
||||||
# Add solver to hash computation data
|
# Add solver to hash computation data
|
||||||
self._hash_data.append(self._solver)
|
self._hash_data.append(self._solver)
|
||||||
self._hash_data.append(self._mage_rep)
|
|
||||||
self._hash_data.append(self._mode)
|
|
||||||
|
|
||||||
self._checker_list = (
|
self._checker_list = (
|
||||||
self._study.checkers() +
|
self._study.checkers() +
|
||||||
@@ -172,7 +169,7 @@ class CheckListWindowAdisTS(PamhyrWindow):
|
|||||||
if not errors:
|
if not errors:
|
||||||
self.find(QPushButton, "pushButton_ok").setEnabled(True)
|
self.find(QPushButton, "pushButton_ok").setEnabled(True)
|
||||||
if self._autorun:
|
if self._autorun:
|
||||||
self.open_solver_log()
|
self._parent.solver_log_adists(self._solver, self._mage_rep)
|
||||||
self.end()
|
self.end()
|
||||||
|
|
||||||
self.update_statusbar()
|
self.update_statusbar()
|
||||||
@@ -199,11 +196,5 @@ class CheckListWindowAdisTS(PamhyrWindow):
|
|||||||
self.end()
|
self.end()
|
||||||
|
|
||||||
def accept(self):
|
def accept(self):
|
||||||
self.open_solver_log()
|
|
||||||
# self.end()
|
|
||||||
|
|
||||||
def open_solver_log(self):
|
|
||||||
if self._mode == "adistt":
|
|
||||||
self._parent.solver_log_adistt(self._solver, self._mage_rep)
|
|
||||||
else:
|
|
||||||
self._parent.solver_log_adists(self._solver, self._mage_rep)
|
self._parent.solver_log_adists(self._solver, self._mage_rep)
|
||||||
|
# self.end()
|
||||||
@@ -43,7 +43,6 @@ from PyQt5.QtWidgets import (
|
|||||||
QDialogButtonBox, QPushButton, QLineEdit,
|
QDialogButtonBox, QPushButton, QLineEdit,
|
||||||
QFileDialog, QTableView, QAbstractItemView,
|
QFileDialog, QTableView, QAbstractItemView,
|
||||||
QComboBox, QUndoStack, QShortcut, QHeaderView,
|
QComboBox, QUndoStack, QShortcut, QHeaderView,
|
||||||
QCheckBox,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
from Modules import Modules
|
from Modules import Modules
|
||||||
@@ -120,17 +119,11 @@ class ConfigureWindow(PamhyrDialog):
|
|||||||
editable_headers=["name", "comment", "minor", "medium"],
|
editable_headers=["name", "comment", "minor", "medium"],
|
||||||
data=self._stricklers,
|
data=self._stricklers,
|
||||||
undo=self._undo_stack,
|
undo=self._undo_stack,
|
||||||
trad=self._trad_stricklers,
|
|
||||||
display_manning=self._config.display_manning,
|
|
||||||
unique_names=True,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def setup_data(self):
|
def setup_data(self):
|
||||||
# Backup
|
# Backup
|
||||||
self.set_check_box("checkBox_backup", self._config.backup_enable)
|
self.set_check_box("checkBox_backup", self._config.backup_enable)
|
||||||
self.set_check_box(
|
|
||||||
"checkBox_display_manning", self._config.display_manning
|
|
||||||
)
|
|
||||||
# self.set_line_edit_text("lineEdit_backup_path",
|
# self.set_line_edit_text("lineEdit_backup_path",
|
||||||
# self._config.backup_path)
|
# self._config.backup_path)
|
||||||
self.set_time_edit("timeEdit_backup_frequence",
|
self.set_time_edit("timeEdit_backup_frequence",
|
||||||
@@ -174,10 +167,6 @@ class ConfigureWindow(PamhyrDialog):
|
|||||||
for button in buttons:
|
for button in buttons:
|
||||||
self.find(QPushButton, button).clicked.connect(buttons[button])
|
self.find(QPushButton, button).clicked.connect(buttons[button])
|
||||||
|
|
||||||
self.find(QCheckBox, "checkBox_display_manning").stateChanged.connect(
|
|
||||||
self.update_stricklers_display
|
|
||||||
)
|
|
||||||
|
|
||||||
def accept(self):
|
def accept(self):
|
||||||
# Solvers
|
# Solvers
|
||||||
self._config.solvers = self.solver_table_model._data.copy()
|
self._config.solvers = self.solver_table_model._data.copy()
|
||||||
@@ -189,9 +178,6 @@ class ConfigureWindow(PamhyrDialog):
|
|||||||
self._config.backup_frequence = self.get_time_edit(
|
self._config.backup_frequence = self.get_time_edit(
|
||||||
"timeEdit_backup_frequence"
|
"timeEdit_backup_frequence"
|
||||||
)
|
)
|
||||||
self._config.display_manning = self.get_check_box(
|
|
||||||
"checkBox_display_manning"
|
|
||||||
)
|
|
||||||
# self._config.backup_max = self.get_spin_box("spinBox_backup_max")
|
# self._config.backup_max = self.get_spin_box("spinBox_backup_max")
|
||||||
|
|
||||||
# Stricklers
|
# Stricklers
|
||||||
@@ -251,12 +237,6 @@ class ConfigureWindow(PamhyrDialog):
|
|||||||
|
|
||||||
# Stricklers
|
# Stricklers
|
||||||
|
|
||||||
def update_stricklers_display(self):
|
|
||||||
self._stricklers_table.display_manning = self.get_check_box(
|
|
||||||
"checkBox_display_manning"
|
|
||||||
)
|
|
||||||
self._stricklers_table.layoutChanged.emit()
|
|
||||||
|
|
||||||
def index_selected_rows_strikclers(self):
|
def index_selected_rows_strikclers(self):
|
||||||
table = self.find(QTableView, f"tableView_stricklers")
|
table = self.find(QTableView, f"tableView_stricklers")
|
||||||
return list(
|
return list(
|
||||||
|
|||||||
@@ -78,7 +78,7 @@ class ComboBoxDelegate(QItemDelegate):
|
|||||||
else:
|
else:
|
||||||
val = list(
|
val = list(
|
||||||
map(
|
map(
|
||||||
lambda n: n.name, self._data.enable_edges()
|
lambda n: n.name, self._data.edges()
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -123,16 +123,9 @@ class D90TableModel(PamhyrTableModel):
|
|||||||
self._undo.indexChanged.connect(lambda _: self.update())
|
self._undo.indexChanged.connect(lambda _: self.update())
|
||||||
|
|
||||||
def _setup_lst(self):
|
def _setup_lst(self):
|
||||||
enabled_reaches = {
|
|
||||||
reach.id for reach in self._river.enable_edges()
|
|
||||||
}
|
|
||||||
self._lst = list(
|
self._lst = list(
|
||||||
filter(
|
filter(
|
||||||
lambda d90: (
|
lambda d90: d90._deleted is False,
|
||||||
d90._deleted is False
|
|
||||||
and (d90.reach in (None, -1)
|
|
||||||
or d90.reach in enabled_reaches)
|
|
||||||
),
|
|
||||||
self._data._data
|
self._data._data
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -80,7 +80,7 @@ class ComboBoxDelegate(QItemDelegate):
|
|||||||
else:
|
else:
|
||||||
val = list(
|
val = list(
|
||||||
map(
|
map(
|
||||||
lambda n: n.name, self._data.enable_edges()
|
lambda n: n.name, self._data.edges()
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -125,16 +125,9 @@ class DIFTableModel(PamhyrTableModel):
|
|||||||
self._undo.indexChanged.connect(lambda _: self.update())
|
self._undo.indexChanged.connect(lambda _: self.update())
|
||||||
|
|
||||||
def _setup_lst(self):
|
def _setup_lst(self):
|
||||||
enabled_reaches = {
|
|
||||||
reach.id for reach in self._river.enable_edges()
|
|
||||||
}
|
|
||||||
self._lst = list(
|
self._lst = list(
|
||||||
filter(
|
filter(
|
||||||
lambda dif: (
|
lambda dif: dif._deleted is False,
|
||||||
dif._deleted is False
|
|
||||||
and (dif.reach in (None, -1)
|
|
||||||
or dif.reach in enabled_reaches)
|
|
||||||
),
|
|
||||||
self._data._data
|
self._data._data
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
|
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
|
import os
|
||||||
|
import psutil
|
||||||
import logging
|
import logging
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
@@ -120,7 +122,10 @@ class TimerWindow(PamhyrWindow):
|
|||||||
parent=parent
|
parent=parent
|
||||||
)
|
)
|
||||||
|
|
||||||
|
self._process = psutil.Process(os.getpid())
|
||||||
|
|
||||||
self.setup_table()
|
self.setup_table()
|
||||||
|
self.setup_label()
|
||||||
self.setup_alarm()
|
self.setup_alarm()
|
||||||
self.setup_connections()
|
self.setup_connections()
|
||||||
|
|
||||||
@@ -136,6 +141,15 @@ class TimerWindow(PamhyrWindow):
|
|||||||
data=None,
|
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):
|
def setup_alarm(self):
|
||||||
self._alarm = QTimer()
|
self._alarm = QTimer()
|
||||||
self._alarm.start(2000)
|
self._alarm.start(2000)
|
||||||
@@ -148,6 +162,7 @@ class TimerWindow(PamhyrWindow):
|
|||||||
|
|
||||||
def update(self):
|
def update(self):
|
||||||
self._table.update_lst()
|
self._table.update_lst()
|
||||||
|
self.setup_label()
|
||||||
|
|
||||||
# def reset(self):
|
# def reset(self):
|
||||||
# self._table.reset_timers()
|
# 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()
|
||||||
+19
-9
@@ -1,5 +1,5 @@
|
|||||||
# translate.py -- Pamhyr
|
# Translate.py -- Pamhyr
|
||||||
# Copyright (C) 2023-2025 INRAE
|
# Copyright (C) 2023-2026 INRAE
|
||||||
#
|
#
|
||||||
# This program is free software: you can redistribute it and/or modify
|
# 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
|
# it under the terms of the GNU General Public License as published by
|
||||||
@@ -23,18 +23,28 @@ from View.Translate import MainTranslate
|
|||||||
_translate = QCoreApplication.translate
|
_translate = QCoreApplication.translate
|
||||||
|
|
||||||
|
|
||||||
class BCTemperatureTranslate(MainTranslate):
|
class EnsemblesTranslate(MainTranslate):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
super(BCTemperatureTranslate, self).__init__()
|
super(EnsemblesTranslate, self).__init__()
|
||||||
|
|
||||||
self._dict["Boundary conditions temperature"] = _translate(
|
self._dict["Ensembles"] = _translate(
|
||||||
"BoundaryConditionsTemperature", "Boundary conditions temperature"
|
"Ensembles", "Ensembles"
|
||||||
)
|
)
|
||||||
self._dict["default"] = _translate(
|
|
||||||
"BoundaryConditionsTemperature", "default"
|
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"] = {
|
self._sub_dict["table_headers"] = {
|
||||||
"name": self._dict["name"],
|
"name": self._dict["name"],
|
||||||
"node": _translate("BoundaryCondition", "Node"),
|
"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()
|
||||||
@@ -20,7 +20,6 @@ import logging
|
|||||||
|
|
||||||
from tools import timer, flatten
|
from tools import timer, flatten
|
||||||
from View.Tools.PamhyrPlot import PamhyrPlot
|
from View.Tools.PamhyrPlot import PamhyrPlot
|
||||||
from View.Tools.CoefficientDisplay import display_coefficient
|
|
||||||
|
|
||||||
from PyQt5.QtCore import (
|
from PyQt5.QtCore import (
|
||||||
QCoreApplication
|
QCoreApplication
|
||||||
@@ -33,7 +32,7 @@ _translate = QCoreApplication.translate
|
|||||||
|
|
||||||
class PlotStricklers(PamhyrPlot):
|
class PlotStricklers(PamhyrPlot):
|
||||||
def __init__(self, data=None, canvas=None, trad=None,
|
def __init__(self, data=None, canvas=None, trad=None,
|
||||||
toolbar=None, display_manning=True, parent=None):
|
toolbar=None, parent=None):
|
||||||
super(PlotStricklers, self).__init__(
|
super(PlotStricklers, self).__init__(
|
||||||
canvas=canvas,
|
canvas=canvas,
|
||||||
trad=trad,
|
trad=trad,
|
||||||
@@ -43,11 +42,7 @@ class PlotStricklers(PamhyrPlot):
|
|||||||
)
|
)
|
||||||
|
|
||||||
self.label_x = self._trad["rk"]
|
self.label_x = self._trad["rk"]
|
||||||
self._display_manning = display_manning
|
self.label_y = self._trad["strickler_plot"]
|
||||||
self.label_y = (
|
|
||||||
self._trad["manning_plot"] if display_manning
|
|
||||||
else self._trad["strickler_plot"]
|
|
||||||
)
|
|
||||||
|
|
||||||
self.line_rk_elevation = [None, None]
|
self.line_rk_elevation = [None, None]
|
||||||
|
|
||||||
@@ -118,12 +113,8 @@ class PlotStricklers(PamhyrPlot):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
coef_minor = [
|
coef_minor = list(map(lambda s: s.minor, coef))
|
||||||
display_coefficient(s.minor, self._display_manning) for s in coef
|
coef_medium = list(map(lambda s: s.medium, coef))
|
||||||
]
|
|
||||||
coef_medium = [
|
|
||||||
display_coefficient(s.medium, self._display_manning) for s in coef
|
|
||||||
]
|
|
||||||
|
|
||||||
self.line_rk_elevation[0] = self.canvas.axes.plot(
|
self.line_rk_elevation[0] = self.canvas.axes.plot(
|
||||||
rk, coef_minor,
|
rk, coef_minor,
|
||||||
|
|||||||
+16
-81
@@ -42,7 +42,6 @@ from View.Frictions.UndoCommand import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
from View.Tools.PamhyrTable import PamhyrTableModel
|
from View.Tools.PamhyrTable import PamhyrTableModel
|
||||||
from View.Tools.CoefficientDisplay import display_strickler
|
|
||||||
|
|
||||||
from View.Frictions.translate import *
|
from View.Frictions.translate import *
|
||||||
|
|
||||||
@@ -52,64 +51,30 @@ _translate = QCoreApplication.translate
|
|||||||
|
|
||||||
|
|
||||||
class ComboBoxDelegate(QItemDelegate):
|
class ComboBoxDelegate(QItemDelegate):
|
||||||
def __init__(self, data=None, study=None, application_stricklers=None,
|
def __init__(self, data=None, study=None,
|
||||||
mode="stricklers", trad=None, display_manning=True,
|
mode="stricklers", trad=None, parent=None):
|
||||||
parent=None):
|
|
||||||
super(ComboBoxDelegate, self).__init__(parent)
|
super(ComboBoxDelegate, self).__init__(parent)
|
||||||
|
|
||||||
self._data = data
|
self._data = data
|
||||||
self._study = study
|
self._study = study
|
||||||
self._application_stricklers = application_stricklers or []
|
|
||||||
self._trad = trad
|
self._trad = trad
|
||||||
self._mode = mode
|
self._mode = mode
|
||||||
self._display_manning = display_manning
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def same_strickler(first, second):
|
|
||||||
return (
|
|
||||||
first.name == second.name
|
|
||||||
and first.comment == second.comment
|
|
||||||
and first.minor == second.minor
|
|
||||||
and first.medium == second.medium
|
|
||||||
)
|
|
||||||
|
|
||||||
def createEditor(self, parent, option, index):
|
def createEditor(self, parent, option, index):
|
||||||
self.editor = QComboBox(parent)
|
self.editor = QComboBox(parent)
|
||||||
|
|
||||||
if self._mode == "stricklers":
|
if self._mode == "stricklers":
|
||||||
self.editor.addItem(self._trad["not_defined"], None)
|
|
||||||
study_stricklers = self._study.river.stricklers.stricklers
|
|
||||||
for strickler in study_stricklers:
|
|
||||||
self.editor.addItem(
|
|
||||||
display_strickler(strickler, self._display_manning),
|
|
||||||
strickler
|
|
||||||
)
|
|
||||||
|
|
||||||
application_stricklers = [
|
|
||||||
application_strickler
|
|
||||||
for application_strickler in self._application_stricklers
|
|
||||||
if not any(
|
|
||||||
self.same_strickler(
|
|
||||||
application_strickler, study_strickler
|
|
||||||
)
|
|
||||||
for study_strickler in study_stricklers
|
|
||||||
)
|
|
||||||
]
|
|
||||||
if application_stricklers:
|
|
||||||
self.editor.insertSeparator(self.editor.count())
|
|
||||||
for strickler in application_stricklers:
|
|
||||||
self.editor.addItem(
|
|
||||||
display_strickler(
|
|
||||||
strickler, self._display_manning
|
|
||||||
),
|
|
||||||
strickler
|
|
||||||
)
|
|
||||||
elif self._mode == "rk":
|
|
||||||
self.editor.addItems(
|
self.editor.addItems(
|
||||||
list(map(str, self._data.reach.get_rk()))
|
[self._trad["not_defined"]] +
|
||||||
|
list(
|
||||||
|
map(
|
||||||
|
lambda s: str(s),
|
||||||
|
self._study.river.stricklers.stricklers
|
||||||
|
)
|
||||||
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
self.editor.setCurrentText(str(index.data(Qt.DisplayRole)))
|
self.editor.setCurrentText(index.data(Qt.DisplayRole))
|
||||||
return self.editor
|
return self.editor
|
||||||
|
|
||||||
def setEditorData(self, editor, index):
|
def setEditorData(self, editor, index):
|
||||||
@@ -117,9 +82,8 @@ class ComboBoxDelegate(QItemDelegate):
|
|||||||
self.editor.currentTextChanged.connect(self.currentItemChanged)
|
self.editor.currentTextChanged.connect(self.currentItemChanged)
|
||||||
|
|
||||||
def setModelData(self, editor, model, index):
|
def setModelData(self, editor, model, index):
|
||||||
value = editor.currentData() if self._mode == "stricklers" else \
|
text = str(editor.currentText())
|
||||||
str(editor.currentText())
|
model.setData(index, text)
|
||||||
model.setData(index, value)
|
|
||||||
editor.close()
|
editor.close()
|
||||||
editor.deleteLater()
|
editor.deleteLater()
|
||||||
|
|
||||||
@@ -136,33 +100,10 @@ class ComboBoxDelegate(QItemDelegate):
|
|||||||
|
|
||||||
|
|
||||||
class FrictionTableModel(PamhyrTableModel):
|
class FrictionTableModel(PamhyrTableModel):
|
||||||
def __init__(self, *args, display_manning=False, **kwargs):
|
|
||||||
self.display_manning = display_manning
|
|
||||||
super(FrictionTableModel, self).__init__(*args, **kwargs)
|
|
||||||
|
|
||||||
def _setup_lst(self):
|
def _setup_lst(self):
|
||||||
self._lst = self._data.frictions
|
self._lst = self._data.frictions
|
||||||
self._study = self._opt_data
|
self._study = self._opt_data
|
||||||
|
|
||||||
def study_strickler(self, strickler):
|
|
||||||
if strickler is None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
study_stricklers = self._study.river.stricklers
|
|
||||||
if any(s is strickler for s in study_stricklers.stricklers):
|
|
||||||
return strickler
|
|
||||||
|
|
||||||
for current in study_stricklers.stricklers:
|
|
||||||
if ComboBoxDelegate.same_strickler(current, strickler):
|
|
||||||
return current
|
|
||||||
|
|
||||||
copied = study_stricklers.new(len(study_stricklers))
|
|
||||||
copied.name = strickler.name
|
|
||||||
copied.comment = strickler.comment
|
|
||||||
copied.minor = strickler.minor
|
|
||||||
copied.medium = strickler.medium
|
|
||||||
return copied
|
|
||||||
|
|
||||||
def data(self, index, role):
|
def data(self, index, role):
|
||||||
if role != Qt.ItemDataRole.DisplayRole:
|
if role != Qt.ItemDataRole.DisplayRole:
|
||||||
return QVariant()
|
return QVariant()
|
||||||
@@ -180,12 +121,12 @@ class FrictionTableModel(PamhyrTableModel):
|
|||||||
value = self._lst.get(row).begin_strickler
|
value = self._lst.get(row).begin_strickler
|
||||||
if value is None:
|
if value is None:
|
||||||
return self._trad["not_defined"]
|
return self._trad["not_defined"]
|
||||||
return display_strickler(value, self.display_manning)
|
return str(value)
|
||||||
elif self._headers[column] == "end_strickler":
|
elif self._headers[column] == "end_strickler":
|
||||||
value = self._lst.get(row).end_strickler
|
value = self._lst.get(row).end_strickler
|
||||||
if value is None:
|
if value is None:
|
||||||
return self._trad["not_defined"]
|
return self._trad["not_defined"]
|
||||||
return display_strickler(value, self.display_manning)
|
return str(value)
|
||||||
|
|
||||||
return QVariant()
|
return QVariant()
|
||||||
|
|
||||||
@@ -219,21 +160,15 @@ class FrictionTableModel(PamhyrTableModel):
|
|||||||
)
|
)
|
||||||
)
|
)
|
||||||
elif self._headers[column] == "begin_strickler":
|
elif self._headers[column] == "begin_strickler":
|
||||||
strickler = value if hasattr(value, "minor") else \
|
|
||||||
self._study.river.strickler(value)
|
|
||||||
strickler = self.study_strickler(strickler)
|
|
||||||
self._undo.push(
|
self._undo.push(
|
||||||
SetBeginStricklerCommand(
|
SetBeginStricklerCommand(
|
||||||
self._lst, row, strickler
|
self._lst, row, self._study.river.strickler(value)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
elif self._headers[column] == "end_strickler":
|
elif self._headers[column] == "end_strickler":
|
||||||
strickler = value if hasattr(value, "minor") else \
|
|
||||||
self._study.river.strickler(value)
|
|
||||||
strickler = self.study_strickler(strickler)
|
|
||||||
self._undo.push(
|
self._undo.push(
|
||||||
SetEndStricklerCommand(
|
SetEndStricklerCommand(
|
||||||
self._lst, row, strickler
|
self._lst, row, self._study.river.strickler(value)
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -67,9 +67,6 @@ class FrictionsWindow(PamhyrWindow):
|
|||||||
def __init__(self, reach=None, study=None, config=None, parent=None):
|
def __init__(self, reach=None, study=None, config=None, parent=None):
|
||||||
trad = FrictionsTranslate()
|
trad = FrictionsTranslate()
|
||||||
|
|
||||||
if config is None and parent is not None:
|
|
||||||
config = getattr(parent, "conf", None)
|
|
||||||
|
|
||||||
if reach is not None:
|
if reach is not None:
|
||||||
self._reach = reach
|
self._reach = reach
|
||||||
else:
|
else:
|
||||||
@@ -104,20 +101,8 @@ class FrictionsWindow(PamhyrWindow):
|
|||||||
self._delegate_stricklers = ComboBoxDelegate(
|
self._delegate_stricklers = ComboBoxDelegate(
|
||||||
data=self._reach,
|
data=self._reach,
|
||||||
study=self._study,
|
study=self._study,
|
||||||
application_stricklers=(
|
|
||||||
self._config.stricklers.stricklers
|
|
||||||
if self._config is not None else []
|
|
||||||
),
|
|
||||||
mode="stricklers",
|
mode="stricklers",
|
||||||
trad=self._trad,
|
trad=self._trad,
|
||||||
display_manning=getattr(self._config, "display_manning", False),
|
|
||||||
parent=self
|
|
||||||
)
|
|
||||||
self._delegate_rk = ComboBoxDelegate(
|
|
||||||
data=self._reach,
|
|
||||||
study=self._study,
|
|
||||||
mode="rk",
|
|
||||||
trad=self._trad,
|
|
||||||
parent=self
|
parent=self
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -130,27 +115,18 @@ class FrictionsWindow(PamhyrWindow):
|
|||||||
editable_headers = []
|
editable_headers = []
|
||||||
|
|
||||||
table = self.find(QTableView, f"tableView")
|
table = self.find(QTableView, f"tableView")
|
||||||
table_headers = self._trad.get_dict("table_headers").copy()
|
|
||||||
table_headers["begin_strickler"] = (
|
|
||||||
self._trad["manning"]
|
|
||||||
if getattr(self._config, "display_manning", False)
|
|
||||||
else self._trad["strickler"]
|
|
||||||
)
|
|
||||||
self._table = FrictionTableModel(
|
self._table = FrictionTableModel(
|
||||||
table_view=table,
|
table_view=table,
|
||||||
table_headers=table_headers,
|
table_headers=self._trad.get_dict("table_headers"),
|
||||||
editable_headers=editable_headers,
|
editable_headers=editable_headers,
|
||||||
delegates={
|
delegates={
|
||||||
"begin_rk": self._delegate_rk,
|
|
||||||
"end_rk": self._delegate_rk,
|
|
||||||
"begin_strickler": self._delegate_stricklers,
|
"begin_strickler": self._delegate_stricklers,
|
||||||
# "end_strickler": self._delegate_stricklers,
|
"end_strickler": self._delegate_stricklers,
|
||||||
},
|
},
|
||||||
data=self._reach,
|
data=self._reach,
|
||||||
trad=self._trad,
|
trad=self._trad,
|
||||||
undo=self._undo_stack,
|
undo=self._undo_stack,
|
||||||
opt_data=self._study,
|
opt_data=self._study
|
||||||
display_manning=getattr(self._config, "display_manning", False)
|
|
||||||
)
|
)
|
||||||
table.setModel(self._table)
|
table.setModel(self._table)
|
||||||
table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
table.setSelectionBehavior(QAbstractItemView.SelectRows)
|
||||||
@@ -182,8 +158,7 @@ class FrictionsWindow(PamhyrWindow):
|
|||||||
canvas=self.canvas_2,
|
canvas=self.canvas_2,
|
||||||
data=self._reach,
|
data=self._reach,
|
||||||
trad=self._trad,
|
trad=self._trad,
|
||||||
toolbar=None,
|
toolbar=None
|
||||||
display_manning=getattr(self._config, "display_manning", False)
|
|
||||||
)
|
)
|
||||||
self.plot_2.draw()
|
self.plot_2.draw()
|
||||||
|
|
||||||
@@ -223,41 +198,9 @@ class FrictionsWindow(PamhyrWindow):
|
|||||||
# self._propagate_update(key=Modules.FRICTION)
|
# self._propagate_update(key=Modules.FRICTION)
|
||||||
|
|
||||||
def _propagated_update(self, key=Modules(0)):
|
def _propagated_update(self, key=Modules(0)):
|
||||||
if Modules.CONFIG in key:
|
if Modules.GEOMETRY not in key:
|
||||||
self.update_config()
|
return
|
||||||
|
|
||||||
if Modules.GEOMETRY in key:
|
|
||||||
self.update_plot()
|
|
||||||
|
|
||||||
for _, window in self.sub_win_list:
|
|
||||||
window._propagated_update(key=key)
|
|
||||||
|
|
||||||
def update_config(self):
|
|
||||||
display_manning = getattr(
|
|
||||||
self._config, "display_manning", False
|
|
||||||
)
|
|
||||||
|
|
||||||
self._delegate_stricklers._application_stricklers = (
|
|
||||||
self._config.stricklers.stricklers
|
|
||||||
if self._config is not None else []
|
|
||||||
)
|
|
||||||
self._delegate_stricklers._display_manning = display_manning
|
|
||||||
|
|
||||||
self._table.display_manning = display_manning
|
|
||||||
self._table._table_headers["begin_strickler"] = (
|
|
||||||
self._trad["manning"] if display_manning
|
|
||||||
else self._trad["strickler"]
|
|
||||||
)
|
|
||||||
self._table.headerDataChanged.emit(
|
|
||||||
Qt.Horizontal, 0, self._table.columnCount() - 1
|
|
||||||
)
|
|
||||||
self._table.layoutChanged.emit()
|
|
||||||
|
|
||||||
self.plot_2._display_manning = display_manning
|
|
||||||
self.plot_2.label_y = (
|
|
||||||
self._trad["manning_plot"] if display_manning
|
|
||||||
else self._trad["strickler_plot"]
|
|
||||||
)
|
|
||||||
self.update_plot()
|
self.update_plot()
|
||||||
|
|
||||||
def _set_current_reach(self):
|
def _set_current_reach(self):
|
||||||
@@ -322,13 +265,13 @@ class FrictionsWindow(PamhyrWindow):
|
|||||||
def edit_stricklers(self):
|
def edit_stricklers(self):
|
||||||
if self.sub_window_exists(
|
if self.sub_window_exists(
|
||||||
StricklersWindow,
|
StricklersWindow,
|
||||||
data=[self._study, self._config]
|
data=[self._study, self.parent.conf]
|
||||||
):
|
):
|
||||||
return
|
return
|
||||||
|
|
||||||
strick = StricklersWindow(
|
strick = StricklersWindow(
|
||||||
study=self._study,
|
study=self._study,
|
||||||
config=self._config,
|
config=self.parent.conf,
|
||||||
parent=self
|
parent=self
|
||||||
)
|
)
|
||||||
strick.show()
|
strick.show()
|
||||||
|
|||||||
@@ -31,18 +31,9 @@ class FrictionsTranslate(MainTranslate):
|
|||||||
self._dict["strickler_plot"] = _translate(
|
self._dict["strickler_plot"] = _translate(
|
||||||
"Frictions", "Strickler ($m^{1/3}/s$)"
|
"Frictions", "Strickler ($m^{1/3}/s$)"
|
||||||
)
|
)
|
||||||
self._dict["manning_plot"] = _translate(
|
|
||||||
"Frictions", "Manning ($s/m^{1/3}$)"
|
|
||||||
)
|
|
||||||
self._dict["stricklers"] = _translate(
|
self._dict["stricklers"] = _translate(
|
||||||
"Frictions", "Stricklers"
|
"Frictions", "Stricklers"
|
||||||
)
|
)
|
||||||
self._dict["strickler"] = _translate(
|
|
||||||
"Frictions", "Strickler"
|
|
||||||
)
|
|
||||||
self._dict["manning"] = _translate(
|
|
||||||
"Frictions", "Manning"
|
|
||||||
)
|
|
||||||
|
|
||||||
self._dict["Edit frictions"] = _translate(
|
self._dict["Edit frictions"] = _translate(
|
||||||
"Frictions", "Edit frictions"
|
"Frictions", "Edit frictions"
|
||||||
|
|||||||
@@ -112,7 +112,7 @@ class PlotAC(PamhyrPlot):
|
|||||||
profile_id = 0
|
profile_id = 0
|
||||||
|
|
||||||
profile = self.data.profile(profile_id)
|
profile = self.data.profile(profile_id)
|
||||||
if profile is None or self._parent.tableView.isRowHidden(profile_id):
|
if profile is None:
|
||||||
return
|
return
|
||||||
|
|
||||||
station = profile.get_station()
|
station = profile.get_station()
|
||||||
@@ -192,24 +192,21 @@ class PlotAC(PamhyrPlot):
|
|||||||
self.plot_selected.set_data([], [])
|
self.plot_selected.set_data([], [])
|
||||||
self.next_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.previous_plot_selected.set_data(
|
||||||
self.data.profile(previous_id).get_station(),
|
self.data.profile(previous_id).get_station(),
|
||||||
self.data.profile(previous_id).z()
|
self.data.profile(previous_id).z()
|
||||||
)
|
)
|
||||||
self.previous_plot_selected.set_visible(True)
|
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.plot_selected.set_data(
|
||||||
self.data.profile(profile_id).get_station(),
|
self.data.profile(profile_id).get_station(),
|
||||||
self.data.profile(profile_id).z()
|
self.data.profile(profile_id).z()
|
||||||
)
|
)
|
||||||
self.plot_selected.set_visible(True)
|
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.next_plot_selected.set_data(
|
||||||
self.data.profile(next_id).get_station(),
|
self.data.profile(next_id).get_station(),
|
||||||
self.data.profile(next_id).z()
|
self.data.profile(next_id).z()
|
||||||
|
|||||||
Loaded 100 of 221 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user