binny.calibration package#

Calibration and fitting of redshift distributions and observational effects.

binny.calibration.calibrate_depth_smail_from_mock(z_true: ndarray, mag: ndarray, *, maglims: ndarray, area_deg2: float, weights: ndarray | None = None, infer_alpha_beta_from: Literal['deep_cut', 'all_selected_at_maglim'] = 'deep_cut', alpha_beta_maglim: float | None = None, z_max: float | None = None) → dict[str, Any]#

Run an end-to-end calibration of survey depth scaling relations.

This routine performs a complete calibration of the relations linking survey limiting magnitude to both the redshift distribution and the galaxy number density of a sample.

The procedure estimates the shape parameters of the Smail redshift distribution from a representative galaxy sample, calibrates how the redshift scale parameter varies with magnitude limit, and measures the corresponding galaxy number density.

The resulting calibration can be used to construct realistic analytic redshift distributions and galaxy densities for survey forecasts.

Parameters:
  • z_true – True redshifts of galaxies in the mock catalog.

  • mag – Apparent magnitudes of the same galaxies.

  • maglims – Limiting magnitudes defining magnitude-limited samples.

  • area_deg2 – Survey area of the mock catalog in square degrees.

  • weights – Optional non-negative weights for fitting the Smail redshift distribution.

  • infer_alpha_beta_from – Strategy used to determine the shape parameters of the Smail distribution.

  • alpha_beta_maglim – Magnitude limit defining the deep sample used to infer the Smail shape parameters.

  • z_max – Maximum redshift included when fitting redshift distributions.

Returns:

Dictionary containing the calibrated Smail parameters, the fitted z0–magnitude relation, and the galaxy density calibration.

binny.calibration.calibrate_psf_depth_from_mock(z_true: ndarray, mag: ndarray, r_gal: ndarray, *, maglims: ndarray, r_psf_values: ndarray, area_deg2: float, z_edges: ndarray, r_min: float = 0.3, selection_kind: Literal['hard', 'sigmoid'] = 'sigmoid', width: float = 0.05, normalize_nz: bool = True) → dict[str, Any]#

Calibrate source redshift distributions versus survey depth and PSF size.

This routine evaluates how the source redshift distribution and selection-weighted galaxy number density change across a grid of limiting magnitudes and PSF sizes. It is intended for forecasting studies that compare baseline and as-built survey scenarios.

Parameters:
  • z_true – True galaxy redshifts from the mock catalog.

  • mag – Apparent magnitudes of the same galaxies.

  • r_gal – Galaxy sizes of the same galaxies.

  • maglims – Limiting magnitudes to evaluate.

  • r_psf_values – PSF sizes to evaluate.

  • area_deg2 – Survey or mock area in square degrees.

  • z_edges – Redshift-bin edges used to histogram the selected samples.

  • r_min – Minimum resolution factor required for shear selection.

  • selection_kind – Selection model used to convert resolution into weights.

  • width – Width of the sigmoid transition for smooth selection.

  • normalize_nz – Whether to normalize each redshift distribution to unit area.

Returns:

Dictionary containing the calibration grid, redshift distributions, and selection-weighted galaxy densities.

Raises:
  • ValueError – If input catalog arrays do not have matching shapes.

  • ValueError – If area_deg2 is not positive.

binny.calibration.eval_ngal_of_maglim(maglim: ndarray, fit: dict[str, Any]) → ndarray#

Evaluate the calibrated galaxy density–magnitude relation.

This function computes the predicted galaxy number density for a set of magnitude limits using a previously calibrated density relation.

Parameters:
  • maglim – Limiting magnitudes at which the density should be evaluated.

  • fit – Calibration result describing the fitted galaxy density relation.

Returns:

Predicted galaxy number densities in galaxies per arcmin².

binny.calibration.eval_z0_of_maglim(maglim: ndarray, fit: dict[str, Any]) → ndarray#

Evaluate the calibrated z0–magnitude relation.

This function computes the characteristic Smail redshift scale for one or more magnitude limits using a previously calibrated z0–magnitude relation.

Parameters:
  • maglim – Limiting magnitudes at which the relation should be evaluated.

  • fit – Calibration result describing the fitted z0–magnitude relation.

Returns:

Predicted z0 values corresponding to the input magnitude limits.

binny.calibration.fit_ngal_of_maglim_from_mock(mag: ndarray, *, maglims: ndarray, area_deg2: float, ngal_law: Literal['linear', 'loglinear'] = 'loglinear') → dict[str, Any]#

Calibrate the galaxy number density as a function of survey depth.

This function measures the number density of galaxies in a mock catalog for a series of magnitude limits and fits a smooth empirical relation between survey depth and galaxy density.

The resulting relation can be used to predict the effective galaxy density expected for different magnitude limits in survey forecasts.

Parameters:
  • mag – Apparent magnitudes of galaxies in the mock catalog.

  • maglims – Limiting magnitudes used to define magnitude-limited samples.

  • area_deg2 – Survey area of the mock catalog in square degrees.

  • ngal_law – Functional form used to model the density–magnitude relation.

Returns:

Dictionary containing measured galaxy densities at each magnitude limit and the parameters of the fitted density relation.

binny.calibration.fit_photoz_errors(z_true: ndarray, z_obs: ndarray, *, core_min_weight: float = 0.5, n_init: int = 10, max_iter: int = 1000, tol: float = 1e-08, seed: int = 0, return_metadata: bool = False) → dict[str, float] | tuple[dict[str, float], dict[str, float | int | bool]]#

Fit a Gaussian core and displaced tail to photometric-redshift residuals.

Fits an unbinned two-component Gaussian mixture to the normalized photometric-redshift residual:

\[\epsilon = \frac{z_{\mathrm{obs}} - z_{\mathrm{true}}} {1 + z_{\mathrm{true}}}.\]

The probability density is

\[p(\epsilon) = (1 - f_{\mathrm{out}}) \mathcal{N}(\epsilon; 0, \sigma_{\mathrm{core}}^2) + f_{\mathrm{out}} \mathcal{N}(\epsilon; \mu_{\mathrm{out}}, \sigma_{\mathrm{out}}^2),\]

where scatter_scale is the core scatter, outlier_scatter_scale is the tail scatter, outlier_mean_shift is the tail displacement, and outlier_frac is the tail mixture fraction.

The core mean is fixed at zero, while the tail mean, both standard deviations, and the mixture fraction are fitted.

The fit uses expectation-maximization with multiple random initializations. All catalogue residuals must be finite; no histogram binning or residual-range truncation is applied.

Parameters:
  • z_true – One-dimensional array of true galaxy redshifts.

  • z_obs – One-dimensional array of observed photometric redshifts, with the same shape as z_true.

  • core_min_weight – Minimum allowed core mixture fraction. Must lie strictly between zero and one. The default value of 0.5 restricts outlier_frac to at most 0.5.

  • n_init – Number of random expectation-maximization initializations. Must be positive. Defaults to 10.

  • max_iter – Maximum number of expectation-maximization iterations per initialization. Must be positive. Defaults to 1000.

  • tol – Relative log-likelihood convergence tolerance. Must be positive and finite. Defaults to 1e-8.

  • seed – Random seed controlling the expectation-maximization initializations. Defaults to 0.

  • return_metadata – Whether to return fitting diagnostics alongside the fitted parameters. Defaults to False.

Returns:

  • scatter_scale: Standard deviation of the zero-mean core.

  • outlier_scatter_scale: Standard deviation of the Gaussian tail.

  • outlier_mean_shift: Mean displacement of the Gaussian tail.

  • outlier_frac: Fitted tail mixture fraction.

If return_metadata=True, returns a tuple containing the fitted parameter dictionary and a metadata dictionary with:

  • loglike: Total log-likelihood of the selected fit.

  • n: Number of catalogue objects used in the fit.

  • n_outside: Number of excluded residuals, always zero.

  • converged: Whether the selected optimization converged.

  • n_iter: Number of iterations in the selected optimization.

  • aic: Akaike information criterion.

  • bic: Bayesian information criterion.

  • ks_statistic: Kolmogorov-Smirnov statistic.

Return type:

Dictionary containing the fitted photometric-redshift parameters

Raises:
  • ValueError – If the catalogue arrays have incompatible shapes, contain insufficient or non-finite values, or contain true redshifts less than or equal to -1.

  • ValueError – If the residual distribution is degenerate.

  • ValueError – If core_min_weight, n_init, max_iter, or tol violates its allowed range.

Notes

The Akaike and Bayesian information criteria are computed using four free mixture parameters. They are intended for relative model comparison rather than as absolute goodness-of-fit measures.

The Kolmogorov-Smirnov statistic is descriptive because the fitted parameters are estimated from the same catalogue.

The reported outlier_frac is a mixture-model parameter and does not necessarily correspond to a uniquely identifiable population of catastrophic photometric-redshift outliers.

The fitted outlier_mean_shift is converted into Binny’s outlier_mean_scale and outlier_mean_offset by to_binny_photoz_params.

binny.calibration.fit_smail_params_from_mock(z_samples: ndarray, *, weights: ndarray | None = None, alpha_bounds: tuple[float, float] = (0.2, 8.0), beta_bounds: tuple[float, float] = (0.2, 6.0), z0_bounds: tuple[float, float] = (0.01, 5.0), x0: tuple[float, float, float] | None = None, z_max: float | None = None, min_n: int = 200) → dict[str, Any]#

Infer Smail distribution parameters from a mock redshift sample.

This function estimates the Smail parameters alpha, beta, and z0 from galaxy redshifts. Optional weights can be used to represent weighted selections, such as PSF-dependent shear-selection weights.

Parameters:
  • z_samples – Galaxy redshifts drawn from a mock or simulated catalog.

  • weights – Optional non-negative weights for the redshift samples.

  • alpha_bounds – Allowed range for the alpha parameter.

  • beta_bounds – Allowed range for the beta parameter.

  • z0_bounds – Allowed range for the z0 parameter.

  • x0 – Initial parameter guess (alpha, beta, z0).

  • z_max – Maximum redshift used when fitting the distribution.

  • min_n – Minimum number of valid redshift samples required to perform the fit.

Returns:

Dictionary containing the fitted parameters, fit status, and summary information about the calibration sample.

Raises:
  • RuntimeError – If SciPy optimization is unavailable.

  • ValueError – If weights does not have the same shape as z_samples.

binny.calibration.fit_z0_of_maglim_from_mock(z_true: ndarray, mag: ndarray, *, maglims: ndarray, alpha: float, beta: float, weights: ndarray | None = None, z0_law: Literal['linear', 'poly2'] = 'linear', z0_bounds: tuple[float, float] = (0.01, 5.0), z_max: float | None = None, min_n_per_cut: int = 200) → dict[str, Any]#

Calibrate the relation between survey depth and the Smail scale parameter.

This function measures how the characteristic redshift scale (z0) of a galaxy population evolves with survey limiting magnitude. For each magnitude limit, galaxies are selected from a mock catalog and the corresponding redshift distribution is fitted with a Smail model with fixed shape parameters.

The resulting z0 measurements are then used to fit a smooth empirical relation between the magnitude limit and the redshift scale.

Parameters:
  • z_true – True redshifts of galaxies in the mock catalog.

  • mag – Apparent magnitudes of galaxies in the same catalog.

  • maglims – Limiting magnitudes at which the calibration should be evaluated.

  • alpha – Fixed alpha parameter of the Smail distribution.

  • beta – Fixed beta parameter of the Smail distribution.

  • weights – Optional non-negative weights for the redshift samples.

  • z0_law – Functional form used to model the z0–magnitude relation.

  • z0_bounds – Allowed range for the fitted z0 values.

  • z_max – Maximum redshift considered when fitting the distribution.

  • min_n_per_cut – Minimum number of galaxies required for a magnitude selection to be included in the calibration.

Returns:

Dictionary containing the measured z0 values at each magnitude limit and the parameters of the fitted z0–magnitude relation.

binny.calibration.photoz_residual_cdf(x: ndarray, *, scatter_scale: float, outlier_scatter_scale: float, outlier_mean_shift: float, outlier_frac: float) → ndarray#

Evaluate the photometric-redshift residual cumulative distribution.

Parameters:
  • x – One-dimensional array of normalized residual values.

  • scatter_scale – Standard deviation of the core component.

  • outlier_scatter_scale – Standard deviation of the outlier component.

  • outlier_mean_shift – Mean displacement of the outlier component.

  • outlier_frac – Outlier mixture fraction between zero and one.

Returns:

Mixture cumulative probability evaluated at each residual value.

Raises:

ValueError – If the residuals or mixture parameters are invalid.

binny.calibration.photoz_residual_pdf(x: ndarray, *, scatter_scale: float, outlier_scatter_scale: float, outlier_mean_shift: float, outlier_frac: float, return_components: bool = False) → ndarray | tuple[ndarray, dict[str, ndarray]]#

Evaluate the photometric-redshift residual probability density.

Evaluates an analytically normalized Gaussian mixture consisting of a zero-mean core and a displaced outlier component.

Parameters:
  • x – One-dimensional array of normalized residual values.

  • scatter_scale – Standard deviation of the core component.

  • outlier_scatter_scale – Standard deviation of the outlier component.

  • outlier_mean_shift – Mean displacement of the outlier component.

  • outlier_frac – Outlier mixture fraction between zero and one.

  • return_components – Whether to return the individual weighted component densities alongside the total density.

Returns:

Mixture probability density evaluated at the supplied residuals. If return_components is True, also returns a dictionary containing the weighted core and outlier densities.

Raises:

ValueError – If the residuals or mixture parameters are invalid.

binny.calibration.resolution_factor(r_gal: ndarray, r_psf: float) → ndarray#

Compute the resolution factor of galaxies relative to the PSF.

The resolution factor describes how well a galaxy is resolved compared with the point-spread function. Values close to zero correspond to poorly resolved galaxies, while values close to one correspond to well-resolved galaxies.

Parameters:
  • r_gal – Intrinsic or pre-seeing galaxy sizes.

  • r_psf – Characteristic PSF size in the same units as r_gal.

Returns:

Galaxy resolution factors.

Raises:

ValueError – If r_psf is negative.

binny.calibration.sample_photoz_errors(z_true: ndarray, *, scatter_scale: float, outlier_scatter_scale: float, outlier_mean_shift: float, outlier_frac: float, seed: int | None = None, rng: Generator | None = None) → ndarray#

Sample observed redshifts from a Gaussian photo-z error model.

Draw normalized residuals from the core and outlier mixture and convert them into observed redshifts.

Parameters:
  • z_true – One-dimensional array of finite true redshifts greater than -1.

  • scatter_scale – Positive, finite core standard deviation.

  • outlier_scatter_scale – Positive, finite tail standard deviation.

  • outlier_mean_shift – Finite tail mean displacement.

  • outlier_frac – Tail mixture fraction between zero and one.

  • seed – Optional random seed.

  • rng – Optional NumPy random number generator. Cannot be supplied together with seed.

Returns:

Sampled observed redshifts with the same shape as z_true.

Raises:

ValueError – If redshifts, mixture parameters, or random number generator arguments are invalid.

Notes

Outlier membership is sampled independently for each galaxy. Observed redshifts are not clipped or truncated.

binny.calibration.selected_number_density_from_mock(mag: ndarray, r_gal: ndarray, *, maglim: float, r_psf: float, area_deg2: float, r_min: float = 0.3, selection_kind: Literal['hard', 'sigmoid'] = 'hard', width: float = 0.05) → float#

Estimates the PSF-selected galaxy density from a mock catalog.

This function computes the selection-weighted source density after applying a magnitude limit and a PSF-dependent shear-selection weight. It does not include shape measurement noise and is therefore distinct from the noise-equivalent weak-lensing effective number density.

Parameters:
  • mag – Apparent magnitudes from the mock catalog.

  • r_gal – Galaxy sizes of the same galaxies.

  • maglim – Limiting magnitude used to define the source sample.

  • r_psf – Characteristic PSF size in the same units as r_gal.

  • area_deg2 – Survey or mock area in square degrees.

  • r_min – Minimum resolution factor required for shear selection.

  • selection_kind – Selection model used to convert resolution into weights.

  • width – Width of the sigmoid transition for smooth selection.

Returns:

Weighted galaxy number density in galaxies per arcmin².

Raises:
  • ValueError – If input catalog arrays do not have matching shapes.

  • ValueError – If area_deg2 is not positive.

binny.calibration.shear_selection_weight(r_gal: ndarray, *, r_psf: float, r_min: float = 0.3, kind: Literal['hard', 'sigmoid'] = 'sigmoid', width: float = 0.05) → ndarray#

Compute PSF-dependent shear-selection weights.

This function assigns each galaxy a weight describing whether it remains usable for shear measurements after accounting for PSF resolution. The selection can be either a hard resolution threshold or a smooth sigmoid transition around the threshold.

Parameters:
  • r_gal – Intrinsic or pre-seeing galaxy sizes.

  • r_psf – Characteristic PSF size in the same units as r_gal.

  • r_min – Minimum resolution factor required for shear selection.

  • kind – Selection model used to convert resolution into weights.

  • width – Width of the sigmoid transition when kind="sigmoid".

Returns:

Shear-selection weights between zero and one.

Raises:
  • ValueError – If r_min is outside [0, 1].

  • ValueError – If kind is not supported.

  • ValueError – If width is not positive for sigmoid selection.

binny.calibration.to_binny_photoz_params(fit: dict) → dict[str, float]#

Convert fitted parameters to Binny’s photometric-redshift assignment model.

Converts the fitted Gaussian-mixture parameters into the complete parameter dictionary expected by Binny’s photometric-redshift assignment model.

The fitted core has zero mean and scatter scatter_scale. The displaced tail has scatter outlier_scatter_scale, displacement outlier_mean_shift, and mixture fraction outlier_frac.

The tail displacement is represented in Binny using

outlier_mean_scale = 1 + outlier_mean_shift outlier_mean_offset = -outlier_mean_shift.

Parameters:

fit – Dictionary containing scatter_scale, outlier_scatter_scale, outlier_mean_shift, and outlier_frac. Additional diagnostic entries are ignored.

Returns:

  • mean_scale: Core mean scale, fixed at 1.

  • mean_offset: Core mean offset, fixed at 0.

  • scatter_scale: Fitted core scatter.

  • outlier_frac: Fitted tail mixture fraction.

  • outlier_mean_scale: Tail mean scale, equal to 1 + outlier_mean_shift.

  • outlier_mean_offset: Tail mean offset, equal to -outlier_mean_shift.

  • outlier_scatter_scale: Fitted tail scatter.

Return type:

Dictionary containing the photometric-redshift assignment parameters

Raises:
  • ValueError – If outlier_mean_shift is less than or equal to -1, making the corresponding mean scale non-positive.

  • KeyError – If a required fitted parameter is missing.

Notes

The conversion preserves the fitted normalized residual model

epsilon = (z_obs - z_true) / (1 + z_true)

when used with Binny’s photometric-redshift assignment probability function.

binny.calibration.weighted_nz_from_mock(z_true: ndarray, mag: ndarray, r_gal: ndarray, *, maglim: float, r_psf: float, z_edges: ndarray, r_min: float = 0.3, selection_kind: Literal['hard', 'sigmoid'] = 'sigmoid', width: float = 0.05, normalize: bool = True) → tuple[ndarray, ndarray, ndarray, ndarray]#

Build a PSF-selected redshift distribution from a mock catalog.

This function estimates the source redshift distribution after applying a magnitude limit and a PSF-dependent shear-selection weight. It returns the selected redshifts, redshift-bin centers, weighted distribution, and selection weights.

Parameters:
  • z_true – True galaxy redshifts from the mock catalog.

  • mag – Apparent magnitudes of the same galaxies.

  • r_gal – Galaxy sizes of the same galaxies.

  • maglim – Limiting magnitude used to define the source sample.

  • r_psf – Characteristic PSF size in the same units as r_gal.

  • z_edges – Redshift-bin edges used to histogram the selected sample.

  • r_min – Minimum resolution factor required for shear selection.

  • selection_kind – Selection model used to convert resolution into weights.

  • width – Width of the sigmoid transition for smooth selection.

  • normalize – Whether to normalize the redshift distribution to unit area.

Returns:

Tuple containing selected redshifts, redshift-bin centers, the weighted redshift distribution, and selection weights.

Raises:
  • ValueError – If input catalog arrays do not have matching shapes.

  • ValueError – If z_edges does not contain at least two bin edges.

Submodules#