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 theFetchContentlines.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(Model&&) noexcept = default¶
A moved-from
Modelmay 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, soif (!m.is_frozen()) m.freeze();silently does nothing.
-
~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_lenandelements == [0..n-1]: exactlylist_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_argumentunless0 <= min_len <= max_len <= universe, and, forListInit::Identity, unlessmin_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 isa - b + margin, with the margin fixed here and stored on the node (seekIntegralStrictMarginin dag.h): 1 when both sides are integral (is_integral), sox < yover integers is exactlyx <= y - 1; the tinykStrictComparisonEpsotherwise.
-
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
funcover 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
ethe variable’selementsandn == 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, andCyclicadds nothing: a single element is not a pair with itself.n == 2:head(e_0) + func(e_0, e_1) + tail(e_1), andCyclicaddsfunc(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.
Cyclicis the tour cost of a TSP over one List.head/tailare the depot legs of a CVRP route, where a cyclic sum over the customers alone would wrongly addfunc(e_{n-1}, e_0). The two are independent, so a cyclic sum with endpoint terms is expressible too.A
Setvariable is accepted, but itselementscarry 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 aList.func,headandtailare invoked by EVERY portfolio worker concurrently once the model is frozen – seefreeze().
-
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
modeoverload.
-
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 alsoat()’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 (
.cblswrites the table). Local derivative 0 for the index; FJ offers index values as the index variable’s jump candidates instead (seecompute_var_jump).Throws
std::invalid_argumenton an empty table, a non-finite entry or a List/Set index, andstd::out_of_rangeon 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.tablemust be rectangular and non-empty in both dimensions.
-
int32_t ceil_expr(int32_t x)¶
std::ceil,std::floorandstd::roundofx(#186).roundtakes a half-way value AWAY from zero (round(2.5) == 3,round(-2.5) == -3), which isstd::round’s rule. No tolerance is applied:ceilof 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). Throwsstd::invalid_argumenton 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_sumwhose 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], asfunc = (i, x) -> c[i][int(x[0])].extraare scalar handles – variables or nodes, any number, in the orderfuncreceives 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 plainlambda_sumdoes on an edit.Not serialisable:
funcis a function of continuous values and cannot be tabulated the way a plainlambda_sumis, sosave_modelrefuses a model holding one, before it writes anything. Shared by every portfolio worker, on the termsfreeze()states.Throws
std::invalid_argumentunlesslist_var_idnames a List or Set variable,funcis non-empty and noextrahandle names a List or Set variable;std::out_of_rangeon 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)withfalso readingextra, on the termslambda_sum’s extra form states. The pair andmodecontract 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
ListPartitionfor why, and for why there is nounassigned()view. Throwsstd::invalid_argumentunless every handle names a distinct List variable, all of them share oneuniverse_size, none is already in a partition,sum(min_len) <= universe, and, forCover::Exact,sum(max_len) >= universe.ListInit::Identityis rejected in a partition of more than one list: it would put every element in every member.Under
Cover::Exactthe members’ListInitis ignored, because the invariant has to hold at the FIRST assignment – no move can repair a partition that starts incomplete, sinceExactadmits no insert or remove that is not half of an inter-list move. Initialisation therefore always lays anExactpartition out as a random COMPLETE one. UnderCover::AtMostOncethere is no such obligation and each member’sListInitdecides 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 partitionvar_idbelongs to, or -1. Same lookup-table shape asvar_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_posand 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 calledfreeze().Every structural method throws afterwards: variable and expression creation,
add_constraint,minimize/maximize,add_var_sequence,reserveandclose. 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_constraintis the one intentional exception: on a frozen model it RETURNS, it does not throw, becausefreeze()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 therequire_openafter it is an unreachable backstop. Do not “fix” the order;tests/test_model_share.cpppins 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_sumcallables 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_bytesof 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 withSearchConfig::cone_cache_bytes.
-
inline bool is_frozen() const noexcept¶
-
inline bool has_cached_cone(int32_t var_id) const noexcept¶
Whether
freeze()cachedvar_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 wherehas_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
Constnode carrying the objective row’s RHS, or -1 when there is no objective row.evaluate()compares against this to know whichConstto readobjective_bound()for instead ofconst_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, likenode().
-
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 readsnode_values()hands out. Their ids come fromtopo_order(), so a check could only pass, yet would run once per node perfull_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_valueis the checked reader.
-
inline IncSums &inc_sums() noexcept¶
The incremental Sums’ per-model state (#188): see
IncSums. Sized and reset by everyfull_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 afterclose(): a node’s children are written once, when it is made, and never change.nodemust be one of THIS model’s nodes (fromnode()ornodes()), unmodified inchild_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
idas a child, in ascending id order, each listed once however many times it namesid(prod(n, n)). Rebuilt byclose()andadd_objective_soft_constraint(). Empty for every node beforeclose(); 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_idas a child, with the same order, dedup and rebuild contract asparents.
-
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_modeland 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 beforeclose().
-
inline int32_t num_domain_rows() const noexcept¶
How many implicit domain rows
close()appended after the modeller’s (#248):arg >= kLogDomainFloorunder aLogor aPowwith a constant negative non-integer exponent,arg >= 0under aSqrtor aPowwith a constant positive non-integer one. A row reads its plainGeqresidual (<= 0) when the argument meets its floor, and that residual plusdomain_margin()when it does not (#258). 0 beforeclose().
-
inline bool is_domain_node(int32_t id) const noexcept¶
Whether node
idis oneclose()made for a domain row: whatsave_modelleaves out, since a reload’sclose()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 ownSearchConfig::feasibility_tolerance, andsolve()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 eachFeasibilityJumpset 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_refsis 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
idsits intopo_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 oftopo_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, likenodes();node_value(id)is the checked reader. Seeset_node_value_uncheckedfor 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 aspair_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. Sizednum_nodes()on a closed model; empty beforeclose().
-
void restore_state(const State &state)¶
Writes the VARIABLES only. Every node value still describes the assignment this replaces, so a
full_evaluateis MANDATORY before anything reads a node value or callsdelta_evaluate. For a built-in op, skipping it merely recomputes late – except an incremental Sum (#188), whichcommit_scalar_movewould 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¶
-
Model()¶
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 <= 0disables the wall clock: bounded bymax_iterationsalone and deterministic per seed; with neither budget it returns at once.coordis 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
modelfirst (#271; Model::freeze), before the clock starts; the cone-cache build is O(config.cone_cache_bytes). Copies of the frozen model share itslambda_sum/pair_lambda_sumcallables, 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¶
-
bool skip_init = false¶
-
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 withfeasible = trueand +inf here (#100); testfeasible, thenstd::isfinite. Minimised sense: undermaximize(e)this is -e (see Model::is_maximizing); SolveProgress::objective follows suit.
-
bool feasible = false¶
Whether
best_statesatisfies every real constraint, whatever the objective is there.
-
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;
counterssplits batches by kind.
-
double time_seconds = 0.0¶
-
TerminationReason termination = TerminationReason::NoBudget¶
Which budget ended the run; qualifies
iterationsandtime_seconds.
-
double best_violation = std::numeric_limits<double>::infinity()¶
Largest real-constraint violation at
best_state(<= the tolerance whenfeasible). 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
perturbationsbecause a repair costs up to min(2.0, remaining()) s against a perturb’s microseconds. Summed by ParallelSearch likeperturbations.
-
int lns_repairs_accepted = 0¶
The subset of
lns_repairswhoseLNS::destroy_repairreturned true (#150); never greater thanlns_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 tokick_origin()(#158). Summed by ParallelSearch likeperturbations.
-
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_feasiblefor “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_launchedis after the executor’s cap; compareworkers_completedwith 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.
-
double objective = std::numeric_limits<double>::infinity()¶
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 tokMaxWorkerRetriesconsecutive 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)¶
-
explicit ParallelSearch(int n_threads = 0)¶
Extension points¶
The hooks that solve, SearchConfig and the portfolio take:
Type |
What it extends |
Header |
|---|---|---|
|
an inner solver run on the search’s incumbents |
|
|
large neighbourhood search |
|
|
extra moves |
|
|
a record of the search |
|
|
the caller’s thread pool for the portfolio |
Inner-solver hooks¶
A problem-specific algorithm runs on the search’s points through a subclass of
InnerSolverHook; the engine stays problem-blind.
Subclass
InnerSolverHookand overridesolve(model, vm, last_changed_vars, stop); it reads the point frommodel, may change any value, and returns with the model fully evaluated (after bulk writes:full_evaluate(model), thenvm.invalidate_cache()).Called after every batch that ends real-feasible (
vm.max_real_violation()withinSearchConfig::feasibility_tolerance; the objective-bound row does not count). Withwants_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.stopis valid only during the call; a hook that reads no clock keeps an iteration-budgeted run bit-reproducible.Pass one to
solveas a pointer (cbls::solve(model, time_limit, seed, &hook)), or toParallelSearch::solveas a factory returning a distinctstd::shared_ptrper 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_callscounts the calls.Worked example: the unit-commitment hook,
uc_hook.h, on the application page.
-
class InnerSolverHook¶
Subclassed by cbls::FloatIntensifyHook
Model files¶
save_model and load_model write and read .cbls files, each by path or by
stream, declared in
io.h.
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.