A Rust interface to the CONOPT nonlinear optimization solver,
built on its C API (conopt-sys/include/conopt.h, version 4.39.3).
The workspace has two crates:
conopt-sys: raw bindings to every function and callback type inconopt.h, plus the build script that links the CONOPT library. Re-exported asconopt::ffi.conopt: the safe API. The problem structure is aModel(withModelBuilderandRawModelas provided ways to supply one), the nonlinear terms come from anEvaluator, and aConoptobject holds the settings and runs the solve.
The CONOPT shared library is not bundled. Point the build at the directory that contains it:
export CONOPT_DIR=/path/to/conopt-linux-x86_64 # an unpacked CONOPT distribution (uses its lib/)
# or: export CONOPT_LIB_DIR=/path/to/directory/with/libconopt
cargo test # whole workspace
cargo run -p conopt --example tutorial # add `-- --hessian` for second derivativesThe conopt crate's tests and examples get an rpath to CONOPT_LIB_DIR. Binaries in other crates
need the library on the loader path at run time (LD_LIBRARY_PATH, DYLD_LIBRARY_PATH or
PATH).
The code in this repository is released under the MIT license (see LICENSE), with one
exception: conopt-sys/include/conopt.h is the CONOPT C API header, copyright GAMS Software
GmbH and GAMS Development Corporation, and is included unchanged under GAMS's terms. CONOPT
itself is not part of this repository and needs its own license from GAMS.
Without a license CONOPT runs in demo mode, which is limited to small models. Provide a license either in code:
solver.set_license(conopt::License { int1, int2, int3, text: "...".into() })?;or through the environment, read at solve time:
export CONOPT_LICENSE_INT_1=...
export CONOPT_LICENSE_INT_2=...
export CONOPT_LICENSE_INT_3=...
export CONOPT_LICENSE_STRING="..." # CONOPT_LICENSE_TEXT is accepted toouse conopt::{Conopt, ConstraintType, EvalResult, Evaluator, ModelBuilder, RowJacobian, Sense};
// min (x - 2)^2 + y s.t. x + y >= 1, y >= 0
struct Problem;
impl Evaluator for Problem {
fn eval_row(&mut self, x: &[f64], _row: usize, value: Option<&mut f64>,
jacobian: Option<&mut RowJacobian<'_>>) -> EvalResult {
// Only row 0 has nonlinear terms, so CONOPT only asks for it.
if let Some(v) = value { *v = (x[0] - 2.0).powi(2); }
if let Some(j) = jacobian { j[0] = 2.0 * (x[0] - 2.0); }
Ok(())
}
}
let mut model = ModelBuilder::new();
let x = model.add_free_variable(0.0);
let y = model.add_variable(0.0, f64::INFINITY, 0.0);
let obj = model.add_constraint(ConstraintType::Free, 0.0).cons();
let c = model.add_constraint(ConstraintType::GreaterEqual, 1.0).cons();
model.add_nonlinear(obj, x); // derivative supplied by the evaluator
model.add_linear(obj, y, 1.0); // constant derivative, never evaluated
model.add_linear(c, x, 1.0);
model.add_linear(c, y, 1.0);
model.set_objective_row(obj, Sense::Minimize);
let result = Conopt::new().solve(&model, &mut Problem)?;
println!("{} / {}: {}", result.model_status, result.solver_status, result.objective);CONOPT reads the model structure once per solve, through its ReadMatrix callback (and
2DLagrStr for the Hessian). In this interface that is the Model trait: it reports
the model's size and objective and fills CONOPT's arrays, given as correctly sized slices. Every
model reaches CONOPT this way, and the interface checks what was written before CONOPT uses
it (types set, colsta consistent, rows in range, nonlinear count, no duplicates, Hessian
order), reporting problems as Error::InvalidModel.
There are three ways to supply a Model, from most to least convenient:
Pass to solve |
What it is | Suited to |
|---|---|---|
&model (a ModelBuilder) |
A builder: add variables, constraints and Jacobian entries in any order. Variables and constraints are referred to by the Var and Cons handles it returns. It is validated and compiled into a RawModel for the solve, which is dropped once CONOPT has read it; the ModelBuilder can be changed and solved again. To compile once and solve many times, call to_raw() (keeps the builder) or into_raw() (consumes it) and solve the RawModel. |
Models written by hand, as in the example above. |
&mut arrays (a RawModel) |
The arrays in CONOPT's own layout as public Vecs, filled whenever you like. Set free_after_read (default false) to release the data CONOPT copies once it has read it. |
Data that is already column-major, or code coming from the C API. |
&mut definition (your own impl Model) |
Your own ReadMatrix, writing straight into CONOPT's arrays; the interface keeps no copy. |
Translating from another representation, such as a modeling layer on top of this crate. |
solve and solve_parallel accept all three. The Hessian structure is given to CONOPT in its
own order (by column, then row). eval_hessian receives the values in that order unless the
model has a Hessian permutation (Model::hessian_permutation, the hessian_permutation field
of RawModel): then entry k of the structure is written to values[perm[k]]. A
ModelBuilder sets this up itself, so its evaluator sees the values in the order the entries
were given to set_hessian_structure.
RawModel and ModelSize are best built with ..Default::default(), as below, so the code
keeps compiling if a field is added.
The problem above as RawModel:
use conopt::{ConstraintType, Objective, RawModel, Sense};
let mut arrays = RawModel {
lower: vec![f64::NEG_INFINITY, 0.0], // x free, y >= 0
upper: vec![f64::INFINITY; 2],
initial: vec![0.0; 2],
constraint_types: vec![ConstraintType::Free, ConstraintType::GreaterEqual],
rhs: vec![0.0, 1.0], // x + y >= 1
colsta: vec![0, 2, 4], // column-major Jacobian
rowno: vec![0, 1, 0, 1],
value: vec![0.0, 1.0, 1.0, 1.0], // constant derivatives
nlflag: vec![1, 0, 0, 0], // only (row 0, x) is nonlinear
objective: Some((Objective::Row(0), Sense::Minimize)),
..Default::default()
};
// conopt.solve(&mut arrays, &mut Problem)and as a definition of its own:
use conopt::{ConstraintType, Model, ModelData, ModelSize, Objective, Sense};
struct Structure;
impl Model for Structure {
fn size(&self) -> ModelSize {
ModelSize { variables: 2, constraints: 2, nonzeros: 4, nonlinear_nonzeros: 1, ..Default::default() }
}
fn objective(&self) -> Option<(Objective, Sense)> {
Some((Objective::Row(0), Sense::Minimize))
}
fn read_matrix(&mut self, m: &mut ModelData<'_>) -> conopt::Result<()> {
m.lower[1] = 0.0; // y >= 0; untouched bounds mean "none"
m.set_constraint_type(0, ConstraintType::Free); // objective row
m.set_constraint_type(1, ConstraintType::GreaterEqual);
m.rhs[1] = 1.0; // x + y >= 1
m.colsta.copy_from_slice(&[0, 2, 4]); // column-major Jacobian
m.rowno.copy_from_slice(&[0, 1, 0, 1]);
m.nlflag.copy_from_slice(&[1, 0, 0, 0]); // only (row 0, x) is nonlinear
m.value.copy_from_slice(&[0.0, 1.0, 1.0, 1.0]); // constant derivatives
Ok(())
}
}
// conopt.solve(&mut Structure, &mut Problem)| Safe API | CONOPT |
|---|---|
ModelBuilder::add_variable / add_constraint |
LOWER, UPPER, CURR, TYPE, RHS in ReadMatrix (infinite bounds keep CONOPT's internal infinity) |
add_linear / add_nonlinear (any order) |
column-major COLSTA, ROWNO, VALUE, NLFLAG |
set_objective_row / set_objective_variable |
COIDEF_ObjCon / COIDEF_ObjVar + COIDEF_OptDir |
set_hessian_structure (any order) |
COIDEF_NumHess, 2DLagrStr; values are permuted into CONOPT's order (hessian_permutation) |
set_initial_basis |
IniStat = 2, VSTA, ESTA |
Conopt::set_fv_includes_linear / set_fv_for_all |
FVincLin / FVforAll |
Evaluator::eval_row |
FDEval (value/jacobian are Some according to MODE; RowJacobian gives JAC dense, or compact over JACNUM with entries_mut) |
Evaluator::eval_start / eval_end |
FDEvalIni / FDEvalEnd |
Evaluator::eval_hessian |
2DLagrVal |
Evaluator::has_directional_second_derivatives + eval_directional |
2DDir (eval_directional_start / _end: 2DDirIni / 2DDirEnd) |
Evaluator::progress returning false |
nonzero return from Progress (user interrupt) |
EvalError::Domain / EvalError::Fatal |
ERRCNT = 1 (or NODRV = 1) / nonzero return code |
EvalError::Unimplemented (default of eval_hessian / eval_directional) |
NODRV = 1, plus a warning |
Conopt::set_option(name, value) |
Option callback (CR-cells); thread options are refused |
Conopt::set_option_file |
COIDEF_Optfile |
Conopt::set_preprocessing_handler |
TriOrd |
Conopt::solve_parallel + ParallelEvaluator |
FDEval / 2DDir called from several threads (ThreadF, Thread2D) |
As with the C API, the function value of a row covers only its nonlinear terms by default, and constant terms belong in the right-hand side.
- Every
solvecreates and frees its own control vector, so oneConoptcan solve many models and no state leaks between solves. solvetakes anEvaluatorwith&mut selfmethods and keeps evaluation single-threaded:set_threadssetsThreadSfor CONOPT's internal work, butThreadFandThread2Dare always 1, and CONOPT calls the evaluator from the thread that calledsolve. For that reasonset_optionrefuses any option whose name contains "thread"; an option file passed toset_option_filemust not set the evaluation thread counts either.solve_paralleltakes aParallelEvaluator(&selfmethods,Sync) and lets CONOPT evaluate rows and directional second derivatives on several threads; each call gets its thread index. To solve independent models at the same time, give each thread its ownConoptinstead.- A panic inside an evaluator stops CONOPT (nonzero return code) and resumes once
COI_Solvereturns. solvereturnsOkwhenever CONOPT reported a status, including infeasible or interrupted solves. Checkmodel_status/solver_status.Erris reserved for invalid models, rejected settings, setup failures and an incompatible CONOPT library.- Every solve first checks the CONOPT library found at run time (
conopt::version()) against the header the interface was built from (conopt::header_version(), 4.39.3). The library must have the same major version and be at least as new; otherwisesolvereturnsError::IncompatibleLibrarywithout calling CONOPT. - Messages go to stdout (screen stream) and error messages to stderr by default; use
quiet(),set_message_handlerorset_error_handlerto redirect them. Error messages are always collected inSolveResult::error_messages. - The interface warns, once per solve, when a model declares a Hessian structure but the
evaluator does not implement
eval_hessian, or asks for directional second derivatives without implementingeval_directional. Warnings go to the screen and documentation streams and are collected inSolveResult::warnings. ModelBuildermethods that declare structure (add_linear,set_objective_row, ...) are checked when the model is compiled, so entries can refer to variables added later; methods that change an existing entry (set_bounds,set_initial_value,set_rhs) panic if it does not exist.- The status enums,
Error,EvalErrorand the result types are#[non_exhaustive], so a later version can add variants and fields. A status code without a name arrives asOther(code); compare with.code()when a specific code matters, since a later version may name it.
Not wrapped in the safe API (use conopt::ffi): FDInterval, 2DDirLagr and 2DLagrSize.
The examples are Rust ports of the C examples of the CONOPT distribution (examples/C_1thread
and examples/C_OpenMP), each in two versions:
conopt/examples/builder/<name>.rs, example<name>: the model is built withModelBuilder;conopt/examples/direct/<name>.rs, example<name>_direct: the model is written throughModel, following the CReadMatrixcode closely.
Each one checks its result the way the C program does and prints <name>: Successful Solve.;
they run as part of cargo test, and one runs with e.g. cargo run -p conopt --example tutorial. Without a license, the examples that exceed the demo limits report themselves as
skipped.