oximo

oximo is a Rust algebraic modeling library for linear, mixed-integer, and nonlinear optimization.
Generated on November 24, 2026

Table of Contents

  1. Installation
  2. Quickstart
  3. Modeling
  4. Solvers
  5. Results
  6. Printing & Debugging
  7. I/O
  8. Generalized Disjunctive Programming
  9. Contributing

Installation

For most projects, installation is one command. The default oximo build provides the modeling layer and file I/O. Solver backends are opt-in.

This site is a guide for tutorials and worked examples. For the complete API reference, see docs.rs/oximo.

πŸ”—Start here

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 2024
cd my-oximo-model
cargo 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.

πŸ”—HiGHS

HiGHS is a bundled LP/MILP/QP solver. Enable it by doing:

cargo add oximo --features highs

The HiGHS build requires a C/C++ compiler:

  • On Windows, install the MSVC C++ build tools.
  • On macOS, run xcode-select --install.
  • On Linux, install your distribution's standard C/C++ build tools.

Then follow the Quickstart to solve the example model.

πŸ”—Clarabel

Clarabel is a pure-Rust solver for continuous LP, QP, and SOCP models:

cargo add oximo --features clarabel

Use this path when you want a solver without a C compiler or external solver installation. Clarabel does not solve mixed-integer models.

πŸ”—Clarabel SDP

Semidefinite programming (SDP) support is available by choosing one BLAS/LAPACK provider:

FeatureProviderTypical platform
clarabel-sdp-openblasOpenBLASLinux; source builds need C and Fortran compilers
clarabel-sdp-mklIntel MKLWindows or Linux
clarabel-sdp-accelerateApple AcceleratemacOS

The bare clarabel-sdp feature enables SDP when your application supplies BLAS/LAPACK linkage. On Windows, the OpenBLAS feature uses a system installation.

See Modeling > Semidefinite constraints for more information.

πŸ”—Other backends

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.

πŸ”—Advanced: exact nonlinear derivatives

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:

RUSTFLAGS="-Zautodiff=Enable" cargo +nightly build --profile enzyme --features pounce-enzyme

πŸ”—Feature reference

FeatureIncluded by defaultPurpose
ioyesMPS, LP, and NL file readers and writers.
highsnoBundled Highs solver for LP, MILP, and QP.
baronnoBaron global-optimization backend.
clarabelnoPure-Rust Clarabel solver for LP, QP, and SOCP.
clarabel-faernoUse Clarabel's faer linear-algebra backend.
clarabel-sdpnoClarabel SDP with supplied BLAS/LAPACK linkage.
clarabel-sdp-openblasnoClarabel SDP with OpenBLAS.
clarabel-sdp-mklnoClarabel SDP with Intel MKL.
clarabel-sdp-acceleratenoClarabel SDP with Apple Accelerate.
gurobinoGurobi backend.
gamsnoGams bridge.
pouncenoPure-Rust Pounce solver for continuous nonlinear models.
pounce-enzymenoExact Enzyme derivatives for POUNCE; requires nightly Rust.
scipnoBundled Scip solver. Downloads SCIP binaries at build time.
scip-systemnoScip backend using an existing installation and libclang.
moseknoMosek backend for MOSEK 11.2.

Quickstart

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.

πŸ”—1. Create a project and enable a solver

This example requires Rust 1.89 or later. Create a project first:

cargo new lp-model --edition 2024
cd 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.

πŸ”—HiGHS

HiGHS is a bundled solver for LP, MILP, and QP. It needs a C/C++ compiler at build time:

cargo add oximo --features highs

πŸ”—Clarabel

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.

πŸ”—2. Understand the model

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.

πŸ”—3. Start a Rust program

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.

πŸ”—4. Declare decision variables

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.

πŸ”—5. Add constraints and an objective

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.

πŸ”—6. Solve and inspect the result

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.

πŸ”—Choose the solver

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.

πŸ”—Next steps

  • 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

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 β‰₯ 0
variable!(m, 0.0 <= y <= 10.0);         // continuous, 0 ≀ y ≀ 10
variable!(m, z);                        // free, unbounded by default
variable!(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 domain
variable!(m, w, lb = 0.0, ub = 10.0, Int); // mixed with a positional domain token
variable!(m, p, lb = 0.0, initial = 3.0);  // warm start (scalar only)
variable!(m, q, fix = 5.0);                // fixed to 5.0 (scalar only)
Domain tokenMeaning
(none)Continuous
BinBinary {0, 1} (alias Binary)
IntGeneral integer (alias Integer)
SemiCont(t)Zero, or continuous in [t, ub]
SemiInt(t)Zero, or integer in [t, ub]

πŸ”—Parameters

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.

Each solve captures the parameter values used by the backend; see Results > Parameter snapshots and scenario queries.

πŸ”—Index sets

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 pattern
set!(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]);

πŸ”—Indexed variables

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 route
variable!(m, y[k in items] >= 0.0, Int);    // integer family
variable!(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);

x[key] returns the Expr for that element, ready to drop into a constraint or objective.

πŸ”—Expressions

Exprs are built with standard Rust operators. Scalars are f64.

let lhs = x + 2.0 * y - 3.0 * z;
let rhs = 4.0 * x + 5.0;

Expressions carry a degree in their Rust type: constant, affine, quadratic, nonlinear, or dynamic. For example, x.square() and x * x are statically quadratic, while x.powi(n) has a dynamic degree because n is a runtime value. Use expr.try_affine()? or expr.try_quadratic()? when an API requires a checked narrower degree. Use expr.erase() when a collection needs to hold expressions of different degrees.

πŸ”—Aggregating over sets

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.

// 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 markets
let 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]);

For the plain dot-product case there is also dot.

πŸ”—Constraints

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.

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.

πŸ”—Functions in sets

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.

πŸ”—Handles and updates

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.

πŸ”—Semidefinite constraints

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 matrices

symmetric_variable!(m, X[n]) returns a SymmetricMatrix<Expr<Affine>> 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.

πŸ”—Affine matrix inequalities

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.

πŸ”—Names, families, and activity

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.

πŸ”—Indicator constraints

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)?;

πŸ”—Special ordered sets (SOS) constraints

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:

sos_constraint!(m, weighted_choice, SOS2, [
    (x, 10.0),
    (y, 20.0),
    (z, 50.0),
]);

πŸ”—Indexed SOS families

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:

sos_constraint!(m, curve[i in 0..n], SOS2, [
    (x[i], 1.0),
    (y[i], 2.0),
    (z[i], 3.0),
]);

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())?;

To query these results with the original x, y, and z handles, use source-result projection.

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.

πŸ”—Objectives

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.

πŸ”—Rule-style constraints

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 expressions

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 NLP
objective!(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.

πŸ”—Incremental affine construction

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.

πŸ”—Next steps

  • Solvers: pick a backend, set options, read the solution
  • Printing & Debugging: print a model as algebra and check what it actually says
  • I/O: export your model to MPS, LP, or NL

Solvers

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.

πŸ”—Choosing a backend

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.

πŸ”—Model kind support

Each row summarizes the backend's coverage of ModelKind. This is a broad classification; validate the complete model for data and option restrictions:

BackendLPMILPQPMIQPQCPMIQCPSOCPMISOCPSDPMISDPNLPMINLP
Highsβœ“βœ“βœ“β€”β€”β€”β€”β€”β€”β€”β€”β€”
Clarabelβœ“β€”βœ“β€”β€”β€”βœ“β€”**βœ“**ΒΉβ€”β€”β€”
Pounceβœ“β€”βœ“β€”βœ“β€”βœ“β€”β€”β€”βœ“β€”
Scipβœ“βœ“βœ“βœ“βœ“βœ“βœ“βœ“β€”β€”βœ“βœ“
Gurobiβœ“βœ“βœ“βœ“βœ“βœ“βœ“βœ“β€”β€”βœ“βœ“
Mosekβœ“βœ“βœ“βœ“βœ“βœ“βœ“βœ“βœ“β€”β€”β€”
Baronβœ“βœ“βœ“βœ“βœ“βœ“βœ“βœ“β€”β€”βœ“βœ“
Gamsβœ“βœ“βœ“βœ“βœ“βœ“βœ“βœ“β€”β€”βœ“βœ“

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.

ΒΉ Clarabel requires an SDP feature and BLAS/LAPACK provider.

πŸ”—Requirements & capabilities

Deployment cost and diagnostic/solve capability per backend.

βœ“ = yes/supported; β€” = no.

BackendLicenseSeparate installC compilerDirect interfaceIISWarm startSol. poolDualsParallel
Highsβ€”β€”βœ“βœ“β€”β€ βœ“β€”βœ“βœ“
Clarabelβ€”β€”β€”βœ“β€”βœ“β€”βœ“βœ“
Pounceβ€”β€”β€”βœ“β€”βœ“β€”βœ“β€”
Scipβ€”β€”β€”βœ“β€”βœ“βœ“βœ“β€‘βœ“
Gurobiβœ“βœ“β€”βœ“βœ“βœ“βœ“βœ“βœ“
Mosekβœ“βœ“β€”βœ“β€”βœ“β€”βœ“βœ“
Baronβœ“βœ“β€”β€”βœ“β€”βœ“βœ“βœ“
Gamsβœ“βœ“β€”β€”β€”β€”βœ“ΒΆβœ“βœ“

Column meanings:

  • 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.
  • Sol. pool: returns multiple solutions, best-first.
  • Duals: shadow prices/reduced costs.
  • Parallel: solver can solve in parallel.

Footnotes:

  • † The highs crate does not support IIS yet.
  • ΒΆ 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.

πŸ”—Checking model compatibility

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.

CapabilityMeaning
NativeThe backend implements the interface; whole-model and data checks still apply.
UnsupportedThe query found no supported interface.
RequiresValidation(reason)The signature alone is insufficient; actual function data or options must be checked.

πŸ”—HiGHS

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))?;

Common HighsOptions:

MethodEffect
.time_limit(d)Stop after d (std::time::Duration)
.threads(n)Cap parallelism
.mip_gap(g)Relative MIP optimality gap (e.g. 0.01 = 1%)
.verbose(b)Stream the solver log
.method(m)LP algorithm via HighsMethod (Simplex, Ipm, …)

πŸ”—Clarabel

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())?;

πŸ”—Semidefinite models

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.

Primal and PSD dual matrices are available through the matrix result accessors.

πŸ”—POUNCE

Pounce is a pure-Rust IPOPT and convex-solver backend. Enable the pounce feature:

use oximo::prelude::*;
use oximo::pounce::{Pounce, PounceOptions, PounceSolverSelection};

let result = Pounce.solve(&m, &PounceOptions::default())?;

πŸ”—Derivatives

  • 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.
  • pounce-enzyme feature: nightly-only exact gradients, sparse Jacobians, and sparse Lagrangian Hessians for nonlinear models. See Installation > Advanced: exact nonlinear derivatives.

Note: pounce-enzyme currently requires the nightly-2026-07-26 toolchain. Later nightly toolchains fail. See rust-lang/rust#160470.

πŸ”—Automatic routing

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.

πŸ”—Options

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

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

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))?;

Common GurobiOptions:

MethodEffect
.time_limit(d)Wall-clock limit
.mip_focus(n)Gurobi MIPFocus (1 = feasibility, 2 = optimality, 3 = bound)
.mip_gap(g)Relative MIP optimality gap
.seed(n)Random seed for reproducible runs

πŸ”—MOSEK

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.

πŸ”—Semidefinite models

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

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

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.

πŸ”—Nonlinear operators

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.

πŸ”—Next steps

  • 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.

πŸ”—Reading results

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>

πŸ”—Status

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.

πŸ”—Fields and accessors

ItemTypeWhat information is available
terminationTerminationStatusWhy the solver stopped
primal_statusPrimalStatusWhether a usable point is present
objective()Option<f64>Objective of the best solution
value_of(expr)Result<Option<f64>, ModelMismatchError>Expression value using solve-time parameters
value_of_captured(&expr)Result<Option<f64>, ModelMismatchError>Captured formula using solve-time parameters
parametersParameterSnapshotParameter values captured for this solve
values_of(&var)Result<iterator, ModelMismatchError>Every element of an indexed variable
dual_of(scalar_handle)Result<Option<f64>, ModelMismatchError>Scalar shadow price (continuous models)
soc_dual_of(handle)Result<Option<f64>, ModelMismatchError>SOC multiplier, when available
value_of_matrix(&matrix)Result<Option<SymmetricMatrix<f64>>, ModelMismatchError>Evaluated symmetric matrix at the best point
psd_dual_of(handle)Result<Option<&SymmetricMatrix<f64>>, ModelMismatchError>PSD cone dual matrix, when available
reduced_costsmap keyed by VarIdReduced costs (continuous models)
best_bound, gapOption<f64>Populated by branch-and-bound backends
solve_timeDurationWall-clock time in the backend
iterationsu64Iteration count when the backend reports one
raw_logOption<String>Backend log, when captured

πŸ”—Parameter snapshots and scenario queries

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 handles

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.

let bands: IndexedRangeConstraint<usize> =
    constraint!(m, bands[i in 0..n_items], 1.0 <= x[i] <= 4.0);

for (i, handles) in bands.iter() {
    match handles {
        RangeConstraintHandles::Interval(handle) => {
            println!("bands[{i}] = {:?}", result.dual_of(handle)?);
        }
        RangeConstraintHandles::Split { lower, upper } => {
            println!("bands[{i}] lower = {:?}", result.dual_of(lower)?);
            println!("bands[{i}] upper = {:?}", result.dual_of(upper)?);
        }
    }
}

πŸ”—Original constraints and stored rows

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.

πŸ”—Indexed variables

values_of walks an indexed family without a manual key loop:

for (key, value) in result.values_of(&x)? {
    println!("x[{}] = {value:.2}", display_index_key(key));
}

πŸ”—PSD matrix results

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.

πŸ”—Solution pools

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.

πŸ”—Next steps

  • Solvers: choose a backend and set its options
  • Printing & Debugging: inspect the model that produced a result
  • 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.

πŸ”—Printing

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 y
s.t.
  c1: x + 2 y <= 14
  c2: 3 x - y >= 0
vars
  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

πŸ”—Debugging

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!:

AdapterRenders
display_expr(e)A bare Expr
display_constraint(handle)?The original named constraint
display_row(id)A stored algebraic row
display_objective()The objective
display_soc(id)One second-order cone

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.

πŸ”—Rule-generated names

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.

πŸ”—Parameters show their current binding

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 = 4

m.set_param(price, 7.5)?;
println!("{m}"); // min 7.5 x ... params: price = 7.5

πŸ”—Checking the model kind

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.

πŸ”—Models with PSD blocks

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.

πŸ”—Diagnosing infeasibility

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.

Call compute_iis from the InfeasibilityDiagnosis trait, then render the result against the model with Iis::report.

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));
irreducible infeasible subsystem (2 members)

constraints (2)
  floor
  ceil

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 VarBoundKind Lower/Upper). compute_iis returns a SolverError if the model turns out feasible, so it doubles as an "is this actually infeasible?" assertion.

For more details on IIS support, see Solvers > Requirements & capabilities.

πŸ”—When printing isn't enough

ErrorDebugging steps
Backend rejects the modelCheck Model::kind() against the backend table
Model is too big to readExport it with io::write_lp (if linear)
Solver returns nothing usableInspect termination and primal_status, not just objective()
Model reports infeasibleCompute an IIS (if supported by backend)
Need the backend's own logsSet .verbose(true) in the options, or read result.raw_log

After a solve, result.report(&m) pairs the model with its solution in one print-out.

πŸ”—Next steps

  • 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

πŸ”—To a string

use oximo::io;

let mps = io::to_mps_string(&m)?;
let lp  = io::to_lp_string(&m)?;
let nl  = io::to_nl_string(&m)?;

Each returns a String you can log, hash, or feed into something else in memory.

πŸ”—To a file

use oximo::io;
use std::fs::File;

io::write_mps(&m, &mut File::create("model.mps")?)?;
io::write_lp(&m, &mut File::create("model.lp")?)?;
io::write_nl(&m, &mut File::create("model.nl")?)?;

Each writer accepts anything that implements std::io::Write.

πŸ”—Picking a format

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.

FormatProsWhen to pick
MPSUniversal, column-oriented, fixed historical formatMaximum solver compatibility, archival
LPHuman-readable, row-oriented, mirrors algebraic notationQuick inspection, sharing in bug reports
NLCompact, carries nonlinear structureNLP/MINLP models, AMPL-compatible solvers

πŸ”—NL options

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.

use oximo::io::{NlFormat, WriteOptions, write_nl_with};
use std::fs::File;

let opts = WriteOptions { format: NlFormat::Ascii, ..Default::default() };
write_nl_with(&m, &mut File::create("model.nl")?, &opts)?;

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.

πŸ”—NL operator support

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:

OpcodeOperationoximo support
o13floorNot represented by the expression model
o14ceilNot represented by the expression model
o15absRead and written
o16unary -Read and written
o34logical notLogical expressions are not represented
o37tanhRead and written
o38tanRead and written
o39sqrtRead and written
o40sinhRead and written
o41sinRead and written
o42log10Read and written
o43logRead and written
o44expRead and written
o45coshRead and written
o46cosRead and written
o47atanhRead and written
o49atanRead and written
o50asinhRead and written
o51asinRead and written
o52acoshRead and written
o53acosRead 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.

πŸ”—Names round-trip

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).

πŸ”—Reading MPS models

Use read_mps_file for a path or read_mps for any text stream:

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)?;

Malformed input returns IoError::InvalidMps. Multiple alternative RHS, range, or bounds vectors and unsupported MPS constructs return IoError::UnsupportedMps.

πŸ”—Reading NL models

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.

πŸ”—Reading LP models

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.

πŸ”—Skipping the writers

If you don't need file export, opt out of the io feature to drop the dependency:

[dependencies]
oximo = { version = "0.8", default-features = false, features = ["highs"] }

πŸ”—Semidefinite constraints

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.

Solve SDP models directly with Clarabel or MOSEK.

Generalized Disjunctive Programming

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.

πŸ”—Enable GDP

Enable the gdp feature on oximo:

[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.

πŸ”—Terminology

This document uses the following terms:

TermMeaningAPI
Boolean variableA logical variable \(Y\), with value true or false.BooleanHandle, declared with boolean_variable! or by disjunct!
IndicatorThe Boolean decision that activates a disjunct or conditional row.handle.indicator()
Binary counterpartThe algebraic variable \(y \in \{0,1\}\) corresponding to \(Y\). Use it in arithmetic and numeric result queries.handle.binary()
Conditional rowAn algebraic relation that applies only when its indicator is true. β€œDisjunct constraint” is the API's name for a conditional row.DisjunctConstraintHandle, disjunct_constraint!
DisjunctA block of conditional rows sharing one indicator.DisjunctHandle, disjunct!
BranchOne 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
DisjunctionA 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.

πŸ”—Boolean decisions

A Boolean variable represents a logical decision:

$$ Y_i \in \{\mathrm{true},\mathrm{false}\}. $$

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.

$$ \begin{aligned} \max\quad & q-c \\ \text{subject to}\quad & \left[\begin{array}{c} Y_{\mathrm{small}} \\ c = 0 \end{array}\right] \underline{\bigvee} \left[\begin{array}{c} Y_{\mathrm{large}} \\ c = 2 \end{array}\right], \\ & 0 \le c \le 2. \end{aligned} $$

The full formulation appears in Disjunct blocks below.

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

$$ y_i = \begin{cases} 1, & Y_i = \mathrm{true}, \\ 0, & Y_i = \mathrm{false}. \end{cases} $$

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.

πŸ”—Disjunct blocks

A disjunct groups conditional rows under one indicator. For a vector of algebraic variables \(x\), write disjunct \(i\) as

$$ D_i = \left[\begin{array}{c} Y_i \\ h_i(x) \le 0 \end{array}\right]. $$

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:

$$ \begin{aligned} \max\quad & q-c \\ \text{subject to}\quad & \left[\begin{array}{c} Y_{\mathrm{small}} \\ q \le 3 \\ c = 0 \end{array}\right] \underline{\bigvee} \left[\begin{array}{c} Y_{\mathrm{large}} \\ 5 \le q \le 8 \\ c = 2 \end{array}\right] \\ & 0 \le q \le 10, \qquad 0 \le c \le 2, \\ & Y_{\mathrm{small}},Y_{\mathrm{large}} \in \{\mathrm{true},\mathrm{false}\}. \end{aligned} $$

\(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.

πŸ”—Boolean-tagged constraints

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\):

$$ \begin{aligned} \max\quad & x \\ \text{subject to}\quad & Y_i \Rightarrow e^x \le L_i, \qquad i \in \{0,1\}, \\ & \operatorname{ExactlyOne}(Y_0,Y_1), \\ & 0 \le x \le 3, \qquad Y_0,Y_1 \in \{\mathrm{true},\mathrm{false}\}. \end{aligned} $$

\(\operatorname{ExactlyOne}\) means exactly one argument is true:

use oximo::prelude::*;

let model = Model::new("tagged choices");
variable!(model, 0.0 <= x <= 3.0);
boolean_variable!(model, selected[i in 0..2]);

let limits = [2.0, 4.0];
let rows = disjunct_constraint!(model, selected[i],
    capacity[i in 0..2], x.exp() <= limits[i]);
let branches = [selected[0], selected[1]];
let choice = disjunction!(model, choice, branches);
objective!(model, Max, x);

model.reformulate_gdp(BigM::default())?;

This produces a mixed-integer nonlinear model. Choose a backend with support for the resulting expressions; see Solvers.

πŸ”—Macro grammar

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.

MacroAccepted formsBinding 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.

ExampleHow 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()).

πŸ”—Disjunction semantics

For a branch index set \(I\), the default exactly-one disjunction requires

$$ \underline{\bigvee}_{i \in I} Y_i = \mathrm{true}. $$

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:

FormRequirement
disjunction!(model, branches) or an explicit ExactlyOneExactly 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 ^ bBinary XOR: exactly one of these two formulas is true.
a ^ b ^ cChained 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.

πŸ”—Logical constraints

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:

Mathematical notationRust expressionMeaning
\(\neg A\)!aNOT
\(A \land B\)a & bAND
\(A \lor B\)a | bInclusive OR
\(A \oplus B\)a ^ bExclusive OR of two formulas
\(A \Rightarrow B\)implies(a, b) or a.implies(b)If a, then b
\(A \Leftrightarrow B\)iff(a, b) or a.equivalent_to(b)Both have the same truth value
\(N = k\)exactly(k, terms)Exactly k terms are true
\(N \le k\)at_most(k, terms)At most k terms are true
\(N \ge k\)at_least(k, terms)At least k terms are true

Assert a formula with logical_constraint!:

logical_constraint!(model, selected.implies(mode[0]));

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.

πŸ”—Nested disjunctions

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.

$$ \begin{aligned} & \left[\begin{array}{c} P \\ \left[\begin{array}{c} Y_0 \\ q \le 3 \end{array}\right] \underline{\bigvee} \left[\begin{array}{c} Y_1 \\ q \le 8 \end{array}\right] \end{array}\right] \underline{\bigvee} \left[\begin{array}{c} A \\ q = 0 \end{array}\right], \\ & 0 \le q \le 8, \qquad P,A,Y_0,Y_1 \in \{\mathrm{true},\mathrm{false}\}. \end{aligned} $$

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.

πŸ”—Reformulations available

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.

MethodHow it worksWhat 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

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:

OptionWhen 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.
BigM::default().with_hierarchical_tightening(false)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

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:

OptionDefault and purpose
Hull::default().with_inclusive_policy(...)Rejects AtLeastOne groups by default. Enable HullInclusivePolicy::Enumerate { max_patterns } to preserve inclusive selection.
options.with_hull_reference_coordinate(variable, reference)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.

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.

πŸ”—Reference example

Restricted-domain functions may require an explicit reference. For example, zero is not a valid reference for the logarithm below:

use oximo::prelude::*;

let model = Model::new("logarithmic Hull");
variable!(model, 1.0 <= flow <= 4.0);
boolean_variable!(model, active);
disjunct_constraint!(model, active, flow.ln() <= 3.0_f64.ln());

let options = GdpReformulationOptions::new(Hull::default())
    .with_hull_reference_coordinate(flow, 1.0);
model.reformulate_gdp(options)?;

Use with_hull_reference_coordinates(...) to set references for several variables at once; see Affine rows and reference coordinates.

πŸ”—Inclusive selection

Hull requires ExactlyOne by default. To preserve AtLeastOne semantics, explicitly enable local activation-pattern enumeration:

use oximo::prelude::*;

let model = Model::new("inclusive Hull");
variable!(model, 0.0 <= flow <= 4.0);
boolean_variable!(model, left);
boolean_variable!(model, right);
disjunct_constraint!(model, left, flow <= 2.0);
disjunct_constraint!(model, right, flow >= 1.0);
disjunction!(model, [left, right], AtLeastOne);

let hull = Hull::default().with_inclusive_policy(
    HullInclusivePolicy::Enumerate { max_patterns: 3 },
);
model.reformulate_gdp(hull)?;

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.

πŸ”—Applying a reformulation

πŸ”—Select during solving

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.

πŸ”—Per-disjunction configuration

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.

πŸ”—Reformulate explicitly

Use explicit reformulation to export the transformed model or inspect all generated values and multipliers:

model.reformulate_gdp(Hull::default())?;
let result = Highs.solve(&model, &HighsOptions::default())?;

To transform an independent copy instead, use model.to_reformulated_gdp_model(...).

πŸ”—Planning and expansion limits

Inspect a fully validated reformulation without changing the source model:

use oximo::prelude::*;

let model = Model::new("planned Hull");
variable!(model, 0.0 <= flow <= 4.0);
boolean_variable!(model, active);
disjunct_constraint!(model, active, flow <= 2.0);

let options = GdpReformulationOptions::new(Hull::default())
    .with_size_limits(GdpSizeLimits {
        variables: Some(10_000),
        constraints: Some(50_000),
        expression_nodes: Some(100_000),
    })
    .with_planning_limits(GdpPlanningLimits {
        row_expansions: Some(200_000),
        expression_nodes: Some(150_000),
    });

let summary = model.plan_gdp(options.clone())?;
println!("generated copies: {}", summary.hull_copies);
println!("final model size: {:?}", summary.total);

let report = model.reformulate_gdp(options)?;
println!("planning work: {:?}", report.planning);

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.

πŸ”—Implementation details

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.

πŸ”—Big-M values

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.

πŸ”—Choosing \(M\)

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.

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 and bound tightening

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.

πŸ”—Explicit values and fallbacks

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\).

PrioritySourceHow to set it
1Explicit value for this row sideoptions.with_big_m(row, BigMValues::upper(value)) or BigMValues::lower(value)
2Automatic estimateGlobal variable bounds and enabled bound tightening
3Fallback on this disjunction's method overrideoptions.with_method(choice, BigM::default().with_fallback_big_m(value))
4Options-level global fallbackoptions.with_fallback_big_m(value)
5Default-method global fallbackGdpReformulationOptions::new(BigM::default().with_fallback_big_m(value))

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.

πŸ”—Hierarchical Big-M

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:

$$ h(x) \le M_{\mathrm{local}}(1-w) + (M_{\mathrm{global}}-M_{\mathrm{local}})(1-p). $$

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:

model.reformulate_gdp(BigM::default().with_hierarchical_tightening(false))?;

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.

πŸ”—Missing \(M\): failure and fixes

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:

constraint!(model, physical_limit, 0.0 <= x <= 22.0);
let options = GdpReformulationOptions::default()
    .with_bound_tightening(false)
    .with_big_m(row, BigMValues::upper(20.0));

model.reformulate_gdp(options)?;

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.

πŸ”—Nonlinear domains

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.

πŸ”—Hull transformation

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.

πŸ”—Affine rows and reference coordinates

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

$$ v_i = y_i(x-r), \qquad (L-r)y_i \le v_i \le (U-r)y_i. $$

The aggregation equation recovers the source coordinate:

$$ x = r + \sum_i v_i, \qquad \sum_i y_i = 1. $$

For an affine conditional row \(a^{\mathsf T}x \le b\), the generated row is

$$ a^{\mathsf T}v_i + (a^{\mathsf T}r-b)y_i \le 0. $$

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 Hull

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

$$ \sum_j v_{pj} = v_p, \qquad \sum_j y_{pj} = y_p. $$

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.

πŸ”—Nonlinear perspectives and domains

For a nonlinear conditional row \(f(x) \le u\), Hull uses the regularized perspective below, with \(v=y(x-r)\):

$$ \begin{aligned} &d(y) = \varepsilon + (1-\varepsilon)y, \\ &d(y) f\!\left(\frac{v}{d(y)}+r\right) - \varepsilon f(r)(1-y) \le uy. \end{aligned} $$

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.

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.

πŸ”—Inclusive disjunctions

With inclusive enumeration enabled, Hull transforms each nonempty selection pattern as an alternative.

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.

πŸ”—Errors and recovery

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.

ErrorCauseFix
GdpError::MissingBigMA row side has no explicit value, finite estimate, or fallback.Establish valid global bounds or supply a justified explicit \(M\); see Missing \(M\).
GdpError::UnsafeDomainA 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::InvalidBigMAn \(M\) value is negative, infinite, or NaN.Supply a finite nonnegative magnitude; zero is accepted.
GdpError::InvalidExpressionA conditional row has invalid numeric values or variable bounds.Check parameters, expression constants, and variable bounds.
GdpError::NumericOverflowGenerated coefficients or bounds are not representable as finite numbers.Rescale the model, tighten bounds, and reduce oversized \(M\) values while preserving validity.
GdpError::PrecisionLossBig-M shifts lose significant precision in the active row.Tighten bounds or supply a smaller valid \(M\); review coefficient scaling.
GdpError::MissingHullBoundsA copied coordinate lacks finite lower or upper bounds.Supply valid global bounds or derive them through unconditional affine constraints.
GdpError::InclusiveHullHull encountered AtLeastOne with enumeration disabled.Enable HullInclusivePolicy::Enumerate or select Big-M for that group.
GdpError::HullPatternLimitAn inclusive group's patterns exceed its configured limit.Review group size and increase the limit only with acceptable expansion costs.
GdpError::InvalidHullEpsilonEpsilon is non-finite or outside the open interval (0, 1).Use a finite epsilon strictly between zero and one.
GdpError::InvalidHullReferenceA reference coordinate is infinite or NaN.Supply a finite reference.
GdpError::ExpectedHullReferenceVariableA reference setter received a compound expression or constant.Pass a bare variable handle. Foreign handles are reported separately.
GdpError::UnsafeHullDomainA 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::HullReferencePrecisionLossA shift loses precision in a copied coordinate's bounds.Choose a closer reference or rescale the coordinate.
GdpError::HullRowPrecisionLossAn active coefficient or effective bound cannot be recovered accurately.Inspect error and tolerance; choose a closer reference or rescale the row.
GdpError::SizeLimit / GdpError::PlanningLimitTotal committed size or temporary planning work exceeds a configured limit.Reduce expansion or review and raise the corresponding limit.
GdpError::ForeignHandleOptions 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::CapacityReformulation would exceed the model's numeric ID capacity.Reduce or partition the model.
GdpSolveError::Reformulationwith_gdp(...).solve(...) wraps a GdpError; the backend has not run.Fix the enclosed GDP error and retry; the model is unchanged.
GdpSolveError::SolverThe backend failed after successful reformulation.Inspect the enclosed solver error and backend configuration. Reformulation remains applied, including its locks.
BooleanValueError::NonBooleanValueA 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::ModelMismatchThe 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_ofThe activation handle or best solution belongs to another model.Obtain a handle from the solved model's reformulation report.

πŸ”—Lifecycle, cloning, and reports

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:

APIContents
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 GdpReformulationReportGenerated 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:

println!("{report}");
println!("{}", report.display(&model));

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.

πŸ”—Hull copy and activation reports

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.

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.

πŸ”—Examples and further reading

From the oximo repository, run:

cargo run -p oximo --example gdp_big_m --features gdp,highs
cargo run -p oximo --example gdp_nonlinear --features gdp,scip
cargo run -p oximo --example gdp_hull_nonlinear --features gdp,scip
  • Modeling: variables, expressions, and indexed constraints.
  • Solvers: choose a backend for the reformulated model.
  • Results: query algebraic variable values and solve status.
  • I/O: export the reformulated model.

Contributing

All contributions are welcome: bug reports, documentation fixes, tests, and code. Everything happens on GitHub.

πŸ”—Reporting bugs

If you hit a bug, unexpected behavior, or an inconsistency, open an issue. Many problems are found by users first, and a report helps everyone.

A useful report includes:

  • A clear description of the problem
  • Steps to reproduce it
  • Expected and actual behavior
  • Relevant error messages or logs
  • A minimal reproducible example, when possible

πŸ”—Improving documentation

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.

Worth sending:

  • Clarifications to existing guides
  • More examples
  • Tutorials
  • Better API explanations
  • Typo and formatting fixes

Open an issue or send a pull request directly.

πŸ”—Contributing code

Bug fixes, performance work, new features, tests, and refactors are all fair game.

  1. Fork the repository
  2. Create a branch for your changes
  3. Make your modifications
  4. Add or update tests when appropriate
  5. Run cargo fmt and make sure cargo clippy passes
  6. Write a commit message following the naming convention
  7. Run the tests relevant to your change
  8. Open a pull request

Keep pull requests focused and reasonably scoped. Smaller ones are easier to review and land.

πŸ”—Testing

Some tests need third-party tools, including commercial solvers. Default features don't depend on any of them.

You are not expected to run tests for crates unrelated to your change. Skip them with --exclude:

cargo test --workspace --exclude oximo-gurobi

A reviewer runs the full suite manually before merging. The GitHub CI workflow can't execute all tests because of solver licensing restrictions.

πŸ”—Commit naming convention

oximo follows a commit naming convention that keeps the history readable and makes the scope of a change obvious at a glance.

ScopePrefix
A single crateoximo-<crate-name>:
Workspace configurationworkspace:
GitHub workflows or repo configgithub:
More than one backendbackends:

Examples:

oximo-core: Improve error handling
workspace: Update dependency versions
github: Add CI workflow for testing
backends: Improve mapping of terminations

πŸ”—AI-assisted contributions

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.

πŸ”—Accountability

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.

πŸ”—Transparency

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.

πŸ”—Licensing

By contributing to oximo you agree that your contributions are licensed under the same dual-license terms as the project:

  • MIT License
  • Apache License 2.0

Unless stated otherwise, all submitted contributions are assumed to be provided under both.

© 2026 oximo