The @init macro

@init builds an initial guess for a problem defined with @def, from a small block of specifications:

ig = @init ocp begin
    a = 0.5                # alias
    x[1](t) := -1 + t      # first state component, function of time
    x₂(T) := X2            # second state component, samples on a time grid
    u(t) := a * t          # control, function of time
    tf := 1.0              # variable
end

This page explains how the macro works and why it is built this way. The user-facing documentation lives in OptimalControl; this page is for those who change the parser.

Division of work with CTModels

@init only rewrites the block. It turns the specifications into a NamedTuple and emits a call to CTModels.build_initial_guess, then CTModels.validate_initial_guess. Everything that depends on the problem — the names of the state, control and variable, their components, their dimensions, the time name — is checked by CTModels, or by code that runs after the model exists.

The reason is structural: @init ocp begin … end receives the symbol ocp, not the model. The model is a run-time value, and the macro expands before it is available. Unlike @def, which reads the declarations x ∈ R², state in its own block, @init cannot know at expansion time what x is, how many components it has or how they are named. Each design choice below follows from this.

Pipeline

@init ocp begin … end  [log = true]
  │
  ├─ init_fun(ocp, e, …)
  │    ├─ _collect_init_specs   expansion time: aliases, left-hand sides, cross-spec references
  │    │                        → keys::Vector{InitKey}, specs::Vector{Tuple}
  │    └─ code generation       one value per spec (__gen_spec_value), then the NamedTuple
  │
  └─ generated code (run time)
       ├─ values: functions t -> …, grids (T, X), constants
       ├─ NamedTuple: literal, or __init_namedtuple(ocp, …) if a key is indexed
       └─ CTModels.validate_initial_guess(ocp, CTModels.build_initial_guess(ocp, nt))

The functions are documented in the Initial Guess API page: CTParser._collect_init_specs, CTParser.init_fun, CTParser.__init_namedtuple.

The block

A statement is one of:

FormMeaning
a = expralias, substituted in the following statements
lhs := rhsconstant specification
lhs(arg) := rhsfunction of time, or time grid

Any other statement is a ParsingError (strict mode), and so is an alias whose left-hand side is not a name: x(t) = …, with a forgotten :, is not silently taken as an alias.

Aliases

An alias is substituted, textually, in every following statement before it is matched. This allows aliases of the time (s = t), aliases that depend on the time (phi = 2π * t; u(t) := sin(phi)), chains (a = t; s = a), grids (T = [0, 0.5, 1]) and indices (i = 2; x[i] := …). Aliases are not part of the initial guess.

Function of time, grid or constant

lhs := rhs is a constant. For lhs(arg) := rhs, the macro has to decide between a function of time and a time grid:

  • if arg appears in rhs, it is a function of time arg -> rhs, and the generated code checks that arg is the time name of the problem;
  • if it does not, the generated code compares arg with the time name: u(t) := 0.5 is a constant function, u(T) := U is the grid (T, U);
  • if arg is not a symbol (a literal array, possibly after alias substitution), it is a grid.

The time name is read from the model, so the comparison is made when the code runs. The test arg in rhs is made at expansion time with has.

Left-hand sides

Left-hand sideKey (CTParser.InitKey)Resolved by
x, u, tf (a block):xCTModels
x₁, q (a component label):x₁CTModels
x[1](:x, 1)__init_component_keys, at run time
x[1:2](:x, 1:2)__init_component_keys, at run time

A name is passed to CTModels as it is: CTModels knows whether it names a block or a component, and rejects an unknown name.

Indexed left-hand sides

@def accepts x[1](t), x[1:2](t) and v[2]; @init accepts the same forms (#434), so a component is written the same way in both blocks.

Resolution at run time. x[1] cannot be rewritten as x₁ at expansion time: the labels are not always x₁, x₂, … (with x = (r, v) ∈ R², state, x[1] is r), and x may be the state, the control or the variable. The generated code therefore calls CTParser.__init_component_keys, which reads the names and components from the model and returns the component names. CTModels then receives ordinary component keys, and its own checks apply unchanged.

Two code paths. Without an indexed key, the NamedTuple is written at expansion time, as before; with one, it is built at run time by CTParser.__init_namedtuple. The run-time path is not type-stable, which does not matter for code that runs once per solve. Keeping the literal path leaves the generated code of existing blocks unchanged.

Literal index. The index is an integer literal or a range a:b of integer literals, after alias substitution. x[end], x[1:2:3], x[i] with i not an alias, or x[[1, 3]] are rejected at expansion time: the key must be known then, to detect duplicates and to build cross-spec references.

Ranges. x[1:2](t) := f becomes one specification per component, t -> f(t)[k]; a constant c becomes c[k]. CTModels only knows block and component keys, and a range is neither. The function is evaluated once per component, which is negligible for an initial guess.

Time grid on a range. x[1:2](T) := X is rejected (PreconditionError) with a suggestion (one line per component, or x(T) := X). Splitting X would require guessing its layout — a matrix with times by rows or by columns, or a vector of vectors — that CTModels does not define for part of a block.

One-dimensional components. A scalar state x ∈ R, state has one component, named x. x[1] resolves to the block key x, consistent with @def where x[1] is an alias of x (1-D is a scalar, DIM1).

Cross-spec references

A specification can use an earlier one in its right-hand side:

q(t) := sin(t)
v(t) := 1 + q(t)        # v(t) := 1 + sin(t)
x[1](t) := t
x[2](t) := 2 * x[1](t)  # x[2](t) := 2 * t

After each specification, the pair (left-hand side, right-hand side) is stored, and substituted in the right-hand side of the following ones. The stored right-hand side is already substituted, so chains are resolved. Only right-hand sides are substituted, never left-hand sides.

The substitution is syntactic. A reference is replaced only when it is written as the earlier left-hand side: x[1](t) refers to x[1](t) := …, not to x₁(t) := …, and the other way round. Identifying them would require the labels, unknown at expansion time. An unresolved reference is left in the code and fails when it runs (UndefVarError, or a global variable of the same name). The rule for users is: refer to a component as you defined it.

Errors

ErrorDetectedException
unrecognised statement, alias with a non-name left-hand sideexpansionParsingError
unsupported left-hand side or indexexpansionParsingError
same left-hand side twice (q(t) and q, x[1] twice)expansionParsingError
wrong time name (u(s) := s when the time is t)run timeIncorrectArgument
unknown name in y[1], index out of rangerun timeIncorrectArgument
constant of the wrong length on a rangerun timeIncorrectArgument
two keys for one component (x[1] and x₁)run timePreconditionError
time grid on a rangerun timePreconditionError
block and component (x and x[1]), dimensions, unknown keyrun timeIncorrectArgument (CTModels)

Every error is a typed CTBase exception (EXC1). The type follows the choice rule: an error about one value is an IncorrectArgument (with got and expected), an error about two things together — two specifications of one component, a range together with a grid — is a PreconditionError (with reason). CTModels types its own duplicates as IncorrectArgument; @init follows the rule rather than that precedent.

How expansion-time errors reach the user. While it reads the block, _collect_init_specs throws a ParsingError with a message and a suggestion. The macro catches only ParsingError, and re-emits it with __throw, which adds the line of the block and returns a throw expression: as in @def, the error is detected when the macro expands and thrown when the generated code runs. Any other exception raised while reading the block is a bug of the parser, and propagates unchanged instead of being shown to the user as a syntax error.

Duplicates are detected at the earliest point possible: the same key twice is visible at expansion time; two keys naming one component only once the model resolves them.

Generated code and hygiene

The generated code refers to CTModels and CTBase by module object (FUN, ERR), never by name, and the helpers of this file (__init_namedtuple) are interpolated as function objects. It therefore runs in any caller module, including one where only the macros are bound (import OptimalControl) or where CTModels names something else (#356, tested in test/test_hygiene.jl).

Choices considered and rejected

AlternativeWhy it was not kept
rewrite x[1] as x₁ at expansion timewrong for named components (x = (r, v)), and x may be the control or the variable
let CTModels accept indexed keysNamedTuple keys are symbols; the index would have to be encoded in a name and CTModels changed, for no gain
identify x[1](t) and x₁(t) in cross-spec referencesneeds the labels at expansion time; possible only with a run-time lookup of earlier specs
split a time grid on a rangethe layout of the data would have to be guessed
always build the NamedTuple at run timechanges the code generated for every existing block, for no benefit

Towards a shared grammar

@def and @init parse the same surface syntax with two grammars, which is how #434 arose. The IR planned in #289 can bring them together (comment): @init would reuse the surface normalisation and the grammar of @def, and resolve its keys with the symbol table of @def, kept in the model. __init_component_keys is written as the first piece of that resolution. Making x[1](t) and x₁(t) equivalent in cross-spec references would in addition require a run-time lookup of earlier specifications instead of a textual substitution.