Вы находитесь на странице: 1из 13

EECS281Fall2013Project4

2013:AMartianOdysseyv1.3
DueSundayDecember8th11:55pm
Overview
WelcometotheplanetMars!Asthenewestmemberoftheexplorationteam,youhavebeen
taskedwithplanningtheexpansionofourgroundfacilitiesandprogrammingthenextstagesof
surfaceexploration.
YourfirsttaskinPartAistoplananetworkofroadsconnectingourexistingresearchbases
efficiently.TheninPartB&C,youwilldeviserouteplansforanunmannedMarsexploration
rover(MER)toreachandcollectsamplesfromgeologicalfeaturesourgeologistsatground
controlhavedeemedofhighscientificvalue.Thesecouldbearangeofrocksandsoilsthatmay
holdcluestopastclimateactivityonMars,andtheyarelocatedatavarietyofelevations.
Theroverislaunchedfromoneoftheresearchstationsandaftercollectingallsamples,the
roverwillreturntothestationsothesamplescanbeanalyzed.Sinceyourroverhavelimited
poweronboard,youneedtominimizethedistancetobetravelledandtheamountofuphill
traversesinceitincursadditionalpowerdrain.
Tobeclear,thesescenariosareseparate,yourprogramwillcreateaplanforoneorthe
other,butnotbothinthesamerun(althoughyoumayfindthatthealgorithmsfromonemode
helpwithanothermode).
ProjectGoals
UnderstandandimplementMSTalgorithms.BeabletodeterminewhetherPrimsor
Kruskalsismoreefficientforaparticularscenario.
UnderstandandimplementaBranchandBoundalgorithm.Developafastandeffective
boundingalgorithm.
Explorevariousheuristicapproachestoachievinganearlyoptimalsolutionasfastas
possible(PartC).
Useofgnuplotforvisualization
MapInput
Onstartup,yourprogram,mars,readsinputfromstandardinput(cin)describingalistof
locations(denotingresearchbasesinpartA,locationsofrock/soilsamplesinpartBandC).The
Martianterrainismappedonagrid.YouwillbegivenalistofMlocationswithassociatedinteger
coordinates(x,y,z).Thelocationsareordered(thefirstcoordinateyoureadcorrespondsto
location0,thesecondcoordinatetolocation1),andareindexed.TheMERalwaysstartsatthe
0thlocationwhichisthehomebaseoftherover.
Formally,theinputwillbegivenbyMthenumberoflocationsbyitselfonaline,followedbyalist
ofx,y,zcoordinatesintheform:xyz(withouttheapostrophes),wherezistheelevationof
thelocation.Youmayassumethattheinputwillalwaysbewellformed(itwillalwaysconformto
thisformatandyoudonotneedtocheckforerrors).Theremaybeblanklinesattheendofthe
filebutnowhereelse.
Sampleinput:
5
430
051
722
381
210
Theabovesamplecanbevisualizedasfollows,wherethenumbersshownaretheposition
indices,

Note:Therearemanywaystorepresentthisconfigurationinternallyinyourprogram,
andthiswillaffectyourruntime.Chooseyourdatastructureswisely!
MovementRules
Distance:
Werepresentthepathbetweenresearchbasesandgeologicalfeaturelocationsasasequence
ofpoints.Forsimplicity,thedistancebetweeneachpairofpointsshouldbecalculatedusing
Manhattandistance.Youshouldrepresentyourdistancesasintegers.Iftheroverisheading
fromP(x1,y1,z1)toQ(x2,y2,z2),thedistanceisgivenby:
Manhattandistance=|x2x1|+|y2y1|+|z2z1|
Youarenotallowedtowraparoundtheedgesoftheworld(youcannotgoabovethetopofthe
maptoarriveatthebottom).
CommandLineInput
Yourprogram,mars,shouldtakethefollowingcasesensitivecommandlineoptions:
m,modeMODE
Thiscommandlineoptionmustbespecified,ifitisnot,printausefulerrormessagetostandard
error(cerr)andexit(1).MODEisarequiredargument.SettheprogrammodetoMODE.MODE
mustbeoneofMST,OPTTSP,orFASTTSP.TheMODEcorrespondstowhatalgorithmmars
runs(andthereforewhatitoutputs).
h,help
Printashortdescriptionofthisprogramanditsargumentsandexit(0).
Validexamplesofhowtoexecutetheprogram:
marsmodeMST(OK)musttypeinputbyhandno<redirect
marsh<inputFile.txt(OK,hhappensbeforewerealizetheresnom)
marsmOPTTSP<inputFile.blah(OK)
marsmBLAH(BAD)
(Rememberthatwhenweredirectinput,itdoesnotaffectthecommandline.Redirectinginput
justsendsthefilecontentstocin.Youshouldnothavetomodifyyourcodetoallowthistowork,
theoperatingsystemwillhandleit.)
Wewillnotbespecificallyerrorcheckingyourcommandlinehandling,howeverwe
expectthatyourprogramconformswiththedefaultbehaviorofgetopt_long.Incorrect
commandlinehandlingmayleadtoavarietyofdifficulttodiagnoseproblems.
Algorithms
Yourprogramshouldrunoneandonlyoneofthefollowingmodesatruntimedependingonthe
modeoptionforthatparticularprogramcall.Wedivideitintopartsforyourconvenience,though
youmayfindthatelementsandalgorithmsofsomepartscanhelpwithothers.
PartAResearchbaseroadplanning(MSTmode)
WhenrunintheMSTmode,yourprogramshouldreturnanetworkofroadsoftheminimaltotal
distancewhichconnectsalltheresearchbases,whichshouldbeaminimalspanningtreewith
vertices=baselocations,andedges=theroadsyouplantobuild(edgeweight=manhattan
distance).YoumayuseeitherPrimsorKruskallstodothis,thoughoneofthemwillprove
faster.Hint:Unlessyouwanttoimplementbothandcompare,thinkaboutthenatureofthegraph
(howmanyverticesandedgesdoesithave?).Youarefreetoadaptcodefromthelectureslides
tofitthisproject,butyouwillwanttocarefullythinkaboutthedatastructuresnecessarytodo
eachpart(storingunnecessarydatacanslowyoudown).Yourprogrammustalwaysgenerate
onevalidMSTforeachinput.
OutputFormat
ForMSTmode,youshouldprintthetotalweightoftheMSTyougeneratebyitselfonthefirstline
thisweightisthesumoftheweightsofalledgesinyourMST(whichwouldbeManhattan
distances).YoushouldthenprintalledgesintheMST.Alloutputshouldbeprintedtostandard
output(cout).
Theoutputshouldbeoftheformat:
totalWeight
nodenode
nodenode
...
wherethenodesarethelocationindices(orderedbyinputorder)correspondingtothevertices
oftheMST.EachlinethatcontainsapairofnodesdescribesanedgeintheMSTfromthefirst
nodetothesecond.Forexample,givenaparticularinputfile(nottheoneabove),yourMST
modeoutputmightbe:
22
03
02
12
Youshouldalsoalwaysprintthepairsofverticesthatdescribeanedgesuchthattheoneonthe
lefthasasmallerintegervaluethantheoneontheright.Inotherwords:
12
ispossiblevalidoutput
21
isnot.
PartsB&CRoverExplorationPlanning(OPTTSP&FASTTSP)
Yourtaskistofindashortest/lowestenergycostpathforyourrovertotravelfromhomebase,
reacheachsamplelocation,andreturntobase.ThisisbasicallyaTravelingSalesmanProblem
(TSP).
ForOPTTSPmode,youmustfindanoptimalsolutiontotheTSP(theactualminimumdistance
necessary).ForFASTTSPmode,youdonotneedtoproduceanoptimalresult,butyour
solutionshouldbeclosetooptimal.BecauseyourFASTTSPalgorithmdoesnotneedtobe
perfectlyoptimal,weexpectittorunmuchfaster.MoreonthedifferencesbetweenOPTTSP
andFASTTSPmodeswillbediscussedlaterinthespec.
Forbothmethods:
Yourroverstartsfromhomebase,the0thlocationininput.
Yourrovervisitseachsamplinglocationexactlyonce(there'snopointinreturningtoaplace
alreadysampled),exceptwhenitreturnstothehomebase.
Thetotalenergycostoftherouteisdefinedasthetotaldistancestravelled(sumofdistanceof
alltraversededges),usingManhattandistanceasspecifiedearlier.
Yourprogrammustprinttheindicesofthesamplinglocationsinanordersuchthatthetotal
lengthofthisrouteplanisassmallaspossible.Moredetailsbelow.
OutputFormat(bothPartsBandC)
Youshouldbeginyouroutputbyprintingtheoveralllengthofyourtour(therouteplanforthe
rover)onthefirstline.Onthenextline,outputthelocationindicesintheorderinwhichyouvisit
them.Theinitiallocationshouldbethehomebase(0)andthelastshouldbethelocationdirectly
beforereturningtohomebase.Thelocationindicesshouldbeseparatedbyasinglespace.After
thelastlocationindex,thefileshouldendwithanewlinecharacter(withnospacebetweenthe
lastlocationandthenewline).Alloutputshouldbeprintedtostandardoutput(cout).
Belowisoutputcorrespondingtothesampleinput.
Input:
5
430
051
722
381
210
Output:
50
04231
or
50
01324
ForPartB:OPTTSP
Tofindanoptimaltour,youcanstartwiththebruteforcemethodofexhaustiveenumerationthat
evaluateseverytourandpicksasmallesttour.Bystructuringthisenumerationinacleverway,
youcoulddeterminethatsomebranchesofthesearchcannotleadtooptimalsolutions.For
example,youcouldcomputelowerboundsonthelengthofanyfulltourthatcanbefoundina
givenbranch.Ifsuchalowerboundexceedsthecostofafullsolutionyouhavefoundpreviously,
youcanskipthisbranchashopeless.Ifimplementedcorrectly,suchabranchandbound
methodshouldalwaysproduceanoptimalsolution.Itwillnotscaleaswellassortingor
searchingalgorithmsdoforotherproblems,butitshouldbeusablewithasmallnumberof
locations.Cleveroptimizations(identifyinghopelessbranchesofsearchearly)canmakeita
hundredtimesfaster.DrawingTSPtoursonpaperandsolvingsmalllocationconfigurationsto
optimalitybyhandshouldbeveryuseful.Rememberthatthereisatradeoffbetweenthe
timeittakestorunyourboundingfunctionandhowmanybranchesthatboundletsyou
prune.
GivenaninputsetofNlocationsdefinedbyintegercoordinates,produceanoptimaltourusing
branchandboundalgorithms.Yourprogramshouldalwaysproducetheshortestpossibletour
asasolution,evenifcomputingthatsolutionistimeconsuming.Youwillbegivena30second
cputimelimit.Ifyourprogramdoesnotproduceavalidsolution,itwillfailthetestcase.
ForPartC:FASTTSP
Forlargenumberofsamplinglocationsitmightbegoodenoughtogenerateagoodenough
routeplanfortheroverinsteadoftheoptimalone.Youcanuseheuristicstofindnearoptimal
tours.Aheuristicisanalgorithmthatcanproduceagoodanswerthatisnotnecessarilythebest
answer.Forexample,youcanskipabranchspeculativelyratherthanwaitingtoknowforafact
thatitcanbeskipped.Therearemanyothersimpleheuristics,suchasstartingwitharandom
tourandtryingtoimproveitbysmallchanges.
YoushouldbeabletoproduceasolutiontotheTSPwithina15secondcputimelimitthatisas
closeaspossibletotheoptimaltourlength,itdoesnotneedtobeoptimal.Inthebestcase,
theproducedtourlengthwillequaltotheoptimaltourlength.
Youareallowedtouseanycombinationofalgorithmsforthissectionthatwehavecoveredin
class,includingtheMSTalgorithmyouwroteforPartAandthebranchandboundalgorithm
fromPartB.(SeeAppendixAforsuggestions)
Youneedtobecreativewhendesigningyouralgorithmsforthissection.Youarefreeto
implementanyotheralgorithmyouchoose,solongasitmeetsthetimeandmemory
constraints.However,youshouldnotuseanyadvancedalgorithmsorformulas(suchas
SimulatedAnnealing,GeneticAlgorithmsandTabusearchtheyaretooslow)thatare
significantlydifferentfromwhathasbeencoveredinclass.Instead,creativelycombinethe
algorithmsthatyoualreadyknowandcomeupwithconciseoptimizations.
LibrariesandRestrictions
WehighlyencouragetheuseoftheSTLforthisprojectwiththeexceptionoftwoprohibited
features:
TheC++11regularexpressionslibrary(whoseimplementationingcc4.7isunreliable)andthe
thread/atomicslibraries(whichspoilruntimemeasurements).Donotuseotherlibraries(e.g.,
boost,pthreads,etc).
TestingandDebugging
Partofthisprojectistoprepareseveraltestcasesthatwillexposedefectsinbuggysolutions
yourownorsomeoneelses.Asthisshouldbeusefulfortestinganddebuggingyourprograms,
westronglyrecommendthatyoufirsttrytocatchafewofourintentionallybuggysolutions
withyourtestcases,beforecompletingyoursolution.Theautograderwillalsotellyouifoneof
yourowntestcasesexposesbugsinyoursolution.
Eachtestcaseshouldconsistofaninputfile.Whenwerunyourtestcasesononeof
intentionallybuggyprojectsolutions,wecomparetheoutputtothatofacorrectprojectsolution.
Iftheoutputsdiffer,thetestcaseissaidtoexposethatbug.
TestcasesshouldbenamedtestnMODE.txtwhere0<n<=10.Theautogradersbuggy
solutionswillrunyourtestcasesinthespecifiedMODE.
Yourtestcasesmayhavenomorethan10linesinanyonefile.Youmaysubmitupto10test
cases(thoughitispossibletogetfullcreditwithfewertestcases).Notethattheteststhe
autograderrunsonyoursolutionareNOTlimitedto10linesinafileyoursolutionshouldnot
imposeanysizelimits(aslongassufficientsystemmemoryisavailable).
SubmittingtotheAutograder
Doallofyourwork(withallneededfiles,aswellastestcases)insomedirectoryotherthanyour
homedirectory.Thiswillbeyour"submitdirectory".Beforeyouturninyourcode,besurethat:
Youhavedeletedall.ofilesandyourexecutable(s).Typingmakecleanshallaccomplish
this.
YourmakefileiscalledMakefile.TypingmakeRrbuildsyourcodewithouterrorsand
generatesanexecutablefilecalledmars.(NotethatthecommandlineoptionsRandrdisable
automaticbuildrules,whichwillnotworkontheautograder).
YourMakefilespecifiesthatyouarecompilingwiththegccoptimizationoptionO3.Thisis
extremelyimportantforgettingalloftheperformancepoints,asO3canspeedupcodebyan
orderofmagnitude.
YourtestcasefilesarenamedtestnMODE.txtandnootherprojectfilenamesbegin
withtest.Upto10testcasesmaybesubmitted.
Thetotalsizeofyourprogramandtestcasesdoesnotexceed2MB.
Youdon'thaveanyunnecessaryfiles(includingtemporaryfilescreatedbyyourtexteditor
andcompiler,etc)orsubdirectoriesinyoursubmitdirectory(i.e.the.gitfolderusedbygitsource
codemanagement).
Yourcodecompilesandrunscorrectlyusingversion4.7.0oftheg++compiler.Thisis
availableontheCAENLinuxsystems(thatyoucanaccessvialogin.engin.umich.edu).Evenif
everythingseemstoworkonanotheroperatingsystemorwithdifferentversionsofGCC,the
coursestaffwillnotsupportanythingotherthanGCC4.7.0runningonLinux(studentsusing
othercompilersandOSdidobserveincompatibilities).Note****:Tocompilewithg++version
4.7.0onCAENyoumustputthefollowingatthetopofyourMakefile:
PATH:=/usr/um/gcc4.7.0/bin:$(PATH)
LD_LIBRARY_PATH:=/usr/um/gcc4.7.0/lib64
LD_RUN_PATH:=/usr/um/gcc4.7.0/lib64
DonotcutandpastetheabovelinesfromthisPDFprojectspecfileitwillNOTwork.PDFfiles
usestrangenonASCIIcharactersforhyphens.
Turninallofthefollowingfiles:
Allyour.handor.cppfilesfortheproject
YourMakefile
Yourtestcasefiles
Youmustprepareacompressedtararchive(.tar.gzfile)ofallofyourfilestosubmittothe
autograder.Onewaytodothisistohaveallofyourfilesforsubmission(andnothingelse)inone
directory.Inthisdirectory,run
dos2unixU*tarczf./submit.tar.gz*.cpp*.hMakefiletest*.txt
Thiswillprepareasuitablefileinyourworkingdirectory.
Submityourprojectfilesdirectlytoeitherofthetwoautogradersat:
https://g2811.eecs.umich.edu/orhttps://g2812.eecs.umich.edu/.Notethatwhenthe
autogradersareturnedonandacceptingsubmissions,therewillbeanannouncement
onPiazza.Theautogradersareidenticalandyourdailysubmissionlimitwillbeshared(andkept
trackof)betweenthem.Youmaysubmituptofourtimespercalendardaywithautograder
feedback.Forthispurpose,daysbeginandendatmidnight(AnnArborlocaltime).Wewillcount
onlyyourlastsubmissionforyourgrade.Partoftheprogrammingskillisknowingwhenyouare
done(whenyouhaveachievedyourtaskandhavenobugs)thisisreflectedinthisgrading
policy.Werealizethatitispossibleforyoutoscorehigherwithearliersubmissionstothe
autograderhoweverthiswillhavenobearingonyourgrade.Westronglyrecommendthatyou
usesomeformofrevisioncontrol(ie:SVN,GIT,etc)andthatyoucommityourfileseverytime
youuploadtotheautogradersothatyoucanalwaysretrieveanolderversionofthecodeas
needed.PleaserefertoyourdiscussionslidesandCToolsregardingtheuseofversioncontrol.
Pleasemakesurethatyoureadallmessagesshownatthetopsectionofyour
autograderresults!Thesemessagesoftenhelpexplainsomeoftheissuesyouare
having(suchaslosingpointsforhavingabadMakefileorwhyyouaresegfaulting).Also
besuretonoteiftheautogradershowsthatoneofyourowntestcasesexposesabug
inyoursolution(atthebottom).
Grading
90pointsYourgradewillbederivedfromcorrectnessandperformance(runtime).Thiswillbe
determinedbytheautograder.Onthisprojectweexpectamuchbroaderspreadofruntimes
thanonpreviousprojects.Therefore,wemayadjusttheruntimesensitivecomponentofthe
scoreforseveraldays,butwillfreezeitafewdaysbeforethedeadline.Aswithallprojects,the
testcasesusedforthefinalgradingarelikelytobedifferent.
10pointsTestcasecoverage(effectivenessatexposingbuggysolutions).
Wealsoreservetherighttodeductupto5pointsforbadprogrammingstyle,codethat
isunnecessarilyduplicated,etc.
RefertotheProject1specfordetailsaboutwhatconstitutesgood/badstyle.
RuntimeQualityTradeoffs
Inthisprojectthereisnosinglecorrectanswer(unlikepreviousprojects).Accordingly,the
gradingofyourproblemwillnotbeassimpleasadiff,butwillinsteadbearesultofevaluating
youroutput.
ForPartCinparticular,weexpecttoseegreatervariationinstudentoutput.PartCasksyouto
solveahardproblem,andwiththegiventimeconstraints,wedontactuallyexpectyouroutputto
beoptimalforallcases.Thequalityofyoursolutionsmayevenvaryfromcasetocase.Wewant
youtoquicklyproducesolutionsthatareclosetooptimal.Thisinevitablycreatestradeoffs
betweensolutionoptimalityandruntime.
Forgrading,wewillimposeauniformtimebudgetof15secondsforallPartCtestcases.This
budgetdoesnotdependonthesizeoftheproblems.Thisfixedbudgetmeansthatyoumayfind
itusefultoimplementmorethanonealgorithmorheuristicthatyouuseinPartCandchoose
whichonetoinvokebasedontheinputsize.Inotherwords,forsmallertestcases,youcanuse
aslower,butmorethoroughsearchalgorithm.
HintsandAdvice
ItwillbedifficulttogetthisprojectrightwithoutvisualizingyourMSTsandTSPtours.We
recommendthatyouusegnuplot(availableonLinuxsystems)yourC++programcan
produceascriptforgnuplot(withpointdataembedded),butyoucanuseanyothertool,suchas
Exceltoachievesimilarresults.Wehaveprovidedasamplescriptforshowinghowtouse
gnuplotinthecontextofthisprojectinResources/Projects/SupplementaryMaterialonctools.
Oneofthefirstvisualchecksyoucanperformperform:ifyourTSPtourselfintersects,thenits
notoptimal(whynot?canthisideabeusedforoptimizationalgorithms?).
Runningyourcodelocallyinvalgrindcanhelpyoufindandremoveundefined(buggy)behavior
andmemoryleaksfromyourcode.Thiscansaveyoufromlosingpointsinthefinalrunwhen
youmistakenlybelieveyourcodetobecorrect.
Itisextremelyhelpfultocompileyourcodewiththefollowinggccoptions:WallWextraWvla
Wconversionpedantic.Thiswaythecompilercanwarnyouaboutpoorstyleandpartsofyour
codethatmayresultinunintended/undefinedbehavior.
Makesurethatyouareusinggetopt_longforhandlingcommandlineoptions.
AppendixA
OnepossibleheuristicistoconstructastartingpointforyourTSPtourbyfollowingMSTedges
andskippingpreviouslyvisitedvertices.Byusingthistechniquecorrectly,youcanfindatourthat
isguaranteedtobenomorethantwicetheoptimalsolutionslength(andusethis2xcheckfor
debugging).Youcanthenusethisstartingpointtomakeadjustmentsanddobetter.
CornerCuttingalgorithmillustrated
Supposelocationsaredistributedinaninputmapasshownbelow:

BelowisanMSTthatwouldbeformedfromtheabovelocations.

BelowisapathtakenbystrictlyfollowingtheedgesoftheMST.

However,bycuttingcorners,aneffectiveTSPsolutioncanbegenerated.Thisispossible
becauseonceavertexisvisited,itwillnotbevisitedagain.Intheabovepaththatstrictlyfollows
theedgesoftheMST,themiddlevertexisvisitedfourtimes(visitedafteranoutervertexis
visited).Ifthemiddlevertexisskippedafterthefirstvisit,aTSPtourshownbelowisachieved.

Thereasonwebringupthistwicearoundthetreeheuristicistostatethetheoremthatthe
resultingtoursarenoworsethan2xtheMSTcost.
Thefollowingisanexplanation/proofsketchforthe2xbound:
IfyouperformaDFStraversalofatreeandreturntotheinitialnode,youhavevisitedeveryedge
exactlytwice("goingin"and"returning"),sothisgivesyouexactlydoublethecost/lengthofthe
MST(thefactthatthetreeisminimalisnotimportantforthelogicoftheproofthisworksfor
anytree).Sincethetreeisspanning,youhavevisitedalllandmarks.Theonlyproblemwiththis
twicearoundthetreeselfintersectingpathisthatit'snotatour.Itcanbeturnedintoatourby
takingshortcuts(i.e.,takingshortcutsisimportantnotonlytoreducethelength).
Whenconsideringotherheuristics,notethat:
1.ThetheoremallowsyoutoupperboundthecostofoptimalTSPtoursbasedonMSTlength.
2.ThetheoremhasaconstructiveproofaheuristicthatalwaysproducesTSPtoursthat
satisfythisupperbound[2].
Asaconsequence,yourheuristicshouldalsosatisfythe2xupperboundifnot,youcanjust
implementthetwicearoundthetreeheuristic.However,wedonotrequirethisbecausethere
aremuchbetterheuristicsonesthatarefasterandproducebetterresults.
AppendixB
BemindfulofhowyoukeeptrackofyourruntimeinPartCcallingsystemfunctionstocheckthe
timecanbeexpensiveandshouldbedonesparingly.Togiveananalogy:
Let'ssayyouaretryingtomakeittoadeadline.So,asyouwork,youlookatyourwatchevery
nowandthen.Atsomepoint,yourealizethatyouarespendingmostofyourtimelookingatthe
watchandmakingverylittleprogress.So,youdecidetothrowthewatchawaytosavetime.Is
thisagoodidea?No,becauseyouwon'tbeabletotracktimeaccurately.Agoodsolutionisto
onlylookatthewatcheveryfewminutes(sothatthemajorityofyourtimeisspentonyourwork)
andtomakesureyouaredoneafewminutesbeforethedeadline.
[1]
Credits:DonWinsor,ErikBrinkman,JieSong,QiYang,SauravLohani,SpencerKim
[2]
Suchheuristicsarealsocalledapproximationalgorithms.

Вам также может понравиться