Link Search Menu Expand Document
PyCSP3
Models & Data GitHub XCSP3 About

Specifying Objectives

Below, we show how to specify an objective when dealing with a COP (Constraint Optimization Problem) instance.

Remark. In PyCSP$^3$, which is currently targeted to XCSP$^3$-core, we currently only consider mono-objective optimization. Multi-objective optimization will be addressed in the future.

To see how it works, we need first to import the library PyCSP$^3$:

from pycsp3 import *

For specifying an objective to optimize, you must call one of the two functions:

  • minimize()
  • maximize()

We can pass a parameter to either functions, which can be:

  • a variable, as in:
    minimize(v)
    
  • an expression, as in:
    minimize(v + w * w)
    
  • a sum, as in:
    minimize(Sum(x))
    
  • a dot product, as in:
    minimize([u,v,w] * [3, 2, 5])
    
  • a generator, as in:
    minimize(Sum((x[i] > 1) * c[i] for i in range(n))) 
    
  • a minimum, as in:
    minimize(Minimum(x))
    
  • a maximum, as in:
    minimize(Maximum(x))
    
  • a number of distinct values, as in:
    minimize(NValues(x))
    
For our illustration, let us declare an array x of 6 variables.
x = VarArray(size=6, dom=range(10))

We can decide to minimize the sum of values assigned to the variables of x. We just write:

minimize(
    Sum(x)
);

To control things, we can display the internal representation of the objective as follows:

print(objective())
minimize(sum(list:[x[0], x[1], x[2], x[3], x[4], x[5]]))

If ever we decide to maximize the number of distinct values assigned to the variables of x, because any new call to minimize() or maximize() overwrites the previous objective (if one was posted), we can write:

maximize(
    NValues(x)
);

We can control that we have a new objective.

print(objective())
maximize(nValues(list:[x[0], x[1], x[2], x[3], x[4], x[5]]))