Frisch Brahim Hnich Chris Je64256erson Ian Miguel School of Computer Science University of St Andrews UK Arti64257cial Intelligence Group Dept of Computer Science University of York UK Department of Computer Engineering Izmir University of Econom ID: 43237
Download Pdf The PPT/PDF document "Conjure Revisited Towards Automated Cons..." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
givenitem_count,capacity:intlettingitembedomainint(1..item_count)givenvolume,value:function(total)item-int(1..)findx:setofitemmaximisingsumielemx.value(i)suchthat(sumielemx.volume(i))capacity Fig.1.Theknapsackproblem,giveninEssence decisionvariablesintomodelsintheEssence0solver-independentmodellinglanguage.ThisworkwasfurtherdevelopedbyFrischandMartinez-Hernandez[12],wholookedindepthattheissuesinvolvedinchannelingecientlybetweenmanydierentrepresentationsofhigh-levelvariables.ThispaperdescribesanewapproachtotheimplementationofConjure,withamuchgreatercoverageoftheEssencelanguageandfewerlimitationsontherewriterulessuchastherequirementoftheIJCAIprototypeto attenanEssencespecicationbeforeapplyingtherewriterules.2BackgroundEssenceisalanguageforspecifyingcombinatorial(decisionoroptimisation)problems(foradetaileddescriptionsee[5]).Itismotivatedbyadesiretoallowuserstowritedownproblemswithoutmakingconstraintmodellingdecisions.Tothisend,ithasahighlevelofabstraction,supportingdecisionvariableswhosetypesmatchthecombinatorialobjectsproblemstypicallyaskustond,suchas:sets,multisets,functions,relationsandpartitions.Thekeyadvancerepresentedbythelanguageisitssupportforthenestingofthesetypes,allowingdecisionvariablesoftypesetofsets,multisetofsetsoffunctionsetc.Hence,problemssuchastheSocialGolfersProblem[6],whichisnaturallyconceivedofasndingasetofpartitionsofgolferssubjecttosomeconstraints,canbespecieddirectlywithouttheneedtomodelthesetsorpartitionsasmatrices.Concomitantwiththedecisiontosupportabstractconstraintspecicationsistherequirementtotransformthesespecicationsintoconstraintmodels.To-day'sconstraintsolverstypicallysupportdecisionvariableswithatomictypes,suchasintegerorBoolean,havelimitedsupportformorecomplextypeslikesetsormultisets,andnosupportfornestedcomplextypes.Hence,abstractspecica-tionsmustberenedintoconstraintmodelssuitableforconstraintsolvers.Thisisachievedbymodellingabstractdecisionvariablesasconstrainedcollectionsofvariablesofmoreprimitivetype.TheConjuresystem,rstpresentedinprototypeformin[4],employsasystemofrewriterulestoreneEssencespecicationsintoconstraintmodelsinEssence0[17],alanguagederivedfromEssencemainlybyremovingfacilitiesforabstractionandaddingfacilitiescommontoexistingconstraintsolversandtoolkits.FromEssence0atoolsuchasTailor[17]canbeusedtotranslatethe Representation Therearetwofundamentaldecisionstobemadeinformu-latingaconstraintmodel.Therstisastotheviewpoint(thechoiceofdecisionvariablesandtheirdomains[9]),andthesecondisthechoiceofconstraintsonthosedecisionvariables.TheConjureprototypeinterleavedthesetwodecisionsinaconstraint-wiserenementprocess[4].Bycontrast,theversionofConjuredescribedhereinexploresallpossibleviewpointsrstbeforeconstraintrenement.ThisphasetakesanEssencespecica-tionandgeneratesasetofspecications,oneperpossiblecombinationofvariablerepresentationdecisions.Ifavariableappearsinmorethanoneconstraint,itispossibleforthatvariabletoberepresentedindierentwaysindierentconstraints,incasethemostecientwayofrepresentingacomplexdecisionvariablediersamongtheconstraintsitappearsin.Ifavariableisrepresentedinmorethanonewayinaspecication,channellingconstraintsbetweenthetwo(ormore)representationsareaddedautomaticallyinPhase5. Auto-Channelling Ifwechoosemorethanonewayofrepresentingacom-binatorialobjectwithinaspecication,weautomaticallyaddchannellingconstraints[12]betweendierentrepresentationsofthesamevariableinthisphasetomaintainconsistency. Addingstructuralconstraints Inthisphaseweaddallnecessarystructuralconstraintsforeverydecisionvariableinthespecication.Thestructuralconstraintforarepresentationofadecisionvariablemakessuretheselectedrepresentationactuallyrepresentsavalidcombinatorialobjectwiththein-tendedproperties(e.g.ensuringthattheelementsofasetaredistinct).Weaddtheseconstraintsbeforerewritingbecausetheywillbeaddedregardlessoftherestofthespecicationandtheyonlydependontherepresentationofacombinatorialobject.4Non-deterministicRewritingWeemployatermrewritingsystemtoreneEssencespecicationsintothetargetlanguageEssence0.Generally,rewriterulescanbethoughtofaspartialfunctions,whichmapfromasubtermtoanequivalentsubterm[14].Givenasetofrewriterulesandaterm,arewritesystemrepeatedlyappliestherulesuntilnofurtherrulescanbeapplied.Thetermisthensaidtobeinnormalform.Inordertoproducealternativemodelswewishtogeneratenotasinglenormal-formterm,butallnormal-formtermsattainablebyapplyingthegivenrulestotheinputterm.Hence,weadjustthedenitionofarewriterule:insteadofafunctionthatmapsfromasubtermtoanequivalentsubterm,wedenearewriteruletobeafunctionthatmapsfromasubtermtoasetofsubterms.Asingleruleisnowsucienttorepresentthewholeruledatabase.Thissingleruleisaone-to-manymappingfromasubtermtothesetofrewritesofthatsubterm.Thisrepresentationisnaturalwhileapplyingtherules,butitisnotanaturalwaytowritethem.Itis,however,trivialtoautomatethecombinationofasetofpartialfunctionsintothesinglefunctionusedbytheimplementation.Forexamplewecancombinerule1,rule2andrule3inallRulesasfollows: asubseteqb;foralli:a.ielembguards:asetof,bsetof Fig.3.Anexamplerewriterule,ruleSetSubsetEq set,mset,function,relation,tuple.Someoftheavailableoperatorsarethefollowing:abs,+,-,*,/,%,=,!=,,]TJ/;ø 9;.962; Tf; 5.2;̄ ; Td;[000;,,=]TJ;/F8 ; .96;& T; 10;.460; 0 ;Td[0;=,not,/\,\/,=]TJ;/F8 ; .96;& T; 10;.460; 0 ;Td[0;=,=000;,card,elem,union,intersect,subset,subseteq,supset,supseteq,max,min,forall,exists,sum,matrixindexing([]),tupleindexing(),functionapplication,functioninverseapplication,relationprojection.ItisusefultoviewourrulesasoperatinguponanAbstractSyntaxTree(AST)representationofanEssencespecication.IntheAST,everynoderepresentsaterminthespecicationandisalsolabelledwiththatterm'stype.TherewritingsystemworksbytraversingtheASTandattemptingtoapplytherulesinthedatabaseateverynode.Aruleisallowedtomodifythesubtreerootedatthecurrentnode,and,forcontextualinformation,isallowedtoaccess(butnottomodify)theremainderoftheASTviatheparentofthecurrentnode.Ifarulematchesthecurrentnode,thewholesubtreeisreplacedwiththeequivalentsubtreetherulesuggests.4.1ExampleRulesInthissectionwewillpresentanumberofexamplerulesrelatingtothere-nementofsetvariables.Thesewilldemonstraterulesshowinghowexpressionsinvolvingsetsarerewrittenandrened.Werstpresentaseriesofrulesthatdemonstratehowexpressionsinvolvingsetscanberewrittenintoexpressionsinvolvingsimpleroperators. a=b;asubseteqb/\bsubseteqaguards:asetof,bsetofruleSetEq:showsarulethatmatcheswithanequalityconstraintbetweentwosets.Itrewritestheequalityintoaconjunctionofmutualsubseteq'sbetweenthetwosets.Theguardsensureitonlyappliestosets. eelems;existsi:s.i=eguards:e,ssetofruleSetElem:showsarulethatmatcheswithanelemconstraintandrewritesitintoanexistentialquanticationovertheset. foralli:(aunionb).k;foralli:a.k/\foralli:b.kexistsi:(aunionb).k;existsi:a.k\/existsi:b.kforalli:(aintersectb).k;foralli:a(ielemb=k)foralli:(aintersectb).k;foralli:b(ielema=k)existsi:(aintersectb).k;existsi:a(ielemb/\k)existsi:(aintersectb).k;existsi:b(ielema/\k)guards:asetof,bsetof foralli:s.k;foralli:r.kkguards:ssetofint,refinement(s)occurrencedeclarations:m=matrixindexedby[dom]ofbooldom=domain(tau(s))kk=(m[i]=true)=kexistsi:s.k;existsi:r.kkguards:ssetofint,refinement(s)occurrencedeclarations:m=matrixindexedby[dom]ofbooldom=domain(tau(s))kk=(m[i]=true)/\ksumi:s.k;sumi:r.kkguards:ssetofint,refinement(s)occurrencedeclarations:m=matrixindexedby[dom]ofbooldom=domain(tau(s))kk=(m[i]=true)*kruleRefineSetQuan(occurrencerepresentation):showsthenalpartofruleRefineSetQuan.Theseruleshandlecaseswherethesetistoberepresentedinoccurrencerepresentation,whereaithelementofamatrixistrueifiisintheset.domainisafunctionwhichreturnsthedomainofitsparameter.tauisafunctionwhichreturnsthetypeofelementacontainertypecontains.5MatchingExpressionsnotConstraintsTheprototypeimplementationdiscussedin[4]operatedbymatchingagainstandrewritingcompleteconstraintsafter atteningallexpressionsbyintroduc-ingauxiliaryvariablesandfurtherconstraints.However,suchanapproachhasanumberofdrawbacks.Itmaynotbescalableingeneralaswemaypossiblyhaveahugenumberofconstrainttypesthatlookverysimilarbutslightlydierent(suchas:xsubseteq(aunionb)andxsupseteq(aunionb)).Further-more,alargenumberofrewriterulesmaybeneeded,oneforeachconstrainttype.Finally,the atteningprocessmayintroducealargenumberofunneces-saryauxiliaryvariablesandchangesthestructureofourconstraintsforwhichwemayhavebetterrewriterulesthatexploitthatstructure.Inthispaper,weovercomethesedrawbacksbyallowingourrulestomatchandrewriteexpressionswithinaconstraintratherthan(necessarily)thewholeconstraint.Thisallowsustoaccomplishthreethings.First,wecanreneagreaterproportionoftheEssencelanguageusingfewerrules.Second,un-liketheprototype,wenolongerneedto attenaspecicationpriortorene-mentavoidingintroducingunnecessaryauxiliaryvariables.Finally,wemayhaveoptimisedrewriterulesforspecicstructuredconstraints.Forinstance,con-sidertheconstraint(aunionb)subseteqc,ifwe attenit,wewouldhavexsubseteqc/\x=aunionbwhichintroducesanauxiliaryvariableandrequiresreningunnecessarilyasetequalityconstraint.Inourapproach,inad-ditiontothisrenement,wemayrewritethisintoaconjunctionoftwosubseteqconstraints,namelyasubseteqc/\bsubseteqc,byhavingadedicatedrewriterulewhichreasonsaboutthestructureofthisconstrainttype. foralls:A.(((max_s-max_t)@(bubble_s/\bubble_t))=k)=(kelems)foralls:A.(((max_s-max_t=k)@(bubble_s/\bubble_t)))=(kelems)foralls:A.(((max_s-max_t=k)=(kelems))@(bubble_s/\bubble_t))Afterndingtherightpositionsforthebubbles,ournextstepsafelyconverts\@"toconjunction\/\"resultinginthefollowingvalidexpression: foralls:A.(((max_s-max_t=k)=(kelems))/\bubble_s/\bubble_t)Ouroptionallaststepistoresolvethescopeforthebubbleexpressionsinsideauniversallyquantiedexpression.ruleLoopInvariant,denedbelow,movesallexpressionsinsideauniversallyquantiedexpressionthatdonotfallinthescopeoftheirquantier.Theruleisdenedasfollows: foralli:s.k;invariants/\foralli:s.variantsdeclarations:ks=splitConjuctionkvariants=filter(hasReferenceToi)ksinvariants=ksnnvariantsGivenaconjunctionofconstraints,thesplitConjuctionfunctionreturnsalistofconstraintsbreakingtheconjunctionsbetweenthemandthefunctionhasReferenceTocheckswhetherthesecondexpressionreferencestherstoneornot.Thus,ournalrenementisasfollows: bubble_t/\foralls:A.(((max_s-max_t=k)=(kelems))/\bubble_s)6CoverageofEssenceandLimitationsTheEssencelanguageasdenedin[4]containsvecoretypeconstructors:set,multi-set,partition,tuple,functionandrelation;andthesimpletypesint,boolanduser-denedenumeratedandunnamedtypes.Currentlyoursys-temhasrulesforhandlingspecicationsonallthetypeconstructors,exceptingpartition.Thereare22operatorsonthesetypeconstructorsdenedin[4].Wesupportalmostallofthem.Thecurrentlymissingoperatorsaremostlyrelatedtotype-conversionandwearecondentthattheywillbeeasytoimplementwithoutchangestoourcurrentsystem.Sincepartitionscanberealisedassetsofsetswithadditionalconstraints,wearecondentthatwecansupporttheseinthenearfuture.Wedonotimplementenumeratedtypesandunnamedtypesyet.TheinitialfocusoftheimplementationwasattackingthechallengingpartsofEssencelikethenestedtypes,ratherthanprovidinganishedproduct.Sinceenumeratedtypesandunnamedtypescanbeeasilytransformedintointbyapreprocessingstep,wepostponetheimplementationofthem. not(a);a=falseguards:aboolruleNot:Thisruleremovesnegatedexpressions. defined(f);defn_fguards:ffunction1-2,isTotal(f)truedeclarations:defn_f=setof1defined(f);defn_f@bubblguards:ffunction1-2,representation(f)Func2DisPartial(f)truedeclarations:defn_f=setof1m=matrixindexedby[dom(1),dom(2)]ofboolbubbl=foralli:dom(2).((sumj:dom(1).m[j,i])0)=ielemdefn_fruleFuncDefined:Renesthedefinedoperatorappliedtoafunctionvariable.Simplyreturnsthedomainsetofthefunction,ifthefunctionisdeclaredtobetotal,elseitcreatesasetvariableandconstraintsit. range(f);range_fguards:ffunction1-2,isSurjective(f)truedeclarations:range_f=setof2range(f);range_f@bubblguards:ffunction1-2,representation(f)Func2DisSurjective(f)6truedeclarations:range_f=setof2m=matrixindexedby[dom(1),dom(2)]ofboolbubbl=foralli:dom(1).((sumj:dom(2).m[i,j])0)=ielemrange_fruleFuncRange:Renestherangeoperatorappliedtoafunctionvariable.ThisruleissimilartoruleFuncDefined. j000;m[i];j000;nguards:mmatrixindexedby[indices]ofomp;onen;ts00;tupledeclarations:n=tuple0omp;s]TJ;/F26; 5.9;ݶ ;Tf 1;6.5;ĕ ;.80; Td;[000;comps0=8c2components.matrixindexedby[indices]oftypeof(c)ruleMatrixOfTuples:Essencesupportsmatricesoftuples,howeverthetargetlanguagedoesnot.Thisrulerewritesamatrixoftuplesintoatupleofmatrices,preservingthematrixindexingandthetupleindexing. i000;t;ttguards:tomp;onen;ts00;tupleiintegerexpressionlength(components)omp;onen;ts00;=ideclarations:tt=typeof(components[i])ruleTupleOut:Rewritesanindexedtupleintoaseparatedecisionvariable. a=b;foralli:r.i000;a=i000;bguards:atuple1omp;onen;ts]T;J/F2; 5.;靶 Tf ;u.3;ŧ ;-0.9;ॣ ;Td[0;,btuple2omp;onen;ts]T;J/F2; 5.;靶 Tf ;u.3;ŧ ;-0.9;ॣ ;Td[0;length(components1)=length(components2)declarations:r=int(0..length(components1)-1) incontrastwithconstraintsolverssuchasIlogSolver[8]andGecode[19],whichareimplementedasalibraryinaprogramminglanguagesuchasC++.TherearetwostandardmethodsforimplementingDSLs.Therstistowriteafullparserandtypecheckerforthelanguageandmapthelanguagetoaninternaldatastructurethatcanbeprocessedandexecuted.Asecond,simplermethodisbyextendinganexistingprogramminglanguage.TheDSLlanguageisthencalledanembedded-DSL(EDSL).Wechooseahybridapproach.WeimplementthelanguageasanEDSLtoHaskelltoleverageitspower,yetwestillimplementacompleteparserandatypecheckerthatcanreadconventionalEssencespecicationsin.Thismaysoundlikeduplicatingsomework,however,wemakeuseoftheEDSLwhilewritingourrewriterules.UsingtheEDSLforrewriterulessavesusagreatdealofeortwhichwouldotherwisemeanre-implementingfeaturesofthehostlanguage.Somelanguages,likeHaskell,areparticularlysuitedtothistask,andcanbeusedtoimplementconciseEDSLsthatareeasytouse.Haskellisastaticallytypedhigher-orderpurefunctionalprogramminglanguage.Itprovidesamodulesystem,anadvancedtypesystemwithtypeclassesandpolymorphictypes.Itisparticularlypowerfulinmanipulatingdatastructuresusingitspowerfulpatternmatchinginfrastructure.ThesefeaturesmakeitanaturalcandidateforhostingEDSLs.ThereareEDSLsinHaskellformanyeldsincludingbutnotlimitedto3Danimations,imagesynthesisandproduction,andgeometricregionanalysis.Thehmatrix-gplkpackage1providesanEDSLforLinearProgramming,aswellasasolver.Rhiger[18]providesfurtherexamplesofEDSLsinHaskell,anddescribesthecommontechniquesusedtodesignthem.BuildingontopofHaskellgivesustheabilitytoleverageHaskell'srichtypesystemandgrowfromexistingtypesandoperations.Asdiscussedin[5],Essenceitselfisspeciedasasequenceofabstractlexemes.Ourchoiceofcon-cretelexemeswasmadetosuitthehostlanguage.ThemappingtotheabstractlexemesoftheEssencelanguagedenitionisstraightforward.8ConclusionThispaperhaspresentedanewversionoftheConjureautomatedmodellingsystem,whichachievesfargreatercoverageoftheEssencelanguagethanpre-viousversions.ThereremainasmallnumberofareasoftheEssencelanguagethatweneedtoextendthesystemtocover,suchaspartitionvariablesandfunc-tionvariablesthatmapfromarbitrarilynestedtypes.Thisformsanimmediatepieceoffuturework.Furtherfutureworkincludesincreasingthequantityandbreadthofourrenementrulesandbeginningtoselectamongthesetofmodelsproduced.AcknowledgementsOzgurAkgunissupportedbyaSICSAprizestudentship.ThisresearchissupportedbyUKEPSRCgrantnoEP/H004092/1. 1http://hackage.haskell.org/package/hmatrix-glpk