ExaModels

ExaModels.ExaModels — Module
ExaModels

An algebraic modeling and automatic differentiation tool in Julia, specialized for SIMD-parallel evaluation of nonlinear programs on CPUs and GPUs.

Computation graph

Expressions are represented as trees of AbstractNode subtypes:

  • Var / DataIndexed — decision variables and data fields
  • Node1 / Node2 — unary / binary operations
  • Constant{T} — compile-time scalar constant; the value T is stored as a type parameter so it is visible to the compiler and to juliac --trim=safe without any runtime storage.
  • SumNode / ProdNode — reduction over a tuple of nodes

Algebraic simplification

Operations involving Constant{T} are simplified at model-construction time: x * Constant(1) → x, x ^ Constant(2) → abs2(x), etc. (see specialization.jl). Combined Constant OP Constant expressions are folded to a new Constant via the rules in register.jl.

For more information, please visit https://github.com/madsuite-org/ExaModels.jl

source
ExaModels.AbstractArgNode — Type
AbstractArgNode

Root type for the symbolic argument expression tree. Nodes are built by ordinary Julia operations on an ArgSource (arg.N, length(arg.v), arg.nh * zeros(10), …) and are resolved to concrete values by instantiate. Ranges and type-directed constructors on arguments (1:arg.N, zeros(T, arg.N), floor(Int, ·), convert(T, ·)) are defined by ExaModelsCompiler, which needs Julia 1.12.

source
ExaModels.AbstractNode — Type
AbstractNode

Root abstract type for all nodes in the ExaModels symbolic computation graph. Every node is callable as node(i, x, θ) and returns the scalar value of the expression at the current evaluation point, where i is the iteration index, x the primal variable vector, and θ the parameter vector.

source
ExaModels.AdjointNode1 — Type
AdjointNode1{F, T, I} <: AbstractAdjointNode

Gradient-pass node for a unary operation F. Stores the primal value and the partial derivative alongside the child so a single forward sweep simultaneously computes both.

Fields

  • x::T: primal value F(inner.x)
  • y::T: derivative F'(inner.x)
  • inner::I: child node
source
ExaModels.AdjointNode2 — Type
AdjointNode2{F, T, I1, I2} <: AbstractAdjointNode

Gradient-pass node for a binary operation F. Stores the primal value and both partial derivatives.

Fields

  • x::T: primal value F(inner1.x, inner2.x)
  • y1::T: partial derivative w.r.t. first argument
  • y2::T: partial derivative w.r.t. second argument
  • inner1::I1: left child
  • inner2::I2: right child
source
ExaModels.AdjointNodeSource — Type
AdjointNodeSource{VT}

Factory for AdjointNodeVar leaves. Indexing with i returns AdjointNodeVar(i, inner[i]), seeding the gradient-pass tree with the current primal value.

Fields

  • inner::VT: primal variable vector (or nothing for a zero-valued seed)
source
ExaModels.AdjointNodeSubexpr — Type
AdjointNodeSubexpr{I, T} <: AbstractAdjointNode

Gradient-pass leaf for a buffered subexpression element.

Fields

  • i::I: θ-slot index of the subexpression element (also the slot in the adjoint buffer)
  • x::T: buffered primal value θ[i]
source
ExaModels.AdjointNodeVar — Type
AdjointNodeVar{I, T} <: AbstractAdjointNode

Leaf node in the gradient-pass tree corresponding to a decision variable.

Fields

  • i::I: variable index
  • x::T: primal value x[i] at the current evaluation point
source
ExaModels.AdjointNull — Type
AdjointNull{V} <: AbstractAdjointNode

Leaf node in the first-order adjoint tree representing a constant (zero contribution to the gradient). Carries the primal value x so that upstream nodes can read it without recomputation.

source
ExaModels.ArgCall — Type
ArgCall{F, A} <: AbstractArgNode

A deferred call f(args...) of arbitrary arity. ArgNode1 / ArgNode2 cover the operator cases that users write and print nicely; ArgCall is what the model-building internals use when an existing helper simply needs to run later against instantiated inputs.

args is always a Tuple, and is written out at every call site. A varargs constructor would be shadowed by the default two-field one for the arity-1 case — ArgCall(f, x) would quietly store x itself rather than (x,) — so there deliberately isn't one.

source
ExaModels.ArgIndexed — Type
ArgIndexed{I, J} <: AbstractArgNode

The lookup inner.J (or inner[J]) where inner is an ArgSource or another ArgIndexed. J is a type parameter, so getproperty / getindex resolves at compile time — the same encoding DataIndexed uses.

source
ExaModels.ArgLeaf — Type
ArgLeaf{A} <: AbstractNode

A scalar drawn from the model arguments, sitting inside the expression graph — h = 1 / (arg.N + 1) used as a coefficient, or a variable offset that is not known until the core is instantiated.

It borrows DataIndexed's handling without being the same thing. A DataIndexed is a parameter of the pattern — its value arrives on every kernel iteration, and the tree is complete without it. An ArgLeaf is a placeholder that will be gone: it is substituted once at instantiation, leaving the plain Real a core built with concrete sizes would have had.

What the two share is that neither has a value while sparsity is being discovered. That discovery evaluates the graph at Identity against a NaNSource, and structure does not depend on values, so both answer NaN there — which is why this leaf needs no separate treatment in the probe.

Wrapping happens automatically: an AbstractArgNode combined with a graph node through any registered operation becomes an ArgLeaf child of the resulting Node2. Arithmetic between argument nodes stays in the argument world and never reaches the graph.

source
ExaModels.ArgNode1 — Type
ArgNode1{F, I} <: AbstractArgNode

A unary operation f(inner) deferred until instantiation. f is stored as a field; for the singleton function types this always holds in practice, that field is zero-size and the call is statically resolved.

source
ExaModels.ArgNode2 — Type
ArgNode2{F, I1, I2} <: AbstractArgNode

A binary operation f(inner1, inner2) deferred until instantiation. Either child may be a plain value (a Number, an AbstractArray, …) so that mixed expressions such as arg.nh * zeros(10) are representable.

source
ExaModels.ArgSource — Type
ArgSource <: AbstractArgNode

Sentinel node standing for the whole argument object supplied at instantiation time. Field access or indexing returns an ArgIndexed node.

Create one where you need it and give it whatever name reads best — it carries no state, so every instance is interchangeable:

arg = ArgSource()
@add_var(c, x, arg.N; start = arg.x0)
source
ExaModels.BufferedExpression — Type
BufferedExpression

A subexpression created by add_expr / @add_expr with buffered = true. Unlike Expression, indexing does NOT splice the subexpression tree into the enclosing objective or constraint: each element is evaluated once per model evaluation into a dedicated θ slot, and consumers reference the slot through a shallow SubexprNode leaf. This keeps compilation cost additive in the nesting depth of expression trees.

Supports the NLPModels evaluation API through second order, including hprod!, on the host and on KernelAbstractions backends; jprod_nln! and jtprod_nln! are host-only for models with buffered subexpressions. Not compatible with oracles or ExaModel(c; prod = true).

source
ExaModels.CompView — Type
CompView{V}

A segment's nonzero compressor on a device: a slice of the layout's flat compressor vector, callable like a Compressor (comp(n)), for the same reason as SegView.

source
ExaModels.CompressedNLPModel — Type
CompressedNLPModel

A wrapper around an AbstractNLPModel that sums duplicate (row, col) entries in the sparse Jacobian and Hessian.

Duplicates arise when multiple constraint or objective patterns contribute to the same matrix position (e.g. after augmentation via add_con!). CompressedNLPModel detects them once at construction and accumulates them on every subsequent jac_coord! / hess_coord! call, so callers receive a matrix with no repeated coordinates.

Construct via CompressedNLPModel(m).

source
ExaModels.CompressedNLPModel — Method
CompressedNLPModel(m)

Wraps m in a CompressedNLPModel.

Queries the full Jacobian and Hessian sparsity patterns from m, identifies duplicate (row, col) pairs, builds pointer arrays for O(nnz) accumulation on subsequent jac_coord! / hess_coord! calls.

source
ExaModels.Compressor — Type
Compressor{I}

Data structure for the sparse index

Fields:

  • inner::I: stores the sparse index as a tuple form
source
ExaModels.ConAugPair — Type
ConAugPair{C, P}

Carries a constraint reference (con) alongside its Pair(idx, expr) during the probe phase of add_con!(core, g[i] += expr for ...). The replace_T method unwraps to the inner Pair, so SIMDFunction stores a plain Pair and all existing offset0 dispatches remain unchanged.

source
ExaModels.Constant — Type
Constant{T} <: AbstractNode

A compile-time constant node whose value T is embedded as a type parameter.

Design rationale

Because T is a type parameter rather than a struct field, the Julia compiler (and juliac --trim=safe) can propagate T concretely through every downstream Node1 / Node2 type, making the entire computation graph type-stable with no runtime storage for the constant.

Construction

Constant(2)      # → Constant{2}()
Constant(3.14)   # → Constant{3.14}()

Evaluation

c = Constant(42)
c(i, x, θ)  # → 42

Algebraic simplification

specialization.jl registers identities for Constant combined with AbstractNode operands:

expressionsimplification
x + Constant(0)x
x * Constant(1)x
x / Constant(1)x
x ^ Constant(0)Constant(1)
x ^ Constant(1)x
x ^ Constant(2)Node1(abs2, x)
x ^ Constant(-1)inv(x)
Constant(0) * xConstant(0)
Constant(0) / xConstant(0)

These rules fire at model-construction time (when the ExaCore is being built), collapsing trivial branches before the graph is finalized.

source
ExaModels.Constraint — Type
Constraint

A block of constraints added to an ExaCore via add_con / @add_con. Each element of the iterator corresponds to one constraint row. Row k of this block maps to global constraint index offset + k. Dual solution values can be retrieved with multipliers. An optional tag field carries user-defined metadata.

source
ExaModels.ConstraintAugmentation — Type
ConstraintAugmentation

An augmentation layer added to an existing Constraint via add_con! / @add_con!. Each element of the iterator yields an idx => expr pair: expr is accumulated into the constraint row identified by idx at evaluation time. Multiple ConstraintAugmentation objects can be stacked on the same base constraint to aggregate contributions from several data sources (e.g. summing arc flows into nodal balance constraints). An optional tag field carries user-defined metadata.

source
ExaModels.ConstraintSlot — Type
ConstraintSlot{C, I}

A lightweight handle returned by getindex on a Constraint or ConstraintAugmentation. When added to an expression node via +, it produces a Pair(idx, expr) suitable for constraint augmentation.

This enables the g[idx] += expr for ... syntactic sugar:

c, _ = add_con!(c, g[i] += sin(x[i]) for i in 1:N)
source
ExaModels.DataIndexed — Type
DataIndexed{I, J} <: AbstractNode

A node representing the lookup inner.J (or inner[J]) where inner is a DataSource or another DataIndexed. The field/index J is encoded as a type parameter so that getfield / getindex can be resolved at compile time.

Constructed implicitly via getproperty / getindex on a DataSource.

source
ExaModels.DataSource — Type
DataSource <: AbstractNode

Sentinel node used as the root of a parameter (data) array. Indexing or accessing fields on a DataSource returns a DataIndexed node that encodes the access path as nested type parameters for zero-overhead data lookup.

source
ExaModels.DeviceSegItr — Type
DeviceSegItr{T, D}

Device layout of a SegmentedItr with several segments: offsets and steps once per segment (seg_*), the hoisted leaves and compressors of all segments in flat vectors (iv, fv, comp1, comp2; K, S, N1, N2 entries per segment), the original iterator elements of all segments concatenated (d), and the cumulative row counts (offs). getindex assembles the MergedRow on the fly, with views into the flat vectors, so a row costs its element and nothing else on the device.

source
ExaModels.EachScenario — Type
EachScenario

Marker type used with add_var, add_par, and add_con to indicate that the declaration is replicated for each scenario in a two-stage stochastic program.

Pass EachScenario() as the second positional argument (before dimensions) to create per-scenario (recourse) variables, parameters, or constraints. Omitting it creates first-stage (design) components shared across all scenarios.

Example

core = TwoStageExaCore(3)                          # 3 scenarios
c, d = add_var(core, 2)                            # 2 design variables (shared)
c, v = add_var(core, EachScenario(), 4)            # 4 recourse variables per scenario
c, g = add_con(core, EachScenario(), v[i] for i in 1:4)  # per-scenario constraints
source
ExaModels.ExaModelWithOracle — Type
ExaModelWithOracle

An AbstractExaModel that augments an ExaModel's SIMD symbolic constraints with one or more VectorNonlinearOracle callback blocks. Constructed automatically by ExaModel(core) when core has registered oracles.

The constraint ordering is:

  1. SIMD symbolic constraints (indices 1 : nsimdcon)
  2. Oracle blocks, in registration order

and analogously for the Jacobian and Hessian nonzero arrays.

source
ExaModels.Expression — Type
Expression

A subexpression created by add_expr / @add_expr. When indexed (e.g. s[i]), the expression is substituted directly into the enclosing objective or constraint — no auxiliary variables or equality constraints are introduced, and the tree is spliced at every use site. Use Expression to share common sub-expressions across multiple objectives or constraints; for deeply nested or widely shared ones see BufferedExpression. An optional tag field carries user-defined metadata.

source
ExaModels.FvRef — Type
FvRef <: AbstractNode

Reads the k-th hoisted Float leaf out of a MergedRow element. The values live in the segment (loop-invariant, one copy per source block), not in θ, so no aliasing with the output vectors blocks LLVM from hoisting the loads out of the row loop.

source
ExaModels.GradTarget — Type
GradTarget{Y, A}

Carrier threaded through drpass in place of the plain gradient vector when the model has buffered subexpressions. Variable leaves accumulate into the dense gradient y; subexpression leaves accumulate into the adjoint buffer abuf (θ-length), which later seeds the stages' own reverse passes.

A dedicated struct (rather than a tuple) is used because drpass's AdjointNodeVar leaf method indexes its target with y[d.i], and a tuple would accept that indexing silently.

source
ExaModels.IvRef — Type
IvRef <: AbstractNode

Reads the k-th hoisted Integer leaf out of a MergedRow element. Available in structure passes (which carry θ = NaNSource), since the value comes from the element, not from θ.

source
ExaModels.MergedRow — Type
MergedRow{T, IV, FV, D, C1, C2}

One row of a merged family: global row offset o0, Jacobian/Hessian nonzero bases o1/o2, the hoisted Integer leaves iv, the hoisted Float leaves fv (of type T; both shared by every row of the segment), the original iterator element d, and the source block's own nonzero compressors comp1/comp2 (shared by every row of the segment). The derivative passes read the compressors from the row (_comp1/_comp2), never from the family's SIMDFunction, so each segment keeps the sparsity its plain block had. On the host iv/fv are tuples and the compressors Compressors; on a device they are views into the layout's arrays (SegView, CompView), since a dynamic index into a tuple held by value in a kernel stages the tuple into per-thread local memory.

source
ExaModels.MergedRows — Type
MergedRows{K, S, T, D, RF, C1, C2}

Materialized merged iterator, used on the host for pair-headed families (their row targets are data-driven, not affine) and, on device backends, as the element array every merged block is finalized into. Growing a family copies the row vector (_merged_append_itr), so earlier cores and models keep the rows they had.

source
ExaModels.Node1 — Type
Node1{F, I} <: AbstractNode

An interior node representing a unary operation F applied to one child node.

Evaluated as F(inner(i, x, θ)).

Fields

  • inner::I: child node
source
ExaModels.Node2 — Type
Node2{F, I1, I2} <: AbstractNode

An interior node representing a binary operation F applied to two children. Either child can be a node or a plain scalar (e.g. Real), allowing numeric coefficients to be stored directly without wrapping in Constant.

Evaluated as F(inner1(i, x, θ), inner2(i, x, θ)).

Fields

  • inner1::I1: left child
  • inner2::I2: right child
source
ExaModels.Null — Type
Null{T} <: AbstractNode

A leaf node that always evaluates to a fixed scalar. The value is stored in a field (as opposed to Constant, which encodes the value as a type parameter). Used when the constant is not known at compile time.

Null() creates a zero-valued node; Null(v) creates a node that returns T(v) where T is the element type of the primal vector.

source
ExaModels.NullRef — Type
NullRef <: AbstractNode

Reads the k-th hoisted Float leaf the way a Null value node would: a plain value under a value source, AdjointNull/SecondAdjointNull under the adjoint sources. A Null leaf is hoisted into this node rather than an FvRef because the two differ in adjoint shape under *: Null(c) * x[i] builds SecondAdjointNode2{*}(SecondAdjointNull, Var), which hrpass0 walks and writes one Hessian slot for, while a plain value builds SecondAdjointNode1{FirstFixed{*}}(Var), whose linear shortcut writes none. The source block's compressors and steps come from its own tree, so the hoisted tree must build the same adjoint nodes, or a slot is accounted and never written.

source
ExaModels.OracleEvaluator — Type
OracleEvaluator

Encapsulates callbacks that augment a set of pre-existing constraint rows (declared via add_con) with values from an opaque function. Registered via add_eval / @add_con! (oracle form).

Unlike VectorNonlinearOracle, an OracleEvaluator does not introduce new constraint rows; it fills rows that already exist.

Callbacks operate on local concatenated vectors:

  • f!(res, x_local): res[1:ncon_total] = f(x_local[1:nvar_total])
  • jac!(vals, x_local): fills vals[1:nnzj] with Jacobian values
  • hess!(vals, x_local, y_local):fills vals[1:nnzh] with Lagrangian Hessian values
  • jvp!(Jv, x_local, v_local): Jv[1:ncon_total] = J(x) * v_local
  • vjp!(Jtv, x_local, w_local): Jtv[1:nvar_total] = J(x)' * w_local
  • hvp!(Hv, x_local, w_local, v_local): Hv[1:nvar_total] = (∑ wᵢ ∇²gᵢ) * v_local
source
ExaModels.Parameter — Type
Parameter

A handle to a block of model parameters added to an ExaCore via add_par / @add_par. Parameter values can be updated at any time with set_value! without rebuilding the model. Use indexing (e.g. θ[i]) to embed parameter values in expressions. An optional tag field carries user-defined metadata.

source
ExaModels.SIMDFunction — Method
SIMDFunction(gen::Base.Generator, o0 = 0, o1 = 0, o2 = 0)

Returns a SIMDFunction using the gen.

Arguments:

  • gen: an iterable function specified in Base.Generator format
  • o0: offset for the function evaluation
  • o1: offset for the derivative evaluation
  • o2: offset for the second-order derivative evaluation
source
ExaModels.ScalarNonlinearOracle — Type
ScalarNonlinearOracle

A scalar objective oracle: adds f(x) to the objective via callbacks. No output variables, no constraints, no Jacobian — only gradient and optionally Hessian-vector product.

Callbacks:

  • f(x) -> Float64: objective value
  • grad!(g, x): fills g[1:nvar] = ∇f(x)
  • hvp!(Hv, x, v) = nothing: fills Hv[1:nvar] = ∇²f(x)·v (optional; L-BFGS if absent)
  • hess!(vals, x) = nothing: fills vals[1:nnzh] = ∇²f(x) at the declared hess_rows/hess_cols slots (optional)

Second-order use: hess_rows/hess_cols declare the (lower-triangular, 1-based) Hessian sparsity. hprod! uses hvp! (an oracle without it adds no hprod! term); hess_coord! uses hess! when it is given and otherwise recovers the declared entries column by column from hvp!. That fallback costs one hvp! call per distinct column and assumes every (row, col) coordinate appears once in the pattern: a repeated coordinate receives the whole assembled entry in each of its slots, and the consumer then sums them. A pattern built blockwise (one dense block per element) repeats coordinates by construction, so such oracles supply hess!. With hvp! and no declared sparsity, a dense lower-triangular pattern is assumed. With neither callback, the oracle is first-order only.

Register via objective(core, oracle).

source
ExaModels.SecondAdjointNode1 — Type
SecondAdjointNode1{F, T, I} <: AbstractSecondAdjointNode

Hessian-pass node for a unary operation F. A single forward sweep stores the primal value, first derivative, and second derivative needed for the reverse Hessian accumulation.

Fields

  • x::T: primal value F(inner.x)
  • y::T: first derivative F'(inner.x)
  • h::T: second derivative F''(inner.x)
  • inner::I: child node
source
ExaModels.SecondAdjointNode2 — Type
SecondAdjointNode2{F, T, I1, I2} <: AbstractSecondAdjointNode

Hessian-pass node for a binary operation F.

Fields

  • x::T: primal value F(inner1.x, inner2.x)
  • y1::T: partial derivative w.r.t. first argument
  • y2::T: partial derivative w.r.t. second argument
  • h11::T: second partial w.r.t. first argument
  • h12::T: mixed second partial
  • h22::T: second partial w.r.t. second argument
  • inner1::I1: left child
  • inner2::I2: right child
source
ExaModels.SecondAdjointNodeSubexpr — Type
SecondAdjointNodeSubexpr{I, T} <: AbstractSecondAdjointNode

Hessian-pass leaf for a buffered subexpression element, treated as an extra coordinate of the extended (x, s) space — the second-order analogue of AdjointNodeSubexpr. Structure passes mark its coordinate with a negated θ-slot; build-time elimination composes the entries with the stage Jacobians and stage Hessians.

source
ExaModels.SecondAdjointNodeVar — Type
SecondAdjointNodeVar{I, T} <: AbstractSecondAdjointNode

Leaf node in the Hessian-pass tree corresponding to a decision variable.

Fields

  • i::I: variable index
  • x::T: primal value x[i] at the current evaluation point
source
ExaModels.SecondAdjointNull — Type
SecondAdjointNull{V} <: AbstractSecondAdjointNode

Leaf node in the second-order adjoint tree representing a constant (zero contribution to both the gradient and the Hessian). Carries the primal value x for upstream consumption.

source
ExaModels.SegView — Type
SegView{V}

A segment's hoisted leaves on a device: a slice (base + 1 : base + K) of the layout's flat leaf vector v, read by IvRef/FvRef with view[k]. A row holds this instead of a copy of the tuple: a dynamic index into a tuple held by value in a kernel stages the whole tuple into per-thread local memory (PTX __local_depot of 1016 bytes, 85 ld.local per row, for the COPS dirichlet PDE block with K = 94, whose Jacobian kernel then ran 4x slower than main's), while a read through the view is one global load at an address uniform across the segment's threads.

source
ExaModels.SegmentedItr — Type
SegmentedItr{K, S, T, D, I, RF, C1, C2}

Lazy merged iterator for affine-offset families: one MergedSeg per source block (holding the iterator _adapt_gen produced for it), rows materialized on demand. rep is the first block's SIMDFunction, the layout key for later arrivals. Appending copies the segment containers (_merged_append_itr) so earlier cores and models keep the iterator they had; the copy changes no types, so the core's type is stable as a family grows.

source
ExaModels.SubexprHess — Type
SubexprHess{T}

Build-time artifact for Hessian evaluation with buffered subexpressions. hess_ext holds the extended-space entries (consumer segment first, then one segment per stage); C holds the merged intermediate cross values. All program slices are per-stage, newest-first, aligned with the stage tuple.

source
ExaModels.SubexprJac — Type
SubexprJac{T}

Build-time artifact holding the buffers, index maps, and final COO structure for Jacobian evaluation with buffered subexpressions.

Value evaluation (see _jac_coord_subexpr!):

  1. per-stage jrpass fills stage_ext (extended-space stage entries);
  2. res[dst] = stage_ext[src] (direct) and res[dst] = stage_ext[a] * res[b] (chained) resolve every stage entry to an x-column, in emission order (b < dst always, so one sequential sweep is valid);
  3. consumer jrpass fills cons_ext;
  4. jac[dst] = cons_ext[src] (direct) and jac[dst] = cons_ext[a] * res[b] (composed) produce the final COO values. Duplicate (row, col) pairs are summed by the COO convention.
source
ExaModels.SubexprNode — Type
SubexprNode{I} <: AbstractNode

Leaf node referencing the buffered value of a subexpression element, stored at θ[i]. In primal mode it reads the buffer directly; in first-order adjoint mode it produces an AdjointNodeSubexpr leaf so the reverse pass can accumulate the adjoint into the subexpression adjoint buffer, from which the subexpression's own reverse pass is later seeded.

source
ExaModels.SubexprStage — Type
SubexprStage{F, I}

One buffered-subexpression evaluation stage. The forward pass writes θ[offset + k] = f(itr[k], x, θ) for each element k; the reverse pass re-evaluates the (shallow) stage tree in adjoint mode and propagates the buffered adjoint seed down to variable leaves and deeper stages.

Fields

  • f::F: the stage SIMDFunction
  • itr::I: the collected iterator
  • offset::Int: θ offset; values live at θ[offset+1 : offset+length(itr)]
source
ExaModels.SubexprSumStage — Type
SubexprSumStage{VT, VI}

A buffered sum stage, one per add_expr! call: slot j holds a constant-coefficient linear combination

θ[offset + j] = init[j] + Σₘ w[m] · source(m)    for m in ptr[j]:ptr[j+1]-1

where source(m) is x[src[m]] when src[m] > 0 and θ[-src[m]] (an older buffered slot) when src[m] < 0. Terms are stored CSR-style by destination slot, so evaluation is one loop over data: no expression tree is traced and the stage is one concrete type regardless of the number of terms, which is what keeps a slot that sums thousands of elements out of every kernel type.

Derivatives need no kernels either: the stage's one-level Jacobian is the constant w, so the build-time elimination consumes it like any other stage, and the μ·∇v∇vᵀ curvature of each slot is accumulated in x-space from the slot's resolved gradient, with one Hessian-index table per distinct x-support — see the rk_*/pat_* fields of SubexprHess.

Fields

  • offset::Int: θ offset; slot j lives at θ[offset + j]
  • n::Int: number of slots
  • init::VT: length-n constant parts of the terms
  • ptr::VI: length n + 1; slot j's terms are ptr[j]:ptr[j+1]-1
  • src::VI: signed sources (> 0 variable index, < 0 negated θ slot)
  • w::VT: constant term weights
source
ExaModels.SumNode — Type
SumNode{I} <: AbstractNode

A node representing the sum of a tuple of child nodes.

Constructed by exa_sum. Within @add_obj, @add_con, and @add_expr macros, sum(body for k in range) is automatically rewritten to exa_sum(k -> body, Val(range)) with the Val hoisted outside the generator closure for type stability under juliac --trim=safe.

In adjoint / second-adjoint mode the children are evaluated and folded via reduce(+, …) (or reduce(*, …) for ProdNode), reusing the existing registered + / * dispatch. No dedicated adjoint node types are needed.

source
ExaModels.TimedNLPModel — Type
TimedNLPModel

A transparent wrapper around any AbstractNLPModel that records wall-clock timings and call counts for each NLP callback (obj, cons!, grad!, jac_coord!, hess_coord!, jac_structure!, hess_structure!).

Statistics accumulate in the stats field and can be printed with print(m). Construct via TimedNLPModel(m).

source
ExaModels.TwoStageExaCore — Method
TwoStageExaCore(nscen; backend = nothing, kwargs...)

Create an ExaCore for building two-stage stochastic programs with nscen scenarios.

Use add_var, add_par, and add_con with EachScenario() to declare per-scenario components, or without it for first-stage (design) components.

Example

core = TwoStageExaCore(5)                    # 5 scenarios
c, d = add_var(core, 3)                      # 3 design variables
c, v = add_var(c, EachScenario(), 2)         # 2 recourse variables per scenario
model = ExaModel(c)
source
ExaModels.Var — Type
Var{I} <: AbstractNode

A leaf node representing the i-th decision variable.

When evaluated as v(i, x, θ), returns x[v.i] (or x[v.i(i,x,θ)] when the index is itself a node).

source
ExaModels.VarSource — Type
VarSource <: AbstractNode

Sentinel node used as the root of a variable array. Indexing a VarSource with an integer i returns Var(i), building the leaf node that refers to the i-th decision variable.

source
ExaModels.VectorNonlinearOracle — Type
VectorNonlinearOracle

Encapsulates a user-supplied nonlinear constraint block that can be registered into an ExaCore with constraint. The block is characterised by:

  • nvar: number of decision variables (= total problem nvar)
  • ncon: number of constraints this oracle contributes
  • nnzj: number of Jacobian nonzeros (0 if matrix-free only; dense structure declared automatically)
  • nnzh: number of Lagrangian Hessian nonzeros (0 to use L-BFGS / finite differences, or matrix-free)
  • jac_rows, jac_cols: sparsity pattern of the Jacobian (1-based, length nnzj)
  • hess_rows, hess_cols: sparsity pattern of the (lower-triangular) Hessian (1-based, length nnzh)
  • lcon, ucon: constraint lower/upper bounds (length ncon)
  • f!: f!(c, x) — writes residuals into c[1:ncon]
  • jac!: jac!(vals, x) — writes Jacobian values into vals[1:nnzj] (nothing if matrix-free only)
  • hess!: hess!(vals, x, y) — writes Hessian values into vals[1:nnzh] (nothing if matrix-free only)
  • jvp!: jvp!(Jv, x, v) — Jacobian-vector product: Jv[1:ncon] = J(x) * v (nothing if explicit only)
  • vjp!: vjp!(Jtv, x, w) — transpose Jacobian-vector product: Jtv[1:nvar] = J(x)' * w (nothing if explicit only)
  • hvp!: hvp!(Hv, x, w, v) — Hessian-vector product: Hv[1:nvar] = (Σ wᵢ ∇²fᵢ) * v (nothing if explicit only)
  • adapt: Val(false) (default) — callbacks receive arrays as-is (device arrays on GPU backends). Val(true) — arrays are copied to CPU (Array) before every call. Use Val(true) when your callbacks are CPU-only; use Val(false) when they are GPU-capable.
source
ExaModels.WrapperNLPModel — Type
WrapperNLPModel

An NLPModels.AbstractNLPModel wrapper that bridges a model whose internal array type differs from the host array type (e.g. a GPU-backed ExaModel wrapped for a CPU-only solver). All NLP callbacks are forwarded to the inner model through intermediate copy buffers.

Use WrapperNLPModel(m) or WrapperNLPModel(VT, m) rather than constructing this struct directly.

source
ExaModels.WrapperNLPModel — Method
WrapperNLPModel(m)

Returns a WrapperNLPModel{Float64,Vector{Float64}} wrapping m, forwarding all NLP callbacks through Float64 CPU copy buffers.

source
ExaModels._amul — Method
_amul(a, b)

Adjoint-propagation product: a * b, except a zero adjoint a annihilates b entirely (branchless select, so _amul(0, Inf) == 0). Keeps reverse-mode sweeps finite on subtrees that a zero adjoint has switched off — e.g. the inactive branch of a bselect blend whose local partials are infinite — without perturbing any live path.

source
ExaModels._anyarg — Method
_anyarg(xs...)

Val(true) if any of xs is an AbstractArgNode, Val(false) otherwise — used to pick between the eager and the deferred form of a build-time operation.

Resolved entirely by dispatch: each method returns a literal Val, and the recursion is over the argument list, so the answer is part of the method signature rather than a Bool that inference has to fold. That matters for juliac --trim=safe, where a Val(::Bool) built from a runtime value would leave the choice — and both branches' return types — unresolved.

source
ExaModels._hess_reconstruct_via_hvp! — Function
_hess_reconstruct_via_hvp!(oracle, x, y, hess, cache, backend=nothing)

Reconstruct the lower-triangular Hessian coordinate values using nvar calls to oracle.hvp!. All buffers are preallocated in cache.

source
ExaModels._jac_reconstruct_via_jvp! — Function
_jac_reconstruct_via_jvp!(oracle, x, jac, cache, backend=nothing)

Reconstruct the Jacobian coordinate values using nvar calls to oracle.jvp!. All buffers are preallocated in cache. For gpu=false on a GPU backend, CPU scratch arrays are used for the callback and results are copied to device.

source
ExaModels._nan_outside — Method
_nan_outside(f)

The function ExaModels calls to evaluate f on numbers. For a function whose real domain is restricted, this returns NaN outside the domain instead of throwing DomainError, which is what the same call does in a GPU kernel. A solver can then reject a trial point that leaves the domain. Any other function is returned unchanged.

source
ExaModels._needs_overload — Method
_needs_overload(f, types)

Return true when ExaModels should add a method for f with the given argument types.

Plain hasmethod is too conservative for Base generics such as max(x,y) = ifelse(isless(x,y),y,x): those definitions match any AbstractNode argument, so hasmethod returns true and would prevent the ExaModels-specific overload from being added. We instead check the owner module of the matching method and only skip when ExaModels already owns it.

source
ExaModels._with_args — Method
_with_args(core, ::Val{N})

The core alone when N == 0, or the core followed by N distinct ArgSource placeholders:

core                = ExaCore()                   # Val(0) — unchanged behaviour
core, N             = ExaCore(nargs = Val(1))
core, N, data       = ExaCore(nargs = Val(2))

N == 0 is the "not a recipe" case, so a separate boolean would say nothing this does not. The placeholders are numbered in the order returned, and ExaModel(core, a...) consumes the concrete objects in that same order. ntuple over a Val keeps the arity in the type, so how many values come back is known statically and destructuring stays inferable.

source
ExaModels.add_con! — Method
add_con!(core, c1, generator; tag = nothing)

Augments the existing constraint c1 by adding extra expression terms to a subset of its rows, and returns (core, ConstraintAugmentation).

This is the primary mechanism for building constraints that aggregate contributions from multiple data sources — for example, nodal power-balance constraints that sum flows over all arcs incident to each bus. Each call to add_con! appends one new "augmentation layer"; multiple layers for the same base constraint are summed at evaluation time.

The bounds (lcon/ucon) remain those set on the original c1 and cannot be changed via add_con!.

Arguments

  • core: The ExaCore to modify.
  • c1: The base Constraint (or a previous ConstraintAugmentation) whose rows are being augmented.
  • generator: A Base.Generator yielding idx => expr pairs, where
    • idx is an index (or tuple of indices) into c1 identifying which constraint row receives the term, and
    • expr is the scalar expression to add to that row.

Notes

  • The index idx must be a valid index of c1's iterator (e.g. an integer for a 1-D constraint, or a tuple (i, j) for a multi-dimensional one).
  • One generator element maps to one non-zero Jacobian row; elements with the same idx are accumulated.
  • The iterator of the generator becomes the SIMD work set, so performance is best when it is a contiguous collection (array, range, or product iterator).

Example

Single-index augmentation — add sin(x[i+1]) to constraint rows 4, 5, 6:

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10);

julia> c, c1 = add_con(c, x[i] + x[i+1] for i=1:9; lcon = -1, ucon = (1+i for i=1:9));

julia> c, c2 = add_con!(c, c1, i => sin(x[i+1]) for i=4:6);

julia> c2
Constraint Augmentation

  g♭ ≤ (...) + ∑_{i ∈ I} h(x,i) ≤ g♯

  h(x,i) = sin(x[i.1 + 1])

  where |I| = 3

Multi-source augmentation (typical power-flow use case) — accumulate arc flows into bus balance constraints:

c, bus = add_con(c, pd[b.i] + gs[b.i]*vm[b.i]^2 for b in data.bus)   # one row per bus
add_con!(c, bus, arc.bus => p[arc.i] for arc in data.arc)              # add arc flows
add_con!(c, bus, gen.bus => -pg[gen.i] for gen in data.gen)            # subtract generation
source
ExaModels.add_con! — Method
add_con!(core::ExaCore, gen::Base.Generator; tag = nothing)

Two-argument form of add_con! supporting the constraint[idx] += expr sugar. The generator must use the pattern g[idx] += expr for ... in itr, where g is an existing Constraint or ConstraintAugmentation.

Equivalent to add_con!(core, g, idx => expr for ... in itr).

Example

c = ExaCore()
c, x = add_var(c, 10)
c, g = add_con(c, 9; lcon = -1.0, ucon = 1.0)
c, _ = add_con!(c, g[i] += x[i] + x[i+1] for i = 1:9)
source
ExaModels.add_con — Method
add_con(core::TwoStageExaCore, ::EachScenario, dims_or_gen...; start = 0, lcon = 0, ucon = 0, name = nothing)

Add second-stage (per-scenario) constraints to a two-stage core. The constraint expression is replicated for each scenario. The iterator element is wrapped so that DataSource()[1] accesses the original data and DataSource()[2] gives the scenario index.

source
ExaModels.add_con — Method
add_con(core::TwoStageExaCore, dims_or_gen...; start = 0, lcon = 0, ucon = 0, name = nothing)

Add first-stage constraints to a two-stage core. Accepts the same forms as the base add_con (generator or dims). Tagged with FirstStageTag().

source
ExaModels.add_con — Method
add_con(core, generator; start = 0, lcon = 0, ucon = 0, name = nothing, tag = nothing)
add_con(core, expr, pars; start = 0, lcon = 0, ucon = 0, name = nothing, tag = nothing)
add_con(core, dims...; start = 0, lcon = 0, ucon = 0, name = nothing, tag = nothing)

Adds constraints to core and returns (core, Constraint).

Generator form: pass a generator that yields one expression per constraint row. Can instead use the low-level add_con(core, expr, pars; ...) if you have already built an expression tree.

Dims form: pass integer or UnitRange dimensions to create empty constraints, then use add_con! / @add_con! to accumulate terms afterwards. dims can be a single integer (add_con(c, 9)), multiple integers (add_con(c, 3, 4) for a 3×4 grid), or AbstractUnitRange values (add_con(c, 1:3, 2:5)) — matching the convention used by add_var.

Keyword Arguments

  • start: The initial guess of the dual solution. Can either be Number, AbstractArray, or Generator.
  • lcon : The constraint lower bound. Can either be Number, AbstractArray, or Generator.
  • ucon : The constraint upper bound. Can either be Number, AbstractArray, or Generator.
  • name : When given as Val(:name), registers the constraint in core for later retrieval as core.name or model.name. See @add_con for the idiomatic named interface.
  • tag : User-defined metadata attached to the constraint block.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10);

julia> c, con = add_con(c, x[i] + x[i+1] for i=1:9; lcon = -1, ucon = (1+i for i=1:9));

julia> con
Constraint

  g♭ ≤ [g(x,i)]_{i ∈ I} ≤ g♯

  g(x,i) = x[i] + x[i + 1]

  where |I| = 9

Empty constraint with augmentation:

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10);

julia> c, g = add_con(c, 9; lcon = -1.0, ucon = 1.0);

julia> c, _ = add_con!(c, g, i => x[i] + x[i+1] for i = 1:9);

julia> g
Constraint

  g♭ ≤ [g(x,i)]_{i ∈ I} ≤ g♯

  g(x,i) = 0

  where |I| = 9
source
ExaModels.add_eval — Method
add_eval(core, cons, vars, f!; jac!, hess!, jvp!, vjp!, hvp!,
         jac_structure!, hess_structure!, nnzj=-1, nnzh=-1, adapt=Val(false))

Register an oracle evaluator that augments pre-existing constraint rows.

  • cons: a tuple of Constraint handles whose rows will be filled.
  • vars: a tuple of Variable handles whose values are passed to the callbacks.
  • f!(res, x_local): fills res[1:ncon_total] given x_local[1:nvar_total].

Sparsity is declared via jac_structure!(rows, cols) / hess_structure!(rows, cols), called once at construction with pre-allocated local-index vectors; or pass nnzj/nnzh directly. Passing nnzj=-1 with no jac_structure! triggers a dense fallback.

Returns (core, evaluator).

Example

core = ExaCore()
@add_var(core, x, 4)
c = @add_con(core, 0.0 * x[i] for i in 1:4; lcon = 0.0, ucon = 0.0)

@add_con!(core, (c,), (x,), (res, xv) -> (res .= xv .^ 2; nothing);
    jac! = (vals, xv) -> (vals .= 2 .* xv; nothing),
    nnzj = 4,
    jac_structure! = (rows, cols) -> begin
        append!(rows, 1:4); append!(cols, 1:4)
    end,
)
source
ExaModels.add_expr! — Method
add_expr!(core, v, pairs)

Augments the buffered subexpression v in place: for each j => term in pairs, term is added to v[j], and every consumer of v (constraints, objectives and buffered subexpressions already added, as well as later ones) sees the augmented value. Returns (core, v). Like add_con! for constraint rows, each call is one layer with its own iterator, and layers sum.

Each term is an affine combination with constant coefficients of buffered subexpression elements (s[k]) and variables (x[i]), including sums of such terms written with exa_sum; plain numbers fold into a constant. Indices must be data values (every term's structure is resolved at build time). The terms are stored as data (one index-table stage per call regardless of the term count), so a slot that sums thousands of elements costs no kernel compilation. Any number of terms may target the same slot and slices may be ragged. A layer may not read v itself.

Typical use is the group-partially-separable pattern: buffer the element functions with add_expr(...; buffered = true), create the group values from their constant parts, and add each group's Σ w·element + Σ a·x with one add_expr! per data source.

@add_var(c, x, nv)
@add_expr(c, e, x[d.i] * x[d.j] for d in elems; buffered = true)
@add_expr(c, v, b[g] for g in 1:ngroups; buffered = true)
@add_expr!(c, v, d.g => d.w * e[d.k] for d in terms)
@add_obj(c, (v[g])^2 for g in 1:ngroups)

The layer is evaluated right after the newest of v and its sources. A buffered subexpression that reads v and was added before one of the layer's sources would therefore read v before the layer: that is an ArgumentError (add the layer first, or buffer the sources earlier).

Supports the NLPModels evaluation API through second order on the host and on KernelAbstractions backends, with the same restrictions as other buffered subexpressions (no oracles, no prod = true, jprod_nln!/jtprod_nln! host-only). The returned core's stage tuple is rebuilt from a vector, so its type is not inferable from the call: later add_* calls on that core dispatch dynamically, and a model builder that calls add_expr! is not compilable under juliac --trim=safe; use it at the build layer.

source
ExaModels.add_expr — Method
add_expr(core, generator; name = nothing, tag = nothing)

Creates a subexpression from a generator and returns (core, Expression). The expression is stored for direct substitution (inlining) when indexed — no auxiliary variables or constraints are added to the problem.

Keyword Arguments

  • name: When given as Val(:name), registers the subexpression in core for later retrieval as core.name or model.name. See @add_expr for the idiomatic named interface.
  • tag : User-defined metadata attached to the expression.
  • lift: introduce the subexpression as a variable pinned by a defining equality constraint (adds rows and columns; 1-D iterators only). Takes precedence over buffered, which is ignored when lift = true.
  • start: starting point for the lifted variable when lift = true.
  • buffered: When true (or Val(true)), returns a BufferedExpression: each element is evaluated once per model evaluation into a dedicated buffer slot, and indexing produces a shallow leaf node referencing the slot instead of splicing the subexpression tree into the use site. This keeps compilation cost additive in the nesting depth of expression trees. Prefer the default (inlining) for subexpressions used once or twice at shallow depth, and buffered = true for subexpressions that are shared across many use sites or nested in other subexpressions.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10);

julia> c, s = add_expr(c, x[i]^2 for i in 1:10);

julia> s
Subexpression (reduced)

  s ∈ R^{10}
  s(x,i) = x[i]^2

julia> c, _ = add_obj(c, s[i] + s[i+1] for i in 1:9);

Multi-dimensional example

c = ExaCore()
c, x = add_var(c, 1:N, 1:K)
itr = [(i, k) for i in 1:N, k in 1:K]
c, s = add_expr(c, x[i, k]^2 for (i, k) in itr)
# s[i, k] substitutes x[i,k]^2 directly
source
ExaModels.add_obj — Method
add_obj(core::ExaCore, generator; name = nothing)

Adds objective terms specified by a generator to core, and returns (core, Objective). The terms are summed.

Keyword Arguments

  • name: When given as Val(:name), registers the objective in core for later retrieval as core.name or model.name. See @add_obj for the idiomatic named interface.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10);

julia> c, obj = add_obj(c, x[i]^2 for i=1:10);

julia> obj
Objective

  ∑_{i ∈ I} f(x,i)

  f(x,i) = x[i]^2

  where |I| = 10
source
ExaModels.add_obj — Method
add_obj(core::ExaCore, expr [, pars]; name = nothing)

Low-level form of add_obj that accepts a pre-built AbstractNode expression expr evaluated over pars, and returns (core, Objective).

When name is given as Val(:name), the objective is also accessible as core.name or model.name.

Prefer the generator form (add_obj(core, gen)) for typical use; this form is intended for code that builds expression trees programmatically.

source
ExaModels.add_par — Method
add_par(core::TwoStageExaCore, value::AbstractArray; name = nothing)
add_par(core::TwoStageExaCore, n::AbstractRange; name = nothing, value = 0)
add_par(core::TwoStageExaCore, dims...; name = nothing, value = 0)

Add first-stage parameters to a two-stage core, tagged with FirstStageTag().

Mirrors the add_par convention from ExaCore:

  • Pass value::AbstractArray as the first positional argument to use its values and infer dimensions from size(value).
  • Pass dimensions (Integer or AbstractRange) as positional arguments and supply the uniform initial value via the value keyword.
source
ExaModels.add_par — Method
add_par(core::TwoStageExaCore, ::EachScenario, value::AbstractVector; name = nothing)

Add second-stage parameters to a two-stage core. The parameter vector value is replicated for each scenario, tagged with SecondStageTag().

source
ExaModels.add_par — Method
add_par(core, dims...; value = 0, name = nothing, tag = nothing)
add_par(core, value::AbstractArray; name = nothing, tag = nothing)

Adds parameters to core and returns (core, Parameter).

The first form specifies dimensions with dims (each an Integer or UnitRange) and initial values via the value keyword. The second form is a convenience that uses size(value) as the dimensions.

Keyword Arguments

  • value: Initial parameter values. Can be a Number, AbstractArray, or Generator.
  • name : When given as Val(:name), registers the parameter in core for later retrieval as core.name or model.name. See @add_par for the idiomatic named interface.
  • tag : User-defined metadata attached to the parameter block.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, θ = add_par(c, ones(10));

julia> θ
Parameter

  θ ∈ R^{10}
source
ExaModels.add_var — Method
add_var(core::TwoStageExaCore, ::EachScenario, dims...; start = 0, lvar = -Inf, uvar = Inf, name = nothing)

Add second-stage (recourse) variables to a two-stage core. Creates prod(dims) * nscen variables total — one copy of the block per scenario — tagged with SecondStageTag(). The last dimension of the resulting variable indexes the scenario.

source
ExaModels.add_var — Method
add_var(core::TwoStageExaCore, dims...; start = 0, lvar = -Inf, uvar = Inf, name = nothing)

Add first-stage (design) variables to a two-stage core. These are shared across all scenarios and tagged with FirstStageTag().

source
ExaModels.add_var — Method
add_var(core, gen::Base.Generator; kwargs...)

Create variables constrained to equal the expressions produced by gen. Equivalent to creating length(gen.iter) variables with equality constraints tying each to the corresponding generator expression. Returns (core, Variable).

source
ExaModels.add_var — Method
add_var(core, dims...; start = 0, lvar = -Inf, uvar = Inf, name = nothing, tag = nothing)

Adds variables with dimensions specified by dims to core. dims can be either Integer or UnitRange. Returns (core, Variable).

Keyword Arguments

  • start: The initial guess of the solution. Can either be Number, AbstractArray, or Generator.
  • lvar : The variable lower bound. Can either be Number, AbstractArray, or Generator.
  • uvar : The variable upper bound. Can either be Number, AbstractArray, or Generator.
  • name : When given as Val(:name), registers the variable in core for later retrieval as core.name or model.name. See @add_var for the idiomatic named interface.
  • tag : User-defined metadata attached to the variable block (e.g., scenario identifier for two-stage models).

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10; start = (sin(i) for i=1:10));

julia> x
Variable

  x ∈ R^{10}

julia> c, y = add_var(c, 2:10, 3:5; lvar = zeros(9,3), uvar = ones(9,3));

julia> y
Variable

  x ∈ R^{9 × 3}
source
ExaModels.bselect — Method
bselect(s, x)

Branch-selecting multiplication: s * x, except that a zero selector annihilates x entirely — bselect(0, x) == 0 even when x is Inf or NaN. Intended for blending conditional branches, with s a 0/1 indicator built from zero-derivative primitives such as sign: the value and the derivatives of an inactive branch cannot poison the blend, so bselect(s, a) + bselect(1 - s, b) reproduces branch-selected values and derivatives exactly (d/ds is defined as 0, d/dx = s).

source
ExaModels.constraint — Method
constraint(core::ExaCore, oracle::VectorNonlinearOracle)

Register a VectorNonlinearOracle with an ExaCore. The oracle's constraint bounds are appended to core.lcon/core.ucon, and the constraint/Jacobian/ Hessian counts are updated. When ExaModel(core) is called afterwards, the result is an ExaModelWithOracle that evaluates both the SIMD symbolic constraints and all registered oracles.

Returns the oracle (for indexing convenience).

source
ExaModels.drpass — Method
drpass(d::D, y, adj)

Performs dense gradient evaluation via the reverse pass on the computation (sub)graph formed by forward pass

Arguments:

  • d: first-order computation (sub)graph
  • y: result vector
  • adj: adjoint propagated up to the current node
source
ExaModels.embed_oracle — Method
embed_oracle(core, x, output_dim; f!, jvp!, vjp!, hvp! = nothing, adapt = Val(false))

Embed an opaque vector function f: ℝⁿ → ℝᵐ into an ExaCore using the full-space pattern. Creates auxiliary variables z ∈ ℝᵐ, registers an oracle constraint z − f(x) = 0, and returns the updated core together with z.

The callbacks operate on local input/output vectors — no global offsets:

  • f!(y, x): y[1:m] = f(x[1:n])
  • jvp!(Jv, x, v): Jv[1:m] = J_f(x) * v[1:n]
  • vjp!(Jtv, x, w): Jtv[1:n] = J_f(x)' * w[1:m]
  • hvp!(Hv, x, w, v): Hv[1:n] = (Σ wᵢ ∇²fᵢ(x)) * v[1:n] (optional)

Returns (core, z, oracle) where core is the updated core and z is the output Variable.

Example

core = ExaCore()
@add_var(core, x, 2; start = [1.0, 1.0])

core, z, _ = embed_oracle(core, x, 1;
    f!   = (y, xv) -> (y[1] = xv[1]^2 + xv[2]^2; nothing),
    jvp! = (Jv, xv, v) -> (Jv[1] = 2xv[1]*v[1] + 2xv[2]*v[2]; nothing),
    vjp! = (Jtv, xv, w) -> (Jtv[1] = 2xv[1]*w[1]; Jtv[2] = 2xv[2]*w[1]; nothing),
    hvp! = (Hv, xv, w, v) -> (Hv[1] = 2w[1]*v[1]; Hv[2] = 2w[1]*v[2]; nothing),
)

@add_obj(core, z[1])                                          # min f(x)
@add_con(core, x[1] + x[2]; lcon = 2.0, ucon = Inf)          # x₁+x₂ ≥ 2
model = ExaModel(core)
source
ExaModels.enable_short_type_printing — Method
enable_short_type_printing()

Print expression-tree types in short form in stack traces and MethodErrors, e.g. Node2{+,…} instead of the full parametric type. fulltype_display! and fulltype then control the long form.

Off by default: the short forms are show methods for types, and defining them invalidates compiled code across the session (for example, a solver's precompiled code recompiles on its next call). Call this at run time, not during precompilation.

source
ExaModels.exa_prod — Method
exa_prod(f, itr)
exa_prod(f, ::Val{range})
exa_prod(gen::Base.Generator)

Build a ProdNode representing ∏ f(k) for k ∈ itr. Inside @add_obj, @add_con, and @add_expr macros, prod(body for k in range) is automatically rewritten to exa_prod(k -> body, Val(range)) with the Val hoisted outside the generator closure.

See exa_sum for supported iterators and juliac usage notes.

source
ExaModels.exa_sum — Method
exa_sum(f, itr)
exa_sum(f, ::Val{range})
exa_sum(gen::Base.Generator)

Build a SumNode representing ∑ f(k) for k ∈ itr. Inside @add_obj, @add_con, and @add_expr macros, sum(body for k in range) is automatically rewritten to exa_sum(k -> body, Val(range)) with the Val hoisted outside the generator closure.

Supported iterators

  • Tuple: type-stable via tail recursion.
  • UnitRange{Int}: type-stable when the length is a compile-time constant.
  • Val{range} (preferred for juliac): exa_sum(f, Val(1:nc)) embeds the range in the type parameter, ensuring juliac --trim=safe can resolve Val{N}.

juliac / AOT usage

Julia's inference cannot propagate constants like nc = 3 through a generator closure boundary. When calling add_con/add_obj programmatically (not via macro), hoist Val(range) outside the generator:

v = Val(1:nc)                                          # outside generator
c, con = add_con(c, (exa_sum(j -> x[j], v) for i in 1:nh))  # v captured
source
ExaModels.expand_family — Method
expand_family(block)

The source blocks of a merged constraint or objective block, as plain blocks (one per segment, each with its own tree, row offset, iterator and shape); [block] for a block that is not a family. Used by writers that serialize expressions. A pair-headed family (MergedRows, from add_con(c, i => expr for ...) on the host) keeps no segments and throws an ArgumentError.

source
ExaModels.fulltype — Method
fulltype(node)
fulltype(io::IO, node)

Print the full unabbreviated type of a node.

After enable_short_type_printing, show for ExaModels node types abbreviates inner graph-structure parameters with … to keep output readable (e.g. Node2{+,…} instead of Node2{typeof(+),Var{Int64},Var{Int64}}). fulltype bypasses this by passing the IOContext key :fulltype => true, which all the short show(::IO, ::Type{...}) methods respect. Without short type printing enabled, types print in full anyway.

Examples

node = Var(1) + Var(2)          # Node2{typeof(+),Var{Int64},Var{Int64}}
show(stdout, typeof(node))      # → Node2{+,…}          (after enable_short_type_printing())
fulltype(node)                  # → Node2{+,Var{Int64},Var{Int64}}

# Equivalent manual form:
show(IOContext(stdout, :fulltype => true), typeof(node))

IOContext flag

Any show call that passes :fulltype => true in its IOContext will render the complete parametric type. This is useful when you need full type output programmatically without calling fulltype directly:

io = IOContext(stderr, :fulltype => true)
show(io, typeof(node))
source
ExaModels.fulltype_display! — Method
fulltype_display!(enabled::Bool)

Globally enable or disable full-type display for ExaModels node types.

When enabled, typeof(node) and error messages (MethodErrors, stacktraces) show the complete parametric type instead of the abbreviated … form.

Takes effect only after enable_short_type_printing; until then types always print in full.

ExaModels.fulltype_display!(true)   # enable — e.g. typeof(x) → Node2{+,Var{Int64},Var{Int64}}
ExaModels.fulltype_display!(false)  # disable — e.g. typeof(x) → Node2{+,…}

For one-off inspection without changing the global setting, use fulltype.

source
ExaModels.get_con_scen — Method
get_con_scen(model::TwoStageExaModel)

Return the scenario-index vector for constraints. Entry k holds the scenario number of the k-th constraint (0 = shared).

findall(==(s), get_con_scen(model))  # constraint indices for scenario s
source
ExaModels.get_cons — Method
get_vars(core_or_model[, name])
get_cons(core_or_model[, name])
get_pars(core_or_model[, name])

The model's named blocks of that kind, as a NamedTuple.

Naming a block registers it (@add_var(c, x, 10) → x), and these are how you ask what a model has rather than what you remember writing — which is the only way to address a compiled model, whose Julia source the caller may never see. The blocks index the solution: pair them with solution, multipliers, multipliers_L / multipliers_U, and get_value / set_value! for parameters.

Note m.vars is a different thing — the positional storage of every block, named or not.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10; name = Val(:x));

julia> m = ExaModel(c);

julia> keys(get_vars(m))
(:x,)

julia> get_vars(m, :x) === get_vars(m).x
true
source
ExaModels.get_cons — Method
get_vars(core_or_model[, name])
get_cons(core_or_model[, name])
get_pars(core_or_model[, name])

The model's named blocks of that kind, as a NamedTuple.

Naming a block registers it (@add_var(c, x, 10) → x), and these are how you ask what a model has rather than what you remember writing — which is the only way to address a compiled model, whose Julia source the caller may never see. The blocks index the solution: pair them with solution, multipliers, multipliers_L / multipliers_U, and get_value / set_value! for parameters.

Note m.vars is a different thing — the positional storage of every block, named or not.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10; name = Val(:x));

julia> m = ExaModel(c);

julia> keys(get_vars(m))
(:x,)

julia> get_vars(m, :x) === get_vars(m).x
true
source
ExaModels.get_pars — Method
get_vars(core_or_model[, name])
get_cons(core_or_model[, name])
get_pars(core_or_model[, name])

The model's named blocks of that kind, as a NamedTuple.

Naming a block registers it (@add_var(c, x, 10) → x), and these are how you ask what a model has rather than what you remember writing — which is the only way to address a compiled model, whose Julia source the caller may never see. The blocks index the solution: pair them with solution, multipliers, multipliers_L / multipliers_U, and get_value / set_value! for parameters.

Note m.vars is a different thing — the positional storage of every block, named or not.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10; name = Val(:x));

julia> m = ExaModel(c);

julia> keys(get_vars(m))
(:x,)

julia> get_vars(m, :x) === get_vars(m).x
true
source
ExaModels.get_pars — Method
get_vars(core_or_model[, name])
get_cons(core_or_model[, name])
get_pars(core_or_model[, name])

The model's named blocks of that kind, as a NamedTuple.

Naming a block registers it (@add_var(c, x, 10) → x), and these are how you ask what a model has rather than what you remember writing — which is the only way to address a compiled model, whose Julia source the caller may never see. The blocks index the solution: pair them with solution, multipliers, multipliers_L / multipliers_U, and get_value / set_value! for parameters.

Note m.vars is a different thing — the positional storage of every block, named or not.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10; name = Val(:x));

julia> m = ExaModel(c);

julia> keys(get_vars(m))
(:x,)

julia> get_vars(m, :x) === get_vars(m).x
true
source
ExaModels.get_start — Method
get_start(model, var::Variable)
get_start(model, con::Constraint)

Return a view of the initial-point values (x0 for variables, y0 for constraints).

source
ExaModels.get_start — Method
get_start(model::TwoStageExaModel, con::SecondStageConstraint, scen)
get_lcon(model::TwoStageExaModel, con::SecondStageConstraint, scen)
get_ucon(model::TwoStageExaModel, con::SecondStageConstraint, scen)

Return a view of y0, lcon, or ucon for con restricted to scenario scen.

source
ExaModels.get_start — Method
get_start(model::TwoStageExaModel, var::SecondStageVariable, scen)
get_lvar(model::TwoStageExaModel, var::SecondStageVariable, scen)
get_uvar(model::TwoStageExaModel, var::SecondStageVariable, scen)

Return a view of x0, lvar, or uvar for var restricted to scenario scen.

source
ExaModels.get_value — Method
get_value(core, param)

Returns a view of the values of parameter block param in a core — the reader paired with set_value!, and the single-stage form of the two-stage get_value(model, param, scen).

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, p = add_par(c, ones(5));

julia> get_value(c, p)
5-element view(::Vector{Float64}, 1:5) with eltype Float64:
 1.0
 1.0
 1.0
 1.0
 1.0
source
ExaModels.get_value — Method
get_value(model, param)

Return a view of all values for param in model.θ.

For second-stage parameters in a two-stage model, use get_value(model, param, scen) to extract a single scenario's slice.

source
ExaModels.get_value — Method
get_value(model::TwoStageExaModel, param::SecondStageParameter, scen)

Return a view of the values for param in scenario scen.

The parameter must have been added with EachScenario. scen must be an integer in 1:get_nscen(model).

source
ExaModels.get_var_scen — Method
get_var_scen(model::TwoStageExaModel)

Return the scenario-index vector for variables. Entry k holds the scenario number of the k-th variable (0 = design variable shared across all scenarios).

findall(==(0), get_var_scen(model))  # design variable indices
findall(==(s), get_var_scen(model))  # indices for scenario s
source
ExaModels.get_vars — Method
get_vars(core_or_model[, name])
get_cons(core_or_model[, name])
get_pars(core_or_model[, name])

The model's named blocks of that kind, as a NamedTuple.

Naming a block registers it (@add_var(c, x, 10) → x), and these are how you ask what a model has rather than what you remember writing — which is the only way to address a compiled model, whose Julia source the caller may never see. The blocks index the solution: pair them with solution, multipliers, multipliers_L / multipliers_U, and get_value / set_value! for parameters.

Note m.vars is a different thing — the positional storage of every block, named or not.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, x = add_var(c, 10; name = Val(:x));

julia> m = ExaModel(c);

julia> keys(get_vars(m))
(:x,)

julia> get_vars(m, :x) === get_vars(m).x
true
source
ExaModels.gradient! — Method
gradient!(y, f, x, adj)

Performs dense gradient evaluation

Arguments:

  • y: result vector
  • f: the function to be differentiated in SIMDFunction format
  • x: variable vector
  • adj: initial adjoint
source
ExaModels.grpass — Method
grpass(d::D, comp, y, o1, cnt, adj)

Performs dsparse gradient evaluation via the reverse pass on the computation (sub)graph formed by forward pass

Arguments:

  • d: first-order computation (sub)graph
  • comp: a Compressor, which helps map counter to sparse vector index
  • y: result vector
  • o1: index offset
  • cnt: counter
  • adj: adjoint propagated up to the current node
source
ExaModels.has_matfree_hess — Method
has_matfree_hess(oracle::VectorNonlinearOracle)

Return true if the oracle provides a matrix-free Hessian-vector product (hvp!).

source
ExaModels.has_matfree_jac — Method
has_matfree_jac(oracle::VectorNonlinearOracle)

Return true if the oracle provides matrix-free Jacobian-vector products (jvp! and vjp!).

source
ExaModels.hdrpass — Method
hdrpass(t1::T1, t2::T2, comp, y1, y2, o2, cnt, adj)

Adds one entry of a binary node's cross term ((df1/dx)(df2/dx)') for a pair of leaves: t1 and t2 are variable (or buffered-subexpression) leaves of the two subtrees, and adj already carries both chain factors. The pairs themselves are enumerated by _cross (see "cross terms of a binary node" below).

Arguments:

  • t1: leaf of the first subtree
  • t2: leaf of the second subtree
  • comp: a Compressor, which helps map counter to sparse vector index
  • y1: result vector #1
  • y2: result vector #2 (only used when evaluating sparsity)
  • o2: index offset
  • cnt: counter
  • adj: second adjoint propagated up to the current node
source
ExaModels.instantiate — Method
instantiate(x, args...)

Resolve every AbstractArgNode inside x against the concrete argument objects args, and return the resulting value. An ArgSource{K} resolves to args[K], so the order here is the order the placeholders came out of ExaCore.

instantiate is the identity on anything that carries no ArgSource dependency — including containers, which are returned unchanged (===) rather than rebuilt — so it is safe to apply to every slot of a model unconditionally.

Example

julia> using ExaModels

julia> arg = ArgSource();

julia> ExaModels.instantiate(arg.nh * ones(3), (nh = 2,))
3-element Vector{Float64}:
 2.0
 2.0
 2.0

julia> x = [1.0, 2.0];

julia> ExaModels.instantiate(x, (nh = 2,)) === x     # identity, no arg dependency
true
source
ExaModels.jrpass — Method
jrpass(d::D, comp, i, y1, y2, o1, cnt, adj)

Performs sparse jacobian evaluation via the reverse pass on the computation (sub)graph formed by forward pass

Arguments:

  • d: first-order computation (sub)graph
  • comp: a Compressor, which helps map counter to sparse vector index
  • i: constraint index (this is i-th constraint)
  • y1: result vector #1
  • y2: result vector #2 (only used when evaluating sparsity)
  • o1: index offset
  • cnt: counter
  • adj: adjoint propagated up to the current node
source
ExaModels.multipliers — Method
multipliers(result, y)

Returns the multipliers for constraints y associated with result, obtained by solving the model.

Example

julia> using ExaModels, NLPModelsIpopt

julia> c = ExaCore();

julia> c, x = add_var(c, 1:10; lvar = -1, uvar = 1);

julia> c, _ = add_obj(c, (x[i]-2)^2 for i in 1:10);

julia> c, y = add_con(c, x[i] + x[i+1] for i=1:9; lcon = -1, ucon = (1+i for i=1:9));

julia> m = ExaModel(c);

julia> result = ipopt(m; print_level=0);

julia> val = multipliers(result, y);


julia> val[1] ≈ 0.81933930
true
source
ExaModels.multipliers_L — Method
multipliers_L(result, x)

Returns the lower-bound dual variables for variable block x associated with result, obtained by solving the model.

multipliers_L[i] ≥ 0 is the dual variable for the bound constraint x[i] ≥ lvar[i]. A nonzero value indicates that the lower bound is active at the solution; the magnitude measures how much the objective would improve if that bound were relaxed.

Example

julia> using ExaModels, NLPModelsIpopt

julia> c = ExaCore();

julia> c, x = add_var(c, 1:10; lvar = -1, uvar = 1);

julia> c, _ = add_obj(c, (x[i]-2)^2 for i in 1:10);

julia> m = ExaModel(c);

julia> result = ipopt(m; print_level=0);

julia> val = multipliers_L(result, x);

julia> isapprox(val, fill(0, 10), atol=sqrt(eps(Float64)), rtol=Inf)
true
source
ExaModels.multipliers_U — Method
multipliers_U(result, x)

Returns the upper-bound dual variables for variable block x associated with result, obtained by solving the model.

multipliers_U[i] ≥ 0 is the dual variable for the bound constraint x[i] ≤ uvar[i]. A nonzero value indicates that the upper bound is active at the solution; the magnitude measures how much the objective would improve if that bound were relaxed.

Example

julia> using ExaModels, NLPModelsIpopt

julia> c = ExaCore();

julia> c, x = add_var(c, 1:10; lvar = -1, uvar = 1);

julia> c, _ = add_obj(c, (x[i]-2)^2 for i in 1:10);

julia> m = ExaModel(c);

julia> result = ipopt(m; print_level=0);

julia> val = multipliers_U(result, x);

julia> isapprox(val, fill(2, 10), atol=sqrt(eps(Float64)), rtol=Inf)
true
source
ExaModels.objective — Method
objective(core::ExaCore, oracle::ScalarNonlinearOracle)

Register a scalar objective oracle with core.

source
ExaModels.precompile_backend — Method
precompile_backend(backend)

Compile the model-independent code of backend for use in a PrecompileTools.@compile_workload: building a model, sorting its sparsity patterns, and the sum and findall kernels. The sizes reach the kernel variants that large models use.

The extensions for CUDA and AMDGPU call this when a device works during precompilation. For another backend, call it from the workload of a package that needs it, in a process where that backend works. Device kernels are stored only by backends whose compiled kernels persist across sessions.

source
ExaModels.precompile_callbacks — Method
precompile_callbacks(m::AbstractExaModel; prod = false)

Evaluate at m's starting point every callback a solver uses: jac_structure!, hess_structure!, obj, grad!, cons!, jac_coord!, and hess_coord! with and without multipliers, also with the views of a longer buffer that MadNLP passes. Buffers have m's own array type, so on a device the kernels run there. Returns nothing.

With prod = true, also evaluate jprod!, jtprod! and hprod!. On a device these need a model built with ExaModel(c; prod = true). They are off by default because they add to the code stored for each model.

Called from a PrecompileTools.@compile_workload, this stores the code of m in the caller's package image. A model's type depends on its expressions, not on its data, so a model of the same formulation but other data then builds and evaluates without compiling.

Each callback is called through Base.invokelatest, as from the top level or from behind a solver's function barrier, so that it is compiled as a standalone method and not only inlined into this function.

An error raised at the starting point, such as a DomainError, propagates.

source
ExaModels.set_start! — Method
set_start!(model, var::Variable, values)
set_start!(model, con::Constraint, values)

Update the initial-point values in-place (x0 for variables, y0 for constraints).

source
ExaModels.set_start! — Method
set_start!(model::TwoStageExaModel, con::SecondStageConstraint, scen, values)
set_lcon!(model::TwoStageExaModel, con::SecondStageConstraint, scen, values)
set_ucon!(model::TwoStageExaModel, con::SecondStageConstraint, scen, values)

Update y0, lcon, or ucon for con in scenario scen in-place.

source
ExaModels.set_start! — Method
set_start!(model::TwoStageExaModel, var::SecondStageVariable, scen, values)
set_lvar!(model::TwoStageExaModel, var::SecondStageVariable, scen, values)
set_uvar!(model::TwoStageExaModel, var::SecondStageVariable, scen, values)

Update x0, lvar, or uvar for var in scenario scen in-place.

source
ExaModels.set_value! — Method
set_value!(core, param, values)

Updates the values of parameter block param in a core, the counterpart of the ExaModel method. Parameters are model state, so this takes effect without rebuilding; the same spelling as the two-stage set_value!, which takes an additional scenario index.

Example

julia> using ExaModels

julia> c = ExaCore();

julia> c, p = add_par(c, ones(5));

julia> set_value!(c, p, ones(5))
source
ExaModels.set_value! — Method
set_value!(model::TwoStageExaModel, param::SecondStageParameter, scen, values)

Update the values for param in scenario scen to values.

The parameter must have been added with EachScenario. values must have param.length ÷ get_nscen(model) elements.

source
ExaModels.sgradient! — Method

sgradient!(y, f, x, adj)

Performs sparse gradient evaluation

Arguments:

  • y: result vector
  • f: the function to be differentiated in SIMDFunction format
  • x: variable vector
  • adj: initial adjoint
source
ExaModels.shessian! — Method
shessian!(y1, y2, f, x, adj1, adj2)

Performs sparse jacobian evaluation

Arguments:

  • y1: result vector #1
  • y2: result vector #2 (only used when evaluating sparsity)
  • f: the function to be differentiated in SIMDFunction format
  • x: variable vector
  • adj1: initial first adjoint
  • adj2: initial second adjoint
source
ExaModels.sjacobian! — Method
sjacobian!(y1, y2, f, x, adj)

Performs sparse jacobian evaluation

Arguments:

  • y1: result vector #1
  • y2: result vector #2 (only used when evaluating sparsity)
  • f: the function to be differentiated in SIMDFunction format
  • x: variable vector
  • adj: initial adjoint
source
ExaModels.solution — Method
solution(result, x)

Returns the primal solution values for variable block x associated with result, obtained by solving the model. The returned array has the same shape as x.

Example

julia> using ExaModels, NLPModelsIpopt

julia> c = ExaCore();

julia> c, x = add_var(c, 1:10; lvar = -1, uvar = 1);

julia> c, _ = add_obj(c, (x[i]-2)^2 for i in 1:10);

julia> m = ExaModel(c);

julia> result = ipopt(m; print_level=0);

julia> val = solution(result, x);

julia> isapprox(val, fill(1, 10), atol=sqrt(eps(Float64)), rtol=Inf)
true
source
ExaModels.@add_con! — Macro
@add_con!(core, c1, generator; kwargs...)
@add_con!(core, c1[idx] += expr for ...; kwargs...)

Macro interface for add_con!. Updates core in the calling scope and returns the new ConstraintAugmentation.

Two calling conventions are supported:

  • Three-argument (@add_con!(core, c1, idx => expr for ...)): the constraint c1 is passed explicitly and the generator yields idx => expr pairs.
  • Two-argument (@add_con!(core, c1[idx] += expr for ...)): the constraint and index are embedded in the generator via += syntax. This form delegates to the function-level add_con!(core, gen), which extracts the target constraint automatically.

See add_con! for full semantics and usage notes.

Example

c = ExaCore()
@add_var(c, x, 10)
@add_con(c, g, x[i] + x[i+1] for i in 1:9; lcon = -1, ucon = 1)

## Three-argument form:
aug = @add_con!(c, g, i => sin(x[i+1]) for i in 4:6)

## Two-argument form (equivalent):
aug = @add_con!(c, g[i] += sin(x[i+1]) for i in 4:6)
source
ExaModels.@add_con — Macro
@add_con(core, [name,] generator; kwargs...)

Macro interface for add_con. Updates core in the calling scope.

  • Named (@add_con(core, g, generator)): binds g to the new Constraint in the local scope and registers it in core for later retrieval as core.g or model.g.
  • Anonymous (@add_con(core, generator)): equivalent to c, g = add_con(c, generator).

Accepts the same keyword arguments as add_con (lcon, ucon, start, etc.).

Example

c = ExaCore()
@add_var(c, x, 10)
@add_con(c, g, x[i] + x[i+1] for i in 1:9; lcon = -1, ucon = 1)  # g in scope; c.g also works
source
ExaModels.@add_expr! — Macro
@add_expr!(core, v, idx => term for ...)

Macro interface for add_expr!. Updates core in the calling scope and evaluates to v.

@add_expr(c, e, x[d.i] * x[d.j] for d in elems; buffered = true)
@add_expr(c, v, b[g] for g in 1:ngroups; buffered = true)
@add_expr!(c, v, d.g => d.w * e[d.k] for d in terms)
source
ExaModels.@add_expr — Macro
@add_expr(core, [name,] generator; kwargs...)

Macro interface for add_expr. Updates core in the calling scope.

  • Named (@add_expr(core, s, generator)): binds s to the new Expression in the local scope and registers it in core for later retrieval as core.s or model.s.
  • Anonymous (@add_expr(core, generator)): equivalent to c, s = add_expr(c, generator).

Example

c = ExaCore()
@add_var(c, x, 10)
@add_expr(c, s, x[i]^2 for i in 1:10)    # s in scope; c.s also works
@add_obj(c, s[i] + s[i+1] for i in 1:9)
source
ExaModels.@add_obj — Macro
@add_obj(core, [name,] generator; kwargs...)

Macro interface for add_obj. Updates core in the calling scope.

  • Named (@add_obj(core, f, generator)): binds f to the new Objective in the local scope and registers it in core for later retrieval as core.f or model.f.
  • Anonymous (@add_obj(core, generator)): equivalent to c, o = add_obj(c, generator).

Example

c = ExaCore()
@add_var(c, x, 10)
@add_obj(c, x[i]^2 for i in 1:10)
source
ExaModels.@add_par — Macro
@add_par(core, [name,] start; kwargs...)

Macro interface for add_par. Updates core in the calling scope.

  • Named (@add_par(core, θ, start)): binds θ to the new Parameter in the local scope and registers it in core for later retrieval as core.θ or model.θ.
  • Anonymous (@add_par(core, start)): equivalent to c, p = add_par(c, start).

Example

c = ExaCore()
@add_par(c, θ, ones(10))  # θ is now in scope; c.θ also works
source
ExaModels.@add_var — Macro
@add_var(core, [name,] dims...; kwargs...)

Macro interface for add_var. Updates core in the calling scope.

  • Named (@add_var(core, x, dims...)): binds x to the new Variable in the local scope and registers it in core for later retrieval as core.x or model.x.
  • Anonymous (@add_var(core, dims...)): equivalent to c, v = add_var(c, dims...).

Accepts the same keyword arguments as add_var.

Example

c = ExaCore()
@add_var(c, x, 10; lvar = -1, uvar = 1)  # x is now in scope; c.x also works
@add_var(c, y, 1:5)                        # y is in scope; c.y also works
source
ExaModels.@register_bivariate — Macro
@register_bivariate(f, df1, df2, ddf11, ddf12, ddf22)

Register a bivariate function f so it can be used inside @add_obj / @add_con expressions. The macro adds four method groups:

  1. Node OP Node — f(d1::AbstractNode, d2::AbstractNode) → Node2(f, d1, d2).
  2. Node OP Real — f(d1::AbstractNode, d2::Real) → Node2(f, d1, d2). Numeric scalars (including iterator-derived values like factorial(j)) are stored directly in Node2 without wrapping in Constant.
  3. Real OP Node — symmetric counterpart of the above.
  4. Constant folding — f(Constant{I1}(), Constant{I2}()) → Constant(f(I1, I2)). Both-constant expressions are evaluated immediately.

Arguments

  • f: the function to register
  • df1: partial derivative w.r.t. the first argument
  • df2: partial derivative w.r.t. the second argument
  • ddf11: second partial w.r.t. the first argument
  • ddf12: mixed second partial
  • ddf22: second partial w.r.t. the second argument

Example

julia> using ExaModels

julia> relu23(x,y) = (x > 0 || y > 0) ? (x + y)^3 : zero(x)
relu23 (generic function with 1 method)

julia> drelu231(x,y) = (x > 0 || y > 0) ? 3 * (x + y)^2 : zero(x)
drelu231 (generic function with 1 method)

julia> drelu232(x,y) = (x > 0 || y > 0) ? 3 * (x + y)^2  : zero(x)
drelu232 (generic function with 1 method)

julia> ddrelu2311(x,y) = (x > 0 || y > 0) ? 6 * (x + y) : zero(x)
ddrelu2311 (generic function with 1 method)

julia> ddrelu2312(x,y) = (x > 0 || y > 0) ? 6 * (x + y) : zero(x)
ddrelu2312 (generic function with 1 method)

julia> ddrelu2322(x,y) = (x > 0 || y > 0) ? 6 * (x + y) : zero(x)
ddrelu2322 (generic function with 1 method)

julia> @register_bivariate(relu23, drelu231, drelu232, ddrelu2311, ddrelu2312, ddrelu2322)
source
ExaModels.@register_univariate — Macro
@register_univariate(f, df, ddf)

Register a univariate function f so it can be used inside @add_obj / @add_con expressions. The macro adds three method groups:

  1. Primal graph node — f(n::AbstractNode) → Node1(f, n). Applied at model-construction time to build the symbolic graph.

  2. Constant folding — f(::Constant{T}) → Constant(f(T)). When the argument is a Constant (value encoded as a type parameter), the result is evaluated immediately and stored as a new Constant, avoiding a Node1 allocation entirely.

  3. Adjoint / second-adjoint nodes — forward-pass nodes for gradient and Hessian computation, using df and ddf as the derivative functions.

Arguments

  • f: the function to register
  • df: first derivative f'(x)
  • ddf: second derivative f''(x)

Example

julia> using ExaModels

julia> relu3(x) = x > 0 ? x^3 : zero(x)
relu3 (generic function with 1 method)

julia> drelu3(x) = x > 0 ? 3*x^2 : zero(x)
drelu3 (generic function with 1 method)

julia> ddrelu3(x) = x > 0 ? 6*x : zero(x)
ddrelu3 (generic function with 1 method)

julia> @register_univariate(relu3, drelu3, ddrelu3)
source