wolfhece 2.1.28__py3-none-any.whl → 2.1.30__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.
@@ -135,7 +135,7 @@ class Accept_Manager():
135
135
  CE_IGN_top10v:str = 'CE_IGN_TOP10V/CE_IGN_TOP10V.shp',
136
136
  EPU_Stations:str = 'AJOUT_PDET_EPU_DG03_STATIONS.shp',
137
137
  Ponderation_csv:str = 'Ponderation.csv',
138
- Vulnerability_csv:str = 'Vulnerability.csv',
138
+ Vuln_csv:str = 'Vulnerability.csv',
139
139
  Intermediate_csv:str = 'Intermediate.csv'
140
140
  ) -> None:
141
141
 
@@ -171,7 +171,7 @@ class Accept_Manager():
171
171
  self.CE_IGN_TOP10V = self.IN_DATABASE / self._ce_ign_top10v
172
172
  self.EPU_STATIONS = self.IN_EPU_STATIONS / EPU_Stations
173
173
 
174
- self.VULNERABILITY_CSV = self.IN_CSV / Vulnerability_csv
174
+ self.VULNERABILITY_CSV = self.IN_CSV / Vuln_csv
175
175
  self.POINTS_CSV = self.IN_CSV / Intermediate_csv
176
176
  self.PONDERATION_CSV = self.IN_CSV / Ponderation_csv
177
177
 
@@ -854,6 +854,53 @@ class Accept_Manager():
854
854
  else:
855
855
  return Modif_Type.COPY
856
856
 
857
+ def check_origin_shape(self) -> list[str]:
858
+
859
+ code = self.get_files_in_rasters_code()
860
+ vuln = self.get_files_in_rasters_vulne()
861
+
862
+ if len(code) == 0:
863
+ logging.error("The code rasters do not exist")
864
+ return False
865
+
866
+ if len(vuln) == 0:
867
+ logging.error("The vulnerability rasters do not exist")
868
+ return False
869
+
870
+ if len(code) != len(vuln):
871
+ logging.error("The number of code and vulnerability rasters do not match")
872
+ return False
873
+
874
+ # we take a reference raster
875
+ ref = gdal.Open(str(code[0]))
876
+ band_ref = ref.GetRasterBand(1)
877
+ proj_ref = ref.GetProjection()
878
+ geo_ref = ref.GetGeoTransform()
879
+ col_ref, row_ref = band_ref.XSize, band_ref.YSize
880
+
881
+ # we compare the reference raster with the others
882
+ diff = []
883
+ for cur in code + vuln + [self.SA_MASKED_RIVER]:
884
+ cur_ = gdal.Open(str(cur))
885
+ band_cur = cur_.GetRasterBand(1)
886
+ proj_cur = cur_.GetProjection()
887
+ geo_cur = cur_.GetGeoTransform()
888
+ col_cur, row_cur = band_cur.XSize, band_cur.YSize
889
+
890
+ if geo_ref != geo_cur:
891
+ logging.error("The geotransforms do not match {}".format(cur))
892
+ diff.append(cur)
893
+
894
+ if proj_ref != proj_cur:
895
+ logging.error("The projections do not match {}".format(cur))
896
+ diff.append(cur)
897
+
898
+ if col_ref != col_cur or row_ref != row_cur:
899
+ logging.error("The dimensions do not match {}".format(cur))
900
+ diff.append(cur)
901
+
902
+ return diff
903
+
857
904
 
858
905
  def clip_layer(layer:str,
859
906
  file_path:str,
@@ -1103,7 +1150,6 @@ def compute_vulnerability(manager:Accept_Manager):
1103
1150
  # Create a JIT function to update the arrays
1104
1151
  # Faster than the classical Python loop or Numpy
1105
1152
  @nb.jit(nopython=True, boundscheck=False, inline='always')
1106
- # @cuda.jit(device=True, inline=True)
1107
1153
  def update_arrays_jit(tmp_vuln, array_vuln):
1108
1154
  for i in range(tmp_vuln.shape[0]):
1109
1155
  for j in range(tmp_vuln.shape[1]):
@@ -1113,11 +1159,14 @@ def compute_vulnerability(manager:Accept_Manager):
1113
1159
  return array_vuln
1114
1160
 
1115
1161
  @nb.jit(nopython=True, boundscheck=False, inline='always')
1116
- # @cuda.jit(device=True, inline=True)
1117
- def update_arrays_jit_coo(row, col, locvuln, array_vuln):
1118
- for i,j in zip(row, col):
1119
- if locvuln >= array_vuln[i, j]:
1120
- array_vuln[i, j] = locvuln
1162
+ def update_arrays_jit_csr(row, col, locvuln, array_vuln):
1163
+ for k in range(len(row)-1):
1164
+ i = k
1165
+ j1 = row[k]
1166
+ j2 = row[k+1]
1167
+ for j in col[j1:j2]:
1168
+ if locvuln >= array_vuln[i, j]:
1169
+ array_vuln[i, j] = locvuln
1121
1170
 
1122
1171
  return array_vuln
1123
1172
 
@@ -1135,7 +1184,7 @@ def compute_vulnerability(manager:Accept_Manager):
1135
1184
  ii = ij_npz['row']
1136
1185
  jj = ij_npz['col']
1137
1186
  # We use the jit
1138
- update_arrays_jit_coo(ii, jj, locvuln, array_vuln)
1187
+ update_arrays_jit_csr(ii, jj, locvuln, array_vuln)
1139
1188
 
1140
1189
  else:
1141
1190
  ds = gdal.OpenEx(str(rasters_vuln[i]), open_options=["SPARSE_OK=TRUE"])
@@ -1194,7 +1243,6 @@ def compute_code(manager:Accept_Manager):
1194
1243
  # Create a JIT function to update the arrays
1195
1244
  # Faster than the classical Python loop or Numpy
1196
1245
  @nb.jit(nopython=True, boundscheck=False, inline='always')
1197
- # @cuda.jit(device=True, inline=True)
1198
1246
  def update_arrays_jit(tmp_code, loccode, array_code):
1199
1247
  for i in range(tmp_code.shape[0]):
1200
1248
  for j in range(tmp_code.shape[1]):
@@ -1204,11 +1252,14 @@ def compute_code(manager:Accept_Manager):
1204
1252
  return array_code
1205
1253
 
1206
1254
  @nb.jit(nopython=True, boundscheck=False, inline='always')
1207
- # @cuda.jit(device=True, inline=True)
1208
- def update_arrays_jit_coo(row, col, loccode, array_code):
1209
- for i,j in zip(row, col):
1210
- if loccode >= array_code[i, j]:
1211
- array_code[i, j] = loccode
1255
+ def update_arrays_jit_csr(row, col, loccode, array_code):
1256
+ for k in range(len(row)-1):
1257
+ i = k
1258
+ j1 = row[k]
1259
+ j2 = row[k+1]
1260
+ for j in col[j1:j2]:
1261
+ if loccode >= array_code[i, j]:
1262
+ array_code[i, j] = loccode
1212
1263
 
1213
1264
  return array_code
1214
1265
 
@@ -1222,7 +1273,7 @@ def compute_code(manager:Accept_Manager):
1222
1273
  ii = ij_npz['row']
1223
1274
  jj = ij_npz['col']
1224
1275
  # We use the jit
1225
- update_arrays_jit_coo(ii, jj, loccode, array_code)
1276
+ update_arrays_jit_csr(ii, jj, loccode, array_code)
1226
1277
 
1227
1278
  else:
1228
1279
  ds = gdal.OpenEx(str(rasters_code[i]), open_options=["SPARSE_OK=TRUE"])
@@ -1277,9 +1328,9 @@ def compute_vulnerability4scenario(manager:Accept_Manager):
1277
1328
  array_mod = gdal.Open(str(curfile))
1278
1329
  array_mod = np.array(array_mod.GetRasterBand(1).ReadAsArray())
1279
1330
 
1280
- ij = np.where(array_mod == 1)
1281
- array_vuln[ij] = 1
1282
- array_code[ij] = 1
1331
+ ij = np.argwhere(array_mod == 1)
1332
+ array_vuln[ij[:,0], ij[:,1]] = 1
1333
+ array_code[ij[:,0], ij[:,1]] = 1
1283
1334
 
1284
1335
  dst_filename= str(manager.TMP_VULN)
1285
1336
  y_pixels, x_pixels = array_vuln.shape # number of pixels in x
@@ -1331,11 +1382,20 @@ def match_vulnerability2sim(inRas:Path, outRas:Path, MODREC:Path):
1331
1382
  ds = gdal.Translate(outRas, ds, projWin = [minx, maxy, maxx, miny])
1332
1383
  ds = None
1333
1384
 
1385
+
1386
+ @nb.jit(nopython=True, boundscheck=False, inline='always')
1387
+ def update_accept(accept, model_h, ij, bounds, loc_accept):
1388
+ for idx in range(len(bounds)):
1389
+ for i,j in ij:
1390
+ if bounds[idx,0] < model_h[i,j] <= bounds[idx,1]:
1391
+ accept[i,j] = loc_accept[idx]
1392
+
1334
1393
  def compute_acceptability(manager:Accept_Manager,
1335
1394
  model_h:np.ndarray,
1336
1395
  vulnerability:np.ndarray,
1337
1396
  interval:int,
1338
- geo_projection):
1397
+ geo_projection:tuple,
1398
+ save_to_file:bool=True) -> np.ndarray:
1339
1399
 
1340
1400
  """
1341
1401
  Compute the local acceptability based on :
@@ -1343,7 +1403,7 @@ def compute_acceptability(manager:Accept_Manager,
1343
1403
  - the water depth
1344
1404
  - the matrices
1345
1405
 
1346
- :param dirsnames: the Dirs_Names object from the calling function
1406
+ :param manager: the Accept_Manager object from the calling function
1347
1407
  :param model_h: the water depth matrix
1348
1408
  :param vulnerability: the vulnerability matrix
1349
1409
  :param interval: the return period
@@ -1353,50 +1413,50 @@ def compute_acceptability(manager:Accept_Manager,
1353
1413
 
1354
1414
  logging.info(interval)
1355
1415
 
1356
- Qfile = pd.read_csv(manager.POINTS_CSV)
1416
+ points_accept = pd.read_csv(manager.POINTS_CSV)
1357
1417
 
1358
- Qfile = Qfile[Qfile["Interval"]==interval]
1359
- Qfile = Qfile.reset_index()
1418
+ points_accept = points_accept[points_accept["Interval"]==interval]
1419
+ points_accept = points_accept.reset_index()
1360
1420
 
1361
- x,y = vulnerability.shape
1362
- accept = np.zeros((x,y))
1421
+ accept = np.zeros(vulnerability.shape, dtype=np.float32)
1363
1422
 
1364
- ij_1 = np.where(vulnerability == 1)
1365
- ij_2 = np.where(vulnerability == 2)
1366
- ij_3 = np.where(vulnerability == 3)
1367
- ij_4 = np.where(vulnerability == 4)
1368
- ij_5 = np.where(vulnerability == 5)
1423
+ bounds = np.asarray([[0., 0.02], [0.02, 0.3], [0.3, 1], [1, 2.5], [2.5, 1000]], dtype=np.float32)
1369
1424
 
1370
- bounds = [(0., 0.02), (0.02, 0.3), (0.3, 1), (1, 2.5), (2.5, 1000)]
1425
+ for i in range(1,6):
1426
+ ij = np.argwhere(vulnerability == i)
1371
1427
 
1372
- accept_1 = [Qfile["h-0"][4], Qfile["h-0.02"][4], Qfile["h-0.3"][4], Qfile["h-1"][4], Qfile["h-2.5"][4]]
1373
- accept_2 = [Qfile["h-0"][3], Qfile["h-0.02"][3], Qfile["h-0.3"][3], Qfile["h-1"][3], Qfile["h-2.5"][3]]
1374
- accept_3 = [Qfile["h-0"][2], Qfile["h-0.02"][2], Qfile["h-0.3"][2], Qfile["h-1"][2], Qfile["h-2.5"][2]]
1375
- accept_4 = [Qfile["h-0"][1], Qfile["h-0.02"][1], Qfile["h-0.3"][1], Qfile["h-1"][1], Qfile["h-2.5"][1]]
1376
- accept_5 = [Qfile["h-0"][0], Qfile["h-0.02"][0], Qfile["h-0.3"][0], Qfile["h-1"][0], Qfile["h-2.5"][0]]
1428
+ idx_pts = 5-i
1429
+ accept_pts = [points_accept["h-0"][idx_pts],
1430
+ points_accept["h-0.02"][idx_pts],
1431
+ points_accept["h-0.3"][idx_pts],
1432
+ points_accept["h-1"][idx_pts],
1433
+ points_accept["h-2.5"][idx_pts]]
1434
+
1435
+ update_accept(accept, model_h, ij, bounds, accept_pts)
1377
1436
 
1378
- accept[:,:] = -99999
1379
- for ij, loc_accept in zip([ij_1, ij_2, ij_3, ij_4, ij_5], [accept_1, accept_2, accept_3, accept_4, accept_5]):
1380
- if len(ij[0]) > 0:
1381
- for idx, (min_bound, max_bound) in enumerate(bounds):
1382
- loc_ij = np.where((model_h[ij] > min_bound) & (model_h[ij] <= max_bound))
1383
- accept[ij[0][loc_ij], ij[1][loc_ij]] = loc_accept[idx]
1437
+ if save_to_file:
1438
+ #save raster
1439
+ dst_filename = str(manager.TMP_QFILES / "Q{}.tif".format(interval))
1384
1440
 
1385
- #save raster
1386
- dst_filename = str(manager.TMP_QFILES / "Q{}.tif".format(interval))
1441
+ y_pixels, x_pixels = accept.shape # number of pixels in x
1442
+ driver = gdal.GetDriverByName('GTiff')
1443
+ dataset = driver.Create(dst_filename,
1444
+ x_pixels, y_pixels,
1445
+ 1,
1446
+ gdal.GDT_Float32,
1447
+ options=["COMPRESS=LZW"])
1387
1448
 
1388
- y_pixels, x_pixels = accept.shape # number of pixels in x
1389
- driver = gdal.GetDriverByName('GTiff')
1390
- dataset = driver.Create(dst_filename, x_pixels, y_pixels, 1, gdal.GDT_Float32, options=["COMPRESS=LZW"])
1391
- dataset.GetRasterBand(1).WriteArray(accept.astype(np.float32))
1449
+ dataset.GetRasterBand(1).WriteArray(accept.astype(np.float32))
1392
1450
 
1393
- geotrans, proj = geo_projection
1394
- dataset.SetGeoTransform(geotrans)
1395
- dataset.SetProjection(proj)
1396
- dataset.FlushCache()
1397
- dataset = None
1451
+ geotrans, proj = geo_projection
1452
+ dataset.SetGeoTransform(geotrans)
1453
+ dataset.SetProjection(proj)
1454
+ dataset.FlushCache()
1455
+ dataset = None
1398
1456
 
1399
- def shp_to_raster(vector_fn:str, raster_fn:str, pixel_size:float = 1.):
1457
+ return accept
1458
+
1459
+ def shp_to_raster(vector_fn:str, raster_fn:str, pixel_size:float = 1., manager:Accept_Manager = None):
1400
1460
  """
1401
1461
  Convert a vector layer to a raster tiff file.
1402
1462
 
@@ -1413,12 +1473,23 @@ def shp_to_raster(vector_fn:str, raster_fn:str, pixel_size:float = 1.):
1413
1473
  # Force the input to be a string
1414
1474
  vector_fn = str(vector_fn)
1415
1475
  raster_fn = str(raster_fn)
1476
+
1477
+ if manager is None:
1478
+ extent_fn = vector_fn
1479
+ logging.warning("The extent file is not provided, the extent will be the same as the vector file")
1480
+ else:
1481
+ extent_fn = str(manager.SA)
1482
+ logging.info("The extent file is provided")
1416
1483
 
1417
1484
  NoData_value = 0 # np.nan is not necessary a good idea
1485
+
1418
1486
  # Open the data sources and read the extents
1419
- source_ds = ogr.Open(vector_fn)
1487
+ source_ds:ogr.DataSource = ogr.Open(vector_fn)
1420
1488
  source_layer = source_ds.GetLayer()
1421
- x_min, x_max, y_min, y_max = source_layer.GetExtent()
1489
+
1490
+ extent_ds:ogr.DataSource = ogr.Open(extent_fn)
1491
+ extent_layer = extent_ds.GetLayer()
1492
+ x_min, x_max, y_min, y_max = extent_layer.GetExtent()
1422
1493
 
1423
1494
  x_min = float(int(x_min))
1424
1495
  x_max = float(np.ceil(x_max))
@@ -1459,6 +1530,8 @@ def vector_to_raster(layer:str,
1459
1530
  """
1460
1531
  Convert a vector layer to a raster tiff file
1461
1532
 
1533
+ FIXME: Test de vulerability value and return immedialty if it is 1 if attribute == "Vulne"
1534
+
1462
1535
  :param layer: the layer name in the GDB file
1463
1536
  :param vector_input: the path to the vector file
1464
1537
  :param extent: the path to the extent file
@@ -1524,11 +1597,31 @@ def vector_to_raster(layer:str,
1524
1597
  "ALL_TOUCHED=TRUE"])
1525
1598
 
1526
1599
  if convert_to_sparse:
1600
+ SPARSITY_THRESHOLD = 0.02
1527
1601
  # Convert the raster to a npz containing the row and col of the non-null values
1528
1602
  array = band.ReadAsArray()
1529
1603
  ij = np.nonzero(array)
1530
- np.savez_compressed(Path(out_file).with_suffix('.npz'), row=ij[0].astype(np.int32), col=ij[1].astype(np.int32))
1604
+
1605
+ if len(ij[0]) < int(x_res * y_res * SPARSITY_THRESHOLD):
1606
+ i,j = convert_to_csr(ij[0], ij[1], y_res)
1607
+ np.savez_compressed(Path(out_file).with_suffix('.npz'), row=np.asarray(i, dtype=np.int32), col=np.asarray(j, dtype=np.int32))
1608
+ else:
1609
+ logging.info("The raster is not sparse enough to be converted to a CSR forma {}".format(layer))
1531
1610
 
1532
1611
  target_ds = None
1533
1612
 
1534
1613
  return 0
1614
+
1615
+ @nb.jit(nopython=True, boundscheck=False, inline='always')
1616
+ def convert_to_csr(i_indices, j_indices, num_rows):
1617
+ row_ptr = [0] * (num_rows + 1)
1618
+ col_idx = []
1619
+
1620
+ for i in range(len(i_indices)):
1621
+ row_ptr[i_indices[i] + 1] += 1
1622
+ col_idx.append(j_indices[i])
1623
+
1624
+ for i in range(1, len(row_ptr)):
1625
+ row_ptr[i] += row_ptr[i - 1]
1626
+
1627
+ return row_ptr, col_idx
@@ -7,6 +7,13 @@ import wx
7
7
  import time
8
8
  from wx.adv import SplashScreen as SplashScreen,SPLASH_CENTRE_ON_SCREEN,SPLASH_TIMEOUT,Sound
9
9
 
10
+ # try:
11
+ # from ..libs import wolfogl
12
+ # except:
13
+ # print("** WolfOGL not found **")
14
+ # print("Without WolfOGL, the application will not work !")
15
+ # print("Please reinstall 'wolfhece' package -- pip install wolfhece")
16
+
10
17
  class WolfLauncher(SplashScreen):
11
18
  """
12
19
  Wolf Splashcreen
@@ -15,10 +22,17 @@ class WolfLauncher(SplashScreen):
15
22
  done = False
16
23
 
17
24
  def __init__(self, parent=None, play_sound=True):
18
-
25
+
19
26
  if self.done:
20
27
  return
21
28
 
29
+ # try:
30
+ # wolfogl.init()
31
+ # except Exception as e:
32
+ # print("Error initializing WolfOGL -- We must stop here !")
33
+ # print("Please reinstall 'wolfhece' package -- pip install wolfhece")
34
+ # exit()
35
+
22
36
  mydir=dirname(__file__)
23
37
  mybitmap = wx.Bitmap(name=join(mydir,".\\WolfPython2.png"), type=wx.BITMAP_TYPE_PNG)
24
38
 
wolfhece/apps/version.py CHANGED
@@ -5,7 +5,7 @@ class WolfVersion():
5
5
 
6
6
  self.major = 2
7
7
  self.minor = 1
8
- self.patch = 28
8
+ self.patch = 30
9
9
 
10
10
  def __str__(self):
11
11