xpress.user
xpress.user |
Purpose
Creates an expression that is computed by means of a user-specified function. The user function can be defined to either provide or not provide the value of all derivatives w.r.t. the variables.
Synopsis
def f(a1, a2, ..., an):
[...]
a = xpress.user(f, t1, t2, ..., tn, derivatives=False)
Arguments
f
|
User function; must be a Python function with as many (possibly optional) arguments as specified in the declaration.
|
t1,...,tn
|
Arguments of the user function.
|
derivatives
|
True if
f returns the derivatives w.r.t. all variables,
False otherwise.
|
Example
The following code shows how to define user functions and use them in an optimization problem:
import math def mynorm(v): return math.sqrt(sum(v[i] for i in range(len(v))) def weighted_sum(t1, t2, t3=0): return (2*t1 + 3*t2 + 4*t1*t3, 2 + 4*t3, 3, 4*t1) x = [xp.var() for i in range(20)] f1 = xp.user(mynorm, x) f2 = xp.user(weighted_sum, x[0], x[1], x[2], derivative=True) # Doesn't use optional arg f3 = xp.user(weighted_sum, x[0], x[1], derivative=True) p = xp.problem() p.addVariable(x) p.addConstraint(f3 <= 4) p.setVariable(f1) p.solve()
Further information
User functions must return a Float, as the behaviour is otherwise undefined. If the derivatives parameter (which is False by default) is set to True, then the function must return a tuple consisting of the objective function value and the derivatives of the function w.r.t. all variables in the list of arguments. If derivatives=False, then the function must return a single float, i.e. the function value.