API
This page documents the public API of caife, organized by the kind of unfolding component that each symbol implements.
Models and latent vectors
- class caife.AbstractModel
Abstract base class that all caife models inherit from.
- abstractmethod create_latents(X)
Create a JAX pytree of latent vectors for this model.
- Parameters:
X – The observations that are to be reconstructed.
- Returns:
A JAX pytree of AbstractLatentVector instances with the same structure that calling this model requires for the params argument.
- abstractmethod fit(X, y, sample_weight=None, systematics=None, background=None)
Fit the model to the given data.
- Parameters:
X – Proxy samples, shape (n_samples,) or (n_samples, n_proxy_features).
y – Target samples that correspond to the proxy samples, shape (n_samples,).
sample_weight (optional) – Per-sample weights, shape (n_samples,). Defaults to None for uniform weights.
systematics (optional) – Per-sample systematic parameters, shape (n_samples, n_systematic_parameters). Defaults to None for no modeling of systematics.
background (optional) – A separate set of background instances, shape (n_background_samples,) or (n_background_samples, n_proxy_features). If the background should be weighted, a tuple of this set and its weights. Defaults to None for no background consideration.
- Returns:
This model itself.
- abstractmethod proxy_view(X, sample_weight=None)
Return a view of the proxy distribution from the given proxy samples.
- Parameters:
X – Proxy samples, shape (n_samples,) or (n_samples, n_proxy_features).
sample_weight (optional) – Per-sample weights, shape (n_samples,). Defaults to None for uniform weights.
- Returns:
The model’s view of the proxy distribution.
- abstractmethod target_view(y, sample_weight=None)
Return a view of the target distribution from the given target samples.
- Parameters:
y – Target samples, shape (n_samples,).
sample_weight (optional) – Per-sample weights, shape (n_samples,). Defaults to None for uniform weights.
- Returns:
The model’s view of the target distribution.
- class caife.LinearCountModel(target_bins: list[float], representation: AbstractRepresentation)
Linear model for solving g = A @ f + b over count histograms g, f, and b.
This model does not consider any systematic parameters; use LinearSystematicsCountModel if systematics need to be modeled.
- Parameters:
target_bins – Bin boundaries of the target quantity, shape (n_target_bins+1,).
representation – The data representation that is computed from the proxy features.
- A_
The fitted transfer matrix A, shape (n_bins_proxy, n_bins_target). Set during fit.
- g_background_
The fitted background proxy distribution b, shape (n_bins_proxy,). Set during fit.
- n_background_samples
Number of background samples, set during fit but meant to be manually changed to the actual number of background samples after fitting.
- n_bins_target
Number of target bins, as determined by the target_bins.
- class caife.LinearSystematicsCountModel(target_bins: list[float], representation: ~caife._qunfold.AbstractRepresentation, C: float | None = None, solver: str = 'L-BFGS-B', solver_options: dict[str, object] = <factory>)
Linear systematics-aware model for solving g = A(s) @ f + b over count histograms g, f, and b and over a vector of systematic parameters s.
Each column of A(s) (representing the mean feature embedding of one target bin) is modeled as one logistic regression that takes s as its input. Through this choice, each column is always properly normalized to a unit sum and each cell varies monotonically with the corresponding entry in s. The full matrix model A(s), consisting of all target bin-associated columns, has n_proxy_bins * n_target_bins * (n_systematic_parameters + 1) parameters, which is only (n_systematic_parameters + 1) times more than a static, systematics-unaware matrix would have.
- Parameters:
target_bins – Bin boundaries of the target quantity, shape (n_target_bins+1,).
representation – The data representation that is computed from the proxy features.
C (optional) – The regularization strength for each logistic regression model, with the behavior defined by scikit-learn. Defaults to None for no regularization.
solver (optional) – The method argument in scipy.optimize.minimize. Defaults to “L-BFGS-B”.
solver_options (optional) – The options argument in scipy.optimize.minimize. Defaults to { “gtol”: 1e-8, “maxiter”: 10_000 }.
- coeffs_
The fitted coefficients of the per-column logistic regressions, shape (n_bins_proxy, n_bins_target, n_systematic_parameters + 1). Set during fit.
- A_mask
A boolean mask of shape (n_bins_proxy, n_bins_target), marking the proxy/target bin combinations that were actually observed while fitting; A(s) is only meaningful for these entries. Set during fit.
- systematic_bounds
The per-parameter (min, max) bounds observed in the training systematics, shape (n_systematic_parameters, 2). Set during fit.
- opt_
The scipy.optimize.OptimizeResult of fitting the logistic regressions, with an additional wallclock_time attribute. Set during fit.
- g_background_
The fitted background proxy distribution b, shape (n_bins_proxy,). Set during fit.
- n_background_samples
Number of background samples, set during fit but meant to be manually changed to the actual number of background samples after fitting.
- n_bins_target
Number of target bins, as determined by the target_bins.
- class caife.MultiTargetModel(target_bins: list[list[float]], representation: AbstractRepresentation)
Linear model for solving g = A @ f + b, where f is a multi-dimensional count histogram.
The MultiTargetModel generalizes the LinearCountModel to several target quantities at once. Each target quantity is discretized independently, according to its own bin boundaries in target_bins, and the resulting per-quantity bins are combined into a single joint class label, in the same way as GridBinning combines several proxy features. The target spectrum f therefore has shape tuple(n_bins_per_target), a multi-dimensional count histogram over all target quantities jointly.
This model does not consider any systematic parameters; use MultiTargetSystematicsModel if systematics need to be modeled.
- Parameters:
target_bins – A list of bin boundary vectors, one vector per target quantity, each ranging from -inf to inf.
representation – The data representation that is computed from the proxy features.
- A_
The fitted transfer matrix A, shape (n_bins_proxy, n_bins_multitarget). Set during fit.
- g_background_
The fitted background proxy distribution b, shape (n_bins_proxy,). Set during fit.
- n_background_samples
Number of background samples, set during fit but meant to be manually changed to the actual number of background samples after fitting.
- n_bins_multitarget
The total number of joint target bins, i.e., the product of n_bins_per_target.
- n_bins_per_target
The number of bins of each individual target quantity, as determined by target_bins.
- class caife.MultiTargetSystematicsModel(target_bins: list[list[float]], representation: ~caife._qunfold.AbstractRepresentation, C: float | None = None, solver: str = 'L-BFGS-B', solver_options: dict[str, object] = <factory>)
Systematics-aware MultiTargetModel, solving g = A(s) @ f + b over a joint, multi-dimensional target spectrum f and a vector of systematic parameters s.
As in LinearSystematicsCountModel, each column of A(s) (representing the mean feature embedding of one joint target bin) is modeled as one logistic regression that takes s as its input, so that each column stays properly normalized to a unit sum and varies monotonically with each entry of s. As in MultiTargetModel, the target quantities are first combined into a single joint class label, over which this logistic regression is fitted, so that A(s) has shape (n_bins_proxy, n_bins_multitarget) and f has shape tuple(n_bins_per_target).
- Parameters:
target_bins – A list of bin boundaries, one list per target quantity, each ranging from -inf to inf.
representation – The data representation that is computed from the proxy features.
C (optional) – The regularization strength for each logistic regression model, with the behavior defined by scikit-learn. Defaults to None for no regularization.
solver (optional) – The method argument in scipy.optimize.minimize. Defaults to “L-BFGS-B”.
solver_options (optional) – The options argument in scipy.optimize.minimize. Defaults to {“gtol”: 1e-8, “maxiter”: 10_000}.
- coeffs_
The fitted coefficients of the per-column logistic regressions, shape (n_bins_proxy, n_bins_multitarget, n_systematic_parameters + 1). Set during fit.
- A_mask
A boolean mask of shape (n_bins_proxy, n_bins_multitarget), marking the proxy/target bin combinations that were actually observed while fitting; A(s) is only meaningful for these entries. Set during fit.
- systematic_bounds
The per-parameter (min, max) bounds observed in the training systematics, shape (n_systematic_parameters, 2). Set during fit.
- opt_
The scipy.optimize.OptimizeResult of fitting the logistic regressions, with an additional wallclock_time attribute. Set during fit.
- g_background_
The fitted background proxy distribution b, shape (n_bins_proxy,). Set during fit.
- n_background_samples
Number of background samples, set during fit but meant to be manually changed to the actual number of background samples after fitting.
- n_bins_multitarget
The total number of joint target bins, i.e., the product of n_bins_per_target.
- n_bins_per_target
The number of bins of each individual target quantity, as determined by target_bins.
- caife.create_mixture_model_fn(models)
Combine a collection of models into a single model that returns a weighted average of the model-wise outputs.
- Parameters:
models – The models to combine, each with the same callable interface *args -> g_est. In particular, *args needs to be identical across all models.
- Returns:
A callable (weights, *args) -> g_est that serves as a single linear model. This model averages the outputs of the individual models with the given weights.
- class caife.AbstractLatentVector
Abstract base class for the latent variables over which caife solvers minimize negative log-likelihoods.
- abstractmethod create_starting_point(rng=None)
Create a random starting point in latent space.
- Parameters:
rng (optional) – Random number generator.
- Returns:
An initial vector in the latent space, shape (latent_dim,).
- class caife.LatentSpectrum(n_samples: int, n_bins_target: int)
Transforms a vector of latent variables through the “soft-max trick” by Bunse (2022) and scales it by the given number of samples. Through this design choice, the output will always be a valid count spectrum with all bin-wise counts larger than zero and the sum of all bin counts equal to the given number of samples.
- Parameters:
n_samples – The desired number of samples.
n_bins_target – The number of target bins.
- class caife.LatentReshape(latent_vector: AbstractLatentVector, shape: list[int])
Reshapes a latent vector.
- Parameters:
latent_vector – The latent vector to reshape.
shape – The desired shape.
- class caife.LatentSystematics(bounds: ArrayLike)
Transforms a latent variable through a sigmoid that is scaled to match the given bounds. Through this design choice, the value of the systematic parameter will always be within the given bounds.
- Parameters:
bounds – The minimum and maximum value for each systematic parameter, shape (n_systematic_parameters, 2).
Representations
- class caife.TreeBinning(tree: object, fit_tree: bool = True)
A proxy representation that partitions the feature space according to the leaves of a decision tree.
A TreeBinning uses a (typically shallow) decision tree classifier to discretize the proxy features X into bins: each leaf of the tree becomes one proxy bin, and fit_transform/transform maps samples to these bins through tree.apply(X). Since decision tree leaves are trained to be informative about the target y, this typically yields proxy bins that carry more information than naive, equidistant binnings. It also supports arbitrary numbers of features natively.
- Parameters:
tree – A tree-based classifier with a scikit-learn-compatible fit(X, y, sample_weight=None) and apply(X) interface, such as an instance of sklearn.tree.DecisionTreeClassifier.
fit_tree (optional) – Whether fit_transform should call tree.fit. Set this to False to reuse an already-fitted tree, e.g., one that was fitted on a separate portion of the data. Defaults to True.
- bin_index_
A mapping from the tree’s (arbitrary) leaf IDs to consecutive proxy bin IDs, shape (max_leaf_id + 1, 2); apply it as bin_index_[tree.apply(X), 1]. Set during fit_transform.
- fit_transform(X, y, sample_weight=None, average=True, n_classes=None)
This abstract method has to fit the representation and to return the transformed input data.
Note
Implementations of this abstract method should check the sanity of labels by calling check_y(y, n_classes) and they must set the property self.p_trn = class_prevalences(y, n_classes).
- Parameters:
X – The feature matrix to which this representation will be fitted.
y – The labels to which this representation will be fitted.
sample_weight (optional) – Importance weights for each (X[i], y[i]) pair to use during fitting. Defaults to None.
average (optional) – Whether to return a transfer matrix M or a transformation f(X). Defaults to True.
n_classes (optional) – The number of expected classes. Defaults to None.
- Returns:
A transfer matrix M if average==True or a transformation f(X) if average==False. f(X) might contain NaN entries if the fitting permits the estimation, e.g., in bootstrapped fitting procedures.
- property n_output_features
The number of output features generated by this representation.
- transform(X, sample_weight=None, average=True)
This abstract method has to transform the data X.
- Parameters:
X – The feature matrix that will be transformed.
sample_weight (optional) – Importance weights for each X[i] to use during averaging if average==True. Defaults to None.
average (optional) – Whether to return a vector q or a transformation f(X). Defaults to True.
- Returns:
A vector q = f(X).average(axis=0, weights=sample_weight) if average==True or a transformation f(X) if average==False.
- class caife.UnivariateBinning(proxy_bins: list[float] | list[list[float]])
A proxy representation that bins each proxy feature independently.
Each proxy feature is discretized into its own bins according to proxy_bins, and the resulting per-feature representations are concatenated along the bin dimension. Unlike GridBinning, which forms the full Cartesian product of per-feature bins, UnivariateBinning’s total number of proxy bins is the sum (not the product) of the per-feature bin counts, which keeps it usable even with several proxy features.
- Parameters:
proxy_bins – The bin boundaries of a single proxy feature, ranging from -inf to inf, or a list of such boundaries, one for each proxy feature.
- fit_transform(X, y, sample_weight=None, average=True, n_classes=None)
This abstract method has to fit the representation and to return the transformed input data.
Note
Implementations of this abstract method should check the sanity of labels by calling check_y(y, n_classes) and they must set the property self.p_trn = class_prevalences(y, n_classes).
- Parameters:
X – The feature matrix to which this representation will be fitted.
y – The labels to which this representation will be fitted.
sample_weight (optional) – Importance weights for each (X[i], y[i]) pair to use during fitting. Defaults to None.
average (optional) – Whether to return a transfer matrix M or a transformation f(X). Defaults to True.
n_classes (optional) – The number of expected classes. Defaults to None.
- Returns:
A transfer matrix M if average==True or a transformation f(X) if average==False. f(X) might contain NaN entries if the fitting permits the estimation, e.g., in bootstrapped fitting procedures.
- property n_output_features
The number of output features generated by this representation.
- transform(X, sample_weight=None, average=True)
This abstract method has to transform the data X.
- Parameters:
X – The feature matrix that will be transformed.
sample_weight (optional) – Importance weights for each X[i] to use during averaging if average==True. Defaults to None.
average (optional) – Whether to return a vector q or a transformation f(X). Defaults to True.
- Returns:
A vector q = f(X).average(axis=0, weights=sample_weight) if average==True or a transformation f(X) if average==False.
- class caife.GridBinning(proxy_bins: list[list[float]])
A proxy representation whose bins are the cells of a regular grid.
Each proxy feature is discretized according to its own bin boundaries in proxy_bins, and the resulting per-feature bin indices are combined into a single joint bin index for each sample, one per cell of the resulting grid. Unlike UnivariateBinning, whose number of bins grows additively with the number of proxy features, GridBinning’s bin number grows multiplicatively (the product of the per-feature numbers of bins), which quickly becomes impractical for more than a few proxy features but is highly informative for a few relevant proxy features.
- Parameters:
proxy_bins – A list of bin boundaries, one list per proxy feature, each ranging from -inf to inf.
- fit_transform(X, y, sample_weight=None, average=True, n_classes=None)
This abstract method has to fit the representation and to return the transformed input data.
Note
Implementations of this abstract method should check the sanity of labels by calling check_y(y, n_classes) and they must set the property self.p_trn = class_prevalences(y, n_classes).
- Parameters:
X – The feature matrix to which this representation will be fitted.
y – The labels to which this representation will be fitted.
sample_weight (optional) – Importance weights for each (X[i], y[i]) pair to use during fitting. Defaults to None.
average (optional) – Whether to return a transfer matrix M or a transformation f(X). Defaults to True.
n_classes (optional) – The number of expected classes. Defaults to None.
- Returns:
A transfer matrix M if average==True or a transformation f(X) if average==False. f(X) might contain NaN entries if the fitting permits the estimation, e.g., in bootstrapped fitting procedures.
- property n_output_features
The number of output features generated by this representation.
- represent_features(X)
Represent all features jointly through binning.
- transform(X, sample_weight=None, average=True)
This abstract method has to transform the data X.
- Parameters:
X – The feature matrix that will be transformed.
sample_weight (optional) – Importance weights for each X[i] to use during averaging if average==True. Defaults to None.
average (optional) – Whether to return a vector q or a transformation f(X). Defaults to True.
- Returns:
A vector q = f(X).average(axis=0, weights=sample_weight) if average==True or a transformation f(X) if average==False.
- class caife.GridSearchRepresentation(base_representation: AbstractRepresentation, param_grid: dict[str, object], criterion: str = 'dussap', n_jobs: int | None = None, is_verbose: bool = False)
A representation that selects the hyper-parameters of its base_representation via grid search.
For each combination of hyper-parameters in param_grid, a clone of base_representation is fitted and its resulting transfer matrix A is scored according to the given criterion. The clone with the lowest score is kept and used for all further calls to transform.
- Parameters:
base_representation – The representation whose hyper-parameters are searched over. It must support scikit-learn’s clone and set_params interface.
param_grid – A dict that maps each hyper-parameter name (as accepted by base_representation.set_params) to a list of candidate values, in the same way as scikit-learn’s GridSearchCV. An empty dict evaluates base_representation itself, unmodified.
criterion (optional) – The criterion used to score each candidate representation’s transfer matrix A, either “dussap” (Dussap et al., 2023; minimizes the inverse of the second-smallest eigenvalue of the centered Gram matrix of A) or “blobel” (Blobel, 1985; minimizes the condition number of A). Defaults to “dussap”.
n_jobs (optional) – The number of parallel processes used to evaluate candidates. Use 1 to evaluate sequentially, without spawning subprocesses; any other value, including None, evaluates candidates through multiprocessing.Pool with that many processes, or with one process per available processor if n_jobs is None or less than 1. Defaults to None.
is_verbose (optional) – Whether to print progress while evaluating candidates. Defaults to False.
- results_
A list of all evaluated candidates, sorted ascending by criterion. Each candidate is represented as a dict with keys “losses”, “params”, “representation”, and “A”. This attribute is set during fit_transform.
- fit_transform(X, y, sample_weight=None, average=True, n_classes=None)
This abstract method has to fit the representation and to return the transformed input data.
Note
Implementations of this abstract method should check the sanity of labels by calling check_y(y, n_classes) and they must set the property self.p_trn = class_prevalences(y, n_classes).
- Parameters:
X – The feature matrix to which this representation will be fitted.
y – The labels to which this representation will be fitted.
sample_weight (optional) – Importance weights for each (X[i], y[i]) pair to use during fitting. Defaults to None.
average (optional) – Whether to return a transfer matrix M or a transformation f(X). Defaults to True.
n_classes (optional) – The number of expected classes. Defaults to None.
- Returns:
A transfer matrix M if average==True or a transformation f(X) if average==False. f(X) might contain NaN entries if the fitting permits the estimation, e.g., in bootstrapped fitting procedures.
- property n_output_features
The number of output features generated by this representation.
- transform(X, sample_weight=None, average=True)
This abstract method has to transform the data X.
- Parameters:
X – The feature matrix that will be transformed.
sample_weight (optional) – Importance weights for each X[i] to use during averaging if average==True. Defaults to None.
average (optional) – Whether to return a vector q or a transformation f(X). Defaults to True.
- Returns:
A vector q = f(X).average(axis=0, weights=sample_weight) if average==True or a transformation f(X) if average==False.
Solvers
- class caife.AbstractSolver(nll: callable, latent_vectors: any, min_trials: int = 1, max_trials: int = 100, min_valid_trials: int = 1, seed: int | None = None)
Abstract base class that all caife solvers inherit from.
- Parameters:
nll – The negative log-likelihood function with the signature nll(params, *args) -> float, where params is a pytree containing vectors in their natural target space, e.g., count spectra or systematic parameter vectors, and args is a tuple of fixed parameters of the function.
latent_vectors – A JAX pytree of latent vectors. These vectors describe, for all model parameters, the mapping between their latent and natural target spaces as well as the generation of their starting points in latent space.
min_trials (optional) – The minimum number of random trials, each with a new, random starting point. Defaults to 1.
max_trials (optional) – The maximum number of random trials. No further trials are started once this number is reached, even if min_valid_trials is not yet met. Defaults to 100.
min_valid_trials (optional) – The minimum number of trials that need to produce a valid result. Further trials are started until this number is reached, unless max_trials is reached first. Defaults to 1.
seed (optional) – Random number generator seed. Defaults to None.
Note
Concrete sub-classes of this abstract class can extend the __post_init__ method to perform additional initialization steps like differentiating the objective function. So far, the __post_init__ method already initializes self.latent_nll_, which should be used in implementations of the abstract method solve_latent.
- create_starting_vector()
Create a starting vector for a new random trial, in latent space.
- Returns:
A single vector ell that concatenates a random starting point from each latent vector in self.latent_vectors, generated using self._rng. Implementations of solve_latent should minimize self.latent_nll_ starting from this vector.
- solve(args=(), return_aux=False)
Solve the unfolding problem.
Random trials are started until at least min_trials trials have been executed and at least min_valid_trials of them have produced a valid result, but no more than max_trials trials are started. The best valid result among all trials is returned.
- Parameters:
args (optional) – A tuple of extra arguments that are passed to nll. Defaults to ().
return_aux (optional) – Whether to return auxiliary information on the solution. This information could include, for instance, the number of iterations or the wall-clock time used for solving. Defaults to False.
- Returns:
A result pytree with the same structure as the given latent_vectors or None if none of the trials produced a valid result. If return_aux is True, return a pair of this result and a dict of auxiliary information.
- abstractmethod solve_latent(args)
Solve the unfolding problem in the corresponding latent space. This abstract method is meant to be implemented by concrete sub-classes of the AbstractSolver but is not meant to be called by a user directly.
- Parameters:
args – A tuple of extra arguments that are passed to latent_nll.
- Returns:
A LatentResult.
Note
Implementations of this abstract method should minimize self.latent_nll_ starting from self.create_starting_vector(). These class members represent the negative log-likelihood function that takes only a single combined latent vector as an argument and the single combined starting point in latent space.
- class caife.ScipySolver(nll: callable, latent_vectors: any, min_trials: int = 1, max_trials: int = 100, min_valid_trials: int = 1, seed: int | None = None, solver: str = 'trust-ncg', solver_options: dict[str, object]=<factory>, rtol: float = 1e-08)
A solver with a SciPy back-end.
- Parameters:
nll – The negative log-likelihood function with the signature nll(params, *args) -> float, where params is a pytree containing vectors in their natural target space, e.g., count spectra or systematic parameter vectors, and args is a tuple of fixed parameters of the function.
latent_vectors – A JAX pytree of latent vectors. These vectors describe, for all model parameters, the mapping between their latent and natural target spaces as well as the generation of their starting points in latent space.
min_trials (optional) – The minimum number of random trials, each with a new, random starting point. Defaults to 1.
max_trials (optional) – The maximum number of random trials. No further trials are started once this number is reached, even if min_valid_trials is not yet met. Defaults to 100.
min_valid_trials (optional) – The minimum number of trials that need to produce a valid result. Further trials are started until this number is reached, unless max_trials is reached first. Defaults to 1.
seed (optional) – Random number generator seed. Defaults to None.
solver (optional) – The method argument in scipy.optimize.minimize. Defaults to “trust-ncg”.
solver_options (optional) – The options argument in scipy.optimize.minimize. Defaults to caife.solvers.scipy.SOLVER_OPTIONS_FACTORY().
rtol (optional) – The relative tolerance for validity checks. Defaults to 1e-8.
Loss functions
- caife.poisson_nll(g_est, g_true, reduce=True)
Compute the (scaled) negative log-likelihood loss between g_est and g_true.
- Parameters:
g_est – A JAX pytree of estimated proxy distributions; could be a single vector of shape (n_proxy_bins,).
g_true – A JAX pytree of observed proxy distributions; could be a single vector of shape (n_proxy_bins,).
reduce (optional) – Whether to reduce the leaf-wise values through addition. Defaults to True.
- Returns:
The value of the (scaled) negative log likelihood. If reduce is False, return a JAX pytree of leaf-wise values.
- caife.tikhonov_regularization(f, scaling_factors=None, order=1, reduce=True)
Compute the Tikhonov regularization.
- Parameters:
f – A candidate solution or a matrix of candidate solutions to regularize, shape (n_classes,) or (n_solutions, n_classes).
scaling_factors (optional) – A vector of (n_classes,) factors that scale the rows of the Tikhonov matrix or None for unit scales. Defaults to None.
order (optional) – The largest order of a polynomial that is not penalized by this regularization term. Defaults to 1, so that any perfectly linear function (i.e., a function of polynomial order one) produces a zero-valued regularization term.
- Returns:
The value of the Tikhonov regularization with shape (n_solutions,) where n_solutions=1 if f.shape==(n_classes,).
Evaluation
- caife.gcc_from_nll(result, nll, args=(), ignore_overflow_bins=True)
Compute the global correlation coefficients of the result components from the target-space negative log-likelihood function.
This function computes the correlations from the Hessian of nll with respect to the target-space result. These legacy correlations ignore the constraints of the latent parameterization that a solver actually fits. Use gcc_from_aux to properly characterize the fitted parameters instead. Also see gcc_from_aux for more information on the global correlation coefficient.
- Parameters:
result – A JAX pytree of result components; could be a single spectrum of shape (n_target_bins,).
nll – The negative log-likelihood function that the result minimizes.
args (optional) – A tuple of extra arguments that are passed to nll. Defaults to ().
ignore_overflow_bins (optional) – Either a single bool, applied to every result component, or a JAX pytree of bools matching the structure of result, to control this per component. Defaults to True.
- Returns:
A JAX pytree of the global correlation coefficients corresponding to result components.
- caife.pcs_from_nll(result, nll, args=(), ignore_overflow_bins=True)
Compute the pair-wise correlation scores of the result components from the target-space negative log-likelihood function.
This function computes the correlations from the Hessian of nll with respect to the target-space result. These legacy correlations ignore the constraints of the latent parameterization that a solver actually fits. Use pcs_from_aux to properly characterize the fitted parameters instead. Also see gcc_from_aux for more information on the global correlation coefficient.
- Parameters:
result – A JAX pytree of result components; could be a single spectrum of shape (n_target_bins,).
nll – The negative log-likelihood function that the result minimizes.
args (optional) – A tuple of extra arguments that are passed to nll. Defaults to ().
ignore_overflow_bins (optional) – Either a single bool, applied to every result component, or a JAX pytree of bools matching the structure of result, to control this per component. Defaults to True.
- Returns:
A JAX pytree of the pair-wise correlation scores corresponding to result components. The score of a component is nan if it has fewer than two entries (after ignoring the overflow bins, if requested), because such a component has no pairs of entries to correlate.
- caife.gcc_from_aux(aux, ignore_overflow_bins=True)
Compute the global correlation coefficients of the result components from the auxiliary information of a solver.
The global correlation coefficient (GCC) was proposed by James: Statistical Methods in Experimental Physics (2006) and by Morik & Rhode: Discovery in Physics (2023). This coefficient should be minimal in unfolding because the true target bins should be independent, such that any correlations should be regarded as artifacts that stem from the reconstruction process. James (2006) defines the GCC of a single parameter P as the maximum correlation between P and all possible linear combinations of all other parameters. This correlation can be computed in multiple ways, and one of them is implemented here. Morik & Rhode (2023) apply this idea to unfolding by assessing the mean GCC over all target bins.
Here, the correlations are computed with respect to the latent-space parameterization that a solver actually fits. Use gcc_from_nll to instead compute the legacy correlations with respect to the target-space result, ignoring constraints imposed by the latent variables.
This function will score each component on the covariance of its own entries. Selecting these entries marginalizes all other entries, like the overflow bins, and all other result components, like systematic parameters, so that the correlations with these nuisance parameters are properly accounted for.
- Parameters:
aux – A dict of auxiliary information, as returned by AbstractSolver.solve(…, return_aux=True) together with a valid result. Must contain the keys ell, hess, and unravel_fn.
ignore_overflow_bins (optional) – Whether to exclude the first and the last entry of a component from its score. Either a single bool, applied to every result component, or a JAX pytree of bools matching the structure of the result, to control this per component. For a multi-dimensional component, like the spectrum of a MultiTargetModel, a single bool applies to every axis and a tuple with one bool per axis controls each axis separately. Defaults to True.
- Returns:
A JAX pytree of the mean global correlation coefficients corresponding to result components. The score of a component is nan if none of its entries remain after ignoring the overflow bins, or if the covariance of the remaining entries is singular. The covariance is singular, for instance, if all bins of a LatentSpectrum are kept, because the fixed number of samples makes each bin an exact linear combination of the other bins.
- caife.pcs_from_aux(aux, ignore_overflow_bins=True)
Compute the pair-wise correlation scores of the result components from the auxiliary information of a solver.
This alternative to the gcc_from_aux computes the correlation matrix from the covariance matrix and averages all off-diagonal entries. Hence, it computes the average pair-wise correlation between target bins instead of the average maximum correlation of each target bin with all linear combinations of the other bins.
Here, the correlations are computed with respect to the latent-space parameterization that a solver actually fits. Use pcs_from_nll to instead compute the legacy correlations with respect to the target-space result, ignoring constraints imposed by the latent variables.
- Parameters:
aux – A dict of auxiliary information, as returned by AbstractSolver.solve(…, return_aux=True) together with a valid result. Must contain the keys ell, hess, and unravel_fn.
ignore_overflow_bins (optional) – Whether to exclude the first and the last entry of a component from its score. Either a single bool, applied to every result component, or a JAX pytree of bools matching the structure of the result, to control this per component. For a multi-dimensional component, like the spectrum of a MultiTargetModel, a single bool applies to every axis and a tuple with one bool per axis controls each axis separately. Defaults to True.
- Returns:
A JAX pytree of the pair-wise correlation scores corresponding to result components. The score of a component is nan if fewer than two of its entries remain after ignoring the overflow bins, because such a component has no pairs of entries to correlate.
- caife.effective_number_of_degrees_of_freedom(result, unreg_nll, tau, ignore_overflow_bins=True)
Compute the effective number of degrees of freedom, as of Blobel (1985, 2002).
- Parameters:
result – A single spectrum of shape (n_target_bins,).
unreg_nll – The un-regularized variant of the negative log-likelihood function that the result minimizes.
tau – The strength of the Tikhonov regularization.
ignore_overflow_bins (optional) – Whether to ignore the correlations with the two over- and underflow bins. Defaults to True.
- Returns:
The effective number of degrees of freedom.
- caife.logarithmic_earth_movers_distance(f_true, f_est)
Compute the Earth Mover’s Distance, a.k.a. Wasserstein L1 distance, between the logarithm of a true spectrum and the logarithm of its estimate. Ignore over- and underflow bins during the computation. Due to the logarithmic scaling, and due to the choice of distance, the resulting value well represents the “physicist’s eye” in assessing similarity between spectra.
- Parameters:
f_true – The true spectrum, shape (n_target_bins,).
f_est – The estimated spectrum, shape (n_target_bins,).
- Returns:
The Earth Mover’s Distance between the two spectra.
- caife.gaussian_nll_score(f_true, f_est, uncertainties, ignore_overflow_bins=True)
Compute the negative log-likelihood of some ground-truth under the Gaussian distributions that a solution represents.
- Parameters:
f_true – The true spectrum, shape (n_target_bins,).
f_est – The estimated spectrum, shape (n_target_bins,).
uncertainties – The uncertainties of f_est, shape (n_target_bins,).
ignore_overflow_bins (optional) – Whether to ignore the two over- and underflow bins. Defaults to True.
- Returns:
The negative log-likelihood of np.ones(n_target_bins,) under Gaussian distributions with means given by f_est / f_true and standard deviations given by uncertainties / f_true.
Uncertainty estimation
- caife.uncertainty_from_hessian(result, nll, args=())
Estimate statistical uncertainties in the style of Minuit.
- Parameters:
result – A JAX pytree of result components; could be a single spectrum of shape (n_target_bins,).
nll – The negative log-likelihood function that the result minimizes.
args (optional) – A tuple of extra arguments that are passed to nll. Defaults to ().
- Returns:
A JAX pytree of the statistical uncertainties corresponding to result components.
- caife.uncertainty_from_aux(aux, n_samples=10000, rng=None)
Estimate statistical uncertainties through sampling in the latent space.
- Parameters:
aux – A dict of auxiliary information from the optimizer. Must contain keys ell, hess, and unravel_fn.
n_samples (optional) – The number of samples to generate in the latent space. Defaults to 10_000.
rng (optional) – The random number generator. Defaults to None.
- Returns:
A pair of JAX pytrees, one corresponding to all lower bounds and one corresponding to all upper bounds of the results within one standard deviation.