我对Pyomo很新,我正试图解决这个常规的TSP问题: enter image description here
我根据我在网上找到的资料编写了这段代码,但我在调试时遇到了一些问题。如果有人能给出一些建议,那就太好了。
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()