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! :)
Related
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.
import pulp as p
import numpy as np
a1=np.array([1000,2000,3000,7000,8000,13000,223000,32000,35000,369000,38000,3885000])
x=p.LpVariable('x', lowBound=5000, cat='Continuous')
y=p.LpVariable('y', lowBound=8000,cat='Continuous')
Lp_prob=(((y-x)*1.3+x)*0.014428)+((a1-y)*1.5*0.014428)
Lp_prob.solve()
I try to do linear programming in pulp. But I have 'LpAffineExpression' object has no attribute 'solve' error.
How can I fix it? Thanks.
I would suggest to first study this example: https://www.coin-or.org/PuLP/CaseStudies/a_blending_problem.html. It has all the ingredients to cover your example.
So a working model can look like:
import pulp as p
import numpy as np
a1=np.array([1000,2000,3000,7000,8000,13000,223000,32000,35000,369000,38000,3885000])
x=p.LpVariable('x', lowBound=5000, cat='Continuous')
y=p.LpVariable('y', lowBound=8000,cat='Continuous')
Lp_prob = p.LpProblem("This_Example_Works",p.LpMaximize)
Lp_prob += (((y-x)*1.3+x)*0.014428)+((a1-y)*1.5*0.014428)
Lp_prob.solve()
print("Status:", p.LpStatus[Lp_prob.status])
Note that PuLP interprets this as:
MAXIMIZE
-0.0043284000000000005*x + -0.24094759999999996*y + 99899.472
VARIABLES
5000 <= x Continuous
8000 <= y Continuous
The very strange construct a1-y is interpreted here as sum(a1-y)=sum(a1)-n*y where n=a1.size. I would suggest not to use NumPy arrays this way in a PuLP model.
I'm a beginner at python and I try to use cvxpy library for my optimization project. I try to change the first value of my n dimensional variable But I get an AttributeError
import cvxpy as cp
S = cp.Variable(100)
S[0].value=320000
output:AttributeError: can't set attribute
It works for 1-dim variable
import cvxpy as cp
S = cp.Variable()
S.value=320000
Thanks in advance
The 'Variable' object does not support item assignment. You may enforce your requirement as a constraint:
import cvxpy as cp
S = cp.Variable(100) # Define your variables
objective = ... # Define your objective function
constraints = [] # Create an array of constraints
constraints.append(S[0]==320000) # Make your requirement a constraint
# Add more constraints
prob = Problem(objective, constraints) # Define your optimization problem
prob.solve(verbose=True) # Solve the problem
print(S.value)
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.