lf2i.plot package¶
Submodules¶
lf2i.plot.animation module¶
- lf2i.plot.animation.parameter_regions_pairplot_animation(*parameter_regions: ndarray, posterior_regions: Sequence[ndarray], true_parameter: ndarray, n_frames: int = 60, alpha: float | None = None, diagonal_pvalues: ndarray | None = None, diagonal_grid: ndarray | None = None, diagonal_levels: Sequence[float] | None = None, posterior_estimator=None, posterior_observations: Sequence | None = None, n_posterior_samples: int = 10000, parameter_space_bounds: Dict[str, Dict[str, float]] | None = None, param_names: ndarray | None = None, labels: ndarray | None = None, colors: Sequence[str] | None = None, region_names: Sequence[str] | None = None, figsize: Sequence[int] = (15, 15), show_legend: bool = True, fps: int = 30, save_path: str | None = None) FuncAnimation[source]¶
Animate the morphing of a posterior pairplot into a confidence-region pairplot.
Diagonal panels interpolate between a normalized posterior KDE curve (frame 0) and a normalized confidence p-value curve (last frame). Off-diagonal panels morph between point clouds via alpha shapes: points are added and removed in order of proximity to the combined centroid of both clouds (posterior outer points disappear first; confidence inner points appear first), and an alpha shape contour is redrawn each frame over the current visible point set.
- Parameters:
*parameter_regions – Confidence region point clouds, each of shape
(n_pts, n_dims).posterior_regions – Posterior sample clouds corresponding 1-to-1 with
parameter_regions, each of shape(n_pts, n_dims).true_parameter – 1-D array of shape
(n_dims,).n_frames – Total number of animation frames.
alpha – Alpha parameter passed to
alphashape.alphashapecontrolling contour tightness.Noneor0produces the convex hull.diagonal_pvalues – Shape
(1, n_dims, grid_size)— normalized p-values for the confidence diagonal curves.diagonal_grid – Shape
(n_dims, grid_size)— x-axis grid coordinates per dimension.diagonal_levels – Unused in the animation (kept for API parity).
posterior_estimator – Object with a
.sample((n,), x=obs)method used to draw posterior samples for the diagonal KDE curves.posterior_observations – Observations passed to
posterior_estimator; the first element is used.n_posterior_samples – Number of posterior samples to draw for each diagonal KDE.
parameter_space_bounds – Dict mapping each param name to
{'low': float, 'high': float}. When provided, sets axis limits on diagonal panels.param_names – Dimension labels; defaults to
θ_0, θ_1, ....labels – Axis labels overriding
param_nameswhen provided.colors – One color per region pair; defaults to a rainbow palette.
region_names – Legend labels for each region pair.
figsize – Figure size passed to
plt.subplots.show_legend – Whether to add a figure-level legend.
fps – Frames per second when saving.
save_path – If given, save the animation to this path via ffmpeg.
- Returns:
FuncAnimation
lf2i.plot.calibration_diagnostics module¶
- lf2i.plot.calibration_diagnostics.calibration_score_plot(parameters: ndarray, scores: ndarray, score_label: str, param_dim: int, save_fig_path: str | None = None, figsize: Tuple = (6, 5), xlims: Tuple[float, float] | None = None, ylims: Tuple[float, float] | None = None, params_labels: Tuple[str] | List[str] | None = None, vmax: float | None = None, n_bins: int | None = None, custom_ax: Axes | None = None, title: str | None = None) Any | None[source]¶
Heatmap of a single per-theta calibration score (e.g. MSE, CRPS, pinball loss) returned by monte_carlo_pvalue_diagnostics.
Green = 0 (best), red = vmax (worst). Mirrors the interface of coverage_probability_plot: when custom_ax is None the function owns the figure, adds a colorbar, and calls plt.show(); when custom_ax is supplied it returns the pcolormesh artist so the caller can attach a shared colorbar.
- lf2i.plot.calibration_diagnostics.calibration_score_panel(evaluation_grid: ndarray, estimation_errors: Dict[str, ndarray], param_dim: int, score_labels: Dict[str, str] | None = None, save_fig_path: str | None = None, figsize: Tuple | None = None, xlims: Tuple[float, float] | None = None, ylims: Tuple[float, float] | None = None, params_labels: Tuple[str] | List[str] | None = None, title: str | None = None) None[source]¶
Side-by-side heatmap panels for every score key in estimation_errors. Direct counterpart of coverage_pairplot for calibration-quality diagnostics.
Intended to be called with the output of monte_carlo_pvalue_diagnostics:
grid, errors = lf2i_obj.monte_carlo_pvalue_diagnostics(...) calibration_score_panel(grid, errors, param_dim=2)
Each panel gets an independent colorbar anchored at zero (green, best) up to the per-panel maximum (red, worst). Use score_labels to override the default display names for any key.
- lf2i.plot.calibration_diagnostics.plot_cdf_comparison(test_statistic: Any, calib_model: Any, theta_eval: ndarray, simulator: Any, monte_carlo_size: int = 2000, n_grid: int = 500, title: str | None = None, figsize: Tuple = (7, 5), save_fig_path: str | None = None, custom_ax: Axes | None = None) None[source]¶
Plot the MC empirical CDF vs. the calibration model’s predicted CDF at a fixed theta.
- Parameters:
test_statistic (TestStatistic) – Fitted test statistic with an
evaluatemethod.calib_model (Any) – A single calibration model (a value from
lf2i.calibration_model), must havepredict_proba. Must be of typelf2i.estimators.AbstractCDFEstimatororlf2i.estimators.AbstractProbabilisticClassifier.theta_eval (np.ndarray, shape (param_dim,) or (1, param_dim)) – The parameter value at which to evaluate.
simulator (Simulator) – lf2i Simulator used to draw MC samples.
monte_carlo_size (int) – Number of MC draws. Default 2000.
n_grid (int) – Resolution of the lambda grid for the parametric CDF curve. Default 500.
title (str, optional)
figsize (Tuple)
save_fig_path (str, optional)
custom_ax (Axes, optional) – If provided, draw onto this axes without calling
plt.show().
- lf2i.plot.calibration_diagnostics.calibration_cdf_panel(evaluation_grid: ndarray, estimation_errors: Dict[str, ndarray], test_statistic: Any, calibration_model: Dict, simulator: Any, param_dim: int, score_key: str = 'crps', monte_carlo_size: int = 2000, n_grid: int = 500, xlims: Tuple[float, float] | None = None, ylims: Tuple[float, float] | None = None, n_bins: int | None = None, params_labels: Tuple[str] | List[str] | None = None, title: str | None = None, figsize: Tuple | None = None, save_fig_path: str | None = None, query_points: ndarray | None = None) None[source]¶
Three-panel diagnostic figure combining a calibration score heatmap with CDF comparisons.
Panels:
Left: calibration score heatmap (from
calibration_score_plot()).Middle/Right: CDF comparisons. When
query_pointsis None (default), these show the worst-match theta (highestscore_key) and best-match theta (lowestscore_key). Whenquery_pointsis provided, one panel is produced per query point and the points are indexed on the score heatmap.
- Parameters:
evaluation_grid (np.ndarray) – Grid of parameter values, as returned by
monte_carlo_pvalue_diagnostics().estimation_errors (Dict[str, np.ndarray]) – Per-theta error arrays, as returned by
monte_carlo_pvalue_diagnostics().test_statistic (TestStatistic) – Fitted test statistic.
calibration_model (Dict) – The
lf2i.calibration_modeldict (key -> model).simulator (Simulator) – lf2i Simulator used to draw MC samples.
param_dim (int) – Dimensionality of the parameter.
score_key (str) – Key in
estimation_errorsused to rank thetas. Default'crps'.monte_carlo_size (int) – MC draws per theta for the CDF panels. Default 2000.
n_grid (int) – Lambda-grid resolution for parametric CDF curves. Default 500.
xlims (Tuple[float, float], optional) – Axis limits for the score heatmap.
ylims (Tuple[float, float], optional) – Axis limits for the score heatmap.
title (str, optional) – Overall figure suptitle.
figsize (Tuple, optional)
save_fig_path (str, optional)
query_points (np.ndarray, optional) – Array of shape
(n_query, param_dim)(or(param_dim,)for a single point). When provided, CDF comparisons are shown for each of these points instead of the automatic worst/best selection, and the points are marked with index labels on the score heatmap.
lf2i.plot.coverage_diagnostics module¶
- lf2i.plot.coverage_diagnostics.coverage_probability_plot(parameters: ndarray, coverage_probability: ndarray, confidence_level: float, param_dim: int, upper_proba: ndarray | None = None, lower_proba: ndarray | None = None, save_fig_path: str | None = None, figsize: Tuple = (10, 8), xlims: Tuple[float] | None = None, ylims: Tuple[float] | None = None, params_labels: Tuple[str] | List[str] | None = None, vmin_vmax: List | Tuple | None = None, custom_ax: Axes | None = None, show_text: bool = False, show_undercoverage: bool = False, title: str | None = None, n_bins: int = 30, n_levels: int = 15) None[source]¶
- lf2i.plot.coverage_diagnostics.coverage_regions_plot(parameters: ndarray, confidence_level: float, coverage_probability: ndarray, upper_proba: ndarray, lower_proba: ndarray, param_dim: int, params_labels: Tuple[str] | List[str] | None = None, figsize: Tuple = (5, 5), save_fig_path: str | None = None, custom_ax: Axes | None = None) None[source]¶
- lf2i.plot.coverage_diagnostics.coverage_pairplot(plot_type: str, parameters: ndarray, probabilities: Dict[str, Dict[str, ndarray]] | ndarray, confidence_level: float, diagnostics_estimator: Any | None = None, aggregate_fun: str | None = None, vmin_vmax: Sequence[float] | None = None, params_labels: Sequence | None = None, plot_title: str | None = None, figsize: Tuple = (15, 15), save_fig_path: str | None = None, **kwargs) None[source]¶
- lf2i.plot.coverage_diagnostics.coverage_barplot(confidence_level: float, mean_proba: ndarray, upper_proba: ndarray | None = None, lower_proba: ndarray | None = None, save_fig_path: str | None = None, tol: float | None = None, figsize: Tuple = (5, 5)) None[source]¶
- lf2i.plot.coverage_diagnostics.coverage_boxplot(probabilities: Sequence[ndarray], labels: Sequence[str], confidence_level: float, whiskers_loc: Tuple[float, float] | float = 1.5, plot_fliers: bool = True, ylim: Sequence[float] | None = (0, 1), save_fig_path: str | None = None, figsize: Tuple = (8, 6)) None[source]¶
- lf2i.plot.coverage_diagnostics.coverage_nominal_actual_band(probabilities: Sequence[ndarray], confidence_levels: ndarray, color: str = 'steelblue', fill_alpha: float = 0.25, ylim: Sequence[float] | None = None, save_fig_path: str | None = None, figsize: Tuple = (5, 5), ax: Axes | None = None) None[source]¶
lf2i.plot.miscellanea module¶
- lf2i.plot.miscellanea.hist_pairplot(data: ndarray, save_fig_path: str | None = None, figsize: Tuple = (15, 15), labels: List | Tuple | None = None) None[source]¶
- lf2i.plot.miscellanea.check_probs_classifier(y_true: ndarray, y_pred_positive_proba: ndarray, parameters: ndarray, confidence_level: float, param_dim: int, params_labels: Sequence | None = None, figsize: Tuple = (15, 15), save_fig_path: str | None = None) None[source]¶
- lf2i.plot.miscellanea.PolygonPathFixed(polygon)[source]¶
FIXED: shapely changed how it handles Polygon exteriors and descartes hasn’t been updated. Constructs a compound matplotlib path from a Shapely or GeoJSON-like geometric object
- lf2i.plot.miscellanea.PolygonPatchFixed(polygon, **kwargs)[source]¶
FIXED: shapely changed how it handles Polygon exteriors and descartes hasn’t been updated. Constructs a matplotlib patch from a geometric object
The polygon may be a Shapely or GeoJSON-like object with or without holes. The kwargs are those supported by the matplotlib.patches.Polygon class constructor. Returns an instance of matplotlib.patches.PathPatch.
Example (using Shapely Point and a matplotlib axes):
>>> b = Point(0, 0).buffer(1.0) >>> patch = PolygonPatch(b, fc='blue', ec='blue', alpha=0.5) >>> axis.add_patch(patch)
lf2i.plot.parameter_regions module¶
- lf2i.plot.parameter_regions.plot_parameter_regions(*parameter_regions: ndarray, param_dim: int, true_parameter: ndarray | None = None, prior_samples: ndarray | None = None, parameter_space_bounds: Dict[str, float] | None = None, colors: Sequence[str] | None = None, region_names: Sequence[str] | None = None, labels: ndarray | None = None, linestyles: Sequence[str] | None = None, param_names: ndarray | None = None, alpha_shape: bool = False, alpha: float | None = None, scatter: bool = True, log_scale: bool = False, title: str | None = None, figsize: Sequence[int] | None = (15, 15), save_fig_path: str | None = None, remove_legend: bool = False, custom_ax: Axes | None = None, show_diagonal: bool | None = False, diagonal_type: str | None = 'hist', diagonal_pvalues: ndarray | None = None, diagonal_grid: ndarray | None = None, diagonal_levels: Sequence[float] | None = None, posterior_estimator=None, posterior_observations: Sequence | None = None, filter_subset: bool | None = False, subset_threshold: float | None = 1.0) None[source]¶
Dispatcher to plot parameter regions of different dimensionality.
For param_dim > 2, creates a pairplot showing all 2D projections.
- lf2i.plot.parameter_regions.plot_parameter_region_1D(parameter_region: ndarray, true_parameter: ndarray, parameter_space_bounds: Dict[str, float] | None = None, figsize: Tuple[int, int] | None = None, color: str | None = 'green', log_scale: bool = False, region_name: str = 'Parameter Region', linestyle: str = '-', custom_ax: Axes | None = None) None[source]¶
Plot 1-dimensional parameter regions using the lower and upper bounds.
- lf2i.plot.parameter_regions.plot_parameter_region_2D(parameter_region: ndarray, true_parameter: ndarray | None = None, parameter_space_bounds: Dict[str, Dict[str, float]] | None = None, labels: Sequence[str] | None = None, param_names: Sequence[str] | None = None, figsize: Tuple[int, int] | None = None, alpha_shape: bool = False, alpha: float | None = None, scatter: bool = True, color: str | None = 'green', linestyle: str | None = '-', region_name: str | None = 'Parameter region', custom_ax: Axes | None = None) None[source]¶
Plot 2-dimensional parameter regions as point clouds.
- lf2i.plot.parameter_regions.parameter_regions_pairplot(*parameter_regions: ndarray, true_parameter: ndarray, parameter_space_bounds: Dict[str, Tuple[float]] | None = None, labels: ndarray | None = None, param_names: ndarray | None = None, colors: Sequence[str] | None = None, region_names: Sequence[str] | None = None, alpha_shape: bool = False, alpha: float | None = None, scatter: bool = True, show_diagonal: bool = False, diagonal_type: str = 'confidence', diagonal_pvalues: ndarray | None = None, diagonal_grid: ndarray | None = None, diagonal_levels: Sequence[float] | None = None, posterior_estimator=None, posterior_observations: Sequence | None = None, figsize: Sequence[int] | None = (15, 15), show_legend: bool = True, save_fig_path: str | None = None) None[source]¶
Plot a pairplot of 2D parameter region projections.
Each upper-triangle cell (row, col) shows the 2D projection onto dimensions [row, col]. The diagonal shows either a confidence curve or posterior density. Lower triangle is hidden.
- Parameters:
*parameter_regions – One or more confidence/credible sets, each of shape
(n_pts, param_dim).true_parameter – 1-D array of shape
(param_dim,)for the single observation being plotted.diagonal_pvalues – Shape
(1, param_dim, grid_size)— p-values for one observation.diagonal_grid – Shape
(param_dim, grid_size)— grid coordinates per dimension.diagonal_levels – Confidence or credibility levels for the diagonal curves.
- lf2i.plot.parameter_regions.plot_parameter_intervals(*parameter_regions: ndarray, param_dim: int, point_estimates: Sequence[ndarray] | None = None, true_parameters: Sequence[ndarray] | None = None, interval_type: str = 'projection', param_names: Sequence[str] | None = None, colors: Sequence | None = None, region_names: Sequence[str] | None = None, parameter_space_bounds: Dict | None = None, title: str | None = None, figsize: Tuple[int, int] | None = None, save_fig_path: str | None = None) None[source]¶
Plot 1D interval summaries of ND confidence sets.
Each parameter dimension gets its own horizontal number line showing the interval as a closed segment with bracket-style endpoint markers and an optional point estimate indicator.
- Parameters:
*parameter_regions (np.ndarray) – One or more confidence sets for a single observation, each of shape
(n_grid_pts, param_dim). For 1D parameters, shape(n_grid_pts,)is also accepted.param_dim (int) – Number of parameter dimensions.
point_estimates (sequence of np.ndarray, optional) – One array of shape
(param_dim,)per region giving the maximum-p-value estimate θ^Focal for that region. Used both to label the indicator and (wheninterval_type='slice') to construct the slice intervals.true_parameters (sequence of np.ndarray, optional) – One array of shape
(param_dim,)per region giving the true parameter values for that region. Plotted as a red star.interval_type (str, optional) –
How to derive 1D intervals from the ND confidence set:
'projection'(default) — take[min, max]of each column.'slice'— fix all dimensions except d at the nearest grid value to θ^Focal, then take[min, max]of column d. Requirespoint_estimates.
param_names (sequence of str, optional) – Axis labels; falls back to
θ_0, θ_1, …if not supplied.colors (sequence, optional) –
One colour per region; defaults to a rainbow palette.
Note: Point estimates are displayed in the first colour in the list.
region_names (sequence of str, optional) – Legend labels for the regions.
parameter_space_bounds (dict, optional) –
{param_name: {'low': float, 'high': float}}used to set per-axis xlim.title (str, optional) – Figure suptitle.
figsize (tuple of int, optional) –
(width, height)in inches. Defaults to(8, 0.9 * param_dim).save_fig_path (str, optional) – If given, save the figure to this path.
- lf2i.plot.parameter_regions.plot_confidence_distributions_1D(all_pvalues: ndarray, grid_values: ndarray, confidence_levels: Sequence[float] | None = None, point_estimates: Sequence[ndarray] | None = None, true_theta: ndarray | None = None, param_names: Sequence[str] | None = None, colors: Sequence | None = None, title: str | None = None, figsize: Tuple[int, int] | None = None, xlim: Tuple[float, float] | None = (-10, 10), save_fig_path: str | None = None, custom_ax: Axes | None = None) None[source]¶
Plot the confidence distribution (p-value curve) for 1D parameter sweeps.
Creates one figure per observation showing the normalised p-value curve, interval bars for each confidence level, and optional point-estimate / true-parameter markers.
- Parameters:
all_pvalues (np.ndarray) – Raw p-values with shape
(n_obs, 1, n_grid).grid_values (np.ndarray) – Grid of parameter values with shape
(1, n_grid)or(n_grid,).confidence_levels (sequence of float) – Confidence levels (e.g.
[0.9, 0.95]). Each produces one horizontal threshold line and one row of interval bars.point_estimates (sequence of np.ndarray, optional) – One array of shape
(1,)per observation for the point estimate.true_theta (np.ndarray, optional) – True parameters with shape
(n_obs, 1)or(n_obs,).param_names (sequence of str, optional) – Axis label for the parameter; defaults to
['$\theta_1$'].colors (sequence, optional) – Colors for each confidence level; defaults to a rainbow palette.
title (str, optional) – Suptitle applied to every figure.
figsize (tuple of int, optional) –
(width, height)in inches. Defaults to(7, 5).xlim (tuple of float, optional) –
(low, high)x-axis limits. Inferred fromgrid_valuesif omitted.save_fig_path (str, optional) – If given, figures are saved as
<save_fig_path>_<obs_idx>.pngand not displayed interactively.custom_ax (Axes, optional) – If provided, draw into this existing axes instead of creating a new figure. Figure creation,
plt.show(), andsave_fig_pathare all skipped; the caller is responsible for display/saving. Intended for embedding into a larger layout (e.g. a pairplot diagonal).
- lf2i.plot.parameter_regions.plot_posterior_distributions_1D(posterior_estimator, observations: Sequence, credibility_levels: Sequence[float], n_samples: int = 10000, param_dim: int = 0, point_estimates: Sequence[ndarray] | None = None, true_theta: ndarray | None = None, param_names: Sequence[str] | None = None, colors: Sequence | None = None, title: str | None = None, figsize: Tuple[int, int] | None = None, xlim: Tuple[float, float] | None = (-10, 10), n_grid: int = 500, save_fig_path: str | None = None, custom_ax: Axes | None = None) None[source]¶
Plot the marginal posterior KDE with HPD intervals for 1D sweeps.
Mirrors the layout of
plot_confidence_distributions_1D: a normalized density curve, one horizontal threshold line per credibility level (at the normalized density of the HPD boundary), and interval bars below the axis.- Parameters:
posterior_estimator – Object with a
.sample((n_samples,), x=obs)method returning an array of shape(n_samples, d_theta).observations – Sequence of individual observations, one per figure.
credibility_levels – Credibility levels, e.g.
[0.9, 0.95].n_samples – Number of posterior samples to draw per observation.
param_dim – Which parameter dimension to marginalize to for plotting.
point_estimates – Optional sequence of arrays of shape
(d_theta,)or(1,), one per observation.true_theta – Optional array of shape
(n_obs, d_theta)or(n_obs,).param_names – x-axis label; defaults to
['$\theta_1$'].colors – Colors for each credibility level; defaults to a rainbow palette.
title – Suptitle applied to every figure.
figsize –
(width, height)in inches. Defaults to(7, 5).xlim –
(low, high)x-axis limits. Inferred from samples if omitted.n_grid – Number of points used to evaluate the KDE curve.
save_fig_path – If given, figures are saved as
<save_fig_path>_<obs_idx>.png.custom_ax (Axes, optional) – If provided, draw into this existing axes instead of creating a new figure. Figure creation,
plt.show(), andsave_fig_pathare all skipped; the caller is responsible for display/saving. Intended for embedding into a larger layout (e.g. a pairplot diagonal).
- class lf2i.plot.parameter_regions.MergedPatchHandler(num_patches, gap_ratio=0.05, **kwargs)[source]¶
Bases:
HandlerPatch- create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)[source]¶
Return the legend artists generated.
- Parameters:
legend (~matplotlib.legend.Legend) – The legend for which these legend artists are being created.
orig_handle (~matplotlib.artist.Artist or similar) – The object for which these legend artists are being created.
xdescent (int) – The rectangle (xdescent, ydescent, width, height) that the legend artists being created should fit within.
ydescent (int) – The rectangle (xdescent, ydescent, width, height) that the legend artists being created should fit within.
width (int) – The rectangle (xdescent, ydescent, width, height) that the legend artists being created should fit within.
height (int) – The rectangle (xdescent, ydescent, width, height) that the legend artists being created should fit within.
fontsize (int) – The fontsize in pixels. The legend artists being created should be scaled according to the given fontsize.
trans (~matplotlib.transforms.Transform) – The transform that is applied to the legend artists being created. Typically from unit coordinates in the handler box to screen coordinates.
lf2i.plot.power_diagnostics module¶
- lf2i.plot.power_diagnostics.set_size_plot(parameters: ndarray, set_sizes: ndarray, param_dim: int, figsize: Tuple = (10, 8), xlims: Tuple[float] | None = None, ylims: Tuple[float] | None = None, params_labels: Tuple[str] | List[str] | None = None, vmin_vmax: List | Tuple | None = None, custom_ax: Axes | None = None, show_text: bool = False, title: str | None = None, save_fig_path: str | None = None, n_bins: int = 30, n_levels: int = 15) None[source]¶
Plot average confidence set sizes across parameter space.
- lf2i.plot.power_diagnostics.set_size_boxplot(set_sizes: Sequence[ndarray], labels: Sequence[str], whiskers_loc: Tuple[float, float] | float = 1.5, plot_fliers: bool = True, ylim: Sequence[float] | None = (0, 1), save_fig_path: str | None = None, figsize: Tuple = (8, 6)) None[source]¶
Boxplot comparing set sizes across different methods.
lf2i.plot.test_statistic_diagnostics module¶
- lf2i.plot.test_statistic_diagnostics.plot_parameter_relevance(test_statistic: TestStatistic, simulator: Simulator, param_bounds: dict, confidence_level: float, monte_carlo_size: int = 2000, grid_size: int = 25, n_curves: int = 10, seed: int = 0)[source]¶
For each parameter, plot MC critical values as a function of that parameter.
Other parameters are drawn uniformly from their bounds (n_curves draws), and one curve is plotted per draw so the dependence on the swept parameter is visible across the range of the nuisances.