psiphy.forecasting

class psiphy.forecasting.fisher.tqdm(iterable, **kwargs)[source]

Minimal stand-in when tqdm is not installed (iteration and set_postfix only).

set_postfix(*args, **kwargs)[source]
class psiphy.forecasting.fisher.FisherMatrix(simulator, theta_fid, param_names, X_mean=0.0, X_std=1.0, verbose=True, cache_file=None, **sim_kwargs)[source]

Numerical Fisher matrix forecast.

F_ij = (dmu/dtheta_i)^T C^{-1} (dmu/dtheta_j)

Parameters:
  • simulator (callable) – Function with signature simulator(theta, initial_seed, noise_seed, **sim_kwargs) -> np.ndarray. Must return a 1D array (the summary statistic).

  • theta_fid (array-like, shape (n_params,)) – Fiducial parameter values.

  • param_names (list of str) – Names for each parameter.

  • X_mean (float or np.ndarray) – Mean for normalisation (0.0 = no normalisation).

  • X_std (float or np.ndarray) – Std for normalisation (1.0 = no normalisation).

  • verbose (bool) – Print progress messages.

  • cache_file (str or None) – Path to pickle file for caching simulation outputs across runs.

  • **sim_kwargs – Additional keyword arguments forwarded to the simulator.

Examples

>>> fm = FisherMatrix(my_sim, theta_fid=[0.0, 1.0], param_names=['mu', 'sigma'])
>>> fm.estimate_covariance(seeds=range(1, 11), noise_seeds=range(10))
>>> fm.estimate_derivatives(delta_frac=0.01)
>>> fm.compute()
>>> fm.plot_ellipses()
run_simulations(theta=None, seeds=range(1, 11), noise_seeds=range(0, 10), save=True, n_jobs=1)[source]

Pre-run and cache simulations.

Parameters:
  • theta (array-like or None) – Parameter values. Defaults to theta_fid.

  • seeds (iterable) – Initial condition seeds.

  • noise_seeds (iterable) – Noise seeds.

  • save (bool) – Save cache to file after running.

  • n_jobs (int) – Number of parallel workers (joblib). -1 uses all CPUs.

Return type:

self

cache_info()[source]

Print a summary of cached simulations grouped by theta.

test_simulator(seed=1, noise_seed=0)[source]

Run the simulator once at fiducial to verify it works.

Returns:

Normalised output at fiducial parameters.

Return type:

np.ndarray

estimate_covariance(seeds=range(1, 11), noise_seeds=range(0, 10), n_jobs=1, n_chunks=1)[source]

Estimate the data covariance matrix at the fiducial point.

Realisations are appended to any existing ones, so you can call this multiple times with different seed ranges to increase the sample size.

Parameters:
  • seeds (iterable) – Initial condition / cosmic variance seeds.

  • noise_seeds (iterable) – Instrument noise seeds.

  • n_jobs (int) – Number of parallel workers (joblib). -1 uses all CPUs. Each worker handles all noise_seeds for one IC seed, so the simulator’s in-memory coeval cache is reused within each job.

  • n_chunks (int) – (parallel only) Run the seeds in this many chunks, writing the cache after each, with a progress bar per finished chunk.

Return type:

self

add_modelling_error(mod_err=0.1)[source]

Add a fractional modelling error to the covariance.

Appends C_mod = diag(mod_err * mu_fid)^2 to the existing covariance and recomputes C_inv with the Hartlap correction.

Parameters:

mod_err (float or np.ndarray) – Fractional error per data bin.

Return type:

self

estimate_derivatives(delta_frac=0.01, seeds=range(1, 11), noise_seed=0, noise_seeds=None, n_stencil=2, use_crn=False, n_jobs=1, n_chunks=1)[source]

Estimate dmu/dtheta via central finite differences.

Parameters:
  • delta_frac (float, dict, or array-like) – Fractional step size h relative to the fiducial value. A dict keyed by parameter name (or an array in param order) sets a per-parameter step, so weakly responding parameters can use larger steps to beat down stochastic derivative noise (~1/h) without inflating truncation error for the others.

  • seeds (iterable) – Seeds to average over for stable derivatives.

  • noise_seed (int or None) – Noise seed for derivatives (0 = noiseless; None = average over 10). Ignored if noise_seeds is given.

  • noise_seeds (iterable or None) – Explicit list of noise seeds to average the derivatives over. Use this for summaries whose expectation depends on the noise level (non-additive statistics): with a seeded simulator, each noise seed gives the identical noise realisation at every stencil point, so the noise cancels in the differences while its suppression of the signal response is retained.

  • n_stencil (int) – Stencil order: 2, 4, or 6. Higher order reduces truncation error O(h^n).

  • use_crn (bool) – Use Common Random Numbers to cancel cosmic variance in the subtraction.

  • n_jobs (int) – Number of parallel workers (joblib). -1 uses all CPUs. Each worker handles all noise_seeds for one (theta_step, IC seed) pair.

  • n_chunks (int) – (parallel only) Run the seeds in this many chunks, writing the cache after each, with a progress bar per finished chunk.

Return type:

self

convergence_test_delta_frac(delta_fracs=None, seeds=range(1, 11), noise_seed=0, noise_seeds=None, n_stencil=2, use_crn=False, plot=True, restore=True, n_jobs=1)[source]

Test sensitivity of dmu/dtheta to the finite-difference step size.

Sweeps delta_fracs and records the per-parameter norm of the derivative and the 1D marginal constraint. A good step size shows a flat plateau in the middle: upturn at small h (stochastic noise) and at large h (truncation error).

Parameters:
  • delta_fracs (array-like or None) – Step sizes to test. Default: 10 log-spaced values from 1e-3 to 0.3.

  • seeds (iterable) – Forwarded to estimate_derivatives.

  • noise_seed (int or None) – Forwarded to estimate_derivatives.

  • n_stencil (int) – Forwarded to estimate_derivatives.

  • use_crn (bool) – Forwarded to estimate_derivatives.

  • plot (bool) – If True, show diagnostic plots.

  • restore (bool) – Restore self.dmu_dtheta to its value before the test.

  • n_jobs (int) – Forwarded to estimate_derivatives.

Returns:

Per-parameter dict with keys ‘delta_fracs’, ‘norms’, ‘sigma_1d’.

Return type:

dict

compute(method='standard', n_bootstrap=0, n_split=None, shrinkage_target='diagonal', debias_derivatives=False)[source]

Compute the Fisher matrix. Results stored in self.F and self.F_inv.

Parameters:
  • method (str) –

    • 'standard': F = J C⁻¹ Jᵀ (default).

    • 'lfim': score-trick estimator via Synthetic Likelihood.

    • 'CoultonWandelt2023': geometric mean of the standard Fisher (biased high by derivative noise) and a compressed Fisher (biased low). Also sets self.F_upper and self.F_lower.

    • 'Shrinkage': Ledoit-Wolf-style covariance regularisation.

  • n_bootstrap (int) – (lfim only) Bootstrap resamples for uncertainty; populates self.F_std.

  • n_split (int or None) – (CoultonWandelt2023 only) Number of derivative IC seeds used for the compression; the rest measure the compressed derivatives, and the two roles are then swapped. Defaults to half.

  • shrinkage_target (str) – (Shrinkage only) ‘diagonal’ or ‘identity’.

  • debias_derivatives (bool) – (‘standard’ only) Subtract the Fisher inflation caused by stochastic error in the estimated derivatives, E[dm^T C^-1 dm] = F + tr(C^-1 Cov(dm)). Cov(dm) is estimated from the per-noise-seed and per-IC-seed derivative scatter recorded by estimate_derivatives (non-CRN path). If the debiased matrix has non-positive eigenvalues, the corresponding directions carry no significant information; eigenvalues are clipped with a warning.

Return type:

self

sigma_1d()[source]

1D marginal 1-sigma errors (marginalised over all other parameters).

Returns:

sigma_i = sqrt(F_inv[i,i])

Return type:

np.ndarray, shape (n_params,)

sigma_2d()[source]

2D marginal errors for all parameter pairs.

Return type:

dict keyed by (i, j) → (sigma_i, sigma_j)

sigma_conditional()[source]

Conditional errors (all other parameters perfectly known).

Returns:

sigma_i = 1 / sqrt(F[i,i])

Return type:

np.ndarray, shape (n_params,)

correlation_matrix()[source]

Parameter correlation matrix derived from F_inv.

Return type:

np.ndarray, shape (n_params, n_params)

sub_fisher(param_indices)[source]

Extract a Fisher sub-matrix for a subset of parameters.

Parameters:

param_indices (list of int)

Return type:

F_sub, F_sub_inv, sigma_sub

ellipse_params(i, j, n_sigma=1)[source]

Compute ellipse parameters for the 2D marginal of parameters (i, j).

Parameters:
  • i (int) – Parameter indices.

  • j (int) – Parameter indices.

  • n_sigma (int) – 1 or 2.

Returns:

dict with keys

Return type:

center, width, height, angle_deg

classmethod joint(blocks, verbose=True)[source]

Fisher matrix of the concatenated data vectors of several FisherMatrix objects.

Use this when the blocks come from the same simulations, e.g. different summaries, or one summary at different redshifts, so they are correlated and F_a + F_b would double count. The covariance is estimated from the concatenated vectors, paired by (seed, noise_seed), and the derivatives are concatenated block by block. Keeping one block (and one cache file) per summary or redshift means that adding a block later reuses the rest.

Every block must have run estimate_covariance on the same (seed, noise_seed) pairs and estimate_derivatives on the same IC seeds. A block whose derivatives used a single noise seed (e.g. noiseless) enters the noise part of the derivative debias with zero scatter.

Parameters:
Returns:

Call compute() on it as usual.

Return type:

FisherMatrix

plot_ellipses(others=None, labels=None, label_names=None, prior_range=None, n_sigma_list=(1, 2), figsize=None, colors=None, filled=False)[source]

Triangle plot of Fisher confidence ellipses.

Parameters:
  • others (dict or None) – Additional FisherMatrix objects to overlay, keyed by label string.

  • labels (str or None) – Label for this Fisher matrix in the legend.

  • label_names (dict or None) – param_name -> LaTeX label string (without $).

  • prior_range (dict or None) – param_name -> (low, high) for axis limits.

  • n_sigma_list (list of int) – Contour levels (1 and/or 2).

  • figsize (tuple or None) – Figure size.

  • colors (dict or None) – label -> colour.

  • filled (bool) – Fill the innermost ellipse.

Return type:

matplotlib.figure.Figure

plot_derivatives(label_names=None, figsize=None)[source]

Plot dmu/dtheta for each parameter.

Return type:

matplotlib.figure.Figure

plot_covariance(figsize=(6, 5))[source]

Plot the covariance and correlation matrices.

Return type:

matplotlib.figure.Figure

sample(n_samples=100000)[source]

Draw Gaussian samples from the Fisher posterior.

Parameters:

n_samples (int)

Return type:

np.ndarray, shape (n_samples, n_params)

to_getdist(n_samples=100000, label=None, label_names=None)[source]

Generate a getdist MCSamples object (Gaussian approximation).

Parameters:
  • n_samples (int)

  • label (str or None)

  • label_names (dict or None) – param_name -> LaTeX label.

Return type:

getdist.MCSamples

save(filepath)[source]

Save Fisher matrix results to an npz file.

Parameters:

filepath (str)

classmethod load(filepath, simulator=None, **sim_kwargs)[source]

Load a FisherMatrix from an npz file.

Parameters:
  • filepath (str)

  • simulator (callable or None)

Return type:

FisherMatrix

psiphy.forecasting.fisher.fisher_blocks(simulator, theta_fid, param_names, blocks, cache_file=None, covariance_kw=None, derivative_kw=None, verbose=False, desc='blocks', fisher_class=None, dali_kw=None)[source]

One FisherMatrix, with its own cache file, per block of a data vector.

A block is any part of the data vector that is simulated separately: one redshift, frequency band, sky patch or summary statistic. Keeping one cache per block means that adding a block later only simulates the new one. Combine the blocks with FisherMatrix.joint, which keeps their cross-covariance.

Parameters:
  • simulator (callable) – simulator(theta, seed, noise_seed, **kwargs) -> data vector of one block.

  • theta_fid – As for FisherMatrix.

  • param_names – As for FisherMatrix.

  • blocks (dict) – Block name -> keyword arguments passed to the simulator for that block, e.g. {z: dict(redshifts=[z]) for z in redshifts}.

  • cache_file (callable or None) – cache_file(name) -> path of the block’s cache file.

  • covariance_kw (dict or None) – Arguments of estimate_covariance and estimate_derivatives, the same for every block (so the blocks can be joined).

  • derivative_kw (dict or None) – Arguments of estimate_covariance and estimate_derivatives, the same for every block (so the blocks can be joined).

  • verbose (bool)

  • desc (str) – Label of the progress bar over the blocks.

  • fisher_class (type or None) – Class of the blocks, FisherMatrix (default) or a subclass such as FisherMatrixDALI. Join them with fisher_class.joint.

  • dali_kw (dict or None) – Arguments of estimate_dali_derivatives, run on every block when given; needs fisher_class=FisherMatrixDALI.

Returns:

Block name -> FisherMatrix with covariance and derivatives estimated.

Return type:

dict

Examples

>>> fms = fisher_blocks(sim, theta, names, {z: dict(redshifts=[z]) for z in (7, 8, 9)},
...                     cache_file=lambda z: f'cache_z{z:.2f}.pkl',
...                     covariance_kw=dict(seeds=range(1, 41), noise_seeds=range(1, 41)),
...                     derivative_kw=dict(seeds=range(1, 41), delta_frac=0.02))
>>> F = FisherMatrix.joint(list(fms.values())).compute()

DALI forecasts: the Fisher expansion extended with higher-order derivatives of the model mean (Sellentin, Quartin & Amendola 2014, arXiv:1401.6892).

class psiphy.forecasting.dali.FisherMatrixDALI(simulator, theta_fid, param_names, **kwargs)[source]

Bases: FisherMatrix

Fisher forecast extended with DALI (Sellentin, Quartin & Amendola 2014).

The Fisher matrix keeps the first derivatives of the mean data vector. DALI also keeps its second (doublet, order=2) and third (triplet, order=3) derivatives, so the approximate likelihood:

ln L = -1/2 r^T C^-1 r,
r = mu_,a D_a + 1/2 mu_,ab D_a D_b + 1/6 mu_,abc D_a D_b D_c,

with D = theta - theta_fid, can be non-Gaussian in the parameters while staying normalisable. The covariance C is parameter-independent, as in FisherMatrix.

Everything of FisherMatrix is inherited (covariance, first derivatives, compute, cache, parallel runs); its Gaussian outputs (sigma_1d, plot_ellipses, …) remain the Fisher baseline.

Parameters:

FisherMatrix. (As for)

Examples

>>> fm = FisherMatrixDALI(my_sim, theta_fid=[0.0, 1.0], param_names=['mu', 'sigma'])
>>> fm.estimate_covariance(seeds=range(1, 11), noise_seeds=range(10))
>>> fm.estimate_derivatives(delta_frac=0.01)
>>> fm.estimate_dali_derivatives(order=2, delta_frac=0.05)
>>> fm.compute()
estimate_dali_derivatives(order=2, delta_frac=0.05, seeds=range(1, 11), noise_seed=0, noise_seeds=None, accuracy=2, snr_warn=3.0, noise_tol=0.1, n_jobs=1, n_chunks=1)[source]

Estimate the second (and third) derivatives of the mean data vector with central finite differences.

Each partial derivative uses the tensor product of central 1D stencils, e.g. (mu_++ - mu_+- - mu_-+ + mu_--) / (4 h_a h_b) for mu_,ab at accuracy=2. The simulator gets the same (seed, noise_seed) at every stencil point, so the realisation largely cancels in the differences. Stencil points shared with estimate_derivatives (same steps) and the covariance runs are taken from the cache.

Finite-difference noise grows as 1/h^2 (1/h^3 for the third derivatives), so these need larger steps than the first derivatives. After the run, the noise of each derivative is estimated from its scatter over the IC seeds, and a warning is printed (independent of verbose) for entries that are both noise-dominated (SNR < snr_warn) and noisy enough to matter: the whitened noise of their term in r at the Fisher 1-sigma scale exceeds noise_tol.

Parameters:
  • order (int) – 2 (doublet: mu_,ab) or 3 (triplet: mu_,ab and mu_,abc).

  • delta_frac (float, dict, or array-like) – Fractional step size per parameter, as for estimate_derivatives.

  • seeds (iterable) – IC seeds to average over. At least 2 are needed for the noise check.

  • noise_seed – As for estimate_derivatives.

  • noise_seeds – As for estimate_derivatives.

  • accuracy (int) – Truncation order of the stencils (error O(h^accuracy)); even, >= 2.

  • snr_warn (float) – SNR below which an entry counts as noise-dominated. SNR is sqrt(m^T C^-1 m / tr(C^-1 Cov(m))) for the mean derivative m, which is about 1 for pure noise.

  • noise_tol (float) – Noise of an entry’s term in r (whitened, at the Fisher 1-sigma offsets) above which a noise-dominated entry is reported. The 1-sigma offsets come from the first derivatives, debiased for their noise when estimate_derivatives recorded per-seed samples; noisy first derivatives without such samples make sigma, and so this check, too small.

  • n_jobs – As for estimate_derivatives.

  • n_chunks – As for estimate_derivatives.

Return type:

self

convergence_test_delta_frac(delta_fracs=None, seeds=range(1, 11), noise_seed=0, noise_seeds=None, n_stencil=2, use_crn=False, plot=True, restore=True, n_jobs=1, order=1, accuracy=2, snr_warn=3.0)[source]

Test sensitivity of the derivatives to the finite-difference step size.

order=1 runs FisherMatrix.convergence_test_delta_frac on the first derivatives. order=2 (or 3) sweeps delta_fracs through estimate_dali_derivatives and records, for every distinct second (and third) derivative, its norm and its SNR over the IC seeds. A good step sits on the plateau between rounding or simulation noise (small h) and truncation error (large h); noise-dominated points (SNR < snr_warn) are marked in the plot. No noise warnings are printed during the sweep.

Parameters:
  • delta_fracs (array-like or None) – Step sizes to test. Default: 10 log-spaced values from 1e-3 to 0.3.

  • seeds – Forwarded to estimate_derivatives / estimate_dali_derivatives.

  • noise_seed – Forwarded to estimate_derivatives / estimate_dali_derivatives.

  • noise_seeds – Forwarded to estimate_derivatives / estimate_dali_derivatives.

  • n_jobs – Forwarded to estimate_derivatives / estimate_dali_derivatives.

  • n_stencil – (order=1 only) Forwarded to estimate_derivatives.

  • use_crn – (order=1 only) Forwarded to estimate_derivatives.

  • plot (bool) – If True, show diagnostic plots.

  • restore (bool) – Restore the derivatives to their values before the test.

  • order (int) – 1, 2 or 3.

  • accuracy (int) – (order >= 2) Forwarded to estimate_dali_derivatives.

  • snr_warn (float) – (order >= 2) SNR below which a point is marked as noise-dominated.

Returns:

order=1: as FisherMatrix.convergence_test_delta_frac. order >= 2: entry name (e.g. ‘d(a)(b)’) -> dict with keys ‘delta_fracs’, ‘norms’ and ‘snr’.

Return type:

dict

classmethod joint(blocks, verbose=True)[source]

DALI forecast of the concatenated data vectors of several FisherMatrixDALI objects, for correlated blocks; see FisherMatrix.joint.

The higher-order derivatives and their per-seed samples are concatenated block by block, up to the highest order every block has. Every block must have run estimate_dali_derivatives on the same IC seeds.

Parameters:
Returns:

Call compute() on it as usual.

Return type:

FisherMatrixDALI

dali_logpdf(theta, order=None, prior_bounds=None, log_prior=None)[source]

DALI log-likelihood, ln L = -1/2 r^T C^-1 r (unnormalised).

Parameters:
  • theta (array-like, shape (n_params,) or (n, n_params))

  • order (int or None) – 1 (Fisher), 2 (doublet) or 3 (triplet); None uses the highest order whose derivatives have been estimated.

  • prior_bounds (list of (low, high) or None) – Box prior; -inf outside.

  • log_prior (callable or None) – log_prior(theta) -> (n,) for a batch theta of shape (n, n_params), added to the log-likelihood.

Return type:

float or np.ndarray, shape (n,)

dali_tensors(order=None)[source]

The DALI tensors T_(i,j) = mu^(i)^T C^-1 mu^(j), mu^(i) being the i-th derivatives of the mean, such that

-ln L = sum_(i,j) T_(i,j) D^(i+j) / (2 i! j!)

over all pairs (i, j) with i, j <= order. T_(1,1) is the Fisher matrix F, T_(2,1) and T_(2,2) are S and Q of Sellentin et al. (2014).

Returns:

(i, j) -> array with i + j parameter axes, for order >= i >= j >= 1.

Return type:

dict

sample(n_samples=100000, approx='dali', **kwargs)[source]

Draw samples from the DALI (or Fisher) posterior.

Parameters:
  • n_samples (int)

  • approx (str) – ‘dali’ (default) or ‘fisher’ (Gaussian, as FisherMatrix.sample).

  • order (int or None) – DALI order; None uses the highest order estimated.

  • method (str) – ‘importance’ (default): importance sampling from the Fisher Gaussian with covariance inflated by inflate**2, then resampled to equal weights; prints a warning when the effective sample size is below ess_warn * n_samples. ‘emcee’: ensemble MCMC with n_walkers walkers and n_burn burn-in steps.

  • prior_bounds – As for dali_logpdf.

  • log_prior – As for dali_logpdf.

Return type:

np.ndarray, shape (n_samples, n_params)

to_getdist(n_samples=100000, label=None, label_names=None, approx='dali', **kwargs)[source]

getdist MCSamples of the DALI (or Fisher) posterior.

Importance samples are passed with their weights. Keyword arguments are those of sample(); prior_bounds also sets the getdist ranges.

Return type:

getdist.MCSamples

plot_dali(orders=None, others=None, n_samples=100000, label_names=None, colors=None, settings=None, width_inch=6, **sample_kw)[source]

getdist triangle plot of the Fisher and DALI posteriors.

Parameters:
  • orders (iterable of int or None) – Orders to plot: 1 (Fisher), 2 (DALI-2), 3 (DALI-3). Default: all estimated orders.

  • others (dict or None) – Label -> getdist MCSamples to overlay filled, e.g. the posterior of the exact likelihood.

  • n_samples (int)

  • label_names (dict or None) – param_name -> LaTeX label.

  • colors (list or None) – One colour per curve (orders first, then others).

  • settings (dict or None) – getdist analysis settings applied to every sample, e.g. {'fine_bins_2D': 1024} for long tails.

  • width_inch (float)

  • **sample_kw – Forwarded to to_getdist for the DALI orders (method, prior_bounds, …).

Return type:

getdist.plots.GetDistPlotter