I have an optimization formulation where I have multiple decision variables, each decision variable has its own quadratic cost function term. I am planning to use a piecewise linear approximation to simplify the objective function through using the 'Piecewise' function in pyomo. I managed to that in a simple toy problem where I have a single decision variable, the issue arises when I am dealing with many decision variables. Having to write a new line for each decision variable with its own 'Piecewise' function is not viable, so I am trying to automate that with a for loop similar to the way you can do that with constraints.
Here's an example toy problem of what I'm trying to do:
import numpy as np
from pyomo.environ import *
from pyomo.core import *
from pyomo.opt import SolverFactory
def cost_function_0(x):
return x ** 2 + 3 * x + 4
def cost_function_1(x):
return x ** 2 + 6 * x - 2
xdata = np.linspace(-10, 10, 50)
ydata_0 = list(cost_function_0(xdata))
ydata_1 = list(cost_function_1(xdata))
xdata = list(xdata)
model = ConcreteModel()
model.N = range(2)
model.X = Var(model.N, bounds=(-10, 10))
model.Y = Var(model.N)
model.piecewise_0 = Piecewise(model.Y[0],model.X[0],
pw_pts=xdata,
pw_constr_type='EQ',
f_rule=ydata_0,
pw_repn='CC')
model.piecewise_1 = Piecewise(model.Y[1],model.X[1],
pw_pts=xdata,
pw_constr_type='EQ',
f_rule=ydata_1,
pw_repn='CC')
model.obj = Objective(expr=model.Y[0] + model.Y[1], sense=minimize)
opt = SolverFactory('glpk')
obj_val = opt.solve(model)
print('Decision variables: ', model.X[0].value, model.X[1].value)
print('Objective value: ', model.Y[0].value + model.Y[1].value)
So I am trying to replace the process of manually creating the Piecewise objects (model.piecewise_0, model.piecewise_1, ....) with an automated for loop but I got no luck so far.
Thanks in advance!