Model Fitting
Fitters
| Function | Description |
|---|---|
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.
| Type | Description |
|---|---|
FitResult | Result from fit_model (fields: x_opt, chi2r, model, ...) |
LsqFitResult | Result from fit_model_lsqfit (adds stderror, covar, converged) |
NestedResult | Result from fit_model_nested (adds logz, logzerr, posterior, result, backend) |
UltraNestResult | Alias for NestedResult |
BootstrapResult | Result 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 |
DataBlocks | Partition of an OIdata into resampling blocks |
ModelConstraint | One relation between model parameters, enforced during fitting |
OITOOLS.fit_model — Function
fit_model(model_dict, list_free_params, data; kwargs...) -> FitResultFit 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 optimizedata::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 penaltiesconstraints— relations between parameters that bounds cannot express, asModelConstraints or(lhs, op, rhs[, tol])tuples, passed to NLopt as nonlinear constraints; amethodthat does not support them is wrapped in:AUGLAG. The reportedchi2is 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, andndofcounts themmethod— NLopt algorithm (default:LD_LBFGS; use:LN_NELDERMEADfor gradient-free)maxeval— maximum function evaluations (default 2000)ftol_rel,xtol_rel— convergence tolerancesnB_workspace— Hankel workspace size (default: nuv from data)verb— print per-evaluation chi2 breakdown
fit_model(model::FlatModel, x0, data; kwargs...) -> FitResultFit 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).
OITOOLS.fit_model_lsqfit — Function
fit_model_lsqfit(model_dict, list_free_params, data; kwargs...) -> LsqFitResultFit 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 dictionarylist_free_params::Vector{String}— names of the free parameters to optimizedata::OIdata— interferometric data
Keywords
lb,ub—Dict{String,Float64}of lower/upper bounds per parameterweights— observable weights [V2, T3amp, T3phi, visamp, visphi, flux, diffphase]nB_workspace— Hankel workspace sizemaxIter— maximum iterations (default 200)constraints— relations between parameters that bounds cannot express, asModelConstraints or(lhs, op, rhs[, tol])tuples, added as extra rows of the residual vector and the Jacobian, socovarandstderrorinclude them. The reportedchi2excludes themmeasurement— the measurement model (measurement_model); withvisphi = :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, orMandq). They enter the residual vector after the data;chi2andndofcount them,chi2_rvis their partverb— print per-evaluation chi2 breakdown
fit_model_lsqfit(model::FlatModel, x0, data; kwargs...) -> LsqFitResultLevenberg-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.
OITOOLS.fit_model_nested — Function
fit_model_nested(model_dict, list_free_params, data; kwargs...) -> NestedResult
fit_model_nested(model::FlatModel, data; kwargs...) -> NestedResultFit 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
| keyword | default | meaning |
|---|---|---|
lb, ub | Dict{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_workspace | from the data | Hankel workspace size |
verb | true | print progress |
cornerplot | true | draw the corner plot when a plotting backend is loaded |
seed | nothing | reproducible run (UltraNest: seeds numpy's generator, restored afterwards, and uses fixed batches of 512 proposals) |
Keywords, :nautilus
| keyword | default | meaning |
|---|---|---|
n_live | 500 | live points in the exploration phase |
n_eff | 2000 | effective sample size to reach before stopping |
f_live | 0.01 | fraction of evidence left in the live set at which exploration ends |
n_networks | 4 | networks in the bounding ensemble |
threaded | nthreads() > 1 | evaluate the likelihood across threads |
Keywords, :ultranest
| keyword | default | meaning |
|---|---|---|
min_num_live_points | 400 | minimum live points |
cluster_num_live_points | 100 | live points per cluster |
num_bootstraps | 30 | bootstraps for the evidence error |
use_stepsampler | false | use RegionSliceSampler |
nsteps | 400 | steps per slice, with use_stepsampler |
frac_remain | 0.001 | termination fraction |
log_interval | 100 | logging 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.
OITOOLS.fit_model_ultranest — Function
fit_model_ultranest(args...; kwargs...) -> NestedResultfit_model_nested pinned to the UltraNest backend. Needs using PythonCall and the Python ultranest package (declared in CondaPkg.toml).
OITOOLS.nested_backend — Function
nested_backend() -> SymbolWhich nested sampler fit_model_nested will use: :nautilus, :ultranest, or :none when no extension is loaded.
OITOOLS.set_nested_backend! — Function
set_nested_backend!(b::Symbol) -> SymbolChoose the nested sampler: :nautilus or :ultranest.
The backend's package must be loaded; otherwise this raises an error.
OITOOLS.chi2_map — Function
chi2_map(model_dict, list_free_params, data, p1, p2; kwargs...) -> Chi2MapEvaluate χ² 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| keyword | default | meaning |
|---|---|---|
n1, n2 | 60 | grid points along each axis |
range1, range2 | from lb/ub | (lo, hi) for each axis, overriding the bounds |
lb, ub | Dict() | 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_workspace | 100 | passed through to parse_model |
on_grid | nothing | called 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.
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.
OITOOLS.FitResult — Type
FitResultWhat every point-estimate fitter returns: fit_model, fit_model_lsqfit and the grid search.
| field | meaning |
|---|---|
x_opt | best-fit values, in list_free_params order |
list_free_params | the names, so x_opt[i] is always identifiable |
chi2, chi2r, ndof | raw weighted χ², χ²/ndof, and the number of DATA POINTS |
n_evals | χ² evaluations spent |
ret | the optimiser's return code |
model | the 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.
OITOOLS.NestedResult — Type
NestedResultResult of fit_model_nested, whichever sampler produced it.
| field | type | meaning |
|---|---|---|
x_opt | Vector{Float64} | maximum-likelihood parameter values |
list_free_params | Vector{String} | parameter names, same order as x_opt |
chi2, chi2r, ndof | Float64, Float64, Int | chi² at x_opt, reduced chi², degrees of freedom |
logz, logzerr | Float64 | Bayesian log-evidence and its uncertainty |
posterior | Matrix{Float64} | (n_samples, n_params) equally weighted posterior samples |
result | Any | the sampler's own result object, passed through unconverted |
model | FlatModel | the compiled model that was fitted |
backend | Symbol | the 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.
OITOOLS.UltraNestResult — Type
UltraNestResultAlias for NestedResult, so code written against the UltraNest-only API keeps working.
OITOOLS.Chi2Map — Type
Chi2MapA χ² surface over two free parameters.
| field | meaning |
|---|---|
p1, p2 | the two parameter names, as they appear in list_free_params |
v1, v2 | the grid values along each axis |
chi2 | (length(v1), length(v2)) matrix of raw weighted χ² |
ndof | number of data points with non-zero weight; chi2 ./ ndof is the reduced map |
x_opt | the full free-parameter vector at the grid minimum |
list_free_params | names for x_opt, in fit-vector order |
model | the 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.
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.
| Function | Description |
|---|---|
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.5m = 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 coverageOther 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.
OITOOLS.DEFAULT_MAX_SIZE_MAS — Constant
Upper bound on an angular size, in mas, used by default_bounds without data: 100.
OITOOLS.max_angular_scale — Function
max_angular_scale(data) -> Float64Largest angular scale of the uv coverage, in mas: 1/Bmin with Bmin the shortest baseline in wavelengths.
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.
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).
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.
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.
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.
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, ...).
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) -> MeasurementModelvisphi = :continuum— each spectral vector's phase residuals minus a polynomial in λ oforder(: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 insidecontinuum(λ ranges in metres) when given.:absolute(default) compares VISPHI as it is.spectral_kernel = k— PMOIRED'swl kernel: before the comparison (and beforevisphi = :continuum), the model is smoothed along each spectral vector with a Gaussian of FWHMkchannels (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 = :continuumcomputed as PMOIRED's DPHI (computeDiffPhiOI): the continuum is every channel (Gaussian and Lorentzian lines included,truncexplines 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.
OITOOLS.MeasurementModel — Type
MeasurementModelHow a fit references the model to the data (see measurement_model).
OITOOLS.spectral_groups — Function
spectral_groups(data::OIdata) -> SpectralGroupsThe 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.
OITOOLS.SpectralGroups — Type
SpectralGroupsThe 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.
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 LsqFitResultOITOOLS.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)
-> MultiStartResultLevenberg-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.
OITOOLS.MultiStartResult — Type
MultiStartResultWhat multistart_fit returns.
minima— the distinct minima, lowest χ²ᵣ first (MultiStartMinimum);minima[1].fitis 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) andexplored(the parameters drawn or gridded);fits— every fit,nothingwhere 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);errorsthe message of each failure;nrejected— starts dropped byconstrainbefore fitting;nclamped— starts moved inside the bounds;seed,elapsed(s),nthreads.
OITOOLS.MultiStartMinimum — Type
MultiStartMinimumOne 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.
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) -> SamplerResultSample 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:0for 2d (d free parameters), at least 4, rounded up to an even number.nsweepsweeps kept afterburnof burn-in, everythin-th (0: about 2000 kept sweeps at most). The walkers start in a small ball about the model's values, inside the bounds.seedmakes 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.
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) -> SamplerResultSample 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_roundsis a power: the run makes 2^n_roundsscans, 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 = truefits a Gaussian reference during the run;n_chains_variational > 0adds 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.
OITOOLS.SamplerResult — Type
SamplerResultWhat fit_model_ensemble and fit_model_pigeons return.
| field | |
|---|---|
x_opt | the highest-likelihood sample (as the nested samplers report) |
list_free_params | parameter names, in the order of x_opt and the posterior's columns |
chi2, chi2r, ndof | the data χ² at x_opt (no constraint penalty), and per degree of freedom |
posterior | equal-weight samples, (n_samples, n_params) |
median, q16, q84 | per parameter, from posterior |
logz, logzerr | the evidence on fit_model_nested's scale; NaN when the sampler gives none |
diagnostics | a NamedTuple: R̂ and τ (ensemble), round trips and chains (Pigeons) |
result | the sampler's own output |
model | the compiled FlatModel |
sampler | :ensemble or :pigeons |
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.
OITOOLS.rhat — Function
rhat(chain) -> VectorGelman-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.
OITOOLS.iat — Function
iat(chain; per_walker = false) -> Float64Integrated 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.
Uncertainty estimation by resampling
| Function | Description |
|---|---|
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...) -> BootstrapResultParameter 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 dictionarylist_free_params::Vector{String}— names of the free parametersdata::OIdata— interferometric data
Keywords
nboot— number of replicates (default 200; use ≥1000 for stable percentiles)mode—:replacement(default),:halfsampleor:weights; seeblock_countsandblock_weights.:pmoiredis PMOIRED's scheme, with uncertainties about √2 too smallgranularity—:config(default),:epochor:point; seedata_blocksfitter—:lsqfit(default, Levenberg-Marquardt with analytic Jacobian) or:nloptrv— radial velocities (read_rv) fitted with the interferometry (:lsqfit); each replicate resamples them with replacement, as it resamples the blockslb,ub,weights,nB_workspace— passed through to the fittermethod,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 (defaultnothing; PMOIRED's plots default to 4.5)chi2r_max— reject replicates whose reduced χ² exceeds this valueseed— replicateiusesXoshiro(seed + i), independent of thread schedulingthreaded— run replicates on all available Julia threads (defaulttrue)verb— progress reporting (defaulttrue)
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)OITOOLS.bootstrap_driver — Function
bootstrap_driver(fitfun, x_opt, list_free_params; kwargs...) -> BootstrapResultRun 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 ininfo.x_opt— best fit to the unresampled data, recorded in the result.list_free_params— parameter names;lengthsets the expected width ofx.
Keywords
nboot— number of replicates (default 200)worker_init(w::Int) -> state— per-worker state, built once per worker, serially, before the tasks start.stateisnothingwithoutworker_init.nworkers— number of replicate-level workers;0(default) meansmin(nthreads(), nboot). Set it to 1 whenfitfunthreads internally, so the two levels do not oversubscribe.info— optionalAbstractVectorof lengthnboot;info[i]receives replicatei's third element.sigma_clipping,chi2r_max— reject replicates beyond this many σ from the median, or above this reduced χ²seed— replicateiusesXoshiro(seed + i), so results do not depend on thread schedulingthreaded— use several workers (defaulttrue; ignored ifnworkersis set)verb— progress reportingmode,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]OITOOLS.data_blocks — Function
data_blocks(data::OIdata; granularity=:config, mjd_digits=5) -> DataBlocksPartition 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.
OITOOLS.resample_blocks — Function
resample_blocks(data, blocks; mode=:replacement, rng=Random.default_rng()) -> OIdata
resample_blocks(data; granularity=:config, mode=:replacement, ...) -> OIdataBootstrap 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.
OITOOLS.block_counts — Function
block_counts(nblocks, mode; rng) -> Vector{Int}Multiplicity of each block under the resampling mode.
Modes
:replacement(default) —nblocksblocks 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. Indemos/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).
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).
OITOOLS.apply_block_counts — Function
apply_block_counts(data, blocks, counts) -> OIdataBuild the OIdata in which each block of blocks appears counts[i] times.
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.
OITOOLS.apply_block_weights — Function
apply_block_weights(data, blocks, w) -> OIdataMultiplier 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.
OITOOLS.perturb_data — Function
perturb_data(data::OIdata; rng=Random.default_rng()) -> OIdataA 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.
OITOOLS.resample_data — Function
resample_data(data::OIdata)Deprecated alias for perturb_data, which adds Gaussian noise. For a bootstrap, see bootstrap_fit and resample_blocks.
OITOOLS.BootstrapResult — Type
BootstrapResultOutcome of bootstrap_fit.
Fields
samples—nboot × nparmatrix of per-replicate best-fit parameterslist_free_params— parameter names, matching the columns ofsamplesx_opt— best fit to the full datasetmedian,sigma,sigma_minus,sigma_plus— median and 16/84 percentile half-widths of the (masked) bootstrap distributioncovar,correlation— parameter covariance and correlation matriceschi2r— reduced χ² of each replicatemask— replicates kept after sigma/χ² clippingnblocks,mode,granularity— resampling setupnfailed— replicates whose fit threw an error
OITOOLS.DataBlocks — Type
DataBlocksPartition 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.