import numpy as np import pandas as pd from plotly import graph_objects as go import plotly.express as px from viewer.utils import PlotOptions def parse_merge_runs_to_plot(df, metric_name, merge_method): if merge_method == "none": return [ (group["steps"], group[metric_name], f'{runname}-s{seed}') for (runname, seed), group in df.groupby(["runname", "seed"]) ] if metric_name not in df.columns: return [] grouped = df.groupby(['runname', 'steps']).agg({metric_name: merge_method}).reset_index() return [ (group["steps"], group[metric_name], runname) for (runname,), group in grouped.groupby(["runname"]) ] def prepare_plot_data(df: pd.DataFrame, metric_name: str, seed_merge_method: str, plot_options: PlotOptions) -> pd.DataFrame: if df is None or "steps" not in df or metric_name not in df.columns: return pd.DataFrame() df = df.copy().sort_values(by=["steps"]) plot_data = parse_merge_runs_to_plot(df, metric_name, seed_merge_method) # Create DataFrame with all possible steps as index all_steps = sorted(set(step for xs, _, _ in plot_data for step in xs)) result_df = pd.DataFrame(index=all_steps) # Populate the DataFrame respecting xs for each series for xs, ys, runname in plot_data: result_df[runname] = pd.Series(index=xs.values, data=ys.values) # Interpolate or keep NaN based on the interpolate flag if plot_options.interpolate: # this is done per run, as each run is in a diff column result_df = result_df.interpolate(method='linear') # Apply smoothing if needed if plot_options.smoothing > 0: result_df = result_df.rolling(window=plot_options.smoothing, min_periods=1).mean() if plot_options.pct: result_df = result_df * 100 return result_df def plot_metric(plot_df: pd.DataFrame, metric_name: str, seed_merge_method: str, pct: bool, statistics: dict, nb_stds: int, language: str = None, barplot: bool = False) -> go.Figure: if barplot: return plot_metric_barplot(plot_df, metric_name, seed_merge_method, pct, statistics, nb_stds, language) return plot_metric_scatter(plot_df, metric_name, seed_merge_method, pct, statistics, nb_stds, language) def plot_metric_scatter(plot_df: pd.DataFrame, metric_name: str, seed_merge_method: str, pct: bool, statistics: dict, nb_stds: int, language: str = None) -> go.Figure: fig = go.Figure() if not isinstance(plot_df, pd.DataFrame) or plot_df.empty: return fig show_error_bars = nb_stds > 0 and not np.isnan(statistics["mean_std"]) error_value = statistics["mean_std"] * nb_stds * (100 if pct else 1) if show_error_bars else 0.0 last_y_values = {runname: plot_df[runname].iloc[-1] for runname in plot_df.columns} sorted_runnames = sorted(last_y_values, key=last_y_values.get, reverse=True) for runname in sorted_runnames: fig.add_trace( go.Scatter(x=plot_df.index, y=plot_df[runname], mode='lines+markers', name=runname, hovertemplate=f'%{{y:.2f}} ({runname})', error_y=dict( type='constant', # Use a constant error value value=error_value, # Single error value visible=show_error_bars # Show error bars )) ) lang_string = f" ({language})" if language else "" fig.update_layout( title=f"Run comparisons{lang_string}: {metric_name}" + (f" ({seed_merge_method} over seeds)" if seed_merge_method != "none" else "") + (f" [%]" if pct else ""), xaxis_title="Training steps", yaxis_title=metric_name, hovermode="x unified" ) return fig def plot_metric_barplot(plot_df: pd.DataFrame, metric_name: str, seed_merge_method: str, pct: bool, statistics: dict, nb_stds: int, language: str = None) -> go.Figure: fig = go.Figure() if not isinstance(plot_df, pd.DataFrame) or plot_df.empty: return fig show_error_bars = nb_stds > 0 and not np.isnan(statistics["mean_std"]) error_value = statistics["mean_std"] * nb_stds * (100 if pct else 1) if show_error_bars else 0.0 last_values = {runname: plot_df[runname].iloc[-1] for runname in plot_df.columns} sorted_runnames = sorted(last_values, key=last_values.get, reverse=True) # Create color map for consistent colors colors = px.colors.qualitative.Set1 color_map = {run: colors[i % len(colors)] for i, run in enumerate(plot_df.columns)} fig.add_trace( go.Bar( x=sorted_runnames, y=[last_values[run] for run in sorted_runnames], marker_color=[color_map[run] for run in sorted_runnames], error_y=dict( type='constant', value=error_value, visible=show_error_bars ), hovertemplate='%{y:.2f}' ) ) lang_string = f" ({language})" if language else "" fig.update_layout( title=f"Run comparisons{lang_string}: {metric_name}" + (f" ({seed_merge_method} over seeds)" if seed_merge_method != "none" else "") + ( f" [%]" if pct else ""), xaxis_title="Runs", yaxis_title=metric_name, hovermode="x" ) return fig