binny.analysis package#

Scientific analysis, comparison, composition, and correlation filtering.

binny.analysis.align_bin_grids(z_a: ndarray, bins_a: Mapping[int, ndarray], z_b: ndarray, bins_b: Mapping[int, ndarray]) → tuple[ndarray, dict[int, ndarray], dict[int, ndarray]]#

Align two bin collections onto their union redshift grid.

binny.analysis.between_bin_overlap(z_a: Any, bins_a: Mapping[int, Any], z_b: Any, bins_b: Mapping[int, Any], *, method: str = 'min', unit: Literal['fraction', 'percent'] = 'fraction', normalize: bool = False, rtol: float = 0.001, atol: float = 1e-06, decimal_places: int | None = 2) → dict[int, dict[int, float]]#

Compare bins from two tomographic samples.

Parameters:
  • z_a – Redshift grid of the first sample.

  • bins_a – Distributions of the first sample.

  • z_b – Redshift grid of the second sample.

  • bins_b – Distributions of the second sample.

  • method – Comparison metric: min, cosine, js, hellinger, or tv.

  • unit – Fraction or percent.

  • normalize – Whether to normalize the distributions.

  • rtol – Relative normalization tolerance.

  • atol – Absolute normalization tolerance.

  • decimal_places – Number of decimal places, or None.

Returns:

Matrix comparing bins from the first and second samples.

Raises:

ValueError – If the metric or input distributions are invalid.

binny.analysis.between_interval_mass_matrix(z: Any, bins: Mapping[int, Any], target_edges: Mapping[int, tuple[float, float]] | Sequence[float] | ndarray, *, unit: Literal['fraction', 'percent'] = 'fraction', decimal_places: int | None = 2) → dict[int, dict[int, float]]#

Measure how much of each bin lies within target intervals.

Parameters:
  • z – Redshift grid.

  • bins – Input redshift distributions.

  • target_edges – Redshift intervals to compare against.

  • unit – Fraction or percent.

  • decimal_places – Number of decimal places, or None.

Returns:

Matrix where entry (i, j) gives the fraction of input bin i within target interval j.

Raises:

ValueError – If the intervals, units, or bin masses are invalid.

binny.analysis.between_overlap_pairs(z_a: Any, bins_a: Mapping[int, Any], z_b: Any, bins_b: Mapping[int, Any], *, threshold: float = 10.0, unit: Literal['fraction', 'percent'] = 'percent', method: str = 'min', direction: Literal['high', 'low'] = 'high', normalize: bool = False, rtol: float = 0.001, atol: float = 1e-06, decimal_places: int | None = 2) → list[tuple[int, int, float]]#

Find bin pairs from two samples that pass a threshold.

Parameters:
  • z_a – Redshift grid of the first sample.

  • bins_a – Distributions of the first sample.

  • z_b – Redshift grid of the second sample.

  • bins_b – Distributions of the second sample.

  • threshold – Minimum or maximum accepted value.

  • unit – Fraction or percent, including the threshold.

  • method – Comparison metric: min, cosine, js, hellinger, or tv.

  • direction – Select values above or below the threshold.

  • normalize – Whether to normalize the distributions.

  • rtol – Relative normalization tolerance.

  • atol – Absolute normalization tolerance.

  • decimal_places – Number of decimal places, or None.

Returns:

Sorted list of matching cross-sample bin pairs.

Raises:

ValueError – If the direction, metric, or inputs are invalid.

binny.analysis.between_pearson_matrix(z_a: Any, bins_a: Mapping[int, Any], z_b: Any, bins_b: Mapping[int, Any], *, normalize: bool = False, rtol: float = 0.001, atol: float = 1e-06, decimal_places: int | None = 2) → dict[int, dict[int, float]]#

Calculate Pearson correlations between bins from two samples.

Parameters:
  • z_a – Redshift grid of the first sample.

  • bins_a – Distributions of the first sample.

  • z_b – Redshift grid of the second sample.

  • bins_b – Distributions of the second sample.

  • normalize – Whether to normalize the distributions.

  • rtol – Relative normalization tolerance.

  • atol – Absolute normalization tolerance.

  • decimal_places – Number of decimal places, or None.

Returns:

Matrix of cross-sample Pearson correlation coefficients.

Raises:

ValueError – If the input distributions are invalid.

binny.analysis.bin_centers(z: Any, bins: Mapping[int, Any], *, method: str = 'mean', decimal_places: int | None = 2) → dict[int, float]#

Compute one center value per tomographic bin.

Supported methods:
  • "mean": weighted mean redshift.

  • "median": weighted median redshift.

  • "mode": grid-point mode.

  • "pXX": weighted percentile, where XX is between 0 and 100

    (e.g. "p50").

Parameters:
  • z – One-dimensional redshift grid shared by all bins.

  • bins – Mapping from bin index to bin curves evaluated on z.

  • method – Center definition.

  • decimal_places – If not None, round each returned center to this many decimal places. If None, return full-precision floats.

Returns:

Mapping from bin index to the chosen center value.

Raises:
  • ValueError – If method is invalid.

  • ValueError – If any bin has non-positive total weight when needed.

binny.analysis.bin_moments(z: Any, nz_bin: Any) → dict[str, float]#

Compute standard shape summaries for a single bin curve.

The input is a redshift grid z and a corresponding bin curve nz_bin evaluated on that grid. The curve is treated as a nonnegative weight function; it does not need to be normalized.

Returned keys:
  • "mean": weighted mean redshift.

  • "median": weighted median redshift.

  • "mode": redshift value on the input grid where nz_bin is maximal.

  • "std": weighted standard deviation.

  • "skewness": standardized third central moment (dimensionless).

  • "kurtosis": standardized fourth central moment minus 3 (dimensionless).

  • "iqr": interquartile range (q75 - q25).

  • "width_68": central 68% interval width (q84 - q16).

Notes

  • Percentile-based summaries depend on the sampling of the grid.

  • The mode is grid-dependent by definition.

Parameters:
  • z – One-dimensional redshift grid.

  • nz_bin – Bin curve values evaluated on z.

Returns:

Dictionary of summary statistics.

Raises:

ValueError – If the total weight (integral of nz_bin) is not positive.

binny.analysis.bin_overlap(z: Any, bins: Mapping[int, Any], *, method: str = 'min', unit: Literal['fraction', 'percent'] = 'fraction', normalize: bool = False, rtol: float = 0.001, atol: float = 1e-06, decimal_places: int | None = 2) → dict[int, dict[int, float]]#

Compare all pairs of bins within one tomographic sample.

Parameters:
  • z – Redshift grid.

  • bins – Redshift distributions indexed by bin.

  • method – Comparison metric: min, cosine, js, hellinger, or tv.

  • unit – Fraction or percent.

  • normalize – Whether to normalize the distributions.

  • rtol – Relative normalization tolerance.

  • atol – Absolute normalization tolerance.

  • decimal_places – Number of decimal places, or None.

Returns:

Symmetric matrix of pairwise comparison values.

Raises:

ValueError – If the metric or input distributions are invalid.

binny.analysis.bin_quantiles(z: Any, nz_bin: Any, qs: Sequence[float]) → dict[float, float]#

Compute weighted quantiles of a single bin curve.

The curve nz_bin is treated as a nonnegative weight curve evaluated on z. For each requested quantile q in [0, 1], this returns the redshift value where the cumulative integral reaches q of the total weight.

Parameters:
  • z – One-dimensional redshift grid.

  • nz_bin – Bin curve values evaluated on z.

  • qs – Quantiles to compute, as fractions between 0 and 1.

Returns:

Mapping from each requested quantile to the corresponding redshift value.

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

  • ValueError – If the total weight is not positive.

binny.analysis.combine_parent_nz(samples: Sequence[Mapping[str, ndarray]], *, interpolate: bool = False, z_target: ndarray | None = None) → tuple[ndarray, ndarray]#

Combine parent redshift distributions on a shared grid.

binny.analysis.combine_tomographies(samples: Sequence[Tomography], *, interpolate: bool = False, z_target: ndarray | None = None) → Tomography#

Combine tomographies with matching bin indices by summing curves.

binny.analysis.comoving_density_per_bin(total_count_per_bin: Mapping[int, float], volume_per_bin: Mapping[int, float]) → dict[int, float]#

Compute per-bin comoving number densities from counts and volumes.

binny.analysis.filter_by_curve_norm_threshold(tuples: Sequence[tuple[int, ...]], *, norms: Sequence[Mapping[int, float]], threshold: float, compare: Literal['lt', 'le', 'gt', 'ge'] = 'ge', mode: Literal['all', 'any'] = 'all') → list[tuple[int, ...]]#

Filter tuples based on per-position curve norms.

This filter keeps tuples based on the integrated normalization of the curve at each tuple position. It is useful for excluding tuples containing bins with negligible support.

For each tuple t, compare the norm at each position p (using t[p]) to the given threshold. With mode=”all”, every position must pass; with mode=”any”, at least one position must pass.

Parameters:
  • tuples – Sequence of index tuples to be filtered.

  • norms – Sequence of per-position norm mappings.

  • threshold – Reference value used for filtering.

  • compare – Comparison operator applied to each norm versus threshold.

  • mode – Whether to require all positions (“all”) or at least one (“any”).

Returns:

List of index tuples that satisfy the norm threshold condition.

Raises:
  • ValueError – If mode is not recognized, or norms do not cover tuple positions.

  • KeyError – If a required index is missing from norms.

binny.analysis.filter_by_metric_threshold(tuples: Sequence[tuple[int, ...]], *, metric: Callable[[...], float], threshold: float, compare: Literal['lt', 'le', 'gt', 'ge'] = 'le') → list[tuple[int, ...]]#

Filter index tuples using an n-ary metric threshold.

Each tuple is evaluated using the supplied metric function and retained if the resulting value satisfies the requested comparison against the given threshold.

The metric is called as metric(*t), where t is the tuple.

Parameters:
  • tuples – Sequence of index tuples to be filtered.

  • metric – Callable returning a scalar metric value for a given tuple.

  • threshold – Reference value used for filtering.

  • compare – Comparison operator applied as metric(*t) op threshold.

Returns:

List of index tuples that satisfy the metric threshold condition.

Raises:

ValueError – If the comparison operator is not recognized.

binny.analysis.filter_by_score_consistency(tuples: Sequence[tuple[int, ...]], *, scores1: Sequence[Mapping[int, float]], scores2: Sequence[Mapping[int, float]], pos_a: int = 0, pos_b: int = 1, relation: Literal['lt', 'le', 'gt', 'ge'] = 'lt') → list[tuple[int, ...]]#

Filter tuples that satisfy the same ordering under two score definitions.

This filter keeps a tuple only if it satisfies the requested ordering under two independently computed score maps (for the same tuple positions), such as peak and mean locations.

For each tuple t, apply the requested relation to the scores at t[pos_a] and t[pos_b] under both scores1 and scores2. The tuple is kept only when the relation holds for both score definitions.

Parameters:
  • tuples – Sequence of index tuples to be filtered.

  • scores1 – First set of per-position score mappings.

  • scores2 – Second set of per-position score mappings.

  • pos_a – First tuple position in the comparison.

  • pos_b – Second tuple position in the comparison.

  • relation – Comparison operator applied for both score definitions.

Returns:

List of index tuples satisfying the ordering under both score maps.

Raises:
  • ValueError – If positions are invalid, tuple is too short, or scores lengths mismatch.

  • KeyError – If a required index is missing from any score mapping.

binny.analysis.filter_by_score_difference(tuples: Sequence[tuple[int, ...]], *, scores: Sequence[Mapping[int, float]], pos_a: int = 0, pos_b: int = 1, min_diff: float | None = None, max_diff: float | None = None) → list[tuple[int, ...]]#

Filter index tuples by signed score difference between two positions.

This filter keeps tuples based on the signed difference between two tuple positions. It is useful for directional selections such as “position pos_b is behind pos_a” when the score encodes an ordering variable.

For each tuple t, compute the signed difference between the scores at t[pos_a] and t[pos_b]. The tuple is kept when the difference falls within the requested bounds (ignoring bounds set to None).

Parameters:
  • tuples – Sequence of index tuples to be filtered.

  • scores – Sequence of per-position score mappings.

  • pos_a – First tuple position in the difference.

  • pos_b – Second tuple position in the difference.

  • min_diff – Optional minimum signed difference to enforce.

  • max_diff – Optional maximum signed difference to enforce.

Returns:

List of index tuples that satisfy the difference bounds.

Raises:
  • ValueError – If pos_a or pos_b is out of range, or tuple is too short.

  • KeyError – If a required index is missing from the score mappings.

binny.analysis.filter_by_score_relation(tuples: Sequence[tuple[int, ...]], *, scores: Sequence[Mapping[int, float]], pos_a: int = 0, pos_b: int = 1, relation: Literal['lt', 'le', 'gt', 'ge'] = 'lt') → list[tuple[int, ...]]#

Filter index tuples by a relation between two position scores.

This filter generalizes pair-wise score comparison to arbitrary tuples by comparing the score at one tuple position to the score at another.

For each tuple t, compare the score associated with t[pos_b] to the score associated with t[pos_a], using the requested relation. The tuple is kept when that comparison passes.

Parameters:
  • tuples – Sequence of index tuples to be filtered.

  • scores – Sequence of per-position score mappings. scores[p] maps the index value at tuple position p to a scalar score.

  • pos_a – First tuple position in the comparison.

  • pos_b – Second tuple position in the comparison.

  • relation – Comparison operator applied between the scores at t[pos_b] and t[pos_a].

Returns:

List of index tuples that satisfy the requested score relation.

Raises:
  • ValueError – If pos_a or pos_b is out of range, or tuple is too short.

  • KeyError – If a required index is missing from the score mappings.

binny.analysis.filter_by_score_separation(tuples: Sequence[tuple[int, ...]], *, scores: Sequence[Mapping[int, float]], pos_a: int = 0, pos_b: int = 1, min_sep: float | None = None, max_sep: float | None = None, absolute: bool = True) → list[tuple[int, ...]]#

Filter index tuples by separation between two position scores.

This filter keeps tuples whose score separation lies within a requested window. It is useful when the score encodes a physical location, such as a peak, mean, or median along a redshift grid.

For each tuple t, compute the separation between the scores at t[pos_a] and t[pos_b]. If absolute=True, the absolute separation is used. The tuple is kept when the separation falls within the requested bounds (ignoring bounds set to None).

Parameters:
  • tuples – Sequence of index tuples to be filtered.

  • scores – Sequence of per-position score mappings.

  • pos_a – First tuple position in the separation.

  • pos_b – Second tuple position in the separation.

  • min_sep – Optional minimum separation to enforce.

  • max_sep – Optional maximum separation to enforce.

  • absolute – If True, apply bounds to the absolute separation.

Returns:

List of index tuples that satisfy the separation bounds.

Raises:
  • ValueError – If positions are invalid, tuple is too short, or bounds are negative.

  • KeyError – If a required index is missing from the score mappings.

binny.analysis.filter_by_width_ratio(tuples: Sequence[tuple[int, ...]], *, widths: Sequence[Mapping[int, float]], pos_a: int = 0, pos_b: int = 1, max_ratio: float = 2.0, symmetric: bool = True) → list[tuple[int, ...]]#

Filter tuples by compatibility of per-index widths at two positions.

This filter compares the width-like scalar at two tuple positions. It is useful when widths encode resolution or spread and you want to avoid mixing extremely different bin widths.

For each tuple t, form the ratio of the width at t[pos_b] to the width at t[pos_a]. If symmetric=True, the ratio is made symmetric by using the larger of r and 1/r. The tuple is kept when the resulting ratio does not exceed max_ratio.

Parameters:
  • tuples – Sequence of index tuples to be filtered.

  • widths – Sequence of per-position width mappings.

  • pos_a – First tuple position in the comparison.

  • pos_b – Second tuple position in the comparison.

  • max_ratio – Maximum allowed ratio (must be >= 1).

  • symmetric – If True, enforce ratio symmetry between the two positions.

Returns:

List of index tuples that satisfy the width ratio constraint.

Raises:
  • ValueError – If positions are invalid, tuple is too short, or max_ratio < 1.

  • KeyError – If a required index is missing from widths.

binny.analysis.galaxy_count_per_bin(density_per_bin: Mapping[int, float], survey_area: float) → dict[int, float]#

Convert per-bin surface densities to effective counts using a survey area.

Conventions:
  • density_per_bin values are in galaxies per square arcminute.

  • survey_area is in square arcminutes.

  • returned counts are dimensionless effective counts.

Parameters:
  • density_per_bin – Mapping from bin index to surface density (gal/arcmin^2).

  • survey_area – Survey area (arcmin^2).

Returns:

Mapping from bin index to effective counts.

Raises:
  • ValueError – If survey_area is not positive.

  • ValueError – If any density is negative.

binny.analysis.galaxy_density_per_bin(metadata: Mapping[str, Any], density_total: float) → dict[int, float]#

Computes per-bin surface densities from tomo metadata and total effective density..

Parameters:
  • metadata – Tomography metadata containing metadata["bins"]["frac_per_bin"].

  • density_total – Total effective surface density (gal/arcmin^2).

Returns:

gal/arcmin^2}.

Return type:

Mapping {bin_idx

Raises:
  • ValueError – If density_total is negative.

  • ValueError – If metadata does not contain valid fractions.

binny.analysis.galaxy_fraction_per_bin(meta: Mapping[str, Any]) → dict[int, float]#

Extract and normalize per-bin population fractions from tomo metadata.

binny.analysis.in_range_fraction(z: Any, nz_bin: Any, z_min: float, z_max: float) → float#

Compute the fraction of a bin curve contained in a redshift range.

This integrates nz_bin over the full grid and over [z_min, z_max] and returns inside / total.

Parameters:
  • z – One-dimensional redshift grid.

  • nz_bin – Bin curve values evaluated on z.

  • z_min – Lower bound of the range.

  • z_max – Upper bound of the range.

Returns:

Fraction of the total bin weight contained in [z_min, z_max].

Raises:
  • ValueError – If z_max <= z_min.

  • ValueError – If the total weight is not positive.

binny.analysis.in_range_fraction_per_bin(z: Any, bins: Mapping[int, Any], bin_edges: Mapping[int, tuple[float, float]] | Sequence[float]) → dict[int, float]#

Compute the in-range fraction for each bin given nominal edges.

bin_edges can be either:
  • mapping {bin_idx: (z_min, z_max)}, or

  • a sequence of edges [e0, e1, ..., eN] where bin i uses [e_i, e_{i+1}].

Parameters:
  • z – One-dimensional redshift grid shared by all bins.

  • bins – Mapping from bin index to bin curves evaluated on z.

  • bin_edges – Nominal edges mapping or edge sequence.

Returns:

Mapping from bin index to fraction of its weight inside its nominal range.

Raises:

ValueError – If required edges are missing or malformed.

binny.analysis.interpolate_tomography(sample: Tomography, z_target: ndarray) → Tomography#

Interpolate a tomography result onto a target redshift grid.

binny.analysis.leakage_matrix(z: Any, bins: Mapping[int, Any], bin_edges: Mapping[int, tuple[float, float]] | Sequence[float] | ndarray, *, unit: Literal['fraction', 'percent'] = 'fraction', decimal_places: int | None = 2) → dict[int, dict[int, float]]#

Measure how much of each bin lies within each nominal bin interval.

Parameters:
  • z – Redshift grid.

  • bins – Redshift distributions indexed by bin.

  • bin_edges – Nominal redshift intervals of the bins.

  • unit – Fraction or percent.

  • decimal_places – Number of decimal places, or None.

Returns:

Matrix where entry (i, j) gives the fraction of bin i within the nominal interval of bin j.

Raises:

ValueError – If the intervals, units, or bin masses are invalid.

binny.analysis.make_bin_combo_filter(tomo: Tomography, other: Tomography | None = None) → BinComboFilter#

Create a bin-combination filter from one or two tomographies.

binny.analysis.metric_from_curves(*, curves: Sequence[Mapping[int, NDArray[float64]]], kernel: Callable[[...], float]) → Callable[[...], float]#

Construct an index metric from a curve-level kernel.

The returned metric evaluates index tuples by applying the provided kernel to the corresponding curve arrays.

With two curve mappings, the callable is pairwise (i, j). With three, it is (i, j, k), and so on.

Parameters:
  • curves – Sequence of curve mappings, one per index slot.

  • kernel – Callable computing a scalar value from N curve arrays.

Returns:

Callable metric function taking N indices and returning a scalar value.

Raises:
  • KeyError – If a requested index is not present in the curve mappings.

  • TypeError – If the returned callable is called with the wrong number of indices.

binny.analysis.metric_min_overlap_fraction(*, z: NDArray[float64], curves: Sequence[Mapping[int, NDArray[float64]]]) → Callable[[...], float]#

Construct a normalized minimum-overlap metric for curve tuples.

The returned metric evaluates the fractional overlap between N curves as the integral of their pointwise minimum divided by the product of their individual integrals.

For N=2 this reduces to the usual pairwise overlap fraction. Supplying three curve mappings yields a triple-overlap fraction, and so on.

Parameters:
  • z – One-dimensional coordinate grid.

  • curves – Sequence of curve mappings, one per index slot.

Returns:

Callable metric function taking N indices and returning a scalar overlap fraction.

Raises:
  • ValueError – If curves is empty or if any curve does not match the shape of z.

  • KeyError – If a requested index is not present in the curve mappings.

  • TypeError – If the returned callable is called with the wrong number of indices.

binny.analysis.metric_overlap_coefficient(*, z: NDArray[float64], curves: Sequence[Mapping[int, NDArray[float64]]]) → Callable[[...], float]#

Construct an overlap coefficient metric for curve tuples.

The overlap coefficient is defined as the integral of the pointwise minimum of N curves divided by the smallest of their individual integrals.

For N=2 this reduces to the usual overlap coefficient. Supplying three curve mappings yields a triple-overlap coefficient, and so on.

Parameters:
  • z – One-dimensional coordinate grid.

  • curves – Sequence of curve mappings, one per index slot.

Returns:

Callable metric function taking N indices and returning a scalar overlap coefficient.

Raises:
  • ValueError – If curves is empty or if any curve does not match the shape of z.

  • KeyError – If a requested index is not present in the curve mappings.

  • TypeError – If the returned callable is called with the wrong number of indices.

binny.analysis.overlap_pairs(z: Any, bins: Mapping[int, Any], *, threshold: float = 10.0, unit: Literal['fraction', 'percent'] = 'percent', method: str = 'min', direction: Literal['high', 'low'] = 'high', normalize: bool = False, rtol: float = 0.001, atol: float = 1e-06, decimal_places: int | None = 2) → list[tuple[int, int, float]]#

Find bin pairs whose comparison values pass a threshold.

Parameters:
  • z – Redshift grid.

  • bins – Redshift distributions indexed by bin.

  • threshold – Minimum or maximum accepted value.

  • unit – Fraction or percent, including the threshold.

  • method – Comparison metric: min, cosine, js, hellinger, or tv.

  • direction – Select values above or below the threshold.

  • normalize – Whether to normalize the distributions.

  • rtol – Relative normalization tolerance.

  • atol – Absolute normalization tolerance.

  • decimal_places – Number of decimal places, or None.

Returns:

Sorted list of matching bin pairs and their values.

Raises:

ValueError – If the direction, metric, or inputs are invalid.

binny.analysis.pairs_all(keys: Sequence[int]) → list[tuple[int, int]]#

Construct all ordered index correlations from a single key set.

This topology enumerates every possible combination of two indices drawn from the same set. The order of indices matters, so both (i, j) and (j, i) are included whenever i and j are distinct.

Formally, this returns all correlations (i, j) such that i and j are elements of the provided key sequence.

Parameters:

keys – Sequence of integer keys.

Returns:

List of ordered correlations (i, j).

binny.analysis.pairs_cartesian(keys_a: Sequence[int], keys_b: Sequence[int]) → list[tuple[int, int]]#

Construct ordered correlations from two distinct key sets.

This topology forms correlations by drawing the first index from one set and the second index from another. The two positions are not interchangeable, and no symmetry is implied.

In index notation, this returns all correlations (i, j) such that i is drawn from the first key set and j is drawn from the second.

Parameters:
  • keys_a – Sequence of integer keys for the first index.

  • keys_b – Sequence of integer keys for the second index.

Returns:

List of ordered correlations (i, j).

binny.analysis.pairs_diagonal(keys: Sequence[int]) → list[tuple[int, int]]#

Construct diagonal index correlations.

This topology keeps only self-correlations, where both indices refer to the same key. It is commonly used when selecting auto-correlations or identity blocks.

In index notation, this returns all correlations (i, i) for i in the key set.

Parameters:

keys – Sequence of integer keys.

Returns:

List of diagonal correlations (i, i).

binny.analysis.pairs_lower_triangle(keys: Sequence[int]) → list[tuple[int, int]]#

Construct ordered correlations forming a lower-triangular subset.

This topology is the complement of the upper-triangular selection and retains only those correlations where the first index does not come before the second under the given key ordering.

In index terms, this returns all correlations (i, j) such that i and j are in the key set and i follows or coincides with j in the key order.

Parameters:

keys – Sequence of integer keys defining the ordering.

Returns:

List of ordered correlations (i, j) with i not before j.

binny.analysis.pairs_off_diagonal(keys: Sequence[int]) → list[tuple[int, int]]#

Construct all ordered off-diagonal index correlations.

This topology includes every ordered pair except self-correlations. It is useful when diagonal contributions must be excluded while preserving order.

In index notation, this returns all correlations (i, j) such that i and j are in the key set and i differs from j.

Parameters:

keys – Sequence of integer keys.

Returns:

List of ordered off-diagonal correlations (i, j).

binny.analysis.pairs_upper_triangle(keys: Sequence[int]) → list[tuple[int, int]]#

Construct ordered correlations forming an upper-triangular subset.

This topology selects a symmetric subset of correlations by keeping only those whose first index does not come after the second under the given key ordering. Each unordered pair appears exactly once.

In index terms, this returns all correlations (i, j) such that i and j are in the key set and i precedes or coincides with j in the key order.

Parameters:

keys – Sequence of integer keys defining the ordering.

Returns:

List of ordered correlations (i, j) with i not after j.

binny.analysis.parent_stats(z: Any, nz: Any, *, decimal_places: int | None = 2, quantiles: Sequence[float] = (0.16, 0.5, 0.84), min_rel_height: float = 0.1) → dict[str, Any]#

Compute shape statistics for the parent redshift distribution.

This function summarizes the shape of the parent n(z), independently of its tomographic binning. The distribution is treated as a nonnegative weight function and does not need to be normalized.

The returned statistics include moments, weighted quantiles, and peak diagnostics. All quantities are computed directly from the supplied parent distribution rather than reconstructed from tomographic bins.

Parameters:
  • z – One-dimensional redshift grid.

  • nz – Parent redshift distribution evaluated on z.

  • decimal_places – Number of decimal places used to round returned statistics. If None, return full-precision values.

  • quantiles – Quantiles to compute, expressed as fractions in [0, 1].

  • min_rel_height – Minimum relative peak height used to identify significant local maxima.

Returns:

  • "moments": Mean, median, mode, standard deviation, skewness, excess kurtosis, interquartile range, and central 68% interval width.

  • "quantiles": Mapping from requested quantiles to redshift values.

  • "peaks": Global mode, mode height, number of significant peaks, and second-highest peak ratio.

Return type:

Dictionary containing the following statistics

Raises:

ValueError – If the redshift grid or distribution is invalid, the total weight is not positive, or a requested quantile is outside [0, 1].

binny.analysis.peak_flags(z: Any, nz_bin: Any, *, min_rel_height: float = 0.1) → dict[str, float | None]#

Compute simple peak diagnostics for a single bin curve.

A point is treated as a peak if it is greater than its immediate neighbors. Peaks below min_rel_height * global_max are ignored.

Returned keys:
  • "mode": redshift of the global maximum on the grid.

  • "mode_height": curve value at the mode.

  • "num_peaks": number of detected peaks passing the height cut.

  • "second_peak_ratio": second-highest peak height divided by the highest (None if no second peak).

binny.analysis.peak_flags_per_bin(z: Any, bins: Mapping[int, Any], *, min_rel_height: float = 0.1) → dict[int, dict[str, float | None]]#

Compute peak diagnostics for each bin curve.

binny.analysis.pearson_matrix(z: Any, bins: Mapping[int, Any], *, normalize: bool = False, rtol: float = 0.001, atol: float = 1e-06, decimal_places: int | None = 2) → dict[int, dict[int, float]]#

Calculate Pearson correlations between bins in one sample.

Parameters:
  • z – Redshift grid.

  • bins – Redshift distributions indexed by bin.

  • normalize – Whether to normalize the distributions.

  • rtol – Relative normalization tolerance.

  • atol – Absolute normalization tolerance.

  • decimal_places – Number of decimal places, or None.

Returns:

Symmetric matrix of Pearson correlation coefficients.

Raises:

ValueError – If the input distributions are invalid.

binny.analysis.population_stats(bins: Mapping[int, Any], metadata: Mapping[str, Any], *, density_total: float | None = None, survey_area: float | None = None, normalize_frac: bool = True, rtol: float = 0.01, atol: float = 0.001, total_count_per_bin: Mapping[int, float] | None = None, volume_per_bin: Mapping[int, float] | None = None, decimal_places: int | None = 2) → dict[str, Any]#

Compute population / normalization statistics for tomographic bins.

This function computes quantities that depend on relative bin populations, using metadata produced by Binny’s tomo builders.

The primary input is metadata["bins"]["frac_per_bin"] (mapping bin index to fraction). Fractions are checked against the bin indices present in bins.

Optional allocations:

  • If density_total is provided, return per-bin allocated surface densities in galaxies per square arcminute.

  • If survey_area is also provided, return effective counts using the surface density and survey area in square arcminutes.

  • If total_count_per_bin and volume_per_bin are provided, return per-bin comoving densities computed as count divided by volume.

Parameters:
  • bins – Mapping from bin index to bin curves.

  • metadata – Tomography metadata containing metadata["bins"]["frac_per_bin"].

  • density_total – Optional total effective surface density in galaxies per square arcminute.

  • survey_area – Optional survey area in square arcminutes. Requires density_total.

  • normalize_frac – If True, renormalize metadata fractions to sum to 1. If False, require they sum to 1 within rtol and atol.

  • rtol – Relative tolerance for sum-to-one checks when normalize_frac=False.

  • atol – Absolute tolerance for sum-to-one checks when normalize_frac=False.

  • total_count_per_bin – Optional mapping from bin index to total galaxy count in that bin.

  • volume_per_bin – Optional mapping from bin index to comoving volume in that bin.

  • decimal_places – Rounding precision for returned values.

Returns:

Mapping with key "fractions" and, when requested, surface-density fields, count fields, or comoving-density fields. Comoving densities are returned under "density_per_bin" with "density_unit" set to "h^3 Mpc^-3".

Raises:
  • ValueError – If bins is empty.

  • ValueError – If metadata does not contain valid per-bin population fractions.

  • ValueError – If metadata fractions are missing any bin index.

  • ValueError – If survey_area is provided without density_total.

  • ValueError – If only one of total_count_per_bin and volume_per_bin is provided.

  • ValueError – If any requested comoving volume is non-positive.

  • ValueError – If fractions cannot be normalized or validated.

binny.analysis.sample_bin_labels(samples: Mapping[str, Tomography]) → list[tuple[str, int]]#

Return sample-aware labels for all tomographic bins.

binny.analysis.sample_bins(samples: Mapping[str, Tomography]) → dict[tuple[str, int], ndarray]#

Return bin curves indexed by sample name and bin index.

binny.analysis.sample_combinations(*collections: Mapping[str, Tomography]) → list[tuple[tuple[str, int], ...]]#

Return Cartesian products of sample-aware bin labels.

binny.analysis.score_credible_width(*, z: NDArray[float64], curves: Mapping[int, NDArray[float64]], mass: float = 0.68) → dict[int, float]#

Compute central credible widths for a collection of curves.

The credible width is defined as the width of the central interval containing the specified fraction of the total integrated curve area.

Parameters:
  • z – One-dimensional coordinate grid.

  • curves – Mapping from index to curve values evaluated on z.

  • mass – Fraction of total area contained within the interval.

Returns:

Mapping from index to credible interval widths.

Raises:

ValueError – If mass is not in the open interval (0, 1) or curve shapes are invalid.

binny.analysis.score_mean_location(*, z: NDArray[float64], curves: Mapping[int, NDArray[float64]]) → dict[int, float]#

Compute mean locations for a collection of curves on a shared grid.

The mean location is defined as the first moment of each curve with respect to the grid coordinate.

Parameters:
  • z – One-dimensional coordinate grid.

  • curves – Mapping from index to curve values evaluated on z.

Returns:

Mapping from index to mean location values.

Raises:

ValueError – If a curve does not have the same shape as z.

binny.analysis.score_median_location(*, z: NDArray[float64], curves: Mapping[int, NDArray[float64]]) → dict[int, float]#

Compute median locations for a collection of curves on a shared grid.

The median location is defined as the grid coordinate at which the cumulative integrated curve reaches one half of its total area.

Parameters:
  • z – One-dimensional coordinate grid.

  • curves – Mapping from index to curve values evaluated on z.

Returns:

Mapping from index to median location values.

Raises:

ValueError – If z has fewer than two points or curve shapes are invalid.

binny.analysis.score_peak_location(*, z: NDArray[float64], curves: Mapping[int, NDArray[float64]]) → dict[int, float]#

Compute peak locations for a collection of curves on a shared grid.

The peak location is defined as the grid coordinate corresponding to the maximum value of each curve.

Parameters:
  • z – One-dimensional coordinate grid.

  • curves – Mapping from index to curve values evaluated on z.

Returns:

Mapping from index to peak location along the grid.

Raises:

ValueError – If a curve does not have the same shape as z.

binny.analysis.shape_stats(z: Any, bins: Mapping[int, Any], *, center_method: str = 'mean', decimal_places: int | None = 2, quantiles: Sequence[float] = (0.16, 0.5, 0.84), min_rel_height: float = 0.1, bin_edges: Mapping[int, tuple[float, float]] | Sequence[float] | None = None) → dict[str, Any]#

Compute shape-only summary statistics for tomographic bin curves.

This function computes redshift-shape diagnostics that depend only on the per-bin curve shapes, not on relative bin populations. It is safe to call on individually normalized bin PDFs.

Per bin, it returns:

Optionally, if bin_edges are supplied, it also returns the fraction of each bin curve contained within its nominal redshift range via in_range_fraction_per_bin().

Parameters:
  • z – One-dimensional redshift grid shared by all bins.

  • bins – Mapping from bin index to bin curves evaluated on z.

  • center_method – Center definition (“mean”, “median”, “mode”, or “pXX”).

  • decimal_places – If not None, round centers to this many decimal places.

  • quantiles – Quantiles to compute per bin (fractions in [0, 1]).

  • min_rel_height – Peak height threshold relative to the global maximum.

  • bin_edges – Optional nominal edges for in-range fractions.

Returns:

  • "centers": {bin_idx: center}

  • "peaks": {bin_idx: peak_flags_dict}

  • "per_bin": {bin_idx: {“moments”: …, “center”: …,

    ”quantiles”: …, “peaks”: …}}

  • "in_range_fraction": {bin_idx: fraction} if bin_edges

    is not None

Return type:

Nested mapping with keys

Raises:
  • ValueError – If bins is empty.

  • ValueError – If any bin has non-positive total weight.

  • ValueError – If center_method is invalid.

  • ValueError – If quantiles are outside [0, 1].

  • ValueError – If bin_edges are malformed when provided.

binny.analysis.tuples_all(keys: Sequence[int], n: int) → list[tuple[int, ...]]#

Construct all ordered index tuples of fixed length.

This topology enumerates every possible ordered tuple of length n drawn from a single key set. It is the direct higher-order analogue of forming all ordered index correlations.

In index notation, this returns all tuples (i_1, i_2, …, i_n) where each entry is drawn from the key set.

Parameters:
  • keys – Sequence of integer keys.

  • n – Tuple length.

Returns:

List of ordered n-tuples.

Raises:

ValueError – If n is less than 1.

binny.analysis.tuples_cartesian(keys_list: Sequence[Sequence[int]]) → list[tuple[int, ...]]#

Construct ordered tuples from multiple key sequences.

This topology forms tuples by drawing one index from each provided key sequence. Each tuple position has its own independent key domain, and no symmetry between positions is assumed.

In index notation, given key sequences K_1, K_2, …, K_n, this returns all tuples (i_1, i_2, …, i_n) with i_t drawn from K_t for t = 1..n, where n = len(keys_list).

Parameters:

keys_list – Sequence of key sequences, one per tuple position.

Returns:

List of ordered tuples formed from the Cartesian product.

Raises:

ValueError – If keys_list is empty.

binny.analysis.tuples_diagonal(keys: Sequence[int], n: int) → list[tuple[int, ...]]#

Construct diagonal index tuples of fixed length.

This topology keeps only tuples where all positions contain the same key. It is useful for selecting purely diagonal or self-coupled contributions in higher-order structures.

In index notation, this returns all tuples (i, i, …, i) of length n for i in the key set.

Parameters:
  • keys – Sequence of integer keys.

  • n – Tuple length.

Returns:

List of diagonal n-tuples.

Raises:

ValueError – If n is less than 1.

binny.analysis.tuples_nondecreasing(keys: Sequence[int], n: int) → list[tuple[int, ...]]#

Construct nondecreasing index tuples of fixed length.

This topology selects a symmetric subset of ordered tuples by requiring that indices do not decrease under the given key ordering. Each unordered combination appears exactly once.

In index notation, this returns all tuples (i_1, i_2, …, i_n) such that i_1 does not come after i_2, and so on through i_n.

Parameters:
  • keys – Sequence of integer keys defining the ordering.

  • n – Tuple length.

Returns:

List of ordered n-tuples with nondecreasing indices.

Raises:

ValueError – If n is less than 1.

Submodules#