Search code examples
pythondjangomathematical-optimizationpulp

NameError at / free variable 'y' referenced before assignment in enclosing scope


I need to make a small project for my university -create webapp that will solve Transportation Problem and I am making MVP version really. I am using Django for webapp and PuLP for transportation problem part.

When launching my problem solving logic I receive an error:

NameError at / free variable 'y' referenced before assignment in enclosing scope

for line:

prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x

I was using PuLP example from their GitHub here

My code for this part is as below:

    Warehouses = [0,1,2]
    supply = { 0: deliver1,
              1: deliver2,
              2: deliver3
              }
    Distributors = [0, 1, 2]
    demand = { 0: receiver1,
               1: receiver2,
               2: receiver3
              }

    costs = [   #dsitributors -static variables for debugging will change that later on
        #D  E  F
        [3, 5, 7],#A  Warehouse
        [12, 10, 9],#B  Warehouse
        [13, 3, 9],#C  Warehouse

    ]

    prob = LpProblem("Transportation Problem",LpMinimize)



    Routes = [(x,y) for x in Warehouses for y in Distributors]
    route_vars = LpVariable.dicts("Route",(Warehouses,Distributors),0,None,LpInteger)

    prob += lpSum([route_vars[x][y]*costs[x][y] for (x,y) in Routes]), "Sum of Transporting Costs"
    for x in Warehouses:
        prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x

    for y in Distributors:
        prob += lpSum([route_vars[x][y] for y in Warehouses]) >= demand[y], "Sum of Products into Distributors %s"%y    


    prob.writeLP("TransportationProblem.lp")
    prob.solve()
    print("Status:", LpStatus[prob.status])
    for v in prob.variables():
        print(v.name, "=", v.varValue)
    print("Total Cost of transportation = ", value(prob.objective))

I guess that's just some stupid mistake I made but cannot really find it... Also naming Warehouses and Distributors by numbers and not names was my workaround for receiving

TypeError: list indices must be integers or slices, not str

for the same line.


Solution

  • In the supply constraints, assign Distributors to y (currently y is undefined), like this:

    for x in Warehouses:
        prob += lpSum([route_vars[x][y] for y in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x
    

    The same error applies to the demand constraints where Warehouses should be assigned to x.

    For deployment Apache and mod_wsgi is one option. https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/modwsgi/