Spaces:
Sleeping
Sleeping
File size: 65,177 Bytes
a97ba13 900ccc6 0e297c4 a97ba13 8101ad8 3dae574 8101ad8 7aa89c2 8101ad8 7aa89c2 0e297c4 8101ad8 0e297c4 8101ad8 fd74317 8101ad8 fd74317 0e297c4 8101ad8 fd74317 0e297c4 8101ad8 2f1afc1 8101ad8 0e297c4 900ccc6 a97ba13 91cb314 8101ad8 91cb314 8101ad8 91cb314 8101ad8 91cb314 8101ad8 91cb314 8101ad8 84e2a5f 8101ad8 91cb314 8101ad8 0e297c4 91cb314 0e297c4 3dae574 91cb314 0e297c4 fd74317 516f61b 0e297c4 fd74317 cf3c061 fd74317 0e297c4 75889ea fd74317 0e297c4 d1ecfaa 8101ad8 fd74317 8101ad8 fd74317 cf3c061 d1ecfaa 8101ad8 0e297c4 fd74317 7aa89c2 0e297c4 516f61b 0e297c4 fd74317 8101ad8 fd74317 0e297c4 8101ad8 7aa89c2 e654566 7aa89c2 8101ad8 91cb314 8101ad8 91cb314 516f61b 8101ad8 91cb314 516f61b 8101ad8 516f61b 8101ad8 516f61b 7aa89c2 915357d 516f61b 8101ad8 516f61b e654566 516f61b 8101ad8 516f61b 8101ad8 516f61b 0e297c4 d1ecfaa e654566 91cb314 8101ad8 0e297c4 fd74317 d1ecfaa e654566 8101ad8 91cb314 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 023c07b 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 91cb314 8101ad8 91cb314 8101ad8 0e297c4 8101ad8 7aa89c2 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 3dae574 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 516f61b 7aa89c2 8101ad8 7aa89c2 8101ad8 7aa89c2 e654566 0e297c4 7aa89c2 d3d8136 7aa89c2 8101ad8 7aa89c2 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 91cb314 915357d 8101ad8 91cb314 0e297c4 8101ad8 0e297c4 fd74317 0e297c4 fd74317 915357d 0e297c4 8101ad8 fd74317 d1ecfaa 0e297c4 d1ecfaa fd74317 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 cf3c061 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 7aa89c2 0e297c4 e654566 0e297c4 e654566 0e297c4 8101ad8 7aa89c2 8101ad8 7aa89c2 023c07b 8101ad8 0e297c4 79bbca8 0e297c4 7aa89c2 d287e98 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 fd74317 8101ad8 0e297c4 fd74317 8101ad8 0e297c4 8101ad8 0e297c4 915357d 8101ad8 0e297c4 2f1afc1 fd74317 0e297c4 fd74317 915357d 0e297c4 fd74317 0e297c4 fd74317 023c07b 91cb314 8101ad8 0e297c4 8101ad8 0e297c4 915357d 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 0e297c4 900ccc6 0e297c4 cf3c061 8101ad8 3d317c4 8101ad8 7aa89c2 0e297c4 7aa89c2 8101ad8 0e297c4 8101ad8 0e297c4 8101ad8 2f1afc1 8101ad8 2f1afc1 8101ad8 2f1afc1 7aa89c2 2f1afc1 8101ad8 0e297c4 cf3c061 fd74317 2f1afc1 0e297c4 fd74317 2f1afc1 fd74317 0e297c4 2f1afc1 91cb314 0e297c4 8101ad8 0e297c4 023c07b 0e297c4 fd74317 900ccc6 d1ecfaa 8101ad8 d1ecfaa 8101ad8 d1ecfaa 2396f42 d1ecfaa 8101ad8 d1ecfaa 91cb314 d1ecfaa 8101ad8 79bbca8 d1ecfaa 8101ad8 7aa89c2 8101ad8 7aa89c2 8101ad8 7aa89c2 8101ad8 7aa89c2 8101ad8 7aa89c2 d1ecfaa 8101ad8 7aa89c2 8101ad8 7aa89c2 8101ad8 7aa89c2 d1ecfaa 7aa89c2 8101ad8 7aa89c2 d1ecfaa 91cb314 8101ad8 d1ecfaa 8101ad8 d1ecfaa 91cb314 d1ecfaa 91cb314 d1ecfaa 8101ad8 d1ecfaa 8101ad8 d1ecfaa 8101ad8 d1ecfaa 8101ad8 d1ecfaa 8101ad8 d1ecfaa 8101ad8 91cb314 d1ecfaa 91cb314 8101ad8 d1ecfaa 8101ad8 d1ecfaa 8101ad8 91cb314 8101ad8 91cb314 8101ad8 91cb314 8101ad8 91cb314 d1ecfaa 8101ad8 023c07b 0e297c4 8101ad8 023c07b 0e297c4 900ccc6 0e297c4 fd74317 8101ad8 7aa89c2 fd74317 7aa89c2 8101ad8 fd74317 75889ea fd74317 d1ecfaa fd74317 7aa89c2 fd74317 8101ad8 fd74317 7aa89c2 fd74317 d1ecfaa 91cb314 d1ecfaa fd74317 0e297c4 8101ad8 fd74317 0e297c4 fd74317 8101ad8 915357d fd74317 0e297c4 91cb314 fd74317 0e297c4 8101ad8 0e297c4 fd74317 915357d 0e297c4 8101ad8 915357d fd74317 d1ecfaa 8101ad8 d1ecfaa 8101ad8 d1ecfaa fd74317 0e297c4 a97ba13 8101ad8 d1ecfaa 8101ad8 d1ecfaa a97ba13 6d3af4d d1ecfaa e654566 d1ecfaa 900ccc6 a97ba13 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 | import hvplot.pandas
import numpy as np
import pandas as pd
import panel as pn
import param
import xarray as xr
import geopandas as gpd
import cartopy.crs as ccrs
from bokeh.models import HoverTool
import holoviews as hv
from holoviews import streams
from holoviews import streams
import geoviews.feature as gf
import geoviews as gv # Import for Graticule
from functools import lru_cache
import matplotlib.colors as mcolors
# ============================================================================
# COLOR MANAGEMENT FUNCTIONS (adapted from clean_rosette_plots.ipynb)
# ============================================================================
def lighten_color(color, amount=0.2):
"""Lighten color by blending with white."""
c = np.array(mcolors.to_rgb(color))
return tuple(1 - amount * (1 - c))
def get_season_colors(seasons):
"""Map seasons to fixed colors for consistency across plots."""
colors = {
'DJF': '#1f77b4', # tab:blue
'MAM': '#2ca02c', # tab:green
'JJA': '#d62728', # tab:red
'SON': '#ff7f0e' # tab:orange
}
return {s: colors[s] for s in seasons if s in colors}
def get_model_colors(models):
"""Map models to fixed colors."""
model_colors = {
'CESM2': '#1f77b4', # tab:blue
'MPI-GE': '#d62728', # tab:red
'EC-Earth3': '#2ca02c', # tab:green
'HadGEM3': '#ff7f0e' # tab:orange
}
return {m: model_colors.get(m, '#7f7f7f') for m in models}
def get_region_colors(regions, base_color=None):
"""Generate region colors, optionally with lightness variations of base color."""
if base_color is None:
# Use tab10 palette directly
cmap_colors = [
'#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'
]
return {r: cmap_colors[i % len(cmap_colors)] for i, r in enumerate(regions)}
else:
# Vary lightness of base color
return {r: lighten_color(base_color, 1 - 0.8 * i / max(1, len(regions) - 1))
for i, r in enumerate(regions)}
def assign_plot_colors(df, season_col='season', region_col='region_id', model_col='model'):
"""
Dynamically assign colors to dataframe rows based on which dimensions vary.
Logic mirrors matplotlib rosette plot:
- If multiple seasons AND regions: blend season color as base with region lightening
- If only seasons: use season colors
- If only regions: use region colors
- If only models: use model colors
- Otherwise: use neutral gray
Returns: dataframe with '_plot_color' column added
"""
df = df.copy()
seasons = df[season_col].unique()
regions = df[region_col].unique()
models = df[model_col].unique()
multi_season = len(seasons) > 1
multi_region = len(regions) > 1
multi_model = len(models) > 1
season_colors = get_season_colors(seasons)
region_colors_base = get_region_colors(regions)
model_colors = get_model_colors(models)
colors = []
for _, row in df.iterrows():
if multi_season and multi_region:
# Blend: season color as base, vary lightness by region
season = row[season_col]
region = row[region_col]
base = season_colors.get(season, '#7f7f7f')
region_lightened = get_region_colors([region], base_color=base)[region]
colors.append(region_lightened)
elif multi_season:
# Only season varies
colors.append(season_colors.get(row[season_col], '#7f7f7f'))
elif multi_region:
# Only region varies
colors.append(region_colors_base.get(row[region_col], '#7f7f7f'))
elif multi_model:
# Only model varies
colors.append(model_colors.get(row[model_col], '#7f7f7f'))
else:
# Fixed color
colors.append('#7f7f7f')
df['_plot_color'] = colors
return df
def build_legend_handles(df, season_col='season', region_col='region_id', model_col='model'):
"""
Build legend handles for HoloViews plots based on which dimensions vary.
Returns dict with 'color_map' for dimension color assignment.
"""
unique_seasons = df[season_col].unique() if season_col in df.columns else []
unique_regions = df[region_col].unique() if region_col in df.columns else []
unique_models = df[model_col].unique() if model_col in df.columns else []
multi_season = len(unique_seasons) > 1
multi_region = len(unique_regions) > 1
multi_model = len(unique_models) > 1
legend_info = {
'multi_season': multi_season,
'multi_region': multi_region,
'multi_model': multi_model,
'season_colors': get_season_colors(unique_seasons) if multi_season else {},
'region_colors': get_region_colors(list(unique_regions)) if multi_region else {},
'model_colors': get_model_colors(list(unique_models)) if multi_model else {},
}
return legend_info
# Custom CSS to highlight the active tab background
# Targeting multiple potential DOM structures for robustness
active_tab_css = """
/* Standard Bokeh/Panel structure */
.bk-tab.bk-active {
background-color: #2196f3 !important;
color: white !important;
font-weight: bold !important;
}
/* Material Design specific overrides if needed */
.mdc-tab--active .mdc-tab__text-label {
color: white !important;
font-weight: bold !important;
}
/* Ensure container header background is consistent */
.bk-tabs-header .bk-tab.bk-active {
background-color: #2196f3 !important;
}
"""
# Configure global loading indicator
pn.config.loading_spinner = 'arc'
pn.config.loading_color = '#333333'
pn.extension(design="material", sizing_mode="stretch_width", raw_css=[active_tab_css])
def get_data():
gdf_regions = gpd.read_file('data/rainfall_regions.geojson',).set_index('index')
region_names = gdf_regions.index.values
def process_csv(path):
df = pd.read_csv(path)
# Map source names
mapping = {'conversion': 'Conversion', 'dynamical': 'Dynamical', 'nonlinear': 'Non Linear'}
df['source'] = df['source'].map(mapping)
# Map region_id (1-based index) to region names
df['region_id'] = df['region_id'].apply(lambda x: region_names[x-1] if 0 < x <= len(region_names) else 'Unknown')
# Determine pivot columns (member exists in ensemble file)
pivot_cols = ['model', 'season', 'region_id', 'source', 'term']
if 'member' in df.columns:
pivot_cols.append('member')
# Convert to Xarray
obj = df.set_index(pivot_cols)['value'].to_xarray()
# Ensure region order matches GeoJSON to prevent mapping bugs
if 'region_id' in obj.coords:
obj = obj.reindex(region_id=region_names)
# Scale units (new CSV data is already aggregated but needs % scaling to match 100% total roughly)
# Multiply by 10000 (100 * 100) as per user request to reach expected percentage scale
return obj / 0.05*100
ds1 = process_csv("data/LENS_paper_terms_df.csv")
ds_ens = process_csv("data/LENS_paper_terms_ens_df.csv")
# Load precursor pattern GeoJSONs for each variable
gdf_precursors_u850 = gpd.read_file('data/precursor_patterns_U850.json')
gdf_precursors_v850 = gpd.read_file('data/precursor_patterns_V850.json')
gdf_precursors_z500 = gpd.read_file('data/precursor_patterns_Z500.json')
return ds1, ds_ens, gdf_regions, gdf_precursors_u850, gdf_precursors_v850, gdf_precursors_z500
ds1, ds_ens, gdf_regions, gdf_precursors_u850, gdf_precursors_v850, gdf_precursors_z500 = get_data()
def get_cached_precursor_map(variable_name, season, region, vmax):
"""Cached version of precursor map plotting."""
if variable_name == 'U850':
gdf = gdf_precursors_u850
elif variable_name == 'V850':
gdf = gdf_precursors_v850
elif variable_name == 'Z500':
gdf = gdf_precursors_z500
else:
return None
filtered = gdf.query("season==@season & region==@region")
if len(filtered) == 0:
return pn.pane.Markdown(f"No data for {region} in {season}")
plot_bounds = filtered.total_bounds
xlim = (plot_bounds[0], plot_bounds[2])
ylim = (plot_bounds[1], plot_bounds[3])
unit = 'm²/s²' if variable_name == 'Z500' else 'm/s'
hover = HoverTool(tooltips=[
(f"{variable_name} anomaly", f"@variable_level{{0.0}} {unit}")
])
plot = (filtered.hvplot.polygons(
crs=ccrs.PlateCarree(),
color='variable_level',
cmap='RdBu_r',
colorbar=False,
clim=(-vmax, vmax),
projection=ccrs.PlateCarree(),
line_width=0,
# projection=ccrs.PlateCarree(),
xlim=xlim,
ylim=ylim,
# frame_width=300,
# frame_height=300,
responsive=True,
aspect=0.75,
tools=[hover],
title=variable_name + f" ({season})"
) * gf.coastline * gf.grid()).opts(
axiswise=True
)
return plot
def get_precursor_plot(season='SON', region='Egypt + East Libya'):
"""Get all three precursor maps side-by-side."""
u850_map = get_cached_precursor_map('U850', season, region, 10)
v850_map = get_cached_precursor_map('V850', season, region, 10)
z500_map = get_cached_precursor_map('Z500', season, region, 2000)
try:
# Use pn.Row for robust handling of independent Geo plots
return pn.Row(u850_map, v850_map, z500_map, sizing_mode='scale_width')
except Exception as e:
print(f"Error in get_precursor_plot composition: {e}")
import traceback
traceback.print_exc()
return pn.pane.Markdown(f"**Error** plotting precursors: {e}", sizing_mode='scale_width')
# OPTIMIZATION 1: Cache the expensive classification computation
@lru_cache(maxsize=256)
def compute_classified_data_v3(model, season, term, nonlinear_pos, source_tuple, min_bias=20, slope_val=0.2):
"""Computation of classified data with dynamic thresholds - CACHED VERSION."""
# 1. Select data components for all regions
try:
ds_model = ds1.sel(model=model, season=season, term=term)
except Exception:
# Return empty DataFrame if selection fails
return pd.DataFrame(columns=['Region', 'Conversion', 'Dynamical', 'Non_Linear', 'X', 'Y', 'Selected_Sum', 'Total', 'Type', 'Text_Color'])
# 2. Extract base components and handle NaNs
conversion = ds_model.sel(source='Conversion').fillna(0)
dynamical = ds_model.sel(source='Dynamical').fillna(0)
nonlinear = ds_model.sel(source='Non Linear').fillna(0)
# 3. Determine X and Y for classification (based on nonlinear_pos setting)
if nonlinear_pos == 'Dynamical':
x_val = conversion
y_val = dynamical + nonlinear
else:
x_val = conversion + nonlinear
y_val = dynamical
# 4. Create DataFrame
# ds_model.sel(source=list(source_tuple)) works because xarray handles lists
df = pd.DataFrame({
'Region': ds_model.region_id.values,
'Conversion': conversion.values,
'Dynamical': dynamical.values,
'Non_Linear': nonlinear.values,
'X': x_val.values,
'Y': y_val.values,
'Selected_Sum': ds_model.sel(source=list(source_tuple)).sum('source').values if source_tuple else 0,
'Total': (conversion + dynamical + nonlinear).values
})
# 5. Add classification logic
def classify(row):
x, y = row['X'], row['Y']
if abs(x) + abs(y) <= min_bias: return 'Minimal'
if abs(x) < slope_val * abs(y): return 'Dynamical'
if abs(y) < slope_val * abs(x): return 'Conversion'
return 'Compounding' if x * y > 0 else 'Cancelling'
df['Type'] = df.apply(classify, axis=1)
# 6. Saturated colors for readable hover text
text_cmap = {
'Minimal': '#1B5E20', # Dark Green
'Conversion': '#B8860B', # Dark Gold
'Dynamical': '#0277BD', # Dark Blue
'Compounding': '#7B1FA2', # Dark Purple
'Cancelling': '#E65100' # Dark Orange
}
df['Text_Color'] = df['Type'].map(text_cmap)
return df
class CMIPApp(param.Parameterized):
model = param.Selector(default='CESM2', objects=list(ds1.model.values))
selected_models = param.ListSelector(default=list(ds1.model.values), objects=list(ds1.model.values), label="Models to include")
season = param.Selector(default='DJF', objects=['DJF', 'MAM', 'JJA', 'SON'])
term = param.Selector(default='bias', objects={'Bias from ERA5': 'bias', 'Change in SSP3-7.0': 'change', 'Uncalibrated Change': 'uncalibrated change'})
source = param.ListSelector(default=['Conversion','Dynamical','Non Linear'], objects=['Dynamical', 'Conversion', 'Non Linear'], label=f'Source of bias/change to plot')
nonlinear_pos = param.Selector(default='Dynamical', objects=['Dynamical', 'Conversion'], label="Non-linear term with:")
vmax = param.Integer(default=100, bounds=(1, 150), label="Colormap Saturation Value")
min_bias_threshold = param.Number(default=20, bounds=(1, 100), label=f"Minimal Bias/Change Threshold (%)")
slope_control = param.Number(default=0.2, bounds=(0.01, 0.5), label="Sector Slope (shallow)")
# Toggle for ensemble members in multi-model tab
show_ensemble_members = param.Boolean(default=False, label="Show Ensemble Members")
# Master selection state
_selection_index = param.List(default=[])
# Track when sync is in progress for loading indicator
_is_syncing = param.Boolean(default=False)
# User-facing region selector for sidebar
selected_regions = param.ListSelector(default=[], objects=list(gdf_regions.index), label="Selected Regions")
# Toggle for performance-intensive precursor maps
show_precursors = param.Boolean(default=False, label="Show Precursor Maps (Slower)")
# Shared color map for sectors
sector_cmap = {
'Minimal': '#C8E6C9', # Pale Green
'Conversion': '#FDFD96', # Pale Yellow
'Dynamical': '#ADD8E6', # Pale Blue
'Compounding': '#E1BEE7', # Pale Purple
'Cancelling': '#FFE0B2' # Pale Orange
}
def __init__(self, **params):
super().__init__(**params)
# Separate streams for each view to prevent source-swapping issues
self.v_map_s = streams.Selection1D()
self.t_map_s = streams.Selection1D()
self.scat_s = streams.Selection1D()
self.sel_map_s = streams.Selection1D()
# Shared map range for linked axes
self.map_r = streams.RangeXY()
# scatter range stream was removed; it caused unwanted autoscale on selection
# Link all streams to update the master selection
self.v_map_s.param.watch(self._sync_selection, 'index')
self.t_map_s.param.watch(self._sync_selection, 'index')
self.scat_s.param.watch(self._sync_selection, 'index')
self.sel_map_s.param.watch(self._sync_selection, 'index')
# Link sidebar region selector to selection index
self.param.watch(self._sync_from_sidebar, 'selected_regions')
self.param.watch(self._sync_to_sidebar, '_selection_index')
# Ensure initial selector state matches data
self.param.selected_models.objects = list(ds1.model.values)
self.param.model.objects = list(ds1.model.values)
# To share actual Bokeh range objects for linked axes across tabs
self._shared_x_range = None
self._shared_y_range = None
# OPTIMIZATION 2: Cache the full classified dataframe
self._cached_classified_data = None
self._cache_key = None
def _sync_selection(self, event):
"""Update master selection only if changed to avoid loops.
This watcher comes from our various Selection1D streams. When a
region is clicked in any view we update ``_selection_index`` and
immediately propagate the choice back out so every widget can
highlight consistently.
"""
print(f"_sync_selection called (event.new={event.new})")
self._is_syncing = True
try:
if self._selection_index != event.new:
self._selection_index = event.new
print(f" master index -> {self._selection_index}")
# propagate right away so other views update immediately
try:
self._propagate_selection_to_streams(type('e',(object,),{'new':self._selection_index}))
except Exception:
pass
finally:
self._is_syncing = False
def _propagate_selection_to_streams(self, event):
"""Push the current index into all registered streams.
Used both from ``_sync_selection`` and when the sidebar list
changes. The print statements allow basic debugging of the
propagation path.
"""
new_idx = event.new or []
print(f"_propagate_selection_to_streams new_idx={new_idx}")
for s in (self.v_map_s, self.t_map_s, self.scat_s, self.sel_map_s):
try:
s.event(index=new_idx)
except Exception:
pass
def _sync_from_sidebar(self, event):
"""Convert selected region names to indices when sidebar changes.
After updating the master index we call the propagation helper so maps
and the scatter are highlighted.
"""
region_names = event.new
print(f"_sync_from_sidebar event.new={region_names}")
self._is_syncing = True
try:
if region_names:
indices = [gdf_regions.index.get_loc(name) for name in region_names if name in gdf_regions.index]
if self._selection_index != indices:
self._selection_index = indices
print(f" sidebar -> master index {self._selection_index}")
self._propagate_selection_to_streams(type('e',(object,),{'new':self._selection_index}))
else:
if self._selection_index != []:
self._selection_index = []
self._propagate_selection_to_streams(type('e',(object,),{'new':self._selection_index}))
finally:
self._is_syncing = False
def _sync_to_sidebar(self, event):
"""Convert selection indices to region names for sidebar display."""
indices = event.new
print(f"_sync_to_sidebar event.new={indices}")
if indices:
region_names = [gdf_regions.index[i] for i in indices if i < len(gdf_regions)]
if self.selected_regions != region_names:
self.selected_regions = region_names
else:
if self.selected_regions != []:
self.selected_regions = []
def _get_classified_data(self):
"""Helper to unify classification and color mapping for all regions - WITH CACHING."""
# Convert list to tuple for hashing
source_tuple = tuple(self.source) if self.source else ()
# OPTIMIZATION 2: Check if we already have this data cached
cache_key = (self.model, self.season, self.term, self.nonlinear_pos,
source_tuple, self.min_bias_threshold, self.slope_control)
if self._cache_key == cache_key and self._cached_classified_data is not None:
return self._cached_classified_data
# Compute and cache
result = compute_classified_data_v3(
self.model, self.season, self.term, self.nonlinear_pos,
source_tuple, self.min_bias_threshold, self.slope_control
)
self._cached_classified_data = result
self._cache_key = cache_key
return result
# include _selection_index so the value map redraws when selection changes
@param.depends('_selection_index','model', 'season', 'term', 'source', 'vmax', 'nonlinear_pos')
def get_value_map(self):
# use 'Total' when all three bias components are included
label = 'Total' if len(self.source) == 3 else ' + '.join(self.source)
return self._render_map_base(self.term, 'BrBG', (-self.vmax, self.vmax),
f"{label} heavy precip. {self.term} (%)",
self.v_map_s, self.map_r)
# include _selection_index so classification map redraws when selection changes
@param.depends('_selection_index','model', 'season', 'term', 'nonlinear_pos', 'min_bias_threshold', 'slope_control')
def get_type_map(self):
return self._render_map_base('Type', self.sector_cmap,
title=f"{self.term.capitalize()} Classification: {self.model} {self.season}",
sel_stream=self.t_map_s, range_stream=self.map_r,
show_value=False)
def _render_map_base(self, color_col, cmap, clim=None, title="", sel_stream=None, range_stream=None, show_value=True):
# Capture current selection before it gets potentially reset by new plot source
current_index = self._selection_index
# Capture current zoom/pan range
current_x_range = range_stream.x_range
current_y_range = range_stream.y_range
# Defaults for PlateCarree (Europe/Med focus)
default_xlim = (-11, 30)
default_ylim = (30, 80)
# Only override if the stream has valid, non-None ranges from a user interaction
if current_x_range and all(x is not None for x in current_x_range):
xlim = current_x_range
else:
xlim = default_xlim
if current_y_range and all(y is not None for y in current_y_range):
ylim = current_y_range
else:
ylim = default_ylim
df_class = self._get_classified_data()
gdf = gdf_regions.copy()
# Use more robust mapping to ensure region alignment
if not df_class.empty:
df_to_map = df_class.set_index('Region')
gdf[self.term] = gdf.index.map(df_to_map['Selected_Sum']).fillna(0)
gdf['Conversion'] = gdf.index.map(df_to_map['Conversion']).fillna(0)
gdf['Dynamical'] = gdf.index.map(df_to_map['Dynamical']).fillna(0)
gdf['Non_Linear'] = gdf.index.map(df_to_map['Non_Linear']).fillna(0)
gdf['Total'] = gdf.index.map(df_to_map['Total']).fillna(0)
gdf['Type'] = gdf.index.map(df_to_map['Type']).fillna('Minimal')
gdf['Text_Color'] = gdf.index.map(df_to_map['Text_Color']).fillna('grey')
else:
# Fallback for empty data
for col in [self.term, 'Conversion', 'Dynamical', 'Non_Linear', 'Total']:
gdf[col] = 0
gdf['Type'] = 'Minimal'
gdf['Text_Color'] = 'grey'
gdf.index = gdf.index.rename('Region_Name')
gdf = gdf.reset_index()
# label dataset for hover; use Total when all three components
gdf.loc[:,'Source'] = 'Total' if len(self.source) == 3 else ' + '.join(self.source)
value_line = f'<div style="margin-top: 5px;"><span style="font-size: 12px;">@Source {self.term}: <b>@{{{self.term}}}{{0.0}}%</b></span></div>' if show_value else ""
tooltips = f"""
<div>
<span style="font-size: 15px; color: @Text_Color; font-weight: bold;">@Region_Name</span>
</div>
<div><span style="font-size: 12px;">Type: <b>@Type {self.term}</b></span></div>
{value_line}
<hr>
<div><span style="font-size: 11px;">Conversion: @Conversion{{0.0}}%</span></div>
<div><span style="font-size: 11px;">Dynamical: @Dynamical{{0.0}}%</span></div>
<div><span style="font-size: 11px;">Non Linear: @Non_Linear{{0.0}}%</span></div>
<hr>
<div><span style="font-size: 11px;"><b>Total {self.term}: @Total{{0.0}}%</b></span></div>
"""
html_hover = HoverTool(tooltips=tooltips)
plot_opts = dict(
# frame_height=450,
# frame_width=500,
responsive=True,
aspect=0.85,
tools=['tap', 'box_select', html_hover],
cmap=cmap,
color=color_col,
projection=ccrs.PlateCarree(),
data_aspect=None,
title=title,
xlim=xlim,
ylim=ylim,
hooks=[self.hook_selection],
line_color='black',
line_width=0.4,
selection_line_color='black',
selection_line_width=0.4,
active_tools=[],
axiswise=True
)
if clim is not None:
plot_opts['clim'] = clim
plot_opts['colorbar'] = True
else:
plot_opts['colorbar'] = False
plot_opts['legend_position'] = 'top_left'
# Back to PlateCarree with data_aspect=1 for correct aspect without coordinate issues
poly_plot = gdf.hvplot.polygons(crs=ccrs.PlateCarree(), color=color_col, hover_cols=['Region_Name', 'Source', 'Conversion', 'Dynamical', 'Non_Linear', 'Total', 'Type', 'Text_Color'], geo=True).opts(**plot_opts)
# IMPORTANT: attach the persistent streams to the new plot
sel_stream.source = poly_plot
range_stream.source = poly_plot
# Selection and ranges are now primarily handled by opts/hooks and dependencies
return poly_plot
def hook_selection(self, plot, element):
if not plot.state:
return
# 0. Sync Bokeh ranges for linked axes across tabs
if self._shared_x_range is None:
self._shared_x_range = plot.state.x_range
self._shared_y_range = plot.state.y_range
else:
plot.state.x_range = self._shared_x_range
plot.state.y_range = self._shared_y_range
# 1. Manually set the selection indices on the plot's data source if available
if 'source' in plot.handles:
plot.handles['source'].selected.indices = self._selection_index or []
# Style legend if this is a qualitative map (Type map)
if plot.state.legend:
legend = plot.state.legend[0] if isinstance(plot.state.legend, list) else plot.state.legend
try:
legend.background_fill_alpha = 0.5
legend.border_line_color = 'grey'
legend.orientation = 'horizontal'
legend.ncols = 2 # 5 items in 2 columns = 3 lines
except Exception:
pass
# Handle ColorBar (Values map)
# Check all layout sides where HoloViews/Bokeh might put it
for side in ['right', 'left', 'above', 'below', 'center']:
side_layout = getattr(plot.state, side)
cbars = [r for r in side_layout if 'ColorBar' in str(type(r))]
for cbar in cbars:
try:
# If it's not in center yet, move it
if side != 'center':
side_layout.remove(cbar)
plot.state.add_layout(cbar, 'center')
cbar.location = 'top_left'
cbar.orientation = 'horizontal'
# Sizes
cbar.height = 12
cbar.width = 250 # Proportional to plot width
# Font sizes & labels
cbar.title_text_font_size = '9pt'
cbar.label_text_font_size = '8pt'
cbar.major_tick_out = 3
cbar.label_standoff = 3
# Visibility & Style
cbar.background_fill_color = 'white'
cbar.background_fill_alpha = 0.8
cbar.border_line_color = 'grey'
cbar.level = 'overlay' # Ensure it is on top
except Exception:
pass
@param.depends('_selection_index', 'model', 'season', 'term', 'min_bias_threshold', 'slope_control', 'vmax', 'nonlinear_pos')
def get_secondary_plot(self, **kwargs):
if not self._selection_index:
return "### Please select a region"
region_iloc_idxs = self._selection_index
regions = gdf_regions.iloc[region_iloc_idxs].index.tolist()
# Select data for all sources because bars typically show decomposition
ds_sel_barplot = ds1.sel(model=self.model, season=self.season, term=self.term, region_id=regions)
# Convert to tidy DataFrame for easier plotting with tooltips
df = ds_sel_barplot.to_dataframe(name=self.term).reset_index()
# Ensure column names match tooltip expectations
# ds_sel_barplot has dims (region_id, source)
# to_dataframe -> index (region_id, source), value (self.term)
# reset_index -> region_id, source, self.term
# Rename if necessary based on existing coords
# If coords are named 'region_id' and 'source', we map them for clarity
df = df.rename(columns={'region_id': 'Region', 'source': 'Source'})
df['Region_Display'] = df['Region']
tooltips = f"""
<div>
<span style="font-size: 15px; color: blue; font-weight: bold;">@Region_Display</span>
</div>
<div>
<span style="font-size: 12px;">@Source {self.term}</span>
</div>
<div>
<span style="font-size: 12px;">@{self.term}</span>
</div>
"""
hover = HoverTool(tooltips=tooltips)
# Plot with detailed tooltips
# Stacked? Or Side-by-side?
# Typically one region -> one set of bars (Source vs Term).
# Multiple regions -> Grouped? Or just stacked?
# Let's keep it simple: x=Term, y=Source (horizontal bars)
bars = df.hvplot.barh(
x='Source',
y=self.term,
by='Region',
title=f"{self.term} by Source",
tools=[hover],
hover_cols=['Region_Display']
)
bars_out = bars.opts(height=400, width=400, toolbar='above') * hv.HLine(0).opts(color='k')
return bars_out
# OPTIMIZATION 4: Cache background generation
@lru_cache(maxsize=32)
def _get_scatter_background_cached(self, slope, min_bias, vmax):
"""Cached background generation."""
L = 200
S = slope
M = min_bias
bg_poly_data = [
{'x': [0, -S*L, -L, -L, 0], 'y': [0, L, L, S*L, 0], 'type': 'Cancelling'},
{'x': [0, S*L, L, L, 0], 'y': [0, -L, -L, -S*L, 0], 'type': 'Cancelling'},
{'x': [0, S*L, L, L, 0], 'y': [0, L, L, S*L, 0], 'type': 'Compounding'},
{'x': [0, -S*L, -L, -L, 0], 'y': [0, -L, -L, -S*L, 0], 'type': 'Compounding'},
{'x': [0, S*L, -S*L, 0], 'y': [0, L, L, 0], 'type': 'Dynamical'},
{'x': [0, -S*L, S*L, 0], 'y': [0, -L, -L, 0], 'type': 'Dynamical'},
{'x': [0, L, L, 0], 'y': [0, S*L, -S*L, 0], 'type': 'Conversion'},
{'x': [0, -L, -L, 0], 'y': [0, -S*L, S*L, 0], 'type': 'Conversion'}
]
min_poly_data = [{'x': [M, 0, -M, 0, M], 'y': [0, M, 0, -M, 0], 'type': 'Minimal'}]
bg_polys = hv.Polygons(bg_poly_data, vdims='type').opts(
color='type', cmap=self.sector_cmap, alpha=0.3, line_width=0, apply_ranges=False, tools=[]
)
min_poly = hv.Polygons(min_poly_data, vdims='type').opts(
color='type', cmap=self.sector_cmap, alpha=1.0, line_width=0.5, line_color='grey', apply_ranges=False, tools=[]
)
# Add labels - use term from instance (not cacheable, so we'll add them outside)
# Add constant apparent bias lines
lines = []
for k in range(-140, 160, 20):
if k == 0: continue
xs = np.array([-L, L])
ys = -xs + k
lines.append(hv.Curve((xs, ys)).opts(color='grey', line_width=0.5, line_dash='dashed', alpha=0.5))
xs = np.array([-L, L])
ys = -xs
lines.append(hv.Curve((xs, ys)).opts(color='black', line_width=1.0, line_dash='dashed', alpha=0.6))
return bg_polys * min_poly * hv.Overlay(lines).opts(apply_ranges=False)
def get_scatter_background(self, x_range=(-150, 150), y_range=(-150, 150)):
"""Generates the background sectors based on current slope and minimal bias settings."""
# Get cached background
bg = self._get_scatter_background_cached(self.slope_control, self.min_bias_threshold, self.vmax)
# Add labels (not cached because they depend on self.term)
labels = [
hv.Text(0, 0, f"Minimal {self.term.split(' ')[0]}", fontsize=8),
hv.Text(90, 0, 'Conversion', fontsize=9),
hv.Text(-90, 0, 'Conversion', fontsize=9),
hv.Text(0, 90, 'Dynamical', fontsize=9, rotation=90),
hv.Text(0, -90, 'Dynamical', fontsize=9, rotation=90),
hv.Text(70, 70, 'Compounding', fontsize=9),
hv.Text(-70, -70, 'Compounding', fontsize=9),
hv.Text(-70, 70, 'Cancelling', fontsize=9),
hv.Text(70, -70, 'Cancelling', fontsize=9),
]
return bg * hv.Overlay(labels)
# scatter must depend on _selection_index so it re-renders when selection changes
# and the hook can apply highlighting to the plot. Also depends on show_ensemble_members
# to toggle ensemble visualization.
@param.depends('_selection_index','model', 'season', 'term', 'nonlinear_pos',
'min_bias_threshold', 'slope_control', 'vmax', 'show_ensemble_members')
def get_scatter_plot(self):
# Get standardized classified data (cached)
df_scatter = self._get_classified_data()
# Setup labels based on nonlinear position
if self.nonlinear_pos == 'Dynamical':
x_label = f"Conversion {self.term} (%)"
y_label = f"Dynamical + Non Linear {self.term} (%)"
x_vars = ['Conversion']
y_vars = ['Dynamical', 'Non_Linear']
else:
x_label = f"Conversion + Non Linear {self.term} (%)"
y_label = f"Dynamical {self.term} (%)"
x_vars = ['Conversion', 'Non_Linear']
y_vars = ['Dynamical']
# Shared Color map for sectors
cmap = self.sector_cmap
if 'Total' not in df_scatter.columns:
df_scatter['Total'] = df_scatter['Conversion'] + df_scatter['Dynamical'] + df_scatter['Non_Linear']
# Prepare mean scatter data
mean_data = df_scatter.copy()
mean_data['Type'] = mean_data['Type'].astype(str)
mean_data['Text_Color'] = mean_data['Text_Color'].astype(str)
mean_data['size_mean'] = 100 # Larger for mean
mean_data['layer'] = 'mean'
tooltips = f"""
<div>
<span style="font-size: 15px; color: @Text_Color; font-weight: bold;">@Region</span>
</div>
<div><span style="font-size: 12px;">Type: <b>@Type {self.term}</b></span></div>
<div style="margin-top: 5px;"><span style="font-size: 11px;">{x_label.replace(' (%)','')}: <b>@X{{0.0}}%</b></span></div>
<div><span style="font-size: 11px;">{y_label.replace(' (%)','')}: <b>@Y{{0.0}}%</b></span></div>
<hr>
<div><span style="font-size: 11px;">Conversion: @Conversion{{0.0}}%</span></div>
<div><span style="font-size: 11px;">Dynamical: @Dynamical{{0.0}}%</span></div>
<div><span style="font-size: 11px;">Non Linear: @Non_Linear{{0.0}}%</span></div>
<hr>
<div><span style="font-size: 11px;"><b>Total {self.term}: @Total{{0.0}}%</b></span></div>
"""
hover = HoverTool(tooltips=tooltips)
opts = dict(
title=f"{self.term.capitalize()} classification: {self.model} {self.season}",
xlabel=x_label,
ylabel=y_label,
responsive=True,
aspect=0.85,
hooks=[self.hook_scatter_selection],
xlim=(-self.vmax, self.vmax),
ylim=(-self.vmax, self.vmax)
)
# Main scatter: mean points
scatter_mean = mean_data.hvplot.scatter(
x='X',
y='Y',
hover_cols=['Region', 'X', 'Y', 'Conversion', 'Dynamical', 'Non_Linear', 'Total', 'Type', 'Text_Color'],
tools=['pan', 'wheel_zoom', 'tap', 'box_select', hover],
color='Type',
cmap=cmap,
size=100,
line_color='white',
line_width=1.5,
legend=False,
aspect='equal'
).opts(**opts)
# Ensemble members: if enabled, add smaller semi-transparent points
overlay_layers = [self.get_scatter_background(), scatter_mean]
if self.show_ensemble_members and not ds_ens.empty:
try:
# Prepare ensemble data with same model/season/term selection
ds_ens_sel = ds_ens.sel(model=self.model, season=self.season, term=self.term)
conversion_ens = ds_ens_sel.sel(source='Conversion').fillna(0)
dynamical_ens = ds_ens_sel.sel(source='Dynamical').fillna(0)
nonlinear_ens = ds_ens_sel.sel(source='Non Linear').fillna(0)
if self.nonlinear_pos == 'Dynamical':
x_ens = conversion_ens
y_ens = dynamical_ens + nonlinear_ens
else:
x_ens = conversion_ens + nonlinear_ens
y_ens = dynamical_ens
# Create ensemble dataframe (one row per member per region)
if x_ens.size > 0:
df_ens = pd.DataFrame({
'Region': x_ens.region_id.values,
'X': x_ens.values,
'Y': y_ens.values,
'Conversion': conversion_ens.values,
'Dynamical': dynamical_ens.values,
'Non_Linear': nonlinear_ens.values,
'Total': (conversion_ens + dynamical_ens + nonlinear_ens).values,
'layer': 'ensemble'
})
# Get type classification for ensemble members (reuse mean types)
df_ens_typed = df_ens.merge(
mean_data[['Region', 'Type', 'Text_Color']],
on='Region',
how='left'
)
scatter_ens = df_ens_typed.hvplot.scatter(
x='X',
y='Y',
hover_cols=['Region', 'X', 'Y', 'Conversion', 'Dynamical', 'Non_Linear', 'Total', 'Type'],
tools=[],
color='Type',
cmap=cmap,
size=25,
line_color='black',
line_width=0.3,
alpha=0.6,
legend=False
).opts(**opts)
overlay_layers.append(scatter_ens)
except Exception as e:
print(f"Warning: Could not add ensemble scatter: {e}")
# Combine all layers
plot = hv.Overlay(overlay_layers).opts(active_tools=['pan', 'wheel_zoom'])
# attach stream to the scatter element so selection events fire correctly
self.scat_s.source = scatter_mean
return plot
def hook_scatter_selection(self, plot, element):
if 'source' in plot.handles:
# keep visual selection in sync with master index
plot.handles['source'].selected.indices = self._selection_index or []
print(f"hook_scatter_selection set indices to {self._selection_index}")
# and propagate any direct scatter selection back to the central state
inds = plot.handles['source'].selected.indices or []
if self._selection_index != inds:
print(f"hook_scatter_selection detected user change -> {inds}")
self._sync_selection(type('e',(object,),{'new': inds}))
# OPTIMIZATION 6: Most important - make bar plot only depend on selection, use cached data
@param.depends('_selection_index')
def get_bar_plot(self):
if not self._selection_index:
return pn.pane.Markdown(f"### {self.term.capitalize()} Decomposition: No region selected\n*Click on a map or scatter point to see the breakdown*")
# OPTIMIZATION: Get cached data, then filter - don't recompute!
df_class = self._get_classified_data()
selected_data = df_class.iloc[self._selection_index].copy()
# Melt to get components for grouping
melted = selected_data.melt(
id_vars=['Region', 'Type', 'Text_Color'],
value_vars=['Conversion', 'Dynamical', 'Non_Linear'],
var_name='Component',
value_name='Value'
)
# Calculate Total for each region and append to melted
totals = selected_data.copy()
totals['Component'] = 'Total'
totals['Value'] = totals['Conversion'] + totals['Dynamical'] + totals['Non_Linear']
totals = totals[['Region', 'Type', 'Text_Color', 'Component', 'Value']]
melted = pd.concat([melted, totals], ignore_index=True)
# Create Tooltip
tooltips = f"""
<div>
<span style="font-size: 14px; font-weight: bold;">@Region</span>
</div>
<div>
<span style="font-size: 12px; color: #333;">@Component {self.term}: <b>@Value{{0.0}}%</b></span>
</div>
"""
hover = HoverTool(tooltips=tooltips)
# Define colors including Total
bar_cmap = {
'Conversion': '#FDFD96',
'Dynamical': '#ADD8E6',
'Non_Linear': '#81C784',
'Total': '#EEEEEE'
}
# Create Horizontal Bar Plot
bar_plot = hv.Bars(melted, kdims=['Component', 'Region'], vdims='Value').opts(
height=400,
responsive=True,
title=f"{self.term.capitalize()} Breakdown for Selected Regions ({self.season})",
xlabel="Region",
ylabel=f"{self.term.capitalize()} (%)",
show_legend=False,
default_tools=[],
tools=[hover, 'xwheel_zoom', 'xpan', 'save', 'reset'],
active_tools=['xwheel_zoom', 'xpan'],
toolbar='above',
invert_axes=True,
color='Component',
cmap=bar_cmap,
xlim=(-self.vmax, self.vmax)
)
# Add vertical lines
vline_pos = hv.HLine(self.vmax).opts(color='red', line_dash='dashed', line_width=1.5, alpha=0.6)
vline_neg = hv.HLine(-self.vmax).opts(color='red', line_dash='dashed', line_width=1.5, alpha=0.6)
vline_zero = hv.HLine(0).opts(color='black', line_width=1.0, alpha=0.8)
return pn.Column(bar_plot * vline_pos * vline_neg * vline_zero, sizing_mode='scale_width', max_width=1200, margin=(20, 0, 0, 20))
@param.depends('_selection_index')
def get_selector_map(self):
# Simplified map for region selection
gdf = gdf_regions.reset_index().rename(columns={'index': 'Region_Name'})
gdf['Color'] = '#E0E0E0' # Lighter grey
tooltips = "<div><span style='font-size: 14px; font-weight: bold;'>@Region_Name</span></div>"
html_hover = HoverTool(tooltips=tooltips)
plot = gdf.hvplot.polygons(
crs=ccrs.PlateCarree(),
color='Color',
geo=True,
hover_cols=['Region_Name']
).opts(
default_tools=[],
responsive=True,
aspect=0.85,
tools=['tap', 'box_select', html_hover],
active_tools=[],
selection_color='red',
nonselection_color='#E0E0E0',
nonselection_alpha=1.0,
line_color='black',
line_width=0.4,
selection_line_color='black',
selection_line_width=0.4,
nonselection_line_color='black',
nonselection_line_width=0.4,
projection=ccrs.PlateCarree(),
xlim=(-11, 30),
ylim=(30, 80),
hooks=[self.hook_selection],
title="Select Regions"
)
self.sel_map_s.source = plot
return plot
@param.depends('_selection_index', 'season', 'term', 'selected_models', 'show_ensemble_members', 'nonlinear_pos', 'min_bias_threshold', 'slope_control', 'vmax')
def get_multi_model_bar_plot(self):
if not self._selection_index:
return pn.pane.Markdown(f"### {self.term.capitalize()} Multi-model Summary: No region selected\n*Select regions on the map to see the model comparison*")
region_names = gdf_regions.iloc[self._selection_index].index.tolist()
# Get model colors for consistent bar coloring
model_colors = get_model_colors(list(self.selected_models))
# Define component colors
component_colors = {
'Conversion': '#FDFD96',
'Dynamical': '#ADD8E6',
'Non Linear': '#81C784',
'Total': '#EEEEEE'
}
# OPTIMIZATION 7: Use lazy tab construction
def make_region_tab(region_name):
"""Lazy constructor for region tab."""
def construct_tab():
# Select data for current season and term
ds_region = ds1.sel(model=self.selected_models, season=self.season, term=self.term, region_id=region_name)
# Convert to tidy DataFrame
df = ds_region.to_dataframe(name='Value').reset_index()
df = df.rename(columns={'source': 'Component'})
# Calculate Total for each model
totals = df.groupby('model')['Value'].sum().reset_index()
totals['Component'] = 'Total'
df = pd.concat([df, totals], ignore_index=True)
# Assign colors: by component primarily, but could highlight models
# For now, use component colors
df['_color'] = df['Component'].map(component_colors).fillna('#7f7f7f')
# Create Tooltip
tooltips = f"""
<div>
<span style="font-size: 14px; font-weight: bold;">@model</span>
</div>
<div>
<span style="font-size: 12px; color: #333;">@Component {self.term}: <b>@Value{{0.0}}%</b></span>
</div>
"""
hover = HoverTool(tooltips=tooltips)
# Create Bar Plot
bar_plot = hv.Bars(df, kdims=['Component', 'model'], vdims='Value').opts(
invert_axes=True,
title=f"Multi-model {self.term.capitalize()} Comparison ({self.season})",
xlabel="Component / Model",
ylabel=f"{self.term.capitalize()} (%)",
show_legend=False,
default_tools=[],
tools=[hover, 'xwheel_zoom', 'xpan', 'save', 'reset'],
active_tools=['xwheel_zoom', 'xpan'],
toolbar='above',
color='Component',
cmap=component_colors,
selection_color='red',
nonselection_alpha=0.4
)
# Add reference lines
vline_zero = hv.HLine(0).opts(color='black', line_width=1.0, alpha=0.8)
bar_opts = dict(toolbar='above', margin=0, frame_height=400, frame_width=400)
bar_overlay = (bar_plot * vline_zero).opts(**bar_opts)
scatter_overlay = self.get_multi_model_scatter_plot(ds_region, region_name).opts(**bar_opts)
return pn.Row(
bar_overlay,
scatter_overlay,
align='start',
margin=(10, 0, 0, 0)
)
return construct_tab
tabs = [(region_name, make_region_tab(region_name)) for region_name in region_names]
# Use dynamic=True for lazy loading
return pn.Tabs(*tabs, sizing_mode='scale_width', margin=(10, 0, 0, 0), dynamic=True)
@param.depends('nonlinear_pos', 'min_bias_threshold', 'slope_control', 'term', 'vmax', 'show_ensemble_members')
def get_multi_model_scatter_plot(self, ds_region, region, **kwargs):
# 1. Extract base components
conversion = ds_region.sel(source='Conversion')
dynamical = ds_region.sel(source='Dynamical')
nonlinear = ds_region.sel(source='Non Linear')
# 2. Determine X and Y for classification
if self.nonlinear_pos == 'Dynamical':
x_val = conversion
y_val = dynamical.fillna(0) + nonlinear.fillna(0)
x_label = f"Conversion {self.term} (%)"
y_label = f"Dynamical + Non Linear {self.term} (%)"
else:
x_val = conversion.fillna(0) + nonlinear.fillna(0)
y_val = dynamical
x_label = f"Conversion + Non Linear {self.term} (%)"
y_label = f"Dynamical {self.term} (%)"
# 3. Create DataFrame for model means
df = pd.DataFrame({
'model': ds_region.model.values,
'Conversion': conversion.values,
'Dynamical': dynamical.values,
'Non_Linear': nonlinear.values,
'X': x_val.values,
'Y': y_val.values,
'Total': (conversion + dynamical + nonlinear).values
})
# 4. Add classification logic (consistent with compute_classified_data_v3)
def classify(row):
x, y = row['X'], row['Y']
if abs(x) + abs(y) <= self.min_bias_threshold: return 'Minimal'
if abs(x) < self.slope_control * abs(y): return 'Dynamical'
if abs(y) < self.slope_control * abs(x): return 'Conversion'
return 'Compounding' if x * y > 0 else 'Cancelling'
df['Type'] = df.apply(classify, axis=1)
# 5. Assign dynamic colors based on model dimensionality (no season/region here, only model)
df = assign_plot_colors(df, season_col='model', region_col='model', model_col='model')
# Map model-only colors correctly
model_colors = get_model_colors(df['model'].unique())
df['_plot_color'] = df['model'].map(model_colors)
# 6. Tooltips
tooltips = f"""
<div>
<span style="font-size: 15px; font-weight: bold;">@model</span>
</div>
<div><span style="font-size: 12px;">Type: <b>@Type {self.term}</b></span></div>
<hr>
<div><span style="font-size: 11px;">{x_label.replace(' (%)','')}: <b>@X{{0.0}}%</b></span></div>
<div><span style="font-size: 11px;">{y_label.replace(' (%)','')}: <b>@Y{{0.0}}%</b></span></div>
<hr>
<div><span style="font-size: 11px;">Conversion: @Conversion{{0.0}}%</span></div>
<div><span style="font-size: 11px;">Dynamical: @Dynamical{{0.0}}%</span></div>
<div><span style="font-size: 11px;">Non Linear: @Non_Linear{{0.0}}%</span></div>
<hr>
<div><span style="font-size: 11px;"><b>Total {self.term}: @Total{{0.0}}%</b></span></div>
"""
hover = HoverTool(tooltips=tooltips)
# 7. Scatter plot of model means using dynamic colors
scatter = df.hvplot.scatter(
x='X', y='Y',
hover_cols=['model', 'X', 'Y', 'Conversion', 'Dynamical', 'Non_Linear', 'Total', 'Type', '_plot_color'],
tools=['pan', 'wheel_zoom', 'save', 'reset', hover],
color='_plot_color',
size=120,
line_color='black',
line_width=1.0,
legend=False
).opts(
title=f"Multi-model {self.term.capitalize()} Classification ({self.season})",
xlabel=x_label,
ylabel=y_label,
xlim=(-max(100, self.vmax), max(100, self.vmax)),
ylim=(-max(100, self.vmax), max(100, self.vmax)),
show_legend=False,
nonselection_alpha=1.0,
nonselection_line_alpha=1.0
)
# 8. Add ensemble members if toggled (with consistent model colors)
if self.show_ensemble_members:
ds_ens_sub = ds_ens.sel(model=self.selected_models, season=self.season, term=self.term, region_id=region)
c_ens = ds_ens_sub.sel(source='Conversion').fillna(0)
d_ens = ds_ens_sub.sel(source='Dynamical').fillna(0)
n_ens = ds_ens_sub.sel(source='Non Linear').fillna(0)
if self.nonlinear_pos == 'Dynamical':
x_ens = c_ens
y_ens = d_ens + n_ens
else:
x_ens = c_ens + n_ens
y_ens = d_ens
df_ens_x = x_ens.to_dataframe(name='X').reset_index()
df_ens_y = y_ens.to_dataframe(name='Y').reset_index()
df_ens = df_ens_x.copy()
df_ens['Y'] = df_ens_y['Y']
# Apply consistent model colors to ensemble members
df_ens['_plot_color'] = df_ens['model'].map(model_colors)
ens_tooltips = f"""
<div>
<span style="font-size: 13px; font-weight: bold;">@model</span>
</div>
<div>
<span style="font-size: 11px;">Member: @member</span>
</div>
<div><span style="font-size: 11px;">{x_label.split(' ')[0]}: <b>@X{{0.0}}%</b></span></div>
<div><span style="font-size: 11px;">{y_label.split(' ')[0]}: <b>@Y{{0.0}}%</b></span></div>
"""
ens_hover = HoverTool(tooltips=ens_tooltips)
ens_scatter = df_ens.hvplot.scatter(
x='X', y='Y',
color='_plot_color',
size=30,
alpha=0.4,
tools=['pan', 'wheel_zoom', ens_hover],
hover_cols=['model', 'member', 'X', 'Y', '_plot_color'],
legend=False
).opts(nonselection_alpha=0.4)
scatter = ens_scatter * scatter
background = self.get_scatter_background()
return (background * scatter).opts(active_tools=['pan', 'wheel_zoom'], margin=0)
# OPTIMIZATION 8: Make precursor maps use dynamic tabs
@param.depends('_selection_index', 'season', 'show_precursors')
def get_precursor_maps(self):
"""Display precursor maps (U850, V850, Z500) for selected regions in tabs."""
if not self.show_precursors:
return pn.pane.Markdown("### Precursor Maps Disabled\n*Enable 'Show Precursor Maps' in the sidebar to view patterns (may reduce performance)*")
if not self._selection_index:
return pn.pane.Markdown("### Precursor maps: No region selected\n*Click on a map or scatter point to see precursor patterns*")
region_iloc_idxs = self._selection_index
regions = gdf_regions.iloc[region_iloc_idxs].index.tolist()
try:
# OPTIMIZATION: Create lazy tab constructors
def make_precursor_tab(region):
"""Lazy constructor for precursor map tab."""
return lambda: get_precursor_plot(season=self.season, region=region)
tabs = [(region, make_precursor_tab(region)) for region in regions]
# Create a shared qualitative colorbar
from bokeh.models import FixedTicker
dummy_data = pd.DataFrame({'x': [0, 1], 'y': [0, 0], 'z': [-1, 1]})
dummy_cbar = dummy_data.hvplot.heatmap(
x='x', y='y', C='z',
cmap='RdBu_r',
clim=(-1, 1),
colorbar=True,
alpha=0,
frame_height=30,
frame_width=1,
edgecolor='none',
xaxis=None, yaxis=None,
clabel='Precursor Anomaly'
).opts(
toolbar=None,
colorbar_opts={
'ticker': FixedTicker(ticks=[-1, 1]),
'major_label_overrides': {-1: ' Low anomaly', 1: 'High anomaly'},
'orientation': 'horizontal',
'title_text_font_size': '0pt',
'bar_line_color': 'black',
'height': 15,
'width': 400,
'padding': 0
}
)
cbar_row = pn.Row(
pn.Spacer(sizing_mode='stretch_width'),
dummy_cbar,
pn.Spacer(sizing_mode='stretch_width'),
margin=(10, 0, 20, 0),
min_height=30
)
# Use dynamic=True for lazy loading
return pn.Column(
pn.pane.Markdown("## Precursor Patterns", margin=(20, 0, 5, 20)),
cbar_row,
pn.Tabs(*tabs, margin=(0, 0, 0, 20), min_height=400, sizing_mode='scale_width', max_width=1200, dynamic=True),
min_height=450,
sizing_mode='scale_width',
max_width=1200
)
except Exception as e:
print(f"Error in get_precursor_maps: {e}")
import traceback
traceback.print_exc()
return pn.pane.Markdown(f"### Error loading maps\n{e}")
def get_sidebar_footer(self):
return pn.pane.Markdown(
"---\n**Reference:** \nOldham-Dorrington, J., Li, C., Sobolowski, S., & Guillaume-Castel, R. (2025). Understanding biases and changes in European heavy precipitation using dynamical flow precursors. *EGUsphere* [preprint]. <a href='https://egusphere.copernicus.org/preprints/2025/egusphere-2025-4977/' target='_blank'>https://egusphere.copernicus.org/preprints/2025/egusphere-2025-4977/</a>\n\nRobin Guillaume-Castel - 2026",
sizing_mode='stretch_width',
margin=(10, 10),
styles={'font-size': '0.75em'}
)
def get_single_model_sidebar(self):
return pn.Column(
pn.Param(self.param,
parameters=['model', 'season', 'term', 'show_precursors'],
widgets={'show_precursors': {'type': pn.widgets.Switch, 'align': 'start'}},
show_name=False, margin=(10, 5)),
pn.Tabs(
("Maps", pn.Column(
pn.Param(self.param, parameters=['source', 'vmax'], show_name=False),
margin=(10, 5)
)),
("Scatter", pn.Column(
pn.Param(self.param, parameters=['nonlinear_pos', 'min_bias_threshold', 'slope_control'],
widgets={
'nonlinear_pos': {'type': pn.widgets.Select},
'min_bias_threshold': {'type': pn.widgets.IntInput},
'slope_control': {'type': pn.widgets.FloatInput, 'step': 0.01}
}, show_name=False),
margin=(10, 5)
)),
("Regions", pn.Column(
pn.Param(self.param, parameters=['selected_regions'],
widgets={'selected_regions': {'height': 300}}, show_name=False),
margin=(10, 5)
)),
dynamic=False, sizing_mode='stretch_width'
),
self.get_sidebar_footer(),
sizing_mode='stretch_both'
)
def get_multi_model_sidebar(self):
return pn.Column(
pn.Param(self.param, parameters=['season', 'term', 'show_ensemble_members'],
widgets={'show_ensemble_members': {'type': pn.widgets.Switch, 'align': 'start'}},
show_name=False, margin=(10, 5)),
pn.pane.Markdown("### Models", margin=(10, 5, 0, 5)),
pn.widgets.CheckBoxGroup.from_param(self.param.selected_models, margin=(0, 5, 10, 5)),
pn.Tabs(
("Scatter Controls", pn.Column(
pn.Param(self.param, parameters=['nonlinear_pos', 'min_bias_threshold', 'slope_control'],
widgets={
'nonlinear_pos': {'type': pn.widgets.Select},
'min_bias_threshold': {'type': pn.widgets.IntInput},
'slope_control': {'type': pn.widgets.FloatInput, 'step': 0.01}
}, show_name=False),
margin=(10, 5)
)),
("Regions", pn.Column(
pn.Param(self.param, parameters=['selected_regions'],
widgets={'selected_regions': {'height': 300}}, show_name=False),
margin=(10, 5)
)),
dynamic=False, sizing_mode='stretch_width'
),
self.get_sidebar_footer(),
sizing_mode='stretch_both'
)
@param.depends('term')
def main_view(self):
scatter_pane = pn.Column(
pn.panel(self.get_scatter_plot, sizing_mode='scale_width'), # Removed loading_indicator
margin=(0, 0, 0, 5),
sizing_mode='scale_width'
)
def make_tab_row(map_func):
return pn.Row(
pn.panel(map_func, sizing_mode='scale_width'), # Removed loading_indicator
pn.Spacer(width=20),
scatter_pane,
sizing_mode='scale_width',
max_width=1200
)
map_tabs = pn.Tabs(
(f'Values', make_tab_row(self.get_value_map)),
(f'Classification', make_tab_row(self.get_type_map)),
margin=(0, 0, 0, 20),
sizing_mode='scale_width',
max_width=1200
)
# Loading indicator that shows during sync
@pn.depends(self.param._is_syncing)
def loading_overlay(_is_syncing):
if _is_syncing:
return pn.pane.Markdown("**⟳ Updating plots...**")
return pn.pane.Markdown("")
return pn.Column(
pn.pane.Markdown(f"# Single model focus"),
pn.pane.Markdown(f"### Maps of {self.term}", margin=(0, 0, 10, 0)),
map_tabs,
pn.panel(self.get_bar_plot), # Removed loading_indicator - now super fast
pn.panel(self.get_precursor_maps, loading_indicator=True), # Keep only here
pn.Spacer(height=200),
sizing_mode='stretch_width',
name="Single model/season focus",
)
def second_view(self):
return pn.Column(
pn.pane.Markdown("# Multi-model focus"),
pn.Row(
pn.Column(
pn.pane.Markdown("### Region Selector"),
pn.panel(self.get_selector_map, sizing_mode='scale_width'), # Removed loading_indicator
width=450
),
align='start'
),
pn.Column(
pn.pane.Markdown("### Selection Summary"),
pn.panel(self.get_multi_model_bar_plot), # Removed loading_indicator
sizing_mode='scale_width'
),
name="Multi-model focus"
)
app_instance = CMIPApp()
# Create the main interface
main_tabs = pn.Tabs(
("Single model/season focus", app_instance.main_view),
app_instance.second_view(),
stylesheets=[active_tab_css]
)
# Reactive function to switch sidebar content based on active tab
@pn.depends(main_tabs.param.active)
def dynamic_sidebar(active_index):
if active_index == 0:
return app_instance.get_single_model_sidebar()
else:
return app_instance.get_multi_model_sidebar()
app = pn.template.MaterialTemplate(
site="CMIP6 European Heavy Rainfall Explorer",
title="",
sidebar=[dynamic_sidebar],
sidebar_width=320,
main=[main_tabs],
)
app.servable() |