Source code for pwassist.core.result

import dataclasses
import os
import pickle
import subprocess
import warnings
from dataclasses import dataclass, field
from pathlib import Path

import numpy as np
import pandas as pd
import scipy

from pwassist.io.binning import EnergyBin, KinematicBin, MassBin, TBin
from pwassist.parser import AmplitudeParser, NamingScheme
from pwassist.plotting.factory import FactoryPlotter
from pwassist.preprocessing.preprocessor import PreprocessReport, ProcessedBin


def _get_current_git_commit_hash() -> str | None:
    try:
        result = subprocess.run(
            ["git", "rev-parse", "HEAD"],
            cwd=Path(__file__).resolve().parent,
            check=True,
            capture_output=True,
            text=True,
        )
    except OSError, subprocess.CalledProcessError:
        return None
    return result.stdout.strip()


[docs] @dataclass class Results: """Assembled, preprocessed, analysis-ready results from a collection of PWA bins. Todo: - Add examples and lots of documentation, as this is the main user-facing class """ # Result dataframes fit: pd.DataFrame data: pd.DataFrame correlation: pd.DataFrame | None = None covariance: pd.DataFrame | None = None norm_int: pd.DataFrame | None = None bootstrap: pd.DataFrame | None = None randomized: pd.DataFrame | None = None # Result metadata kinematic_bins: list[KinematicBin] = field(default_factory=list) unique_mass_bins: frozenset[MassBin] = field(init=False) unique_t_bins: frozenset[TBin] = field(init=False) unique_energy_bins: frozenset[EnergyBin] = field(init=False) reports: list[PreprocessReport] = field(default_factory=list) is_acc_corrected: bool = field(init=False) final_state_parity: int | None = field(default=None) git_commit_hash: str | None = field( default_factory=_get_current_git_commit_hash, repr=False ) # Amplitude-based attributes coherent_sums: dict[str, tuple[str, ...]] = field(default_factory=dict, init=False) amplitudes: tuple[str, ...] = field(default_factory=tuple, init=False) phase_differences: tuple[str, ...] = field(default_factory=tuple, init=False) parser: AmplitudeParser = field(init=False) are_reactions_constrained: bool = False are_sums_constrained: bool = False _phase_difference_dict: dict[tuple[str, str], str] = field( default_factory=dict, init=False ) _naming_scheme: str | None | NamingScheme = field(default=None) _factory_plotter: FactoryPlotter | None = field( default=None, init=False, repr=False ) def __post_init__(self) -> None: self._factory_plotter = FactoryPlotter(self) if self._naming_scheme is None: self._naming_scheme = "auto" self.parser = AmplitudeParser( self._naming_scheme, final_state_parity=self.final_state_parity ) self.amplitudes = tuple(self.parser.get_amplitudes(self.fit.columns.to_list())) if self.amplitudes is None or len(self.amplitudes) == 0: warnings.warn( f"No amplitudes found in fit dataframe using naming scheme" f" '{self._naming_scheme}'. This will affect plotting scripts.", UserWarning, ) # ensure that the coherent sums and phase differences are immutable coh_sums = self.parser.get_coherent_sums(self.fit.columns.to_list()) self.coherent_sums = { sum_label: tuple(coh_sum) for sum_label, coh_sum in coh_sums.items() } self.phase_differences = tuple( self.parser.get_phase_differences(self.fit.columns.to_list()) ) self._phase_difference_dict = self._build_phase_difference_dict() self.is_acc_corrected = self._is_fit_acc_corrected() self.unique_mass_bins = frozenset( sorted(kb.mass_bin for kb in self.kinematic_bins) ) self.unique_t_bins = frozenset(sorted(kb.t_bin for kb in self.kinematic_bins)) self.unique_energy_bins = frozenset( sorted(kb.energy_bin for kb in self.kinematic_bins) ) # We can infer whether reaction/sum names are constrained by counting the number # of "::" occurrences in the production coefficient columns. prod_coeff_cols = [c for c in self.fit.columns if "_re" in c or "_im" in c] if any([c.count("::") > 2 for c in prod_coeff_cols]): raise ValueError(f"Unexpected format for production coefficient columns") elif any([c.count("::") == 2 for c in prod_coeff_cols]): # labeled '<reaction>::<sum>::<amplitude>_<part>' self.are_sums_constrained = False self.are_reactions_constrained = False elif any([c.count("::") == 1 for c in prod_coeff_cols]): # labeled '<sum>::<amplitude>_<part>' self.are_sums_constrained = False self.are_reactions_constrained = True else: # labeled '<amplitude>_<part>' self.are_sums_constrained = True self.are_reactions_constrained = True return # ---------------------------------------------------------------------------------- # Constructors and Loaders # ----------------------------------------------------------------------------------
[docs] @classmethod def from_processed_bins( cls, processed_bins: list[ProcessedBin], naming_scheme: str | None | NamingScheme = None, final_state_parity: int | None = None, ) -> "Results": """Construct a Results instance from a list of ProcessedBin objects.""" # sort the processed bins by kinematic bin to ensure consistent ordering processed_bins = sorted(processed_bins, key=lambda pb: pb.kinematic_bin) # concatenate all dataframes for each file type across all bins fit_df = pd.concat([pb.fit for pb in processed_bins], ignore_index=True) data_df = pd.concat([pb.data for pb in processed_bins], ignore_index=True) correlations = ( pd.concat( [pb.correlation for pb in processed_bins if pb.correlation is not None], ignore_index=True, ) if any(pb.correlation is not None for pb in processed_bins) else None ) covariances = ( pd.concat( [pb.covariance for pb in processed_bins if pb.covariance is not None], ignore_index=True, ) if any(pb.covariance is not None for pb in processed_bins) else None ) norm_ints = ( pd.concat( [pb.norm_int for pb in processed_bins if pb.norm_int is not None], ignore_index=True, ) if any(pb.norm_int is not None for pb in processed_bins) else None ) randomized = ( pd.concat( [pb.randomized for pb in processed_bins if pb.randomized is not None], ignore_index=True, ) if any(pb.randomized is not None for pb in processed_bins) else None ) bootstrap = ( pd.concat( [pb.bootstrap for pb in processed_bins if pb.bootstrap is not None], ignore_index=True, ) if any(pb.bootstrap is not None for pb in processed_bins) else None ) return cls( fit=fit_df, data=data_df, correlation=correlations, covariance=covariances, norm_int=norm_ints, randomized=randomized, bootstrap=bootstrap, kinematic_bins=[pb.kinematic_bin for pb in processed_bins], reports=[pb.report for pb in processed_bins], _naming_scheme=naming_scheme, final_state_parity=final_state_parity, )
[docs] @classmethod def load(cls, filepath: str | Path) -> "Results": """Load a Results instance from a pickle file.""" filepath = Path(filepath) with open(filepath, "rb") as f: data: dict = pickle.load(f) data.setdefault("git_commit_hash", None) return cls(**data)
[docs] def save(self, filepath: str | Path) -> None: """Save the Results instance to a pickle file.""" data = { "fit": self.fit, "data": self.data, "correlation": self.correlation, "covariance": self.covariance, "norm_int": self.norm_int, "randomized": self.randomized, "bootstrap": self.bootstrap, "kinematic_bins": self.kinematic_bins, "reports": self.reports, "final_state_parity": self.final_state_parity, "git_commit_hash": self.git_commit_hash, "_naming_scheme": self._naming_scheme, } with open(filepath, "wb") as f: pickle.dump(data, f)
def _matches_current_git_commit(self) -> bool: current_commit = _get_current_git_commit_hash() return ( self.git_commit_hash is not None and current_commit is not None and self.git_commit_hash == current_commit )
[docs] def filter_by_kinematic_bins( self, kinematic_bins: KinematicBin | list[KinematicBin] | None = None, t_bins: ( tuple[float, float] | TBin | list[tuple[float, float]] | list[TBin] | None ) = None, energy_bins: ( tuple[float, float] | EnergyBin | list[tuple[float, float]] | list[EnergyBin] | None ) = None, mass_bins: ( tuple[float, float] | MassBin | list[tuple[float, float]] | list[MassBin] | None ) = None, ) -> "Results": """Return a new Results instance filtered by the specified kinematic bins. Args: kinematic_bins (KinematicBin | list[KinematicBin] | None): List of KinematicBin instances to filter by. If specified, t_bins, energy_bins, and mass_bins will be ignored. t_bins ( tuple[float, float] | TBin | list[tuple[float, float]] | list[TBin] | None): List of requested t bins, either as (low, high) tuples or TBin instances. energy_bins ( tuple[float, float] | EnergyBin | list[tuple[float, float]] | list[EnergyBin] | None): List of requested energy bins, either as (low, high) tuples or EnergyBin instances. mass_bins ( tuple[float, float] | MassBin | list[tuple[float, float]] | list[MassBin] | None): List of requested mass bins, either as (low, high) tuples or MassBin instances. """ selected_bins: list[KinematicBin] # Get the selected kinematic bins and corresponding bin_ids if kinematic_bins is not None: if isinstance(kinematic_bins, KinematicBin): selected_bins = [kinematic_bins] else: selected_bins = kinematic_bins if any(kb not in self.kinematic_bins for kb in selected_bins): raise KeyError( "One or more specified kinematic bins are not present in the" " results." ) else: selected_bins = self._resolve_kinematic_bins( t_bins=t_bins, energy_bins=energy_bins, mass_bins=mass_bins ) selected_ids = {kb.bin_id for kb in selected_bins} if not selected_ids: raise KeyError( "No kinematic bins found matching the specified criteria. Please check" " the input parameters." ) def _filter(df: pd.DataFrame | None) -> pd.DataFrame | None: if df is None: return None return df[df["bin_id"].isin(selected_ids)].reset_index(drop=True) return dataclasses.replace( self, fit=_filter(self.fit), data=_filter(self.data), correlation=_filter(self.correlation), covariance=_filter(self.covariance), norm_int=_filter(self.norm_int), bootstrap=_filter(self.bootstrap), randomized=_filter(self.randomized), kinematic_bins=selected_bins, reports=[r for r in self.reports if r.bin_id in selected_ids], )
# ---------------------------------------------------------------------------------- # Reports # ----------------------------------------------------------------------------------
[docs] def summary(self) -> None: """Print a summary of the Results instance and its preprocessor warnings.""" try: width = os.get_terminal_size().columns except OSError: width = 80 # default width if terminal size cannot be determined print(f"{'-' * ((width -16)// 2)}Results Summary:{'-' * ((width -16)// 2)}") print(f"Number of kinematic bins: {len(self.kinematic_bins)}") print(f"\tUnique mass bins: {len(self.unique_mass_bins)}") print(f"\tUnique t bins: {len(self.unique_t_bins)}") print(f"\tUnique beam energy bins: {len(self.unique_energy_bins)}") print(f"Number of preprocessing reports: {len(self.reports)}") for name in ( "fit", "data", "correlation", "covariance", "norm_int", "randomized", "bootstrap", ): df = getattr(self, name) if df is not None: print(f"\n{name}") print(df.info()) self.warnings()
[docs] def warnings(self) -> None: """Print a summary of all warnings from the preprocessing reports.""" if not self.reports: print("No preprocessing reports available.") return flagged = [r for r in self.reports if r.warnings] total_ms = sum(r.total_time_ms for r in self.reports) print(f"{len(self.reports)} bins were processed in {total_ms:.2f} ms.") for report in flagged: print(f"\nBin ID: {report.bin_id}") for warning in report.warnings: print(f"\t- {warning}")
[docs] def preprocess_summary(self) -> None: """Print a summary of the preprocessing reports.""" if not self.reports: print("No preprocessing reports available.") return print(f"Preprocessing Summary:") for report in self.reports: print(f"\nBin ID: {report.bin_id}") print(f" Applied Steps: {report.applied_steps}") print(f" Warnings: {report.warnings}") print(f" Timings (ms): {report.timings_ms}") print(f" Total Time (ms): {report.total_time_ms}")
# ---------------------------------------------------------------------------------- # Kinematic Bin Extraction # ----------------------------------------------------------------------------------
[docs] def mass_kinematic_bins( self, t_bin: tuple[float, float] | TBin | None, energy_bin: tuple[float, float] | EnergyBin | None, ) -> list[KinematicBin]: """List of mass bins, optionally filtered by t and/or energy bins. Args: t_bin (tuple[float,float] | TBin | None): Low and high edges of the t bin to select, or a TBin instance. Only needs specification if the results span multiple t bins. If None, the sole available t bin will be used. energy_bin (tuple[float,float] | EnergyBin | None): Low and high edges of the energy bin to select, or an EnergyBin instance. Only needs specification if the results span multiple energy bins. If None, the sole available energy bin will be used. Returns: list[KinematicBin]: List of mass bins that match the specified t and energy bins. Raises: KeyError: If no kinematic bins match the specified t and energy bins, or if the results are ambiguous. ValueError: If multiple t or energy bins are present and none is specified, making the mass bin selection ambiguous. """ matching_kinematic_bins: list[KinematicBin] = self._resolve_kinematic_bins( t_bins=t_bin, energy_bins=energy_bin ) if not matching_kinematic_bins and ( t_bin is not None or energy_bin is not None ): raise KeyError( f"No kinematic bins found matching t_bins={t_bin} and" f" energy_bins={energy_bin}." ) elif not matching_kinematic_bins: raise KeyError( "No kinematic bins found in the results. Please check the data." ) # If the t_bins or energy_bins are not specified, ensure that there is only one # unique t_bin and energy_bin in the matching kinematic bins matching_t_bins = {kb.t_bin for kb in matching_kinematic_bins} matching_energy_bins = {kb.energy_bin for kb in matching_kinematic_bins} if len(matching_t_bins) > 1 or len(matching_energy_bins) > 1: raise ValueError( f"Cannot determine a mass range because multiple t or energy bins are" f" present and must be specified. Found t_bins={matching_t_bins} and" f" energy_bins={matching_energy_bins}." ) return sorted(matching_kinematic_bins)
[docs] def t_kinematic_bins( self, energy_bin: tuple[float, float] | EnergyBin | None = None, mass_bin: tuple[float, float] | MassBin | None = None, ) -> list[KinematicBin]: """List of t bins, optionally filtered by mass and/or energy bins. Args: mass_bin (tuple[float,float] | MassBin | None): Low and high edges of the mass bin to select, or a MassBin instance. Only needs specification if the results span multiple mass bins. If None, the sole available mass bin will be used. energy_bin (tuple[float,float] | EnergyBin | None): Low and high edges of the energy bin to select, or an EnergyBin instance. Only needs specification if the results span multiple energy bins. If None, the sole available energy bin will be used. Returns: list[KinematicBin]: List of t bins that match the specified mass and energy bins. Raises: KeyError: If no kinematic bins match the specified mass and energy bins, or if the results are ambiguous. ValueError: If multiple mass or energy bins are present and none is specified, making the mass bin selection ambiguous. """ matching_kinematic_bins = self._resolve_kinematic_bins( mass_bins=mass_bin, energy_bins=energy_bin ) if not matching_kinematic_bins and ( mass_bin is not None or energy_bin is not None ): raise KeyError( f"No kinematic bins found matching t_bins={mass_bin} and" f" energy_bins={energy_bin}." ) elif not matching_kinematic_bins: raise KeyError( "No kinematic bins found in the results. Please check the data." ) # If the mass_bins or energy_bins are not specified, ensure that there is only # one unique mass_bin and energy_bin in the matching kinematic bins matching_mass_bins = {kb.mass_bin for kb in matching_kinematic_bins} matching_energy_bins = {kb.energy_bin for kb in matching_kinematic_bins} if len(matching_mass_bins) > 1 or len(matching_energy_bins) > 1: raise ValueError( f"Cannot determine a mass range because multiple t or energy bins are" f" present and must be specified. Found t_bins={matching_mass_bins} and" f" energy_bins={matching_energy_bins}." ) return sorted(matching_kinematic_bins)
[docs] def energy_kinematic_bins( self, t_bin: tuple[float, float] | TBin | None, mass_bin: tuple[float, float] | MassBin | None, ) -> list[KinematicBin]: """List of energy bins, optionally filtered by t and/or mass bins. Args: t_bin (tuple[float,float] | TBin | None): Low and high edges of the t bin to select, or a TBin instance. Only needs specification if the results span multiple t bins. If None, the sole available t bin will be used. mass_bin (tuple[float,float] | MassBin | None): Low and high edges of the mass bin to select, or a MassBin instance. Only needs specification if the results span multiple mass bins. If None, the sole available mass bin will be used. Returns: list[KinematicBin]: List of energy bins that match the specified t and mass bins. Raises: KeyError: If no kinematic bins match the specified t and mass bins, or if the results are ambiguous. ValueError: If multiple t or mass bins are present and none is specified, making the energy bin selection ambiguous. """ matching_kinematic_bins = self._resolve_kinematic_bins( t_bins=t_bin, mass_bins=mass_bin ) if not matching_kinematic_bins and (t_bin is not None or mass_bin is not None): raise KeyError( f"No kinematic bins found matching t_bins={t_bin} and" f" mass_bins={mass_bin}." ) elif not matching_kinematic_bins: raise KeyError( "No kinematic bins found in the results. Please check the data." ) # If the t_bins or mass_bins are not specified, ensure that there is only # one unique t_bin and mass_bin in the matching kinematic bins matching_t_bins = {kb.t_bin for kb in matching_kinematic_bins} matching_mass_bins = {kb.mass_bin for kb in matching_kinematic_bins} if len(matching_t_bins) > 1 or len(matching_mass_bins) > 1: raise ValueError( f"Cannot determine a mass range because multiple t or mass bins are" f" present and must be specified. Found t_bins={matching_t_bins}" f" and mass_bins={matching_mass_bins}." ) return sorted(matching_kinematic_bins)
# ---------------------------------------------------------------------------------- # Amplitude-based Queries # ----------------------------------------------------------------------------------
[docs] def find_phase(self, amp1: str, amp2: str) -> str | None: """Find the phase difference column name for a given pair of amplitudes. Args: amp1 (str): Name of the first amplitude. amp2 (str): Name of the second amplitude. Returns: str | None: The name of the phase difference column, or None if not found. """ return self._phase_difference_dict.get((amp1, amp2), None)
# ---------------------------------------------------------------------------------- # Analysis # ---------------------------------------------------------------------------------- @property def plot(self) -> FactoryPlotter: """Return a FactoryPlotter instance for plotting the results.""" if self._factory_plotter is None: self._factory_plotter = FactoryPlotter(self) return self._factory_plotter
[docs] def get_uncertainty( self, label: str, kinematic_bins: list[KinematicBin] | None = None ) -> pd.Series: """Get the uncertainty for a given label Args: label (str): column in fit result get calculate uncertainty for. kinematic_bins (list[KinematicBin] | None, optional): Optional list of kinematic bins to narrow down to. Defaults to None. Raises: KeyError: If 'label' is found in neither the bootstrap dataframe or as a '<label>_err' column in the fit dataframe. Returns: pd.Series: Standard deviations of bootstrap samples (if exists), or '<label>_err' column. """ if self.bootstrap is not None and label in self.bootstrap.columns: grouped = self.bootstrap.groupby("bin_id", sort=False)[label] if label in self.phase_differences: uncertainty = grouped.apply(self._circular_std) else: uncertainty = grouped.std() if kinematic_bins is not None: bin_ids = [kinematic_bin.bin_id for kinematic_bin in kinematic_bins] uncertainty = uncertainty.reindex(bin_ids) return uncertainty else: if f"{label}_err" not in self.fit.columns: raise KeyError( f"{label} could not be found in bootstrap data, and '{label}_err'" " does not exist in the best fit result. Could not determine" f" uncertainty of {label}" ) if kinematic_bins is not None: bin_ids = [kinematic_bin.bin_id for kinematic_bin in kinematic_bins] selected = self.fit.set_index("bin_id", drop=False).loc[ bin_ids, f"{label}_err" ] return selected.reset_index(drop=True) else: return self.fit[f"{label}_err"]
# ---------------------------------------------------------------------------------- # Pass-Through # ----------------------------------------------------------------------------------
[docs] @staticmethod def set_plot_style(style: str | Path) -> None: """Set the global matplotlib style used by all plotters.""" from pwassist.plotting.base import BasePWAPlotter BasePWAPlotter.set_style(style)
[docs] @staticmethod def get_plot_style_name() -> str: """Get the current global matplotlib style name used by all plotters.""" from pwassist.plotting.base import BasePWAPlotter return BasePWAPlotter.get_style_name()
[docs] @staticmethod def get_plot_style_path() -> Path: """Get the current global matplotlib style path used by all plotters.""" from pwassist.plotting.base import BasePWAPlotter return BasePWAPlotter.get_style_path()
# ---------------------------------------------------------------------------------- # Helpers # ---------------------------------------------------------------------------------- def _build_phase_difference_dict(self) -> dict[tuple[str, str], str]: """Build dictionary of all pairs of amplitudes and corresponding phases Since the phase_difference orderings are not known a priori, it's unclear how to request a phase difference column from a dataframe. This dictionary will allow for easy lookup of the phase difference for a pair of amplitudes, regardless of their order in the dataframe. """ if self.parser is None: raise ValueError("AmplitudeParser is not initialized.") possible_pairs_to_phases = {} for phase in self.phase_differences: amps = phase.split("_") if len(amps) != 2: raise ValueError( f"Phase difference '{phase}' does not correspond to a pair of" " amplitudes." ) possible_pairs_to_phases[tuple(amps)] = phase possible_pairs_to_phases[tuple(amps[::-1])] = phase return possible_pairs_to_phases def _is_fit_acc_corrected(self) -> bool: """Determine if the fit is acceptance-corrected This is done by checking if the sum of the reflectivities exceeds the number of detected events. Warning: If the fit does not contain reflectivity-based amplitudes, or if the naming scheme is not recognized, this method will return False and issue a warning. """ refl_sums = self.coherent_sums.get("e") total_reflectivity = ( [e.sum() for e in self.fit[list(refl_sums)].to_numpy()] if refl_sums else None ) if total_reflectivity is not None: detected_events = self.fit["intensity"].to_numpy() if (total_reflectivity > detected_events).any(): return True else: return False warnings.warn( "Could not determine if fit is acceptance-corrected. This may be due to" " the naming scheme not being recognized or the fit not containing" " reflectivity-based amplitudes. Please check the fit data and naming" " scheme to ensure that the results are interpreted correctly.", UserWarning, ) return False def _resolve_kinematic_bins( self, t_bins: ( tuple[float, float] | TBin | list[tuple[float, float]] | list[TBin] | None ) = None, energy_bins: ( tuple[float, float] | EnergyBin | list[tuple[float, float]] | list[EnergyBin] | None ) = None, mass_bins: ( tuple[float, float] | MassBin | list[tuple[float, float]] | list[MassBin] | None ) = None, ) -> list[KinematicBin]: """Resolve requested kinematic bins against the bins present in results. Args: t_bins (list[tuple[float, float]] | list[TBin] | None): List of requested t bins, either as (low, high) tuples or TBin instances. energy_bins (list[tuple[float, float]] | list[EnergyBin] | None): List of requested energy bins, either as (low, high) tuples or EnergyBin instances. mass_bins (list[tuple[float, float]] | list[MassBin] | None): List of requested mass bins, either as (low, high) tuples or MassBin instances. Returns: list[KinematicBin]: List of resolved kinematic bins that match the requested bins. If any of the requested bin types are None, then all kinematic bins of that type will be selected. Otherwise, only the specified bins will be selected. Raises: KeyError: If any of the requested bins are not found in the results, or if the requested bins are invalid (e.g. low >= high). """ def _normalize(bins, bin_cls) -> list: """Convert a bin, tuple, or list of either into a list of bin_cls.""" if bins is None: return [] items = bins if isinstance(bins, list) else [bins] normalized = [] for item in items: if isinstance(item, bin_cls): normalized.append(item) elif isinstance(item, tuple): normalized.append(bin_cls.from_tuple(item)) else: raise TypeError( f"Cannot interpret {item!r} as a {bin_cls.__name__}; expected" f" a {bin_cls.__name__} or a (low, high) tuple." ) return normalized formatted_t_bins: list[TBin] = _normalize(t_bins, TBin) formatted_energy_bins: list[EnergyBin] = _normalize(energy_bins, EnergyBin) formatted_mass_bins: list[MassBin] = _normalize(mass_bins, MassBin) if t_bins is not None and any( t not in self.unique_t_bins for t in formatted_t_bins ): raise KeyError( f"Requested t bins {t_bins} not found in results. Available t bins:" f" {[str(b) for b in self.unique_t_bins]}" ) if energy_bins is not None and any( e not in self.unique_energy_bins for e in formatted_energy_bins ): raise KeyError( f"Requested energy bins {energy_bins} not found in results. Available" f" energy bins: {[str(b) for b in self.unique_energy_bins]}" ) if mass_bins is not None and any( m not in self.unique_mass_bins for m in formatted_mass_bins ): raise KeyError( f"Requested mass bins {mass_bins} not found in results. Available mass" f" bins: {[str(b) for b in self.unique_mass_bins]}" ) return [ kb for kb in self.kinematic_bins if (t_bins is None or kb.t_bin in formatted_t_bins) and (energy_bins is None or kb.energy_bin in formatted_energy_bins) and (mass_bins is None or kb.mass_bin in formatted_mass_bins) ] def _circular_std(self, angles: pd.Series) -> float: """Calculate the circular standard deviation of a series of angles Args: angles (pd.Series): Series of angles (in degrees). Preprocessing should ensure that angles are within [-180, 180] degrees. Raises: ValueError: if angles are not within [-180, 180] degrees. Returns: float: circular standard deviation in degrees. Returns NaN if the input series is empty or contains only NaN values. Note: This automatically corrects for the sign ambiguity in the phase differences by taking the absolute value before calculating. """ angles = angles.dropna() if len(angles) == 0: return np.nan angles_rad = np.abs(np.deg2rad(angles)) # corrected for sign ambiguity if angles_rad.max() > np.pi: raise ValueError("Data must be within [-pi, pi]; check preprocessing.") return np.rad2deg(scipy.stats.circstd(angles_rad, low=0, high=np.pi))