Skip to content

How a solve runs, in the code

Every use case runs the same loop: build a first solution, then improve it one move at a time, each move judged by an acceptor, with perturbation when the search stalls, until a limit is reached. This page follows that loop step by step and says, for each step, where it is in the code, which settings change it, and how to add to it. The steps and their names are those of the flowchart on optimaru.com.

The loop itself is Solver::run in core/optimaru/solver.hpp. It delegates moves to plugins. Built-in operators live under core/optimaru/search/, the acceptance rules are in core/optimaru/accept/ and the operator selection in core/optimaru/select/. A use case registers its own operators and acceptors through the same interfaces the built-in ones use. Each step below is marked in Solver::solve (step 1) and Solver::run (the rest) with a comment that names it (// How it solves, 3: ...), so you can find it there by its number.

Paths are relative to the repository root. Settings are named as Python reads them (config.<group>.<name>, see optimaru/_config.py); the C++ Settings in core/optimaru/settings.hpp has the same groups apart from cost, which a use case reads itself (stop is of type Limits there).

Step Where To add one
1. Construction construct/construction.hpp Construction instead of search
2. Current and best solver.hpp, solution/snapshot.hpp
3. Stop condition stop/stop_condition.hpp Solver::add_stop_criterion
4. Search stalled? solver.hpp, accept/history_stages.hpp
5. Perturbation search/perturbation/, search/ruin/, insert/ A ruin instead of a move
6. Built-in strategy search/strategies/ an engine change
7. Use-case moves search/operators.hpp, select/ Adding a move
8. Move mix search/move_mix/move_mix.hpp an engine change
9. Incremental score solution/editor.hpp, score/ Adding a cost
10. Acceptor accept/ Solver::set_acceptor_factory, or an engine change
11. New best solver.hpp

All paths in the table are under core/optimaru/. A use case adds moves, ruins and costs in its own files, optimaru/<uc>/cpp/<ns>/, and never edits these.

Before the loop

1. Construction

Each unassigned entity gets its best placement; a solution passed in is kept and only the rest is built. Assignment shape: the best value for each entity. Sequence shape: cheapest insertion, the best list and position for each element.

  • Code: Construction<Solution>::run in core/optimaru/construct/construction.hpp, called by Solver::solve before Solver::run; each heuristic has its own file in the same folder: first_fit.hpp (assignment) and cheapest_insertion.hpp (sequence).
  • Settings: config.construction (where the use case has it, such as first_fit_decreasing). In C++, ConstructionSettings::difficulty orders the entities (first fit decreasing).
  • To change it for one use case: a difficulty order, or a construction of the use case's own registered with Solver::set_construction (Construction instead of search).

2. Current and best

The current solution s and the best one s_best both start from the construction's. The best is kept as a snapshot apart from the solution the search works on, so a step that makes things worse never loses it, and it is put back when the solve ends.

Each step, until a stop condition holds

3. Stop condition

At the start of each step, the solver checks the configured stop conditions, which can include time or step limits, time or steps since the last improvement, and a target score. The first condition met ends the solve. Long-running strategies check the same conditions between batches of evaluations, so one move cannot run far past the time limit.

  • Code: StopCondition::should_stop in core/optimaru/stop/stop_condition.hpp, which assembles the criteria of config.stop, one file each in the same folder: max_runtime.hpp, no_improvement_time.hpp, max_steps.hpp, no_improvement_steps.hpp, target_score.hpp, stop_requested.hpp (all read the StopState of stop_state.hpp); the throttle long moves use is in stop/stop_throttle.hpp.
  • Settings: config.stop (time_limit_seconds, step_limit, unimproved_time_limit_seconds, unimproved_step_limit, target_score).
  • A stop rule of a use case's own: a StopCriterion (stop/stop_criterion.hpp) registered with Solver::add_stop_criterion, asked after the built-in ones. The factory makes one per solve and per start of a multi-start run, so it is called concurrently there.

4. Search stalled?

The search has stalled when no new best has come for as many steps as it usually takes between new bests (eight times their moving average), and at least for the configured trigger. Each perturbation doubles the wait, up to 4096 times the trigger. A new best resets it, so the wait grows only while perturbations find no improvement. Where late acceptance runs in stages with growing history, a stall can start the next stage.

  • Code: the patience and stalled lines of Solver::run in core/optimaru/solver.hpp, and HistoryStages in core/optimaru/accept/history_stages.hpp.
  • Settings: config.perturbation (enabled, unimproved_steps). The stages are AcceptanceSettings::history_growth in C++, which a use case sets in its solver where it measured that they pay (facility location and quadratic assignment, for two).

5. Perturbation

Perturbation removes and reinserts part of the current solution so the search can explore alternatives. An adaptive selector picks a removal operator, which removes 10 to 30% by default. Regret-k insertion (k = 3 by default) places the item that would lose the most by waiting first. With regret_k below 2, the engine uses cheapest insertion. A short hill climb with the move mix follows. The result becomes the current solution even if it scores worse. The score helps the selector choose removal operators in future perturbations.

  • Code: StagnationKick::apply in core/optimaru/search/perturbation/stagnation_kick.hpp; how many it ruins (shared with the step 6 strategies that ruin) in count.hpp; the ruin operators and their selection in pool.hpp (random, related, worst, and for sequences SISR and route ruins, one file each beside it); the rebuild in insert/repair.hpp; the selection schemes in core/optimaru/select/.
  • Settings: config.perturbation (enabled, unimproved_steps, min_ruin_fraction, max_ruin_fraction, max_ruin_count, polish_steps) and config.ruin_recreate (selection_type, rewards, the ruin switches, regret_k, ...).
  • To add a ruin for one use case: a RuinOperator registered with add_ruin_operator(); it joins the built-in ones in the same pool (A ruin instead of a move).

6. Built-in strategy

The step's move is asked for in a fixed order (Solver::choose_move). First, each built-in strategy gets one draw by its weight, in priority order, and the first that hits makes the move. A strategy searches a large neighbourhood in one move: route elimination, ejection chain and iterated local search (these three on sequences only), descent, and ruin and recreate as an ordinary move, which the acceptor judges like any other.

7. Use-case moves

If the use case adds moves of its own, then on a set share of the steps left an adaptive selector picks one of them or the move mix, by what each has found so far. (Box sizing lets them take turns evenly instead: its moves on the set of sizes are turned down most of the time and are still the only ones that reach another set.)

  • Code: Solver::choose_move and Solver::custom_operators_get_a_turn in core/optimaru/solver.hpp; the interface, MoveOperator, in core/optimaru/search/operators.hpp; the selection schemes in core/optimaru/select/. A use case's own moves are in optimaru/<uc>/cpp/<ns>/search/moves/, registered in its registerMoves() in solver.cpp.
  • Settings: config.custom_moves (share, and the use case's switches).
  • To add one: Adding a move. This is the most common contribution, and it never touches the engine.

8. Move mix

Otherwise one ordinary small move is drawn by relative weight. Assignment shape: change (another value for one entity) and swap. Sequence shape: relocate, swap, 2-opt, Or-opt, 2-opt* (tail swap) and CROSS-exchange. What it moves is chosen by the selection rules: nearby candidates first where a distance is configured, and the use case's entity and value hints.

  • Code: MoveMixSampler::sample in core/optimaru/search/move_mix/move_mix.hpp, which draws among the moves, one file each in the same folder: change.hpp, swap.hpp, relocate.hpp, element_swap.hpp, two_opt.hpp, or_opt.hpp, two_opt_star.hpp, cross_exchange.hpp (what they draw with is in move_draw.hpp); the sequence moves' preview, apply and undo in list_move.hpp.
  • Settings: config.moves (the weights), config.selection (nearby, hints).
  • Before writing a move, check whether reweighting these does the job (First, check the built-in moves).

9. Incremental score

Only what the move touched is scored again, which is what makes a step cheap. A sequence move is often scored from the objective's cached data without being applied at all (a preview), and applied only if the acceptor takes it. With config.run.full_assert every incremental score is compared with a full recompute.

  • Code: Editor in core/optimaru/solution/editor.hpp (the only way a move changes the solution), the Objective contract in core/optimaru/score/objective.hpp, and DecomposedObjective with its per-unit and global constraints in score/decomposed_objective.hpp. A use case's costs are in optimaru/<uc>/cpp/<ns>/constraints/.
  • Settings: config.cost where the use case has it; the constraints themselves are picked and weighted per solve (constraints=).
  • To add a cost: Adding a cost, and the worked example in each use case's docs/use-cases/<slug>/extending.md.

10. Acceptor

The acceptor decides whether the search moves to the candidate. Late acceptance by default: a move is taken if it is no worse than the current solution or than the one a fixed number of steps ago. The engine has seven rules: hill climbing, late acceptance, entity tabu, simulated annealing, great deluge, step counting hill climbing and record-to-record travel. A rejected move is undone (a previewed one was never applied).

  • Code: one file per rule in core/optimaru/accept/, the interface in acceptor.hpp and the factory, make_acceptor, in acceptors.hpp.
  • Settings: config.acceptance (rule, and each rule's own settings).
  • A use case can set its own acceptor with Solver::set_acceptor_factory; a new built-in rule is a file there, a line in acceptors.hpp, a value of AcceptanceRule and a case in make_acceptor.

11. New best

If the current solution is better than the best, it becomes the best (the snapshot is taken again) and the stall counters start over. Then the next step begins.

After the loop

The best snapshot is put back into the solution and its score returned. With config.run.parallel_solver_count above 1, Solver::solve_multistart (in core/optimaru/solver.hpp) runs that many solves from different seeds on threads and keeps the best. A use case that registers moves of its own on each start goes through solve_parallel_starts in core/optimaru/solver_config.hpp instead, which does the same around the use case's own solve.

Where to extend

  • Most extensions are a move (step 7) or a cost (step 9) for one use case: CONTRIBUTING.md has the setup and the short recipes, extending.md the full steps with real code.
  • A change to steps 3 to 11 in the engine must keep every use case's seeded results and speed: see Changing the engine.