pyomo
pyomo copied to clipboard
LinearExpression cache doesn't do anything?
Summary
The cache for LinearExpression properties linear_vars and linear_coefs is a class attribute, which means that it always gets overwritten, making those properties quite slow unless you only have one linear expression. Here is an example:
import pyomo.environ as pe
from pyomo.common.timing import TicTocTimer
import sys
def get_vars(a, b):
res = list(a.linear_vars)
res.extend(b.linear_vars)
return res
def main():
m = pe.ConcreteModel()
m.a = pe.Set(initialize=list(range(10)))
m.x = pe.Var(m.a)
m.y = pe.Var(m.a)
e1 = sum(i*v for i, v in enumerate(m.x.values()))
e2 = sum(i*v for i, v in enumerate(m.y.values()))
e1.linear_vars
e2.linear_vars
n = int(sys.argv[1])
timer = TicTocTimer()
timer.tic('start')
for i in range(n):
get_vars(e1, e1)
timer.toc('done with a single expression')
for i in range(n):
get_vars(e1, e2)
timer.toc('done with two expressions')
if __name__ == '__main__':
main()
Output with n=1,000,000:
[ 0.00] start
[+ 0.30] done with a single expression
[+ 2.37] done with two expressions
I think that we should deprecate those properties and encourage people to use the args property.