Table of Contents

Class Constraint

Namespace
OptalCP
Assembly
OptalCP.dll

A restriction on variable values, created by comparison operators or constraint-posting methods.

public class Constraint : ModelElement
Inheritance
Constraint
Inherited Members

Remarks

A constraint is a condition that must be satisfied by a valid solution. Constraints are created by calling constraint-creating methods on the model or on expressions.

Important: Constraints are automatically registered with the model when created. There is no need to explicitly add them using Model.enforce() or similar methods.

Note that comparison operators on integer expressions (like x <= 10) return BoolExpr, not Constraint. Boolean expressions must be explicitly enforced using Model.Enforce or BoolExpr.Enforce.

Unlike BoolExpr, constraints cannot be combined using logical operators like Model.And/Model.Or or &/|.

Common ways to create constraints:

var model = new Model();

// Scheduling constraint - automatically registered
var tasks = Enumerable.Range(0, 3).Select(i =>
  model.IntervalVar(length: 5, name: $"t_{i}")
).ToArray();
model.NoOverlap(tasks);

// Precedence constraint - automatically registered
var task1 = model.IntervalVar(length: 10, name: "task1");
var task2 = model.IntervalVar(length: 10, name: "task2");
task1.EndBeforeStart(task2);

// Cumulative constraint - use model.Enforce() for clarity
var resource = model.Sum(tasks.Select(t => model.Pulse(t, 1)));
model.Enforce(resource <= 2);

See also:

  • Model.Enforce — for enforcing boolean expressions as constraints.
  • BoolExpr — for boolean expressions that can also be enforced as constraints.