friendlysam.opt.piecewise_affine

friendlysam.opt.piecewise_affine(points, name=None)

Create a piecewise affine expression and constraints.

There are several ways to express piecewise affine functions in MILP problems. This function helps with one of them, using SOS2 variables.

Definition:

f(x) is the linear interpolation of a data set (x_0, y_0), (x_1, y_1), \ldots, (x_n, y_n).

The x_i are ordered: x_0 \leq x_1 \leq \ldots \leq x_n.

See http://en.wikipedia.org/wiki/Linear_interpolation

Parameters:
  • points (dict or sequence of pairs) –

    The x_i, y_i pairs.

    Alternative 1: Provide a dict, e.g. {x0: y0, x1: y1, ..., x_n: y_n}.

    Alternative 2: Provide a sequence of pairs, e.g. [(x0, y0), (x1, y1), ..., (xn, yn)]

    The points are automatically sorted in increasing x_i.

  • name (str, optional) – A name base for the variables.
Returns:

(x, y, constraints)

x is an expression for the argument of the function.

y is an expression for the function value.

constraints is a set of SOS2 and Constraint instances that must be added to an optimization problem to enforce the relation between x and y.

Examples

>>> points = {1: 30, 1.5: 20, 2: 40}
>>> x, y, constraints = fs.piecewise_affine(points, name='pwa_vars')
>>> prob = fs.Problem()
>>> prob.objective = fs.Minimize(y)
>>> prob.add(constraints)
>>> solution = get_solver().solve(prob)
>>> for var in x.variables:
...     var.take_value(solution)
...
>>> float(x) == 1.5
True
>>> float(y) == 20
True