Main functions and types
Most uses of the package need only what is on this page.
ODEParameterEstimation.ODEParameterEstimation — Module
ODEParameterEstimationEstimate the parameters and initial conditions of an ODE model from time-series data.
Build a ParameterEstimationProblem from a ModelingToolkit system and your data, call estimate, and read the ParameterEstimationResults it returns. The manual is at https://orebas.github.io/ODEParameterEstimation.jl/dev/.
Setting up a problem
ODEParameterEstimation.ParameterEstimationProblem — Method
ParameterEstimationProblem(system, measured_quantities; data, true_values, name, solver)Set up an estimation problem from a ModelingToolkit System and the quantities that were measured.
measured_quantities is a vector of equations such as [y1 ~ x1, y2 ~ x1 + x2]. Each left-hand side names one measured series; each right-hand side says what it measures in terms of the model's states and parameters.
Keywords
data: the measurements. ANamedTuple, a dictionary, or anything with named columns such as aDataFrame, with the time points undertand one vector per measured quantity under its name, for example(t = times, y1 = first_series, y2 = second_series). All series share the time points. For series measured at different times, pass anObservationData. Leave it out to simulate data withsample_problem_data.true_values: the parameter values and initial conditions that generated the data, as pairs such as[a => 0.4, x1 => 1.0], when they are known. They are needed only to simulate data and to report errors against the truth. Numbers the system already carries, as in@parameters a = 0.4, are used for anything not listed.name: a label for the problem. Defaults to the system's name.solver: the ODE solver used to simulate the model while estimating. Defaults toAutoVern9(Rodas5P()).sample_problem_datareplaces it with itsode_solveroption.
Example
using ModelingToolkit
using ModelingToolkit: t_nounits as t, D_nounits as D
@parameters a b
@variables x1(t) x2(t) y1(t) y2(t)
@named model = System([D(x1) ~ -a * x2, D(x2) ~ b * x1], t)
problem = ParameterEstimationProblem(model, [y1 ~ x1, y2 ~ x2];
data = (t = times, y1 = first_series, y2 = second_series))
results = estimate(problem)ODEParameterEstimation.ParameterEstimationProblem — Type
ParameterEstimationProblemA model, the quantities measured on it, and the measurements.
Build one from a ModelingToolkit System with ParameterEstimationProblem(system, measured_quantities; data). The example models in ODEParameterEstimation.Examples, such as lotka_volterra(), return ready-made problems without data.
Fields
name: a label for the problem.model: the system, as anOrderedODESystem.measured_quantities: equations such asy1 ~ x1, one per measured series.data_sample: the measurements, ornothingbefore any are attached. Either a dictionary with the time points under"t"and each series under the right-hand side of its measured quantity, or anObservationData.solver: the ODE solver used to simulate the model while estimating.p_true,ic: the true parameter values and initial conditions,NaNwhere they are not known.recommended_time_interval,unident_count: notes carried by the built-in example models. Estimation does not read them.
The struct can also be built by passing all nine fields in the order name, model, measured_quantities, data_sample, recommended_time_interval, solver, p_true, ic, unident_count.
ODEParameterEstimation.sample_problem_data — Function
sample_problem_data(problem; options...) -> ParameterEstimationProblem
sample_problem_data(problem, options::EstimationOptions)Simulate measurements for problem from its true parameter values and initial conditions, and return a copy of the problem that carries them.
problem = sample_problem_data(problem; datasize = 51, time_interval = [0.0, 10.0], noise_level = 0.01)The options that matter here are:
datasize: the number of time points.time_interval:[start, stop]; the points are evenly spaced over it. An example model fromODEParameterEstimation.Exampleshas an interval of its own, which the keyword form uses when you give none.uneven_sampling_times(experimental): if not empty, use these time points instead oftime_interval. There must bedatasizeof them, in increasing order. The initial conditions are the values at the first of them.noise_levelandnoise_model: add Gaussian noise.:additiveuses a standard deviation ofnoise_leveltimes the mean absolute value of each series;:relativescales each value by1 + noise_level * randn();:noneadds none.ode_solver,abstol,reltol: the ODE solver and tolerances for the simulation. The returned problem keepsode_solveras its solver.seed: with an integer, the noise is the same on every call and the caller's default RNG is left untouched. Withnothing(the default), noise is drawn from the caller's default RNG, soRandom.seed!controls it.
ODEParameterEstimation.ObservationData — Type
ObservationData(series; initial_time = 0.0)Measurements in which each series has its own time points. Pass one as data to ParameterEstimationProblem in place of a table.
Arguments
series: a vector ofObservationSeries.initial_time: the time at which initial conditions are reported. It cannot be later than the first measurement.
The series have to overlap in time, because the equations are solved inside the interval that all of them cover. Gaps are not filled in and repeated measurements are not averaged. Uncertainty (compute_uncertainty) is not available for data of this kind.
ODEParameterEstimation.ObservationSeries — Type
ObservationSeries(name, experiment, quantity, times, values; noise_std = nothing)One measured series with its own time points.
Arguments
name: a label for the series.experiment: a label for the experiment it belongs to.quantity: what was measured, as an expression in the model's states, such asx1orx1 + x2.times,values: the measurements. They are copied and sorted by time. A time may appear more than once.noise_std: the standard deviation of the noise in each value, if you know it. It is kept with the series. Estimation does not use it.
ODEParameterEstimation.observation_times — Function
observation_times(data, quantity)The times at which quantity was measured.
Estimating
ODEParameterEstimation.estimate — Function
estimate(problem; options...) -> Vector{ParameterEstimationResult}
estimate(problem, options::EstimationOptions)Estimate the parameters and initial conditions of problem from its data.
Returns the solutions found, best fit first. There is usually one. There are several when the data cannot tell them apart, and each then fits equally well. The vector is empty if no solution was found.
Keyword arguments are the fields of EstimationOptions, for example estimate(problem; seed = 1, progress = true).
These are the returned_results of analyze_parameter_estimation_problem, without the states the package adds for inputs such as sin(c * t). Call that function instead when you also want the error statistics against known true values or the uncertainty report, which is experimental.
Example
results = estimate(problem)
best = first(results)
best.parameters # OrderedDict of parameter => value
best.states # initial conditions
best[a] # one value, by symbol or by name (best[:a])ODEParameterEstimation.analyze_parameter_estimation_problem — Function
analyze_parameter_estimation_problem(problem, options = EstimationOptions())Estimate the parameters and initial conditions of problem and return everything the run produced, as (raw_results, analysis, uq).
estimate is the short form: it returns analysis.returned_results, without the states the package adds for inputs such as sin(c * t).
Returns
raw_results: every candidate solution the solver found, before ranking, with the identifiability findings. Mostly useful for debugging.analysis: a named tuple with these fields, in this order, so it can also be unpacked by position:returned_results: the solutions, best fit first, asParameterEstimationResults.besterror,best_min_error,best_mean_error,best_median_error,best_max_error: relative errors against the problem's true values, leaving out the quantities the data cannot determine, each the best over all candidates;besterroris the same asbest_max_error. They areInfwhen the true values are not known.best_approximation_error: the fit error of the best solution.best_rms_error: the root-mean-square relative error, as above.algebraic_multiplicity: the number of solutions the equations admit, when it was determined.
uq: withcompute_uncertainty = true, anUncertaintyReport, or anUncertaintyUnavailablethat says why there is none; otherwisenothing. Uncertainty estimation is experimental.
ODEParameterEstimation.EstimationOptions — Type
EstimationOptions(; options...)Everything that can be adjusted about an estimation. Every option has a default, and the defaults are meant to be used: estimate(problem) is the normal call.
Options are given by keyword, either directly or through this struct:
estimate(problem; seed = 1, progress = true)
options = EstimationOptions(seed = 1, progress = true)
estimate(problem, options)The options most people reach for come first. The rest adjust one stage of the method each, and are grouped by stage.
Options marked experimental are for studying the method. They may change or be removed in a minor release. The others change only in a major release.
Everyday options
interpolators: the curve fits used to estimate derivatives of the data, as a vector such as[InterpolatorAAA]. Each is run and their candidate solutions are pooled. The default runs nine: Gaussian processes, rational approximations and Chebyshev series. A shorter list is faster.InterpolatorAAA, a rational approximation, suits exact or nearly exact data;InterpolatorGP, a Gaussian process, suits noisy data;InterpolatorGPUncertaintyis needed forcompute_uncertainty; andInterpolatorCustomuses a function of your own.polish_solutions(defaulttrue): refine each solution by least squares against the data.falsereturns the algebraic estimates as they are.opt_lb,opt_ub(defaultnothing): lower and upper bounds, as vectors with the states first and then the parameters. Refinement stays inside them. They cannot yet be used with a model that has an input such assin(c * t).seed(defaultnothing): with an integer, repeated runs give identical results and Julia's default random number generator is left as it was. Withnothing, random draws come from the default generator, so results vary a little from run to run unless you callRandom.seed!first.progress(defaultfalse): print one timestamped line as each stage starts and finishes.shooting_points(default12): how many time points the equations are solved at. Fewer is faster.abstol,reltol(default1e-14): tolerances for solving the model's ODEs, both when simulating data and during refinement and the other steps that integrate the model.
Simulated data
These are read by sample_problem_data, which also uses abstol, reltol and seed.
datasize(default21): the number of time points.time_interval(default[-0.5, 0.5]): the first and last time.noise_level(default0.0): the size of the Gaussian noise added.noise_model(default:additive): with:additive, the noise has standard deviationnoise_leveltimes the mean absolute value of the series. With:relative, each value is multiplied by1 + noise_level * randn().:noneadds no noise.uneven_sampling_times(default empty, experimental): if not empty, sample at these times, of which there must bedatasize, instead of evenly overtime_interval. The initial conditions are the values at the first of them.ode_solver(defaultAutoVern9(Rodas5P())): the ODE solver for the simulation. The problemsample_problem_datareturns keeps it as its solver for the estimation.
Output
nooutput(defaulttrue): print nothing and pass only errors to the logger.falseprints the stages and a summary of the results.diagnostics(defaultfalse): print detailed diagnostics and write the candidate-synthesis log underartifacts/diagnostics/.save_system(defaultfalse),save_filepath(default""): save the polynomial systems to files, undersave_filepathor elsesaved_systems/.profile_phases(defaultfalse, experimental): print the time and memory each stage took.hc_show_progress(defaultfalse): show HomotopyContinuation's progress bar.
Estimating derivatives
custom_interpolators(defaultFunction[]): your own functions(times, values) -> curve, one for eachInterpolatorCustomentry ininterpolators, in order.auto_filter_interpolators(defaulttrue): leave out the rational interpolators when the data look noisy, because they amplify noise.s3_adapt_k(default10.0, experimental): noise multiplier for the tolerance of the two default curve fits that pass a Gaussian process through a rational approximation. Higher keeps fewer support points.gp_derivative_lengthscale_factor(default1.0, experimental): multiplies the fitted length scale ofInterpolatorGPUncertainty. Values below one smooth less.
Building and solving the equations
flow(defaultFlowStandard):FlowStandardis the algebraic method.FlowDirectOptfits by local optimization alone.system_solver(defaultSolverHC): how the polynomial systems are solved.SolverHCis homotopy continuation, which finds every solution. The others are local solvers and can miss solutions:SolverTrustRegionis a trust-region method started from several points, andSolverLevenbergMarquardtis Levenberg–Marquardt from one point.use_si_template(defaulttrue, experimental): has no effect. The equations are always built with StructuralIdentifiability.jl, andfalseis refused.si_probability(default0.99): the probability with which the identifiability analysis is correct.si_fix_strategy(default:local_basis): how values are chosen for quantities that cannot be determined::local_basisor:identifiable_functions.system_construction_policy(default:noise_frontier, experimental): which equations are used.:noise_frontierprefers systems that need lower derivatives of the data and have fewer solutions.:legacyis the earlier choice.construction_candidate_limit(default64),construction_beam_width(default16),construction_compute_mixed_volume(defaulttrue), experimental: limits on the search that:noise_frontierdoes.shooting_warp(defaulttrue),shooting_warp_beta(default3.0), experimental: place more of theshooting_pointsnear the start of the data, and how strongly.use_multipoint(defaulttrue): also solve systems that combine equations from several time points.multipoint_n_points(default2),multipoint_max_pairs(default20),multipoint_pair_strategy(default:spread), experimental: how many time points each of those systems combines, how many combinations are tried, and how they are chosen,:spreador:boundary_order.auto_handle_transcendentals(defaulttrue): rewritesin(c*t),cos(c*t)andexp(c*t)in polynomial form.auto_rescale(defaulttrue): rescale states, parameters and data by powers of two to bring them near one, and convert the estimates back.use_parameter_homotopy(defaulttrue): solve at one time point and track the solutions to the others, which is faster than solving each afresh.homotopy_tracking_mode(default:generic_start, experimental): how that tracking is done::generic_start,:gamma_straight,:gamma_straight_fallbackor:parameter.gamma_max_seeds(default5),gamma_seed(default0), experimental: the number of random restarts for the tracking, and their seed.0uses a fixed seed for each problem, a positive value is used as given, and a negative value draws a new one every run, whichseedcannot make repeatable.use_column_scaling(defaulttrue, experimental): scale the unknowns of each polynomial system by the size of the data derivatives.hc_real_tol(default1e-9, experimental): how small the imaginary part of a solution must be for it to count as real.hc_threading(defaulttrue): let HomotopyContinuation use threads.hc_compile_mode(default:all, experimental): whether HomotopyContinuation compiles the systems::all,:noneor:mixed.
Choosing the solutions to return
algebraic_multiplicity(defaultnothing): the number of solutions the equations have. It is worked out automatically unless you set it. At most this many results are returned.compute_algebraic_multiplicity(defaulttrue, experimental):falseskips working it out.branch_top_k(default20): the most results returned when that number is not known.0returns all of them.branch_detection(defaulttrue, experimental): rank without using the true values.falseranks by distance to them, which is only meaningful in a benchmark.clustering_threshold(default1e-5, experimental): the relative distance below which two candidates are the same solution.rough_cluster_eps(default1.0),subspace_cluster_eps(default0.05), experimental: how near-duplicate results are merged. Candidates that are far apart are separated first, then close ones within each group are merged, at these two distances.branch_cluster_eps(default0.001),branch_err_factor(default100.0), experimental: before refinement, drop candidates whose fit error is more thanbranch_err_factortimes the best, and merge the rest at this distance.branch_diversity_selection(defaulttrue),branch_diversity_eps(default0.01), experimental: when several results are returned, prefer ones that differ by at least this relative distance.branch_completion(defaulttrue): when the equations have several solutions, take the best one found and solve for the others from it.branch_completion_max_anchors(default1),branch_completion_residual_tol(default1e-6), experimental: how many of the best solutions to start from, and the residual a new solution must reach.synthesize_aggregate_candidates(defaulttrue): add candidates made by combining the others: the median, mean and trimmed mean of each value.
Refining solutions
polish_solver_solutions(defaulttrue): refine each solution of the polynomial equations against those equations.polish_solver_jacobian(default:forwarddiff),polish_solver_chunk_size(default1), experimental: how the Jacobian for that is computed,:forwarddiff,:symbolicor:finitediff, and ForwardDiff's chunk size, where0chooses automatically.polish_method(defaultPolishLeastSquares): the optimizer forpolish_solutions.PolishLeastSquaresis Levenberg–Marquardt.PolishBFGSandPolishLBFGSminimize the sum of squares directly.polish_maxiters(default100),polish_maxtime(default3600.0seconds),polish_max_concurrency(defaultThreads.nthreads()): limits on the iterations and time spent on each solution, and on how many are refined at once.polish_divergence_factor(default10.0),polish_stagnation_window(default50), experimental: stop when the loss has grown by this factor, or has not improved for this many iterations.polish_ode_maxiters(default5000, experimental): the step limit for the ODE solver during refinement.polish_coordinate_policy(default:auto, experimental): the coordinates refinement works in.:autotakes logarithms of quantities whose bounds are positive. The others are:linear,:log_onlyand:shifted_log_only.polish_regularization_lambda(default0.0, experimental): the strength of an L2 penalty in those coordinates.polish_softwall_lambda(default1e-2),polish_softwall_epsilon(default0.10), experimental: a penalty that keeps values off their bounds: its strength, and the width of the band beside each bound where it acts, as a fraction of the range.polish_lso_delta(default10.0),polish_lso_x_tol,polish_lso_f_tol,polish_lso_g_tol(default-1.0), experimental: the trust-region radius and tolerances ofPolishLeastSquares. A negative tolerance meansabstolorreltol.opt_maxiters(default10000): the iteration limit for the local optimization ofFlowDirectOpt.opt_ad_backend(default:forward, experimental): how the optimizers get derivatives::forwardfor ForwardDiff or:finitefor finite differences.terminal_fallback(default:direct_opt): what to do when the algebraic method finds nothing.:direct_optfits by local optimization, withinpolish_maxitersandpolish_maxtime.:nonereturns no results.backsolve_recovery(default:algebraic_resolve): what to do when a solution blows up as it is integrated back to the first time point.:algebraic_resolvekeeps its parameters and solves for the states at that time again.:nonedoes nothing.use_sensitivity_seeds(defaultfalse),sensitivity_seed_probe_scale(default1.0),sensitivity_seed_eigenvalue_threshold(default0.01),sensitivity_seed_mahalanobis_threshold(default-1.0),sensitivity_sigma_d_kappa(default2.0), experimental: add starting points for refinement along the directions in which the data constrain a solution least.
Uncertainty
All of these are experimental.
compute_uncertainty(defaultfalse): also estimate standard errors for the best solution. NeedsInterpolatorGPUncertaintyininterpolators.uq_failure_policy(default:return_failed): when standard errors cannot be computed,:return_failedreturns anUncertaintyUnavailablethat says why, and:throwthrows anODEParameterEstimation.UncertaintyError.uq_noise_source(default:learned_gp_homoscedastic): where the noise level comes from: the Gaussian process fit, or with:smoother_residual_edfthe residuals of that fit.
The result type
ODEParameterEstimation.ParameterEstimationResult — Type
ParameterEstimationResultOne solution: parameter values and initial conditions with which the model reproduces the data.
Printing a result shows its values. result[a], result[:a] and result["a"] look one up.
Fields
parameters: the estimated parameter values, keyed by symbol.states: the estimated states atreport_time, keyed by symbol.report_time: the time those states belong to: the first time point of the data, or theinitial_timeof anObservationData.err: the fit error, the sum of squared differences between the data and the simulated model over all series and time points, after each series is scaled by a power of two to be of order one (unlessauto_rescale = false). Results are ranked by it.all_unidentifiable: the parameters and initial conditions that the measured quantities cannot determine. Their reported values are arbitrary.unident_dict: the values those were fixed at while solving.solution: the simulated trajectory.datasize: the number of time points.at_time: the time point at which the equations were solved.interpolator_source: the interpolator whose derivative estimates led here.provenance: aResultProvenancerecord of how the solution was produced.return_code: an older summary of the same::algebraic,:direct_opt, or the name of a recovery path.branch_size: how many candidate solutions were merged into this one.
When the package rescales a badly scaled problem internally (auto_rescale), err, solution and unident_dict stay in the rescaled units. parameters and states are always in yours.
Base.getindex — Method
result[variable]The estimated value of a parameter, or of a state's initial condition. variable is the symbol, or its name: result[a], result[:a] and result["a"] are the same.
Errors
ODEParameterEstimation.UnsupportedModelClassError — Type
UnsupportedModelClassErrorThrown when a model is not rational: it applies a function such as sin, exp or sqrt to a state or to an unknown parameter. expressions lists the terms found, and category says which kind they are.
sin(c * t), cos(c * t) and exp(c * t) with a number c depend on time alone and are accepted.
ODEParameterEstimation.UnsupportedDerivativeOrderError — Type
UnsupportedDerivativeOrderErrorThrown when a model needs a higher derivative of the measured data than the package computes (order 20). This happens when a few measured quantities have to account for many states and parameters.
ODEParameterEstimation.SamplingFailureError — Type
SamplingFailureErrorThrown by sample_problem_data when the model cannot be simulated over the whole time interval, for example because the solution blows up.