Source code for rank_preserving_calibration.api

"""Public JTBD API: diagnose, calibrate, pareto, and evaluate."""

from __future__ import annotations

from typing import TYPE_CHECKING, Literal

import numpy as np

from ._conic import solve_kl, solve_qp
from ._ipf import solve_ipf
from ._metrics import (
    brier_score,
    count_rank_reversals,
    find_worst_reversals,
    kl_div,
    nll_score,
    weak_rank_l1,
    weak_rank_violation,
)
from ._types import (
    CalibrationError,
    CalibrationResult,
    DiagnosisResult,
    EvaluationResult,
    ParetoResult,
)
from ._validation import (
    normalized_weights,
    validate_labels,
    validate_optional_matrix,
    validate_probs,
    validate_row_weights,
    validate_target_shares,
)

if TYPE_CHECKING:
    from collections.abc import Sequence

    from numpy.typing import ArrayLike

_FEASIBILITY_TOL = 1e-6
_DEFAULT_LAMBDAS: tuple[float, ...] = (
    0.0,
    0.1,
    0.25,
    0.5,
    1.0,
    2.0,
    5.0,
    10.0,
    50.0,
    float("inf"),
)


def _package_calibration_result(
    Q: np.ndarray,
    R: np.ndarray,
    A: np.ndarray,
    target_shares: np.ndarray,
    *,
    row_weights: np.ndarray | None,
    ties: str,
    iterations: int,
    feasibility_tol: float,
) -> CalibrationResult:
    w_share = normalized_weights(row_weights, Q.shape[0])
    max_row_error = float(np.max(np.abs(Q.sum(axis=1) - 1.0)))
    max_marginal_error = float(np.max(np.abs(w_share @ Q - target_shares)))
    max_viol = weak_rank_violation(Q, A, ties=ties)
    l1_viol = weak_rank_l1(Q, A, ties=ties)
    _, _, pres_pct = count_rank_reversals(Q, A, tol=max(1e-6, feasibility_tol))
    return CalibrationResult(
        probs=Q,
        converged=max(max_row_error, max_marginal_error) <= feasibility_tol,
        kl_divergence=kl_div(Q, R, row_weights=row_weights),
        max_row_error=max_row_error,
        max_marginal_error=max_marginal_error,
        max_rank_violation=max_viol,
        l1_rank_violation=l1_viol,
        rank_preservation_pct=pres_pct,
        iterations=iterations,
    )


[docs] def diagnose( probs: ArrayLike, target_shares: ArrayLike, *, row_weights: ArrayLike | None = None, top_k: int = 5, tol: float = 1e-9, ) -> DiagnosisResult: """Diagnose whether standard IPF reverses within-class rankings. Runs weighted Iterative Proportional Fitting (IPF) to match ``target_shares`` and reports how large the marginal shift is, how many within-class pairs IPF reverses, and the ``top_k`` largest reversals. Args: probs: Predicted probability matrix of shape ``(N, J)``. target_shares: Target class proportions of shape ``(J,)`` summing to ``1.0``. row_weights: Optional positive row weights of shape ``(N,)`` (e.g., poststratification cell counts or survey weights). top_k: Number of largest reversed pairs to include in ``worst_reversals``. tol: IPF convergence tolerance. Returns: :class:`DiagnosisResult` with IPF probabilities, multipliers, shift magnitude, and rank-reversal diagnostics. Raises: CalibrationError: If inputs are invalid. """ P = validate_probs(probs) N, J = P.shape w = validate_row_weights(row_weights, N) t_shares = validate_target_shares(target_shares, J) if not np.isfinite(tol) or tol <= 0: raise CalibrationError(f"tol must be positive, got {tol}") w_share = normalized_weights(w, N) P_norm = np.divide(P, np.maximum(P.sum(axis=1, keepdims=True), 1e-300)) emp_shares = w_share @ P_norm l1_shift = float(np.sum(np.abs(t_shares - emp_shares))) Q_ipf, multipliers, _, _ = solve_ipf(P, t_shares, row_weights=w, tol=tol) n_rev, _, pres_pct = count_rank_reversals(Q_ipf, P, tol=1e-6) worst = find_worst_reversals(Q_ipf, P, top_k=top_k, tol=1e-6) return DiagnosisResult( ipf_probs=Q_ipf, multipliers=multipliers, l1_shift=l1_shift, max_rank_violation=weak_rank_violation(Q_ipf, P, ties="weak"), l1_rank_violation=weak_rank_l1(Q_ipf, P, ties="weak"), rank_preservation_pct=pres_pct, n_reversed_pairs=n_rev, worst_reversals=worst, )
[docs] def calibrate( probs: ArrayLike, target_shares: ArrayLike, *, rank_penalty: float | None = None, row_weights: ArrayLike | None = None, reference: ArrayLike | None = None, anchor: ArrayLike | None = None, ties: Literal["weak", "stable"] = "weak", loss: Literal["kl", "euclidean"] = "kl", tol: float = 1e-9, verbose: bool = False, ) -> CalibrationResult: """Calibrate multiclass probabilities to match target class shares. Finds a probability matrix ``Q`` whose rows sum to ``1`` and whose weighted column averages equal ``target_shares``, minimizing weighted KL divergence (or squared Euclidean distance) from ``reference`` subject to within-class weak-order constraints anchored to ``anchor``. Control rank preservation with a single continuous dial ``rank_penalty``: * ``rank_penalty=None`` (default): strict weak-order preservation (zero rank reversals). * ``rank_penalty=0.0``: unconstrained marginal matching (weighted IPF under ``loss="kl"``). * ``rank_penalty > 0``: soft weak-order calibration charging ``rank_penalty`` per unit of L1 rank violation (e.g., ``1.0``). Args: probs: Predicted probability matrix of shape ``(N, J)``. target_shares: Target class proportions of shape ``(J,)`` summing to ``1.0``. rank_penalty: ``None`` for strict rank preservation, ``0.0`` for unconstrained marginal matching, or a positive float for soft rank regularization. row_weights: Optional strictly positive row weights of shape ``(N,)`` (e.g., poststratification cell counts or survey weights). reference: Optional reference probability matrix ``R`` of shape ``(N, J)`` from which divergence is measured. Defaults to ``probs``. Use with :func:`apply_temperature` to decouple source recalibration from the ranking anchor. anchor: Optional score matrix ``A`` of shape ``(N, J)`` defining the within-class order to preserve. Defaults to ``probs``. ties: ``"weak"`` (default) uses permutation-invariant block-boundary constraints so tied anchor scores are unconstrained relative to each other; ``"stable"`` imposes row-index order among ties. loss: ``"kl"`` (default, multiplicative exponential-cone solve) or ``"euclidean"`` (exact sparse quadratic program). tol: Solver convergence tolerance. verbose: If True, print solver progress. Returns: :class:`CalibrationResult` containing calibrated probabilities and feasibility/rank diagnostics. Raises: CalibrationError: If inputs are invalid or strict rank preservation cannot be certified. """ P = validate_probs(probs) N, J = P.shape w = validate_row_weights(row_weights, N) t_shares = validate_target_shares(target_shares, J) R = validate_optional_matrix(reference, P, name="reference", non_negative=True) A = validate_optional_matrix(anchor, P, name="anchor", non_negative=False) if ties not in ("weak", "stable"): raise CalibrationError(f"ties must be 'weak' or 'stable', got {ties!r}") if loss not in ("kl", "euclidean"): raise CalibrationError(f"loss must be 'kl' or 'euclidean', got {loss!r}") if not np.isfinite(tol) or tol <= 0: raise CalibrationError(f"tol must be positive, got {tol}") if rank_penalty is not None: if np.isnan(rank_penalty) or rank_penalty < 0: raise CalibrationError( f"rank_penalty must be None, non-negative, or inf; got {rank_penalty}" ) if np.isinf(rank_penalty): rank_penalty = None feas_tol = max(_FEASIBILITY_TOL, 100.0 * tol) rank_tol = max(1e-6, 100.0 * tol) if loss == "euclidean": Q, iterations = solve_qp( R, A, t_shares, lam=rank_penalty, row_weights=w, ties=ties, tol=tol, verbose=verbose, ) return _package_calibration_result( Q, R, A, t_shares, row_weights=w, ties=ties, iterations=iterations, feasibility_tol=feas_tol, ) # loss == "kl" if rank_penalty == 0.0: Q_ipf, _, iterations, _ = solve_ipf(R, t_shares, row_weights=w, tol=tol) return _package_calibration_result( Q_ipf, R, A, t_shares, row_weights=w, ties=ties, iterations=iterations, feasibility_tol=feas_tol, ) if rank_penalty is not None: Q, iterations, achieved = solve_kl( R, A, t_shares, lam=float(rank_penalty), row_weights=w, ties=ties, tol=tol, verbose=verbose, ) return _package_calibration_result( Q, R, A, t_shares, row_weights=w, ties=ties, iterations=iterations, feasibility_tol=max(feas_tol, 10.0 * achieved), ) # Strict rank-preserving KL calibration. if ties == "weak": Q, iterations, achieved = solve_kl( R, A, t_shares, lam=None, row_weights=w, ties="weak", tol=tol, verbose=verbose, ) eff_feas = max(feas_tol, 10.0 * achieved) eff_rank = max(rank_tol, 10.0 * achieved) res = _package_calibration_result( Q, R, A, t_shares, row_weights=w, ties="weak", iterations=iterations, feasibility_tol=eff_feas, ) if res.converged and res.max_rank_violation <= eff_rank: return res # Fallback / stable-tie exact-penalty path. for lam_exact in (1e3, 1e4, 1e5): Q, iterations, achieved = solve_kl( R, A, t_shares, lam=lam_exact, row_weights=w, ties=ties, tol=tol, verbose=verbose, ) eff_feas = max(feas_tol, 10.0 * achieved) eff_rank = max(rank_tol, 10.0 * achieved) res = _package_calibration_result( Q, R, A, t_shares, row_weights=w, ties=ties, iterations=iterations, feasibility_tol=eff_feas, ) if res.converged and res.max_rank_violation <= eff_rank: return res raise CalibrationError( "KL calibration could not certify strict rank preservation: violations " "remain at penalty 1e5 (for instance, a zero in reference high in an " "anchor column forces every lower entry to zero)." )
[docs] def pareto( probs: ArrayLike, target_shares: ArrayLike, *, lambdas: Sequence[float] | np.ndarray | None = None, row_weights: ArrayLike | None = None, reference: ArrayLike | None = None, anchor: ArrayLike | None = None, ties: Literal["weak", "stable"] = "weak", loss: Literal["kl", "euclidean"] = "kl", tol: float = 1e-9, verbose: bool = False, ) -> ParetoResult: """Trace the accuracy vs. rank-preservation Pareto frontier across ``lambdas``. Solves :func:`calibrate` over a sorted grid of rank penalties—by default spanning ``0.0`` (unconstrained IPF) through soft penalties to ``inf`` (strict weak-order preservation). Args: probs: Predicted probability matrix of shape ``(N, J)``. target_shares: Target class proportions of shape ``(J,)`` summing to ``1.0``. lambdas: Optional sequence of non-negative penalty values (may include ``0.0`` and ``float("inf")``). row_weights: Optional strictly positive row weights of shape ``(N,)``. reference: Optional reference probability matrix ``R``. anchor: Optional ranking anchor matrix ``A``. ties: ``"weak"`` (default) or ``"stable"``. loss: ``"kl"`` (default) or ``"euclidean"``. tol: Solver convergence tolerance. verbose: If True, print solver progress. Returns: :class:`ParetoResult` containing sorted penalties, calibrated matrices, KL divergences, and rank-violation trajectories. Raises: CalibrationError: If ``lambdas`` is empty or contains invalid values. """ grid_raw = _DEFAULT_LAMBDAS if lambdas is None else list(lambdas) if len(grid_raw) == 0: raise CalibrationError("lambdas must contain at least one value") grid = sorted(float(x) for x in grid_raw) if any(np.isnan(x) or x < 0 for x in grid): raise CalibrationError("lambdas must be non-negative (or inf)") probs_list: list[np.ndarray] = [] kl_list: list[float] = [] l1_list: list[float] = [] max_list: list[float] = [] pres_list: list[float] = [] for lam in grid: res = calibrate( probs, target_shares, rank_penalty=None if np.isinf(lam) else lam, row_weights=row_weights, reference=reference, anchor=anchor, ties=ties, loss=loss, tol=tol, verbose=verbose, ) probs_list.append(res.probs) kl_list.append(res.kl_divergence) l1_list.append(res.l1_rank_violation) max_list.append(res.max_rank_violation) pres_list.append(res.rank_preservation_pct) return ParetoResult( lambdas=grid, probs=probs_list, kl_divergences=kl_list, l1_rank_violations=l1_list, max_rank_violations=max_list, rank_preservation_pcts=pres_list, )
[docs] def evaluate( calibrated: ArrayLike, probs: ArrayLike, target_shares: ArrayLike, *, row_weights: ArrayLike | None = None, reference: ArrayLike | None = None, anchor: ArrayLike | None = None, y: ArrayLike | None = None, tol: float = 1e-6, ) -> EvaluationResult: """Audit any calibrated probability matrix against marginals, ranks, and labels. Works on outputs from :func:`calibrate`, IPF, BISG, or any external calibrator. Args: calibrated: Calibrated probability matrix of shape ``(N, J)`` to audit. probs: Original pre-calibration probability matrix of shape ``(N, J)``. target_shares: Target class proportions of shape ``(J,)`` summing to ``1.0``. row_weights: Optional positive row weights of shape ``(N,)``. reference: Optional reference matrix for KL divergence (defaults to ``probs``). anchor: Optional anchor matrix for rank metrics (defaults to ``probs``). y: Optional integer class labels of shape ``(N,)`` in ``{0, ..., J-1}`` to compute multiclass Brier score and negative log-likelihood. tol: Numerical slack for counting pairwise rank reversals. Returns: :class:`EvaluationResult` with feasibility, divergence, rank, and optional proper-scoring diagnostics. Raises: CalibrationError: If any input array has invalid shape or values. """ Q = validate_probs(calibrated, name="calibrated") P = validate_probs(probs, name="probs") if Q.shape != P.shape: raise CalibrationError( f"calibrated shape {Q.shape} must match probs shape {P.shape}" ) N, J = P.shape w = validate_row_weights(row_weights, N) t_shares = validate_target_shares(target_shares, J) R = validate_optional_matrix(reference, P, name="reference", non_negative=True) A = validate_optional_matrix(anchor, P, name="anchor", non_negative=False) w_share = normalized_weights(w, N) max_row_error = float(np.max(np.abs(Q.sum(axis=1) - 1.0))) max_marginal_error = float(np.max(np.abs(w_share @ Q - t_shares))) _, _, pres_pct = count_rank_reversals(Q, A, tol=tol) brier: float | None = None nll: float | None = None if y is not None: y_arr = validate_labels(y, N, J) brier = brier_score(Q, y_arr, row_weights=w) nll = nll_score(Q, y_arr, row_weights=w) return EvaluationResult( max_row_error=max_row_error, max_marginal_error=max_marginal_error, kl_divergence=kl_div(Q, R, row_weights=w), max_rank_violation=weak_rank_violation(Q, A, ties="weak"), l1_rank_violation=weak_rank_l1(Q, A, ties="weak"), rank_preservation_pct=pres_pct, brier=brier, nll=nll, )