# Error when defining variables in Pyomo

I just started to learn about Pyomo. In several tutorials it is stated that the command for creating a variable is just model.Variable = VAR(...). However, I get the error message when using the Var function:

NameError: name 'Var' is not defined


Why do I get this error? Here you see my full code (the problematic statement is the last line):

import pyomo.environ as pyo

model = pyo.ConcreteModel()

#Sets

#empty set
model.A = pyo.Set()

#initialized set with values
model.D = pyo.Set(initialize=['red', 'green', 'blue'])

#Define a function to create ta sequence of numbers
def createSequenceOfNumbers(startNumber, endNumber):
return (i for i in range (startNumber, endNumber + 1))

model.C = pyo.Set(initialize=createSequenceOfNumbers(4, 9))
model.E = pyo.RangeSet(5,9)

#printing a set
model.C.pprint()
model.D.pprint()
model.E.pprint()

#Parameter

#define sets
model.A_P = pyo.RangeSet(1,3)
model.B_P = pyo.RangeSet(1,3)

#Values for the sets by using a dict-datatype.
valuesForParam = {}
valuesForParam [1,1] = 1
valuesForParam [1,3] = 2
valuesForParam [2,3] = 10

#define Parameters (2 dimensional)
model.P = pyo.Param(model.A_P, model.B_P, initialize=valuesForParam, default=0)

model.P.pprint()

#Variables

model.variable1 = Var(within=NonNegativeReals, bounds =(0,6), initialize=1.5)

• Use pyo.Var instead of just Var – Stradivari Jan 29 at 12:01
• Thanks Stradivari for your comment. When I use your suggested code I get the following error message "NameError: name 'NonNegativeReals' is not defined" – PeterBe Jan 29 at 12:40
• Please prepend pyo when using its variables. pyo.NonNegativeReals – Stradivari Jan 29 at 12:48
• Thanks for your comment Stradivari. Now it is okay :-). However, I do not understand, why I always have to use pyo before the commands in this case while in all tutorials they do not use it? By the way: If you write your comments in an answer, I will accept and upvote it such that you get points for that. Anyways, thanks a lot for your good help. I really appreciate it. – PeterBe Jan 29 at 13:14

You are just importing the pyomo.environ module while the tutorials probably use the from syntax.

These variables are inside pyomo.environ so you have 3 alternatives:

1. Import them explicitly from pyomo.environ import Var, NonNegativeReals
2. Import them using a wildcard from pyomo.environ import * (this is considered an antipattern)
3. Import the module (with an alias in this case) import pyomo.environ as pyo and access them like pyo.VariableName