Search code examples
pyomo

Unexpected exception while loading model: (0, 0)


I just started working with pyomo framework and python. I am trying to solve simple models. And when I formulate the objective function, I receive the following error before when run the code

KeyError: (0, 0)

Here is the formulation of the problem: Formulation

And the code:

from pyomo.environ import *  

N = 3
M = 4
P = 3
d = {(1, 1): 1.7, (1, 2): 7.2, (1, 3): 9.0, (1, 4): 8.3,
(2, 1): 2.9, (2, 2): 6.3, (2, 3): 9.8, (2, 4): 0.7,
(3, 1): 4.5, (3, 2): 4.8, (3, 3): 4.2, (3, 4): 9.3}

seq = ConcreteModel()
seq.Locations = range(N) #Set N
seq.Customers = range(M) #Set M

seq.x = Var(seq.Locations, seq.Customers, bounds=(0.0, 1.0)) #x[n,m]
seq.y = Var(seq.Locations, within=Binary)

seq.obj=Objective(expr = sum( d[n,m]*seq.x[n,m] for n in seq.Locations for m in seq.Customers))

seq.single_x = ConstraintList()
for m in seq.Customers:
    seq.single_x.add(
        sum(seq.x[n,m] for n in model.Locations ) == 1.0)
    
seq.bound_y = ConstraintList()
for n in seq.Locations:
    for m in seq.Customers:
        seq.bound_y.add( seq.x[n,m] <= seq.y[n] )

seq.num_facilities = Constraint(
    expr=sum( seq.y[n] for n in seq.Locations) == P)

What could be an issue? Thank you!


Solution

  • The key error you are getting is due to the fact that your dictionary d doesn't have an entry for [0, 0].

    My recommendation is that you bring everything into the model (see my edits below). That way you can "pretty print" the model, which makes it super easy to troubleshoot while building.

    Good luck!

    from pyomo.environ import *  
    
    N = 3
    M = 4
    P = 3
    d = {(1, 1): 1.7, (1, 2): 7.2, (1, 3): 9.0, (1, 4): 8.3,
    (2, 1): 2.9, (2, 2): 6.3, (2, 3): 9.8, (2, 4): 0.7,
    (3, 1): 4.5, (3, 2): 4.8, (3, 3): 4.2, (3, 4): 9.3}
    
    seq = ConcreteModel()
    
    ###  SETS
    seq.Locations = Set(initialize = list(range(1, N+1))) #Set N  # note the capitalization Set, the pyomo type
    seq.Customers = Set(initialize = list(range(1, M+1))) #Set M
    
    ### PARAMS
    seq.d = Param(seq.Locations, seq.Customers, initialize=d)
    
    ### VARS
    seq.x = Var(seq.Locations, seq.Customers, bounds=(0.0, 1.0)) #x[n,m]
    seq.y = Var(seq.Locations, within=Binary)
    
    seq.obj=Objective(expr = sum( seq.d[n,m]*seq.x[n,m] for n in seq.Locations for m in seq.Customers))
    
    seq.single_x = ConstraintList()
    for m in seq.Customers:
        seq.single_x.add(
            sum(seq.x[n,m] for n in seq.Locations ) == 1.0)
        
    seq.bound_y = ConstraintList()
    for n in seq.Locations:
        for m in seq.Customers:
            seq.bound_y.add( seq.x[n,m] <= seq.y[n] )
    
    seq.num_facilities = Constraint(
        expr=sum( seq.y[n] for n in seq.Locations) == P)
    
    seq.pprint()