Getting Started

ExaModels can create nonlinear programming models and allows solving the created models using NLP solvers (in particular, those that are interfaced with NLPModels, such as NLPModelsIpopt and MadNLP. This documentation page will describe how to use ExaModels to model and solve nonlinear optimization problems.

We will first consider the following simple nonlinear program [3]:

\[\begin{aligned} \min_{\{x_i\}_{i=0}^N} &\sum_{i=2}^N 100(x_{i-1}^2-x_i)^2+(x_{i-1}-1)^2\\ \text{s.t.} & 3x_{i+1}^3+2x_{i+2}-5+\sin(x_{i+1}-x_{i+2})\sin(x_{i+1}+x_{i+2})+4x_{i+1}-x_i e^{x_i-x_{i+1}}-3 = 0 \end{aligned}\]

We will follow the following Steps to create the model/solve this optimization problem.

  • Step 0: import ExaModels.jl
  • Step 1: create a ExaCore object, wherein we can progressively build an optimization model.
  • Step 2: create optimization variables with @add_var (or add_var), while attaching it to previously created ExaCore.
  • Step 3 (interchangable with Step 3): create objective function with @add_obj (or add_obj), while attaching it to previously created ExaCore.
  • Step 4 (interchangable with Step 2): create constraints with @add_con (or add_con), while attaching it to previously created ExaCore.
  • Step 5: create an ExaModel based on the ExaCore.

Now, let's jump right in. We import ExaModels via (Step 0):

using ExaModels

Now, all the functions that are necessary for creating model are imported to into Main.

ExaCore

An ExaCore object can be created simply by (Step 1):

c = ExaCore(concrete = Val(true))
An ExaCore

  Float type: ...................... Float64
  Array type: ...................... Vector{Float64}
  Backend: ......................... Nothing

  number of objective patterns: .... 0
  number of constraint patterns: ... 0

This is where our optimization model information will be progressively stored. This object is not yet an NLPModel, but it will essentially store all the necessary information.

Variables

Now, let's create the optimization variables. From the problem definition, we can see that we will need $N$ scalar variables. We will choose $N=10$, and create the variable $x\in\mathbb{R}^{N}$ with the following command:

N = 10
@add_var(c, x, N; start = (mod(i, 2) == 1 ? -1.2 : 1.0 for i in 1:N))
Variable

  x ∈ R^{10}

This creates the variable x, which we will be able to refer to when we create constraints/objective constraints. Also, this modifies the information in the ExaCore object properly so that later an optimization model can be properly created with the necessary information. Observe that we have used the keyword argument start to specify the initial guess for the solution. The variable upper and lower bounds can be specified in a similar manner. For example, if we wanted to set the lower bound of the variable x to 0.0 and the upper bound to 10.0, we could do it as follows:

@add_var(c, x, N; start = (mod(i, 2) == 1 ? -1.2 : 1.0 for i = 1:N), lvar = 0.0, uvar = 10.0)

Objective

The objective can be set as follows:

@add_obj(c, 100 * (x[i - 1]^2 - x[i])^2 + (x[i - 1] - 1)^2 for i in 2:N)
Objective

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

  f(x,i) = 100 * x[i - 1]^2 - x[i]^2 + x[i - 1] - 1^2

  where |I| = 9
Note

Note that the terms here are summed, without explicitly using sum( ... ) syntax.

Constraints

The constraints can be set as follows:

@add_con(
    c,
    3x[i + 1]^3 + 2 * x[i + 2] - 5 + sin(x[i + 1] - x[i + 2])sin(x[i + 1] + x[i + 2]) + 4x[i + 1] -
        x[i]exp(x[i] - x[i + 1]) - 3 for i in 1:(N - 2)
)
Constraint

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

  g(x,i) = 3 * x[i + 1]^3 + 2 * x[i + 2] - 5 + sin(x[i + 1] - x[i + 2]) * sin(x[i + 1] + x[i + 2]) + 4 * x[i + 1] - x[i] * exp(x[i] - x[i + 1]) - 3

  where |I| = 8

Note that ExaModels always assume that the constraints are doubly-bounded inequalities. That is, the constraint above is treated as

\[ g^\flat \leq \left[g^{(m)}(x; q_j)\right]_{j\in [J_m]} +\sum_{n\in [N_m]}\sum_{k\in [K_n]}h^{(n)}(x; s^{(n)}_{k}) \leq g^\sharp\]

where g^\flat and g^\sharp are the lower and upper bounds of the constraint, respectively. In this case, both bounds are zero, i.e., g^\flat = g^\sharp = 0.

You can use the keyword arguments lcon and ucon to specify the lower and upper bounds of the constraints, respectively. For example, if we wanted to set the lower bound of the constraint to -1 and the upper bound to 1, we could do it as follows:

@add_con(
    c,
    3x[i + 1]^3 + 2 * x[i + 2] - 5 + sin(x[i + 1] - x[i + 2])sin(x[i + 1] + x[i + 2]) + 4x[i + 1] -
        x[i]exp(x[i] - x[i + 1]) - 3 for i in 1:(N - 2);
    lcon = -1.0, ucon = 1.0
)
Constraint

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

  g(x,i) = 3 * x[i + 1]^3 + 2 * x[i + 2] - 5 + sin(x[i + 1] - x[i + 2]) * sin(x[i + 1] + x[i + 2]) + 4 * x[i + 1] - x[i] * exp(x[i] - x[i + 1]) - 3

  where |I| = 8

If you want to create a single-bounded constraint, you can set lcon to -Inf or ucon to Inf. For example, if we wanted to set the lower bound of the constraint to -1 and the upper bound to infinity, we could do it as follows:

@add_con(
    c,
    3x[i + 1]^3 + 2 * x[i + 2] - 5 + sin(x[i + 1] - x[i + 2])sin(x[i + 1] + x[i + 2]) + 4x[i + 1] -
        x[i]exp(x[i] - x[i + 1]) - 3 for i in 1:(N - 2);
    lcon = -1.0, ucon = Inf
)
Constraint

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

  g(x,i) = 3 * x[i + 1]^3 + 2 * x[i + 2] - 5 + sin(x[i + 1] - x[i + 2]) * sin(x[i + 1] + x[i + 2]) + 4 * x[i + 1] - x[i] * exp(x[i] - x[i + 1]) - 3

  where |I| = 8

Subexpressions

When complex expressions are reused across multiple objectives or constraints, you can define them as subexpressions using @add_expr (or add_expr). This improves code readability and avoids duplicating the expression tree.

Subexpressions are inlined: when you index s[i], the original expression is substituted directly — no auxiliary variables or equality constraints are created. Derivative code is shared across all uses of the same subexpression pattern.

Here's a simple example:

c2 = ExaCore(concrete = Val(true))
@add_var(c2, y, N; start = 1.0)
Variable

  y ∈ R^{10}

Define a subexpression for y[i]^2

@add_expr(c2, s, y[i]^2 for i in 1:N)
Subexpression (reduced)

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

Now s[i] can be used in objectives and constraints

@add_obj(c2, (s[i] - 1)^2 for i in 1:N)
@add_con(c2, s[i] + s[i + 1] for i in 1:(N - 1); lcon = 0.0)
Constraint

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

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

  where |I| = 9

Multi-dimensional subexpressions are also supported with automatic dimension inference:

@add_expr(c, dx, x[t, i] - x[t-1, i] for t in 1:T, i in 1:N)
# dx[t, i] can now be used in constraints
@add_con(c, dx[t, i] - something for t in 1:T, i in 1:N)

When subexpressions are deeply nested (subexpressions referencing other subexpressions), inlining duplicates the tree at every use site, and compilation cost grows multiplicatively with the nesting depth. Passing buffered = true stores the subexpression in an internal buffer instead: each element is evaluated once per model evaluation, consumers reference the buffered value through a single leaf node, and first- and second-order derivatives are propagated through the buffer, so compilation cost is additive in the nesting depth.

@add_expr(c, s, x[i]^2 + sin(x[i+1]) for i in 1:(N - 1); buffered = true)
@add_expr(c, t, s[i] * s[i+1] for i in 1:(N - 2); buffered = true)
@add_obj(c, t[i]^2 for i in 1:(N - 2))

When a consumer must sum many buffered elements, as a group argument in a group-partially-separable problem does, add_expr! adds the sum to a buffered expression as data instead of as an expression tree, the way add_con! adds terms to constraint rows: each term is an affine combination of existing buffered slots and variables with constant coefficients, so a slot summing thousands of elements costs one stage and nothing grows with the term count, and every consumer of the expression, earlier or later, sees the augmented value. Buffer the element functions, create the group values from their constant parts, then add the terms. With elems the element data, terms the (group, weight, element) triples and b the group constants:

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

A third form, add_expr(...; lift = true), introduces the subexpression as a variable pinned by a defining equality constraint (adding rows and columns to the problem), which keeps every consumer's tree shallow at the cost of a larger KKT system.

Choosing between inlined and buffered subexpressions

Inlining (the default) substitutes the subexpression into each use site at no runtime cost, and is preferable when a subexpression is used once or twice at shallow depth. Buffering evaluates the subexpression once per model evaluation and is preferable when a subexpression is shared across many objectives or constraints, or nested inside other subexpressions: inlined compilation cost grows multiplicatively with the nesting depth, while buffered compilation cost is additive, and inlined evaluation recomputes each shared subexpression at every use site, while buffered evaluation computes it once. Buffered subexpressions work on GPU backends, including hprod!; jprod_nln! and jtprod_nln! are not available for them on device backends, while the sparse Jacobian and Hessian callbacks used by interior-point solvers are fully supported.

Block merging and the sparsity footprint

Constraint and objective blocks whose expression trees have the same structure are merged into one family at construction time, so a model written as a loop of scalar add_con/add_obj calls costs what the single-generator form costs to compile. Merging does not change the sparsity of a block: each block keeps the nonzero layout its plain form has, in both storage modes, so repeated references to one variable in a row share one Jacobian entry and an inlined subexpression spliced at several sites counts each variable once. meta.nnzj/meta.nnzh and the coordinate lists are those of the unmerged model; recipe cores (built against ArgSource placeholders) are stored unmerged, and a recipe and a direct build of one model agree on them.

For a comprehensive example using subexpressions, see the Distillation Column example.

ExaModel

Finally, we are ready to create an ExaModel from the data we have collected in ExaCore. Since ExaCore includes all the necessary information, we can do this simply by:

m = ExaModel(c)
An ExaModel{Float64, Vector{Float64}, ...}

  Problem name: Generic
   All variables: ████████████████████ 10     All constraints: ████████████████████ 24    
            free: ████████████████████ 10                free: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0     
           lower: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0                lower: ███████⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 8     
           upper: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0                upper: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0     
         low/upp: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0              low/upp: ███████⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 8     
           fixed: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0                fixed: ███████⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 8     
          infeas: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0               infeas: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0     
            nnzh: (-210.91% sparsity)   171             linear: ⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅⋅ 0     
                                                    nonlinear: ████████████████████ 24    
                                                         nnzj: ( 70.00% sparsity)   72    
                                                     lin_nnzj: (------% sparsity)         
                                                     nln_nnzj: ( 70.00% sparsity)   72    

Now, we got an optimization model ready to be solved. This problem can be solved with for example, with the Ipopt solver, as follows.

using NLPModelsIpopt
result = ipopt(m)
"Execution stats: first-order stationary"

Here, result is an AbstractExecutionStats, which typically contains the solution information. We can check several information as follows.

println("Status: $(result.status)")
println("Number of iterations: $(result.iter)")
Status: first_order
Number of iterations: 8

Solutions

The solution values for variable x can be inquired by:

sol = solution(result, x)
10-element view(::Vector{Float64}, 1:10) with eltype Float64:
 -0.9505563573613093
  0.9139008176388945
  0.9890905176644905
  0.9985592422681151
  0.9998087408802769
  0.9999745932450962
  0.9999966246997652
  0.999999551252415
  0.9999999449191489
  0.9999999300651202

This will return the primal solution of the variable x as a vector. Dual solutions can be inquired similarly, by using the multipliers function.

ExaModels provide several APIs similar to this:

This concludes a short tutorial on how to use ExaModels to model and solve optimization problems. Want to learn more? Take a look at the following examples, which provide further tutorial on how to use ExaModels.jl. Each of the examples are designed to instruct a few additional techniques.


This page was generated using Literate.jl.