Repository navigation
Expand file tree
/
Copy pathmap.py
More file actions
189 lines (169 loc) · 6.99 KB
/
Copy pathmap.py
File metadata and controls
189 lines (169 loc) · 6.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import math
import snowflake.connector
import structlog
from fastapi import APIRouter
from app.core.config import settings
logger = structlog.get_logger()
router = APIRouter()
def _generate_dynamic_risk_polygon(points, buffer=0.012):
if not points:
return []
avg_lon = sum(p[0] for p in points) / len(points)
avg_lat = sum(p[1] for p in points) / len(points)
outer_points = []
for lon, lat in points:
for angle_deg in range(0, 360, 45):
rad = math.radians(angle_deg)
outer_points.append((lon + buffer * math.cos(rad), lat + buffer * math.sin(rad)))
sorted_pts = sorted(outer_points, key=lambda p: math.atan2(p[1] - avg_lat, p[0] - avg_lon))
unique_pts = []
for p in sorted_pts:
if not unique_pts or (
abs(p[0] - unique_pts[-1][0]) > 0.003 or abs(p[1] - unique_pts[-1][1]) > 0.003
):
unique_pts.append([round(p[0], 5), round(p[1], 5)])
if unique_pts:
unique_pts.append(unique_pts[0])
return [unique_pts]
def _fetch_snowflake_map_features():
try:
conn = snowflake.connector.connect(
user=settings.SNOWFLAKE_USER,
password=settings.SNOWFLAKE_PASSWORD,
account=settings.SNOWFLAKE_ACCOUNT,
warehouse=settings.SNOWFLAKE_WAREHOUSE,
database=settings.SNOWFLAKE_DATABASE,
schema=settings.SNOWFLAKE_SCHEMA,
role=settings.SNOWFLAKE_ROLE,
)
cursor = conn.cursor()
features = []
# 1. Fetch Dynamic Risk Zone Polygons based on live high-risk sensors & barangay GPS locations
cursor.execute("""
SELECT b.barangay, b.latitude, b.longitude, r.water_level
FROM barangays b
JOIN river_sensors r ON b.barangay = r.barangay
WHERE r.water_level >= 6.0
""")
high_risk_rows = cursor.fetchall()
if high_risk_rows:
# Cluster by proximity (main city cluster vs outer barangays)
main_cluster_pts = [
(float(r[2]), float(r[1])) for r in high_risk_rows if float(r[1]) < 7.0
]
outer_cluster_pts = [
(float(r[2]), float(r[1])) for r in high_risk_rows if float(r[1]) >= 7.0
]
if main_cluster_pts:
poly_coords = _generate_dynamic_risk_polygon(main_cluster_pts, buffer=0.015)
if poly_coords and len(poly_coords[0]) >= 4:
features.append(
{
"type": "Feature",
"properties": {
"type": "risk_zone",
"name": "Tumaga / Central River Basin Active Flood Zone",
"risk_level": "High",
},
"geometry": {"type": "Polygon", "coordinates": poly_coords},
}
)
if outer_cluster_pts:
poly_coords_outer = _generate_dynamic_risk_polygon(outer_cluster_pts, buffer=0.012)
if poly_coords_outer and len(poly_coords_outer[0]) >= 4:
features.append(
{
"type": "Feature",
"properties": {
"type": "risk_zone",
"name": "North Zamboanga River Spillway Risk Zone",
"risk_level": "High",
},
"geometry": {
"type": "Polygon",
"coordinates": poly_coords_outer,
},
}
)
# 2. Fetch Evacuation Centers directly from Snowflake DB
cursor.execute("""
SELECT name, capacity, current_occupancy, latitude, longitude
FROM evacuation_centers
""")
for row in cursor.fetchall():
name, cap, occ, lat, lon = row
if lat is not None and lon is not None:
features.append(
{
"type": "Feature",
"properties": {
"type": "evacuation_center",
"name": name,
"capacity": cap,
"occupancy": occ,
},
"geometry": {
"type": "Point",
"coordinates": [float(lon), float(lat)],
},
}
)
# 3. Fetch Hospitals directly from Snowflake DB
cursor.execute("""
SELECT hospital, beds_available, latitude, longitude
FROM hospitals
""")
for row in cursor.fetchall():
h_name, beds, lat, lon = row
if lat is not None and lon is not None:
features.append(
{
"type": "Feature",
"properties": {
"type": "hospital",
"name": h_name,
"beds": beds,
},
"geometry": {
"type": "Point",
"coordinates": [float(lon), float(lat)],
},
}
)
# 4. Fetch River Sensors directly from Snowflake DB
cursor.execute("""
SELECT sensor_id, water_level, latitude, longitude
FROM river_sensors
""")
for row in cursor.fetchall():
s_id, level, lat, lon = row
if lat is not None and lon is not None:
status = "Critical" if level >= 8.0 else ("Warning" if level >= 6.0 else "Normal")
features.append(
{
"type": "Feature",
"properties": {
"type": "sensor",
"name": s_id,
"level": f"{level}m",
"status": status,
},
"geometry": {
"type": "Point",
"coordinates": [float(lon), float(lat)],
},
}
)
cursor.close()
conn.close()
return {"type": "FeatureCollection", "features": features}
except Exception as e:
logger.error("failed_to_fetch_snowflake_map_data", error=str(e))
return {"type": "FeatureCollection", "features": []}
@router.get("/data")
def get_map_data():
"""Returns dynamic GeoJSON map data fetched live from active Snowflake database."""
db_features = _fetch_snowflake_map_features()
if db_features and "features" in db_features:
return db_features
return {"type": "FeatureCollection", "features": []}