Datasets:
Upload folder using huggingface_hub
Browse files- .gitattributes +1 -60
- README.md +82 -0
- river_data_facilities.geoparquet +3 -0
- river_data_segments.geoparquet +3 -0
- river_proximity.py +617 -0
- visualize_facilities_rivers.py +311 -0
- visualize_single_facility.py +191 -0
.gitattributes
CHANGED
|
@@ -1,60 +1 @@
|
|
| 1 |
-
*.
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.avro filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.lz4 filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.mds filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 36 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 37 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 38 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 39 |
-
# Audio files - uncompressed
|
| 40 |
-
*.pcm filter=lfs diff=lfs merge=lfs -text
|
| 41 |
-
*.sam filter=lfs diff=lfs merge=lfs -text
|
| 42 |
-
*.raw filter=lfs diff=lfs merge=lfs -text
|
| 43 |
-
# Audio files - compressed
|
| 44 |
-
*.aac filter=lfs diff=lfs merge=lfs -text
|
| 45 |
-
*.flac filter=lfs diff=lfs merge=lfs -text
|
| 46 |
-
*.mp3 filter=lfs diff=lfs merge=lfs -text
|
| 47 |
-
*.ogg filter=lfs diff=lfs merge=lfs -text
|
| 48 |
-
*.wav filter=lfs diff=lfs merge=lfs -text
|
| 49 |
-
# Image files - uncompressed
|
| 50 |
-
*.bmp filter=lfs diff=lfs merge=lfs -text
|
| 51 |
-
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 52 |
-
*.png filter=lfs diff=lfs merge=lfs -text
|
| 53 |
-
*.tiff filter=lfs diff=lfs merge=lfs -text
|
| 54 |
-
# Image files - compressed
|
| 55 |
-
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 56 |
-
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
| 57 |
-
*.webp filter=lfs diff=lfs merge=lfs -text
|
| 58 |
-
# Video files - compressed
|
| 59 |
-
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
-
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
*.geoparquet filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
README.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# EEA Industrial Emissions - River Proximity Dataset
|
| 2 |
+
|
| 3 |
+
This dataset matches **160,576 industrial facilities** from the European Environment Agency (EEA) Industrial Emissions database to nearby river segments from HydroRIVERS, with upstream/downstream flow analysis.
|
| 4 |
+
|
| 5 |
+
## Dataset Description
|
| 6 |
+
|
| 7 |
+
For each facility within 1km of a river:
|
| 8 |
+
- **Upstream segments**: River parts flowing *toward* the facility (potential source water)
|
| 9 |
+
- **Downstream segments**: River parts flowing *away* from the facility (potentially affected by emissions)
|
| 10 |
+
|
| 11 |
+
The split point is the closest point on the river to each facility.
|
| 12 |
+
|
| 13 |
+
## Files
|
| 14 |
+
|
| 15 |
+
### `river_data_facilities.geoparquet`
|
| 16 |
+
Main dataset with 160,576 facilities and their river associations.
|
| 17 |
+
|
| 18 |
+
| Column | Description |
|
| 19 |
+
|--------|-------------|
|
| 20 |
+
| `facilityName` | Name of the industrial facility |
|
| 21 |
+
| `city`, `countryName` | Location |
|
| 22 |
+
| `EPRTR_SectorCode/Name` | Industry sector |
|
| 23 |
+
| `Pollutant`, `Releases` | Emission data |
|
| 24 |
+
| `closest_river_id` | HydroRIVERS segment ID |
|
| 25 |
+
| `distance_to_river_m` | Distance to nearest river (meters) |
|
| 26 |
+
| `river_strahler` | Strahler stream order |
|
| 27 |
+
| `river_discharge` | Average discharge (m³/s) |
|
| 28 |
+
| `upstream_segment_ids` | List of upstream HydroRIVERS IDs |
|
| 29 |
+
| `downstream_segment_ids` | List of downstream HydroRIVERS IDs |
|
| 30 |
+
| `n_upstream`, `n_downstream` | Count of segments |
|
| 31 |
+
| `upstream_line_wkb`, `downstream_line_wkb` | River line geometries (WKB) |
|
| 32 |
+
| `upstream_poly_wkb`, `downstream_poly_wkb` | Water surface polygons (WKB) |
|
| 33 |
+
| `geometry` | Facility point location |
|
| 34 |
+
|
| 35 |
+
### `river_data_segments.geoparquet`
|
| 36 |
+
28,434 river segment geometries with direction labels.
|
| 37 |
+
|
| 38 |
+
| Column | Description |
|
| 39 |
+
|--------|-------------|
|
| 40 |
+
| `HYRIV_ID` | HydroRIVERS segment ID |
|
| 41 |
+
| `direction` | "upstream" or "downstream" |
|
| 42 |
+
| `ORD_STRA` | Strahler stream order |
|
| 43 |
+
| `DIS_AV_CMS` | Average discharge (m³/s) |
|
| 44 |
+
| `LENGTH_KM` | Segment length (km) |
|
| 45 |
+
| `geometry` | LineString geometry |
|
| 46 |
+
|
| 47 |
+
## Usage
|
| 48 |
+
|
| 49 |
+
```python
|
| 50 |
+
import geopandas as gpd
|
| 51 |
+
from shapely import wkb
|
| 52 |
+
|
| 53 |
+
# Load facilities
|
| 54 |
+
facilities = gpd.read_parquet("river_data_facilities.geoparquet")
|
| 55 |
+
|
| 56 |
+
# Get a facility's upstream river geometry
|
| 57 |
+
facility = facilities[facilities['facilityName'].str.contains('PRECHEZA')].iloc[0]
|
| 58 |
+
upstream_line = wkb.loads(facility['upstream_line_wkb'])
|
| 59 |
+
downstream_line = wkb.loads(facility['downstream_line_wkb'])
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
## Visualization Scripts
|
| 63 |
+
|
| 64 |
+
- `visualize_single_facility.py` - Interactive map for a single facility
|
| 65 |
+
- `visualize_facilities_rivers.py` - Overview map with sampled facilities
|
| 66 |
+
|
| 67 |
+
## Source Data
|
| 68 |
+
|
| 69 |
+
- **Facilities**: [EEA Industrial Emissions Database](https://www.eea.europa.eu/data-and-maps/data/industrial-reporting-under-the-industrial-6)
|
| 70 |
+
- **Rivers**: [HydroRIVERS v1.0](https://www.hydrosheds.org/products/hydrorivers)
|
| 71 |
+
- **Water Polygons**: [EU-Hydro River Network Database](https://land.copernicus.eu/imagery-in-situ/eu-hydro)
|
| 72 |
+
|
| 73 |
+
## Parameters Used
|
| 74 |
+
|
| 75 |
+
- Max distance to river: 1,000m
|
| 76 |
+
- Upstream trace distance: 10km
|
| 77 |
+
- Downstream trace distance: 10km
|
| 78 |
+
- Polygon buffer: 600m
|
| 79 |
+
|
| 80 |
+
## License
|
| 81 |
+
|
| 82 |
+
The derived dataset follows the licenses of the source datasets. See original sources for details.
|
river_data_facilities.geoparquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f77d31ba498f4865a4f9212842a001391e0a9a7a34420bf481511a64308d23a3
|
| 3 |
+
size 2623539851
|
river_data_segments.geoparquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f42748db4285312ce018be67ca74543e72c385af36653cd8f666f56cf7b6537c
|
| 3 |
+
size 1658895
|
river_proximity.py
ADDED
|
@@ -0,0 +1,617 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Match industrial facilities to nearby river segments with upstream/downstream split.
|
| 3 |
+
|
| 4 |
+
Optimized for batch processing:
|
| 5 |
+
1. Find closest rivers for all facilities (using spatial index)
|
| 6 |
+
2. Trace upstream/downstream segment IDs (fast lookups)
|
| 7 |
+
3. Batch build geometries at the end using lookup dicts
|
| 8 |
+
4. Batch clip polygons once at the end
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import geopandas as gpd
|
| 12 |
+
import pandas as pd
|
| 13 |
+
import numpy as np
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from shapely.ops import unary_union
|
| 16 |
+
from shapely.geometry import Point, LineString, MultiLineString
|
| 17 |
+
from shapely import STRtree
|
| 18 |
+
from collections import defaultdict
|
| 19 |
+
import sys
|
| 20 |
+
|
| 21 |
+
def log(msg):
|
| 22 |
+
print(msg, flush=True)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def load_facilities(filepath: Path) -> gpd.GeoDataFrame:
|
| 26 |
+
"""Load water-releasing facilities and convert to GeoDataFrame."""
|
| 27 |
+
log(f"Loading facilities from {filepath}...")
|
| 28 |
+
df = pd.read_csv(filepath, low_memory=False)
|
| 29 |
+
df = df.dropna(subset=["Longitude", "Latitude"])
|
| 30 |
+
gdf = gpd.GeoDataFrame(
|
| 31 |
+
df,
|
| 32 |
+
geometry=gpd.points_from_xy(df.Longitude, df.Latitude),
|
| 33 |
+
crs="EPSG:4326"
|
| 34 |
+
)
|
| 35 |
+
log(f"Loaded {len(gdf):,} facilities with valid coordinates")
|
| 36 |
+
return gdf
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def load_rivers(filepath: Path, min_strahler_order: int = 1) -> gpd.GeoDataFrame:
|
| 40 |
+
"""Load HydroRIVERS data."""
|
| 41 |
+
log(f"Loading HydroRIVERS from {filepath}...")
|
| 42 |
+
gdf = gpd.read_parquet(filepath)
|
| 43 |
+
if min_strahler_order > 1:
|
| 44 |
+
original_count = len(gdf)
|
| 45 |
+
gdf = gdf[gdf["ORD_STRA"] >= min_strahler_order].copy()
|
| 46 |
+
log(f"Filtered rivers: {original_count:,} -> {len(gdf):,} (Strahler >= {min_strahler_order})")
|
| 47 |
+
else:
|
| 48 |
+
log(f"Loaded {len(gdf):,} river segments")
|
| 49 |
+
return gdf
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def load_river_polygons(polygon_dir: Path) -> gpd.GeoDataFrame:
|
| 53 |
+
"""Load all EU-Hydro river polygon shards."""
|
| 54 |
+
log(f"Loading EU-Hydro river polygons from {polygon_dir}...")
|
| 55 |
+
shards = sorted(polygon_dir.glob("*.geoparquet"))
|
| 56 |
+
if not shards:
|
| 57 |
+
raise FileNotFoundError(f"No geoparquet files found in {polygon_dir}")
|
| 58 |
+
gdfs = [gpd.read_parquet(shard) for shard in shards]
|
| 59 |
+
result = pd.concat(gdfs, ignore_index=True)
|
| 60 |
+
result = gpd.GeoDataFrame(result, geometry="geometry", crs=gdfs[0].crs)
|
| 61 |
+
log(f"Loaded {len(result):,} river polygons from {len(shards)} basin shards")
|
| 62 |
+
return result
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def build_river_network(rivers: gpd.GeoDataFrame) -> tuple[dict, dict, dict]:
|
| 66 |
+
"""Build lookup dictionaries for river network traversal."""
|
| 67 |
+
log("Building river network graph...")
|
| 68 |
+
id_to_downstream = dict(zip(rivers["HYRIV_ID"], rivers["NEXT_DOWN"]))
|
| 69 |
+
id_to_length = dict(zip(rivers["HYRIV_ID"], rivers["LENGTH_KM"]))
|
| 70 |
+
|
| 71 |
+
id_to_upstream = {}
|
| 72 |
+
for hyriv_id, next_down in id_to_downstream.items():
|
| 73 |
+
if next_down != 0:
|
| 74 |
+
if next_down not in id_to_upstream:
|
| 75 |
+
id_to_upstream[next_down] = []
|
| 76 |
+
id_to_upstream[next_down].append(hyriv_id)
|
| 77 |
+
|
| 78 |
+
log(f" Network has {len(id_to_downstream):,} segments")
|
| 79 |
+
return id_to_downstream, id_to_upstream, id_to_length
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def build_river_lookups(rivers: gpd.GeoDataFrame, rivers_proj: gpd.GeoDataFrame):
|
| 83 |
+
"""Build lookup dictionaries for fast access."""
|
| 84 |
+
log("Building river lookup dictionaries...")
|
| 85 |
+
|
| 86 |
+
# Geometry lookup (projected for line splitting)
|
| 87 |
+
id_to_geom_proj = dict(zip(rivers_proj["HYRIV_ID"], rivers_proj.geometry))
|
| 88 |
+
|
| 89 |
+
# Metadata lookup
|
| 90 |
+
id_to_strahler = dict(zip(rivers["HYRIV_ID"], rivers["ORD_STRA"]))
|
| 91 |
+
id_to_discharge = dict(zip(rivers["HYRIV_ID"], rivers["DIS_AV_CMS"]))
|
| 92 |
+
|
| 93 |
+
log(f" Built lookups for {len(id_to_geom_proj):,} segments")
|
| 94 |
+
return id_to_geom_proj, id_to_strahler, id_to_discharge
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def split_line_at_point(line: LineString, point: Point) -> tuple[LineString, LineString]:
|
| 98 |
+
"""
|
| 99 |
+
Split a LineString at the closest point to the given point.
|
| 100 |
+
Returns (upstream_part, downstream_part).
|
| 101 |
+
"""
|
| 102 |
+
distance_along = line.project(point)
|
| 103 |
+
|
| 104 |
+
if distance_along <= 0:
|
| 105 |
+
return None, line
|
| 106 |
+
elif distance_along >= line.length:
|
| 107 |
+
return line, None
|
| 108 |
+
|
| 109 |
+
split_point = line.interpolate(distance_along)
|
| 110 |
+
coords = list(line.coords)
|
| 111 |
+
|
| 112 |
+
upstream_coords = [coords[0]]
|
| 113 |
+
downstream_coords = []
|
| 114 |
+
|
| 115 |
+
cumulative_dist = 0
|
| 116 |
+
split_inserted = False
|
| 117 |
+
|
| 118 |
+
for i in range(1, len(coords)):
|
| 119 |
+
segment = LineString([coords[i-1], coords[i]])
|
| 120 |
+
segment_length = segment.length
|
| 121 |
+
|
| 122 |
+
if not split_inserted and cumulative_dist + segment_length >= distance_along:
|
| 123 |
+
upstream_coords.append((split_point.x, split_point.y))
|
| 124 |
+
downstream_coords.append((split_point.x, split_point.y))
|
| 125 |
+
downstream_coords.append(coords[i])
|
| 126 |
+
split_inserted = True
|
| 127 |
+
elif not split_inserted:
|
| 128 |
+
upstream_coords.append(coords[i])
|
| 129 |
+
else:
|
| 130 |
+
downstream_coords.append(coords[i])
|
| 131 |
+
|
| 132 |
+
cumulative_dist += segment_length
|
| 133 |
+
|
| 134 |
+
upstream_line = LineString(upstream_coords) if len(upstream_coords) >= 2 else None
|
| 135 |
+
downstream_line = LineString(downstream_coords) if len(downstream_coords) >= 2 else None
|
| 136 |
+
|
| 137 |
+
return upstream_line, downstream_line
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def trace_downstream_segments(
|
| 141 |
+
start_id: int,
|
| 142 |
+
id_to_downstream: dict,
|
| 143 |
+
id_to_length: dict,
|
| 144 |
+
max_distance_km: float
|
| 145 |
+
) -> list:
|
| 146 |
+
"""Trace downstream and return list of segment IDs in order."""
|
| 147 |
+
segments = []
|
| 148 |
+
current_id = id_to_downstream.get(start_id, 0)
|
| 149 |
+
distance = 0
|
| 150 |
+
|
| 151 |
+
while current_id != 0 and distance < max_distance_km:
|
| 152 |
+
segments.append(current_id)
|
| 153 |
+
distance += id_to_length.get(current_id, 0)
|
| 154 |
+
current_id = id_to_downstream.get(current_id, 0)
|
| 155 |
+
|
| 156 |
+
return segments
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def trace_upstream_segments(
|
| 160 |
+
start_id: int,
|
| 161 |
+
id_to_upstream: dict,
|
| 162 |
+
id_to_length: dict,
|
| 163 |
+
max_distance_km: float
|
| 164 |
+
) -> list:
|
| 165 |
+
"""Trace upstream using BFS and return list of segment IDs."""
|
| 166 |
+
segments = []
|
| 167 |
+
queue = [(uid, 0) for uid in id_to_upstream.get(start_id, [])]
|
| 168 |
+
visited = set()
|
| 169 |
+
|
| 170 |
+
while queue:
|
| 171 |
+
current_id, dist = queue.pop(0)
|
| 172 |
+
if current_id in visited or dist > max_distance_km:
|
| 173 |
+
continue
|
| 174 |
+
visited.add(current_id)
|
| 175 |
+
segments.append(current_id)
|
| 176 |
+
seg_len = id_to_length.get(current_id, 0)
|
| 177 |
+
for uid in id_to_upstream.get(current_id, []):
|
| 178 |
+
queue.append((uid, dist + seg_len))
|
| 179 |
+
|
| 180 |
+
return segments
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def process_facilities_fast(
|
| 184 |
+
facilities: gpd.GeoDataFrame,
|
| 185 |
+
facilities_proj: gpd.GeoDataFrame,
|
| 186 |
+
rivers_proj: gpd.GeoDataFrame,
|
| 187 |
+
id_to_downstream: dict,
|
| 188 |
+
id_to_upstream: dict,
|
| 189 |
+
id_to_length: dict,
|
| 190 |
+
id_to_geom_proj: dict,
|
| 191 |
+
id_to_strahler: dict,
|
| 192 |
+
id_to_discharge: dict,
|
| 193 |
+
max_distance_m: float,
|
| 194 |
+
upstream_distance_km: float,
|
| 195 |
+
downstream_distance_km: float,
|
| 196 |
+
):
|
| 197 |
+
"""Process all facilities in an optimized way."""
|
| 198 |
+
|
| 199 |
+
# Build spatial index
|
| 200 |
+
log("Building spatial index for rivers...")
|
| 201 |
+
river_tree = STRtree(rivers_proj.geometry.values)
|
| 202 |
+
river_indices = rivers_proj.index.values
|
| 203 |
+
river_ids = rivers_proj["HYRIV_ID"].values
|
| 204 |
+
log(f" Spatial index built for {len(rivers_proj):,} rivers")
|
| 205 |
+
|
| 206 |
+
log(f"\nProcessing {len(facilities):,} facilities...")
|
| 207 |
+
|
| 208 |
+
results = []
|
| 209 |
+
all_upstream_ids = set()
|
| 210 |
+
all_downstream_ids = set()
|
| 211 |
+
|
| 212 |
+
# Store split line parts for later geometry building
|
| 213 |
+
facility_split_parts = {} # facility_idx -> (upstream_part_proj, downstream_part_proj)
|
| 214 |
+
|
| 215 |
+
for i, (idx, row) in enumerate(facilities.iterrows()):
|
| 216 |
+
if i % 10000 == 0 and i > 0:
|
| 217 |
+
log(f" Processed {i:,}/{len(facilities):,}...")
|
| 218 |
+
|
| 219 |
+
facility_point_proj = facilities_proj.loc[idx].geometry
|
| 220 |
+
|
| 221 |
+
# Find closest river using spatial index
|
| 222 |
+
buffer = facility_point_proj.buffer(max_distance_m)
|
| 223 |
+
candidate_indices = river_tree.query(buffer)
|
| 224 |
+
|
| 225 |
+
if len(candidate_indices) == 0:
|
| 226 |
+
continue
|
| 227 |
+
|
| 228 |
+
# Get candidates
|
| 229 |
+
candidate_geoms = rivers_proj.geometry.iloc[candidate_indices]
|
| 230 |
+
distances = candidate_geoms.distance(facility_point_proj)
|
| 231 |
+
|
| 232 |
+
# Filter by max distance
|
| 233 |
+
nearby_mask = distances <= max_distance_m
|
| 234 |
+
if not nearby_mask.any():
|
| 235 |
+
continue
|
| 236 |
+
|
| 237 |
+
# Get closest
|
| 238 |
+
closest_local_idx = distances[nearby_mask].idxmin()
|
| 239 |
+
closest_distance = distances[closest_local_idx]
|
| 240 |
+
closest_river_id = rivers_proj.loc[closest_local_idx, "HYRIV_ID"]
|
| 241 |
+
|
| 242 |
+
# Get the geometry from lookup (faster than GeoDataFrame access)
|
| 243 |
+
river_geom_proj = id_to_geom_proj.get(closest_river_id)
|
| 244 |
+
if river_geom_proj is None:
|
| 245 |
+
continue
|
| 246 |
+
|
| 247 |
+
# Split the closest segment at the nearest point to facility
|
| 248 |
+
upstream_part, downstream_part = split_line_at_point(river_geom_proj, facility_point_proj)
|
| 249 |
+
|
| 250 |
+
# Trace further upstream/downstream (just IDs, very fast)
|
| 251 |
+
upstream_segment_ids = trace_upstream_segments(closest_river_id, id_to_upstream, id_to_length, upstream_distance_km)
|
| 252 |
+
downstream_segment_ids = trace_downstream_segments(closest_river_id, id_to_downstream, id_to_length, downstream_distance_km)
|
| 253 |
+
|
| 254 |
+
# Collect all segment IDs
|
| 255 |
+
all_upstream_ids.update(upstream_segment_ids)
|
| 256 |
+
all_downstream_ids.update(downstream_segment_ids)
|
| 257 |
+
all_upstream_ids.add(closest_river_id)
|
| 258 |
+
all_downstream_ids.add(closest_river_id)
|
| 259 |
+
|
| 260 |
+
# Store split parts for geometry building later
|
| 261 |
+
facility_split_parts[idx] = (upstream_part, downstream_part)
|
| 262 |
+
|
| 263 |
+
# Build result (without geometries for now)
|
| 264 |
+
results.append({
|
| 265 |
+
"facility_idx": idx,
|
| 266 |
+
"facilityName": row.get("facilityName"),
|
| 267 |
+
"city": row.get("city"),
|
| 268 |
+
"countryName": row.get("countryName"),
|
| 269 |
+
"EPRTR_SectorCode": row.get("EPRTR_SectorCode"),
|
| 270 |
+
"EPRTR_SectorName": row.get("EPRTR_SectorName"),
|
| 271 |
+
"Pollutant": row.get("Pollutant"),
|
| 272 |
+
"Releases": row.get("Releases"),
|
| 273 |
+
"facility_lon": row.get("Longitude"),
|
| 274 |
+
"facility_lat": row.get("Latitude"),
|
| 275 |
+
"closest_river_id": closest_river_id,
|
| 276 |
+
"distance_to_river_m": closest_distance,
|
| 277 |
+
"river_strahler": id_to_strahler.get(closest_river_id),
|
| 278 |
+
"river_discharge": id_to_discharge.get(closest_river_id),
|
| 279 |
+
"upstream_segment_ids": upstream_segment_ids,
|
| 280 |
+
"downstream_segment_ids": downstream_segment_ids,
|
| 281 |
+
"n_upstream": len(upstream_segment_ids) + (1 if upstream_part else 0),
|
| 282 |
+
"n_downstream": len(downstream_segment_ids) + (1 if downstream_part else 0),
|
| 283 |
+
})
|
| 284 |
+
|
| 285 |
+
log(f" Found {len(results):,} facilities with nearby rivers")
|
| 286 |
+
log(f" Total unique upstream segments: {len(all_upstream_ids):,}")
|
| 287 |
+
log(f" Total unique downstream segments: {len(all_downstream_ids):,}")
|
| 288 |
+
|
| 289 |
+
return results, all_upstream_ids, all_downstream_ids, facility_split_parts
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def build_geometries_and_clip_polygons(
|
| 293 |
+
results: list,
|
| 294 |
+
facility_split_parts: dict,
|
| 295 |
+
id_to_geom_proj: dict,
|
| 296 |
+
river_polygons: gpd.GeoDataFrame,
|
| 297 |
+
buffer_meters: float,
|
| 298 |
+
):
|
| 299 |
+
"""Build line geometries and clip polygons for all facilities."""
|
| 300 |
+
log("\nBuilding line geometries and clipping polygons...")
|
| 301 |
+
|
| 302 |
+
# Ensure polygons in EPSG:3035
|
| 303 |
+
if river_polygons.crs.to_epsg() != 3035:
|
| 304 |
+
river_polygons_proj = river_polygons.to_crs("EPSG:3035")
|
| 305 |
+
else:
|
| 306 |
+
river_polygons_proj = river_polygons
|
| 307 |
+
|
| 308 |
+
# Build spatial index for polygons
|
| 309 |
+
polygon_sindex = river_polygons_proj.sindex
|
| 310 |
+
|
| 311 |
+
for i, result in enumerate(results):
|
| 312 |
+
if i % 5000 == 0 and i > 0:
|
| 313 |
+
log(f" Processed {i:,}/{len(results):,}...")
|
| 314 |
+
|
| 315 |
+
facility_idx = result["facility_idx"]
|
| 316 |
+
upstream_part, downstream_part = facility_split_parts.get(facility_idx, (None, None))
|
| 317 |
+
|
| 318 |
+
# Build upstream line geometry (in projected CRS)
|
| 319 |
+
upstream_geoms = []
|
| 320 |
+
if upstream_part is not None and not upstream_part.is_empty:
|
| 321 |
+
upstream_geoms.append(upstream_part)
|
| 322 |
+
for seg_id in result["upstream_segment_ids"]:
|
| 323 |
+
geom = id_to_geom_proj.get(seg_id)
|
| 324 |
+
if geom is not None:
|
| 325 |
+
upstream_geoms.append(geom)
|
| 326 |
+
|
| 327 |
+
# Build downstream line geometry (in projected CRS)
|
| 328 |
+
downstream_geoms = []
|
| 329 |
+
if downstream_part is not None and not downstream_part.is_empty:
|
| 330 |
+
downstream_geoms.append(downstream_part)
|
| 331 |
+
for seg_id in result["downstream_segment_ids"]:
|
| 332 |
+
geom = id_to_geom_proj.get(seg_id)
|
| 333 |
+
if geom is not None:
|
| 334 |
+
downstream_geoms.append(geom)
|
| 335 |
+
|
| 336 |
+
# Merge line geometries (still in EPSG:3035)
|
| 337 |
+
upstream_line_proj = unary_union(upstream_geoms) if upstream_geoms else None
|
| 338 |
+
downstream_line_proj = unary_union(downstream_geoms) if downstream_geoms else None
|
| 339 |
+
|
| 340 |
+
# Clip polygons based on line geometries
|
| 341 |
+
upstream_poly_proj = None
|
| 342 |
+
downstream_poly_proj = None
|
| 343 |
+
|
| 344 |
+
if upstream_line_proj is not None:
|
| 345 |
+
upstream_buffer = upstream_line_proj.buffer(buffer_meters)
|
| 346 |
+
candidates_idx = list(polygon_sindex.intersection(upstream_buffer.bounds))
|
| 347 |
+
if candidates_idx:
|
| 348 |
+
candidates = river_polygons_proj.iloc[candidates_idx]
|
| 349 |
+
intersecting = candidates[candidates.intersects(upstream_buffer)]
|
| 350 |
+
if len(intersecting) > 0:
|
| 351 |
+
clipped = [row.geometry.intersection(upstream_buffer) for _, row in intersecting.iterrows()]
|
| 352 |
+
clipped = [p for p in clipped if not p.is_empty]
|
| 353 |
+
if clipped:
|
| 354 |
+
upstream_poly_proj = unary_union(clipped)
|
| 355 |
+
|
| 356 |
+
if downstream_line_proj is not None:
|
| 357 |
+
downstream_buffer = downstream_line_proj.buffer(buffer_meters)
|
| 358 |
+
candidates_idx = list(polygon_sindex.intersection(downstream_buffer.bounds))
|
| 359 |
+
if candidates_idx:
|
| 360 |
+
candidates = river_polygons_proj.iloc[candidates_idx]
|
| 361 |
+
intersecting = candidates[candidates.intersects(downstream_buffer)]
|
| 362 |
+
if len(intersecting) > 0:
|
| 363 |
+
clipped = [row.geometry.intersection(downstream_buffer) for _, row in intersecting.iterrows()]
|
| 364 |
+
clipped = [p for p in clipped if not p.is_empty]
|
| 365 |
+
if clipped:
|
| 366 |
+
downstream_poly_proj = unary_union(clipped)
|
| 367 |
+
|
| 368 |
+
# Convert everything to WGS84
|
| 369 |
+
upstream_line = None
|
| 370 |
+
downstream_line = None
|
| 371 |
+
upstream_poly = None
|
| 372 |
+
downstream_poly = None
|
| 373 |
+
|
| 374 |
+
if upstream_line_proj:
|
| 375 |
+
upstream_line = gpd.GeoSeries([upstream_line_proj], crs="EPSG:3035").to_crs("EPSG:4326").iloc[0]
|
| 376 |
+
if downstream_line_proj:
|
| 377 |
+
downstream_line = gpd.GeoSeries([downstream_line_proj], crs="EPSG:3035").to_crs("EPSG:4326").iloc[0]
|
| 378 |
+
if upstream_poly_proj:
|
| 379 |
+
upstream_poly = gpd.GeoSeries([upstream_poly_proj], crs="EPSG:3035").to_crs("EPSG:4326").iloc[0]
|
| 380 |
+
if downstream_poly_proj:
|
| 381 |
+
downstream_poly = gpd.GeoSeries([downstream_poly_proj], crs="EPSG:3035").to_crs("EPSG:4326").iloc[0]
|
| 382 |
+
|
| 383 |
+
result["upstream_line_geom"] = upstream_line
|
| 384 |
+
result["downstream_line_geom"] = downstream_line
|
| 385 |
+
result["upstream_poly_geom"] = upstream_poly
|
| 386 |
+
result["downstream_poly_geom"] = downstream_poly
|
| 387 |
+
|
| 388 |
+
log(f" Processed {len(results):,} facilities")
|
| 389 |
+
return results
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def batch_clip_polygons(
|
| 393 |
+
all_segment_ids: set,
|
| 394 |
+
direction: str,
|
| 395 |
+
rivers_proj: gpd.GeoDataFrame,
|
| 396 |
+
river_polygons: gpd.GeoDataFrame,
|
| 397 |
+
buffer_meters: float,
|
| 398 |
+
) -> gpd.GeoDataFrame:
|
| 399 |
+
"""Batch clip polygons for all segments at once."""
|
| 400 |
+
log(f" Clipping {direction} polygons for {len(all_segment_ids):,} segments...")
|
| 401 |
+
|
| 402 |
+
if not all_segment_ids:
|
| 403 |
+
return gpd.GeoDataFrame(columns=["geometry", "direction", "HYRIV_ID", "matched_river_ids", "source_basin"])
|
| 404 |
+
|
| 405 |
+
# Get all segment geometries
|
| 406 |
+
segments_gdf = rivers_proj[rivers_proj["HYRIV_ID"].isin(all_segment_ids)].copy()
|
| 407 |
+
if len(segments_gdf) == 0:
|
| 408 |
+
return gpd.GeoDataFrame(columns=["geometry", "direction", "HYRIV_ID", "matched_river_ids", "source_basin"])
|
| 409 |
+
|
| 410 |
+
# Create buffer for each segment
|
| 411 |
+
segments_gdf["buffer"] = segments_gdf.geometry.buffer(buffer_meters)
|
| 412 |
+
|
| 413 |
+
# Ensure polygons in EPSG:3035
|
| 414 |
+
if river_polygons.crs.to_epsg() != 3035:
|
| 415 |
+
river_polygons_proj = river_polygons.to_crs("EPSG:3035")
|
| 416 |
+
else:
|
| 417 |
+
river_polygons_proj = river_polygons
|
| 418 |
+
|
| 419 |
+
# Build spatial index for polygons
|
| 420 |
+
polygon_sindex = river_polygons_proj.sindex
|
| 421 |
+
|
| 422 |
+
clipped_results = []
|
| 423 |
+
processed = 0
|
| 424 |
+
|
| 425 |
+
for idx, seg_row in segments_gdf.iterrows():
|
| 426 |
+
seg_id = seg_row["HYRIV_ID"]
|
| 427 |
+
buffer_geom = seg_row["buffer"]
|
| 428 |
+
|
| 429 |
+
# Find candidate polygons
|
| 430 |
+
candidates_idx = list(polygon_sindex.intersection(buffer_geom.bounds))
|
| 431 |
+
if not candidates_idx:
|
| 432 |
+
continue
|
| 433 |
+
|
| 434 |
+
candidates = river_polygons_proj.iloc[candidates_idx]
|
| 435 |
+
intersecting = candidates[candidates.intersects(buffer_geom)]
|
| 436 |
+
|
| 437 |
+
for poly_idx, poly_row in intersecting.iterrows():
|
| 438 |
+
clipped = poly_row.geometry.intersection(buffer_geom)
|
| 439 |
+
if not clipped.is_empty:
|
| 440 |
+
clipped_results.append({
|
| 441 |
+
"geometry": clipped,
|
| 442 |
+
"direction": direction,
|
| 443 |
+
"HYRIV_ID": seg_id,
|
| 444 |
+
"matched_river_ids": [seg_id],
|
| 445 |
+
"source_basin": poly_row.get("source_basin"),
|
| 446 |
+
"OBJECT_ID": poly_row.get("OBJECT_ID"),
|
| 447 |
+
})
|
| 448 |
+
|
| 449 |
+
processed += 1
|
| 450 |
+
if processed % 10000 == 0:
|
| 451 |
+
log(f" Processed {processed:,}/{len(segments_gdf):,} segments...")
|
| 452 |
+
|
| 453 |
+
if not clipped_results:
|
| 454 |
+
return gpd.GeoDataFrame(columns=["geometry", "direction", "HYRIV_ID", "matched_river_ids", "source_basin"])
|
| 455 |
+
|
| 456 |
+
result = gpd.GeoDataFrame(clipped_results, crs="EPSG:3035")
|
| 457 |
+
log(f" Clipped {len(result):,} polygons")
|
| 458 |
+
return result.to_crs("EPSG:4326")
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def main(
|
| 462 |
+
facilities_path: Path,
|
| 463 |
+
rivers_path: Path,
|
| 464 |
+
polygons_path: Path,
|
| 465 |
+
output_facilities_path: Path,
|
| 466 |
+
output_segments_path: Path,
|
| 467 |
+
max_distance_m: float = 1000,
|
| 468 |
+
upstream_distance_km: float = 10,
|
| 469 |
+
downstream_distance_km: float = 10,
|
| 470 |
+
polygon_buffer_m: float = 600,
|
| 471 |
+
min_strahler_order: int = 1,
|
| 472 |
+
limit: int = None,
|
| 473 |
+
):
|
| 474 |
+
"""Main pipeline - polygons are stored per-facility as WKB."""
|
| 475 |
+
|
| 476 |
+
# Load data
|
| 477 |
+
facilities = load_facilities(facilities_path)
|
| 478 |
+
rivers = load_rivers(rivers_path, min_strahler_order)
|
| 479 |
+
river_polygons = load_river_polygons(polygons_path)
|
| 480 |
+
|
| 481 |
+
# Keep only needed columns
|
| 482 |
+
river_columns = ["HYRIV_ID", "NEXT_DOWN", "ORD_STRA", "DIS_AV_CMS", "LENGTH_KM", "UPLAND_SKM", "DIST_DN_KM"]
|
| 483 |
+
rivers = rivers[["geometry"] + river_columns]
|
| 484 |
+
|
| 485 |
+
# Build network
|
| 486 |
+
id_to_downstream, id_to_upstream, id_to_length = build_river_network(rivers)
|
| 487 |
+
|
| 488 |
+
# Project for distance calculations
|
| 489 |
+
log("Projecting data to EPSG:3035...")
|
| 490 |
+
facilities_proj = facilities.to_crs("EPSG:3035")
|
| 491 |
+
rivers_proj = rivers.to_crs("EPSG:3035")
|
| 492 |
+
|
| 493 |
+
# Build lookups
|
| 494 |
+
id_to_geom_proj, id_to_strahler, id_to_discharge = build_river_lookups(rivers, rivers_proj)
|
| 495 |
+
|
| 496 |
+
# Process facilities
|
| 497 |
+
if limit:
|
| 498 |
+
facilities = facilities.head(limit)
|
| 499 |
+
facilities_proj = facilities_proj.head(limit)
|
| 500 |
+
|
| 501 |
+
# Phase 1: Process all facilities (fast - just IDs)
|
| 502 |
+
results, all_upstream_ids, all_downstream_ids, facility_split_parts = process_facilities_fast(
|
| 503 |
+
facilities, facilities_proj, rivers_proj,
|
| 504 |
+
id_to_downstream, id_to_upstream, id_to_length,
|
| 505 |
+
id_to_geom_proj, id_to_strahler, id_to_discharge,
|
| 506 |
+
max_distance_m, upstream_distance_km, downstream_distance_km
|
| 507 |
+
)
|
| 508 |
+
|
| 509 |
+
if not results:
|
| 510 |
+
log("No facilities found near rivers!")
|
| 511 |
+
return None, None, None
|
| 512 |
+
|
| 513 |
+
# Phase 2: Build line geometries and clip polygons per facility
|
| 514 |
+
results = build_geometries_and_clip_polygons(
|
| 515 |
+
results, facility_split_parts, id_to_geom_proj,
|
| 516 |
+
river_polygons, polygon_buffer_m
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
# Create facilities GeoDataFrame
|
| 520 |
+
result_df = pd.DataFrame(results)
|
| 521 |
+
|
| 522 |
+
# Convert line and polygon geometries to WKB for parquet storage
|
| 523 |
+
from shapely import wkb
|
| 524 |
+
result_df["upstream_line_wkb"] = result_df["upstream_line_geom"].apply(
|
| 525 |
+
lambda g: g.wkb if g is not None else None
|
| 526 |
+
)
|
| 527 |
+
result_df["downstream_line_wkb"] = result_df["downstream_line_geom"].apply(
|
| 528 |
+
lambda g: g.wkb if g is not None else None
|
| 529 |
+
)
|
| 530 |
+
result_df["upstream_poly_wkb"] = result_df["upstream_poly_geom"].apply(
|
| 531 |
+
lambda g: g.wkb if g is not None else None
|
| 532 |
+
)
|
| 533 |
+
result_df["downstream_poly_wkb"] = result_df["downstream_poly_geom"].apply(
|
| 534 |
+
lambda g: g.wkb if g is not None else None
|
| 535 |
+
)
|
| 536 |
+
result_df = result_df.drop(columns=["upstream_line_geom", "downstream_line_geom", "upstream_poly_geom", "downstream_poly_geom"])
|
| 537 |
+
|
| 538 |
+
facilities_gdf = gpd.GeoDataFrame(
|
| 539 |
+
result_df,
|
| 540 |
+
geometry=gpd.points_from_xy(result_df["facility_lon"], result_df["facility_lat"]),
|
| 541 |
+
crs="EPSG:4326"
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
# Phase 3: Build segments dataset
|
| 545 |
+
log(f"\nBuilding segments dataset...")
|
| 546 |
+
|
| 547 |
+
all_segment_ids = all_upstream_ids | all_downstream_ids
|
| 548 |
+
segments_data = []
|
| 549 |
+
|
| 550 |
+
for seg_id in all_segment_ids:
|
| 551 |
+
seg_row = rivers[rivers["HYRIV_ID"] == seg_id]
|
| 552 |
+
if len(seg_row) == 0:
|
| 553 |
+
continue
|
| 554 |
+
seg_row = seg_row.iloc[0]
|
| 555 |
+
|
| 556 |
+
direction = []
|
| 557 |
+
if seg_id in all_upstream_ids:
|
| 558 |
+
direction.append("upstream")
|
| 559 |
+
if seg_id in all_downstream_ids:
|
| 560 |
+
direction.append("downstream")
|
| 561 |
+
|
| 562 |
+
for d in direction:
|
| 563 |
+
segments_data.append({
|
| 564 |
+
"HYRIV_ID": seg_id,
|
| 565 |
+
"direction": d,
|
| 566 |
+
"geometry": seg_row.geometry,
|
| 567 |
+
"ORD_STRA": seg_row["ORD_STRA"],
|
| 568 |
+
"DIS_AV_CMS": seg_row["DIS_AV_CMS"],
|
| 569 |
+
"LENGTH_KM": seg_row["LENGTH_KM"],
|
| 570 |
+
})
|
| 571 |
+
|
| 572 |
+
segments_gdf = gpd.GeoDataFrame(segments_data, crs=rivers.crs)
|
| 573 |
+
log(f" Created {len(segments_gdf):,} segment entries")
|
| 574 |
+
|
| 575 |
+
# Save outputs (polygons are now stored per-facility in facilities file as WKB)
|
| 576 |
+
log(f"\nSaving outputs...")
|
| 577 |
+
log(f" Facilities: {output_facilities_path}")
|
| 578 |
+
facilities_gdf.to_parquet(output_facilities_path)
|
| 579 |
+
|
| 580 |
+
log(f" Segments: {output_segments_path}")
|
| 581 |
+
segments_gdf.to_parquet(output_segments_path)
|
| 582 |
+
|
| 583 |
+
# Note: Polygons are now stored per-facility as upstream_poly_wkb and downstream_poly_wkb
|
| 584 |
+
# in the facilities file, so we don't create a separate polygons file
|
| 585 |
+
|
| 586 |
+
log("\nDone!")
|
| 587 |
+
log(f" Facilities with rivers: {len(facilities_gdf):,}")
|
| 588 |
+
if len(facilities_gdf) > 0:
|
| 589 |
+
log(f" Avg upstream parts: {facilities_gdf['n_upstream'].mean():.1f}")
|
| 590 |
+
log(f" Avg downstream parts: {facilities_gdf['n_downstream'].mean():.1f}")
|
| 591 |
+
|
| 592 |
+
return facilities_gdf, segments_gdf
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
if __name__ == "__main__":
|
| 596 |
+
base_dir = Path(__file__).resolve().parent
|
| 597 |
+
|
| 598 |
+
facilities_path = base_dir / "tabular" / "F2_4_Water_Releases_Facilities.csv"
|
| 599 |
+
rivers_path = base_dir.parent / "hydro-rivers-europe" / "HydroRIVERS_v10_eu.geoparquet"
|
| 600 |
+
polygons_path = base_dir.parent / "eu-hydro-master-skeleton" / "eu_hydro_master_skeleton_geoparquet" / "river_polygons"
|
| 601 |
+
|
| 602 |
+
output_facilities_path = base_dir / "river_data_facilities.geoparquet"
|
| 603 |
+
output_segments_path = base_dir / "river_data_segments.geoparquet"
|
| 604 |
+
|
| 605 |
+
result = main(
|
| 606 |
+
facilities_path=facilities_path,
|
| 607 |
+
rivers_path=rivers_path,
|
| 608 |
+
polygons_path=polygons_path,
|
| 609 |
+
output_facilities_path=output_facilities_path,
|
| 610 |
+
output_segments_path=output_segments_path,
|
| 611 |
+
max_distance_m=1000,
|
| 612 |
+
upstream_distance_km=10,
|
| 613 |
+
downst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+
Uses polygon WKB stored per facility for correct clipping.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import geopandas as gpd
|
| 7 |
+
import folium
|
| 8 |
+
from folium.plugins import AntPath, MarkerCluster
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from shapely import wkb
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def load_facilities(filepath: Path) -> gpd.GeoDataFrame:
|
| 14 |
+
"""Load facility data with upstream/downstream geometries."""
|
| 15 |
+
print(f"Loading facilities from {filepath}...")
|
| 16 |
+
gdf = gpd.read_parquet(filepath)
|
| 17 |
+
print(f"Loaded {len(gdf):,} facilities")
|
| 18 |
+
return gdf
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def load_segments(filepath: Path) -> gpd.GeoDataFrame:
|
| 22 |
+
"""Load river segments with direction info."""
|
| 23 |
+
print(f"Loading segments from {filepath}...")
|
| 24 |
+
gdf = gpd.read_parquet(filepath)
|
| 25 |
+
print(f"Loaded {len(gdf):,} segments ({gdf['direction'].value_counts().to_dict()})")
|
| 26 |
+
return gdf
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def get_facility_color(sector_code: int) -> str:
|
| 30 |
+
"""Color based on industry sector."""
|
| 31 |
+
colors = {
|
| 32 |
+
1: "#e41a1c", # Energy - red
|
| 33 |
+
2: "#377eb8", # Metals - blue
|
| 34 |
+
3: "#4daf4a", # Minerals - green
|
| 35 |
+
4: "#984ea3", # Chemical - purple
|
| 36 |
+
5: "#ff7f00", # Waste/wastewater - orange
|
| 37 |
+
6: "#a65628", # Paper - brown
|
| 38 |
+
7: "#f781bf", # Livestock - pink
|
| 39 |
+
8: "#999999", # Food - gray
|
| 40 |
+
9: "#66c2a5", # Other - teal
|
| 41 |
+
}
|
| 42 |
+
return colors.get(sector_code, "#999999")
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Upstream = green/teal tones (coming from nature)
|
| 46 |
+
# Downstream = red/orange tones (affected by pollution)
|
| 47 |
+
UPSTREAM_LINE_COLOR = "#2ca02c" # Green
|
| 48 |
+
DOWNSTREAM_LINE_COLOR = "#d62728" # Red
|
| 49 |
+
UPSTREAM_POLY_COLOR = "#98df8a" # Light green
|
| 50 |
+
DOWNSTREAM_POLY_COLOR = "#ff9896" # Light red
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def create_map(
|
| 54 |
+
facilities: gpd.GeoDataFrame,
|
| 55 |
+
segments: gpd.GeoDataFrame,
|
| 56 |
+
output_path: Path,
|
| 57 |
+
sample_facilities: int = 2000
|
| 58 |
+
) -> None:
|
| 59 |
+
"""Create interactive map with upstream/downstream visualization."""
|
| 60 |
+
print("Creating map...")
|
| 61 |
+
|
| 62 |
+
# Sample facilities for performance
|
| 63 |
+
if len(facilities) > sample_facilities:
|
| 64 |
+
print(f"Sampling {sample_facilities} facilities for performance...")
|
| 65 |
+
facilities = facilities.sample(sample_facilities, random_state=42)
|
| 66 |
+
|
| 67 |
+
# Get segment IDs for sampled facilities
|
| 68 |
+
upstream_ids = set()
|
| 69 |
+
downstream_ids = set()
|
| 70 |
+
for _, row in facilities.iterrows():
|
| 71 |
+
upstream_ids.update(row.get("upstream_segment_ids", []))
|
| 72 |
+
downstream_ids.update(row.get("downstream_segment_ids", []))
|
| 73 |
+
|
| 74 |
+
# Filter segments
|
| 75 |
+
upstream_segments = segments[(segments["direction"] == "upstream") & (segments["HYRIV_ID"].isin(upstream_ids))]
|
| 76 |
+
downstream_segments = segments[(segments["direction"] == "downstream") & (segments["HYRIV_ID"].isin(downstream_ids))]
|
| 77 |
+
|
| 78 |
+
print(f" Upstream segments: {len(upstream_segments):,}")
|
| 79 |
+
print(f" Downstream segments: {len(downstream_segments):,}")
|
| 80 |
+
|
| 81 |
+
# Calculate center
|
| 82 |
+
center_lat = facilities.geometry.y.mean()
|
| 83 |
+
center_lon = facilities.geometry.x.mean()
|
| 84 |
+
|
| 85 |
+
# Create map
|
| 86 |
+
m = folium.Map(
|
| 87 |
+
location=[center_lat, center_lon],
|
| 88 |
+
zoom_start=5,
|
| 89 |
+
tiles="CartoDB positron"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# Feature groups
|
| 93 |
+
upstream_poly_layer = folium.FeatureGroup(name="Upstream Polygons", show=True)
|
| 94 |
+
downstream_poly_layer = folium.FeatureGroup(name="Downstream Polygons", show=True)
|
| 95 |
+
upstream_line_layer = folium.FeatureGroup(name="Upstream Flow", show=True)
|
| 96 |
+
downstream_line_layer = folium.FeatureGroup(name="Downstream Flow", show=True)
|
| 97 |
+
|
| 98 |
+
# Add polygons from facility WKB
|
| 99 |
+
print("Adding polygons from facility data...")
|
| 100 |
+
poly_count_up = 0
|
| 101 |
+
poly_count_down = 0
|
| 102 |
+
|
| 103 |
+
for _, row in facilities.iterrows():
|
| 104 |
+
# Upstream polygon
|
| 105 |
+
if row.get("upstream_poly_wkb") is not None:
|
| 106 |
+
try:
|
| 107 |
+
geom = wkb.loads(row["upstream_poly_wkb"])
|
| 108 |
+
if geom is not None and not geom.is_empty:
|
| 109 |
+
if geom.geom_type == "Polygon":
|
| 110 |
+
polys = [geom]
|
| 111 |
+
elif geom.geom_type == "MultiPolygon":
|
| 112 |
+
polys = list(geom.geoms)
|
| 113 |
+
else:
|
| 114 |
+
polys = []
|
| 115 |
+
|
| 116 |
+
for poly in polys:
|
| 117 |
+
coords = [[c[1], c[0]] for c in poly.exterior.coords]
|
| 118 |
+
folium.Polygon(
|
| 119 |
+
locations=coords,
|
| 120 |
+
color=UPSTREAM_LINE_COLOR,
|
| 121 |
+
weight=1,
|
| 122 |
+
fill=True,
|
| 123 |
+
fill_color=UPSTREAM_POLY_COLOR,
|
| 124 |
+
fill_opacity=0.5,
|
| 125 |
+
).add_to(upstream_poly_layer)
|
| 126 |
+
poly_count_up += 1
|
| 127 |
+
except:
|
| 128 |
+
pass
|
| 129 |
+
|
| 130 |
+
# Downstream polygon
|
| 131 |
+
if row.get("downstream_poly_wkb") is not None:
|
| 132 |
+
try:
|
| 133 |
+
geom = wkb.loads(row["downstream_poly_wkb"])
|
| 134 |
+
if geom is not None and not geom.is_empty:
|
| 135 |
+
if geom.geom_type == "Polygon":
|
| 136 |
+
polys = [geom]
|
| 137 |
+
elif geom.geom_type == "MultiPolygon":
|
| 138 |
+
polys = list(geom.geoms)
|
| 139 |
+
else:
|
| 140 |
+
polys = []
|
| 141 |
+
|
| 142 |
+
for poly in polys:
|
| 143 |
+
coords = [[c[1], c[0]] for c in poly.exterior.coords]
|
| 144 |
+
folium.Polygon(
|
| 145 |
+
locations=coords,
|
| 146 |
+
color=DOWNSTREAM_LINE_COLOR,
|
| 147 |
+
weight=1,
|
| 148 |
+
fill=True,
|
| 149 |
+
fill_color=DOWNSTREAM_POLY_COLOR,
|
| 150 |
+
fill_opacity=0.5,
|
| 151 |
+
).add_to(downstream_poly_layer)
|
| 152 |
+
poly_count_down += 1
|
| 153 |
+
except:
|
| 154 |
+
pass
|
| 155 |
+
|
| 156 |
+
print(f" Added {poly_count_up:,} upstream polygons, {poly_count_down:,} downstream polygons")
|
| 157 |
+
|
| 158 |
+
# Add upstream segments with flow animation (reverse direction - going upstream)
|
| 159 |
+
print("Adding upstream segments...")
|
| 160 |
+
for idx, row in upstream_segments.iterrows():
|
| 161 |
+
geom = row.geometry
|
| 162 |
+
if geom is None or geom.is_empty:
|
| 163 |
+
continue
|
| 164 |
+
|
| 165 |
+
if geom.geom_type == "LineString":
|
| 166 |
+
coords = list(geom.coords)
|
| 167 |
+
elif geom.geom_type == "MultiLineString":
|
| 168 |
+
coords = []
|
| 169 |
+
for part in geom.geoms:
|
| 170 |
+
coords.extend(list(part.coords))
|
| 171 |
+
else:
|
| 172 |
+
continue
|
| 173 |
+
|
| 174 |
+
if not coords:
|
| 175 |
+
continue
|
| 176 |
+
|
| 177 |
+
# Reverse coords for upstream (animation goes against flow)
|
| 178 |
+
coords_latlon = [[c[1], c[0]] for c in reversed(coords)]
|
| 179 |
+
weight = max(1, row["ORD_STRA"] - 2)
|
| 180 |
+
|
| 181 |
+
popup_html = f"""
|
| 182 |
+
<b>Upstream Segment</b><br>
|
| 183 |
+
<b>ID:</b> {row['HYRIV_ID']}<br>
|
| 184 |
+
<b>Strahler:</b> {row['ORD_STRA']}<br>
|
| 185 |
+
<b>Discharge:</b> {row['DIS_AV_CMS']:.1f} m³/s
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
AntPath(
|
| 189 |
+
locations=coords_latlon,
|
| 190 |
+
weight=weight,
|
| 191 |
+
color=UPSTREAM_LINE_COLOR,
|
| 192 |
+
pulse_color="#ffffff",
|
| 193 |
+
delay=800,
|
| 194 |
+
dash_array=[10, 20],
|
| 195 |
+
popup=folium.Popup(popup_html, max_width=250)
|
| 196 |
+
).add_to(upstream_line_layer)
|
| 197 |
+
|
| 198 |
+
# Add downstream segments with flow animation
|
| 199 |
+
print("Adding downstream segments...")
|
| 200 |
+
for idx, row in downstream_segments.iterrows():
|
| 201 |
+
geom = row.geometry
|
| 202 |
+
if geom is None or geom.is_empty:
|
| 203 |
+
continue
|
| 204 |
+
|
| 205 |
+
if geom.geom_type == "LineString":
|
| 206 |
+
coords = list(geom.coords)
|
| 207 |
+
elif geom.geom_type == "MultiLineString":
|
| 208 |
+
coords = []
|
| 209 |
+
for part in geom.geoms:
|
| 210 |
+
coords.extend(list(part.coords))
|
| 211 |
+
else:
|
| 212 |
+
continue
|
| 213 |
+
|
| 214 |
+
if not coords:
|
| 215 |
+
continue
|
| 216 |
+
|
| 217 |
+
coords_latlon = [[c[1], c[0]] for c in coords]
|
| 218 |
+
weight = max(1, row["ORD_STRA"] - 2)
|
| 219 |
+
|
| 220 |
+
popup_html = f"""
|
| 221 |
+
<b>Downstream Segment</b><br>
|
| 222 |
+
<b>ID:</b> {row['HYRIV_ID']}<br>
|
| 223 |
+
<b>Strahler:</b> {row['ORD_STRA']}<br>
|
| 224 |
+
<b>Discharge:</b> {row['DIS_AV_CMS']:.1f} m³/s
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
AntPath(
|
| 228 |
+
locations=coords_latlon,
|
| 229 |
+
weight=weight,
|
| 230 |
+
color=DOWNSTREAM_LINE_COLOR,
|
| 231 |
+
pulse_color="#ffffff",
|
| 232 |
+
delay=800,
|
| 233 |
+
dash_array=[10, 20],
|
| 234 |
+
popup=folium.Popup(popup_html, max_width=250)
|
| 235 |
+
).add_to(downstream_line_layer)
|
| 236 |
+
|
| 237 |
+
# Add facilities
|
| 238 |
+
print("Adding facilities...")
|
| 239 |
+
marker_cluster = MarkerCluster(name="Facilities").add_to(m)
|
| 240 |
+
|
| 241 |
+
for _, row in facilities.iterrows():
|
| 242 |
+
color = get_facility_color(row.get("EPRTR_SectorCode", 0))
|
| 243 |
+
|
| 244 |
+
popup_html = f"""
|
| 245 |
+
<b>{row.get('facilityName', 'Unknown')}</b><br>
|
| 246 |
+
<b>City:</b> {row.get('city', 'N/A')}<br>
|
| 247 |
+
<b>Sector:</b> {row.get('EPRTR_SectorName', 'N/A')}<br>
|
| 248 |
+
<b>Pollutant:</b> {row.get('Pollutant', 'N/A')}<br>
|
| 249 |
+
<b>Upstream segments:</b> {row.get('n_upstream', 0)}<br>
|
| 250 |
+
<b>Downstream segments:</b> {row.get('n_downstream', 0)}
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
folium.CircleMarker(
|
| 254 |
+
location=[row.geometry.y, row.geometry.x],
|
| 255 |
+
radius=6,
|
| 256 |
+
color=color,
|
| 257 |
+
fill=True,
|
| 258 |
+
fill_color=color,
|
| 259 |
+
fill_opacity=0.7,
|
| 260 |
+
popup=folium.Popup(popup_html, max_width=300)
|
| 261 |
+
).add_to(marker_cluster)
|
| 262 |
+
|
| 263 |
+
# Add layers
|
| 264 |
+
upstream_poly_layer.add_to(m)
|
| 265 |
+
downstream_poly_layer.add_to(m)
|
| 266 |
+
upstream_line_layer.add_to(m)
|
| 267 |
+
downstream_line_layer.add_to(m)
|
| 268 |
+
folium.LayerControl().add_to(m)
|
| 269 |
+
|
| 270 |
+
# Legend
|
| 271 |
+
legend_html = """
|
| 272 |
+
<div style="position: fixed; bottom: 50px; left: 50px; z-index: 1000;
|
| 273 |
+
background-color: white; padding: 15px; border-radius: 8px;
|
| 274 |
+
border: 2px solid #333; font-size: 12px; max-width: 200px;
|
| 275 |
+
box-shadow: 0 2px 6px rgba(0,0,0,0.3);">
|
| 276 |
+
<b>River Flow Analysis</b><br><br>
|
| 277 |
+
<b style="color: #2ca02c;">━━━ Upstream</b><br>
|
| 278 |
+
Source water (green)<br><br>
|
| 279 |
+
<b style="color: #d62728;">━━━ Downstream</b><br>
|
| 280 |
+
Potentially affected (red)<br><br>
|
| 281 |
+
<b>Facilities:</b><br>
|
| 282 |
+
Colored by industry sector<br>
|
| 283 |
+
<small>Click for details</small>
|
| 284 |
+
</div>
|
| 285 |
+
"""
|
| 286 |
+
m.get_root().html.add_child(folium.Element(legend_html))
|
| 287 |
+
|
| 288 |
+
# Save
|
| 289 |
+
print(f"Saving map to {output_path}...")
|
| 290 |
+
m.save(str(output_path))
|
| 291 |
+
print(f"Done!")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def main():
|
| 295 |
+
base_dir = Path(__file__).resolve().parent
|
| 296 |
+
|
| 297 |
+
# Paths
|
| 298 |
+
facilities_path = base_dir / "river_data_facilities.geoparquet"
|
| 299 |
+
segments_path = base_dir / "river_data_segments.geoparquet"
|
| 300 |
+
output_path = base_dir / "facilities_rivers_map.html"
|
| 301 |
+
|
| 302 |
+
# Load data
|
| 303 |
+
facilities = load_facilities(facilities_path)
|
| 304 |
+
segments = load_segments(segments_path)
|
| 305 |
+
|
| 306 |
+
# Create map
|
| 307 |
+
create_map(facilities, segments, output_path, sample_facilities=2000)
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
if __name__ == "__main__":
|
| 311 |
+
main()
|
visualize_single_facility.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Visualize a single facility with its upstream/downstream river split.
|
| 3 |
+
Uses pre-generated river_data files with polygon WKB stored per facility.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import geopandas as gpd
|
| 7 |
+
import folium
|
| 8 |
+
from folium.plugins import AntPath
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import sys
|
| 11 |
+
from shapely import wkb
|
| 12 |
+
|
| 13 |
+
UPSTREAM_COLOR = "#2ca02c" # Green
|
| 14 |
+
DOWNSTREAM_COLOR = "#d62728" # Red
|
| 15 |
+
UPSTREAM_POLY_COLOR = "#98df8a"
|
| 16 |
+
DOWNSTREAM_POLY_COLOR = "#ff9896"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def create_facility_map(facility_name: str, output_path: Path):
|
| 20 |
+
"""Create a map focused on a single facility showing upstream/downstream split."""
|
| 21 |
+
|
| 22 |
+
base_dir = Path(__file__).resolve().parent
|
| 23 |
+
|
| 24 |
+
# Load pre-generated facility data
|
| 25 |
+
print(f"Loading data...")
|
| 26 |
+
facilities_path = base_dir / "river_data_facilities.geoparquet"
|
| 27 |
+
facilities = gpd.read_parquet(facilities_path)
|
| 28 |
+
print(f"Loaded {len(facilities):,} facilities")
|
| 29 |
+
|
| 30 |
+
# Find facility
|
| 31 |
+
facility_matches = facilities[facilities['facilityName'].str.contains(facility_name, case=False, na=False)]
|
| 32 |
+
if len(facility_matches) == 0:
|
| 33 |
+
print(f"Facility '{facility_name}' not found!")
|
| 34 |
+
return
|
| 35 |
+
|
| 36 |
+
facility = facility_matches.iloc[0]
|
| 37 |
+
print(f"Found: {facility['facilityName']} in {facility['city']}")
|
| 38 |
+
print(f" Closest river: {facility['closest_river_id']} ({facility['distance_to_river_m']:.0f}m away)")
|
| 39 |
+
print(f" Upstream: {facility['n_upstream']} parts")
|
| 40 |
+
print(f" Downstream: {facility['n_downstream']} parts")
|
| 41 |
+
|
| 42 |
+
# Parse geometries from WKB
|
| 43 |
+
upstream_line_geom = None
|
| 44 |
+
downstream_line_geom = None
|
| 45 |
+
upstream_poly_geom = None
|
| 46 |
+
downstream_poly_geom = None
|
| 47 |
+
|
| 48 |
+
if 'upstream_line_wkb' in facility.index and facility['upstream_line_wkb'] is not None:
|
| 49 |
+
upstream_line_geom = wkb.loads(facility['upstream_line_wkb'])
|
| 50 |
+
if 'downstream_line_wkb' in facility.index and facility['downstream_line_wkb'] is not None:
|
| 51 |
+
downstream_line_geom = wkb.loads(facility['downstream_line_wkb'])
|
| 52 |
+
if 'upstream_poly_wkb' in facility.index and facility['upstream_poly_wkb'] is not None:
|
| 53 |
+
upstream_poly_geom = wkb.loads(facility['upstream_poly_wkb'])
|
| 54 |
+
if 'downstream_poly_wkb' in facility.index and facility['downstream_poly_wkb'] is not None:
|
| 55 |
+
downstream_poly_geom = wkb.loads(facility['downstream_poly_wkb'])
|
| 56 |
+
|
| 57 |
+
# Create map
|
| 58 |
+
m = folium.Map(
|
| 59 |
+
location=[facility.geometry.y, facility.geometry.x],
|
| 60 |
+
zoom_start=13,
|
| 61 |
+
tiles="CartoDB positron"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
# Add upstream polygons
|
| 65 |
+
if upstream_poly_geom is not None:
|
| 66 |
+
if upstream_poly_geom.geom_type == "Polygon":
|
| 67 |
+
polys = [upstream_poly_geom]
|
| 68 |
+
elif upstream_poly_geom.geom_type == "MultiPolygon":
|
| 69 |
+
polys = list(upstream_poly_geom.geoms)
|
| 70 |
+
else:
|
| 71 |
+
polys = []
|
| 72 |
+
|
| 73 |
+
for poly in polys:
|
| 74 |
+
coords = [[c[1], c[0]] for c in poly.exterior.coords]
|
| 75 |
+
folium.Polygon(
|
| 76 |
+
locations=coords,
|
| 77 |
+
color=UPSTREAM_COLOR,
|
| 78 |
+
weight=1,
|
| 79 |
+
fill=True,
|
| 80 |
+
fill_color=UPSTREAM_POLY_COLOR,
|
| 81 |
+
fill_opacity=0.4,
|
| 82 |
+
popup="Upstream water surface"
|
| 83 |
+
).add_to(m)
|
| 84 |
+
|
| 85 |
+
# Add downstream polygons
|
| 86 |
+
if downstream_poly_geom is not None:
|
| 87 |
+
if downstream_poly_geom.geom_type == "Polygon":
|
| 88 |
+
polys = [downstream_poly_geom]
|
| 89 |
+
elif downstream_poly_geom.geom_type == "MultiPolygon":
|
| 90 |
+
polys = list(downstream_poly_geom.geoms)
|
| 91 |
+
else:
|
| 92 |
+
polys = []
|
| 93 |
+
|
| 94 |
+
for poly in polys:
|
| 95 |
+
coords = [[c[1], c[0]] for c in poly.exterior.coords]
|
| 96 |
+
folium.Polygon(
|
| 97 |
+
locations=coords,
|
| 98 |
+
color=DOWNSTREAM_COLOR,
|
| 99 |
+
weight=1,
|
| 100 |
+
fill=True,
|
| 101 |
+
fill_color=DOWNSTREAM_POLY_COLOR,
|
| 102 |
+
fill_opacity=0.4,
|
| 103 |
+
popup="Downstream water surface"
|
| 104 |
+
).add_to(m)
|
| 105 |
+
|
| 106 |
+
# Add upstream line (animated going upstream = reversed coords)
|
| 107 |
+
if upstream_line_geom is not None:
|
| 108 |
+
if upstream_line_geom.geom_type == "LineString":
|
| 109 |
+
lines = [upstream_line_geom]
|
| 110 |
+
elif upstream_line_geom.geom_type == "MultiLineString":
|
| 111 |
+
lines = list(upstream_line_geom.geoms)
|
| 112 |
+
else:
|
| 113 |
+
lines = []
|
| 114 |
+
|
| 115 |
+
for line in lines:
|
| 116 |
+
coords = [[c[1], c[0]] for c in reversed(list(line.coords))]
|
| 117 |
+
AntPath(
|
| 118 |
+
locations=coords,
|
| 119 |
+
weight=4,
|
| 120 |
+
color=UPSTREAM_COLOR,
|
| 121 |
+
pulse_color="#ffffff",
|
| 122 |
+
delay=600,
|
| 123 |
+
dash_array=[10, 20],
|
| 124 |
+
popup="Upstream (source water)"
|
| 125 |
+
).add_to(m)
|
| 126 |
+
|
| 127 |
+
# Add downstream line (animated going downstream)
|
| 128 |
+
if downstream_line_geom is not None:
|
| 129 |
+
if downstream_line_geom.geom_type == "LineString":
|
| 130 |
+
lines = [downstream_line_geom]
|
| 131 |
+
elif downstream_line_geom.geom_type == "MultiLineString":
|
| 132 |
+
lines = list(downstream_line_geom.geoms)
|
| 133 |
+
else:
|
| 134 |
+
lines = []
|
| 135 |
+
|
| 136 |
+
for line in lines:
|
| 137 |
+
coords = [[c[1], c[0]] for c in line.coords]
|
| 138 |
+
AntPath(
|
| 139 |
+
locations=coords,
|
| 140 |
+
weight=4,
|
| 141 |
+
color=DOWNSTREAM_COLOR,
|
| 142 |
+
pulse_color="#ffffff",
|
| 143 |
+
delay=600,
|
| 144 |
+
dash_array=[10, 20],
|
| 145 |
+
popup="Downstream (affected area)"
|
| 146 |
+
).add_to(m)
|
| 147 |
+
|
| 148 |
+
# Add facility marker
|
| 149 |
+
folium.Marker(
|
| 150 |
+
location=[facility.geometry.y, facility.geometry.x],
|
| 151 |
+
popup=f"""
|
| 152 |
+
<b>{facility['facilityName']}</b><br>
|
| 153 |
+
{facility.get('city', '')}, {facility.get('countryName', '')}<br>
|
| 154 |
+
<hr>
|
| 155 |
+
<b>Closest river:</b> {facility['closest_river_id']}<br>
|
| 156 |
+
<b>Distance:</b> {facility['distance_to_river_m']:.0f}m<br>
|
| 157 |
+
<b>River order:</b> {facility['river_strahler']}<br>
|
| 158 |
+
<b>Discharge:</b> {facility['river_discharge']:.1f} m³/s<br>
|
| 159 |
+
<hr>
|
| 160 |
+
<b style="color:{UPSTREAM_COLOR}">Upstream:</b> {facility['n_upstream']} parts<br>
|
| 161 |
+
<b style="color:{DOWNSTREAM_COLOR}">Downstream:</b> {facility['n_downstream']} parts
|
| 162 |
+
""",
|
| 163 |
+
icon=folium.Icon(color='orange', icon='industry', prefix='fa')
|
| 164 |
+
).add_to(m)
|
| 165 |
+
|
| 166 |
+
# Legend
|
| 167 |
+
legend_html = f"""
|
| 168 |
+
<div style="position: fixed; bottom: 50px; left: 50px; z-index: 1000;
|
| 169 |
+
background-color: white; padding: 15px; border-radius: 8px;
|
| 170 |
+
border: 2px solid #333; font-size: 12px; max-width: 220px;">
|
| 171 |
+
<b>{facility['facilityName']}</b><br>
|
| 172 |
+
<small>{facility.get('city', '')}</small><br><br>
|
| 173 |
+
<b style="color: {UPSTREAM_COLOR};">━━━ Upstream ({facility['n_upstream']})</b><br>
|
| 174 |
+
Source water flowing toward facility<br><br>
|
| 175 |
+
<b style="color: {DOWNSTREAM_COLOR};">━━━ Downstream ({facility['n_downstream']})</b><br>
|
| 176 |
+
Water flowing away (potentially affected)<br><br>
|
| 177 |
+
<small>River split at closest point to facility</small>
|
| 178 |
+
</div>
|
| 179 |
+
"""
|
| 180 |
+
m.get_root().html.add_child(folium.Element(legend_html))
|
| 181 |
+
|
| 182 |
+
# Save
|
| 183 |
+
print(f"Saving to {output_path}...")
|
| 184 |
+
m.save(str(output_path))
|
| 185 |
+
print("Done!")
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
facility_name = sys.argv[1] if len(sys.argv) > 1 else "PRECHEZA"
|
| 190 |
+
output_path = Path(__file__).resolve().parent / "facility_map.html"
|
| 191 |
+
create_facility_map(facility_name, output_path)
|