Code generation utilities

These are lower-level functions that ModelingToolkit leverages to generate code for building numerical problems.

ModelingToolkitBase.generate_rhsFunction
generate_rhs(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    implicit_dae,
    scalar,
    override_discrete,
    cachesyms,
    extra_args
) -> Any

Generate the RHS function for the equations of a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.
  • implicit_dae: Whether the generated function should be in the implicit form. Applicable only for ODEs/DAEs or discrete systems. Instead of f(u, p, t) (f(du, u, p, t) for the in-place form) the function is f(du, u, p, t) (respectively f(resid, du, u, p, t)).
  • override_discrete: Whether to assume the system is discrete regardless of is_discrete_system(sys).
  • scalar: Whether to generate a single-out-of-place function that returns a scalar for the only equation in the system.
  • extra_args: Extra trailing symbolic arguments appended after all standard arguments and kept out of the MTKParameters collapse, so they stay live scalar arguments of the generated function (e.g. the homotopy continuation λ, threaded as the "t slot"). Empty by default, which leaves the standard codegen path byte-identical.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_diffusion_functionFunction
generate_diffusion_function(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions
) -> Any

Generate the diffusion function for the noise equations of a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_jacobianFunction
generate_jacobian(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    simplify,
    sparse
) -> Any

Generate the jacobian function for the equations of a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.
  • simplify, sparse: Forwarded to calculate_jacobian.
  • checkbounds: Whether to check correctness of indices at runtime if sparse. Also forwarded to build_function_wrapper.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_tgradFunction
generate_tgrad(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    simplify
) -> Any

Generate the tgrad function for the equations of a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_WFunction
generate_W(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    simplify,
    sparse
) -> Any

Generate the W = γ * M + J function for the equations of a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.
  • simplify, sparse: Forwarded to calculate_jacobian.
  • checkbounds: Whether to check correctness of indices at runtime if sparse. Also forwarded to build_function_wrapper.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_dae_jacobianFunction
generate_dae_jacobian(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    simplify,
    sparse
) -> Any

Generate the DAE jacobian γ * J′ + J function for the equations of a System. J′ is the jacobian of the equations with respect to the du vector, and J is the standard jacobian.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_historyFunction
generate_history(
    sys::System,
    u0,
    opts::ModelingToolkitBase.GeneratedFunctionOptions
) -> Any

Generate the history function for a System, given a symbolic representation of the u0 vector prior to the initial time.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_boundary_conditionsFunction
generate_boundary_conditions(
    sys::System,
    u0,
    u0_idxs,
    t0,
    opts::ModelingToolkitBase.GeneratedFunctionOptions
) -> Any

Generate the boundary condition function for a System given the state vector u0, the indexes of u0 to consider as hard constraints u0_idxs and the initial time t0.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_trajectoryFunction
generate_trajectory(
    sys::System,
    expr,
    opts::ModelingToolkitBase.GeneratedFunctionOptions
) -> Any

Generate a function f(p, t) which evaluates the symbolic expression expr at time t with the parameter object p. expr may involve the independent variable, parameters, observed variables and bound parameters of sys (the latter two are inlined symbolically), but not its unknowns. The f(p, t) signature matches the initial guess function convention used across the SciML ecosystem, e.g. by BVProblem.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.
source
ModelingToolkitBase.generate_costFunction
generate_cost(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions
) -> Any

Generate the cost function for a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_cost_gradientFunction
generate_cost_gradient(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    simplify
) -> Any

Generate the gradient of the cost function with respect to unknowns for a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_cost_hessianFunction
generate_cost_hessian(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    simplify,
    sparse,
    return_sparsity
) -> Any

Generate the hessian of the cost function for a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.
  • simplify, sparse: Forwarded to calculate_cost_hessian.
  • return_sparsity: Whether to also return the sparsity pattern of the hessian as the second return value.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_consFunction
generate_cons(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions
) -> Any

Generate the constraint function for a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_constraint_jacobianFunction
generate_constraint_jacobian(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    return_sparsity,
    simplify,
    sparse
) -> Any

Generate the jacobian of the constraint function for a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.
  • simplify, sparse: Forwarded to calculate_constraint_jacobian.
  • return_sparsity: Whether to also return the sparsity pattern of the jacobian as the second return value.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_constraint_hessianFunction
generate_constraint_hessian(
    sys::System,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    return_sparsity,
    simplify,
    sparse
) -> Any

Generate the hessian of the constraint function for a System.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.
  • simplify, sparse: Forwarded to calculate_constraint_hessian.
  • return_sparsity: Whether to also return the sparsity pattern of the hessian as the second return value.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_control_jacobianFunction
generate_control_jacobian(
    sys::ModelingToolkitBase.AbstractSystem,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    simplify,
    sparse
) -> Any

Generate the jacobian function of the equations of sys with respect to the inputs.

Keyword arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_paramjacFunction
generate_paramjac(
    sys::ModelingToolkitBase.AbstractSystem,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    simplify,
    sparse
) -> Any

Generate the parameter-jacobian function for the equations of sys. The generated function has the signature pJ = f(u, p, t) (out-of-place) and f(pJ, u, p, t) (in-place), matching the paramjac field of a SciMLBase.ODEFunction. For a time-independent system the t argument is omitted.

See calculate_paramjac for the meaning of the columns of pJ.

Keyword Arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.
  • simplify, sparse: Forwarded to calculate_paramjac. A sparse in-place function writes into the nzval of its output and therefore requires a SparseMatrixCSC buffer with exactly the generated sparsity pattern. Pass checkbounds = true to assert that at runtime.
  • checkbounds: Whether to check the sparsity pattern of the output buffer at runtime if sparse. Also forwarded to build_function_wrapper.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.build_explicit_observed_functionFunction
build_explicit_observed_function(sys, ts; kwargs...) -> Function(s)

Generates a function that computes the observed value(s) ts in the system sys, while making the assumption that there are no cycles in the equations.

Arguments

  • sys: The system for which to generate the function
  • ts: The symbolic observed values whose value should be computed

Keywords

  • return_inplace = Val(false): If true and the observed value is a vector, then return both the in place and out of place methods. Can take boolean true or false values, but Val(true) or Val(false) is preferred.
  • expression = false: Generates a Julia Exprcomputing the observed value ifexpression` is true
  • eval_expression = false: If true and expression = false, evaluates the returned function in the module eval_module
  • output_type = Array the type of the array generated by a out-of-place vector-valued function
  • param_only = false if true, only allow the generated function to access system parameters
  • inputs = nothing additinoal symbolic variables that should be provided to the generated function
  • disturbance_inputs = nothing symbolic variables representing unknown disturbance inputs (removed from parameters, not added as function arguments)
  • known_disturbance_inputs = nothing symbolic variables representing known disturbance inputs (removed from parameters, added as function arguments)
  • checkbounds: whether to check bounds when destructuring parameters (defaults to false, i.e. generated code is wrapped in @inbounds)
  • throw = true if true, throw an error when generating a function for ts that reference variables that do not exist.
  • wrap_delays = is_dde(sys): Whether to add an argument for the history function and use it to calculate all delayed variables.

Returns

The return value will be either:

  • a single function f_oop if the input is a scalar or if the input is a Vector but return_inplace is false
  • the out of place and in-place functions (f_ip, f_oop) if return_inplace is true and the input is a Vector

The function(s) f_oop (and potentially f_ip) will be:

  • RuntimeGeneratedFunctions by default,
  • A Julia Expr if expression is true,
  • A directly evaluated Julia function in the module eval_module if eval_expression is true and expression is false.

The signatures will be of the form g(...) with arguments:

  • output for in-place functions
  • unknowns if param_only is false
  • inputs if inputs is an array of symbolic inputs that should be available in ts
  • p... unconditionally; note that in the case of MTKParameters more than one parameters argument may be present, so it must be splatted
  • t if the system is time-dependent; for example systems of nonlinear equations will not have t
  • known_disturbance_inputs if provided; these are disturbance inputs that are known and provided as arguments

For example, a function g(op, unknowns, p..., inputs, t, known_disturbances) will be the in-place function generated if return_inplace is true, ts is a vector, an array of inputs inputs is given, known_disturbance_inputs is provided, and param_only is false for a time-dependent system.

source
ModelingToolkitBase.generate_control_functionFunction
generate_control_function(sys::ModelingToolkitBase.AbstractSystem, input_ap_name::Union{Symbol, Vector{Symbol}, AnalysisPoint, Vector{AnalysisPoint}}, dist_ap_name::Union{Symbol, Vector{Symbol}, AnalysisPoint, Vector{AnalysisPoint}}; system_modifier = identity, kwargs)

When called with analysis points as input arguments, we assume that all analysis points corresponds to connections that should be opened (broken). The use case for this is to get rid of input signal blocks, such as Step or Sine, since these are useful for simulation but are not needed when using the plant model in a controller or state estimator.

source
generate_control_function(sys, inputs = default_codegen_inputs(sys),
    disturbance_inputs = disturbances(sys); kwargs...) -> (; f, dvs, ps, io_sys)

Generate the dynamics of an input-output system as callable functions of its state, inputs, parameters, and independent variable.

Arguments

  • sys::AbstractSystem: The system to generate dynamics for. An unscheduled system is compiled with mtkcompile; a scheduled system is used as given.
  • inputs: Symbolic variables that form the generated input argument u. By default, declared inputs are used for scheduled systems and external inputs for unscheduled systems.
  • disturbance_inputs: Unknown disturbance inputs. Their state and dynamics are retained, but their values are set to zero and are not function arguments.

Keywords

  • known_disturbance_inputs = nothing: Disturbance inputs supplied as a final generated argument w; they are removed from the parameter arguments.
  • implicit_dae::Bool = false: Generate residual dynamics for an implicit DAE.
  • simplify::Bool = false: Forwarded to mtkcompile when sys is unscheduled.
  • split::Bool = true: Forwarded to mtkcompile to select split-system generation.
  • eval_expression::Bool = false: Evaluate generated code in eval_module instead of returning a runtime-generated function.
  • eval_module::Module = @__MODULE__: Module used when eval_expression = true.
  • disturbance_argument = false: Deprecated compatibility option. Use known_disturbance_inputs instead.
  • kwargs...: Forwarded to Symbolics.CodegenFunctionOptions.

Returns

A named tuple with:

  • f: A pair (f_oop, f_iip) of generated out-of-place and in-place dynamics wrappers. The basic call signatures are f_oop(x, u, p..., t) and f_iip(dx, x, u, p..., t). With known disturbances, both have a final w argument.
  • dvs: The selected state variables, ordered as the x argument of f.
  • ps: The selected parameter variables, ordered as the parameter arguments of f.
  • io_sys: The scheduled system used to generate f.

Example

using ModelingToolkitBase
import ModelingToolkitBase: t_nounits as t, D_nounits as D

@variables x(t) u(t)
@parameters k
@named sys = System([D(x) ~ -k * (x + u)], t)

(; f, dvs, ps, io_sys) = generate_control_function(sys, [u]; simplify = true)
p = [2.0]
f[1]([1.0], [3.0], p, 0.0) # [-8.0]
source
ModelingToolkitBase.generate_update_AFunction
generate_update_A(
    sys::System,
    A::AbstractMatrix,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    cachesyms
) -> Any

Given a system sys and the A from calculate_A_b generate the function that updates A given the parameter object.

Keyword arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkitBase.generate_update_bFunction
generate_update_b(
    sys::System,
    b::AbstractVector,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    cachesyms
) -> Any

Given a system sys and the b from calculate_A_b generate the function that updates b given the parameter object.

Keyword arguments

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.
  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.
  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.
  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper.

source
ModelingToolkit.generate_semiquadratic_functionsFunction
generate_semiquadratic_functions(
    sys::System,
    A,
    B,
    C,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    stiff_linear,
    stiff_quadratic,
    stiff_nonlinear
) -> Tuple{Any, Any}

Generate f1 and f2 for SemilinearODEFunction (internally represented as a SplitFunction). A, B, C are the matrices returned from calculate_semiquadratic_form. This expects that the system has the necessary extra parameters added by add_semiquadratic_parameters.

Keyword Arguments

  • stiff_linear: Whether the linear part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no linear part.

  • stiff_quadratic: Whether the quadratic part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no quadratic part.

  • stiff_nonlinear: Whether the non-linear non-quadratic part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no such non-linear non-quadratic part.

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.

  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.

  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.

  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper. Note that all three of stiff_linear, stiff_quadratic, stiff_nonlinear cannot be identical, and at least two of A, B, C returned from calculate_semiquadratic_form must be non-nothing. In other words, both of the functions in the split form must be non-empty.

Warn

This API is experimental and may change in a future non-breaking release.

source
ModelingToolkit.generate_semiquadratic_jacobianFunction
generate_semiquadratic_jacobian(
    sys::System,
    A,
    B,
    C,
    Cjac,
    opts::ModelingToolkitBase.GeneratedFunctionOptions;
    sparse,
    stiff_linear,
    stiff_quadratic,
    stiff_nonlinear
) -> Any

Generate the jacobian of f1 for SemilinearODEFunction (internally represented as a SplitFunction). A, B, C are the matrices returned from calculate_semiquadratic_form. Cjac is the jacobian of C with respect to the unknowns of the system, or nothing if C === nothing. This expects that the system has the necessary extra parameters added by add_semiquadratic_parameters.

Keyword Arguments

  • stiff_linear: Whether the linear part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no linear part.

  • stiff_quadratic: Whether the quadratic part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no quadratic part.

  • stiff_nonlinear: Whether the non-linear non-quadratic part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no such non-linear non-quadratic part.

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.

  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.

  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.

  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

All other keyword arguments are forwarded to build_function_wrapper. Note that all three of stiff_linear, stiff_quadratic, stiff_nonlinear cannot be identical, and at least two of A, B, C returned from calculate_semiquadratic_form must be non-nothing. In other words, both of the functions in the split form must be non-empty.

Warn

This API is experimental and may change in a future non-breaking release.

source
ModelingToolkit.get_semiquadratic_W_sparsityFunction
get_semiquadratic_W_sparsity(
    sys::System,
    A,
    B,
    C,
    Cjac;
    stiff_linear,
    stiff_quadratic,
    stiff_nonlinear,
    mm
) -> SparseArrays.SparseMatrixCSC{Bool, Int64}

Return the sparsity pattern of the jacobian of f1 for SemilinearODEFunction (internally represented as a SplitFunction). A, B, C are the matrices returned from calculate_semiquadratic_form. Cjac is the jacobian of C with respect to the unknowns of the system, or nothing if C === nothing. This expects that the system has the necessary extra parameters added by add_semiquadratic_parameters.

Keyword Arguments

  • stiff_linear: Whether the linear part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no linear part.

  • stiff_quadratic: Whether the quadratic part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no quadratic part.

  • stiff_nonlinear: Whether the non-linear non-quadratic part of the equations should be part of the stiff function in the split form. Has no effect if the equations have no such non-linear non-quadratic part.

  • expression: Val{true} if this should return an Expr (or tuple of Exprs) of the generated code. Val{false} otherwise.

  • wrap_gfw: Val{true} if the returned functions should be wrapped in a callable struct to make them callable using the expected syntax. The callable struct itself is internal API. If expression == Val{true}, the returned expression will construct the callable struct. If this function returns a tuple of functions/expressions, both will be identical if wrap_gfw == Val{true}.

  • eval_expression: Whether to compile any functions via eval or RuntimeGeneratedFunctions.

  • eval_module: If eval_expression == true, the module to eval into. Otherwise, the module in which to generate the RuntimeGeneratedFunction.

  • mm: The mass matrix of sys.

Note that all three of stiff_linear, stiff_quadratic, stiff_nonlinear cannot be identical, and at least two of A, B, C returned from calculate_semiquadratic_form must be non-nothing. In other words, both of the functions in the split form must be non-empty.

Warn

This API is experimental and may change in a future non-breaking release.

source
ModelingToolkitBase.CompilerOptionsType
CompilerOptions(; optlevel = -1, compile = :default, infer = :default)

Options controlling the Julia compiler for generated functions.

Note that this feature is considered experimental.

Keywords

  • optlevel::Int = -1: LLVM optimization level (0-3), or -1 to inherit from the module.
  • compile::Union{Int, Symbol} = :default: Compilation mode as an integer (0=off, 1=on, 2=all, 3=min), or -1 to inherit. It also accepts :off, :on, :all, :min, and :default.
  • infer::Union{Int, Bool, Symbol} = :default: Type inference mode as 0 (off), 1 (on), or -1 (inherit). It also accepts Bool and :default.

Returns

  • CompilerOptions: Compiler options suitable for a generated-function constructor.

Examples

using ModelingToolkitBase

CompilerOptions(optlevel = 3, compile = :all, infer = true)
source
ModelingToolkitBase.generate_custom_functionFunction
generate_custom_function(
    sys::AbstractSystem, exprs, dvs = unknowns(sys), ps = parameters(sys); kwargs...
)

Generate a function to evaluate exprs. exprs is a symbolic expression or array of symbolic expressions involving symbolic variables in sys. If split = true was passed to complete, mtkcompile, or @mtkcompile, p is an MTKParameters object.

Arguments

  • sys::AbstractSystem: A completed system that owns the symbolic variables.
  • exprs: A symbolic expression or array of expressions to evaluate.
  • dvs = unknowns(sys): State variables supplied as u.
  • ps = parameters(sys): Parameters supplied as p.

Keywords

  • expression = Val{true}: Return generated expression(s) when Val{true}, or callable function(s) when Val{false}.
  • eval_expression = false: Evaluate generated expressions in eval_module rather than using RuntimeGeneratedFunctions.
  • eval_module = @__MODULE__: Module in which expressions are evaluated when eval_expression = true.
  • cachesyms = (): Symbols supplied as cache arguments to the generated function.
  • kwargs...: Code-generation options forwarded to Symbolics.CodegenFunctionOptions.

Returns

  • Generated expression(s) or callable function(s). Time-dependent functions accept f(u, p, t) or f(du, u, p, t); time-independent functions omit t.

Examples

using ModelingToolkitBase

@independent_variables t
@variables x(t)
sys = complete(System(Equation[], t, [x], []; name = :sys))
f = generate_custom_function(sys, x; expression = Val(false))
f([1.0], MTKParameters(sys, []), 0.0)
source

For functions such as jacobian calculation which require symbolic computation, there are calculate_* equivalents to obtain the symbolic result without building a function.

ModelingToolkitBase.calculate_tgradFunction
calculate_tgrad(sys::System; simplify) -> Any

Calculate the gradient of the equations of sys with respect to the independent variable. simplify is forwarded to Symbolics.expand_derivatives.

source
ModelingToolkitBase.calculate_jacobianFunction
calculate_jacobian(
    sys::System;
    sparse,
    simplify,
    dvs
) -> Union{SparseArrays.SparseMatrixCSC{Num, Int64}, Matrix{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}}}

Calculate the jacobian of the equations of sys.

Keyword arguments

  • simplify, sparse: Forwarded to Symbolics.jacobian.
  • dvs: The variables with respect to which the jacobian should be computed.
source
ModelingToolkitBase.calculate_hessianFunction
calculate_hessian(
    sys::System;
    simplify,
    sparse
) -> Vector{Matrix{Num}}

Return an array of symbolic hessians corresponding to the equations of the system.

Keyword Arguments

  • sparse: Controls whether the symbolic hessians are sparse matrices
  • simplify: Forwarded to Symbolics.hessian
source
ModelingToolkitBase.calculate_massmatrixFunction
calculate_massmatrix(
    sys::System;
    simplify
) -> Union{LinearAlgebra.UniformScaling{Bool}, LinearAlgebra.Diagonal{Float64, Vector{Float64}}, Matrix{Float64}}

Calculate the mass matrix of sys. simplify controls whether Symbolics.simplify is applied to the symbolic mass matrix. Returns a Diagonal or LinearAlgebra.I wherever possible.

source
ModelingToolkitBase.calculate_W_prototypeFunction
calculate_W_prototype(W_sparsity; u0, sparse) -> Any

Return the matrix to use as the jacobian prototype given the W-sparsity matrix of the system. This is not the same as the jacobian sparsity pattern.

Keyword arguments

  • u0: The u0 vector for the problem.
  • sparse: The prototype is nothing for non-sparse matrices.
source
ModelingToolkitBase.calculate_cost_gradientFunction
calculate_cost_gradient(
    sys::System;
    simplify
) -> Vector{Num}

Calculate the gradient of the consolidated cost of sys with respect to the unknowns. simplify is forwarded to Symbolics.gradient.

source
ModelingToolkitBase.calculate_cost_hessianFunction
calculate_cost_hessian(
    sys::System;
    sparse,
    simplify
) -> Matrix{Num}

Calculate the hessian of the consolidated cost of sys with respect to the unknowns. simplify is forwarded to Symbolics.hessian. sparse controls whether a sparse matrix is returned.

source
ModelingToolkitBase.calculate_constraint_jacobianFunction
calculate_constraint_jacobian(
    sys::System;
    simplify,
    sparse,
    return_sparsity
) -> Any

Return the jacobian of the constraints of sys with respect to unknowns.

Keyword arguments

  • simplify, sparse: Forwarded to Symbolics.jacobian.
  • return_sparsity: Whether to also return the sparsity pattern of the jacobian.
source
ModelingToolkitBase.calculate_constraint_hessianFunction
calculate_constraint_hessian(
    sys::System;
    simplify,
    sparse,
    return_sparsity
) -> Any

Return the hessian of the constraints of sys with respect to unknowns.

Keyword arguments

  • simplify, sparse: Forwarded to Symbolics.hessian.
  • return_sparsity: Whether to also return the sparsity pattern of the hessian.
source
ModelingToolkitBase.calculate_control_jacobianFunction
calculate_control_jacobian(
    sys::ModelingToolkitBase.AbstractSystem;
    sparse,
    simplify
) -> Any

Calculate the jacobian of the equations of sys with respect to the inputs.

Keyword arguments

  • simplify, sparse: Forwarded to Symbolics.jacobian.
source
ModelingToolkitBase.calculate_paramjacFunction
calculate_paramjac(
    sys::ModelingToolkitBase.AbstractSystem;
    sparse,
    simplify,
    ps
) -> Any

Calculate the jacobian of the equations of sys with respect to its parameters, df/dp.

pJ[i, j] is the derivative of equation i of full_equations(sys) with respect to entry j of SciMLStructures.canonicalize(SciMLStructures.Tunable(), p)[1], where p is the parameter object of a problem built from sys. For split = true (the default) that array is the tunable portion of MTKParameters, already flattened, so parameters outside the tunable portion (tunable = false, integer-valued, nonnumeric, discrete and Initial(...) parameters) have no column, and array parameters occupy consecutive column-major columns. For split = false there is no index cache and p is a plain vector, so the columns are every parameter in parameters(sys; initial_parameters = true) order, including non-tunable and Initial(...) parameters. Array parameters are scalarized into one column each, so that correspondence is exact only for a system whose parameters are all scalars; a non-split system with array parameters cannot currently be turned into a problem anyway.

The column order is the parameter-buffer order, which is not the order in which the parameters were declared. Use reorder_dimension_by_tunables with dim = 2 to permute the columns into a chosen order, e.g. reorder_dimension_by_tunables(sys, pJ, [a, b, c]; dim = 2).

Keyword arguments

  • simplify, sparse: Forwarded to Symbolics.jacobian/Symbolics.sparsejacobian.
  • ps: The parameters with respect to which the jacobian should be computed.

A parameter that is only reached through a registered function with no derivative rule leaves an unexpanded Differential in the result, which generates a function returning Num rather than a number. calculate_jacobian has the same limitation for a registered function of an unknown.

source
ModelingToolkitBase.calculate_A_bFunction
calculate_A_b(
    sys::System;
    sparse,
    throw
) -> Union{Nothing, Tuple{Union{SparseArrays.SparseMatrixCSC{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}, Int64}, Matrix{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}}}, Vector{SymbolicUtils.BasicSymbolicImpl.var"typeof(BasicSymbolicImpl)"{SymReal}}}}

Return matrix A and vector b such that the system sys can be represented as A * x = b where x is unknowns(sys).

Keyword arguments

  • sparse: return a sparse A.
  • throw: whether to throw an error if the system is not affine.
source

A system can be marked as unsupported by symbolic automatic differentiation, in which case the calculate_* functions above throw instead of producing a wrong derivative.

ModelingToolkitBase.SymbolicADDisallowedType
abstract type SymbolicADDisallowed

Metadata key used to mark a system as incompatible with symbolic automatic differentiation. When set on a system via setmetadata(sys, SymbolicADDisallowed, reason), any attempt to perform symbolic AD on the equations of that system (e.g. via calculate_jacobian, calculate_tgrad, linearize_symbolic, or during structural simplification) will throw an error. The value associated with this key should be a descriptive String explaining why symbolic AD is unsupported, or true if no explanation is available.

See also: check_symbolic_ad_allowed.

source

All code generation eventually calls build_function_wrapper.

ModelingToolkitBase.build_function_wrapperFunction
build_function_wrapper(sys::AbstractSystem, expr, args...; kwargs...)

Backwards-compatibility keyword-argument form of build_function_wrapper. The keyword arguments (documented on BuildFunctionWrapperOptions) are bundled into a BuildFunctionWrapperOptions and forwarded to the primary method, build_function_wrapper(sys, expr, args, opts::BuildFunctionWrapperOptions). This method exists only for backwards compatibility; new code should construct a BuildFunctionWrapperOptions and call that method directly.

source
build_function_wrapper(sys::AbstractSystem, expr, args, opts::BuildFunctionWrapperOptions)

A wrapper around build_function which performs the necessary transformations for code generation of all types of systems. expr is the expression returned from the generated functions, and args is the Vector{Any} of arguments.

Options are supplied as a BuildFunctionWrapperOptions; see its docstring for the available options. This is the primary method — the keyword-argument form of build_function_wrapper is a backwards-compatibility shim that bundles its keywords into a BuildFunctionWrapperOptions and calls this method.

source