C++ reference

The supported part of the C++ library, in namespace cbls: what <cbls/cbls.h> brings in, plus <cbls/io_nl.h> for AMPL .nl models. This page has the main entry point of each concept and links the headers that declare the rest. What else <cbls/cbls.h> brings in (the DAG, the violation manager, the moves) is documented in its headers. Headers outside that set, such as structural_batch.h and arg_parse.h, serve this repository’s runners and tests.

Using it from CMake

Build it inside your project and link the target cbls::cbls, which brings the headers and C++17:

cmake_minimum_required(VERSION 3.15)
project(app LANGUAGES CXX)

if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release)  # else cbls compiles unoptimised
endif()

include(FetchContent)
FetchContent_Declare(cbls
    GIT_REPOSITORY https://github.com/spoorendonk/cbls.git
    GIT_TAG        main)  # or a commit, to pin it
FetchContent_MakeAvailable(cbls)

add_executable(app main.cpp)
target_link_libraries(app PRIVATE cbls::cbls)
  • From an install (cmake --install build): find_package(cbls 0.1 CONFIG REQUIRED) replaces the FetchContent lines.

  • Clone or submodule in your source tree: add_subdirectory(cbls) replaces them.

  • Needs zlib, found with find_package(ZLIB); the first configure fetches nlohmann/json’s headers.

  • Versions: the library is static and 0.x, with no source or ABI compatibility between releases.

Model

Model builds variables, expressions and constraints. model.h also declares ListPartition and Cover, for Lists that partition a ground set.

class Model

Public Functions

Model()
Model(const Model &other)

Copies the per-model state (variables, node values) and either SHARES the structure (a FROZEN model; the copy is frozen too, so it cannot change what its peers read) or deep-copies it (an OPEN model, so the copy can be built further independently). The delta probe’s scratch is not copied: it is overwritten before every read.

The copy constructor enumerates every member explicitly: a member added and forgotten there is default-initialised in every portfolio replica while the master looks right, which shows only as a trajectory divergence.

Model &operator=(const Model &other)
Model(Model&&) noexcept = default

A moved-from Model may only be destroyed or assigned to: it holds no structure, so every accessor that reads the structure is undefined on it (s() asserts, so a Debug or sanitizer build names it). is_frozen() reports TRUE for one, so if (!m.is_frozen()) m.freeze(); silently does nothing.

Model &operator=(Model&&) noexcept = default
~Model() = default
int32_t bool_var(const std::string &name = "")
int32_t int_var(int lb, int ub, const std::string &name = "")
int32_t float_var(double lb, double ub, const std::string &name = "")
int32_t list_var(int n, const std::string &name = "")

A fixed-length permutation of {0..n-1}: universe == min_len == max_len and elements == [0..n-1]: exactly list_var(n, n, n, ListInit::Identity, name) (#164).

int32_t list_var(int universe, int min_len, int max_len, ListInit init = ListInit::Empty, const std::string &name = "")

An ordered sequence of DISTINCT elements drawn from {0..universe-1}, whose length stays within [min_len, max_len] (#164).

Throws std::invalid_argument unless 0 <= min_len <= max_len <= universe, and, for ListInit::Identity, unless min_len == max_len == universe.

int32_t set_var(int n, int min_size = 0, int max_size = -1, const std::string &name = "")
int32_t constant(double val)
int32_t neg(int32_t x)
int32_t sum(const std::vector<int32_t> &args)
int32_t prod(int32_t a, int32_t b)
int32_t div_expr(int32_t a, int32_t b)
int32_t pow_expr(int32_t base, int32_t exp)
int32_t min_expr(const std::vector<int32_t> &args)
int32_t max_expr(const std::vector<int32_t> &args)
int32_t abs_expr(int32_t x)
int32_t sin_expr(int32_t x)
int32_t cos_expr(int32_t x)
int32_t tan_expr(int32_t x)
int32_t exp_expr(int32_t x)
int32_t log_expr(int32_t x)
int32_t sqrt_expr(int32_t x)
int32_t signpower_expr(int32_t base, int32_t exp)
int32_t tanh_expr(int32_t x)
int32_t if_then_else(int32_t cond, int32_t then_, int32_t else_)
int32_t at(int32_t list_var_id, int32_t index_expr)
int32_t count(int32_t var_id)
int32_t leq(int32_t a, int32_t b)
int32_t eq_expr(int32_t a, int32_t b)
int32_t geq(int32_t a, int32_t b)
int32_t neq(int32_t a, int32_t b)
int32_t lt(int32_t a, int32_t b)

Strict a < b / a > b. The row’s residual is a - b + margin, with the margin fixed here and stored on the node (see kIntegralStrictMargin in dag.h): 1 when both sides are integral (is_integral), so x < y over integers is exactly x <= y - 1; the tiny kStrictComparisonEps otherwise.

int32_t gt(int32_t a, int32_t b)
bool is_integral(int32_t handle) const

Whether the expression handle

(a variable or node handle) takes only integer values at every integral assignment of its variables: a Bool or Int variable, an integer constant, a Ceil/Floor/Round, a Count or a Neq, and Neg/Sum/Prod/Min/Max/Abs over integral children, an If over integral branches, a Pow of an integral base to a non-negative integer constant. Conservative: anything else – every Float, every other op – is “not

known integral”, which is the safe reading for both callers (the strict margin, and the objective-bound step in

solve()).

int32_t lambda_sum(int32_t list_var_id, std::function<double(int)> func)
int32_t pair_lambda_sum(int32_t list_var_id, std::function<double(int, int)> func, PairMode mode = PairMode::Open)

Sum func over the consecutive pairs of a List (or Set) variable’s elements, optionally closing the chain and optionally charging the first and last element against a fixed endpoint.

With e the variable’s elements and n == e.size():

head(e_0) + sum_{k < n-1} func(e_k, e_{k+1}) + tail(e_{n-1})
           + [mode == Cyclic && n >= 2] func(e_{n-1}, e_0)

The short cases are DEFINED, not edge cases – a List whose length varies makes them routine:

  • n == 0: 0.0 for every variant, head and tail included. An unused route costs nothing.

  • n == 1: head(e_0) + tail(e_0). There is no pair, and Cyclic adds nothing: a single element is not a pair with itself.

  • n == 2: head(e_0) + func(e_0, e_1) + tail(e_1), and Cyclic adds func(e_1, e_0) – the two-city tour traverses its one edge twice, which is the convention a distance matrix that need not be symmetric requires.

Cyclic is the tour cost of a TSP over one List. head/tail are the depot legs of a CVRP route, where a cyclic sum over the customers alone would wrongly add func(e_{n-1}, e_0). The two are independent, so a cyclic sum with endpoint terms is expressible too.

A Set variable is accepted, but its elements carry no modelled order: the sum then reads whatever order they happen to be stored in, which the search moves arbitrarily. Consecutive pairs are a meaningful cost on a List.

func, head and tail are invoked by EVERY portfolio worker concurrently once the model is frozen – see freeze().

int32_t pair_lambda_sum(int32_t list_var_id, std::function<double(int, int)> func, std::function<double(int)> head, std::function<double(int)> tail, PairMode mode = PairMode::Open)

The fixed-endpoint form. Either callable may be empty, meaning “no term”; passing both empty is the plain mode overload.

int32_t element(const std::vector<double> &table, int32_t index)

table[index]: a numeric table looked up by a decision (#186), e.g. a cost by vehicle type where the type is an Int variable.

The index may be any scalar expression; its value is truncated toward zero, which is how at() reads its index. An index outside [0, table.size()) – or a non-finite one – reads 0.0, which is also at()’s rule for a position past the List. A model that must never read outside the table bounds its index variable to [0, n-1].

The table is COPIED into the model. It is ordinary data, so the node is serialisable (.cbls writes the table). Local derivative 0 for the index; FJ offers index values as the index variable’s jump candidates instead (see compute_var_jump).

Throws std::invalid_argument on an empty table, a non-finite entry or a List/Set index, and std::out_of_range on a handle naming nothing.

int32_t element(const std::vector<std::vector<double>> &table, int32_t row, int32_t col)

table[row][col], with both indices read as in the one-index form and 0.0 when EITHER is out of range. table must be rectangular and non-empty in both dimensions.

int32_t ceil_expr(int32_t x)

std::ceil, std::floor and std::round of x (#186). round takes a half-way value AWAY from zero (round(2.5) == 3, round(-2.5) == -3), which is std::round’s rule. No tolerance is applied: ceil of a quotient that lands one ulp above an integer is the next integer, as in plain C++. Each is exact on non-finite input (ceil(inf) == inf, NaN stays NaN).

Local derivative 0, so a Newton step sees nothing through them. FJ offers the plateau edges instead (see compute_var_jump). Throws std::invalid_argument on a List/Set argument.

int32_t floor_expr(int32_t x)
int32_t round_expr(int32_t x)
int32_t lambda_sum(int32_t list_var_id, LambdaExtraFunc func, const std::vector<int32_t> &extra)

lambda_sum whose functor also reads other decisions (#186):

sum_{e in list} func(e, [value(extra_0), value(extra_1), ...])

e.g. a stop cost that depends on the route’s vehicle type, sum_{i in route} c[i][type_r], as func = (i, x) -> c[i][int(x[0])].

extra are scalar handles – variables or nodes, any number, in the order func receives them. They become children of the node, so a change to one re-evaluates it; so does any edit to the list. Both re-sum the list, which is what a plain lambda_sum does on an edit.

Not serialisable: func is a function of continuous values and cannot be tabulated the way a plain lambda_sum is, so save_model refuses a model holding one, before it writes anything. Shared by every portfolio worker, on the terms freeze() states.

Throws std::invalid_argument unless list_var_id names a List or Set variable, func is non-empty and no extra handle names a List or Set variable; std::out_of_range on a handle naming nothing.

int32_t pair_lambda_sum(int32_t list_var_id, PairLambdaExtraFunc func, PairMode mode, const std::vector<int32_t> &extra)

pair_lambda_sum(list, f, mode) with f also reading extra, on the terms lambda_sum’s extra form states. The pair and mode contract is the plain form’s; there is no head/tail term in this form.

void add_constraint(int32_t expr_id)
void minimize(int32_t expr_id)
void maximize(int32_t expr_id)
Expr Bool(const std::string &name = "")
Expr Int(int lb, int ub, const std::string &name = "")
Expr Float(double lb, double ub, const std::string &name = "")
Expr List(int n, const std::string &name = "")
Expr List(int universe, int min_len, int max_len, ListInit init = ListInit::Empty, const std::string &name = "")
Expr Set(int n, int min_size = 0, int max_size = -1, const std::string &name = "")
Expr Constant(double val)
void add_constraint(const Expr &e)
void minimize(const Expr &e)
void maximize(const Expr &e)
void add_var_sequence(const std::vector<int32_t> &var_ids, int min_block_on = 1, int min_block_off = 1)
inline const std::vector<VarSequence> &var_sequences() const noexcept
std::pair<int, int> var_sequence_for(int32_t var_id) const
int32_t add_list_partition(const std::vector<int32_t> &lists, Cover cover = Cover::Exact)

Declare that lists (List variable handles) partition their shared universe, and return the new partition’s index (#164).

Maintained structurally, not by a constraint row – see ListPartition for why, and for why there is no unassigned() view. Throws std::invalid_argument unless every handle names a distinct List variable, all of them share one universe_size, none is already in a partition, sum(min_len) <= universe, and, for Cover::Exact, sum(max_len) >= universe.

ListInit::Identity is rejected in a partition of more than one list: it would put every element in every member.

Under Cover::Exact the members’ ListInit is ignored, because the invariant has to hold at the FIRST assignment – no move can repair a partition that starts incomplete, since Exact admits no insert or remove that is not half of an inter-list move. Initialisation therefore always lays an Exact partition out as a random COMPLETE one. Under Cover::AtMostOnce there is no such obligation and each member’s ListInit decides how much beyond its minimum it is given.

inline const std::vector<ListPartition> &list_partitions() const noexcept
int partition_of_list(int32_t var_id) const

The index into list_partitions() of the partition var_id belongs to, or -1. Same lookup-table shape as var_sequence_for.

void close()
void freeze(size_t cone_cache_bytes = kDefaultConeCacheBytes)

Make the structure immutable, so that copies of this model SHARE it instead of deep-copying the DAG per portfolio worker (#157). close()s the model if it is still open, folds the objective into the constraint set if there is one, then drops the writable handle on the structure. Idempotent. The builders refuse a closed model (#173), so the structure it freezes is complete.

The freeze point is AFTER the objective row, not at close(): that row rebuilds the back-references, the topological order, topo_pos and G_v, which N workers must not redo on one shared DAG. solve() freezes whatever model it is handed (#271), so a solved model comes back frozen and its later copies share its callables (below) whether or not the caller ever called freeze().

Every structural method throws afterwards: variable and expression creation, add_constraint, minimize/maximize, add_var_sequence, reserve and close. Not copy-on-write: a silent detach would put that worker back on its own full copy, every test green, the memory saving gone.

add_objective_soft_constraint is the one intentional exception: on a frozen model it RETURNS, it does not throw, because freeze() has already run it and a caller may still call it on a frozen replica. So its idempotent early return comes before the frozen check, and the require_open after it is an unreachable backstop. Do not “fix” the order; tests/test_model_share.cpp pins it.

A frozen model can still do everything a search does: assign variables, evaluate, snapshot and restore state, tighten and release the objective bound. For its copies:

  • a copy starts from THIS model’s node values, verbatim, so it is already consistent with its variables and needs no full_evaluate;

  • the lambda_sum/pair_lambda_sum callables are shared, so several workers invoke the same callable object at once: one that carries mutable state of its own is a data race, whether that state is captured by value or by reference.

It also caches every variable’s dirty cone in topological order (#271), so a one-variable walk neither collects nor sorts it: up to cone_cache_bytes of node ids, shared by every replica like the rest of the structure. Variables are cached in id order up to the first whose cone would cross the cap; it and every later one walk as an unfrozen model’s do. 0 caches nothing. The FIRST call’s cap holds; a later call is the no-op above. solve() freezes with SearchConfig::cone_cache_bytes.

inline bool is_frozen() const noexcept
inline bool has_cached_cone(int32_t var_id) const noexcept

Whether freeze() cached var_id’s cone; false on an unfrozen model and for any id outside the cached prefix, a negative one included.

inline ConstSpan<int32_t> cached_cone(int32_t var_id) const noexcept

var_id’s cached cone: every node above it, each once, in topological order. Only where has_cached_cone(var_id).

inline size_t num_cached_cones() const noexcept

The cone cache’s size: variables cached, and bytes of node ids held.

inline size_t cone_cache_bytes() const noexcept
void add_objective_soft_constraint()
inline bool has_objective_constraint() const noexcept
inline int32_t objective_constraint_idx() const noexcept
void set_objective_bound(double bound)
inline double objective_bound() const noexcept
inline int32_t objective_bound_node() const noexcept

The Const node carrying the objective row’s RHS, or -1 when there is no objective row. evaluate() compares against this to know which Const to read objective_bound() for instead of const_value.

inline ConstSpan<int32_t> constraints_of_var(int32_t var_id) const
inline uint32_t constraints_of_var_offset(int32_t var_id) const
inline size_t num_var_constraint_incidences() const
std::vector<std::pair<int32_t, double>> per_constraint_violation_delta(int32_t var_id, double j)
double weighted_violation_delta(int32_t var_id, double j, const std::vector<double> &weights)
double weighted_violation_delta(int32_t var_id, double j, const std::vector<double> &weights, const std::vector<double> &second, double &second_delta)
inline const Variable &var(int32_t id) const
inline Variable &var_mut(int32_t id)
inline const ExprNode &node(int32_t id) const
inline double node_value(int32_t id) const

Node id’s current value: the evaluation cache, which is per-model mutable state and therefore NOT part of the shared structure (#157). Range-checked, like node().

inline void set_node_value_unchecked(int32_t id, double value) noexcept

Write node id’s value WITHOUT a range check: the evaluation loops’ write, paired with the unchecked reads node_values() hands out. Their ids come from topo_order(), so a check could only pass, yet would run once per node per full_evaluate (4.3M per call on the largest MIPfeas instance). NOT bound to Python: an index from there would be an unguarded heap write (#156). node_value is the checked reader.

inline IncSums &inc_sums() noexcept

The incremental Sums’ per-model state (#188): see IncSums. Sized and reset by every full_evaluate; empty before the first. Not bound to Python (#156): the walks index it by slot unchecked.

inline const IncSums &inc_sums() const noexcept
inline ProbeUndo &probe_undo() noexcept

The pending probe’s undo log (#270): see ProbeUndo. Not bound to Python (#156): the rollback writes its node ids unchecked.

inline const std::vector<int32_t> &inc_sum_nodes() const noexcept

Slot -> node id of every incremental Sum; see ModelStructure.

inline ConstSpan<ChildRef> children(const ExprNode &node) const noexcept

node’s children, in the order they were given when it was created. Valid from creation, not only after close(): a node’s children are written once, when it is made, and never change.

node must be one of THIS model’s nodes (from node() or nodes()), unmodified in child_begin/child_count. Its offsets are read against this model’s array unchecked – this is the evaluation hot path – so a node taken from a different Model reads whatever that range holds in this one.

inline ConstSpan<int32_t> parents(int32_t id) const

The distinct nodes that name node id as a child, in ascending id order, each listed once however many times it names id (prod(n, n)). Rebuilt by close() and add_objective_soft_constraint(). Empty for every node before close(); the builders cannot add one after it (#173).

inline ConstSpan<int32_t> dependents(int32_t var_id) const

The distinct nodes that name variable var_id as a child, with the same order, dedup and rebuild contract as parents.

inline int32_t objective_id() const noexcept
inline bool is_maximizing() const noexcept
inline const std::vector<int32_t> &constraint_ids() const noexcept

Every row the engine scores: the modeller’s, then the implicit domain rows close() appends (#248), then the objective row. What the search, the weights, verify_model and the feasibility test index.

inline size_t num_user_constraints() const noexcept

How many of constraint_ids() the modeller added: they are its first entries. Every row before close().

inline int32_t num_domain_rows() const noexcept

How many implicit domain rows close() appended after the modeller’s (#248): arg >= kLogDomainFloor under a Log or a Pow with a constant negative non-integer exponent, arg >= 0 under a Sqrt or a Pow with a constant positive non-integer one. A row reads its plain Geq residual (<= 0) when the argument meets its floor, and that residual plus domain_margin() when it does not (#258). 0 before close().

inline bool is_domain_node(int32_t id) const noexcept

Whether node id is one close() made for a domain row: what save_model leaves out, since a reload’s close() makes them again.

bool set_domain_tolerance(double tol)

The step a violated domain row adds to its residual: the smallest double above the feasibility tolerance last set, so that an argument below its floor reads violated at that tolerance however little it misses by (a miss smaller than the margin’s ulp rounds away in the sum, which then is the margin itself, still above the tolerance). An argument at or above the floor adds nothing.

Per-model state, as objective_bound() is: each portfolio worker solves at its own SearchConfig::feasibility_tolerance, and solve() sets it. Re-evaluates the domain rows and returns true when the margin changed; the caller then invalidates any violation cache on the model. The margin stays until the next call: solve() and each FeasibilityJump set it from their own tolerance. Allowed on a frozen model.

inline double domain_margin() const noexcept
inline void reserve(size_t n_vars, size_t n_nodes, size_t n_child_refs = 0)

Size the variable, node and child-reference arrays up front, when the caller already knows how big the model will be. n_child_refs is the total number of children over all nodes, i.e. the DAG’s edge count.

On a large model this is what stops a multi-gigabyte array being copied to grow it: a reader appending a node per matrix entry grows the node and child arrays by doubling, each doubling copying everything so far. Over-reserving costs address space and nothing else, so an estimate that is merely close is worth making.

inline const std::vector<int32_t> &topo_order() const noexcept
inline int32_t topo_position(int32_t id) const noexcept

Where id sits in topo_order(), so a caller holding a handful of nodes can put them in evaluation order without walking the whole order to find them: delta_evaluate’s dirty set is typically a few dozen nodes, where a scan of topo_order() is O(all nodes) per call.

inline const std::vector<Variable> &variables() const noexcept
inline const std::vector<ExprNode> &nodes() const noexcept
inline const std::vector<double> &node_values() const noexcept

Every node’s current value, indexed by node id and always num_nodes() long. Unchecked indexing, like nodes(); node_value(id) is the checked reader. See set_node_value_unchecked for why the writer is unchecked.

inline size_t num_vars() const noexcept
inline size_t num_nodes() const noexcept
inline bool is_closed() const noexcept
inline const std::function<double(int)> &lambda_func(int32_t idx) const
inline const std::function<double(int, int)> &pair_lambda_func(int32_t idx) const
inline const PairLambdaSpec &pair_lambda_spec(int32_t idx) const

The closing rule and endpoint terms of the pair lambda idx. Same index space as pair_lambda_func, and the two tables are kept the same length.

inline const LambdaExtraFunc &lambda_extra_func(int32_t idx) const
inline const PairLambdaExtraFunc &pair_lambda_extra_func(int32_t idx) const
inline PairMode pair_lambda_extra_mode(int32_t idx) const
inline const ElementTable &element_table(int32_t idx) const
inline bool has_lambda_extra_nodes() const noexcept

Whether any extra-lambda node exists: the O(1) test save_model’s refusal starts from.

inline bool has_breakpoint_nodes() const noexcept

See ModelStructure::has_breakpoint_nodes.

inline const std::vector<uint8_t> &breakpoint_flags() const noexcept

See ModelStructure::breakpoint_flags. Sized num_nodes() on a closed model; empty before close().

State copy_state() const
void restore_state(const State &state)

Writes the VARIABLES only. Every node value still describes the assignment this replaces, so a full_evaluate is MANDATORY before anything reads a node value or calls delta_evaluate. For a built-in op, skipping it merely recomputes late – except an incremental Sum (#188), which commit_scalar_move would update from its stale value. Every C++ caller pairs the two; Python does not: the binding exposes this method raw, with no sweep attached, so a Python caller must add one.

Public Static Attributes

static constexpr size_t kDefaultConeCacheBytes = size_t{256} << 20

freeze()’s default cone-cache cap: 256 MiB of node ids. A memory guard against an O(nodes x vars) cache on a deep shared chain, not a tuned value: the cache changes no trajectory, only walk cost. Measured caches are far below it (#271: atlanta-ip 3.3 MB, ucp200-168p 10.2 MB).

struct State

Public Members

std::vector<double> values
std::vector<std::vector<int32_t>> elements

Expression functions

An Expr composes with the arithmetic and comparison operators (equality and inequality are the members eq and neq), and with sin, cos, tan, exp, log, sqrt, abs, pow, min, max, if_then_else, ceil, floor, round and element (a table lookup, by one index or by row and column), declared in expr.h.

Solving

solve runs one search, under a SearchConfig, and returns a SearchResult. search.h also declares TerminationReason, WorkerFailure, and the SolveCallback that receives a SolveProgress. stop.h has StopToken and StopRef, to stop a solve from outside.

SearchResult cbls::solve(Model &model, double time_limit = 10.0, uint64_t seed = 42, InnerSolverHook *hook = nullptr, LNS *lns = nullptr, int lns_interval = 3, SolveCallback *callback = nullptr, const SearchConfig &config = {}, SearchCoordination *coord = nullptr)

time_limit <= 0 disables the wall clock: bounded by max_iterations alone and deterministic per seed; with neither budget it returns at once. coord is ParallelSearch’s cross-worker channel; null everywhere else, and then the trajectory is bit-identical to a run without it (tests/test_parallel.cpp).

Freezes model first (#271; Model::freeze), before the clock starts; the cone-cache build is O(config.cone_cache_bytes). Copies of the frozen model share its lambda_sum/pair_lambda_sum callables, so a callable with mutable state races under parallel copies.

struct SearchConfig

Public Members

bool skip_init = false
int64_t max_iterations = 0
int lns_interval = 3
int64_t batch_iterations = 1000
int perturbation_period = 100
double perturbation_probability = 0.1
double structural_batch_probability = -1.0
std::vector<std::shared_ptr<const MoveGenerator>> move_generators
bool default_structural_generators = true
StructuralSelection structural_selection = StructuralSelection::Auto
int structural_sample_size = 8
std::shared_ptr<const NeighbourList> structural_neighbours
bool use_compound_moves = true
double novelty_jump_probability = 0.5
double fpr_batch_probability = 0.0
bool fpr_dag_propagation = false
int fpr_worker = 0
bool lns_repair_fpr = false
double feasibility_tolerance = kDefaultFeasibilityTolerance
size_t cone_cache_bytes = Model::kDefaultConeCacheBytes
int64_t unproductive_iterations = 300
bool fj_objective_tie_break = true
bool diversify_workers = false
double float_start_jitter = 0.0
StopRef stop
Tracer *tracer = nullptr
SearchAuditor *auditor = nullptr
struct SearchResult

Public Members

double objective = std::numeric_limits<double>::infinity()

Objective at best_state, or +inf when there is nothing to report. +inf does not imply infeasible: a feasible point whose objective overflows is returned with feasible = true and +inf here (#100); test feasible, then std::isfinite. Minimised sense: under maximize(e) this is -e (see Model::is_maximizing); SolveProgress::objective follows suit.

bool feasible = false

Whether best_state satisfies every real constraint, whatever the objective is there.

Model::State best_state
int64_t iterations = 0

The work max_iterations is charged against: the larger of the GLS iterations FJ and Novelty batches charged (Novelty move 3, bump 1) and the outer batch count (#201). Never 0 for a run that ran a batch; counters splits batches by kind.

double time_seconds = 0.0
TerminationReason termination = TerminationReason::NoBudget

Which budget ended the run; qualifies iterations and time_seconds.

double best_violation = std::numeric_limits<double>::infinity()

Largest real-constraint violation at best_state (<= the tolerance when feasible). On an infeasible run, the closest approach found.

bool escape_probe_armed = false

Whether the Float escape probe was armed at exit (#117): a latch, not a count, so false does not mean “never armed”. ParallelSearch cannot sum or attribute a latch, so it always reads false there.

int perturbations = 0

Diversification kicks taken (both the perturbation_period and the #102 route); SolveProgress::perturbations sampled at exit. ParallelSearch sums it over workers and restarts: work done, not comparable to a single run at the same wall time.

int lns_repairs = 0

LNS destroy-repair cycles attempted; counted apart from perturbations because a repair costs up to min(2.0, remaining()) s against a perturb’s microseconds. Summed by ParallelSearch like perturbations.

int lns_repairs_accepted = 0

The subset of lns_repairs whose LNS::destroy_repair returned true (#150); never greater than lns_repairs. The built-in LNS returns true when the repaired state beat the kick origin on (real violation, objective) and was kept; an override defines its own true. A rejection still draws from the RNG, spends the budget and rolls the assignment back to kick_origin() (#158). Summed by ParallelSearch like perturbations.

double first_feasible_objective = std::numeric_limits<double>::quiet_NaN()

Objective at the first feasible point this run recorded (#149), before that batch’s inner-solver polish and any bound tightening. Observational: nothing reads it back; the cost is one clock read, latched. May be non-finite on a run that did reach feasibility (#100), so test time_to_first_feasible for “ever feasible”. 0.0 on a model with no objective. ParallelSearch reports the pair from the earliest worker and restart, with the time shifted onto the portfolio’s clock.

double time_to_first_feasible = std::numeric_limits<double>::quiet_NaN()

Seconds from solve()’s start to the first feasible point; NaN if and only if none was recorded. See first_feasible_objective.

SearchCounters counters

Where the run spent its work: batches by kind, structural acceptance, inner-solver cost, portfolio restarts (#169). Summed by ParallelSearch through SearchCounters::merge. Observational; see SearchCounters::inner_solver_seconds for the one clock read it adds.

int workers_launched = 1

Portfolio workers launched and completed (#170). A worker is completed when its last solve() attempt returned, or when it never started because a peer had solved the model or the host had cancelled. It is not when its last attempt threw (also after earlier results or a retry cut off), when its model, hook, LNS or tracer factory threw, or when the deadline passed before it started. So workers_completed + worker_failures.size() == workers_launched. workers_launched is after the executor’s cap; compare workers_completed with the threads asked for. A single solve() reports 1 and 1 (its throw propagates); ParallelSearch throws when every worker died without a result.

int workers_completed = 1
std::vector<WorkerFailure> worker_failures

One entry per worker that did not complete – it threw, or the deadline starved it – in worker order. Empty on every non-portfolio result.

Portfolio

ParallelSearch runs the search on several threads. ParallelConfig is beside it in pool.h.

class ParallelSearch

A cooperative portfolio: N workers, each searching its own Model on its own thread, sharing solutions (and the best objective) through one mutex-guarded SolutionPool, never search state. A worker submits every new incumbent at once; follows the portfolio’s best objective as its bound (#179); restarts from the pool’s better half when stalled (get_restart_point); and is restarted on the remaining clock when its solve() returns early. A pure-feasibility model’s first feasible solution stops every worker. A throwing solve() is retried up to kMaxWorkerRetries consecutive times (src/pool.cpp); the model factory is called once per worker and never retried.

Public Functions

explicit ParallelSearch(int n_threads = 0)
SearchResult solve(std::function<Model()> model_factory, double time_limit = 10.0, uint64_t seed = 42)
SearchResult solve(Model &master, double time_limit = 10.0, uint64_t seed = 42)
SearchResult solve(Model &master, double time_limit, uint64_t seed, const SearchConfig &config, std::function<std::shared_ptr<InnerSolverHook>(Model&)> hook_factory, std::function<std::shared_ptr<LNS>()> lns_factory, SolveCallback *callback, const ParallelConfig &par_config)
SearchResult solve(std::function<Model()> model_factory, double time_limit, uint64_t seed, const SearchConfig &config, std::function<std::shared_ptr<InnerSolverHook>(Model&)> hook_factory, std::function<std::shared_ptr<LNS>()> lns_factory, SolveCallback *callback, const ParallelConfig &par_config)

Extension points

The hooks that solve, SearchConfig and the portfolio take:

Type

What it extends

Header

InnerSolverHook, FloatIntensifyHook

an inner solver run on the search’s incumbents

inner_solver.h

LNS

large neighbourhood search

lns.h

MoveGenerator, MoveContext, NeighbourList

extra moves

move_generator.h

Tracer

a record of the search

tracer.h

ExecutorRef

the caller’s thread pool for the portfolio

executor.h

Inner-solver hooks

A problem-specific algorithm runs on the search’s points through a subclass of InnerSolverHook; the engine stays problem-blind.

  • Subclass InnerSolverHook and override solve(model, vm, last_changed_vars, stop); it reads the point from model, may change any value, and returns with the model fully evaluated (after bulk writes: full_evaluate(model), then vm.invalidate_cache()).

  • Called after every batch that ends real-feasible (vm.max_real_violation() within SearchConfig::feasibility_tolerance; the objective-bound row does not count). With wants_infeasible() true, also after every other batch, uncapped: such a hook budgets itself. Not started once the run is stopping.

  • Result: recorded only if real-feasible and strictly better than the worker’s incumbent (or its first feasible point). The search never rolls the point back, so a hook that cannot improve it leaves it as found.

  • Stop: the call cannot be pre-empted; a hook whose work can outlast the budget polls stop.requested() and returns promptly. stop is valid only during the call; a hook that reads no clock keeps an iteration-budgeted run bit-reproducible.

  • Pass one to solve as a pointer (cbls::solve(model, time_limit, seed, &hook)), or to ParallelSearch::solve as a factory returning a distinct std::shared_ptr per worker. A worker keeps its hook across pool restarts, so its state must stay valid then.

  • C++ only: a Python subclass is never called (no nanobind trampoline). SearchCounters::inner_solver_calls counts the calls.

  • Worked example: the unit-commitment hook, uc_hook.h, on the application page.

class InnerSolverHook

Subclassed by cbls::FloatIntensifyHook

Public Functions

virtual ~InnerSolverHook() = default
virtual void solve(Model &model, ViolationManager &vm, const std::vector<int32_t> &last_changed_vars = {}, StopRef stop = {}) = 0
inline virtual bool wants_infeasible() const

Model files

save_model and load_model write and read .cbls files, each by path or by stream, declared in io.h.

Model cbls::load_model(const std::string &path)

MPS

mps_to_model(read_mps(path)) gives a model. They and MpsProblem, MpsToModelOptions and MpsToModelResult are in io_mps.h.

MpsToModelResult cbls::mps_to_model(const MpsProblem &prob, const MpsToModelOptions &opts = {})

AMPL .nl

nl_to_model(read_nl(path)) gives a model, and parse_nl parses an already-loaded buffer, text or binary. They and NlProblem, NlToModelOptions and NlToModelResult are in io_nl.h.

NlToModelResult cbls::nl_to_model(const NlProblem &prob, const NlToModelOptions &opts = {})

Checking a solution

verify_model re-checks the point a model is left at and returns a VerifyResult of VerifyErrors, from verify.h.

VerifyResult cbls::verify_model(const Model &model, double tol = 1e-6)