Source code for pwassist.plotting.scan

import itertools
import warnings
from dataclasses import dataclass
from typing import Any, Literal

import matplotlib.axes
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from matplotlib.lines import Line2D
from scipy.stats import gaussian_kde
from uncertainties import ufloat, unumpy

from pwassist.io.binning import EnergyBin, KinematicBin, MassBin, TBin
from pwassist.parser import SCHEMES, NamingScheme
from pwassist.plotting.base import BasePWAPlotter

# Different naming schemes use different reflectivity characters
_POSITIVE_REFLECTIVITY_CHARS = frozenset({"p", "+"})
_NEGATIVE_REFLECTIVITY_CHARS = frozenset({"n", "m", "-"})

# Ordering of orbital angular momentum letters
_L_ORDER = "SPDFGHIKLM"

# Shorthand kinematic variables and their axis labels
_KIN_VARIABLE_XLABELS: dict[str, str] = {
    "m": r"Mass $(GeV)$",
    "t": r"$-t$ $(GeV^2)$",
    "e": r"Beam Energy $(GeV)$",
}
_KIN_VARIABLE_YLABELS: dict[str, str] = {
    "m": r"Events / NUM $(GeV)$",  # replace NUM with bin width in functions
    "t": r"Events / NUM $(GeV^2)$",
    "e": r"Events / NUM $(GeV)$",
}

# Quantum numbers that identify a "wave", i.e. an amplitude with its reflectivity
# removed. Unused quantum numbers in a naming scheme are empty strings, so they are
# harmless for grouping and sorting.
_WAVE_QUANTUM_NUMBERS = ("J", "P", "m", "L")

_REFLECTIVITIES = ("positive", "negative")


@dataclass(frozen=True)
class _Wave:
    """A wave (all quantum numbers but reflectivity) and its available amplitudes"""

    label: str  # LaTeX label without reflectivity
    positive: str | None = None  # positive-reflectivity amplitude name
    negative: str | None = None  # negative-reflectivity amplitude name


def _numeric_sort_key(value: str) -> float:
    """Numeric ordering for quantum-number character or string.

    Args:
        value (str): Quantum-number string to derive sort key from
    Returns:
        float: for sorting the string
    """
    if value in _L_ORDER:
        return float(_L_ORDER.index(value))

    sign_map = {"p": 1.0, "m": -1.0, "n": -1.0}

    if value and value[0] in sign_map and (value[1:] == "" or value[1:].isdigit()):
        magnitude = float(value[1:]) if value[1:] else 1.0
        return sign_map[value[0]] * magnitude

    try:
        return float(value)
    except ValueError:
        return 0.0


def _format_spin_projection(m: str) -> str:
    """Render spin-projection as a signed integer string

    Args:
        m (str): spin-projection e.g. "-1", "+0", "p2", "m", etc.
    Returns:
        str: signed integer e.g. "m1" -> "-1", or original if uninterpretable
    """
    sign_map = {"p": "+", "m": "-", "n": "-"}
    if m and m[0] in sign_map:
        digits = m[1:] or "0"
        return f"{sign_map[m[0]]}{digits}"
    return m


[docs] class ScanPlotter(BasePWAPlotter): """Plotter for all results that scan across a range of bins, e.g. mass, t, etc. Most methods will have an optional 'kin_variable' that specifies with kinematic quantity (mass, t, energy, or some other 'data' dataframe column) they want to scan across. This is paired with a 'stat' argument determining the bin centroid and edges, and optional t/energy/mass bin selections in case the results bundle spans multiple bins for the non-plotted scan variable. """
[docs] def coherent_sum( self, sum_label: str, data_legend: str = "GlueX-I Data", fractional: bool = False, kin_variable: str = "m", stat: Literal["edges", "avg"] = "edges", t_bin: tuple[float, float] | TBin | None = None, energy_bin: tuple[float, float] | EnergyBin | None = None, mass_bin: tuple[float, float] | MassBin | None = None, indices: list[int] | None = None, ax: matplotlib.axes.Axes | None = None, kwargs: dict[str, dict[str, Any]] | None = None, ) -> matplotlib.axes.Axes: """Plot coherent sum group across the bins. A sum group is defined by the quantum numbers that the sum groups together and the amplitude naming scheme. For example, in the `JLme` scheme, one can plot all the available `JLe` coherent sums i.e. those that sum over the spin-projection `m`. If not plotting as fit fractions (fractional='false'), then data points are also plotted. Args: sum_label (str): The label of the coherent sum group to plot. See the `coherent_sums` member of the `Results` class for a list of available sum groups and the amplitudes that belong to each group. data_legend (str): The legend label for the data points. Defaults to "GlueX-I Data". fractional (bool): Whether to plot the sums as a fraction of the total intensity. Defaults to False. kin_variable (str): Shorthand ("m", "t", "e") or exact 'data' dataframe column name for the kinematic variable to plot against. Default to 'm' (mass). stat (Literal['edges', 'avg']): Whether x-value/error is from the bin center and (high-low)/2 'edges' (default) or from the actual bin average and rms of the underlying data. t_bin (tuple[float, float] | TBin | None): Fixes the t bin to plot from if the results span multiple t bins. If only 1 t bin is available, specification is unnecessary. Defaults to None. energy_bin (tuple[float,float] | EnergyBin | None): Fixes the beam energy bin to plot from if the results span multiple energy bins. If only 1 energy bin is available, specification is unnecessary. Defaults to None. mass_bin (tuple[float,float] | MassBin | None): Fixes the mass bin to plot from if the results span multiple mass bins. If only 1 mass bin is available, specification is unnecessary. Defaults to None. indices (list[int] | None): Optional list of positions within the resolved kinematic bin to select specific bins. Defaults to None. ax (matplotlib.axes.Axes | None): Optional axes to plot on. If None, a new figure and axes will be created. kwargs (dict[str, dict[str, Any]] | None): Optional dictionary of keyword arguments for each coherent sum, passed directly to ax.errorbar Raises: KeyError: If the specified sum_label is not found in the coherent sums, or or if stat='avg' but the requested corresponding columns are not present in the 'data' dataframe. ValueError: If a bin is given for the dimension being scanned over, or if multiple bins are present on a non-scammed dimension, leaving an ambiguous plot range. """ if sum_label not in self.results.coherent_sums: raise KeyError( f"Sum label '{sum_label}' not found in coherent sums." f" Available sum labels: {list(self.results.coherent_sums.keys())}" ) coherent_sums = self.results.coherent_sums[sum_label] plot_columns = ( list(coherent_sums) + ["intensity", "ac_intensity"] if fractional else coherent_sums ) fit_df, data_df, x_label, y_label = self._scan_dataframes( columns=plot_columns, kin_variable=kin_variable, stat=stat, t_bin=t_bin, energy_bin=energy_bin, mass_bin=mass_bin, indices=indices, ) # default to Dark2 colormap, and cycle if more columns than colors colors = plt.get_cmap("Dark2").colors # type: ignore colors = list(itertools.islice(itertools.cycle(colors), len(coherent_sums))) default_kwargs = { k: { "marker": ".", "linestyle": "", "alpha": 0.7, "color": colors[coherent_sums.index(k)], } for k in coherent_sums } for k in default_kwargs.keys(): default_kwargs[k].update(kwargs.get(k, {}) if kwargs else {}) kwargs = default_kwargs if fractional: y_label = ( y_label.replace("Events", "Fit Fraction") if "Events" in y_label else "Fit Fraction" ) with self._style(): fig, ax = ( plt.subplots(layout="constrained") if ax is None else (ax.get_figure(), ax) ) if not fractional: # plot the data points with error bars, using the appropriate events # column based on whether the results are acceptance-corrected or not if self.results.is_acc_corrected: data_points = unumpy.uarray( data_df["ac_events"], data_df["ac_events_err"] ) else: data_points = unumpy.uarray( data_df["events"], data_df["events_err"] ) ax.errorbar( x=data_df["x_center"], xerr=data_df["x_err"], y=unumpy.nominal_values(data_points), yerr=unumpy.std_devs(data_points), label=data_legend, marker=".", linestyle="", color="black", ) # plot each coherent sum with error bars for sum_idx, coh_sum in enumerate(coherent_sums): label = rf"${self.results.parser.to_latex(coh_sum, sum_label)}$" if "label" not in kwargs[coh_sum]: kwargs[coh_sum]["label"] = label if fractional: intensity = ( unumpy.uarray( fit_df["ac_intensity"], fit_df["ac_intensity_err"] ) if self.results.is_acc_corrected else unumpy.uarray(fit_df["intensity"], fit_df["intensity_err"]) ) y = ( unumpy.uarray(fit_df[coh_sum], fit_df[f"{coh_sum}_err"]) / intensity ) y_vals = unumpy.nominal_values(y) y_errs = unumpy.std_devs(y) else: y_vals = fit_df[coh_sum] y_errs = fit_df[f"{coh_sum}_err"] ax.errorbar( x=data_df["x_center"], xerr=data_df["x_err"], y=y_vals, yerr=y_errs, **kwargs[coh_sum], ) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.set_ylim(bottom=0) ax.legend() return ax
[docs] def amplitudes( self, fractional: bool = False, sharey: bool = False, reflectivity: Literal["positive", "negative", "all"] = "all", kin_variable: str = "m", stat: Literal["edges", "avg"] = "edges", t_bin: tuple[float, float] | TBin | None = None, energy_bin: tuple[float, float] | EnergyBin | None = None, mass_bin: tuple[float, float] | MassBin | None = None, indices: list[int] | None = None, axs: np.ndarray | None = None, kwargs: dict[str, dict[str, Any]] | None = None, ) -> np.ndarray: """Plot a grid of amplitudes, organized by spin (rows) and projection (columns) This plot will create a grid of all amplitudes plotted as a function of the selected kinematic variable, with the rows corresponding to the spin+parity+angular momenta combo (J^P L) and the columns corresponding to the spin-projection m. Any quantum numbers unavailable due to the naming scheme are dropped. Reflectivities are plotted together in the same plot, with the option to select only positive or negative reflectivities. Args: fractional (bool): Whether to plot the amplitudes as a fraction of the total intensity. Defaults to False. sharey (bool): Whether to share the y-axis across all amplitude plots. Defaults to False. reflectivity (Literal["positive", "negative", "all"]): Which reflectivity amplitudes to plot. Defaults to "all". kin_variable (str): Shorthand ("m", "t", "e") or exact 'data' dataframe column name for the kinematic variable to plot against. Defaults to "m" (mass). stat (Literal['edges', 'avg']): Whether x-value/error is from the bin center and (high-low)/2 'edges' (default) or from the actual bin average and rms of the underlying data. t_bin (tuple[float, float] | TBin | None): Fixes the t bin to plot from if the results span multiple t bins. If only 1 t bin is available, specification is unnecessary. Defaults to None. energy_bin (tuple[float,float] | EnergyBin | None): Fixes the beam energy bin to plot from if the results span multiple energy bins. If only 1 energy bin is available, specification is unnecessary. Defaults to None. mass_bin (tuple[float,float] | EnergyBin | None): Fixes the mass bin to plot from if the results span multiple mass bins. If only 1 mass bin is available, specification is unnecessary. Defaults to None. indices (list[int] | None): Optional list of positions within the resolved kinematic bin to select specific bins. Defaults to None. axs (np.ndarray | None): Optional array of axes to plot on. If None, a new figure and axes will be created. Note that one must be careful that the axes shape matches the expected shape. kwargs (dict[str, dict[str, Any]] | None): Optional dictionary of keyword arguments to customize the plot appearance. Recognized keys are "positive" and "negative" mapping to a dict of matplotlib 'errorbar' kwargs that override the defaults for the respective reflectivity amplitudes. e.g. {"positive": {"color": "red"}, "negative": {"color": "blue"}}. Defaults to None. Returns: np.ndarray: The array of axes objects containing the amplitude plots. Raises: ValueError: If the reflectivity argument is not one of "positive", "negative", or "all". If no naming scheme could be determined from the amplitudes, or if a bin is given for the dimension being scanned over, or if multiple bins are present along a non-scanned dimension, leaving an ambiguous plot range. IndexError: If the provided axes shape does not match the expected shape based on the number of amplitudes. """ if reflectivity not in ["positive", "negative", "all"]: raise KeyError( f"Invalid reflectivity value: {reflectivity}. Must be one of " "'positive', 'negative', or 'all'." ) amps = list(self.results.amplitudes) if not amps: raise KeyError("No amplitudes found in the results to plot.") # resolve naming scheme from the amplitudes (common across all, so select one) parser = self.results.parser scheme = parser.requested_scheme if scheme == NamingScheme.AUTO: scheme = parser.infer_naming_scheme(amps[0]) if scheme == NamingScheme.AUTO: raise ValueError("Could not determine naming scheme from amplitudes.") scheme_def = SCHEMES[scheme] # Determine the row and column quantum numbers based on the naming scheme. row_quantum_numbers = tuple( qn for qn in scheme_def.single_amplitudes if qn not in ("m", "e") ) row_group_key = "".join(row_quantum_numbers) parsed_amps = [(amp, parser.parse_amplitude(amp)) for amp in amps] def _keep(parsed) -> bool: if reflectivity == "all": return True if reflectivity == "positive": return parsed.e in _POSITIVE_REFLECTIVITY_CHARS return parsed.e in _NEGATIVE_REFLECTIVITY_CHARS parsed_amps = [(amp, parsed) for amp, parsed in parsed_amps if _keep(parsed)] if not parsed_amps: raise ValueError( f"No amplitudes found for reflectivity '{reflectivity}'. " f"Available amplitudes: {amps}" ) row_groups: dict[tuple[str, ...], list[tuple[str, Any]]] = {} col_values: set[str] = set() for amp, parsed in parsed_amps: row_key = tuple(parsed.get(qn) for qn in row_quantum_numbers) row_groups.setdefault(row_key, []).append((amp, parsed)) col_values.add(parsed.m) sorted_rows = sorted( row_groups, key=lambda rk: tuple(_numeric_sort_key(qn) for qn in rk) ) sorted_cols = sorted(col_values, key=_numeric_sort_key) nrows, ncols = len(sorted_rows), len(sorted_cols) plot_columns = [amp for amp, _ in parsed_amps] if fractional: plot_columns.extend(["intensity", "ac_intensity"]) fit_df, data_df, x_label, y_label = self._scan_dataframes( columns=plot_columns, kin_variable=kin_variable, stat=stat, t_bin=t_bin, energy_bin=energy_bin, mass_bin=mass_bin, indices=indices, ) # default styling default_kwargs = { "positive": { "marker": ".", "linestyle": "", "alpha": 0.7, "color": "tab:red", }, "negative": { "marker": ".", "linestyle": "", "alpha": 0.7, "color": "tab:blue", }, } if fractional: y_label = ( y_label.replace("Events", "Fit Fraction") if "Events" in y_label else "Fit Fraction" ) max_value: float = 0.0 # for resetting y_lim later # mark the grid cells that will fill, so that labels go on these present = np.zeros((nrows, ncols), dtype=bool) for row_idx, row_key in enumerate(sorted_rows): for col_idx, col_value in enumerate(sorted_cols): present[row_idx, col_idx] = any( parsed.m == col_value for _, parsed in row_groups[row_key] ) first_col_in_row = [int(np.flatnonzero(present[i])[0]) for i in range(nrows)] first_row_in_col = [int(np.flatnonzero(present[:, j])[0]) for j in range(ncols)] with self._style(): if axs is None: fig, axs = plt.subplots( nrows=nrows, ncols=ncols, sharey=sharey, squeeze=False, figsize=(4 * ncols, 3 * nrows), layout="constrained", ) else: axs = np.asarray(axs) try: axs = axs.reshape(nrows, ncols) except ValueError: raise IndexError( f"Provided axes shape {axs.shape} does not match expected " f"shape ({nrows}, {ncols}) based on the number of amplitudes." ) fig = axs.flat[0].figure for row_idx, row_key in enumerate(sorted_rows): row_label = self.results.parser.to_latex( "".join(row_key), row_group_key ) for col_idx, col_value in enumerate(sorted_cols): ax = axs[row_idx, col_idx] if not present[row_idx, col_idx]: ax.set_visible(False) continue amps_here = [ (amp, parsed) for amp, parsed in row_groups[row_key] if parsed.m == col_value ] # plot positive reflectivity first amps_here.sort( key=lambda item: item[1].e not in _POSITIVE_REFLECTIVITY_CHARS ) for amp, parsed in amps_here: refl_kind = ( "positive" if parsed.e in _POSITIVE_REFLECTIVITY_CHARS else "negative" ) if fractional: values = unumpy.uarray(fit_df[amp], fit_df[f"{amp}_err"]) intensity = ( unumpy.uarray( fit_df["ac_intensity"], fit_df["ac_intensity_err"] ) if self.results.is_acc_corrected else unumpy.uarray( fit_df["intensity"], fit_df["intensity_err"] ) ) fraction = values / intensity y = unumpy.nominal_values(fraction) yerr = unumpy.std_devs(fraction) else: y = fit_df[amp].to_numpy() yerr = fit_df[f"{amp}_err"].to_numpy() max_value = max(max_value, y.max() + y.max() * 0.1) default_kwargs[refl_kind][ "label" ] = rf"${self.results.parser.to_latex(amp)}$" for refl in ("positive", "negative"): default_kwargs[refl].update( kwargs.get(refl, {}) if kwargs else {} ) ax.errorbar( x=data_df["x_center"], xerr=data_df["x_err"], y=y, yerr=yerr, **default_kwargs[refl_kind], ) ax.set_ylim(bottom=0) ax.legend(fontsize="x-small") # row label J^P L on y-axis of first existing plot if col_idx == first_col_in_row[row_idx]: ax.set_ylabel( rf"${row_label}$", loc="center", labelpad=10, ) ax.tick_params(labelleft=True) # column label "m" on title of first existing plot if row_idx == first_row_in_col[col_idx]: ax.set_title(rf"$m={_format_spin_projection(col_value)}$") if row_idx == nrows - 1: ax.set_xlabel(x_label) fig.supylabel(y_label, fontsize="large", weight="bold") # adjust y limits after plotting if using common axis if sharey: for ax in axs.flatten(): ax.set_ylim(top=max_value) return axs
[docs] def interference( self, amp1: str, amp2: str, indices: list[int] | None = None, amp1_kwargs: dict[str, Any] | None = None, amp2_kwargs: dict[str, Any] | None = None, amp_ax: matplotlib.axes.Axes | None = None, phase_ax: matplotlib.axes.Axes | None = None, ) -> np.ndarray: """Plot two amplitudes and their interference phase as a function of mass. Args: amp1 (str): The label of the first amplitude to plot. amp2 (str): The label of the second amplitude to plot. indices (list[int] | None): Optional list of indices to select specific mass bins. If None, all bins will be plotted. amp1_kwargs (dict[str, Any] | None): Optional dictionary of keyword arguments to customize the appearance of the first amplitude plot. amp2_kwargs (dict[str, Any] | None): Optional dictionary of keyword arguments to customize the appearance of the second amplitude plot. amp_ax (matplotlib.axes.Axes | None): Optional axes to plot the amplitudes on. If None, a new figure and axes will be created. phase_ax (matplotlib.axes.Axes | None): Optional axes to plot the phase difference on. If None, a new figure and axes will be created. Returns: np.ndarray: The array of axes objects containing the amplitude and phase difference plots. Raises: KeyError: If either phase is not in the fit results. ValueError: If only one of amp_ax or phase_ax is provided, but not both """ if amp1 not in self.results.fit.columns: raise KeyError( f"Amplitude '{amp1}' not found in fit results. " f"Available amplitudes: {list(self.results.fit.columns)}" ) if amp2 not in self.results.fit.columns: raise KeyError( f"Amplitude '{amp2}' not found in fit results. " f"Available amplitudes: {list(self.results.fit.columns)}" ) if amp_ax is None and phase_ax is None: fig, axs = plt.subplots( nrows=2, ncols=1, sharex=True, gridspec_kw={"wspace": 0.0, "hspace": 0.07}, height_ratios=[3, 1], layout="constrained", ) elif amp_ax is None or phase_ax is None: raise ValueError( "Both amp_ax and phase_ax must be provided if one is specified." ) else: axs = np.array([amp_ax, phase_ax]) # TODO: obtain the relevant dataframes, and plot their amplitude and phase # differences on the appropriate axes. Use the provided kwargs for # customization. return axs
[docs] def model_matrix( self, stat: Literal["edges", "avg"] = "edges", t_bin: tuple[float, float] | TBin | None = None, energy_bin: tuple[float, float] | EnergyBin | None = None, indices: list[int] | None = None, axs: np.ndarray | None = None, kwargs: dict[str, dict[str, Any]] | None = None, ) -> np.ndarray: """Plot the entire model behavior as a function of mass in a matrix of plots Each row/column is a "wave": an amplitude with its reflectivity removed (e.g. J^P L_m). The diagonal shows the intensity of each wave, with both reflectivities overlaid. The off-diagonal plots show the phase difference between the row and column waves. The upper triangle is for the positive reflectivity amplitudes, and the lower triangle for the negative. Since the sign of a phase difference is ambiguous, both +|phase| and -|phase| are drawn. Uncertainties are drawn as filled bands, as the subplots are small. Args: stat (Literal['edges', 'avg']): Whether x-value is from the bin center 'edges' (default) or from the actual bin average of the underlying data. t_bin (tuple[float, float] | TBin | None): Fixes the t bin to plot from if the results span multiple t bins. If only 1 t bin is available, specification is unnecessary. Defaults to None. energy_bin (tuple[float,float] | EnergyBin | None): Fixes the beam energy bin to plot from if the results span multiple energy bins. If only 1 energy bin is available, specification is unnecessary. Defaults to None. indices (list[int] | None): Optional list of positions within the resolved mass scan to select specific bins. If None, all bins will be plotted. axs (np.ndarray | None): Optional array of axes to plot on. If None, a new figure and axes will be created. Note that one must be careful that the axes shape matches the expected shape (n_waves, n_waves). kwargs (dict[str, dict[str, Any]] | None): Optional dictionary of matplotlib 'plot' kwargs overriding the defaults for each reflectivity, e.g. {"positive": {"color": "red"}, "negative": {"linewidth": 2}}. The uncertainty band takes its color from the "color" entry. Returns: np.ndarray: The (n_waves, n_waves) array of axes objects containing the intensity and phase difference plots. Raises: KeyError: If no amplitudes are found in the results. IndexError: If the provided axes shape does not match the expected shape based on the number of waves. ValueError: If multiple t or energy bins are present and not fixed, leaving an ambiguous plot range. """ waves = self._group_waves() n_waves = len(waves) # Resolve the phase column for every off-diagonal cell, which also tells us # which cells have nothing to plot. phase_columns = { (row, col): self._matrix_phase_column(waves, row, col) for row, col in itertools.permutations(range(n_waves), 2) } amp_columns = [ amp for wave in waves for amp in (wave.positive, wave.negative) if amp ] fit_df, data_df, x_label, _ = self._scan_dataframes( columns=amp_columns + [p for p in phase_columns.values() if p], kin_variable="m", stat=stat, t_bin=t_bin, energy_bin=energy_bin, indices=indices, ) x = data_df["x_center"].to_numpy() xerr = data_df["x_err"].to_numpy() styles = { "positive": {"color": "tab:red", "linestyle": "none", "marker": "."}, "negative": {"color": "tab:blue", "linestyle": "none", "marker": "."}, } for refl in _REFLECTIVITIES: styles[refl].update((kwargs or {}).get(refl, {})) # all intensities share one scale, as do all phases max_intensity = fit_df[amp_columns].to_numpy().max() with self._style(): if axs is None: fig, axs = plt.subplots( nrows=n_waves, ncols=n_waves, sharex=True, squeeze=False, figsize=(3 * n_waves, 2.5 * n_waves), layout="constrained", ) else: axs = np.asarray(axs) try: axs = axs.reshape(n_waves, n_waves) except ValueError: raise IndexError( f"Provided axes shape {axs.shape} does not match expected " f"shape ({n_waves}, {n_waves}) based on the number of waves." ) fig = axs[0, 0].get_figure() for row, col in itertools.product(range(n_waves), repeat=2): ax = axs[row, col] if row == col: for refl in _REFLECTIVITIES: if amp := getattr(waves[row], refl): ax.errorbar( x=x, xerr=xerr, y=fit_df[amp].to_numpy(), yerr=fit_df[f"{amp}_err"].to_numpy(), **styles[refl], ) ax.set_ylim(0, 1.05 * max_intensity) # emphasize the diagonal for spine in ax.spines.values(): spine.set_linewidth(2) else: refl = "positive" if col > row else "negative" if phase := phase_columns[row, col]: value = fit_df[phase].abs().to_numpy() err = fit_df[f"{phase}_err"].abs().to_numpy() # sign of the phase difference is ambiguous, so show both ax.errorbar(x=x, xerr=xerr, y=value, yerr=err, **styles[refl]) ax.errorbar(x=x, xerr=xerr, y=-value, yerr=err, **styles[refl]) ax.set_ylim(-180, 180) ax.set_yticks([-180, -90, 0, 90, 180]) # label the outer edge with waves, and drop redundant tick labels if row == 0: ax.set_title(rf"${waves[col].label}$", fontsize="large") if col == 0: ax.set_ylabel(rf"${waves[row].label}$", fontsize="large") else: ax.tick_params(labelleft=False) ax.tick_params(labelsize="x-small") # diagonal intensities share a scale, so only label the first for row in range(1, n_waves): axs[row, row].tick_params(labelleft=False) # the last column carries the right-hand tick labels: phases (degrees) in # the off-diagonal cells, and the intensity scale for the bottom-right # diagonal cell, mirroring the upper-left one if n_waves > 1: for row in range(n_waves): axs[row, -1].tick_params(right=True, labelright=True) fig.supxlabel(x_label) fig.legend( handles=[ Line2D([], [], color=styles[refl]["color"], label=label) for refl, label in zip( _REFLECTIVITIES, (r"$\varepsilon=+1$", r"$\varepsilon=-1$") ) ], loc="outside upper right", ) return axs
[docs] def convergence_rate( self, kin_variable: str = "m", stat: Literal["edges", "avg"] = "edges", t_bin: tuple[float, float] | TBin | None = None, energy_bin: tuple[float, float] | EnergyBin | None = None, mass_bin: tuple[float, float] | MassBin | None = None, indices: list[int] | None = None, ax: matplotlib.axes.Axes | None = None, kwargs: dict[str, Any] | None = None, ) -> matplotlib.axes.Axes: """Plot the convergence rate of the fit across bins. Requires randomized fits to be in the results. Plots the percentage of successful, failed, and converged-with-bad-error-matrix fits across the selected kinematic bins. This can be useful for diagnosing issues with the fit and understanding the stability of the fit across the mass range. Args: kin_variable (str): Shorthand ("m", "t", "e") or exact 'data' dataframe column name for the kinematic variable to plot against. Default to 'm' (mass). stat (Literal['edges', 'avg']): Whether x-value/error is from the bin center and (high-low)/2 'edges' (default) or from the actual bin average and rms of the underlying data. t_bin (tuple[float, float] | TBin | None): Fixes the t bin to plot from if the results span multiple t bins. If only 1 t bin is available, specification is unnecessary. Defaults to None. energy_bin (tuple[float,float] | EnergyBin | None): Fixes the beam energy bin to plot from if the results span multiple energy bins. If only 1 energy bin is available, specification is unnecessary. Defaults to None. mass_bin (tuple[float,float] | MassBin | None): Fixes the mass bin to plot from if the results span multiple mass bins. If only 1 mass bin is available, specification is unnecessary. Defaults to None. indices (list[int] | None): Optional list of positions within the resolved kinematic bin to select specific bins. Defaults to None. ax (matplotlib.axes.Axes | None): Optional axes to plot on. If None, a new figure and axes will be created. kwargs (dict[str, Any] | None): Optional dictionary of keyword arguments to customize the plot appearance. Organized per fit status type as 'successful', 'bad error matrix', 'failed', so given value lists should be in the same ordering e.g. "labels" : ["Success", "Bad Error", "Failed"]. Returns: matplotlib.axes.Axes: The axes object containing the convergence rate plot. Raises: KeyError: If randomized fits are not available in the results. Todo: - change this style to mimic this example https://matplotlib.org/stable/gallery/lines_bars_and_markers/horizontal_barchart_distribution.html """ if self.results.randomized is None: raise KeyError("Randomized fits are required to plot convergence rate.") fit_status_columns = ["eMatrixStatus", "lastMinuitCommandStatus"] df, data_df, x_label, _ = self._scan_dataframes( columns=fit_status_columns, frame="randomized", kin_variable=kin_variable, stat=stat, t_bin=t_bin, energy_bin=energy_bin, mass_bin=mass_bin, indices=indices, ) successful_fits = ( df.groupby("bin_id") .apply( ( lambda x: ( (x["eMatrixStatus"] == 3) & (x["lastMinuitCommandStatus"] == 0) ).sum() ) ) .to_numpy() ) bad_eMatrix_fits = ( df.groupby("bin_id") .apply( ( lambda x: ( (x["eMatrixStatus"] != 3) & (x["lastMinuitCommandStatus"] == 0) ).sum() ) ) .to_numpy() ) failed_fits = ( df.groupby("bin_id") .apply((lambda x: (x["lastMinuitCommandStatus"] != 0).sum())) .to_numpy() ) max_length = max(len(successful_fits), len(bad_eMatrix_fits), len(failed_fits)) if max_length == 0: raise ValueError( "No labelled fit statuses could be found, check validity of the" " randomized dataframe" ) successful_fits = ( np.zeros(max_length) if len(successful_fits) == 0 else successful_fits ) bad_eMatrix_fits = ( np.zeros(max_length) if len(bad_eMatrix_fits) == 0 else bad_eMatrix_fits ) failed_fits = np.zeros(max_length) if len(failed_fits) == 0 else failed_fits default_kwargs = { "colors": ["tab:blue", "tab:orange", "tab:red"], "labels": ["Success", "Inaccurate Errors", "Failed"], } default_kwargs.update(kwargs or {}) kwargs = default_kwargs with self._style(): fig, ax = ( plt.subplots(layout="constrained") if ax is None else (ax.get_figure(), ax) ) bottom = np.zeros(len(successful_fits)) for i, fit_status in enumerate( [successful_fits, bad_eMatrix_fits, failed_fits] ): ax.bar( data_df["x_center"], fit_status, data_df["x_err"], label=kwargs["labels"][i], color=kwargs["colors"][i], bottom=bottom, ) bottom += fit_status ax.set_xlabel(x_label) ax.set_ylabel(r"# of fits") ax.set_ylim(bottom=0) ax.legend() return ax
[docs] def likelihood_distribution( self, delta_lnL_groups: tuple[float, ...] | None = None, kin_variable: str = "m", stat: Literal["edges", "avg"] = "edges", t_bin: tuple[float, float] | TBin | None = None, energy_bin: tuple[float, float] | EnergyBin | None = None, mass_bin: tuple[float, float] | MassBin | None = None, indices: list[int] | None = None, ax: matplotlib.axes.Axes | None = None, kwargs: dict[str, Any] | None = None, ) -> matplotlib.axes.Axes: """Plot the number of fits that fall within a group of delta lnL ranges. Each kinematic bin will plot len(delta_lnLgroups)-1 bars, where each bar corresponds to the number of fits that fall within the delta lnL range defined by the delta_lnL_groups. For example, if delta_lnL_groups = (0, 1, 5, np.inf) ( the default setting), then the first bar will be the number of fits with delta lnL in (0, 1], and so on. The delta lnL is calculated as the difference between a randomized fit's likelihood and the minimum likelihood in that bin. Args: delta_lnL_groups (tuple[float, ...] | None, optional): Groups of ranges to count delta lnL within. Defaults to None. kin_variable (str): Shorthand ("m", "t", "e") or exact 'data' dataframe column name for the kinematic variable to plot against. Default to 'm' (mass). stat (Literal['edges', 'avg']): Whether x-value/error is from the bin center and (high-low)/2 'edges' (default) or from the actual bin average and rms of the underlying data. t_bin (tuple[float, float] | TBin | None): Fixes the t bin to plot from if the results span multiple t bins. If only 1 t bin is available, specification is unnecessary. Defaults to None. energy_bin (tuple[float,float] | EnergyBin | None): Fixes the beam energy bin to plot from if the results span multiple energy bins. If only 1 energy bin is available, specification is unnecessary. Defaults to None. mass_bin (tuple[float,float] | MassBin | None): Fixes the mass bin to plot from if the results span multiple mass bins. If only 1 mass bin is available, specification is unnecessary. Defaults to None. indices (list[int] | None): Optional list of positions within the resolved kinematic bin to select specific bins. Defaults to None. ax (matplotlib.axes.Axes | None): Optional axes to plot on. If None, a new figure and axes will be created. kwargs (dict[str, Any] | None): Optional dictionary of keyword arguments to customize the plot appearance. Passed directly to ax.grouped_bar() call, so see that method for details. Defaults to None. Raises: KeyError: if no randomized fit results are available. Returns: matplotlib.axes.Axes: The axes object containing the likelihood distribution plot. """ if self.results.randomized is None: raise KeyError( "Randomized fits are required to plot the likelihood distribution." ) df, data_df, x_label, _ = self._scan_dataframes( columns=["likelihood"], frame="randomized", kin_variable=kin_variable, stat=stat, t_bin=t_bin, energy_bin=energy_bin, mass_bin=mass_bin, indices=indices, ) if delta_lnL_groups is None: delta_lnL_groups = (0.0, 1.0, 5.0, np.inf) # list of length N kinematic bins that tracks the number of fits that fall # within the likelihood ranges indicated by delta_lnL_groups. Each entry is a # tuple of length len(delta_lnL_groups)-1 grouped_counts: list[tuple[float, ...]] = [] percentages: list[tuple[float, ...]] = [] # similar, but % of total rand fits for bin_id, group in df.groupby("bin_id"): # Initialize counts for each likelihood range counts = [0] * (len(delta_lnL_groups) - 1) min_likelihood = np.min(group["likelihood"]) for _, row in group.iterrows(): delta_lnL = row["likelihood"] - min_likelihood for i, upper_lim in enumerate(delta_lnL_groups[1:], start=1): lower_lim = delta_lnL_groups[i - 1] if delta_lnL <= upper_lim and delta_lnL > lower_lim: counts[i - 1] += 1 total_in_group = len(group) if total_in_group > 0: percentages.append( tuple(count / total_in_group * 100 for count in counts) ) else: percentages.append(tuple(0.0 for _ in counts)) grouped_counts.append(tuple(counts)) with self._style(): fig, ax = ( plt.subplots(layout="constrained") if ax is None else (ax.get_figure(), ax) ) groups = { rf"{delta_lnL_groups[i]} < $\Delta(-2ln\mathcal{{L}})$" rf" $\leq$ {delta_lnL_groups[i + 1]}": [ counts[i] for counts in grouped_counts ] for i in range(len(delta_lnL_groups) - 1) } default_kwargs = { "colors": ["tab:blue", "tab:orange", "tab:red"], "labels": list(groups.keys()), "group_spacing": 1, } default_kwargs.update(kwargs or {}) kwargs = default_kwargs plot = ax.grouped_bar( heights=groups.values(), # type: ignore tick_labels=[f"{x:.3f}" for x in data_df["x_center"].to_list()], **kwargs, ) # label each bar with its percentage of fits in that likelihood range for idx, container in enumerate(plot.bar_containers): # type: ignore ax.bar_label( container, labels=[ f"{percentages[j][idx]:.1f}%" for j in range(len(percentages)) ], label_type="edge", rotation=90, ) ax.set_xlabel(x_label) ax.set_ylabel(r"# of fits") ax.set_ylim(bottom=0, top=ax.get_ylim()[1] * 1.25) # add room for legend ax.legend(ncols=int(np.ceil(np.sqrt(len(groups))))) return ax
[docs] def ridgeline( self, columns: list[str], overlap: float = 1.5, scale: Literal["global", "ridge"] = "global", equidistant: bool = False, bw_method: str | float | None = None, n_points: int = 256, cmap: str = "Dark2", kin_variable: str = "m", stat: Literal["edges", "avg"] = "edges", t_bin: tuple[float, float] | TBin | None = None, energy_bin: tuple[float, float] | EnergyBin | None = None, mass_bin: tuple[float, float] | MassBin | None = None, indices: list[int] | None = None, ax: matplotlib.axes.Axes | None = None, kwargs: dict[str, Any] | None = None, ) -> matplotlib.axes.Axes: """Create a ridgeline (joyplot) of bootstrap distributions across a scan. Each kinematic bin gets one "ridge" per column, a KDE of the bootstrap distribution for the column, drawn on a baseline located at the bin's position along the scan variable (y-axis). The column values are on the x-axis. Ridges from lower values are drawn in front of those from higher values. Args: columns (list[str]): Columns of the 'bootstrap' frame to plot. Each is given a different color, in the order given by cmap. overlap (float, optional): Control how much neighboring ridges overlap, as the height of the teallest ridge in units of baseline spacing (median distance between adjacent bins). overlap=1.0: tallest ridge just touches the next baseline. overlap<1.0 leaves gaps. Defaults to 1.5. scale (Literal['global', 'ridge']): 'global' (default) scales all KDEs by a single common factor, so narrower distributions appear taller. 'ridge' scale each KDE to the same peak height, useful when widths vary largely between bins or columns. equidistant (bool): If True, the baselines are evenly spaced, one step per bin in scan order. y tick-labels still show each bin's value as usual. If False (default), baselines sit at actual bin positions at scale. bw_method (str | float | None, optional): KDE bandwidth, passed to scipy.stats.gaussian_kde. Can be 'scott' or 'silverman', or a scalar bandwidth factor. Defaults to None, or Scott's rule. n_points (int, optional): Number of x points each KDE is evaluated on. Defaults to 256. cmap (str, optional): Name of qualitative matplotlib colormap used to color the columns. Cycles if there are more columns than colors. Defaults to "Dark2". kin_variable (str): Shorthand ("m", "t", "e") or exact 'data' dataframe column name for the kinematic variable to plot against. Default to 'm' (mass). stat (Literal['edges', 'avg']): Whether x-value/error is from the bin center and (high-low)/2 'edges' (default) or from the actual bin average and rms of the underlying data. t_bin (tuple[float, float] | TBin | None): Fixes the t bin to plot from if the results span multiple t bins. If only 1 t bin is available, specification is unnecessary. Defaults to None. energy_bin (tuple[float,float] | EnergyBin | None): Fixes the beam energy bin to plot from if the results span multiple energy bins. If only 1 energy bin is available, specification is unnecessary. Defaults to None. mass_bin (tuple[float,float] | MassBin | None): Fixes the mass bin to plot from if the results span multiple mass bins. If only 1 mass bin is available, specification is unnecessary. Defaults to None. indices (list[int] | None): Optional list of positions within the resolved kinematic bin to select specific bins. Defaults to None. ax (matplotlib.axes.Axes | None): Optional axes to plot on. If None, a new figure and axes will be created. kwargs (dict[str, Any] | None): Optional dictionary of keyword arguments to customize the plot appearance. Recognized keys are 'colors' (list of one color per column, overriding 'cmap'), 'alpha' (fill transparency) and 'linewidth' (KDE outline width, default 1.0). Returns: matplotlib.axes.Axes: The axes object containing the ridgeline plot Raises: KeyError: If bootstrap dataframe is not in the results, or any requested columns are not found. ValueError: If no columns are requested, 'overlap' < 0, 'scale' is not in list options, 'n_points' < 2, or no KDE can be computed. """ if self.results.bootstrap is None: raise KeyError( "Bootstrap dataframe is required to create the ridgeline plot" ) if not columns: raise ValueError("At least one column must be requested") columns = list(dict.fromkeys(columns)) missing = [c for c in columns if c not in self.results.bootstrap.columns] if missing: raise KeyError( f"Columns {missing} not found in bootstrap dataframe. Available columns" f" {list(self.results.bootstrap.columns)}" ) if overlap <= 0: raise ValueError(f"overlap must be > 0, got {overlap}") if scale not in ("global", "ridge"): raise ValueError(f"scale must be 'global' or 'ridge', got '{scale}'") if n_points < 2: raise ValueError(f"n_points must be at least 2, got {n_points}") df, data_df, y_label, _ = self._scan_dataframes( columns=columns, frame="bootstrap", kin_variable=kin_variable, stat=stat, t_bin=t_bin, energy_bin=energy_bin, mass_bin=mass_bin, indices=indices, ) color_map = plt.get_cmap(cmap) palette = ( list(color_map.colors) # type: ignore if hasattr(color_map, "colors") else list(color_map(np.linspace(0, 1, len(columns)))) ) default_kwargs = { "colors": list(itertools.islice(itertools.cycle(palette), len(columns))), "alpha": 0.6, "linewidth": 1.0, } default_kwargs.update(kwargs or {}) kwargs = default_kwargs # common x grid for KDEs all_values = df[columns].to_numpy(dtype=float) lo, hi = all_values.min(), all_values.max() pad = 0.1 * (hi - lo) if hi > lo else 0.5 x_grid = np.linspace(lo - pad, hi + pad, n_points) # baseline of each ridge and their spacing scan_values = data_df["x_center"].to_numpy(dtype=float) bin_ids = data_df["bin_id"].to_numpy() if equidistant: baselines = np.argsort(np.argsort(scan_values, kind="stable")).astype(float) spacing = 1.0 else: baselines = scan_values if len(baselines) > 1: spacing = float(np.median(np.diff(np.sort(baselines)))) else: spacing = 2.0 * float(data_df["x_err"].iloc[0]) if not np.isfinite(spacing) or spacing <= 0: spacing = 1.0 height = overlap * spacing # compute KDE of each column in each bin grouped = dict(tuple(df.groupby("bin_id"))) ridges: list[tuple[float, int, np.ndarray]] = [] skipped: list[tuple[Any, str]] = [] for baseline, bin_id in zip(baselines, bin_ids): group = grouped.get(bin_id) if group is None: continue for col_idx, col in enumerate(columns): values = group[col].to_numpy(dtype=float) values = values[np.isfinite(values)] if values.size < 2 or np.ptp(values) == 0: skipped.append((bin_id, col)) continue density = gaussian_kde(values, bw_method=bw_method)(x_grid) ridges.append((float(baseline), col_idx, density)) if skipped: warnings.warn( f"Skipped {len(skipped)} (bin_id, column) distributions with fewer than" f" 2 distinct finite values: {skipped}" ) if not ridges: raise ValueError("No bootstrap distributions could be estimated") global_peak = max(density.max() for _, _, density in ridges) ridges.sort(key=lambda ridge: -ridge[0]) with self._style(): fig, ax = ( plt.subplots(layout="constrained") if ax is None else (ax.get_figure(), ax) ) labeled: set[int] = set() for order, (baseline, col_idx, density) in enumerate(ridges): peak = density.max() if scale == "ridge" else global_peak top = baseline + height * density / peak color = kwargs["colors"][col_idx] zorder = 2 + order * 1e-3 label = None if col_idx not in labeled: label = rf"${self.results.parser.to_latex(columns[col_idx])}$" labeled.add(col_idx) ax.fill_between( x_grid, baseline, top, facecolor=color, alpha=kwargs["alpha"], linewidth=0, label=label, zorder=zorder, ) ax.plot( x_grid, top, color=color, linewidth=kwargs["linewidth"], zorder=zorder, ) tick_order = np.argsort(baselines) ax.set_yticks( baselines[tick_order], [f"{v:.3f}" for v in scan_values[tick_order]] ) ax.set_ylabel(y_label) ax.set_xlabel( rf"${self.results.parser.to_latex(columns[0])}$" if len(columns) == 1 else "Bootstrap value" ) ax.margins(y=0.03) ax.legend() return ax
# ---------------------------------------------------------------------------------- # Helpers # ---------------------------------------------------------------------------------- def _group_waves(self) -> list[_Wave]: """Group the results' amplitudes into waves, sorted by their quantum numbers A wave is an amplitude with its reflectivity removed, so each holds at most one positive and one negative reflectivity amplitude. Raises: KeyError: If no amplitudes are found in the results. """ parser = self.results.parser grouped: dict[tuple[str, ...], dict[str, str]] = {} for amp in self.results.amplitudes: parsed = parser.parse_amplitude(amp) is_positive = parsed.e in _POSITIVE_REFLECTIVITY_CHARS refl = "positive" if is_positive else "negative" key = tuple(parsed.get(qn) for qn in _WAVE_QUANTUM_NUMBERS) grouped.setdefault(key, {})[refl] = amp if not grouped: raise KeyError("No amplitudes found in the results to plot.") return [ _Wave(label=parser.to_latex(next(iter(amps.values()))), **amps) for _, amps in sorted( grouped.items(), key=lambda item: tuple(_numeric_sort_key(qn) for qn in item[0]), ) ] def _matrix_phase_column( self, waves: list[_Wave], row: int, col: int ) -> str | None: """Phase difference column for an off-diagonal cell of the model matrix The upper triangle (col > row) uses positive reflectivity amplitudes and the lower triangle negative. Returns None if either amplitude or their phase difference is not in the results. """ refl = "positive" if col > row else "negative" amp1, amp2 = getattr(waves[row], refl), getattr(waves[col], refl) if amp1 is None or amp2 is None: return None return self.results.find_phase(amp1, amp2) def _resolve_kin_variable( self, kin_variable: str, stat: Literal["edges", "avg"] = "edges", ) -> tuple[str | None, str | None, str | None, str | None, str, str]: """Resolve a shorthand or column name to 'data' dataframe column. Args: kin_variable (str): A known shorthand ("m", "t", "e") or exact name of a column in the 'data' dataframe to use as the x-axis values. stat (Literal['edges', 'avg']): Whether x-value/error is from the bin center and (high-low)/2 'edges' (default) or from the actual bin average and rms of the underlying data. Returns: tuple[str | None, str | None, str | None, str | None, str, str]: Central value column name (None if no dedicated "_center" column), the low-edge column name (if available), the high-edge column name (if available), and LaTeX formatted x,y axis label. Raises: KeyError: If kin_variable cannot be resolved, or for stat='edges' that there aren't enough columns to compute one, in the 'data' dataframe. Also if stat='avg' is requested but the corresponding <kin_variable>_<avg/rms> columns are not available. ValueError: If stat is not 'edges' or 'avg' """ if stat not in ("edges", "avg"): raise ValueError(f"stat must be 'edges' or 'avg', got '{stat}'") columns = self.results.data.columns if kin_variable in _KIN_VARIABLE_XLABELS: x_label = _KIN_VARIABLE_XLABELS[kin_variable] y_label = _KIN_VARIABLE_YLABELS[kin_variable] low = f"{kin_variable}_low" if f"{kin_variable}_low" in columns else None high = f"{kin_variable}_high" if f"{kin_variable}_high" in columns else None bin_width = ( self.results.data[high] - self.results.data[low] if (low is not None and high is not None) else None ) if bin_width is not None and ( (np.std(bin_width) / np.mean(bin_width)) < 0.01 ): # if relative standard deviation of the bin width is within 1%, we can # reasonably assume that we have a constant bin width to label the # y-axis with y_label = y_label.replace("NUM", f"{bin_width.mean():.3f}") else: # bin width is either unknown or variable, so cut down y_label to just # "Events" y_label = y_label.split("/")[0] if stat == "avg": center, rms = f"{kin_variable}_avg", f"{kin_variable}_rms" if center not in columns or rms not in columns: raise KeyError( f"stat='avg' requires '{center}' and '{rms}' columns in the" f" data dataframe for kin_variable='{kin_variable}', but at" f" least one was not found. Available columns:" f" {list(columns)}" ) return center, None, None, rms, x_label, y_label # stat == 'edges': prefers a dedicated "<kin_variable>_center" column, # but will otherwise compute midpoint from low/high columns. Falls back to # <kin_variable>_avg as a last resort. if f"{kin_variable}_center" in columns: center: str | None = f"{kin_variable}_center" elif low is not None and high is not None: center = None # computed as (high-low)/2 in _scan_dataframes elif f"{kin_variable}_avg" in columns: center = f"{kin_variable}_avg" else: raise KeyError( f"Could not resolve a center for kin_variable '{kin_variable}' with" f" stat='edges': no '{kin_variable}'_center," f" '{kin_variable}_low/high pair, and no '{kin_variable}_avg'" f" column were found. Available columns {list(columns)}" ) return center, low, high, None, x_label, y_label elif kin_variable in columns: return kin_variable, None, None, None, kin_variable, kin_variable else: raise KeyError( f"kin_variable '{kin_variable}' cannot be resolved. Must be one of " f"{list(_KIN_VARIABLE_XLABELS.keys())} or a column in the 'data' " f"dataframe: {list(columns)}" ) def _resolve_scan_bins( self, kin_variable: str, t_bin: tuple[float, float] | TBin | None, energy_bin: tuple[float, float] | EnergyBin | None, mass_bin: tuple[float, float] | MassBin | None, ) -> list[KinematicBin]: """Resolve the ordered list of kinematic bins to scan over. Results may span multiple bins e.g. 3 t bins x 2 energy bins x 10 mass bins. To plot as a function of one kinematic variable, the other two must be fixed to a single bin each. We only need to do this though if more than one unscanned bin is available. For example, if the results span 3 t bins and 2 energy bins, but only 1 mass bin, then we can plot as a function of t without needing to fix the mass bin, but would need to fix the energy bin. Args: kin_variable (str): The kinematic variable to scan over ("m", "t", "e"). Any other value is treated as a column name in the 'data' dataframe, and will be used as the x-axis. The given t-bin/energy-bin/mass-bin will be used to select the appropriate bin to plot from. t_bin (tuple[float, float] | TBin | None): Optional fixed t bin. energy_bin (tuple[float, float] | EnergyBin | None): Optional fixed energy bin. mass_bin (tuple[float, float] | MassBin | None): Optional fixed mass bin. Returns: list[KinematicBin]: The ordered list of kinematic bins to scan over. Raises: ValueError: If a bin is given for the dimension being scanned over, or if multiple bins are present on a non-scanned dimension, leaving an ambiguous plot range. """ if kin_variable == "m": if mass_bin is not None: raise ValueError( "Cannot specify a mass bin when scanning over mass. " "Please leave mass_bin as None." ) return self.results.mass_kinematic_bins(t_bin=t_bin, energy_bin=energy_bin) elif kin_variable == "t": if t_bin is not None: raise ValueError( "Cannot specify a t bin when scanning over t. " "Please leave t_bin as None." ) return self.results.t_kinematic_bins( mass_bin=mass_bin, energy_bin=energy_bin ) elif kin_variable == "e": if energy_bin is not None: raise ValueError( "Cannot specify an energy bin when scanning over energy. " "Please leave energy_bin as None." ) return self.results.energy_kinematic_bins(t_bin=t_bin, mass_bin=mass_bin) # arbitrary 'data' column case: no per-axis results method exists to check for # for ambiguity along an unknown axis, so this just applies whichever bins were # given as a plain filter return self._resolve_kinematic_bins(t_bin, energy_bin, mass_bin) def _scan_dataframes( self, columns: tuple[str, ...] | list[str] | None = None, frame: Literal[ "fit", "correlation", "covariance", "norm_int", "randomized", "bootstrap" ] = "fit", kin_variable: str = "m", stat: Literal["edges", "avg"] = "edges", t_bin: tuple[float, float] | TBin | None = None, energy_bin: tuple[float, float] | EnergyBin | None = None, mass_bin: tuple[float, float] | MassBin | None = None, indices: list[int] | None = None, ) -> tuple[pd.DataFrame, pd.DataFrame, str, str]: """Get a results dataframe and 'data' dataframe over a kinematic variable scan Every plot in this class needs two things: the set of kinematic bins to scan over, resolved and ordered along 'kin_variable' (see '_resolve_scan_bins'), and rows from one of the 'result' dataframes restricted to those bins. This does both, for any of the 'results.fit', '.correlation', ... . Fit, randomized, and bootstrap dataframes share the same per-quantity "<col>"/"<col>_err" convention, so those columns are automatically appended. Matrix-like results (norm-int, covariance, etc.) use 'columns' as-is. Unlike 'fit' or 'data' frames, the other frames have several rows per bin. These returned frames always keep a "bin_id" column so those rows stay identifiable. Args: columns (tuple[str, ...] | list[str] | None): The columns to include from 'frame'. For 'fit'/'randomized'/'bootstrap' frames, the "_err" companions are automatically added, if available. If None (default) all columns are included. frame (Literal['fit', 'correlation', 'covariance', 'norm_int', 'randomized' 'bootstrap']): Which 'results' dataframe to pull 'columns' from. Defaults to 'fit'. kin_variable (str): The kinematic variable to scan over ("m", "t", "e"). Any other value is treated as a column name in the 'data' dataframe, and will be used as the x-axis. The given t-bin/energy-bin/mass-bin will be used to select the appropriate bin to plot from. stat (Literal['edges', 'avg']): Whether x-value/error is from the bin center and (high-low)/2 'edges' (default) or from the actual bin average and rms of the underlying data. t_bin (tuple[float, float] | TBin | None): Optional fixed t bin. energy_bin (tuple[float, float] | EnergyBin | None): Optional fixed energy bin. mass_bin (tuple[float, float] | MassBin | None): Optional fixed mass bin. indices (list[int] | None): Optional list of indices, within the resolved and sorted scan, to select specific bins. If None, all bins will be used. Returns: tuple[pd.DataFrame, pd.DataFrame, str, str]: The requested 'frame's rows (restricted to the resolve bins, 'bin_id' retained, grouped/ordered to match the scan), the 'data' dataframe (kinematic variable renamed to 'x_center' and 'x_err', 'bin_id' retained) and LaTeX formatted x-y axis labels for the kinematic variable. Raises: KeyError: If kin_variable cannot be resolved to a known shorthand or column name in the 'data' dataframe, or requested 'frame' is not available. ValueError: If a bin is given for the dimension being scanned over, or if multiple bins are present on a non-scanned dimension, leaving an ambiguous plot range. """ center_col, low_col, high_col, rms_col, x_label, y_label = ( self._resolve_kin_variable(kin_variable, stat) ) kinematic_bins = self._resolve_scan_bins( kin_variable, t_bin, energy_bin, mass_bin ) if indices is not None: kinematic_bins = [kinematic_bins[i] for i in indices] bin_ids = [kb.bin_id for kb in kinematic_bins] if not bin_ids: raise ValueError( "No kinematic bins found for the specified scan. Please check the " "provided t_bin, energy_bin, and mass_bin arguments." ) requested_frame, frame_columns = self._frame_columns(frame, columns) value_df = self._select_by_bin_id(requested_frame, bin_ids, frame_columns) if frame == "fit": value_df = self._replace_errors_with_bootstrap(value_df) data_columns = [ "events", "events_err", "ac_events", "ac_events_err", ] for extra_col in (center_col, low_col, high_col, rms_col): if extra_col is not None: data_columns.append(extra_col) data_df = self._select_by_bin_id(self.results.data, bin_ids, data_columns) if center_col is not None: data_df = data_df.rename(columns={center_col: "x_center"}) else: # no dedicated center column, use the midpoint of the bin edges instead data_df["x_center"] = (data_df[low_col] + data_df[high_col]) / 2.0 if rms_col is not None: data_df["x_err"] = data_df[rms_col] elif low_col is not None and high_col is not None: data_df["x_err"] = (data_df[high_col] - data_df[low_col]) / 2.0 else: data_df["x_err"] = np.nan return value_df, data_df, x_label, y_label