-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.py
More file actions
1574 lines (1454 loc) · 59.4 KB
/
Copy pathdashboard.py
File metadata and controls
1574 lines (1454 loc) · 59.4 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import json
import math
import os
import ee
import altair as alt
import folium
from folium import MacroElement
from folium.template import Template
import pandas as pd
import streamlit as st
from datetime import datetime
from streamlit_folium import st_folium
from boomerang_alerts import (
SEVERITY_LABEL,
alerts_to_dataframe_rows,
build_alerts,
fetch_marine_sea_level_hourly,
fetch_open_meteo_archive_precipitation,
fetch_open_meteo_precip_forecast,
forecast_vs_history_context,
peak_precipitation_day_72h,
)
from gee_layers import (
_s2_classified_median,
classify_landcover_from_s2,
compute_flood_proxy_stats,
demo_zone_names,
extra_categorical_masks,
gmw_mangrove_mask_2020,
inundacion_buffer_meters,
inundacion_mask,
zone_inundacion_ranking,
zones_geojson_for_map,
)
from zone_notifications_demo import (
citizen_flood_cards_pair,
format_day_en,
human_depth_phrase_cm,
water_depth_cm_from_forecast_mm,
)
def format_day_es(iso_date: str | None) -> str:
"""Etiqueta corta en español: «28 Mar»."""
if not iso_date:
return "—"
try:
from datetime import datetime as _dt
d = _dt.strptime(str(iso_date)[:10], "%Y-%m-%d")
except ValueError:
return str(iso_date)
meses = ("Ene","Feb","Mar","Abr","May","Jun","Jul","Ago","Sep","Oct","Nov","Dic")
return f"{d.day} {meses[d.month - 1]}"
st.set_page_config(page_title="Boomerang — Greater Guayaquil", layout="wide", page_icon="🌊")
st.markdown(
"""
<style>
/* Mapa a casi todo el ancho, centrado (layout wide + menos márgenes laterales) */
.main .block-container {
padding-top: 1.2rem;
max-width: min(1920px, 100%);
padding-left: clamp(0.75rem, 2vw, 1.5rem);
padding-right: clamp(0.75rem, 2vw, 1.5rem);
}
h1 { letter-spacing: -0.02em; }
/* Sidebar alineada a tema oscuro (evita franja blanca con “Dark” del navegador/Streamlit) */
[data-testid="stSidebar"] {
background: linear-gradient(185deg, #1a1d24 0%, #0e1117 100%) !important;
border-right: 1px solid rgba(255, 255, 255, 0.08);
}
[data-testid="stSidebar"] [data-testid="stMarkdownContainer"] p,
[data-testid="stSidebar"] [data-testid="stMarkdownContainer"] h3 {
color: #e6edf3 !important;
}
[data-testid="stSidebar"] .stCaption { color: #9da7b3 !important; }
</style>
""",
unsafe_allow_html=True,
)
@st.cache_resource
def init_ee():
import pathlib
project = os.environ.get("EE_PROJECT_ID", "august-tower-470819-s6")
# Sin secrets.toml, cualquier acceso a st.secrets (in, .get, etc.) dispara _parse() y
# StreamlitSecretNotFoundError. Solo leer ee_token si existe el archivo.
ee_token = None
if st.secrets.load_if_toml_exists():
ee_token = st.secrets.get("ee_token")
if ee_token:
creds_dir = pathlib.Path.home() / ".config" / "earthengine"
creds_dir.mkdir(parents=True, exist_ok=True)
with open(creds_dir / "credentials", "w") as f:
json.dump(dict(ee_token), f)
ee.Initialize(project=project)
init_ee()
roi = ee.Geometry.Rectangle([-80.10, -2.30, -79.85, -1.98])
# Folium: [[south, west], [north, east]] — mismo rectángulo que clip en GEE
ROI_FIT_BOUNDS = [[-2.30, -80.10], [-1.98, -79.85]]
ROI_CENTER = [
(ROI_FIT_BOUNDS[0][0] + ROI_FIT_BOUNDS[1][0]) / 2,
(ROI_FIT_BOUNDS[0][1] + ROI_FIT_BOUNDS[1][1]) / 2,
]
# streamlit-folium no aplica bien fit_bounds del HTML; hay que pasar zoom/center al componente.
# Con poco alto en px, el zoom máximo que encaja la latitud del ROI es ~11 → rectángulo “pequeño”.
# ~940 px de alto permite zoom 12 sin recortar el ROI en vertical (Web Mercator aprox.).
MAIN_MAP_HEIGHT_PX = 940
# Ancho de referencia para calcular zoom/center (iframe suele ser ~ancho del contenedor en layout wide).
MAIN_MAP_WIDTH_REF_PX = 1500.0
# Mapa base por defecto: imágenes satélite (Esri World Imagery). Sin API key; atribución en `attr`.
DEFAULT_BASEMAP_TILES = (
"https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
)
DEFAULT_BASEMAP_ATTR = "Esri — World Imagery"
def _zoom_center_for_roi_panel(
width_px: float,
height_px: float,
) -> tuple[tuple[float, float], int]:
"""
Zoom y centro para que el bbox del ROI llene el panel (misma idea que Leaflet fitBounds).
Devuelve zoom entero y centro (lat, lon).
"""
south, west = ROI_FIT_BOUNDS[0]
north, east = ROI_FIT_BOUNDS[1]
lat_c = (south + north) / 2.0
lon_c = (west + east) / 2.0
def lat_y(lat_deg: float) -> float:
# Proyección esférica Web Mercator (Y en fracción de mundo 0..1)
s = math.sin(math.radians(lat_deg))
return 0.5 - math.log((1 + s) / (1 - s)) / (4 * math.pi)
y_min = lat_y(min(south, north))
y_max = lat_y(max(south, north))
y_frac = abs(y_max - y_min)
x_min = (west + 180.0) / 360.0
x_max = (east + 180.0) / 360.0
x_frac = abs(x_max - x_min)
if x_frac > 0.5:
x_frac = 1.0 - x_frac
WORLD_DIM = 256.0
ZOOM_MAX = 18
best_z = 10
for z in range(ZOOM_MAX, 4, -1):
scale = 2**z
px_per_world_y = height_px / (y_frac * WORLD_DIM * scale) if y_frac > 1e-9 else float("inf")
px_per_world_x = width_px / (x_frac * WORLD_DIM * scale) if x_frac > 1e-9 else float("inf")
if px_per_world_y >= 1.0 and px_per_world_x >= 1.0:
best_z = z
break
return (lat_c, lon_c), best_z
# Flags de capas (un mapa; visibilidad en el iframe vía JS — sin rerun de Streamlit).
LAYER_FLAG_LABELS: dict[str, str] = {
"rgb": "Sentinel-2 RGB",
"classified": "S2 land cover (thresholds)",
"ndvi": "NDVI",
"gmw": "GMW 2020 mangrove",
"prot": "Protected (coastal strip)",
"exp": "Exposed (urban)",
"vuln": "Vulnerable",
"marea": "Water spread (tide proxy)",
"inun": "Flood proxy",
"bosque": "Dry forest (proxy)",
"ind": "Industrial (proxy)",
"cont": "High NDCI water (proxy)",
"zones": "Neighbourhoods (demo)",
}
# Texto en el panel del mapa: nombre corto + ayuda (atributo title) para el cliente final.
LAYER_PANEL_UI: dict[str, dict[str, str]] = {
"classified": {
"label": "Land use",
"help": "Green = vegetation/mangrove, red = built-up, blue = water, gold = soil/farmland. See legend.",
},
"ndvi": {
"label": "Greenness (plants)",
"help": "Red to green: sparse to dense cover. NDVI is a technical index, not a crop map.",
},
"gmw": {
"label": "Mangrove (global map)",
"help": "Where GMW mapped mangrove in 2020. Reference layer, not an official inventory.",
},
"prot": {
"label": "Vegetated coast",
"help": "Strip near the water with plant cover (more buffered against surge).",
},
"exp": {
"label": "City facing the water",
"help": "Built-up coast with less natural mangrove buffer.",
},
"vuln": {
"label": "Medium-risk coast",
"help": "Between protected and highly exposed (illustrative).",
},
"marea": {
"label": "Rising water (simulation)",
"help": "Blue: wider water if tide rises in this test. Not a real tide forecast.",
},
"inun": {
"label": "Flooding (simulation)",
"help": "Red: model flood mask for the chosen scenario. Not a substitute for official hazard maps.",
},
"bosque": {
"label": "Dry forest",
"help": "Drier vegetation (not mangrove). Approximate indicator.",
},
"ind": {
"label": "Industrial area",
"help": "Built or industrial fabric (satellite estimate).",
},
"cont": {
"label": "Water quality (indicator)",
"help": "Purple tones: more material in the water (visual proxy, not lab data).",
},
"zones": {
"label": "Neighbourhoods (demo)",
"help": "Rough boxes for demo alerts; not official boundaries.",
},
}
# Leyendas por capa: solo se muestran en el panel si esa capa está activa (layer_ids = boom_id).
MAP_LEGEND_GROUPS: list[dict] = [
{
"layer_ids": ["classified"],
"title": "Land use — what each colour means",
"rows": [
{"hex": "#228B22", "text": "Green: wet vegetation / mangrove (estimate)"},
{"hex": "#FF4500", "text": "Red: urban or built-up"},
{"hex": "#4169E1", "text": "Blue: open water"},
{"hex": "#DAA520", "text": "Gold: bare soil or farmland"},
],
},
{
"layer_ids": ["ndvi"],
"title": "Greenness (low to high)",
"rows": [
{"hex": "#FF0000", "text": "Red: sparse vegetation"},
{"hex": "#FFFF00", "text": "Yellow: medium cover"},
{"hex": "#006400", "text": "Dark green: dense vegetation"},
],
},
{
"layer_ids": ["gmw"],
"title": "Mangrove (global 2020 reference)",
"rows": [
{"hex": "#00FF88", "text": "Light green: mangrove per GMW (science reference)"},
],
},
{
"layer_ids": ["prot"],
"title": "Vegetated coast",
"rows": [
{"hex": "#00FF00", "text": "Green: coast with more plant cover"},
],
},
{
"layer_ids": ["exp"],
"title": "City facing the water",
"rows": [
{"hex": "#FF0000", "text": "Red: urban very close to water"},
],
},
{
"layer_ids": ["vuln"],
"title": "Medium-risk coast",
"rows": [
{"hex": "#FFA500", "text": "Orange: in-between situation"},
],
},
{
"layer_ids": ["marea"],
"title": "Rising water (simulation)",
"rows": [
{"hex": "#1E90FF", "text": "Blue: wider water with the simulated tide"},
],
},
{
"layer_ids": ["inun"],
"title": "Flooding (simulation)",
"rows": [
{"hex": "#DC143C", "text": "Red: flood proxy for the chosen scenario"},
],
},
{
"layer_ids": ["bosque"],
"title": "Dry forest",
"rows": [
{"hex": "#CD853F", "text": "Brown: dry vegetation (not mangrove)"},
],
},
{
"layer_ids": ["ind"],
"title": "Industrial zone",
"rows": [
{"hex": "#708090", "text": "Grey: industrial or mixed fabric"},
],
},
{
"layer_ids": ["cont"],
"title": "Water quality (indicator)",
"rows": [
{"hex": "#DA70D6", "text": "Purple: more material in the water (visual proxy)"},
],
},
{
"layer_ids": ["zones"],
"title": "Neighbourhoods (demo)",
"rows": [
{"hex": "#3388ff", "text": "Outline: approximate area (pick the name in the selector below the map)"},
],
},
]
OVERLAY_FLAG_KEYS = [k for k in LAYER_FLAG_LABELS if k != "rgb"]
# Rejilla de escenarios precalculados (marea × lluvia) para cambiar teselas en el iframe sin nueva petición GEE.
SCENARIO_GRID_VALUES = [0, 25, 50, 75, 100]
# Etiquetas cualitativas (misma rejilla 0–100; proxy morfológico, no mm ni marea oficial INOCAR).
TIDE_SCENARIO_LABELS = [
"Low tide — little spread from water",
"Low to mid tide",
"Mid tide",
"High tide",
"High water / spring — maximum spread",
]
RAIN_SCENARIO_LABELS = [
"No heavy showers / isolated drizzle",
"Light rain (~5–15 mm/day)",
"Moderate rain (~15–40 mm/day)",
"Heavy rain (~40–80 mm/day)",
"Very heavy rain / local storm (≥ ~80 mm/day)",
]
@st.cache_resource
def get_tile_url(_image, vis_params):
map_id = _image.getMapId(vis_params)
return map_id['tile_fetcher'].url_format
@st.cache_resource
def load_tiles():
s2 = (ee.ImageCollection('COPERNICUS/S2_SR_HARMONIZED')
.filterBounds(roi).filterDate('2023-06-01', '2024-12-31')
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE', 40))
.median().clip(roi))
ndvi = s2.normalizedDifference(['B8', 'B4']).rename('NDVI')
mndwi = s2.normalizedDifference(['B3', 'B11']).rename('MNDWI')
ndbi = s2.normalizedDifference(['B11', 'B8']).rename('NDBI')
classified = classify_landcover_from_s2(s2, roi)
water_mask = classified.eq(3)
coastal_buffer = water_mask.focal_max(radius=500, units='meters')
coastal_zone = coastal_buffer.And(water_mask.Not())
coastal_classified = classified.updateMask(coastal_zone)
tiles = {
'rgb': get_tile_url(s2, {'bands': ['B4','B3','B2'], 'min': 0, 'max': 3000}),
'classified': get_tile_url(classified, {'min': 1, 'max': 4, 'palette': ['228B22','FF4500','4169E1','DAA520']}),
'ndvi': get_tile_url(ndvi, {'min': -0.1, 'max': 0.8, 'palette': ['red','yellow','green','darkgreen']}),
'protected': get_tile_url(coastal_classified.eq(1).selfMask(), {'palette': ['00FF00']}),
'exposed': get_tile_url(coastal_classified.eq(2).selfMask(), {'palette': ['FF0000']}),
'vulnerable': get_tile_url(coastal_classified.eq(4).selfMask(), {'palette': ['FFA500']}),
}
try:
gmw = gmw_mangrove_mask_2020(roi)
tiles['gmw_2020'] = get_tile_url(gmw, {'palette': ['00FF88']})
except Exception:
tiles['gmw_2020'] = None
try:
xm = extra_categorical_masks(s2, classified, roi)
tiles['bosque_seco'] = get_tile_url(xm['bosque_seco'], {'palette': ['CD853F']})
tiles['industrial'] = get_tile_url(xm['industrial'], {'palette': ['708090']})
tiles['contaminacion_agua'] = get_tile_url(xm['contaminacion_agua'], {'palette': ['DA70D6']})
except Exception:
tiles['bosque_seco'] = None
tiles['industrial'] = None
tiles['contaminacion_agua'] = None
return tiles
tiles = load_tiles()
# Opacidad “encendida” por capa tesela (misma lógica que antes; tope 0.42 salvo RGB).
def _overlay_tile_opacity_on(flag: str) -> float:
cap = 0.42
raw = {
"classified": 0.92,
"ndvi": 0.88,
"gmw": 0.68,
"prot": 0.95,
"exp": 0.95,
"vuln": 0.95,
"marea": 0.45,
"inun": 0.78,
"bosque": 0.78,
"ind": 0.72,
"cont": 0.7,
}.get(flag, cap)
return min(float(raw), cap)
def _overlay_tile_url(flag: str, tiles_static: dict, sim: dict) -> str | None:
if flag == "classified":
return tiles_static.get("classified")
if flag == "ndvi":
return tiles_static.get("ndvi")
if flag == "gmw":
return tiles_static.get("gmw_2020")
if flag == "prot":
return tiles_static.get("protected")
if flag == "exp":
return tiles_static.get("exposed")
if flag == "vuln":
return tiles_static.get("vulnerable")
if flag == "marea":
return sim.get("marea")
if flag == "inun":
return sim.get("inundacion")
if flag == "bosque":
return tiles_static.get("bosque_seco")
if flag == "ind":
return tiles_static.get("industrial")
if flag == "cont":
return tiles_static.get("contaminacion_agua")
return None
class _BoomerangLeafletControls(MacroElement):
"""
streamlit-folium solo ejecuta JS en el bundle MacroElement; <script> suelto en HTML no corre en el iframe.
"""
_template = Template(
"""
{% macro script(this, kwargs) %}
{{ this.js_body|safe }}
{% endmacro %}
"""
)
def __init__(self, js_body: str):
super().__init__()
self._name = "BoomerangLeafletControls"
self.js_body = js_body
def _scenario_labels_for_js(
scenario_grid: list[int],
tide_labels: list[str] | None,
rain_labels: list[str] | None,
) -> tuple[list[str], list[str]]:
"""Misma longitud que ``scenario_grid``; si faltan etiquetas, se usan porcentajes."""
n = len(scenario_grid)
t = tide_labels if tide_labels and len(tide_labels) == n else None
r = rain_labels if rain_labels and len(rain_labels) == n else None
t_out = t if t else [f"{g} %" for g in scenario_grid]
r_out = r if r else [f"{g} %" for g in scenario_grid]
return t_out, r_out
def _inject_leaflet_map_scripts(
m: folium.Map,
panel_specs: list[dict],
scenario_cache: dict[str, dict],
scenario_grid: list[int],
initial_scenario_t: int,
initial_scenario_r: int,
legend_groups: list[dict] | None = None,
scenario_tide_labels: list[str] | None = None,
scenario_rain_labels: list[str] | None = None,
) -> None:
"""
Casillas + escenario en JS (opacidad / setUrl). id del mapa en streamlit-folium: map_div.
localStorage del escenario incluye `py` = clave del run Python para alinear con la barra lateral.
"""
legends = legend_groups if legend_groups is not None else MAP_LEGEND_GROUPS
legends_json = json.dumps(legends, ensure_ascii=False)
cfg_json = json.dumps({"specs": panel_specs}, ensure_ascii=False)
sc_json = json.dumps(scenario_cache, ensure_ascii=False)
grid_json = json.dumps(scenario_grid)
_tl, _rl = _scenario_labels_for_js(
scenario_grid, scenario_tide_labels, scenario_rain_labels
)
grid_tide_labels_json = json.dumps(_tl, ensure_ascii=False)
grid_rain_labels_json = json.dumps(_rl, ensure_ascii=False)
it = int(initial_scenario_t)
ir = int(initial_scenario_r)
js_body = f"""
(function() {{
var CONFIG = {cfg_json};
var LEGENDS = {legends_json};
var SCENARIO_CACHE = {sc_json};
var GRID = {grid_json};
var GRID_TIDE_LABELS = {grid_tide_labels_json};
var GRID_RAIN_LABELS = {grid_rain_labels_json};
var MAP_DIV_ID = 'map_div';
var LS_VIS = 'boomerang_layer_vis';
var LS_SCN = 'boomerang_scenario_tr';
var INIT_T = {it};
var INIT_R = {ir};
var PYTHON_SCENARIO = INIT_T + '_' + INIT_R;
var BOOM_BOOT_TRIES = 0;
var BOOM_BOOT_MAX = 240;
function getMap() {{
if (typeof L === 'undefined') return null;
try {{
if (typeof map_div !== 'undefined' && map_div && map_div.whenReady && map_div.getContainer)
return map_div;
}} catch (e0) {{}}
try {{
if (typeof window !== 'undefined' && window.map_div && window.map_div.whenReady)
return window.map_div;
}} catch (e1) {{}}
var el = document.getElementById(MAP_DIV_ID);
if (!el) {{
var qs = document.querySelectorAll('.folium-map');
if (qs && qs.length) el = qs[0];
}}
if (!el) return null;
if (el._leaflet_id != null && L.Map && L.Map._instances && L.Map._instances[el._leaflet_id])
return L.Map._instances[el._leaflet_id];
var lc = el.querySelector ? el.querySelector('.leaflet-container') : null;
if (lc && lc._leaflet_id != null && L.Map && L.Map._instances && L.Map._instances[lc._leaflet_id])
return L.Map._instances[lc._leaflet_id];
if (L.Map && L.Map._instances) {{
var inst = L.Map._instances;
for (var k in inst) {{
if (!Object.prototype.hasOwnProperty.call(inst, k)) continue;
var mm = inst[k];
if (!mm || !mm.getContainer) continue;
var c = mm.getContainer();
if (c === el || (el.contains && el.contains(c))) return mm;
}}
}}
return null;
}}
function boot() {{
BOOM_BOOT_TRIES += 1;
var map = getMap();
if (!map) {{
if (BOOM_BOOT_TRIES < BOOM_BOOT_MAX) setTimeout(boot, 50);
return;
}}
map.whenReady(function() {{
var zfix = document.createElement('style');
zfix.textContent = '#map_div .leaflet-control-container,' +
'#map_div .leaflet-top.leaflet-left,' +
'#map_div .leaflet-top.leaflet-right,' +
'#map_div .leaflet-bottom.leaflet-right {{ z-index: 10002 !important; }}' +
'#map_div .boomerang-layer-panel input[type=checkbox] {{ width:18px;height:18px;flex-shrink:0;margin-top:2px; }}';
document.head.appendChild(zfix);
var byId = {{}};
map.eachLayer(function(layer) {{
var o = layer.options || {{}};
var bid = o.boomId || o.boom_id;
if (bid) byId[bid] = layer;
}});
var stored = {{}};
try {{ stored = JSON.parse(localStorage.getItem(LS_VIS) || '{{}}'); }} catch (e) {{}}
var vis = {{}};
var boomRefreshLegends = function() {{}};
var boomLegendSetOpen = function() {{}};
function anyLayerOn() {{
var on = false;
CONFIG.specs.forEach(function(ss) {{ if (vis[ss.boom_id]) on = true; }});
return on;
}}
function applyOne(id, on) {{
var spec = CONFIG.specs.find(function(s) {{ return s.boom_id === id; }});
var layer = byId[id];
if (!spec || !layer) return;
if (spec.kind === 'tile') {{
layer.setOpacity(on ? spec.opacity_on : 0);
}} else if (spec.kind === 'geojson') {{
if (on) {{ if (!map.hasLayer(layer)) map.addLayer(layer); }}
else {{ if (map.hasLayer(layer)) map.removeLayer(layer); }}
}}
}}
CONFIG.specs.forEach(function(s) {{
vis[s.boom_id] = Object.prototype.hasOwnProperty.call(stored, s.boom_id)
? !!stored[s.boom_id] : !!s.initial;
applyOne(s.boom_id, vis[s.boom_id]);
}});
function saveVis() {{
try {{ localStorage.setItem(LS_VIS, JSON.stringify(vis)); }} catch (e) {{}}
}}
var panel = L.control({{position: 'topleft'}});
panel.onAdd = function() {{
var div = L.DomUtil.create('div', 'boomerang-layer-panel');
div.style.cssText = 'background:rgba(255,255,255,0.96);padding:12px 14px;border-radius:10px;max-width:320px;max-height:min(85vh,640px);overflow:auto;font:14px/1.4 system-ui,Segoe UI,sans-serif;box-shadow:0 2px 12px rgba(0,0,0,0.25);color:#111;z-index:1000001;position:relative;';
L.DomEvent.disableClickPropagation(div);
L.DomEvent.disableScrollPropagation(div);
var h = document.createElement('div');
h.textContent = 'What to show on the map';
h.style.cssText = 'font-weight:600;margin-bottom:6px;font-size:16px;';
div.appendChild(h);
var hint = document.createElement('div');
hint.textContent = 'Turn layers on or off. Satellite imagery stays underneath; the page does not reload.';
hint.style.cssText = 'font-size:12px;color:#444;margin-bottom:8px;line-height:1.4;';
div.appendChild(hint);
var checkboxes = [];
CONFIG.specs.forEach(function(s) {{
var row = document.createElement('label');
row.style.cssText = 'display:flex;align-items:flex-start;gap:10px;margin:6px 0;cursor:pointer;';
if (s.help) row.title = s.help;
var cb = document.createElement('input');
cb.type = 'checkbox';
cb.setAttribute('data-boom', s.boom_id);
if (s.help) cb.title = s.help;
cb.checked = !!vis[s.boom_id];
cb.addEventListener('change', function() {{
vis[s.boom_id] = cb.checked;
applyOne(s.boom_id, vis[s.boom_id]);
saveVis();
boomRefreshLegends();
if (cb.checked) {{
boomLegendSetOpen(true);
}} else {{
if (!anyLayerOn()) boomLegendSetOpen(false);
}}
}});
checkboxes.push(cb);
var span = document.createElement('span');
span.textContent = s.label;
if (s.help) span.title = s.help;
span.style.cssText = 'line-height:1.4;font-size:14px;';
row.appendChild(cb);
row.appendChild(span);
div.appendChild(row);
}});
var rowBtn = document.createElement('div');
rowBtn.style.cssText = 'display:flex;gap:8px;margin-top:10px;padding-top:8px;border-top:1px solid #ddd;';
function syncChecks() {{
checkboxes.forEach(function(cb) {{
var id = cb.getAttribute('data-boom');
cb.checked = !!vis[id];
}});
}}
function setAll(on) {{
CONFIG.specs.forEach(function(s) {{
vis[s.boom_id] = on;
applyOne(s.boom_id, on);
}});
saveVis();
syncChecks();
boomRefreshLegends();
if (on) boomLegendSetOpen(true);
else boomLegendSetOpen(false);
}}
var b1 = document.createElement('button');
b1.type = 'button';
b1.textContent = 'Show all';
b1.title = 'Turn on every layer in the list.';
b1.style.cssText = 'flex:1;padding:7px 10px;font-size:13px;border-radius:6px;border:1px solid #ccc;background:#f4f4f4;cursor:pointer;';
b1.onclick = function() {{ setAll(true); }};
var b2 = document.createElement('button');
b2.type = 'button';
b2.textContent = 'Hide all';
b2.title = 'Turn off every layer in the list.';
b2.style.cssText = b1.style.cssText;
b2.onclick = function() {{ setAll(false); }};
rowBtn.appendChild(b1);
rowBtn.appendChild(b2);
div.appendChild(rowBtn);
var legNote = document.createElement('div');
legNote.textContent = 'Legends (bottom right) open when you turn a layer on; use the button to close.';
legNote.style.cssText = 'font-size:11px;color:#666;margin-top:10px;padding-top:8px;border-top:1px solid #eee;line-height:1.4;';
div.appendChild(legNote);
return div;
}};
panel.addTo(map);
var legendToggle = L.control({{position: 'bottomright'}});
legendToggle.onAdd = function() {{
var wrap = L.DomUtil.create('div', 'boomerang-legend-toggle');
wrap.style.cssText = 'display:flex;flex-direction:column;align-items:flex-end;gap:8px;margin:0 8px 10px 0;';
L.DomEvent.disableClickPropagation(wrap);
L.DomEvent.disableScrollPropagation(wrap);
var panelEl = document.createElement('div');
panelEl.style.cssText = 'display:none;background:rgba(255,255,255,0.97);padding:12px 14px;border-radius:10px;max-width:320px;max-height:min(55vh,460px);overflow-y:auto;font:14px/1.4 system-ui,Segoe UI,sans-serif;box-shadow:0 2px 14px rgba(0,0,0,0.28);color:#111;text-align:left;';
var legH = document.createElement('div');
legH.textContent = 'Leyendas (solo capas activas)';
legH.style.cssText = 'font-weight:600;font-size:15px;margin-bottom:6px;color:#222;';
panelEl.appendChild(legH);
var legHint = document.createElement('div');
legHint.textContent = 'Se muestran solo las leyendas de las casillas marcadas a la izquierda.';
legHint.style.cssText = 'font-size:12px;color:#666;margin-bottom:8px;line-height:1.4;';
panelEl.appendChild(legHint);
var legendBody = document.createElement('div');
legendBody.className = 'boomerang-legend-body';
panelEl.appendChild(legendBody);
function fillLegendBody() {{
legendBody.innerHTML = '';
var any = false;
LEGENDS.forEach(function(g) {{
var ids = g.layer_ids || [];
if (!ids.length) return;
var show = ids.some(function(id) {{ return !!vis[id]; }});
if (!show) return;
any = true;
var gt = document.createElement('div');
gt.style.cssText = 'font-size:13px;font-weight:600;color:#333;margin:8px 0 4px;';
gt.textContent = g.title;
legendBody.appendChild(gt);
g.rows.forEach(function(r) {{
var lr = document.createElement('div');
lr.style.cssText = 'display:flex;align-items:flex-start;gap:8px;margin:4px 0;font-size:12px;line-height:1.4;';
var sw = document.createElement('span');
sw.style.cssText = 'width:14px;height:14px;border-radius:3px;border:1px solid #bbb;flex-shrink:0;margin-top:3px;background:' + (r.hex || '#ccc');
var tx = document.createElement('span');
tx.textContent = r.text;
tx.style.cssText = 'color:#444;';
lr.appendChild(sw);
lr.appendChild(tx);
legendBody.appendChild(lr);
}});
}});
if (!any) {{
var empty = document.createElement('div');
empty.textContent = 'No layer is on. Check at least one layer on the left to see colours here.';
empty.style.cssText = 'font-size:12px;color:#666;line-height:1.4;';
legendBody.appendChild(empty);
}}
}}
boomRefreshLegends = fillLegendBody;
fillLegendBody();
var btn = document.createElement('button');
btn.type = 'button';
btn.textContent = 'Legends';
btn.title = 'Open or close the colour guide (for active layers)';
btn.style.cssText = 'padding:10px 18px;font-size:14px;font-weight:600;border-radius:8px;border:1px solid #bbb;background:linear-gradient(180deg,#fff,#f0f0f0);box-shadow:0 2px 10px rgba(0,0,0,0.22);cursor:pointer;color:#222;';
var open = false;
function syncLegendPanelUi() {{
panelEl.style.display = open ? 'block' : 'none';
btn.textContent = open ? 'Close legends' : 'Legends';
btn.title = open ? 'Hide the legend panel' : 'See colours for active layers';
}}
boomLegendSetOpen = function(wantOpen) {{
open = !!wantOpen;
if (open) fillLegendBody();
syncLegendPanelUi();
}};
btn.onclick = function() {{
open = !open;
if (open) fillLegendBody();
syncLegendPanelUi();
}};
if (anyLayerOn()) {{
open = true;
fillLegendBody();
syncLegendPanelUi();
}}
wrap.appendChild(panelEl);
wrap.appendChild(btn);
return wrap;
}};
legendToggle.addTo(map);
if (Object.keys(SCENARIO_CACHE).length === 0) return;
var scT = INIT_T, scR = INIT_R;
try {{
var sc = JSON.parse(localStorage.getItem(LS_SCN) || 'null');
if (sc && sc.py === PYTHON_SCENARIO) {{
if (sc.t !== undefined && GRID.indexOf(Number(sc.t)) >= 0) scT = Number(sc.t);
if (sc.r !== undefined && GRID.indexOf(Number(sc.r)) >= 0) scR = Number(sc.r);
}}
}} catch (e2) {{}}
function applyScenario(kt, kr) {{
var key = kt + '_' + kr;
var pack = SCENARIO_CACHE[key];
if (!pack) return;
var lr = byId['rgb'], lm = byId['marea'], li = byId['inun'];
if (lr && pack.rgb && typeof lr.setUrl === 'function') lr.setUrl(pack.rgb);
if (lm && pack.marea && typeof lm.setUrl === 'function') lm.setUrl(pack.marea);
if (li && pack.inundacion && typeof li.setUrl === 'function') li.setUrl(pack.inundacion);
try {{
localStorage.setItem(LS_SCN, JSON.stringify({{t: kt, r: kr, py: PYTHON_SCENARIO}}));
}} catch (e3) {{}}
}}
applyScenario(scT, scR);
}});
}}
if (document.readyState === 'loading')
document.addEventListener('DOMContentLoaded', boot);
else
boot();
}})();
"""
_BoomerangLeafletControls(js_body).add_to(m)
def make_map(
sim: dict,
tiles_static: dict,
geojson_fc=None,
fit_bounds=None,
lock_roi: bool = True,
apply_fit_bounds: bool = True,
scenario_cache: dict[str, dict] | None = None,
scenario_grid: list[int] | None = None,
initial_scenario_t: int = 0,
initial_scenario_r: int = 0,
scenario_tide_labels: list[str] | None = None,
scenario_rain_labels: list[str] | None = None,
show_demo_zones_on_map: bool = False,
):
"""
Todas las teselas GEE con boom_id; visibilidad y escenario en JS (opacidad / setUrl).
``show_demo_zones_on_map``: polígonos de barrios (GeoJSON); por defecto ocultos en satélite.
"""
map_kw: dict = {
'location': ROI_CENTER,
'zoom_start': 12,
'tiles': DEFAULT_BASEMAP_TILES,
'attr': DEFAULT_BASEMAP_ATTR,
'control_scale': True,
}
if lock_roi:
map_kw['max_bounds'] = True
map_kw['min_lat'] = ROI_FIT_BOUNDS[0][0]
map_kw['max_lat'] = ROI_FIT_BOUNDS[1][0]
map_kw['min_lon'] = ROI_FIT_BOUNDS[0][1]
map_kw['max_lon'] = ROI_FIT_BOUNDS[1][1]
m = folium.Map(**map_kw)
panel_specs: list[dict] = []
# Sentinel-2 RGB (siempre presente; no entra en el panel de casillas)
folium.TileLayer(
tiles=sim["rgb"],
attr='Google Earth Engine',
name=LAYER_FLAG_LABELS["rgb"],
overlay=True,
opacity=0.48,
control=False,
boom_id='rgb',
).add_to(m)
for flag in OVERLAY_FLAG_KEYS:
if flag == "zones":
continue
url = _overlay_tile_url(flag, tiles_static, sim)
if not url:
continue
op_on = _overlay_tile_opacity_on(flag)
folium.TileLayer(
tiles=url,
attr='Google Earth Engine',
name=LAYER_FLAG_LABELS.get(flag, flag),
overlay=True,
opacity=op_on,
control=False,
boom_id=flag,
).add_to(m)
ui = LAYER_PANEL_UI.get(flag, {})
panel_specs.append(
{
"boom_id": flag,
"label": ui.get("label", LAYER_FLAG_LABELS.get(flag, flag)),
"help": ui.get("help", ""),
"kind": "tile",
"opacity_on": op_on,
"initial": True,
}
)
if show_demo_zones_on_map and geojson_fc and geojson_fc.get("features"):
# Sin GeoJsonTooltip: el JS extra + iframe de streamlit-folium a veces rompe el visor.
# El nombre del barrio está en el selector debajo del mapa.
gj = folium.GeoJson(
geojson_fc,
name="Neighbourhood reference (demo)",
style_function=lambda _feat: {
"fillColor": "#3388ff",
"color": "#1a5fb4",
"weight": 1.2,
"fillOpacity": 0.06,
},
boom_id="zones",
control=False,
)
gj.add_to(m)
zui = LAYER_PANEL_UI.get("zones", {})
panel_specs.append(
{
"boom_id": "zones",
"label": zui.get("label", "Neighbourhoods (demo)"),
"help": zui.get("help", ""),
"kind": "geojson",
"opacity_on": 1.0,
"initial": True,
}
)
if lock_roi:
folium.Rectangle(
bounds=ROI_FIT_BOUNDS,
color='#e8e8e8',
weight=2,
fill=False,
).add_to(m)
fb = fit_bounds if fit_bounds is not None else (ROI_FIT_BOUNDS if lock_roi else None)
if apply_fit_bounds and fb is not None:
m.fit_bounds(fb, padding=(2, 2), max_zoom=18)
_inject_leaflet_map_scripts(
m,
panel_specs,
scenario_cache=scenario_cache or {},
scenario_grid=scenario_grid or SCENARIO_GRID_VALUES,
initial_scenario_t=initial_scenario_t,
initial_scenario_r=initial_scenario_r,
scenario_tide_labels=scenario_tide_labels,
scenario_rain_labels=scenario_rain_labels,
)
return m
@st.cache_data(ttl=3600, show_spinner="Running simulation in Earth Engine…")
def tide_simulation_tiles(tide_pct: float, rain_stress_pct: float):
"""
Proxy visual alineado con `inundacion_mask` en gee_layers: marea + estrés de lluvia.
tide_pct y rain_stress_pct 0–100 amplían el buffer desde la máscara de agua.
"""
s2, classified = _s2_classified_median(roi)
flood = inundacion_mask(classified, tide_pct, rain_stress_pct)
water = classified.eq(3)
buffer_m = inundacion_buffer_meters(tide_pct, rain_stress_pct)
expanded = water.focal_max(radius=buffer_m, units='meters')
return {
'rgb': get_tile_url(s2, {'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 3000}),
'marea': get_tile_url(expanded.selfMask(), {'palette': ['1E90FF']}),
'inundacion': get_tile_url(flood, {'palette': ['DC143C']}),
}
@st.cache_data(ttl=3600, show_spinner="Precomputing scenario grid (GEE)…")
def precache_scenario_tiles_grid(grid_tuple: tuple[int, ...]) -> dict[str, dict]:
"""Todas las combinaciones (marea × lluvia) en la rejilla; cache para el mapa y métricas."""
out: dict[str, dict] = {}
for t in grid_tuple:
for r in grid_tuple:
out[f"{t}_{r}"] = tide_simulation_tiles(float(t), float(r))
return out
def _snap_to_grid(v: float, grid: list[int]) -> int:
return min(grid, key=lambda g: abs(float(g) - float(v)))
@st.cache_data(ttl=3600, show_spinner="Loading neighbourhoods (Earth Engine)…")
def zones_geojson_cached():
return zones_geojson_for_map(roi)
@st.cache_data(ttl=3600, show_spinner="Computing zone ranking (GEE)…")
def zone_ranking_cached(tide_pct: float, rain_stress_pct: float):
return zone_inundacion_ranking(roi, tide_pct, rain_stress_pct)
@st.cache_data(ttl=1800, show_spinner="Syncing forecast, sea level, and alert engine…")
def alert_bundle_cached():
daily, err = fetch_open_meteo_precip_forecast()
marine, merr = fetch_marine_sea_level_hourly()
alerts, metrics = build_alerts(daily, err, marine, merr)
return alerts, metrics
@st.cache_data(ttl=3600, show_spinner="Computing flood proxy % (GEE)…")
def flood_proxy_stats_cached(tide_pct: float, rain_stress_pct: float):
return compute_flood_proxy_stats(roi, tide_pct=tide_pct, rain_stress_pct=rain_stress_pct)