Model Fitting

Fitters

FunctionDescription
fit_model(model, x0, data)Fit a FlatModel via NLopt
fit_model_lsqfit(model, x0, data)Fit a FlatModel via Levenberg-Marquardt
fit_model_nested(model, data; lb, ub)Nested sampling: posterior and log-evidence; needs finite bounds
fit_model_ultranest(model, data; lb, ub)fit_model_nested pinned to the UltraNest backend
nested_backend(), set_nested_backend!(b)The default nested sampler: :nautilus or :ultranest
fit_model_ensemble(model, free, data; lb, ub)Posterior samples by Ensemble Slice Sampling, with R̂ and τ
fit_model_pigeons(model, free, data; lb, ub)Posterior samples and log-evidence by parallel tempering; needs using Pigeons
chi2_map(model_dict, free, data, p1, p2)χ² surface over a grid of two free parameters

The packages each fitter needs are listed under What each optimiser needs.

TypeDescription
FitResultResult from fit_model (fields: x_opt, chi2r, model, ...)
LsqFitResultResult from fit_model_lsqfit (adds stderror, covar, converged)
NestedResultResult from fit_model_nested (adds logz, logzerr, posterior, result, backend)
UltraNestResultAlias for NestedResult
BootstrapResultResult from bootstrap_fit (adds samples, median, sigma_minus, sigma_plus, covar)
Chi2Mapχ² surface over two free parameters from chi2_map; FitResult(map) gives its best grid point
DataBlocksPartition of an OIdata into resampling blocks
ModelConstraintOne relation between model parameters, enforced during fitting
OITOOLS.fit_model — Function
fit_model(model_dict, list_free_params, data; kwargs...) -> FitResult

Fit a parametric model to interferometric data using NLopt.

Arguments

  • model_dict::Dict{String} — flat parameter dictionary (values are numbers or expression strings)
  • list_free_params::Vector{String} — names of the free parameters to optimize
  • data::OIdata — interferometric data

Keywords

  • lb, ub — Dict{String,Float64} of lower/upper bounds per parameter (default: ±Inf)
  • weights — observable weights [V2, T3amp, T3phi, visamp, visphi, flux, diffphase]
  • priors — Vector of (expr_str, target, sigma) tuples for Gaussian penalties
  • constraints — relations between parameters that bounds cannot express, as ModelConstraints or (lhs, op, rhs[, tol]) tuples, passed to NLopt as nonlinear constraints; a method that does not support them is wrapped in :AUGLAG. The reported chi2 is the data χ²
  • rv — radial velocities (read_rv) fitted with the interferometry, against the orbit of the model's component on an orbit; their χ² is added, and ndof counts them
  • method — NLopt algorithm (default :LD_LBFGS; use :LN_NELDERMEAD for gradient-free)
  • maxeval — maximum function evaluations (default 2000)
  • ftol_rel, xtol_rel — convergence tolerances
  • nB_workspace — Hankel workspace size (default: nuv from data)
  • verb — print per-evaluation chi2 breakdown
source
fit_model(model::FlatModel, x0, data; kwargs...) -> FitResult

Fit a pre-compiled FlatModel starting from parameter vector x0.

This method skips the dict_to_model step, which is useful when fitting the same model multiple times (e.g. bootstrap, grid search).

Bounds lb and ub can be Dict{String,Float64} (keyed by parameter name) or Vector{Float64} (ordered to match model.list_free_params).

source
OITOOLS.fit_model_lsqfit — Function
fit_model_lsqfit(model_dict, list_free_params, data; kwargs...) -> LsqFitResult

Fit a parametric model by Levenberg-Marquardt. Returns the covariance and 1σ uncertainties, both scaled to χ²ᵣ = 1.

A parameter that reaches a bound is held there and left out of the step. Besides LsqFit's gradient and step tests, the iteration stops when the Gauss-Newton step would lower χ² by less than 0.001 · max(1, χ²/n) (n data points). reason gives the test that stopped it, and at_bound the parameters held on a bound. The Jacobian is analytic (residuals_flat_jac).

Arguments

  • model_dict::Dict{String} — flat parameter dictionary
  • list_free_params::Vector{String} — names of the free parameters to optimize
  • data::OIdata — interferometric data

Keywords

  • lb, ub — Dict{String,Float64} of lower/upper bounds per parameter
  • weights — observable weights [V2, T3amp, T3phi, visamp, visphi, flux, diffphase]
  • nB_workspace — Hankel workspace size
  • maxIter — maximum iterations (default 200)
  • constraints — relations between parameters that bounds cannot express, as ModelConstraints or (lhs, op, rhs[, tol]) tuples, added as extra rows of the residual vector and the Jacobian, so covar and stderror include them. The reported chi2 excludes them
  • measurement — the measurement model (measurement_model); with visphi = :continuum, each spectral vector's VISPHI residuals are referenced to a polynomial fitted over its continuum channels, as PMOIRED's DPHI (ndof reduced by the coefficients)
  • rv — radial velocities (read_rv) fitted with the interferometry, against the orbit of the model's component on an orbit (c,orb Ka, Kb, gamma, or M and q). They enter the residual vector after the data; chi2 and ndof count them, chi2_rv is their part
  • verb — print per-evaluation chi2 breakdown
source
fit_model_lsqfit(model::FlatModel, x0, data; kwargs...) -> LsqFitResult

Levenberg-Marquardt fit on a pre-compiled FlatModel starting from x0. Bounds lb and ub can be Dicts or Vectors. Radial velocities rv need rv_component, the component on an orbit.

source
OITOOLS.fit_model_nested — Function
fit_model_nested(model_dict, list_free_params, data; kwargs...) -> NestedResult
fit_model_nested(model::FlatModel, data; kwargs...)             -> NestedResult

Fit a parametric model by nested sampling: posterior samples, log-evidence and the maximum-likelihood point. The starting values are not used. Every free parameter needs finite bounds, which define the uniform prior.

using OITOOLS, Nautilus
r = fit_model_nested(model_dict, ["star,ud"], data;
                     lb = Dict("star,ud" => 0.5), ub = Dict("star,ud" => 10.0))
r.logz, r.logzerr        # the evidence, for comparing models
r.posterior              # equally weighted samples, (n_samples, n_params)

backend selects the sampler and defaults to nested_backend(); see set_nested_backend! to change it for a session.

Keywords, both backends

keyworddefaultmeaning
lb, ubDict{String,Float64} bounds, required for every free parameter
weights[1,1,1,0,0,0,0]observable weights [V2, T3amp, T3phi, visamp, visphi, flux, diffphase]
constraints[]ModelConstraints or (lhs, op, rhs[, tol]) tuples, added to the log-likelihood as -penalty/2
nB_workspacefrom the dataHankel workspace size
verbtrueprint progress
cornerplottruedraw the corner plot when a plotting backend is loaded
seednothingreproducible run (UltraNest: seeds numpy's generator, restored afterwards, and uses fixed batches of 512 proposals)

Keywords, :nautilus

keyworddefaultmeaning
n_live500live points in the exploration phase
n_eff2000effective sample size to reach before stopping
f_live0.01fraction of evidence left in the live set at which exploration ends
n_networks4networks in the bounding ensemble
threadednthreads() > 1evaluate the likelihood across threads

Keywords, :ultranest

keyworddefaultmeaning
min_num_live_points400minimum live points
cluster_num_live_points100live points per cluster
num_bootstraps30bootstraps for the evidence error
use_stepsamplerfalseuse RegionSliceSampler
nsteps400steps per slice, with use_stepsampler
frac_remain0.001termination fraction
log_interval100logging interval

:nautilus is importance nested sampling with neural-network bounds. On the α Cen A and B power-law fits its logzerr is 0.019, against 0.18–0.31 for UltraNest, with x_opt equal to four decimals.

source
OITOOLS.set_nested_backend! — Function
set_nested_backend!(b::Symbol) -> Symbol

Choose the nested sampler: :nautilus or :ultranest.

The backend's package must be loaded; otherwise this raises an error.

source
OITOOLS.chi2_map — Function
chi2_map(model_dict, list_free_params, data, p1, p2; kwargs...) -> Chi2Map

Evaluate χ² on a grid over the two free parameters p1 and p2, holding every other free parameter at its starting value.

m = read_model_file("LD_power.toml")
map = chi2_map(m.model, m.free, data, "star,ldpow", "star,alpha"; m.lb, m.ub, weights = [1.0,0,0])
res = FitResult(map)          # the best grid point
keyworddefaultmeaning
n1, n260grid points along each axis
range1, range2from lb/ub(lo, hi) for each axis, overriding the bounds
lb, ubDict()bounds; used as the default axis extent
weights[1,1,1,0,0,0,0]observable weights [V2, T3amp, T3phi, visamp, visphi, flux, diffphase]
nB_workspace100passed through to parse_model
on_gridnothingcalled before the first evaluation with (; p1, p2, v1, v2, chi2): the axes and the χ² array, NaN until each point is evaluated

Each axis needs finite bounds or an explicit range. p1 and p2 must both be free.

source
OITOOLS.delta_chi2_levels — Constant
delta_chi2_levels

Δχ² for the 68.3, 95.4 and 99.7% confidence regions of two jointly estimated parameters: 2.30, 6.17, 11.8.

The one-parameter values are 1, 4, 9.

source
OITOOLS.FitResult — Type
FitResult

What every point-estimate fitter returns: fit_model, fit_model_lsqfit and the grid search.

fieldmeaning
x_optbest-fit values, in list_free_params order
list_free_paramsthe names, so x_opt[i] is always identifiable
chi2, chi2r, ndofraw weighted χ², χ²/ndof, and the number of DATA POINTS
n_evalsχ² evaluations spent
retthe optimiser's return code
modelthe compiled FlatModel the fit ran against

ndof counts data points and is not reduced by the number of free parameters, so it is not a degrees-of-freedom in the model-comparison sense; compute AIC or BIC from chi2 and the parameter count rather than reading them off chi2r.

See also LsqFitResult, UltraNestResult and Chi2Map.

source
OITOOLS.NestedResult — Type
NestedResult

Result of fit_model_nested, whichever sampler produced it.

fieldtypemeaning
x_optVector{Float64}maximum-likelihood parameter values
list_free_paramsVector{String}parameter names, same order as x_opt
chi2, chi2r, ndofFloat64, Float64, Intchi² at x_opt, reduced chi², degrees of freedom
logz, logzerrFloat64Bayesian log-evidence and its uncertainty
posteriorMatrix{Float64}(n_samples, n_params) equally weighted posterior samples
resultAnythe sampler's own result object, passed through unconverted
modelFlatModelthe compiled model that was fitted
backendSymbolthe sampler: :nautilus or :ultranest

result is backend-specific: under :ultranest a PythonCall.Py wrapping UltraNest's result dict (index with result["key"], convert with pyconvert(T, …)), under :nautilus the sampler state Nautilus returned.

source
OITOOLS.Chi2Map — Type
Chi2Map

A χ² surface over two free parameters.

fieldmeaning
p1, p2the two parameter names, as they appear in list_free_params
v1, v2the grid values along each axis
chi2(length(v1), length(v2)) matrix of raw weighted χ²
ndofnumber of data points with non-zero weight; chi2 ./ ndof is the reduced map
x_optthe full free-parameter vector at the grid minimum
list_free_paramsnames for x_opt, in fit-vector order
modelthe compiled model the map was computed with

The other free parameters are held at their starting values: the map is a slice through the χ² surface, not a profile.

See also chi2_map and delta_chi2_levels.

source

Bounds, constraints and model files

lb/ub bound each parameter. Relations between parameters (a ring's outer diameter larger than its inner one, two fluxes summing to one) are ModelConstraints.

FunctionDescription
default_bounds(model_dict, free; data, max_size)Suggested lb/ub per free parameter; with data, angular sizes are capped at 2 λ/B_min
max_angular_scale(data)The largest angular scale the shortest baseline senses, in mas
ModelConstraint(lhs, op, rhs; tol)A relation between parameters, with op one of <, <=, >, >=, =
parse_constraints(specs)Constraints from ModelConstraints, (lhs, op, rhs[, tol]) tuples (PMOIRED's layout) or dicts
check_constraints(constraints, model_dict)Which constraints the starting model already satisfies
read_model_file(path)Read a TOML model file into (; model, free, lb, ub, constraints, priors, name)
write_model_file(path, model_dict; free, lb, ub, constraints, priors)Write a TOML model file

fit_model passes constraints to NLopt as nonlinear constraints, which hold at the optimum; an algorithm that does not support them (including the default :LD_LBFGS) is wrapped in :AUGLAG. fit_model_lsqfit, fit_model_nested and the samplers add a one-sided quadratic penalty on the normalised violation, as PMOIRED's prior list does; a steep χ² can outweigh it.

A TOML model file holds the model dict, the free parameters, the bounds, the constraints and the priors.

free = ["star,ud", "disk,pa"]

[model]
"star,ud"   = 6.5
"disk,fwhm" = "$star,ud * 3"

[bounds]
"star,ud" = [0.0, 20.0]

[[constraints]]
param = "disk,diamout"
op    = ">"
value = "disk,diamin"
tol   = 0.001

[[priors]]
expr   = "star,ud"
target = 6.0
sigma  = 0.5
m = read_model_file("binary.toml")
res = fit_model(m.model, m.free, data; m.lb, m.ub, m.constraints, m.priors)

free is a top-level key; [model] holds the model dict as it is, global keys included.

OITOOLS.default_bounds — Function
default_bounds(model_dict, list_free_params; data = nothing, max_size = nothing) -> (lb, ub)

Suggested lower and upper bounds for each free parameter, as two Dict{String,Float64} for the fitters' lb/ub.

Bounds are chosen from the parameter's suffix, the part after the first comma ("star,ud" is looked up as "ud"). Azimuthal-mode keys ("c,az amp1", "c,az projang1") are recognised by prefix. Other parameters, including global ones, get (-Inf, Inf).

Angular sizes and offsets are bounded by 2 λ/B_min with data (max_angular_scale), by DEFAULT_MAX_SIZE_MAS without; max_size overrides both.

lb, ub = default_bounds(model_dict, free)              # 100 mas ceiling
lb, ub = default_bounds(model_dict, free; data = data) # sized to this uv coverage

Other bounds: fluxes [0, Inf), thick and croff [0, 1], inclination [0, 90], position angles [-180, 180], u and w [-1, 1], alpha [0, 3], Claret coefficients [-3, 3], azimuthal amplitudes az ampN [0, 1] (PMOIRED leaves them unbounded), and orbit elements (orb …) their own ranges. Nested sampling needs finite bounds, so free fluxes need an upper bound set by hand.

See also display_model, which checks values against bounds.

source
OITOOLS.max_angular_scale — Function
max_angular_scale(data) -> Float64

Largest angular scale of the uv coverage, in mas: 1/Bmin with Bmin the shortest baseline in wavelengths.

source
OITOOLS.ModelConstraint — Type
ModelConstraint(lhs, op, rhs; tol = DEFAULT_CONSTRAINT_TOL)

A relation between model parameters, enforced during fitting.

lhs and rhs are parameter names ("disk,diamout") or expressions over parameter names ("2 * star,ud"); rhs may be a number. op is one of "<", "<=", ">", ">=", "=", as a string or a symbol. tol: see DEFAULT_CONSTRAINT_TOL.

fit_model passes constraints to NLopt as nonlinear constraints. fit_model_lsqfit, fit_model_nested and the samplers apply a one-sided quadratic penalty, which a steep χ² can outweigh; tol is then its stiffness.

ModelConstraint("disk,diamout", ">", "disk,diamin")
ModelConstraint("star,f + disk,f", "=", 1.0)
ModelConstraint("star,ud", "<", 4.0; tol = 0.01)

Global keys (no comma) are written with a \$, as "\$PA", as in a model expression; a bare name with no comma and no arithmetic gets its \$ added.

See also fit_model and read_model_file.

source
OITOOLS.parse_constraints — Function
parse_constraints(specs) -> Vector{ModelConstraint}

Constraints from ModelConstraints, tuples (lhs, op, rhs[, tol]) (PMOIRED's prior layout), or Dicts / NamedTuples with keys param/lhs, op, value/rhs and tol (as read from a TOML file).

source
OITOOLS.check_constraints — Function
check_constraints(constraints, model_dict; verb = true) -> Vector{Bool}

Which constraints the model satisfies at its current values. A violated constraint at the start is not an error.

source
OITOOLS.DEFAULT_CONSTRAINT_TOL — Constant

Default tolerance of a constraint, 1e-3, in the units of the constrained quantity. For NLopt it is the feasibility tolerance; for the penalty (least-squares fit, nested sampling, samplers) a violation of tol costs one unit of penalty.

source
OITOOLS.read_model_file — Function
read_model_file(path) -> (; model, free, lb, ub, constraints, priors, name)

Read a TOML model file into the arguments of the fitters:

m = read_model_file("binary.toml")
res = fit_model(m.model, m.free, data; m.lb, m.ub, m.constraints, m.priors)

Only [model] is required; without free the model has no free parameters. A bound absent from the file is ±Inf (not taken from default_bounds).

An image component's c,image path, when relative, is taken relative to the model file and returned absolute.

$WL is in microns. In a file without wl_unit = "um", $WL is in metres and is read as ($WL*1e-6), with a message; write_model_file writes the marker.

See also write_model_file, ModelConstraint and default_bounds.

source
OITOOLS.write_model_file — Function
write_model_file(path, model_dict; free, lb, ub, constraints, priors, name)

Write a model and its fit settings to a TOML file readable by read_model_file.

write_model_file("binary.toml", model; free, lb, ub,
                 constraints = [ModelConstraint("disk,diamout", ">", "disk,diamin")])

Keys are sorted. Bounds infinite on both sides are omitted. To write a fit result, merge the fitted values into the model: write_model_file(path, merge(model, Dict(zip(res.list_free_params, res.x_opt))); free = res.list_free_params, ...).

source

Measurement model

fit_model_lsqfit(…; measurement) sets how the model is compared with spectrally resolved data: differential phases referenced to the continuum of each spectral vector (visphi = :continuum), and PMOIRED's spectral kernel (spectral_kernel). A spectral vector is one table row (a baseline, triangle or telescope at one time) across the wavelengths.

OITOOLS.measurement_model — Function
measurement_model(; visphi = :absolute, order = :auto, continuum = nothing,
                  spectral_kernel = 0, pmoired = false) -> MeasurementModel
  • visphi = :continuum — each spectral vector's phase residuals minus a polynomial in λ of order (:auto: PMOIRED's max(2, ⌊ptp(λ_continuum)/0.2 µm⌋)) fitted over its continuum channels: those outside the model's spectral lines (± 1.5 FWHM for a Gaussian, ± 3 widths for a Lorentzian, PMOIRED's widths), and inside continuum (λ ranges in metres) when given. :absolute (default) compares VISPHI as it is.
  • spectral_kernel = k — PMOIRED's wl kernel: before the comparison (and before visphi = :continuum), the model is smoothed along each spectral vector with a Gaussian of FWHM k channels (2⌊2k⌋ + 3 taps, normalised, edges mirrored): the complex visibility and the complex triple product as phasors, V² separately. PMOIRED's setupFit uses k = 2 for GRAVITY. Only the channels present are smoothed; at the edges of a filtered window the values are mirrored, while PMOIRED smooths across them.
  • pmoired = true — visphi = :continuum computed as PMOIRED's DPHI (computeDiffPhiOI): the continuum is every channel (Gaussian and Lorentzian lines included, truncexp lines excluded), and the data's polynomial is weighted by 1/σ² while the model's is unweighted: (d − Pw d) − (m − Pu m). The default fits one weighted polynomial to the residuals over the channels away from the lines.
source
OITOOLS.spectral_groups — Function
spectral_groups(data::OIdata) -> SpectralGroups

The dataset's spectral vectors: VIS and V² points sharing their table, their two stations and their MJD; T3 points their three stations; flux points their station (0 for a calibrated spectrum) — each vector ordered by wavelength.

source
OITOOLS.SpectralGroups — Type
SpectralGroups

The spectral vectors of a dataset, each a vector of indices into the observable's own arrays (visphi, v2, t3phi, flux), ordered by wavelength: vis, v2, t3, flux.

source

Many starts

multistart_fit is PMOIRED's gridFit: Levenberg-Marquardt from every node of a grid (grid = ["p" => (min, max, step)]) and/or from uniform or normal draws (rand, randn, nstarts), without the starts outside constrain. The fits are sorted as in PMOIRED's analyseGrid: failed fits, fits without uncertainties and fits that did not move are set aside, and the rest are grouped into distinct minima, lowest χ²ᵣ first. An explored parameter that is fixed in the model is held at each start's value (PMOIRED's doNotFit), so a grid over held parameters gives a χ² profile. The fits run on threads; start i draws from Xoshiro(seed + i), so the result does not depend on the number of threads. For a component on an orbit, minima whose MJD0 differ by whole periods are merged.

r = multistart_fit(m, ["B,f", "B,x", "B,y"], data; weights = [0, 0, 1, 1, 0, 0, 0],
                   grid = ["B,x" => (-12, 12, 1.5), "B,y" => (-12, 12, 1.5)],
                   constrain = [("sqrt(\$B,x^2 + \$B,y^2)", "<=", 12)])
r.minima[1].fit          # the global minimum, an LsqFitResult
OITOOLS.multistart_fit — Function
multistart_fit(model_dict, list_free_params, data; grid, rand, randn, nstarts, constrain,
               lb, ub, weights, constraints, rv, deltachi2, seed, threaded, maxIter, verbose)
    -> MultiStartResult

Levenberg-Marquardt fits (fit_model_lsqfit) from many starting points, and the distinct minima they reach: PMOIRED's gridFit.

The parameters explored, each in one of

  • grid — "p" => (min, max, step): every node, PMOIRED's count ⌊(max − min)/step + 1⌋ from min to max; several grids make every combination (the first varying slowest);
  • rand — "p" => (min, max): uniform; randn — "p" => (mean, σ): normal; one draw per start;

as a Dict (taken by name) or a vector of pairs (in order). With a grid the number of starts is its node count (draws added to each node); without one, nstarts. The other free parameters start from model_dict. An explored parameter that is not free (a fixed number in model_dict) is held at the start's value in that fit, so a grid over held parameters gives a χ² profile. A start outside lb/ub is moved onto the bound.

constrain drops the starts that violate its conditions, written as constraints (("sqrt($B,x^2 + $B,y^2)", "<=", 12), ModelConstraint). constraints, lb, ub, weights, rv and maxIter apply to every fit, as in fit_model_lsqfit.

The fits are sorted as in PMOIRED's analyseGrid. Fits that failed, have no uncertainties, moved their explored parameters by less than 1σ in all, or end above the best χ²ᵣ + deltachi2 (when given) are set aside. Two of the remaining fits are one minimum when the mean over the free parameters of (bᵢ − bⱼ)²/(σᵢσⱼ), divided again by their number, is below 1 (a gridded held parameter counts, with σ half its step); each minimum is represented by its lowest χ²ᵣ. For a component on an orbit, MJD0 values whole periods apart are the same.

Threads (threaded = true): one compiled model per thread; start i draws its values from Xoshiro(seed + i), so the starts and results do not depend on the thread count.

source
OITOOLS.MultiStartResult — Type
MultiStartResult

What multistart_fit returns.

  • minima — the distinct minima, lowest χ²ᵣ first (MultiStartMinimum); minima[1].fit is the global one;
  • starts — the starting point of every fit (the free parameters then the held ones × starts), list_free_params, held (explored parameters that are not free, held at their start's value in each fit) and explored (the parameters drawn or gridded);
  • fits — every fit, nothing where it failed; status — :minimum (grouped into a minimum), :failed (an error, or χ² not finite), :no_uncertainties, :did_not_move (the explored parameters moved less than 1σ in all), :chi2 (above the best χ²ᵣ + deltachi2); errors the message of each failure;
  • nrejected — starts dropped by constrain before fitting; nclamped — starts moved inside the bounds; seed, elapsed (s), nthreads.
source
OITOOLS.MultiStartMinimum — Type
MultiStartMinimum

One distinct minimum of a multistart_fit: fit, the best fit that reached it (an LsqFitResult), best the index of its start, and starts, the indices of the starts that ended there.

source

Posterior samplers

Two samplers besides nested sampling return a posterior for the free parameters, with the bounds as a uniform prior and −(χ² + constraint penalty)/2 as the log-likelihood: Ensemble Slice Sampling (the zeus algorithm, gradient-free) and non-reversible parallel tempering with Pigeons.jl, for multimodal posteriors. Both return a SamplerResult; its posterior is drawn by plot_corner_makie and the Modeling tab's corner view.

OITOOLS.fit_model_ensemble — Function
fit_model_ensemble(model_dict, list_free_params, data; lb, ub, weights, constraints,
                   nwalkers = 0, nsweep = 2000, burn = nsweep ÷ 2, thin = 0, seed,
                   verb = true) -> SamplerResult

Sample the posterior of a model's free parameters with Ensemble Slice Sampling (ensemble_slice; Karamanis & Beutler 2020), gradient-free and affine-invariant.

The log-likelihood is −(χ² + constraint penalty)/2; the prior is uniform within the bounds, which may be infinite (an improper prior).

  • nwalkers: 0 for 2d (d free parameters), at least 4, rounded up to an even number.
  • nsweep sweeps kept after burn of burn-in, every thin-th (0: about 2000 kept sweeps at most). The walkers start in a small ball about the model's values, inside the bounds.
  • seed makes the run reproducible.

diagnostics carries R̂ per parameter (rhat; above 1.01, not converged) and τ, the integrated autocorrelation time in sweeps (iat; above about nsweep/50, a lower bound), and the number of evaluations. logz is NaN.

source
OITOOLS.fit_model_pigeons — Function
fit_model_pigeons(model_dict, list_free_params, data; lb, ub, weights, constraints,
                  n_chains = 10, n_rounds = 10, explorer = :slice, variational = false,
                  n_chains_variational = 0, reference_sigma = 3.0, seed,
                  multithreaded = Threads.nthreads() > 1, verb = true) -> SamplerResult

Sample the posterior with non-reversible parallel tempering (Syed et al. 2021) through Pigeons.jl, for multimodal posteriors. Needs using Pigeons.

The free parameters are mapped to ℝ (a logistic for two finite bounds, lo + exp(z) for one, the identity for none) and the ladder anneals from N(0, reference_sigma²) on those coordinates. The log-likelihood is −(χ² + constraint penalty)/2; the bounds are the prior.

  • n_rounds is a power: the run makes 2^n_rounds scans, each round tuning the ladder for the next. n_chains ≈ 2Λ (the global communication barrier) is the sizing rule.
  • explorer: :slice (no gradient) or :mala (AutoMALA, on the closed-form χ² gradient).
  • variational = true fits a Gaussian reference during the run; n_chains_variational > 0 adds a leg with the fixed reference (the stabilised variant, Surjanovic et al. 2022). On AX Cir's binary (4 parameters, bounds ±60 mas) the fixed reference gives 0–1 round trips at 8–10 rounds, the variational or stabilised reference 76–352.

logz is the stepping-stone evidence on fit_model_nested's scale (the log volume of the bounds subtracted), NaN when a bound is infinite. logzerr is 1/√(round trips) and does not include the bias of a short run: on α Cen A's power-law fit (Nautilus: −712.528), −711.71 at 8 rounds (1 round trip), −712.29 at 10 (18), −712.536 at 12 (103). diagnostics holds the number of round trips; with fewer than 3, other modes may not have been visited.

source
OITOOLS.SamplerResult — Type
SamplerResult

What fit_model_ensemble and fit_model_pigeons return.

field
x_optthe highest-likelihood sample (as the nested samplers report)
list_free_paramsparameter names, in the order of x_opt and the posterior's columns
chi2, chi2r, ndofthe data χ² at x_opt (no constraint penalty), and per degree of freedom
posteriorequal-weight samples, (n_samples, n_params)
median, q16, q84per parameter, from posterior
logz, logzerrthe evidence on fit_model_nested's scale; NaN when the sampler gives none
diagnosticsa NamedTuple: R̂ and τ (ensemble), round trips and chains (Pigeons)
resultthe sampler's own output
modelthe compiled FlatModel
sampler:ensemble or :pigeons
source
OITOOLS.ensemble_slice — Function
ensemble_slice(logp, x0; nsweep = 5000, burn = 2000, thin = 10, mu0 = 1.0, tune = true,
               max_expand, maxshrink, patience = 5, tol = 0.05, rng, verb = true)
    -> (chain, logps, diagnostics)

Ensemble Slice Sampling of logp from walkers x0, (nwalkers, ndim), an even number of them. chain is (n_kept_sweeps, nwalkers, ndim) and logps (n_kept_sweeps, nwalkers), the walkers' log-densities.

Each half of the walkers is updated with directions drawn from the other half; the halves are reshuffled every sweep (zeus's shuffle_ensemble=True). mu is tuned during burn-in toward equal numbers of expansions and contractions, and frozen once the balance has held patience times, as in zeus.

source
OITOOLS.rhat — Function
rhat(chain) -> Vector

Gelman-Rubin R̂ per parameter from a (nsweep, nwalkers, ndim) chain, each walker a chain. Above about 1.01 the chain has not converged. The walkers of an ensemble are coupled, so this R̂ can be low while the ensemble as a whole drifts.

source
OITOOLS.iat — Function
iat(chain; per_walker = false) -> Float64

Integrated autocorrelation time in sweeps, averaged over parameters, from a (nsweep, nwalkers, ndim) chain with Sokal's t > 5τ window. By default the walkers are concatenated into one series per parameter; per_walker = true is biased low (−24 % at τ = 99 on an AR(1) series). A τ above about nsweep/50 is a lower bound.

source

Uncertainty estimation by resampling

FunctionDescription
bootstrap_fit(model_dict, list_free_params, data)Nonparametric block bootstrap: refit replicates in which blocks of data are resampled
bootstrap_driver(fitfun, x_opt, list_free_params)The replicate loop and statistics of bootstrap_fit, for another fitter or resampling unit
data_blocks(data; granularity)Partition data into resampling blocks (:config, :epoch, :point)
resample_blocks(data, blocks; mode)One bootstrap replicate (:replacement, :halfsample, :weights; :pmoired is PMOIRED's scheme, √2 too small)
block_counts(nblocks, mode)Block multiplicities drawn by a resampling scheme
block_weights(nblocks)Continuous block weights for the multiplier (Bayesian) bootstrap
apply_block_weights(data, blocks, w)Build the weighted replicate (error bars scaled by 1/√w)
apply_block_counts(data, blocks, counts)Build the replicate for given block multiplicities
perturb_data(data)Add Gaussian noise drawn from the error bars (deprecated alias resample_data)

bootstrap_fit resamples blocks of data, by default one per (MJD, telescope configuration), so its error bars include correlated calibration errors and wrong error bars, which the analytic covariance of fit_model_lsqfit does not. See Uncertainties for the calibration study.

OITOOLS.bootstrap_fit — Function
bootstrap_fit(model_dict, list_free_params, data; kwargs...) -> BootstrapResult

Parameter uncertainties by block bootstrap: the model is refitted to nboot replicates in which the blocks of data (by default one per MJD and telescope configuration) are resampled. Correlated calibration errors and wrong error bars appear as scatter between replicates. The blocks must be numerous and exchangeable; with fewer than 10 a warning is printed. See Uncertainties.

Arguments

  • model_dict::Dict{String} — flat parameter dictionary
  • list_free_params::Vector{String} — names of the free parameters
  • data::OIdata — interferometric data

Keywords

  • nboot — number of replicates (default 200; use ≥1000 for stable percentiles)
  • mode — :replacement (default), :halfsample or :weights; see block_counts and block_weights. :pmoired is PMOIRED's scheme, with uncertainties about √2 too small
  • granularity — :config (default), :epoch or :point; see data_blocks
  • fitter — :lsqfit (default, Levenberg-Marquardt with analytic Jacobian) or :nlopt
  • rv — radial velocities (read_rv) fitted with the interferometry (:lsqfit); each replicate resamples them with replacement, as it resamples the blocks
  • lb, ub, weights, nB_workspace — passed through to the fitter
  • method, maxeval — NLopt settings (fitter=:nlopt)
  • maxIter — LsqFit iterations (fitter=:lsqfit)
  • start_scatter — perturb each replicate's starting point by this many σ of the full-data fit (default 0; PMOIRED uses the equivalent of 1). Non-zero values add optimiser scatter to the uncertainty.
  • sigma_clipping — reject replicates beyond this many σ from the median (default nothing; PMOIRED's plots default to 4.5)
  • chi2r_max — reject replicates whose reduced χ² exceeds this value
  • seed — replicate i uses Xoshiro(seed + i), independent of thread scheduling
  • threaded — run replicates on all available Julia threads (default true)
  • verb — progress reporting (default true)

Example

data  = readoifits("data/AlphaCenA.oifits")[1,1]
model = Dict{String,Any}("star,ldlin" => 8.0, "star,u" => 0.3, "star,f" => 1.0)
boot  = bootstrap_fit(model, ["star,ldlin", "star,u"], data;
                      lb=Dict("star,ldlin"=>5.0, "star,u"=>0.0),
                      ub=Dict("star,ldlin"=>12.0, "star,u"=>1.0),
                      weights=[1.0, 0.0, 0.0], nboot=500)
source
OITOOLS.bootstrap_driver — Function
bootstrap_driver(fitfun, x_opt, list_free_params; kwargs...) -> BootstrapResult

Run nboot bootstrap replicates of any fit and summarise the parameters' scatter: the replicate loop, seeding, threading, failure handling, clipping and statistics of bootstrap_fit, without the model or the resampling.

Arguments

  • fitfun(state, rng) -> (x, chi2r) — one replicate: resample the data, fit, and return the best-fit parameters and the reduced χ². A third element, (x, chi2r, extra), is stored in info.
  • x_opt — best fit to the unresampled data, recorded in the result.
  • list_free_params — parameter names; length sets the expected width of x.

Keywords

  • nboot — number of replicates (default 200)
  • worker_init(w::Int) -> state — per-worker state, built once per worker, serially, before the tasks start. state is nothing without worker_init.
  • nworkers — number of replicate-level workers; 0 (default) means min(nthreads(), nboot). Set it to 1 when fitfun threads internally, so the two levels do not oversubscribe.
  • info — optional AbstractVector of length nboot; info[i] receives replicate i's third element.
  • sigma_clipping, chi2r_max — reject replicates beyond this many σ from the median, or above this reduced χ²
  • seed — replicate i uses Xoshiro(seed + i), so results do not depend on thread scheduling
  • threaded — use several workers (default true; ignored if nworkers is set)
  • verb — progress reporting
  • mode, granularity, nblocks — metadata only, copied into the result

Example

# a fit with no data at all: recover the scatter of a known Gaussian
x_true = [1.0, 2.0]
r = bootstrap_driver((state, rng) -> (x_true .+ 0.1 .* randn(rng, 2), 1.0),
                     x_true, ["a", "b"]; nboot = 500, seed = 1, verb = false)
r.sigma   # ≈ [0.1, 0.1]
source
OITOOLS.data_blocks — Function
data_blocks(data::OIdata; granularity=:config, mjd_digits=5) -> DataBlocks

Partition data into resampling blocks.

Granularity

  • :config (default) — one block per (MJD, telescope configuration): the baseline for V² and VIS, the triangle for T3, the telescope for FLUX. A block holds all wavelength channels and all observables of that configuration at that MJD (PMOIRED's spectral vector).
  • :epoch — one block per MJD, all baselines and observables.
  • :point — one block per data point (i.i.d. bootstrap). It ignores correlations between channels and observables, so it underestimates uncertainties on real data.

mjd_digits sets the rounding used to group MJDs into a common epoch (default 5 decimals ≈ 0.86 s, matching PMOIRED).

readoifits stores the MJDs (v2_mjd, t3_mjd, vis_mjd, flux_mjd, uv_mjd) as Float64 for any T, so the blocks are the same with T = Float32 and T = Float64.

source
OITOOLS.resample_blocks — Function
resample_blocks(data, blocks; mode=:replacement, rng=Random.default_rng()) -> OIdata
resample_blocks(data; granularity=:config, mode=:replacement, ...) -> OIdata

Bootstrap replicate of data: the blocks are drawn according to mode (block_counts); a block drawn twice appears twice, a block not drawn is absent. Values and error bars are unchanged. The uv table is unchanged; duplicated points share their uv row.

source
OITOOLS.block_counts — Function
block_counts(nblocks, mode; rng) -> Vector{Int}

Multiplicity of each block under the resampling mode.

Modes

  • :replacement (default) — nblocks blocks drawn with replacement; multiplicities have mean 1 and variance 1.
  • :halfsample — a random half of the blocks, each once (balanced repeated replication). Each replicate fits half the data. In demos/bootstrap_validation: ratio 0.94–1.06 with 180 blocks, 1.24–1.56 with 18.
  • :pmoired — PMOIRED's scheme: two copies of the dataset, a random half of the blocks dropped in each, the union fitted. Multiplicities are 0/1/2 with probabilities 1/4, 1/2, 1/4 (variance 1/2).
`:pmoired` gives uncertainties √2 too small

In demos/bootstrap_validation it gives 0.62–0.79 of the true scatter, with 1σ coverage near 0.50. It is for comparison with PMOIRED results.

resample_blocks also accepts mode = :weights, the multiplier (Bayesian) bootstrap with continuous weights (block_weights).

source
OITOOLS.apply_block_counts — Function
apply_block_counts(data, blocks, counts) -> OIdata

Build the OIdata in which each block of blocks appears counts[i] times.

source
OITOOLS.block_weights — Function
block_weights(nblocks; rng) -> Vector{Float64}

Weights for the multiplier (Bayesian) bootstrap: a Dirichlet(1, …, 1) draw rescaled to mean 1 (variance 1 − 1/nblocks, as the multiplicities of a draw with replacement). See apply_block_weights.

source
OITOOLS.apply_block_weights — Function
apply_block_weights(data, blocks, w) -> OIdata

Multiplier bootstrap replicate: block i gets the weight w[i] in the χ², its error bars divided by sqrt(w[i]). The reduced χ² of the replicate is not meaningful.

source
OITOOLS.perturb_data — Function
perturb_data(data::OIdata; rng=Random.default_rng()) -> OIdata

A copy of data with independent Gaussian noise added to every observable, scaled by each point's error bar. uv coordinates, flags and the number of points are unchanged.

Refitting such replicates (parametric Monte Carlo) reproduces the analytic covariance of the fit; with correlated calibration errors it gave 11–25× too small an uncertainty in demos/bootstrap_validation. bootstrap_fit estimates uncertainties.

source
OITOOLS.BootstrapResult — Type
BootstrapResult

Outcome of bootstrap_fit.

Fields

  • samples — nboot × npar matrix of per-replicate best-fit parameters
  • list_free_params — parameter names, matching the columns of samples
  • x_opt — best fit to the full dataset
  • median, sigma, sigma_minus, sigma_plus — median and 16/84 percentile half-widths of the (masked) bootstrap distribution
  • covar, correlation — parameter covariance and correlation matrices
  • chi2r — reduced χ² of each replicate
  • mask — replicates kept after sigma/χ² clipping
  • nblocks, mode, granularity — resampling setup
  • nfailed — replicates whose fit threw an error
source
OITOOLS.DataBlocks — Type
DataBlocks

Partition of an OIdata into resampling units. Each block holds the row indices it owns in each observable table (OI_VIS, OI_VIS2, OI_T3, OI_FLUX). Built by data_blocks.

source