Shouldn't the following result in a number different than zero?
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
m = pyo.ConcreteModel()
m.x = pyo.Var([1,2], domain=pyo.Reals,initialize=0)
m.obj = pyo.Objective(expr = 2*m.x[1] + 3*m.x[2],sense=pyo.minimize)
m.c1 = pyo.Constraint(expr = 3*m.x[1] + 4*m.x[2] >= 3)
SolverFactory('glpk', executable='/usr/bin/glpsol').solve(m)
pyo.value(m.x[1])
I have tried following the documentation but its quite limited for simple examples. When I execute this code it just prints zero...
The problem you have written is unbounded. Try changing the domain of x to NonNegativeReals or put in constraints to do same.
You should always check the solver status, which you seem to have skipped over and will state “unbounded” for this model.
Related
In Pyomo with "Ipopt" solver, I am trying to define a nonlinear objective function to be piecewise such that when the decision variables q_i < 1, it is a quadratic function; otherwise it is a log function. As suggested by the answer here, using the "Expr_If" expression should do the job. However, when I run the code (below), the solver indicates that it reaches an optimal solution and I can print the value of optimal decision variables by running:
for x in model.q: print(model.q[x].value)
but I can not print the optimal value of the objective function when I run:
model.total_cost() such that I get this error "math domain error". This error might suggest that a log function is being evaluated at a negative value, but based on the objective function that I defined this should not happen. Also, I can calculate the value of the objective function by rewriting it (after obtaining the optimal solution) directly using the values of optimal solution by running the code:
total_cost_ = 0
for i in model.P:
if model.q[i].value>=1:
total_cost_ += model.Beta[i] * log(model.q[i])
else:
total_cost_ += (-0.5)*model.Alpha[i] * (model.q[i]-1)**2
print(total_cost_())
Do you know why I am getting the "math domain error" when I run model.total_cost() ?
My code:
model = ConcreteModel()
#Define the set
model.P = Set(initialize=['P1','P2','P3','P4'])
#Parameters
model.Beta = Param(model.P, initialize = {'P1':1,'P2':1.2,'P3':1.4,'P4':1.6})
model.Alpha = Param(model.P, initialize = {'P1':0.1,'P2':0.2,'P3':0.3,'P4':0.4})
#Variables
model.q = Var(model.P)
#Objective
def Total_Cost(model):
return sum(Expr_if(IF=model.q[i]>=1, THEN=model.Beta[i] * log(model.q[i]),
ELSE=(-0.5)*model.Alpha[i] * (model.q[i]-1)**2) for i in model.P)
model.total_cost = Objective(expr = Total_Cost, sense = maximize)
#Constraints
def limit(model, i):
return -1.1<= model.q[i]
model.limit = Constraint(model.P, rule = limit)
def balance(model):
return summation(model.q) == 0
model.balance = Constraint(rule = balance)
solver = SolverFactory('ipopt')
solver.solve(model)
#model.pprint()
model.total_cost()
You'd get more luck posting this in the Operations Research SE.
I know that ROmodel works with pyomo.environ, but I haven’t been able to get it to work with pyomo.kernel. Admittedly, it says here that pyomo.kernel is not compatible with extension modules. Here’s my attempt at getting it to work with ROmodel:
import romodel as ro
import pyomo.kernel as pmo
import numpy as np
# Create Pyomo model using pyomo.environ
m = pmo.block()
m.x = pmo.variable(value = 1, lb = 0, ub = 4)
# Add some regular constraints (not uncertain)
m.c1 = pmo.constraint(m.x <= 0)
m.c2 = pmo.constraint(0 <= m.x)
# Create Objective function
m.o = pmo.objective(-m.x)
# # solve deterministic model
solver = pmo.SolverFactory('ipopt') # other options gurobi, ipopt, cplex, glpk
solver.solve(m)
print('decision variable values are')
print('objective value is ', m.o.expr())
# create Robust model
from romodel.uncset import PolyhedralSet
# # Define polyhedral set
m.uncset_d = PolyhedralSet(mat=[[1]], rhs=[100]) # can't add this to block object because no attribute "parent"
upper_bound = 500
m.uncset_b = PolyhedralSet(mat=[[1]], rhs=[upper_bound])
m.d = ro.UncParam([0], nominal=[0.1], uncset=m.uncset_d)
m.b = ro.UncParam([0], nominal=[1], uncset=m.uncset_b)
m.unc_const_d = pmo.constraint(expr = m.x[0] + m.d[0] <= 1)
m.unc_const_b = pmo.constraint(expr = m.x[0] + m.b[0] <= 1)
I was excited to find pyomo.kernel, because I’m writing a robust optimization problem, and it would be nice to take advantage of the vectorized constraints in pyomo.kernel. However, if pyomo.kernel isn’t compatible with ROmodel, then this won’t work.
Is there either:
A way to get pyomo.kernel to integrate with ROmodel?
OR
Another Robust Optimization framework that extends Pyomo which offers vectorized constraints? I saw PyROS and RSOME. But I couldn’t tell if those offer vectorized constraints.
I'm trying to solve a MILP problem using PYOMO and gurobi solvers but I'm not sure about the formulation of my code. Can I have an example (code) of how to solve a simple MILP problem please ?
Thank you in advance
You can find many of those online!
Here is one:
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
model = pyo.ConcreteModel()
# define variables
model.x = pyo.Var(within=Integers, bounds=(0,10))
model.y = pyo.Var(bounds=(0,10))
# define objective: maximize x + y
model.obj = pyo.Objective(expr= model.x+model.y, sense=maximize)
# define constraints
model.C1 = pyo.Constraint(expr= -model.x+2*model.y<=7)
model.C2 = pyo.Constraint(expr= 2*model.x+model.y<=14)
model.C3 = pyo.Constraint(expr= 2*model.x-model.y<=10)
# solve with gurobi
opt = SolverFactory('gurobi')
opt.solve(model)
And print the result:
print(pyo.value(model.obj))
Gives
>>> 9.5
Here you can find more examples, specifically for pyomo.
Good luck! :)
I have a linear programming problem with 8 variables.How I can generate a set of constraints (equalities and/or inequalities) with upper and lower bounds on Python in order to minimize an objective function?. I am specifically asking to do it with Pyomo solver if possible,if not using any other solver on Python (e.g., Gurobi, Cplex,etc) is fine, I just want to have an idea on how to tackle this problems on Python.
Very simple bus and zoo example:
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
opt = pyo.SolverFactory('cplex')
model = pyo.ConcreteModel()
model.nbBus = pyo.Var([40,30], domain=pyo.PositiveIntegers)
model.OBJ = pyo.Objective(expr = 500*model.nbBus[40] + 400*model.nbBus[30])
model.Constraint1 = pyo.Constraint(expr = 40*model.nbBus[40] + 30*model.nbBus[30] >= 300)
results = opt.solve(model)
print("nbBus40=",model.nbBus[40].value)
print("nbBus30=",model.nbBus[30].value)
I'm quite new to pyomo but I'm having a hard time figuring how to create a time dependant model and plot it on a graph. By time dependant I mean just a variable that assumes different values for each time step (like from 1 to T in this case).
I used this very simple model but when I run the script I receive in output only one solution. How can I change that?
I also have errors related to the constraint function but I'm not sure what's wrong
(ValueError: Constraint 'constraint[1]' does not have a proper value. Found . at 0x7f202b540850>' Expecting a tuple or equation.)
I'd like to show how the value of x(t) varies in all timesteps.
Any help is appreciated.
from __future__ import division
from pyomo.environ import *
from pyomo.opt import SolverFactory
import sys
model = AbstractModel()
model.n = Param()
model.T = RangeSet(1, model.n)
model.a = Param(model.T)
model.b = Param(model.T)
model.x = Var(model.T, domain= NonNegativeReals)
data = DataPortal()
data.load(filename='N.csv', range='N', param=model.n)
data.load(filename='A.csv', range= 'A', param=model.a)
data.load(filename='B.csv', range= 'B', param=model.b)
def objective(model):
return model.x
model.OBJ = Objective(rule=objective)
def somma(model):
return model.a[t]*model.x[t] for t in model.T) >= model.b[t] for t in model.T
model.constraint = Constraint(model.T, rule=somma)
instance = model.create_instance(data)
opt = SolverFactory('glpk')
results = opt.solve(instance)
You can build up lists of the values you would like to plot like this:
T_plot = list(instance.T)
x_plot = [value(instance.x[t]) for t in T_plot]
and then use your favorite Python plotting package to make the plots. I usually use Matplotlib.