Designing a search strategy

How to design search strategies?

Automatic search configuration with BlackBoxConfigurator

BlackBoxConfigurator builds a complete search strategy for a model: variables are grouped by type (integer, set, graph, real), each group gets a strategy, then a meta-strategy (e.g. last conflict) and a restart policy are added. It is what Choco uses when no search strategy is declared (BlackBoxConfigurator.init().make(model)).

Two presets are tuned for satisfaction (forCSP()) and optimization (forCOP()) problems:

// a configuration for optimization problems (forCSP() for satisfaction problems),
// applied to all the variables of the model
BlackBoxConfigurator.forCOP().make(model);

Each part can be changed with a set... method before calling make(model): setIntVarStrategy, setSetVarStrategy, setGraphVarSearch, setRealVarStrategy, setIntObjVarStrategy, setMetaStrategy, setRestartPolicy, setNogoodOnRestart, setRestartOnSolution, setExcludeViews, setExcludeObjective, …

BlackBoxConfigurator.forCOP()
        // dom/wdeg on integer variables, smallest value first
        .setIntVarStrategy(vars -> Search.domOverWDegSearch(vars))
        // Luby restarts: cutoff 500, maximum 50,000 restarts, reset the cutoff on solutions
        .setRestartPolicy(SearchParams.Restart.LUBY, 500, 0., 50_000, true)
        .setNogoodOnRestart(true)
        .make(model);

complete(model, strategy) completes a declared strategy with the black-box one, for the variables it does not cover.


MetaStrategy: Composing strategies

Overview

MetaStrategy is an abstract class for wrapping base strategies with meta-heuristics. Meta-strategies enhance the behavior of a base strategy without changing the base strategy itself.

Common meta-strategies include:

  • Last-Conflict (LastConflict): Focuses on variables involved in recent failures
  • Conflict Ordering Search (COS): Combines search history with variable selection

Using MetaStrategy

import org.chocosolver.solver.search.strategy.strategy.MetaStrategy;
import static org.chocosolver.solver.search.strategy.Search.*;

Solver solver = model.getSolver();

// Wrap a base strategy with last-conflict
AbstractStrategy<IntVar> baseStrategy = minDomLBSearch(x, y, z);
AbstractStrategy<IntVar> metaStrategy = lastConflict(baseStrategy);

solver.setSearch(metaStrategy);

Composing multiple meta-strategies

You can compose multiple strategies, with the first being executed, then falling back to subsequent ones:

solver.setSearch(
    lastConflict(domOverWDegSearch(x, y, z)),
    setVarSearch(sets),
    realVarSearch(reals)
);

Common meta-strategies in Search factory

  • lastConflict(AbstractStrategy<IntVar>, int k) — Focus on k variables involved in recent failures
  • conflictOrderingSearch(AbstractStrategy<IntVar>) — COS: use conflict history
  • greedySearch(AbstractStrategy<IntVar>) — No backtracking (greedy)
  • sequencer(AbstractStrategy...) — Chain multiple strategies

IntDomainSticky: phase saving

IntDomainSticky is a value selector implementing phase saving: it selects the last value a variable took during propagation, if this value is still in its domain, and falls back to another value selector otherwise. It is useful together with restarts, to drive the search back towards the regions it explored before:

// try first the last value each variable took during propagation (phase saving),
// or the smallest value of its domain if this value is no longer available
IntDomainSticky sticky = new IntDomainSticky(vars, new IntDomainMin(), null);
solver.setSearch(Search.intVarSearch(new FirstFail(model), sticky, vars));
solver.setLubyRestart(500, new FailCounter(model, 500), 50_000);

Designing your own search strategy

Using selectors

To design your own strategy using Search.intVarSearch, you simply have to implement your own variable and value selectors:

public static IntStrategy intVarSearch(VariableSelector<IntVar> varSelector,
                                    IntValueSelector valSelector,
                                    IntVar... vars)

For instance, to select the first non instantiated variable and assign it to its lower bound:

Solver s = model.getSolver();
s.setSearch(intVarSearch(
        // variable selector
        (VariableSelector<IntVar>) variables -> {
            for(IntVar v:variables){
                if(!v.isInstantiated()){
                    return v;
                }
            }
            return null;
        },
        // value selector
        (IntValueSelector) var -> var.getLB(),
        // variables to branch on
        x, y
));

NOTE: When all variables are instantiated, a VariableSelector must return null.

From scratch

You can design your own strategy by creating Decision objects directly as follows:

s.setSearch(new AbstractStrategy<IntVar>(x,y) {
    // enables to recycle decision objects (good practice)
    PoolManager<IntDecision> pool = new PoolManager();
    @Override
    public Decision getDecision() {
        IntDecision d = pool.getE();
        if(d==null) d = new IntDecision(pool);
        IntVar next = null;
        for(IntVar v:vars){
            if(!v.isInstantiated()){
                next = v; break;
            }
        }
        if(next == null){
            return null;
        }else {
            // next decision is assigning nextVar to its lower bound
            d.set(next,next.getLB(), DecisionOperator.int_eq);
            return d;
        }
    }
});

Making a decision greedy

You can make a decision non-refutable by using decision.setRefutable(false) inside your

To make an entire search strategy greedy, use:

Solver s = model.getSolver();
s.setSearch(greedySearch(inputOrderLBSearch(x,y,z)));

Large Neighborhood Search (LNS)

Defining its own neighborhoods

A presentation of the functioning of LNS was given earlier. It is said that anyone can define its own neighbor, dedicated to the problem solved. This is achieved by extending either the abstract class IntNeighbor or by implementing the interface INeighbor. The former implements all methods from the latter but void fixSomeVariables() throws ContradictionException; that defines which variables should be fixed to their value in the last solution.

INeighbor forces to implements the following methods:

/**
 * Action to perform on a solution. 
 * Typically, storing the current variables’ value.
 */
public void recordSolution() {
    // where `values` and `variables` are class instances
    for (int i = 0; i < variables.length; i++) {
        values[i] = variables[i].getValue();
    }
}  
/**
 * Fix some variables to their value in the last solution.
 */
public void fixSomeVariables() throws ContradictionException{
    // An example of random neighbor where a coin is tossed
    // for each variable to choose if it is fixed or not in the current fragment
    for (int i = 0; i < variables.length; i++) {
        if(Math.random() < .9){
            variables[i].instantiateTo(values[i], this);
            // alternatively call: `this.freeze(i);`    
        }
    }
}
/**
 * Relax the number of variables fixed. 
 * Called when no solution was found during a LNS run 
 * (i.e., trapped into a local optimum).
 * if the fragment is based on a class instance (e.g, number of fixed variables)
 * it may be updated there
 */
void restrictLess()
// for instance, the threshold (0.9) previously declare in `fixSomeVariables()`
// can be reduced here
/** 
 * Indicates whether the neighbor is complete, that is, can end.
 * Most of the time, this is related to `restrictLess()`
 */
boolean isSearchComplete()

Recommendations and best practices

When to use each approach

Situation Recommended Reason
Quick prototyping BlackBoxConfigurator Automatic tuning, minimal code
CSP/COP problem BlackBoxConfigurator Handles both satisfaction and optimization
Custom domain knowledge Manual selectors Fine-grained control for expert optimization
Research/education Manual design Understanding how search works
Production system BlackBoxConfigurator Robustness across problem variations
LNS with custom operators Manual + IntNeighbor Domain-specific optimizations

Strategy selection workflow

  1. Start with BlackBoxConfigurator — it handles most problems well
  2. Profile and identify bottlenecks — use solver statistics
  3. If performance is insufficient, consider:
    • Customizing BlackBoxConfigurator settings
    • Adding meta-strategies (lastConflict, COS)
    • Implementing custom selectors
  4. For LNS, implement domain-specific neighbors

Performance tips

  • Use IntDomainSticky (phase saving) together with restarts
  • Combine strategies rather than replacing them
  • Apply lastConflict to adaptive/dynamic problems
  • Monitor solver statistics to detect inefficiencies
  • Test different configurations with your instances // for instance, if the threshold is 0. after a certain number of attempts.