API Reference
This page documents the public API of DiffEqParamEstim.jl.
Objective Builders
DiffEqParamEstim.build_loss_objective — Function
build_loss_objective(prob::SciMLBase.AbstractSciMLProblem, alg, loss,
adtype = SciMLBase.NoAD(), regularization = nothing, args...;
priors = nothing, prob_generator = STANDARD_PROB_GENERATOR,
kwargs...) -> SciMLBase.OptimizationFunctionBuild an OptimizationFunction that solves prob for a candidate parameter vector and reduces the resulting solution to a scalar via loss.
The returned function has the signature cost(p, _ = nothing). For each p it regenerates a problem with prob_generator(prob, p), solves it with alg, and returns loss(sol). When loss is an L2Loss or LogLikeLoss, the solve saves only at the loss timepoints (saveat = loss.t, save_everystep = false, dense = false); otherwise the solve uses the passed keyword arguments as-is.
Arguments
prob: theAbstractSciMLProblem(ODE, SDE, DAE, DDE, or another supported problem) to solve.alg: the solver algorithm matchingprob.loss: a callable mapping a solution to a scalar cost, such asL2Loss,LogLikeLoss, or a user-definedloss(sol).adtype: the automatic differentiation choice passed toOptimizationFunction. Defaults toSciMLBase.NoAD().regularization: an optional callable ofpadded to the loss, such asRegularization. The defaultnothingadds no regularization.args...: extra positional arguments forwarded tosolve.
Keywords
priors: an array of univariate distributions, one per parameter, or a multivariate distribution. The negative log prior fromprior_lossis added to the loss when supplied.prob_generator: a function(prob, p) -> newprobused to build the problem for each parameter vector. The default remakesprobwith the element type ofpand the new parameter vector.kwargs...: extra keyword arguments forwarded to the differential equationsolvecall.
Returns
An OptimizationFunction wrapping the cost function with adtype, ready to be used to construct an OptimizationProblem.
Examples
prob = ODEProblem((u, p, t) -> p[1] * u, [1.0], (0.0, 1.0), [0.5])
loss = L2Loss([0.0, 1.0], [1.0 1.5])
objective = build_loss_objective(prob, Tsit5(), loss)DiffEqParamEstim.multiple_shooting_objective — Function
multiple_shooting_objective(prob::SciMLBase.AbstractDEProblem, alg, loss,
adtype = SciMLBase.NoAD(), regularization = nothing;
priors = nothing, discontinuity_weight = 1.0,
prob_generator = STANDARD_MS_PROB_GENERATOR,
kwargs...) -> SciMLBase.OptimizationFunctionBuild an OptimizationFunction that fits parameters by multiple shooting.
Multiple shooting splits prob.tspan into K shorter intervals and treats both the differential equation parameters and the initial state of each interval as optimization variables. The returned cost function solves each interval with alg, merges the segment solutions into a single trajectory, evaluates loss on it, and adds a discontinuity penalty for the mismatch between the end of each segment and the start of the next. This is often more robust than a single-shot objective, as in boundary value problems.
The parameter vector p is laid out as the concatenation of the per-interval initial states followed by the length(prob.p) differential equation parameters; the default prob_generator = STANDARD_MS_PROB_GENERATOR slices p into the correct per-segment problems.
Arguments
prob: theAbstractDEProblemto fit.alg: the solver algorithm matchingprob.loss: a callable mapping the merged solution to a scalar, such asL2LossorLogLikeLoss.adtype: the automatic differentiation choice passed toOptimizationFunction. Defaults toSciMLBase.NoAD().regularization: an optional callable ofp, such asRegularization. The defaultnothingadds no regularization.
Keywords
priors: univariate distributions (one per parameter) or a multivariate distribution. The negative log prior fromprior_lossis applied to the differential-equation parameters when supplied.discontinuity_weight: a scalar or array weight on the squared mismatch between consecutive segments. Defaults to1.0.prob_generator: a function(prob, p, k) -> segment_probproducing the problem for intervalkfromp. The default splits the initial states and parameters according to the layout described above.kwargs...: extra keyword arguments forwarded tosolve.
Returns
An OptimizationFunction wrapping the multiple-shooting cost with adtype.
Examples
objective = multiple_shooting_objective(prob, Tsit5(), L2Loss(tpoints, data))
value = objective(initial_state_and_parameter_vector)DiffEqParamEstim.two_stage_objective — Function
two_stage_objective(prob::SciMLBase.AbstractDEProblem, tpoints, data,
adtype = SciMLBase.NoAD(); kernel = EpanechnikovKernel()) ->
SciMLBase.OptimizationFunctionBuild an OptimizationFunction for the two-stage (non-parametric collocation) parameter estimation method.
The two-stage method avoids repeatedly solving the differential equation: it first builds a kernel-smoothed estimate of the state trajectory and its derivative from data, then measures, for a candidate p, the squared mismatch between the model right-hand side prob.f evaluated at the smoothed state and the smoothed derivative. It is less accurate than solve-based objectives but much faster, and is a good way to get into the neighborhood of good parameters before refining with another method.
Arguments
prob: theAbstractDEProblemwhose right-hand side is being fit. Both in-place and out-of-place right-hand sides are supported.tpoints: the timepoints at whichdatais sampled.data: the measured state values used for collocation smoothing.adtype: the automatic differentiation choice passed toOptimizationFunction. Defaults toSciMLBase.NoAD().
Keywords
kernel: the collocation smoothing kernel, either aCollocationKernelinstance or aSymbolselecting one of:Epanechnikov,:Uniform,:Triangular,:Quartic,:Triweight,:Tricube,:Gaussian,:Cosine,:Logistic,:Sigmoid, and:Silverman. Defaults toEpanechnikovKernel().
Returns
An OptimizationFunction wrapping a TwoStageCost with adtype. The returned cost also exposes the smoothed estimated_solution and estimated_derivative.
Examples
objective = two_stage_objective(prob, tpoints, data; kernel = :Triangular)
cost = objective([1.0])Cost Functions
DiffEqParamEstim.L2Loss — Type
L2Loss(t, data; differ_weight = nothing, data_weight = nothing,
colloc_grad = nothing, dudt = nothing) -> L2LossAn optimized L2-distance loss for fitting a differential equation solution to data. Calling the loss with a solution sol returns the weighted sum of squared residuals between sol and data at t. It returns Inf when the solution has an unsuccessful return code.
Arguments
t: the timepoints at which the data are given.data: the measured values. Columniholds the state att[i]; a vector is reshaped to a1 x Nmatrix.
Keywords
data_weight: a scalar or an array matchingdatathat weights each squared residual. The defaultnothinggives unit weights.differ_weight: a scalar or an array weighting the first-difference residuals between consecutive solution and data values. The defaultnothingdisables this term.colloc_grad: a matrix of collocation gradients fordata, usually created bycolloc_grad. When supplied, a derivative-residual term is added.dudt: a derivative buffer used withcolloc_grad. The defaultnothingallocates a buffer automatically.
Fields
t::T: the loss timepoints.data::D: the observed values, stored as a matrix.differ_weight::U: the first-difference weight ornothing.data_weight::W: the data weight ornothing.colloc_grad::G: the collocation derivative matrix ornothing.dudt::G: the derivative buffer used during evaluation.du_buf::B: an internal buffer used for derivative evaluation.
Examples
t = range(0, 1; length = 11)
data = reshape(sin.(t), 1, :)
loss = L2Loss(t, data; data_weight = 2.0)DiffEqParamEstim.LogLikeLoss — Type
LogLikeLoss(t, data_distributions)
LogLikeLoss(t, data_distributions, diff_distributions)
LogLikeLoss(t, data_distributions, diff_distributions, weight)A negative log-likelihood loss for fitting a differential equation solution to a field of distributions. Calling a LogLikeLoss on a solution sol returns the negative total log-likelihood of sol under data_distributions at the timepoints t (so minimizing it performs maximum likelihood estimation), returning Inf if the solve was unsuccessful.
There are two forms for data_distributions:
- If
data_distributions[i, j]is aUnivariateDistribution, it gives the likelihood att[i]for componentj. - If
data_distributions[i]is aMultivariateDistribution, it gives the likelihood att[i]over the full state vector.
These distributions can be produced with fit_mle on a dataset against a chosen distribution type.
Arguments
t: the timepoints at which the distributions apply.data_distributions: the likelihood distributions. A vector is reshaped to a1 x Nmatrix.diff_distributions: an optional field of distributions for the first-difference termssol[i] - sol[i - 1]. The three-argument constructor usesweight = 1for this term.weight: the scalar multiplier for the first-difference likelihood term. Usenothingwhendiff_distributionsis not supplied.
Fields
t::T: the loss timepoints.data_distributions::D: the distributions for the observed state values.diff_distributions: the optional first-difference distributions.weight: the first-difference likelihood weight.
Examples
using Distributions
t = 0:2
data_distributions = [Normal(0, 1) for _ in t]
loss = LogLikeLoss(t, data_distributions)DiffEqParamEstim.Regularization — Type
Regularization(λ, penalty = L2Penalty()) -> RegularizationA callable regularization term for use with an objective builder such as build_loss_objective. Calling it with a parameter vector p returns λ * value(penalty, p). The default penalty is L2Penalty().
penalty can be any penalty function supported by PenaltyFunctions.jl.
Fields
λ::L: the scalar weight applied to the penalty term.penalty::P: the penalty function evaluated on the parameter vector.
Examples
regularization = Regularization(0.1)
penalty = regularization([1.0, 2.0])DiffEqParamEstim.TwoStageCost — Type
TwoStageCost(cost_function, estimated_solution, estimated_derivative) -> TwoStageCostThe callable cost object produced by two_stage_objective.
Calling a TwoStageCost on a parameter vector p forwards to cost_function(p, _p), which measures how well the differential equation's right-hand side evaluated at the collocation-smoothed solution matches the collocation-smoothed derivative. The smoothed trajectory and its derivative are stored so they can be inspected after construction.
Fields
cost_function::F: the underlying cost closure with signature(p, _p = nothing).estimated_solution::D: the kernel-smoothed state trajectory at the collocation points.estimated_derivative::D: the kernel-smoothed state derivative at the collocation points.
Examples
cost = TwoStageCost((p, _) -> sum(abs2, p), [1.0], [0.0])
value = cost([1.0])Helper Functions
DiffEqParamEstim.prior_loss — Function
prior_loss(prior, p) -> RealReturn the negative log prior of the parameter vector p under prior.
If eltype(prior) <: UnivariateDistribution, prior is treated as a collection of univariate distributions and the result is -sum(logpdf(prior[i], p[i])). Otherwise prior is treated as a single multivariate distribution and the result is -logpdf(prior, p). Adding this term to a loss turns maximum likelihood estimation into a maximum a posteriori (MAP) objective. It is used by build_loss_objective and multiple_shooting_objective when priors is supplied.
Arguments
prior: a collection of univariate distributions or one multivariate distribution.p: the parameter vector at which to evaluate the prior.
Examples
using Distributions
priors = [Normal(1.0, 0.2), Normal(2.0, 0.5)]
map_penalty = prior_loss(priors, [1.1, 1.8])DiffEqParamEstim.colloc_grad — Function
colloc_grad(t, data) -> AbstractMatrixEstimate the time-derivative of data by spline collocation, for use as the colloc_grad argument of L2Loss.
For each state (row of data), a cubic (third-order) Dierckx.Spline1D is fit to data against t and differentiated at the timepoints in t. The derivatives are returned in a matrix with the same shape as data, where column i is the estimate at t[i].
Arguments
t: a length-Nvector of strictly ordered timepoints.data: anm x Nmatrix of measured state values.
Returns
An m x N matrix of collocation-estimated derivatives.
Examples
t = range(0, 1; length = 11)
data = reshape(sin.(t), 1, :)
grad = colloc_grad(t, data)DiffEqParamEstim.l2lossgradient! — Function
l2lossgradient!(grad, sol, data, sensitivities, num_p) -> nothingCompute, in place, the gradient of an L2 loss with respect to num_p parameters and write it into grad.
Given a solution sol, the target data, and the parameter sensitivities (where sensitivities[i] is the derivative of the solution with respect to parameter i), this accumulates grad[i] -= sum(2 * (data - sol) .* sensitivities[i]) over all state components and timepoints. grad is zeroed before accumulation. Returns nothing.
Arguments
grad: a length-num_pvector, overwritten with the loss gradient.sol: the solution values, shaped likedata.data: the target data.sensitivities: a collection of lengthnum_pof parameter sensitivities, each shaped likedata.num_p: the number of parameters.
Examples
grad = zeros(1)
sensitivities = [ones(1, 2)]
l2lossgradient!(grad, zeros(1, 2), ones(1, 2), sensitivities, 1)