Setting Up Your First CP-SAT Model in OR-Tools

Learn to build a complete CP-SAT model in Python with OR-Tools: declaring integer and Boolean variables, adding linear constraints, setting an objective, invoking the solver, and reading back the optimal values.

Step 1 of 157%

Tutorial

The CpModel Object and Decision Variables

A CP-SAT model is a Python object that holds decision variables, constraints, and (optionally) an objective function. We build one by importing the library and instantiating a CpModel\texttt{CpModel}:

from ortools.sat.python import cp_modelmodel = cp_model.CpModel()\begin{aligned}&\texttt{from ortools.sat.python import cp\_model} \\ &\texttt{model = cp\_model.CpModel()}\end{aligned}

To add an integer decision variable, call NewIntVar(lb, ub, name)\texttt{NewIntVar(lb, ub, name)}, where lb\texttt{lb} and ub\texttt{ub} are the inclusive integer lower and upper bounds, and name\texttt{name} is a string used in solver output:

x = model.NewIntVar(0, 10, ’x’)\texttt{x = model.NewIntVar(0, 10, 'x')}

This declares a variable xx with domain {0,1,2,,10}.\{0, 1, 2, \ldots, 10\}. For Boolean variables (domain {0,1}\{0, 1\}), use NewBoolVar(name)\texttt{NewBoolVar(name)} instead:

b = model.NewBoolVar(’b’)\texttt{b = model.NewBoolVar('b')}

Every variable must be created by the same CpModel\texttt{CpModel} instance that will later hold constraints referring to it. The argument order is always (lb,ub,name)(\texttt{lb}, \texttt{ub}, \texttt{name}) — bounds first, name last.

navigate · Enter open · Esc close · ⌘K/Ctrl K toggle