0

I am fairly new to Pyomo and I am trying to solve this regular formulation of TSP problem: enter image description here

I have written this code based on material I could find online, but I am having some problems debugging it. It would be great if somebody could give some advice.

from pyomo.environ import * 
from pyomo.opt import SolverFactory
import pyomo.environ

n=5
distanceMatrix=[[0,8,4,10,12],
    [8,0,7,6,8],
    [4,7,0,7,9],
    [10,6,7,0,6],
    [12,8,9,6,0]] 
startCity = 0

model = ConcreteModel()
model.M = RangeSet(n)
model.N = RangeSet(n)
model.c = Param(model.N, model.M, initialize=lambda model, i, j: distanceMatrix[i-1][j-1])
model.x=Var(model.N,model.M, within=Binary)
model.u=Var(model.N, within=NonNegativeReals)

def obj_rule(model):            
    return sum(model.c[n,j]*model.x[n,j] for n in model.N for j in model.M)

model.obj = Objective(rule=obj_rule,sense=minimize)

def con_rule1(model,j):
    return sum(model.x[i,j] for i in model.M if i==0 for j in model.N if j!=i ) == 1

def con_rule2(model,i):
    return sum(model.x[i,j] for j in model.N if j==0 for i in model.M if i!=j ) == 1

def con_rule3(model,n,i,j):
    for i in model.M:
        for j in model.N:
           return model.u[i] - model.u[j] + model.x[i,j] * n <= (n - 1)

model.con1 = Constraint(model.N, rule=con_rule1, doc='constraint1')
model.con2= Constraint(model.M, rule=con_rule2, doc='constraint2')
model.con3= Constraint(model.M, model.N, rule=con_rule3,doc='constraint3')

opt = SolverFactory("gurobi", solver_io="python") 
results = opt.solve(model)
results.write()
Mike
  • 375
  • 1
  • 4
  • 14
  • One problem I saw about your constraints: Basically if you have an argument of `i` in a constraint definition, and lets say `i=5`, it means that this constraint will run for 5 times from 1 to 5. Example: Lets assume following is our const: `def const(model,i): return (x[i] = 10)`, it means that `x[1] = 10`, `x[2] = 10`, and so on. I can't really open imgur links, so I can't check if your constraint definitions are right with the ones in image, however what I can see is that you are using too many for-loops and I don't really think they are right. – oakca Apr 02 '18 at 19:53
  • Yes, indeed. I have reformulated that problem. Thanks – Mike Apr 03 '18 at 02:58

0 Answers0