feat: Initial CBPOA commit — 武汉儿童呼吸疾病风险评估系统

Context: Build a spatial risk assessment system correlating air quality
data with children's respiratory disease incidence across Wuhan.

Approach: FastAPI backend serving PostGIS spatial queries, React
frontend with Deck.gl maps, and a PyTorch SpatialTemporalGCN pipeline
for multi-day (1d/3d/7d) risk prediction.

Changes:
- backend/ — FastAPI API with auth (JWT), alerts, risk analysis,
  geocoded case data, grid statistics, and report endpoints
- frontend/ — React dashboard with interactive risk maps, alert
  monitoring, district comparison charts, and timeline player
- models/ — SpatialTemporalGCN model with trained weights and ONNX
  export for inference
- scripts/ — ETL pipeline for weather + medical data, grid generation,
  feature engineering, training, and daily inference
- deploy/ — Docker Compose configs for backend, frontend, and MLflow
- docs/ — API docs, deployment guide, user guide, and code review

Impact: Enables spatial risk visualization, alert monitoring, and
ML-driven health risk forecasting for environmental health teams.
This commit is contained in:
2026-06-05 02:13:49 +08:00
commit fc468464b2
117 changed files with 18282 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""Shared utility modules for CBPOA backend."""

View File

@@ -0,0 +1,50 @@
"""
Date utilities: finding latest dates from GeoJSON files, parsing date strings.
"""
import glob
import re
from pathlib import Path
from fastapi import HTTPException
from config import DATA_DIR, DATE_FORMAT_GEOJSON
def get_latest_date() -> str:
"""Get latest available date from GeoJSON files in DATA_DIR."""
pattern = str(DATA_DIR / "risk_*.geojson")
files = glob.glob(pattern)
if not files:
raise HTTPException(status_code=500, detail="No risk data files found")
dates = []
for f in files:
match = re.search(r"risk_(\d{8})\.geojson", f)
if match:
dates.append(match.group(1))
if not dates:
raise HTTPException(status_code=500, detail="No valid risk data files found")
return max(dates)
def get_available_dates(days: int = 30) -> list[str]:
"""Get list of available dates, most recent first."""
pattern = str(DATA_DIR / "risk_*.geojson")
files = glob.glob(pattern)
dates: list[str] = []
for f in files:
match = re.search(r"risk_(\d{8})\.geojson", f)
if match:
dates.append(match.group(1))
dates.sort(reverse=True)
return dates[:days]
def validate_date_format(date: str) -> bool:
"""Check if date string matches YYYYMMDD format."""
import re
return bool(re.compile(r"^\d{8}$").match(date))

43
backend/utils/geo.py Normal file
View File

@@ -0,0 +1,43 @@
"""
Geographic utilities: point-in-polygon testing via ray casting.
"""
def point_in_polygon(lat: float, lon: float, polygon_coords: list) -> bool:
"""Check if a point is inside a polygon (supports Polygon and MultiPolygon)."""
if not polygon_coords:
return False
# MultiPolygon: check each polygon
if isinstance(polygon_coords[0], list) and isinstance(polygon_coords[0][0], list):
for polygon in polygon_coords:
if polygon and isinstance(polygon[0], list):
ring = polygon[0] if isinstance(polygon[0][0], list) else polygon
if point_in_ring(lat, lon, ring):
return True
return False
# Single Polygon: use first ring (outer boundary)
ring = polygon_coords[0] if isinstance(polygon_coords[0], list) else polygon_coords
return point_in_ring(lat, lon, ring)
def point_in_ring(lat: float, lon: float, ring: list) -> bool:
"""Ray casting algorithm for point-in-ring test."""
n = len(ring)
inside = False
x, y = lon, lat
p1x, p1y = ring[0]
for i in range(1, n + 1):
p2x, p2y = ring[i % n]
if y > min(p1y, p2y):
if y <= max(p1y, p2y):
if x <= max(p1x, p2x):
xinters = (y - p1y) * (p2x - p1x) / (p2y - p1y) if p1y != p2y else p1x
if p1x == p2x or x <= xinters:
inside = not inside
p1x, p1y = p2x, p2y
return inside

53
backend/utils/geojson.py Normal file
View File

@@ -0,0 +1,53 @@
"""
GeoJSON file parsing utilities.
"""
import json
from pathlib import Path
from typing import Any
from config import WUHAN_BOUNDARY_PATH
from utils.risk import risk_value_to_level
def parse_geojson_file(filepath: Path) -> list[dict[str, Any]]:
"""Parse GeoJSON file and extract grid data with standard fields."""
with open(filepath, "r", encoding="utf-8") as f:
geojson = json.load(f)
grids: list[dict[str, Any]] = []
for feature in geojson.get("features", []):
props = feature.get("properties", {})
coords = feature.get("geometry", {}).get("coordinates", [0, 0])
risk_1d = props.get("risk_1d", 0)
grids.append({
"grid_id": str(props.get("node_id", "")),
"latitude": props.get("lat", coords[1] if len(coords) > 1 else 0),
"longitude": props.get("lon", coords[0] if len(coords) > 0 else 0),
"risk_value": risk_1d,
"risk_3d": props.get("risk_3d", 0),
"risk_7d": props.get("risk_7d", 0),
"risk_level": risk_value_to_level(risk_1d),
})
return grids
def load_districts() -> list[dict[str, Any]]:
"""Load Wuhan district boundaries from GeoJSON."""
if not WUHAN_BOUNDARY_PATH.exists():
return []
with open(WUHAN_BOUNDARY_PATH, "r", encoding="utf-8") as f:
geojson = json.load(f)
districts = []
for feature in geojson.get("features", []):
props = feature.get("properties", {})
districts.append({
"name": props.get("name", ""),
"adcode": props.get("adcode", ""),
"coordinates": feature.get("geometry", {}).get("coordinates", []),
})
return districts

56
backend/utils/risk.py Normal file
View File

@@ -0,0 +1,56 @@
"""
Risk level classification and trend calculation utilities.
"""
from typing import Literal
from config import (
RISK_HIGH,
RISK_MEDIUM_HIGH,
RISK_MEDIUM,
RISK_MEDIUM_LOW,
TREND_SLOPE_THRESHOLD,
)
def risk_value_to_level(risk_value: float) -> str:
"""Convert risk value (0-1) to risk level string."""
if risk_value >= RISK_HIGH:
return "high"
elif risk_value >= RISK_MEDIUM_HIGH:
return "medium_high"
elif risk_value >= RISK_MEDIUM:
return "medium"
elif risk_value >= RISK_MEDIUM_LOW:
return "medium_low"
else:
return "low"
def calculate_trend(values: list[float]) -> Literal["up", "down", "stable"]:
"""Calculate trend direction from a series of values using linear regression slope."""
if len(values) < 2:
return "stable"
n = len(values)
x_mean = (n - 1) / 2
y_mean = sum(values) / n
numerator = sum((i - x_mean) * (values[i] - y_mean) for i in range(n))
denominator = sum((i - x_mean) ** 2 for i in range(n))
if denominator == 0:
return "stable"
slope = numerator / denominator
if y_mean == 0:
return "stable"
relative_slope = slope / y_mean
if relative_slope > TREND_SLOPE_THRESHOLD:
return "up"
elif relative_slope < -TREND_SLOPE_THRESHOLD:
return "down"
else:
return "stable"