ExaModels
ExaModels.ExaModels — Module
ExaModelsAn 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 fieldsNode1/Node2— unary / binary operationsConstant{T}— compile-time scalar constant; the valueTis stored as a type parameter so it is visible to the compiler and tojuliac --trim=safewithout 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
ExaModels.AbstractAdjointNode — Type
AbstractAdjointNodeAbstract type for nodes in the first-order (gradient) forward-pass tree.
ExaModels.AbstractArgNode — Type
AbstractArgNodeRoot 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.
ExaModels.AbstractExaModel — Type
AbstractExaModelAn abstract type for ExaModel, which is a subtype of NLPModels.AbstractNLPModel.
ExaModels.AbstractNode — Type
AbstractNodeRoot 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.
ExaModels.AbstractSecondAdjointNode — Type
AbstractSecondAdjointNodeAbstract type for nodes in the second-order (Hessian) reverse-pass tree.
ExaModels.AdjointNode1 — Type
AdjointNode1{F, T, I} <: AbstractAdjointNodeGradient-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 valueF(inner.x)y::T: derivativeF'(inner.x)inner::I: child node
ExaModels.AdjointNode2 — Type
AdjointNode2{F, T, I1, I2} <: AbstractAdjointNodeGradient-pass node for a binary operation F. Stores the primal value and both partial derivatives.
Fields
x::T: primal valueF(inner1.x, inner2.x)y1::T: partial derivative w.r.t. first argumenty2::T: partial derivative w.r.t. second argumentinner1::I1: left childinner2::I2: right child
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 (ornothingfor a zero-valued seed)
ExaModels.AdjointNodeSubexpr — Type
AdjointNodeSubexpr{I, T} <: AbstractAdjointNodeGradient-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]
ExaModels.AdjointNodeVar — Type
AdjointNodeVar{I, T} <: AbstractAdjointNodeLeaf node in the gradient-pass tree corresponding to a decision variable.
Fields
i::I: variable indexx::T: primal valuex[i]at the current evaluation point
ExaModels.AdjointNull — Type
AdjointNull{V} <: AbstractAdjointNodeLeaf 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.
ExaModels.ArgCall — Type
ArgCall{F, A} <: AbstractArgNodeA 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.
ExaModels.ArgIndexed — Type
ArgIndexed{I, J} <: AbstractArgNodeThe 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.
ExaModels.ArgLeaf — Type
ArgLeaf{A} <: AbstractNodeA 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.
ExaModels.ArgNode1 — Type
ArgNode1{F, I} <: AbstractArgNodeA 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.
ExaModels.ArgNode2 — Type
ArgNode2{F, I1, I2} <: AbstractArgNodeA 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.
ExaModels.ArgSource — Type
ArgSource <: AbstractArgNodeSentinel 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)ExaModels.BufferedExpression — Type
BufferedExpressionA 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).
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.
ExaModels.CompressedNLPModel — Type
CompressedNLPModelA 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).
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.
ExaModels.Compressor — Type
Compressor{I}Data structure for the sparse index
Fields:
inner::I: stores the sparse index as a tuple form
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.
ExaModels.Constant — Type
Constant{T} <: AbstractNodeA 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, θ) # → 42Algebraic simplification
specialization.jl registers identities for Constant combined with AbstractNode operands:
| expression | simplification |
|---|---|
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) * x | Constant(0) |
Constant(0) / x | Constant(0) |
These rules fire at model-construction time (when the ExaCore is being built), collapsing trivial branches before the graph is finalized.
ExaModels.Constraint — Type
ConstraintA 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.
ExaModels.ConstraintAugmentation — Type
ConstraintAugmentationAn 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.
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)ExaModels.DataIndexed — Type
DataIndexed{I, J} <: AbstractNodeA 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.
ExaModels.DataSource — Type
DataSource <: AbstractNodeSentinel 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.
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.
ExaModels.EachScenario — Type
EachScenarioMarker 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 constraintsExaModels.ExaModelWithOracle — Type
ExaModelWithOracleAn 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:
- SIMD symbolic constraints (indices 1 : nsimdcon)
- Oracle blocks, in registration order
and analogously for the Jacobian and Hessian nonzero arrays.
ExaModels.Expression — Type
ExpressionA 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.
ExaModels.FvRef — Type
FvRef <: AbstractNodeReads 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.
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.
ExaModels.IvRef — Type
IvRef <: AbstractNodeReads 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 θ.
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.
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.
ExaModels.Node1 — Type
Node1{F, I} <: AbstractNodeAn interior node representing a unary operation F applied to one child node.
Evaluated as F(inner(i, x, θ)).
Fields
inner::I: child node
ExaModels.Node2 — Type
Node2{F, I1, I2} <: AbstractNodeAn 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 childinner2::I2: right child
ExaModels.Null — Type
Null{T} <: AbstractNodeA 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.
ExaModels.NullRef — Type
NullRef <: AbstractNodeReads 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.
ExaModels.Objective — Type
ObjectiveAn objective term group added to an ExaCore via add_obj / @add_obj. All Objective objects in a core are summed at evaluation time to form the total objective value.
ExaModels.OracleEvaluator — Type
OracleEvaluatorEncapsulates 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): fillsvals[1:nnzj]with Jacobian valueshess!(vals, x_local, y_local):fillsvals[1:nnzh]with Lagrangian Hessian valuesjvp!(Jv, x_local, v_local):Jv[1:ncon_total] = J(x) * v_localvjp!(Jtv, x_local, w_local):Jtv[1:nvar_total] = J(x)' * w_localhvp!(Hv, x_local, w_local, v_local):Hv[1:nvar_total] = (∑ wᵢ ∇²gᵢ) * v_local
ExaModels.Parameter — Type
ParameterA 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.
ExaModels.ProdNode — Type
ProdNode{I} <: AbstractNodeA node representing the product of a tuple of child nodes.
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 inBase.Generatorformato0: offset for the function evaluationo1: offset for the derivative evaluationo2: offset for the second-order derivative evaluation
ExaModels.ScalarNonlinearOracle — Type
ScalarNonlinearOracleA 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 valuegrad!(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 declaredhess_rows/hess_colsslots (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).
ExaModels.SecondAdjointNode1 — Type
SecondAdjointNode1{F, T, I} <: AbstractSecondAdjointNodeHessian-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 valueF(inner.x)y::T: first derivativeF'(inner.x)h::T: second derivativeF''(inner.x)inner::I: child node
ExaModels.SecondAdjointNode2 — Type
SecondAdjointNode2{F, T, I1, I2} <: AbstractSecondAdjointNodeHessian-pass node for a binary operation F.
Fields
x::T: primal valueF(inner1.x, inner2.x)y1::T: partial derivative w.r.t. first argumenty2::T: partial derivative w.r.t. second argumenth11::T: second partial w.r.t. first argumenth12::T: mixed second partialh22::T: second partial w.r.t. second argumentinner1::I1: left childinner2::I2: right child
ExaModels.SecondAdjointNodeSource — Type
SecondAdjointNodeSource{VT}Factory for SecondAdjointNodeVar leaves. Indexing with i returns SecondAdjointNodeVar(i, inner[i]), seeding the Hessian-pass tree.
Fields
inner::VT: primal variable vector (ornothingfor a zero-valued seed)
ExaModels.SecondAdjointNodeSubexpr — Type
SecondAdjointNodeSubexpr{I, T} <: AbstractSecondAdjointNodeHessian-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.
ExaModels.SecondAdjointNodeVar — Type
SecondAdjointNodeVar{I, T} <: AbstractSecondAdjointNodeLeaf node in the Hessian-pass tree corresponding to a decision variable.
Fields
i::I: variable indexx::T: primal valuex[i]at the current evaluation point
ExaModels.SecondAdjointNull — Type
SecondAdjointNull{V} <: AbstractSecondAdjointNodeLeaf 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.
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.
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.
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.
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!):
- per-stage
jrpassfillsstage_ext(extended-space stage entries); res[dst] = stage_ext[src](direct) andres[dst] = stage_ext[a] * res[b](chained) resolve every stage entry to an x-column, in emission order (b < dstalways, so one sequential sweep is valid);- consumer
jrpassfillscons_ext; jac[dst] = cons_ext[src](direct) andjac[dst] = cons_ext[a] * res[b](composed) produce the final COO values. Duplicate (row, col) pairs are summed by the COO convention.
ExaModels.SubexprNode — Type
SubexprNode{I} <: AbstractNodeLeaf 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.
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 stageSIMDFunctionitr::I: the collected iteratoroffset::Int: θ offset; values live atθ[offset+1 : offset+length(itr)]
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]-1where 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; slotjlives atθ[offset + j]n::Int: number of slotsinit::VT: length-nconstant parts of the termsptr::VI: lengthn + 1; slotj's terms areptr[j]:ptr[j+1]-1src::VI: signed sources (> 0variable index,< 0negated θ slot)w::VT: constant term weights
ExaModels.SumNode — Type
SumNode{I} <: AbstractNodeA 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.
ExaModels.TimedNLPModel — Type
TimedNLPModelA 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).
ExaModels.TimedNLPModel — Method
TimedNLPModel(m)Wraps m in a TimedNLPModel with all counters and timers reset to zero.
ExaModels.TimedNLPModel — Method
TimedNLPModel(core::ExaCore; kwargs...)Builds an ExaModel from core (forwarding kwargs...) and wraps it in a TimedNLPModel.
ExaModels.TwoStageExaCore — Type
TwoStageExaCore{T,VT,B}Type alias for an ExaCore whose tag is a [TwoStageExaModelTag]. Create one with TwoStageExaCore(nscen).
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)ExaModels.TwoStageExaModel — Type
TwoStageExaModel{T,VT,E,V,P,O,C,R}Type alias for an ExaModel built from a TwoStageExaCore. Use get_nscen, get_var_scen, and get_con_scen to query the scenario structure after building the model.
ExaModels.Var — Type
Var{I} <: AbstractNodeA 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).
ExaModels.VarSource — Type
VarSource <: AbstractNodeSentinel 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.
ExaModels.VectorNonlinearOracle — Type
VectorNonlinearOracleEncapsulates 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 problemnvar)ncon: number of constraints this oracle contributesnnzj: 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, lengthnnzj)hess_rows,hess_cols: sparsity pattern of the (lower-triangular) Hessian (1-based, lengthnnzh)lcon,ucon: constraint lower/upper bounds (lengthncon)f!:f!(c, x)— writes residuals intoc[1:ncon]jac!:jac!(vals, x)— writes Jacobian values intovals[1:nnzj](nothing if matrix-free only)hess!:hess!(vals, x, y)— writes Hessian values intovals[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. UseVal(true)when your callbacks are CPU-only; useVal(false)when they are GPU-capable.
ExaModels.WrapperNLPModel — Type
WrapperNLPModelAn 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.
ExaModels.WrapperNLPModel — Method
WrapperNLPModel(VT, m)Returns a WrapperModel{T,VT} wrapping m <: AbstractNLPModel{T}
ExaModels.WrapperNLPModel — Method
WrapperNLPModel(m)Returns a WrapperNLPModel{Float64,Vector{Float64}} wrapping m, forwarding all NLP callbacks through Float64 CPU copy buffers.
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.
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.
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.
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.
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.
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.
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.
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: TheExaCoreto modify.c1: The baseConstraint(or a previousConstraintAugmentation) whose rows are being augmented.generator: ABase.Generatoryieldingidx => exprpairs, whereidxis an index (or tuple of indices) intoc1identifying which constraint row receives the term, andexpris the scalar expression to add to that row.
Notes
- The index
idxmust be a valid index ofc1'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
idxare 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| = 3Multi-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 generationExaModels.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)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.
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().
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 beNumber,AbstractArray, orGenerator.lcon: The constraint lower bound. Can either beNumber,AbstractArray, orGenerator.ucon: The constraint upper bound. Can either beNumber,AbstractArray, orGenerator.name: When given asVal(:name), registers the constraint incorefor later retrieval ascore.nameormodel.name. See@add_confor 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| = 9Empty 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| = 9ExaModels.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 ofConstrainthandles whose rows will be filled.vars: a tuple ofVariablehandles whose values are passed to the callbacks.f!(res, x_local): fillsres[1:ncon_total]givenx_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,
)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.
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 asVal(:name), registers the subexpression incorefor later retrieval ascore.nameormodel.name. See@add_exprfor 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 overbuffered, which is ignored whenlift = true.start: starting point for the lifted variable whenlift = true.buffered: Whentrue(orVal(true)), returns aBufferedExpression: 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, andbuffered = truefor 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 directlyExaModels.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 asVal(:name), registers the objective incorefor later retrieval ascore.nameormodel.name. See@add_objfor 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| = 10ExaModels.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.
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::AbstractArrayas the first positional argument to use its values and infer dimensions fromsize(value). - Pass dimensions (
IntegerorAbstractRange) as positional arguments and supply the uniform initial value via thevaluekeyword.
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().
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 aNumber,AbstractArray, orGenerator.name: When given asVal(:name), registers the parameter incorefor later retrieval ascore.nameormodel.name. See@add_parfor 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}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.
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().
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).
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 beNumber,AbstractArray, orGenerator.lvar: The variable lower bound. Can either beNumber,AbstractArray, orGenerator.uvar: The variable upper bound. Can either beNumber,AbstractArray, orGenerator.name: When given asVal(:name), registers the variable incorefor later retrieval ascore.nameormodel.name. See@add_varfor 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}
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).
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).
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)graphy: result vectoradj: adjoint propagated up to the current node
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)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.
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.
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, ensuringjuliac --trim=safecan resolveVal{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 capturedExaModels.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.
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))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.
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 sExaModels.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
trueExaModels.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
trueExaModels.get_lcon — Method
get_lcon(model, con::Constraint)Return a view of the lower bounds for con.
ExaModels.get_lvar — Method
get_lvar(model, var::Variable)Return a view of the lower bounds for var.
ExaModels.get_nscen — Method
get_nscen(model::TwoStageExaModel)Return the total number of scenarios.
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
trueExaModels.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
trueExaModels.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).
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.
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.
ExaModels.get_ucon — Method
get_ucon(model, con::Constraint)Return a view of the upper bounds for con.
ExaModels.get_uvar — Method
get_uvar(model, var::Variable)Return a view of the upper bounds for var.
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.0ExaModels.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.
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).
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 sExaModels.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
trueExaModels.gradient! — Method
gradient!(y, f, x, adj)Performs dense gradient evaluation
Arguments:
y: result vectorf: the function to be differentiated inSIMDFunctionformatx: variable vectoradj: initial adjoint
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)graphcomp: aCompressor, which helps map counter to sparse vector indexy: result vectoro1: index offsetcnt: counteradj: adjoint propagated up to the current node
ExaModels.has_matfree_hess — Method
has_matfree_hess(oracle::VectorNonlinearOracle)Return true if the oracle provides a matrix-free Hessian-vector product (hvp!).
ExaModels.has_matfree_jac — Method
has_matfree_jac(oracle::VectorNonlinearOracle)Return true if the oracle provides matrix-free Jacobian-vector products (jvp! and vjp!).
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 subtreet2: leaf of the second subtreecomp: aCompressor, which helps map counter to sparse vector indexy1: result vector #1y2: result vector #2 (only used when evaluating sparsity)o2: index offsetcnt: counteradj: second adjoint propagated up to the current node
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
trueExaModels.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)graphcomp: aCompressor, which helps map counter to sparse vector indexi: constraint index (this isi-th constraint)y1: result vector #1y2: result vector #2 (only used when evaluating sparsity)o1: index offsetcnt: counteradj: adjoint propagated up to the current node
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
trueExaModels.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)
trueExaModels.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)
trueExaModels.objective — Method
objective(core::ExaCore, oracle::ScalarNonlinearOracle)Register a scalar objective oracle with core.
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.
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.
ExaModels.set_lcon! — Method
set_lcon!(model, con::Constraint, values)Update the lower bounds for con in-place.
ExaModels.set_lvar! — Method
set_lvar!(model, var::Variable, values)Update the lower bounds for var in-place.
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).
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.
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.
ExaModels.set_ucon! — Method
set_ucon!(model, con::Constraint, values)Update the upper bounds for con in-place.
ExaModels.set_uvar! — Method
set_uvar!(model, var::Variable, values)Update the upper bounds for var in-place.
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))ExaModels.set_value! — Method
set_value!(model, param, values)Update all values for param in model.θ to values.
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.
ExaModels.sgradient! — Method
sgradient!(y, f, x, adj)
Performs sparse gradient evaluation
Arguments:
y: result vectorf: the function to be differentiated inSIMDFunctionformatx: variable vectoradj: initial adjoint
ExaModels.shessian! — Method
shessian!(y1, y2, f, x, adj1, adj2)Performs sparse jacobian evaluation
Arguments:
y1: result vector #1y2: result vector #2 (only used when evaluating sparsity)f: the function to be differentiated inSIMDFunctionformatx: variable vectoradj1: initial first adjointadj2: initial second adjoint
ExaModels.sjacobian! — Method
sjacobian!(y1, y2, f, x, adj)Performs sparse jacobian evaluation
Arguments:
y1: result vector #1y2: result vector #2 (only used when evaluating sparsity)f: the function to be differentiated inSIMDFunctionformatx: variable vectoradj: initial adjoint
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)
trueExaModels.@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 constraintc1is passed explicitly and the generator yieldsidx => exprpairs. - 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-leveladd_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)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)): bindsgto the newConstraintin the local scope and registers it incorefor later retrieval ascore.gormodel.g. - Anonymous (
@add_con(core, generator)): equivalent toc, 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 worksExaModels.@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)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)): bindssto the newExpressionin the local scope and registers it incorefor later retrieval ascore.sormodel.s. - Anonymous (
@add_expr(core, generator)): equivalent toc, 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)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)): bindsfto the newObjectivein the local scope and registers it incorefor later retrieval ascore.formodel.f. - Anonymous (
@add_obj(core, generator)): equivalent toc, o = add_obj(c, generator).
Example
c = ExaCore()
@add_var(c, x, 10)
@add_obj(c, x[i]^2 for i in 1:10)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 newParameterin the local scope and registers it incorefor later retrieval ascore.θormodel.θ. - Anonymous (
@add_par(core, start)): equivalent toc, p = add_par(c, start).
Example
c = ExaCore()
@add_par(c, θ, ones(10)) # θ is now in scope; c.θ also worksExaModels.@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...)): bindsxto the newVariablein the local scope and registers it incorefor later retrieval ascore.xormodel.x. - Anonymous (
@add_var(core, dims...)): equivalent toc, 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 worksExaModels.@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:
- Node OP Node —
f(d1::AbstractNode, d2::AbstractNode) → Node2(f, d1, d2). - Node OP Real —
f(d1::AbstractNode, d2::Real) → Node2(f, d1, d2). Numeric scalars (including iterator-derived values likefactorial(j)) are stored directly inNode2without wrapping inConstant. - Real OP Node — symmetric counterpart of the above.
- Constant folding —
f(Constant{I1}(), Constant{I2}()) → Constant(f(I1, I2)). Both-constant expressions are evaluated immediately.
Arguments
f: the function to registerdf1: partial derivative w.r.t. the first argumentdf2: partial derivative w.r.t. the second argumentddf11: second partial w.r.t. the first argumentddf12: mixed second partialddf22: 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)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:
Primal graph node —
f(n::AbstractNode) → Node1(f, n). Applied at model-construction time to build the symbolic graph.Constant folding —
f(::Constant{T}) → Constant(f(T)). When the argument is aConstant(value encoded as a type parameter), the result is evaluated immediately and stored as a newConstant, avoiding aNode1allocation entirely.Adjoint / second-adjoint nodes — forward-pass nodes for gradient and Hessian computation, using
dfandddfas the derivative functions.
Arguments
f: the function to registerdf: first derivativef'(x)ddf: second derivativef''(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)