rapsoj commited on
Commit
b48a96a
·
verified ·
1 Parent(s): 5880145

Delete hazards/hazards

Browse files
Files changed (1) hide show
  1. hazards/hazards/flood.py +0 -115
hazards/hazards/flood.py DELETED
@@ -1,115 +0,0 @@
1
- from data.geometry import get_geometry, has_associated_features
2
- import math, os, rasterio, urllib.request
3
- from rasterio.merge import merge
4
- from rasterio.mask import mask
5
- from bs4 import BeautifulSoup
6
- from datetime import datetime
7
- import requests, tempfile
8
-
9
- def generate_flood_raster(iso: str, rp: int, gis_name: str = None):
10
- iso = iso.upper()
11
- base_url = "https://gis.unhcr.org/arcgis/rest/services/core_v2/wrl_polbnd_adm1_a_unhcr/MapServer/0/query"
12
-
13
- has_features, _ = has_associated_features(iso, base_url)
14
- if has_features:
15
- gdf = get_geometry(iso, url=base_url)
16
- # If a specific subdivision is selected, filter to it
17
- if gis_name:
18
- gdf = gdf[gdf['gis_name'] == gis_name]
19
- if gdf.empty:
20
- return None, f"❌ No geometry found for {gis_name} in {iso}."
21
- else:
22
- if not gis_name:
23
- return None, f"❌ Subdivision required for {iso}."
24
- gdf = get_geometry(iso, gis_name)
25
- if gdf is None or gdf.empty:
26
- return None, f"❌ No geometry found for {gis_name} in {iso}."
27
-
28
- geoms = [feature["geometry"] for feature in gdf.__geo_interface__["features"]]
29
- bounds = gdf.total_bounds # left, bottom, right, top
30
-
31
- # --- Determine tiles to download ---
32
- top = math.ceil(bounds[3] / 10) * 10
33
- left = (int(bounds[0]) // 10) * 10
34
- right = math.ceil(bounds[2] / 10) * 10
35
- bottom = (int(bounds[1]) // 10) * 10
36
-
37
- url_base = f"https://jeodpp.jrc.ec.europa.eu/ftp/jrc-opendata/CEMS-GLOFAS/flood_hazard/RP{rp}/"
38
- page = requests.get(url_base)
39
- soup = BeautifulSoup(page.text, "html.parser")
40
- all_links = [a['href'] for a in soup.find_all('a') if a['href'].endswith('.tif')]
41
-
42
- tif_paths = []
43
- col = left
44
- while col < right:
45
- row = top
46
- while row > bottom:
47
- prefix = f"{'N' if row >= 0 else 'S'}{abs(row)}_{'E' if col >= 0 else 'W'}{abs(col)}"
48
- match = [l for l in all_links if prefix in l]
49
- if match:
50
- tif_paths.append(match[0])
51
- row -= 10
52
- col += 10
53
-
54
- if not tif_paths:
55
- return None, "❌ No tiles found for selected region."
56
-
57
- # --- Create temporary working folder ---
58
- workdir = tempfile.mkdtemp(dir=tempfile.gettempdir(), prefix="flood_")
59
- cropped_files = []
60
-
61
- # --- Download, crop, and write tiles one by one ---
62
- for tif in tif_paths:
63
- remote = url_base + tif
64
- local = os.path.join(workdir, tif)
65
- urllib.request.urlretrieve(remote, local)
66
-
67
- # crop tile to geometry
68
- with rasterio.open(local) as src:
69
- out_image, out_transform = mask(src, geoms, crop=True, nodata=-9999)
70
- out_meta = src.meta.copy()
71
- out_meta.update({
72
- "height": out_image.shape[1],
73
- "width": out_image.shape[2],
74
- "transform": out_transform,
75
- "nodata": -9999
76
- })
77
-
78
- cropped_path = os.path.join(workdir, f"cropped_{tif}")
79
- with rasterio.open(cropped_path, "w", **out_meta) as dst:
80
- dst.write(out_image)
81
-
82
- cropped_files.append(cropped_path)
83
- os.remove(local) # remove original tile to save disk
84
-
85
- if not cropped_files:
86
- return None, "❌ No cropped tiles available."
87
-
88
- # --- Merge cropped tiles using generator to reduce memory ---
89
- sources = [rasterio.open(f) for f in cropped_files]
90
- mosaic, merge_transform = merge(sources)
91
-
92
- # After merging, close sources to free RAM
93
- for src in sources:
94
- src.close()
95
-
96
- timestamp = datetime.utcnow().strftime("%Y%m%d%H%M%S")
97
- output_path = os.path.join(workdir, f"merged_raster_{iso}_{rp}_{timestamp}.tif")
98
-
99
- out_meta = rasterio.open(cropped_files[0]).meta.copy()
100
- out_meta.update({
101
- "driver": "GTiff",
102
- "height": mosaic.shape[1],
103
- "width": mosaic.shape[2],
104
- "transform": merge_transform,
105
- "nodata": -9999
106
- })
107
-
108
- with rasterio.open(output_path, "w", **out_meta) as dest:
109
- dest.write(mosaic)
110
-
111
- # Cleanup
112
- for f in cropped_files:
113
- os.remove(f)
114
-
115
- return output_path, f"✅ Raster generated for {iso} ({rp}-year return period). Click to download below."