oximo requires Rust 1.89 or later (edition 2024). Install Rust with
rustup if you do not already have it.
Create a project and add oximo:
cargo new my-oximo-model --edition 2024cd my-oximo-modelcargo add oximo
This default dependency is enough to construct models and use the MPS, LP, and
NL I/O APIs. You will need to choose a solver feature before solving a model.
Semidefinite programming (SDP) support is available by choosing one BLAS/LAPACK provider:
Feature
Provider
Typical platform
clarabel-sdp-openblas
OpenBLAS
Linux; source builds need C and Fortran compilers
clarabel-sdp-mkl
Intel MKL
Windows or Linux
clarabel-sdp-accelerate
Apple Accelerate
macOS
The bare clarabel-sdp feature enables SDP when your application supplies BLAS/LAPACK linkage.
On Windows, the OpenBLAS feature uses a system installation.
The Solvers guide compares model-kind support and summarizes the
installation requirements of every backend. Enable a backend with its feature,
for example:
[dependencies]oximo = { version = "0.8", features = ["pounce"] }
With no solver feature, you can still construct models and export them through
the default io feature.
pounce uses finite-difference derivatives for nonlinear expressions by
default. The nightly-only pounce-enzyme feature provides exact gradients,
Jacobians, and Hessians through Enzyme.
It requires a nightly Rust toolchain with the enzyme component,
RUSTFLAGS="-Zautodiff=Enable", and a fat-LTO profile:
This guide builds a small linear program one piece at a time. Youβll declare
variables, add constraints and an objective, then solve the model and inspect
the result. For a full setup walkthrough, see Installation.
This example requires Rust 1.89 or later. Create a project first:
cargo new lp-model --edition 2024cd lp-model
Important:cargo add oximo by itself does not enable a solver. Add oximo with a backend feature so this program can solve the model. Choose one of the following commands and run it from the project directory.
If you donβt have a C/C++ compiler, use Clarabel instead. It is pure Rust and
solves continuous LP, QP, and SOCP models, but does not solve mixed-integer
models:
cargo add oximo --features clarabel
The modeling code is the same with either backend. See Solvers
for the full backend list and compatibility comparison.
Weβll maximize the value of two decision variables, x and y, subject to a
few constraints:
$$
\begin{aligned}
\max \quad & 3x + 4y \\
\text{s.t.} \quad & x + 2y \le 14 \\
& 3x \ge y \\
& x \le y + 2 \\
& x \ge 0 \\
& 0 \le y \le 4
\end{aligned}
$$
The objective rewards larger values of x and y. The constraints limit their
combination, require x to be nonnegative, and keep y between zero and four.
Open src/main.rs. The following lines create the model. This version uses
HiGHS; if you chose Clarabel, use the alternative shown in Choose the solver.
use oximo::prelude::*;use oximo::solvers::Highs;fn main() -> Result<(), Box<dyn std::error::Error>> { let m = Model::new("example LP");
The prelude brings in the modeling macros and common types. Model::new
creates an empty model; the ? in main lets errors from solving and querying
results propagate to the caller.
To create the variables, add these lines inside main, after Model::new:
variable!(m, x >= 0.0); variable!(m, 0.0 <= y <= 4.0);
Each variable! call registers a variable on the model and makes its name
available as an expression in Rust. Bounds are part of the declaration, so the
solver cannot return a value outside them.
Next, add the three relationships and tell oximo what to maximize:
constraint!(m, capacity, x + 2.0 * y <= 14.0); constraint!(m, ratio, 3.0 * x >= y); constraint!(m, balance, x <= y + 2.0); objective!(m, Max, 3.0 * x + 4.0 * y);
A constraint has a name followed by an algebraic relation. The names make solver output easier to read later. objective! records the expression and direction.
To query the results, we can use print statements, then close main:
let result = Highs.solve(&m, &HighsOptions::default())?; println!("objective = {:?}", result.objective()); println!("x = {:?}", result.value_of(x)?); println!("y = {:?}", result.value_of(y)?); Ok(())}
Run the program from the project directory:
cargo run
The optimum is x = 6, y = 4, with objective value 34. The
result accessors return Option values because a solve might not produce a
usable solution; for real applications, check the solver status before relying
on them. See Results for status handling and more result queries.
If you installed Clarabel instead of HiGHS, change the solver import and solve
line in main.rs:
use oximo::solvers::Clarabel;let result = Clarabel.solve(&m, &ClarabelOptions::default())?;
Remove use oximo::solvers::Highs; and replace the HiGHS solve line with the Clarabel line. All the model declarations stay the same. Both backends implement the same Solver interface.
Modeling: indexed variables, sets, parameters, and nonlinear expressions
Solvers: compare backends and configure solver options
Results: check termination status, values, duals, and reduced costs
Modeling
oximo's modeling layer lets you describe an optimization problem with idiomatic Rust.
You write models using declarative macros that mirror algebraic notation, set algebra for indices, operator-overloaded expressions, and rule-style constraint generation.
Everything on this page is re-exported from oximo::prelude.
Variables are the quantities a solver may choose. variable!
registers one on the model and binds a Rust variable of the same name, so the
symbol is immediately usable in later expressions. Bounds are written the way
you'd write them on paper.
use oximo::prelude::*;let m = Model::new("my_model");variable!(m, x >= 0.0); // continuous, x β₯ 0variable!(m, 0.0 <= y <= 10.0); // continuous, 0 β€ y β€ 10variable!(m, z); // free, unbounded by defaultvariable!(m, b, Bin); // binary {0, 1} (also Binary)variable!(m, n >= 0.0, Int); // general integer (also Integer)variable!(m, s <= 10.0, SemiCont(2.0)); // semicontinuous: 0 or in [2, 10]
Bounds, domain, warm start, and fixing can also be passed as keyword arguments after the name:
variable!(m, x, lb = 0.0, ub = 1.0); // same as `0.0 <= x <= 1.0`variable!(m, n, lb = 0.0, domain = Int); // keyword domainvariable!(m, w, lb = 0.0, ub = 10.0, Int); // mixed with a positional domain tokenvariable!(m, p, lb = 0.0, initial = 3.0); // warm start (scalar only)variable!(m, q, fix = 5.0); // fixed to 5.0 (scalar only)
A parameter is data that can change while the model structure stays fixed. It
stays symbolic in the model, so param! lets you build once and re-bind its
value between solves without rebuilding variables, constraints, or the
objective. This is useful for scenario sweeps.
param!(m, p1 = 0.0);variable!(m, x1 >= 0.0);objective!(m, Max, p1 * x1);for price in [1.0, 1.6, 2.0] { p1.set_param_value(price)?; let result = Highs.solve(&m, &HighsOptions::default())?; println!("{price} -> {:?}", result.objective());}
A parameter times a variable stays linear, so the model kind is unchanged by re-binding.
Re-binding returns a ModelError when the write is invalid, for example a
non-finite value or a bound-ordering conflict, and leaves the previous value in
place.
For parameter sweeps, it is recommended to use a Persistent solver if available. See Solvers for details.
A Set is the modeling-layer container for an ordered, finite index set
over integers, strings, or tuples. Use one to name the domain of an indexed
variable, a generated constraint, or a sum.
Most domains need no explicit Set, since an integer range is already
a domain (x[i in 0..5], sum!(β¦ for i in 0..n)).
Reach for Set when keys are strings, tuples, sparse, or a
subset reused across statements.
The set! macro binds a named set. A plain right side is normalized to an owned set, while a pat in domain [if cond] comprehension builds and optionally filters one.
use oximo::prelude::*;let plants = Set::strings(["seattle", "san-diego"]);set!(items = 0..5); // range normalized to Set<usize>set!(routes = plants * plants); // Cartesian product// Comprehension: product domain + by-value `if`. These two are equivalent.set!(arcs = (p, q) in &plants * &plants if p != q); // single tuple patternset!(arcs = i in plants, j in plants if i != j); // multi-bind product// The typed filter is also a Set method (the receiver pins the key type):let diag = (&plants * &plants).filter_typed(|(p, q)| p == q);// Sparse / string leaf sets:let sparse = Set::from_ints([0, 2, 4, 8]);
Many optimization quantities vary by period, product, or route. The indexed
form, variable!(m, x[k in set]), registers one scalar per key and auto-names
it like x[seattle,nyc]. Bounds apply uniformly by default. A multi-index
family ranges over a Cartesian product.
let m = Model::new("transport");variable!(m, x[r in routes] >= 0.0); // one var per routevariable!(m, y[k in items] >= 0.0, Int); // integer familyvariable!(m, z[a in rows, b in cols], Bin); // multi-index (Cartesian product)// Scalar lookup: any type that converts to IndexKey works.let e1 = x[("seattle", "nyc")];let e2 = z[(a, b)];// Per-key bounds may reference the index, including a per-key parameter.variable!(m, 0.0 <= w[(p, q) in routes] <= capacity_for(&p, &q));variable!(m, v[k in items], lb = 0.0, ub = cap[k]);// Filtered family: keep only matching keys (no trivial elements built).variable!(m, d[(i, j) in rc if i == j] >= 0.0);
The variable! and param! macros bind reusable Copy identities,
VariableHandle and ParameterHandle. Expressions such as p * x * x + x
work directly, both inside and outside modeling macros.
Arithmetic produces non-Copy computed expressions. Borrow a computed
expression to reuse it, or pass it by value to consume it:
let m = Model::new("expression ownership");variable!(m, x);variable!(m, y);let e = x + y;let a = &e + x; // reuse elet b = e + y; // consume eobjective!(m, Min, &a + b);constraint!(m, cap, a <= 5.0);
The same rule applies when passing a computed expression directly to a macro:
objective!(m, Min, &e) shares it, while objective!(m, Min, e) consumes it.
Cloning a computed expression shares its node and does not copying its expression graph.
When an expression has one term per key, use sum! instead of building a Rust
loop. It produces one Expr that can go anywhere an expression is
accepted.
sum!(body for k in set) reads as \(\sum_{k \in \text{set}} \text{body}\).
The min! and max! macros use the same domains, Cartesian products, and
filters to build one flattened minimum or maximum expression. Their domains
must contain at least one selected key.
Empty sums are handled as the additive identity when the model is known. Sums
inside constraint!, objective!, soc_constraint!, and psd_constraint! inherit that macro's
model automatically, including nested sums and filtered domains:
// If maybe_empty has no selected keys, this contributes the model's zero.constraint!(m, balance, sum!(x[i] for i in maybe_empty) == 0.0);// Use the explicit model form for a standalone sum.let total = sum!(m, x[i] for i in maybe_empty);
The explicit sum!(model, ...) form also ensures that every selected term
belongs to that model. An unanchored standalone sum still needs at least one
term, because it has no model-owned expression context from which to construct
the empty result.
Borrow stored computed terms when a comprehension reuses them. Filtered and
unfiltered sums accept the same owned or borrowed inputs:
let terms = [x + 1.0, x + 2.0];let total = sum!(m, &terms[i] for i in 0..2);let filtered = sum!(m, &terms[i] for i in 0..2 if i != 0);
// Single sum: sum over i in items of weights[i] * x[i]constraint!(m, cap, sum!(weights[i] * x[i] for i in items) <= capacity);// Double sum, flat: sum over (p, q) in plants x marketslet total_cost = sum!(c[p, q] * x[p, q] for p in plants, q in markets);// Filtered sum.let active = sum!(x[i] for i in 0..n if online[i]);// Indexed extrema, with the same domain and filter syntax.let least_slack = min!(capacity[i] - x[i] for i in items);let peak_load = max!(load[t] for t in periods if online[t]);
Constraints define which combinations of variable values are allowed. Give each
one a stable name for readable solver output and diagnostics, then use
constraint! with a relation written as <=, >=, or ==.
A two-sided range becomes a single constraint.
constraint!(m, cap, 2.0 * x + 3.0 * y <= 100.0);constraint!(m, demand, x >= 5.0);constraint!(m, balance, x - y == 0.0);constraint!(m, band, 1.0 <= x + y <= 10.0); // two-sided range -> one constraint
For SOC constraints, use the soc_constraint! macro. Write
[terms] <= t for the standard cone ||terms||_2 <= t, or
[terms] in rotated(u, v) for the rotated cone ||terms||_2^2 <= 2*u*v with
u, v >= 0:
Both heads of a rotated cone are affine expressions or plain numbers, such as
rotated(t, 1.0). The cone itself requires them to be nonnegative, so you do not
declare separate sign constraints.
SOC components and bounds, PSD matrix entries, and indicator consequents must
have constant or affine Rust types. Narrow dynamic expressions explicitly with
try_affine() before passing them to these constructors:
let m = Model::new("checked affine input");variable!(m, x);variable!(m, t >= 0.0);let component = x.powi(1).try_affine().expect("component must be affine");soc_constraint!(m, [component] <= t);
Narrowing checks the expression at runtime and returns an error if it is not
affine. Calling erase() produces a dynamic type and does not satisfy this
requirement. Ordinary scalar constraints still accept dynamic and nonlinear
expressions directly.
A constraint means that a function's value belongs to a set. The familiar
x <= 5.0 pairs an affine function with LessThan(5.0); >=, ==, and
constant two-sided bounds use GreaterThan, EqualTo, and Interval.
SOC and PSD declarations similarly require membership in a cone.
The macros create these pairs for you. When building constraints in a helper
function, you can also register a pair directly:
let cap = m.add_constraint( "capacity", Constraint::new((2.0 * x + y).into_function(), LessThan(100.0)),);
Registration preserves the original function and set, including symbolic
parameters. A mathematically valid pair still needs a compatible backend;
see Checking model compatibility.
Capture the return value of a declaration to keep its typed, model-bound handle.
let cap = constraint!(m, capacity, x <= 5.0);m.set_constraint_set(cap, LessThan(8.0))?;m.set_constraint_function(cap, (2.0 * x).into_function())?;m.set_constraint_active(cap, false)?;m.set_constraint_active(cap, true)?;
Updates preserve the ID and the function/set types. To replace LessThan with
EqualTo, or an affine function with a quadratic one, deactivate the old
constraint and add a new one. Invalid bounds, incompatible dimensions, and handles
from another model are rejected.
For a collection of different constraint types, store handle.erase().
After an SOS or indicator has been reformulated, its source cannot be edited
or reactivated.
A positive semidefinite (PSD) constraint requires every eigenvalue of a real
symmetric matrix to be nonnegative. Use symmetric_variable! to declare its
entries and psd_constraint! to require the matrix to be PSD. A symmetric
variable declaration alone creates free continuous variables and it does not
impose positivity or bounds.
symmetric_variable!(m, X[n]) returns a SymmetricMatrix<VariableHandle<'_>> with
n * (n + 1) / 2 independent variables. Mirrored entries refer to the same
variable. Use X[(i, j)] in Rust expressions, while modeling macros also accept
the X[i, j] notation. The side dimension must be positive.
For numeric matrix data, dense rows avoid triangle ordering:
let c = SymmetricMatrix::try_from_rows([[2.0, 1.0], [1.0, 2.0]])?;let identity = SymmetricMatrix::<f64>::identity(2);println!("C = {c}");println!("I = {identity}");
Matrices support addition, subtraction, negation, scalar multiplication,
trace(), and frobenius(&other). frobenius computes the full matrix inner
product, counting each stored off-diagonal product twice. Matrices combined by
arithmetic must have matching dimensions.
A PSD constraint can contain any symmetric matrix of constant or affine
entries, including symbolic parameters.
For example, minimizing t subject to t I - C being PSD gives the largest
eigenvalue of C. The eigenvalues of t I - C are t minus those of C, so
PSD membership requires t to be at least the largest eigenvalue.
Quadratic and nonlinear matrix entries are rejected. The current SDP support is
limited to real symmetric matrices.
PSD declarations support named, anonymous, computed-name, indexed, and filtered
forms. For a symmetric matrix variable X:
let identity = SymmetricMatrix::<f64>::identity(2);let shifts = [0.0, 1.0, 2.0];psd_constraint!(m, shifted[i in 0..shifts.len()], &X + shifts[i] * &identity);let extra = psd_constraint!(m, name = "extra positivity".to_owned(), &X);m.set_psd_active(extra, false)?;
A scalar declaration returns a PsdConstraintHandle. Retrieve a registered
handle with m.psd_constraint_handle("shifted[0]"). PSD constraints have their
own registry, separate from scalar and SOC constraints. Inactive PSD blocks
are excluded from solving and model-kind classification.
The indicator_constraint! macro applies an affine
relation only when a binary trigger has a selected value. The implication is
one-way: when the trigger has the other value, the relation is not enforced.
variable!(m, enabled, Binary);variable!(m, -10.0 <= x <= 20.0);indicator_constraint!(m, capacity, enabled == 1 => x <= 8.0);indicator_constraint!(m, shutdown, enabled == 0 => x == 0.0);indicator_constraint!(m, operating_band, enabled == 1 => -2.0 <= x <= 4.0);
The trigger must be a bare binary variable from the same model, its selected
value must be the literal 0 or 1, and the consequent must be affine. The
constraint does not imply the reverse direction: satisfying x <= 8.0 does
not force enabled to equal 1.
Indicator constraints support the same indexed-family and computed-name forms
as ordinary constraints:
variable!(m, enabled[t in periods], Binary);variable!(m, production[t in periods] >= 0.0);indicator_constraint!( m, capacity[t in periods if available[t]], enabled[t] == 1 => production[t] <= capacity_at(t),);let row_name = "shutdown_final";indicator_constraint!( m, name = row_name, enabled[last] == 0 => production[last] == 0.0,);
Gurobi, MOSEK, and SCIP consume indicators natively. GAMS supports them when an
explicit COPT, CPLEX, Gurobi, SCIP, or Xpress sub-solver is selected. Other
backends return SolverError::UnsupportedIndicator while active indicators
remain in the model. To use one of those backends, explicitly replace the
indicators with linear Big-M rows:
use oximo::prelude::*;use oximo::{HighsOptions, solvers::Highs};let m = Model::new("reformulated_indicators");variable!(m, produce, Binary);variable!(m, 0.0 <= quantity <= 10.0);indicator_constraint!(m, capacity, produce == 1 => quantity <= 7.0);indicator_constraint!(m, shutdown, produce == 0 => quantity == 0.0);objective!(m, Max, quantity + 2.0 * produce);let artifacts = m.reformulate_indicators(IndicatorReformulationOptions::default())?;let result = Highs.solve(&m, &HighsOptions::default())?;
Model::reformulate_indicators changes the model in place without cloning it
and returns artifacts containing GeneratedConstraintId values. To retain the
native-indicator model, use m.to_reformulated_indicator_model(options) to make
an independent transformed model. Both forms preserve source indicator IDs,
mark the sources inactive, and record generated constraint IDs in
indicator_reformulations(). They add no variables. For one indicator, use its
handle's reformulate(&m, options) or to_reformulated_model(&m, options) method.
To query a transformed copy's results with your original model's handles,
use source-result projection.
Each returned report supports println!("{report}") for a summary and
report.display(&m) for the source indicator and generated algebraic rows.
Each finite side of an indicator gets a Big-M row. oximo derives M from the
body's affine coefficients and variable bounds, including the zero option for
semi-continuous and semi-integer variables. For an unbounded side, pass a
positive, finite fallback M to the in-place call instead:
let options = IndicatorReformulationOptions::default().with_fallback_big_m(1.0e6);m.reformulate_indicators(options)?;
SOS1 and SOS2 constraints are native special ordered sets. SOS1 allows at most
one nonzero member. SOS2 allows at most two adjacent nonzero members according
to their ordering weights.
Use the short form when member order itself defines the weights. It assigns
consecutive weights 1.0, 2.0, and so on:
sos_constraint!(m, one_choice, SOS1, [x, y, z]);sos_constraint!(m, adjacent_choice, SOS2, [x, y, z]);
Use explicit (variable, weight) pairs when the ordering values are meaningful
or nonuniform:
The indexed form creates one SOS constraint for every key in the binder. The
index domain must be written explicitly; the macro cannot infer it from an
IndexedVar:
variable!(m, x[i in 0..n] >= 0.0);variable!(m, y[i in 0..n] >= 0.0);variable!(m, z[i in 0..n] >= 0.0);sos_constraint!(m, choice[i in 0..n], SOS1, [x[i], y[i], z[i]]);
This registers choice[0], choice[1], and so on, with positional weights
1.0, 2.0, and 3.0 in each set. Explicit weights work in the same form:
For one SOS over a dynamically assembled collection, use the method API:
let members = vec![x, y, z];m.add_sos_constraint_auto_weights("one_choice", SosType::Sos1, members);
Use Model::add_sos_constraint instead when supplying explicit weights from a
runtime iterator.
Backends with native SOS support, such as Gurobi and SCIP, consume these constraints
directly. Other backends reject a model while it still contains active SOS
constraints. oximo never changes the formulation implicitly, but you can
explicitly replace every active SOS with a portable MILP formulation before
using a backend such as HiGHS:
use oximo::prelude::*;use oximo::{HighsOptions, solvers::Highs};let m = Model::new("reformulated_sos");variable!(m, 0.0 <= x <= 10.0);variable!(m, 0.0 <= y <= 10.0);variable!(m, 0.0 <= z <= 10.0);let choice = sos_constraint!(m, choice, SOS1, [x, y, z]);objective!(m, Max, x + 2.0 * y + 3.0 * z);// Uses each member's finite bounds as its Big-M values. The source SOS is// retained as inactive provenance, while binary variables and linear rows are// appended to `m`.let artifacts = m.reformulate_sos(SosReformulationOptions::default())?;let result = Highs.solve(&m, &HighsOptions::default())?;
Model::reformulate_sos modifies the model in place and returns the generated
variable and constraint IDs. To retain the native-SOS modelβfor example, to
solve it with Gurobi as wellβproduce an independent transformed model instead:
let reformulated = m.to_reformulated_sos_model(SosReformulationOptions::default())?;let result = Highs.solve(&reformulated, &HighsOptions::default())?;
Each returned report supports println!("{report}") for a compact summary.
Use report.display(&m) to include the source SOS, generated variable names and
bounds, and algebraic rows:
for report in &artifacts { println!("{}", report.display(&m));}
For programmatic variable inspection, use report.generated_variables(&m)
to access read-only metadata directly.
To reformulate only one SOS constraint, call
choice.reformulate(&m, options) or choice.to_reformulated_model(&m, options).
A member needs finite bounds in every direction in which it can be nonzero. If
that is not available, pass a positive finite fallback to the in-place call
instead:
let options = SosReformulationOptions::default().with_fallback_big_m(1.0e6);m.reformulate_sos(options)?;
A fallback that is too small truncates the feasible region. Generated Big-M
rows embed the member bounds that existed during reformulation, so those bounds
cannot subsequently be changed on the transformed model. Set those bounds
before reformulating, or change them on a retained native source and make a
fresh reformulated model.
A Model has exactly one objective function, the quantity it minimizes or
maximizes among feasible solutions. Add it after defining the expressions it
uses, with the sense written next to the model.
objective!(m1, Min, 3.0 * x + 5.0 * y);objective!(m2, Max, x + 2.0 * y); // also Minimize/min, Maximize/max
If you have a feasibility problem, use the feas/Feasibility sense.
Use the indexed form of constraint! when the same rule applies
across a set. It emits one constraint per key, auto-named like
supply[seattle], without an explicit Rust loop. A trailing if filters the
keys, and name = expr gives a computed run-time name.
// Scalar set: one constraint per period.let periods = Set::range(0..T);constraint!(m, setup[t in periods], x[t] <= capacity * s[t]);// Tuple set + inner sum builds the LHS expression (key types inferred).constraint!(m, supply[p in plants], sum!(x[p, q] for q in markets) <= supply_of(&p));// Filtered family: only the keys passing the guard are built.constraint!(m, diag[(i, j) in arcs if i == j], x[i, j] <= 1.0);// Computed run-time name.constraint!(m, name = format!("bal_{p}"), inflow[p] - outflow[p] == 0.0);
Nonlinear operations are first-class expression nodes, so they compose with
linear terms and indexed aggregations. Expr provides:
powers: pow, powi, and powf,
roots and magnitude: sqrt, cbrt, and abs,
exponentials and logarithms: exp, exp2, expm1, log/ln, log2,
log10, and log1p/ln_1p,
trigonometric and inverse-trigonometric functions: sin, cos, tan,
asin, acos, and atan,
hyperbolic and inverse-hyperbolic functions: sinh, cosh, tanh,
asinh, acosh, and atanh,
binary atan2, min, and max.
// Rosenbrock NLPobjective!(m1, Min, (1.0 - x).powi(2) + 100.0 * (y - x.powi(2)).powi(2));// Quadratic expression (this disk may be recognized as a second-order cone)constraint!(m2, disk, x.square() + y.square() <= 1.0);// Second-order cone ||(x, y)|| <= t (model kind: SOCP)soc_constraint!(m3, cone, [x, y] <= t);// Transcendental utility (MINLP when any variable is integer/binary)objective!(m4, Max, sum!(u[i] * (1.0 + w[i] * x[i]).log() for i in items));// Functions and extrema compose as ordinary expressions.constraint!(m5, response, x.exp() + y.tanh() <= x.max(y) + 3.0);
Check the inferred ModelKind with Model::kind(). It
summarizes the built-in algebraic and conic views. Use
validate_model to check whether the
chosen backend accepts the complete model, its declared pairs, and options.
πPreserving factors during nonlinear evaluation
Numeric polynomial compaction can change floating-point rounding. Expanding a
square with a large offset can lose a small residual through cancellation,
which can also change the domain of an enclosing logarithm or reciprocal.
Use square_factored() or mul_factored(rhs) when evaluation should retain the
original factors:
let delta = x - 100_000_000.0;let response = delta.square_factored().ln();objective!(m, Min, response);
Use model.affine_builder() to construct an affine expression by adding
terms incrementally, without creating intermediate addition nodes. The
builder accepts constant or affine terms (weighted sums of variables plus a
constant) from the same model.
use oximo::prelude::*;let m = Model::new("incremental terms");variable!(m, x[i in 0..3]);let mut builder = m.affine_builder();for (i, weight) in [2.0, 3.0, 4.0].into_iter().enumerate() { builder.add_term(weight, x[i]);}builder.add_constant(5.0);let lhs = builder.build();constraint!(m, capacity, lhs <= 100.0);
build() returns an affine expression, resets the pending terms and constant,
and retains scratch capacity for reuse in the next row. Numeric terms are
combined into a compact expression. Parameter-dependent terms stay symbolic.
Combining affine terms can change how floating-point additions are grouped.
Mathematically equivalent constructions may therefore produce different
coefficients, especially when large terms cancel.
For repeated contributions to a coefficient with large magnitude differences,
choose model.compensated_affine_builder(). Supplying the original weights
[1e16, 1.0, -1e16] for the same variable retains the coefficient 1, while
ordinary floating-point accumulation gives 0. Compensated summation is
explicit and uses additional arithmetic and scratch storage. It cannot recover
rounding already present in an input expression.
sum! automatically combines f64 or i32 weights with constant or affine
inputs. This can change floating-point rounding. Add unfused: to disable
automatic fusion:
let total = sum!(m, weights[i] * x[i] for i in 0..n);let unfused = sum!(m, unfused: weights[i] * x[i] for i in 0..n);
unfused: also applies to nested sums. Ordinary operator simplifications and
explicit weighted_term inputs remain active.
Generic code may skip automatic fusion and produce different rounding. Use
weighted_term(weight, input) to request builder accumulation explicitly:
let total = sum!(m, weighted_term(weights[i], &terms[i]) for i in 0..n);
Use model.quadratic_builder() when numeric quadratic coefficients or affine
products arrive incrementally. Adding terms writes no intermediate expression
nodes:
let m = Model::new("quadratic coefficients");variable!(m, x);variable!(m, y);let mut builder = m.quadratic_builder();builder.add_product(3.0, x, x)?;builder.add_product(2.0, x, y)?;builder.add_term(-4.0, x)?;builder.add_constant(5.0)?;let quadratic = builder.build(); // 3*x*x + 2*x*y - 4*x + 5objective!(m, Min, quadratic);builder.add_product(1.0, y, y)?;let next = builder.build(); // only y*y; the previous build reset pending termsconstraint!(m, bound, next <= 9.0);
oximo is solver-agnostic, and provides a variety of backends to solve your optimization models.
Every backend implements the same Solver trait, so swapping engines is a one-line change. The general pattern is:
let result = Backend.solve(&model, &BackendOptions::default())?;
result is a SolverResult, the same struct regardless of backend.
Every solve captures the parameters used to translate or update the native
problem. A persistent solve refreshes this snapshot even when only an unused
parameter changes and the native problem is reused. Earlier results keep their
own snapshots, and a solve with no solution still retains its captured
parameters. See Results > Parameter snapshots and scenario queries
for queries using saved or current parameter values.
To determine what backend to use, consider what each backend solves (by model kind) and what it costs and offers (license, install, diagnostics). Each backend's Cargo feature flag is named in its own section below.
The GAMS adapter accepts every model kind at the oximo layer, but actual support depends on the selected sub-solver. Choose one that handles the kind you emit.
License: the underlying solver is commercial and needs a license at runtime. The oximo wrapper crates are all MIT OR Apache-2.0.
Direct interface: talks to the solver in-process. C API/FFI for HiGHS, SCIP, Gurobi, and MOSEK. Pure Rust for Clarabel and POUNCE. BARON and GAMS instead exchange model/result files (.bar, .gms) with an external executable.
C compiler: whether a C/C++ compiler is required at build time.
IIS: computes an irreducible infeasible set to explain an infeasible model.
Warm start: persistent handle for incremental re-solves.
ΒΆ GAMS's pool and duals come from the underlying sub-solver's GDX output (e.g. CPLEX solnpool).
β‘ SCIP returns LP duals and reduced costs only when it can certify a complete original-model LP solution.
Clarabel's build requirements above describe the base clarabel feature.
SDP adds native BLAS/LAPACK dependencies. Compiler and installation requirements
depend on the selected provider.
Use validate_model with the options you intend to solve with. It checks the
complete combination of constraints, objective, and variable domains, including
backend restrictions that a ModelKind alone cannot express:
let mut solver = Highs;let options = HighsOptions::default();let validation = solver.validate_model(&m, &options);for diagnostic in &validation.errors { eprintln!("{}: {}", diagnostic.location(), diagnostic.reason);}validation.into_result()?;let result = solver.solve(&m, &options)?;
Validation uses the complete model structure, selected options, and actual
function data.
Individual support does not establish that constructs can be combined: HiGHS
accepts integer linear models and continuous quadratic objectives separately,
but rejects MIQP.
Capability
Meaning
Native
The backend implements the interface; whole-model and data checks still apply.
Unsupported
The query found no supported interface.
RequiresValidation(reason)
The signature alone is insufficient; actual function data or options must be checked.
Highs is enabled with the highs Cargo feature. No external solver
install is required, but a C/C++ compiler is needed at build time. Add it with
cargo add oximo --features highs.
use oximo::prelude::*;use oximo::solvers::Highs;use std::time::Duration;let result = Highs.solve(&m, &HighsOptions::default() .time_limit(Duration::from_secs(60)) .threads(4) .mip_gap(0.01) .verbose(true) .method(HighsMethod::Ipm))?;
Clarabel is a conic interior-point solver. The base clarabel
feature is pure Rust, requires no external solver installation or license,
and handles continuous LP, QP (convex quadratic objectives), and SOCP models.
use oximo::prelude::*;use oximo::solvers::Clarabel;let result = Clarabel.solve(&m, &ClarabelOptions::default())?;
Enable clarabel-sdp with BLAS/LAPACK linkage, or select a provider feature
such as clarabel-sdp-mkl; see Installation.
This adds continuous SDP with real symmetric affine PSD blocks, linear rows,
and SOC constraints. Objectives may be affine or convex quadratic when
minimizing (concave quadratic when maximizing). General quadratic constraints,
nonlinear expressions, and integer variables are unsupported on this path.
Clarabel.persistent() updates compatible numerical data between solves.
Changes to cone structure rebuild the solver. Chordal decomposition,
presolve, or dropped structural zeros can also prevent a native update, in
which case oximo rebuilds automatically.
Default stable path: LP/QP/QCP models use exact analytic derivatives,
including Jacobian rows and the constant Lagrangian Hessian. Nonlinear models
use compiled tapes with finite-difference nonlinear derivatives and a
limited-memory L-BFGS Hessian.
PounceSolverSelection::Auto is the default. It certifies convexity before
selecting a specialized engine:
LP and convex QP use the convex IPM.
SOCP with a convex objective uses the conic IPM, including explicit cones and
recognized quadratic SOC forms.
QCP, indefinite QP, and general NLP use the TNLP/builder path.
Inconclusive convexity checks fall back to NLP.
A numerical failure in an automatically selected LP or detected-SOCP route gets
one NLP attempt. The specialized convex engines currently have no
time-limit hook, with a time limit, Auto uses NLP.
PounceOptions provides dedicated setters and typed builders for POUNCE's
option reference:
use oximo::pounce::{MuStrategy, PounceOptions, PounceSolverSelection};let options = PounceOptions::default() .tol(1e-8) .mu_strategy(MuStrategy::Adaptive) .solver_selection(PounceSolverSelection::Auto) .presolve(true) .linear_solver("feral");// Escape hatch for an option not exposed by a dedicated setter.let options = options.set("acceptable_tol", 1e-5);
The backend manages print_level, max_cpu_time, warm_start_init_point, and
hessian_approximation. Configure those through the corresponding oximo options
or persistent handle.
Scip solves LP, MILP, QP, MIQP, QCP, MIQCP, SOCP, MISOCP, NLP,
and MINLP models through russcip. Enable scip to download bundled SCIP
binaries at build time:
[dependencies]oximo = { version = "0.8", features = ["scip"] }
use oximo::prelude::*;use oximo::solvers::Scip;use oximo::ScipOptions;let result = Scip::new().solve(&m, &ScipOptions::default() .mip_gap(0.01) .node_limit(10_000))?;
For an existing SCIP installation, use scip-system instead of scip. Set
SCIPOPTDIR to a SCIP development tree containing include/scip headers and
lib/libscip*, or let the build find SCIP via CONDA_PREFIX or standard system
paths. The system build generates bindings with libclang. The scip and
scip-system features cannot be combined.
SCIP supports native SOS1/SOS2 sets, affine indicator constraints,
semi-continuous and semi-integer variables, and explicit second-order cones.
Nonlinear expressions support arithmetic, division, constant powers, negation,
abs, sqrt, exp, log, sin, and cos. Nonlinear objectives are translated using
an auxiliary variable and an epigraph or hypograph constraint.
ScipOptions includes universal time, thread, and verbosity controls, typed
SCIP limits and tolerances, and .param(name, value) for other supported
parameters. .concurrent(true) enables SCIP's concurrent solver; the thread
option alone only sets the maximum thread count.
Scip::new().persistent() reuses compatible models across solves and accepts
append-only variables and constraints. solve_detailed also returns SCIP
statistics and values for columns generated by pricers. Scip::with_plugins
registers event handlers, separators, pricers, branching rules, heuristics,
constraint handlers, and node selectors. Custom Rust plugins cannot be used
with concurrent solving.
Gurobi uses gurobi-rs when the
gurobi Cargo feature is enabled. It requires a licensed Gurobi installation.
Set GUROBI_HOME to the installation directory before building and make sure a
Gurobi license is active.
Note: Only Gurobi v13 and later are supported.
[dependencies]oximo = { version = "0.8", features = ["gurobi"] }
use oximo::prelude::*;use oximo::solvers::Gurobi;use std::time::Duration;let result = Gurobi.solve(&m, &GurobiOptions::default() .time_limit(Duration::from_secs(120)) .mip_focus(1) .seed(101))?;
Mosek supports LP, MILP, convex QP/MIQP, convex QCP/MIQCP,
SOCP/MISOCP, and continuous SDP models. It requires the mosek Cargo feature, a licensed MOSEK
11.2 installation, and MOSEK_BINDIR_112 when MOSEK is outside its default
location. MOSEK validates the convexity of quadratic data. The backend links
through the mosek crate.
On Windows, setting MOSEK_BINDIR_112 directly to a path containing spaces can
fail because of an unquoted linker flag in the current mosek crate build
script. Create a junction with a space-free path and point the environment
variable at that junction; see mosek.rust#1.
Only MOSEK 11.2 is currently supported.
[dependencies]oximo = { version = "0.8", features = ["mosek"] }
use oximo::prelude::*;use oximo::solvers::Mosek;use std::time::Duration;let result = Mosek.solve(&m, &MosekOptions::default() .time_limit(Duration::from_secs(120)) .threads(4) .mio_tol_rel_gap(1e-4))?;
MosekOptions provides builders for every MOSEK 11.2 parameter. Universal
options such as time_limit, threads, and verbose are applied first.
MOSEK-specific parameter builders are then applied in call order.
The MOSEK backend supports real symmetric affine PSD blocks through the
existing mosek feature. The current SDP path requires an affine objective and
accepts linear and SOC constraints alongside PSD blocks. Quadratic objectives
with PSD blocks and mixed integer SDP are rejected; use
Mosek.validate_model(&m, &options) before selecting this backend.
Mosek.persistent() currently rebuilds SDP tasks on each solve, including
parameter-only changes. Primal and PSD dual matrices use the same
result accessors and conventions as Clarabel.
Baron is a global solver for LP/MILP/QP/MIQP/QCP/MIQCP/SOCP/MISOCP/
NLP/MINLP models. The oximo adapter supports all of these model kinds and
translates explicit second-order cones to BARON's quadratic constraint
representation. It requires the baron feature, a licensed BARON installation
on PATH, and exchanges model and result files with the external executable.
[dependencies]oximo = { version = "0.8", features = ["baron"] }
use oximo::prelude::*;use oximo::solvers::Baron;let result = Baron::new().solve(&m, &BaronOptions::default())?;
Gams requires the gams Cargo feature plus a GAMS installation on
PATH. It exchanges model and result files with GAMS, which is useful when you
want to route a model through GAMS-managed solvers (CPLEX, BARON, IPOPT,
KNITRO, ...).
For a model containing indicators, select COPT, CPLEX, Gurobi, SCIP, or Xpress
explicitly in GamsOptions. The default solver selection is rejected because
indicator handling is sub-solver-specific.
[dependencies]oximo = { version = "0.8", features = ["gams"] }
use oximo::prelude::*;use oximo::solvers::Gams;let result = Gams::new().solve(&m, &GamsOptions::default())?;
See GamsOptions and the per-solver option structs in oximo::gams (GamsCplexOptions, GamsBaronOptions, GamsIpoptOptions, ...) for tuning the underlying solver.
A solver accepting NLP or MINLP does not imply that a backend can represent every
nonlinear expression. oximo validates the expressions before solving
and returns SolverError::UnsupportedNonlinearOperator when a
translation is unavailable.
Results: inspect solver status, values, duals, and solution pools
Printing & Debugging: print a model as algebra and track down what it actually says
I/O: write your model to MPS, LP or NL for use with external tools
Results
Every oximo backend returns the same SolverResult. Read it
the same way independently of the solver.
It is recommended to first check what stopped the solve and whether a usable point is available, then
inspect the values relevant to your application.
The quickest option is the built-in report, which renders a model-aware summary:
print!("{}", result.report(&m)?);
For programmatic access, SolverResult separates why the
solver stopped from whether a usable point came back. That split matters because,
for example, a run that hits a time limit can still carry a good incumbent.
let result = Highs.solve(&m, &HighsOptions::default())?;match result.termination { TerminationStatus::Optimal => { // `objective()` is Option, since a model may have no objective. if let Some(obj) = result.objective() { println!("optimal: {obj}"); } } TerminationStatus::Infeasible => println!("infeasible"), TerminationStatus::TimeLimit if result.has_solution() => { println!("time limit, best = {:?}", result.objective()); } _ => {}}let x_val = result.value_of(x)?; // Option<f64>let dual = result.dual_of(scalar_handle)?; // Option<f64>
TerminationStatus says why the solver stopped:
Optimal, LocallyOptimal, Feasible, Infeasible, Unbounded,
InfeasibleOrUnbounded, IterationLimit, TimeLimit, NodeLimit,
Interrupted, NumericError, NotSolved, or Other(String) for an unmapped
backend status.
PrimalStatus says what you actually got: NoSolution,
FeasiblePoint, or OptimalPoint. result.has_solution() is the shorthand.
Always check it before trusting a value.
Expression, matrix, algebraic-constraint, and SOC queries use the parameter
values captured when the backend translated or updated the problem. Rebinding
a parameter does not change an old result's answers. Each SolutionPoint,
including pooled points, retains the parameter values used for its solve.
You can use the _with_current_parameters methods to evaluate the saved
primal point under the model's current bindings.
Scenario queries do not change stored objectives, statuses, bounds, duals, or
other solver certificates. The saved point may be infeasible under the new bindings.
Constraint definitions and bounds still come from the supplied model, since the
snapshot does not preserve structural edits. Both query modes reject foreign
model handles, including handles from transformed copies. Raw VarId and
ParamId lookups cannot check ownership.
Constraint declarations return handles that let you query their rows after a
solve. A scalar relation returns a model-bound ConstraintHandle.
A two-sided range returns RangeConstraintHandles,
which identifies either one interval row or its separate lower and upper rows.
The model identity prevents accidentally querying a result with a handle from a
different model. .id() returns a tagged SemanticConstraintId. Typed scalar
handles expose .row_id() when a raw algebraic ConstraintId
is required. Cone handles expose .soc_id() or .psd_id() for their respective
registries. Erased handles provide fallible accessors such as .try_row_id().
Use result.soc_dual_of(handle)? for SOC handles and
result.psd_dual_of(handle)? for PSD handles.
Capture an indexed declaration when you need to query its rows. The returned
IndexedConstraint maps each typed key to its registered
handle, so dual queries do not need to reconstruct generated names:
let cover = constraint!(m, cover[i in 0..n_items], x[i] >= demand[i]);let handle = cover.get(0).expect("cover row exists");let dual = result.dual_of(handle)?;for (i, handle) in cover.iter() { println!("cover[{i}] dual = {:?}", result.dual_of(handle)?);}
get(key) also works for sparse, filtered, string, and tuple domains, and
iter() yields typed (key, ConstraintHandle) pairs in domain order. Handles
carry their model identity and remain usable after the model declaration block.
Indexed two-sided ranges return an IndexedRangeConstraint.
Each key maps to RangeConstraintHandles::Interval(handle) when the row stays a
native interval, or to RangeConstraintHandles::Split { lower, upper } when
symbolic bounds or a nonlinear body require two rows. Match the value and query
each handle with result.dual_of separately; a family can contain both forms.
result.dual_of(handle)? returns the multiplier for the original declaration.
A stored row can have a different scaling: x <= 2 and 2 * x <= 4 describe
the same bound, but their multipliers differ by a factor of two. The raw
result.dual map is keyed by stored algebraic row IDs;
prefer handles for queries about your model.
dual_of returns None when the backend supplies no dual or a transformation
has no mapping back to the original constraint.
Constraint evaluation also uses the original function and bounds. A custom
function that cannot be evaluated through the scalar API returns None.
As with other result queries, parameter values come from the solve-time snapshot,
while constraint definitions come from the supplied model.
Query matrix values and PSD duals separately. result.value_of_matrix(&matrix)
evaluates a symmetric matrix variable or expression at the best solution.
result.psd_dual_of(handle) retrieves the dual matrix associated with the
PsdConstraintHandle returned by psd_constraint!.
Display prints the full matrix as nested rows, including mirrored entries.
Both matrices contain ordinary, unscaled symmetric entries, with mirrored
indexing and upper-triangle column order. Use frobenius for the matrix inner product.
For a constraint F(x) PSD, the dual matrix Y is PSD within solver
tolerances for both minimization and maximization. Its Lagrangian contribution
is -<Y, F(x)>, with the objective taken as f(x) for minimization and -f(x)
for maximization. Compute complementarity using the evaluated constraint
matrix F(x) and its dual Y. At an optimal primal/dual pair, their inner
product is approximately zero.
psd_dual_of takes a PsdConstraintHandle, rather than a scalar constraint
handle. It returns None when no dual matrix is available, including for
inactive blocks; infeasibility certificates are not returned as PSD duals.
As with scalar results, model identity mismatches return an error.
value_of_matrix also accepts affine matrix expressions, such as t I - C,
and is available on individual SolutionPoints. It evaluates symbolic
parameters using their solve-time snapshot and returns None when there is no
solution, a required variable value is missing, or a parameter was added after
the solve.
Backends that can return multiple points expose them, best-first:
for i in 0..result.result_count() { let point = result.solution(i).unwrap(); println!("objective {:?}", point.objective);}
Each point retains the solve-time parameters when cloned or queried after
rebinding. Use point.value_of(expr)? for an expression at that pooled point,
or point.value_of_with_current_parameters(expr)? for a scenario query.
I/O: export a model for inspection in another tool
Printing & Debugging
Macros that generate families of constraints are convenient right up until the model doesn't say what you thought it said. Model implements Display, so the fastest way to check is to print it.
You can print the complete model as a readable algebra block to the console with println!("{m}");.
let m = Model::new("diet");variable!(m, x >= 0.0);variable!(m, y >= 0.0);constraint!(m, c1, x + 2.0 * y <= 14.0);constraint!(m, c2, 3.0 * x - y >= 0.0);objective!(m, Min, 3.0 * x + 4.0 * y);println!("{m}");
Model 'diet' (LP)min 3 x + 4 ys.t. c1: x + 2 y <= 14 c2: 3 x - y >= 0vars x >= 0 y >= 0
The header carries the inferred ModelKind, which helps check the
model's algebraic structure. Backend compatibility also depends on the complete
model and options; see validation.
Ranges, cones, and domains all render in the algebraic form you wrote:
max x + y band: 1 <= x + t <= 4 disk: ||x, t|| <= x + 1 0 <= y <= 1, binary
Printing a 10,000-constraint model is not debugging. Display adapters render a single piece, which is what you want inside an assertion or a targeted dbg!:
Keep the declaration's handle, or retrieve it with constraint_handle(name),
then render the original function and set. A foreign handle returns an error:
let c = m.constraint_handle("c1").unwrap();println!("{}", m.display_constraint(c)?);assert_eq!(m.display_expr(2.0 * x - y).to_string(), "2 x - y");
For a raw algebraic constraint_id, use m.display_row(id). This can
differ from the original declaration when a transformation changes the stored row.
Because these return Display adapters rather than String, they're cheap to leave in test assertions. The rendering only happens when something formats them.
Indexed constraints are auto-named base[key], and that name is exactly what constraint_handle expects. This is the usual way to confirm a rule expanded over the keys you intended:
constraint!(m, supply[p in plants], sum!(x[p, q] for q in markets) <= supply_of(&p));let c = m.constraint_handle("supply[seattle]").unwrap();println!("{}", m.display_constraint(c)?);
To render a key the same way the auto-namer does, use display_index_key.
A printed model resolves parameters to whatever they're bound to right now, which makes it easy to confirm a scenario sweep is re-binding what you think:
param!(m, price = 4.0);objective!(m, Min, price * x);println!("{m}"); // min 4 x ... params: price = 4m.set_param(price, 7.5)?;println!("{m}"); // min 7.5 x ... params: price = 7.5
oximo infers the ModelKind from the expressions you write. You never declare it. A backend that rejects your model is usually telling you an expression is a different kind than you assumed, so you can pin it down in a test:
assert_eq!(m.kind(), ModelKind::LP);
Compare the result against the backend table
for an initial choice, then use solver.validate_model(&m, &options) to check
the complete model. m.kind() summarizes the registered representations; it does
not establish compatibility with every constraint, domain, and selected option.
Active PSD blocks normally give a model the SDP kind, or MISDP when it has
integer variables or other discrete requirements. General quadratic constraints
and nonlinear expressions take precedence.
See SDP backend limits for objective restrictions.
Sometimes the backend accepts the model's kind and still returns infeasible. Each constraint is fine on its own, but together they can't all hold. Backends built on a solver with a native conflict refiner can express why by computing an irreducible infeasible subsystem (IIS), a minimal set of constraints and variable bounds that are jointly infeasible, where dropping any one member makes the rest feasible.
use oximo::solvers::Gurobi;let m = Model::new("iis");variable!(m, x >= 0.0);constraint!(m, floor, x >= 2.0);constraint!(m, ceil, x <= 1.0);objective!(m, Min, x);let iis = Gurobi.compute_iis(&m, &GurobiOptions::default())?;println!("{}", iis.report(&m));
The report uses the model's own names, so floor and ceil point straight back to the constraint! lines that conflict. The x >= 0 bound isn't part of the conflict, so it isn't listed. Reach the members programmatically through Iis's constraints, soc_constraints, and var_bounds fields (each bound tagged VarBoundKindLower/Upper). compute_iis returns a SolverError if the model turns out feasible, so it doubles as an "is this actually infeasible?" assertion.
I/O: export your model to MPS, LP, or NL for inspection in other tools
Modeling: back to variables, sets, and rule-style constraints
I/O
The oximo-io crate writes Models to the standard text formats MPS, LP, and NL, and can read all three formats back into a Model. All I/O is gated on the io Cargo feature, which is on by default.
Use this when you want to:
Hand a Model to a solver oximo doesn't bundle (COPT, FICO XPress, CPLEX, ...)
Feed a nonlinear model to an AMPL-compatible solver via NL
Reproduce a bug report against a third-party tool
Save an exact, inspectable copy of the problem instance for later analysis or reproduction
MPS and LP describe linear and quadratic models. In general, you should use LP and reach for NL when the model has
nonlinear expressions that MPS and LP cannot represent.
Format
Pros
When to pick
MPS
Universal, column-oriented, fixed historical format
The NL writer is the most configurable of the three. write_nl_with and to_nl_string_with take a WriteOptions to select the NlFormat (binary or ASCII) and attach solver metadata: suffixes, defined variables, imported functions, and complementarity pairs.
write_nl_files emits the .nl alongside its companion .col/.row name files, which is what most AMPL-compatible solvers expect when you want readable names in the solution.
The NL writer emits supported nonlinear operations as exact prefix opcode
trees. The reader uses the same mapping for ASCII and little-endian binary NL:
Opcode
Operation
oximo support
o13
floor
Not represented by the expression model
o14
ceil
Not represented by the expression model
o15
abs
Read and written
o16
unary -
Read and written
o34
logical not
Logical expressions are not represented
o37
tanh
Read and written
o38
tan
Read and written
o39
sqrt
Read and written
o40
sinh
Read and written
o41
sin
Read and written
o42
log10
Read and written
o43
log
Read and written
o44
exp
Read and written
o45
cosh
Read and written
o46
cos
Read and written
o47
atanh
Read and written
o49
atan
Read and written
o50
asinh
Read and written
o51
asin
Read and written
o52
acosh
Read and written
o53
acos
Read and written
exp2(x) is written exactly as the power expression 2 ^ x (o5), because
NL has no separate exp2 opcode.
The oximo operations cbrt, expm1, log1p, and log2 also have no direct
NL opcode. Writing one returns
IoError::UnsupportedNonlinearOperator.
Reading floor, ceil, logical not, or another
well-formed but unrepresentable opcode returns IoError::UnsupportedNl.
All writers preserve the Variable and constraint names from your model, so exported files cross-reference cleanly with SolverResult lookups such as dual_of and reduced_costs (see Results).
use oximo::io::{read_mps, read_mps_file};use std::fs::File;let model = read_mps_file("model.mps")?;let model_from_stream = read_mps(File::open("model.mps")?)?;
The reader accepts the standard linear sections, range rows, integer markers,
binary and semi-variable bounds, SOS sections, INDICATORS records, and the
QUADOBJ, QMATRIX, QCMATRIX, and QSECTION quadratic extensions. An MPS
indicator references an ordinary affine row using IF row binary 0|1; ranged
indicator bodies are represented as two rows. MPS does not identify the
coefficient scaling used by quadratic constraints, so the default is the
Gurobi convention. Select CPLEX or MOSEK scaling explicitly when needed:
use oximo::io::{ MpsQuadraticFormat, MpsReadOptions, read_mps_file_with,};let options = MpsReadOptions { quadratic_format: MpsQuadraticFormat::Cplex,};let model = read_mps_file_with("cplex-model.mps", &options)?;
The NL reader imports models produced by oximo or compatible
AMPL-style tools. Use read_nl_file for a path or read_nl
for any byte stream:
use oximo::io::{read_nl, read_nl_file};use std::fs::File;let model = read_nl_file("model.nl")?;let model_from_stream = read_nl(File::open("model.nl")?)?;
Both ASCII and little-endian binary NL encodings are accepted. When a .row or
.col sidecar exists beside the file, it supplies the original row and column
names; otherwise deterministic names are generated. Interval rows and initial
values are preserved when they can be represented by the core model.
The reader rejects malformed input with IoError::InvalidNl and
well-formed NL sections that the core model cannot represent with
IoError::UnsupportedNl. Imported functions, defined variables,
logical/network constraints, complementarity sections, and unsupported expression
opcodes are intentionally rejected.
LP files can be imported from a byte stream or a path with read_lp
and read_lp_file:
use oximo::io::{read_lp, read_lp_file};use std::fs::File;let model = read_lp_file("model.lp")?;let model_from_stream = read_lp(File::open("model.lp")?)?;
The reader supports the CPLEX LP linear and quadratic subset represented by the
core model, including objectives, constraints, bounds, integer/binary and
semicontinuous domains, quadratic terms, SOS sections, and inline indicator
rows of the form binary = 0|1 -> affine relation. Ranged indicator bodies are
written as two indicator rows. Malformed input returns
IoError::InvalidLp with its source line and column. Unsupported LP
sections return IoError::UnsupportedLp.
NL has no native segment for the indicator representation used by oximo.
Writing a model with an active indicator returns IoError::UnsupportedNl.
The MPS, LP, and NL writers do not support active PSD constraints. Writing
such a model returns IoError::Conic, including when other expressions make
its model kind QCP or NLP. Inactive PSD blocks are skipped.
Generalized Disjunctive Programming (GDP) expresses optimization problems with
logical decisions and groups of conditional rows. For example, choosing
a small unit activates its capacity constraints, while choosing a large unit
activates a different set of constraints.
The optional oximo-gdp crate adds GDP modeling to the ordinary Model.
Reformulation converts the logical and conditional components into algebraic
constraints that a compatible solver can handle. Choose from
Big-M and Hull. For solving, prefer
solver.with_gdp(...).solve(...): it reformulates the model and returns results
for your declared variables and Hull activations. Use explicit reformulation to
export or inspect the transformed model, or to create an independent copy.
[dependencies]oximo = { version = "0.8.0", features = ["gdp", "highs"] }
In this case, gdp provides modeling and reformulation while highs provides
a solver for the linear example below. Import oximo::prelude::* for the macros, types, and
GdpModelExt methods.
A logical variable \(Y\), with value true or false.
BooleanHandle, declared with boolean_variable! or by disjunct!
Indicator
The Boolean decision that activates a disjunct or conditional row.
handle.indicator()
Binary counterpart
The algebraic variable \(y \in \{0,1\}\) corresponding to \(Y\). Use it in arithmetic and numeric result queries.
handle.binary()
Conditional row
An algebraic relation that applies only when its indicator is true. βDisjunct constraintβ is the API's name for a conditional row.
DisjunctConstraintHandle, disjunct_constraint!
Disjunct
A block of conditional rows sharing one indicator.
DisjunctHandle, disjunct!
Branch
One member of a disjunction: a disjunct handle or a separately declared Boolean decision. A Boolean branch may have conditional rows attached to it.
An element of the branches argument
Disjunction
A selection rule over a collection of branches.
DisjunctionHandle, disjunction!
The relationship between \(Y\) and \(y\) is shown in Boolean decisions.
Use conditional row for the relation and disjunct constraint when referring to its API.
It is distinct from an algebraic variable such as a flow \(x \in \mathbb{R}\).
For example, \(Y_i = \mathrm{true}\) can mean that operating mode \(i\) is selected.
Boolean variables are intended for logical expressions and do not participate
directly in algebraic expressions. For example, \(Y_i + 1\) is undefined,
so an objective such as \(q - 2Y_{\mathrm{large}}\) is also undefined.
To model a conditional operating cost, introduce an algebraic
variable \(c\) and use a disjunction. Here, \(\underline{\bigvee}\) denotes
exactly-one selection, the default rule for disjunction!.
Plain \(\bigvee\) denotes inclusive OR, where at least one block must be selected.
Declare Boolean decisions independently when you want to use them in logical
constraints or attach them to individual conditional rows:
use oximo::prelude::*;let model = Model::new("Boolean decisions");boolean_variable!(model, selected);boolean_variable!(model, mode[i in 0..2]);
A disjunct block also declares its own Boolean decision. The GDP formulation
uses \(Y_i\). Its algebraic counterpart is a binary variable \(y_i\) satisfying
handle.binary() exposes this numeric counterpart for algebraic expressions and
numeric result queries. Read a Boolean selection with result.boolean_value_of(handle).
Arithmetic on \(y_i\) is valid because it is a binary
algebraic variable. This explicit mapping does not make \(Y_i\) itself numeric.
Here \(Y_i\) is the Boolean decision and \(h_i(x) \le 0\) represents all the
conditional rows in its block. The block means \(Y_i \Rightarrow h_i(x) \le 0\).
Its rows apply when \(Y_i\) is true. When \(Y_i\) is false, that block imposes
no restrictions on \(x\). Equalities and ranges can also appear inside a disjunct block.
A disjunction specifies which blocks must be selected. The default exactly-one
rule selects either the small or the large unit:
\(q\) is flow and \(c\) is operating cost. The objective and variable bounds are
global; capacity, minimum flow, and fixed cost belong to their respective blocks.
use oximo::prelude::*;use oximo::{HighsOptions, solvers::Highs};fn main() -> Result<(), Box<dyn std::error::Error>> { let model = Model::new("unit selection"); variable!(model, 0.0 <= flow <= 10.0); variable!(model, 0.0 <= cost <= 2.0); let small = disjunct!(model, small, |d| { constraint!(d, capacity, flow <= 3.0); constraint!(d, fixed_cost, cost == 0.0); }); let large = disjunct!(model, large, |d| { constraint!(d, operating_range, 5.0 <= flow <= 8.0); constraint!(d, fixed_cost, cost == 2.0); }); let choice = disjunction!(model, unit, [small, large]); objective!(model, Max, flow - cost); let result = Highs .with_gdp(BigM::default()) .solve(&model, &HighsOptions::default())?; println!("objective: {:?}", result.objective()); println!("flow: {:?}", result.value_of(flow)?); println!("cost: {:?}", result.value_of(cost)?); let selected = result.boolean_value_of(large)?; println!("large unit selected: {selected:?}"); Ok(())}
Expected output, apart from any solver log:
objective: Some(6.0)flow: Some(8.0)cost: Some(2.0)large unit selected: Some(true)
The solution selects the large unit; its conditional rows enforce the cost.
boolean_value_of returns Result<Option<bool>, BooleanValueError>. The
helper uses a fixed absolute tolerance of 1e-5. Values within 1e-5 of zero or
one become Some(false) or Some(true). A missing solution or value stays
None, and values farther from both, or non-finite values, return
BooleanValueError::NonBooleanValue.
To inspect fractional selections from an LP relaxation, use the numeric query
result.value_of(large.binary())?. See Results for checking solve
status and solution availability.
Declare algebraic variables and objectives on the global model. The block
receiver supports scalar algebraic constraints, including nonlinear expressions,
ranges, indexed families, and sum!. Conditional variables, objectives, cones,
native indicators, and SOS constraints are not supported.
disjunct_constraint! attaches a conditional row to an existing Boolean decision,
so you can add conditions without declaring a disjunct block. Each row expresses an
implication \(Y_i \Rightarrow l_i \le f_i(x) \le u_i\).
For the nonlinear example below, \(L_0 = 2\) and \(L_1 = 4\):
In this table, m is the model or disjunct context, label is a name written as
a Rust identifier, and name = expr computes the registered name at runtime.
body is a closure such as |d| { constraint!(d, x <= 2.0); }, relation is an
algebraic comparison or range, and formula is a Boolean expression.
The forms in each cell are alternatives.
Macro
Accepted forms
Binding or return value
boolean_variable!
boolean_variable!(m, decision) boolean_variable!(m, decision[i in domain])
Binds decision locally to a Boolean handle or indexed family. A name is required; anonymous and computed-name forms are not accepted.
disjunct!
disjunct!(m, body) disjunct!(m, label, body) disjunct!(m, name = expr, body) disjunct!(m, label[i in domain], body)
Returns a disjunct handle or indexed family.
disjunction!
disjunction!(m, branches) disjunction!(m, label, branches) disjunction!(m, name = expr, branches) disjunction!(m, label[i in domain], branches)
Returns a disjunction handle or indexed family. Each form also accepts the options below.
disjunct_constraint!
disjunct_constraint!(m, indicator, relation) disjunct_constraint!(m, indicator, label, relation) disjunct_constraint!(m, indicator, name = expr, relation) disjunct_constraint!(m, indicator[i], label[i in domain], relation)
Returns a conditional-row handle, range handles, or an indexed family, depending on the relation.
logical_constraint!
logical_constraint!(m, formula) logical_constraint!(m, label, formula) logical_constraint!(m, name = expr, formula) logical_constraint!(m, label[i in domain], formula)
Returns a logical-constraint handle or indexed family.
The macros that return handles do not bind their registered names as Rust
variables. You need to capture the result explicitly, for example
let choice = disjunction!(model, unit, [small, large]);. Here, unit names the
disjunction in the model, while choice is the Rust variable holding its handle.
For disjunction!, append a selector (ExactlyOne or AtLeastOne),
parent = indicator, or both to any form. The selector defaults to ExactlyOne.
The two options may appear in either order, and each may appear only once.
Example
How the arguments are read
disjunction!(model, unit, branches)
unit is the name; branches is the collection.
disjunction!(model, branches, AtLeastOne)
Anonymous disjunction; branches is the collection; AtLeastOne is the selector.
disjunction!(model, branches, parent = present)
Anonymous disjunction; branches is the collection; present is the parent indicator.
disjunction!(model, unit, branches, AtLeastOne, parent = present)
Named disjunction with an inclusive selector and a parent.
An indexed name may use multiple domains and a filter:
label[i in domain, j in other_domain if condition]. The index variables are
available in the body, indicator, formula, branches, and parent expression as
appropriate. String and tuple keys are supported. Families provide get, iter,
indexing, and len. Use family.values() to pass an indexed family to a logical
builder, for example exactly(1, family.values()).
The underlined operator means exactly one branch is true, equivalent to
\(\operatorname{ExactlyOne}(Y_i : i \in I)\). Supply AtLeastOne for
inclusive OR, which requires
$$
\bigvee_{i \in I} Y_i = \mathrm{true}.
$$
At least one branch must be true, and several may be true. Every selected
branch enforces all of its conditional rows:
let branches = [small, large];disjunction!(model, branches, AtLeastOne);
This is an alternative to the exactly-one declaration in the first example.
Each branch can belong to at most one disjunction, so select the desired form
when constructing the model. ExactlyOne is also accepted explicitly.
Compare selection rules with logical XOR:
Form
Requirement
disjunction!(model, branches) or an explicit ExactlyOne
Exactly one branch is true, for any number of branches.
disjunction!(model, branches, AtLeastOne)
One or more branches are true; several may be selected together.
a ^ b
Binary XOR: exactly one of these two formulas is true.
a ^ b ^ c
Chained XOR: an odd number of formulas is true, including all three.
For three or more decisions, use exactly(1, terms) for an exactly-one logical
constraint. Chaining ^ would also admit three, five, or more true terms.
A logical constraint asserts that a Boolean formula \(\Omega(Y)\) is true:
$$
\Omega(Y) = \mathrm{true}.
$$
For example, \(Y_a \Rightarrow Y_b\) means selecting \(a\) requires selecting \(b\).
Logical constraints connect decisions without writing these relationships
manually as algebraic inequalities. With \(A\) and \(B\) denoting Boolean formulas,
and \(N\) denoting the number of true terms:
logical_and(terms) and logical_or(terms) accept iterators. Terms may be
Boolean handles, Boolean constants, or compound logical expressions, including
cardinality expressions. An empty AND is true, while an empty OR is false.
Use & and | for model logic, since Rust's && and || require actual Rust Booleans.
Parenthesize compound formulas.
A nested disjunction is selected only when its parent decision \(P\) is true.
For exactly-one children \(Y_i\), its meaning is
$$
P \Rightarrow \operatorname{ExactlyOne}(Y_i : i \in I),
\qquad Y_i \Rightarrow P \quad \text{for every } i \in I.
$$
If \(P\) is false, every child is false. If \(P\) is true, exactly one child is true.
For inclusive selection, replace \(\operatorname{ExactlyOne}\) with
\(\bigvee_{i \in I}Y_i\). A logical formula declared in the parent's context
expresses \(P \Rightarrow \Omega(Y)\).
For example, a unit is either present or absent. When present, it chooses one
of two technologies with different flow limits. The inner disjunction sits
inside the present branch.
Here \(P\) is present, \(A\) is absent, \(q\) is flow, and the
children are technology[0] and technology[1]. Attach them to the parent
with parent = ...:
use oximo::prelude::*;let model = Model::new("nested technology selection");variable!(model, 0.0 <= flow <= 8.0);boolean_variable!(model, present);boolean_variable!(model, absent);boolean_variable!(model, technology[i in 0..2]);disjunct_constraint!(model, absent, no_flow, flow == 0.0);let limits = [3.0, 8.0];disjunct_constraint!(model, technology[i], capacity[i in 0..2], flow <= limits[i]);disjunction!(model, unit, [present, absent]);let branches = [technology[0], technology[1]];disjunction!(model, branches, parent = present);model.reformulate_gdp(BigM::default())?;
You can also declare child disjuncts and their disjunction directly inside a
parent block. The nesting graph must be acyclic.
oximo provides Big-M and Hull reformulations. Both turn conditional rows
and logical decisions into an algebraic model. The choice affects its size and
continuous relaxation, where binary variables can take fractional values.
GdpReformulationOptions::default() selects Big-M.
Method
How it works
What to consider
BigM::default()
Adds \(M\) terms that relax a row when its branch is inactive.
Produces a compact model. Needs valid \(M\) values; large values can weaken the relaxation and cause numerical difficulties.
Hull::default()
Introduces branch-specific variable copies and transforms the rows that use them.
Can strengthen the relaxation, at the cost of more variables and rows. Requires finite lower and upper bounds on copied variables.
Both methods support affine and nonlinear conditional rows, nested disjunctions,
and standalone conditional rows. Choose a solver that supports the resulting
algebraic expressions.
Big-M is a useful reformulation when model size matters and you can establish
tight, valid bounds. The default method estimates \(M\) values from global variable
bounds and uses unconditional affine constraints to tighten those bounds.
For nested groups, it also uses parent and ancestor constraints to tighten local
\(M\) values. Both forms of tightening are enabled by default.
The bounds must remain valid in every feasible mode, including when a branch
is inactive. Constraints inside a branch do not establish global bounds. An \(M\)
that is too small can remove feasible solutions, while a larger valid \(M\) may slow solving.
The main options are:
Option
When to use it
options.with_big_m(row, BigMValues::upper(value)) or BigMValues::lower(value)
Supply a justified \(M\) for one row side when you can improve on automatic estimation. Values must be finite and nonnegative.
BigM::default().with_fallback_big_m(value)
Supply a justified value for sides where automatic estimation cannot find a finite \(M\). It does not replace a finite automatic estimate.
Disable ancestor tightening for nested groups, for example to compare formulations.
options.with_bound_tightening(false)
Disable affine bound propagation, including hierarchical propagation. Estimates then rely on declared bounds.
There is no large default \(M\). If neither estimation nor your settings supply a
valid value, reformulation returns MissingBigM. Nonlinear expressions must also
be defined over the global domain, even when their branch is inactive; supplying
an \(M\) does not repair an unsafe domain.
See Big-M values for the generated inequalities, \(M\) precedence,
and examples of fixing missing estimates or unsafe domains.
Hull is useful when a stronger relaxation can justify a larger algebraic model.
It avoids choosing \(M\) values, but every variable that needs a copy must have
finite lower and upper bounds. The default affine propagation pass can derive
these bounds from unconditional constraints.
The main options are:
Option
Default and purpose
Hull::default().with_inclusive_policy(...)
Rejects AtLeastOne groups by default. Enable HullInclusivePolicy::Enumerate { max_patterns } to preserve inclusive selection.
References default to zero. Set a finite reference when a nonlinear function is undefined at zero, or to improve coordinate scaling. Pass a bare variable handle from the source model.
Hull::default().with_epsilon(value)
Uses 1e-6 for nonlinear perspective regularization. A custom value must be finite and strictly between zero and one.
Hull::default().with_quadratic(...)
Uses HullQuadratic::Perspective. Select an exact, epsilon-free form for rows whose nonlinear part is quadratic; see Quadratic rows.
A nonlinear reference must make both the reference evaluation and the generated
perspective domain safe. It doesn't need to satisfy the branch's constraints, and a
point inside the source domain is not always safe for the generated expression.
For convex disjunct sets, smaller epsilon values bring the continuous relaxation
closer to the closed perspective.
See Nonlinear perspectives and domains
for the equations and validation rules.
By default, quadratic rows rely on the same regularized perspective formulation as other nonlinear rows. However, this approach divides by the activation variable, is exact only at binary values, and introduces a dependence on epsilon. Following Gusev and Bernal Neira,
Exact Hull Reformulation for Quadratically Constrained Generalized Disjunctive Programs, rows with quadratic nonlinearities can instead use an exact Hull formulation that eliminates both division and epsilon.:
HullQuadratic
Generated rows
Use with
Perspective
Regularized perspective (default).
Solvers that accept general nonlinear expressions.
Homogeneous
Quadratic rows that are exact at every activation value. A convex source row usually becomes nonconvex.
Global solvers for nonconvex quadratics, such as Gurobi, SCIP, or BARON.
Conic
Convex sides become a rotated second-order cone plus a linear row, using one extra variable per side. Other sides use the Homogeneous form.
Solvers that detect second-order cones in quadratic rows when your quadratic disjunct rows are convex.
use oximo::prelude::*;let model = Model::new("two disks");variable!(model, -5.0 <= x <= 5.0);variable!(model, -5.0 <= w <= 5.0);let upper = disjunct!(model, upper, |d| { constraint!(d, (x - 1.0) * (x - 1.0) + (w - 1.0) * (w - 1.0) <= 1.0);});let left = disjunct!(model, left, |d| { constraint!(d, (x + 2.0) * (x + 2.0) + w * w <= 0.5);});disjunction!(model, [upper, left]);objective!(model, Max, x + w);let hull = Hull::default().with_quadratic(HullQuadratic::Conic);let result = Gurobi .with_gdp(GdpReformulationOptions::new(hull)) .solve(&model, &GurobiOptions::default())?;
Conic treats each one-sided row side separately. A <= side becomes a cone
when its quadratic part is convex, and a >= side when it is concave. Equality
rows and all other sides use the Homogeneous form. Convexity is checked
numerically for each block of variables linked by cross terms, and a side whose
block has more than 512 such variables also uses the Homogeneous form.
Rows that cannot use the requested form at all keep the default perspective.
This applies to rows whose nonlinear part is not quadratic and to rows that use
a variable without a Hull copy. These rows, and one-sided sides that are not
convex or exceed the limit, are listed in report.hull_quadratic_fallbacks with
their reason; see Quadratic Hull reports.
In nested disjunctions, set the same with_quadratic option on enclosing Hull
disjunctions. An ancestor that
enumerates inclusive patterns with Perspective turns
nested quadratic rows, including cones, back into regularized perspectives.
Cone rows whose activation is a complement 1 - b (activation_kind is
Complement in the report) are exact and convex, but solvers may not detect
them as cones.
An inclusive group with n branches has 2^n - 1 nonempty selection patterns,
so enumeration grows exponentially. The limit applies to each group separately.
For larger inclusive groups, consider Big-M or inspect the expansion with
plan_gdp before transforming the model.
Prefer with_gdp for routine GDP solves. It reformulates pending GDP components
in place, calls the backend with its ordinary options, and returns results for
your declared variables and Hull activations:
let result = Highs .with_gdp(Hull::default()) .solve(&model, &HighsOptions::default())?;println!("flow: {:?}", result.value_of(flow)?);
Other generated variables and multipliers for generated rows are omitted,
including auxiliaries from earlier SOS or indicator reformulations. This also
applies to duals retrieved through dual_of. Variables and ordinary constraints
declared between solves remain available in later results.
The transformation report is available through
model.gdp_reformulations(); see Hull activation queries.
Changing data or methods between solves. Both with_gdp and explicit
reformulation lock bounds and parameter values used by transformed rows. To
change those inputs or compare methods, keep the source unreformulated and use
to_reformulated_gdp_model(...) for an independent copy. See
Lifecycle, cloning, and reports.
Use GdpReformulationOptions to mix methods or change settings for individual
disjunctions. This configuration uses Big-M by default and Hull for choice:
let gdp = GdpReformulationOptions::new(BigM::default()) .with_method(choice, Hull::default());let result = Highs .with_gdp(gdp) .solve(&model, &HighsOptions::default())?;
The same configuration can instead be passed to model.reformulate_gdp(gdp)
or model.to_reformulated_gdp_model(gdp).
Every disjunction without an override uses the method supplied to new,
including any third choice you did not list with with_method. Each nested
disjunction uses its own override or that same method; overrides do not inherit
from parents. Standalone conditional rows also use the settings supplied to
new. The last override for a handle wins, and foreign-model handles are rejected.
Reformulation processes only pending components. Selecting another method after
an in-place transformation does not replace the existing reformulation. To
compare methods, retain an unreformulated source and create independent copies
with to_reformulated_gdp_model.
summary.generated and summary.total give exact counts of variables,
constraints, and committed expression nodes. Totals include existing objects
and native constraints. hull_copies and hull_patterns count Hull artifacts.
Planning performs full validation and builds temporary artifacts, but leaves the
source and its dependency locks unchanged. The summary is not a reusable plan;
subsequent reformulation plans again against the then-current source model.
GdpSizeLimits caps the final model, including existing objects, across all groups.
GdpPlanningLimits additionally caps cumulative row expansions and private arena
nodes, including cloned source nodes and temporary rewrites. summary.planning
and report.planning expose row_expansions and private_expression_nodes.
Set total limits when enumerating nested groups: a small per-group pattern limit
can still produce thousands of copies and rows across ancestors. A size or
planning limit failure leaves the source unchanged, including when requesting
an independent transformed copy. None leaves the corresponding resource unlimited.
The sections above cover choosing and applying a method. The following explains
the generated algebraic constraints, bound estimation, and domain checks for
users who want to inspect or tune the reformulation.
The API represents methods with GdpMethod, which includes BigM and Hull.
It is non-exhaustive, so matching it requires a wildcard arm.
For a conditional row \(Y \Rightarrow l \le f(x) \le u\), let \(y\) be the
binary counterpart of the Boolean decision \(Y\). Big-M generates the applicable
sides of:
$$
f(x) \ge l - M_l(1-y), \qquad
f(x) \le u + M_u(1-y).
$$
At y = 1, these enforce the original row. At y = 0, sufficiently large
\(M\) values relax it over the global variable bounds. Equalities and ranges have
separate lower and upper \(M\) values. Values are nonnegative magnitudes; zero is valid.
To choose the best \(M\) value, start with the tightest valid global bounds you can
derive from the problem. They must cover every feasible operating mode, including
when the row's indicator is false. Tight bounds allow smaller \(M\) values and strengthen
the LP relaxation, where binary counterparts can take fractional values. Large \(M\) values
weaken that relaxation and increase differences in coefficient scale, which can
slow solving and cause numerical problems. An \(M\) that is too small can remove
feasible solutions.
Solver integrality tolerances can also interact with \(M\). If a binary value
near zero is accepted as zero within tolerance, a linking row such as
\(x \le My\) may still permit a small positive \(x\), roughly on the order
of \(M\) times that tolerance (in addition to primal-feasibility effects).
Large \(M\) values magnify this possible leakage, another reason to derive
valid, tight values and check the returned solution against the original
conditional rows.
Prefer a per-row explicit \(M\) when you can justify a tighter value using
problem-specific restrictions that automatic estimation does not capture.
Use a fallback only when a single justified value covers every unresolved row
side to which it applies. Neither an explicit \(M\) nor a fallback establishes a
missing bound or repairs a nonlinear domain. Check the \(M\) values and their
origins in the returned reformulation report before tuning solver settings.
Automatic estimation uses the current global variable bounds and parameter
values. By default, an affine propagation pass also tightens bounds using active
unconditional algebraic constraints connected to pending GDP expressions.
Variables and parameters used by supporting global rows are locked along with
GDP dependencies after successful reformulation. Use
GdpReformulationOptions::default().with_bound_tightening(false) to skip this preprocessing.
Only small affine rows are used for tightening; unsupported or unexamined rows
retain estimates from the inherited variable bounds. Nested rows additionally
use affine parent and ancestor constraints in separate conditional contexts, as
explained in Hierarchical Big-M.
Conditional rows do not establish global bounds. Ancestor rows establish local
bounds only, while sibling rows are excluded.
Each row side uses the first available value in the table below. Fallbacks are
consulted only when automatic estimation cannot supply a finite \(M\). There is no
large default \(M\).
Priority
Source
How to set it
1
Explicit value for this row side
options.with_big_m(row, BigMValues::upper(value)) or BigMValues::lower(value)
2
Automatic estimate
Global variable bounds and enabled bound tightening
Use a default-method fallback when reusing a configured BigM method; use the
options-level fallback to replace its global fallback without changing the method.
If both are set, the options-level value wins.
Priorities 3 and 5 use the same BigM::default().with_fallback_big_m(value)
constructor; its scope depends on where you attach it. with_method(choice, method)
sets a fallback only for that disjunction, while new(method) or passing the
method directly to reformulation sets the default global fallback. An
options-level global fallback does not replace a disjunction's local fallback.
Standalone conditional rows have no disjunction fallback. Nested disjunctions
use their own override; a parent's fallback does not become a child's fallback.
Use BigMValues::lower(value) or BigMValues::upper(value) for one-sided
overrides. options.with_range_big_m(range, values) sets both sides of a
constant interval or maps them to the appropriate split rows when bounds are
expressions.
For a child constraint \(h(x) \le 0\) with binary indicator \(w\) and
parent indicator \(p\), the default Big-M method uses the parent's affine
constraints to estimate a local relaxation amount. It emits:
When the parent is active, the child row uses the smaller local \(M\). When both
parent and child are inactive, the two amounts restore the global \(M\), so the row
remains relaxed over the global domain. For deeper nesting, ancestor contexts
inherit the bounds of their own ancestors; the differences between successive
\(M\) estimates give additional ancestor terms. Sibling constraints are excluded.
The differences are rounded outward to avoid reducing the inactive allowance.
This follows the hierarchical Big-M formulation in Theorem 2 and equations
(8a)-(12) of Perez and Grossmann (2024),
Extensions to generalized disjunctive programming: hierarchical structures and first-order logic.
oximo estimates \(M\) values using affine propagation and interval bounds without
solving the paper's auxiliary optimization problems. These estimates can match
the tightest \(M\) values, but may be larger when propagation cannot capture all
constraints together. Larger valid \(M\) values preserve integer feasibility but
can weaken the continuous relaxation and slow solving.
For example, with \(0 \le x \le 10\), a parent constraint \(x \le 4\)
and child constraint \(x \le 1\), the generated child row is, apart from
outward rounding:
$$
x \le 1 + 3(1-w) + 6(1-p).
$$
At \(p=0.5\) and \(w=0.25\), this gives \(x \le 6.25\); the
single-indicator child row \(x \le 1+9(1-w)\) gives \(x \le 7.75\).
The parent row additionally gives \(x \le 7\), which is still weaker.
Hierarchical tightening is enabled by default. To compare with the
single-indicator formulation, use:
The setting also works with with_method for individual disjunctions. Disabling
GdpReformulationOptions::with_bound_tightening skips both global and hierarchical
propagation. Explicit \(M\) values and fallbacks retain their meaning as global
relaxation amounts. Nonlinear expressions still undergo global domain validation
before any local estimates are used.
For each row, report.rows[i].lower_m and upper_m retain the global amounts
and their origins. When a row is split, hierarchical_m lists the actual
nonnegative lower and upper amounts for the child and ancestor indicators.
It is empty when no side benefits from a split.
The following model fails because the inactive row has no finite global upper bound
on \(x\). The upper-only row \(x \le 2\) needs only an upper \(M\); the missing
lower bound does not matter:
use oximo::prelude::*;let model = Model::new("missing M");variable!(model, x);boolean_variable!(model, active);let row = disjunct_constraint!(model, active, limit, x <= 2.0);assert!(matches!( model.reformulate_gdp(BigM::default()), Err(GdpError::MissingBigM { side: BoundSide::Upper, .. })));
Choose one of the following fixes:
Fix 1: tighter global bounds. If the process guarantees \(0 \le x \le 22\),
encode that restriction when rebuilding the source. The upper \(M\) is then estimated
as 20, apart from numerical rounding:
let bounded = Model::new("bounded M");variable!(bounded, 0.0 <= x <= 22.0);boolean_variable!(bounded, active);disjunct_constraint!(bounded, active, limit, x <= 2.0);bounded.reformulate_gdp(BigM::default())?;
Fix 2: a justified explicit \(M\). Alternatively, the process limit can be
represented by a global constraint. On the original model, the failed call left
the source unchanged, so the following adds that restriction.
With default tightening enabled, the estimator recognizes this one-variable
affine range and estimates \(M\) as 20; an explicit \(M\) would be redundant. This
alternative deliberately disables tightening, so estimation uses the declared,
unbounded variable and the supplied \(M\) is needed:
Here \(M = 20\) is justified by the global limit, since the inactive row becomes
\(x \le 2 + 20 = 22\). Prefer the default automatic estimate for this simple
range when tightening is enabled. An explicit \(M\) is also useful when a valid
limit follows from more complex restrictions that the estimator does not use.
If \(x\) truly has no finite upper limit when inactive, no finite \(M\) is valid
for this row.
Big-M retains the original nonlinear expression even when the branch is inactive.
Declared global bounds, together with any enabled tightening from unconditional
constraints, must establish that every expression is defined.
For example, x.ln() needs a strictly positive global lower bound. A conditional
constraint imposing positivity inside the same branch does not establish that
global domain.
Unsafe logarithms, roots, divisions, powers, inverse functions, and tangent poles
return GdpError::UnsafeDomain, including when an explicit \(M\) is supplied.
For example, the following fails because \(x=0\) is permitted globally, even
though a conditional row would make \(x\) positive when selected:
use oximo::prelude::*;let model = Model::new("unsafe logarithm");variable!(model, 0.0 <= x <= 10.0);boolean_variable!(model, active);disjunct_constraint!(model, active, positive, x >= 1.0);let log_row = disjunct_constraint!(model, active, log_cap, x.ln() <= 1.0);let options = GdpReformulationOptions::default() .with_big_m(log_row, BigMValues::upper(10.0));assert!(matches!( model.reformulate_gdp(options), Err(GdpError::UnsafeDomain { operation: "log", .. })));
Choose one of the following fixes:
Fix 1: a safe variable domain. If positivity is valid for every operating
mode, rebuild with a strictly positive global lower bound:
let safe = Model::new("safe logarithm");variable!(safe, 1.0 <= x <= 10.0);boolean_variable!(safe, active);disjunct_constraint!(safe, active, log_cap, x.ln() <= 1.0);safe.reformulate_gdp(BigM::default())?;
Fix 2: a global constraint that establishes the domain. On the original
model, make the positivity restriction unconditional. The failed call applied
no reformulation or locks, and its explicit-\(M\) option was not stored.
The new x >= 1.0 constraint is a small, one-variable affine global row, so
default tightening uses it to establish positivity before the domain check:
constraint!(model, global_positive, x >= 1.0);model.reformulate_gdp(BigM::default())?;
If tightening is disabled, the declared lower bound remains zero for domain
analysis and this retry still returns UnsafeDomain.
An explicit \(M\) is not a fix for UnsafeDomain. The logarithm remains in the
generated algebraic expression when inactive. If nonpositive values must remain
feasible in other modes, this formulation needs a domain-safe modeling change.
The Hull transformation disaggregates variables into continuous copies scaled by
branch activations. The following describes the generated rows, nested scopes,
and nonlinear perspectives. For requirements and configuration, see Hull.
Consider a root exactly-one group with binary indicators \(y_i\), a source
coordinate \(x\) bounded by \(L\) and \(U\), and reference \(r\).
For each branch, the full-copy formulation introduces the shifted copy
At \(y_i=1\), this recovers the original inequality. At \(y_i=0\), the
copy bounds force \(v_i=0\). Lower bounds are transformed in the same way;
equalities and ranges generate both applicable sides. A standalone conditional
block uses an implicit on/off Hull, retaining a copy for the inactive alternative.
References default to zero. Set a coordinate with
GdpReformulationOptions::with_hull_reference_coordinate(variable, reference).
A reference shifts affine copies and rows as well as nonlinear perspectives:
a generated copy represents activation * (source - reference).
Use with_hull_reference_coordinates(variables.iter().map(|(_, v)| (v, reference)))
for an indexed family, or supply different values for each entry.
Setters require bare variable handles from the source model.
In flat root ExactlyOne groups, two or more branches that never use a coordinate
share one unused copy activated by their summed selectors. If just one branch
uses the coordinate, this activation is its complement. Otherwise a continuous
BranchSum weight records the unused activation. Coordinates with the same
branch support can share a weight. This preserves the projection of the full-copy
Hull relaxation while reducing generated artifacts. Nested groups retain scoped copies.
Nested disjunctions are transformed inside-out, starting with the deepest groups.
A child's generated rows and auxiliaries remain in the enclosing branch's scope,
while parent reformulation links child copies to the appropriate parent copy.
With zero references, a parent copy \(v_p\) and its exactly-one child copies
satisfy
When the parent is inactive, its copies and descendant selectors are zero.
This preserves the hierarchy described in Section 3.3 of
Perez and Grossmann (2024).
Each nested group retains its own scope.
use oximo::prelude::*;use oximo::{HighsOptions, solvers::Highs};fn main() -> Result<(), Box<dyn std::error::Error>> { let model = Model::new("nested Hull technology selection"); variable!(model, 0.0 <= flow <= 8.0); boolean_variable!(model, present); boolean_variable!(model, absent); boolean_variable!(model, technology[i in 0..2]); disjunct_constraint!(model, absent, flow == 0.0); let limits = [3.0, 8.0]; disjunct_constraint!(model, technology[i], capacity[i in 0..2], flow <= limits[i]); disjunction!(model, [present, absent]); disjunction!(model, [technology[0], technology[1]], parent = present); objective!(model, Max, flow); let result = Highs .with_gdp(Hull::default()) .solve(&model, &HighsOptions::default())?; println!("flow: {:?}", result.value_of(flow)?); println!("high-capacity technology: {:?}", result.boolean_value_of(technology[1])?); Ok(())}
The optimum is flow = 8.0, with present and technology[1] selected.
Hull and Big-M can be mixed within this hierarchy using per-disjunction
with_method overrides. Big-M stages inside mixed subtrees use global bounds
for safe \(M\) estimation; independent subtrees using only Big-M retain the
ancestor tightening described above.
Hull::default() uses epsilon 1e-6; Hull::default().with_epsilon(value) requires a
finite value strictly between zero and one. At binary activations the transformed
row recovers the source behavior. For convex disjunct sets, the continuous
relaxation approximates the closed perspective as epsilon approaches zero.
Nonconvex source rows remain nonconvex. Choose a backend that supports the
generated nonlinear expressions, such as SCIP. Quadratic rows can avoid epsilon
with with_quadratic; see
Exact quadratic Hull.
A reference need not satisfy the branch's constraints, but it must make reference
evaluations and the generated perspective domains safe. Validation covers the
entire independent box of generated variable bounds, including points outside
the scaled bound rows. A reference inside the source domain can therefore fail:
for flow in [1, 4] in the reference example, reference
1 works, while references 2 and 4 make the
generated logarithm argument box cross zero. UnsafeHullDomain identifies the
operation, argument intervals, source row, scope, and whether validation failed
at the reference or over the generated box.
Large reference shifts can also lose significant precision in bounds or transformed
rows. Recovery checks account for summation and multiplication roundoff.
HullRowPrecisionLoss includes the absolute recovery error and allowed
tolerance; choose a closer reference or rescale the row when it occurs.
Zero effective bounds allow ordinary roundoff based on the retained source
coefficients, independently of reference magnitudes. Nonzero effective bounds
use a relative precision check.
For a source row \(x^\top Q x + c^\top x + d \le 0\) and activation \(y\),
HullQuadratic::Homogeneous multiplies the perspective by \(y\) instead of
dividing by it. With unshifted copies \(u = y x\), it generates
$$
u^\top Q u + (c^\top u)\, y + d\, y^2 \le 0.
$$
At \(y = 1\) this is the source row, and at \(y = 0\) it forces \(u = 0\)
together with the copy bounds. For \(y > 0\) it is the source row at
\(x = u / y\), so for convex disjunct sets the continuous relaxation is the
exact Hull, without epsilon.
HullQuadratic::Conic uses an epigraph variable \(t\) for a convex side:
$$
u^\top Q u \le t\, y, \qquad t + c^\top u + d\, y \le 0, \qquad
0 \le t \le U y.
$$
The first row is a rotated second-order cone, and \(U\) bounds \(t\) over
the variable bounds. A >= side uses \(-Q\), \(-c\), and \(-d\). For a copy
with a nonzero reference, Hull adds a
variable \(u = z + r y\) defined by a linear equality, so that \(y\) appears
only in the product with \(t\).
An inclusive group with n branches creates 2^n - 1 nonempty patterns. Each
pattern enforces every selected branch's rows, so this retains simultaneous
selection rather than replacing it with exactly-one semantics. Pattern weights
are continuous and linked to the original binary indicators. The pattern limit
is checked before allocation, separately for each group; nested groups retain
their own scopes.
Physical coordinates retain their supplied references. Descendant selectors
and generated child auxiliaries use reference zero when copied by an inclusive
ancestor, so an inactive nested group recombines to zero. Reports record each
copy's effective reference in its scope.
Reformulation validates domains, references, \(M\) values, size limits, and generated
numbers before changing the model. A reformulation error leaves the source unchanged, so you can correct
the data or options and retry.
The result-query rows also cover Boolean and Hull activation ownership.
Error
Cause
Fix
GdpError::MissingBigM
A row side has no explicit value, finite estimate, or fallback.
Establish valid global bounds or supply a justified explicit \(M\); see Missing \(M\).
GdpError::UnsafeDomain
A nonlinear expression is undefined somewhere in the global domain, even with its branch inactive.
Establish a safe domain through global bounds or supported unconditional constraints; \(M\) alone cannot fix it. See Nonlinear domains.
GdpError::InvalidBigM
An \(M\) value is negative, infinite, or NaN.
Supply a finite nonnegative magnitude; zero is accepted.
GdpError::InvalidExpression
A conditional row has invalid numeric values or variable bounds.
Check parameters, expression constants, and variable bounds.
GdpError::NumericOverflow
Generated coefficients or bounds are not representable as finite numbers.
Rescale the model, tighten bounds, and reduce oversized \(M\) values while preserving validity.
GdpError::PrecisionLoss
Big-M shifts lose significant precision in the active row.
Tighten bounds or supply a smaller valid \(M\); review coefficient scaling.
GdpError::MissingHullBounds
A copied coordinate lacks finite lower or upper bounds.
Supply valid global bounds or derive them through unconditional affine constraints.
GdpError::InclusiveHull
Hull encountered AtLeastOne with enumeration disabled.
Enable HullInclusivePolicy::Enumerate or select Big-M for that group.
GdpError::HullPatternLimit
An inclusive group's patterns exceed its configured limit.
Review group size and increase the limit only with acceptable expansion costs.
GdpError::InvalidHullEpsilon
Epsilon is non-finite or outside the open interval (0, 1).
Use a finite epsilon strictly between zero and one.
GdpError::InvalidHullReference
A reference coordinate is infinite or NaN.
Supply a finite reference.
GdpError::ExpectedHullReferenceVariable
A reference setter received a compound expression or constant.
Pass a bare variable handle. Foreign handles are reported separately.
GdpError::UnsafeHullDomain
A reference evaluation or generated perspective box crosses a function's domain.
Inspect the operation, argument intervals, scope and context; choose a safe reference or another method.
GdpError::HullReferencePrecisionLoss
A shift loses precision in a copied coordinate's bounds.
Choose a closer reference or rescale the coordinate.
GdpError::HullRowPrecisionLoss
An active coefficient or effective bound cannot be recovered accurately.
Inspect error and tolerance; choose a closer reference or rescale the row.
GdpError::SizeLimit / GdpError::PlanningLimit
Total committed size or temporary planning work exceeds a configured limit.
Reduce expansion or review and raise the corresponding limit.
GdpError::ForeignHandle
Options refer to an unknown handle or a handle from another model.
Use handles belonging to the model being reformulated; rebind handles for independent copies.
GdpError::Capacity
Reformulation would exceed the model's numeric ID capacity.
Reduce or partition the model.
GdpSolveError::Reformulation
with_gdp(...).solve(...) wraps a GdpError; the backend has not run.
Fix the enclosed GDP error and retry; the model is unchanged.
GdpSolveError::Solver
The backend failed after successful reformulation.
Inspect the enclosed solver error and backend configuration. Reformulation remains applied, including its locks.
BooleanValueError::NonBooleanValue
A selection value is non-finite or farther than 1e-5 from both zero and one.
Check the solution's feasibility and integrality. For an LP relaxation, query the numeric value with value_of(handle.binary()).
BooleanValueError::ModelMismatch
The Boolean handle belongs to another model, even if no solution value is available.
Query with a handle from the solved model; rebind handles when using a reformulated copy.
ModelMismatchError from hull_activation_value_of
The activation handle or best solution belongs to another model.
Obtain a handle from the solved model's reformulation report.
model.reformulate_gdp(options) transforms the model in place. It validates the
complete plan before making changes; an error leaves the model unchanged.
Repeated calls transform only pending GDP components. Changing an already applied
method requires a fresh source model.
Use model.to_reformulated_gdp_model(options) to transform an independent copy
and retain the source for other data or method choices. Query the copy's results
using handles belonging to that copy:
let transformed = model.to_reformulated_gdp_model(BigM::default())?;let transformed_flow = transformed.variable_handle(flow.var_id().unwrap());let transformed_large = transformed.boolean_handle(large.id());let result = Highs.solve(&transformed, &HighsOptions::default())?;println!("flow: {:?}", result.value_of(transformed_flow)?);let selected = result.boolean_value_of(transformed_large)?;println!("large unit selected: {selected:?}");
Call the clone API before an in-place transformation when you want to retain
an unreformulated source. The copy enforces its own reformulation locks.
Successful transformations retain source records and provenance:
API
Contents
model.gdp()
Borrowed view of Boolean decisions, conditional rows, disjunctions, and logical source constraints
model.gdp_snapshot()
Owned copy of the GDP source records
model.gdp_reformulations()
Transformation history
Returned GdpReformulationReport
Generated rows and auxiliaries, Boolean/binary mappings, methods, per-side \(M\) values, and Hull copies, references, patterns and branch sums
Print the report directly for a compact summary, or use report.display(&model)
to include generated variable names, bounds, and algebraic rows:
For programmatic variable inspection, report.generated_variables(&model)
Generated variable and row fields use GeneratedVarId and
GeneratedConstraintId. Ordinary variable-handle and scalar-row APIs do not
accept these types directly. Use id.raw_id() explicitly when inspecting the
transformed model's registries. Use the Hull activation helpers below to query
activation values retained by with_gdp.
report.hull_variables describes each copy through its source, generated,
bounds, effective reference, and activation. The source can be another
generated child copy, selector, or pattern weight. Its ReformulationVarId
provides source() and generated() accessors to distinguish these cases;
raw_id() retrieves the underlying registry ID. constraints lists the copy's
bound artifacts, including ancestor transformations; use report.rows to trace
the source's conditional rows. hull_patterns records inclusive selections and
weights. hull_branch_sums records weights shared by unused branches.
activation_kind distinguishes an indicator, complement, joint pattern, or branch
sum. Copies activated by complements, patterns, or branch sums have
indicator = None. The raw activation expression ID is also available.
Obtain model-bound activation handles through report.hull_activation(copy_index)
or report.hull_activations() in copy order, then query numeric values without
evaluating an expression ID:
let reports = model.gdp_reformulations();for report in reports.iter() { for (copy, activation) in report.hull_variables.iter().zip(report.hull_activations()) { let value = result.hull_activation_value_of(activation)?; println!("copy {:?}, activation: {value:?}", copy.generated); }}
This helper works on SolverResult and SolutionPoint, preserves fractional
relaxation values, and returns Ok(None) for missing values or solutions.
It rejects a foreign handle even without a solution, and checks the best
solution's identity for SolverResult. Use the transformed copy's report when
querying that copy's result. When a model is copied, its reports rebind ownership while sharing
artifact storage.
With with_quadratic, three more report fields describe the
generated artifacts:
Field
Contents
report.hull_epigraphs
One entry per cone: source row, side, the epigraph variable generated, its bound upper, and the activation, as in hull_variables.
report.hull_unshifted
One entry per shifted copy used in a cone: the copy, the unshifted variable generated, and its defining row in constraints.
report.hull_quadratic_fallbacks
Source rows, or row sides, that did not use the requested form. side is None when the whole row fell back, and reason explains why.
for fallback in &report.hull_quadratic_fallbacks { println!("{:?} {:?}: {:?}", fallback.source, fallback.side, fallback.reason);}
Printing the report also shows the number of cones and fallbacks.
Transformed disjunct groups cannot be extended. Bound and parameter mutations
that would invalidate transformed rows are rejected. To change dependent data,
update the unreformulated source and create a fresh transformed copy.
Ordinary solver calls, persistent solves, and LP/MPS/NL export reject pending
GDP components. with_gdp(...).solve(...) reformulates them before invoking the
backend. Use model.has_unreformulated_gdp() to check whether reformulation is
still required. Exported files contain the resulting algebraic model.
If part of this guide is confusing, incomplete, outdated, or hard to follow, say so. Getting stuck while trying to do something in oximo usually means the docs can be better, not that you missed something.
AI-assisted contributions are allowed. Contributors remain fully responsible for the quality, correctness, licensing, and usefulness of what they submit. The standards are the same either way.
Review and validate AI-assisted content before submitting it. Using an AI tool does not transfer responsibility for correctness, code quality, license compliance, security, or documentation accuracy.
Disclose it when a significant portion of a contribution is generated by, or copied verbatim from, an AI tool. Routine help (grammar, spelling, minor phrasing) needs no disclosure.
Note it in the pull request description, or use a commit trailer:
Assisted-by: generic LLM chatbot
This helps the project evaluate tooling practices and refine these guidelines over time.