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'
@Source {self.term}: @{{{self.term}}}{{0.0}}%
' if show_value else "" tooltips = f"""
@Region_Name
Type: @Type {self.term}
{value_line}
Conversion: @Conversion{{0.0}}%
Dynamical: @Dynamical{{0.0}}%
Non Linear: @Non_Linear{{0.0}}%

Total {self.term}: @Total{{0.0}}%
""" 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"""
@Region_Display
@Source {self.term}
@{self.term}
""" 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"""
@Region
Type: @Type {self.term}
{x_label.replace(' (%)','')}: @X{{0.0}}%
{y_label.replace(' (%)','')}: @Y{{0.0}}%

Conversion: @Conversion{{0.0}}%
Dynamical: @Dynamical{{0.0}}%
Non Linear: @Non_Linear{{0.0}}%

Total {self.term}: @Total{{0.0}}%
""" 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"""
@Region
@Component {self.term}: @Value{{0.0}}%
""" 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 = "
@Region_Name
" 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"""
@model
@Component {self.term}: @Value{{0.0}}%
""" 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"""
@model
Type: @Type {self.term}

{x_label.replace(' (%)','')}: @X{{0.0}}%
{y_label.replace(' (%)','')}: @Y{{0.0}}%

Conversion: @Conversion{{0.0}}%
Dynamical: @Dynamical{{0.0}}%
Non Linear: @Non_Linear{{0.0}}%

Total {self.term}: @Total{{0.0}}%
""" 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"""
@model
Member: @member
{x_label.split(' ')[0]}: @X{{0.0}}%
{y_label.split(' ')[0]}: @Y{{0.0}}%
""" 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]. https://egusphere.copernicus.org/preprints/2025/egusphere-2025-4977/\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()