HexalyOCaml bindings for the Hexaly Optimizer (formerly LocalSolver).
Hexaly is a commercial mathematical optimization solver supporting mixed-integer programming, constraint programming, and the specialized decision variables (interval, list, set) that distinguish it from classical MIP solvers.
let opt = Hexaly.create () in
Hexaly.set_verbosity (Hexaly.param opt) 0;
let m = Hexaly.model opt in
let xs = Array.init n (fun _ -> Hexaly.bool_var m) in
let value = Hexaly.sum m (Array.to_list (Array.mapi
(fun i x -> Hexaly.mul m (Hexaly.int_const m values.(i)) x) xs))
in
Hexaly.maximize m value;
Hexaly.close m;
Hexaly.solve opt;
assert (Hexaly.status (Hexaly.solution opt) = Hexaly.Status.Optimal)The user-facing types (model, param, solution, expr, Inconsistency.t, callback) are records that hold their parent. Holding any descendant keeps the optimizer alive; once nothing refers to the optimizer or its descendants, the GC frees all of them. This costs one word per handle and rules out using a handle after its optimizer is freed.
solve releases the OCaml runtime lock for its duration, so other OCaml threads can run and so callbacks invoked from Hexaly worker threads can safely re-enter OCaml. Every other Hexaly call is short and holds the lock.
module Error : sig ... endexception Hexaly_error of Error.code * stringEvery Hexaly call site can raise Hexaly_error (code, msg).
module State : sig ... endmodule Status : sig ... endmodule Callback_type : sig ... endmodule Op : sig ... endOperator tags mirroring HxOperator. Used by create_expression for operators without a named helper.
module Version : sig ... endWhich backend this build links. Mock is a brute-force test double bundled for CI and contributors without a license; its solve only handles tiny models and is not the Hexaly solver.
val backend : unit -> backendThe backend chosen at build time. On Mock, create prints a one-time warning to stderr unless the environment variable HEXALY_BACKEND is set to mock.
val create : unit -> optimizerAcquire a license token and create a fresh optimizer.
val solve : optimizer -> unitRun the solver. Blocks the calling OCaml thread; releases the runtime lock so other OCaml threads can run.
val stop : optimizer -> unitval running_time : optimizer -> intval nb_iterations : optimizer -> int64val save_environment : optimizer -> string -> unitSave the model as a Hexaly Modeler script. The destination file's suffix selects the format: .hxm (Hexaly Modeler, recommended) or .lsp (legacy LocalSolver script). The result is loadable by the hexaly CLI and HexalyModeler.
Note: as of Hexaly 14.5, the saved file is NOT a complete environment snapshot: solver state and best solution are not round-tripped through load_environment. For sharing/debugging models, this is the canonical export path.
val load_environment : optimizer -> string -> unitLoad a Hexaly snapshot file produced by Hexaly Studio or a future version of save_environment. As of Hexaly 14.5 the formats accepted here are NOT the same as those produced by save_environment; do not assume round-trip.
Hexaly supports lexicographic multi-objective optimization. The pattern:
Hexaly.minimize m cost; (* objective 0 *)
Hexaly.minimize m makespan; (* objective 1 *)
Hexaly.close m;
let p0 = Hexaly.Phase.create opt in
Hexaly.Phase.set_optimized_objective p0 0;
Hexaly.Phase.set_time_limit p0 30;
let p1 = Hexaly.Phase.create opt in
Hexaly.Phase.set_optimized_objective p1 1;
Hexaly.Phase.set_time_limit p1 30;
Hexaly.solve optHexaly runs the phases in order: it optimizes objective 0 to convergence (or its time/iteration limit), then optimizes objective 1 while constraining objective 0 to its best value.
module Phase : sig ... endmodule Inconsistency : sig ... endval compute_inconsistency : optimizer -> Inconsistency.tRun Hexaly's inconsistency analysis to identify a minimal set of constraints whose conflict makes the model infeasible. Only meaningful after a solve that reported Infeasible or Inconsistent.
Opaque handle to a registered callback. The callback keeps firing until remove_callback is called or its optimizer is collected, whether or not you keep this handle. A closure that captures its optimizer does not keep that optimizer alive.
val add_callback : optimizer -> Callback_type.t -> (unit -> unit) -> callbackRegister an OCaml closure to be invoked on every event of the given type during solve. The closure receives unit; capture the optimizer in its closure if you need to inspect state.
Exceptions raised by the closure are caught and printed to stderr, because they cannot propagate through Hexaly's C++ code. To stop the solve from a callback, call stop.
Example: print progress every 5 seconds during a long solve.
let start = Unix.gettimeofday () in
let last = ref start in
let _cb = Hexaly.add_callback opt Hexaly.Callback_type.Time_ticked
(fun () ->
let now = Unix.gettimeofday () in
if now -. !last >= 5.0 then begin
Printf.printf "[%.0fs] iter=%Ld\n%!"
(now -. start) (Hexaly.nb_iterations opt);
last := now
end)
in
Hexaly.solve optval remove_callback : callback -> boolRemove a previously registered callback. Returns true if it was found and removed. Safe to call multiple times. Do not call it from inside a callback.
interval_var m min_start max_end creates a half-open interval decision: start ≥ min_start, end ≤ max_end. Read via interval_value.
Like interval_var but the interval can be absent (length 0).
list_var m n creates a list decision: an ordered sequence of distinct values from \{0, ..., n-1\}. The list may be partial; add count l = n to force a permutation. Read via collection_value.
set_var m n creates a subset decision over \{0, ..., n-1\}. Read via collection_value.
val close : model -> unitval is_closed : model -> boolval nb_expressions : model -> intInspection
val nb_constraints : model -> intval nb_objectives : model -> intval nb_decisions : model -> intRead an interval decision as (start, end). End is exclusive (count = end - start).
Read a list-var or set-var as an array of element indices in 0..n-1.
is_violated sol expr returns true if expr is a violated constraint in this solution.
is_undefined sol expr returns true if expr has no defined value in this solution (e.g. an optional interval that was absent).
Set an initial value for a decision before solve. Hexaly will use it as a starting point.
set_interval_value sol expr ~start ~end_ hints an interval's (start, end) for the next solve.
val clear_solution : solution -> unitDiscard all warm-start hints.
val set_time_limit : param -> int -> unitval set_iteration_limit : param -> int64 -> unitval set_seed : param -> int -> unitval set_nb_threads : param -> int -> unitval set_verbosity : param -> int -> unitval set_warning_level : param -> int -> unitHexaly warning level (0..3). Higher = more output.
val set_time_between_displays : param -> int -> unitSeconds between progress-line displays in the console log.
val set_time_between_ticks : param -> int -> unitSeconds between Time_ticked callback firings.
val set_iteration_between_ticks : param -> int64 -> unitIterations between Iteration_ticked callback firings.
val set_log_file : param -> string -> unitMirror Hexaly's solver log to a file. Empty string disables.
val set_int_objective_threshold : param -> int -> int -> unitSet an objective-specific integer threshold: solver stops when this objective reaches the threshold. Index is the objective's position in declaration order.
val set_double_objective_threshold : param -> int -> float -> unitval set_advanced_int : param -> string -> int -> unitAdvanced parameters
Hexaly exposes many tuning knobs by attribute name (see the Hexaly documentation for the catalog). Unknown keys are silently ignored.
val set_advanced_double : param -> string -> float -> unitval set_advanced_string : param -> string -> string -> unitmodule Syntax : sig ... end