wolfhece 2.1.77__py3-none-any.whl → 2.1.78__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,552 +1,564 @@
1
- """
2
- Author: University of Liege, HECE, LEMA
3
- Date: 2024
4
-
5
- Copyright (c) 2024 University of Liege. All rights reserved.
6
-
7
- This script and its content are protected by copyright law. Unauthorized
8
- copying or distribution of this file, via any medium, is strictly prohibited.
9
- """
10
-
11
- from .Parallels import parallel_gpd_clip, parallel_v2r, parallel_datamod
12
- from .func import data_modification, compute_vulnerability, compute_vulnerability4scenario
13
- from .func import match_vulnerability2sim, compute_acceptability, shp_to_raster, clip_layer
14
- from .func import Accept_Manager, cleaning_directory, EXTENT, Vulnerability_csv, compute_code
15
-
16
- import pandas as pd
17
- import os
18
- from osgeo import gdal
19
- import fiona
20
- import glob
21
- import numpy as np
22
- import geopandas as gpd
23
- from pathlib import Path
24
- import logging
25
- from tqdm import tqdm
26
- from enum import Enum
27
- from pyogrio import read_dataframe
28
-
29
- class steps_base_data_creation(Enum):
30
- """
31
- Enum for the steps in the base data creation
32
- """
33
- CLIP_GDB = 1
34
- CLIP_CADASTER = 2
35
- CLIP_PICC = 3
36
- POINTS2POLYS = 4
37
- RASTERIZE_IGN = 5
38
- PREPROCESS_VULNCODE = 6
39
- DATABASE_TO_RASTER = 7
40
-
41
- class steps_vulnerability(Enum):
42
- """
43
- Enum for the steps in the vulnerability computation
44
- """
45
- CREATE_RASTERS = 1
46
- CREATE_RASTERS_VULN = 10
47
- CREATE_RASTERS_CODE = 11
48
- APPLY_MODIFS = 2
49
- MATCH_SIMUL = 3
50
-
51
- class steps_acceptability(Enum):
52
- """
53
- Enum for the steps in the acceptability computation
54
- """
55
- COMPUTE_LOCAL_ACCEPT = 1
56
- LOAD_FROM_FILES = 2
57
- COMPUTE_MEAN_ACCEPT = 3
58
-
59
- def Base_data_creation(main_dir:str = 'Data',
60
- Original_gdb:str = 'GT_Resilence_dataRisques202010.gdb',
61
- Study_area:str = 'Bassin_Vesdre.shp',
62
- CaPa_Walloon:str = 'Cadastre_Walloon.gpkg',
63
- PICC_Walloon:str = 'PICC_vDIFF.gdb',
64
- CE_IGN_top10v:str = 'CE_IGN_TOP10V/CE_IGN_TOP10V.shp',
65
- resolution:float = 1.,
66
- number_procs:int = 8,
67
- steps:list[int] | list[steps_base_data_creation] = [1,2,3,4,5,6,7],
68
- Vuln_csv:str = 'Vulnerability.csv'):
69
- """
70
- Create the databse.
71
-
72
- In this step, the following operations are performed:
73
- - Clip the original gdb file to the study area
74
- - Clip the Cadastre Walloon file to the study area
75
- - Clip the PICC Walloon file to the study area
76
- - Clip and Rasterize the IGN top10v file
77
- - Create the study area database with the vulnerability levels
78
-
79
-
80
- :param main_dir: The main data directory
81
- :param Original_gdb: The original gdb file from SPW - GT Resilience
82
- :param Study_area: The study area shapefile -- Data will be clipped to this area
83
- :param CaPa_Walloon: The Cadastre Walloon file -- Shapfeile from SPW
84
- :param PICC_Walloon: The PICC Walloon file -- Shapefile from SPW
85
- :param CE_IGN_top10v: The CE "Cours d'eau" IGN top10v file -- Shapefile from IGN with river layer
86
- :param resolution: The output resolution of the raster files
87
- :param number_procs: The number of processors to use for parallel processing
88
-
89
- """
90
- LAYER_CABU = "CaBu"
91
- LAYER_CAPA = "CaPa"
92
- LAYER_BATIEMPRISE = "CONSTR_BATIEMPRISE"
93
-
94
- manager = Accept_Manager(main_dir,
95
- Study_area,
96
- Original_gdb=Original_gdb,
97
- CaPa_Walloon=CaPa_Walloon,
98
- PICC_Walloon=PICC_Walloon,
99
- CE_IGN_top10v=CE_IGN_top10v,
100
- Vuln_csv=Vuln_csv)
101
-
102
- if not manager.check_before_database_creation():
103
- logging.error("The necessary files are missing - Verify logs for more information")
104
- return
105
-
106
- done = []
107
-
108
- if 1 in steps or 6 in steps or steps_base_data_creation.PREPROCESS_VULNCODE in steps or steps_base_data_creation.CLIP_GDB in steps:
109
- # Load the vulnerability CSV to get the layers
110
- vulnerability_csv = Vulnerability_csv(manager.VULNERABILITY_CSV)
111
-
112
- if 1 in steps or steps_base_data_creation.CLIP_GDB in steps:
113
- # Clean the directory to avoid any conflict
114
- # GPKG driver does not overwrite the existing file but adds new layers
115
- cleaning_directory(manager.TMP_CLIPGDB)
116
-
117
- # ********************************************************************************************************************
118
- # Step 1, Clip Original GDB
119
-
120
- # Clip the GDB file and store it in dirsnames.SA_DATABASE
121
- parallel_gpd_clip(vulnerability_csv.get_layers(), manager.ORIGINAL_GDB, manager.SA, manager.TMP_CLIPGDB, number_procs)
122
-
123
- done.append(steps_base_data_creation.CLIP_GDB)
124
-
125
- if 2 in steps or steps_base_data_creation.CLIP_CADASTER in steps:
126
- # ********************************************************************************************************************
127
- # Step 2, Clip Cadaster data
128
- cleaning_directory(manager.TMP_CADASTER)
129
-
130
- # Only 2 layers are present in the Cadastre Walloon file
131
- # Clip the Cadastre Walloon file and store it in dirsnames.SA_CAPA
132
- parallel_gpd_clip([LAYER_CABU, LAYER_CAPA], manager.CAPA_WALLOON, manager.SA, manager.TMP_CADASTER, min(2, number_procs))
133
-
134
- done.append(steps_base_data_creation.CLIP_CADASTER)
135
-
136
- if 3 in steps or steps_base_data_creation.CLIP_PICC in steps:
137
- # ********************************************************************************************************************
138
- # Step 3, Clip PICC data
139
- cleaning_directory(manager.TMP_PICC)
140
-
141
- # ONly 1 layer is needed from the PICC Walloon file
142
- # Clip the PICC Walloon file and store it in dirsnames.SA_PICC
143
- parallel_gpd_clip([LAYER_BATIEMPRISE], manager.PICC_WALLOON, manager.SA, manager.TMP_PICC, min(1, number_procs))
144
-
145
- done.append(steps_base_data_creation.CLIP_PICC)
146
-
147
- if 4 in steps or steps_base_data_creation.POINTS2POLYS in steps:
148
- # ********************************************************************************************************************
149
- # Step 4, create database based on changes in report
150
-
151
- cleaning_directory(manager.TMP_WMODIF)
152
-
153
- # PreLoad Picc and CaPa from clipped files
154
- Picc:gpd.GeoDataFrame = read_dataframe(str(manager.TMP_PICC / (LAYER_BATIEMPRISE+EXTENT)), layer=LAYER_BATIEMPRISE)
155
- CaPa:gpd.GeoDataFrame = read_dataframe(str(manager.TMP_CADASTER / (LAYER_CAPA+EXTENT)), layer=LAYER_CAPA)
156
-
157
- assert Picc.crs == CaPa.crs, "The crs of the two shapefiles are different"
158
-
159
- parallel_datamod(manager=manager, picc=Picc, capa=CaPa, number_procs=number_procs)
160
-
161
- done.append(steps_base_data_creation.POINTS2POLYS)
162
-
163
- if 5 in steps or steps_base_data_creation.RASTERIZE_IGN in steps:
164
- # ********************************************************************************************************************
165
- # Step 5 : Rasaterize the IGN data "Course d'eau" to get the riverbed mask
166
- LAYER_IGN = "CE_IGN_TOP10V"
167
- clip_layer(layer=LAYER_IGN, file_path=manager.CE_IGN_TOP10V, Study_Area=manager.SA, output_dir=manager.TMP_IGNCE)
168
- shp_to_raster(manager.TMP_IGNCE / (LAYER_IGN + '.gpkg'), manager.SA_MASKED_RIVER, resolution, manager=manager)
169
-
170
- done.append(steps_base_data_creation.RASTERIZE_IGN)
171
-
172
- if 6 in steps or steps_base_data_creation.PREPROCESS_VULNCODE in steps:
173
- # ********************************************************************************************************************
174
- # Step 6 : Pre-processing for Vulnerability
175
- # Save the database with vulnerability levels and codes
176
- # This database will be rasterized in 'Database_to_raster'
177
-
178
- layers_sa = manager.get_layers_in_wmodif()
179
- layers_csv = vulnerability_csv.get_layers()
180
-
181
- # Search difference between the two lists of layers
182
- list_shp = list(set(layers_csv).difference(layers_sa))
183
-
184
- logging.info("Excluded layers due to no features in shapefiles:")
185
- logging.info(list_shp)
186
-
187
- not_in_csv = [curlayer for curlayer in layers_sa if curlayer not in layers_csv]
188
- if len(not_in_csv) > 0:
189
- logging.error("Not treated layers due to no vulnerability level or code:")
190
- logging.error(not_in_csv)
191
-
192
- logging.info("STEP1: Saving the database for Vulnerability with attributes Vulne and Code")
193
-
194
- for curlayer in layers_sa:
195
- logging.info(curlayer)
196
-
197
- in_file = str(manager.TMP_WMODIF / (curlayer+EXTENT))
198
- out_file = str(manager.TMP_CODEVULNE / (curlayer+EXTENT))
199
-
200
- shp:gpd.GeoDataFrame = gpd.read_file(in_file)
201
-
202
- nb_lines, _ = shp.shape
203
- if nb_lines > 0:
204
- shp["Path"] = curlayer
205
- shp["Vulne"] = vulnerability_csv.get_vulnerability_level(curlayer)
206
- shp["Code"] = vulnerability_csv.get_vulnerability_code(curlayer)
207
- shp = shp[["geometry", "Path", "Vulne","Code"]]
208
- shp.to_file(out_file)
209
- else:
210
- # Normally, Phase 1 should have removed the empty shapefiles
211
- # But, we never know... ;-)
212
- logging.warning(f"Empty shapefile {curlayer} in {in_file}")
213
-
214
- done.append(steps_base_data_creation.PREPROCESS_VULNCODE)
215
-
216
- if 7 in steps or steps_base_data_creation.DATABASE_TO_RASTER in steps:
217
- # Rasterize the database
218
- cleaning_directory(manager.TMP_RASTERS)
219
- cleaning_directory(manager.TMP_RASTERS_CODE)
220
- cleaning_directory(manager.TMP_RASTERS_VULNE)
221
-
222
- Database_to_raster(main_dir,
223
- Study_area,
224
- resolution,
225
- number_procs=number_procs,
226
- Vuln_csv=Vuln_csv)
227
-
228
- done.append(steps_base_data_creation.DATABASE_TO_RASTER)
229
-
230
- return done
231
-
232
- def Database_to_raster(main_dir:str = 'Data',
233
- Study_area:str = 'Bassin_Vesdre.shp',
234
- resolution:float = 1.,
235
- number_procs:int = 16,
236
- Vuln_csv:str = 'Vulnerability.csv'):
237
- """
238
- Convert the vector database to raster database based on their vulnerability values
239
-
240
- Each leyer is converted to a raster file with the vulnerability values
241
- and the code values.
242
-
243
- They are stored in the TEMP/DATABASES/*StudyArea*/VULNERABILITY/RASTERS in:
244
- - Code
245
- - Vulne
246
-
247
- :param main_dir: The main data directory
248
- :param Study_area: The study area shapefile
249
- :param resolution: The resolution of the output raster files - default is 1 meter
250
- :param number_procs: The number of processors to use for parallel processing
251
-
252
- The parallel processing is safe as each layer is processed independently.
253
- """
254
-
255
- manager = Accept_Manager(main_dir, Study_area, Vuln_csv=Vuln_csv)
256
-
257
- resolution = float(resolution)
258
-
259
- if not manager.check_before_rasterize():
260
- logging.error("The necessary files are missing - Verify logs for more information")
261
- return
262
-
263
- logging.info("Convert vectors to raster based on their vulnerability values")
264
-
265
- attributes = ["Vulne", "Code"]
266
- for cur_attrib in attributes:
267
- parallel_v2r(manager, cur_attrib, resolution, number_procs, convert_to_sparse=True)
268
-
269
- def Vulnerability(main_dir:str = 'Data',
270
- scenario:str = 'Scenario1',
271
- Study_area:str = 'Bassin_Vesdre.shp',
272
- resolution:float = 1.,
273
- steps:list[int] | list[steps_vulnerability] = [1,10,11,2,3],
274
- Vuln_csv:str = 'Vulnerability.csv',
275
- Intermediate_csv:str = 'Intermediate.csv'):
276
- """
277
- Compute the vulnerability for the study area and the scenario, if needed.
278
-
279
- The vulnerability is computed in 3 steps:
280
- 1. Compute the vulnerability for the study area
281
- 2. Compute the vulnerability for the scenario
282
- 3. Clip the vulnerability rasters to the simulation area
283
-
284
- During step 3, three matrices are computed and clipped to the simulation area:
285
- - Vulnerability
286
- - Code
287
- - Masked River
288
-
289
- :param main_dir: The main data directory
290
- :param scenario: The scenario name
291
- :param Study_area: The study area shapefile
292
- :param resolution: The resolution of the output raster files - default is 1 meter
293
- :param steps: The steps to compute the vulnerability - default is [1,2,3]
294
-
295
- To be more rapid, the steps can be computed separately.
296
- - [1,2,3] : All steps are computed - Necessary for the first time
297
- - [2,3] : Only the scenario and clipping steps are computed -- Useful for scenario changes
298
- - [3] : Only the clipping step is computed -- Useful if simulation area changes but scenario is the same
299
-
300
- """
301
-
302
- manager = Accept_Manager(main_dir,
303
- Study_area,
304
- scenario=scenario,
305
- Vuln_csv=Vuln_csv,
306
- Intermediate_csv=Intermediate_csv)
307
-
308
- if not manager.check_before_vulnerability():
309
- logging.error("The necessary files are missing - Verify logs for more information")
310
- return
311
-
312
- logging.info("Starting VULNERABILITY computations at {} m resolution".format(resolution))
313
-
314
- done = []
315
-
316
- if 1 in steps or steps_vulnerability.CREATE_RASTERS in steps:
317
- # Step 1 : Compute the vulnerability rasters for the study area
318
- # The data **will not** be impacted by the scenario modifications
319
-
320
- logging.info("Generate Vulnerability rasters {}m".format(resolution))
321
-
322
- cleaning_directory(manager.TMP_SCEN_DIR)
323
-
324
- if 10 in steps or steps_vulnerability.CREATE_RASTERS_VULN in steps:
325
- compute_vulnerability(manager)
326
- done.append(steps_vulnerability.CREATE_RASTERS_VULN)
327
-
328
- if 11 in steps or steps_vulnerability.CREATE_RASTERS_CODE in steps:
329
- compute_code(manager)
330
- done.append(steps_vulnerability.CREATE_RASTERS_CODE)
331
-
332
- done.append(steps_vulnerability.CREATE_RASTERS)
333
-
334
- if 2 in steps or steps_vulnerability.APPLY_MODIFS in steps:
335
- # Step 2 : Compute the vulnerability rasters for the scenario
336
- # The data **will be** impacted by the scenario modifications
337
-
338
- if not manager.check_vuln_code_sa():
339
- logging.error("The vulnerability and code files for the study area are missing")
340
- logging.warning("Force the computation even if not prescribed in the steps")
341
-
342
- Vulnerability(main_dir, scenario, Study_area, resolution, [1])
343
-
344
- bu:list[Path] = manager.get_files_in_rm_buildings()
345
-
346
- if len(bu)>0:
347
- for curfile in bu:
348
- tiff_file = manager.TMP_RM_BUILD_DIR / (curfile.stem + ".tiff")
349
- shp_to_raster(curfile, tiff_file)
350
-
351
- compute_vulnerability4scenario(manager)
352
- else:
353
- logging.warning(f"No buildings were removed in water depth analysis OR No shapefiles in {manager.IN_RM_BUILD_DIR}")
354
-
355
- done.append(steps_vulnerability.APPLY_MODIFS)
356
-
357
- if 3 in steps or steps_vulnerability.MATCH_SIMUL in steps:
358
- # Step 3 : Clip the vulnerability/code rasters to the **simulation area**
359
-
360
- logging.info("Save Vulnerability files for the area of interest")
361
-
362
- return_periods = manager.get_return_periods()
363
- TMAX = manager.get_filepath_for_return_period(return_periods[-1])
364
-
365
- if TMAX is None:
366
- logging.error("The file for the maximum return period is missing")
367
- return
368
-
369
- match_vulnerability2sim(manager.SA_MASKED_RIVER,manager.OUT_MASKED_RIVER, TMAX)
370
- match_vulnerability2sim(manager.SA_VULN, manager.OUT_VULN, TMAX)
371
- match_vulnerability2sim(manager.SA_CODE, manager.OUT_CODE, TMAX)
372
-
373
- done.append(steps_vulnerability.MATCH_SIMUL)
374
-
375
- return done
376
-
377
- def Acceptability(main_dir:str = 'Vesdre',
378
- scenario:str = 'Scenario1',
379
- Study_area:str = 'Bassin_Vesdre.shp',
380
- coeff_auto:bool = True,
381
- Ponderation_csv:str = 'Ponderation.csv',
382
- resample_size:int = 100,
383
- steps:list[int] | list[steps_acceptability] = [1,2,3]):
384
- """ Compute acceptability for the scenario """
385
-
386
- done = []
387
-
388
- manager = Accept_Manager(main_dir,
389
- Study_area,
390
- scenario=scenario,
391
- Ponderation_csv=Ponderation_csv)
392
-
393
- # Load the vulnerability raster **for the scenario**
394
- vulne = gdal.Open(str(manager.OUT_VULN))
395
-
396
- # Load the river mask
397
- riv = gdal.Open(str(manager.OUT_MASKED_RIVER))
398
-
399
- # Get the geotransform and projection for the output tiff
400
- geotrans = riv.GetGeoTransform()
401
- proj = riv.GetProjection()
402
-
403
- assert vulne.GetGeoTransform() == riv.GetGeoTransform(), "The geotransform of the two rasters is different"
404
- assert vulne.GetProjection() == riv.GetProjection(), "The projection of the two rasters is different"
405
-
406
- # Convert to numpy array
407
- vulne = vulne.GetRasterBand(1).ReadAsArray()
408
- riv = riv.GetRasterBand(1).ReadAsArray()
409
-
410
- # Get the return periods available
411
- return_periods = manager.get_return_periods()
412
-
413
- # Prepare the river bed filter
414
- # Useful as we iterate over the return periods
415
- # and the river bed is the same for all return periods
416
- ij_riv = np.argwhere(riv == 1)
417
-
418
- # Initialize the dictionary to store the acceptability values
419
- part_accept = {}
420
-
421
- if 1 in steps or steps_acceptability.COMPUTE_LOCAL_ACCEPT in steps:
422
- # Compute acceptability for each return period
423
- for curT in tqdm(return_periods):
424
-
425
- # Load the **FILLED** modelled water depth for the return period
426
- model_h = gdal.Open(str(manager.get_sim_file_for_return_period(curT)))
427
- # Convert to numpy array
428
- model_h = model_h.GetRasterBand(1).ReadAsArray()
429
-
430
- assert model_h.shape == vulne.shape, "The shape of the modelled water depth is different from the vulnerability raster"
431
-
432
- # Set 0. if the water depth is 0.
433
- model_h[model_h == 0] = 0
434
- # Set 0. in the river bed
435
- model_h[ij_riv[:,0], ij_riv[:,1]] = 0
436
-
437
- assert model_h[ij_riv[0][0], ij_riv[0][1]] == 0, "The river bed is not set to 0 in the modelled water depth"
438
- assert model_h.max() > 0, "The maximum water depth is 0"
439
- if model_h.min() < 0:
440
- logging.warning("The minimum water depth is negative - {} cells".format(np.count_nonzero(model_h<0)))
441
- logging.warning("Setting the negative values to 0")
442
- model_h[model_h < 0] = 0
443
-
444
- logging.info("Return period {}".format(curT))
445
-
446
- # Compute the local acceptability for the return period
447
- part_accept[curT] = compute_acceptability(manager, model_h, vulne, curT, (geotrans, proj))
448
-
449
- done.append(steps_acceptability.COMPUTE_LOCAL_ACCEPT)
450
-
451
- # At this point, the local acceptability for each return period is computed
452
- # and stored in tiff files in the TEMP/SutyArea/scenario/Q_FILES directory.
453
- # The arrays are also stored in the part_accept dictionary.
454
-
455
- if 2 in steps or steps_acceptability.LOAD_FROM_FILES in steps:
456
- # Load/Reload the acceptability values from files
457
-
458
- if 1 in steps or steps_acceptability.COMPUTE_LOCAL_ACCEPT in steps:
459
- # We have computed/updted the acceptibility values.
460
- # We do not need to reload them.
461
- logging.warning("The acceptability values have been computed in step 1 - avoid reloading")
462
- logging.info("If you want to reload the acceptability values, please remove step 1 from the list of steps")
463
- else:
464
-
465
- # Get the list of Q files
466
- qs = manager.get_q_files()
467
-
468
- # Iterate over the return periods
469
- for curT in return_periods:
470
- logging.info(curT)
471
-
472
- # We set the filename from the return period, not the "qs" list
473
- q_filename = manager.TMP_QFILES / "Q{}.tif".format(curT)
474
-
475
- # Check if the file exists
476
- assert q_filename.exists(), "The file {} does not exist".format(q_filename)
477
- # Check if the file is in the "qs" list
478
- assert q_filename in qs, "The file {} is not in the list of Q files".format(q_filename)
479
-
480
- # Load the Q file for the return period
481
- tmp_data = gdal.Open(str(q_filename))
482
- # Convert to numpy array
483
- part_accept[curT] = tmp_data.GetRasterBand(1).ReadAsArray()
484
-
485
- done.append(steps_acceptability.LOAD_FROM_FILES)
486
-
487
- if 3 in steps or steps_acceptability.COMPUTE_MEAN_ACCEPT in steps:
488
-
489
- assert len(part_accept) == len(return_periods), "The number of acceptability files is not equal to the number of return periods"
490
-
491
- # Pointing the last return period, maybe 1000 but not always
492
- array_tmax = part_accept[return_periods[-1]]
493
-
494
- # Get ponderations for the return periods
495
- if coeff_auto:
496
- logging.info("Automatic ponderation")
497
- pond = manager.get_ponderations()
498
- assert pond["Ponderation"].sum() > 0.999999 and pond["Ponderation"].sum()<1.0000001, "The sum of the ponderations is not equal to 1"
499
-
500
- elif manager.is_valid_ponderation_csv:
501
- logging.info("Manual ponderation")
502
- # Load the ponderation file
503
- pond = pd.read_csv(manager.PONDERATION_CSV)
504
- # Set the index to the interval, so we can use the interval as a key
505
- pond.set_index("Interval", inplace=True)
506
-
507
- else:
508
- logging.error("The ponderation file is missing")
509
- logging.info("Please provide the ponderation file or set 'coeff_auto' to True")
510
- return -1
511
-
512
- assert len(pond) == len(return_periods), "The number of ponderations is not equal to the number of return periods"
513
-
514
- # Initialize the combined acceptability matrix -- Ponderate mean of the local acceptability
515
- comb = np.zeros(part_accept[return_periods[-1]].shape, dtype=np.float32)
516
-
517
- for curT in return_periods:
518
- assert part_accept[curT].dtype == np.float32, "The dtype of the acceptability matrix is not np.float32"
519
- assert part_accept[curT].shape == comb.shape, "The shape of the acceptability matrix is not the right one"
520
-
521
- comb += part_accept[curT] * float(pond["Ponderation"][curT])
522
-
523
- y_pixels, x_pixels = comb.shape # number of pixels in x
524
-
525
- # Set up output GeoTIFF
526
- driver = gdal.GetDriverByName('GTiff')
527
- dataset = driver.Create(str(manager.OUT_ACCEPT),
528
- x_pixels, y_pixels,
529
- 1,
530
- gdal.GDT_Float32,
531
- options=["COMPRESS=LZW"])
532
-
533
- assert comb.dtype == np.float32, "The dtype of the combined acceptability matrix is not np.float32"
534
-
535
- dataset.GetRasterBand(1).WriteArray(comb)
536
- dataset.SetGeoTransform(geotrans)
537
- dataset.SetProjection(proj)
538
- dataset.FlushCache()
539
- dataset=None
540
-
541
- # Resample to XXm
542
- Agg = gdal.Warp(str(manager.OUT_ACCEPT_100M),
543
- str(manager.OUT_ACCEPT),
544
- xRes=resample_size,
545
- yRes=resample_size,
546
- resampleAlg='Average')
547
- Agg.FlushCache()
548
- Agg = None
549
-
550
- done.append(steps_acceptability.COMPUTE_MEAN_ACCEPT)
551
-
1
+ """
2
+ Author: University of Liege, HECE, LEMA
3
+ Date: 2024
4
+
5
+ Copyright (c) 2024 University of Liege. All rights reserved.
6
+
7
+ This script and its content are protected by copyright law. Unauthorized
8
+ copying or distribution of this file, via any medium, is strictly prohibited.
9
+ """
10
+
11
+ from .Parallels import parallel_gpd_clip, parallel_v2r, parallel_datamod
12
+ from .func import data_modification, compute_vulnerability, compute_vulnerability4scenario
13
+ from .func import match_vulnerability2sim, compute_acceptability, shp_to_raster, clip_layer
14
+ from .func import Accept_Manager, cleaning_directory, EXTENT, Vulnerability_csv, compute_code
15
+
16
+ import pandas as pd
17
+ import os
18
+ from osgeo import gdal
19
+ import fiona
20
+ import glob
21
+ import numpy as np
22
+ import geopandas as gpd
23
+ from pathlib import Path
24
+ import logging
25
+ from tqdm import tqdm
26
+ from enum import Enum
27
+ from pyogrio import read_dataframe
28
+
29
+ class steps_base_data_creation(Enum):
30
+ """
31
+ Enum for the steps in the base data creation
32
+ """
33
+ CLIP_GDB = 1
34
+ CLIP_CADASTER = 2
35
+ CLIP_PICC = 3
36
+ POINTS2POLYS = 4
37
+ RASTERIZE_IGN = 5
38
+ PREPROCESS_VULNCODE = 6
39
+ DATABASE_TO_RASTER = 7
40
+
41
+ @classmethod
42
+ def get_list_names(cls):
43
+ return [f'{cur.name} - {cur.value}' for cur in cls]
44
+
45
+ class steps_vulnerability(Enum):
46
+ """
47
+ Enum for the steps in the vulnerability computation
48
+ """
49
+ CREATE_RASTERS = 1
50
+ CREATE_RASTERS_VULN = 10
51
+ CREATE_RASTERS_CODE = 11
52
+ APPLY_MODIFS = 2
53
+ MATCH_SIMUL = 3
54
+
55
+ @classmethod
56
+ def get_list_names(cls):
57
+ return [f'{cur.name} - {cur.value}' for cur in cls]
58
+
59
+ class steps_acceptability(Enum):
60
+ """
61
+ Enum for the steps in the acceptability computation
62
+ """
63
+ COMPUTE_LOCAL_ACCEPT = 1
64
+ LOAD_FROM_FILES = 2
65
+ COMPUTE_MEAN_ACCEPT = 3
66
+
67
+ @classmethod
68
+ def get_list_names(cls):
69
+ return [f'{cur.name} - {cur.value}' for cur in cls]
70
+
71
+ def Base_data_creation(main_dir:str = 'Data',
72
+ Original_gdb:str = 'GT_Resilence_dataRisques202010.gdb',
73
+ Study_area:str = 'Bassin_Vesdre.shp',
74
+ CaPa_Walloon:str = 'Cadastre_Walloon.gpkg',
75
+ PICC_Walloon:str = 'PICC_vDIFF.gdb',
76
+ CE_IGN_top10v:str = 'CE_IGN_TOP10V/CE_IGN_TOP10V.shp',
77
+ resolution:float = 1.,
78
+ number_procs:int = 8,
79
+ steps:list[int] | list[steps_base_data_creation] = [1,2,3,4,5,6,7],
80
+ Vuln_csv:str = 'Vulnerability.csv'):
81
+ """
82
+ Create the databse.
83
+
84
+ In this step, the following operations are performed:
85
+ - Clip the original gdb file to the study area
86
+ - Clip the Cadastre Walloon file to the study area
87
+ - Clip the PICC Walloon file to the study area
88
+ - Clip and Rasterize the IGN top10v file
89
+ - Create the study area database with the vulnerability levels
90
+
91
+
92
+ :param main_dir: The main data directory
93
+ :param Original_gdb: The original gdb file from SPW - GT Resilience
94
+ :param Study_area: The study area shapefile -- Data will be clipped to this area
95
+ :param CaPa_Walloon: The Cadastre Walloon file -- Shapfeile from SPW
96
+ :param PICC_Walloon: The PICC Walloon file -- Shapefile from SPW
97
+ :param CE_IGN_top10v: The CE "Cours d'eau" IGN top10v file -- Shapefile from IGN with river layer
98
+ :param resolution: The output resolution of the raster files
99
+ :param number_procs: The number of processors to use for parallel processing
100
+
101
+ """
102
+ LAYER_CABU = "CaBu"
103
+ LAYER_CAPA = "CaPa"
104
+ LAYER_BATIEMPRISE = "CONSTR_BATIEMPRISE"
105
+
106
+ manager = Accept_Manager(main_dir,
107
+ Study_area,
108
+ Original_gdb=Original_gdb,
109
+ CaPa_Walloon=CaPa_Walloon,
110
+ PICC_Walloon=PICC_Walloon,
111
+ CE_IGN_top10v=CE_IGN_top10v,
112
+ Vuln_csv=Vuln_csv)
113
+
114
+ if not manager.check_before_database_creation():
115
+ logging.error("The necessary files are missing - Verify logs for more information")
116
+ return
117
+
118
+ done = []
119
+
120
+ if 1 in steps or 6 in steps or steps_base_data_creation.PREPROCESS_VULNCODE in steps or steps_base_data_creation.CLIP_GDB in steps:
121
+ # Load the vulnerability CSV to get the layers
122
+ vulnerability_csv = Vulnerability_csv(manager.VULNERABILITY_CSV)
123
+
124
+ if 1 in steps or steps_base_data_creation.CLIP_GDB in steps:
125
+ # Clean the directory to avoid any conflict
126
+ # GPKG driver does not overwrite the existing file but adds new layers
127
+ cleaning_directory(manager.TMP_CLIPGDB)
128
+
129
+ # ********************************************************************************************************************
130
+ # Step 1, Clip Original GDB
131
+
132
+ # Clip the GDB file and store it in output directory : manager.TMP_CLIPGDB
133
+ parallel_gpd_clip(vulnerability_csv.get_layers(), manager.ORIGINAL_GDB, manager.SA, manager.TMP_CLIPGDB, number_procs)
134
+
135
+ done.append(steps_base_data_creation.CLIP_GDB)
136
+
137
+ if 2 in steps or steps_base_data_creation.CLIP_CADASTER in steps:
138
+ # ********************************************************************************************************************
139
+ # Step 2, Clip Cadaster data
140
+ cleaning_directory(manager.TMP_CADASTER)
141
+
142
+ # Only 2 layers are present in the Cadastre Walloon file
143
+ # Clip the Cadastre Walloon file and store it in output directory : manager.TMP_CADASTER
144
+ parallel_gpd_clip([LAYER_CABU, LAYER_CAPA], manager.CAPA_WALLOON, manager.SA, manager.TMP_CADASTER, min(2, number_procs))
145
+
146
+ done.append(steps_base_data_creation.CLIP_CADASTER)
147
+
148
+ if 3 in steps or steps_base_data_creation.CLIP_PICC in steps:
149
+ # ********************************************************************************************************************
150
+ # Step 3, Clip PICC data
151
+ cleaning_directory(manager.TMP_PICC)
152
+
153
+ # ONly 1 layer is needed from the PICC Walloon file
154
+ # Clip the PICC Walloon file and store it in output dir : manager.TMP_PICC
155
+ parallel_gpd_clip([LAYER_BATIEMPRISE], manager.PICC_WALLOON, manager.SA, manager.TMP_PICC, min(1, number_procs))
156
+
157
+ done.append(steps_base_data_creation.CLIP_PICC)
158
+
159
+ if 4 in steps or steps_base_data_creation.POINTS2POLYS in steps:
160
+ # ********************************************************************************************************************
161
+ # Step 4, create database based on changes in report
162
+
163
+ cleaning_directory(manager.TMP_WMODIF)
164
+
165
+ # PreLoad Picc and CaPa from clipped files
166
+ Picc:gpd.GeoDataFrame = read_dataframe(str(manager.TMP_PICC / (LAYER_BATIEMPRISE+EXTENT)), layer=LAYER_BATIEMPRISE)
167
+ CaPa:gpd.GeoDataFrame = read_dataframe(str(manager.TMP_CADASTER / (LAYER_CAPA+EXTENT)), layer=LAYER_CAPA)
168
+
169
+ assert Picc.crs == CaPa.crs, "The crs of the two shapefiles are different"
170
+
171
+ parallel_datamod(manager=manager, picc=Picc, capa=CaPa, number_procs=number_procs)
172
+
173
+ done.append(steps_base_data_creation.POINTS2POLYS)
174
+
175
+ if 5 in steps or steps_base_data_creation.RASTERIZE_IGN in steps:
176
+ # ********************************************************************************************************************
177
+ # Step 5 : Rasaterize the IGN data "Course d'eau" to get the riverbed mask
178
+ LAYER_IGN = "CE_IGN_TOP10V"
179
+ clip_layer(layer=LAYER_IGN, file_path=manager.CE_IGN_TOP10V, Study_Area=manager.SA, output_dir=manager.TMP_IGNCE)
180
+ shp_to_raster(manager.TMP_IGNCE / (LAYER_IGN + '.gpkg'), manager.SA_MASKED_RIVER, resolution, manager=manager)
181
+
182
+ done.append(steps_base_data_creation.RASTERIZE_IGN)
183
+
184
+ if 6 in steps or steps_base_data_creation.PREPROCESS_VULNCODE in steps:
185
+ # ********************************************************************************************************************
186
+ # Step 6 : Pre-processing for Vulnerability
187
+ # Save the database with vulnerability levels and codes
188
+ # This database will be rasterized in 'Database_to_raster'
189
+
190
+ layers_sa = manager.get_layers_in_wmodif()
191
+ layers_csv = vulnerability_csv.get_layers()
192
+
193
+ # Search difference between the two lists of layers
194
+ list_shp = list(set(layers_csv).difference(layers_sa))
195
+
196
+ logging.info("Excluded layers due to no features in shapefiles:")
197
+ logging.info(list_shp)
198
+
199
+ not_in_csv = [curlayer for curlayer in layers_sa if curlayer not in layers_csv]
200
+ if len(not_in_csv) > 0:
201
+ logging.error("Not treated layers due to no vulnerability level or code:")
202
+ logging.error(not_in_csv)
203
+
204
+ logging.info("STEP1: Saving the database for Vulnerability with attributes Vulne and Code")
205
+
206
+ for curlayer in layers_sa:
207
+ logging.info(curlayer)
208
+
209
+ in_file = str(manager.TMP_WMODIF / (curlayer+EXTENT))
210
+ out_file = str(manager.TMP_CODEVULNE / (curlayer+EXTENT))
211
+
212
+ shp:gpd.GeoDataFrame = gpd.read_file(in_file)
213
+
214
+ nb_lines, _ = shp.shape
215
+ if nb_lines > 0:
216
+ shp["Path"] = curlayer
217
+ shp["Vulne"] = vulnerability_csv.get_vulnerability_level(curlayer)
218
+ shp["Code"] = vulnerability_csv.get_vulnerability_code(curlayer)
219
+ shp = shp[["geometry", "Path", "Vulne","Code"]]
220
+ shp.to_file(out_file)
221
+ else:
222
+ # Normally, Phase 1 should have removed the empty shapefiles
223
+ # But, we never know... ;-)
224
+ logging.warning(f"Empty shapefile {curlayer} in {in_file}")
225
+
226
+ done.append(steps_base_data_creation.PREPROCESS_VULNCODE)
227
+
228
+ if 7 in steps or steps_base_data_creation.DATABASE_TO_RASTER in steps:
229
+ # Rasterize the database
230
+ cleaning_directory(manager.TMP_RASTERS)
231
+ cleaning_directory(manager.TMP_RASTERS_CODE)
232
+ cleaning_directory(manager.TMP_RASTERS_VULNE)
233
+
234
+ Database_to_raster(main_dir,
235
+ Study_area,
236
+ resolution,
237
+ number_procs=number_procs,
238
+ Vuln_csv=Vuln_csv)
239
+
240
+ done.append(steps_base_data_creation.DATABASE_TO_RASTER)
241
+
242
+ return done
243
+
244
+ def Database_to_raster(main_dir:str = 'Data',
245
+ Study_area:str = 'Bassin_Vesdre.shp',
246
+ resolution:float = 1.,
247
+ number_procs:int = 16,
248
+ Vuln_csv:str = 'Vulnerability.csv'):
249
+ """
250
+ Convert the vector database to raster database based on their vulnerability values
251
+
252
+ Each leyer is converted to a raster file with the vulnerability values
253
+ and the code values.
254
+
255
+ They are stored in the TEMP/DATABASES/*StudyArea*/VULNERABILITY/RASTERS in:
256
+ - Code
257
+ - Vulne
258
+
259
+ :param main_dir: The main data directory
260
+ :param Study_area: The study area shapefile
261
+ :param resolution: The resolution of the output raster files - default is 1 meter
262
+ :param number_procs: The number of processors to use for parallel processing
263
+
264
+ The parallel processing is safe as each layer is processed independently.
265
+ """
266
+
267
+ manager = Accept_Manager(main_dir, Study_area, Vuln_csv=Vuln_csv)
268
+
269
+ resolution = float(resolution)
270
+
271
+ if not manager.check_before_rasterize():
272
+ logging.error("The necessary files are missing - Verify logs for more information")
273
+ return
274
+
275
+ logging.info("Convert vectors to raster based on their vulnerability values")
276
+
277
+ attributes = ["Vulne", "Code"]
278
+ for cur_attrib in attributes:
279
+ parallel_v2r(manager, cur_attrib, resolution, number_procs, convert_to_sparse=True)
280
+
281
+ def Vulnerability(main_dir:str = 'Data',
282
+ scenario:str = 'Scenario1',
283
+ Study_area:str = 'Bassin_Vesdre.shp',
284
+ resolution:float = 1.,
285
+ steps:list[int] | list[steps_vulnerability] = [1,10,11,2,3],
286
+ Vuln_csv:str = 'Vulnerability.csv',
287
+ Intermediate_csv:str = 'Intermediate.csv'):
288
+ """
289
+ Compute the vulnerability for the study area and the scenario, if needed.
290
+
291
+ The vulnerability is computed in 3 steps:
292
+ 1. Compute the vulnerability for the study area
293
+ 2. Compute the vulnerability for the scenario
294
+ 3. Clip the vulnerability rasters to the simulation area
295
+
296
+ During step 3, three matrices are computed and clipped to the simulation area:
297
+ - Vulnerability
298
+ - Code
299
+ - Masked River
300
+
301
+ :param main_dir: The main data directory
302
+ :param scenario: The scenario name
303
+ :param Study_area: The study area shapefile
304
+ :param resolution: The resolution of the output raster files - default is 1 meter
305
+ :param steps: The steps to compute the vulnerability - default is [1,2,3]
306
+
307
+ To be more rapid, the steps can be computed separately.
308
+ - [1,2,3] : All steps are computed - Necessary for the first time
309
+ - [2,3] : Only the scenario and clipping steps are computed -- Useful for scenario changes
310
+ - [3] : Only the clipping step is computed -- Useful if simulation area changes but scenario is the same
311
+
312
+ """
313
+
314
+ manager = Accept_Manager(main_dir,
315
+ Study_area,
316
+ scenario=scenario,
317
+ Vuln_csv=Vuln_csv,
318
+ Intermediate_csv=Intermediate_csv)
319
+
320
+ if not manager.check_before_vulnerability():
321
+ logging.error("The necessary files are missing - Verify logs for more information")
322
+ return
323
+
324
+ logging.info("Starting VULNERABILITY computations at {} m resolution".format(resolution))
325
+
326
+ done = []
327
+
328
+ if 1 in steps or steps_vulnerability.CREATE_RASTERS in steps:
329
+ # Step 1 : Compute the vulnerability rasters for the study area
330
+ # The data **will not** be impacted by the scenario modifications
331
+
332
+ logging.info("Generate Vulnerability rasters {}m".format(resolution))
333
+
334
+ cleaning_directory(manager.TMP_SCEN_DIR)
335
+
336
+ if 10 in steps or steps_vulnerability.CREATE_RASTERS_VULN in steps:
337
+ compute_vulnerability(manager)
338
+ done.append(steps_vulnerability.CREATE_RASTERS_VULN)
339
+
340
+ if 11 in steps or steps_vulnerability.CREATE_RASTERS_CODE in steps:
341
+ compute_code(manager)
342
+ done.append(steps_vulnerability.CREATE_RASTERS_CODE)
343
+
344
+ done.append(steps_vulnerability.CREATE_RASTERS)
345
+
346
+ if 2 in steps or steps_vulnerability.APPLY_MODIFS in steps:
347
+ # Step 2 : Compute the vulnerability rasters for the scenario
348
+ # The data **will be** impacted by the scenario modifications
349
+
350
+ if not manager.check_vuln_code_sa():
351
+ logging.error("The vulnerability and code files for the study area are missing")
352
+ logging.warning("Force the computation even if not prescribed in the steps")
353
+
354
+ Vulnerability(main_dir, scenario, Study_area, resolution, [1])
355
+
356
+ bu:list[Path] = manager.get_files_in_rm_buildings()
357
+
358
+ if len(bu)>0:
359
+ for curfile in bu:
360
+ tiff_file = manager.TMP_RM_BUILD_DIR / (curfile.stem + ".tiff")
361
+ shp_to_raster(curfile, tiff_file)
362
+
363
+ compute_vulnerability4scenario(manager)
364
+ else:
365
+ logging.warning(f"No buildings were removed in water depth analysis OR No shapefiles in {manager.IN_RM_BUILD_DIR}")
366
+
367
+ done.append(steps_vulnerability.APPLY_MODIFS)
368
+
369
+ if 3 in steps or steps_vulnerability.MATCH_SIMUL in steps:
370
+ # Step 3 : Clip the vulnerability/code rasters to the **simulation area**
371
+
372
+ logging.info("Save Vulnerability files for the area of interest")
373
+
374
+ return_periods = manager.get_return_periods()
375
+ TMAX = manager.get_filepath_for_return_period(return_periods[-1])
376
+
377
+ if TMAX is None:
378
+ logging.error("The file for the maximum return period is missing")
379
+ return
380
+
381
+ match_vulnerability2sim(manager.SA_MASKED_RIVER,manager.OUT_MASKED_RIVER, TMAX)
382
+ match_vulnerability2sim(manager.SA_VULN, manager.OUT_VULN, TMAX)
383
+ match_vulnerability2sim(manager.SA_CODE, manager.OUT_CODE, TMAX)
384
+
385
+ done.append(steps_vulnerability.MATCH_SIMUL)
386
+
387
+ return done
388
+
389
+ def Acceptability(main_dir:str = 'Vesdre',
390
+ scenario:str = 'Scenario1',
391
+ Study_area:str = 'Bassin_Vesdre.shp',
392
+ coeff_auto:bool = True,
393
+ Ponderation_csv:str = 'Ponderation.csv',
394
+ resample_size:int = 100,
395
+ steps:list[int] | list[steps_acceptability] = [1,2,3]):
396
+ """ Compute acceptability for the scenario """
397
+
398
+ done = []
399
+
400
+ manager = Accept_Manager(main_dir,
401
+ Study_area,
402
+ scenario=scenario,
403
+ Ponderation_csv=Ponderation_csv)
404
+
405
+ # Load the vulnerability raster **for the scenario**
406
+ vulne = gdal.Open(str(manager.OUT_VULN))
407
+
408
+ # Load the river mask
409
+ riv = gdal.Open(str(manager.OUT_MASKED_RIVER))
410
+
411
+ # Get the geotransform and projection for the output tiff
412
+ geotrans = riv.GetGeoTransform()
413
+ proj = riv.GetProjection()
414
+
415
+ assert vulne.GetGeoTransform() == riv.GetGeoTransform(), "The geotransform of the two rasters is different"
416
+ assert vulne.GetProjection() == riv.GetProjection(), "The projection of the two rasters is different"
417
+
418
+ # Convert to numpy array
419
+ vulne = vulne.GetRasterBand(1).ReadAsArray()
420
+ riv = riv.GetRasterBand(1).ReadAsArray()
421
+
422
+ # Get the return periods available
423
+ return_periods = manager.get_return_periods()
424
+
425
+ # Prepare the river bed filter
426
+ # Useful as we iterate over the return periods
427
+ # and the river bed is the same for all return periods
428
+ ij_riv = np.argwhere(riv == 1)
429
+
430
+ # Initialize the dictionary to store the acceptability values
431
+ part_accept = {}
432
+
433
+ if 1 in steps or steps_acceptability.COMPUTE_LOCAL_ACCEPT in steps:
434
+ # Compute acceptability for each return period
435
+ for curT in tqdm(return_periods):
436
+
437
+ # Load the **FILLED** modelled water depth for the return period
438
+ model_h = gdal.Open(str(manager.get_sim_file_for_return_period(curT)))
439
+ # Convert to numpy array
440
+ model_h = model_h.GetRasterBand(1).ReadAsArray()
441
+
442
+ assert model_h.shape == vulne.shape, "The shape of the modelled water depth is different from the vulnerability raster"
443
+
444
+ # Set 0. if the water depth is 0.
445
+ model_h[model_h == 0] = 0
446
+ # Set 0. in the river bed
447
+ model_h[ij_riv[:,0], ij_riv[:,1]] = 0
448
+
449
+ assert model_h[ij_riv[0][0], ij_riv[0][1]] == 0, "The river bed is not set to 0 in the modelled water depth"
450
+ assert model_h.max() > 0, "The maximum water depth is 0"
451
+ if model_h.min() < 0:
452
+ logging.warning("The minimum water depth is negative - {} cells".format(np.count_nonzero(model_h<0)))
453
+ logging.warning("Setting the negative values to 0")
454
+ model_h[model_h < 0] = 0
455
+
456
+ logging.info("Return period {}".format(curT))
457
+
458
+ # Compute the local acceptability for the return period
459
+ part_accept[curT] = compute_acceptability(manager, model_h, vulne, curT, (geotrans, proj))
460
+
461
+ done.append(steps_acceptability.COMPUTE_LOCAL_ACCEPT)
462
+
463
+ # At this point, the local acceptability for each return period is computed
464
+ # and stored in tiff files in the TEMP/SutyArea/scenario/Q_FILES directory.
465
+ # The arrays are also stored in the part_accept dictionary.
466
+
467
+ if 2 in steps or steps_acceptability.LOAD_FROM_FILES in steps:
468
+ # Load/Reload the acceptability values from files
469
+
470
+ if 1 in steps or steps_acceptability.COMPUTE_LOCAL_ACCEPT in steps:
471
+ # We have computed/updted the acceptibility values.
472
+ # We do not need to reload them.
473
+ logging.warning("The acceptability values have been computed in step 1 - avoid reloading")
474
+ logging.info("If you want to reload the acceptability values, please remove step 1 from the list of steps")
475
+ else:
476
+
477
+ # Get the list of Q files
478
+ qs = manager.get_q_files()
479
+
480
+ # Iterate over the return periods
481
+ for curT in return_periods:
482
+ logging.info(curT)
483
+
484
+ # We set the filename from the return period, not the "qs" list
485
+ q_filename = manager.TMP_QFILES / "Q{}.tif".format(curT)
486
+
487
+ # Check if the file exists
488
+ assert q_filename.exists(), "The file {} does not exist".format(q_filename)
489
+ # Check if the file is in the "qs" list
490
+ assert q_filename in qs, "The file {} is not in the list of Q files".format(q_filename)
491
+
492
+ # Load the Q file for the return period
493
+ tmp_data = gdal.Open(str(q_filename))
494
+ # Convert to numpy array
495
+ part_accept[curT] = tmp_data.GetRasterBand(1).ReadAsArray()
496
+
497
+ done.append(steps_acceptability.LOAD_FROM_FILES)
498
+
499
+ if 3 in steps or steps_acceptability.COMPUTE_MEAN_ACCEPT in steps:
500
+
501
+ assert len(part_accept) == len(return_periods), "The number of acceptability files is not equal to the number of return periods"
502
+
503
+ # Pointing the last return period, maybe 1000 but not always
504
+ array_tmax = part_accept[return_periods[-1]]
505
+
506
+ # Get ponderations for the return periods
507
+ if coeff_auto:
508
+ logging.info("Automatic ponderation")
509
+ pond = manager.get_ponderations()
510
+ assert pond["Ponderation"].sum() > 0.999999 and pond["Ponderation"].sum()<1.0000001, "The sum of the ponderations is not equal to 1"
511
+
512
+ elif manager.is_valid_ponderation_csv:
513
+ logging.info("Manual ponderation")
514
+ # Load the ponderation file
515
+ pond = pd.read_csv(manager.PONDERATION_CSV)
516
+ # Set the index to the interval, so we can use the interval as a key
517
+ pond.set_index("Interval", inplace=True)
518
+
519
+ else:
520
+ logging.error("The ponderation file is missing")
521
+ logging.info("Please provide the ponderation file or set 'coeff_auto' to True")
522
+ return -1
523
+
524
+ assert len(pond) == len(return_periods), "The number of ponderations is not equal to the number of return periods"
525
+
526
+ # Initialize the combined acceptability matrix -- Ponderate mean of the local acceptability
527
+ comb = np.zeros(part_accept[return_periods[-1]].shape, dtype=np.float32)
528
+
529
+ for curT in return_periods:
530
+ assert part_accept[curT].dtype == np.float32, "The dtype of the acceptability matrix is not np.float32"
531
+ assert part_accept[curT].shape == comb.shape, "The shape of the acceptability matrix is not the right one"
532
+
533
+ comb += part_accept[curT] * float(pond["Ponderation"][curT])
534
+
535
+ y_pixels, x_pixels = comb.shape # number of pixels in x
536
+
537
+ # Set up output GeoTIFF
538
+ driver = gdal.GetDriverByName('GTiff')
539
+ dataset = driver.Create(str(manager.OUT_ACCEPT),
540
+ x_pixels, y_pixels,
541
+ 1,
542
+ gdal.GDT_Float32,
543
+ options=["COMPRESS=LZW"])
544
+
545
+ assert comb.dtype == np.float32, "The dtype of the combined acceptability matrix is not np.float32"
546
+
547
+ dataset.GetRasterBand(1).WriteArray(comb)
548
+ dataset.SetGeoTransform(geotrans)
549
+ dataset.SetProjection(proj)
550
+ dataset.FlushCache()
551
+ dataset=None
552
+
553
+ # Resample to XXm
554
+ Agg = gdal.Warp(str(manager.OUT_ACCEPT_100M),
555
+ str(manager.OUT_ACCEPT),
556
+ xRes=resample_size,
557
+ yRes=resample_size,
558
+ resampleAlg='Average')
559
+ Agg.FlushCache()
560
+ Agg = None
561
+
562
+ done.append(steps_acceptability.COMPUTE_MEAN_ACCEPT)
563
+
552
564
  return done