Passing variables to a function for evaluation then returning the result for optimization
AnsweredI am trying to figure out a way to pass variables to a function for evaluation during optimization and then return allow the function to return the result for optimization.
For example, let $x_{i}$ be a continuous variable where i = 0,1,2,...,N and let $b_{i}$ be a binary variable.
out of the set of xi, a random number of elements will be chosen. Let $A$ be an 1D array with a shape of (1,N) of binary values that determine which x elements were chosen and a list can be created based on the values in A
observations = ['x2', 'x4', 'x5', 'x8']
this list of observation will then be used to declare variables:
x2 = m.addVar(lb=0, ub=18, vtype=GRB.CONTINUOUS, name="x2")
x4 = m.addVar(lb=12, ub=20, vtype=GRB.CONTINUOUS, name="x4")
x5 = m.addVar(lb=0, ub=5, vtype=GRB.CONTINUOUS, name="x5")
x8 = m.addVar(lb=4, ub=7, vtype=GRB.CONTINUOUS, name="x8")
a variable will also be declared for the result after the function is evaluated and a scaler value is returned
z = m.addVar(vtype=GRB.CONTINUOUS, name="z")
the x values will then be places in an array and passed to a function for evaluation:
inputArray = np.zeros((1,N))
inputArray[:,2] = m.getVarByName("x2")
inputArray[:,4] = m.getVarByName("x4")
inputArray[:,5] = m.getVarByName("x5")
inputArray[:,8] = m.getVarByName("x8")
def fun(inputArray):
return val
z = fun(inputArray)
Then we need to see which variables are needed to satisfy the constraint:
b2 = m.addVar(vtype=GRB.BINARY, name="b2")
b4 = m.addVar(vtype=GRB.BINARY, name="b4")
b5 = m.addVar(vtype=GRB.BINARY, name="b5")
b8 = m.addVar(vtype=GRB.BINARY, name="b8")
Next we add a budget constraint:

Hi Marcus,
You can pass optimization variables as arguments to other functions. However, note that you cannot access their values before an optimization run has been performed. It is because the Var object does not have any value. The parameter fields of a Var object get filled after/during an optimization run and can be accessed via its attributes.
A simple function to construct some objective function would be:
import gurobipy as gp
from gurobipy import GRB
def myfunc(x,I):
lexpr = gp.quicksum((i+1) * x[i] for i in range(I))
return lexpr
m = gp.Model("test")
x = m.addVars(5)
m.setObjective(myfunc(x,5))In the above function \(\texttt{myfunc}\) computes the LinExpr object \(1 x_0 + 2 x_1 + 3 x_2 + 4 x_3 + 5 x_4\).
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
1 comment