Professional Documents
Culture Documents
TSP in Spreadsheets
TSP in Spreadsheets
TSPinSpreadsheetsaGuided
Tour
RasmusRasmussen
Abstract
Thetravellingsalesmanproblem(TSP)isawellknownbusinessproblem,andvariantslikethemaximum
benefitTSPorthepricecollectingTSPmayhavenumerouseconomicapplications.Wearelookingatseveral
differentvariantsofTSP;allsolvedinspreadsheets,notusingtailoredsolversforTSP.Astheseproblemsare
NPhard,solvingthoseusingstandardLP/MIPsolvershasbeenregardedfeasibleonlyforverysmallsized
problems.However,acarefulconsiderationofthespreadsheetlayoutmayfacilitateefficientsoftware
utilisation.Forrealworldproblemsthiscanhaveconsiderableeffects,andwiththerecentadvancementsin
solverengines,problemspreviouslyregardedasbigarenoweasilysolvableinspreadsheets.Thispaper
showsyouhow;andhowtheflexibilityofspreadsheetsmakesitaconvenienttoolsolvingmanyvariantsof
TSP,wheretailoredsolverssimplywouldnotfit.
JELclassification:C61,Z00
1. Introduction
Afteraformalstatementoftheproblem,threedifferentspreadsheetmodelswillbeillustrated.The
flexibilityofspreadsheetswillalsobedemonstrated,aswillhowspreadsheetlayoutmayhelpinmaking
anefficientproblemformulation,inadditiontohelpingtoclearlycommunicateanddisplaythe
solution.Thedirectpermutationapproachispresentedfirst,applyingintegervariablestodescribethe
sequenceofthevisits.Thedirectpermutationapproachfitssmallproblemswell,andrequiresverylittle
workafterdatahasbeenobtained.Noconstraintstoeliminatesubtoursareneeded,buttheproblemis
nonlinearandnonsmooth,requiringheuristicsolvers.Second,anetworkformulationispresented,
wherebinaryvariablesareusedtomakealinearformulationoftheproblem.Anefficientspreadsheet
layoutispresentedfornoncompletegraphs.Thirdlyanassignmentformulationispresented,applying
aspreadsheetlayoutmoresuitableforcompletegraphs.
VariantsofTSPnotfittingtailoredTSPsoftwarearealsosolved.Inadditionsomeconfiningsideeffects
ofcommonsubtoureliminatingconstraintsarediscussed,particularlywhenmultiplevisitsarerequired.
2. ThestandardTSP
Travellingsalesmanproblems(TSP)areeasytodescribe:asalesmanneedstovisitallhiscustomers
locatedindifferentcitiesinhisregion,andhewouldliketofindthecheapesttourthatwillassurethat
allcitieshavebeenvisited.UnfortunatelyTSPisnotsoeasytoformulate,andrelativelyhardtosolve.
Whenmakingamathematicalformulationoftheseproblemswewillforthemostpartuseanetwork
framework.Thecitiesarethencallednodes,andtheroadsconnectingthecitiesarecalledarcs.See
GutinandPunnen(2007)forafulltreatmentofTSPanditsvariants.
ThesetofnodestobevisitedaredefinedasN={1,2,...,n}wherenisthetotalnumberofnodes
(referredtoasthesizeofaTSP),andthesetofarcsconnectingthenodesisdefinedasA={(i,j):i,jN,
InternationalReviewofEconomicsEducation
ij},wherethepair(i,j)indicatesthearcbetweennodeiandj.AstandardassumptioninTSPisto
assumedirectlinksbetweeneverypairofnodes,usuallyreferredtoasacompletegraph.Thegraph
consistingofthenodesNandarcsAisthenconnected;thereisaconnectionorpathfromanynodeto
anyothernodeinthegraph.Thebasicstandardassumptionistorestrictthenumberofvisitstoexactly
oneforeachnode.Whythesalesmanisnotallowedtovisitanodemorethanonceisnotobvious.One
canspeculatethatsucharequirementmakesiteasiertodevelopsolutionprocedures,therebyfitting
theproblemtothetoolsathand.AcommondefinitionofthesetofdecisionvariablesisX{xij:i,jN,
ij}wherexij=1ifthesalesmantravelsfromnodeitoj(nodeiisvisitedimmediatelybeforenodej),
and0otherwise.ThecostmatrixisdefinedasC={cij:i,jN,ij}andusuallyassumedtobepositive,
wherecijrepresentsthecostoftraversingfromnodeitonodej.InstandardTSPacommonassumption
isthatthesquarecostmatrixissymmetric,cij=cji,thecostisthesameinbothdirections.Another
standardassumptionistoassumethetriangleinequality;cij+cjkciki,j,kN,thedirectconnection
betweentwonodesisalwaysthecheapest.
OnebasicassumptioninTSPistoassumethatthesalesmanhastoreturntothenodewherehestarts
thetour;thisnodeisusuallyreferredtoasthebasecityordepot.Thisassumptioniscalledaclosed
tour.Foraclosedtouranynodecanbeselectedasthestartingnode,butforpracticalreasonsnode1is
settobethestartingnode.Node1isthenthebasecityordepot.
ForastandardTSPthereisalwaysafeasiblesolution(asacompletegraphisalwaysconnected),andwe
canchooseanynodetostart(asthetourisclosedandallnodesarevisited).Therearealways
alternativeoptimalsolutions;thetourcangoineitherdirection(asthecostsaresymmetric).Andinthe
optimaltour(s)everynodeisvisitedonlyonce(becauseofthetriangleinequality,andtheobjectiveis
alwaysminimisation).
3. VariantsofTSP
Quitealotofreallifeproblemsdonotfittheseassumptions.OftenwemustallowforthesetAnot
beingcomplete,incaseswheresomenodesdonothavedirectlinkstoallothernodes.Graphsthatare
notcompletearenolongerguaranteedtobeconnected,andfordisconnectedgraphsthereisno
feasiblesolution.Inreallifewealsohavetoallowforcijcji,thecostoftravellingfromnodeitojmay
notbethesameastravellingfromjtonodei.Thisrepresentstheasymmetrictravellingsalesman
problem(ATSP),andimpliesdirectedarcs.Similarlyitisnotalwayscheapesttotravelthedirectlink
fromnodeitonodek,sometimesitmaybecheapertotravelvianodej.Thuswemustallowforthe
triangleinequalitynottoapply.Thebasicstandardassumptiontorestrictthevisitstoexactlyonefor
eachnodemayalsobeskipped;TSPwithmultiplevisitsisreferredtoasTSPM,asinGutinandPunnen
(2007).
Ofcoursethereasonforthesalesmantomakethetouristoderivesomebenefitfromvisitingthe
nodes.ThenletB={bj:jN},wherebjisthebenefitfromvisitingnodej.Forsuchproblemswehave
themaximumbenefittravellingsalesmanproblem(MBTSP);seeMalandrakiandDaskin(1993).Another
variantisthepricecollectingTSP(orPCTSP),seeGutin(2007).
Sometimesthesalesmandoesnothavetoreturntothebase,andrelaxingsucharequirementiscalled
anopentour.Foranopentouritmaybeadvantageoustobeabletoselecttheendingnodeaspartof
theproblemsolution,butthismayincreasetheproblemsizeforsometypesofformulations,exceptfor
thedirectpermutationapproach.
Thereisawideselectionofliteratureontheseproblems,andseveralvariantsofproblemformulations.
Wewillgrouptheformulationsintwoclasses:theassignmentformulationsandtheflowformulations.
Further,ineachgroupthemodelsvaryaccordingtowhichassumptionsaremade,mostnotably
whetheracompletegraphisassumed.
95
Fulltitleofthepresentarticle:doubleclicktoeditthis
4. AssignmentformulationofTSP
Fortheclosedtouranassignmentformulationcouldbeofthefollowingform:
n n
Minimize cij xij (1)
i =1 j =1
n
x
i =1
ij =1 , j N (2)
n
x
j =1
ij =1 , i N (3)
Inadditionsubtoureliminationconstraints(SECs)areneeded.Constraints(2)and(3)arethestandard
assignmentconstraints.Theobjectivein(1)willminimisethetotalcostalongallthearcsusedto
completethetour.However,aswrittenthisformulationassumesacompletegraph,andifthedataare
beingarrangedinasquarematrixwillalsoincludethediagonal.Foracompletegraphtheonlyarcsthat
donotexistarerelatedtotheselfloopvariablexi,i(alongthediagonal).Thereforeitusuallyismore
convenienttoexcludethesevariablesbyanewconstraint(5),insteadofexcludingtheminthe
definitionofthesetX.Thisconveniencecomesatthecostofincreasedproblemsize(bothintermsof
variablesandconstraints).Foracompletegraphthefollowingconstraintwillfixthediagonalinasquare
nmatrixofthebinaryvariablesxijequaltozero:
xi ,i = 0 i N (5)
Adifferentapproachtorectifythis,andallowforinstancesofnoncompletegraphs;istosetthecostcij
sufficientlylargefornonexistingarcs,therebypreventingthemfromenteringthefinalsolution.
Howeverthisisnotafoolprooftrick.Inaconnectedgraphthereisapathfromanynodetoanyother
nodeinthegraph,andacompletegraphisalwaysconnected,andthushasafeasiblesolution.Non
completegraphsmaynotbeconnected(disconnected),andwillassuchhavenofeasiblesolution.A
highcostfornonexistingarcsisthennoguaranteeforthesesarcstobeexcludedinthefinalsolution.
Thereforeanotherstrategyistosetanewparameter:eij=1ifnodeiisdirectlyconnectedtonodej,
otherwise0;andreplaceconstraint(5)with(6):
Thisformulationdoesnotrequireacompletegraphandallowsforasymmetriccostsandalsoforthe
triangleinequalitynottoapply,butunfortunatelyithassomeflaws.Iftheassumptionofacomplete
graphisnotsatisfied(andthereforeconstraint(6)isrequired),thenafeasiblesolutionforaclosedtour
mayrequiresomenodestobevisitedtwice,breakingthe=requirementinconstraint(2).
Thelimitationofvisitingeachnodeexactlyoncemayalsocausedifficultiesevenforproblemswitha
completegraph,ifthetriangleinequalityisnotsatisfied.Thisrequirementwilleffectivelyprohibithub
likesolutions,evenwhensuchsolutionsarethemostcosteffective.Aproblemformulationthat
excludessuchpossibleoptimalsolutionsisgenerallynotrecommended.
96
InternationalReviewofEconomicsEducation
5. FlowformulationofTSP
Aflowformulationoftheclosedtour,thatexplicitlyconsidersvalidconnectionsonly,canbemadeafter
redefiningC={ci,j:(i,j)A}andX{xi,j:(i,j)A}.Thisformulationwillthusworkevenwhenthe
graphisnotcomplete:
Minimize
( i , j ) A
ci , j xi , j (7)
i : ( i , j ) A
xi , j 1 j N (8)
i : ( i , k ) A
xi , k =
j : ( k , j ) A
xk , j k N (9)
xi , j {0,1} ( i , j ) A (10)
OfcourseSECsarealsorequired.Theobjective(7)willminimisethetotalcostofthetour,only
consideringvalidarcs.Constraint(8)statesthatthesalesmanhastoarriveeachnodeatleastonce.
Constraint(9)statesthatthesalesmanhastoleaveeachnodeasmanytimesashearrivethenode.By
usinginsteadof=in(8),weavoidthepossibilityofmakingtheprobleminfeasiblefornoncomplete
graphswheresomenodesneedtobevisitedtwice,andwedonotexcludehublikeoptimalsolutions
ifthetriangleinequalitydoesnotapply.
6. FlowformulationofopentourTSP
FortheopentourformulationweaddtheparametersD={di:iN}wherediisthenetdemandin
nodei;anddi=1forthestartnode(thebasecityisnumberednode1);di=+1fortheendnode,for
thetransitorintermediatenodesdi=0.Theopentourformulationcanthenbestatedas:
Minimize
( i , j ) A
ci , j xi , j (11)
i : ( i , j ) A
xi , j 1 j > 1 N (12)
i : ( i , k ) A
xi , k
j : ( k , j ) A
xk , j = d k k N (13)
xi , j {0,1} ( i , j ) A (14)
WemustaddSECstocompletetheTSPformulation.Theobjectivein(11)isidenticalto(7).Constraint
(12)issimilarto(8),exceptthatwedonotrequirethesalesmantoarrive/returntothestartingnode1.
Constraints(13)requirethesalesmantoleavethestartingnodeonemoretimethanentering,enterthe
stoppingnodeonemoretimethanleaving,andleaveanyintermediatenodeasoftenasarrivingthe
node.Byremovingconstraint(12)wehavethecommonshortestpathproblem.Iftheendnodeisnot
specified,thediparametersmaybeconvertedtobinaryvariables(exceptforthestartnode),requiring
theirsumtoequal1.
97
Fulltitleofthepresentarticle:doubleclicktoeditthis
7. Subtoureliminatingconstraints(SECs)
AkeypartofaTSPistomakesurethetouriscontinuous,thatthearcsarelinkedfromthebasecityall
thewaytoeverycityvisited.Withoutsuchconstraintswequiteoftenwillgetsolutionscontaining
degeneratetoursbetweenintermediatenodesandnotconnectedtothebasecity.TheoriginallySECs
wasformedin1954byDantzigFulkersonJohnson(DFJ)(seeDantzig,FulkersonandJohnson,1954):
x
iS jS
i, j S 1, S N \ {1}, S (15)
Unfortunatelythisintroducesanexponentialnumberofconstraints,andbecomesimpracticalevenfor
smallsizedproblems.AdifferentSECproposedin1960byMillerTuckerZemlin(MTZ)(seeMiller,
TuckerandZemlin,1960)introducesonlyamaximum1of(n2)2constraints,atthedisadvantageofa
weakLPrelaxation:
ui u j + 1 ( n 1) (1 xi , j ) ( i, j ) A, : i, j 1 (16)
In(16)anewsetofvariablesU={ui:iN,i1}isrequired.Theuiarearbitraryrealnumbers,butcan
berankedtononnegativeintegers,representingthesequencethenodesarebeingvisited.For
conveniencewemayaddu11(node1isthebasecity),andlimittherangeofui,thushelpingthe
optimisationsoftware(seealsoPataki(2003)):
2 ui n i > 1 N (17)
TheMTZSECswillbeusedinthispaper,andhavethefollowingproperties:
node1isrequiredtobethebasecity;
theymakesurethateverycityvisitedbelongstoatourconnectedtothebasecity,thereby
eliminatingsubtours;
theyallownodestobevisitedmorethanonce(unlessotherconstraintspreventsuchasolution);
theydonotrequireallnodesbeingvisited(unlessotherconstraintsmakesuchrequirements);
theyallowunidirectionalarcstobeutilisedinbothdirectionsonthesametour.
Foraclosedtourvisitingallnodesthebasenodecanalwaysbechosenarbitrarily.Afundamental
weaknessofMTZSECsisthatfeasibilityandfinalsolutionmaydependonwhichnodeisselectedasthe
basecity.TheMTZSECsmayfailtofindafeasiblesolutionevenifsuchexists,andtheymayfailtofind
theglobaloptimalsolution.Problemswithfeasibilitymayoccurinnoncompletegraphs,whereall
feasiblesolutionsrequiresomenodestobevisitedtwice.Problemsfindingtheglobaloptimalsolution
mayoccurincompletegraphswherethetriangleinequalitydoesnotapply,andwheretheglobal
optimalsolutionrequiressomenodestobevisitedmorethanonce.Itisthereforeimportanttobe
awareofthesetwosituationswhereapplyingtheMTZSECsmaymakethefinalsolutionsensitiveasto
whichnodeisselectedasthestartingnode.Theywillneverfailiftheglobaloptimalsolutionvisitseach
nodeonlyonce.
8. ClosedTSPinacompletegraph
AsanexampleofaTSPinacompletegraphweshallusethefollowingexample.Asupplyshipisserving
10oilrigsatsea.Thebaseislocatedatcoordinates(0,0),andtherigsarelocatedasdisplayedinFigure
1
Inasquarennmatrix;thefirstrow,firstcolumnandthediagonalareexcluded.
98
InternationalReviewofEconomicsEducation
1.Assumingopenseathedistancesbetweenanypairofnodes(oilrigs)canbecalculatedasstraight
lines(ignoringthefactthatthesealevelisnotflat).ThisisastandardsymmetricTSPwithacomplete
graphwherethetriangleinequalityapplies.DataistakenfromRagsdale(2001).
Figure1Locationsoftheoilrigstovisit
9. Adirectpermutationapproach
Inthissimpleformtheproblemistofindtheorderforeachnodeinthesequenceofthetourthat
minimisesthetotaldistance(cost).Ifthesupplyshiptakesthetourbasedontherignumbers:012...
9100;thetotaldistanceis205.67.Weseektheorderorpermutationthatminimisesthetotal
distance.Thisdirectapproachisveryeasytoimplementinspreadsheets,asdisplayedinFigure2.
Figure2SpreadsheetfordirectpermutationofTSP
99
Fulltitleofthepresentarticle:doubleclicktoeditthis
Table1:FormulasforspreadsheetinFigure2
Figure3SolversettingsforthespreadsheetinFigure2
Thespreadsheetisorganisedintwoparts.Theupperpartholdsatableofthecoordinatesforthe
nodes,andacorrespondingtablecalculatingthedistances.Thelowerpartholdsatableofthetour
sequenceandthecostofeachleg,andacorrespondingtablewiththecoordinatesofeachleg,to
facilitateaplotofthetour.Thetableofthetoursequencestartsatthebase.Notethatnodenumber0
isusedforthedepotinthisexample,tofacilitateuseoftheAlldifferentconstraintinSolver.(Atrial
versionofSolverisavailableatwww.solver.com.)Theproblemistoselectwhichnodetogotonextin
thesequence(headingSequenceinFigure2).Thelastleghastoreturntothebase.Theminimum
totaldistance/costof122.77isachievedbythetoursequence0946572810130(orreverse).To
modelanopentoursimplydeleterow27inthesheet.Figure4displaystheoptimalopentour,which
hasacostof103.58.
Thescatterplotconsistsoftwoseries.Oneseriesisaplotofthenodes(C3:D13inFigure2),with
markersbutnoline.Thesecondseriesisthetour(G13:H27inFigure2),withnomarkersandaline.
100
InternationalReviewofEconomicsEducation
Figure4TheopenTSPsolution
BoththespreadsheetandtheSolversettingsareverysimple.Wehave10decisionvariables(numberof
nodeslessthedepot),namedSequenceinthespreadsheet.TheobjectiveintheSolversettingsisto
minimisethevalueinthecellnamedTotal_cost,andtheonlyconstraintisthatthevariablesmustbe
alldifferent.Thealldifferentconstraintsetsthevariablestointegersrangingfrom1tothenumberof
variables,andallaredifferent.(ThistypeofconstraintisnotavailableintheStandardSolverthatships
withExcelpriortoExcel2010,butisintroducedintheeducationalversionofSolver,includedinmany
textbooks.)
TheuseoftheIndexfunctioninExceltolookupthecostateachlegmakestheobjectivefunctionnon
smooth,becausethedecisionvariablesareusedasargumentsintheIndexfunction.Anintegernon
smoothproblemisnoteasytosolve,andisdefinitelynotthepreferredformforlargeproblems.Inthis
casethePremiumSolverPlatform(PSP)selectstheOptQuestsolverengine,andSolverspendslessthan
twosecondsinfindingtheoptimaltour(theAutoStopoptionforOptQuestwasincreasedfrom100to
1000iterationstoavoidaprematureending).Asthissolverengineappliesheuristics,itcannot
guaranteethataglobaloptimalsolutionhasbeenfound.Whensuchproblemsbecomelarge,thisnon
linearapproachisnolongerefficient.Wewillthereforeintroducethelinearformulation,whichwillbe
appliedintherestofthepaper.Alsonotethatthedirectpermutationapproachdoesnotallowfor
multiplevisits.
10. TSPinanoncompletegraph,flowformulation
AsanintroductoryexampleforanoncompletegraphtheGridspeedpuzzlewillbeused,takenfrom
Chlond(2008).Figure5presentsthepuzzle,basedonarectangulargridstreetplan,wherethedistance
betweenanytwointersectionsis10kilometres.(Ihavetakenthelibertytotransformthedatatothe
metricsystem.)Thespeedalongallnorthsouthstreetsandalleastwestavenuesisconstant.However
thespeedonthenorthsouthstreetsishighestontheeastendofthegrid,andfortheavenueseast
westthespeedishighestinthesouthendofthegrid.Thefastestareaisthereforeatthesoutheast
edgesofthegrid,andslowestinnorthwest.
101
Fulltitleofthepresentarticle:doubleclicktoeditthis
Figure5Streetplan
10 km/h 20 km/h 30 km/h 40 km/h 50 km/h 60 km/h
(6, 1) (6, 6)
10 km/h
20 km/h
30 km/h
40 km/h
50 km/h
60 km/h
(1, 1) 10 km (1, 6)
OnepuzzlerelatedtoFigure5istofindthefastestroutefromintersection(6,1)(northwest)to
intersection(1,1)(southwest),butvisitingeachintersectionatleastonce.Theoriginalproblemisto
visiteachintersectiononceandonlyonce.Howeverthisismorerestrictedthanrequired.Sinceit
obviouslywilltakemoretimetovisitanintersectionmorethanonce,andwewanttospendasshort
timeaspossibleonthetour,itissufficienttousetherequirementtovisiteachintersectionatleast
once.
Itisnecessarytotransformtheproblembynumberingtheintersectionsandcalculatethetravelling
timebetweeneach(directlyconnectednode),tofacilitateamathematicalformulation.Thenumbered
intersectionsarethenodes,andthelinesconnectingthenodesarethearcs.Thetravellingtime(in
minutes)alongeacharciscalculatedasshowninFigure6.
Figure6Relabelledstreetplan
60 60 60 60 60
1 2 3 4 5 6
60 30 20 15 12 10
30 30 30 30 30
7 8 9 10 11 12
60 30 20 15 12 10
20 20 20 20 20
13 14 15 16 17 18
60 30 20 15 12 10
15 15 15 15 15
19 20 21 22 23 24
60 30 20 15 12 10
12 12 12 12 12
25 26 27 28 29 30
60 30 20 15 12 10
10 10 10 10 10
31 32 33 34 35 36
102
InternationalReviewofEconomicsEducation
Figure7SpreadsheetofopenTSP,noncompletegraph(rows66121arehidden)
103
Fulltitleofthepresentarticle:doubleclicktoeditthis
Table2FormulasforthespreadsheetinFigure7
11. Theopentour
Wewillfirsthavealookattheopentourvariantofthepuzzle.Anefficientlayoutofthisnetworkina
spreadsheetwouldbetoorganisetheproblemintwotables,onetableforthearcsandthebinary
decisionvariables,andanothertableforthenodesandthecontinuousvariables(asinRagsdale,2001).
Thiswillfacilitatetheentryoftheequations(11)(14),(16)and(17),andalsomakeasolutioneasyto
understand.Oncethedatahasbeenenteredinthespreadsheet,themodelcaneasilybebuiltaround
thedata.Noticethatfornondirectedarcsitissufficienttoentertheminonedirection,andusesimple
formulastomirrortheotherdirection.Athirdtablehasbeenaddedtothespreadsheettofacilitatea
plotofthetour,whichofcourseisnotneededforsolvingtheproblem,buthandyfordisplayingthe
solution.
Anewconstrainthasbeenadded,tospeedupthesolutionprocess:
xi , j + x j ,i 1 ( i , j ) A (18)
Constraint(18)simplystatesthatnoarcwillbeusedinbothdirections,whichisquiteobviousforthis
problem.Suchboundsonthevariablesareveryhelpfulfortheoptimisationprocess,particularlysofor
binaryvariables.Howevertheyshouldbeusedwithcare,sinceaddingthemcanmakesomeproblems
infeasible.
InFigure7thetableforthearcsislistedfirst;thenthetableforthenodesandfinallythetablefor
facilitatingaplotofthetour.Thefirsthalfofthearcsarelisted(allarcsinonedirection)andafewof
therest,togetherwiththeobjective.(Therestofthearcsareinthehiddenrows66121.)Weseethat
104
InternationalReviewofEconomicsEducation
theoptimalvalueoftheobjective(11)is726;thefastestopentourfromnode1tonode31takesa
minimumof726minutes.TheformulasinthespreadsheetaredisplayedinTable2,andtheSolver
settingsarelistedinFigure8.
ThefirstthreerowsinTable2arepurelyforeasydataentry.Theoptimisationmodelconsistsofthe
nextsixrows.Thefollowingfiverowsareusedfornamingsomekeycells,makingthemodeleasierto
read.Thelastfourrowsfacilitateaplotofthesolution,assumingonlynlegsinthetour(eachnodeis
visitedonlyonce).ThescatterplotinFigure7consistsoftwodataseries.Oneseriesisthexy
coordinatesofthenodes(incolumnVandW),withnoline,andacircle(size20)asmarker.2The
secondseriesisthexycoordinatesofthetour(incolumnRandS),withnomarkerandaline.Fora
closedtourafinallegisaddedattheend(byreferringtothefirstlegincolumnQ).
Figure8SolversettingsforFigure7
TheStandardSolverParameterDialogBoxdisplayedinFigure8hasascrollbartodisplaythe
constraintsnotfittingthefixedsizeofthebox.Hereconstraint(14)isnotdisplayed;thisisthe
declarationofthexijvariablebeingbinary.Observethatconstraint(14)and(17)isentereddirectlyin
Solver,involvingnoformulasinthespreadsheet.Constraints(17)arethelasttwovisibleconstraintsin
theSolverParameterDialogBox.
Thismodelhas120binaryvariablesand35continuousvariables,155boundsonthevariablesand191
constraints.Thenumberofconstraintscanbereducedby4ifwegroupthefourarcsconnectedtonode
1andlistthemfirst,thennotincludetheminconstraints(16).Inthespreadsheettheformulafor(16)
includethesearcs,butfixtheirvalueto0,therebysatisfyingtheconstraint.
ExcelandtheStandardSolvertakelessthanfivesecondstofindtheoptimalsolutionfortheopentour.
(ThesolutiontimewillofcoursedependontheversionofExcel,theoperatingsystem,andthe
computer.)Thisspreadsheetdesignisquiteversatileformanytypesofnetworkproblems.Ifwedrop
(12),(16),(17)and(18)wehavetheshortestpathproblem.(WemaythendeletecolumnF,G,JandP
W.)
12. AclosedTSPinanoncompletegraph,assignmentformulation
Wewillnowrephrasetheproblemtoaclosedtour,requiringthesalesmantoreturntothebase.We
willimplementtheassignmentformulationandcompareitwithaflowformulation(notshown).We
willalsodemonstrateanefficientlayoutforthespreadsheetofaTSPinacompletegraph,eventhough
thisparticularexampleisnoncomplete.ForaTSPinacompletegraph,itismoreefficienttogroupthe
probleminthreetables;onetableforthecostmatrixandtheobjective(1),asecondtableforthexij
2
ThelabelsofthescatterplotweremadebytheXYChartLabeleraddinforExcel,freeatwww.appspro.com.
105
Fulltitleofthepresentarticle:doubleclicktoeditthis
binarydecisionvariablesandconstraint(2)and(3),andathirdtablefortheSECsandtherelatedui
variables.Forconvenienceatableofthecoordinatesofthenodescanbeaddedtofacilitateaplotof
thetour.Forlargeproblemsthesematrixesmaybeenteredindifferentsheetsintheworkbook.(Itis
moreeffectivethoughforSolvertohavetheobjective,constraintsandvariablesinonesheet.Thecost
matrixandtheplotdatacanbestoredinaseparatesheet.)
Amatrixlayoutofthecostsisveryefficientforacompletegraph,whentherearedirectlinksbetween
anynodetoeveryothernode.However,itisalsoverycommontousethesameapproachfornon
completegraphs,maybebecauseitisconsideredhandierfordataentry,atleastinthepreferred
softwaretoolsmostcommonlyused.
Unfortunatelythisconveniencehasatradeoff.Addingenormousamountofnonexistingvariablesand
correctingthisbyaddinganequalamountofnonexistingconstraints,makesasubstantialburdenon
thesoftware.Incontrast,enteringthedatainaspreadsheetmayactuallybeeasierfornoncomplete
graphsituations,usingonlytwotablesinsteadofthree.
Figure9MatrixofcostsforTSPnoncompletegraph,assignmentformulation
106
InternationalReviewofEconomicsEducation
Figure10MatrixofbinaryvariablesforTSPnoncompletegraph,assignmentformulation
107
Fulltitleofthepresentarticle:doubleclicktoeditthis
Figure11MatrixofSECsandplotdataforTSPnoncompletegraph,assignmentformulation
Figure12TheplotoftheclosedTSPinanoncompletegraph,assignmentformulation
108
InternationalReviewofEconomicsEducation
Figure13SolversettingsforFigures9to11
Table3:FormulasforspreadsheetinFigures9to11
Cell Formula Copiedto Name/Task
AM39 =SUMPRODUCT(C3:AL38;C42:AL77) Eq1
AM42 =SUM(C42:AL42) AM43:AM77 Eq3(LHS)
C78 =SUM(C42:C77) D78:AL78 Eq2(LHS)
=INDEX($AM$82:$AM$117;$B83)
D83 INDEX($AM$82:$AM$117;D$81) D83:AL117 Eq15(LHS)
+INDEX($C$42:$AL$77;$B83;D$81)*$B$37
C3:AL38 Eq6(RHS)
C42:AL77 Var_x
B36 Param_n_2
B38 Param_n
AM83:AM117 Var_u
AO82 =RANK(AM82;$AM$82:$AM$117;1) AO83:AO117 Therankofanode
AP82 =MATCH(AT82;$AO$82:$AO$117;0) AP83:AP117 Visitingsequence
AP118 =AP82 Lastleg,returntobase
Avisitednodesx
AQ82 =INDEX($AT$82:$AV$117;$AP82;2) AQ83:AQ118
coordinate
Avisitednodesy
AR82 =INDEX($AT$82:$AV$117;$AP82;3) AR83:AR118
coordinate
109
Fulltitleofthepresentarticle:doubleclicktoeditthis
DuetoitssizethisformulationcannotbesolvedbytheStandardSolverinExcel,whichhasalimitof
200variables.WeseefromFigure9thattheminimumtimetocompleteaclosedtouris834,thevalue
fortheobjective(1).
InTable4themodelinFigure7,aclosednetworkversion(notshown),andtheclosedassignment
versioninFigures9to11arecompared.Thesolutiontimefortheassignmentformulationoftheclosed
tourismorethan6.2timesthesolutiontimefortheflowformulation(usingtheGurobiSolverEnginein
RSPV9.04forExcel).
Table4:Keyfeaturesofthemodels
ModelsofTSP Figure7 Notshown Figure911
Type, Open, Closed, Closed,
model network network assignment
Integervariables 155 155 1296
Continuousvariables 35 35 35
Constraints 248 249 1297
Boundsonvariables 70 70 1331
Solutiontime(seconds) 0.44 3.84 24.01
Lessonslearnedfromthissmallexamplearethatformulationmatters.Avoidusingnonexisting
variablesrectifiedbynonexistingconstraints.However,addingconstraintsmayhaveagreatimpact,
evenwhennotchangingtheoptimalsolution.Constraintsthataretighteningthefeasiblespacemay
speedupthesolutiontime(orthecontrary),butsuchconstraintsmustnoteliminateanotherwise
optimalsolution.
13. AclosedMBTSPinanoncompletegraph,flowformulation
Theultimateminimumcostforanyproblemiszero;simplydonothing.Sotheremustbeareasonfor
doingsomething(presumablythereisanullalternative).Minimisingcostscanoftenturnouttobe
solvingthewrongproblem.Unlessanyrevenuesarecompletelyunaffectedbythedecisionsathandwe
cannotbesurethatminimisingcostsisavalidmodelthataccuratelyrepresentstherelevant
characteristicsoftheproblem.
Letusassumetherearesomerevenuesorbenefitsbjbyvisitingnodej;wherejN.Alsointroducethe
setY={yj:jN,j1,yj{0,1}}wherethebinarydecisionvariableyj=1ifthesalesmanvisitsnodej,
else0.Definetheparametery1=1astherequirementtovisit/returntothedepot(node1),a
consequenceofourSECs.
Theobjectivenowistomaximisethetotalnetbenefit(totalbenefitsminustotalcosts):
maximize b
jN
j yj
( i , j ) A
ci , j xi , j (19)
Thesalesmanhastoarrive(atleast)onceeachnodehedecidestovisit:
i:( i , j )A
xi , j y j j N (20)
110
InternationalReviewofEconomicsEducation
Inadditionthebalanceconstraint(9)andbinaryconditions(10)apply,aswellastheSECs(16)andthe
correspondingbounds(17).Here(19)and(20)replacetheoriginalobjective(7)andconstraint(8),
whencomparedtotheclosedTSPflowformulation.
TherevisedproblemispresentedinFigure14.Therevenuesareenteredwith$symbolsundereach
nodenumber,indicatingtherevenueifthenodeisbeingvisited.Thecostisassumedtobe1$foreach
minuteoftraveltime,sowehaveacommonunitofmeasurementintheobjective.Observethatnode
10andnode28havenorevenues,andarethereforeobviouscandidatesfornovisits.
Figure14RelabelledstreetplanforMBTSP
1 -$60 2 -$60 3 -$60 4 -$60 5 -$60 6
$90 $80 $70 $60 $50 $40
111
Fulltitleofthepresentarticle:doubleclicktoeditthis
Figure15ClosedMBTSPflowformulationinaspreadsheet,rows66119arehidden
112
InternationalReviewofEconomicsEducation
Table5:FormulasforspreadsheetinFigure15
Cell Formula Copiedto Name/Task
B63 =C3 B64:B122 Reversearcs:stopstart
C63 =B3 C64:C122 Reversearcs:startstop
D63 =D3 D64:D122 Reversearcs:copycosts
D123 =SUMPRODUCT(D3:D122;E3:E122) Computingcosts
=IF(OR(B3=1;C3=1);0;INDEX($K$3:$K$38;B3)
F3 F4:F122 Eq16(LHS)
INDEX($K$3:$K$38;C3)+$H$37*E3)
I39 =SUMPRODUCT(I3:I38;J3:J38) Computingrevenues
I40 =I39D123 Eq19
L3 =SUMIF($C$3:$C$122;$H$3:$H$38;$E$3:$E$122) L4:L38 Eq20(LHS)
M3 =SUMIF($B$3:$B$122;$H$3:$H$38;$E$3:$E$122) M4:M38 Eq9(RHS)
E3:E122 Var_x
H36 Param_n_2
H38 Param_n
K4:K38 Var_u
J4:J38 Var_y
O3 =IF(J3=0;"";RANK(K3;$K$3:$K$38;1)) O4:O38 Apreliminaryrankofnodes
P3 =IF(J3=0;"";RANK(O3;$O$3:$O$38;1)) P4:P38 Rankofanodeinthetour
Q3 =MATCH(U3;$P$3:$P$38;0) Q4:Q38 Visitingsequence
Q39 =Q3 Lastleg,returntodepot
R3 =INDEX($U$3:$W$38;$Q3;2) R4:R39 Avisitednodesxcoordinate
S3 =INDEX($U$3:$W$38;$Q3;3) S4:S39 Avisitednodesycoordinate
Figure16SolversettingsforspreadsheetinFigure15
FromFigure15weseethatthesalesmanvisitsonly30ofthe36nodes,withanetprofitof$812.Notice
thatthetouractuallyincludesnode10with$0benefits,butskipnode13with$30inbenefits.Using
theStandardSolverittakesmorethanafullweekendtofindtheoptimalsolution.Anearlytestversion
ofExcel2010(TechnicalPreview)withthenewStandardSolverfinishedduringanovernightrun.Again,
anassignmentformulationapplyingafullnnmatrixofthexvariableswouldincludetoomany
variablesfortheStandardSolver.UsingthecommercialPSPV9.04,thesolutiontimeinExcelis9.06
secondsfortheflowformulation.Thisalsorevealsanalternativeoptimalsolution,visiting32nodes.
Thesolutiontimewhentheassignmentformulationisimplementedis11.45seconds,onthesame
113
Fulltitleofthepresentarticle:doubleclicktoeditthis
computer.Intheassignmentformulationacompletegraphisassumed,andtheextravariablesare
eliminatedbyextraconstraints,therebyincreasingthesolutiontime.
UnfortunatelytheMTZSEQsused(16)(17)assumesnode1tobethedepot.Thereforewecannot
applythistypeofSECifourgoalistofindtheoptimallocationforthedepot.
14. PitfallsusingMTZSECs
Foraclosedtourthestartingnodecanalwaysbechosenarbitrarily,ifallnodeshavetobevisited.
Unfortunately,whenapplyingtheMTZSECs,thesolutionmaydependuponwhichnodehasbeen
selectedasthestartnode.Whendoweneedtostayalert?
15. Noncompletegraphsrequiringmultiplevisits
TakealookatFigure17.Twoidenticalgraphsaredisplayed,exceptthatnode1and2havebeen
renumbered.Youcaneasilyfindtheoptimalsolutionbyvisualinspection.Tryingtosolveoneofthem
fails,whereastheothersucceeds,iftheMTZSECsareappliedinaclosedTSP.Therearetwoother
nodesthatcouldberenumberedasnumber1.Noneofthemwillsucceedifwetrytosolveusingthe
MTZSECs.
Figure17TSPinanoncompletegraph,requiringmultiplevisitsinaclosedtour
5 5 4
4
4 4
4.47 4.47
3 4 3 4
2 2
1 1 3 1 2
3 2 2 3 1 2 3
1 2 3 4 5 6 1 2 3 4 5 6
Sincethisisanoncompletegraph,aspreadsheetlayoutsimilartoFigure7isprobablymostefficient,
skippingequation(18),asitishardlyneeded.
16. Thetriangleinequalityisnotalwayssatisfied
HavealookatthecostmatrixesinTable6.Theonlydifferenceisthatoncemorethenodes1and2
havebeenrenumbered.Thisisacompletegraph,asthereisadirectlinkbetweenanynodetoevery
othernode.
114
InternationalReviewofEconomicsEducation
Table6:Identicalcostmatrixesofacompletegraph,thetriangleinequalitydoesnotapply
cij 1 2 3 4 5 cij 1 2 3 4 5
1 - 2 3 4 5 1 - 5 130 140 150
2 5 - 130 140 150 2 2 - 3 4 5
3 4 123 - 40 50 3 123 4 - 40 50
4 3 124 34 - 45 4 124 3 34 - 45
5 2 135 35 54 - 5 135 2 35 54 -
Solvingoneofthemusingtheflowformulation(7)(10)andtheMTZSECs(16)(17)returnsa
solutionwithaminimalcostof209,visitingeverynodeonce.Solvingtheotherreturnsaminimumcost
of28,visitingfourofthenodesonceandvisitingonenodefourtimes.Thenumberingofthenodeshas
thusagreatimpactonwhichsolutionisobtained.Theassignmentformulationwouldreturna
minimumcostof209insteadof28.SeealsoLeeandRaffensperger(2006)forusingAMPLteachingTSP,
wheretheDFJSECsarebeingimplemented.
ForacompletegraphaspreadsheetlayoutsimilartoFigures9to11isprobablymostefficient,skipping
columnsAOARandtheplot,sincenocoordinatesaregiveninthisexample.
17. Conclusion
SolvingTSPusinggeneralpurposeoptimisationtoolslikeMIPsolversinspreadsheetshasbeen
regardedpracticalonlyforproblemsofasmallsize.Recentadvancementsinthesetypesofsoftware
haveincreasedthislimit;problemsofsize358ofnoncompletegraphshavebeensolvedinlessthan10
minutes.
SuchgeneralpurposeoptimisationtoolsalsoallowforagreatervarietyoftypesofTSP,whereas
proceduresdesignedspecificallyforTSPoftenrestricttheproblemtoalimitednumberofvariants.In
fact,wemayoverlookthebestsolutionbyapplyingthestandardapproachusingtheassignment
formulationorthesespecifictoolsforsolvingTSP.Wemustbeabsolutelysureourproblemformulation
isvalidallrelevantcostsandrevenueshavetobeconsidered,andtheconstraintsmustnotbetoo
limiting.Otherwisewemayendupsolvingthewrongproblem.Anticipatingaspecifictypeofsolution
whenformulatingtheproblemislikestartingatthewrongend,andmayleadtoapoorresult.
However,theSECsneededinaTSPformulationmayhaveunfortunateconsequencesandlimitations.
WhenusingtheMTZSECs,theselectionofthebasenodecanbecritical,evenforaclosedtourina
completegraph.Itmayalsoprohibitasolution,eveninaconnectedgraph.
Wehavefurtherseenthatformulationmattersincludingnonexistingvariablesandeliminatingthem
byaddingnonexistingconstraintscanbothincreasesolutiontimeandcauseproblemsinfindingthe
optimalsolution(thenumberofvariablesorconstraintsmayevenbecometoobigforthesolver).A
wideformulationwillalwaysincludetheoptimalsolution.Atightformulationmayhelpfindingthe
optimalsolution,butmayalsoexcludetheoptimalsolution.Atightformulationmayreduceor
increasethesolutiontime,thisdependsonthetypeofsolverusedandtheproblemathand.
Toplaysafeawideformulationseemslikeagoodstrategy.Ifthegraphisnotcompleteorthetriangle
inequalitydoesnotapply,bothimplysituationswheremultiplevisitsmayberequired,thena
replacementofthecostmatrixmaybeadvisable.Thenthecostsshouldbereplacedbyaminimumcost
matrix(youcanusetheshortestpathformulation(n1)2times),whichformanylinksmayinvolvea
lengthytourvisitingmanynodesfromnodeitonodej.TheTSPmodelcanthenbetight,whichmayor
maynotbehelpfulforsomesolvers.UnfortunatelytheTSPmodelwillthenalsobeblindeyed;ithasno
115
Fulltitleofthepresentarticle:doubleclicktoeditthis
realtrackofthetourorhowmanyvisitsareactuallybeingmadeateachnode.TheTSPsolutionthen
onlyindicatesthesequenceofthevisits,andignoresanyrevisits.
References
Chlond,M.J.(2008).Shashasgridspeedpuzzle,INFORMSTransactionsofEducation,Vol.9(1),pp.4652.
Availableonlineathttp://ite.pubs.informs.org/.
Dantzig,G.,Fulkerson,D.andJohnson,S.(1954).Solutionofalargescaletravelingsalesmanproblem,
OperationsResearch,Vol.2,pp.393410.
Gutin,G.andPunnen,A.P.(eds)(2007).Thetravelingsalesmanproblemanditsvariations,NewYork:
Springer.
LeeJ.,andJ.F.Raffensperger:(2006).UsingAMPLforteachingtheTSP,INFORMSTransactionson
Education,Vol.7(1),pp.3769.http://archive.ite.journal.informs.org/Vol7No1/LeeRaffensperger/
Malandraki,C.andDaskin,M.S.(1993).ThemaximumbenefitChinesepostmanproblemandthemaximum
benefittravelingsalesmanproblem,EuropeanJournalofOperationalResearch,Vol.65,pp.21834.
Miller,C.E.,Tucker,A..W.andZemlin,R.A.(1960).Integerprogrammingformulationoftravelingsalesman
problems,JournalofACM,Vol.7,pp.3269.
Pataki,G(2003).Teachingintegerprogrammingformulationsusingthetravelingsalesmanproblem,SIAM
Review,Vol.45(1),pp.11623.
Ragsdale,C.T.(2001).SpreadsheetModelingandDecisionAnalysis,Cincinatti:SouthWesternCollege
Publishing.
AuthorBiography
RasmusRasmussensteachingexperienceismostlyinthefieldsofbusinesseconomics,financeand
managementscience.Hisresearchinterestsareinthefieldsofappliedmanagementsciencerelatedto
problemsinbusinesseconomics,quiteoftenusingspreadsheets,thetoolfrequentlyusedalsoin
teaching.
Contactdetails
RasmusRasmussen
MoldeUniversityCollege
P.O.Box2110
6402Molde,Norway
Tel:+4771214242
Fax:+4771214100
rasmus.rasmussen@himolde.no
116