Question: TSP: k _ tsp _ mtz _ encoding ( ) : I set up an LP problem with PULP to solve this TSP optimization, but
TSP: ktspmtzencoding:
I set up an LP problem with PULP to solve this TSP optimization, but the answers Im getting are suboptimal. What is the cause of the issue?
Complete the implementation of the function ktspmtzencodingn k costmatrix below. It follows the same input convention as the code supplied in the notes. The input n denotes the size of the graph with vertices labeled n k is the number of salespeople, and costmatrix is a list of lists wherein costmatrixij is the edge cost to go from i to j for i j Your code must avoid accessing costmatrixii to avoid bugs. These entries will be supplied as None in the test cases.
Your code must return a list lst that has exactly
lists in it wherein lstj represents the locations visited by the
salesperson.
For the example above, for
your code must return
For the example above, for
your code must return
from pulp import
def ktspmtzencodingn k costmatrix:
# check inputs are OK
assert k n
assert lencostmatrix n f'Cost matrix is not nxn
assert alllencj n for cj in costmatrix f'Cost matrix is not nxn
prob LpProblemkTSP LpMinimize
# finish your implementation here
# your code must return a list of klists i il jjl wherein
# the ith entry in our list of lists represents the
# tour undertaken by the ith salesperson
# your code here
# variables for each edge
x i j p: LpVariablefxijp cat'Binary'
for i in rangen for j in rangen for p in rangek
# Objective function: minimize the total cost
prob lpSumcostmatrixij xi j p
for i in rangen for j in rangen if i j for p in rangek
# constraints:each city is visited exactly once by exactly one salesperson
# ensure that each salesperson begins and ends at vertex
for i in range n:
prob lpSumxi j p for j in rangen if i j for p in rangek
prob lpSumxj i p for j in rangen if i j for p in rangek
for p in rangek:
prob lpSumx j p for j in range n
prob lpSumxj p for j in range n
# Subtour elimination constraints using mtz
u i: LpVariablefui lowBound upBoundn cat'Integer' for i in rangen
for i in range n:
for j in range n:
if i j:
for p in rangek:
#here is the actual mtz logic
prob ui ujn xi j p n
# Solve the problem
prob.solve
# Extract the solution
tours for in rangek
for i in rangen:
for j in rangen:
for p in rangek:
if xi j pvarValue :
tourspappendi
break
return tours
Attached is a screenshot of the failing test case
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
