rguilcas's picture
Simplify tooltips for intro view
52442c5
Raw History Blame Contribute Delete
64.3 kB
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 from shapely.geometry import Polygon, GeometryCollection 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 glob # 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/aux/rainfall_regions.geojson',).set_index('index') gdf_regions = gdf_regions.reset_index() dummy_polygon = Polygon([ (0, -80), (1, -80), (1, -79), (0, -79) ]) gdf_regions.loc[1 - 0.5] = ["Region 2", dummy_polygon] # temporary fractional index gdf_regions = gdf_regions.sort_index().reset_index(drop=True) gdf_regions = gdf_regions.set_index("index") # Insert dummy line to replace missing region 2. # dummy_line = gdf_regions.iloc[[0]].copy() # dummy_line.index = ['Region 2'] # gdf_regions = gpd.GeoDataFrame(pd.concat([gdf_regions[:1], dummy_line, gdf_regions[1:]])) region_names = gdf_regions.index.values # region_names = np.insert(region_names, 1, 'none') # Insert 'none' at index 1 to match region_id mapping in CSV (region 2 is missing) 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) obj = obj / 0.05*100 # Replace zeros with NaN so they are greyed out in plots obj = obj.where(obj != 0) return obj list_ensemble_mean_files = glob.glob("data/results/ensemble_mean/*.csv") list_ensemble_members_files = glob.glob("data/results/ensemble/*.csv") data_ensemble_mean = xr.concat([process_csv(f) for f in list_ensemble_mean_files], dim='model') data_ensemble_members = xr.concat([process_csv(f) for f in list_ensemble_members_files], dim='model') data_ensemble_mean = data_ensemble_mean.reindex(region_id=region_names) data_ensemble_members = data_ensemble_members.reindex(region_id=region_names) # Load precursor pattern GeoJSONs for each variable gdf_precursors_u850 = gpd.read_file('data/aux/precursor_patterns_U850.json') gdf_precursors_v850 = gpd.read_file('data/aux/precursor_patterns_V850.json') gdf_precursors_z500 = gpd.read_file('data/aux/precursor_patterns_Z500.json') return data_ensemble_mean, data_ensemble_members, gdf_regions, gdf_precursors_u850, gdf_precursors_v850, gdf_precursors_z500 data_ensemble_mean, data_ensemble_members, 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 = data_ensemble_mean.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 (keep NaN instead of filling) conversion = ds_model.sel(source='Conversion') dynamical = ds_model.sel(source='Dynamical') nonlinear = ds_model.sel(source='Non Linear') # 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 (keep NaN values) # 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', min_count=1).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 either X or Y is NaN, return NaN (this will filter them out from scatter) if pd.isna(x) or pd.isna(y): return np.nan 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 'No Data': '#D3D3D3' # Light Grey for missing data } df['Text_Color'] = df['Type'].map(text_cmap) df['Text_Color'] = df['Text_Color'].fillna('#D3D3D3') return df class CMIPApp(param.Parameterized): model = param.Selector(default='CESM2' if 'CESM2' in data_ensemble_mean.model.values else list(data_ensemble_mean.model.values)[0], objects=list(data_ensemble_mean.model.values)) selected_models = param.ListSelector(default=list(data_ensemble_mean.model.values), objects=list(data_ensemble_mean.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") # Interval (percent) between diagonal constant-apparent-bias lines diag_interval = param.Integer(default=20, bounds=(1, 100), label="Apparent constant bias every (%)") # 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=[ k for k in list(gdf_regions.index) if 'Region 2' not in k], 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 'No Data': '#D3D3D3' # Light Grey for missing data } 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 map 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.sel_map_s.param.watch(self._sync_selection, 'index') # Scatter stream needs special handling: convert scatter positions to region names self.scat_s.param.watch(self._sync_selection_from_scatter, '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(data_ensemble_mean.model.values) self.param.model.objects = list(data_ensemble_mean.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 map Selection1D streams. event.new contains iloc indices relative to gdf_regions. """ 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 _sync_selection_from_scatter(self, event): """Handle scatter stream selection by converting positions to region names. The scatter DataFrame is filtered (rows with NaN Type removed), so its indices do not match gdf_regions iloc positions. Convert them to region names, then forward to _sync_selection. """ scatter_indices = event.new or [] print(f"_sync_selection_from_scatter called (event.new={scatter_indices})") self._is_syncing = True try: if not scatter_indices: # No selection if self._selection_index != []: self._selection_index = [] self._propagate_selection_to_streams(type('e',(object,),{'new':self._selection_index})) else: # Get the classified data (same as in get_scatter_plot) df_scatter = self._get_classified_data() df_scatter = df_scatter[df_scatter['Type'].notna()].copy() df_scatter = df_scatter.reset_index(drop=True) # Map scatter positions to region names try: region_names = df_scatter['Region'].iloc[scatter_indices].tolist() # Convert names to gdf_regions iloc indices new_indices = [gdf_regions.index.get_loc(name) for name in region_names if name in gdf_regions.index] if self._selection_index != new_indices: self._selection_index = new_indices print(f" scatter -> master index {self._selection_index}") self._propagate_selection_to_streams(type('e',(object,),{'new':self._selection_index})) except Exception as e: print(f" scatter sync error: {e}") finally: self._is_syncing = False def _propagate_selection_to_streams(self, event): """Push the current indices into all registered map streams. Only propagate to maps (not scatter) to avoid re-triggering the scatter watcher. The scatter hook handles visual highlighting independently. """ indices = event.new or [] print(f"_propagate_selection_to_streams indices={indices}") for s in (self.v_map_s, self.t_map_s, self.sel_map_s): try: s.event(index=indices) 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 () cache_key = (self.model, self.season, self.term, self.nonlinear_pos, source_tuple, self.min_bias_threshold, self.slope_control) # Only recompute if cache key changes 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 ) # Avoid repeated type conversions float_cols = ['X', 'Y', 'Conversion', 'Dynamical', 'Non_Linear', 'Total'] for col in float_cols: if col in result.columns and result[col].dtype != 'float': result[col] = result[col].astype('float') self._cached_classified_data = result self._cache_key = cache_key return result # Simple value map with sinpler tooltips @param.depends('_selection_index','model', 'season', 'term', 'source', 'vmax', 'nonlinear_pos') def get_value_map_simple_tooltip(self): # use 'Total' when all three bias components are included show_value=True label = 'Total' if len(self.source) == 3 else ' + '.join(self.source) value_line = f'<div style="margin-top: 5px;"><span style="font-size: 12px;">@Source heavy precip. {self.term}: <b>@{{{self.term}}}{{0.0}}%</b></span></div>' if show_value else "" tooltips = f""" <div><span style="font-size: 13px; color: 'darkgrey'; font-weight: bold; ">@Region_Name</span></div> <div><span style="font-size: 10px; color: 'darkgrey'; font-weight: bold; ">{self.model}</span></div> {value_line} """ html_hover = HoverTool(tooltips=tooltips) return self._render_map_base(self.term, 'BrBG', (-self.vmax, self.vmax), f"{self.model} - {label} heavy precip. {self.term} (%)", self.v_map_s, self.map_r).opts(tools=['tap', 'box_select', html_hover],) # 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']) gdf['Conversion'] = gdf.index.map(df_to_map['Conversion']) gdf['Dynamical'] = gdf.index.map(df_to_map['Dynamical']) gdf['Non_Linear'] = gdf.index.map(df_to_map['Non_Linear']) gdf['Total'] = gdf.index.map(df_to_map['Total']) gdf['Type'] = gdf.index.map(df_to_map['Type']).fillna('No Data') gdf['Text_Color'] = gdf.index.map(df_to_map['Text_Color']).fillna('#D3D3D3') 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 [] # 2. 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 = data_ensemble_mean.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, diag): """Cached background generation. `diag` controls the spacing (in percent) between diagonal dashed constant-apparent-bias lines. """ 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 = [] # draw apparent-bias offset lines every `diag` percent for k in range(0, 200, diag): 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)) for k in range(0, -200, -diag): 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 (include diagonal interval setting) bg = self._get_scatter_background_cached(self.slope_control, self.min_bias_threshold, self.vmax, self.diag_interval) # 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 @param.depends('_selection_index','model', 'season', 'term', 'nonlinear_pos', 'min_bias_threshold', 'slope_control', 'vmax', 'diag_interval', watch=True) def get_scatter_plot(self): # Get standardized classified data (cached) df_scatter = self._get_classified_data() # Filter out rows with NaN Type (missing data) df_scatter = df_scatter[df_scatter['Type'].notna()].copy() # 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} (%)" else: x_label = f"Conversion + Non Linear {self.term} (%)" y_label = f"Dynamical {self.term} (%)" # 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'] 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) ) scatter = df_scatter.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=60, line_color='black', line_width=0.6, legend=False, aspect='equal' ).opts(**opts) background = self.get_scatter_background() plot = (background * scatter).opts(active_tools=['pan']) # attach stream to the scatter element so selection events fire correctly self.scat_s.source = scatter return plot def hook_scatter_selection(self, plot, element): # The scatter plot may be built from a filtered DataFrame so the # row positions (selected.indices) do *not* always match the # master region index. We therefore translate back and forth using # the region name stored in the data source. if 'source' not in plot.handles: return df = pd.DataFrame(plot.handles['source'].data) # Apply master selection to scatter (visual highlighting) # Master selection contains gdf_regions iloc indices; convert to region names if self._selection_index: master_names = [gdf_regions.index[i] for i in self._selection_index if i < len(gdf_regions)] scatter_pos = df.index[df['Region'].isin(master_names)].tolist() else: scatter_pos = [] plot.handles['source'].selected.indices = scatter_pos print(f"hook_scatter_selection set scatter_pos {scatter_pos} from master {self._selection_index}") # 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() # Define colors consistent with get_bar_plot bar_cmap = { '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 = data_ensemble_mean.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(min_count=1).reset_index() totals['Component'] = 'Total' df = pd.concat([df, totals], ignore_index=True) # 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=bar_cmap, 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. 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) # 6. Scatter plot of model means scatter = df.hvplot.scatter( x='X', y='Y', hover_cols=['model', 'X', 'Y', 'Conversion', 'Dynamical', 'Non_Linear', 'Total', 'Type'], tools=['pan', 'wheel_zoom', 'save', 'reset', hover], color='model', cmap='Category20', size=120, line_color='black', line_width=1.0, legend=True ).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=True, legend_position='right', nonselection_alpha=1.0, nonselection_line_alpha=1.0 ) # 7. Add ensemble members if toggled if self.show_ensemble_members: data_ensemble_members_sub = data_ensemble_members.sel(model=self.selected_models, season=self.season, term=self.term, region_id=region) c_ens = data_ensemble_members_sub.sel(source='Conversion').fillna(0) d_ens = data_ensemble_members_sub.sel(source='Dynamical').fillna(0) n_ens = data_ensemble_members_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'] 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='model', cmap='Category20', size=30, alpha=0.4, tools=['pan', 'wheel_zoom', ens_hover], hover_cols=['model', 'member', 'X', 'Y'], 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_intro_sidebar(self): return pn.Column( pn.pane.Markdown( "## Change climate model,season and variable of interest here."), pn.Param(self.param, parameters=['model', 'season', 'term'], show_name=False, margin=(10, 5)), self.get_sidebar_footer(), sizing_mode='stretch_both' ) 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', 'diag_interval'], widgets={ 'nonlinear_pos': {'type': pn.widgets.Select}, 'min_bias_threshold': {'type': pn.widgets.IntInput}, 'slope_control': {'type': pn.widgets.FloatInput, 'step': 0.01}, 'diag_interval': {'type': pn.widgets.IntInput} }, 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', 'diag_interval'], widgets={ 'nonlinear_pos': {'type': pn.widgets.Select}, 'min_bias_threshold': {'type': pn.widgets.IntInput}, 'slope_control': {'type': pn.widgets.FloatInput, 'step': 0.01}, 'diag_interval': {'type': pn.widgets.IntInput} }, 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 intro_view(self): return pn.Column( # pn.pane.Markdown(f"# Introduction page"), # pn.pane.Markdown(f"### Maps of {self.term}", margin=(0, 0, 10, 0)), pn.Row( pn.pane.Markdown(""" # Classification Map This is a text to explain what is going on here. You can add a lot of stuff here. Maybe even plots from a paper. """, margin=(0, 20, 10, 20)), pn.panel(self.get_value_map_simple_tooltip, sizing_mode='scale_width'), # Removed loading_indicator ), pn.Spacer(height=200), sizing_mode='stretch_width', name="Introduction page", ) @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 multimodel_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_intro = CMIPApp() app_single = CMIPApp() app_multi = CMIPApp() main_tabs = pn.Tabs( ("Introduction page", app_intro.intro_view), ("Single model/season focus", app_single.main_view), app_multi.multimodel_view(), stylesheets=[active_tab_css] ) @pn.depends(main_tabs.param.active) def dynamic_sidebar(active_index): if active_index == 0: return app_intro.get_intro_sidebar() elif active_index == 1: return app_single.get_single_model_sidebar() else: return app_multi.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()
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
from shapely.geometry import Polygon, GeometryCollection
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 glob
# 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/aux/rainfall_regions.geojson',).set_index('index')
gdf_regions = gdf_regions.reset_index()
dummy_polygon = Polygon([
(0, -80),
(1, -80),
(1, -79),
(0, -79)
])
gdf_regions.loc[1 - 0.5] = ["Region 2", dummy_polygon] # temporary fractional index
gdf_regions = gdf_regions.sort_index().reset_index(drop=True)
gdf_regions = gdf_regions.set_index("index")
# Insert dummy line to replace missing region 2.
# dummy_line = gdf_regions.iloc[[0]].copy()
# dummy_line.index = ['Region 2']
# gdf_regions = gpd.GeoDataFrame(pd.concat([gdf_regions[:1], dummy_line, gdf_regions[1:]]))
region_names = gdf_regions.index.values
# region_names = np.insert(region_names, 1, 'none') # Insert 'none' at index 1 to match region_id mapping in CSV (region 2 is missing)
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)
obj = obj / 0.05*100
# Replace zeros with NaN so they are greyed out in plots
obj = obj.where(obj != 0)
return obj
list_ensemble_mean_files = glob.glob("data/results/ensemble_mean/*.csv")
list_ensemble_members_files = glob.glob("data/results/ensemble/*.csv")
data_ensemble_mean = xr.concat([process_csv(f) for f in list_ensemble_mean_files], dim='model')
data_ensemble_members = xr.concat([process_csv(f) for f in list_ensemble_members_files], dim='model')
data_ensemble_mean = data_ensemble_mean.reindex(region_id=region_names)
data_ensemble_members = data_ensemble_members.reindex(region_id=region_names)