Module Hexaly

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

Quick start

  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)

Lifetimes and the GC

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.

Threading

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.

Types

type optimizer
type model
type expr
type solution
type param

Errors

module Error : sig ... end
exception Hexaly_error of Error.code * string

Every Hexaly call site can raise Hexaly_error (code, msg).

Solver state, solution status, callback types

module State : sig ... end
module Status : sig ... end
module Callback_type : sig ... end
module Op : sig ... end

Operator tags mirroring HxOperator. Used by create_expression for operators without a named helper.

Hexaly version and license configuration

module Version : sig ... end

Backend

type backend =
  1. | Real
  2. | Mock

Which 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 -> backend

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

Lifecycle

val create : unit -> optimizer

Acquire a license token and create a fresh optimizer.

val model : optimizer -> model
val param : optimizer -> param
val solution : optimizer -> solution
val solve : optimizer -> unit

Run the solver. Blocks the calling OCaml thread; releases the runtime lock so other OCaml threads can run.

val stop : optimizer -> unit

Introspection

val state : optimizer -> State.t
val running_time : optimizer -> int
val nb_iterations : optimizer -> int64

Environment save/load

val save_environment : optimizer -> string -> unit

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

  • raises Hexaly_error

    if the file cannot be written or the suffix is unrecognized.

val load_environment : optimizer -> string -> unit

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

Multi-objective phases

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 opt

Hexaly 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 ... end

Inconsistency analysis (IIS)

module Inconsistency : sig ... end
val compute_inconsistency : optimizer -> Inconsistency.t

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

Callbacks

type callback

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

Register 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 opt
val remove_callback : callback -> bool

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

Decision variables

val bool_var : model -> expr
val int_var : model -> int -> int -> expr
val float_var : model -> float -> float -> expr
val interval_var : model -> int -> int -> expr

interval_var m min_start max_end creates a half-open interval decision: start ≥ min_start, end ≤ max_end. Read via interval_value.

val optional_interval_var : model -> int -> int -> expr

Like interval_var but the interval can be absent (length 0).

val list_var : model -> int -> expr

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.

val set_var : model -> int -> expr

set_var m n creates a subset decision over \{0, ..., n-1\}. Read via collection_value.

Constants

val int_const : model -> int -> expr
val float_const : model -> float -> expr
val int_array_const : model -> int array -> expr
val float_array_const : model -> float array -> expr

Generic expression builder

val create_expression : model -> Op.t -> ?operands:expr array -> ?ints:int array -> ?floats:float array -> unit -> expr
val sum : model -> expr list -> expr

Arithmetic

val prod : model -> expr list -> expr
val add : model -> expr -> expr -> expr
val sub : model -> expr -> expr -> expr
val mul : model -> expr -> expr -> expr
val div : model -> expr -> expr -> expr
val neg : model -> expr -> expr
val abs : model -> expr -> expr
val dist : model -> expr -> expr -> expr
val mod_ : model -> expr -> expr -> expr
val max : model -> expr list -> expr
val min : model -> expr list -> expr
val sqrt : model -> expr -> expr

Math functions

val log : model -> expr -> expr
val exp : model -> expr -> expr
val pow : model -> expr -> expr -> expr
val cos : model -> expr -> expr
val sin : model -> expr -> expr
val tan : model -> expr -> expr
val ceil : model -> expr -> expr
val floor : model -> expr -> expr
val round : model -> expr -> expr
val eq : model -> expr -> expr -> expr

Comparison (returns boolean expression)

val neq : model -> expr -> expr -> expr
val lt : model -> expr -> expr -> expr
val leq : model -> expr -> expr -> expr
val gt : model -> expr -> expr -> expr
val geq : model -> expr -> expr -> expr
val and_ : model -> expr list -> expr

Logical

val or_ : model -> expr list -> expr
val xor_ : model -> expr list -> expr
val not_ : model -> expr -> expr
val if_ : model -> expr -> expr -> expr -> expr
val array : model -> expr list -> expr

Array / collection operators

val at : model -> expr -> expr list -> expr
val scalar : model -> expr -> expr -> expr
val count : model -> expr -> expr
val index_of : model -> expr -> expr -> expr
val contains : model -> expr -> expr -> expr
val partition : model -> expr list -> expr
val disjoint : model -> expr list -> expr
val distinct : model -> expr -> expr
val find : model -> expr -> expr -> expr
val sort : model -> expr -> expr
val intersection : model -> expr list -> expr
val union_ : model -> expr list -> expr
val hull : model -> expr list -> expr
val start : model -> expr -> expr

Interval operators

val end_ : model -> expr -> expr
val length : model -> expr -> expr
val presence : model -> expr -> expr
val add_constraint : model -> expr -> unit

Constraints, objectives, model state

val minimize : model -> expr -> unit
val maximize : model -> expr -> unit
val close : model -> unit
val is_closed : model -> bool
val nb_expressions : model -> int

Inspection

val nb_constraints : model -> int
val nb_objectives : model -> int
val nb_decisions : model -> int

Solution access

val int_value : solution -> expr -> int
val float_value : solution -> expr -> float
val interval_value : solution -> expr -> int * int

Read an interval decision as (start, end). End is exclusive (count = end - start).

val collection_value : solution -> expr -> int array

Read a list-var or set-var as an array of element indices in 0..n-1.

val is_violated : solution -> expr -> bool

is_violated sol expr returns true if expr is a violated constraint in this solution.

val is_undefined : solution -> expr -> bool

is_undefined sol expr returns true if expr has no defined value in this solution (e.g. an optional interval that was absent).

val status : solution -> Status.t

Warm start (initial solution)

val set_int_value : solution -> expr -> int -> unit

Set an initial value for a decision before solve. Hexaly will use it as a starting point.

val set_float_value : solution -> expr -> float -> unit
val set_interval_value : solution -> expr -> start:int -> end_:int -> unit

set_interval_value sol expr ~start ~end_ hints an interval's (start, end) for the next solve.

val clear_solution : solution -> unit

Discard all warm-start hints.

Solver parameters

val set_time_limit : param -> int -> unit
val set_iteration_limit : param -> int64 -> unit
val set_seed : param -> int -> unit
val set_nb_threads : param -> int -> unit
val set_verbosity : param -> int -> unit
val set_warning_level : param -> int -> unit

Hexaly warning level (0..3). Higher = more output.

val set_time_between_displays : param -> int -> unit

Seconds between progress-line displays in the console log.

val set_time_between_ticks : param -> int -> unit

Seconds between Time_ticked callback firings.

val set_iteration_between_ticks : param -> int64 -> unit

Iterations between Iteration_ticked callback firings.

val set_log_file : param -> string -> unit

Mirror Hexaly's solver log to a file. Empty string disables.

val set_int_objective_threshold : param -> int -> int -> unit

Set 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 -> unit
val set_advanced_int : param -> string -> int -> unit

Advanced 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 -> unit
val set_advanced_string : param -> string -> string -> unit

Operator syntax sugar

module Syntax : sig ... end