# cbls % The README from its subtitle on: the site has its own logo and title. ```{include} ../README.md :relative-docs: docs/ :relative-images: :start-after: :end-before: ``` % Drawn by figures/make_method.py; one copy per colour mode, in place of the % README's , which Sphinx cannot take. ```{figure} figures/method-light.svg :figclass: only-light :align: center :width: 100% :alt: Left, a small model as an expression DAG, with the cone one variable move re-evaluates highlighted. Right, the search loop of batches, feasibility checks and kicks. Left: a model's expression DAG; moving `y` re-evaluates the amber nodes only. Right: the search loop, with the steps a solve runs only when asked. ``` ```{figure} figures/method-dark.svg :figclass: only-dark :align: center :width: 100% :alt: Left, a small model as an expression DAG, with the cone one variable move re-evaluates highlighted. Right, the search loop of batches, feasibility checks and kicks. Left: a model's expression DAG; moving `y` re-evaluates the amber nodes only. Right: the search loop, with the steps a solve runs only when asked. ``` ```{include} ../README.md :relative-docs: docs/ :relative-images: :start-after: ``` ```{toctree} :hidden: Quick reference Options Results Method examples/modelling uc-chped C++ reference Python reference ``` # Quick reference How to call cbls, as a command or a library, and what it prints. ## Terminal ```bash # Build the C++ CLI, ./build/cbls, from a clone git clone https://github.com/spoorendonk/cbls && cd cbls cmake -B build cmake --build build -j4 # Install for Python: import cbls, and the cbls command (needs a C++17 compiler and zlib) pip install git+https://github.com/spoorendonk/cbls # Solve a file: .cbls, .mps, .mps.gz or .nl (also python -m cbls; ./build/cbls: .cbls only) cbls examples/simple.cbls --time-limit 1 # Every option and default, and the exit status (the same for python -m cbls and ./build/cbls) cbls --help ``` A MINLPLib `.nl` file (`st_e38`, a pressure-vessel design, optimum 7197.727149) and a MIPLIB `.mps.gz` file (`neos5`, 63 columns), from a clone's root; the test suite runs both lines: ```bash cbls benchmarks/instances/minlplib/st_e38.nl --time-limit 2 --threads 1 --seed 42 --quiet cbls benchmarks/instances/miplib-fj/neos5.mps.gz --time-limit 2 --threads 1 --seed 42 --format jsonl --quiet ``` - **Output.** `--format human`: progress rows (`*` on a new best), then `Status:`, `Objective:`, `Time:` and `Solution:` lines. `--format jsonl`: one JSON object per line, `start`, `progress`, then `result` with `status`, `feasible`, `objective` (null when none), `termination`, `time`, `iterations` and `solution` (its names sorted as text: `d1`, `d10`, `d11`, ...). - **Exit status.** 0 when a feasible point was found; 1 when not, and on a bad argument or model file (the message on stderr). ## Python ```python import cbls # Build a model and solve it, any option as a keyword m = cbls.Model() x, y = m.Int(0, 10, "x"), m.Float(0, 10, "y") m.add_constraint(x + y >= 3) m.minimize(x * x + y) m.close() result = cbls.solve(m, time_limit=1, seed=42, threads=1) print(result.feasible, result.objective, result.value(x)) # Load a file, one loader per format (paths from a clone's root) model = cbls.load_model("examples/simple.cbls") converted = cbls.nl_to_model(cbls.read_nl("benchmarks/instances/minlplib/st_e38.nl")) # converted = cbls.mps_to_model(cbls.read_mps("benchmarks/instances/miplib-fj/neos5.mps.gz")) result = cbls.solve(converted.model, time_limit=2) print(result.feasible, converted.original_values()) # one value per file column ``` - **`.nl` files.** Solve one only if `converted.supported`; else `converted.skipped_reasons` names the operators cbls does not model. A maximisation keeps its sense in `result.objective`; `result.search.objective` is the engine's minimised value. - **`.mps` files.** Infinite bounds are derived from the rows where they can be, else clamped to 1e9, which can cut off solutions (`converted.n_clamped_columns` counts them). `OBJSENSE MAX` is refused: negate the costs. - **Whole programs** that solve a file and verify the point independently: [`examples/minlplib.py`](https://github.com/spoorendonk/cbls/blob/main/examples/minlplib.py), [`examples/mip.py`](https://github.com/spoorendonk/cbls/blob/main/examples/mip.py), and their C++ versions beside them. ## C++ Link the target `cbls::cbls`: the [C++ reference](cpp.md#using-it-from-cmake) has the CMake file. Reference: [C++](cpp.md), [Python](https://spoorendonk.dk/cbls/autoapi/cbls/index.html); all the docs as text: , . # Options Both command lines take the options in their `--help` below; `cbls.solve` takes them as keywords, with the same defaults. - **Flag to keyword**: `--time-limit` → `time_limit=`, `--seed` → `seed=`, `--threads` → `threads=`, `--lns` → `lns=`, `--intensify` → `intensify=True`, `--lns-interval` → `config.lns_interval`; `--format` and `--quiet` have no keyword. - **Python only**: `callback=` (a `SolveCallback`, whose `on_progress` gets the progress rows as `SolveProgress`), `stop=` (a `StopToken` that ends the solve from another thread), `config=` (a `SearchConfig`). ## Input formats The model file's format is chosen by its extension. - **`.cbls`**: cbls's JSONL model, one variable, node, constraint or objective per line ([example](https://github.com/spoorendonk/cbls/blob/main/examples/simple.cbls)); both CLIs, `cbls.load_model(path)`. - **`.mps`, `.mps.gz`**: MPS ([reader](https://github.com/spoorendonk/cbls/blob/main/include/cbls/io_mps.h)); the Python CLI, `cbls.mps_to_model(cbls.read_mps(path)).model`. - **`.nl`**: AMPL's `.nl` ([spec](https://ampl.github.io/nlwrite.pdf)); the Python CLI, `cbls.nl_to_model(cbls.read_nl(path)).model`. ## C++ CLI: `./build/cbls --help` ```text Usage: cbls [OPTIONS] MODEL Constraint-Based Local Search solver. Reads a JSONL model file (.cbls) and finds optimal or feasible variable assignments. Arguments: MODEL Path to JSONL model file (.cbls) Options: --time-limit SECS Maximum solve time in seconds (default: 10.0) --seed INT Random seed for reproducibility (default: 42) --lns FRACTION LNS destroy fraction, e.g. 0.3 (default: off) --lns-interval INT LNS fires every N diversification kicks (default: 3) --intensify Enable float intensification hook (default: off) --threads N Number of search threads (default: 0 = one per core) --format human|jsonl Output format (default: human) --quiet Print only the final result, no progress (default: off) --help Show this help message --version Show version number Exit status: 0 when a feasible point is found, else 1 (also on a bad argument or model) ``` ## Python CLI: `cbls --help`, `python -m cbls --help` ```text Usage: cbls [OPTIONS] MODEL Constraint-Based Local Search solver. Reads a model file (.cbls JSONL, .mps, .mps.gz or AMPL .nl, by extension) and finds optimal or feasible variable assignments. Arguments: MODEL Path to the model file (.cbls, .mps, .mps.gz, .nl) Options: --time-limit SECS Maximum solve time in seconds (default: 10.0) --seed INT Random seed for reproducibility (default: 42) --lns FRACTION LNS destroy fraction, e.g. 0.3 (default: off) --lns-interval INT LNS fires every N diversification kicks (default: 3) --intensify Enable float intensification hook (default: off) --threads N Number of search threads (default: 0 = one per core) --format human|jsonl Output format (default: human) --quiet Print only the final result, no progress (default: off) --help Show this help message --version Show version number Exit status: 0 when a feasible point is found, else 1 (also on a bad argument or model) ``` # Results ## Known issues - `Set` variables are expressible, not competitive: on weighted OR-Library set covering, the `Set` encoding landed several times above the optimum, where the same model in Bools came close to it (measured on an older engine, `35ec07c`). - `List` variables have no published result: CVRP is an example only. - UC-CHPED's `ucp100` and `ucp200` are built here from `ucp40`, with no published bounds: their gaps are to the best result any method found. ## The solvers compared - **CP-SAT** (OR-Tools) runs a portfolio of workers: a constraint-programming search over a clause-learning SAT core, LP relaxations with cuts, large neighbourhood search, and local-search workers (`fj`, `ls`) that run the same ViolationLS as cbls. Its variables are integers: it scales a MIPLIB file's continuous columns to integers, and it has no `sin`, `exp` or `log`. - **SCIP** solves a nonlinear model by spatial branch-and-bound: LP relaxations of the nonlinear terms, tightened by branching on continuous variables, with local NLP solves by Ipopt (an interior-point method) as a heuristic. It proves bounds and optimality; cbls proves neither. - **Where cbls fits:** models whose terms CP-SAT cannot state (continuous, non-convex, transcendental or non-smooth), when a good solution early matters more than a proof. On a MILP, CP-SAT is ahead; on MINLPLib's general roster, SCIP is; on unit commitment with valve-point costs, cbls reaches good solutions first. A problem's own search code plugs into cbls as an [inner-solver hook](cpp.md#inner-solver-hooks); CP-SAT takes no such code, and SCIP takes it as a heuristic plugin. The published rows run without one. Every comparison solver runs at its own defaults. The metrics (primal integral, GM(gap+1), wins, losses and ties) are defined under the [README's results table](index.md#results). Per-instance rows are committed under `benchmarks/instances//`. ## MIPfeas Run 2026-11-02 on AMD Ryzen 9 3950X (16 cores, 32 threads): 211 held-out MIPLIB instances (`roster.csv` less 22 tuning ones), 60 s each; cbls seed 1 on 16 threads; CP-SAT (OR-Tools 9.15.6755) at its defaults, 32 workers, on its presolved model. Rows: [`benchmarks/instances/mipfeas/comparison.csv`](https://github.com/spoorendonk/cbls/blob/main/benchmarks/instances/mipfeas/comparison.csv). | Solver | Feasible | Matched the MIPLIB reference | Primal integral, SGM | mean | median | Did not search | |---|---|---|---|---|---|---| | cbls | 140 | 22 | 0.390 | 0.948 | 0.750 | **0** | | CP-SAT | **175** | **87** | **0.168** | **0.605** | **0.172** | 10 | ## MINLPLib Mittelmann's nontrivial roster, 195 instances counted, 60 s each. cbls seed 1 on 16 threads at its defaults, run 2026-11-26 on AMD Ryzen 9 3950X (16 cores, 32 threads); SCIP 10.0.2 at its defaults, single-threaded, 16 solves at once, run 2026-11-01. The pool is the 165 instances both solve with a finite best known. Rows: [`benchmarks/instances/minlplib/nontrivial/`](https://github.com/spoorendonk/cbls/tree/main/benchmarks/instances/minlplib/nontrivial). | Solver | Feasible | Feasible, only this solver | GM(gap+1) on the pool | Wins on the pool | |---|---|---|---|---| | cbls | 169 | 4 | 3.60 | 27 | | SCIP | **187** | **22** | **2.15** | **62** | - Ratio cbls/SCIP 1.676, 95% CI 1.181-2.378 (a t-interval on the 165 paired log ratios); 76 ties. ## UC-CHPED Run 2026-11-28 on AMD Ryzen 9 3950X (16 cores, 32 threads): the 24 rows of [the application page](uc-chped.md), demand as the source's equality, an equal wall budget per horizon (10-600 s), 16 threads for every method. cbls is the median of seeds 1, 2 and 42, seed 42 alone on the 4 rows of 48 and 168 periods; Pedroso et al.'s method (`pwl`) and SCIP's MINLP (`exact`) run once each on SCIP 11.0.0 preview. Final gaps within 0.01 % tie. Rows: [`benchmarks/instances/uc-chped/equal-time/primal_integral.csv`](https://github.com/spoorendonk/cbls/blob/main/benchmarks/instances/uc-chped/equal-time/primal_integral.csv). | Method | Lowest primal integral (of 24) | Best or tied final gap (of 24) | Best final gap alone (of 24) | |---|---|---|---| | cbls | **23** | 6 | 3 | | Pedroso's method (`pwl`) | 1 | **21** | **18** | | SCIP's MINLP (`exact`) | 0 | 3 | 0 | - On `ucp100-168p`, `ucp200-48p` and `ucp200-168p` the reference is cbls's own best final result, so its best gap there is 0 by construction. ## Instances - **MIPfeas:** the MIPLIB 2017 benchmark set ([miplib.zib.de](https://miplib.zib.de/)) less the instances MIPLIB marks infeasible, 233 in all, as GAMS's [MIPfeas](https://www.gams.com/blog/2026/03/expanding-the-focus-introducing-the-mipfeas-benchmark/) defines it; reference values are MIPLIB's `miplib2017-v36.solu`. The table counts the 211 outside the 22 cbls's settings were tuned on, at 60 s each. MIPLIB states no licence for the files, only a request to cite it; they are downloaded and checked against committed sha256 pins, not redistributed. - **MINLPLib:** the 200 names of Mittelmann's [`nontrivial.txt`](https://plato.asu.edu/ftp/nontrivial.txt), the MINLP set of the SCIP 8 paper, read from [MINLPLib](https://www.minlplib.org/)'s NL archive of 2026-11-01: 196 are still there with a known solution and a model cbls reads, and 195 are counted (`elec50`, a documented failure, is left out), at 60 s each. No setting was tuned on this roster. minlplib.org states CC BY 4.0 in its site footer; the roster and bounds are committed, the `.nl` files downloaded. - **UC-CHPED:** Pedroso, Kubo and Viana's `ucp13` and `ucp40`, identical field by field to the authors' data, over 1, 3, 6, 12 and 24 periods, and `ucp100` and `ucp200`, built here from `ucp40`, over those and 48 and 168: 24 rows, at a budget per horizon from 10 s (1 period) to 600 s (48 and 168). The instance files are cbls's own (MIT); the authors' instance code, which they publish under GPL-3, is not vendored, and the SCIP references, a port of their solver, are GPL-3.0-or-later. ## Reproduce ```bash # README results table, the MIPfeas, MINLPLib and UC-CHPED tables and the UC rows, from the committed rows .venv/bin/python benchmarks/readme_results.py --write README.md docs/results.md docs/uc-chped.md # MIPfeas: rerun cbls and CP-SAT on the full roster, score the 211 held out .venv/bin/python benchmarks/instances/mipfeas/download.py cmake --build build --target cbls_mipfeas .venv/bin/python benchmarks/mipfeas/run_benchmark.py --roster full --budget 60 --engines cbls --seed 1 --cbls-threads 16 --cpuset 0-15 .venv/bin/python benchmarks/mipfeas/run_benchmark.py --roster full --budget 60 --engines cpsat .venv/bin/python benchmarks/mipfeas/primal_integral.py --results-dir results/mipfeas --budget 60 --held-out benchmarks/instances/mipfeas/tuned.txt --out results/mipfeas/comparison.csv # MINLPLib: rerun SCIP and cbls on the nontrivial roster (MINLPLib's NL files, the committed bounds.csv), then score curl -LO https://www.minlplib.org/minlplib_nl.zip && unzip -q minlplib_nl.zip -d runs cp benchmarks/instances/minlplib/nontrivial/bounds.csv runs/minlplib/nl/ .venv/bin/python benchmarks/minlplib/scip_shards.py --nl-dir runs/minlplib/nl --shards runs/scip --jobs 16 --time-limit 60 taskset -c 0-15 .venv/bin/python benchmarks/minlplib/run_benchmark.py --inst-dir runs/minlplib/nl --threads 16 --no-merge --staging-dir runs/cbls --out runs/comparison.csv --trace-out runs/trace.csv .venv/bin/python benchmarks/minlplib/gm_ratio.py --bounds runs/minlplib/nl/bounds.csv --cbls runs/comparison.csv --scip-shards runs/scip # UC-CHPED: rerun the 20 rows up to 24 periods, cbls at seeds 1, 2 and 42 (its budget per horizon is the run's), # each SCIP method once per row at that budget, then one score call; each longer row (48, 168) runs and # scores the same way on its own at 600 s, cbls at seed 42 alone, its roster that one row (--roster ucp100-48p:48) rev=$(git rev-parse HEAD) for seed in 1 2 42; do build/cbls_uc_chped --demand-equality --threads 16 --seed $seed --periods 1 --periods 3 --periods 6 --periods 12 --periods 24 --commit $rev --verify --out runs/uc/seed$seed.csv --trace runs/uc/trace$seed.csv done for row in ucp13 ucp40 ucp100 ucp200; do for t in 1:10 3:30 6:60 12:120 24:300; do for method in pwl exact; do .venv/bin/python benchmarks/uc-chped/pedroso/ucp_valve_scip.py --backend driver --threads 16 --method $method --instance $row --periods ${t%:*} --time-limit ${t#*:} --out runs/uc/$method.jsonl done done done .venv/bin/python benchmarks/uc-chped/score.py runs/uc/seed1.csv runs/uc/seed2.csv runs/uc/seed42.csv --roster ucp13:1,3,6,12,24 ucp40:1,3,6,12,24 ucp100:1,3,6,12,24 ucp200:1,3,6,12,24 --scip runs/uc/pwl.jsonl --scip runs/uc/exact.jsonl --trace 1:runs/uc/trace1.csv --trace 2:runs/uc/trace2.csv --trace 42:runs/uc/trace42.csv ``` # Method cbls is a local search over complete assignments: every variable always has a value, and the search changes values until every row holds and the objective is as low as it can get. How far an assignment is from feasible is the weighted violation $V_w$ of its rows. It follows ViolationLS [1], which combines: - **Feasibility Jump (FJ):** pick a variable and move it to the value that lowers $V_w$ most, its jump value; - **guided local search (GLS) weights:** at a local minimum, where no such move lowers $V_w$, the rows still violated gain weight, so that satisfying them becomes worth more and the search leaves the minimum; - **Novelty Jump:** compound moves, a short sequence of jumps kept when together they lower $V_w$; - **the objective as one more row**, $f(x) \leq F$: after each feasible point $F$ drops below its objective, so the objective row is violated again until the search finds a better one. New here: - Float, List and Set variables in a nonlinear expression DAG; - structural moves for List and Set; - an adaptive objective step; - an inner solver for Floats, and hooks for a problem's own inner solver; - large neighbourhood search (LNS): on every few kicks, randomise part of the variables and repair with FJ, keeping the result if it is better; - a portfolio of workers sharing incumbents and the objective bound. Two deviations: the batch kind is drawn every batch, and a kick starts from the incumbent. The algorithms below leave out guards, tolerances and caps. | Name | Default | Options | |---|---|---| | threads | 0 (one per core) | `--threads`, `threads=`; 1 = one search | | time limit, seed | 10 s, 42 | `--time-limit`, `--seed`; `time_limit=`, `seed=` | | iteration cap | 0 (none) | `max_iterations` | | [Novelty Jump](#novelty-jump) | on, 0.5 of scalar batches | `use_compound_moves`, `novelty_jump_probability` | | [structural batch](#structural-moves) | auto: 0.33 with List/Set, 1 with no scalar work, else 0 | `structural_batch_probability` | | [structural selection](#structural-moves) | Auto | `structural_selection`, `structural_sample_size` (8), `structural_neighbours`; C++: `move_generators`, `default_structural_generators` | | [objective tie-break](#feasibility-jump) | on | `fj_objective_tie_break` | | [feasibility tolerance](#violation-and-weights) | $10^{-6}$ | `feasibility_tolerance` | | [inner solver](#inner-solver) | off | `--intensify`, `intensify=True`; C++: `FloatIntensifyHook` fields | | [LNS](#diversification) | off | `--lns φ`, `lns=φ`; `--lns-interval`, `lns_interval` (3) | | [FPR](#diversification) | 0; repair off | `fpr_batch_probability`, `fpr_dag_propagation`, `lns_repair_fpr` | | [kick cadence](#diversification) | 100 batches, $p = 0.1$, 300 | C++: `perturbation_period`, `perturbation_probability`, `unproductive_iterations`, `batch_iterations` (1000) | | [worker variants, Float jitter](#diversification) | off, 0 | `diversify_workers`, `float_start_jitter` $\in [0, 1]$ | | [shared bound, pool size](#diversification) | on, $\max(10, 2N)$ | C++: `ParallelConfig::share_objective_bound`, `pool_capacity` | Plain names are `cbls.SearchConfig` fields (C++ `SearchConfig`); flags are both CLIs'; keywords are `cbls.solve`'s; C++ marks what only C++ reaches. ## Model and evaluation The model, $\min f(x)$ s.t. $g_i(x) \le 0$, $h_j(x) = 0$, $x_k \in D_k$, is a DAG: variables are leaves, nodes are operations, each row is a comparison node. Moving $x_v$ changes only its cone $C(v)$, the nodes reachable from $v$. A row affine in $x_v$ is scored in closed form from its cached slope instead. Commit is Probe without the log. ```{pcode} \begin{algorithm} \caption{Probe and rollback} \begin{algorithmic} \Function{Probe}{$v, a$} \State $L \gets [(n, \mathrm{val}(n)) : n \in C(v)]$; $x_v \gets a$ \State $\mathrm{val}(n) \gets \mathrm{eval}(n)$ for each $n \in C(v)$, in topological order \EndFunction \Function{Rollback}{$v, a_0$} \State $x_v \gets a_0$; $\mathrm{val}(n) \gets b$ for each $(n, b) \in L$, with no re-evaluation \EndFunction \end{algorithmic} \end{algorithm} ``` ## Violation and weights $$ v_i(x) = \min\bigl(10^{30}, \max(0, g_i(x))\bigr), \qquad v_j(x) = \min\bigl(10^{30}, \lvert h_j(x) \rvert\bigr) $$ - $V_w(x) = \sum_r w_r\, v_r(x)$ over every row, the objective row $v_0 = \max(0, f(x) - F)$ included; NaN reads as $10^{30}$. - A row holds at $v_r \le \tau = 10^{-6}$ (absolute); the implicit domain rows ($\log$ argument $\ge 10^{-9}$, $\sqrt{\cdot}$ and fractional-power arguments $\ge 0$) only at $v_r = 0$. Feasible: every row but the objective row holds. - Weights start at 1 and reset to 1 at each new best and each kick. At a local minimum, $w_r \leftarrow \rho\, w_r + [\, v_r(x) > \tau \,]$ for every row, with $\rho \in \lbrace 0.95, 1 \rbrace$ drawn uniformly at the start, at each new best and at each kick. ## Feasibility Jump $$ \Delta_v(a) = V_w(x[v{:=}a]) - V_w(x), \qquad a_v^* = \arg\min_{a \in K_v} \Delta_v(a), \qquad s_v = -\Delta_v(a_v^*), $$ ties going to the first candidate in the order below. | Type | Candidates $K_v$ | |---|---| | Bool | $1 - x_v$ | | Int, window $\le 256$ wide | every integer in the domain window | | Int, wider | the window's ends, $x_v \pm 1$, a 32-point grid | | Float | $x_v - v_c / \partial_v v_c$ for up to 4 violated rows $c$ of $v$ (Newton, clamped), the midpoint, the bounds | - A variable that reaches a Ceil, Floor, Round or Element node also gets that node's breakpoints. - Once the search stalls, a Float at a stationary point of its violated rows also gets $x_v \pm \lbrace 10^{-6}, 10^{-2} \rbrace (\lvert x_v \rvert + 1)$. - A violated objective row gives a Newton candidate onto $f = F$: this is how the search descends $f$. - Objective tie-break: before the first feasible point the objective row is inert; for an affine $f$, an exact tie in $\Delta_v$ goes to the candidate that lowers $f$ most, and a jump that only lowers $f$ scores the smallest positive double. ```{pcode} \begin{algorithm} \caption{Feasibility Jump batch} \begin{algorithmic} \For{$L = 1000$ iterations} \State $S \gets \emptyset$ \While{$|S| < 5$ and $Q \setminus S \ne \emptyset$} \State draw $v$ uniformly from $Q \setminus S$; if $J_v$ is stale, $J_v \gets (a_v^*, s_v)$ \State if $s_v \le 0$, $Q \gets Q \setminus \{v\}$, else $S \gets S \cup \{v\}$ \EndWhile \If{$S \ne \emptyset$} \State $v \gets \arg\max_{u \in S} s_u$; $x_v \gets a_v^*$ \State invalidate $J$ of $v$'s row neighbours; add those in violated rows to $Q$ \ElsIf{no row is violated} \State \Return feasible \Else \State $w_r \gets \rho\, w_r + [v_r > \tau]$ for every row; add the variables of violated rows to $Q$ \Comment{local minimum} \EndIf \EndFor \end{algorithmic} \end{algorithm} ``` $Q$: the variables in a violated row; $J$: the cached jumps. A batch also ends after 300 iterations without a new low of the unweighted real-row violation (an unproductive batch, see [Diversification](#diversification)). ## Novelty Jump A Novelty batch searches compound moves under $w'_r = w_r$ for rows violated at entry and $w'_r = w_r / 1024$ otherwise; a move that breaks a satisfied row lifts it to $w_r$. With $s'_v$ the jump score under $w'$, $s_v$ that jump's score under $w$, $s_m$ the summed $s$ of the moves on the stack $T$ and $s_c$ the best $s$ tried at this level, a variable passes the filter $$ F(v):\quad s_m + s'_v > 0 \ \ \lor\ \ s_v > s_c . $$ ```{pcode} \begin{algorithm} \caption{Novelty Jump} \begin{algorithmic} \Function{Search}{$s_m, b$} \State $s_c \gets 0$ \While{$b \ge 0$} \State $v \gets$ the highest $s'_v$ of up to 3 draws from $Q' \setminus T$ that pass $F(v)$ \If{there is none} \State \Return false \EndIf \State $s_c \gets \max(s_c, s_v)$; apply $v$'s jump; push $v$ on $T$ \If{$s_m + s_v > 0$ or \Call{Search}{$s_m + s_v, b$}} \State \Return true \Comment{commit the compound move} \EndIf \State undo $v$; $b \gets b - 1$ \EndWhile \State \Return false \EndFunction \Function{ApplyNoveltyJump}{} \For{$b = 0, 1, 2$} \While{\Call{Search}{$0, b$}} \State clear $T$; $b \gets 0$ \EndWhile \State reset $w'$ on the rows that changed \EndFor \EndFunction \end{algorithmic} \end{algorithm} ``` Search and ApplyNoveltyJump are [1]'s Algorithms 5 and 4. A Novelty batch is GLS over ApplyNoveltyJump (a local minimum updates the weights as in FJ), charged 3 iterations per move and 1 per weight update against the same 1000. ## Structural moves List and Set variables move only in structural batches, LNS and kicks. Every move keeps its variable in its domain (distinct elements, size in $[\text{min}, \text{max}]$, a partition's cover). A move $m$ is scored over the rows $R(m)$ it can change, $\Delta(m) = \sum_{r \in R(m)} w_r \bigl(v_r(m(x)) - v_r(x)\bigr)$. | Variable | Moves | |---|---| | List | swap, 2-opt, relocate, or-opt (2, 3), insert, exchange, remove | | Set | add, remove, swap | | ListPartition | relocate, swap, 2-opt\*, and insert/remove under an at-most-once cover, between member lists | ```{pcode} \begin{algorithm} \caption{Structural batch, first improving} \begin{algorithmic} \For{each generator $g$ (one per List or Set, one per partition), until the deadline} \State $C \gets$ the candidates $g$ generates at $x$; $x_a \gets x$ \For{$m \in C$} \If{$V_w(m(x)) - V_w(x_a) < -10^{-12}$} \State $x_a \gets m(x)$ \EndIf \EndFor \State $x \gets x_a$ \EndFor \end{algorithmic} \end{algorithm} ``` Each $m$ is an edit of $x$. Selection (`structural_selection`): - `FirstImprovingSample`: the algorithm above. - `BestOfSample`: commits the best of at least `structural_sample_size` candidates. - `ViolationGuided`: the same, only for generators whose variables reach a violated row. - `GranularBest`: offers, per partition element, every move pairing it with one of its $k$ nearest neighbours [3]. - `Auto`: `GranularBest` with a neighbour list, else `FirstImprovingSample`. ## Objective bound $$ F = \begin{cases} +\infty & \text{before the first feasible point,} \\ f^* - 1 & f \text{ integer-valued,} \\ f^* - \delta\,(\lvert f^* \rvert + 1) & \text{otherwise,} \end{cases} $$ with $f^*$ the best feasible objective. $\delta$ starts at $10^{-3}$, becomes $\min(10^{-3}, 2\delta)$ at each recorded incumbent and $\max(10^{-6}, \delta/10)$ at a full-period stall, where $F$ is recomputed; it is both the smallest improvement asked for and, through the Newton candidate onto $F$, the descent step. A model without an objective stops at its first feasible point. ## Inner solver With `intensify`, the Floats are polished after each feasible batch on $A(x) = f(x) + V_w(x)$, and the point is recorded again if it stays feasible. Candidates for one Float, each clamped to its bounds, skipping $\lvert \partial \rvert \le 10^{-12}$: $$ x_v - \frac{v_c}{\partial_v v_c} \ \text{(first 3 violated rows } c \text{ of } v\text{)}, \qquad x_v - 0.1 \cdot 2^{-k}\, \partial_v f \ \ (k = 0, \dots, 4). $$ The minimum-norm Newton step on row $c$ moves every Float with $\lvert \partial_v v_c \rvert > 10^{-12}$ (at least two) by $\Delta x = -v_c \nabla v_c / \lVert \nabla v_c \rVert^2$. ```{pcode} \begin{algorithm} \caption{Intensify} \begin{algorithmic} \Repeat \State for each Float $v$: commit its candidate with the lowest $A$, if below $A(x)$ \State for each of the first 5 violated rows $c$: take the minimum-norm Newton step if $A$ drops \Until{neither half improved, or after 3 sweeps} \end{algorithmic} \end{algorithm} ``` This polish is one `InnerSolverHook`, the generic one. In C++ a hook of your own takes its place: problem-specific code the search calls after each feasible batch, and after every batch if it asks, which may change any value and is recorded only if the point is feasible and improves. That is how cbls specialises to a problem without changing the engine; the [UC-CHPED page](uc-chped.md#a-problem-specific-inner-solver) shows one, and the [C++ reference](cpp.md#inner-solver-hooks) the contract. ## Diversification ```{pcode} \begin{algorithm} \caption{Solve} \begin{algorithmic} \State $x \gets$ scalars at their domain value closest to 0, List and Set random; $F \gets +\infty$ \While{budget left} \State kind $\gets$ Structural w.p. $p_s$, else Novelty w.p. 0.5, else FJ, drawn every batch; run one batch \State if $x$ is feasible: record it; \Call{Intensify}{}; record it \State if a new best: $w \gets 1$; redraw $\rho$; stall $\gets 0$; else stall $\gets$ stall $+ 1$ \If{stall $\ge 100$} \State shrink $\delta$; adopt from the pool unless LNS is due, else \Call{Kick}{} \ElsIf{the FJ batch was unproductive and stall $\ge 5$} \State \Call{Kick}{} \Comment{stall kept} \EndIf \EndWhile \State \Return the best point, or the closest approach \Function{Kick}{} \State $x \gets$ the incumbent or the adopted point, if there is one \State \Call{DestroyRepair}{} if LNS is due, else \Call{Perturb}{$p = 0.1$}; $w \gets 1$; redraw $\rho$ \EndFunction \end{algorithmic} \end{algorithm} ``` - **Perturb:** each scalar takes a uniform value in its domain window with probability $p$, each List/Set $\max(1, \operatorname{round}(p\,\lvert e \rvert))$ random moves; if nothing moved, one scalar is forced to a new value. - **LNS** (`lns` $= \phi$): due every `lns_interval`-th kick that may run it (after the first feasible point, only full-period kicks may). It ruins and recreates each ListPartition (SISR [2]), randomises $\max(1, \lfloor \phi n \rfloor)$ other variables (whole registered sequences where given), repairs with FJ (2000 iterations, at most 2 s), and keeps the result only if $(\text{real violation}, f)$ is lexicographically smaller. - **FPR** [4]: a batch fixes integer variables one at a time under propagation of the linear rows (with `fpr_dag_propagation`, also monotone nonlinear rows) and repairs with FJ; `lns_repair_fpr` runs one such dive on LNS's destroyed scalars before its FJ repair. - **Pool:** feasible first, then by $f$; capacity $\max(10, 2N)$; each worker submits every incumbent at once. Adopt draws uniformly from the better half; it adopts nothing from an empty pool and never the current point. - **Portfolio:** $N$ workers, each a search on a copy sharing the model's structure. At each batch boundary a worker lowers its $F$ to the bound of the pool's best feasible objective; one whose search ends with time left restarts from its own point with a new seed. One thread is reproducible per seed; more are not. - **Worker variants:** `diversify_workers` gives workers 1–7 (mod 8) fixed variants of the Novelty probability, kick cadence, FPR, LNS interval and tie-break. `float_start_jitter` $J$ moves each Float's start by a uniform draw in $\pm J \min(\max(1, \lvert x \rvert), \text{half its width})$, in a direct solve and on odd portfolio workers. ## Limits - No lower bound and no proof of optimality or infeasibility: a run ends at its budget, and "infeasible" means no feasible point was found. - Tightly coupled equality rows are slow: a one-variable jump that fixes one row breaks the others, and only weights and compound moves get through. ## References 1. T. O. Davies, F. Didier, L. Perron. ViolationLS: Constraint-Based Local Search in CP-SAT. CPAIOR 2024. 2. J. Christiaens, G. Vanden Berghe. Slack Induction by String Removals for Vehicle Routing Problems. Transportation Science 54(2), 2020. 3. P. Toth, D. Vigo. The Granular Tabu Search and Its Application to the Vehicle-Routing Problem. INFORMS Journal on Computing 15(4), 2003. 4. D. Salvagnin, R. Roberti, M. Fischetti. A fix-propagate-repair heuristic for mixed integer programming. Mathematical Programming Computation, 2024. # Modelling What a model can use, then three models in Python. The test suite runs the first two models as written; the third is the model part of a whole program. ## What a model can use In Python, with `m = cbls.Model()`, `x` and `y` expressions and `h` an expression's `.handle`. C++ has the same operations in `namespace cbls` and on `Model`, except the two table sums, which are Python's: C++ passes callables to `lambda_sum` and `pair_lambda_sum`. C++ spells `x ** y` as `x.pow(y)`. | Kind | Python | |---|---| | Variables | `m.Bool()`, `m.Int(lb, ub)`, `m.Float(lb, ub)`, `m.List(n)`, `m.Set(n)`; `m.Constant(v)` | | Arithmetic | `x + y`, `x - y`, `x * y`, `x / y`, `-x`, `x ** y`, `cbls.pow(x, y)` | | Nonlinear | `cbls.sin`, `cos`, `tan`, `exp`, `log`, `sqrt`, `abs`; `m.tanh_expr(h)`, `m.signpower_expr(h, h2)` | | Piecewise and logic | `cbls.min([x, y])`, `cbls.max([x, y])`, `cbls.if_then_else(c, x, y)`, `cbls.ceil`, `floor`, `round`, `cbls.element(table, i)` | | Rows | `m.add_constraint(...)` of `x <= y`, `x >= y`, `x < y`, `x > y`, `x.eq(y)`, `x.neq(y)` | | List and Set | `m.at(h, hi)` (the element at position `hi`, a handle), `m.count(h)` (the size), `m.lambda_table_sum`, `m.pair_table_sum`, `m.lambda_sum`, `m.pair_lambda_sum`, `m.add_list_partition` | | Objective | `m.minimize(x)`, `m.maximize(x)` | - **Nonlinear terms need no form:** non-convex, non-smooth and discontinuous expressions are scored as written; `log`, `sqrt` and fractional powers add domain rows that hold exactly. - **An inner solver**, problem-specific code the search calls on its points, is a C++ plugin: [inner-solver hooks](../cpp.md#inner-solver-hooks). ## Lot sizing with set-up costs Bools and Ints with constraints: make at least 60 units on three machines, each with capacity 40, a unit cost and a set-up cost paid when it runs. ```python import cbls m = cbls.Model() cost, setup = [4, 3, 5], [20, 30, 10] on = [m.Bool() for _ in cost] n = [m.Int(0, 40) for _ in cost] for i in range(3): m.add_constraint(n[i] <= 40 * on[i]) m.add_constraint(sum(n) >= 60) m.minimize(sum(c * a + f * b for c, a, f, b in zip(cost, n, setup, on))) m.close() result = cbls.solve(m, time_limit=1) print(result.objective, [result.value(a) for a in n]) ``` ## A tour as one List variable A permutation as one `List` variable: the shortest closed tour of 12 points. It needs NumPy, which cbls does not install (`pip install numpy`). ```python import cbls import numpy as np xy = np.random.default_rng(1).random((12, 2)) dist = np.linalg.norm(xy[:, None] - xy[None], axis=2) m = cbls.Model() tour = m.List(12) m.minimize(m.pair_table_sum(tour.handle, dist, cyclic=True)) m.close() result = cbls.solve(m, time_limit=1) print(result.objective, result.elements[0]) ``` ## Vehicle routes as List variables A capacitated vehicle routing problem (CVRP): each route is one `List`, the Lists partition the customers, no route carries more than `capacity`, and the total length is minimised. `n` customers, `fleet` routes; `demand`, `from_depot` and `to_depot` are NumPy arrays of length `n`, `between` is `n` by `n`, all without the depot, and `capacity` is a `model.constant(...)`: ```python routes = [model.list_var(n, 0, n, cbls.ListInit.Empty, f"route{r}") for r in range(fleet)] model.add_list_partition(routes, cbls.Cover.Exact) lengths = [] for route in routes: model.add_constraint(model.leq(model.lambda_table_sum(route, demand), capacity)) lengths.append(model.pair_table_sum(route, between, head=from_depot, tail=to_depot)) model.minimize(model.sum(lengths)) model.close() ``` - The partition is an invariant, not a penalised constraint: the search starts from a random complete partition and its moves keep it complete. - `lambda_table_sum` adds a route's demands; `pair_table_sum` its legs, with `head` and `tail` the legs from and to the depot. An empty route costs 0. - [`examples/cvrp.py`](https://github.com/spoorendonk/cbls/blob/main/examples/cvrp.py) reads a CVRPLIB instance, solves it and checks the routes; [`examples/cvrp.cpp`](https://github.com/spoorendonk/cbls/blob/main/examples/cvrp.cpp) is the C++ version. The test suite runs the Python one on `X-n115-k10`: ```bash python examples/cvrp.py benchmarks/instances/cvrp/X/X-n115-k10.vrp ``` # Application: unit commitment with valve-point costs Unit commitment decides which thermal generators run in each hour of a horizon and how much each one produces, so that demand and a spinning reserve are met at the least fuel and start-up cost. With the valve-point effect, each unit's fuel cost carries a term $\lvert d_u \sin(e_u (P_u^{\min} - P)) \rvert$, non-convex and non-smooth in the dispatch, which CP-SAT cannot state. This page solves the formulation and instances of Pedroso, Kubo and Viana, [*Unit commitment with valve-point loading effect*](https://arxiv.org/abs/1404.4944) (2014). % Drawn by figures/make_schedule.py from a cbls solve; one copy per colour mode. ```{figure} figures/schedule-light.svg :figclass: only-light :align: center :width: 560px :alt: Bands of generator output stacked hour by hour, rising to a midday peak and falling again, under a dashed step line of committed capacity. The unit commitment cbls finds for Pedroso et al.'s `ucp13` over 24 hours. Each band is one generator's output, stacked to meet the hourly demand exactly. The dashed line is the committed capacity, which must also cover a spinning reserve. ``` ```{figure} figures/schedule-dark.svg :figclass: only-dark :align: center :width: 560px :alt: Bands of generator output stacked hour by hour, rising to a midday peak and falling again, under a dashed step line of committed capacity. The unit commitment cbls finds for Pedroso et al.'s `ucp13` over 24 hours. Each band is one generator's output, stacked to meet the hourly demand exactly. The dashed line is the committed capacity, which must also cover a spinning reserve. ``` ## The problem Units $u \in \mathcal{U}$, periods $t \in \mathcal{T} = \{1, \ldots, T\}$. The commitment $y_{u,t}$ and the dispatch $p_{u,t}$ are the decisions: $$ \begin{aligned} \min\ & \sum_{u \in \mathcal{U}} \sum_{t \in \mathcal{T}} \big[\, y_{u,t}\, F_u(p_{u,t}) + SC_{u,t} \,\big] \\ \text{s.t.}\ & \textstyle\sum_{u} p_{u,t} = D_t, && t \in \mathcal{T}, \\ & \textstyle\sum_{u} P_u^{\max}\, y_{u,t} \geq D_t + R_t, && t \in \mathcal{T}, \\ & P_u^{\min}\, y_{u,t} \leq p_{u,t} \leq P_u^{\max}\, y_{u,t}, && u \in \mathcal{U},\ t \in \mathcal{T}, \\ & y_{u,t} - y_{u,t-1} \leq y_{u,\tau}, && u \in \mathcal{U},\ t, \tau \in \mathcal{T},\ t < \tau < t + UT_u, \\ & y_{u,t-1} - y_{u,t} \leq 1 - y_{u,\tau}, && u \in \mathcal{U},\ t, \tau \in \mathcal{T},\ t < \tau < t + DT_u, \\ & y_{u,t} = y_{u,0}, && u \in \mathcal{U},\ t \in \mathcal{T},\ t \leq L_u, \\ & y_{u,t} \in \{0, 1\},\ p_{u,t} \geq 0, && u \in \mathcal{U},\ t \in \mathcal{T}, \end{aligned} $$ with the fuel and start-up costs $$ \begin{aligned} F_u(P) &= a_u + b_u P + c_u P^2 + \left| d_u \sin\big(e_u (P_u^{\min} - P)\big) \right|, \\ SC_{u,t} &= \max(0,\ y_{u,t} - y_{u,t-1}) \cdot \begin{cases} A_u^{\text{hot}} & \text{if } y_{u,\tau} = 1 \text{ for some } t - \tau_u^{\text{cold}} \leq \tau < t, \\ A_u^{\text{cold}} & \text{otherwise.} \end{cases} \end{aligned} $$ The data: demand $D_t$ and reserve $R_t$ per period; per unit, the output limits $P_u^{\min}$ and $P_u^{\max}$, the fuel coefficients $a_u, \ldots, e_u$, the hot and cold start-up costs $A_u^{\text{hot}}$ and $A_u^{\text{cold}}$, the cold-start time $\tau_u^{\text{cold}}$, the minimum up and down times $UT_u$ and $DT_u$, and the state $y_{u,0}$ the unit has held for $n_u$ periods before the horizon. - **Objective:** fuel while a unit is committed, plus start-ups. The valve-point term $\lvert d_u \sin(\cdot) \rvert$ makes each unit's fuel cost non-convex and non-smooth in its dispatch. - **Demand:** the units' output meets each period's demand $D_t$ exactly. The runner's default is $\geq$, a relaxation (with a valve-point cost, producing more can cost less); `--demand-equality` solves the $=$, as the published rows do. - **Spinning reserve:** the *committed capacity*, not the dispatch, covers demand plus the reserve $R_t$. - **Dispatch limits:** a committed unit runs between $P_u^{\min}$ and $P_u^{\max}$; a unit that is off produces nothing. - **Minimum up and down times:** a unit that starts stays on for $UT_u$ periods, and one that stops stays off for $DT_u$, up to the horizon's end. A unit keeps its state before the horizon for what it still owes: $L_u = UT_u - n_u$ periods if it was on, $DT_u - n_u$ if it was off (none if negative). - **Start-up cost:** hot if the unit ran within its last $\tau_u^{\text{cold}}$ periods, cold otherwise; every start-up on these instances is cold. - There are no ramp rates, in the source or here. | Instance | Units | Periods | Source | |---|---:|---:|---| | `ucp13` | 13 | 1, 3, 6, 12, 24 | Pedroso et al.'s data, checked field by field | | `ucp40` | 40 | 1, 3, 6, 12, 24 | Pedroso et al.'s data, checked field by field | | `ucp100` | 100 | 1, 3, 6, 12, 24, 48, 168 | constructed from `ucp40` | | `ucp200` | 200 | 1, 3, 6, 12, 24, 48, 168 | constructed from `ucp40` | Pedroso et al. publish bounds for `ucp13` and `ucp40` only; the runner restates them as cited rows in its `comparison.csv`. How `ucp100` and `ucp200` are built is in the [developer notes](https://github.com/spoorendonk/cbls/blob/main/dev/benchmarks.md#uc-chped), and every runner flag in `cbls_uc_chped --help`. In cbls, each $y_{u,t}$ is a `Bool` and each $p_{u,t}$ a `Float`; the fuel cost is an expression over `sin` and `abs`, the start-up price an `if_then_else` over a `max` of past commitments ([`uc_model.h`](https://github.com/spoorendonk/cbls/blob/main/benchmarks/uc-chped/uc_model.h)). ## A problem-specific inner solver The engine knows nothing about unit commitment. A C++ subclass of `InnerSolverHook` adds what it knows, as a plugin the search calls on its points ([C++ reference](cpp.md#inner-solver-hooks)). The runner ships one, [`uc_hook.h`](https://github.com/spoorendonk/cbls/blob/main/benchmarks/uc-chped/uc_hook.h). It reads the commitment $y$ and dispatch $p$ at the search's point. It acts only on a commitment that meets the minimum up and down times and the initial state and can be dispatched in every period: committed $\sum P_u^{\max}$ covers $D_t + R_t$ and committed $\sum P_u^{\min}$ does not exceed $D_t$. With `--uc-repair` it first tries to repair one that does not, mainly by switching units on; a commitment that still fails, or any failing one without the flag, is skipped. It then works in two layers. **Dispatch.** For a fixed commitment the cost separates by period, and each period is an economic dispatch over the units that are on, balanced to $D_t$ exactly whatever demand row the model uses: $$ ED_t(y) = \min_{p} \sum_{u : y_{u,t} = 1} F_u(p_u) \quad \text{s.t.} \quad \sum_{u : y_{u,t} = 1} p_u = D_t, \qquad P_u^{\min} \leq p_u \leq P_u^{\max}. $$ The $\lvert \sin \rvert$ term is zero, a kink of $F_u$, at the valve points $P_u^{\min} + k\pi / e_u$, $k = 0, 1, \ldots$; these and $P_u^{\max}$ are each unit's candidate outputs. The fast dispatch solves the quadratic part by $\lambda$-dispatch ($b_u + 2 c_u p_u = \lambda$, clamped to the limits, with $\lambda$ set so the output meets $D_t$), snaps each unit to its nearest candidate and rebalances by whole steps between candidates; one unit closes the remaining residual where it can, else units are filled to their limits in turn. The polish, at most 4 sweeps, moves one unit onto another candidate while a second unit absorbs the difference, when that lowers the cost. **Commitment.** With `full`, over such commitments it minimises $$ C(y) = \sum_{t} ED_t(y) + \sum_{u,t} SC_{u,t}(y), $$ each $ED_t$ priced by the fast dispatch (by default), by first-improvement descent: per unit, drop, shrink or extend a block of on periods, fill a gap between two blocks, or add a block of $UT_u$ periods (cut at the horizon) at a few sampled off periods; then switch a block of one unit off and an idle unit on over the same periods. A move re-dispatches only the periods it changes. Optionally, an iterated local search kicks the commitment with random moves and descends again, keeping the better. The polish then runs on the final commitment's dispatch. The hook writes $(y, p)$ back only if the model finds it feasible and cheaper than the point it read; at an infeasible point (if asked to run there), cheaper than the best it has seen, or any feasible one before it has seen one. Otherwise it restores the point. `--uc-hook ed` runs the dispatch only; `--uc-hook full` adds the commitment search. The hook is off by default, and the results below are without it. ## Results At equal time and threads, cbls has the lowest primal integral on most rows: it reaches good solutions first. Pedroso et al.'s method ends with the best final gap on most. The setup and the counts are on the [results page](results.md#uc-chped). Row by row: the primal integral (PI; 0 if the best known is found at once, up to 2 if nothing is found) and the final gap in % to the row's reference, the lowest objective any method or the source reached. For cbls, the PI is the median over its seeds and the gap the median over the seeds that found a solution; `pwl` is Pedroso et al.'s method and `exact` SCIP's MINLP, one run each. In bold: the strictly lowest PI, and every gap tied for lowest at 0.01 %; `-` is no solution in the budget. | Row | Budget (s) | PI cbls | PI pwl | PI exact | Gap % cbls | Gap % pwl | Gap % exact | |---|---:|---:|---:|---:|---:|---:|---:| | `ucp13` T=1 | 10 | **0.0002** | 0.0184 | 0.0315 | **0.00** | **0.00** | **0.00** | | `ucp13` T=3 | 30 | **0.0014** | 0.0131 | 0.0173 | **0.00** | **0.00** | **0.00** | | `ucp13` T=6 | 60 | **0.0055** | 0.0092 | 0.0168 | 0.32 | **0.00** | 0.14 | | `ucp13` T=12 | 120 | **0.0056** | 0.0083 | 0.1294 | 0.42 | **0.00** | 0.37 | | `ucp13` T=24 | 300 | **0.0085** | 0.0123 | 0.5273 | 0.60 | **0.00** | 0.57 | | `ucp40` T=1 | 10 | **0.0040** | 0.0313 | 0.0523 | **0.00** | **0.00** | **0.00** | | `ucp40` T=3 | 30 | 0.0214 | **0.0210** | 0.0677 | 1.80 | **0.00** | 0.08 | | `ucp40` T=6 | 60 | **0.0118** | 0.0248 | 0.1503 | 0.96 | **0.05** | 0.36 | | `ucp40` T=12 | 120 | **0.0177** | 0.0181 | 0.3688 | 1.30 | **0.00** | 10.04 | | `ucp40` T=24 | 300 | **0.0307** | 0.0364 | 0.4129 | 2.46 | **0.00** | 8.12 | | `ucp100` T=1 | 10 | **0.0224** | 0.0484 | 0.2510 | 1.13 | **0.00** | 0.10 | | `ucp100` T=3 | 30 | **0.0262** | 0.0389 | 0.3770 | 2.39 | **0.00** | 0.45 | | `ucp100` T=6 | 60 | **0.0155** | 0.0677 | 0.6931 | 1.24 | **0.00** | 0.61 | | `ucp100` T=12 | 120 | **0.0299** | 0.2276 | 0.9962 | 2.51 | **0.00** | 0.89 | | `ucp100` T=24 | 300 | **0.0516** | 0.4058 | 0.6230 | 4.29 | **0.00** | 0.88 | | `ucp100-48p` | 600 | **0.0645** | 1.9715 | 0.4995 | 5.95 | **0.00** | 12.37 | | `ucp100-168p` | 600 | **0.0024** | 0.5494 | 2.0000 | **0.00** | 2.66 | - | | `ucp200` T=1 | 10 | **0.0581** | 0.1606 | 0.1580 | 4.57 | **0.00** | 0.41 | | `ucp200` T=3 | 30 | **0.0351** | 0.1366 | 0.5173 | 3.05 | **0.00** | 1.75 | | `ucp200` T=6 | 60 | **0.0226** | 0.2307 | 0.9627 | 1.66 | **0.00** | 17.49 | | `ucp200` T=12 | 120 | **0.0425** | 0.7539 | 0.6402 | 3.36 | **0.00** | 0.74 | | `ucp200` T=24 | 300 | **0.0699** | 0.8342 | 1.0674 | 6.04 | **0.00** | 0.77 | | `ucp200-48p` | 600 | **0.0029** | 2.0000 | 2.0000 | **0.00** | - | - | | `ucp200-168p` | 600 | **0.0079** | 2.0000 | 2.0000 | **0.00** | - | - | On `ucp100-168p`, `ucp200-48p` and `ucp200-168p` the reference is cbls's own best final result, so its best seed's gap there is 0 by construction. ## How to run it Build the runner from the repository root, after `cmake -B build`: ```bash cmake --build build --target cbls_uc_chped ``` Solve `ucp13` over 3 periods for 2 s with the source's equality demand, verify it, and write the row and the solution to a temporary directory: ```bash out=$(mktemp -d) ./build/cbls_uc_chped benchmarks/instances/uc-chped --instance ucp13 --periods 3 \ --time-limit 2 --seed 1 --demand-equality --verify \ --out "$out/ucp13.csv" --solution-out "$out/ucp13.jsonl" ``` Check each solution independently of the engine, from the instance file alone, against Pedroso et al.'s `=` model at 1e-6 (prints `OK` per solution): ```bash .venv/bin/python benchmarks/uc-chped/check_solutions.py benchmarks/instances/uc-chped "$out/ucp13.jsonl" ``` - Without `--instance`, `--periods` and `--time-limit`, the runner solves the whole roster at its per-horizon budgets (10 s at 1 period up to 600 s at 168). - `--threads N` runs the parallel portfolio; `cbls_uc_chped --help` lists every flag. - The SCIP references, Pedroso et al.'s Algorithm 1 ported to SCIP (`pwl`) and SCIP's MINLP with the true valve-point term (`exact`), are in [`benchmarks/uc-chped/pedroso/`](https://github.com/spoorendonk/cbls/blob/main/benchmarks/uc-chped/pedroso/README.md) (GPL-3.0-or-later). # C++ reference The supported part of the C++ library, in namespace `cbls`: what `` brings in, plus `` for AMPL `.nl` models. This page has the main entry point of each concept and links the headers that declare the rest. What else `` 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 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`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/model.h) also declares `ListPartition` and `Cover`, for Lists that partition a ground set. ```{doxygenclass} cbls::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`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/expr.h). ## Solving `solve` runs one search, under a `SearchConfig`, and returns a `SearchResult`. [`search.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/search.h) also declares `TerminationReason`, `WorkerFailure`, and the `SolveCallback` that receives a `SolveProgress`. [`stop.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/stop.h) has `StopToken` and `StopRef`, to stop a solve from outside. ```{doxygenfunction} cbls::solve ``` ```{doxygenstruct} cbls::SearchConfig ``` ```{doxygenstruct} cbls::SearchResult ``` ## Portfolio `ParallelSearch` runs the search on several threads. `ParallelConfig` is beside it in [`pool.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/pool.h). ```{doxygenclass} cbls::ParallelSearch ``` ## 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`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/inner_solver.h) | | `LNS` | large neighbourhood search | [`lns.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/lns.h) | | `MoveGenerator`, `MoveContext`, `NeighbourList` | extra moves | [`move_generator.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/move_generator.h) | | `Tracer` | a record of the search | [`tracer.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/tracer.h) | | `ExecutorRef` | the caller's thread pool for the portfolio | [`executor.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/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`](https://github.com/spoorendonk/cbls/blob/main/benchmarks/uc-chped/uc_hook.h), on the [application page](uc-chped.md#a-problem-specific-inner-solver). ```{doxygenclass} cbls::InnerSolverHook ``` ## Model files `save_model` and `load_model` write and read `.cbls` files, each by path or by stream, declared in [`io.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/io.h). ```{doxygenfunction} 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`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/io_mps.h). ```{doxygenfunction} cbls::mps_to_model ``` ### 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`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/io_nl.h). ```{doxygenfunction} cbls::nl_to_model ``` ## Checking a solution `verify_model` re-checks the point a model is left at and returns a `VerifyResult` of `VerifyError`s, from [`verify.h`](https://github.com/spoorendonk/cbls/blob/main/include/cbls/verify.h). ```{doxygenfunction} cbls::verify_model ``` cbls ==== .. py:module:: cbls .. autoapi-nested-parse:: CBLS: constraint-based local search over an expression DAG. The public surface is `__all__`: models, variables, expressions and their math functions, `solve`, its configuration, result and callbacks, and file I/O. The engine's internals stay reachable as `cbls._cbls_core` (#464). Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/cbls/__main__/index /autoapi/cbls/_cbls_core/index /autoapi/cbls/_solve/index Classes ------- .. autoapisummary:: cbls.BoundPropagationStats cbls.Cover cbls.Expr cbls.ExprNode cbls.GeneratorCounters cbls.ListInit cbls.ListPartition cbls.Model cbls.ModelState cbls.MpsProblem cbls.MpsToModelOptions cbls.MpsToModelResult cbls.NeighbourList cbls.NlProblem cbls.NlToModelOptions cbls.NlToModelResult cbls.NodeOp cbls.SearchConfig cbls.SearchCounters cbls.SearchResult cbls.SolveCallback cbls.SolveProgress cbls.StopToken cbls.StructuralSelection cbls.TerminationReason cbls.Variable cbls.VarType cbls.WorkerFailure cbls.SolveResult Functions --------- .. autoapisummary:: cbls.ceil cbls.cos cbls.element cbls.exp cbls.floor cbls.if_then_else cbls.load_model cbls.log cbls.mps_to_model cbls.nearest_neighbours cbls.nl_to_model cbls.read_mps cbls.read_nl cbls.save_model cbls.sin cbls.sqrt cbls.tan cbls.solve Package Contents ---------------- .. py:class:: BoundPropagationStats .. py:property:: passes :type: int .. py:property:: n_tightened :type: int .. py:property:: n_finitized :type: int .. py:property:: n_fixed :type: int .. py:property:: infeasible :type: bool .. py:property:: hit_pass_limit :type: bool .. py:class:: Cover Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: Exact :value: 0 .. py:attribute:: AtMostOnce :value: 1 .. py:class:: Expr .. py:property:: model :type: Model .. py:property:: handle :type: int .. py:method:: var_id() -> int .. py:method:: __add__(arg: Expr, /) -> Expr __add__(arg: float, /) -> Expr .. py:method:: __radd__(arg: float, /) -> Expr .. py:method:: __mul__(arg: Expr, /) -> Expr __mul__(arg: float, /) -> Expr .. py:method:: __rmul__(arg: float, /) -> Expr .. py:method:: __sub__(arg: Expr, /) -> Expr __sub__(arg: float, /) -> Expr .. py:method:: __rsub__(arg: float, /) -> Expr .. py:method:: __truediv__(arg: Expr, /) -> Expr __truediv__(arg: float, /) -> Expr .. py:method:: __rtruediv__(arg: float, /) -> Expr .. py:method:: __neg__() -> Expr .. py:method:: __pow__(arg: Expr, /) -> Expr __pow__(arg: int, /) -> Expr __pow__(arg: float, /) -> Expr .. py:method:: __rpow__(arg: float, /) -> Expr .. py:method:: __le__(arg: Expr, /) -> Expr __le__(arg: float, /) -> Expr .. py:method:: __ge__(arg: Expr, /) -> Expr __ge__(arg: float, /) -> Expr .. py:method:: __lt__(arg: Expr, /) -> Expr __lt__(arg: float, /) -> Expr .. py:method:: __gt__(arg: Expr, /) -> Expr __gt__(arg: float, /) -> Expr .. py:method:: __ceil__() -> Expr .. py:method:: __floor__() -> Expr .. py:method:: __round__(ndigits: int | None = None) -> Expr .. py:method:: __abs__() -> Expr .. py:method:: is_var() -> bool .. py:method:: eq(arg: Expr, /) -> Expr .. py:method:: neq(arg: Expr, /) -> Expr .. py:method:: pow(arg: Expr, /) -> Expr .. py:class:: ExprNode .. py:property:: id :type: int .. py:property:: op :type: NodeOp .. py:class:: GeneratorCounters .. py:property:: name :type: str .. py:property:: moves_tried :type: int .. py:property:: moves_accepted :type: int .. py:class:: ListInit Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: Identity :value: 0 .. py:attribute:: Empty :value: 1 .. py:attribute:: Random :value: 2 .. py:class:: ListPartition .. py:property:: list_ids :type: list[int] .. py:property:: cover :type: Cover .. py:property:: universe_size :type: int .. py:class:: Model .. py:method:: bool_var(name: str = '') -> int .. py:method:: int_var(lb: int, ub: int, name: str = '') -> int .. py:method:: float_var(lb: float, ub: float, name: str = '') -> int .. py:method:: list_var(n: int, name: str = '') -> int list_var(universe: int, min_len: int, max_len: int, init: ListInit = ListInit.Empty, name: str = '') -> int An ordered sequence of distinct elements of {0..universe-1} whose length stays within [min_len, max_len]. .. py:method:: set_var(n: int, min_size: int = 0, max_size: int = -1, name: str = '') -> int .. py:method:: add_list_partition(lists: collections.abc.Sequence[int], cover: Cover = Cover.Exact) -> int add_list_partition(lists: collections.abc.Sequence[int], cover: str) -> int .. py:method:: partition_of_list(var_id: int) -> int Index into list_partitions() of the partition this variable id belongs to, or -1. Takes a var ID, not a handle. .. py:property:: list_partitions :type: list[ListPartition] .. py:method:: constant(arg: float, /) -> int .. py:method:: neg(arg: int, /) -> int .. py:method:: sum(arg: collections.abc.Sequence[int], /) -> int .. py:method:: prod(arg0: int, arg1: int, /) -> int .. py:method:: div_expr(arg0: int, arg1: int, /) -> int .. py:method:: pow_expr(arg0: int, arg1: int, /) -> int .. py:method:: min_expr(arg: collections.abc.Sequence[int], /) -> int .. py:method:: max_expr(arg: collections.abc.Sequence[int], /) -> int .. py:method:: abs_expr(arg: int, /) -> int .. py:method:: sin_expr(arg: int, /) -> int .. py:method:: cos_expr(arg: int, /) -> int .. py:method:: tan_expr(arg: int, /) -> int .. py:method:: exp_expr(arg: int, /) -> int .. py:method:: log_expr(arg: int, /) -> int .. py:method:: sqrt_expr(arg: int, /) -> int .. py:method:: signpower_expr(arg0: int, arg1: int, /) -> int .. py:method:: tanh_expr(arg: int, /) -> int .. py:method:: if_then_else(arg0: int, arg1: int, arg2: int, /) -> int .. py:method:: at(arg0: int, arg1: int, /) -> int .. py:method:: count(arg: int, /) -> int .. py:method:: element(table: collections.abc.Sequence[float], index: int) -> int element(table: collections.abc.Sequence[collections.abc.Sequence[float]], row: int, col: int) -> int table[row][col] over a rectangular table; 0.0 when either index is out of range. .. py:method:: ceil_expr(x: int) -> int .. py:method:: floor_expr(x: int) -> int .. py:method:: round_expr(x: int) -> int round half away from zero, as C's round(). .. py:method:: leq(arg0: int, arg1: int, /) -> int .. py:method:: eq_expr(arg0: int, arg1: int, /) -> int .. py:method:: geq(arg0: int, arg1: int, /) -> int .. py:method:: neq(arg0: int, arg1: int, /) -> int .. py:method:: lt(arg0: int, arg1: int, /) -> int .. py:method:: gt(arg0: int, arg1: int, /) -> int .. py:method:: lambda_sum(list_var: int, func: collections.abc.Callable[[int], float]) -> int lambda_sum(list_var: int, func: collections.abc.Callable[[int, collections.abc.Sequence[float]], float], *, extra: collections.abc.Sequence[int]) -> int Sum `func(e, x)` over the elements of a List or Set variable, where `x` is the list of the CURRENT values of the `extra` handles, in order -- a per-element term that depends on other decisions, e.g. a stop cost by the route's vehicle type: `func=lambda i, x: c[i][int(x[0])]`. A change to any extra, or any edit to the list, re-sums the list. The node cannot be written to a .cbls file: the C++ save_model (not bound in Python) refuses the model. Every call re-acquires the GIL, as a plain lambda_sum's does. `extra` is keyword-only, here and in pair_lambda_sum, whose third positional parameter is already `cyclic`. .. py:method:: lambda_table_sum(list_var: int, table: Annotated[numpy.typing.NDArray[numpy.float64], dict(shape=(None, ), order='C', device='cpu', writable=False)]) -> int lambda_sum with the function given as a length-n float64 array over the variable's universe. Copied into the engine at node creation, so the search makes no Python call. .. py:method:: pair_lambda_sum(list_var: int, func: collections.abc.Callable[[int, int], float], cyclic: bool = False, head: collections.abc.Callable[[int], float] | None = None, tail: collections.abc.Callable[[int], float] | None = None) -> int pair_lambda_sum(list_var: int, func: collections.abc.Callable[[int, int, collections.abc.Sequence[float]], float], *, extra: collections.abc.Sequence[int], cyclic: bool = False) -> int Sum `func(e_k, e_{k+1}, x)` over consecutive pairs, `x` as in the extra form of lambda_sum. cyclic=True adds the closing pair when n >= 2. There are no head/tail terms in this form. `extra` is keyword-only. .. py:method:: pair_table_sum(list_var: int, dist: Annotated[numpy.typing.NDArray[numpy.float64], dict(shape=(None, None), order='C', device='cpu', writable=False)], cyclic: bool = False, head: Annotated[numpy.typing.NDArray[numpy.float64], dict(shape=(None, ), order='C', device='cpu', writable=False)] | None = None, tail: Annotated[numpy.typing.NDArray[numpy.float64], dict(shape=(None, ), order='C', device='cpu', writable=False)] | None = None) -> int pair_lambda_sum with the function given as a distance matrix. dist is an (n, n) float64 array over the variable's universe_size, and head/tail are length-n arrays. All are COPIED into the engine at node creation, so the search makes no Python call at all and resizing or freeing the caller's array afterwards is harmless. A wrong shape raises here rather than being read past. Copied once per MODEL, not once per process. ParallelSearch's Python entry points take a model factory, so a portfolio builds one Model -- and one copy of this matrix -- per worker: an (n, n) float64 table costs 8 * n * n bytes per thread. .. py:method:: add_constraint(arg: int, /) -> None add_constraint(arg: Expr, /) -> None .. py:method:: minimize(arg: int, /) -> None minimize(arg: Expr, /) -> None .. py:method:: maximize(arg: int, /) -> None maximize(arg: Expr, /) -> None .. py:method:: add_var_sequence(var_ids: collections.abc.Sequence[int], min_block_on: int = 1, min_block_off: int = 1) -> None .. py:method:: var_sequence_for(arg: int, /) -> tuple[int, int] .. py:method:: close() -> None .. py:method:: freeze(cone_cache_bytes: int = 268435456) -> None .. py:method:: is_frozen() -> bool .. py:method:: is_closed() -> bool .. py:method:: num_cached_cones() -> int .. py:method:: cone_cache_bytes() -> int .. py:method:: var(arg: int, /) -> Variable A handle to variable `id` of this model. It holds the model and the id, not a pointer into the model's storage, so it stays valid across builders and always reads the variable's current state. Keeps the model alive. var() and var_mut() return the same kind of handle. .. py:method:: var_mut(arg: int, /) -> Variable A handle to variable `id` of this model. It holds the model and the id, not a pointer into the model's storage, so it stays valid across builders and always reads the variable's current state. Keeps the model alive. var() and var_mut() return the same kind of handle. .. py:method:: node(arg: int, /) -> ExprNode A COPY of node `id`'s id and op -- neither ever changes once the node exists, so the copy cannot go stale. Its current value is Model.node_value(id). .. py:method:: node_value(id: int) -> float .. py:method:: objective_id() -> int .. py:method:: is_maximizing() -> bool .. py:method:: constraint_ids() -> list[int] .. py:method:: num_user_constraints() -> int .. py:method:: num_domain_rows() -> int .. py:method:: is_domain_node(id: int) -> bool .. py:method:: constraints_of_var(var_id: int) -> list[int] .. py:method:: per_constraint_violation_delta(var_id: int, j: float) -> list[tuple[int, float]] .. py:method:: num_vars() -> int .. py:method:: num_nodes() -> int .. py:method:: copy_state() -> ModelState .. py:method:: restore_state(arg: ModelState, /) -> None .. py:method:: Bool(name: str = '') -> Expr .. py:method:: Int(lb: int, ub: int, name: str = '') -> Expr .. py:method:: Float(lb: float, ub: float, name: str = '') -> Expr .. py:method:: List(n: int, name: str = '') -> Expr List(universe: int, min_len: int, max_len: int, init: ListInit = ListInit.Empty, name: str = '') -> Expr .. py:method:: Set(n: int, min_size: int = 0, max_size: int = -1, name: str = '') -> Expr .. py:method:: Constant(arg: float, /) -> Expr .. py:class:: ModelState .. py:property:: values :type: list[float] .. py:property:: elements :type: list[list[int]] .. py:class:: MpsProblem .. py:property:: name :type: str .. py:property:: objective_row_name :type: str .. py:property:: objective_offset :type: float .. py:property:: maximize :type: bool .. py:property:: num_vars :type: int .. py:property:: num_rows :type: int .. py:property:: num_nonzeros :type: int .. py:class:: MpsToModelOptions .. py:property:: inf_clamp :type: float .. py:property:: propagate_bounds :type: bool .. py:property:: max_propagation_passes :type: int .. py:class:: MpsToModelResult .. py:property:: model :type: Model .. py:property:: var_handles :type: list[int] .. py:property:: constraint_node_ids :type: list[int] .. py:property:: objective_node_id :type: int .. py:property:: bound_stats :type: BoundPropagationStats .. py:property:: n_clamped_columns :type: int .. py:method:: original_values() -> list[float] The model's current point as one value per source column. .. py:class:: NeighbourList NeighbourList(rows: collections.abc.Sequence[collections.abc.Sequence[int]]) .. py:method:: universe() -> int .. py:method:: neighbours_of(element: int) -> list[int] Element's neighbours, nearest first. Empty for an out-of-range element. .. py:property:: offsets :type: list[int] .. py:property:: ids :type: list[int] .. py:method:: __len__() -> int .. py:class:: NlProblem .. py:property:: name :type: str .. py:property:: n_vars :type: int .. py:property:: n_cons :type: int .. py:property:: n_objs :type: int .. py:property:: n_defined_vars :type: int .. py:property:: n_discrete_vars :type: int .. py:class:: NlToModelOptions .. py:property:: propagate_bounds :type: bool .. py:property:: max_propagation_passes :type: int .. py:property:: inf_clamp :type: float .. py:property:: int_inf_clamp :type: float .. py:class:: NlToModelResult .. py:property:: model :type: Model .. py:property:: var_handles :type: list[int] .. py:property:: constraint_node_ids :type: list[int] .. py:property:: objective_node_id :type: int .. py:property:: bound_stats :type: BoundPropagationStats .. py:property:: n_clamped_columns :type: int .. py:method:: original_values() -> list[float] The model's current point as one value per source column. .. py:property:: supported :type: bool .. py:property:: skipped_reasons :type: list[str] .. py:class:: NodeOp Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: Const :value: 0 .. py:attribute:: Neg :value: 1 .. py:attribute:: Sum :value: 2 .. py:attribute:: Prod :value: 3 .. py:attribute:: Div :value: 4 .. py:attribute:: Pow :value: 5 .. py:attribute:: Min :value: 6 .. py:attribute:: Max :value: 7 .. py:attribute:: Abs :value: 8 .. py:attribute:: Sin :value: 9 .. py:attribute:: Cos :value: 10 .. py:attribute:: If :value: 17 .. py:attribute:: At :value: 18 .. py:attribute:: Count :value: 19 .. py:attribute:: Lambda :value: 20 .. py:attribute:: PairLambda :value: 21 .. py:attribute:: Leq :value: 22 .. py:attribute:: Eq :value: 23 .. py:attribute:: Tan :value: 11 .. py:attribute:: Exp :value: 12 .. py:attribute:: Log :value: 13 .. py:attribute:: Sqrt :value: 14 .. py:attribute:: SignPower :value: 15 .. py:attribute:: Tanh :value: 16 .. py:attribute:: Geq :value: 24 .. py:attribute:: Neq :value: 25 .. py:attribute:: Lt :value: 26 .. py:attribute:: Gt :value: 27 .. py:attribute:: Element :value: 28 .. py:attribute:: Ceil :value: 29 .. py:attribute:: Floor :value: 30 .. py:attribute:: Round :value: 31 .. py:attribute:: LambdaExtra :value: 32 .. py:attribute:: PairLambdaExtra :value: 33 .. py:class:: SearchConfig .. py:method:: __copy__() -> SearchConfig .. py:property:: skip_init :type: bool .. py:property:: max_iterations :type: int .. py:property:: lns_interval :type: int .. py:property:: structural_batch_probability :type: float .. py:property:: use_compound_moves :type: bool .. py:property:: novelty_jump_probability :type: float .. py:property:: fpr_batch_probability :type: float .. py:property:: fpr_worker :type: int .. py:property:: lns_repair_fpr :type: bool .. py:property:: fpr_dag_propagation :type: bool .. py:property:: structural_selection :type: StructuralSelection .. py:property:: structural_sample_size :type: int .. py:property:: structural_neighbours :type: NeighbourList | None .. py:property:: feasibility_tolerance :type: float .. py:property:: cone_cache_bytes :type: int .. py:property:: fj_objective_tie_break :type: bool .. py:property:: diversify_workers :type: bool .. py:property:: float_start_jitter :type: float .. py:property:: stop :type: bool A cbls.StopToken whose request() ends this solve at its next batch boundary, or None. Reads back as a bool (whether one is attached). The token is kept alive by this config for as long as the config lives, which is what stops the C++ side reading a collected object. That tie only ACCUMULATES: a long-lived config assigned several tokens retains every one of them, and `config.stop = None` detaches the view but does not release the tie. Harmless -- it errs toward keeping objects alive -- but build a fresh SearchConfig per solve if that matters. .. py:class:: SearchCounters .. py:property:: batches :type: int .. py:property:: fj_batches :type: int .. py:property:: novelty_batches :type: int .. py:property:: novelty_moves :type: int .. py:property:: novelty_commits :type: int .. py:property:: novelty_weight_bumps :type: int .. py:property:: structural_batches :type: int .. py:property:: fpr_batches :type: int .. py:property:: fpr_setup_seconds :type: float .. py:property:: structural_moves_tried :type: int .. py:property:: structural_moves_accepted :type: int .. py:property:: by_generator :type: list[GeneratorCounters] .. py:property:: inner_solver_calls :type: int .. py:property:: inner_solver_seconds :type: float .. py:property:: inner_solver_infeasible_calls :type: int .. py:property:: portfolio_restarts :type: int .. py:property:: cone_cache_walks :type: int .. py:property:: cone_fallback_walks :type: int .. py:property:: shared_bound_tightenings :type: int .. py:property:: own_best_behind_global :type: int .. py:property:: bound_behind_global_batches :type: int .. py:property:: bound_behind_global_seconds :type: float .. py:class:: SearchResult .. py:property:: objective :type: float .. py:property:: feasible :type: bool .. py:property:: iterations :type: int .. py:property:: time_seconds :type: float .. py:property:: termination :type: TerminationReason .. py:property:: workers_launched :type: int .. py:property:: workers_completed :type: int .. py:property:: worker_failures :type: list[WorkerFailure] .. py:property:: counters :type: SearchCounters .. py:property:: best_state :type: ModelState .. py:class:: SolveCallback .. py:method:: on_progress(arg: SolveProgress, /) -> None .. py:class:: SolveProgress .. py:property:: iteration :type: int .. py:property:: time_seconds :type: float .. py:property:: objective :type: float .. py:property:: total_violation :type: float .. py:property:: feasible :type: bool .. py:property:: new_best :type: bool .. py:property:: perturbations :type: int .. py:class:: StopToken .. py:method:: request() -> None Ask the solve to stop. Safe to call from any thread, including while a solve is running -- which is the point: cbls.solve releases the GIL, so another Python thread can reach this. The run ends at its next batch boundary with termination == TerminationReason.Cancelled. .. py:method:: reset() -> None Clear the flag so the token can be reused. A solve does NOT reset it: handing the same raised token to the next solve cancels that one too. .. py:method:: requested() -> bool .. py:class:: StructuralSelection Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: FirstImprovingSample :value: 0 .. py:attribute:: BestOfSample :value: 1 .. py:attribute:: ViolationGuided :value: 2 .. py:attribute:: GranularBest :value: 3 .. py:attribute:: Auto :value: 4 .. py:class:: TerminationReason Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: TimeLimit :value: 0 .. py:attribute:: IterationLimit :value: 1 .. py:attribute:: Feasible :value: 2 .. py:attribute:: NoBudget :value: 3 .. py:attribute:: Stopped :value: 4 .. py:attribute:: Cancelled :value: 5 .. py:class:: Variable .. py:property:: id :type: int .. py:property:: type :type: VarType .. py:property:: value :type: float .. py:property:: lb :type: float .. py:property:: ub :type: float .. py:property:: name :type: str .. py:property:: elements :type: list[int] .. py:property:: universe_size :type: int .. py:property:: min_size :type: int .. py:property:: max_size :type: int .. py:property:: list_init :type: ListInit .. py:property:: partitioned :type: bool .. py:class:: VarType Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: Bool :value: 0 .. py:attribute:: Int :value: 1 .. py:attribute:: Float :value: 2 .. py:attribute:: List :value: 3 .. py:attribute:: Set :value: 4 .. py:class:: WorkerFailure .. py:property:: worker :type: int .. py:property:: produced_result :type: bool .. py:property:: reason :type: str .. py:function:: ceil(arg: Expr, /) -> Expr .. py:function:: cos(arg: Expr, /) -> Expr .. py:function:: element(table: collections.abc.Sequence[float], index: Expr) -> Expr element(table: collections.abc.Sequence[collections.abc.Sequence[float]], row: Expr, col: Expr) -> Expr .. py:function:: exp(arg: Expr, /) -> Expr .. py:function:: floor(arg: Expr, /) -> Expr .. py:function:: if_then_else(arg0: Expr, arg1: Expr, arg2: Expr, /) -> Expr .. py:function:: load_model(path: str) -> Model Read a .cbls (JSON lines) model file. .. py:function:: log(arg: Expr, /) -> Expr .. py:function:: mps_to_model(problem: MpsProblem, options: MpsToModelOptions = ...) -> MpsToModelResult Build a closed Model from a read_mps problem: one variable per column, one linear constraint per row. .. py:function:: nearest_neighbours(universe: int, k: int, cost: collections.abc.Callable[[int, int], float]) -> NeighbourList Each element's k nearest others under cost(a, b), nearest first, ties broken by ascending id. O(universe^2) cost calls, and `cost` is a Python callable invoked from C++, so this is a setup-time convenience for a universe of a few thousand. Build the rows yourself and use NeighbourList(rows) for anything larger. .. py:function:: nl_to_model(problem: NlProblem, options: NlToModelOptions = ...) -> NlToModelResult Build a Model from a read_nl problem. An unsupported operator does not raise: `supported` is False, `skipped_reasons` says why, and the model is not closed and must not be solved. .. py:function:: read_mps(filename: str) -> MpsProblem Read an MPS file, fixed or free format; `.gz` is decompressed. .. py:function:: read_nl(filename: str) -> NlProblem Read an AMPL .nl file, text or binary. .. py:function:: save_model(model: Model, path: str) -> None Write `model` as a .cbls (JSON lines) file. .. py:function:: sin(arg: Expr, /) -> Expr .. py:function:: sqrt(arg: Expr, /) -> Expr .. py:function:: tan(arg: Expr, /) -> Expr .. py:class:: SolveResult What `cbls.solve` returns: the engine's report and the best point found. `objective` is in the model's own sense, as the CLI prints it. The engine minimises, so a maximisation model's `search.objective`, its objective node's value and `SolveProgress.objective` are the negation (#472). An infeasible run reports +inf in either sense: nothing to report. A feasible point can carry ±inf too, an overflowed objective (#100): test `feasible`, then `math.isfinite`. `values[i]` and `elements[i]` belong to the variable with id `i`; the model itself is also left at that point. `search` is the full `SearchResult` (counters, portfolio worker accounting, `best_state`). .. py:attribute:: objective :type: float .. py:attribute:: feasible :type: bool .. py:attribute:: iterations :type: int .. py:attribute:: time_seconds :type: float .. py:attribute:: termination :type: cbls._cbls_core.TerminationReason .. py:attribute:: values :type: tuple[float, ...] .. py:attribute:: elements :type: tuple[tuple[int, ...], ...] .. py:attribute:: search :type: cbls._cbls_core.SearchResult .. py:method:: value(var: int | cbls._cbls_core.Expr | cbls._cbls_core.Variable) -> float The value of one variable: its handle, a variable `Expr` or a `Variable`. .. py:function:: solve(model: cbls._cbls_core.Model, time_limit: float = 10.0, seed: int = 42, threads: int = 0, lns: float | None = None, intensify: bool = False, callback: cbls._cbls_core.SolveCallback | None = None, stop: cbls._cbls_core.StopToken | None = None, config: cbls._cbls_core.SearchConfig | None = None) -> SolveResult Solve a closed `model`, as the `cbls` CLI does, with its defaults. `threads` 1 runs the single-threaded search, any other count the parallel portfolio (0: one worker per core). `lns` is the LNS destroy fraction (None: off); `intensify` adds the float intensification hook. `stop` is attached to a copy of `config` (a fresh `SearchConfig` when None), which also holds `lns_interval`. The model is left at the best point found, which the result also carries by variable id; a portfolio with no worker result (cancelled before one finished) leaves it at its start, as the CLI does. An unclosed model raises ValueError: `nl_to_model` leaves an unsupported one so. The result's objective is in the model's sense, but `callback` receives the engine's: negated for a maximisation model. The GIL is released while the search runs; see `cbls._cbls_core.solve` and `ParallelSearch.solve_master` for what that permits. cbls.__main__ ============= .. py:module:: cbls.__main__ .. autoapi-nested-parse:: The `cbls` console script and `python -m cbls`: src/cli.cpp over the module (#465). Same options, output and exit codes as the C++ CLI, through its own formatters and flag parsing (bound in `_cbls_core`). One difference: the model file may also be MPS (`.mps`, `.mps.gz`) or AMPL `.nl`, chosen by extension. Attributes ---------- .. autoapisummary:: cbls.__main__.HELP cbls.__main__._INT_MIN cbls.__main__._INT_MAX cbls.__main__._VALUE_FLAGS Exceptions ---------- .. autoapisummary:: cbls.__main__._UsageError cbls.__main__._LoadError Classes ------- .. autoapisummary:: cbls.__main__._Options cbls.__main__._TextSink Functions --------- .. autoapisummary:: cbls.__main__._out_of_range cbls.__main__._is_utf8 cbls.__main__._number cbls.__main__._integer cbls.__main__._int cbls.__main__._take_value cbls.__main__._parse_args cbls.__main__._load cbls.__main__._run cbls.__main__._default_signals cbls.__main__.main Module Contents --------------- .. py:data:: HELP :value: Multiline-String .. raw:: html
Show Value .. code-block:: python """Usage: cbls [OPTIONS] MODEL Constraint-Based Local Search solver. Reads a model file (.cbls JSONL, .mps, .mps.gz or AMPL .nl, by extension) and finds optimal or feasible variable assignments. Arguments: MODEL Path to the model file (.cbls, .mps, .mps.gz, .nl) Options: --time-limit SECS Maximum solve time in seconds (default: 10.0) --seed INT Random seed for reproducibility (default: 42) --lns FRACTION LNS destroy fraction, e.g. 0.3 (default: off) --lns-interval INT LNS fires every N diversification kicks (default: 3) --intensify Enable float intensification hook (default: off) --threads N Number of search threads (default: 0 = one per core) --format human|jsonl Output format (default: human) --quiet Print only the final result, no progress (default: off) --help Show this help message --version Show version number Exit status: 0 when a feasible point is found, else 1 (also on a bad argument or model) """ .. raw:: html
.. py:data:: _INT_MIN :value: -2147483648 .. py:data:: _INT_MAX :value: 2147483647 .. py:exception:: _UsageError Bases: :py:obj:`Exception` A malformed command line: `Error: `, exit 1. .. py:class:: _Options src/cli.cpp's CliOptions, with its defaults. .. py:attribute:: model_path :type: str :value: '' .. py:attribute:: time_limit :type: float :value: 10.0 .. py:attribute:: seed :type: int :value: 42 .. py:attribute:: intensify :type: bool :value: False .. py:attribute:: lns_fraction :type: float :value: 0.0 .. py:attribute:: config :type: cbls._cbls_core.SearchConfig .. py:attribute:: format :type: str :value: 'human' .. py:attribute:: quiet :type: bool :value: False .. py:attribute:: threads :type: int :value: 0 .. py:function:: _out_of_range(flag: str, text: str) -> _UsageError .. py:function:: _is_utf8(text: str) -> bool False for a POSIX argv's undecodable bytes (surrogateescape), which no binding takes. .. py:function:: _number(flag: str, text: str) -> float .. py:function:: _integer(flag: str, text: str, unsigned: bool = False) -> int .. py:function:: _int(flag: str, text: str) -> int .. py:function:: _take_value(opt: _Options, flag: str, text: str) -> None One `--flag VALUE` option, `flag` one of `_VALUE_FLAGS`. .. py:data:: _VALUE_FLAGS :value: ('--format', '--time-limit', '--seed', '--lns', '--lns-interval', '--threads') .. py:function:: _parse_args(argv: collections.abc.Sequence[str]) -> _Options | None The options, or None when --help or --version has been answered. As src/cli.cpp's loop: the last positional is the model, and a value flag with nothing after it is an unknown option. .. py:exception:: _LoadError Bases: :py:obj:`Exception` A model file that could not be read: `Error loading model: `. .. py:function:: _load(path: str) -> cbls._cbls_core.Model The model in `path`, read by its extension; anything else is .cbls, as the CLI. Case-sensitive, as read_mps's own `.gz` test (#465). .. py:class:: _TextSink(text: TextIO) The formatters' bytes into a text-only sys.stdout (a StringIO under redirect_stdout). .. py:attribute:: _text .. py:method:: write(data: bytes) -> None .. py:method:: flush() -> None .. py:function:: _run(opt: _Options) -> int .. py:function:: _default_signals() -> None SIGINT and SIGPIPE kill the process, as they do the C++ CLI. Python's SIGINT handler only sets a flag, which nothing reads while the search runs with the GIL released, so Ctrl-C would wait out the time limit; an ignored SIGPIPE turns `| head` into a BrokenPipeError. Only the main thread may set a handler. .. py:function:: main(argv: collections.abc.Sequence[str] | None = None) -> int Run the CLI on `argv`; returns the exit code. With no `argv` it is the process (the console script, `python -m cbls`): it reads sys.argv and takes the default SIGINT and SIGPIPE handling. cbls._cbls_core =============== .. py:module:: cbls._cbls_core .. autoapi-nested-parse:: CBLS: Constraint-Based Local Search engine (C++ core) Attributes ---------- .. autoapisummary:: cbls._cbls_core.version Classes ------- .. autoapisummary:: cbls._cbls_core.VarType cbls._cbls_core.NodeOp cbls._cbls_core.Variable cbls._cbls_core.ListInit cbls._cbls_core.Cover cbls._cbls_core.ListPartition cbls._cbls_core.ExprNode cbls._cbls_core.TerminationReason cbls._cbls_core.StopToken cbls._cbls_core.StructuralSelection cbls._cbls_core.NeighbourList cbls._cbls_core.BatchKind cbls._cbls_core.GeneratorCounters cbls._cbls_core.SearchCounters cbls._cbls_core.WorkerFailure cbls._cbls_core.SearchResult cbls._cbls_core.Model cbls._cbls_core.Expr cbls._cbls_core.ModelState cbls._cbls_core.ViolationManager cbls._cbls_core.RNG cbls._cbls_core.EditKind cbls._cbls_core.ElementEdit cbls._cbls_core.MoveChange cbls._cbls_core.Move cbls._cbls_core.SavedValues cbls._cbls_core.LNS cbls._cbls_core.Solution cbls._cbls_core.SolutionPool cbls._cbls_core.ParallelConfig cbls._cbls_core.SearchConfig cbls._cbls_core.ParallelSearch cbls._cbls_core.BoundPropagationStats cbls._cbls_core.MpsProblem cbls._cbls_core.MpsToModelOptions cbls._cbls_core.MpsToModelResult cbls._cbls_core.NlProblem cbls._cbls_core.NlToModelOptions cbls._cbls_core.NlToModelResult cbls._cbls_core.InnerSolverHook cbls._cbls_core.FloatIntensifyHook cbls._cbls_core.SolveProgress cbls._cbls_core.SolveCallback cbls._cbls_core.HumanFormatter cbls._cbls_core.JsonlFormatter Functions --------- .. autoapisummary:: cbls._cbls_core.nearest_neighbours cbls._cbls_core.sin cbls._cbls_core.cos cbls._cbls_core.tan cbls._cbls_core.exp cbls._cbls_core.log cbls._cbls_core.sqrt cbls._cbls_core.abs cbls._cbls_core.pow cbls._cbls_core.min cbls._cbls_core.max cbls._cbls_core.if_then_else cbls._cbls_core.ceil cbls._cbls_core.floor cbls._cbls_core.round cbls._cbls_core.element cbls._cbls_core.load_model cbls._cbls_core.save_model cbls._cbls_core.read_mps cbls._cbls_core.mps_to_model cbls._cbls_core.read_nl cbls._cbls_core.nl_to_model cbls._cbls_core.portfolio_worker_seed cbls._cbls_core.full_evaluate cbls._cbls_core.delta_evaluate cbls._cbls_core.compute_partial cbls._cbls_core.compute_all_partials cbls._cbls_core.generate_standard_moves cbls._cbls_core.apply_move cbls._cbls_core.save_move_values cbls._cbls_core.undo_move cbls._cbls_core._parse_double cbls._cbls_core._parse_int64 cbls._cbls_core._parse_uint64 cbls._cbls_core.solve cbls._cbls_core.initialize_random cbls._cbls_core.initialize_structured_random cbls._cbls_core.fj_nl_initialize Module Contents --------------- .. py:data:: version :type: str :value: '0.1.0' .. py:class:: VarType Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: Bool :value: 0 .. py:attribute:: Int :value: 1 .. py:attribute:: Float :value: 2 .. py:attribute:: List :value: 3 .. py:attribute:: Set :value: 4 .. py:class:: NodeOp Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: Const :value: 0 .. py:attribute:: Neg :value: 1 .. py:attribute:: Sum :value: 2 .. py:attribute:: Prod :value: 3 .. py:attribute:: Div :value: 4 .. py:attribute:: Pow :value: 5 .. py:attribute:: Min :value: 6 .. py:attribute:: Max :value: 7 .. py:attribute:: Abs :value: 8 .. py:attribute:: Sin :value: 9 .. py:attribute:: Cos :value: 10 .. py:attribute:: If :value: 17 .. py:attribute:: At :value: 18 .. py:attribute:: Count :value: 19 .. py:attribute:: Lambda :value: 20 .. py:attribute:: PairLambda :value: 21 .. py:attribute:: Leq :value: 22 .. py:attribute:: Eq :value: 23 .. py:attribute:: Tan :value: 11 .. py:attribute:: Exp :value: 12 .. py:attribute:: Log :value: 13 .. py:attribute:: Sqrt :value: 14 .. py:attribute:: SignPower :value: 15 .. py:attribute:: Tanh :value: 16 .. py:attribute:: Geq :value: 24 .. py:attribute:: Neq :value: 25 .. py:attribute:: Lt :value: 26 .. py:attribute:: Gt :value: 27 .. py:attribute:: Element :value: 28 .. py:attribute:: Ceil :value: 29 .. py:attribute:: Floor :value: 30 .. py:attribute:: Round :value: 31 .. py:attribute:: LambdaExtra :value: 32 .. py:attribute:: PairLambdaExtra :value: 33 .. py:class:: Variable .. py:property:: id :type: int .. py:property:: type :type: VarType .. py:property:: value :type: float .. py:property:: lb :type: float .. py:property:: ub :type: float .. py:property:: name :type: str .. py:property:: elements :type: list[int] .. py:property:: universe_size :type: int .. py:property:: min_size :type: int .. py:property:: max_size :type: int .. py:property:: list_init :type: ListInit .. py:property:: partitioned :type: bool .. py:class:: ListInit Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: Identity :value: 0 .. py:attribute:: Empty :value: 1 .. py:attribute:: Random :value: 2 .. py:class:: Cover Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: Exact :value: 0 .. py:attribute:: AtMostOnce :value: 1 .. py:class:: ListPartition .. py:property:: list_ids :type: list[int] .. py:property:: cover :type: Cover .. py:property:: universe_size :type: int .. py:class:: ExprNode .. py:property:: id :type: int .. py:property:: op :type: NodeOp .. py:class:: TerminationReason Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: TimeLimit :value: 0 .. py:attribute:: IterationLimit :value: 1 .. py:attribute:: Feasible :value: 2 .. py:attribute:: NoBudget :value: 3 .. py:attribute:: Stopped :value: 4 .. py:attribute:: Cancelled :value: 5 .. py:class:: StopToken .. py:method:: request() -> None Ask the solve to stop. Safe to call from any thread, including while a solve is running -- which is the point: cbls.solve releases the GIL, so another Python thread can reach this. The run ends at its next batch boundary with termination == TerminationReason.Cancelled. .. py:method:: reset() -> None Clear the flag so the token can be reused. A solve does NOT reset it: handing the same raised token to the next solve cancels that one too. .. py:method:: requested() -> bool .. py:class:: StructuralSelection Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: FirstImprovingSample :value: 0 .. py:attribute:: BestOfSample :value: 1 .. py:attribute:: ViolationGuided :value: 2 .. py:attribute:: GranularBest :value: 3 .. py:attribute:: Auto :value: 4 .. py:class:: NeighbourList NeighbourList(rows: collections.abc.Sequence[collections.abc.Sequence[int]]) .. py:method:: universe() -> int .. py:method:: neighbours_of(element: int) -> list[int] Element's neighbours, nearest first. Empty for an out-of-range element. .. py:property:: offsets :type: list[int] .. py:property:: ids :type: list[int] .. py:method:: __len__() -> int .. py:function:: nearest_neighbours(universe: int, k: int, cost: collections.abc.Callable[[int, int], float]) -> NeighbourList Each element's k nearest others under cost(a, b), nearest first, ties broken by ascending id. O(universe^2) cost calls, and `cost` is a Python callable invoked from C++, so this is a setup-time convenience for a universe of a few thousand. Build the rows yourself and use NeighbourList(rows) for anything larger. .. py:class:: BatchKind Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: FeasibilityJump :value: 0 .. py:attribute:: NoveltyJump :value: 1 .. py:attribute:: Structural :value: 2 .. py:attribute:: FixPropagateRepair :value: 3 .. py:class:: GeneratorCounters .. py:property:: name :type: str .. py:property:: moves_tried :type: int .. py:property:: moves_accepted :type: int .. py:class:: SearchCounters .. py:property:: batches :type: int .. py:property:: fj_batches :type: int .. py:property:: novelty_batches :type: int .. py:property:: novelty_moves :type: int .. py:property:: novelty_commits :type: int .. py:property:: novelty_weight_bumps :type: int .. py:property:: structural_batches :type: int .. py:property:: fpr_batches :type: int .. py:property:: fpr_setup_seconds :type: float .. py:property:: structural_moves_tried :type: int .. py:property:: structural_moves_accepted :type: int .. py:property:: by_generator :type: list[GeneratorCounters] .. py:property:: inner_solver_calls :type: int .. py:property:: inner_solver_seconds :type: float .. py:property:: inner_solver_infeasible_calls :type: int .. py:property:: portfolio_restarts :type: int .. py:property:: cone_cache_walks :type: int .. py:property:: cone_fallback_walks :type: int .. py:property:: shared_bound_tightenings :type: int .. py:property:: own_best_behind_global :type: int .. py:property:: bound_behind_global_batches :type: int .. py:property:: bound_behind_global_seconds :type: float .. py:class:: WorkerFailure .. py:property:: worker :type: int .. py:property:: produced_result :type: bool .. py:property:: reason :type: str .. py:class:: SearchResult .. py:property:: objective :type: float .. py:property:: feasible :type: bool .. py:property:: iterations :type: int .. py:property:: time_seconds :type: float .. py:property:: termination :type: TerminationReason .. py:property:: workers_launched :type: int .. py:property:: workers_completed :type: int .. py:property:: worker_failures :type: list[WorkerFailure] .. py:property:: counters :type: SearchCounters .. py:property:: best_state :type: ModelState .. py:class:: Model .. py:method:: bool_var(name: str = '') -> int .. py:method:: int_var(lb: int, ub: int, name: str = '') -> int .. py:method:: float_var(lb: float, ub: float, name: str = '') -> int .. py:method:: list_var(n: int, name: str = '') -> int list_var(universe: int, min_len: int, max_len: int, init: ListInit = ListInit.Empty, name: str = '') -> int An ordered sequence of distinct elements of {0..universe-1} whose length stays within [min_len, max_len]. .. py:method:: set_var(n: int, min_size: int = 0, max_size: int = -1, name: str = '') -> int .. py:method:: add_list_partition(lists: collections.abc.Sequence[int], cover: Cover = Cover.Exact) -> int add_list_partition(lists: collections.abc.Sequence[int], cover: str) -> int .. py:method:: partition_of_list(var_id: int) -> int Index into list_partitions() of the partition this variable id belongs to, or -1. Takes a var ID, not a handle. .. py:property:: list_partitions :type: list[ListPartition] .. py:method:: constant(arg: float, /) -> int .. py:method:: neg(arg: int, /) -> int .. py:method:: sum(arg: collections.abc.Sequence[int], /) -> int .. py:method:: prod(arg0: int, arg1: int, /) -> int .. py:method:: div_expr(arg0: int, arg1: int, /) -> int .. py:method:: pow_expr(arg0: int, arg1: int, /) -> int .. py:method:: min_expr(arg: collections.abc.Sequence[int], /) -> int .. py:method:: max_expr(arg: collections.abc.Sequence[int], /) -> int .. py:method:: abs_expr(arg: int, /) -> int .. py:method:: sin_expr(arg: int, /) -> int .. py:method:: cos_expr(arg: int, /) -> int .. py:method:: tan_expr(arg: int, /) -> int .. py:method:: exp_expr(arg: int, /) -> int .. py:method:: log_expr(arg: int, /) -> int .. py:method:: sqrt_expr(arg: int, /) -> int .. py:method:: signpower_expr(arg0: int, arg1: int, /) -> int .. py:method:: tanh_expr(arg: int, /) -> int .. py:method:: if_then_else(arg0: int, arg1: int, arg2: int, /) -> int .. py:method:: at(arg0: int, arg1: int, /) -> int .. py:method:: count(arg: int, /) -> int .. py:method:: element(table: collections.abc.Sequence[float], index: int) -> int element(table: collections.abc.Sequence[collections.abc.Sequence[float]], row: int, col: int) -> int table[row][col] over a rectangular table; 0.0 when either index is out of range. .. py:method:: ceil_expr(x: int) -> int .. py:method:: floor_expr(x: int) -> int .. py:method:: round_expr(x: int) -> int round half away from zero, as C's round(). .. py:method:: leq(arg0: int, arg1: int, /) -> int .. py:method:: eq_expr(arg0: int, arg1: int, /) -> int .. py:method:: geq(arg0: int, arg1: int, /) -> int .. py:method:: neq(arg0: int, arg1: int, /) -> int .. py:method:: lt(arg0: int, arg1: int, /) -> int .. py:method:: gt(arg0: int, arg1: int, /) -> int .. py:method:: lambda_sum(list_var: int, func: collections.abc.Callable[[int], float]) -> int lambda_sum(list_var: int, func: collections.abc.Callable[[int, collections.abc.Sequence[float]], float], *, extra: collections.abc.Sequence[int]) -> int Sum `func(e, x)` over the elements of a List or Set variable, where `x` is the list of the CURRENT values of the `extra` handles, in order -- a per-element term that depends on other decisions, e.g. a stop cost by the route's vehicle type: `func=lambda i, x: c[i][int(x[0])]`. A change to any extra, or any edit to the list, re-sums the list. The node cannot be written to a .cbls file: the C++ save_model (not bound in Python) refuses the model. Every call re-acquires the GIL, as a plain lambda_sum's does. `extra` is keyword-only, here and in pair_lambda_sum, whose third positional parameter is already `cyclic`. .. py:method:: lambda_table_sum(list_var: int, table: Annotated[numpy.typing.NDArray[numpy.float64], dict(shape=(None, ), order='C', device='cpu', writable=False)]) -> int lambda_sum with the function given as a length-n float64 array over the variable's universe. Copied into the engine at node creation, so the search makes no Python call. .. py:method:: pair_lambda_sum(list_var: int, func: collections.abc.Callable[[int, int], float], cyclic: bool = False, head: collections.abc.Callable[[int], float] | None = None, tail: collections.abc.Callable[[int], float] | None = None) -> int pair_lambda_sum(list_var: int, func: collections.abc.Callable[[int, int, collections.abc.Sequence[float]], float], *, extra: collections.abc.Sequence[int], cyclic: bool = False) -> int Sum `func(e_k, e_{k+1}, x)` over consecutive pairs, `x` as in the extra form of lambda_sum. cyclic=True adds the closing pair when n >= 2. There are no head/tail terms in this form. `extra` is keyword-only. .. py:method:: pair_table_sum(list_var: int, dist: Annotated[numpy.typing.NDArray[numpy.float64], dict(shape=(None, None), order='C', device='cpu', writable=False)], cyclic: bool = False, head: Annotated[numpy.typing.NDArray[numpy.float64], dict(shape=(None, ), order='C', device='cpu', writable=False)] | None = None, tail: Annotated[numpy.typing.NDArray[numpy.float64], dict(shape=(None, ), order='C', device='cpu', writable=False)] | None = None) -> int pair_lambda_sum with the function given as a distance matrix. dist is an (n, n) float64 array over the variable's universe_size, and head/tail are length-n arrays. All are COPIED into the engine at node creation, so the search makes no Python call at all and resizing or freeing the caller's array afterwards is harmless. A wrong shape raises here rather than being read past. Copied once per MODEL, not once per process. ParallelSearch's Python entry points take a model factory, so a portfolio builds one Model -- and one copy of this matrix -- per worker: an (n, n) float64 table costs 8 * n * n bytes per thread. .. py:method:: add_constraint(arg: int, /) -> None add_constraint(arg: Expr, /) -> None .. py:method:: minimize(arg: int, /) -> None minimize(arg: Expr, /) -> None .. py:method:: maximize(arg: int, /) -> None maximize(arg: Expr, /) -> None .. py:method:: add_var_sequence(var_ids: collections.abc.Sequence[int], min_block_on: int = 1, min_block_off: int = 1) -> None .. py:method:: var_sequence_for(arg: int, /) -> tuple[int, int] .. py:method:: close() -> None .. py:method:: freeze(cone_cache_bytes: int = 268435456) -> None .. py:method:: is_frozen() -> bool .. py:method:: is_closed() -> bool .. py:method:: num_cached_cones() -> int .. py:method:: cone_cache_bytes() -> int .. py:method:: var(arg: int, /) -> Variable A handle to variable `id` of this model. It holds the model and the id, not a pointer into the model's storage, so it stays valid across builders and always reads the variable's current state. Keeps the model alive. var() and var_mut() return the same kind of handle. .. py:method:: var_mut(arg: int, /) -> Variable A handle to variable `id` of this model. It holds the model and the id, not a pointer into the model's storage, so it stays valid across builders and always reads the variable's current state. Keeps the model alive. var() and var_mut() return the same kind of handle. .. py:method:: node(arg: int, /) -> ExprNode A COPY of node `id`'s id and op -- neither ever changes once the node exists, so the copy cannot go stale. Its current value is Model.node_value(id). .. py:method:: node_value(id: int) -> float .. py:method:: objective_id() -> int .. py:method:: is_maximizing() -> bool .. py:method:: constraint_ids() -> list[int] .. py:method:: num_user_constraints() -> int .. py:method:: num_domain_rows() -> int .. py:method:: is_domain_node(id: int) -> bool .. py:method:: constraints_of_var(var_id: int) -> list[int] .. py:method:: per_constraint_violation_delta(var_id: int, j: float) -> list[tuple[int, float]] .. py:method:: num_vars() -> int .. py:method:: num_nodes() -> int .. py:method:: copy_state() -> ModelState .. py:method:: restore_state(arg: ModelState, /) -> None .. py:method:: Bool(name: str = '') -> Expr .. py:method:: Int(lb: int, ub: int, name: str = '') -> Expr .. py:method:: Float(lb: float, ub: float, name: str = '') -> Expr .. py:method:: List(n: int, name: str = '') -> Expr List(universe: int, min_len: int, max_len: int, init: ListInit = ListInit.Empty, name: str = '') -> Expr .. py:method:: Set(n: int, min_size: int = 0, max_size: int = -1, name: str = '') -> Expr .. py:method:: Constant(arg: float, /) -> Expr .. py:class:: Expr .. py:property:: model :type: Model .. py:property:: handle :type: int .. py:method:: var_id() -> int .. py:method:: __add__(arg: Expr, /) -> Expr __add__(arg: float, /) -> Expr .. py:method:: __radd__(arg: float, /) -> Expr .. py:method:: __mul__(arg: Expr, /) -> Expr __mul__(arg: float, /) -> Expr .. py:method:: __rmul__(arg: float, /) -> Expr .. py:method:: __sub__(arg: Expr, /) -> Expr __sub__(arg: float, /) -> Expr .. py:method:: __rsub__(arg: float, /) -> Expr .. py:method:: __truediv__(arg: Expr, /) -> Expr __truediv__(arg: float, /) -> Expr .. py:method:: __rtruediv__(arg: float, /) -> Expr .. py:method:: __neg__() -> Expr .. py:method:: __pow__(arg: Expr, /) -> Expr __pow__(arg: int, /) -> Expr __pow__(arg: float, /) -> Expr .. py:method:: __rpow__(arg: float, /) -> Expr .. py:method:: __le__(arg: Expr, /) -> Expr __le__(arg: float, /) -> Expr .. py:method:: __ge__(arg: Expr, /) -> Expr __ge__(arg: float, /) -> Expr .. py:method:: __lt__(arg: Expr, /) -> Expr __lt__(arg: float, /) -> Expr .. py:method:: __gt__(arg: Expr, /) -> Expr __gt__(arg: float, /) -> Expr .. py:method:: __ceil__() -> Expr .. py:method:: __floor__() -> Expr .. py:method:: __round__(ndigits: int | None = None) -> Expr .. py:method:: __abs__() -> Expr .. py:method:: is_var() -> bool .. py:method:: eq(arg: Expr, /) -> Expr .. py:method:: neq(arg: Expr, /) -> Expr .. py:method:: pow(arg: Expr, /) -> Expr .. py:function:: sin(arg: Expr, /) -> Expr .. py:function:: cos(arg: Expr, /) -> Expr .. py:function:: tan(arg: Expr, /) -> Expr .. py:function:: exp(arg: Expr, /) -> Expr .. py:function:: log(arg: Expr, /) -> Expr .. py:function:: sqrt(arg: Expr, /) -> Expr .. py:function:: abs(arg: Expr, /) -> Expr .. py:function:: pow(arg0: Expr, arg1: Expr, /) -> Expr .. py:function:: min(arg: collections.abc.Sequence[Expr], /) -> Expr .. py:function:: max(arg: collections.abc.Sequence[Expr], /) -> Expr .. py:function:: if_then_else(arg0: Expr, arg1: Expr, arg2: Expr, /) -> Expr .. py:function:: ceil(arg: Expr, /) -> Expr .. py:function:: floor(arg: Expr, /) -> Expr .. py:function:: round(arg: Expr, /) -> Expr .. py:function:: element(table: collections.abc.Sequence[float], index: Expr) -> Expr element(table: collections.abc.Sequence[collections.abc.Sequence[float]], row: Expr, col: Expr) -> Expr .. py:class:: ModelState .. py:property:: values :type: list[float] .. py:property:: elements :type: list[list[int]] .. py:class:: ViolationManager(arg: Model, /) .. py:method:: constraint_violation(arg: int, /) -> float .. py:method:: total_violation() -> float .. py:method:: augmented_objective() -> float .. py:method:: is_feasible(tol: float = 1e-06) -> bool .. py:method:: violated_constraints(tol: float = 1e-06) -> list[int] .. py:method:: bump_weights(factor: float = 1.0) -> None .. py:method:: weighted_violation_delta(var_id: int, j: float) -> float .. py:method:: invalidate_cache() -> None .. py:property:: weights :type: list[float] .. py:class:: RNG(seed: int = 42) .. py:method:: uniform(arg0: float, arg1: float, /) -> float .. py:method:: integers(arg0: int, arg1: int, /) -> int .. py:method:: normal(arg0: float, arg1: float, /) -> float .. py:method:: random() -> float .. py:method:: seed() -> int .. py:class:: EditKind Bases: :py:obj:`enum.Enum` Create a collection of name/value pairs. Example enumeration: >>> class Color(Enum): ... RED = 1 ... BLUE = 2 ... GREEN = 3 Access them by: - attribute access: >>> Color.RED - value lookup: >>> Color(1) - name lookup: >>> Color['RED'] Enumerations can be iterated over, and know how many members they have: >>> len(Color) 3 >>> list(Color) [, , ] Methods can be added to enumerations, and members can have their own attributes -- see the documentation for details. .. py:attribute:: None_ :value: 0 .. py:attribute:: Replace :value: 1 .. py:attribute:: Swap :value: 2 .. py:attribute:: Reverse :value: 3 .. py:attribute:: MoveSegment :value: 4 .. py:attribute:: Insert :value: 5 .. py:attribute:: Erase :value: 6 .. py:attribute:: Assign :value: 7 .. py:class:: ElementEdit .. py:property:: kind :type: EditKind .. py:property:: from_pos :type: int .. py:property:: to_pos :type: int .. py:property:: length :type: int .. py:property:: element :type: int .. py:class:: MoveChange .. py:property:: var_id :type: int .. py:property:: new_value :type: float .. py:property:: edits :type: list[ElementEdit] .. py:property:: replacement :type: list[int] .. py:method:: elements_after(elements: collections.abc.Sequence[int]) -> list[int] The elements this change produces from `elements` -- the absolute vector a change carried before #164. The engine edits in place. .. py:method:: is_noop(elements: collections.abc.Sequence[int]) -> bool .. py:class:: Move .. py:property:: changes :type: list[MoveChange] .. py:property:: move_type :type: str .. py:property:: delta_F :type: float .. py:class:: SavedValues .. py:property:: values :type: list[float] .. py:property:: elements :type: list[list[int]] .. py:class:: LNS(destroy_fraction: float = 0.3) .. py:method:: destroy_repair(model: Model, vm: ViolationManager, rng: RNG, repair_time_limit: float = 2.0) -> bool .. py:method:: destroy_repair_cycle(model: Model, vm: ViolationManager, rng: RNG, n_rounds: int = 10, repair_time_limit: float = 2.0) -> int .. py:class:: Solution .. py:property:: state :type: ModelState .. py:property:: objective :type: float .. py:property:: feasible :type: bool .. py:property:: violation :type: float .. py:class:: SolutionPool(capacity: int = 10) .. py:method:: submit(arg: Solution, /) -> bool .. py:method:: best() -> Solution | None .. py:method:: top_k(arg: int, /) -> list[Solution] .. py:method:: size() -> int .. py:method:: best_feasible_objective() -> float .. py:class:: ParallelConfig .. py:property:: n_threads :type: int .. py:property:: pool_capacity :type: int .. py:property:: share_objective_bound :type: bool .. py:property:: stop :type: bool A cbls.StopToken whose request() cancels every worker, or None. Reads back as a bool (whether one is attached), not as the token: the C++ side holds a view, not the object. Same accumulating keep-alive as SearchConfig.stop -- see its docstring. .. py:class:: SearchConfig .. py:method:: __copy__() -> SearchConfig .. py:property:: skip_init :type: bool .. py:property:: max_iterations :type: int .. py:property:: lns_interval :type: int .. py:property:: structural_batch_probability :type: float .. py:property:: use_compound_moves :type: bool .. py:property:: novelty_jump_probability :type: float .. py:property:: fpr_batch_probability :type: float .. py:property:: fpr_worker :type: int .. py:property:: lns_repair_fpr :type: bool .. py:property:: fpr_dag_propagation :type: bool .. py:property:: structural_selection :type: StructuralSelection .. py:property:: structural_sample_size :type: int .. py:property:: structural_neighbours :type: NeighbourList | None .. py:property:: feasibility_tolerance :type: float .. py:property:: cone_cache_bytes :type: int .. py:property:: fj_objective_tie_break :type: bool .. py:property:: diversify_workers :type: bool .. py:property:: float_start_jitter :type: float .. py:property:: stop :type: bool A cbls.StopToken whose request() ends this solve at its next batch boundary, or None. Reads back as a bool (whether one is attached). The token is kept alive by this config for as long as the config lives, which is what stops the C++ side reading a collected object. That tie only ACCUMULATES: a long-lived config assigned several tokens retains every one of them, and `config.stop = None` detaches the view but does not release the tie. Harmless -- it errs toward keeping objects alive -- but build a fresh SearchConfig per solve if that matters. .. py:class:: ParallelSearch(n_threads: int = 0) .. py:method:: solve(model_factory: collections.abc.Callable[[], Model], time_limit: float = 10.0, seed: int = 42) -> SearchResult Run the parallel search and return the best result the workers found. The GIL is released for the duration of the C++ call, which is what makes this callable at all: the workers have to acquire the GIL to invoke a Python callable, and a caller holding it across the join deadlocks them. model_factory is invoked ONCE PER WORKER -- not once per restart -- each from that worker's own thread, so several calls are in flight at once. A progress callback is called from EVERY worker, serialized on one mutex inside the portfolio: rows arrive one at a time and in order, but on whichever worker thread produced them, and a slow callback throttles every worker rather than only its own. nanobind re-acquires the GIL around every invocation, so the interpreter itself is safe; what that does not give you is atomicity across bytecodes, so a callable that mutates Python-side state must lock it. `solve_parallel` accepts a Python hook_factory and lns_factory. Both are invoked once per worker, on that worker's own thread, immediately after model_factory. Both return a shared_ptr, so the C++ side shares ownership with the interpreter instead of adopting a pointer Python still owns (issue #129). The last reference is dropped before solve_parallel returns, under the GIL, at the end of the worker that built it. Return a FRESH object from every call. Each worker searches its own model on its own thread and the search never locks the hook or the LNS, so one shared instance that carries state is a data race. The old raw-pointer signature caught that as a double free; a shared_ptr accepts it silently. A FROZEN Model is the one sanctioned exception, and the way to avoid duplicating a large DAG per worker (#157). model_factory is declared to return a Model by value, so nanobind COPIES whatever object it hands back -- and copying a frozen model shares its immutable structure while giving the worker its own variables, node values and objective bound. So `m.freeze()` once and `lambda: m` is correct here, where returning a shared MUTABLE model would not be: `freeze()` is what makes the shared half unwritable, and every structural call on it raises instead. What a Python factory can usefully return is NARROW. Neither InnerSolverHook nor LNS has a nanobind trampoline, so C++ dispatches through the base vtable: a Python subclass is constructed and released correctly, but an override of `solve` or `destroy_repair` is never called. The two fail differently, and the second is the trap. `solve` is not bound at all, so a Python `solve` is merely a new attribute nothing reads. `LNS.destroy_repair` IS bound, so an override does shadow it when called from Python -- and silently does not when the search calls it from C++. In practice these arguments buy a separately configured FloatIntensifyHook or LNS per worker, not a Python implementation of either. InnerSolverHook itself is abstract and exposes no constructor. The Model handed to hook_factory is a COPY of the worker's model, not a handle on it: nanobind casts an lvalue reference by copying. Mutating it changes nothing the worker will search. What that copy costs depends on the model: a FROZEN one shares its structure, so the copy is the variables and the node values; an open one is deep-copied whole, once per worker (#157). An exception raised by the factory in every worker is re-raised here with its original type and message, while one that fails in only some workers is absorbed and the survivors' result is returned. An exception raised by the progress callback's on_progress ends the solve of the worker that made the call -- NOT the portfolio. That worker is restarted, and stops after three consecutive failed attempts, or earlier when the time limit runs out or a peer settles a model that has no objective. A worker that stops that way without ever completing an attempt has FAILED. An exception is re-raised here -- the original object, with its type, message and traceback; the lowest-numbered failed worker's last one -- only if every worker failed, or if some worker failed and no worker returned or shared any result, feasible or not. Otherwise it is DISCARDED, with nothing reported, and the best result found is returned. That includes a failed worker's incumbents shared before it died, and a worker that raised after completing an attempt (SearchConfig.max_iterations makes that possible), which does not count as failed. Which workers call the callback at all depends on timing: a worker other than the first reports only a new portfolio-wide best, so a callback that raises on every call may kill the first worker alone and let the run return normally -- after which the periodic no-improvement rows, which only the first worker sends, stop. Raising is therefore not a way to stop a run; catch inside on_progress if a failure there must be seen. (The module-level, single-threaded cbls.solve differs: there a raising callback ends the search and the exception propagates at once.) .. py:method:: solve_parallel(model_factory: collections.abc.Callable[[], Model], time_limit: float = 10.0, seed: int = 42, config: SearchConfig = ..., hook_factory: collections.abc.Callable[[Model], InnerSolverHook] | None = None, lns_factory: collections.abc.Callable[[], LNS] | None = None, callback: SolveCallback | None = None, par_config: ParallelConfig = ...) -> SearchResult Run the parallel search and return the best result the workers found. The GIL is released for the duration of the C++ call, which is what makes this callable at all: the workers have to acquire the GIL to invoke a Python callable, and a caller holding it across the join deadlocks them. model_factory is invoked ONCE PER WORKER -- not once per restart -- each from that worker's own thread, so several calls are in flight at once. A progress callback is called from EVERY worker, serialized on one mutex inside the portfolio: rows arrive one at a time and in order, but on whichever worker thread produced them, and a slow callback throttles every worker rather than only its own. nanobind re-acquires the GIL around every invocation, so the interpreter itself is safe; what that does not give you is atomicity across bytecodes, so a callable that mutates Python-side state must lock it. `solve_parallel` accepts a Python hook_factory and lns_factory. Both are invoked once per worker, on that worker's own thread, immediately after model_factory. Both return a shared_ptr, so the C++ side shares ownership with the interpreter instead of adopting a pointer Python still owns (issue #129). The last reference is dropped before solve_parallel returns, under the GIL, at the end of the worker that built it. Return a FRESH object from every call. Each worker searches its own model on its own thread and the search never locks the hook or the LNS, so one shared instance that carries state is a data race. The old raw-pointer signature caught that as a double free; a shared_ptr accepts it silently. A FROZEN Model is the one sanctioned exception, and the way to avoid duplicating a large DAG per worker (#157). model_factory is declared to return a Model by value, so nanobind COPIES whatever object it hands back -- and copying a frozen model shares its immutable structure while giving the worker its own variables, node values and objective bound. So `m.freeze()` once and `lambda: m` is correct here, where returning a shared MUTABLE model would not be: `freeze()` is what makes the shared half unwritable, and every structural call on it raises instead. What a Python factory can usefully return is NARROW. Neither InnerSolverHook nor LNS has a nanobind trampoline, so C++ dispatches through the base vtable: a Python subclass is constructed and released correctly, but an override of `solve` or `destroy_repair` is never called. The two fail differently, and the second is the trap. `solve` is not bound at all, so a Python `solve` is merely a new attribute nothing reads. `LNS.destroy_repair` IS bound, so an override does shadow it when called from Python -- and silently does not when the search calls it from C++. In practice these arguments buy a separately configured FloatIntensifyHook or LNS per worker, not a Python implementation of either. InnerSolverHook itself is abstract and exposes no constructor. The Model handed to hook_factory is a COPY of the worker's model, not a handle on it: nanobind casts an lvalue reference by copying. Mutating it changes nothing the worker will search. What that copy costs depends on the model: a FROZEN one shares its structure, so the copy is the variables and the node values; an open one is deep-copied whole, once per worker (#157). An exception raised by the factory in every worker is re-raised here with its original type and message, while one that fails in only some workers is absorbed and the survivors' result is returned. An exception raised by the progress callback's on_progress ends the solve of the worker that made the call -- NOT the portfolio. That worker is restarted, and stops after three consecutive failed attempts, or earlier when the time limit runs out or a peer settles a model that has no objective. A worker that stops that way without ever completing an attempt has FAILED. An exception is re-raised here -- the original object, with its type, message and traceback; the lowest-numbered failed worker's last one -- only if every worker failed, or if some worker failed and no worker returned or shared any result, feasible or not. Otherwise it is DISCARDED, with nothing reported, and the best result found is returned. That includes a failed worker's incumbents shared before it died, and a worker that raised after completing an attempt (SearchConfig.max_iterations makes that possible), which does not count as failed. Which workers call the callback at all depends on timing: a worker other than the first reports only a new portfolio-wide best, so a callback that raises on every call may kill the first worker alone and let the run return normally -- after which the periodic no-improvement rows, which only the first worker sends, stop. Raising is therefore not a way to stop a run; catch inside on_progress if a failure there must be seen. (The module-level, single-threaded cbls.solve differs: there a raising callback ends the search and the exception propagates at once.) .. py:method:: solve_master(model: Model, time_limit: float = 10.0, seed: int = 42, config: SearchConfig = ..., hook_factory: collections.abc.Callable[[Model], InnerSolverHook] | None = None, lns_factory: collections.abc.Callable[[], LNS] | None = None, callback: SolveCallback | None = None, par_config: ParallelConfig = ...) -> SearchResult Run the parallel search on ONE model and return the best result. The C++ `Model& master` entry point, which the factory forms cannot reach. `model` is FROZEN on this thread first and each worker searches a copy that shares its immutable structure (#157), so the model comes back frozen: build any further structure before calling this. hook_factory, lns_factory, callback and par_config behave as in solve_parallel (see there, including that hook_factory is handed a COPY of its worker's model, the GIL release and the exception contract). While this runs, structural writes to `model` from Python -- builders, close, freeze -- raise RuntimeError, as under cbls.solve. .. py:function:: load_model(path: str) -> Model Read a .cbls (JSON lines) model file. .. py:function:: save_model(model: Model, path: str) -> None Write `model` as a .cbls (JSON lines) file. .. py:class:: BoundPropagationStats .. py:property:: passes :type: int .. py:property:: n_tightened :type: int .. py:property:: n_finitized :type: int .. py:property:: n_fixed :type: int .. py:property:: infeasible :type: bool .. py:property:: hit_pass_limit :type: bool .. py:class:: MpsProblem .. py:property:: name :type: str .. py:property:: objective_row_name :type: str .. py:property:: objective_offset :type: float .. py:property:: maximize :type: bool .. py:property:: num_vars :type: int .. py:property:: num_rows :type: int .. py:property:: num_nonzeros :type: int .. py:function:: read_mps(filename: str) -> MpsProblem Read an MPS file, fixed or free format; `.gz` is decompressed. .. py:class:: MpsToModelOptions .. py:property:: inf_clamp :type: float .. py:property:: propagate_bounds :type: bool .. py:property:: max_propagation_passes :type: int .. py:class:: MpsToModelResult .. py:property:: model :type: Model .. py:property:: var_handles :type: list[int] .. py:property:: constraint_node_ids :type: list[int] .. py:property:: objective_node_id :type: int .. py:property:: bound_stats :type: BoundPropagationStats .. py:property:: n_clamped_columns :type: int .. py:method:: original_values() -> list[float] The model's current point as one value per source column. .. py:function:: mps_to_model(problem: MpsProblem, options: MpsToModelOptions = ...) -> MpsToModelResult Build a closed Model from a read_mps problem: one variable per column, one linear constraint per row. .. py:class:: NlProblem .. py:property:: name :type: str .. py:property:: n_vars :type: int .. py:property:: n_cons :type: int .. py:property:: n_objs :type: int .. py:property:: n_defined_vars :type: int .. py:property:: n_discrete_vars :type: int .. py:function:: read_nl(filename: str) -> NlProblem Read an AMPL .nl file, text or binary. .. py:class:: NlToModelOptions .. py:property:: propagate_bounds :type: bool .. py:property:: max_propagation_passes :type: int .. py:property:: inf_clamp :type: float .. py:property:: int_inf_clamp :type: float .. py:class:: NlToModelResult .. py:property:: model :type: Model .. py:property:: var_handles :type: list[int] .. py:property:: constraint_node_ids :type: list[int] .. py:property:: objective_node_id :type: int .. py:property:: bound_stats :type: BoundPropagationStats .. py:property:: n_clamped_columns :type: int .. py:method:: original_values() -> list[float] The model's current point as one value per source column. .. py:property:: supported :type: bool .. py:property:: skipped_reasons :type: list[str] .. py:function:: nl_to_model(problem: NlProblem, options: NlToModelOptions = ...) -> NlToModelResult Build a Model from a read_nl problem. An unsupported operator does not raise: `supported` is False, `skipped_reasons` says why, and the model is not closed and must not be solved. .. py:function:: portfolio_worker_seed(base_seed: int, worker: int, restart: int) -> int RNG seed for one portfolio worker's one run: a splitmix64 finalizer over (base_seed, worker, restart). Mixed rather than added so that adjacent base seeds give genuinely different portfolios. .. py:function:: full_evaluate(arg: Model, /) -> float .. py:function:: delta_evaluate(arg0: Model, arg1: collections.abc.Set[int], /) -> float .. py:function:: compute_partial(arg0: Model, arg1: int, arg2: int, /) -> float .. py:function:: compute_all_partials(arg0: Model, arg1: int, /) -> list[float] .. py:function:: generate_standard_moves(arg0: Variable, arg1: RNG, /) -> list[Move] .. py:function:: apply_move(arg0: Model, arg1: Move, /) -> list[int] .. py:function:: save_move_values(arg0: Model, arg1: Move, /) -> SavedValues .. py:function:: undo_move(arg0: Model, arg1: Move, arg2: SavedValues, /) -> None .. py:class:: InnerSolverHook .. py:class:: FloatIntensifyHook Bases: :py:obj:`InnerSolverHook` .. py:property:: max_sweeps :type: int .. py:property:: initial_step_size :type: float .. py:property:: max_line_search_steps :type: int .. py:property:: max_multi_var_constraints :type: int .. py:class:: SolveProgress .. py:property:: iteration :type: int .. py:property:: time_seconds :type: float .. py:property:: objective :type: float .. py:property:: total_violation :type: float .. py:property:: feasible :type: bool .. py:property:: new_best :type: bool .. py:property:: perturbations :type: int .. py:class:: SolveCallback .. py:method:: on_progress(arg: SolveProgress, /) -> None .. py:class:: HumanFormatter(stream: object) Bases: :py:obj:`SolveCallback` The `cbls` CLI's human format as a SolveCallback, written as bytes to the binary `stream` (write and flush), such as sys.stdout.buffer. .. py:method:: print_header(model_path: str, model: Model, seed: int, time_limit: float) -> None .. py:method:: print_result(result: SearchResult, model: Model) -> None .. py:class:: JsonlFormatter(stream: object) Bases: :py:obj:`SolveCallback` The `cbls` CLI's JSON-lines format as a SolveCallback, written as bytes to the binary `stream` (write and flush), such as sys.stdout.buffer. .. py:method:: print_header(model_path: str, model: Model, seed: int, time_limit: float) -> None .. py:method:: print_result(result: SearchResult, model: Model) -> None .. py:function:: _parse_double(text: str) -> tuple[str, float] .. py:function:: _parse_int64(text: str) -> tuple[str, int] .. py:function:: _parse_uint64(text: str) -> tuple[str, int] .. py:function:: solve(model: Model, time_limit: float = 10.0, seed: int = 42, hook: InnerSolverHook | None = None, lns: LNS | None = None, lns_interval: int = 3, callback: SolveCallback | None = None, config: SearchConfig = ...) -> SearchResult Single-threaded solve. The GIL is RELEASED for the whole C++ call (#169). That is what lets another Python thread raise a cbls.StopToken mid-solve -- and it makes touching `model` from another thread while this runs a DATA RACE: the search writes variables and node values throughout and nothing locks them. Read the model only after this returns. STRUCTURAL writes to `model` -- its builders, close, freeze and Expr operators over it -- raise RuntimeError while this runs, from any thread, a SolveCallback included. A raw Python function passed to lambda_sum or pair_lambda_sum also re-acquires the GIL on every evaluation now; use the lambda_table_sum or pair_table_sum forms where the function is a table. An exception raised by callback.on_progress ends the search and propagates out of this call unchanged -- no result is returned, and the model is left at the assignment the search had reached -- with its internal objective bound still tightened if a feasible point had been found (the next solve resets it). (ParallelSearch.solve_parallel absorbs one instead unless every worker fails, or a worker fails and no worker returned any result; see its docstring.) NOTE: a Python subclass of InnerSolverHook or LNS is constructed and destroyed correctly, but its overrides are never called -- neither class has a nanobind trampoline, so C++ dispatches through the base vtable. These arguments configure the built-in classes; they do not let you implement one in Python. .. py:function:: initialize_random(model: Model, rng: RNG) -> None .. py:function:: initialize_structured_random(model: Model, rng: RNG) -> None .. py:function:: fj_nl_initialize(model: Model, vm: ViolationManager, max_iterations: int = 10000, rng: RNG | None = None, time_limit: float = 2.0, tolerance: float = 1e-06) -> int cbls._solve =========== .. py:module:: cbls._solve .. autoapi-nested-parse:: `cbls.solve`: the C++ CLI's solve as one call (#464). Classes ------- .. autoapisummary:: cbls._solve.SolveResult Functions --------- .. autoapisummary:: cbls._solve._variable_id cbls._solve._effective_threads cbls._solve._search_config cbls._solve.solve cbls._solve._solve_parallel cbls._solve._user_objective cbls._solve._result Module Contents --------------- .. py:class:: SolveResult What `cbls.solve` returns: the engine's report and the best point found. `objective` is in the model's own sense, as the CLI prints it. The engine minimises, so a maximisation model's `search.objective`, its objective node's value and `SolveProgress.objective` are the negation (#472). An infeasible run reports +inf in either sense: nothing to report. A feasible point can carry ±inf too, an overflowed objective (#100): test `feasible`, then `math.isfinite`. `values[i]` and `elements[i]` belong to the variable with id `i`; the model itself is also left at that point. `search` is the full `SearchResult` (counters, portfolio worker accounting, `best_state`). .. py:attribute:: objective :type: float .. py:attribute:: feasible :type: bool .. py:attribute:: iterations :type: int .. py:attribute:: time_seconds :type: float .. py:attribute:: termination :type: cbls._cbls_core.TerminationReason .. py:attribute:: values :type: tuple[float, ...] .. py:attribute:: elements :type: tuple[tuple[int, ...], ...] .. py:attribute:: search :type: cbls._cbls_core.SearchResult .. py:method:: value(var: int | cbls._cbls_core.Expr | cbls._cbls_core.Variable) -> float The value of one variable: its handle, a variable `Expr` or a `Variable`. .. py:function:: _variable_id(var: int | cbls._cbls_core.Expr | cbls._cbls_core.Variable) -> int .. py:function:: _effective_threads(threads: int) -> int `--threads`: 0 is one per core, as `std::thread::hardware_concurrency`. .. py:function:: _search_config(config: cbls._cbls_core.SearchConfig | None, stop: cbls._cbls_core.StopToken | None) -> cbls._cbls_core.SearchConfig `config` with `stop` attached to a copy: the caller's config is never changed. .. py:function:: solve(model: cbls._cbls_core.Model, time_limit: float = 10.0, seed: int = 42, threads: int = 0, lns: float | None = None, intensify: bool = False, callback: cbls._cbls_core.SolveCallback | None = None, stop: cbls._cbls_core.StopToken | None = None, config: cbls._cbls_core.SearchConfig | None = None) -> SolveResult Solve a closed `model`, as the `cbls` CLI does, with its defaults. `threads` 1 runs the single-threaded search, any other count the parallel portfolio (0: one worker per core). `lns` is the LNS destroy fraction (None: off); `intensify` adds the float intensification hook. `stop` is attached to a copy of `config` (a fresh `SearchConfig` when None), which also holds `lns_interval`. The model is left at the best point found, which the result also carries by variable id; a portfolio with no worker result (cancelled before one finished) leaves it at its start, as the CLI does. An unclosed model raises ValueError: `nl_to_model` leaves an unsupported one so. The result's objective is in the model's sense, but `callback` receives the engine's: negated for a maximisation model. The GIL is released while the search runs; see `cbls._cbls_core.solve` and `ParallelSearch.solve_master` for what that permits. .. py:function:: _solve_parallel(model: cbls._cbls_core.Model, time_limit: float, seed: int, n_threads: int, lns: float | None, intensify: bool, callback: cbls._cbls_core.SolveCallback | None, config: cbls._cbls_core.SearchConfig) -> cbls._cbls_core.SearchResult The CLI's portfolio path; the winner is restored into `model`. .. py:function:: _user_objective(model: cbls._cbls_core.Model, internal: float, feasible: bool) -> float `internal` in the model's sense. An infeasible run's +inf is "nothing to report" and stays; a feasible point's, finite or overflowed (#100), flips. .. py:function:: _result(model: cbls._cbls_core.Model, result: cbls._cbls_core.SearchResult) -> SolveResult ***************** Source Code Files ***************** This section contains source code files from the project repository. These files are included to provide implementation context and technical details that complement the documentation above. **Files included:** .. code-block:: text README.md audit.h cbls.h counters.h dag.h dag_ops.h executor.h expr.h feasibility_jump.h formatter.h inner_solver.h io.h io_mps.h io_nl.h lns.h model.h move_generator.h moves.h nlp_polish.h pool.h randomize.h rng.h search.h stop.h tracer.h verify.h violation.h README.md ========= .. code-block:: markdown # cbls *Constraint-based local search* [![Docs](https://img.shields.io/badge/docs-spoorendonk.dk%2Fcbls-b45309)](https://spoorendonk.dk/cbls/) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24758098.svg)](https://doi.org/10.5281/zenodo.24758098) [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](https://github.com/spoorendonk/cbls/blob/main/LICENSE) A constraint-based local search engine for small-to-medium mixed discrete-continuous models whose terms an exact MIP or CP solver cannot take as written: non-convex, transcendental or discontinuous ones. It moves variables, mostly one at a time, to lower the weighted violation of the constraints, weights the ones that stay violated more, and treats the objective as one more constraint that tightens at each solution found: ViolationLS (Davies et al., CPAIOR 2024), over an expression DAG. It comes as a C++17 library, a command-line solver and a Python module. Left, a small model as an expression DAG, with the cone one variable move re-evaluates highlighted. Right, the search loop of batches, feasibility checks and kicks. *Left: a model's expression DAG; moving `y` re-evaluates the amber nodes only. Right: the search loop, with the steps a solve runs only when asked.* ## Problem $$ \begin{aligned} \min_x\ & f(x) \\ \text{s.t.}\ & g_i(x) \le 0, && i \in I, \\ & h_j(x) = 0, && j \in J, \\ & x_k \in D_k, && k \in K. \end{aligned} $$ Each $D_k$ is Bool, Int or Float (a range), List (an ordered sequence of distinct elements of $\lbrace 0, \dots, n-1 \rbrace$) or Set (a subset of it). $f$, $g_i$ and $h_j$ are expressions over $x$, not necessarily convex, smooth or continuous; the model's rows hold within an absolute $10^{-6}$. Moves keep each $x_k$ in $D_k$; the search minimises the weighted violation $$ V_w(x) = \sum_{i \in I} w_i \max(0, g_i(x)) + \sum_{j \in J} w_j \lvert h_j(x) \rvert + w_0 \max(0, f(x) - F), $$ with row weights $w$ and an objective bound $F$, each term capped at $10^{30}$, a NaN too. $\log$, $\sqrt{\cdot}$ and fractional powers add rows $g_i$, held exactly, for their domains. ## Method The search follows ViolationLS ([Davies et al., 2024](https://doi.org/10.1007/978-3-031-60597-0_16)); new here are Float, List and Set variables in a nonlinear expression DAG, and an inner solver. 1. **An expression DAG:** a one-variable move re-evaluates only that variable's cone, and undoes from a log. 2. **The objective is a row**, $f(x) \le F$: $F = +\infty$ until a feasible point, then strictly below the best objective found. 3. **Batches search:** Feasibility Jump moves one variable to the value that lowers $V_w$ most, Novelty Jump makes compound moves (a few jumps that together lower it), Structural batches move List and Set variables. The weights are guided local search's: they start at 1; at a local minimum they decay by $\rho \in \lbrace 0.95, 1 \rbrace$ and violated rows gain 1; a new best or a kick resets them. 4. **An inner solver**, if asked for (`intensify=True`), polishes the Floats at each feasible point with Newton steps and line search. In C++ a problem's own inner solver plugs in as an `InnerSolverHook`, so the search specialises without changes to the engine, as the unit-commitment hook does. 5. **On stagnation the search kicks:** it perturbs some variables, runs large neighbourhood search if asked for (`lns=`: randomise part of the variables, repair, keep it if better), or adopts a state from the workers' shared pool. Details: [method](https://spoorendonk.dk/cbls/method.html). Limits: no bound and no proof of optimality or infeasibility; tightly coupled equality rows are slow. ## Results | Benchmark | Compared against | cbls | Comparator | Reading | |---|---|---|---|---| | MIPfeas: 211 MIPLIB instances, 60 s | CP-SAT (OR-Tools 9.15.6755) at its defaults | 140 feasible, primal integral 0.390 | 175 feasible, primal integral 0.168 | CP-SAT ahead | | MINLPLib: 195 nontrivial instances, 60 s | SCIP 10.0.2 at its defaults | 169 feasible, GM(gap+1) 3.60 | 187 feasible, GM(gap+1) 2.15 | SCIP ahead: ratio 1.68 (95% CI 1.18-2.38), cbls wins/losses/ties 27/62/76 over the 165 in the pool | | UC-CHPED: 24 unit-commitment rows, 10-600 s | Pedroso et al. 2014's method on SCIP 11.0.0 preview; SCIP's MINLP | lowest primal integral on 23 of 24, best or tied final gap (to 0.01 %) on 6 of 24 | Pedroso's method: lowest primal integral on 1 of 24, best or tied final gap on 21 of 24; SCIP's MINLP: 0 and 3 of 24 | cbls first to good solutions, Pedroso's method ends better | - Run November 2026: cbls on 16 threads on AMD Ryzen 9 3950X (16 cores, 32 threads), one run (UC-CHPED: the median of 3 seeds on 20 rows); CP-SAT started 32 workers; SCIP single-threaded, 16 at once (MINLPLib), on 16 threads (UC-CHPED). - Primal integral: the gap to the best known, averaged over the time limit; 0 (best known from the start) to 2 (never feasible); MIPfeas: geometric mean shifted 0.001. - GM(gap+1): geometric mean of 1 + % gap (negative as 0) over instances both solve with a finite best known; ratio below 1: cbls ahead; a win: the other's gap+1 over 1 % larger, else a tie. - Claim: cbls is behind the exact solvers on MIPLIB and MINLPLib at 60 s; on the non-convex unit-commitment rows it has the lowest primal integral on 23 of 24. Per-benchmark tables and known issues: [results](https://spoorendonk.dk/cbls/results.html). ## Usage ```bash pip install git+https://github.com/spoorendonk/cbls # Python package and cbls command ``` ```console $ cbls examples/simple.cbls --time-limit 1 --quiet Status: feasible Objective: 12.500000 ... Solution: x = 2.50 y = 2.50 ``` The figure's model, in Python: ```python import cbls m = cbls.Model() x, y = m.Int(0, 10, "x"), m.Float(0, 10, "y") s = x + y m.add_constraint(s >= 3) m.minimize(x * x + s * cbls.sin(y)) m.close() result = cbls.solve(m, time_limit=1) print(result.feasible, result.objective, result.value(x), result.value(y)) ``` More: [quick reference](https://spoorendonk.dk/cbls/quickref.html) · [options](https://spoorendonk.dk/cbls/options.html) · [results](https://spoorendonk.dk/cbls/results.html) · [method](https://spoorendonk.dk/cbls/method.html) ## Citing ```bibtex @software{spoorendonk2026cbls, title = {cbls: constraint-based local search over an expression DAG}, author = {Spoorendonk, Simon}, year = {2026}, version = {0.1.0}, doi = {10.5281/zenodo.24758098}, url = {https://doi.org/10.5281/zenodo.24758098} } ``` - The concept DOI resolves to the latest release; its Zenodo page lists each version's own DOI. - GitHub's *Cite this repository* reads [`CITATION.cff`](https://github.com/spoorendonk/cbls/blob/main/CITATION.cff). ## License MIT. See [LICENSE](https://github.com/spoorendonk/cbls/blob/main/LICENSE). `benchmarks/uc-chped/pedroso/` is GPL-3.0-or-later; see [README.md](https://github.com/spoorendonk/cbls/blob/main/benchmarks/uc-chped/pedroso/README.md). audit.h ======= .. code-block:: c #pragma once #include namespace cbls { class FeasibilityJump; /// Where in `solve()`'s outer loop a `SearchAuditor` is being called (#225). enum class AuditPoint : std::uint8_t { /// At the top of every outer iteration, before the batch runs: after the /// previous batch's outcome (bound tightening, weight reset, resync), any /// diversification kick (perturb, LNS repair, adoption from the pool) and /// the shared-bound sync have all been applied. Every incremental structure /// the next batch reads must agree with the assignment here. BeforeBatch, /// Straight after a Feasibility-Jump batch returns, or a fix-propagate-repair /// batch (its dive, then any FJ batch it ran; #429). AfterFeasibilityJump, /// Straight after a Novelty-Jump batch returns. AfterNoveltyJump, }; /// A test-facing consistency hook (#225): `solve()` hands it the search's /// `FeasibilityJump` at each `AuditPoint`, so a test can compare the engine's /// incremental state against a from-scratch recompute /// (`FeasibilityJump::audit`) at points no public API otherwise reaches. /// /// Not a host integration point -- that is `Tracer`. The default is a null /// `SearchConfig::auditor`, which costs one predictable null compare per /// batch. A non-null auditor must not change the assignment: it is handed a /// const view, and an auditor that reaches around it voids the trajectory. class SearchAuditor { public: SearchAuditor() = default; SearchAuditor(const SearchAuditor&) = default; SearchAuditor& operator=(const SearchAuditor&) = default; SearchAuditor(SearchAuditor&&) = default; SearchAuditor& operator=(SearchAuditor&&) = default; virtual ~SearchAuditor(); virtual void audit(AuditPoint point, const FeasibilityJump& fj) = 0; }; } // namespace cbls cbls.h ====== .. code-block:: c #pragma once namespace cbls { inline constexpr const char* kVersion = "0.1.0"; } #include "audit.h" #include "counters.h" #include "dag.h" #include "dag_ops.h" #include "executor.h" #include "expr.h" #include "feasibility_jump.h" #include "formatter.h" #include "inner_solver.h" #include "io.h" #include "io_mps.h" #include "lns.h" #include "model.h" #include "move_generator.h" #include "moves.h" #include "nlp_polish.h" #include "pool.h" #include "randomize.h" #include "rng.h" #include "search.h" #include "stop.h" // structural_batch.h is deliberately NOT here: StructuralBatch is the engine's // own sweep, constructed by solve(). A caller registers generators through // SearchConfig and never builds one. The tests that drive it directly include it // directly. #include "tracer.h" #include "verify.h" #include "violation.h" counters.h ========== .. code-block:: c #pragma once #include #include #include namespace cbls { /// Which batch the ViolationLS outer loop ran (paper Algorithm 6 alternates /// FJ/NJ; Structural is the List/Set peer). Public since #169 for /// `SearchCounters` and `Tracer::batch_end`. A Structural batch commits outside /// FJ's scan-set and jump-table, so the loop owes `fj.resync()` after it; a /// Novelty batch rebuilds FJ's state itself (#209). A FixPropagateRepair /// batch writes a fix-propagate-repair dive's point and resyncs FJ (#426). enum class BatchKind : std::uint8_t { FeasibilityJump, NoveltyJump, Structural, FixPropagateRepair }; /// Stable snake_case token for a `BatchKind` ("feasibility_jump", /// "novelty_jump", "structural", "fix_propagate_repair"). Returns a static string; never null. const char* batch_kind_name(BatchKind kind); /// One move generator's share of the structural work, keyed per generator /// since a registered one may cover several variables (#165). struct GeneratorCounters { /// `MoveGenerator::name()`, copied (the generator is a per-worker clone), /// with `#` appended where one batch built several of that name: /// `merge`'s by-name path keys on it and built-ins name themselves by type. /// The suffix only matters when merged vectors differ in length or order; /// same-order vectors merge positionally. Not unique if a registered /// `name()` already ends in `#` (documented limit, `StructuralBatch`). std::string name; /// Candidates APPLIED and SCORED, not generated (sampling may draw fewer). int64_t moves_tried = 0; /// Acceptances, not surviving changes: under `FirstImprovingSample` a later /// commit can undo an earlier one (see `MoveGenerator::on_commit`). int64_t moves_accepted = 0; }; /// Where a run spent its work. Observational only: the search never reads /// these back, so filling them leaves the trajectory unchanged. Fields /// already on `SearchResult` (iterations, perturbations, LNS) stay there /// (#169). struct SearchCounters { /// `fj_batches + novelty_batches + structural_batches + fpr_batches == /// batches` exactly (pinned by `tests/test_counters.cpp`). int64_t batches = 0; int64_t fj_batches = 0; int64_t novelty_batches = 0; /// Novelty batch work (#209): moves applied (each compound leg and each /// explored-then-undone move once; undos not), compound moves committed, /// and GLS weight bumps. Separates Novelty from FJ work, which the /// iteration count cannot (3 per move, 1 per bump). int64_t novelty_moves = 0; int64_t novelty_commits = 0; int64_t novelty_weight_bumps = 0; int64_t structural_batches = 0; /// Fix-propagate-repair batches (#426), its leaf-repair FJ work included. int64_t fpr_batches = 0; /// Seconds building the FPR batch before the search starts (row store, /// propagator, root propagation; no deadline bounds it, #423). Filled only /// under a wall-clock budget, else 0.0; summed over workers. The FPR LNS /// repair's own store and propagator, built at its first kick, are not timed. double fpr_setup_seconds = 0.0; /// Totals over `by_generator`, so callers need not sum the vector. int64_t structural_moves_tried = 0; int64_t structural_moves_accepted = 0; /// One row per GENERATOR the structural batch built, in its order (the /// `#` suffix keeps same-name rows apart); a portfolio merges rows /// across workers. Empty when the batch builds no generator. std::vector by_generator; /// `InnerSolverHook::solve` calls (always counted; reads no clock) and /// their seconds, filled only under a wall-clock budget, else 0.0. Timing /// adds two clock reads per CALL, scaling with the run, where an /// iteration-budgeted run's other reads are O(1) per run (per batch with a /// `SolveCallback`); the gate keeps such runs bit-reproducible (#169), as /// `last_improvement_` in `src/search.cpp` does. Timed runs pay it whether /// read or not: the hook fires per feasible batch (and, with /// `InnerSolverHook::wants_infeasible()`, per other batch), so on the #125 /// models at 1s (pk1 201, ucp13-1p 52, chain50 0 calls) at 1359ns/read /// (HPET, pessimistic; ~20-25ns via vDSO/TSC) it costs 0.055%, 0.014% and /// 0 of the budget (count x per-read cost, not differenced timings). int64_t inner_solver_calls = 0; double inner_solver_seconds = 0.0; /// Of `inner_solver_calls`, those after an infeasible batch (#454); 0 /// unless the hook's `wants_infeasible()` is true. int64_t inner_solver_infeasible_calls = 0; /// Portfolio restarts beyond a worker's first solve, summed over workers; /// always 0 for `cbls::solve()`. Counts solves that produced a result, so /// a retry after a throwing solve is not a restart (`src/pool.cpp`). int64_t portfolio_restarts = 0; /// One-variable DAG walks served by the cone cache vs. collected and sorted /// because the variable was past the cache's cap (#271; `ConeCacheCounters` /// in dag_ops.h). Counted on the solving thread between `solve()`'s entry /// and exit, so user-callback walks are included. Summed over workers. int64_t cone_cache_walks = 0; int64_t cone_fallback_walks = 0; /// Shared objective bound engagement (#179): 0 for a single /// `cbls::solve()`; under `ParallelSearch` summed over workers. Filled with /// `ParallelConfig::share_objective_bound` on or off: the global best is /// read either way, and with sharing off only these counters depend on it. /// "Global" is the pool's, so after a restart it includes this worker's /// earlier solve (all four fields): a restarted solve reopens its bound at /// +inf and the first sync re-tightens it, with no peer involved. /// /// Times the global best tightened this worker's bound (batch boundary, or /// record_best after a peer improved). Always 0 with sharing off. Excludes /// the cap from an adoption's re-grounding (an adoption is a /// `perturbations` event). int64_t shared_bound_tightenings = 0; /// New own-bests recorded while the pool already held a strictly better /// objective (a peer's, or after a restart this worker's earlier solve). /// Nonzero in both arms: sharing moves the bound, not the incumbent. int64_t own_best_behind_global = 0; /// Batches that RAN with this worker's bound looser than the global best, /// including those before its own first feasible point. 0 by construction /// with sharing on (tightened at the boundary; mid-batch peer gains are not /// charged), so it measures the control arm's wasted search. int64_t bound_behind_global_batches = 0; /// Wall seconds of those batches; same gate as `inner_solver_seconds`. double bound_behind_global_seconds = 0.0; /// Add `other` into this: every scalar adds, and `by_generator` merges by /// NAME (a present name adds in, a new one is appended). Used for both /// portfolio aggregations (across restarts and across workers). void merge(const SearchCounters& other); }; } // namespace cbls dag.h ===== .. code-block:: c #pragma once #include #include #include #include #include #include #include #include namespace cbls { /// Default tolerance below which a constraint counts as satisfied, on the /// node's *absolute* residual (|lhs - rhs| for an equality). Matches SCIP's /// `numerics/feastol` and `verify_model`. Much tighter is meaningless in double /// precision (a 1e4 body would need ~13 digits). Here, not in violation.h, /// because `Model::set_domain_tolerance` defaults domain margins from it. inline constexpr double kDefaultFeasibilityTolerance = 1e-6; enum class VarType : uint8_t { Bool, Int, Float, List, Set }; /// True for the types carrying `elements` rather than a scalar `value`. The /// complement is exactly `FeasibilityJump::jumpable()`, and `solve()` relies on /// the two partitioning VarType to initialise every variable once (#108). /// Both are `==` whitelists, not switches, so no -Wswitch catches a new type: /// it would silently be neither initialised nor jumped. Add it here and to /// `jumpable()` in the same change. constexpr bool is_structured(VarType type) { return type == VarType::List || type == VarType::Set; } /// How `initialize_structured_random` fills a List (#164). /// /// The STARTING assignment only; the moves reach the rest from any. A /// partition member is filled by `randomize_list_partition`, which reads it /// only under `Cover::AtMostOnce`: an `Exact` cover is kept by the moves, not a /// penalty row, so it must hold from the start (`Model::add_list_partition`). enum class ListInit : uint8_t { /// `elements == [0, 1, ..., universe-1]`, a permutation. Requires /// `min_size == max_size == universe_size`, as `list_var(n)` builds, whose /// randomisation stays `rng.permutation(max_size)` (#164). Identity, /// `elements == []`; draws no random numbers. Requires `min_size == 0` /// (else it starts outside the length window). Empty, /// A uniformly random subset of a uniformly random admissible size, in a /// uniformly random order. Random, }; struct Variable { int32_t id = -1; VarType type = VarType::Float; double value = 0.0; double lb = 0.0; double ub = 0.0; std::string name; std::vector elements; // List/Set current elements // For both structured types (#164), `elements` is drawn from // {0..universe_size-1} with size in [min_size, max_size]. A List's elements // are DISTINCT and ORDERED; a Set's stored order means nothing. // `list_var(n)` is universe == min == max == n, a permutation. int32_t universe_size = 0; // List/Set: universe {0..n-1} int32_t min_size = 0; // List/Set: minimum length/cardinality int32_t max_size = 0; // List/Set: maximum length/cardinality /// List only: how `initialize_structured_random` fills it. ListInit list_init = ListInit::Identity; /// List only, set by `Model::add_list_partition`: `list_moves` then emits /// no `list_insert`/`list_remove`, which would duplicate a sibling's /// element or drop one from an `Exact` cover. `generate_partition_moves` /// owns both. bool partitioned = false; // Its readers are `Model::dependents(id)`, a slice of a model-owned array. }; /// A read-only view of a contiguous run of `T` (C++17 has no `std::span`): /// what `Model::children`, `parents`, `dependents` and `constraints_of_var` /// hand out, each a slice of one flat model-owned array. /// /// Invalidated by whatever reallocates that array: appending a node for /// `children`, the rebuild in `close()` / `add_objective_soft_constraint()` /// for the other three. No caller holds one across either. /// /// `operator[]` asserts its bound because an overrun lands silently on the /// NEXT slice of the same heap block, invisible to AddressSanitizer. Free /// under NDEBUG. template class ConstSpan { public: constexpr ConstSpan() noexcept = default; constexpr ConstSpan(const T* data, size_t size) noexcept : data_(data), size_(size) {} [[nodiscard]] constexpr const T* begin() const noexcept { return data_; } [[nodiscard]] constexpr const T* end() const noexcept { return data_ + size_; } [[nodiscard]] constexpr size_t size() const noexcept { return size_; } [[nodiscard]] constexpr bool empty() const noexcept { return size_ == 0; } [[nodiscard]] constexpr const T& operator[](size_t i) const noexcept { assert(i < size_); return data_[i]; } private: const T* data_ = nullptr; size_t size_ = 0; }; enum class NodeOp : uint8_t { Const, Neg, Sum, Prod, Div, Pow, Min, Max, Abs, Sin, Cos, Tan, Exp, Log, Sqrt, SignPower, Tanh, If, At, Count, Lambda, PairLambda, Leq, Eq, Geq, Neq, Lt, Gt, // A new op shows up as -Wswitch / `clang-diagnostic-switch` in the // `default:`-free tables of `src/dag.cpp` and `src/io.cpp` (#171) -- not // in `if`/`==` chains, nor in `node_is_affine` (src/feasibility_jump.cpp), // whose deliberate `default:` silently classes it non-affine. So // `grep -rn 'NodeOp::' src/ include/ python/` for the rest. // // The six below (#186) are piecewise constant or opaque functors: local // derivative 0, never affine. FJ instead offers the plateau edges of // Ceil/Floor/Round and the index values of Element, reached through // `carries_slope` ops, as jump candidates (`compute_var_jump`). /// `table[i]` or `table[i][j]` over a numeric table, each index any scalar, /// truncated toward zero -- 1 or 2 children, every one an index. The table /// is `ModelStructure::element_tables[lambda_func_id]`. See /// `Model::element` for the index rule. Element, /// `std::ceil` of its one child. Ceil, /// `std::floor` of its one child. Floor, /// `std::round` of its one child: half-way cases away from zero. Round, /// `lambda_sum` whose functor also reads scalar children: children[0] is /// the List/Set variable, children[1..] the `extra` scalars, whose current /// values the functor receives. `lambda_extra_funcs[lambda_func_id]`. LambdaExtra, /// `pair_lambda_sum` whose functor also reads scalar children, laid out as /// `LambdaExtra`. `pair_lambda_extra_funcs[lambda_func_id]`, closing rule /// in `pair_lambda_extra_modes` at the same index. PairLambdaExtra }; struct ChildRef { int32_t id = -1; bool is_var = false; }; /// One DAG node, owning no heap block: children are the slice /// `[child_begin, child_begin + child_count)` of the model's flat child array /// (`Model::children(node)`), parents are `Model::parents(id)` (#156). Offsets, /// not pointers, so copying a `Model` per portfolio worker rebases nothing, /// deep-copied or shared (#157). /// /// NO evaluation result: values live in the per-model `node_values()` /// (`Model::node_value(id)`), so the node array can sit in the immutable /// `ModelStructure` replicas share (#157). struct ExprNode { int32_t id = -1; NodeOp op = NodeOp::Const; /// The incremental Sum (#177, #188), set by `Model::close()`: `kIncSum` on /// a `Sum` that `commit_scalar_move` moves by its terms' changes rather /// than re-summing, `kFeedsIncSum` on a term of one. A Sum qualifies when /// no term is a Sum or named twice and every reader is a top-level /// comparison against a variable or constant (reasons: /// `Model::classify_incremental_sums`). Its per-model state /// (`Model::inc_sum_state`) is at slot `lambda_func_id`. Sits in padding /// after `op` (no memory) and is read from the already-loaded node (no /// extra load per dirty node). uint8_t inc_sum_flags = 0; static constexpr uint8_t kIncSum = 1; static constexpr uint8_t kFeedsIncSum = 2; /// A `Const`'s literal; on `Lt`/`Gt`, the row's strictness margin (see /// `strict_comparison_margin`). Unused by every other op. double const_value = 0.0; uint32_t child_begin = 0; uint32_t child_count = 0; /// Which table entry this node's user code lives in, by op: /// /// - `Lambda`, and a `PairLambda`'s head/tail: `ModelStructure::lambda_funcs` /// - `PairLambda`: `pair_lambda_funcs` and the parallel `pair_lambda_specs` /// - `Element`: `ModelStructure::element_tables` (#186) /// - `LambdaExtra`: `lambda_extra_funcs`; `PairLambdaExtra`: /// `pair_lambda_extra_funcs` and the parallel `pair_lambda_extra_modes` /// - a `Sum` with `kIncSum`: its slot in `Model::inc_sum_state()` and /// `ModelStructure::inc_sum_nodes` (#188) /// /// One field for all, since no node is two of them and a model can have /// 4.3M nodes. -1 for every other op. int32_t lambda_func_id = -1; }; // `inc_sum_flags` sits in padding: pinned so a field added later cannot grow // every node of a 4.3M-node model without someone deciding to (#177). static_assert(sizeof(ExprNode) == 32, "ExprNode grew; see inc_sum_flags"); /// How a `PairLambda` node closes its chain of consecutive pairs. enum class PairMode : uint8_t { Open, ///< e_0-e_1, ..., e_{n-2}-e_{n-1}. The original behaviour. Cyclic ///< the Open pairs plus e_{n-1}-e_0, for n >= 2. }; /// Everything a `PairLambda` node needs beyond its pair function: the closing /// rule and the two optional fixed-endpoint terms. /// /// A SIDE TABLE in `ModelStructure`, parallel to `pair_lambda_funcs` and keyed /// by `ExprNode::lambda_func_id`, not more `NodeOp`s: every variant runs the /// same loop, and `src/dag.cpp`'s two dispatch tables (each already under a /// complexity suppression) would gain six cases apiece for nothing. /// /// `head_id`/`tail_id` index `ModelStructure::lambda_funcs` (as `lambda_sum` /// fills it), or -1 for no term; shared across workers on that table's terms. struct PairLambdaSpec { PairMode mode = PairMode::Open; int32_t head_id = -1; // index into ModelStructure::lambda_funcs, or -1 int32_t tail_id = -1; // index into ModelStructure::lambda_funcs, or -1 }; /// Residual of `a <= b`, i.e. `a - b`, with the IEEE `inf - inf` indeterminacy /// resolved by the comparison the residual stands for — but *only* where the /// infinity is a written bound rather than an arithmetic overflow. /// /// `a_is_const` / `b_is_const` say whether that side is a literal `Const` node. /// That flag is the whole point of this function, because an infinity means two /// completely different things depending on where it came from: /// /// - **Sentinel.** A `Const` +-inf means "this side is absent": `a <= +inf` /// and `-inf <= b` hold for every a/b. Plain `a - b` gives NaN at same-sign /// infinities, read as maximal violation, so a *vacuous* row would rank /// worst -- destroying the feasibility signal when the folded `obj <= bound` /// overflows against the initial +inf bound (#100). /// /// - **Overflow.** A computed infinity only left double range: /// `exp(1000) <= exp(720)` is genuinely violated. It keeps the NaN, which /// the clamp makes a maximal violation, as the engine's NaN guards expect. /// /// Only the side that would make the row vacuous is consulted (+inf on both /// with `b` a literal, -inf on both with `a` one). Everything else is the plain /// difference, already right: +-inf for opposite infinities, NaN for a NaN. /// /// A sentinel-vacuous row returns 0.0, on the boundary. `Lt`/`Gt` add their /// margin; an inf constant is not integral, so it is 1e-9, inside the default /// 1e-6 tolerance: a vacuous strict row stays satisfied. /// /// Used by `Leq`/`Geq`/`Lt`/`Gt`. `Eq`/`Neq` keep plain `|a - b|`, so `x == y` /// at inf/inf stays NaN: infinity is a bound idiom, and "exactly infinite" is /// not evaluable, so it is safest left maximally violated. inline double comparison_residual(double a, double b, bool a_is_const, bool b_is_const) { if (a == b && std::isinf(a)) { const bool sentinel = (a > 0.0) ? b_is_const : a_is_const; if (sentinel) { return 0.0; } } return a - b; } /// Whether a node of this op is a comparison row (`Leq`/`Geq`/`Lt`/`Gt`/`Eq`): /// its value is a residual of its two children, not an expression in them. A /// constraint whose node is anything else is a bare body, read as `expr <= 0`. /// One predicate for every place that splits rows so (#192, #190). inline bool is_comparison_op(NodeOp op) { return op == NodeOp::Leq || op == NodeOp::Geq || op == NodeOp::Lt || op == NodeOp::Gt || op == NodeOp::Eq; } /// The margin `Lt`/`Gt` add to `comparison_residual`, so a strict row is /// violated by it at equality. Fixed per node by `Model::lt`/`gt` in /// `ExprNode::const_value`; `evaluate` and `linear_jump.h` both read it there, /// so they reproduce one residual. /// /// Integral sides (`Model::is_integral`) get 1: over integers `a < b` IS /// `a - b + 1 <= 0`, exactly (#211; an epsilon inside the 1e-6 tolerance let /// `x < y` accept x = y). Any other strict row gets `kStrictComparisonEps` /// and so behaves as `a <= b` up to the tolerance: strictness over a continuous /// side has no closest feasible point, which is why MPS and NL carry no strict /// rows. A caller who needs a gap writes `x + delta <= y`. inline constexpr double kStrictComparisonEps = 1e-9; inline constexpr double kIntegralStrictMargin = 1.0; constexpr double strict_comparison_margin(bool integral_sides) { return integral_sides ? kIntegralStrictMargin : kStrictComparisonEps; } // Forward declaration class Model; double evaluate(const ExprNode& node, const Model& model); double local_derivative(const ExprNode& node, int child_idx, const Model& model); /// Element, Ceil, Floor, Round: the piecewise-constant ops whose plateaus FJ /// offers as jump candidates (#186). bool is_breakpoint_op(NodeOp op) noexcept; /// Whether the breakpoint walk (#186) carries a slope through `op`: every op /// with a meaningful `local_derivative`, i.e. all but the structural ops, user /// code, the breakpoint ops themselves and Const. A default-free switch in /// src/dag.cpp, so a new op must choose. bool carries_slope(NodeOp op) noexcept; } // namespace cbls dag_ops.h ========= .. code-block:: c #pragma once #include "dag.h" #include #include #include #include #include namespace cbls { double full_evaluate(Model& model); /// What a `delta_evaluate` call means. `Commit` and `Probe` recompute the cone /// from the current assignment; a `Probe` also logs the cone's prior values /// (`ProbeUndo`, #270), which `Rollback` writes back: O(cone) stores instead /// of collect, sort and evaluate, and exact, so a drifting incremental `Sum` /// (#188) returns to the bit. enum class DeltaMode : uint8_t { /// The evaluated assignment is the new committed one: an applied move, and /// both legs of an evaluate-forwards-evaluate-back probe. The default. Commit, /// A counterfactual the caller WILL undo; the cone's values are logged for /// the matching `Rollback`. Probe, /// The caller restored the `Probe`'s starting assignment; the probe's cone /// gets its logged values back, nothing re-evaluated. Must directly follow /// a `Probe` over the same changed-variable set in the same order: any /// other walk, `full_evaluate`, `reground_inc_sum`, /// `Model::set_objective_bound` or `Model::set_domain_tolerance` between /// drops the log and this acts as `Commit`. Over a different set it writes /// the log back, then commits the union of both sets: correct either way. Rollback, }; // Primary signature: accepts a contiguous range of var IDs. double delta_evaluate(Model& model, const int32_t* changed_var_ids, size_t count, DeltaMode mode = DeltaMode::Commit); /// An incremental Sum's kIncSumPeriod-th inexact update since its last re-sum /// re-sums instead (#188), so it carries at most 63; exact updates (all, on /// integral data) do not count. A safety cap on drift between re-groundings, /// not a tuned optimum: picked by a pre-registered rule on held-out instances, /// costing <1% throughput vs never re-summing /// (`dev/incremental-sum-drift.md`). 0 means never: drift is then /// bounded only by the batch-end re-grounding and the gate. constexpr uint32_t kIncSumPeriod = 64; /// `Commit` of one scalar whose previous value was `old_value` (new one /// already written): `delta_evaluate(model, &var_id, 1)`, but each incremental /// `Sum` in the cone (`ExprNode::kIncSum`) moves by its terms' changes, O(1) /// each, rather than re-summing (#177, #188): O(|G_v|) instead of /// O(sum of |row| over G_v) per MIP move. /// /// Each update is TwoSum-tested: an exact one adds no rounding and no drift (on /// integral data within 2^53 every update is exact, so values equal the /// re-sum's bit for bit); an inexact one adds its exact roundings to /// `IncSumState::drift_bound`. After /// `kIncSumPeriod - 1` (63) inexact updates the next inexact one re-sums, as /// do a non-finite value and the first commit after a `full_evaluate` or /// plain `delta_evaluate` over the Sum (which re-sum unchecked). /// /// Precondition, stronger than `delta_evaluate`'s: every node value describes /// the assignment apart from `var_id`'s change. A write without a walk /// (`restore_state` without `full_evaluate`) leaves a stale base this would /// update rather than repair. double commit_scalar_move(Model& model, int32_t var_id, double old_value); /// The `Probe` counterpart: the commit's updates from the committed values, /// so an identity move on a drifted state scores exactly 0. Where the commit /// would re-sum (untracked Sum, `kIncSumPeriod` reached, non-finite) the /// probe still updates, so scores can differ by the drift bound plus the /// re-sum's rounding. `delta_evaluate(..., Rollback)` restores the state to /// the bit (see `DeltaMode`). No drift state changes. double probe_scalar_move(Model& model, int32_t var_id, double old_value); /// Re-sums (checked) the incremental Sum in `slot` and re-evaluates the rows /// that read it (by construction its only readers); afterwards /// `IncSumState::drifting` is 0. O(|terms| + |readers|). void reground_inc_sum(Model& model, int32_t slot); /// `reground_inc_sum` for every Sum still drifting on `IncSums::drifted`, /// appending each slot to `regrounded`, then empties the list; O(1) if nothing /// drifted since the last call. /// FeasibilityJump calls it at every batch end, keeping drift inside a batch. void reground_drifted_sums(Model& model, std::vector& regrounded); /// Diagnostics for tests and profiling (#177, #188), per thread since last /// reset to `IncrementalSumCounters{}`; the engine never reads them. struct IncrementalSumCounters { /// Commits that took an incremental Sum as its terms' updates left it. uint64_t incremental = 0; /// Commit-mode walks that re-summed one instead. uint64_t resummed = 0; /// Of the updates behind `incremental`, the inexact ones. uint64_t inexact = 0; /// Term updates a Probe applied to an incremental Sum: one per probe of a /// variable that is a term of it. uint64_t probe_pushes = 0; /// FeasibilityJump: local minima where some row's verdict was undecided by /// its Sum's drift bound, so the Sum was re-summed first (the gate). uint64_t gated_minima = 0; /// Gated minima where the re-sum moved a row into or out of V, so the /// iteration sampled again instead of bumping or stopping. uint64_t gate_flips = 0; }; IncrementalSumCounters& incremental_sum_counters() noexcept; /// One-variable walks on this thread since last reset to `ConeCacheCounters{}` /// (#271): cone read from `Model::freeze()`'s cache, or collected and sorted /// (unfrozen model, or variable past the cap). A Rollback from the undo log /// and a multi-variable walk (always collects) count in neither. `solve()` /// reports its own run's in `SearchCounters`. struct ConeCacheCounters { uint64_t cached_walks = 0; uint64_t fallback_walks = 0; }; ConeCacheCounters& cone_cache_counters() noexcept; // Convenience overloads inline double delta_evaluate(Model& model, const std::vector& changed_var_ids, DeltaMode mode = DeltaMode::Commit) { return delta_evaluate(model, changed_var_ids.data(), changed_var_ids.size(), mode); } inline double delta_evaluate(Model& model, const std::set& changed_var_ids, DeltaMode mode = DeltaMode::Commit) { std::vector ids(changed_var_ids.begin(), changed_var_ids.end()); return delta_evaluate(model, ids.data(), ids.size(), mode); } inline double delta_evaluate(Model& model, std::initializer_list changed_var_ids, DeltaMode mode = DeltaMode::Commit) { return delta_evaluate(model, changed_var_ids.begin(), changed_var_ids.size(), mode); } // Reverse-mode AD over the cone of `expr_id`, in reverse topological order: // O(c log c) for a cone of c nodes, falling back to the full-order walk when // the sort would not pay; bit-identical either way (cutover at `reverse_sweep` // in src/dag_ops.cpp). All three share one thread_local scratch, so none may // be called from inside another on one thread. `expr_id` must be a node id of // `model` (not a variable handle); unchecked here (hot path), checked by the Python binding. /// One chain-rule step: `acc += edge * carried`, `edge` the local derivative, /// `carried` the adjoint or forward slope. Every propagation pass uses it /// (reverse sweep, `UpConePartials`, FJ's pruned breakpoint slopes; #260). /// A zero edge (untaken If branch, Min's unselected operand) is skipped, so /// an inf/NaN `carried` cannot turn a true 0 partial into NaN; live paths /// still propagate inf/NaN. For finite `carried` only a zero's sign changes. inline void add_chain_term(double& acc, double edge, double carried) { if (edge != 0.0) { acc += edge * carried; } } /// d(parent)/d(child) for one DAG edge, summed over `parent`'s operands naming /// `child` (the forward up-cone walk sees a parent once). For a Sum it is the /// operand's multiplicity, 1 unless `Model::close()` marked it /// `kRepeatedChild`, so an n-term Sum costs O(1) per edge, not O(n); other ops /// scan their children. Requires a closed model. double up_edge_derivative(const Model& model, int32_t parent, const ChildRef& child); /// ∂expr/∂var for one variable; 0.0 for a `var_id` outside the model. double compute_partial(const Model& model, int32_t expr_id, int32_t var_id); /// d(node)/d(var) for every node above one variable, forward mode (#249): /// collect the up-cone (via `Model::parents`), sort topologically, carry the /// slope along each parent edge by `up_edge_derivative`. Same chain rule as /// `compute_partial`, so `of(row)` matches it up to summation order on finite /// paths; both skip zero edges (`add_chain_term`). Where infinite paths meet /// the modes can differ (inf + -inf = NaN at different nodes), including a /// parent naming a child twice (`z / z`): this pass sums the operand /// derivatives before the zero test, the reverse sweep tests each. /// /// COST: O(u log u) for an up-cone of u nodes plus their parent edges, giving /// EVERY node's partial at once, vs `compute_partial`'s whole row cone per /// row. Wins with a large row cone and small up-cone (separable `obj <= /// bound`; UC-CHPED ucp200-168p: ~30 ms per reverse sweep over a 1.38M-node /// cone, 42% of a 60 s run); loses with a large up-cone and small rows (a /// variable in many nonlinear rows), so `build` gives up past a node budget /// and the caller takes the reverse sweep. /// /// Requires a closed model. Not thread-safe: one instance per thread, reused /// (epoch-stamped entries, so a call never clears the arrays). class UpConePartials { public: /// Collects and sweeps `var_id`'s up-cone. False, every `of` at 0, when the /// model is not closed or the cone outgrows `max_nodes`; a throwing build /// also leaves every `of` at 0. bool build(const Model& model, int32_t var_id, size_t max_nodes); /// d(node)/dv at the point `build` saw; 0 for a node the variable cannot reach. [[nodiscard]] double of(int32_t node_id) const { const auto i = static_cast(node_id); return i < stamp_.size() && stamp_[i] == epoch_ ? slope_[i] : 0.0; } private: bool sweep(const Model& model, int32_t var_id, size_t max_nodes); void next_epoch(); std::vector stamp_; std::vector slope_; std::vector cone_; uint32_t epoch_ = 0; }; /// Batch AD: partials of `expr_id` w.r.t. ALL variables in one reverse pass; /// entry[i] = ∂expr/∂var_i, size `num_vars()`. That O(num_vars) result is /// the floor; prefer `compute_partials_sparse` on a large model. std::vector compute_all_partials(const Model& model, int32_t expr_id); /// Sparse batch AD: fills `out` (cleared first; the caller's buffer, reused) /// with (var_id, ∂expr/∂var_id) for each variable with a nonzero partial, /// once each, in the sweep's deterministic first-reach order; values /// bit-identical to `compute_all_partials`. Costs the sweep plus O(output), /// never O(num_vars). Exactly-0.0 partials are absent. /// /// Partials are at CURRENT node values, so a cached slope stays valid only /// while every op on the path has a constant local derivative: `Sum`, `Neg`, /// `Prod`/`Div` by a constant, `Leq`/`Geq`/`Lt`/`Gt`. `Eq` is sign(residual) /// (0.0 when satisfied, sign-flipping otherwise); `Neq` and the structural /// ops are always 0.0. void compute_partials_sparse(const Model& model, int32_t expr_id, std::vector>& out); } // namespace cbls executor.h ========== .. code-block:: c #pragma once #include #include #include #if defined(__cpp_concepts) && __cpp_concepts >= 201907L #include #endif namespace cbls { /// Implementation vocabulary, not API: `FunctionRef` is safe only as a PARAMETER /// invoked before the call returns, and cannot police that itself: an rvalue /// must bind, or `exec.parallel_for(0, n, [](int){})` would not compile, which /// rules out `StopRef`'s deleted `const S&&` overload. Storing one dangles with no /// diagnostic, which is why it is not in `cbls::`. namespace detail { /// A NON-OWNING view of a callable (the C++26 `function_ref` shape: two /// pointers, no allocation, no ownership). `std::function` would allocate and /// copy; a template parameter would make `ExecutorRef`, a concrete type compiled /// into `cbls_lib`, a template. THE REFERENT MUST OUTLIVE THE CALL. /// /// Binds a non-const lvalue or a temporary; a `const` callable does not compile, /// deliberately, since the thunk has to be able to invoke a `mutable` lambda. template class FunctionRef; template class FunctionRef { public: /// The `enable_if` keeps this from hijacking the copy constructor, which a /// forwarding-reference constructor otherwise matches better than the /// implicit one. template , FunctionRef>>> // Implicit by design: this is a parameter type, and the call site writes a // lambda. FunctionRef(F&& callable) noexcept : obj_(std::addressof(callable)), fn_(&thunk>) {} R operator()(Args... args) const { return fn_(obj_, std::forward(args)...); } private: template static R thunk(void* obj, Args... args) { return (*static_cast(obj))(std::forward(args)...); } void* obj_; R (*fn_)(void*, Args...); }; } // namespace detail /// A NON-OWNING, type-erased view of a caller-owned thread pool (#169). /// /// Without it `ParallelSearch` creates its own `std::thread`s, and a host that /// already owns a pool oversubscribes its cores with no way to say "use mine". /// Other optimisation libraries are converging on this small executor shape, so /// taking it lets cbls drop in beside them without an adapter. /// /// THE SHAPE. Anything with these four members, however spelled internally: /// /// ``` /// e.parallel_for(begin, end, f); // f(i) for i in [begin, end) /// e.parallel_for_chunked(begin, end, f); // f(chunk_begin, chunk_end, chunk_idx) /// e.parallel_invoke(f, g); // both, possibly concurrently /// int n = e.n_threads(); /// ``` /// /// `chunk_idx` is unique in `[0, n_threads())` -- a CHUNK index, not a thread id /// -- so a caller can index per-chunk storage without a lock. Empty and inverted /// ranges are no-ops, short-circuited here so an adapted executor never sees one. /// /// A C++20 caller can check its type against the concept below at compile time /// (`static_assert(cbls::Executor)`); under C++17 a mismatch is a /// template error inside the constructor. No translation unit here is C++20, so /// no gate compiles the concept: check it by hand with a C++20 compiler when it /// changes. /// /// OWNERSHIP AND LIFETIME. The CALLER owns the pool. This is a pointer plus a /// vtable pointer, copied by value; nothing in cbls owns, copies or destroys the /// pool, and the pool must outlive the solve. Same rule, same reason, as /// `StopRef`. /// /// EVERY `parallel_*` CALL IS A JOIN POINT: it must not return until every call /// or chunk it made has finished. `src/pool.cpp` hands `parallel_for_chunked` a /// callable holding references into `solve_portfolio`'s stack frame (the shared /// solution pool, the stop flag, the per-worker results), so an executor that /// ENQUEUES its chunks and returns reads freed stack in every worker. /// /// CONCURRENCY IS REQUIRED, not merely permitted: portfolio workers are /// long-running and COOPERATIVE (they share incumbents and restart from a /// peer's), so they must run at the same time. An executor that runs chunks /// SEQUENTIALLY is not an error but degenerates: under a WALL CLOCK to a /// one-worker portfolio, since the first worker takes the whole shared deadline /// and every later one finds it past and returns without searching; with /// `time_limit <= 0` to N full `max_iterations` solves in series, N times the /// wall time. Nothing detects either. class ExecutorRef { public: /// Non-explicit on purpose: `par_config.executor = my_pool;` is the call /// shape. The `enable_if` keeps the copy constructor from being hijacked. template , ExecutorRef>>> // Implicit by design; see above. ExecutorRef(E& executor) : obj_(std::addressof(executor)), table_(&kTableFor) {} /// `f(i)` for each `i` in `[begin, end)`, possibly concurrently. /// /// MUST NOT RETURN UNTIL EVERY CALL HAS FINISHED. See the note on the class. void parallel_for(int begin, int end, detail::FunctionRef f) const { if (end <= begin) { return; } table_->parallel_for(obj_, begin, end, f); } /// `f(chunk_begin, chunk_end, chunk_idx)` over a partition of /// `[begin, end)`, possibly concurrently. This is the one `ParallelSearch` /// uses. /// /// MUST NOT RETURN UNTIL EVERY CHUNK HAS FINISHED. See the note on the class. void parallel_for_chunked(int begin, int end, detail::FunctionRef f) const { if (end <= begin) { return; } table_->parallel_for_chunked(obj_, begin, end, f); } /// Run both, possibly concurrently. Returns once both have finished. void parallel_invoke(detail::FunctionRef f, detail::FunctionRef g) const { table_->parallel_invoke(obj_, f, g); } /// How many chunks may run at once -- the bound on the portfolio's worker /// count. The adapted `n_threads()` should return `int`; anything merely /// convertible is converted in the return statement, which is a narrowing /// conversion if it is wider. /// /// A value below 1 is clamped to 1 by `src/pool.cpp`, which keeps the /// per-worker vectors non-empty. That is all the clamp buys: it cannot make a /// zero-width pool actually RUN a chunk, and a pool that runs nothing leaves /// the portfolio with no result to return -- reported as `NoBudget`, exactly /// as a run handed no budget is. Must be >= 1: supply a pool that runs what it /// is given. [[nodiscard]] int n_threads() const { return table_->n_threads(obj_); } private: struct VTable { void (*parallel_for)(void*, int, int, detail::FunctionRef); void (*parallel_for_chunked)(void*, int, int, detail::FunctionRef); void (*parallel_invoke)(void*, detail::FunctionRef, detail::FunctionRef); int (*n_threads)(void*); }; // One table per adapted type, with static storage duration: a `static // constexpr` data member of a template is implicitly inline in C++17, so // this costs one 32-byte object per executor type and no initialisation // order to reason about. template static constexpr VTable kTableFor{ [](void* obj, int begin, int end, detail::FunctionRef f) { static_cast(obj)->parallel_for(begin, end, f); }, [](void* obj, int begin, int end, detail::FunctionRef f) { static_cast(obj)->parallel_for_chunked(begin, end, f); }, [](void* obj, detail::FunctionRef f, detail::FunctionRef g) { static_cast(obj)->parallel_invoke(f, g); }, // The return type is spelled on the lambda, not cast inside it: a cast of an // `n_threads()` that already returns `int` is redundant, itself a lint finding. [](void* obj) -> int { return static_cast(obj)->n_threads(); }, }; void* obj_; const VTable* table_; }; #if defined(__cpp_concepts) && __cpp_concepts >= 201907L /// The shape `ExecutorRef` adapts, as a concept, for a C++20 caller that wants /// the error at its own declaration rather than inside our constructor. /// Compiled only when the INCLUDING translation unit is C++20 or later. /// `ExecutorRef` does not constrain on it, so the constructor's availability /// does not depend on the caller's language mode. template concept Executor = requires(E e, int n) { e.parallel_for(0, n, [](int) {}); e.parallel_for_chunked(0, n, [](int, int, int) {}); e.parallel_invoke([] {}, [] {}); { e.n_threads() } -> std::convertible_to; }; /// `cbls::static_assert_executor();` -- a one-line compile-time check /// with a readable failure, for callers who would rather not write the /// `static_assert` themselves. template constexpr void static_assert_executor() { static_assert(Executor, "type does not satisfy cbls::Executor: it needs parallel_for, " "parallel_for_chunked, parallel_invoke and n_threads"); } #endif } // namespace cbls expr.h ====== .. code-block:: c #pragma once #include "model.h" #include namespace cbls { class Expr { public: Model* model; int32_t handle; // negative = var, non-negative = node Expr(Model* m, int32_t h) : model(m), handle(h) {} // Query [[nodiscard]] bool is_var() const { return handle < 0; } // Convenience accessors (only valid when is_var() == true) [[nodiscard]] int32_t var_id() const { return -(handle + 1); } [[nodiscard]] Variable& var_mut() const { return model->var_mut(var_id()); } [[nodiscard]] const Variable& var() const { return model->var(var_id()); } // Arithmetic operators Expr operator+(const Expr& rhs) const; Expr operator-(const Expr& rhs) const; Expr operator*(const Expr& rhs) const; Expr operator/(const Expr& rhs) const; Expr operator-() const; // Mixed scalar operators (friends) friend Expr operator+(double lhs, const Expr& rhs); friend Expr operator+(const Expr& lhs, double rhs); friend Expr operator*(double lhs, const Expr& rhs); friend Expr operator*(const Expr& lhs, double rhs); friend Expr operator-(double lhs, const Expr& rhs); friend Expr operator-(const Expr& lhs, double rhs); friend Expr operator/(double lhs, const Expr& rhs); friend Expr operator/(const Expr& lhs, double rhs); // Comparison operators (return Expr constraint, NOT bool) Expr operator<=(const Expr& rhs) const; Expr operator>=(const Expr& rhs) const; Expr operator<(const Expr& rhs) const; Expr operator>(const Expr& rhs) const; [[nodiscard]] Expr eq(const Expr& rhs) const; // NOT operator== (would break containers) [[nodiscard]] Expr neq(const Expr& rhs) const; // Scalar comparison (friends) friend Expr operator<=(const Expr& lhs, double rhs); friend Expr operator<=(double lhs, const Expr& rhs); friend Expr operator>=(const Expr& lhs, double rhs); friend Expr operator>=(double lhs, const Expr& rhs); friend Expr operator<(const Expr& lhs, double rhs); friend Expr operator<(double lhs, const Expr& rhs); friend Expr operator>(const Expr& lhs, double rhs); friend Expr operator>(double lhs, const Expr& rhs); // Power [[nodiscard]] Expr pow(const Expr& exp) const; }; // Free math functions Expr sin(const Expr& x); Expr cos(const Expr& x); Expr tan(const Expr& x); Expr exp(const Expr& x); Expr log(const Expr& x); Expr sqrt(const Expr& x); Expr abs(const Expr& x); Expr pow(const Expr& base, const Expr& exp); Expr min(const std::vector& args); Expr max(const std::vector& args); Expr if_then_else(const Expr& cond, const Expr& then_, const Expr& else_); // #186: piecewise-constant rounding, and a table looked up by a decision. The // contracts are `Model::ceil_expr` and `Model::element`'s. Expr ceil(const Expr& x); Expr floor(const Expr& x); Expr round(const Expr& x); Expr element(const std::vector& table, const Expr& index); Expr element(const std::vector>& table, const Expr& row, const Expr& col); } // namespace cbls feasibility_jump.h ================== .. code-block:: c #pragma once #include "linear_jump.h" #include "model.h" #include "rng.h" #include "violation.h" #include #include #include #include #include #include #include namespace cbls { // Generalised Feasibility Jump (ViolationLS, Davies et al. CPAIOR 2024, // Algorithms 1-3): apply the best of a sampled set of improving // single-variable jumps, with GLS weight bumping on stagnation. Paper state // S = : G = Model, X = variable values, W = // ViolationManager::weights, V = violated constraints, Q = scan set, J = // JumpTable. Only Bool/Int/Float are jumped; List/Set are left to structural // moves. // Score of a jump that improves only the objective (#218): the smallest // positive double. Its f is 0, so JumpTable::scale_scores leaves it alone. inline constexpr double kObjectiveTieScore = std::numeric_limits::denorm_min(); // Per-variable cached jump: best value and score = -W.deltaG(v, jump_value) // (> 0 improving). Lazily invalidated when a neighbouring variable changes // (paper Algorithm 1). class JumpTable { public: explicit JumpTable(size_t num_vars) : entries_(num_vars) {} [[nodiscard]] bool valid(int32_t var_id) const { return entries_[var_id].valid; } void invalidate(int32_t var_id) { entries_[var_id].valid = false; } void invalidate_all() { for (auto& e : entries_) { e.valid = false; } } void set(int32_t var_id, double jump_value, double score) { entries_[var_id] = {jump_value, score, true}; } [[nodiscard]] double jump_value(int32_t var_id) const { return entries_[var_id].jump_value; } [[nodiscard]] double score(int32_t var_id) const { return entries_[var_id].score; } /// Multiply every cached score by `factor` when LazyWeightDecay folds a /// factor into the weights (#175): a score is linear in the weights. /// O(#vars), only on a fold. `keep_objective_ties` (#218) skips /// kObjectiveTieScore entries, which a factor <= 0.5 would round to 0. void scale_scores(double factor, bool keep_objective_ties = false) { for (auto& e : entries_) { if (e.valid && (!keep_objective_ties || e.score != kObjectiveTieScore)) { e.score *= factor; } } } private: struct Entry { double jump_value = 0.0; double score = 0.0; bool valid = false; }; std::vector entries_; }; // Best jump for one scalar variable; score = -delta (> 0 improving). struct JumpResult { double jump_value = 0.0; double score = 0.0; }; // Best jump for `var_id` (must be Bool/Int/Float) under `weights`: the // candidate minimising the weighted violation delta, score = -delta. Float // candidates: a Newton step toward each violated row's root (reverse-mode AD) // plus the domain midpoint and endpoints; one call is not a converged 1-D // minimiser. GLS weights give the FJ score, novelty weights the Novelty-Jump // argmin. `allow_escape_probe` adds a two-sided probe at a Float stationary // point (a last resort; see feasibility_jump.cpp). // // `linear` scores candidates in closed form where every weighted row of G_v // is linear (see linear_jump.h), else falls back to // Model::weighted_violation_delta. Same candidates and first-seen-minimum // rule; scores agree to rounding, so the selected jump is identical only on // integral data. `tol`: a row within it is satisfied and offers no Newton // candidate. // // `objective_coef` (var_id's coefficient in an affine objective) turns on the // tie-break (#218): among candidates with exactly the minimum f, the largest // objective decrease wins, lexicographically, so it never overrides a // violation decrease. An objective-only win scores kObjectiveTieScore. Between // variables, apply_jump breaks an exact score tie on the objective gain. JumpResult compute_var_jump(Model& model, const std::vector& weights, int32_t var_id, bool allow_escape_probe = false, LinearJumpScorer* linear = nullptr, double tol = kDefaultFeasibilityTolerance, const double* objective_coef = nullptr); // GLS weight update (paper Algorithm 3, lines 8-10): decay all weights by rho, // then bump every violated row by 1; rows masked to 0 stay 0. Eager, // O(#constraints); FJ uses LazyWeightDecay (#175), and this stays as the // reference it is tested against. void gls_update_weights(ViolationManager& vm, double rho, double tol = kDefaultFeasibilityTolerance); // The GLS decay of Algorithm 3, stored lazily (#175); the algorithm's weights // are unchanged. With global scale s the stored vector holds w'_c = w_c / s: // // decay by rho: s <- s * rho O(1), not O(#rows) // bump row c: w'_c <- w'_c + 1/s (if w'_c > 0) O(1) per violated row // effective w_c: s * w'_c // // Equal to the eager form to rounding (bit-identical at rho = 1, s = 1), as in // CP-SAT's violation_ls, but trajectories differ: eager left cached scores // stale (#175). Cached scores stay exact in the scaled space across a decay // (dev/architecture.md). // // Scale-free readers: FJ's GLS loop only compares weighted sums with each // other or 0, so it reads w' directly. `active()` reads w' > 0 (s > 0). // // Renormalisation: s stays in [kMinScale, kMaxScale]; a decay that would leave // it folds s * rho into every stored weight (O(#rows)) and resets s = 1. A // weighted term is at most ~1e60x its effective weight, far from overflow; at // rho = 0.95 a fold happens once per 1347 decays. A rho the scale cannot // absorb (0, negative, NaN, one-step underflow) takes the fold, i.e. the eager // update. // // Weight 0 stays exactly 0 and a positive weight stays positive: an // underflowing fold floors at the smallest subnormal, since a 0 row is masked // for good. Only rho = 0 zeroes a positive weight, as eager `w * 0` does. // // Between folds the stored vector is not the effective weights: the owner // must `materialise` before anything else reads them. FJ does so on every // exit from its GLS loop. class LazyWeightDecay { public: static constexpr double kMinScale = 1e-30; static constexpr double kMaxScale = 1e30; /// Decay every weight in `w` by rho. Returns the factor folded into the /// stored weights, 1.0 when none was: the caller must multiply anything /// else it keeps in the scaled space (cached jump scores) by it. double decay(std::vector& w, double rho); /// The bump of row c: effective w_c += 1, unless the row is masked (0). void bump(std::vector& w, size_t c) const { if (w[c] > 0.0) { w[c] += step_; } } /// Row c's effective weight, s * w'_c. [[nodiscard]] double effective(const std::vector& w, size_t c) const { return scale_ * w[c]; } /// Fold s into the stored weights so they ARE the effective weights, and /// reset s = 1. O(#rows) unless s is already 1, when it touches nothing. /// Returns the factor folded (1.0 if none), as `decay` does. double materialise(std::vector& w); [[nodiscard]] double scale() const { return scale_; } private: double fold(std::vector& w, double factor); double scale_ = 1.0; double step_ = 1.0; // 1 / scale_, so a bump is one add }; struct GFJConfig { // Best-of-N ApplyJump sample: ViolationLS §3 uses 5 for a Feasibility Jump // in either phase (#211); 3 is its Novelty sample (kNoveltySample). int sample_size_linear = 5; int sample_size_general = 5; double rho = 0.95; // GLS decay; caller samples from {0.95, 1.0} per batch // A row with residual <= this is satisfied: out of V, never bumped, no // Newton candidate. solve() sets it to SearchConfig::feasibility_tolerance // (#211). double tolerance = kDefaultFeasibilityTolerance; // OR-Tools' use of the objective before the first feasible point (#218): // ComputeScore's epsilon (a violation tie goes to the candidate lowering // the objective most; see compute_var_jump) and ShouldScan's // HasBetterObjectiveValue (a variable not at its objective-better bound stays // in Q). Off here (the pre-#218 path bit for bit); solve() turns it on via // SearchConfig::fj_objective_tie_break (#226). Needs an affine objective, // read once at construction; otherwise inert. FJ batches only: Novelty and // LNS repair do not take it. bool objective_tie_break = false; bool two_phase = true; // GLS on linear submodel first, then full model bool set_initial_x = true; // set X[v] to the domain value closest to 0 first int64_t max_iterations = 0; // 0 = unbounded (bounded by time_limit) double time_limit = 0.0; // seconds; 0 = no limit // End a batch after this many GLS iterations without reducing the real // rows' unweighted violation below the batch's best; <= 0 disables. Batch // API only: gls()/run() have no outer loop to return to. See // unweighted_violation_. 300 is a coarse grid pick on MINLPLib, not a tuned // optimum, and is dimensionless on a quantity whose scale is not (#102, // #145). int64_t unproductive_iterations = 300; }; enum class GFJStatus : std::uint8_t { Feasible, Unsolved }; class FeasibilityJump { public: FeasibilityJump(Model& model, ViolationManager& vm, RNG& rng, GFJConfig config = {}); // Run GLS until feasible or the iteration/time budget is spent (single-shot // use). GFJStatus run(); // Batch API for the ViolationLS outer loop (Algorithm 6). The caller owns // the loop: begin() once, then batch() repeatedly, calling reset_weights() // on a new best (after tightening the objective bound) and perturb() on // stagnation. set_rho() re-randomises the GLS decay between batches. void begin(bool set_initial_x); bool batch(int64_t batch_iterations); // true if feasible (no active violated) // Whether the last batch() ended unproductive (GFJConfig:: // unproductive_iterations) rather than on budget or deadline. Valid only // straight after batch(); cleared at batch entry. [[nodiscard]] bool batch_stuck() const { return batch_stuck_; } void reset_weights(); // W <- 1 and rebuild the scan set void resync(); // rebuild the scan set from current state, keep weights // Randomise each jumpable var w.p. p, then apply // clamp(round(p*|elements|), 1, |elements|) random structural moves to each // List/Set var (#111); if nothing moved, force one variable, a scalar if // any can move (#109). The fallback leaves large models bit-identical to // plain p-draws, and a model without List/Set keeps its exact draw // sequence. void perturb(double probability); void set_rho(double rho) { config_.rho = rho; } // Armed by the search loop once it has stagnated; see solve(). void set_escape_probe(bool on) { escape_probe_ = on; } // The armed state, for the caller and its tests. [[nodiscard]] bool escape_probe() const { return escape_probe_; } // Arm/disarm the unproductive-batch exit for the next batch. Armed at // begin(); solve() re-decides it before every batch (see the second-witness // note on unweighted_violation_). void set_watch_progress(bool on) { watch_progress_ = on; } // Unweighted violation of the active real rows (see // unweighted_violation_). For tests; the search does not read it. [[nodiscard]] double unweighted_violation() const { return unweighted_violation_; } /// Incremental violated-row state, for tests (#174); the search never reads /// these. /// - `row_violated(ci)`: row `ci` is in V; /// - `violated_rows()`: a sorted copy of V (kept in flip order); /// - `active_violated_rows_of(v)`: rows listing `v` that are violated and /// active (weight > 0) as of their last reconcile; 0 for a structured /// variable. /// `row_violated` and `active_violated_rows_of` throw std::out_of_range on an /// unknown index. [[nodiscard]] bool row_violated(int32_t ci) const; [[nodiscard]] std::vector violated_rows() const; [[nodiscard]] int32_t active_violated_rows_of(int32_t var_id) const; /// For tests (#206): true iff Q and Q' (Novelty's) hold no duplicate, their /// membership flags match their contents, and no var on Novelty's /// compound-move stack is in Q'. Valid between calls. O(|V| + |Q| + |Q'|). [[nodiscard]] bool scan_sets_consistent() const; /// Compare every incremental structure against a from-scratch recompute /// (#225); one line per disagreement, empty when consistent. For tests via /// SearchAuditor; valid between calls. Checks node values, V (its index, /// counted bits and per-variable counts), every valid jump entry's value and /// score, and that no improving jump is missing from Q. Not the unweighted /// progress accumulator, which rounds by design. /// Values agree within 1e-9 * (1 + |fresh|), plus a drifting Sum's tracked /// bound; scores within 1e-7 * (1 + |cached| + |fresh|), since the closed /// form agrees with the probe only to rounding. /// O(#nodes + #rows + jumpable vars x |G_v|) and a model copy per call. [[nodiscard]] std::vector audit() const; /// The cached jump entry for `var_id`, or nullopt when invalid. For tests /// (#210); throws std::out_of_range on an unknown index. [[nodiscard]] std::optional cached_jump(int32_t var_id) const; /// Objective-row neighbour walks skipped as inert since construction (#210, /// #209): update_var's, and Novelty's re-queues. Diagnostics. [[nodiscard]] int64_t objective_walks_skipped() const { return objective_skips_fj_; } [[nodiscard]] int64_t novelty_objective_walks_skipped() const { return objective_skips_novelty_; } [[nodiscard]] bool all_satisfied() const; [[nodiscard]] int64_t iterations() const { return iterations_; } // total GLS iterations since begin() // ---- Deadline-check tuning (#113) ---- // // The GLS loop reads the clock on a stride sized in time: at most // kStrideBudgetFraction of the budget, or one GLS iteration if larger. // That is a batch's worst-case overrun. static constexpr double kStrideBudgetFraction = 1.0 / 64.0; static constexpr int64_t kStrideGrowth = 8; // max growth per adjustment // Iteration cap on the stride, and why the overrun is bounded: a stride // grown while iterations were cheap is spent in full once they turn // expensive, since a shrink applies only at a check. 64 was the old fixed // stride, so the worst case is no worse than before (#113). Costs ~1.2% // throughput on cheap iterations (#113). static constexpr int64_t kMaxDeadlineStride = 64; // Pure function of the last measurement; exposed for testing. static int64_t next_deadline_stride(int64_t stride, double elapsed_seconds, double target_seconds); // `deadline_checks()` counts clock reads inside the GLS loop (the kick's // structural pass counts its own: structural_kick_checks()); // `deadline_check_stride()` is the live stride. Both paths read the clock // only under `has_deadline_`. [[nodiscard]] int64_t deadline_checks() const { return deadline_checks_; } [[nodiscard]] int64_t deadline_check_stride() const { return deadline_stride_; } // ---- The structural kick's own deadline bound (#115) ---- // // The last perturb()'s structural pass, counted in structural moves (one // move-set generation plus one apply). `structural_kick_checks()` is 0 on a // run with no wall clock. Excluded: force_structural_move's fallback move (a // kick's worst case is one move more) and arm_structural_kick's one clock // read per kick. [[nodiscard]] int64_t structural_kick_moves() const { return kick_moves_; } [[nodiscard]] int64_t structural_kick_checks() const { return kick_checks_; } /// The closed-form linear scorer (its counters; tests check its scores). /// `prepare` touches only its own scratch, never the assignment. [[nodiscard]] const LinearJumpScorer& linear_scorer() const { return linear_; } [[nodiscard]] LinearJumpScorer& linear_scorer() { return linear_; } [[nodiscard]] int64_t structural_kick_stride() const { return kick_stride_; } // Novelty Jump (paper Algorithms 4-5): one stand-alone ApplyNoveltyJump // (Algorithm 4) from a fresh W' and Q', capped at novelty_work_budget() // applied moves, each charging 3 to iterations(). Committed compound moves // stay applied; returns true if feasible. Call from a local optimum with // violated_/weights current; the caller must resync() afterwards. W' = // kCompoundDiscount*W on rows satisfied at entry, W on violated ones. The // search uses novelty_batch() instead. bool apply_novelty_jump(); /// One Novelty Jump batch (#209): GLS with ApplyNoveltyJump as its move /// (ViolationLS Algorithm 6 line 22, Algorithm 3 with M = Algorithm 4). /// When ApplyNoveltyJump finds no compound move at its largest discrepancy /// budget, the GLS weights are decayed and bumped as in batch(). W' and Q' /// are set up once per batch and kept incrementally. Each applied move costs /// kNoveltySample = 3 iterations (undos 0), each bump 1; bounded by /// `batch_iterations` (<= 0: none), the deadline (polled per move and bump) /// and GFJConfig::max_iterations. Returns true if no active row is violated. /// Leaves V, Q and the jump table current: no resync() needed. bool novelty_batch(int64_t batch_iterations); /// Moves (applies, not undos) the last apply_novelty_jump() made, and the /// cap on them (#206). [[nodiscard]] int64_t novelty_moves_last_call() const { return nj_moves_this_call_; } [[nodiscard]] static constexpr int64_t novelty_work_budget() { return kNoveltyWorkBudget; } /// Cumulative Novelty moves applied, compound moves committed and GLS bumps /// since construction. Diagnostics. [[nodiscard]] int64_t novelty_moves() const { return novelty_moves_; } [[nodiscard]] int64_t novelty_commits() const { return novelty_commits_; } [[nodiscard]] int64_t novelty_weight_bumps() const { return novelty_bumps_; } /// Row `ci`'s novelty weight W' as Novelty last left it, for tests (#209). /// Throws std::out_of_range on an unknown row or before W' is sized. [[nodiscard]] double novelty_weight(int32_t ci) const; /// For tests (#209): true iff every row not noted for the next level reset /// holds its level-start W' (W[c] if violated, kCompoundDiscount * W[c] /// otherwise) and the noted list matches its flags; the invariant that lets /// a level reset visit only noted rows. Valid between calls. O(#rows). [[nodiscard]] bool novelty_weights_consistent() const; /// Times Q' has been seeded from V's rows since construction: once per /// apply_novelty_jump() or novelty_batch() (#209). [[nodiscard]] int64_t novelty_scan_set_seeds() const { return novelty_seeds_; } private: // One GLS pass over the constraints whose weight is currently > 0 (the // "active" set). Returns Feasible if all active constraints are satisfied. GFJStatus gls(int sample_size); // GLS inner loop reusing current state, bounded by a per-call iteration // limit (<=0 for none) plus the global budget/deadline. GFJStatus gls_loop(int sample_size, int64_t batch_iter_limit); // gls_loop's body. The weights are in LazyWeightDecay's scaled space while it // runs; gls_loop materialises them on every way out. GFJStatus gls_loop_scaled(int sample_size, int64_t batch_iter_limit); [[nodiscard]] bool any_active_violated() const; // A budget exit's status: Feasible only if nothing active is violated, read // after re-grounding (#188). Every budget exit of gls_loop uses it. [[nodiscard]] GFJStatus batch_end_status() { reground_drifted_rows(); return any_active_violated() ? GFJStatus::Unsolved : GFJStatus::Feasible; } // ---- The incremental Sums' drift (#188) ---- // // Whether row c's verdict is undecided: it reads a drifting incremental Sum // directly (row_slot_) and the interval of width drift_bound around // `residual` straddles GFJConfig::tolerance (0 for a domain row, #258). [[nodiscard]] bool verdict_undecided(int32_t c, double residual) const; [[nodiscard]] bool domain_verdict_undecided(double residual, double drift_bound) const; // Put row c on uncertain_rows_ if undecided; called wherever a row's value // or its Sum's drift changes in a batch. void note_row_certainty(int32_t c, double residual); // The local-minimum gate: re-sum the Sum under each still-undecided row and // settle the rows that moved. True when V changed, so the caller re-samples // instead of bumping or declaring feasibility. bool settle_undecided_rows(); // Re-sum every Sum that drifted since the last call and settle moved rows; // true when V changed. Called at batch end, Novelty entry and every // Feasible verdict. bool reground_drifted_rows(); // After reground_inc_sum(s) of slot_scratch_: settle each moved row as // update_var does, from row_before_. True if V changed. bool settle_regrounded_rows(); // Snapshot the rows of `slot` into row_before_ ahead of its re-sum. void capture_rows_of_slot(int32_t slot); void build_row_slots(); // No improving jump in the scan set: bump the violated rows' weights and // re-queue their variables. void bump_weights_and_requeue(); // Fold the lazy decay's scale into vm_.weights and the cached scores // (#175); every exit from gls_loop calls it, exceptional ones included. void materialise_weights(); // Fold the last iteration into the batch's progress: running minimum of the // unweighted real-row violation and the streak since it moved. True when // the streak hits its limit and an exact re-grounding confirms it. bool track_batch_progress(double& batch_best_violation, bool watch_progress); // Read the clock and re-size the stride; true if the deadline passed. Only // on countdown expiry, off the per-iteration path. bool deadline_passed_and_retune(); // Recompute unweighted_violation_ from scratch (finite positive residuals // of active real rows). The only re-grounding of the accumulator; called at // gls_loop entry, before batch_stuck_ is set, and in // rebuild_violated_and_scan_set. void refresh_unweighted_violation(); // ApplyJump (Algorithm 2): sample up to `sample_size` vars from Q, apply the // best improving jump via update_var. Returns false if none improves. bool apply_jump(int sample_size); // UpdateVar (Algorithm 1): commit X[v] <- jump, refresh V, invalidate // neighbour jumps, replenish Q. void update_var(int32_t var_id); // Whether moving the objective's value from `before` to `after` leaves every // cached jump and Novelty verdict of the row's other variables unchanged, // so the neighbour walk can be skipped (#210). See the definition for the // cost argument. [[nodiscard]] bool objective_row_inert(double before, double after); // The objective's value as the DAG holds it now; 0.0 without an objective row. [[nodiscard]] double objective_value() const; // Whether every jumpable objective column lies in its declared box (the // finite-bound skip's premise). O(objective support). [[nodiscard]] bool objective_columns_in_box() const; [[nodiscard]] bool active(int32_t constraint_idx) const; // weight > 0 [[nodiscard]] bool jumpable(int32_t var_id) const; // scalar var // Uniform jumpable var with at least two domain values, perturb()'s // fallback; -1 if none (then a no-op kick is correct). int32_t pick_forced_perturb_var(); // The List/Set half of a kick (#111): clamp(round(p * |elements|), 1, // |elements|) typed moves per structure, plus a ListPartition member's // inter-list moves (#164). True if any variable's elements net changed (set // equality for a Set). Draws nothing on a model without List/Set. // Deadline-bounded between moves (#115). bool perturb_structural(double probability); // Reset the kick's move counter and stride tuner, once per pass. void arm_structural_kick(); // True when the structural pass must stop on the deadline (strided in // moves). Never before the first move, so a kick is never a no-op (#109). bool kick_past_deadline(); // Apply one structural move to some List/Set that can take one (the // structural pick_forced_perturb_var); false if none can. bool force_structural_move(); [[nodiscard]] bool participates_in_active_violated(int32_t var_id) const { return active_violated_of_var_[static_cast(var_id)] > 0; } void rebuild_violated_and_scan_set(); // ---- Incremental violated-row state (#174); see violated_rows_ ---- // Move row `c` into or out of V; staying in, reconcile its counted bit with // the live active(c). void set_violated(int32_t c, bool now); // Bring row c's counted bit in line with violated && active(c), adjusting // active_violated_of_var_ over the row's variable list if it changes. void reconcile_counted(int32_t c); // Re-derive the list, positions, counted bits and per-variable counts from // violated_'s in-V bits. O(#constraints + nonzeros of counted rows). void rebuild_violated_index(); // reconcile_counted over V, O(|V|); at every gls_loop entry, since weights // may change between batches. void reconcile_all_counted(); // Drop row c's contribution to active_violated_of_var_ if it is counted, // leaving it in V (kInV kept). void uncount(int32_t c); void set_initial_assignment(); void compute_linear_constraints(); /// Throw unless every per-row and per-variable table, and the /// ViolationManager's weights, are sized for the model as it is now /// (checked per batch; see the definition). void require_tables_in_step() const; // audit()'s three parts (#225): node values, V and its counts, and the jump // table with Q's completeness; audit_admits is Q's rule read off `fresh`. void audit_nodes(const Model& fresh, std::vector& out) const; void audit_violated_set(std::vector& out) const; void audit_counts(const std::vector& counts, size_t in_v, std::vector& out) const; void audit_jump_table(Model& fresh, std::vector& out) const; [[nodiscard]] bool audit_admits(int32_t v, const Model& fresh) const; void enqueue(int32_t var_id); // Novelty Jump internals (Algorithm 5): a candidate var, its W'-argmin jump // and both scores. struct NoveltyPick { int32_t var = -1; double jump = 0.0; double score = 0.0; // -W . deltaG(v, jump) double novelty_score = 0.0; // -W' . deltaG(v, jump) }; // How an ApplyNoveltyJump (Algorithm 4) ended. enum class NoveltyOutcome : uint8_t { Feasible, // a committed compound move left no active row violated LocalMin, // no compound move at the largest discrepancy budget: bump OutOfWork, // the work bound or the deadline cut the search short }; // Set up W', Q' and the stack for a Novelty run: the per-batch O(#rows) W' // init and O(nnz(V)) seed. void begin_novelty_run(); void init_novelty_weights(); void seed_novelty_scan_set(); void nj_enqueue(int32_t var_id); // `objective_before`: the objective's value before v's move or undo // (objective_value()), for the inert-row skip. void nj_requeue_neighbours(int32_t v, double objective_before); NoveltyPick select_novelty_var(double s_m, double s_c); bool novelty_jump_search(double s_m, int budget); // Algorithm 5 lines 11-16 and 20-21: one leg applied, and one undone. void nj_apply(int32_t v, double jump); void nj_undo(int32_t v, double old_value); // Algorithm 4 over the state begin_novelty_run() set up, incrementally. NoveltyOutcome novelty_descent(); // Algorithm 4 lines 3-5 for the next discrepancy level, in O(rows whose W' // moved off its level-start value) rather than O(#rows). void reset_changed_novelty_weights(); void note_novelty_weight_changed(int32_t c); // Algorithm 3 lines 8-12 inside a Novelty batch. void novelty_bump_weights(); // Multiply W' by a lazy-decay fold factor, under LazyWeightDecay::fold's rule. void fold_novelty_weights(double factor); void clear_novelty_stack(); Model& model_; ViolationManager& vm_; RNG& rng_; GFJConfig config_; JumpTable jumps_; // The GLS decay's lazy scale (#175); s != 1 only inside gls_loop. LazyWeightDecay weight_decay_; // ---- V, the violated set, kept incrementally (#174) ---- // // Per constraint two bits: kInV (in V) and kCounted (in V and active, // weight > 0, when last evaluated; counted in active_violated_of_var_). // kCounted implies kInV, so `violated_[c] != 0` reads "in V". Written only // through set_violated, reconcile_counted, uncount and // rebuild_violated_index. Derived: // - violated_rows_ + violated_pos_: V as a dense list with a position index // (-1 = absent), swap-removed on the way out; // - active_violated_of_var_: per variable, the counted rows whose // vars_of_constraint_ list names it, so participates_in_active_violated // is O(1) instead of O(|G_v|). // // Cost: any_active_violated, the Novelty seed and the bump scan are O(|V|) // plus the variable lists of the rows they queue from, instead of // O(#rows), + one O(#rows + #vars) fold per gls_loop exit that decayed; V // is visited in flip order (deterministic, not sorted). A // Novelty batch stays O(#rows) once per batch (#209). The price is a // constant per row flip (a push or swap-remove plus a walk of the row's // variable list), paid by Novelty's apply and undo too; it loses where // almost every row flips on every move, and on Novelty probes over long rows. // Memory per worker: 4 B per row, up to 4 B more per row of violated_rows_ // capacity, and 4 B per variable. // // "Active" is read live: set_violated, the bump and reconcile_all_counted // (every gls_loop entry) re-read it, so a weight changed between batches is // picked up. Nothing may change a weight while gls_loop runs. static constexpr uint8_t kInV = 1; static constexpr uint8_t kCounted = 2; std::vector violated_; // per constraint: kInV | kCounted std::vector violated_rows_; // V, dense std::vector violated_pos_; // per constraint: index in violated_rows_, or -1 std::vector active_violated_of_var_; // per var: counted rows listing it std::vector in_queue_; // per var: in Q std::vector queue_; // scan set Q (vars with possibly-positive score) // ---- The incremental Sums' drift (#188) ---- // Row -> slot of the incremental Sum it reads directly, or -1; and slot -> // rows as CSR (an MPS range row is two rows over one Sum). Built in the // constructor: 4 B per row and per slot. std::vector row_slot_; std::vector slot_rows_begin_; std::vector slot_rows_; // Rows whose verdict was undecided by drift when last evaluated, each once // (in_uncertain_). Emptied by settle_undecided_rows and the re-groundings. std::vector uncertain_rows_; std::vector in_uncertain_; // Scratch: the slots a gate or a re-grounding re-summed, and (row, value // before) for each of their rows. std::vector slot_scratch_; std::vector> row_before_; std::vector is_linear_; // per constraint // Closed-form scoring over linear rows; its eligibility is set with // is_linear_, in compute_linear_constraints. LinearJumpScorer linear_; std::vector> vars_of_constraint_; // constraint idx -> jumpable vars (G_c) // Arm/disarm the deadline and reset the stride tuner (both entry points). void arm_deadline(); std::chrono::steady_clock::time_point deadline_; // Wall-clock deadline observation (#113); untouched, and the clock unread, // while has_deadline_ is false. std::chrono::steady_clock::time_point last_deadline_check_; int64_t deadline_stride_ = 1; // iterations between clock reads int64_t deadline_countdown_ = 1; // iterations left until the next one int64_t deadline_checks_ = 0; // clock reads made inside the GLS loop // The same for the structural kick (#115), separate because the loops // advance in different units and interleave. Also untouched while // has_deadline_ is false. std::chrono::steady_clock::time_point last_kick_check_; int64_t kick_stride_ = 1; // structural moves between clock reads int64_t kick_countdown_ = 1; // moves left until the next one int64_t kick_checks_ = 0; // clock reads made inside the structural pass int64_t kick_moves_ = 0; // structural moves the last kick applied bool has_deadline_ = false; int64_t iterations_ = 0; // Armed by the search loop once stuck: after `perturbation_period` batches // without improvement, or a quarter of a wall-clock budget with no new best // (#117); cleared on every new best. Gates the Float escape probe, keeping it // a last resort. The unproductive-batch exit (#102) is deliberately not a // third route: it would leave the probe always on (#107). bool escape_probe_ = false; // ---- Unproductive-batch detection (#102) ---- // // Without it, before the first feasible solution the kick cadence is a // fixed one per perturbation_period * batch_iterations iterations. GLS // weights alone cannot break a limit cycle under either rho (#102), so a // batch ends after GFJConfig::unproductive_iterations iterations without a // new minimum of this measure; any new minimum resets the count, so a // descending batch is never cut. // // A batch whose measure is zero is never declared stuck: the measure sums // real rows only, so once they are satisfied it cannot improve, and the // search there descends against the objective row. Exact zero is not // enough after feasibility either (a positive equilibrium; equalities // never reach 0), so the exit also needs the outer loop's witness // (watch_progress_): solve() arms it only after perturbation_period / 20 // non-improving batches, making it an acceleration of the stagnation window, // not a replacement. A search that keeps improving never arms it and is // bit-identical to one without the mechanism. // // The measure: sum of the finite positive residuals of the active real // rows. Unweighted, because GLS bumps move the weighted total without the // assignment moving. Real rows only: the `obj <= bound` row can clamp at // kInfPenalty = 1e30 (#116), which would swallow every real row (#100, // #118). Built per constraint in update_var (each row's own before/after // differenced), so an unchanged row contributes exactly 0. +inf/NaN // residuals contribute 0, the same in the fresh and incremental forms. // // Drift is bounded three ways: re-grounding at every gls_loop entry (error // stays within one batch's roundings); a relative progress floor // (kProgressRelEps); and an exact recompute before batch_stuck_ is set, // one O(rows) sweep per unproductive_iterations iterations. // // Relative floor on what counts as a new minimum. static constexpr double kProgressRelEps = 1e-9; double unweighted_violation_ = 0.0; // Armed at begin() and re-decided by solve() before every batch (the // second witness above); stays armed for a caller driving batch() directly. bool watch_progress_ = true; int64_t unproductive_streak_ = 0; bool batch_stuck_ = false; // Index of the `obj <= bound` row in constraint_ids(), or -1 without an // objective; fixed at close(), cached for the hot path. int32_t objective_ci_ = -1; // The objective row's max single-variable variation over its jumpable // variables (OR-Tools' row_max_variations), built on first need by // objective_row_inert. NotAffine: no slopes, the skip never applies. enum class ObjectiveSlopes : uint8_t { Unbuilt, Built, NotAffine }; ObjectiveSlopes objective_slopes_ = ObjectiveSlopes::Unbuilt; // Per-variable coefficient of an affine objective (#218), read at // construction under GFJConfig::objective_tie_break; empty = off. std::vector objective_coef_; // compute_var_jump's tie-break handle for var_id; null when off. [[nodiscard]] const double* objective_tie(int32_t var_id) const { return (config_.objective_tie_break && !objective_coef_.empty()) ? &objective_coef_[static_cast(var_id)] : nullptr; } // Whether var_id can still lower the objective inside its box (OR-Tools' // HasBetterObjectiveValue): what keeps it in Q under objective_tie_break. [[nodiscard]] bool objective_scan(int32_t var_id) const; // Q's membership rule: a variable of an active violated row, or, under // objective_tie_break, one objective_scan admits. [[nodiscard]] bool should_scan(int32_t var_id) const { return participates_in_active_violated(var_id) || (config_.objective_tie_break && objective_scan(var_id)); } double objective_max_variation_ = 0.0; // objective_columns_in_box() as of the last rebuild_violated_and_scan_set. // False disables the finite-bound skip until the next rebuild: an // out-of-box value (via the API plus `skip_init`) can move a jump further // than M. FJ's own moves stay in the box. bool objective_in_box_ = true; int64_t objective_skips_fj_ = 0; // see objective_walks_skipped() int64_t objective_skips_novelty_ = 0; // see novelty_objective_walks_skipped() // Novelty Jump state (Algorithms 4-5). static constexpr double kCompoundDiscount = 1.0 / 1024.0; // epsilon (OR-tools value) static constexpr int64_t kNoveltyWorkBudget = 256; // max moves applied per apply_novelty_jump static constexpr int64_t kNoveltySample = 3; // vars select_novelty_var keeps (paper §4) int64_t nj_work_remaining_ = 0; // bounds compound-move search cost int64_t nj_moves_this_call_ = 0; // see novelty_moves_last_call() int64_t nj_move_cost_ = 1; // work units a move takes from nj_work_remaining_ int64_t novelty_moves_ = 0; // see novelty_moves() int64_t novelty_commits_ = 0; // see novelty_commits() int64_t novelty_bumps_ = 0; // see novelty_weight_bumps() int64_t novelty_seeds_ = 0; // see novelty_scan_set_seeds() std::vector novelty_weights_; // W' // Rows whose W' may differ from its level-start value, each once (OR-Tools' // compound_weight_changed). See reset_changed_novelty_weights. std::vector nw_changed_; std::vector nw_in_changed_; // per row: on nw_changed_ std::vector nj_queue_; // novelty scan set Q std::vector nj_in_queue_; // per var: in the novelty scan set std::vector on_stack_; // per var: on the compound-move stack (the paper's T) struct StackMove { int32_t var; double old_value; }; std::vector move_stack_; }; } // namespace cbls formatter.h =========== .. code-block:: c #pragma once #include "model.h" #include "search.h" #include #include namespace cbls { class HumanFormatter : public SolveCallback { public: explicit HumanFormatter(std::ostream& out = std::cout) : out_(out) {} void print_header(const std::string& model_path, const Model& model, uint64_t seed, double time_limit); void on_progress(const SolveProgress& p) override; void print_result(const SearchResult& result, const Model& model); private: std::ostream& out_; // The model's sense, read at print_header: the engine reports a maximised // objective negated (it minimises -f), and this prints f (#225). bool maximizing_ = false; }; class JsonlFormatter : public SolveCallback { public: explicit JsonlFormatter(std::ostream& out = std::cout) : out_(out) {} void print_header(const std::string& model_path, const Model& model, uint64_t seed, double time_limit); void on_progress(const SolveProgress& p) override; void print_result(const SearchResult& result, const Model& model); private: std::ostream& out_; // As `HumanFormatter::maximizing_` (#225). bool maximizing_ = false; }; } // namespace cbls inner_solver.h ============== .. code-block:: c #pragma once #include "model.h" #include "stop.h" #include "violation.h" #include #include namespace cbls { // The extension point for a problem-specific solver (#452, #454). Contract: // - The search calls solve() after every batch that ends real-feasible // (ViolationManager::max_real_violation() within // SearchConfig::feasibility_tolerance), after that point is offered to the // incumbent; with wants_infeasible() also after every other batch, // uncapped, so such a hook budgets itself. // - It mutates the model directly and leaves it fully evaluated. The search // records the result only if it is real-feasible and strictly better than // this worker's incumbent (model.objective_bound() sits below that: it is // the target the search pushes toward, not the acceptance test). A worker's // first feasible point is recorded even with a non-finite objective (#100). // It does // not roll the hook's point back: it resyncs and continues from it, unless // a diversification kick due in the same pass replaces it (restoring the // kick origin or adopting a pool point). So a hook may repair an // infeasible point; one that cannot should leave it. // - On a run that ends infeasible, the closest approach reported is taken // from batch ends, before the hook: the hook's own result counts only if // a later batch ends on it unchanged. // - One hook object serves every solve() it is passed to: under // ParallelSearch a worker keeps its hook across pool restarts while the // incumbent and bound start over, so state it carries must stay valid then. // - Hooks are C++ only (no nanobind trampoline). A call that does nothing still // costs a resync and counts in SearchCounters::inner_solver_calls. class InnerSolverHook { public: virtual ~InnerSolverHook() = default; // Mutates the model directly (var values + delta_evaluate). // last_changed_vars: var IDs of the last accepted jump, empty when // untracked (after a perturbation or LNS repair); the search passes {}. // // stop (#191): requested once the deadline passes, a peer stops the // portfolio, or the host cancels. The search cannot preempt this call, so // a hook that can outlast the budget must poll it and return promptly, // leaving every committed value delta-evaluated. With no wall clock it // reads no clock, so an iteration-budgeted run stays bit-reproducible; the // default (direct calls) is never requested. Valid only until solve() // returns: the hook's own threads may poll it during the call, not after. // // A parameter, not a second virtual: with two, a subclass that overrode // only the stop-less one was silently bypassed by the search. An // old-signature override fails to compile // if marked `override` or if it left a direct subclass abstract; UNMARKED // in a FloatIntensifyHook subclass it compiles and is hidden, flagged only // by -Woverloaded-virtual (GCC 15 -Wall, clang-tidy), not use-override. virtual void solve(Model& model, ViolationManager& vm, const std::vector& last_changed_vars = {}, StopRef stop = {}) = 0; // Opt-in (#454): also call solve() after a batch that ends infeasible, so a // hook that can repair the point is not starved where the search rarely // lands feasible. Read once per such batch, before the deadline check. [[nodiscard]] virtual bool wants_infeasible() const { return false; } }; // Generic Float intensification: coordinate-descent sweeps over all Float vars // using Newton steps on violated constraints + gradient steps on objective. class FloatIntensifyHook : public InnerSolverHook { public: int max_sweeps = 3; double initial_step_size = 0.1; int max_line_search_steps = 5; int max_multi_var_constraints = 5; // Polls `stop` before each sweep's first Float variable, then every // vars_per_poll(model) Float variables, and before every multi-variable // Newton step; returns at the first raised poll. Each unit between polls // commits or rolls back whole, so an early return leaves a consistent // model. A never-raised `stop` leaves the descent unchanged. void solve(Model& model, ViolationManager& vm, const std::vector& last_changed_vars = {}, StopRef stop = {}) override; // Float variables between two polls: 65536 / max(rows, nodes), clamped to // [1, 256] (argument in src/inner_solver.cpp). Public so tests can predict // the poll sequence. static int vars_per_poll(const Model& model); }; } // namespace cbls io.h ==== .. code-block:: c #pragma once #include "model.h" #include #include namespace cbls { Model load_model(const std::string& path); Model load_model(std::istream& input); void save_model(const Model& model, const std::string& path); void save_model(const Model& model, std::ostream& out); } // namespace cbls io_mps.h ======== .. code-block:: c #pragma once // MPS / .solu reader interface for CBLS. // // The reader implementation is vendored from spoorendonk/mipx // (https://github.com/spoorendonk/mipx) and adapted to populate the // minimal POD `MpsProblem` defined here instead of the heavier // `mipx::LpProblem`. // // The MPS-to-Model adapter (`mps_to_model`) builds a closed CBLS // `Model` from an `MpsProblem`. #include "bound_propagation.h" #include "model.h" #include #include #include #include namespace cbls { inline constexpr double kMpsInf = std::numeric_limits::infinity(); /// Variable kind from MPS COLUMNS / BOUNDS sections. enum class MpsVarKind : uint8_t { Continuous, Integer, Binary, }; /// Constraint sense from MPS ROWS section. /// 'N' rows are not stored as constraints — the first 'N' row becomes the /// objective; any further 'N' rows are ignored. enum class MpsRowSense : uint8_t { L, ///< <= rhs G, ///< >= rhs E, ///< == rhs }; struct MpsVar { std::string name; double lb = 0.0; ///< MPS default 0; -inf if FR/MI applied. double ub = kMpsInf; ///< MPS default +inf; finite if UP/UI/BV/FX. MpsVarKind kind = MpsVarKind::Continuous; }; struct MpsRow { std::string name; MpsRowSense sense = MpsRowSense::L; double rhs = 0.0; /// Range value (0 if absent). Interpretation depends on `sense`: /// L: lower = rhs - |range|, upper = rhs /// G: lower = rhs, upper = rhs + |range| /// E: range > 0 -> [rhs, rhs+range] /// range < 0 -> [rhs+range, rhs] double range = 0.0; }; /// One nonzero coefficient of the constraint matrix or objective. /// `row_idx == -1` denotes the objective row (the first MPS 'N' row). struct MpsNonzero { int32_t row_idx = -1; int32_t col_idx = -1; double value = 0.0; }; struct MpsProblem { std::string name; std::string objective_row_name; ///< First 'N' row name; empty if none. double objective_offset = 0.0; ///< From RHS of the objective row. /// True if the MPS had `OBJSENSE MAX|MAXIMIZE`. The reader records this /// faithfully; `mps_to_model` currently rejects it (CBLS expects min). bool maximize = false; std::vector vars; std::vector rows; std::vector nonzeros; ///< (row_idx, col_idx, value); row_idx = -1 = objective. }; /// Read an MPS file (fixed or free format). Auto-detects `.gz` for gzip. /// If CBLS was built with `CBLS_USE_BZIP2`, also handles `.bz2`. MpsProblem read_mps(const std::string& filename); /// Entry from a MIPLIB `.solu` file. struct SoluEntry { std::string name; double value = 0.0; bool is_infeasible = false; ///< true for `=inf=` lines. bool is_optimal = false; ///< true for `=opt=` lines (false otherwise). }; /// Read a MIPLIB-style `.solu` file with known optimal / infeasible tags. std::vector read_solu(const std::string& filename); /// Build a closed CBLS `Model` from an `MpsProblem`. /// /// One CBLS variable per MPS column (Int when kind != Continuous, otherwise /// Float). One linear constraint per row, sense translated from `MpsRowSense`. /// Objective is the linear cost expression from the 'N' row (plus `offset`). /// /// CBLS variables require finite bounds, so a column with an infinite one has /// to acquire a finite substitute. `propagate_bounds` derives that bound from /// the constraints (see `bound_propagation.h`), which cannot remove a feasible /// point; `inf_clamp` is the fallback where propagation finds no finite bound, /// and *can* lose solutions, so it is only ever consulted last. struct MpsToModelOptions { double inf_clamp = 1.0e9; /// Derive implied bounds from the rows before falling back on `inf_clamp`. bool propagate_bounds = true; /// Fixed-point iteration cap for that pass; see `BoundPropagationOptions`. int max_propagation_passes = 10; }; struct MpsToModelResult { Model model; /// `var_handles[i]` is the CBLS variable handle (negative encoding /// `-(var_id + 1)`) for MPS column `i`. std::vector var_handles; /// `constraint_node_ids[i]` is the constraint expression node id for MPS /// row `i`. A range row, and an `E` row with a RANGES entry, adds a second /// constraint not listed here. The listed one is `>=` for a `G` row, `<=` /// for `L` and ranged `E`. std::vector constraint_node_ids; int32_t objective_node_id = -1; ///< -1 if the MPS had no 'N' row. /// Outcome of the propagation pass; all-zero when it was disabled. BoundPropagationStats bound_stats; /// Columns whose bounds `inf_clamp` or the int32 clip still had to supply /// after propagation, i.e. where the unsound fallback was actually used. int n_clamped_columns = 0; /// The model's current point as one value per MPS column. /// `model` must be this result's model (or a copy of it). [[nodiscard]] std::vector original_values(const Model& model) const; }; MpsToModelResult mps_to_model(const MpsProblem& prob, const MpsToModelOptions& opts = {}); } // namespace cbls io_nl.h ======= .. code-block:: c #pragma once // AMPL NL reader interface for CBLS. // // The NL format is the AMPL solver interface "nl" file. This reader handles // both variants: text (header begins with 'g') and binary ('b'), the latter // only in the host's byte order. The format is publicly specified by David Gay, // "Writing .nl Files" (https://ampl.github.io/nlwrite.pdf) and "Hooking Your // Solver to AMPL" (https://ampl.com/REFS/hooking2.pdf); this is an original // implementation from those public specifications and carries no third-party // license. // // The reader populates the minimal POD `NlProblem` defined here. The // NL-to-Model adapter (`nl_to_model`, in src/io/nl_to_model.cpp) builds a closed // CBLS `Model` from an `NlProblem`, skipping (not throwing on) instances whose // operator set is unsupported. #include "bound_propagation.h" #include "model.h" #include #include #include #include namespace cbls { inline constexpr double kNlInf = std::numeric_limits::infinity(); /// One expression-graph node, stored in postfix-free prefix form: each segment /// of the file is parsed into a small tree of these. Children are indices into /// the owning expression's `nodes` vector. enum class NlNodeKind : uint8_t { Num, ///< numeric constant (value in `num`) Var, ///< variable reference (index in `index`) Op, ///< operator (opcode in `opcode`, children in `children`) }; struct NlExprNode { NlNodeKind kind = NlNodeKind::Num; double num = 0.0; ///< Num: constant value int32_t index = -1; ///< Var: variable index int32_t opcode = -1; ///< Op: AMPL opcode (see nl_reader.cpp table) std::vector children; ///< Op: child node indices into the same expr }; /// A nonlinear expression: a flat node pool with a designated root. An empty /// pool (root == -1) means "no nonlinear part" (the segment was absent / 0). struct NlExpr { std::vector nodes; int32_t root = -1; [[nodiscard]] bool empty() const { return root < 0; } }; /// Bound/constraint type codes from the NL `r` (constraint) and `b` (variable) /// segments. The numeric encoding matches the NL spec exactly. enum class NlBoundType : uint8_t { Range = 0, ///< lower <= body <= upper (two finite bounds) Upper = 1, ///< body <= upper (<=) Lower = 2, ///< body >= lower (>=) Free = 3, ///< no bound Equal = 4, ///< body == value }; struct NlVarBound { NlBoundType type = NlBoundType::Free; double lower = -kNlInf; double upper = kNlInf; }; struct NlConBound { NlBoundType type = NlBoundType::Free; double lower = -kNlInf; double upper = kNlInf; }; /// One linear coefficient (variable index, value). struct NlLinTerm { int32_t var = -1; double coef = 0.0; }; struct NlConstraint { NlExpr nonlinear; ///< nonlinear part (may be empty) std::vector linear; ///< linear part from the `J` segment NlConBound bound; }; struct NlObjective { bool maximize = false; ///< NL O-segment sense (0=min, 1=max) NlExpr nonlinear; ///< nonlinear part (may be empty) std::vector linear; ///< linear part from the `G` segment }; /// A defined variable (an NL `V` segment, AMPL's common subexpression): its value /// is `sum(linear) + nonlinear`. Expressions reference it as `v`. struct NlDefinedVar { bool defined = false; ///< false until its `V` segment is read std::vector linear; ///< linear part (terms may name other defined vars) NlExpr nonlinear; ///< nonlinear part (may be the constant 0) }; struct NlProblem { std::string name; int32_t n_vars = 0; int32_t n_cons = 0; int32_t n_objs = 0; /// Defined-variable count from the header's common-expression line /// (comb + comc + como + comc1 + como1). Not columns: the model inlines them. int32_t n_defined_vars = 0; /// Total integer/binary variable count from the NL header's discrete-variable /// line (nbv + niv + nlvbi + nlvci + nlvoi). int32_t n_discrete_vars = 0; /// Per-column integrality, size n_vars: 1 if NL column j is an integer or /// binary variable. Recovered from the header counts plus Gay's variable /// ordering (see `nl_reader.cpp`); `sum(var_is_discrete) == n_discrete_vars`. std::vector var_is_discrete; std::vector var_bounds; ///< size n_vars (from `b`) std::vector initial_x; ///< size n_vars; from `x`, NaN if unset std::vector constraints; ///< size n_cons std::vector objectives; ///< size n_objs /// size n_defined_vars; entry k is NL variable `n_vars + k`. std::vector defined_vars; }; /// Read an AMPL NL file, text ('g' header) or binary ('b'). Throws /// std::runtime_error on a malformed file or a binary one in a byte order /// other than the host's. NlProblem read_nl(const std::string& filename); /// Parse NL from an already-loaded buffer, text or binary (used by tests with /// inline fixtures). `name` labels the resulting problem. NlProblem parse_nl(const std::string& text, const std::string& name = ""); /// Build a closed CBLS `Model` from an `NlProblem`. /// /// One CBLS variable per NL column: Int for columns flagged in `var_is_discrete`, Float /// otherwise. A defined variable (`V` segment) is not a column: it is inlined, /// built once as an expression node that every use shares. Each constraint body /// (`nonlinear + linear`) is translated to one or two CBLS comparison /// constraints from its `r` bound. The first objective is used; its sense /// drives minimize/maximize. /// /// Unsupported operators do NOT throw: `supported` is set false and a reason is /// appended to `skipped_reasons`. On an unsupported instance the returned model /// is left un-closed and should not be solved. struct NlToModelOptions { /// Derive implied bounds from the linear rows (a row whose nonlinear part /// is absent or a lone constant: AMPL's `n0` rows included) before falling /// back on the clamps below (see `bound_propagation.h`). An implied bound /// cannot cut off a feasible point; a clamp can, so it is only ever /// consulted last. bool propagate_bounds = true; /// Fixed-point iteration cap for that pass; see `BoundPropagationOptions`. int max_propagation_passes = 10; /// ±inf variable bounds clamped to this magnitude. Where the column's other /// side is finite and already at or beyond it, the missing side is placed /// this far beyond that bound instead, so the box keeps the bound (#357). double inf_clamp = 1.0e9; /// ±inf bounds on an *integer* column clamp to this instead, by the same /// rule relative to a finite other side. A ±1e9 integer /// domain is not a searchable space; unbounded integers in practice mean /// "small non-negative count", so a far tighter box is the useful default. double int_inf_clamp = 1.0e6; }; struct NlToModelResult { Model model; /// `var_handles[i]` is the CBLS variable handle for NL column `i`. std::vector var_handles; /// `constraint_node_ids[i]` is the *primary* constraint node for NL row `i` /// (the second node of a range row is added to the model but not recorded): /// the upper side of a range. -1 for a Free row. std::vector constraint_node_ids; int32_t objective_node_id = -1; ///< -1 if no objective bool supported = true; ///< false if any operator was unsupported std::vector skipped_reasons; /// Outcome of the propagation pass; all-zero when it was disabled. BoundPropagationStats bound_stats; /// Columns whose bounds a clamp still had to supply *after* propagation, /// i.e. where the unsound fallback was actually used. int n_clamped_columns = 0; /// The model's current point as one value per NL column. /// `model` must be this result's model (or a copy of it). [[nodiscard]] std::vector original_values(const Model& model) const; }; NlToModelResult nl_to_model(const NlProblem& prob, const NlToModelOptions& opts = {}); } // namespace cbls lns.h ===== .. code-block:: c #pragma once #include "model.h" #include "rng.h" #include "violation.h" #include #include #include #include #include namespace cbls { class LinearRowStore; class NeighbourList; /// The key the built-in LNS accepts a repair on, compared lexicographically: /// (real violation, objective). The real violation sums each row's residual /// ABOVE `tol` -- a row at or below it is satisfied and adds nothing -- over /// every row but the artificial `obj <= bound`; a NaN row makes it +inf, and a /// NaN objective ranks as +inf. Public so the rule can be tested directly. std::pair lns_acceptance_key(const Model& model, double tol); /// Destroy-and-repair diversification for the ViolationLS loop. /// /// Two destroy/repair pairs, by variable kind (#202): /// /// - Every `ListPartition`'s members are ruined and recreated (ASB-RR/SISR, /// Christiaens & Vanden Berghe, Transportation Science 54(2) 2020, with the /// paper's parameters; `ruin_recreate_partition` in src/lns.cpp lists the /// two departures): strings are removed from a few lists and reinserted one /// by one at their best position under the acceptance key, probed through /// the DAG. FJ cannot move a List, so perturb-then-FJ only worsens routes. /// - Every other variable: a random `destroy_fraction` is randomised and an /// FJ pass repairs it. A model with no partition draws as it always did. /// /// An extension point, like InnerSolverHook: `solve()` takes an `LNS*` and /// `ParallelSearch` a `shared_ptr` factory, so C++ can override /// `destroy_repair`. C++ only: the binding has no trampoline, so a Python /// override is never dispatched to and this base runs instead. The virtual /// destructor serves deletion through a base `LNS*` and nanobind's /// polymorphic downcast (#129). class LNS { public: explicit LNS(double destroy_fraction = 0.3); virtual ~LNS(); // Move-only: the FPR repair's engine is bound to one store (#431). LNS(LNS&&) noexcept; LNS& operator=(LNS&&) noexcept; // `repair_time_limit` seconds bound the FJ repair; <= 0 leaves only its // iteration budget, which makes it deterministic. `solve()` passes // `min(2.0, remaining budget)`: no early kick monopolises a long run, no // late one overruns the deadline. An override must honour it, or `solve()` // breaks its wall-clock budget. // // NO DEFAULT ARGUMENT: defaults bind statically, so through an `LNS*` (how // `solve()` calls) an override's default would be silently ignored. // `destroy_repair_cycle` is non-virtual, so its default is safe. virtual bool destroy_repair(Model& model, ViolationManager& vm, RNG& rng, double repair_time_limit); int destroy_repair_cycle(Model& model, ViolationManager& vm, RNG& rng, int n_rounds = 10, double repair_time_limit = 2.0); /// The residual a row may keep and count as satisfied, in the repair's FJ /// and the acceptance key (which clamps each row to 0 at or below it, so /// feasible states rank by objective, not rounding noise, #211). `solve()` /// sets it to `SearchConfig::feasibility_tolerance` before each kick. void set_feasibility_tolerance(double tol) { feasibility_tolerance_ = tol; } [[nodiscard]] double feasibility_tolerance() const { return feasibility_tolerance_; } /// The relatedness the partition ruin draws strings by: each element's /// neighbours, nearest first (#202). `solve()` sets it from /// `SearchConfig::structural_neighbours` before each kick. Null (default): /// after the seed, strings are taken near randomly drawn elements. void set_neighbours(std::shared_ptr neighbours) { neighbours_ = std::move(neighbours); } [[nodiscard]] const std::shared_ptr& neighbours() const { return neighbours_; } /// Fix-propagate-repair before the scalar repair's FJ (#431): the linear /// rows of the model being repaired, built by `solve()` when /// `SearchConfig::lns_repair_fpr` is on, set before each kick and cleared /// when the solve ends. Null (default): plain FJ repair, drawing exactly as /// before. With a store, each round fixes the kept scalars at their /// incumbent values (clamped to their bounds) under propagation (a conflict, or the repair /// deadline, skips FPR for the round), dives once over the destroyed ones from their randomised /// values, writes their values, then FJ repairs. The propagator and engine are built on the /// first round with a new store; a refuted root skips FPR for good. The store must be built /// from the model repaired, with the feasibility tolerance as its `row_tolerance` (as `solve()` /// does) so that a kept value a row only just accepts holds (#433); one of another width skips /// FPR. void set_repair_store(std::shared_ptr store); [[nodiscard]] const std::shared_ptr& repair_store() const { return repair_store_; } /// What the FPR repair did, summed over this LNS's rounds (#431). struct FprRepairStats { int64_t dives = 0; ///< rounds that ran a dive and wrote its values int64_t kept_conflicts = 0; ///< rounds whose kept values propagation refuted int64_t root_refuted = 0; ///< rounds skipped: the linear rows refute the root int64_t nodes = 0; ///< dive nodes, summed /// Rounds the repair deadline stopped before the dive, so plain FJ (#434). int64_t deadline_stops = 0; }; [[nodiscard]] const FprRepairStats& fpr_repair_stats() const { return fpr_stats_; } protected: // Holds the kept scalars and writes one dive's values into `destroyed`; // `deadline` (nullable) stops the dive, and the setup before it (#434). // True when values were written. bool fpr_repair(Model& model, const std::vector& destroyed, RNG& rng, const std::chrono::steady_clock::time_point* deadline); private: struct FprRepair; double destroy_fraction_; double feasibility_tolerance_ = kDefaultFeasibilityTolerance; std::shared_ptr neighbours_; std::shared_ptr repair_store_; std::unique_ptr fpr_; // over `repair_store_`, built lazily FprRepairStats fpr_stats_; }; } // namespace cbls model.h ======= .. code-block:: c #pragma once #include "dag.h" #include #include #include #include #include #include #include #include #include #include #include namespace cbls { class Expr; struct VarSequence { std::vector var_ids; // ordered variable IDs in this sequence int min_block_on = 1; // minimum consecutive vars to set to 1 int min_block_off = 1; // minimum consecutive vars to set to 0 }; /// How completely a `ListPartition` covers its shared universe (#164). enum class Cover : uint8_t { /// Every element of the universe is in EXACTLY one of the partition's lists. Exact, /// Every element is in AT MOST one of them; the rest are unassigned. AtMostOnce, }; /// A group of List variables over one shared universe whose membership is /// maintained BY THE MOVES rather than by a penalty row (#164). /// /// As a soft row, "each element exactly once" forces every repair through a /// doubly-served or unserved state; inter-list relocate, swap and 2-opt* /// preserve it instead. So the engine never proposes a move that breaks it: /// `list_moves` emits no `list_insert`/`list_remove` for a member /// (`Variable::partitioned`), and `generate_partition_moves` proposes the /// inter-list moves that keep it. /// /// There is no `unassigned(partition)` view, deliberately (#164): a skip /// penalty is already `sum_e p(e) - sum_{lists L} lambda_sum(L, p)`, the first /// term a constant, while a shadow Set variable would need excluding from /// randomisation, the structural sweep, the kick, LNS destroy and `set_moves`. struct ListPartition { std::vector list_ids; ///< member variable IDs, in the order given Cover cover = Cover::Exact; int32_t universe_size = 0; ///< the universe every member shares }; /// The functor of a `lambda_sum` / `pair_lambda_sum` that reads other decisions /// (#186): the element (or pair) first, then the CURRENT values of the node's /// `extra` children, in the order they were given. The span is valid for the /// duration of the call only. using LambdaExtraFunc = std::function)>; using PairLambdaExtraFunc = std::function)>; /// The data of one `Element` node (#186): a `rows x cols` table, row-major. A /// one-index node has `cols == 1` and reads `values[i]`; a two-index node reads /// `values[i * cols + j]`. Which of the two a node is, is its child count. struct ElementTable { int32_t rows = 0; int32_t cols = 0; std::vector values; /// Representative indices, computed once at build: the index candidates /// `compute_var_jump` offers when a table is too large to offer every index /// (#186). `row_reps_by_col[c]` are rows of column `c` -- the candidates for /// the row index while the column index reads `c` -- and `col_reps_by_row[r]` /// the columns of row `r`; a one-index table has one column and no /// `col_reps_by_row`. Each list holds, for up to 32 of the line's distinct /// values picked at evenly spaced ranks (the smallest and the largest /// always among them), the first index holding that value. std::vector> row_reps_by_col; std::vector> col_reps_by_row; }; /// Convert variable handle (negative, from int_var/float_var/etc.) /// to var ID (non-negative, for model.var()/model.var_mut()). inline int32_t handle_to_var_id(int32_t handle) { return -(handle + 1); } /// The floor of a `Log` argument's implicit domain row (#248): SCIP's /// `expr/log/minzerodistance` default, which cuts off (0, 1e-9) as SCIP does. inline constexpr double kLogDomainFloor = 1e-9; /// Everything about a model that no search writes: the DAG's nodes and edges, /// the derived indices over them, the constraint list, the lambda tables and the /// variable sequences. A FROZEN model hands it to every portfolio worker by /// reference instead of deep-copying it per worker (#157). /// /// Reached only through `Model`'s accessors, and after `Model::freeze()` only /// through a `shared_ptr`, so a write to it from a search /// path does not compile rather than corrupting a peer's search. /// /// NOT here: what a search writes (node values, variables, the objective bound, /// the probe scratch), and the structural scalars (`objective_id_`, /// `is_maximizing_`, the objective-row node ids, `closed_`): immutable after /// `freeze()` too, but twenty bytes per worker is not worth an indirection. struct ModelStructure { std::vector nodes; // The DAG's edges, flat (#156): per-node and per-variable vectors cost a few // small allocations per node at build and a deep copy of all of them per // portfolio replica. // // `child_refs` is append-only: a node's children are written when the node // is made and addressed by its (child_begin, child_count), so they are // readable before close(). The two back-reference arrays are CSR, rebuilt // wholesale by `Model::rebuild_back_references`: the parents of node `i` are // `parent_ids[parent_offsets[i] .. parent_offsets[i + 1])`, and likewise // for variables. Once its owner array is non-empty, each offsets array holds // at least one entry more (creating a node or variable appends an empty // range first), so the accessors, which range-check the id against the // owner first, need no "not built yet" branch, and a node made after a // rebuild reads as parentless. Hence Model hands out no mutable nodes or // vars vector: an element that bypassed push_node/alloc_var would have no range. std::vector child_refs; std::vector parent_offsets; std::vector parent_ids; std::vector dependent_offsets; std::vector dependent_ids; std::vector topo_order; /// Inverse of `topo_order`: node id -> its index there. Rebuilt with it, /// and only ever read through `Model::topo_position`. std::vector topo_pos; std::vector constraint_ids; /// The implicit domain rows (#248), set once by `Model::append_domain_rows`: /// the modeller's rows are `constraint_ids[0 .. num_user_constraints)`, the /// domain rows the next `num_domain_rows`, and the objective row, if any, /// comes after them. The domain rows' nodes are the ids /// `[domain_node_begin, domain_node_end)`. -1 until the rows are appended. int64_t num_user_constraints = -1; int32_t num_domain_rows = 0; int32_t domain_node_begin = -1; int32_t domain_node_end = -1; // var_id -> constraint indices (G_v), CSR like the back-references above. // Empty until close(), then sized for the variables that existed at the last // build: unlike dependent_offsets it is NOT grown by the builders, which keeps // constraints_of_var's range check meaningful before close(). std::vector var_constraint_offsets; std::vector var_constraint_ids; // Shared, so invoked by every worker CONCURRENTLY once a model is frozen and // replicated: a callable carrying mutable state of its own is a data race, // however that state is captured. `Model::freeze` states it for callers. std::vector> lambda_funcs; std::vector> pair_lambda_funcs; // Parallel to `pair_lambda_funcs` and the same length: entry i is the // closing rule and the fixed-endpoint terms of the node whose // `lambda_func_id` is i. See `PairLambdaSpec` in dag.h for why this is a // side table rather than more `NodeOp` enumerators. std::vector pair_lambda_specs; // #186. Shared as `lambda_funcs` is, with the same race on a callable's own // mutable state. The mode table is parallel to `pair_lambda_extra_funcs` // and kept the same length. std::vector lambda_extra_funcs; std::vector pair_lambda_extra_funcs; std::vector pair_lambda_extra_modes; std::vector element_tables; /// Whether any node is an `Element`, `Ceil`, `Floor` or `Round` -- the ops /// whose plateaus `compute_var_jump` offers as jump candidates (#186). A /// model without one keeps its pre-#186 candidate generation unchanged and /// skips the per-variable walk that would find nothing to add. bool has_breakpoint_nodes = false; /// Per node, rebuilt with the topological order: `kReachesBreakpoint` (only /// when `has_breakpoint_nodes`) on a breakpoint node and on every node that /// reaches one through ops that carry a slope (`carries_slope`), and /// `kRepeatedChild` on every Sum that names a child more than once. The /// first gates FJ's breakpoint walk per variable and prunes it; the second /// is what lets that walk and `UpConePartials` (#249) count `x + x` as /// slope 2 without scanning every Sum's children. std::vector breakpoint_flags; static constexpr uint8_t kReachesBreakpoint = 1; static constexpr uint8_t kRepeatedChild = 2; /// Slot -> node id of every incremental Sum (`ExprNode::kIncSum`, #188), in /// topological order. A Sum's slot is its `lambda_func_id`. std::vector inc_sum_nodes; std::vector var_sequences; std::vector> var_to_seq; // var_id -> (seq_idx, pos), resized lazily std::vector list_partitions; std::vector var_to_partition; // var_id -> partition index (-1), resized lazily /// Each variable's dirty cone in topological order (#271): every node above /// it, the nodes a one-variable walk recomputes. Built by `Model::freeze()` /// only, so an open or merely closed model has none. CSR like the /// back-references, over the first `cone_prefix` variables only: variable /// `v < cone_prefix` has its cone in `cone_ids[cone_offsets[v] .. /// cone_offsets[v + 1])`. Variable `cone_prefix` is the first whose cone /// would have crossed the byte cap; it and every later one have none. std::vector cone_offsets; std::vector cone_ids; size_t cone_prefix = 0; }; /// One incremental Sum's per-model state (#188; see `ExprNode::kIncSum` and /// the incremental-Sum section of `src/dag_ops.cpp`). struct IncSumState { /// An upper bound on |the Sum's node value - the real sum of its stored /// terms|: the exact rounding errors of its last checked re-sum plus those /// of every inexact update since, rounded up. 0 when every one of them was /// exact -- always, on integral data whose partial sums stay within 2^53. double drift_bound = 0.0; /// Inexact updates since the last checked re-sum: what `kIncSumPeriod` /// counts. uint32_t inexact = 0; /// 1 once a checked re-sum has set `drift_bound`. `full_evaluate` re-sums /// without the check and clears it, so a Sum's first commit after one /// re-sums instead of updating. uint8_t tracked = 0; /// 1 while the value may differ from a re-sum of the current terms: it was /// updated since the last re-sum and `drift_bound` is not 0. Not only after /// an inexact update -- a re-sum's own rounding, carried through exact /// updates, is no longer the rounding a re-sum of the new terms would make. /// A Sum not drifting is exact (bound 0) or a fresh re-sum. uint8_t drifting = 0; /// On `IncSums::drifted`. uint8_t listed = 0; }; /// The per-model side of every incremental Sum (#188). Per model because it /// describes `node_values_`. struct IncSums { /// Indexed by slot (the `lambda_func_id` of a `kIncSum` Sum). std::vector slots; /// Slots that started drifting since `reground_drifted_sums` last emptied /// the list, each once. Some may have been re-summed since. std::vector drifted; }; /// The undo log of the last `Probe` walk (#270), which the matching `Rollback` /// writes back instead of walking the cone again. Per model because it /// describes `node_values_`. `delta_evaluate` and its siblings in /// src/dag_ops.cpp arm and spend it; every writer of node values outside a /// walk must drop it (`pending`). See `DeltaMode::Rollback`. struct ProbeUndo { /// The probe's changed-variable set, as it was passed: a `Rollback` over /// any other set is not this probe's. std::vector vars; /// Every node of the probe's cone with its value before the probe, so the /// write-back is exact by construction -- an incremental Sum's drift (#188) /// included. (node id, value). std::vector> values; /// Armed by a `Probe`, spent by the `Rollback` and dropped by every other /// walk, `full_evaluate`, `reground_inc_sum`, `set_objective_bound` and /// `set_domain_tolerance`: each rewrites node values, after which the log /// no longer describes anything to roll back to. A new out-of-walk writer /// of node values must drop it too, or its write is undone by the Rollback. bool pending = false; }; class Model { public: Model(); /// 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(const Model& other); Model& operator=(const Model& other); /// 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(Model&&) noexcept = default; Model& operator=(Model&&) noexcept = default; ~Model() = default; // The builders below are for an OPEN model: on a closed or frozen one each // throws `std::logic_error` (#173; see `require_buildable`). Build the whole // model before `close()`. // Variable creation — returns var ID 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 = ""); /// 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 n, 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 list_var(int universe, int min_len, int max_len, ListInit init = ListInit::Empty, const std::string& name = ""); int32_t set_var(int n, int min_size = 0, int max_size = -1, const std::string& name = ""); // Expression creation — returns node ID int32_t constant(double val); int32_t neg(int32_t x); int32_t sum(const std::vector& 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& args); int32_t max_expr(const std::vector& 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); // sign(base) * |base|^exp (AMPL/MINLPLib signpower). exp is typically a // constant node giving the power. 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); /// 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 lt(int32_t a, int32_t b); int32_t gt(int32_t a, int32_t b); /// 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()`). [[nodiscard]] bool is_integral(int32_t handle) const; int32_t lambda_sum(int32_t list_var_id, std::function func); /// 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 func, 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 pair_lambda_sum(int32_t list_var_id, std::function func, std::function head, std::function tail, PairMode mode = PairMode::Open); /// `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& table, int32_t index); /// `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 element(const std::vector>& table, int32_t row, int32_t col); /// `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 ceil_expr(int32_t x); int32_t floor_expr(int32_t x); int32_t round_expr(int32_t x); /// `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 lambda_sum(int32_t list_var_id, LambdaExtraFunc func, const std::vector& 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. int32_t pair_lambda_sum(int32_t list_var_id, PairLambdaExtraFunc func, PairMode mode, const std::vector& extra); void add_constraint(int32_t expr_id); void minimize(int32_t expr_id); void maximize(int32_t expr_id); // Expr-returning variable creation 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); // Overloaded constraint/objective accepting Expr void add_constraint(const Expr& e); void minimize(const Expr& e); void maximize(const Expr& e); // Variable sequences for block moves void add_var_sequence(const std::vector& var_ids, int min_block_on = 1, int min_block_off = 1); [[nodiscard]] const std::vector& var_sequences() const noexcept { return s().var_sequences; } // Returns (seq_index, position) or (-1, -1) if not in any sequence [[nodiscard]] std::pair var_sequence_for(int32_t var_id) const; /// 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. int32_t add_list_partition(const std::vector& lists, Cover cover = Cover::Exact); [[nodiscard]] const std::vector& list_partitions() const noexcept { return s().list_partitions; } /// The index into `list_partitions()` of the partition `var_id` belongs to, /// or -1. Same lookup-table shape as `var_sequence_for`. [[nodiscard]] int partition_of_list(int32_t var_id) const; void close(); /// 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`. void freeze(size_t cone_cache_bytes = kDefaultConeCacheBytes); [[nodiscard]] bool is_frozen() const noexcept { return open_structure_ == nullptr; } /// `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). static constexpr size_t kDefaultConeCacheBytes = size_t{256} << 20; /// Whether `freeze()` cached `var_id`'s cone; false on an unfrozen model /// and for any id outside the cached prefix, a negative one included. [[nodiscard]] bool has_cached_cone(int32_t var_id) const noexcept { return static_cast(var_id) < s().cone_prefix; } /// `var_id`'s cached cone: every node above it, each once, in topological /// order. Only where `has_cached_cone(var_id)`. [[nodiscard]] ConstSpan cached_cone(int32_t var_id) const noexcept { const ModelStructure& st = s(); const uint32_t begin = st.cone_offsets[var_id]; return {st.cone_ids.data() + begin, st.cone_offsets[var_id + 1] - begin}; } /// The cone cache's size: variables cached, and bytes of node ids held. [[nodiscard]] size_t num_cached_cones() const noexcept { return s().cone_prefix; } [[nodiscard]] size_t cone_cache_bytes() const noexcept { return s().cone_ids.size() * sizeof(int32_t); } // ViolationLS objective-as-soft-constraint (paper §5, P2 #67). Folds the // objective into the constraint set as `objective_expr <= bound`, with the // bound a mutable RHS. Must be called after close() and only when an // objective is set; re-runs the topological sort and adjacency. The bound // starts at +inf (the constraint is inert until tightened), so search drives // the objective down by tightening it on each new feasible solution. void add_objective_soft_constraint(); [[nodiscard]] bool has_objective_constraint() const noexcept { return objective_constraint_idx_ >= 0; } // Index of the objective constraint in constraint_ids(), or -1. [[nodiscard]] int32_t objective_constraint_idx() const noexcept { return objective_constraint_idx_; } // Tighten/relax the objective bound (RHS). Recomputes the objective // constraint node in place; caller invalidates any violation cache. // Per-model state, NOT structure: each portfolio worker tightens its own // bound, so `evaluate()`'s `Const` arm reads it through // `objective_bound_node()`, not the shared node's `const_value` (#157). // Allowed on a frozen model. void set_objective_bound(double bound); [[nodiscard]] double objective_bound() const noexcept { return objective_bound_; } /// 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`. [[nodiscard]] int32_t objective_bound_node() const noexcept { return objective_bound_node_; } // Accessors // Constraints (by index into constraint_ids()) that variable var_id can // affect. This is the paper's G_v, in ascending constraint index. Built by // close() and add_objective_soft_constraint() for the variables that existed // then; any other id -- every id, before close() -- is out of range. [[nodiscard]] ConstSpan constraints_of_var(int32_t var_id) const { const ModelStructure& st = s(); if (var_id < 0 || static_cast(var_id) + 1 >= st.var_constraint_offsets.size()) { throw std::out_of_range("var id out of range"); } const uint32_t begin = st.var_constraint_offsets[var_id]; return {st.var_constraint_ids.data() + begin, st.var_constraint_offsets[var_id + 1] - begin}; } // Where `constraints_of_var(var_id)` starts in the flat incidence array of // every G_v (length `num_var_constraint_incidences()`), for a per-incidence // table kept parallel to it. Same range check. The layout is rebuilt, and // every later offset moves, whenever G_v is (close(), // add_objective_soft_constraint()). [[nodiscard]] uint32_t constraints_of_var_offset(int32_t var_id) const { const ModelStructure& st = s(); if (var_id < 0 || static_cast(var_id) + 1 >= st.var_constraint_offsets.size()) { throw std::out_of_range("var id out of range"); } return st.var_constraint_offsets[var_id]; } [[nodiscard]] size_t num_var_constraint_incidences() const { return s().var_constraint_ids.size(); } // Sparse per-constraint violation deltas if var_id <- j, WITHOUT committing. // Returns (constraint_index, delta) pairs for affected constraints whose // violation changes. Scalar variables only (Bool/Int/Float); throws on // List/Set. Does not clamp j to [lb, ub] — it is a pure counterfactual. // PRECONDITION: node values are consistent with the current assignment // (true after close(), full_evaluate(), or a committed move). The probe // restores exactly to that consistent state; it does not snapshot a dirty // mid-move state. std::vector> per_constraint_violation_delta(int32_t var_id, double j); // Change in total WEIGHTED violation if var_id <- j: sum_c weights[c]*delta_c, // accumulated PER CONSTRAINT rather than as a difference of two whole sums, so // a row clamped to kInfPenalty cancels exactly instead of absorbing the O(1) // real rows (#100; the definition in src/model.cpp says why). Uses a member // scratch buffer, so it is allocation-free once warmed up but not on the // first calls; the per_constraint variant allocates on every call and is for // sparse/tooling use. `weights` is indexed by constraint index (constraint_ids()). Scalar // variables only; same no-commit / precondition contract as above. double weighted_violation_delta(int32_t var_id, double j, const std::vector& weights); // The same delta under `weights`, which it returns, and under `second`, // written to `second_delta`, from ONE probe (#272). Each is summed exactly // as the single-weight call sums it, so both are the doubles two separate // calls would return. `second` is indexed like `weights`. double weighted_violation_delta(int32_t var_id, double j, const std::vector& weights, const std::vector& second, double& second_delta); [[nodiscard]] const Variable& var(int32_t id) const { if (id < 0 || id >= static_cast(vars_.size())) { throw std::out_of_range("var id out of range"); } return vars_[id]; } Variable& var_mut(int32_t id) { if (id < 0 || id >= static_cast(vars_.size())) { throw std::out_of_range("var id out of range"); } return vars_[id]; } [[nodiscard]] const ExprNode& node(int32_t id) const { if (id < 0 || id >= static_cast(s().nodes.size())) { throw std::out_of_range("node id out of range"); } return s().nodes[id]; } /// 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()`. [[nodiscard]] double node_value(int32_t id) const { // Checked against the NODE array, not the value array: `push_node` appends // the value first, so a throwing node append can leave the value array one // entry longer, and that entry belongs to no node. if (id < 0 || id >= static_cast(s().nodes.size())) { throw std::out_of_range("node id out of range"); } return node_values_[id]; } /// 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. void set_node_value_unchecked(int32_t id, double value) noexcept { node_values_[id] = value; } /// 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. [[nodiscard]] IncSums& inc_sums() noexcept { return inc_sums_; } [[nodiscard]] const IncSums& inc_sums() const noexcept { return inc_sums_; } /// The pending probe's undo log (#270): see `ProbeUndo`. Not bound to /// Python (#156): the rollback writes its node ids unchecked. [[nodiscard]] ProbeUndo& probe_undo() noexcept { return probe_undo_; } /// Slot -> node id of every incremental Sum; see `ModelStructure`. [[nodiscard]] const std::vector& inc_sum_nodes() const noexcept { return s().inc_sum_nodes; } /// `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. [[nodiscard]] ConstSpan children(const ExprNode& node) const noexcept { return {s().child_refs.data() + node.child_begin, node.child_count}; } /// 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). [[nodiscard]] ConstSpan parents(int32_t id) const { const ModelStructure& st = s(); if (id < 0 || id >= static_cast(st.nodes.size())) { throw std::out_of_range("node id out of range"); } const uint32_t begin = st.parent_offsets[id]; return {st.parent_ids.data() + begin, st.parent_offsets[id + 1] - begin}; } /// The distinct nodes that name variable `var_id` as a child, with the same /// order, dedup and rebuild contract as `parents`. [[nodiscard]] ConstSpan dependents(int32_t var_id) const { if (var_id < 0 || var_id >= static_cast(vars_.size())) { throw std::out_of_range("var id out of range"); } const ModelStructure& st = s(); const uint32_t begin = st.dependent_offsets[var_id]; return {st.dependent_ids.data() + begin, st.dependent_offsets[var_id + 1] - begin}; } [[nodiscard]] int32_t objective_id() const noexcept { return objective_id_; } [[nodiscard]] bool is_maximizing() const noexcept { return is_maximizing_; } /// 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. [[nodiscard]] const std::vector& constraint_ids() const noexcept { return s().constraint_ids; } /// How many of `constraint_ids()` the modeller added: they are its first /// entries. Every row before `close()`. [[nodiscard]] size_t num_user_constraints() const noexcept { const ModelStructure& st = s(); return st.num_user_constraints < 0 ? st.constraint_ids.size() : static_cast(st.num_user_constraints); } /// 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()`. [[nodiscard]] int32_t num_domain_rows() const noexcept { return s().num_domain_rows; } /// Whether node `id` is one `close()` made for a domain row: what /// `save_model` leaves out, since a reload's `close()` makes them again. [[nodiscard]] bool is_domain_node(int32_t id) const noexcept { return id >= s().domain_node_begin && id < s().domain_node_end; } /// 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. bool set_domain_tolerance(double tol); [[nodiscard]] double domain_margin() const noexcept { return domain_margin_; } /// 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. void reserve(size_t n_vars, size_t n_nodes, size_t n_child_refs = 0) { ModelStructure& st = mut(); vars_.reserve(n_vars); st.dependent_offsets.reserve(n_vars + 1); st.nodes.reserve(n_nodes); node_values_.reserve(n_nodes); st.parent_offsets.reserve(n_nodes + 1); st.child_refs.reserve(n_child_refs); } [[nodiscard]] const std::vector& topo_order() const noexcept { return s().topo_order; } /// 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. [[nodiscard]] int32_t topo_position(int32_t id) const noexcept { return s().topo_pos[id]; } [[nodiscard]] const std::vector& variables() const noexcept { return vars_; } [[nodiscard]] const std::vector& nodes() const noexcept { return s().nodes; } /// 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. [[nodiscard]] const std::vector& node_values() const noexcept { return node_values_; } [[nodiscard]] size_t num_vars() const noexcept { return vars_.size(); } [[nodiscard]] size_t num_nodes() const noexcept { return s().nodes.size(); } [[nodiscard]] bool is_closed() const noexcept { return closed_; } // Lambda function access [[nodiscard]] const std::function& lambda_func(int32_t idx) const { if (idx < 0 || idx >= static_cast(s().lambda_funcs.size())) { throw std::out_of_range("lambda func index out of range"); } return s().lambda_funcs[idx]; } [[nodiscard]] const std::function& pair_lambda_func(int32_t idx) const { if (idx < 0 || idx >= static_cast(s().pair_lambda_funcs.size())) { throw std::out_of_range("pair lambda func index out of range"); } return s().pair_lambda_funcs[idx]; } /// 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. [[nodiscard]] const PairLambdaSpec& pair_lambda_spec(int32_t idx) const { if (idx < 0 || idx >= static_cast(s().pair_lambda_specs.size())) { throw std::out_of_range("pair lambda spec index out of range"); } return s().pair_lambda_specs[idx]; } // #186's tables, range-checked like the lambda tables above. [[nodiscard]] const LambdaExtraFunc& lambda_extra_func(int32_t idx) const { if (idx < 0 || idx >= static_cast(s().lambda_extra_funcs.size())) { throw std::out_of_range("lambda extra func index out of range"); } return s().lambda_extra_funcs[idx]; } [[nodiscard]] const PairLambdaExtraFunc& pair_lambda_extra_func(int32_t idx) const { if (idx < 0 || idx >= static_cast(s().pair_lambda_extra_funcs.size())) { throw std::out_of_range("pair lambda extra func index out of range"); } return s().pair_lambda_extra_funcs[idx]; } [[nodiscard]] PairMode pair_lambda_extra_mode(int32_t idx) const { if (idx < 0 || idx >= static_cast(s().pair_lambda_extra_modes.size())) { throw std::out_of_range("pair lambda extra mode index out of range"); } return s().pair_lambda_extra_modes[idx]; } [[nodiscard]] const ElementTable& element_table(int32_t idx) const { if (idx < 0 || idx >= static_cast(s().element_tables.size())) { throw std::out_of_range("element table index out of range"); } return s().element_tables[idx]; } /// Whether any extra-lambda node exists: the O(1) test `save_model`'s /// refusal starts from. [[nodiscard]] bool has_lambda_extra_nodes() const noexcept { return !s().lambda_extra_funcs.empty() || !s().pair_lambda_extra_funcs.empty(); } /// See `ModelStructure::has_breakpoint_nodes`. [[nodiscard]] bool has_breakpoint_nodes() const noexcept { return s().has_breakpoint_nodes; } /// See `ModelStructure::breakpoint_flags`. Sized `num_nodes()` on a closed /// model; empty before `close()`. [[nodiscard]] const std::vector& breakpoint_flags() const noexcept { return s().breakpoint_flags; } // State snapshot/restore struct State { std::vector values; std::vector> elements; }; [[nodiscard]] State copy_state() const; /// 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. void restore_state(const State& state); private: /// The structure, for reading: const, which makes a write to the shared side /// a compile error (#157). Null only on a moved-from `Model`; the assert costs /// nothing under NDEBUG and turns that read into a named abort in the Debug /// and sanitizer builds. [[nodiscard]] const ModelStructure& s() const noexcept { assert(structure_ != nullptr); return *structure_; } /// The structure, for writing. Throws once `freeze()` has run: the structure /// is then shared with every replica, so a structural change would mutate a /// peer's model. NOT copy-on-write, for the reason `freeze()` gives. ModelStructure& mut() { if (open_structure_ == nullptr) { throw std::logic_error("model is frozen: its structure is shared and cannot change"); } return *open_structure_; } std::vector vars_; /// Node id -> its current value, kept out of the node array so that it holds /// nothing a search writes (#157). Kept exactly as long as /// `s().nodes` by `push_node`, the one place a node is made. std::vector node_values_; /// The immutable side (#157). Both handles point at the same object while the /// model is open; `freeze()` drops `open_structure_`, after which `mut()` /// throws and the only handle left is a const one. Two pointers rather than /// one plus a flag, so that the defaulted move leaves no writable handle /// behind on the moved-from model. std::shared_ptr structure_; std::shared_ptr open_structure_; int32_t objective_id_ = -1; bool is_maximizing_ = false; int32_t objective_bound_node_ = -1; // Const node holding the objective RHS int32_t objective_constraint_node_ = -1; // the `obj - bound` node int32_t objective_constraint_idx_ = -1; // its index in constraint_ids() double objective_bound_ = 0.0; double domain_margin_ = std::nextafter(kDefaultFeasibilityTolerance, std::numeric_limits::infinity()); bool closed_ = false; // Scratch for weighted_violation_delta's pre-probe violations. A member so // the hot scoring path allocates only until it reaches the widest variable's // constraint count. Not reentrant — same single-thread-per-Model contract as // the probe's transient node mutation. std::vector probe_old_violation_; // Both weighted_violation_deltas: `second` null for the single-weight one. double probe_weighted_delta(int32_t var_id, double j, const std::vector& weights, const std::vector* second, double* second_delta); /// See `inc_sums()`. Last, after the members every walk reads: placed /// among them it pushed those onto more cache lines, which cost a /// probe-bound model ~5% (#188). IncSums inc_sums_; /// See `probe_undo()`. Last for the reason `inc_sums_` is. Not copied: a /// replica starts owing no rollback (see the copy constructor). ProbeUndo probe_undo_; /// Throws if the model is frozen. `mut()` is the backstop for anything that /// writes the structure; this is for the public mutators that would otherwise /// change something observable -- an objective id, say -- before reaching it, /// and it names the method in the message where `mut()` cannot. void require_open(const char* method) const; /// Throws if the model is frozen (as `require_open`) or CLOSED (#173). Every /// public builder takes it -- variable and expression creation, /// `add_constraint`, `minimize`/`maximize`, `add_var_sequence`, /// `add_list_partition` -- because a node or row appended to a closed model /// is never placed in the topological order: no evaluation computes it and /// `solve()` would report feasible over it. The one internal post-close /// addition, `add_objective_soft_constraint`, uses the private allocators /// below, which do not take it, and rebuilds the derived indices itself. /// `reserve`, `close` and the per-model writes (`var_mut`, /// `set_objective_bound`, `restore_state`) are not builders and stay open. void require_buildable(const char* method) const; void append_domain_rows(); void build_var_constraints(); void rebuild_back_references(); void rebuild_topo_positions(); void classify_incremental_sums(); void build_cone_cache(size_t cap_bytes); int32_t alloc_var(VarType type, double lb, double ub, const std::string& name); /// `constant`'s body without its closed-model refusal, for the objective row. int32_t push_constant(double val); int32_t alloc_node(NodeOp op, std::initializer_list children); int32_t alloc_node_over_handles(NodeOp op, const std::vector& handles); int32_t push_node(NodeOp op, size_t child_begin); // Decode a var or node handle, throwing std::out_of_range if it names // nothing this model has made yet. [[nodiscard]] ChildRef wrap(int32_t handle) const; // `wrap`, refusing a List or Set variable: for an input read as a scalar. [[nodiscard]] ChildRef wrap_scalar(int32_t handle, const char* what) const; [[nodiscard]] std::vector lambda_extra_children(int32_t list_var_id, const std::vector& extra, const char* what) const; int32_t alloc_node_over_refs(NodeOp op, const std::vector& kids); int32_t push_element(ElementTable tbl, const std::vector& kids); void classify_breakpoint_reach(); }; } // namespace cbls move_generator.h ================ .. code-block:: c #pragma once #include "dag.h" #include "moves.h" #include "rng.h" #include #include #include #include #include namespace cbls { class Model; class ViolationManager; /// Granular neighbourhood (Toth & Vigo, INFORMS J. Computing 15(4), 2003): for /// each element `e` of `{0..n-1}`, the others a move involving `e` may reach, /// nearest first, supplied by the model author since the engine knows no cost. /// /// CSR: `of(e)` is `ids[offsets[e] .. offsets[e+1])`. Invariants (offsets /// non-decreasing from 0 to `ids.size()`, ids in the universe) are checked /// ONCE at construction, since `of()` is on the hot path. `of()` is still /// total: an out-of-range `e` gives an empty span, not a heap read, so a list /// built for another variable degrades to no neighbours (#156; this type is /// reachable from Python). class NeighbourList { public: NeighbourList() = default; /// From a per-element row list: `rows[e]` are `e`'s neighbours, nearest /// first. Throws `std::invalid_argument` on an id outside `[0, rows.size())`. explicit NeighbourList(const std::vector>& rows); /// From CSR arrays. Throws `std::invalid_argument` unless `offsets` is /// non-decreasing, starts at 0, ends at `ids.size()`, and every id lies in /// `[0, offsets.size() - 1)`. NeighbourList(std::vector offsets, std::vector ids); /// Elements the list is defined over; 0 for a default-constructed list. [[nodiscard]] int32_t universe() const noexcept { return offsets_.empty() ? 0 : static_cast(offsets_.size()) - 1; } [[nodiscard]] bool empty() const noexcept { return ids_.empty(); } /// `e`'s neighbours, nearest first. Empty for an out-of-range `e`. [[nodiscard]] ConstSpan of(int32_t e) const noexcept { // Widened before +1: `e + 1` overflows at INT32_MAX, reachable from // Python, in a function that must be total. if (e < 0 || static_cast(e) + 1 >= offsets_.size()) { return {}; } const int32_t begin = offsets_[static_cast(e)]; const int32_t end = offsets_[static_cast(e) + 1]; return {ids_.data() + begin, static_cast(end - begin)}; } [[nodiscard]] const std::vector& offsets() const noexcept { return offsets_; } [[nodiscard]] const std::vector& ids() const noexcept { return ids_; } private: void validate() const; std::vector offsets_; std::vector ids_; }; /// Each element's `k` nearest others under `cost`, nearest first, ties by /// ascending id (a function of the cost, not the sort's stability). /// O(universe^2) cost calls, O(universe^2 log k) work: a setup convenience for /// a few thousand elements, not a spatial index; larger or geometric callers /// build rows themselves. `k <= 0` or `universe <= 1` yields no neighbours, /// which every built-in generator reads as "use the uniform draw". NeighbourList nearest_neighbours(int universe, int k, const std::function& cost); /// How the structural batch turns a generator's candidates into a commit. /// `FirstImprovingSample` is bit-for-bit the pre-#165 batch; the default /// `Auto` picks it or `GranularBest`. The others change the trajectory. enum class StructuralSelection : std::uint8_t { /// Take every improving candidate from one sample, in order. FirstImprovingSample, /// Call the generator until it offered at least /// `SearchConfig::structural_sample_size` candidates (at least one call), /// score all, commit the best improving one. A floor on effort, not a cap /// on count: the built-in List generator yields 5 even at size 1. BestOfSample, /// `BestOfSample`, restricted to generators whose scope can change a /// VIOLATED row. Exact, not heuristic: if no row in the scope's G_v union /// is violated, every move there leaves the weighted violation equal or /// higher. Variable-level, not #165's element-level: incidence is per /// variable, and a `Set` read through one `Lambda` puts every element in /// every row; element-level needs a generator-supplied scorer, beyond what /// a `NeighbourList` gives. ViolationGuided, /// `ViolationGuided`, with each `ListPartition` searched by the GRANULAR /// COMPLETE neighbourhood of one random element per `generate` call (#203; /// Toth & Vigo 2003): every relocate / swap / 2-opt / 2-opt* with each of /// its k nearest neighbours, plus a move into each empty list /// (`generate_granular_partition_moves` states how it differs from the /// paper). Commits the best improving candidate; short calls are topped up /// with another element's neighbourhood. Needs /// `SearchConfig::structural_neighbours`, else it is `ViolationGuided`. /// With a list, partition members' intra-list generators propose nothing /// (the neighbour pairs cover them); Lists/Sets outside a partition are /// sampled as under `ViolationGuided`. GranularBest, /// The default (#203): `GranularBest` with a /// `SearchConfig::structural_neighbours` list (won #203's CVRP smoke, 15/15 /// vs `ViolationGuided`), else `FirstImprovingSample`, so a run without one /// keeps the pre-#165 trajectory. Resolved once when the batch is built. Auto, }; /// The policy a search actually runs: `Auto` resolved against whether a /// neighbour list is present, every other value unchanged. StructuralSelection resolve_structural_selection(StructuralSelection selection, bool has_neighbours); /// Stable snake_case token for a `StructuralSelection`, and its inverse; the /// one spelling used by the benchmark flags and the Python bindings. const char* structural_selection_name(StructuralSelection selection); bool try_parse_structural_selection(std::string_view text, StructuralSelection& out); /// What a generator may look at while proposing. READ-ONLY except the RNG: /// the batch applies, scores and rolls back each candidate itself, so a /// generator moving a variable corrupts the baseline later candidates use. struct MoveContext { const Model& model; /// GLS weights `W` and the per-constraint violations of the CURRENT /// assignment. const ViolationManager& vm; RNG& rng; /// The policy the batch is running, so a generator can spend more effort /// when its candidates are going to be ranked rather than taken in order. StructuralSelection selection = StructuralSelection::FirstImprovingSample; /// Per-constraint clamped violations of the last ACCEPTED assignment -- the /// baseline the batch scores candidates against. One entry per constraint, /// indexed as `ViolationManager::weights` is. Never null. const std::vector* violations = nullptr; }; /// A source of candidate structural moves. The built-in List/Set moves are /// generators too (`default_move_generators`), so a domain move is a peer. /// Register instances on `SearchConfig::move_generators`. /// /// CONTRACTS the batch relies on: /// - a structured change is a POSITIONAL EDIT on `elements` (`ElementEdit`) /// or a whole `replacement` (`replace_change`, paying the copy), applied /// to the assignment the sample was drawn against, which the batch /// restores before each candidate. /// - `generate` returns in bounded time AND appends a bounded number of /// candidates: the deadline is checked only BETWEEN generators (#105), and /// every candidate on offer is applied, evaluated, scored and rolled back, /// so 100 000 instant candidates overrun `solve()`'s budget like a hang. /// Built-ins append at most 5, except the partition generator under /// `GranularBest` (bound in `generate_granular_partition_moves`). Only the /// sampling policies cap the count (`SearchConfig::structural_sample_size`); /// `FirstImprovingSample` takes all. /// - `generate` APPENDS; it must not clear or reorder `out`. /// - `generate` must not change the model's assignment (see `MoveContext`). /// - `clone()` returns an independent object and is safe to call /// concurrently on one prototype: each portfolio worker clones the single /// registered instance on its own thread, so a `clone()` writing shared /// state needs a lock (as `tests/test_parallel.cpp`'s `CountingGenerator`). /// Clone-held caches, cursors and counters are per-worker; sharing them /// races (#157). A clone dies with its worker's `solve()`; each restart /// (`src/pool.cpp`) clones afresh, so no state survives a restart. /// - `scope()` names every variable the moves can change and is constant for /// the generator's lifetime. `ViolationGuided`/`GranularBest` skip /// generators by it, so an incomplete scope can skip a helpful move. /// Scoring ignores it: it uses the rows each move's variables reach (#273). class MoveGenerator { public: MoveGenerator() = default; MoveGenerator(const MoveGenerator&) = default; MoveGenerator& operator=(const MoveGenerator&) = default; MoveGenerator(MoveGenerator&&) = default; MoveGenerator& operator=(MoveGenerator&&) = default; virtual ~MoveGenerator(); /// A stable name for logging and for per-generator counters. Must outlive /// the generator (a string literal, or a member it owns). [[nodiscard]] virtual std::string_view name() const = 0; /// The variables this generator's moves can change: one list, a partition of /// lists, a set. Ascending order is not required. [[nodiscard]] virtual ConstSpan scope() const = 0; /// Append candidate moves. Called once per batch under /// `FirstImprovingSample`, and repeatedly under the sampling policies until /// the sample is full or a call adds nothing. /// /// Every candidate of one call is built against, and applied to, the SAME /// assignment: the batch restores every variable any candidate of the /// sample names before applying each one (#164), so a positional /// `ElementEdit` lands where it was built and the state is always the /// sample's own plus one candidate. Under `FirstImprovingSample` the batch /// may commit several in turn, so committing k then k+1 leaves k's change /// gone (harmless for the built-ins: same as rejecting k). The built-in /// `ListPartition` still emits at most ONE candidate per call (except under /// take-best `GranularBest`), since a cover kept by construction is costly /// to get wrong. For a larger sample, rely on the baseline or run under /// `BestOfSample` / `ViolationGuided`, which commit at most one per call. virtual void generate(MoveContext& ctx, std::vector& out) = 0; /// One of THIS generator's moves was committed; the default does nothing. /// A private notification, NOT an assignment-change broadcast: peer /// commits, FJ/Novelty batches, the kick, LNS and pool restarts move the /// assignment silently. So anything DERIVED from the assignment (an /// element-to-list index, a position map) must be recomputed in `generate` /// from `ctx.model`; only the generator's own state (cursor, counter, tabu /// tenure) may carry across calls. Under `FirstImprovingSample` a notified /// commit can still be undone by a later one from the same sample (see /// `generate`); a generator whose bookkeeping must track the assignment /// should emit one candidate per call or run under a one-commit policy. virtual void on_commit(const Move& move); /// A per-worker copy. See the cloning contract above. [[nodiscard]] virtual std::unique_ptr clone() const = 0; }; /// The built-in structural generators for `model`: one per List/Set variable, /// in variable-id order, each proposing the typed moves of /// `generate_standard_moves` (List: swap / 2-opt / relocate / or-opt(2) / /// or-opt(3) from one random position pair; Set: one add, remove and swap). /// Empty with no structured variable. Non-null `neighbours` draws a move's /// target from the moved element's list, changing the trajectory; null keeps /// the pre-#165 path. Public so a custom set can extend the built-ins. std::vector> default_move_generators( const Model& model, const std::shared_ptr& neighbours = nullptr); } // namespace cbls moves.h ======= .. code-block:: c #pragma once #include "inline_vector.h" #include "model.h" #include "rng.h" #include #include #include #include namespace cbls { class NeighbourList; /// What one `ElementEdit` does to a structured variable's `elements` (#164). /// /// POSITIONS RATHER THAN A WHOLE VECTOR: a whole-vector candidate costs AT /// LEAST two heap allocations and three O(n) copies per candidate SCORED for a /// move touching two positions (the floor dev/architecture.md also states; /// the two must agree). Every kind but /// `Replace` edits the existing vector in place. An allocation-count /// argument, true on any machine and n, that makes a larger candidate sample /// affordable (`StructuralSelection`). `Replace` covers what positions cannot /// express: an inter-list tail exchange and an unknown generator's move. enum class EditKind : uint8_t { None, ///< absent. A scalar change carries `new_value` and no edit. Replace, ///< `elements = replacement`. The pre-#164 form. Swap, ///< exchange positions `from` and `to`. Reverse, ///< reverse the inclusive range [`from`, `to`]. MoveSegment, ///< erase `length` elements at `from`, reinsert at `to` of the ///< SHORTENED vector. A `std::rotate`. Insert, ///< insert `element` at `from`. Erase, ///< erase position `from`. Assign, ///< `elements[from] = element`. }; /// One in-place rewrite of a structured variable's `elements`. /// /// Which fields a kind reads: /// /// Swap from, to /// Reverse from, to /// MoveSegment from, to, length /// Insert from, element /// Erase from /// Assign from, element /// Replace the change's `replacement` vector /// /// RELATIVE TO THE ASSIGNMENT THE MOVE WAS BUILT AGAINST: on another, the /// positions name other elements and `Erase`/`Assign` can be out of range. The /// structural batch's baseline keeps several candidates per sample safe (see /// `MoveGenerator::generate`). struct ElementEdit { EditKind kind = EditKind::None; int32_t from = 0; int32_t to = 0; int32_t length = 1; int32_t element = -1; }; struct Move { /// One variable's part of a move: a scalar value, or up to two positional /// edits applied in ORDER (`set_swap` erases the dropped element, then /// appends the new one). A trailing `EditKind::None` means one edit. struct Change { int32_t var_id = -1; double new_value = 0.0; std::array edits{}; std::vector replacement; // EditKind::Replace only }; /// Two inline: every built-in move has one or two changes, so no malloc /// per candidate (#274). InlineVector changes; /// The kind's name: a STRING LITERAL or other static-storage string only; /// a temporary std::string dangles. A view, so no per-candidate allocation /// for names past the small-string buffer (#274). std::string_view move_type; double delta_F = 0.0; }; /// A scalar variable's change. Move::Change scalar_change(int32_t var_id, double new_value); /// A structured variable's change, as one or two positional edits. Move::Change edit_change(int32_t var_id, const ElementEdit& first, const ElementEdit& second = ElementEdit{}); /// A structured variable's change, as a whole replacement vector. The general /// form, for what positions cannot express. Move::Change replace_change(int32_t var_id, std::vector replacement); inline ElementEdit swap_edit(int32_t a, int32_t b) { return {EditKind::Swap, a, b, 1, -1}; } inline ElementEdit reverse_edit(int32_t lo, int32_t hi) { return {EditKind::Reverse, lo, hi, 1, -1}; } inline ElementEdit segment_edit(int32_t from, int32_t length, int32_t to) { return {EditKind::MoveSegment, from, to, length, -1}; } inline ElementEdit insert_edit(int32_t pos, int32_t element) { return {EditKind::Insert, pos, 0, 1, element}; } inline ElementEdit erase_edit(int32_t pos) { return {EditKind::Erase, pos, 0, 1, -1}; } inline ElementEdit assign_edit(int32_t pos, int32_t element) { return {EditKind::Assign, pos, 0, 1, element}; } /// Apply `change`'s edits to `elements` in place. Out-of-range positions are /// ignored, not indexed: `Variable.elements` is writable from Python, so an /// edit can meet a shorter vector than it was built for (#156). void apply_element_edits(const Move::Change& change, std::vector& elements); /// `elements` with `change` applied, without touching the model (tests, /// Python). The engine edits in place instead. std::vector elements_after(const Move::Change& change, const std::vector& elements); /// Does `change` leave `elements` exactly as it is? Decided per kind, without /// materialising the result. /// /// EXACT FOR A SINGLE EDIT OVER DISTINCT ELEMENTS (every change the engine /// builds): `change_is_noop(c, e) == (elements_after(c, e) == e)`, pinned in /// `tests/test_moves.cpp`. Distinct elements make any non-empty reversal or /// displaced segment a reorder; an out-of-range edit reads as inert because /// applying it is inert (#156). /// /// OTHERWISE CONSERVATIVE: it may say "changed" for an unchanged result, never /// the reverse, so the cost is a needless scored candidate. Reachable only via /// Python-written `Variable::elements`: (1) edits are judged INDEPENDENTLY, so /// `erase(1)` then `insert(1, 11)` on `{10, 11, 12}` reads as changed; (2) on /// repeated elements `Reverse`/`MoveSegment` decide by position alone. [[nodiscard]] bool change_is_noop(const Move::Change& change, const std::vector& elements); /// The whole pre-move state of the variables a `Move` touches: absolute, not /// an inverse edit list, since `undo_move` is off the hot path (the structural /// batch restores from its sample baseline). The public and Python way to try /// a move and take it back. struct SavedValues { std::vector values; std::vector> elements; }; // Move generators std::vector generate_standard_moves(const Variable& var, RNG& rng); /// Appending form of the above, called by the structural batch's built-in /// generators (#165): same moves and RNG draws in the same order; /// the overload above is this with `out` empty and `neighbours` null. /// /// Non-null `neighbours` makes the TARGET granular: a List move pairs position /// `i` with one of `elements[i]`'s nearest neighbours; a Set add/swap brings in /// a selected element's nearest neighbour not already in. Both fall back to the /// uniform draw when the list offers nothing, so a partial list limits where /// the search looks, never what it reaches. Null (the default) keeps an /// unconfigured run on its trajectory. /// /// Cost: a guided List move adds an O(|elements|) element -> position index /// per call, a constant factor on construction that is already O(|elements|); /// it buys an asymptotic SEARCH win (k candidates from a k-nearest list, not /// the universe), and is paid only when a list was supplied. void generate_standard_moves(const Variable& var, RNG& rng, std::vector& out, const NeighbourList* neighbours); /// Append AT MOST ONE candidate inter-list move over `partition` (#164): /// relocate, swap or 2-opt* between two of its lists, and -- under /// `Cover::AtMostOnce` -- an insert from the unassigned elements or a removal. /// The kind is drawn uniformly from those the partition admits; a kind whose /// guards reject the draw appends nothing. /// /// AT MOST ONE CANDIDATE PER CALL, deliberately. The batch's per-sample /// baseline makes several safe (argument in `move_generator.h`), but one is /// kept because a cover maintained by construction is costly to get wrong, and /// one is safe under any batch that applies moves, not just this one's /// discipline. Sampling policies call `generate` repeatedly for full samples. /// /// `anchor`: a member list id every candidate must change, or -1 to draw both /// lists; the diversification kick names one because it judges its effect on /// that variable alone. `neighbours` makes the TARGET granular as for /// intra-list moves (nearest neighbours in the other list); null by default. void generate_partition_moves(const Model& model, int partition, int32_t anchor, RNG& rng, std::vector& out, const NeighbourList* neighbours); /// The GRANULAR COMPLETE neighbourhood of one element of `partition`, for /// `StructuralSelection::GranularBest` (#203; Toth & Vigo 2003, INFORMS J. /// Computing 15(4)). Draws one element `e` of the universe uniformly, then /// appends every move pairing `e` with each of its `neighbours`: /// /// - relocate `e` just after and just before `f` (within one list a segment /// move, across two an erase and an insert); /// - swap `e` and `f`; /// - the 2-opt that makes `e` and `f` adjacent: within one list the two /// reversals that do, across two lists the 2-opt* tail exchange in both /// orientations. /// /// Under `Cover::AtMostOnce` an assigned `e` is also offered for removal, and /// an unassigned one inserted just after and before each assigned `f`. `e` is /// also moved into every EMPTY member list, so an emptied list can reopen. /// Length bounds hold and no-ops are dropped. At most /// `5 * |neighbours.of(e)| + 1 + |empty lists|` candidates, so the batch's /// bounded-yield contract holds for any fixed k and fleet. /// /// Deviations from Toth & Vigo, as #203 specified: the sparse graph is each /// element's k NEAREST neighbours, not edges below nu = beta * z / (n + K) plus /// depot edges; and one call covers ONE drawn element, not the whole /// neighbourhood. /// /// SEVERAL CANDIDATES PER CALL, for a policy committing at most one /// (take-best); all are built against the current assignment, which the /// batch's per-sample baseline restores before each. `slot_scratch`: the /// caller's reusable element -> (list, position) index, rebuilt every call. void generate_granular_partition_moves(const Model& model, int partition, RNG& rng, const NeighbourList& neighbours, std::vector& out, std::vector& slot_scratch); // Move application std::vector apply_move(Model& model, const Move& move); SavedValues save_move_values(const Model& model, const Move& move); void undo_move(Model& model, const Move& move, const SavedValues& saved); } // namespace cbls nlp_polish.h ============ .. code-block:: c #pragma once #include "inner_solver.h" #include #include #include #include namespace cbls { // Opt-in NLP polish (#453, landed #474): with every discrete variable fixed, a // projected-gradient descent of the objective over the Float variables on the // active real rows (equalities and near-tight inequalities), each trial step // pulled back onto those rows by Gauss-Newton minimum-norm restoration. A // trial is kept only if it satisfies every row the Float columns reach and // lowers the objective, and the whole polish is undone if the search's own // test then disagrees, so a feasible point stays feasible. When the polish // improves nothing, FloatIntensifyHook's descent runs. // // Dense linear algebra: skipped above `max_free_vars` Float columns or // `max_active_rows` active rows. A discrete assignment already polished from // a start at least as good is not polished again within a solve (a rise in // the objective bound marks a new one). Rows here are the real rows the // Float columns reach, `Neq` excepted: the search's final check holds the // polish to those, and a restoration may not break one that held. The time // share carries over between solves. class NlpPolishHook : public FloatIntensifyHook { public: // The solve's SearchConfig::feasibility_tolerance; the hook classifies // and accepts points with it (#474 review). double feasibility_tolerance = kDefaultFeasibilityTolerance; int max_iterations = 30; int max_free_vars = 2000; int max_active_rows = 600; int max_restoration_steps = 8; int max_step_halvings = 12; void solve(Model& model, ViolationManager& vm, const std::vector& last_changed_vars = {}, StopRef stop = {}) override; // Also called after infeasible batches: Gauss-Newton restoration of the // Float columns (discrete fixed) on the rows they reach, kept only if every // such row ends satisfied, else the point is put back. A violation left on // a row no Float column reaches is the discrete search's to repair. Off, // a point above `feasibility_tolerance` gets FloatIntensifyHook's descent. bool restore_infeasible = false; int max_restore_steps = 20; int max_restore_rows = 300; [[nodiscard]] bool wants_infeasible() const override { return restore_infeasible; } // Polish and restore together hold to `time_share` of the wall time since // the first call; a call gets the unspent share, at least // `min_call_seconds`, and stops at that deadline or the search's stop, // checked between dense steps, keeping accepted steps (#453). double time_share = 0.1; double min_call_seconds = 0.01; // Diagnostics: polishes run / improved, restorations run / succeeded. int64_t polish_runs = 0; int64_t polish_improvements = 0; int64_t restore_runs = 0; int64_t restore_successes = 0; private: void polish(Model& model, ViolationManager& vm, StopRef stop, double deadline); void restore_point(Model& model, StopRef stop, double deadline); // The deadline for a call starting now, or a negative value to skip it. double begin_call(double now); // False if this discrete assignment was polished from a start at least as // good; else records `start` for it (the map is cleared past 100000). bool claim_polish(uint64_t discrete_key, double start); double first_call_ = -1.0; double spent_seconds_ = 0.0; double last_bound_ = -std::numeric_limits::infinity(); // Discrete-assignment hash -> best objective a polish started from. std::unordered_map polished_; }; } // namespace cbls pool.h ====== .. code-block:: c #pragma once #include "executor.h" #include "inner_solver.h" #include "lns.h" #include "model.h" #include "search.h" #include "solution_pool.h" #include "stop.h" #include "tracer.h" #include #include #include #include namespace cbls { struct ParallelConfig { int n_threads = 0; // 0 = hardware_concurrency() /// Solutions kept in the shared pool; <= 0 = auto, `max(10, 2 * workers)` /// over the workers that run (an `executor` cap narrows it). Below the /// worker count the pool cannot hold one point per worker, since `submit` /// has no per-worker quota. int pool_capacity = 0; /// Share the portfolio's best objective as every worker's `obj <= bound` /// at each batch boundary (#179; SearchCoordination::share_objective_bound). /// False is the A/B control arm. bool share_objective_bound = true; /// The host's cancellation channel for the whole portfolio (#169), OR-ed /// with `SearchConfig::stop`: either ends every worker at its next batch /// boundary with TerminationReason::Cancelled. Non-owning (see StopRef); /// polled from every worker thread, so the source must be safe to read /// concurrently (StopToken is). StopRef stop; /// Builds one Tracer per worker, given its index in `[0, n_workers)` (#169); /// null = no tracing. A null return means that worker is untraced; it never /// falls back to `SearchConfig::tracer`. A `SearchConfig::tracer` without a /// factory throws std::invalid_argument on the calling thread when more than /// one worker would run, since one tracer cannot serve N threads. /// Called once per worker, on its thread, before its first solve (a tracer /// spans the worker's restarts); called from N threads at once, so shared /// state in the factory needs its own lock. `unique_ptr` because a Tracer /// is C++-only. std::function(int worker)> tracer_factory; /// The caller's thread pool, or unset for std::thread workers (#169). /// Worker `i` runs as index `i` of `parallel_for_chunked(0, n_workers, ...)` /// with `n_workers = min(n_threads, executor->n_threads())`: a worker holds /// its chunk for the whole deadline. The executor must run chunks /// concurrently; a sequential one is not detected and degenerates to one /// worker under a wall clock, or N serial solves without one (see /// ExecutorRef). Non-owning. C++-only: a Python executor would serialise on /// the GIL. std::optional executor; }; /// The pool capacity a portfolio uses: `requested` when positive, otherwise /// `max(10, 2 * n_threads)` over the workers that run. See /// `ParallelConfig::pool_capacity`. Exposed for testing. [[nodiscard]] int effective_pool_capacity(int requested, int n_threads); /// The RNG seed for one portfolio worker's one run: a splitmix64 finalizer over /// (base_seed, worker, restart), so adjacent base seeds give unrelated /// portfolios. Exposed for testing. [[nodiscard]] uint64_t portfolio_worker_seed(uint64_t base_seed, int worker, int restart); /// The variant `SearchConfig::diversify_workers` gives portfolio worker /// `worker`, applied over the config as given (typed values included). Index /// `worker % 8` picks it: 0 none; 1, 2 Novelty Jump probability 0.2, 0.8; /// 3, 4 kick period 50 / probability 0.2, period 200 / 0.05; 5 FPR batches /// (probability at least 0.1) and the FPR dive in the LNS repair; 6 an LNS /// repair at every kick; 7 the objective tie-break flipped and kick /// probability 0.3. The table is #453's campaign choice (#474). Exposed /// for testing; ParallelSearch calls it per restart when the field is on. void apply_worker_variant(SearchConfig& cfg, int worker); /// 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. class ParallelSearch { public: explicit ParallelSearch(int n_threads = 0); // Every overload throws if every worker threw and none produced a result; // a partial failure returns the survivors' best and reports the dead workers // in `SearchResult::workers_completed` / `worker_failures` (#170). SearchResult solve(std::function model_factory, double time_limit = 10.0, uint64_t seed = 42); // Portfolio over one master model whose immutable structure every worker // shares (#157); implemented as a factory returning a copy of the frozen // master. Sharing follows from the model, not the overload: a factory // returning copies of a frozen model shares too; one returning an open or // fresh model deep-copies the DAG per worker. // // `master` is freeze()d on the calling thread before any worker exists // (see Model::freeze), so it comes back frozen with the `obj <= bound` row // and its assignment unchanged; this overload can therefore throw before // any worker runs. One master, one solve at a time; do not write the master // at all (values, node values, objective bound) while a solve runs: workers // copy it at arbitrary points and nothing detects the race. // // Each replica shares the structure and starts bit-for-bit from the // master's assignment. A one-worker portfolio is still not a single solve(): // it seeds with `portfolio_worker_seed(seed, 0, 0)`, has a non-null // SearchCoordination and may restart with `skip_init`. A // `lambda_sum`/`pair_lambda_sum` callable is shared by all workers, so // mutable state in it is a data race. 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(Model&)> hook_factory, std::function()> lns_factory, SolveCallback* callback, const ParallelConfig& par_config); // Full-featured solve with hooks, LNS, config, and parallel config. // // Each factory is called once per worker (not per restart) and must return // a distinct object each call: the search never locks a hook or an LNS. // `shared_ptr` because nanobind cannot relinquish ownership of an in-place // instance to a `unique_ptr` (#129). A Python hook_factory receives a copy // of the worker's Model (deep for an open model, #157); a C++ one gets the // worker's own. // // `callback` sees the portfolio's stream through one mutex-guarded // wrapper, invoked under that mutex: it needs no lock of its own, a slow // callback throttles every worker, and it must not call back into the // portfolio. See SolveProgress for which fields are the portfolio's. SearchResult solve(std::function model_factory, double time_limit, uint64_t seed, const SearchConfig& config, std::function(Model&)> hook_factory, std::function()> lns_factory, SolveCallback* callback, const ParallelConfig& par_config); private: int n_threads_; [[nodiscard]] int effective_threads(const ParallelConfig& pc) const; static SearchResult solve_portfolio( std::function& model_factory, double time_limit, uint64_t seed, const SearchConfig& config, std::function(Model&)>& hook_factory, std::function()>& lns_factory, SolveCallback* callback, int n_threads, const ParallelConfig& par_config); }; } // namespace cbls randomize.h =========== .. code-block:: c #pragma once #include "dag.h" #include "rng.h" #include // Uniform randomisation of a single variable over its own domain: the one // implementation behind initialize_random / initialize_structured_random, // LNS's destroy step and the scalar half of FJ's kick (#112; the kick's // List/Set half uses typed moves, #111). // // Every scalar entry point is total: a finite in-domain value for any domain // the model can hold, unbounded ones included (see `domain_window`). This // covers only randomisation: a Float jump candidate still reads var.lb/var.ub // directly, so an unbounded model can still reach an infinite assignment. namespace cbls { class Model; struct ListPartition; /// Magnitude standing in for an infinite Bool/Float bound when sampling; equal /// to NlToModelOptions::inf_clamp and MpsToModelOptions::inf_clamp, so an API /// model lands in the box the readers would give it. inline constexpr double kRandomInfClamp = 1.0e9; /// Magnitude standing in for an infinite Int bound when sampling; equal to /// NlToModelOptions::int_inf_clamp. inline constexpr double kRandomIntInfClamp = 1.0e6; /// Largest magnitude at which a double names every integer below it (2^53). /// `int_sample_window` trims to it so the int64_t cast and `+ 1` stay defined; /// `int_jump_candidates` checks it before stepping by 1.0, which past it does /// not advance. inline constexpr double kExactIntMagnitude = 9007199254740992.0; // 2^53 /// A finite `[lo, hi]` interval over a scalar variable's domain. `lo > hi` /// means empty, which only `int_sample_window` returns; `domain_window` always /// yields a non-empty subset of the domain. struct DomainWindow { double lo = 0.0; double hi = 0.0; }; /// `var`'s bounds, made safe to sample and to cast. A finite declared bound is /// returned untouched, so models that need no guard keep their RNG draws bit /// for bit. Rewritten only: /// - an infinite bound, to the clamp magnitude (`kRandomIntInfClamp` for Int, /// else `kRandomInfClamp`), since `uniform_real_distribution` needs /// `ub - lb <= DBL_MAX`; /// - on a half-infinite domain, the substituted end is pushed past the declared /// one where needed, so the window stays inside the domain; /// - two finite bounds whose width overflows, to the clamp box. /// Not trimmed to int64_t range (that is `int_sample_window`'s job, #112). /// Scalar types only. DomainWindow domain_window(const Variable& var); /// The subset of `domain_window(var)` that the int64_t cast and `+1` can name, /// rounded inward. Empty (`lo > hi`) when the domain lies wholly past 2^53; /// then `random_in_domain` draws from the untrimmed window, `int_rand` drops /// the move and `movable_domain` reports immovable. Int only; otherwise /// `domain_window`. DomainWindow int_sample_window(const Variable& var); /// Whether a scalar variable's domain holds at least two values (#109, #201). /// Bool reads its bounds; Int reads `int_sample_window` (`[0.9, 1.2]` is /// immovable); Float needs positive width. Scalar types only. bool movable_domain(const Variable& var); /// A uniform value from a scalar variable's domain, finite and in-domain (see /// `domain_window`). Bool draws from {0, 1} without reading its bounds, so a /// Bool pinned by `lb == ub` (unreachable today) would not be respected. double random_in_domain(const Variable& var, RNG& rng); /// How a List's new order relates to its current one. On a permutation List /// both draw a uniform permutation with identical RNG use; on a variable-length /// List (#164) only `Perturb` preserves length and membership, which keeps a /// ListPartition's cover intact under LNS. enum class ListOrder : std::uint8_t { /// Lay the List out from scratch per its `ListInit` (initialisers). Regenerate, /// Shuffle the current `elements` in place, keeping membership (LNS /// destroy/repair). Perturb, }; /// Redraw a List/Set variable's `elements` per its `ListInit` (List) or as a /// uniform admissible subset (Set). Per variable, so it cannot lay out a /// ListPartition: use `randomize_list_partition`. No-op on a scalar. void randomize_structured_var(Variable& var, RNG& rng, ListOrder order = ListOrder::Regenerate); /// Randomise one variable in place, whatever its type: `value` for a scalar, /// `elements` for a List/Set. void randomize_var(Variable& var, RNG& rng, ListOrder order = ListOrder::Regenerate); /// Lay a ListPartition out as a random assignment satisfying its cover (#164). /// Not uniform once a list's length bound binds. The initialisers call it /// instead of `randomize_var` on the members, so an `Exact` partition starts /// complete (no `Exact` move can repair one that is not). void randomize_list_partition(Model& model, const ListPartition& part, RNG& rng); } // namespace cbls rng.h ===== .. code-block:: c #pragma once #include #include #include #include #include namespace cbls { class RNG { public: explicit RNG(uint64_t seed = 42) : gen_(seed), seed_(seed) {} double uniform(double lo, double hi) { std::uniform_real_distribution dist(lo, hi); return dist(gen_); } int64_t integers(int64_t lo, int64_t hi) { // [lo, hi) exclusive of hi, like numpy std::uniform_int_distribution dist(lo, hi - 1); return dist(gen_); } double normal(double mean, double stddev) { std::normal_distribution dist(mean, stddev); return dist(gen_); } double random() { std::uniform_real_distribution dist(0.0, 1.0); return dist(gen_); } template void shuffle(std::vector& vec) { std::shuffle(vec.begin(), vec.end(), gen_); } std::vector permutation(int32_t n) { std::vector v(n); std::iota(v.begin(), v.end(), 0); shuffle(v); return v; } // Choose k elements from [0, n) without replacement std::vector choice(int32_t n, int32_t k) { std::vector pool(n); std::iota(pool.begin(), pool.end(), 0); std::shuffle(pool.begin(), pool.end(), gen_); pool.resize(k); return pool; } [[nodiscard]] uint64_t seed() const noexcept { return seed_; } std::mt19937_64& engine() { return gen_; } private: std::mt19937_64 gen_; uint64_t seed_; }; } // namespace cbls search.h ======== .. code-block:: c #pragma once #include "counters.h" #include "inner_solver.h" #include "lns.h" #include "model.h" #include "move_generator.h" #include "moves.h" #include "randomize.h" #include "rng.h" #include "stop.h" #include "violation.h" #include #include #include #include #include namespace cbls { /// Defined in `solution_pool.h`; forward-declared so `search.h` does not pull /// in ``, `` and `SolutionPool`. struct SearchCoordination; /// Defined in `tracer.h`; forward-declared for the same reason. class Tracer; /// Defined in `audit.h` (#225), forward-declared for the same reason. class SearchAuditor; struct SearchConfig { // Keep the caller's assignment whole: no List/Set randomisation and no // FJ closest-to-zero scalar start. bool skip_init = false; // Total GLS iterations (not batches); 0 = unlimited (bounded by time_limit). // Checked at batch boundaries, so it may be overrun by up to // batch_iterations - 1. A Novelty move charges 3, a weight bump 1 (#209). // The batch count is held to the same limit, since Structural batches charge // no GLS iteration: the run stops when either count reaches it and // SearchResult::iterations reports the larger (#201). int64_t max_iterations = 0; int lns_interval = 3; // ViolationLS batch outer loop (Algorithm 6). int64_t batch_iterations = 1000; // GLS iterations per batch; must be > 0 int perturbation_period = 100; // batches without improvement before perturbing // Share of the model a diversification kick moves: each scalar is // randomised with this probability; each List/Set gets // clamp(round(p * |elements|), 1, |elements|) structural moves (#111), so // every structure moves on every kick, p = 0 included. A kick moves at // least one variable (#109); one that hits the deadline stops between // moves (#115). double perturbation_probability = 0.1; // P(a batch is Structural: typed List/Set moves kept when they reduce // weighted violation). < 0 = automatic: 0.33 when the batch would build a // generator (an entry in move_generators, or a List/Set variable with // default_structural_generators on), else 0.0; 1.0 when it would and FJ // has no jumpable work: no Bool/Int/Float variable with >= 2 domain values // that some row reads, the folded objective included (#201). An explicit // value is honoured; on such a model its empty FJ/Novelty batches neither // kick nor count toward perturbation_period. A scalar read only by the // objective, or one FJ settles early, still counts as FJ work: set 1.0 // explicitly (#201). double structural_batch_probability = -1.0; // ---- structural batch: what proposes moves, and how one is chosen (#165) -- // // Extra move generators, on top of the built-in List/Set ones. Each // portfolio worker clones every generator, so per-generator state is // per-worker; the registered instances are never mutated (hence `const`) // and may be shared between searches. std::vector> move_generators; // Also register the built-in List/Set generators (off = custom moves only). bool default_structural_generators = true; // How candidates become a commit. Auto = GranularBest when // `structural_neighbours` is set, else the pre-#165 rule (#203). StructuralSelection structural_selection = StructuralSelection::Auto; // Candidates scored per generator under BestOfSample / ViolationGuided / // GranularBest (inert under FirstImprovingSample); GranularBest tops its // one-element neighbourhoods up to this floor. 8 is an unmeasured // placeholder (#203); sweep it per instance set. int structural_sample_size = 8; // Optional k-nearest neighbourhood for the built-in generators: a move's // target is a neighbour of the moved element instead of a uniform draw // (after Toth & Vigo 2003; see generate_granular_partition_moves). Null // keeps the uniform draw; set, Auto becomes GranularBest (#203). Shared, // not cloned: it is immutable (#157). std::shared_ptr structural_neighbours; // Run Novelty Jump batches (else FJ only). On by default since #209 // bounded a Novelty batch's cost; the UC-CHPED runner turns it off. bool use_compound_moves = true; // run Novelty Jump batches (else FJ only) // P(a scalar batch is Novelty Jump), drawn every batch, not held until a new // best as ViolationLS §5 does (#209; see pick_batch_kind). double novelty_jump_probability = 0.5; // P(a batch is fix-propagate-repair, #426): one LP-free dive over the // linear rows (`FprSearch`, the portfolio rotated per attempt) written to // the model, then, for a repairing mode, an FJ batch from it. Drawn first, // and only when > 0, so 0 (off) draws nothing and builds nothing. A // refuted root builds nothing either: the run is then the one at 0. A Dfs // attempt without a leaf keeps FJ's point and runs an FJ batch. Dives stop // at the deadline. In [0, 1]. double fpr_batch_probability = 0.0; // The FPR batch's propagator also revises the nonlinear rows over // monotone ops (Sum, Neg, Prod, Min, Max, Exp, Log), HC4-style (#424; // `DagRowStore`). Off by default: no store is built. Only the FPR batch; // the LNS repair's dive propagates linear rows alone. bool fpr_dag_propagation = false; // Keys the FPR portfolio rotation (`fpr_portfolio_config(worker, // attempt)`); ParallelSearch sets each worker's index. int fpr_worker = 0; // LNS repair runs one fix-propagate-repair dive over the destroyed scalars, // the kept ones fixed, before its FJ (#431; LNS::set_repair_store). Off by // default: no store is built and the trajectory is unchanged. The store's // build at the first LNS kick stops at the time limit (#434). bool lns_repair_fpr = false; // A constraint is satisfied when its violation is <= this: absolute, on the // constraint node's value (|lhs - rhs| for an equality). See // kDefaultFeasibilityTolerance. double feasibility_tolerance = kDefaultFeasibilityTolerance; // Byte cap on the per-variable cone cache solve() builds when it freezes // the model (#271; see Model::freeze); shared by all workers; 0 caches // nothing. Changes no trajectory. A pre-frozen model keeps its own cap. size_t cone_cache_bytes = Model::kDefaultConeCacheBytes; // End an FJ batch after this many GLS iterations without reducing the // unweighted violation of the real rows, and take the diversification kick // as due (#102); <= 0 = the fixed perturbation_period cadence. The kick // does not arm the Float escape probe or reset stagnation (#107). // Forwarded to GFJConfig::unproductive_iterations. Bounded twice: // 1. it fires only when `stagnation >= perturbation_period / 20`, since // its measure cannot see the `obj <= bound` row; // 2. once a feasible solution exists, it draws only the perturb half of a // kick, never an LNS repair: that measure is blind after feasibility // and a repair costs up to 2 s (#158; see SearchResult::lns_repairs). int64_t unproductive_iterations = 300; // Use the objective to break ties before the first feasible point (#218); // forwarded to GFJConfig::objective_tie_break (affine objectives only). On // here since #226; GFJConfig's own default stays off. bool fj_objective_tie_break = true; // ParallelSearch workers 1.. run a fixed table of variants of this config, // keyed by worker index (`apply_worker_variant`, pool.h); worker 0 keeps it // as given (#474; the table is #453's campaign choice, not measured // held-out). Read only by the portfolio; off by default. bool diversify_workers = false; // In [0, 1]. > 0: after FJ's start, each Float moves by a uniform draw in // +-jitter * min(max(1, |x|), half its finite width), clamped into its // bounds (#474). solve() applies it unless skip_init; ParallelSearch only on // odd-indexed workers, so a one-worker portfolio never does. 0 draws nothing. double float_start_jitter = 0.0; // ---- host integration (#169): cancellation and tracing ------------------ // // Both are non-owning: the caller keeps the objects alive for the whole // solve. Fields, not solve() parameters, so a binding cannot drop them and // they reach every portfolio restart (run_worker copies this struct). // Host cancellation; unset = bounded by time_limit and max_iterations // alone. A raised stop ends the run at the next batch boundary with // TerminationReason::Cancelled. See StopRef for the lifetime rule. StopRef stop; // Host event sink, or null (one null compare per event site). Per worker: // share a Tracer between workers only if it is thread-safe; otherwise use // ParallelConfig::tracer_factory. See Tracer for granularity and cost. Tracer* tracer = nullptr; // Test-facing consistency hook (#225), or null; non-owning. See // SearchAuditor. SearchAuditor* auditor = nullptr; }; /// Why solve()'s outer loop stopped; exactly one ends every run. The qualifier /// on `time_seconds`: it tells a run that exhausted its budget from one that /// converged, and lets a test prove which budget bound it (#104). enum class TerminationReason : std::uint8_t { /// The wall-clock deadline from `solve()`'s `time_limit` expired. TimeLimit, /// `SearchConfig::max_iterations` was reached (GLS iterations, or the batch /// count when structural/novelty batches stall the iteration counter). IterationLimit, /// Pure-feasibility model (no objective): the first feasible solution is the /// answer, so the search stopped on finding one. Feasible, /// Neither a wall-clock nor an iteration budget was set: returned at once, /// having done no work. NoBudget, /// A peer worker ended the run (`SearchCoordination::stop`) while budget /// remained; only from ParallelSearch, when a worker solved a /// pure-feasibility model. Not TimeLimit: the clock did not run out. Stopped, /// The host cancelled (`SearchConfig::stop` or `ParallelConfig::stop`) /// while budget remained. Outranks Stopped (the host's cancel is the outer /// cause); Feasible outranks both. Cancelled, }; /// Stable snake_case token for a TerminationReason ("time_limit", /// "iteration_limit", "feasible", "no_budget", "stopped", "cancelled"): the /// CLI's JSONL `termination` field and its human output. Static; never null. const char* termination_reason_name(TerminationReason reason); /// One `ParallelSearch` worker that did not complete, and why (#170). See /// `SearchResult::workers_completed` for what "complete" means. struct WorkerFailure { /// The worker's index in `[0, workers_launched)`. int worker = 0; /// Whether the worker returned at least one solve before it died; those /// solves are in the aggregate's iterations and counters, the throwing /// attempt is not. False means "no counters in the aggregate", not /// "contributed nothing": an incumbent it pooled may still be the answer. bool produced_result = false; /// `what()` of the exception that ended the worker (nanobind's traceback /// for a Python one), a fixed string for a non-std exception, or a fixed /// sentence for a worker the deadline starved before its first solve. std::string reason; }; struct SearchResult { /// 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. double objective = std::numeric_limits::infinity(); /// Whether `best_state` satisfies every real constraint, whatever the /// objective is there. bool feasible = false; Model::State best_state; /// 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. int64_t iterations = 0; double time_seconds = 0.0; /// Which budget ended the run; qualifies `iterations` and `time_seconds`. TerminationReason termination = TerminationReason::NoBudget; /// Largest real-constraint violation at `best_state` (<= the tolerance when /// `feasible`). On an infeasible run, the closest approach found. double best_violation = std::numeric_limits::infinity(); /// 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. bool escape_probe_armed = false; /// 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 perturbations = 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 = 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`. int lns_repairs_accepted = 0; /// 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 first_feasible_objective = std::numeric_limits::quiet_NaN(); /// Seconds from solve()'s start to the first feasible point; NaN if and /// only if none was recorded. See `first_feasible_objective`. double time_to_first_feasible = std::numeric_limits::quiet_NaN(); /// 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. SearchCounters counters; /// 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_launched = 1; int workers_completed = 1; /// One entry per worker that did not complete -- it threw, or the deadline /// starved it -- in worker order. Empty on every non-portfolio result. std::vector worker_failures; }; /// One progress row. Under ParallelSearch, `time_seconds`, `objective` and /// `new_best` are the portfolio's (monotone; the last row matches the result), /// while `iteration`, `total_violation`, `feasible` and `perturbations` are the /// reporting worker's, so not monotone. See PortfolioProgress in src/pool.cpp. struct SolveProgress { int64_t iteration = 0; double time_seconds = 0.0; double objective = std::numeric_limits::infinity(); /// Weighted violation over all rows, the `obj <= bound` row included, so /// routinely positive when feasible; ~1e30 on a feasible point with a /// non-finite objective (#116). double total_violation = 0.0; bool feasible = false; bool new_best = false; int perturbations = 0; // diversification kicks so far (ViolationLS) }; class SolveCallback { public: virtual ~SolveCallback(); virtual void on_progress(const SolveProgress& p) = 0; }; /// Randomise every variable, scalars included. solve() does not call it (FJ /// owns the scalar start); pair it with `SearchConfig::skip_init = true`. Safe /// on unbounded domains: draws a finite window (#112). void initialize_random(Model& model, RNG& rng); /// Randomise only the List/Set variables; what solve() calls, since FJ's /// `begin(set_initial_x)` sets the scalars to their closest-to-zero value (#108). void initialize_structured_random(Model& model, RNG& rng); /// Returns the GLS iterations the repair pass spent; below `max_iterations` /// it converged or `time_limit` cut it short (#104). int64_t fj_nl_initialize(Model& model, ViolationManager& vm, int max_iterations = 10000, RNG* rng = nullptr, double time_limit = 2.0, double tolerance = kDefaultFeasibilityTolerance); /// Throws std::invalid_argument on a config the search cannot run: today /// `batch_iterations <= 0`, which would let a counter-only loop ignore the time /// limit (#211). solve() and ParallelSearch call it on entry. void validate_search_config(const SearchConfig& config); /// `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. SearchResult 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); } // namespace cbls stop.h ====== .. code-block:: c #pragma once #include #include namespace cbls { /// A host's cancellation channel, type-erased and NON-OWNING (#169), for a /// host that cancels for reasons the engine cannot see (a peer finished, a /// user stop, another clock). `SearchCoordination::stop` is not this API. /// /// Adapts anything with `bool requested() const`. Nothing here owns, copies or /// destroys the source, so the SOURCE MUST OUTLIVE THE SOLVE. A default /// `StopRef` is never requested and costs one null compare, so the /// unconfigured search keeps exactly its trajectory. /// /// `std::stop_token` does not fit (its member is `stop_requested()`; it fails /// to compile inside `thunk`). A C++20 host writes the adaptor, held as a NAMED /// lvalue because the deleted rvalue constructor refuses a temporary: /// /// ``` /// struct CancelOn { /// std::stop_token token; /// bool requested() const { return token.stop_requested(); } /// }; /// CancelOn cancel{source.get_token()}; /// config.stop = cancel; /// ``` /// /// `requested()` is polled at the search's safe points (where the wall clock /// is read), so a raised stop ends the run within ONE batch, not one /// iteration; see `SearchConfig::stop`. It is called from the search thread /// and from EVERY `ParallelSearch` worker, so it must be safe to call /// concurrently. class StopRef { public: /// Never requested. The default on `SearchConfig` and `ParallelConfig`. StopRef() = default; /// Non-explicit so `config.stop = token;` works. The `enable_if` keeps this /// template from hijacking the copy constructor. template , StopRef>>> // Implicit by design; see above. StopRef(const S& source) : obj_(&source), fn_(&thunk) {} /// Rejects a TEMPORARY at compile time: `const S&` above would bind /// `config.stop = HostFlag{};` and read freed memory at every poll. Mirrors /// `ExecutorRef`, which takes `E&`. `const S&&` binds rvalues only. template , StopRef>>> StopRef(const S&&) = delete; /// False when no source is attached. A source whose `requested()` throws /// is a contract violation. [[nodiscard]] bool requested() const { return fn_ != nullptr && fn_(obj_); } /// Whether a source is attached (for reporting and the bindings). /// /// AN ATTACHED STOP IS NOT A BUDGET: a run with no wall clock and no /// iteration limit returns at once with `TerminationReason::NoBudget`, so a /// host that forgets to cancel cannot hang it. Give such a run a generous /// `time_limit` and cancel inside it. [[nodiscard]] bool attached() const noexcept { return fn_ != nullptr; } private: template static bool thunk(const void* obj) { return static_cast(obj)->requested(); } const void* obj_ = nullptr; bool (*fn_)(const void*) = nullptr; }; /// The built-in stop source: a thread-safe flag a host raises from anywhere. /// Relaxed ordering: the flag guards no data, and seeing it late costs one /// batch. Non-copyable and non-movable, so a `StopRef` to it cannot dangle by /// relocation; own it for at least as long as the solve. class StopToken { public: StopToken() = default; StopToken(const StopToken&) = delete; StopToken& operator=(const StopToken&) = delete; StopToken(StopToken&&) = delete; StopToken& operator=(StopToken&&) = delete; ~StopToken() = default; void request() noexcept { flag_.store(true, std::memory_order_relaxed); } /// Clear the flag for reuse. A solve does NOT reset it: a raised token /// handed to the next solve cancels that one before it starts. void reset() noexcept { flag_.store(false, std::memory_order_relaxed); } [[nodiscard]] bool requested() const noexcept { return flag_.load(std::memory_order_relaxed); } private: std::atomic flag_{false}; }; } // namespace cbls tracer.h ======== .. code-block:: c #pragma once #include "counters.h" #include namespace cbls { /// Which diversification kick `Tracer::kick` is reporting. enum class KickKind : std::uint8_t { /// A random perturbation of the assignment (`diversify`, the cheap half). Perturb, /// An LNS destroy-repair cycle was drawn; `Tracer::lns` reports its outcome /// immediately after. LNS, /// Restart from a peer's pool solution instead of perturbing. Portfolio /// only: `adopt_from_pool` returns false at once without a pool. Adopt, }; /// Stable snake_case token for a `KickKind` ("perturb", "lns", "adopt"). /// Returns a static string; never null. const char* kick_kind_name(KickKind kind); /// An unthrottled event sink, delivered on the search's own thread with no /// rewriting; distinct from `SolveCallback`, the throttled (~1/s) progress /// stream on the portfolio's clock and incumbent. Under a portfolio each /// worker gets its own `Tracer` (`ParallelConfig::tracer_factory`, by worker /// index), so hosts aggregate themselves; routing through the progress /// wrapper would serialise workers on one mutex per batch. /// /// Granularity is the batch, never the iteration (a per-iteration virtual /// call would sit on the GLS hot loop): each method fires at most once per /// batch, kick or inner-solver call. Default `SearchConfig::tracer` is null: /// one predictable null compare per site, nothing else. Methods are no-ops; /// override only what you want. /// /// Attaching a tracer adds clock reads (one per new best, two per /// inner-solver call), even on an iteration-budgeted run (`time_limit <= 0`, /// no callback) whose loop otherwise reads none (`dev/architecture.md`); the /// trajectory is unchanged, but iteration throughput pays for them. /// /// A throwing method propagates out of `solve()` like a raising /// `SolveCallback::on_progress`, leaving the model at the reached assignment; /// under `ParallelSearch` it is absorbed per worker. class Tracer { public: Tracer() = default; Tracer(const Tracer&) = default; Tracer& operator=(const Tracer&) = default; Tracer(Tracer&&) = default; Tracer& operator=(Tracer&&) = default; /// Out-of-line: the key function, so the vtable is emitted once. virtual ~Tracer(); /// One batch finished. `iterations` is the run's CUMULATIVE GLS count /// after it (as `SearchResult::iterations`); difference consecutive events /// for a batch's cost. Structural batches charge none, so it repeats; a /// Novelty batch charges 3 per move and 1 per weight bump (#209). /// `improved`: the batch produced a new best. virtual void batch_end(BatchKind kind, int64_t iterations, bool improved); /// A new best real-feasible solution, with seconds since this `solve()` /// started. Arrives before the `batch_end` of the batch that produced it, /// which is what lets a consumer attribute it; fires before the inner /// polish and again after it if the polish improved. A pool adoption /// (`adopt_from_pool`) that installs a better incumbent is NOT reported /// here, since it happens after `batch_end`; it is `kick(KickKind::Adopt)`. /// So this stream is THIS worker's own improvements; the portfolio's /// incumbent is what `SolveCallback` reports. virtual void new_best(double objective, double seconds); /// A diversification kick was taken. `KickKind::LNS` is followed by exactly /// one `lns()` event carrying its outcome. virtual void kick(KickKind kind); /// An LNS destroy-repair cycle finished; `accepted` is what /// `LNS::destroy_repair` returned (see /// `SearchResult::lns_repairs_accepted`). virtual void lns(bool accepted); /// An `InnerSolverHook::solve` call finished, and how long it took. virtual void hook(double seconds); }; } // namespace cbls verify.h ======== .. code-block:: c #pragma once #include "model.h" #include #include #include #include namespace cbls { struct VerifyError { enum class Kind : std::uint8_t { VarBounds, VarIntegrality, ConstraintViolation, ObjectiveMismatch, DagConsistency, Custom }; Kind kind; std::string entity; double expected = 0.0; double actual = 0.0; std::string message; }; struct VerifyResult { bool ok = true; std::vector errors; void add_error(VerifyError e) { ok = false; errors.push_back(std::move(e)); } void merge(const VerifyResult& other) { for (const auto& e : other.errors) { add_error(e); } } void print_diagnostics(FILE* out = stderr) const { if (ok) { fprintf(out, "verify: PASS\n"); return; } fprintf(out, "verify: FAIL (%d errors)\n", static_cast(errors.size())); for (const auto& e : errors) { const char* kind_str = "?"; switch (e.kind) { case VerifyError::Kind::VarBounds: kind_str = "VarBounds"; break; case VerifyError::Kind::VarIntegrality: kind_str = "VarIntegrality"; break; case VerifyError::Kind::ConstraintViolation: kind_str = "ConstraintViolation"; break; case VerifyError::Kind::ObjectiveMismatch: kind_str = "ObjectiveMismatch"; break; case VerifyError::Kind::DagConsistency: kind_str = "DagConsistency"; break; case VerifyError::Kind::Custom: kind_str = "Custom"; break; } fprintf(out, " [%s] %s: expected=%.6f actual=%.6f %s\n", kind_str, e.entity.c_str(), e.expected, e.actual, e.message.c_str()); } } operator bool() const { return ok; } }; VerifyResult verify_model(const Model& model, double tol = 1e-6); } // namespace cbls violation.h =========== .. code-block:: c #pragma once #include "model.h" #include #include #include namespace cbls { /// The engine's blowup clamp: every non-finite or absurdly large violation /// maps here, so inf/NaN stays well-ordered. It is also the largest objective /// the violation machinery can tell from a blowup, so `record_best` installs it /// as the sentinel bound for a feasible point with a non-finite objective /// (#116); that is sound only while clamp and sentinel are one constant. inline constexpr double kInfPenalty = 1.0e30; /// A constraint node's value as a violation: max(0, value), with +inf, NaN /// and values above kInfPenalty mapped to kInfPenalty (very bad, still /// ordered). One definition for ViolationManager, `Model`'s jump scoring and /// FJ's closed-form linear scorer, which must all agree on it. inline double clamped_node_violation(double node_value) { // Before max(): std::max(0.0, NaN) is 0.0, which would mask NaN as // satisfied. NaN is a maximal violation; nothing says it holds. if (std::isnan(node_value)) { return kInfPenalty; } const double v = std::max(0.0, node_value); if (v > kInfPenalty) { // also catches +inf return kInfPenalty; } return v; } class ViolationManager { public: explicit ViolationManager(Model& model); double constraint_violation(int i) const; double total_violation() const; // Raw objective + unit-weighted total violation; InnerSolverHook descends // it. While solve() folds in `obj <= bound`, the objective counts twice: // fine for local polish, wrong for accept rules (LNS checks feasibility). double augmented_objective() const; bool is_feasible(double tol = kDefaultFeasibilityTolerance) const; /// Largest unweighted violation over the real constraints, the objective /// row (`obj <= bound`) excluded; 0.0 when all hold, +inf if any row is NaN. /// The search's own feasibility test is `max_real_violation() <= /// SearchConfig::feasibility_tolerance`; a hook classifies a point with it /// (#454). `is_feasible` counts the objective row, which a non-improving /// feasible point violates, and holds domain rows to 0. [[nodiscard]] double max_real_violation() const; std::vector violated_constraints(double tol = kDefaultFeasibilityTolerance) const; void bump_weights(double factor = 1.0); // sum_c W[c] * delta_c if var_id <- j, uncommitted (the paper's -score). // Scalar variables only; throws on List/Set. `const` is logical only: it // mutates and restores the model, so it is NOT reentrant on a shared Model // (each search thread owns its own). double weighted_violation_delta(int32_t var_id, double j) const; // Per-constraint clamped violations, and the weighted change against such // a snapshot: the List/Set counterpart of weighted_violation_delta. They // difference PER CONSTRAINT because subtracting two totals (a) lets a // kInfPenalty row absorb every O(1) row (#100, #118) and (b) misses an // exact 0 for an unchanged row by an ulp of accumulator drift (#118). // // Snapshot the accepted state once, read weighted_delta_from() after each // applied candidate, re-snapshot only when one is kept. It throws unless // the snapshot has one entry per constraint. Both are O(#constraints); // snapshot_violations also refreshes the cached total, the other no cache. void snapshot_violations(std::vector& out) const; double weighted_delta_from(const std::vector& snapshot) const; /// The same quantity over `rows`: constraint indices, STRICTLY ASCENDING. /// Bit-identical to the full scan when `rows` covers the union of the /// moved variables' G_v (`Model::constraints_of_var`): rows outside it /// equal their snapshot and add nothing, and ascending order sums the same /// terms in the same sequence (pinned by /// `tests/test_structural_batch.cpp`). /// /// O(|rows|) against O(#constraints): the structural batch scores every /// candidate this way, and a List move touches only the rows reading it. /// /// `differing`, when non-null, gets each row of `rows` whose violation /// differs from the snapshot (the rows that contributed a term), appended /// in `rows` order (#273). Throws like the full scan on a wrong-size /// snapshot; an out-of-range entry in `rows` throws `std::out_of_range`. double weighted_delta_from(const std::vector& snapshot, ConstSpan rows, std::vector* differing = nullptr) const; // Invalidate cached total (call after weights change or full_evaluate) void invalidate_cache() { cache_valid_ = false; } std::vector weights; private: /// Throw unless `weights` and the violation cache have one entry per /// constraint of the model as it is NOW. `freeze()` / the first `solve()` /// of a model with an objective append the objective row, so a manager /// built before is one row short: reads would overread the heap and /// `bump_weights` write past it. Build a new manager then. Also catches a /// C++ caller shortening the public `weights` (Python's setter rejects a /// length change, #156, but against the manager's size, not the model's). /// One compare is noise against O(#constraints) bodies; /// `weighted_violation_delta` is not one, but FJ bypasses it (it calls /// `Model::weighted_violation_delta`), so only Python and tests pay. void require_row_count() const; void recompute_cache() const; Model& model_; mutable std::vector cached_violations_; // max(0, node_value(cid)) per constraint mutable double cached_total_ = 0.0; mutable bool cache_valid_ = false; mutable int incremental_updates_ = 0; // counter to trigger periodic full recompute }; } // namespace cbls