I have a problem with the optimization code. The code I have written should optimize the two objectives considering their expressions and produce value that can be plotted. This is my code as mentioned below.
from pyomo.environ import *
import numpy as np
import pandas as pd
import random
import matplotlib.pyplot as plt
model = ConcreteModel()
st1 = []
st2 = []
rows =10
n = []
for i in range(rows):
rn = random.randint(1,10)
n.append(rn)
print(rn)
model.x1 = Var(within=NonNegativeReals, initialize=rn)
model.x2 = Var(within=NonNegativeReals, initialize=rn)
model.x3 = Var(within=NonNegativeReals, initialize=rn)
model.x4 = Var(within=NonNegativeReals, initialize=rn)
model.f1 = Var()
model.f2 = Var()
model.C_f1 = Constraint(expr= model.f1 == 2 * model.x1 - model.x2 + 4 * model.x3 + model.x4)
model.C_f2 = Constraint(expr= model.f2 == -3 * model.x1 + model.x2 + 2 * model.x3 - 2 * model.x4)
model.O_f1 = Objective(expr= model.f1, sense=maximize)
model.O_f2 = Objective(expr= model.f2, sense=maximize)
model.O_f1.activate()
model.O_f2.deactivate()
solver = SolverFactory('glpk')
solver.solve(model);
print('( x1 , x2 , x3 , x4 ) = ( ' + str(value(model.x1)) + ' , ' + str(value(model.x2)) + ' , ' + str(value(model.x3)) + ' , ' + str(value(model.x4)) + ' )')
st1.append(value(model.f1))
st2.append(value(model.f2))
model.O_f2.activate()
model.O_f1.deactivate()
solver = SolverFactory('glpk')
solver.solve(model);
print('( x1 , x2 , x3 , x4 ) = ( ' + str(value(model.x1)) + ' , ' + str(value(model.x2)) + ' , ' + str(value(model.x3)) + ' , ' + str(value(model.x4)) + ' )')
st1.append(value(model.f1))
st2.append(value(model.f2))
print(n)
print(st1)
print(st2)
plt.scatter(st1, st2)
plt.xlabel('Objective A')
plt.ylabel('Objective B')
plt.show()
This is the error that comes up,
7
( x1 , x2 , x3 , x4 ) = ( 7 , 7 , 7 , 7 )
ERROR: evaluating object as numeric value: f1
(object: <class 'pyomo.core.base.var.ScalarVar'>)
No value for uninitialized NumericValue object f1
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-c6162a718dc9> in <module>
34
35 print('( x1 , x2 , x3 , x4 ) = ( ' + str(value(model.x1)) + ' , ' +
str(value(model.x2)) + ' , ' + str(value(model.x3)) + ' , ' + str(value(model.x4)) + ' )')
---> 36 st1.append(value(model.f1))
37 st2.append(value(model.f2))
38
pyomo\core\expr\numvalue.pyx in pyomo.core.expr.numvalue.value()
pyomo\core\expr\numvalue.pyx in pyomo.core.expr.numvalue.value()
ValueError: No value for uninitialized NumericValue object f1
Can anyone please help me out with this by showing me the error or helping me with an alternative
The problem is that your model is unbounded. You are trying to maximize it and there is no upper constraint, so the values could be infinite.
You should always check the solver status first after solve to see what you got before digging in. Add this: