Private API

This page lists non-exported (internal) symbols of CTParser.


From CTParser

@init [Macro]

CTParser.@init — Macro
@init ocp begin
    ...
end

Build an initial guess object for an optimal control problem from a small initialisation DSL.

The block following @init is interpreted as a collection of assignment rules for the state, control and variable components of an optimal control problem, using a compact syntax of the form

q(t) := sin(t)     # time-dependent function
x(T) := X          # time grid and associated samples
u := 0.1           # constant value
a = 1.0           # ordinary Julia alias (not part of the initial guess)
v(t) := a         # time-dependent function using the alias above

The left-hand side is the name of a block (x, u, the variable), the label of a component (x₁, or q with x = (q, v) ∈ R², state), or, as in @def, an indexed block: x[1](t) := …, x[2] := …, x[1](T) := …, x[1:2](t) := …, x[1:2] := …. The index is an integer literal or a range a:b of integer literals, after alias substitution. An indexed left-hand side is resolved to component names when the generated code runs, since only the model knows them. A range is split per component; a time grid on a range is not supported.

A specification can refer to an earlier one in its right-hand side, written as the earlier left-hand side: x[1](t) refers to x[1](t) := …, not to x₁(t) := ….

A left-hand side written twice is a CTBase.ParsingError, detected at expansion time; two left-hand sides naming the same component (x[1] and x₁) are a CTBase.PreconditionError, and an out-of-range index or an unknown name a CTBase.IncorrectArgument, detected when the generated code runs.

The macro itself only rewrites this DSL into a NamedTuple-based representation. All dimensional checks, interpretation of aliases and construction of the concrete initial guess object are delegated to CTModels, via build_initial_guess and validate_initial_guess.

An optional keyword-like trailing argument controls logging:

ig = @init ocp begin
    u(t) := t
end log = true

When log = true, the macro additionally prints a human-readable NamedTuple-like representation of the specification.

Arguments

  • ocp: symbolic optimal control problem built with @def.
  • begin ... end: block containing the initialisation DSL.
  • log: optional Boolean keyword (default false) enabling textual logging of the parsed specification.

Returns

  • AbstractInitialGuess: initial guess object produced by CTModels.

Throws

  • CTBase.ParsingError: detected at expansion time, for an unrecognised statement, an unsupported left-hand side or index, a left-hand side written twice, or a trailing argument other than log = ….
  • CTBase.IncorrectArgument: when the generated code runs, for a time variable that is not the time name of the problem, an indexed left-hand side that cannot be resolved (unknown name, index out of range), a constant of the wrong length on a range, and any inconsistency CTModels detects (dimension, block mixed with components).
  • CTBase.PreconditionError: when the generated code runs, for two specifications of the same component (x[1] and x₁) and for a time grid on a range.

See the developer page "The @init macro" for the design.

Example

julia> using CTParser

julia> ocp = @def begin
           t ∈ [0, 1], time
           x ∈ R, state
           u ∈ R, control
           ẋ(t) == u(t)
           x(0) == 0
           x(1) == 0
           ∫(0.5u(t)^2) → min
       end

julia> ig = @init ocp begin
           u(t) := t
       end

julia> ig isa CTModels.AbstractInitialGuess
true

InitKey [Struct]

CTParser.InitKey — Type

Key of an @init specification.

It is either the name written on the left-hand side (x, x₁, u, tf), or, for an indexed left-hand side, the pair (name, index): (:x, 1) for x[1], (:x, 1:2) for x[1:2]. A name is passed to CTModels as it is. An indexed key is resolved to component names when the generated code runs, with __init_component_keys, since only the model knows them: with x = (r, v) ∈ R², state, x[1] is r.

See also: __init_key, __init_namedtuple

__gen_spec_value [Function]

CTParser.__gen_spec_value — Function
__gen_spec_value(pref, ocp, spec) -> Tuple{Symbol, Expr}

Generate runtime code for a single initialisation specification.

This function dispatches based on the specification kind (:constant or :temporal) and delegates to the appropriate code generator.

Arguments

  • pref::Module: module providing the backend (see FUN).
  • ocp: symbolic OCP variable.
  • spec::Tuple: specification tuple, either (:constant, rhs) or (:temporal, arg, rhs, arg_in_rhs).

Returns

  • val_sym::Symbol: generated symbol to store the value.
  • code::Expr: expression to insert in the generated code.

__gen_temporal_value [Function]

CTParser.__gen_temporal_value — Function
__gen_temporal_value(
    pref,
    ocp,
    arg,
    rhs,
    arg_in_rhs
) -> Tuple{Symbol, Expr}

Generate runtime code for a temporal specification lhs(arg) := rhs.

This function produces the Julia expression that will be evaluated at runtime to determine whether the specification represents a time-dependent function or a time grid, based on whether arg matches time_name(ocp).

Arguments

  • pref::Module: module providing time_name (interpolated into the generated code, so it resolves where @init is defined — see FUN).
  • ocp: symbolic OCP variable passed from the macro.
  • arg: argument used in the specification (e.g. :t, :s, or a literal array after alias expansion).
  • rhs: right-hand side expression.
  • arg_in_rhs::Bool: whether arg appears in rhs (computed at parse-time via has).

Returns

  • val_sym::Symbol: generated symbol to store the computed value.
  • code::Expr: expression block to insert in the generated code.

Notes

When arg is not a Symbol (e.g., a literal array after alias expansion like [0.0, 0.5, 1.0]), it is always treated as a time grid specification.

When arg is a Symbol and arg_in_rhs is true, the specification is definitely a time-dependent function, so we validate that arg == Symbol(time_name(ocp)) and throw an error if not. When arg_in_rhs is false, we generate a runtime conditional that checks whether arg matches the time name to decide between a constant function or a time grid.

__init_component_keys [Function]

CTParser.__init_component_keys — Function
__init_component_keys(
    ocp,
    name::Symbol,
    idx::Union{UnitRange{Int64}, Int64}
) -> Vector{Symbol}

Resolve the indexed @init key name[idx] to component names of ocp.

It is called by the code @init generates, when it runs, because the component names are stored in the model and @init only receives the symbol ocp. name must be the name of the state, the control or the variable. For a one-dimensional component, the only component name is the name itself, so x[1] on a scalar state resolves to the block key x, as x[1] is an alias of x in @def.

This function maps a (name, index) pair to components. It is meant to be shared with @def once both macros resolve names through the same symbol table (#289).

Arguments

  • ocp: the optimal control problem, built with @def.
  • name::Symbol: the name before the brackets, x in x[1].
  • idx::Union{Int,UnitRange{Int}}: the index or the range.

Returns

  • Vector{Symbol}: the component names, one per index: [:x₁] for x[1], [:r, :v] for x[1:2] with x = (r, v) ∈ R², state.

Throws

  • CTBase.IncorrectArgument: name is not the state, control or variable name of ocp (a component label such as x₁ cannot be indexed), or idx is not within the dimension.

See also: __init_namedtuple

__init_index [Function]

CTParser.__init_index — Function
__init_index(i) -> Union{Nothing, UnitRange{Int64}, Int64}

Read the index of an indexed @init left-hand side, after alias substitution.

Only literal indices are accepted, because the index is read when @init expands: an alias such as i = 2 is substituted before, but a value known only at run time is not.

Arguments

  • i: the index expression, 2 in x[2] or :(1:2) in x[1:2].

Returns

  • Int: for an integer literal.
  • UnitRange{Int}: for a range a:b of integer literals with a ≤ b.
  • Nothing: for any other form: end, a step range a:s:b, an empty range, a name that is not an alias, a non-integer literal.

Example

julia> CTParser.__init_index(2)
2

julia> CTParser.__init_index(:(1:3))
1:3

julia> CTParser.__init_index(:end) === nothing
true

__init_key [Function]

CTParser.__init_key — Function
__init_key(
    lhs
) -> Union{Symbol, Tuple{Symbol, Union{UnitRange{Int64}, Int64}}}

Return the InitKey of an @init left-hand side.

Arguments

  • lhs: the left-hand side before := or (arg) :=, after alias substitution.

Returns

  • Symbol: the name itself, when lhs is a Symbol.
  • Tuple{Symbol,Union{Int,UnitRange{Int}}}: (name, index) for name[i] or name[a:b], with the index read by __init_index.

Throws

  • CTBase.ParsingError: for an unsupported index (x[end], x[1:2:3], x[i] with i not an alias) or any other left-hand side (x[1, 2], x[1][2], (q + v)). @init re-emits it with the line of the block.

Example

julia> CTParser.__init_key(:x₁)
:x₁

julia> CTParser.__init_key(:(x[1:2]))
(:x, 1:2)

__init_key_string [Function]

CTParser.__init_key_string — Function
__init_key_string(key::Symbol) -> String

Format an InitKey as it is written in the @init block.

Used in the log string (log = true) and in error messages.

Arguments

  • key: a name, or a (name, index) pair.

Returns

  • String: "x", "x[1]" or "x[1:2]".

__init_namedtuple [Function]

CTParser.__init_namedtuple — Function
__init_namedtuple(ocp, entries...) -> NamedTuple

Build the NamedTuple passed to build_initial_guess when an @init block has an indexed key.

Without an indexed key, @init writes the NamedTuple when it expands. With one, the keys are only known when the generated code runs: names are kept, indexed keys are resolved with __init_component_keys, and range values are split with __init_split. Two specifications that resolve to the same component, such as x[1] and x₁, are rejected here, since @init cannot see that they are the same. Mixing a component with its whole block (x[1] and x) is rejected by CTModels.

Arguments

  • ocp: the optimal control problem, built with @def.
  • entries...: one (key, value, temporal) tuple per specification, in the order of the block, where key is an InitKey and temporal says whether the specification is written lhs(arg) := rhs.

Returns

  • NamedTuple: one field per component or block name, in the order of the block.

Throws

  • CTBase.PreconditionError: two specifications initialise the same component.
  • CTBase.IncorrectArgument, CTBase.PreconditionError: an indexed key cannot be resolved or split (see __init_component_keys and __init_split).

__init_split [Function]

CTParser.__init_split — Function
__init_split(
    val,
    n::Int64,
    temporal::Bool,
    key
) -> Vector{Any}

Split the value of an @init specification on a range of components, one value per component.

A function of time f gives t -> f(t)[k], which evaluates f once per component; a constant c gives c[k]. A time grid (T, X) on a range is not supported: the layout of X (matrix or vector of vectors, by rows or by columns) would have to be guessed.

Arguments

  • val: the value of the specification, as computed by the generated code.
  • n::Int: the length of the range.
  • temporal::Bool: whether the specification is written lhs(arg) := rhs; a temporal value that is not a function is a time grid.
  • key: the InitKey, for error messages.

Returns

  • Vector{Any}: the n values.

Throws

  • CTBase.PreconditionError: the value is a time grid (a range combined with a grid).
  • CTBase.IncorrectArgument: the value is a constant whose length is not n.

__log_spec [Function]

CTParser.__log_spec — Function
__log_spec(key, spec) -> String

Format a single initialisation specification for logging.

This function produces a human-readable string representation of a specification, used when log = true is passed to @init.

Arguments

  • key: the InitKey: a name (:u, :x) or a (name, index) pair.
  • spec::Tuple: specification tuple.

Returns

  • String: formatted string like "u = t -> sin(t)", "x = 1.0" or "x[1] = t -> t".

_collect_init_specs [Function]

CTParser._collect_init_specs — Function
_collect_init_specs(
    ex,
    lnum::Int64,
    line_str::String
) -> Tuple{Any, Vector{Tuple}}

Internal helper that parses the body of an @init block.

The function walks through the expression ex and splits it into

  • alias statements of the form lhs = rhs, which are stored in a dictionary and substituted into subsequent statements at parse-time using subs;
  • initialisation specifications of the form lhs := rhs or lhs(arg) := rhs, which are converted into structured specification tuples after alias and cross-spec expansion.

The left-hand side of a specification is a name (x, x₁, tf) or an indexed name (x[1], x[1:2]), read by __init_key. A left-hand side written twice (same key, whatever the form := or (arg) :=) is rejected here. Two different keys that name the same component (x[1] and x₁) can only be detected when the generated code runs, by __init_namedtuple.

For expressions of the form lhs(arg) := rhs, this function uses has(rhs, arg) to determine whether arg appears in the right-hand side. This information is stored in the specification tuple and used later to generate appropriate runtime code that distinguishes time-dependent functions from time grids.

Alias substitution happens before each statement is matched, enabling time-dependent aliases like phi = 2π * t and accumulated aliases like a = t; s = a.

After each specification is matched, its (pattern, rhs) pair is stored for cross-spec substitution: subsequent specifications can reference previous ones in their right-hand side. Substitution is applied on the RHS only (post-matching) to avoid corrupting the LHS. The already-substituted RHS is stored, so transitive references are resolved automatically.

All combinations are supported:

  • temporal → temporal: q(t) := sin(t); v(t) := 1.0 + q(t)
  • constant → temporal: c := 0.1; v(t) := c + sin(t)
  • constant → constant: a := 1.0; b := a + 2.0
  • indexed: x[1](t) := sin(t); x[2](t) := 1 + x[1](t)

Order matters: a spec can only reference specs that appear before it. The substitution is syntactic: a reference is replaced only if it is written as the earlier left-hand side, so x[1](t) does not refer to an earlier x₁(t) := ….

Arguments

  • ex::Any: expression or block coming from the body of @init.
  • lnum::Int: line number for error reporting.
  • line_str::String: line string for error reporting.

Returns

  • keys::Vector{InitKey}: keys of the specifications, in the order of the block: names (e.g. :q, :v, :u, :tf) or (name, index) pairs (see InitKey).
  • specs::Vector{Tuple}: specification tuples, either (:constant, rhs) for constant values or (:temporal, arg, rhs, arg_in_rhs) for temporal specifications where arg_in_rhs indicates whether arg appears in rhs.

Throws

  • CTBase.ParsingError: for an unrecognised statement, an alias whose left-hand side is not a name, an unsupported left-hand side or index, or a left-hand side written twice. @init re-emits it with the line of the block; any other exception is a parser bug and propagates as it is.

init_fun [Function]

CTParser.init_fun — Function
init_fun(
    ocp,
    e,
    lnum::Int64,
    line_str::String
) -> Tuple{String, Expr}

Lowering function used by @init to build the expanded code.

Given an optimal control problem ocp and the body e of an @init block, this function collects the initialisation specifications, builds an appropriate NamedTuple expression and constructs the call to build_initial_guess / validate_initial_guess on CTModels (the module is interpolated into the generated code — see FUN).

The NamedTuple is written at expansion time when every key is a name. When a key is indexed (x[1]), the generated code calls __init_namedtuple instead, which resolves the keys against the model when it runs. Blocks without an indexed key therefore generate the same code as before indexed keys existed.

It also produces a compact string representation of the specification, used for optional logging when log = true is requested at the macro level.

Arguments

  • ocp: symbolic optimal control problem built with @def.
  • e: expression corresponding to the body of the @init block.
  • lnum::Int: line number for error reporting.
  • line_str::String: line string for error reporting.

Returns

  • log_str::String: human-readable NamedTuple-like description of the specification.
  • code_expr::Expr: block of Julia code that builds and validates the initial guess when executed.