-
Notifications
You must be signed in to change notification settings - Fork 3
/
ClassMascaret.py
3318 lines (2953 loc) · 139 KB
/
ClassMascaret.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
/***************************************************************************
Name : Mascaret
Description : Pre and Postprocessing for Mascaret for QGIS
Date : June,2017
copyright : (C) 2017 by Artelia
email :
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
import copy
import csv
import datetime
import gc
import json
import os
import re
import shutil
import subprocess
import sys
from xml.etree.ElementTree import ElementTree, Element, SubElement
from xml.etree.ElementTree import parse as et_parse
from qgis.PyQt.QtCore import qVersion
from qgis.core import *
from qgis.gui import *
from qgis.utils import *
from .Function import del_symbol
from .Function import str2bool, del_accent, copy_dir_to_dir
from .Graphic.ClassResProfil import ClassResProfil
from .HydroLawsDialog import dico_typ_law
from .Structure.ClassMascStruct import ClassMascStruct
from .Structure.ClassPostPreFG import ClassPostPreFG
from .WaterQuality.ClassMascWQ import ClassMascWQ
from .api.ClassAPIMascaret import ClassAPIMascaret
from .ui.custom_control import ClassWarningBox
if int(qVersion()[0]) < 5: # qt4
from qgis.PyQt.QtGui import *
else: # qt5
from qgis.PyQt.QtWidgets import *
class ClassMascaret:
""" Class contain model files creation and run model mascaret"""
def __init__(self, main, rep_run=None):
self.mgis = main
self.mdb = self.mgis.mdb
self.iface = self.mgis.iface
if not rep_run:
self.dossierFileMasc = os.path.join(self.mgis.masplugPath,
"mascaret")
else:
self.dossierFileMasc = rep_run
if not os.path.isdir(self.dossierFileMasc):
os.mkdir(self.dossierFileMasc)
self.dossierFileMascOri = os.path.join(self.mgis.masplugPath,
"mascaret_ori")
self.dossierFile_bin = os.path.join(self.mgis.masplugPath, "bin")
self.baseName = "mascaret"
self.nomfichGEO = self.baseName + ".geo"
self.box = ClassWarningBox()
# state list
self.listeState = ['Steady', 'Unsteady', 'Transcritical unsteady']
# kernel list
self.Klist = ["steady", "unsteady", "transcritical"]
self.dico_basinnum = {}
self.dico_linknum = {}
self.wq = ClassMascWQ(self.mgis, self.dossierFileMasc)
self.clmeth = ClassMascStruct(self.mgis)
self.cond_api = self.mgis.cond_api
self.save_res_struct = None
def creer_geo(self):
"""creation of gemoetry file"""
try:
nomfich = os.path.join(self.dossierFileMasc, self.baseName + '.geo')
if os.path.isfile(nomfich):
sauv = nomfich.replace(".geo", "_old.geo")
shutil.move(nomfich, sauv)
requete = self.mdb.select("profiles", "active", "abscissa")
with open(nomfich, 'w') as fich:
for i, nom in enumerate(requete["name"]):
branche = requete["branchnum"][i]
abs = requete["abscissa"][i]
temp_x = requete["x"][i]
temp_z = requete["z"][i]
lit_min_g = requete["leftminbed"][i]
lit_min_d = requete["rightminbed"][i]
if lit_min_d is not None and lit_min_g is None:
lit_min_g = 0.0
if branche and abs and temp_x and temp_z and lit_min_g \
and lit_min_d:
# tabX = list(map(lambda x: round(float(x), 2),
# temp_x.split()))
# tab_z = list(map(lambda x: round(float(x), 2),
# temp_z.split()))
tab_z = []
tab_x = []
# fct1 = lambda x: round(float(x), 2)
for var1, var2 in zip(temp_x.split(), temp_z.split()):
tab_x.append(self.around(var1))
tab_z.append(self.around(var2))
fich.write('PROFIL Bief_{0} {1} {2}\n'.format(branche,
nom, abs))
for x, z in zip(tab_x, tab_z):
if lit_min_g <= x <= lit_min_d:
type = "B"
else:
type = "T"
fich.write(
'{0:.2f} {1:.2f} {2}\n'.format(x, z, type))
self.mgis.add_info("Creation the geometry is done")
except Exception as e:
err = "Error: save the geometry .\n"
err += str(e)
self.mgis.add_info(err)
raise Exception(err)
def creer_geo_ref(self):
# """creation of gemoetry file"""
try:
branche, nom = None, None
nomfich = os.path.join(self.dossierFileMasc, self.baseName + '.geo')
if os.path.isfile(nomfich):
sauv = nomfich.replace(".geo", "_old.geo")
shutil.move(nomfich, sauv)
requete = self.mdb.select("profiles", "active", "abscissa")
# To get projection and Line coordinated.
vlayer = self.mdb.make_vlayer(self.mdb.register['profiles'])
vlayer_dp = vlayer.dataProvider()
vlayer_crs = vlayer_dp.crs()
vlayer_crs_str = vlayer_crs.authid()
# Write the File
with open(nomfich, 'w') as fich:
fich.write('# DATE : {0:%d/%m/%Y %H:%M:%S}\n'
'# PROJ. : {1}\n'.format(datetime.date.today(),
vlayer_crs_str))
iter = vlayer.getFeatures()
feature_list = [v for v in iter]
name_feature = [v['name'] for v in feature_list]
for i, nom in enumerate(requete["name"]):
if nom in name_feature:
id = name_feature.index(nom)
# fetch geometry
geom = feature_list[id].geometry()
branche = requete["branchnum"][i]
abs = requete["abscissa"][i]
temp_x = requete["x"][i]
temp_z = requete["z"][i]
lit_min_g = requete["leftminbed"][i]
lit_min_d = requete["rightminbed"][i]
if lit_min_d is not None and lit_min_g is None:
lit_min_g = 0.0
if branche is not None and abs is not None \
and temp_x is not None \
and temp_z is not None \
and lit_min_g is not None \
and lit_min_d is not None:
tab_z = []
tab_x = []
# fct1 = lambda x: round(float(x), 2)
for var1, var2 in zip(temp_x.split(),
temp_z.split()):
tab_x.append(self.around(var1))
tab_z.append(self.around(var2))
points = geom.asMultiPolyline()[0]
(cood1X, cood1Y) = points[0]
(cood2X, cood2Y) = points[1]
cood_axe_x = cood1X + (cood2X - cood1X) / 2.
cood_axe_y = cood1Y + (cood2Y - cood1Y) / 2.
fich.write(
'PROFIL Bief_{0} {1} {2} {3} {4} {5} {6} '
'AXE {7} {8}\n'.format(
branche, nom,
abs,
cood1X, cood1Y,
cood2X, cood2Y,
cood_axe_x,
cood_axe_y))
dif = tab_x[-1] - geom.length()
if dif > 0:
dif += 1
# garde line centree
geom = geom.extendLine(dif / 2., dif / 2.)
feature_list[id].setGeometry(geom)
# change geometry
vlayer.startEditing()
vlayer.updateFeature(feature_list[id])
# Call commit to save the changes
vlayer.commitChanges()
for x, z in zip(tab_x, tab_z):
if lit_min_g <= x <= lit_min_d:
type = "B"
else:
type = "T"
# interpolate the distance on profile
dpoint = geom.interpolate(x).asPoint()
fich.write(
'{0:.2f} {1:.2f} {2} {3} '
'{4}\n'.format(x, z,
type,
dpoint[
0],
dpoint[
1]))
self.mgis.add_info("Creation the geometry is done")
except Exception as e:
err = "Error: save the geometry {}-{}".format(branche, nom)
err += str(e)
self.mgis.add_info(err)
raise Exception(err)
# Fonction de creation du fichier .casier avec la loi surface-volume
def creer_geo_casier(self):
try:
nomfich = os.path.join(self.dossierFileMasc,
self.baseName + '.casier')
if os.path.isfile(nomfich):
sauv = nomfich.replace(".casier", "_old.casier")
shutil.move(nomfich, sauv)
casiers = self.mdb.select("basins", "active ORDER BY basinnum")
with open(nomfich, 'w') as fich:
for i, nom in enumerate(casiers["name"]):
fich.write('CASIER {0}\n'.format(nom))
cotes = casiers["level"][i]
surfaces = casiers["area"][i]
volumes = casiers["volume"][i]
for j, cote in enumerate(cotes.split()):
fich.write(
'{0:.2f} {1:.2f} {2:.2f}\n'.format(
float(cotes.split()[j]),
float(surfaces.split()[j]),
float(volumes.split()[j])))
self.mgis.add_info("Creation of the basin file is done")
except Exception as e:
err = "Error: save the basin file"
err += str(e)
self.mgis.add_info(err)
raise Exception(err)
# Fonction de remplacement des None de la liste par la valeur
# remplaceNone
# cad -1 ou -1.0 pour le moteur Mascaret
def fmt_sans_none(self, liste, remplace_none):
liste = [remplace_none if var is None else var for var in liste]
return " ".join([str(var) for var in liste])
# Fonction de transformation de la liste de numeros basin/link sous
# Qgis en une chaine de numeros pour le moteur Mascaret
def fmt_num_basin(self, liste, dico_num, remplace_none):
liste_num_masca = []
for num_qgis in liste:
if num_qgis is None:
# Ajout d'une valeur nulle codee ici par remplaceNone, cad -1
# ou -1.0, pour le moteur mascaret
liste_num_masca.append(remplace_none)
else:
# Inversion du dictionnaire: on cherche le numero mascaret
# pour le numero de casier sous Qgis
liste_num_masca.append(list(dico_num.keys())[
list(dico_num.values()).index(
num_qgis)])
return " ".join([str(var) for var in liste_num_masca])
# Fonction de calcul du planimetrage entre 2 niveaux de la loi surface
# volume du casier
def fmt_plani_casier(self, liste):
liste_plani = []
for chaine_z in liste:
try:
liste_z = chaine_z.split()
# Calcul des parties entieres et decimale de la planimetrie
plani_entier = int((float(liste_z[1]) - float(liste_z[0])) // 1)
liste_plani.append(str(plani_entier))
plani_decimale = int(
(float(liste_z[1]) - float(liste_z[0])) % 1)
if plani_decimale > 0:
self.mgis.add_info(
"Simulation Error: the basin planimetry has "
"to be an integer value")
except:
self.mgis.add_info(
"Simulation Error: the basin planimetry is not correct")
return " ".join([str(var) for var in liste_plani])
def indent(self, elem, level=0):
"""indentation auto"""
i = '\n' + level * ' '
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + ' '
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
self.indent(elem, level + 1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
elif level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def planim_select(self):
sql = """SELECT MIN(t1.planim) AS pas, MIN(t2.nombre),MAX(t2.nombre)
FROM (SELECT branch, planim, ST_UNION(geom) AS geom
FROM (SELECT branch,
planim,
geom,
row_number()
OVER (PARTITION BY branch, planim
ORDER BY branch,zonenum)
- zonenum AS grp
FROM {0}.branchs
WHERE active) x
GROUP BY branch, planim, grp) AS t1,
(SELECT ROW_NUMBER() OVER(ORDER BY abscissa) AS nombre, geom
FROM {0}.profiles
WHERE active ) AS t2
WHERE ST_INTERSECTS(t1.geom,t2.geom)
GROUP BY t1.geom
ORDER BY min;"""
(results, namCol) = self.mdb.run_query(sql.format(self.mdb.SCHEMA),
fetch=True, namvar=True)
dico = {}
colonnes = [col[0] for col in namCol]
for col in colonnes:
dico[col] = []
for row in results:
for i, val in enumerate(row):
try:
dico[colonnes[i]].append(val.strip())
except:
dico[colonnes[i]].append(val)
return dico
def maillage_select(self):
sql = """SELECT MIN(t1.mesh) AS pas,
MIN(t2.nombre),
MAX(t2.nombre)+MIN(diff)+1 AS max
FROM (SELECT branch, mesh,
ST_UNION(geom) AS geom,
MIN(diff) AS diff
FROM (SELECT branch,
mesh,
geom,
row_number()
OVER (PARTITION BY branch,
mesh ORDER BY branch,zonenum)
- zonenum AS grp,
branch-lead(branch,1,branch+1)
OVER (ORDER BY branch,zonenum) AS diff
FROM {0}.branchs
WHERE active) x
GROUP BY branch, mesh, grp) AS t1,
(SELECT ROW_NUMBER() OVER(ORDER BY abscissa)
AS nombre, geom
FROM {0}.profiles
WHERE active ) AS t2
WHERE ST_INTERSECTS(t1.geom,t2.geom)
GROUP BY t1.geom
ORDER BY min;"""
(results, namCol) = self.mdb.run_query(sql.format(self.mdb.SCHEMA),
fetch=True, namvar=True)
dico = {}
colonnes = [col[0] for col in namCol]
for col in colonnes:
dico[col] = []
for row in results:
for i, val in enumerate(row):
try:
dico[colonnes[i]].append(val.strip())
except:
dico[colonnes[i]].append(val)
return dico
def geom_obj_toname(self, nom, type_):
""" get name law"""
condition = "geom_obj='{0}' AND " \
"id_law_type={1} AND active".format(nom, type_)
inf_law = self.mdb.select_one('law_config', condition)
if inf_law:
if 'name' in inf_law.keys():
return inf_law['name']
return nom
def creer_xcas(self, noyau):
"""To create xcas file"""
dict_lois = {}
# try:
fichier_sortie = os.path.join(self.dossierFileMasc,
self.baseName + ".xcas")
extr_toloi = {0: 6, 1: 1, 2: 2, 3: 4, 4: 5, 5: 4, 8: 3, 6: 6, 7: 7}
abaque_toloi = {1: 6, 2: 4, 5: 2, 6: 5, 7: 5, 8: 7}
# création du fichier xml
fichier_cas = Element("fichier_cas")
cas = SubElement(fichier_cas, "parametresCas")
sql = "SELECT {0} FROM {1}.{2} WHERE parametre='presenceTraceurs';"
rows = self.mdb.run_query(
sql.format(noyau, self.mdb.SCHEMA, "parametres"), fetch=True)
if rows is not None:
tracer = str2bool(rows[0][0])
else:
tracer = False
# requête pour récupérer les paramètres
sql = "SELECT parametre, {0}, balise1, balise2 FROM {1}.{2} " \
"WHERE gui_type = 'parameters' ORDER BY id;"
rows = self.mdb.run_query(
sql.format(noyau, self.mdb.SCHEMA, "parametres"), fetch=True)
for param, valeur, b1, b2 in rows:
# self.mgis.add_info("valeur : {0}, param : {1} , b1 : {2} , b2:
# {3}".format(valeur, param, b1, b2))
if b1:
try:
cas.find(b1).text
except:
balise1 = SubElement(cas, b1)
# if not cas.find(b1):
# balise1 = SubElement(cas, b1)
if b2:
try:
balise1.find(b2).text
except:
balise2 = SubElement(balise1, b2)
# if not balise1.find(b2):
# balise2 = SubElement(balise1, b2)
par = SubElement(balise2, param)
par.text = valeur.lower()
else:
par = SubElement(balise1, param)
par.text = valeur.lower()
# requete sur les couches
apports = self.mdb.select("lateral_inflows", "active", "abscissa")
var = "branch, startb, endb"
branches = self.mdb.select_distinct(var, "branchs", "active")
zones = self.mdb.select("branchs", "active", "branch, zoneabsstart")
deversoirs = self.mdb.select("lateral_weirs", "active", "abscissa")
noeuds = self.mdb.select("extremities", "type=10", "active")
libres = self.mdb.select("extremities", "type!=10 ", "active")
pertescharg = self.mdb.select("hydraulic_head", "active", "abscissa")
profils = self.mdb.select("profiles", "active", "abscissa")
prof_seuil = self.mdb.select("profiles", "NOT active", "abscissa")
seuils = self.mdb.select("weirs", "active", "abscissa")
sorties = self.mdb.select("outputs", "active", "abscissa")
planim = self.planim_select()
maillage = self.maillage_select()
dico_str = self.mdb.select('struct_config', "active", "abscissa")
seuils, loi_struct = self.modif_seuil(seuils, dico_str)
casiers = self.mdb.select("basins", "active ORDER BY basinnum ")
liaisons = self.mdb.select("links", "active ORDER BY linknum ")
# Extrémités
numero = branches["branch"]
branches["abscdebut"] = []
branches["abscfin"] = []
liste = list(zip(profils["abscissa"], profils["branchnum"]))
for i, num in enumerate(numero):
temp = [a for a, n in liste if n == num]
if temp:
branches["abscdebut"].append(min(temp))
branches["abscfin"].append(max(temp))
else:
self.mgis.add_info('Checked if the profiles are activated.')
dict_noeuds = {}
dict_libres = {"nom": [], "num": [], "extrem": [], "typeCond": [],
"typeCond_tr": [], "law_wq": []}
# 'law_wq','active','tracer_boundary_condition_type',num
for n, d, f in zip(numero, branches["startb"], branches["endb"]):
if noeuds and d in noeuds["name"]:
if d not in dict_noeuds.keys():
dict_noeuds[d] = []
dict_noeuds[d].append(n * 2 - 1)
if noeuds and f in noeuds["name"]:
if f not in dict_noeuds.keys():
dict_noeuds[f] = []
dict_noeuds[f].append(n * 2)
if libres and d in libres["name"]:
i = libres["name"].index(d)
type = libres["type"][i]
formule = libres["method"][i]
dict_libres["nom"].append(libres["name"][i])
dict_libres["typeCond"].append(type)
dict_libres["num"].append(len(dict_libres["nom"]))
dict_libres["extrem"].append(n * 2 - 1)
dict_libres["typeCond_tr"].append(
libres["tracer_boundary_condition_type"][i])
dict_libres["law_wq"].append(libres["law_wq"][i])
dict_lois[d] = {'type': extr_toloi[type],
'formule': formule,
'valeurperm': libres["firstvalue"][i],
'couche': 'extremites'}
if libres and f in libres["name"]:
i = libres["name"].index(f)
type = libres["type"][i]
formule = libres["method"][i]
dict_libres["nom"].append(libres["name"][i])
dict_libres["typeCond"].append(type)
dict_libres["num"].append(len(dict_libres["nom"]))
dict_libres["extrem"].append(n * 2)
dict_libres["typeCond_tr"].append(
libres["tracer_boundary_condition_type"][i])
dict_libres["law_wq"].append(libres["law_wq"][i])
dict_lois[f] = {'type': extr_toloi[type],
'formule': formule,
'valeurperm': libres["firstvalue"][i],
'couche': 'extremites'}
# Zones
nb_pas = 0
i = 0
# zones['num1erProf'] = [1] * len(zones["zoneabsstart"])
# zones['numDerProfPlanim'] = [1] * len(zones["zoneabsstart"])
# zones['numDerProfMaill'] = [1] * len(zones["zoneabsstart"])
liste_stock = {"numProfil": [],
'limGauchLitMaj': [],
'limDroitLitMaj': []}
tab = zip(profils["abscissa"],
profils["x"],
profils["z"],
profils["leftstock"],
profils["rightstock"],
profils["branchnum"])
for j, (abs, x, z, sg, sd, n) in enumerate(tab):
try:
xx = [float(var) for var in x.split()]
zz = [float(var) for var in z.split()]
diff = max(zz) - min(zz)
except:
self.mgis.add_info("Check the {} profile if it's ok ".format(
profils["name"][j]))
raise Exception("Check the {} profile if it's ok ".format(
profils["name"][j]))
return dict_lois
if abs > zones['zoneabsend'][i]:
i = i + 1
try:
nb_pas = max(int(diff / float(zones['planim'][i])) + 1, nb_pas)
except:
self.mgis.add_info("Check planim ")
index = numero.index(n)
zones["zoneabsstart"][i] = max(zones["zoneabsstart"][i],
branches["abscdebut"][index])
zones["zoneabsend"][i] = min(zones["zoneabsend"][i],
branches["abscfin"][index])
if sg or sd:
if sg:
lim_gauch_lit_maj = sg
else:
lim_gauch_lit_maj = min(xx)
if sd:
lim_droit_lit_maj = sd
else:
lim_droit_lit_maj = max(xx)
liste_stock["numProfil"].append(j + 1)
liste_stock["limGauchLitMaj"].append(lim_gauch_lit_maj)
liste_stock["limDroitLitMaj"].append(lim_droit_lit_maj)
for i, type in enumerate(seuils["type"]):
if type not in (3, 4):
dict_lois[seuils["name"][i]] = {'type': abaque_toloi[type],
'couche': 'seuils'}
for i, nom in enumerate(apports["name"]):
if nom not in dict_lois.keys():
dict_lois[nom] = {'type': 1,
'formule': apports['method'][i],
'valeurperm': apports["firstvalue"][i],
'couche': 'apports'}
for i, nom in enumerate(deversoirs["name"]):
if nom not in dict_lois.keys() and deversoirs["type"][i] == 2:
dict_lois[nom] = {'type': 4, 'couche': 'deversoirs'}
# Géométrie du réseau
reseau = cas.find("parametresGeometrieReseau")
# liste des Branches
liste_branch = SubElement(reseau, "listeBranches")
SubElement(liste_branch, "nb").text = str(len(numero))
SubElement(liste_branch, "numeros").text = self.fmt(numero)
SubElement(liste_branch, "abscDebut").text = self.fmt(
branches["abscdebut"])
SubElement(liste_branch, "abscFin").text = self.fmt(branches["abscfin"])
extrem_debut = [i * 2 - 1 for i in numero]
SubElement(liste_branch, "numExtremDebut").text = self.fmt(extrem_debut)
extrem_fin = [i * 2 for i in numero]
SubElement(liste_branch, "numExtremFin").text = self.fmt(extrem_fin)
# liste des Noeuds
liste_noeuds = SubElement(reseau, "listeNoeuds")
SubElement(liste_noeuds, "nb").text = str(len(dict_noeuds.keys()))
e_tnoeuds = SubElement(liste_noeuds, "noeuds")
for k in sorted(dict_noeuds.keys()):
noeud = SubElement(e_tnoeuds, "noeud")
temp = dict_noeuds[k] + [0] * (5 - len(dict_noeuds[k]))
SubElement(noeud, "num").text = self.fmt(temp)
# liste des extrémités libres
extr_libres = SubElement(reseau, "extrLibres")
liste = dict_libres["nom"]
SubElement(extr_libres, "nb").text = str(len(liste))
SubElement(extr_libres, "num").text = self.fmt(dict_libres["num"])
SubElement(extr_libres, "numExtrem").text = self.fmt(
dict_libres["extrem"])
noms = SubElement(extr_libres, "noms")
for nom in liste:
SubElement(noms, "string").text = nom
SubElement(extr_libres, "typeCond").text = self.fmt(
dict_libres["typeCond"])
# temp=[]
# for nom in liste:
# if nom in libres["name"] and (dictLois[nom]['type'] == 6 or dictLois[nom]['type'] == 7):
# temp.append(1)
# else:
# temp.append(sorted(dictLois.keys()).index(nom) + 1)
temp = [sorted(dict_lois.keys()).index(nom) + 1 for nom in liste]
SubElement(extr_libres, "numLoi").text = self.fmt(temp)
# Confluents
confluents = SubElement(cas, "parametresConfluents")
SubElement(confluents, "nbConfluents").text = str(
len(dict_noeuds.keys()))
confluent = SubElement(confluents, "confluents")
for k in sorted(dict_noeuds.keys()):
struct = SubElement(confluent, "structureParametresConfluent")
l = len(dict_noeuds[k])
SubElement(struct, "nbAffluent").text = str(l)
SubElement(struct, "nom").text = k
i = noeuds["name"].index(k)
a_en = ["abscissa", "ordinates", "angles"]
for kk, a in enumerate(["abscisses", "ordonnees", "angles"]):
if noeuds[a_en[kk]][i] is None or l != 3:
SubElement(struct, a).text = " 0.0" * l
else:
SubElement(struct, a).text = noeuds[a_en[kk]][i]
# Planimétrage et maillage
planimaill = SubElement(cas, "parametresPlanimetrageMaillage")
SubElement(planimaill, "methodeMaillage").text = '5'
planim_e = SubElement(planimaill, "planim")
SubElement(planim_e, 'nbPas').text = str(nb_pas)
SubElement(planim_e, 'nbZones').text = str(len(planim["pas"]))
SubElement(planim_e, 'valeursPas').text = self.fmt(planim['pas'])
SubElement(planim_e, 'num1erProf').text = self.fmt(planim['min'])
SubElement(planim_e, 'numDerProf').text = self.fmt(planim['max'])
maillage_e = SubElement(planimaill, "maillage")
SubElement(maillage_e, 'modeSaisie').text = '2'
SubElement(maillage_e, 'sauvMaillage').text = 'false'
maillage_c = SubElement(maillage_e, 'maillageClavier')
SubElement(maillage_c, 'nbSections').text = '0'
SubElement(maillage_c, 'nbPlages').text = str(len(maillage["pas"]))
SubElement(maillage_c, 'num1erProfPlage').text = self.fmt(
maillage['min'])
SubElement(maillage_c, 'numDerProfPlage').text = self.fmt(
maillage['max'])
SubElement(maillage_c, 'pasEspacePlage').text = self.fmt(
maillage['pas'])
SubElement(maillage_c, 'nbZones').text = '0'
# Singularites
singularite = SubElement(cas, "parametresSingularite")
# Seuils
SubElement(singularite, "nbSeuils").text = str(len(seuils["name"]))
if len(seuils["name"]) > 0:
e_tseuils = SubElement(singularite, "seuils")
liste = ["type", "numBranche", "abscisse", "coteCrete", "coteCreteMoy",
"coteRupture", "coeffDebit", "largVanne", "epaisseur"]
liste_en = ["type", "branchnum", "abscissa", "z_crest",
"z_average_crest",
"z_break", "flowratecoeff", "wide_floodgate", "thickness"]
for i, nom in enumerate(seuils["name"]):
struct = SubElement(e_tseuils, "structureParametresSeuil")
SubElement(struct, "nom").text = nom
for kk, l in enumerate(liste):
if seuils[liste_en[kk].lower()][i] is None:
SubElement(struct, l).text = '-0'
else:
SubElement(struct, l).text = str(
seuils[liste_en[kk].lower()][i])
if seuils["type"][i] not in (3, 4):
SubElement(struct, "numLoi").text = str(
sorted(dict_lois.keys()).index(nom) + 1)
else:
SubElement(struct, "numLoi").text = '-0'
if seuils["type"][i] != 3:
SubElement(struct, "nbPtLoiSeuil").text = '-0'
else:
try:
i = prof_seuil["name"].index(nom)
long = len(prof_seuil['x'][i].split())
SubElement(struct, "nbPtLoiSeuil").text = str(long)
# SubElement(struct, "abscTravCrete").text = prof_seuil['x'][i]
# SubElement(struct, "cotesCrete").text = prof_seuil['z'][i]
# traitment profil because of too many significant number
new_profx = ' '.join([str(round(float(vvv), 3))
for vvv in
prof_seuil['x'][i].split()])
SubElement(struct, "abscTravCrete").text = new_profx
new_profz = ' '.join([str(round(float(vvv), 3))
for vvv in
prof_seuil['z'][i].split()])
SubElement(struct, "cotesCrete").text = new_profz
except:
msg = 'Profil de crete introuvable pour {}'
QMessageBox.warning(None, 'Message', msg.format(nom))
return
SubElement(struct, "gradient").text = "-0"
# Pertes de charges
if len(pertescharg["name"]) > 0:
pertes = SubElement(singularite, "pertesCharges")
SubElement(pertes, "nbPerteCharge").text = str(
len(pertescharg["name"]))
SubElement(pertes, "numBranche").text = self.fmt(
pertescharg["branchnum"])
SubElement(pertes, "abscisses").text = self.fmt(
pertescharg["abscissa"])
SubElement(pertes, "coefficients").text = self.fmt(
pertescharg["coeff"])
# Casiers et liaisons
if len(casiers["name"]) > 0:
self.add_basin_xcas(fichier_cas, casiers, liaisons)
# Apports et déversoirs
apport_dever = SubElement(cas, "parametresApportDeversoirs")
# Apports
e_tapports = SubElement(apport_dever, "debitsApports")
SubElement(e_tapports, "nbQApport").text = str(len(apports["name"]))
noms = SubElement(e_tapports, "noms")
for nom in apports["name"]:
SubElement(noms, "string").text = nom
SubElement(e_tapports, "numBranche").text = self.fmt(
apports["branchnum"])
if self.check_none(apports["abscissa"]):
self.mgis.add_info(
'Warning : Geometric object for lateral inflows is not found')
SubElement(e_tapports, "abscisses").text = self.fmt(apports["abscissa"])
if self.check_none(apports["length"]):
self.mgis.add_info(
'Warning : Lenght for lateral inflows is not found')
SubElement(e_tapports, "longueurs").text = self.fmt(apports["length"])
temp = [sorted(dict_lois.keys()).index(nom) + 1 for nom in
apports["name"]]
SubElement(e_tapports, "numLoi").text = self.fmt(temp)
# Déversoirs
devers_late = SubElement(apport_dever, "devers_late")
SubElement(devers_late, "nbDeversoirs").text = str(
len(deversoirs["name"]))
noms = SubElement(devers_late, "noms")
for nom in deversoirs["name"]:
SubElement(noms, "string").text = nom
SubElement(devers_late, "type").text = self.fmt(deversoirs["type"])
l_en = ["branchnum", "abscissa", "length", "z_crest", "flowratecoef"]
for kk, l in enumerate(
["numBranche", "abscisse", "longueur", "coteCrete",
"coeffDebit"]):
SubElement(devers_late, l).text = self.fmt(
deversoirs[l_en[kk].lower()])
temp = []
for nom in deversoirs["name"]:
if nom in dict_lois.keys():
temp.append(sorted(dict_lois.keys()).index(nom) + 1)
else:
temp.append(0)
SubElement(devers_late, "numLoi").text = self.fmt(temp)
# Calage
calage = SubElement(cas, "parametresCalage")
# frottement
frottement = SubElement(calage, "frottement")
SubElement(frottement, "loi").text = '1'
SubElement(frottement, "nbZone").text = str(len(zones["zoneabsstart"]))
SubElement(frottement, "numBranche").text = self.fmt(zones["branch"])
l_en = ['zoneabsstart', 'zoneabsend', 'minbedcoef', 'majbedcoef']
for kk, l in enumerate(
["absDebZone", "absFinZone", "coefLitMin", "coefLitMaj"]):
SubElement(frottement, l).text = self.fmt(zones[l_en[kk].lower()])
# stockage
zone_stockage = SubElement(calage, "zoneStockage")
SubElement(zone_stockage, "loi").text = '1'
n = len(liste_stock["numProfil"])
SubElement(zone_stockage, "nbProfils").text = str(n)
for l in ["numProfil", "limGauchLitMaj", "limDroitLitMaj"]:
SubElement(zone_stockage, l).text = self.fmt(liste_stock[l])
# Lois hydrauliques
hydrauliques = SubElement(cas, "parametresLoisHydrauliques")
for nom in dict_lois.keys():
if nom in libres["name"] and (
dict_lois[nom]['type'] == 6 or \
dict_lois[nom]['type'] == 7):
# les types sont ceux de
if dict_lois[nom]['type'] == 6:
# TODO and noyau!='transcritical'
dict_lois[nom]['type'] = 1
if self.mgis.DEBUG:
self.mgis.add_info(
'The {} law changes type 6 => 1'.format(nom))
elif dict_lois[nom]['type'] == 7:
dict_lois[nom]['type'] = 2
if self.mgis.DEBUG:
self.mgis.add_info(
'The {} law changes type 7 => 2'.format(nom))
nb = len(dict_lois.keys())
SubElement(hydrauliques, "nb").text = str(nb)
lois = SubElement(hydrauliques, "lois")
for nom in sorted(dict_lois.keys()):
struct = SubElement(lois, "structureParametresLoi")
SubElement(struct, "nom").text = nom
SubElement(struct, "type").text = str(dict_lois[nom]['type'])
donnees = SubElement(struct, "donnees")
SubElement(donnees, "modeEntree").text = '1'
# WARNING The law must be sorted because of the order of law must be the same than order File.law for API
# SubElement(donnees, "fichier").text = '{}.loi'.format(
# del_symbol(self.geom_obj_toname(nom, dict_lois[nom]['type'])))
SubElement(donnees, "fichier").text = '{}.loi'.format(del_symbol(nom))
SubElement(donnees, "uniteTps").text = '-0'
SubElement(donnees, "nbPoints").text = '-0'
SubElement(donnees, "nbDebitsDifferents").text = '-0'
# impression résultats
init = cas.find("parametresImpressionResultats")
stockage = init.find("stockage")
SubElement(stockage, 'nbSite').text = str(len(sorties["name"]))
SubElement(stockage, 'branche').text = self.fmt(sorties["branchnum"])
SubElement(stockage, 'abscisse').text = self.fmt(sorties["abscissa"])
# ******** XCAS tracer ********
if tracer:
self.add_wq_xcas(fichier_cas, noyau, dict_libres)
# ******** XCAS modiication of type when steady case ********
# only type rating curve 4 => liminigraph et 5 => liminigraph
# if noyau == 'steady':
#
# param_cas = fichier_cas.find('parametresCas')
# # parametres_generaux = param_cas.find('parametresGeneraux')
# geom_reseau = param_cas.find('parametresGeometrieReseau')
# type_cond = geom_reseau.find('extrLibres').find('typeCond')
# type_cond.text = type_cond.text.replace('4', '2')
# lois_hydrauliques = param_cas.find('parametresLoisHydrauliques')
# lois = lois_hydrauliques.find('lois')
# for child in lois:
# # no possible to use rating curve with steady
# if child.find('type').text == '5':
# child.find('type').text = '2'
# **********************************
self.indent(fichier_cas)
arbre = ElementTree(fichier_cas)
arbre.write(fichier_sortie)
self.mgis.add_info("Save the Xcas file is done")
# ****** XCAS initialisation **********
temps_max = 3600
np_pas_temps_init = 2
dt_init = temps_max / np_pas_temps_init
param_cas = fichier_cas.find('parametresCas')
parametres_generaux = param_cas.find('parametresGeneraux')
fich_xcas = '{}_init.xcas'.format(self.baseName)
parametres_generaux.find('fichMotsCles').text = fich_xcas
parametres_generaux.find('code').text = '1'
parametres_generaux.find('presenceCasiers').text = 'false'
parametres_temporels = param_cas.find('parametresTemporels')
parametres_temporels.find('pasTemps').text = '{}'.format(dt_init)
parametres_temporels.find('critereArret').text = '2'
parametres_temporels.find('nbPasTemps').text = '{}'.format(
np_pas_temps_init)
parametres_temporels.find('tempsMax').text = '{}'.format(temps_max)
parametres_temporels.find('pasTempsVar').text = 'false'
geom_reseau = param_cas.find('parametresGeometrieReseau')
type_cond = geom_reseau.find('extrLibres').find('typeCond')
type_cond.text = type_cond.text.replace('4', '2')
# type_cond.text = type_cond.text.replace('4', '2').replace('6',
# '1').replace(
# '7', '2')
type_cond.text = type_cond.text.replace('6', '1').replace('7', '2')
lois_hydrauliques = param_cas.find('parametresLoisHydrauliques')
lois = lois_hydrauliques.find('lois')
for child in lois:
# # tarage loi
if child.find('type').text == '5':
child.find('type').text = '2'
donnee = child.find('donnees').find('fichier')
temp = donnee.text.split('.')
donnee.text = '{}_init.loi'.format(
del_symbol(temp[0]))
initiales = param_cas.find('parametresConditionsInitiales')
initiales.find('repriseEtude').find('repriseCalcul').text = 'false'
initiales.find('ligneEau').find('LigEauInit').text = 'false'
resultats = param_cas.find('parametresImpressionResultats')
fich_opt = '{}_init.opt'.format(self.baseName)
resultats.find('resultats').find('fichResultat').text = fich_opt
resultats.find('impression').find('impressionCalcul').text = 'true'
resultats.find('pasStockage').find('premPasTpsStock').text = '1'
resultats.find('pasStockage').find('pasStock').text = '1'
resultats.find('pasStockage').find('pasImpression').text = '1'
resultats.find('stockage').find('option').text = '1'
# tracers
if tracer:
parametres_tracer = param_cas.find('parametresTraceur')
parametres_tracer.find('presenceTraceurs').text = 'false'
self.indent(fichier_cas)
arbre = ElementTree(fichier_cas)
arbre.write(os.path.join(self.dossierFileMasc, fich_xcas))