Python MIP Optimization: TypeError: 'Var' object is not subscriptable

1,250 views
Skip to first unread message

Shax Studio

unread,
Jun 8, 2021, 12:57:21 PM6/8/21
to Python-MIP

Can Someone help me about this error?


from mip import Model, xsum, maximize, BINARY

el_price = 6.43 # Electricity price
del_t = .25 # duration of time step
demand = [3,4,5,6,7,8] # Electicity demand


gas_p = [0.23, 0.52, 0.34] # Gas price for different gases
em_fc = 0.2 # emission factor
co2_p = .25 # CO2 Price
capacity = [3,3,4,6,7,8] # capacity for the power plant


T = range(len(demand))
I = range(len(gas_p))

m = Model("Maximizing profit")
 


y = [m.add_var(lb = 0) for t in T for i in I] # Electricity generation

 
print(y)
 


# Revenue = Electricity price * demand/generation
# Cost = Fuel price = gas price + emission_factor * co2 price

# Max Proft = Revenue - Cost

m.objective = maximize(xsum((el_price * del_t * y[t][i]) for t in T for i in I) - (xsum(gas_p[i] for i in I) + (em_fc * co2_p) ))



m.objective




And getting this error: 

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-26f3ed634d21> in <module> 4 # Max Proft = Revenue - Cost 5 ----> 6 m.objective = maximize(xsum((el_price * del_t * y[t][i]) for t in T for i in I) - (xsum(gas_p[i] for i in I) + (em_fc * co2_p) )) 7 8 ~/Library/Python/3.8/lib/python/site-packages/mip/model.py in xsum(terms) 1546 """ 1547 result = mip.LinExpr() -> 1548 for term in terms: 1549 result.add_term(term) 1550 return result <ipython-input-6-26f3ed634d21> in <genexpr>(.0) 4 # Max Proft = Revenue - Cost 5 ----> 6 m.objective = maximize(xsum((el_price * del_t * y[t][i]) for t in T for i in I) - (xsum(gas_p[i] for i in I) + (em_fc * co2_p) )) 7 8 TypeError: 'Var' object is not subscriptable

For better view:



Thanks for your help. 

Joshua Ivanhoe

unread,
Jun 10, 2021, 7:59:23 AM6/10/21
to Python-MIP
You have an error in the way you define the variable 'y'. It should be:

y = [[m.add_var(lb = 0) for i in I] for t in T] 

(Note that I have used a nested list comprehension) 
Reply all
Reply to author
Forward
0 new messages