Class CpModel

java.lang.Object
com.google.ortools.sat.CpModel

public final class CpModel extends Object
Main modeling class.

Proposes a factory to create all modeling objects understood by the SAT solver.

  • Constructor Details

    • CpModel

      public CpModel()
  • Method Details

    • getClone

      public CpModel getClone()
    • newIntVar

      public IntVar newIntVar(long lb, long ub, String name)
      Creates an integer variable with domain [lb, ub].
    • newIntVarFromDomain

      public IntVar newIntVarFromDomain(Domain domain, String name)
      Creates an integer variable with given domain.
      Parameters:
      domain - an instance of the Domain class.
      name - the name of the variable
      Returns:
      a variable with the given domain.
    • newBoolVar

      public BoolVar newBoolVar(String name)
      Creates a Boolean variable with the given name.
    • newConstant

      public IntVar newConstant(long value)
      Creates a constant variable.
    • trueLiteral

      public Literal trueLiteral()
      Returns the true literal.
    • falseLiteral

      public Literal falseLiteral()
      Returns the false literal.
    • getBoolVarFromProtoIndex

      public BoolVar getBoolVarFromProtoIndex(int index)
      Rebuilds a Boolean variable from an index. Useful after cloning a model.
    • getIntVarFromProtoIndex

      public IntVar getIntVarFromProtoIndex(int index)
      Rebuilds an integer variable from an index. Useful after cloning a model.
    • addBoolOr

      public Constraint addBoolOr(Literal[] literals)
      Adds Or(literals) == true.
    • addBoolOr

      public Constraint addBoolOr(Iterable<Literal> literals)
      Adds Or(literals) == true.
    • addAtLeastOne

      public Constraint addAtLeastOne(Literal[] literals)
      Same as addBoolOr. Sum(literals) >= 1.
    • addAtLeastOne

      public Constraint addAtLeastOne(Iterable<Literal> literals)
      Same as addBoolOr. Sum(literals) >= 1.
    • addAtMostOne

      public Constraint addAtMostOne(Literal[] literals)
      Adds AtMostOne(literals): Sum(literals) <= 1.
    • addAtMostOne

      public Constraint addAtMostOne(Iterable<Literal> literals)
      Adds AtMostOne(literals): Sum(literals) <= 1.
    • addExactlyOne

      public Constraint addExactlyOne(Literal[] literals)
      Adds ExactlyOne(literals): Sum(literals) == 1.
    • addExactlyOne

      public Constraint addExactlyOne(Iterable<Literal> literals)
      Adds ExactlyOne(literals): Sum(literals) == 1.
    • addBoolAnd

      public Constraint addBoolAnd(Literal[] literals)
      Adds And(literals) == true.
    • addBoolAnd

      public Constraint addBoolAnd(Iterable<Literal> literals)
      Adds And(literals) == true.
    • addBoolXor

      public Constraint addBoolXor(Literal[] literals)
      Adds XOr(literals) == true.
    • addBoolXor

      public Constraint addBoolXor(Iterable<Literal> literals)
      Adds XOr(literals) == true.
    • addImplication

      public Constraint addImplication(Literal a, Literal b)
      Adds a => b.
    • addLinearExpressionInDomain

      public Constraint addLinearExpressionInDomain(LinearArgument expr, Domain domain)
      Adds expr in domain.
    • addLinearConstraint

      public Constraint addLinearConstraint(LinearArgument expr, long lb, long ub)
      Adds lb <= expr <= ub.
    • addEquality

      public Constraint addEquality(LinearArgument expr, long value)
      Adds expr == value.
    • addEquality

      public Constraint addEquality(LinearArgument left, LinearArgument right)
      Adds left == right.
    • addLessOrEqual

      public Constraint addLessOrEqual(LinearArgument expr, long value)
      Adds expr <= value.
    • addLessOrEqual

      public Constraint addLessOrEqual(LinearArgument left, LinearArgument right)
      Adds left <= right.
    • addLessThan

      public Constraint addLessThan(LinearArgument expr, long value)
      Adds expr < value.
    • addLessThan

      public Constraint addLessThan(LinearArgument left, LinearArgument right)
      Adds left < right.
    • addGreaterOrEqual

      public Constraint addGreaterOrEqual(LinearArgument expr, long value)
      Adds expr >= value.
    • addGreaterOrEqual

      public Constraint addGreaterOrEqual(LinearArgument left, LinearArgument right)
      Adds left >= right.
    • addGreaterThan

      public Constraint addGreaterThan(LinearArgument expr, long value)
      Adds expr > value.
    • addGreaterThan

      public Constraint addGreaterThan(LinearArgument left, LinearArgument right)
      Adds left > right.
    • addDifferent

      public Constraint addDifferent(LinearArgument expr, long value)
      Adds expr != value.
    • addDifferent

      public Constraint addDifferent(LinearArgument left, LinearArgument right)
      Adds left != right.
    • addAllDifferent

      public Constraint addAllDifferent(LinearArgument[] expressions)
      Adds AllDifferent(expressions).

      This constraint forces all affine expressions to have different values.

      Parameters:
      expressions - a list of affine integer expressions
      Returns:
      an instance of the Constraint class
    • addAllDifferent

      public Constraint addAllDifferent(Iterable<? extends LinearArgument> expressions)
      Adds AllDifferent(expressions).
    • addElement

      public Constraint addElement(IntVar index, IntVar[] variables, IntVar target)
      Adds the element constraint: variables[index] == target.
    • addElement

      public Constraint addElement(IntVar index, long[] values, IntVar target)
      Adds the element constraint: values[index] == target.
    • addElement

      public Constraint addElement(IntVar index, int[] values, IntVar target)
      Adds the element constraint: values[index] == target.
    • addCircuit

      public CircuitConstraint addCircuit()
      Adds Circuit().

      Adds an empty circuit constraint.

      A circuit is a unique Hamiltonian path in a subgraph of the total graph. In case a node 'i' is not in the path, then there must be a loop arc 'i -> i' associated with a true literal. Otherwise this constraint will fail.

    • addMultipleCircuit

      public MultipleCircuitConstraint addMultipleCircuit()
      Adds MultipleCircuit().

      Adds an empty multiple circuit constraint.

      A multiple circuit is set of cycles in a subgraph of the total graph. The node index by 0 must be part of all cycles of length > 1. Each node with index > 0 belongs to exactly one cycle. If such node does not belong in any cycle of length > 1, then there must be a looping arc on this node attached to a literal that will be true. Otherwise, the constraint will fail.

    • addAllowedAssignments

      public TableConstraint addAllowedAssignments(IntVar[] variables)
      Adds AllowedAssignments(variables).

      An AllowedAssignments constraint is a constraint on an array of variables that forces, when all variables are fixed to a single value, that the corresponding list of values is equal to one of the tuples of the tupleList.

      Parameters:
      variables - a list of variables
      Returns:
      an instance of the TableConstraint class without any tuples. Tuples can be added directly to the table constraint.
    • addAllowedAssignments

      public TableConstraint addAllowedAssignments(Iterable<IntVar> variables)
      Adds AllowedAssignments(variables).
      See Also:
    • addForbiddenAssignments

      public TableConstraint addForbiddenAssignments(IntVar[] variables)
      Adds ForbiddenAssignments(variables).

      A ForbiddenAssignments constraint is a constraint on an array of variables where the list of impossible combinations is provided in the tuples list.

      Parameters:
      variables - a list of variables
      Returns:
      an instance of the TableConstraint class without any tuples. Tuples can be added directly to the table constraint.
    • addForbiddenAssignments

      public TableConstraint addForbiddenAssignments(Iterable<IntVar> variables)
      Adds ForbiddenAssignments(variables).
      See Also:
    • addAutomaton

      public AutomatonConstraint addAutomaton(IntVar[] transitionVariables, long startingState, long[] finalStates)
      Adds an automaton constraint.

      An automaton constraint takes a list of variables (of size n), an initial state, a set of final states, and a set of transitions that will be added incrementally directly on the returned AutomatonConstraint instance. A transition is a triplet ('tail', 'transition', 'head'), where 'tail' and 'head' are states, and 'transition' is the label of an arc from 'head' to 'tail', corresponding to the value of one variable in the list of variables.

      This automaton will be unrolled into a flow with n + 1 phases. Each phase contains the possible states of the automaton. The first state contains the initial state. The last phase contains the final states.

      Between two consecutive phases i and i + 1, the automaton creates a set of arcs. For each transition (tail, label, head), it will add an arc from the state 'tail' of phase i and the state 'head' of phase i + 1. This arc labeled by the value 'label' of the variables 'variables[i]'. That is, this arc can only be selected if 'variables[i]' is assigned the value 'label'.

      A feasible solution of this constraint is an assignment of variables such that, starting from the initial state in phase 0, there is a path labeled by the values of the variables that ends in one of the final states in the final phase.

      Parameters:
      transitionVariables - a non empty list of variables whose values correspond to the labels of the arcs traversed by the automaton
      startingState - the initial state of the automaton
      finalStates - a non empty list of admissible final states
      Returns:
      an instance of the Constraint class
    • addInverse

      public Constraint addInverse(IntVar[] variables, IntVar[] inverseVariables)
      Adds Inverse(variables, inverseVariables).

      An inverse constraint enforces that if 'variables[i]' is assigned a value 'j', then inverseVariables[j] is assigned a value 'i'. And vice versa.

      Parameters:
      variables - an array of integer variables
      inverseVariables - an array of integer variables
      Returns:
      an instance of the Constraint class
      Throws:
      CpModel.MismatchedArrayLengths - if variables and inverseVariables have different length
    • addReservoirConstraint

      public ReservoirConstraint addReservoirConstraint(long minLevel, long maxLevel)
      Adds a reservoir constraint with optional refill/emptying events.

      Maintain a reservoir level within bounds. The water level starts at 0, and at any time, it must be within [min_level, max_level].

      Given an event (time, levelChange, active), if active is true, and if time is assigned a value t, then the level of the reservoir changes by levelChange (which is constant) at time t. Therefore, at any time t:

      sum(levelChanges[i] * actives[i] if times[i] <= t) in [min_level, max_level]

      Note that min level must be <= 0, and the max level must be >= 0. Please use fixed level_changes to simulate an initial state.

      Parameters:
      minLevel - at any time, the level of the reservoir must be greater of equal than the min level. minLevel must me <= 0.
      maxLevel - at any time, the level of the reservoir must be less or equal than the max level. maxLevel must be >= 0.
      Returns:
      an instance of the ReservoirConstraint class
      Throws:
      IllegalArgumentException - if minLevel > 0
      IllegalArgumentException - if maxLevel < 0
    • addMapDomain

      public void addMapDomain(IntVar var, Literal[] booleans, long offset)
      Adds var == i + offset <=> booleans[i] == true for all i in [0, booleans.length).
    • addMinEquality

      public Constraint addMinEquality(LinearArgument target, LinearArgument[] exprs)
      Adds target == Min(vars).
    • addMinEquality

      public Constraint addMinEquality(LinearArgument target, Iterable<? extends LinearArgument> exprs)
      Adds target == Min(exprs).
    • addMaxEquality

      public Constraint addMaxEquality(LinearArgument target, LinearArgument[] exprs)
      Adds target == Max(vars).
    • addMaxEquality

      public Constraint addMaxEquality(LinearArgument target, Iterable<? extends LinearArgument> exprs)
      Adds target == Max(exprs).
    • addDivisionEquality

      public Constraint addDivisionEquality(LinearArgument target, LinearArgument num, LinearArgument denom)
      Adds target == num / denom, rounded towards 0.
    • addAbsEquality

      public Constraint addAbsEquality(LinearArgument target, LinearArgument expr)
      Adds target == Abs(expr).
    • addModuloEquality

      public Constraint addModuloEquality(LinearArgument target, LinearArgument var, LinearArgument mod)
      Adds target == var % mod.
    • addModuloEquality

      public Constraint addModuloEquality(LinearArgument target, LinearArgument var, long mod)
      Adds target == var % mod.
    • addMultiplicationEquality

      public Constraint addMultiplicationEquality(LinearArgument target, LinearArgument[] exprs)
      Adds target == Product(exprs).
    • addMultiplicationEquality

      public Constraint addMultiplicationEquality(LinearArgument target, LinearArgument left, LinearArgument right)
      Adds target == left * right.
    • newIntervalVar

      public IntervalVar newIntervalVar(LinearArgument start, LinearArgument size, LinearArgument end, String name)
      Creates an interval variable from three affine expressions start, size, and end.

      An interval variable is a constraint, that is itself used in other constraints like NoOverlap.

      Internally, it ensures that start + size == end.

      Parameters:
      start - the start of the interval. It needs to be an affine or constant expression.
      size - the size of the interval. It needs to be an affine or constant expression.
      end - the end of the interval. It needs to be an affine or constant expression.
      name - the name of the interval variable
      Returns:
      An IntervalVar object
    • newFixedSizeIntervalVar

      public IntervalVar newFixedSizeIntervalVar(LinearArgument start, long size, String name)
      Creates an interval variable from an affine expression start, and a fixed size.

      An interval variable is a constraint, that is itself used in other constraints like NoOverlap.

      Parameters:
      start - the start of the interval. It needs to be an affine or constant expression.
      size - the fixed size of the interval.
      name - the name of the interval variable.
      Returns:
      An IntervalVar object
    • newFixedInterval

      public IntervalVar newFixedInterval(long start, long size, String name)
      Creates a fixed interval from its start and its size.
    • newOptionalIntervalVar

      public IntervalVar newOptionalIntervalVar(LinearArgument start, LinearArgument size, LinearArgument end, Literal isPresent, String name)
      Creates an optional interval variable from three affine expressions start, size, end, and isPresent.

      An optional interval variable is a constraint, that is itself used in other constraints like NoOverlap. This constraint is protected by an isPresent literal that indicates if it is active or not.

      Internally, it ensures that isPresent => start + size == end.

      Parameters:
      start - the start of the interval. It needs to be an affine or constant expression.
      size - the size of the interval. It needs to be an affine or constant expression.
      end - the end of the interval. It needs to be an affine or constant expression.
      isPresent - a literal that indicates if the interval is active or not. A inactive interval is simply ignored by all constraints.
      name - The name of the interval variable
      Returns:
      an IntervalVar object
    • newOptionalFixedSizeIntervalVar

      public IntervalVar newOptionalFixedSizeIntervalVar(LinearArgument start, long size, Literal isPresent, String name)
      Creates an optional interval variable from an affine expression start, and a fixed size.

      An interval variable is a constraint, that is itself used in other constraints like NoOverlap.

      Parameters:
      start - the start of the interval. It needs to be an affine or constant expression.
      size - the fixed size of the interval.
      isPresent - a literal that indicates if the interval is active or not. A inactive interval is simply ignored by all constraints.
      name - the name of the interval variable.
      Returns:
      An IntervalVar object
    • newOptionalFixedInterval

      public IntervalVar newOptionalFixedInterval(long start, long size, Literal isPresent, String name)
      Creates an optional fixed interval from start and size, and an isPresent literal.
    • addNoOverlap

      public Constraint addNoOverlap(IntervalVar[] intervalVars)
      Adds NoOverlap(intervalVars).

      A NoOverlap constraint ensures that all present intervals do not overlap in time.

      Parameters:
      intervalVars - the list of interval variables to constrain
      Returns:
      an instance of the Constraint class
    • addNoOverlap

      public Constraint addNoOverlap(Iterable<IntervalVar> intervalVars)
      Adds NoOverlap(intervalVars).
    • addNoOverlap2D

      public NoOverlap2dConstraint addNoOverlap2D()
      Adds NoOverlap2D(xIntervals, yIntervals).

      A NoOverlap2D constraint ensures that all present rectangles do not overlap on a plan. Each rectangle is aligned with the X and Y axis, and is defined by two intervals which represent its projection onto the X and Y axis.

      Furthermore, one box is optional if at least one of the x or y interval is optional.

      Returns:
      an instance of the NoOverlap2dConstraint class. This class allows adding rectangles incrementally.
    • addCumulative

      public CumulativeConstraint addCumulative(LinearArgument capacity)
      Adds Cumulative(capacity).

      This constraint enforces that:

      forall t: sum(demands[i] if (start(intervals[t]) <= t < end(intervals[t])) and (t is present)) <= capacity.

      Parameters:
      capacity - the maximum capacity of the cumulative constraint. It must be a positive affine expression.
      Returns:
      an instance of the CumulativeConstraint class. this class allows adding (interval, demand) pairs incrementally.
    • addCumulative

      public CumulativeConstraint addCumulative(long capacity)
      Adds Cumulative(capacity).
      See Also:
    • addHint

      public void addHint(IntVar var, long value)
      Adds hinting to a variable
    • clearHints

      public void clearHints()
      Remove all solution hints
    • addAssumption

      public void addAssumption(Literal lit)
      Adds a literal to the model as assumption
    • addAssumptions

      public void addAssumptions(Literal[] literals)
      Adds multiple literals to the model as assumptions
    • clearAssumptions

      public void clearAssumptions()
      Remove all assumptions from the model
    • minimize

      public void minimize(LinearArgument expr)
      Adds a minimization objective of a linear expression.
    • minimize

      public void minimize(DoubleLinearExpr expr)
      Adds a minimization objective of a linear expression.
    • maximize

      public void maximize(LinearArgument expr)
      Adds a maximization objective of a linear expression.
    • maximize

      public void maximize(DoubleLinearExpr expr)
      Adds a maximization objective of a linear expression.
    • clearObjective

      public void clearObjective()
      Clears the objective.
    • hasObjective

      public boolean hasObjective()
      Checks if the model contains an objective.
    • addDecisionStrategy

      Adds DecisionStrategy(expressions, varStr, domStr).
    • addDecisionStrategy

      public void addDecisionStrategy(Iterable<? extends LinearArgument> expressions, DecisionStrategyProto.VariableSelectionStrategy varStr, DecisionStrategyProto.DomainReductionStrategy domStr)
      Adds DecisionStrategy(expressions, varStr, domStr).
    • modelStats

      public String modelStats()
      Returns some statistics on model as a string.
    • validate

      public String validate()
      Returns a non empty string explaining the issue if the model is invalid.
    • exportToFile

      public Boolean exportToFile(String file)
      Write the model as a protocol buffer to 'file'.
      Parameters:
      file - file to write the model to. If the filename ends with 'txt', the model will be written as a text file, otherwise, the binary format will be used.
      Returns:
      true if the model was correctly written.
    • model

      public CpModelProto model()
    • negated

      public int negated(int index)
    • getBuilder

      public CpModelProto.Builder getBuilder()
      Returns the model builder.