API Reference¶
PDF Classes¶
Calculate the probability density function (PDF) and cumulative distribution function (CDF) for the King spatial distribution. |
|
King PDF convolved with a HEALPix template map using spherical harmonics. |
Fitting¶
- class kingmaker.fitting.KingPSFFitter(signal_events: ndarray[tuple[Any, ...], dtype[Any]], parametrization_bins: Dict[str, int | List | Tuple | ndarray[tuple[Any, ...], dtype[_ScalarT]]], dpsi_nbins: int = 101, minimum_counts: int = 100, remove_weight_outliers=True, weight_outlier_percentiles=[0, 95], weight_field: str | None = 'ow', true_ra_name: str = 'trueRa', true_dec_name: str = 'trueDec', true_energy_name: str = 'trueE', spectral_indices: List[float] | ndarray[tuple[Any, ...], dtype[floating]] | None = None, angular_cutoff: float = 3.141592653589793)[source]¶
Bases:
objectFit King PSF parameters to simulated signal events in arbitrary dimensions.
This class bins signal Monte Carlo events along user-specified observables and fits King distribution parameters (alpha, beta) to the angular error distribution in each bin.
- Parameters:
signal_events (structured array) – Numpy structured array containing signal MC events. Must include: - ‘ra’, ‘dec’: reconstructed coordinates (radians) - ‘true_ra’, ‘true_dec’: true coordinates (radians) Additional fields can be used for parameterization binning.
parametrization_bins (dict) – Dictionary mapping observable names to bin edges or number of bins. Keys must correspond to fields in signal_events. Values can be: - int: number of equal-probability bins - array-like: explicit bin edges
dpsi_nbins (int, optional) – Number of bins in angular error (dpsi) for fitting. Default is 101.
minimum_counts (int, optional) – Minimum number of events required in a bin for fitting. Default is 100.
remove_weight_outliers (bool) – If True, remove events with weights beyond the bounds of weight_outlier_percentiles (calculated per parametrization bin) from the fit. Used to stabilize fits by removing weighting outliers. Default is True.
weight_outlier_percentiles (list, optional) – The percentiles (ranging from 0-100) defining the range of weights to accept for the per-parametrization bin histogramming and fitting. Note that these are applied based on the weights based on sorted index value and not cumulative weight value like np.percentile. Default is [0, 95],
weight_field (str, optional) – Field name for oneweight. If None, equal weights are used.
true_ra_name (str) – Field name for the true value of the signal events’ right ascension.
true_dec_name (str) – Field name for the true value of the signal events’ declination.
true_energy_name (str) – Field name for the true value of the signal events’ energy.
spectral_indices (array-like, optional) – Spectral indices (gamma) for reweighting. Default is [2.0].
angular_cutoff (float, optional) – Maximum angular separation for King PDF. Default is pi.
- fit_alpha¶
Fitted alpha parameters for each bin.
- Type:
ndarray
- fit_beta¶
Fitted beta parameters for each bin.
- Type:
ndarray
- histograms¶
Histogram values for each bin.
- Type:
ndarray
- uncertainties¶
Histogram uncertainties for each bin.
- Type:
ndarray
- dpsi_bins¶
Angular error bin edges for each bin.
- Type:
ndarray
- fit_quality¶
Chi-square values indicating fit quality.
- Type:
ndarray
- fit_all_bins(verbose: bool = True) Dict[str, ndarray[tuple[Any, ...], dtype[_ScalarT]]][source]¶
Fit King PSF parameters in all bins.
Iterates over all bins defined by parametrization_bins and spectral_indices, fitting King distribution parameters to the angular error distribution.
- Parameters:
verbose (bool, optional) – Print progress information. Default is True.
- Returns:
Dictionary containing fit results with keys: - ‘alpha’: fit_alpha array - ‘beta’: fit_beta array - ‘histograms’: histogram values - ‘uncertainties’: histogram uncertainties - ‘dpsi_bins’: angular error bin edges - ‘fit_quality’: chi-square values - ‘event_counts’: number of events per bin
- Return type:
- get_interpolator(gamma_index: int = 0) Tuple[Any, Any][source]¶
Get an interpolator for fitted parameters at a given spectral index.
- Parameters:
gamma_index (int, optional) – Index of the spectral index to use. Default is 0.
- Returns:
(alpha_interpolator, beta_interpolator) functions that interpolate fitted parameters based on parameterization bin values.
- Return type:
Notes
Requires scipy.interpolate.RegularGridInterpolator (not imported by default to avoid dependency). This method will raise ImportError if scipy is not available.
- plot_fit(bin_indices: Tuple[int, ...] | Dict[str, int], gamma_index: int = 0, ax: Any | None = None) Any[source]¶
Plot the fitted King PDF for a specific bin.
- Parameters:
- Returns:
The axes object.
- Return type:
matplotlib.axes.Axes
Notes
Requires matplotlib (not imported by default). This method will raise ImportError if matplotlib is not available.
Likelihood Wrapper¶
- class kingmaker.wrapper.KingSpatialLikelihood(signal_events: ndarray[tuple[Any, ...], dtype[Any]], parametrization_bins: Dict[str, int | List | Tuple | ndarray[tuple[Any, ...], dtype[_ScalarT]]], dpsi_nbins: int = 101, minimum_counts: int = 100, spectral_indices: List[float] | ndarray[tuple[Any, ...], dtype[floating]] = [1.0, 2.0, 3.0, 4.0], angular_cutoff: float = 3.141592653589793, cache_parameters: bool = True, cache_name: str = './king_parameters_cache.npz', remove_weight_outliers=True, weight_outlier_percentiles=(0, 95), weight_field: str = 'ow', true_ra_name: str = 'trueRa', true_dec_name: str = 'trueDec', true_energy_name: str = 'trueE', enable_marginalization: bool = False, marginalization_source_decs: ndarray[tuple[Any, ...], dtype[floating]] | None = None, marginalization_angular_cutoff: float | None = None, marginalization_points_alpha: ndarray[tuple[Any, ...], dtype[floating]] | None = None, marginalization_points_beta: ndarray[tuple[Any, ...], dtype[floating]] | None = None, marginalization_n_signed_delta_dec: int = 200, marginalization_n_ra_bins: int = 100)[source]¶
Bases:
objectWrapper class to encapsulate King distribution functionality, including PDF evaluation and parameter fitting. This class provides a unified interface for working with King distributions, allowing users to easily fit simulation and evaluate the PDF over events for likelihood calculations.
Users create an instance of KingSpatialLikelihood by passing in parameters, binning, and simulated events. The class then fits King distribution parameters using the requested parameter binning. From this point onward, users only need to call either the “PDF” or “template” evaluation methods with their events to obtain likelihood values for their analyses. These methods interpolate the fitted King distribution parameters per-event using the event’s observable parameters and the provided binning, and then evaluate the PDF or template-smoothed PDF at the event’s reconstructed equatorial position.
- set_events(events: ndarray[tuple[Any, ...], dtype[Any]], source_ras: ndarray[tuple[Any, ...], dtype[floating]] | None, source_decs: ndarray[tuple[Any, ...], dtype[floating]] | None) None[source]¶
Cache per-event King PDF values for each spectral index ahead of a call to
evaluate_pdf().For each event, the nearest parametrization bin is looked up to obtain per-event alpha/beta parameters, the angular distance to the source is computed, and the King PDF is evaluated and cached for every spectral index in
spectral_indices. This must be called beforeevaluate_pdf(). Calling it again with the sameevents,source_ras, andsource_decsas the previous call is a cheap no-op, so it is safe to call once per trial without checking first.- Parameters:
events (structured array) – Data events to evaluate. Must contain
raanddecfields (reconstructed equatorial coordinates, in radians) plus any fields referenced byparametrization_bins.source_ras (ndarray) – Source right ascension(s) in radians.
source_decs (ndarray) – Source declination(s) in radians. Must have the same length as
source_ras.
- Raises:
ValueError – If
source_ras/source_decsare not provided, or their lengths do not match.
Notes
Support for multiple simultaneous sources is experimental and logs a one-time warning; results should be checked carefully in that case.
- get_alpha_beta(events)[source]¶
Look up fitted alpha/beta parameters for each event via nearest-bin lookup.
Used internally by
set_events(). Useful for inspecting the fitted King parameters assigned to specific events.- Parameters:
events (structured array) – Events to look up. Must contain the fields referenced by
parametrization_bins. Only events selected by the mask set in the most recentset_events()call are returned.- Returns:
alpha (ndarray, shape (n_gamma, n_masked_events)) – Fitted alpha values for each spectral index and event.
beta (ndarray, shape (n_gamma, n_masked_events)) – Fitted beta values for each spectral index and event.
- get_alpha_beta_gamma(gamma, events=None, alpha=None, beta=None)[source]¶
Get alpha/beta at a given spectral index, interpolating if necessary.
If
gammamatches one of the spectral indices the parameters were fit at, the stored values are returned directly. Otherwise, alpha and beta are linearly interpolated between the two bracketing spectral indices.- Parameters:
gamma (float) – Spectral index at which to evaluate alpha/beta. Can be any value; values outside the range of
spectral_indicesare extrapolated from the nearest bracketing pair.events (structured array, optional) – Events to look up alpha/beta for via
get_alpha_beta(). Only used ifalpha/betaare not already provided.alpha (ndarray, optional) – Pre-computed alpha values for all spectral indices, e.g. from
get_alpha_beta(). If provided,eventsis ignored.beta (ndarray, optional) – Pre-computed beta values for all spectral indices, matching
alpha.
- Returns:
alpha_gamma (ndarray or float) – Alpha value(s) at the requested spectral index.
beta_gamma (ndarray or float) – Beta value(s) at the requested spectral index.
- evaluate_pdf(events: ndarray[tuple[Any, ...], dtype[Any]], gamma: float = 2) csr_array[source]¶
Evaluate the King PDF at each event’s position for a given spectral index.
Uses the sparse PDF matrices cached by the most recent call to
set_events(), interpolating over spectral index as needed via a scalar lerp on the underlying.dataarrays — O(nnz) and cache-warm.- Parameters:
events (structured array) – Data events to evaluate. Must be the same events most recently passed to
set_events().gamma (float, optional) – Spectral index at which to evaluate the PDF. Default is 2.0. Interpolated between the bracketing values in
spectral_indicesif not an exact match.
- Returns:
Sparse PDF matrix. Nonzero entries hold the King PDF value (probability/steradian) for each (event, source) pair within the angular cutoff; pairs outside the cutoff are implicitly zero.
- Return type:
csr_array, shape (n_events, n_sources)
- Raises:
RuntimeError – If
eventsdoes not match the events passed to the most recent call toset_events().
- evaluate_marginalized_pdf(events: ndarray[tuple[Any, ...], dtype[Any]], gamma: float = 2) csr_array[source]¶
Evaluate the RA-marginalized King PDF for all (event, source) pairs.
Returns a sparse
(n_events, n_sources)matrix whose nonzero entries are the signal-subtraction PDF values at the requested spectral index. The result is obtained by linearly interpolating the precomputed sparse matrices fromset_events()directly on their underlying.dataarrays — both bracketing matrices share the same sparsity structure, so element-wise interpolation is valid and O(nnz).Must be called after
set_events()with the sameeventsarray. Requiresenable_marginalization=Trueat construction.- Parameters:
events (structured array) – Data events. Must match the events passed to the most recent
set_events()call.gamma (float, optional) – Spectral index at which to evaluate. Interpolated between the two nearest values in
spectral_indices. Default is 2.0.
- Returns:
Sparse marginalized PDF matrix. Zero entries correspond to (event, source) pairs separated by more than the marginalization angular cutoff.
- Return type:
csr_array, shape (n_events, n_sources)
- Raises:
RuntimeError – If marginalization was not enabled at construction, if
set_events()has not been called, or ifeventsdoes not match the cached event set.
Utilities¶
- kingmaker.utils.angular_distance(src_ra: float | ndarray[tuple[Any, ...], dtype[floating]], src_dec: float | ndarray[tuple[Any, ...], dtype[floating]], ra: float | ndarray[tuple[Any, ...], dtype[floating]], dec: float | ndarray[tuple[Any, ...], dtype[floating]]) float | ndarray[tuple[Any, ...], dtype[floating]][source]¶
Calculate angular distance on the sphere using the haversine formula.
Computes the great-circle distance between celestial coordinates using spherical trigonometry.
- Parameters:
- Returns:
Angular separation(s) in radians.
- Return type:
float or ndarray
- kingmaker.utils.meshgrid2d(a: ndarray[tuple[Any, ...], dtype[floating]], b: ndarray[tuple[Any, ...], dtype[floating]]) Tuple[ndarray[tuple[Any, ...], dtype[floating]], ndarray[tuple[Any, ...], dtype[floating]]][source]¶
Create a 2D meshgrid from 1D coordinate arrays, compatible with numba JIT compilation.
Returns transposed grids in matrix indexing (‘ij’) convention.
- Parameters:
a (ndarray) – 1D array of coordinates for first dimension.
b (ndarray) – 1D array of coordinates for second dimension.
- Returns:
grid_a (ndarray) – 2D grid of ‘a’ values with shape (len(b), len(a)).
grid_b (ndarray) – 2D grid of ‘b’ values with shape (len(b), len(a)).