Main functions and types

Most uses of the package need only what is on this page.

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. A NamedTuple, a dictionary, or anything with named columns such as a DataFrame, with the time points under t and 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 an ObservationData. Leave it out to simulate data with sample_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 to AutoVern9(Rodas5P()). sample_problem_data replaces it with its ode_solver option.

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)
source
ODEParameterEstimation.ParameterEstimationProblem — Type
ParameterEstimationProblem

A 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 an OrderedODESystem.
  • measured_quantities: equations such as y1 ~ x1, one per measured series.
  • data_sample: the measurements, or nothing before 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 an ObservationData.
  • solver: the ODE solver used to simulate the model while estimating.
  • p_true, ic: the true parameter values and initial conditions, NaN where 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.

source
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 from ODEParameterEstimation.Examples has 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 of time_interval. There must be datasize of them, in increasing order. The initial conditions are the values at the first of them.
  • noise_level and noise_model: add Gaussian noise. :additive uses a standard deviation of noise_level times the mean absolute value of each series; :relative scales each value by 1 + noise_level * randn(); :none adds none.
  • ode_solver, abstol, reltol: the ODE solver and tolerances for the simulation. The returned problem keeps ode_solver as its solver.
  • seed: with an integer, the noise is the same on every call and the caller's default RNG is left untouched. With nothing (the default), noise is drawn from the caller's default RNG, so Random.seed! controls it.
source
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 of ObservationSeries.
  • 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.

source
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 as x1 or x1 + 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.
source

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])
source
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, as ParameterEstimationResults.
    • 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; besterror is the same as best_max_error. They are Inf when 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: with compute_uncertainty = true, an UncertaintyReport, or an UncertaintyUnavailable that says why there is none; otherwise nothing. Uncertainty estimation is experimental.
source
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; InterpolatorGPUncertainty is needed for compute_uncertainty; and InterpolatorCustom uses a function of your own.
  • polish_solutions (default true): refine each solution by least squares against the data. false returns the algebraic estimates as they are.
  • opt_lb, opt_ub (default nothing): 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 as sin(c * t).
  • seed (default nothing): with an integer, repeated runs give identical results and Julia's default random number generator is left as it was. With nothing, random draws come from the default generator, so results vary a little from run to run unless you call Random.seed! first.
  • progress (default false): print one timestamped line as each stage starts and finishes.
  • shooting_points (default 12): how many time points the equations are solved at. Fewer is faster.
  • abstol, reltol (default 1e-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 (default 21): the number of time points.
  • time_interval (default [-0.5, 0.5]): the first and last time.
  • noise_level (default 0.0): the size of the Gaussian noise added.
  • noise_model (default :additive): with :additive, the noise has standard deviation noise_level times the mean absolute value of the series. With :relative, each value is multiplied by 1 + noise_level * randn(). :none adds no noise.
  • uneven_sampling_times (default empty, experimental): if not empty, sample at these times, of which there must be datasize, instead of evenly over time_interval. The initial conditions are the values at the first of them.
  • ode_solver (default AutoVern9(Rodas5P())): the ODE solver for the simulation. The problem sample_problem_data returns keeps it as its solver for the estimation.

Output

  • nooutput (default true): print nothing and pass only errors to the logger. false prints the stages and a summary of the results.
  • diagnostics (default false): print detailed diagnostics and write the candidate-synthesis log under artifacts/diagnostics/.
  • save_system (default false), save_filepath (default ""): save the polynomial systems to files, under save_filepath or else saved_systems/.
  • profile_phases (default false, experimental): print the time and memory each stage took.
  • hc_show_progress (default false): show HomotopyContinuation's progress bar.

Estimating derivatives

  • custom_interpolators (default Function[]): your own functions (times, values) -> curve, one for each InterpolatorCustom entry in interpolators, in order.
  • auto_filter_interpolators (default true): leave out the rational interpolators when the data look noisy, because they amplify noise.
  • s3_adapt_k (default 10.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 (default 1.0, experimental): multiplies the fitted length scale of InterpolatorGPUncertainty. Values below one smooth less.

Building and solving the equations

  • flow (default FlowStandard): FlowStandard is the algebraic method. FlowDirectOpt fits by local optimization alone.
  • system_solver (default SolverHC): how the polynomial systems are solved. SolverHC is homotopy continuation, which finds every solution. The others are local solvers and can miss solutions: SolverTrustRegion is a trust-region method started from several points, and SolverLevenbergMarquardt is Levenberg–Marquardt from one point.
  • use_si_template (default true, experimental): has no effect. The equations are always built with StructuralIdentifiability.jl, and false is refused.
  • si_probability (default 0.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_basis or :identifiable_functions.
  • system_construction_policy (default :noise_frontier, experimental): which equations are used. :noise_frontier prefers systems that need lower derivatives of the data and have fewer solutions. :legacy is the earlier choice.
  • construction_candidate_limit (default 64), construction_beam_width (default 16), construction_compute_mixed_volume (default true), experimental: limits on the search that :noise_frontier does.
  • shooting_warp (default true), shooting_warp_beta (default 3.0), experimental: place more of the shooting_points near the start of the data, and how strongly.
  • use_multipoint (default true): also solve systems that combine equations from several time points.
  • multipoint_n_points (default 2), multipoint_max_pairs (default 20), 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, :spread or :boundary_order.
  • auto_handle_transcendentals (default true): rewrite sin(c*t), cos(c*t) and exp(c*t) in polynomial form.
  • auto_rescale (default true): rescale states, parameters and data by powers of two to bring them near one, and convert the estimates back.
  • use_parameter_homotopy (default true): 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_fallback or :parameter.
  • gamma_max_seeds (default 5), gamma_seed (default 0), experimental: the number of random restarts for the tracking, and their seed. 0 uses a fixed seed for each problem, a positive value is used as given, and a negative value draws a new one every run, which seed cannot make repeatable.
  • use_column_scaling (default true, experimental): scale the unknowns of each polynomial system by the size of the data derivatives.
  • hc_real_tol (default 1e-9, experimental): how small the imaginary part of a solution must be for it to count as real.
  • hc_threading (default true): let HomotopyContinuation use threads.
  • hc_compile_mode (default :all, experimental): whether HomotopyContinuation compiles the systems: :all, :none or :mixed.

Choosing the solutions to return

  • algebraic_multiplicity (default nothing): 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 (default true, experimental): false skips working it out.
  • branch_top_k (default 20): the most results returned when that number is not known. 0 returns all of them.
  • branch_detection (default true, experimental): rank without using the true values. false ranks by distance to them, which is only meaningful in a benchmark.
  • clustering_threshold (default 1e-5, experimental): the relative distance below which two candidates are the same solution.
  • rough_cluster_eps (default 1.0), subspace_cluster_eps (default 0.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 (default 0.001), branch_err_factor (default 100.0), experimental: before refinement, drop candidates whose fit error is more than branch_err_factor times the best, and merge the rest at this distance.
  • branch_diversity_selection (default true), branch_diversity_eps (default 0.01), experimental: when several results are returned, prefer ones that differ by at least this relative distance.
  • branch_completion (default true): when the equations have several solutions, take the best one found and solve for the others from it.
  • branch_completion_max_anchors (default 1), branch_completion_residual_tol (default 1e-6), experimental: how many of the best solutions to start from, and the residual a new solution must reach.
  • synthesize_aggregate_candidates (default true): add candidates made by combining the others: the median, mean and trimmed mean of each value.

Refining solutions

  • polish_solver_solutions (default true): refine each solution of the polynomial equations against those equations.
  • polish_solver_jacobian (default :forwarddiff), polish_solver_chunk_size (default 1), experimental: how the Jacobian for that is computed, :forwarddiff, :symbolic or :finitediff, and ForwardDiff's chunk size, where 0 chooses automatically.
  • polish_method (default PolishLeastSquares): the optimizer for polish_solutions. PolishLeastSquares is Levenberg–Marquardt. PolishBFGS and PolishLBFGS minimize the sum of squares directly.
  • polish_maxiters (default 100), polish_maxtime (default 3600.0 seconds), polish_max_concurrency (default Threads.nthreads()): limits on the iterations and time spent on each solution, and on how many are refined at once.
  • polish_divergence_factor (default 10.0), polish_stagnation_window (default 50), experimental: stop when the loss has grown by this factor, or has not improved for this many iterations.
  • polish_ode_maxiters (default 5000, experimental): the step limit for the ODE solver during refinement.
  • polish_coordinate_policy (default :auto, experimental): the coordinates refinement works in. :auto takes logarithms of quantities whose bounds are positive. The others are :linear, :log_only and :shifted_log_only.
  • polish_regularization_lambda (default 0.0, experimental): the strength of an L2 penalty in those coordinates.
  • polish_softwall_lambda (default 1e-2), polish_softwall_epsilon (default 0.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 (default 10.0), polish_lso_x_tol, polish_lso_f_tol, polish_lso_g_tol (default -1.0), experimental: the trust-region radius and tolerances of PolishLeastSquares. A negative tolerance means abstol or reltol.
  • opt_maxiters (default 10000): the iteration limit for the local optimization of FlowDirectOpt.
  • opt_ad_backend (default :forward, experimental): how the optimizers get derivatives: :forward for ForwardDiff or :finite for finite differences.
  • terminal_fallback (default :direct_opt): what to do when the algebraic method finds nothing. :direct_opt fits by local optimization, within polish_maxiters and polish_maxtime. :none returns 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_resolve keeps its parameters and solves for the states at that time again. :none does nothing.
  • use_sensitivity_seeds (default false), sensitivity_seed_probe_scale (default 1.0), sensitivity_seed_eigenvalue_threshold (default 0.01), sensitivity_seed_mahalanobis_threshold (default -1.0), sensitivity_sigma_d_kappa (default 2.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 (default false): also estimate standard errors for the best solution. Needs InterpolatorGPUncertainty in interpolators.
  • uq_failure_policy (default :return_failed): when standard errors cannot be computed, :return_failed returns an UncertaintyUnavailable that says why, and :throw throws an ODEParameterEstimation.UncertaintyError.
  • uq_noise_source (default :learned_gp_homoscedastic): where the noise level comes from: the Gaussian process fit, or with :smoother_residual_edf the residuals of that fit.
source

The result type

ODEParameterEstimation.ParameterEstimationResult — Type
ParameterEstimationResult

One 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 at report_time, keyed by symbol.
  • report_time: the time those states belong to: the first time point of the data, or the initial_time of an ObservationData.
  • 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 (unless auto_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: a ResultProvenance record 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.

source
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.

source

Errors

ODEParameterEstimation.UnsupportedModelClassError — Type
UnsupportedModelClassError

Thrown 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.

source