I have a simple model:
import pyomo.environ as pyo
import numpy as np
import csv
Nmax = 10
def up_constraint(model,n,t):
s = model.a[t] + model.b
return sum(model.imp[n,t]-model.exp[n,t] for n in model.N) <= s
def build_model(N,T,Tup):
model = pyo.ConcreteModel()
# Define the parameters
model.N = pyo.Set(initialize=N)
model.T = pyo.Set(initialize=T)
model.Tup = pyo.Set(initialize=Tup)
# Parameters
model.a = np.ones(Nmax) * 1.5
model.b = 10
# Decision variables
model.imp = pyo.Var(model.N,model.T)
model.up = pyo.Constraint(model.N,model.Tup,rule= up_constraint)
return model
But when I call build_model:
N = np.array([n for n in range(0,10)])
T = np.array([t for t in range(0,96)])
Tup = np.array([t for t in range(56,80)])
build_model(N,T,Tup)
ERROR: Rule failed when generating expression for constraint up with
index (0, 56): AttributeError: 'numpy.ndarray' object has no attribute
'is_expression_type'
You have a couple things biting at you here...
At the root of the error you mention is a problem with your numpy.ones
array. You are passing it N
which is a list of numbers (more below). The first number in the list is 0, so you are creating a multi-dimensional array with a zero size first index. Example:
In [30]: import numpy as np
In [31]: N = np.array([t for t in range(3)])
In [32]: X = np.ones(N)
In [33]: X.shape
Out[33]: (0, 1, 2)
In [34]: len(X)
Out[34]: 0
Advice: Forget about numpy
when getting started with these models. It is not useful. Just use python lists, sets, dictionaries.
Several other things "need some love" while you have the hood up.
You seem to be treating N
as both a fixed value and an array, which is leading to the problem above.
You are creating model.a
to be an array of the same value. Why not make it non-indexed? And you are indexing it with t
in your constraint, where I think you mean n
. Just make it a singleton.
Advice: use pyo.Param
to construct these things and if you need to print your model, it is much easier to troubleshoot.
You are passing n
to the constraint construction, but not using it as you are providing n in model.N
within the function
Comment me back if you are still stuck! Good luck!