Constraint programming

On this page 7

Constraint programming (CP) is a declarative problem-solving paradigm in which a problem is stated as a set of decision variables, the domains of values each variable may take, and the constraints that any acceptable combination of values must satisfy. A general-purpose constraint solver then searches for one solution, all solutions or an optimal solution. Within Symbolic AI & reasoning, constraint programming sits alongside logic programming, Boolean satisfiability and classical planning as a core technique for combinatorial search over symbolic models.

The defining idea is the separation of model and search: the modeler describes what a valid answer looks like, and the solver decides how to find it. This makes CP the method of choice for scheduling, timetabling, rostering, configuration and routing, where rules are numerous, heterogeneous and frequently changed.

How a constraint solver finds solutions

A constraint solver alternates between propagation and branching until every variable has a single value or a contradiction proves that no solution exists in the current branch. Propagation removes values from domains that cannot appear in any solution; branching makes a tentative decision and explores its consequences.

Each constraint is implemented by a propagator, a small filtering algorithm that inspects the current domains and deletes inconsistent values. When one domain shrinks, the solver wakes the propagators of every constraint that mentions that variable, and the process repeats until a fixed point is reached. This cascade is constraint propagation, and its strength determines how much of the search tree is never explored.

When propagation stalls, the solver picks a variable and a value according to a search heuristic, records the decision and propagates again. A failure triggers backtracking to the most recent choice point. Modern solvers add restarts, nogood learning and randomization so that early bad decisions do not trap the search.

The table below lists the main components of a typical solver and the role each one plays during the search.

ComponentRole in solvingTypical example
Variables and domainsRepresent the open decisionsStart time of a task in 0..480 minutes
PropagatorsFilter impossible valuesBounds reasoning for a linear sum
Global constraintsCapture common substructures efficientlyalldifferent, cumulative, element
Branching heuristicChoose the next decisionSmallest domain first
Search strategyOrder the exploration of choicesDepth-first with restarts
Objective handlingImprove solution qualityBranch and bound on cost
Core components of a constraint solver

Consistency levels and global constraints

The amount of filtering a propagator performs is described by its consistency level. Stronger consistency removes more values but costs more time per call, so solver designers balance pruning power against propagation cost for every constraint type.

The following table compares the most common consistency levels used in practice.

Consistency levelWhat it guaranteesRelative cost
Node consistencyEach value satisfies all unary constraintsVery low
Bounds consistencyDomain minimum and maximum have supportLow
Arc consistencyEvery value has support in each binary constraintModerate
Generalized arc consistencyEvery value has support in each n-ary constraintModerate to high
Path consistencyPairs of assignments extend to a third variableHigh
Common consistency levels

Global constraints are the practical strength of CP. A constraint such as alldifferent over twenty variables could be decomposed into 190 pairwise inequalities, but a dedicated propagator based on bipartite matching detects infeasibility that the decomposition misses. Likewise, cumulative reasons about resource capacity over time, and circuit enforces a single Hamiltonian tour in routing models. Catalogs of global constraints describe several hundred such patterns.

Constraint programming overlaps with several neighboring techniques, and the boundaries have blurred as solvers borrow ideas from each other. The table summarizes how CP differs from the most frequently compared approaches.

ApproachModel languageMain strengthMain weakness
Constraint programmingFinite-domain variables, rich constraintsComplex scheduling and side rulesWeak bounds for large optimization
Boolean satisfiabilityPropositional clausesClause learning on huge instancesArithmetic must be encoded
Satisfiability modulo theoriesLogic plus theories such as arithmeticVerification and symbolic reasoningLess tuned for scheduling objectives
Mixed-integer programmingLinear inequalities, integer variablesStrong relaxation boundsPoor fit for disjunctive rules
Answer set programmingLogic rules with stable modelsCompact knowledge-rich modelsGrounding can explode in size
Constraint programming and neighboring approaches

The most successful modern CP solvers are hybrids. Lazy clause generation combines propagation with SAT-style conflict learning, and many systems call a linear relaxation to obtain bounds. Constraint logic programming, the historical root of the field, embeds constraints directly in Prolog-style logic programs.

Modeling and applying constraint programming

Good results in CP depend more on the quality of the model than on solver settings. Experienced modelers choose a compact variable representation, express structure through global constraints, add redundant constraints that strengthen propagation, and introduce symmetry-breaking constraints so the solver does not explore equivalent solutions repeatedly.

Models are usually written in a solver-independent modeling language such as MiniZinc or through a library embedded in a general-purpose language. Well-known solvers include OR-Tools CP-SAT, Gecode, Chuffed and IBM ILOG CP Optimizer. The decision table below indicates when CP is a sensible first choice.

SituationRecommended choiceReason
Tight scheduling with precedence and resourcesConstraint programmingCumulative and disjunctive propagation
Large linear cost model with few side rulesMixed-integer programmingRelaxation gives strong bounds
Pure logical feasibility with millions of clausesBoolean satisfiabilityClause learning scales better
Frequently changing business rulesConstraint programmingConstraints are added without reformulation
Very large instances needing fast answersCP with local searchLarge neighborhood search improves quickly
When to choose constraint programming

Limitations and common mistakes

Constraint satisfaction over finite domains is NP-complete in general, so no solver guarantees fast answers on every instance. Performance can vary by orders of magnitude between two models of the same problem, and that sensitivity is the main practical risk.

  • Decomposing global constraints into many small ones weakens propagation and slows search.
  • Ignoring symmetry forces the solver to prove the same failure many times.
  • Using huge numeric domains without bounds reasoning makes propagation ineffective.
  • Relying on default heuristics for hard instances often leaves performance unrealized.
  • Expecting optimality proofs on large problems is unrealistic; a time limit and a good incumbent are usually the practical goal.

The short version

Constraint programming is a way to solve puzzles with many rules. You list the choices to make. You list the allowed options for each choice. Then you write down the rules every answer must follow. A program called a solver does the searching for you.

Think of a sudoku. Each empty cell is a choice, the digits one to nine are the options, and the rules say no digit may repeat in a row, column or box. Each time you fill a cell, other cells lose options. The solver works the same way, only much faster. You describe the goal, and the computer finds the answer.

Where it makes a difference

A regional hospital must build a four-week nurse roster for 60 nurses across three daily shifts. The rules include minimum staffing per shift, at least 11 hours of rest between shifts, no more than five consecutive working days, approved leave and individual preferences for weekends. Planners previously spent about three days building the roster by hand in a spreadsheet, and late changes often broke earlier rules.

The planning team writes a constraint programming model in which each variable is the shift assigned to one nurse on one day. Staffing levels become cardinality constraints, rest rules become sequence constraints, and preferences enter a weighted objective. A CP solver with large neighborhood search returns a fully compliant roster in under ten minutes, and when a nurse reports sick, the planners fix the remaining assignments and re-solve in seconds. The result is fewer rule violations and far less manual rework each month.