Science Arts & Métiers (SAM)
is an open access repository that collects the work of Arts et Métiers Institute of
Technology researchers and makes it freely available over the web where possible.
This is an author-deposited version published in:
https://sam.ensam.eu
Handle ID: .
http://hdl.handle.net/10985/16740
To cite this version :
Mathias KLEINER, Marcos DIDONET DEL FABRO - A generic approach to model generation
operations - Journal of Systems and Software - Vol. 142, p.136–155 - 2018
Any correspondence concerning this service should be sent to the repository
Administrator :
archiveouverte@ensam.eu
Controversy
Corner
A
generic
approach
to
model
generation
operations
Mathias
Kleiner
a,
Marcos
Didonet
Del
Fabro
b,∗a CNRS, LSIS, Arts et Mtiers, Aix-en-Provence, France
b Depto de Informatica, UFPR - Universidade Federal do Parana, C3SL Labs, Curitiba, Brazil
a
b
s
t
r
a
c
t
ModelgenerationoperationsareimportantartifactsinMDEapplications.Theseapproachescanbeused formodelverification,modelfinding,andothers.Inmanyscenarios,modeltransformationscanaswell be representedby amodel generationoperation. Thisoftencomes withthe advantageofbeing bidi-rectionalandsupportingincrements.However,mostpartofmodelgenerationapproachesdonottarget severaloperationkinds,butnarrowerscenariosbymappingthegenerationproblemintosolverspecific problems.Theyareefficient,butoftendon’thaveasupportingframework.Inthispaper,wepresentan approachandframeworkthatallowstospecifyandtoexecutemodeloperationsthatcanberepresented intermsofmodelgenerationoperations.Wefirstintroduceamodelsearchlayerthatcanbeusedwith different solvers.We illustrate thislayer witha drivingexample implementedusing Alloy/SAT solver. On topofthis,weintroduceatransformationlayer,whichspecificationaretranslated intothemodel searchlayer,independentlyfromanysolver.Thesolutionisnativelybidirectional,incrementalanditis notrestrictedtoone-and-onescenarios.Theapproachisillustratedbytwousecasesandwith3different scenarios,backedbyafull,extensibleandfreeimplementation.
1. Introduction
InModel-DrivenEngineering(MDE)approaches, studiedor de-velopedsystemsare capturedthrougha setofmodels represent-ing different structural and behavioural points of view.A model mustcomplytoconstraintswhichmaybeeithergenericrulesthat applytoanymodels ofitskind(thelanguage syntax and seman-tics),orsystem-specificconsiderationsthatstemfromtheuser ob-jectives. Therefore one kind of model operation is the ability to (semi)-automaticallygenerateorcompleteagivenpartial(possibly empty)model. This operation, herecalled model generation, has differentuses:modelverification,languagetesting,usecases gen-erationoruserassistanceindefiningthesystem.Giventhe graph-like structure and mostly discrete properties of meta-languages, existingapproachestomodelgenerationusuallyrelyon combina-torialtechniquessuchasconstraintprogrammingsolvers.The pro-cess thus consists in mapping the model generation problem to a solver-specificproblemdefinition whereresolution is achieved, andthen mapping the solution(s) (if any) back to the modeling world.ThisapproachisusedforinstanceinGogollaetal.(2007),
Kleiner et al. (2010) and Macedo et al. (2013). The main draw-backsarethelimitationsofthechosensolver.Indeed,thenatureof
∗ Corresponding author.
E-mail addresses: mathias.kleiner@ensam.eu (M. Kleiner), marcos.ddf@inf.ufpr.br
(M. Didonet Del Fabro).
meta-languagesyields hard combinatorial problemsthat may re-quiresolverstodealwithsolutionsofaprioriunknownsize,amix ofdiscreteandcontinuousvariables,orcomplexstrings manipula-tion.Therefore differentproblemsmight requiredifferentsolvers, andoftenneedto besimplified inorderto beturned intoviable specifications.
Additionally, the different models of a system are usually re-lated,meaningthatsome,ifnotall,ofagivenmodelelementscan bededucedfromtheothers.Thisyieldsasecondkindofoperation, herecalledmodeltransformation,wherethegoalistoobtainaset of(target)modelsfromasetof(source)models.Afirstsetof ap-proaches that rely on rules andpatternmatching (Czarneckiand Helsen, 2006) have been successful for a large number of use cases. However, the system development process is rarely linear, meaningthatexistingmodelsmaybemodifiedandshouldstillbe kept consistent. These usecases have outlined the unidirectional andnon-incrementallimitationsofmostoftheseapproaches, lead-ing to studies in novel transformation techniques having bidi-rectional and incremental properties (Hidaka et al., 2016). Some of these approaches, such as JTL (Eramo et al., 2012), MOMoT (Fleck et al., 2016) or Echo (Macedo and Cunha, 2013), propose to represente model transformations in terms of a model gener-ationproblem.However,thesupportformultiplekindsof genera-tionoperationscouldbeimproved.
Inthisarticlewepresentagenericapproachandframeworkto specifyandto execute modeloperationsthat can be represented
in terms of model generation operations. This article re-founds andextendsworkpresentedinpreviousconferencepapers(Kleiner etal.,2010;2013).Theapproachhasthefollowingmainhighlights.
Model search: we present a layer called model search (MS), which handles the model generation process. This layer is broke downintosolver-specificandsolver-independentcomponents.The solver-specific ones provide the extraction/injection of the input and output models into/fromthe solver format. The solver inde-pendentpartsare theremainingcomponents.Weprovidea com-pletelyrewrittenopensourceimplementationbasedontheEclipse Modeling Framework (EMF) (Czarnecki andHelsen, 2006), where theexecuted chaincan beeasily adapted,improvingconsiderably its applicability.We also providea fullyoperational example im-plementation of the generic approach that targets the Alloy/SAT solver(Hidakaetal.(2016)).
Multi-level transformations: we provide a generic bridge be-tween themodeling problemandsolvertechnicalspaces,through
the implementation of reflexive model transformation, called
multi-level transformations. The transformations are implemented usingonlythemetametamodelselements.Theydiscoverthe meta-model and model elements during execution time. This enables having one single transformation for any input metamodels and theircorresponding models,andwithoutrelyingonan unification format.Thesameisvalidfortheoutputmodels.
Model transformations as search (TAS): we present a TAS layer that is independent fromtheunderlying solver, conceptually and practically.Thismeansthatamodeltransformationspecificationis defined usingonly modeling components. These are transformed intoamodelsearchproblemandsolutionsarethenmappedback totheresultingmodels.Inaddition,theapproachisnotrestricted toone-to-onetransformationscenarios,itismulti-directional and incremental. We havedeveloped as well a set of components to develop model transformations and to interact with the model searchlayer.
Unified formalism: finally, we revisited and provided an inte-grated conceptual view from both model and transformation as search.
Plan ofthearticle. Section 2provides thetheoretical background. In Section 3,we formally define the modelsearch layer, theoret-ically andwith a practical guiding example.In Section 4 we de-scribe the transformation and synchronization layer. We provide experimental results andanalyse the strengths anddrawbacksof theapproachwithadditionalcommentsontwoexamplesfromthe literatureandtheindustry.Section5presentstherelatedwork. Fi-nally,weconcludeinSection6.
2. Context
2.1. Briefintroductiontomodelingandmodeltransformation
Model Driven Engineering (MDE) considers models, through
multipleabstractrepresentationlevels, asa unifyingconcept.The central concepts used in such approaches are terminal model, metamodel,andmetametamodel.Aterminalmodelisa represen-tation of a system. It captures some characteristics of the
sys-tem and provides knowledge about it. MDE tools act on
mod-els expressed in precise modeling languages.The abstract syntax of a modeling language, when expressed as a model, is called
a metamodel. The relationbetween a modeland themetamodel
of its language is called conformance. Metamodels are in turn expressed in a modeling language for which conceptual founda-tions arecapturedinan auto-descriptivemodelcalled metameta-model.There aremultiplemodeldefinitions intheliterature (see
Kühne,2006 fora deepstudy),we refine inthisarticlethe ones
introducedinJouaultandBézivin(2006)sincesimplegraph-based definitionswillproveusefulinourcontext.
Definition1(model). AmodelMisatriple <G,
ω
,μ
> where: • Gisadirectedlabelledmultigraph,•
ω
(calledthereferencemodelofM)iseitheranothermodelor Mitself(i.e.,self-reference).•
μ
isa function associating nodes andedges of G tonodes ofGω (thegraphassociatedtoitsreferencemodel
ω
).Definition2(conformance). Therelationbetweenamodelandits referencemodeliscalledconformanceanddenotedconformsToor
c2.
Definition3(metametamodel). Ametametamodelisamodelthat isitsownreferencemodel(i.e.,itconformsToitself).
Definition 4(metamodel). Ametamodelis amodel such thatits referencemodelisametametamodel.
Definition5(terminalmodel). Aterminalmodelisamodelsuch thatitsreferencemodelisametamodel.
Althoughthepresentedworkmaybeadaptedtoother metalan-guages,wewillassumeinthefollowingtheuseofECORE(an im-plementationofOMG’sEMOF)asthemetametamodel(EMF,2018), since it is supported by a wide set of modeling tools.The main wayto automateMDE is by executing operationsonmodels. For
instance, the production of a model Mb from a model Ma by a
transformation Mt is called a model transformation. The OMG’s QueryViewTransformation(QVT)(QVT,2011)definesasetof use-fulmodeloperationslanguages.Inparticular,itdefinesalanguage calledQVT-operationalwhichis restrictedtounidirectional trans-formations scenarios,and a language calledQVT-relational which canbeusedforbidirectionalandsynchronizationscenarios.
2.2.Constrainedmetamodels
ThenotionofconstraintsiscloselycoupledtoMDE. Engineers have been using constraints to complete the definition of meta-models for a long time, as it can be found in implementations combining UML/OCL(e.g., Eclipse OCL project,2018). Constraints canbe,forinstance,checkedagainstone givenmodelinorderto validate it. Inour approach we will always consider metamodels with potential constraints attached. We first formally define the combination:
Definition 6 (constrained metamodel). A constrained metamodel
CMMis a pair <MM, C> whereMM is ametamodel andCis a set(aconjunction)ofpredicatesoverelementsofthegraphG as-sociatedtoMM.Wewillconsideranoraclethat,givenamodelM, returnstrue(notedM∈C(MM)whereC(MM)isthesetofallvalid models)iff MsatisfiesallpredicatesfromC.
Theconformancerelationbetweenamodelanditsreferenceis thennaturallyextendedtoconstrainedmetamodels.
Definition7(constrainedconformance). AmodelMconformsToa constrainedmetamodelCMMiff itconformsToMMandM∈C(MM). Many languages can be used to define predicates (i.e., con-straints)withdifferentlevelsofexpressiveness. Inthisarticle,we will assume the use ofOCL, though the presented work maybe adaptedtoother constraintlanguages.Indeed,OCLiswidespread, well integratedin modeling technologies, and expressive (it sup-portsoperators on basic datatypes, sets and relations as well as universal/existentialquantifiersandvariousiterators).
2.3.Briefintroductiontomodelfinding
We call model findingthe problemoffinding andexhibitinga model(initsbroadmathematicalacceptance)fromagiven defini-tion.Computationaltechniquesforsuchproblemsisavastareaof theoreticalandappliedresearchandrelatestovarioustypesof de-cision, satisfaction andoptimization problems. Obviously, finding a model (in its MDE acceptance) that complies to a constrained metamodelisamodelfinding problem,inwhichthesearchspace
is implicitlydefined by the set of potential well-formedmodels. Although this work does not assume any particular model find-ingtechnique, focus willbe puton constraintprogramming(CP), theusualapproach inmodelingenvironments. CPisadeclarative programmingtechnique to solve combinatorial (usually NP-hard) problems.A constraint, in its wider sense, is a predicate on ele-ments(representedbyvariables).ACPproblemisthusdefinedby a setof elementsand a setof constraints.The objective of a CP solveris to find an assignment (i.e., a setof values forthe vari-ables)that satisfies all the constraints. There are several CP for-malismsandtechniques (Jaffar andMaher,1994) which differby theirexpressiveness,theabstractnessofthelanguageandthe solv-ingalgorithms. Forinstance,theSAT (booleanSATisfiability prob-lem)formalism.ASATproblemistodecideif,foragivenboolean formula, each boolean variable can be given an assignment such that theformula evaluates to true.SAT is known asbeinga NP-completeproblem(Cook, 1971), andassuch anyCPproblemcan bereducedintoSAT
Since SATis alow-level formalism,manipulatingonly boolean variables,higher-levellanguages havebeenproposed to ease real problemsspecifications.One ofthoseis Alloy (Jackson, 2000), an expressiverelationallanguage that uses abuilt-in compiler (Kod-Kod)toproduceSATproblems.TheAlloytoolofferstosolveusing severalunderlyingSATenginesandtranslatessolutionsbacktoits relationalidiom.
3. Modelsearch
We considertheoperation thataims atgeneratingacomplete and valid model of a constrained meta-model, starting with an
incomplete (possibly empty) model. We first propose a formal
model-baseddefinitionofsuchataskasafirst-classmodel opera-tioncalledmodelsearch.Wethendescribeanexampleprocessasa genericpatternforsolver-specificimplementations.Finally,we de-scribeadetailedexampleimplementationusingAlloy/SATtogether withexperiments.
3.1.Modelsearchdefinition
Inordertoformallydefinemodelsearch,letusfirstdefineaset ofnotionsthatrelatetoconstrainedmetamodels.
Relaxedmetamodelsandpartialmodels.
Definition 8 (relaxed metamodel). Let CMM=<MM,C>
(with MM=<G,
ω
,μ
>) be a constrained metamodel.CMMr=<MMr,Cr> (withMMr=<Gr,
ω
,μ
>) isa relaxed meta-modelofCMM(notedCMMr∈Rx(CMM))ifandonlyifGMMr⊆ GMMandCr⊆C.
In other words, a relaxed metamodel is a less constrained (andpossibly smaller) metamodel.A simpleone can be straight-forwardly obtained by the removal of all constraints: structural (makingreferencesandattributesoptional)andexternal(removing predicates).Computingsucharelaxedmetamodel,asimple opera-tion,iscalledrelaxationinthefollowing.Inmanyframeworks, in-cludingECORE-basedones, therelaxedmetamodeldoesnotneed
Fig. 1. The model search operation.
to be an additionalconcreteartifact, since the implementationis flexibleenoughtosupportit.
Definition 9(partialmodel,p-conformsTo). LetCMM=<MM,C>
bea constrainedmetamodelandMramodel.Mr p− con formsTo
CMMiff itconformstoametamodelCMMrsuchthatCMMrisa re-laxedmetamodelofCMM(CMMr∈Rx(CMM)).Mriscalledapartial modelofCMM.
Informally,apartialmodelissimplyunderstoodasbeingan in-completeorfaultymodel.
Modelsearch.
Definition 10 (model search). Let CMM=<MM,C> be a con-strained metamodel,andMr=<Gr,MMr,
μ
r> a partial modelofCMM. Model search is the operation of finding a (finite) model
Ms=<Gs,MM,
μ
s>suchthatGr⊆Gs,μ
r⊆μ
s(embeddingi.e.,∀
x∈Gr,
μ
s(
x)
=μ
r(
x))
,andMsconformsToCMM.Informally, model search extends a partial model Mr into a modelMsconformingtoitsconstrainedmetamodelCMM(or gen-eratesonewhennoMrisgiven).Inthefollowing,Mriscalledthe
requestmodel,andMsthesolutionmodel.TherestrictionthatGris includedinGscouldberemovedifthesolversupportsremovalof elements, orthiscould be circumvented byre-generating a com-pletenewmodel,withoutthedeletedelements.
Thisoperation isillustrated inFig. 1.Inother words, we con-sider modelsearchasa operationwherethe request(metamodel andmodel)isan instanceofanon-deterministic(often combina-torial)problemandthesolutionmodelisoneoftheresults(ifany exists).Fromthesolverpointofview,therequestmetamodelacts astheproblemdefinitionwhereastherequestmodelisagiven par-tialassignment.
3.2. Modelsearchprocess
We provide belowan example generic process, independently ofanysolver,toexplaintheusualstepsinvolvedwhen implement-ingmodelsearch inamodelingenvironment.Thissoftwarechain isillustrated inFig.2,wheredarkgraysquaresare solver-specific parts.Itiscomposedof5maintasks.
(1) Problem definition generation: this task, illustrated by the
CMM2SP transformation,expresses the constrainedmetamodelas asolverproblemdefinition.However,theCMM2SParrowisa sim-plified view ofthe operation,since thereare actually two source models as input to the transformation. Fig. 3 shows the actual transformation andits simplified view.The metamodel MM con-tains the structural constraints,which may be expressed, for in-stance,by ECORE. However, typical modelsearch applications re-quire more complex domain constraints (e.g., to set up a
maxi-Fig. 2. Model search example implementation process in a modeling environment.
Fig. 3. Generation of the problem definition.
mum cardinalityvalueforanattribute).Thesedomainconstraints are expressed intheconstraint modelC,which can,for instance, conform to the OCL metamodel.The constraints referto the ele-ments ofMM. Thus, a combination of ECORE+OCL could be one pairofinputmodels.
Thedifficultyofexpressingaconstrainedmetamodelasasolver problemishighlydependentontheabstractionlevelandthebasic elementsofferedbythetargetsolver.Someimplementationissues willbediscussedinSection3.4.
(2)Partialassignmentgeneration:thistaskis illustrated bythe
M2SP transformation.Ittakesthe requestMrasinput and gener-atesthecorresponding partialassignmentforthesolver.Herethe maindifficultyisthattheinputmetamodelMMisdomain depen-dent, which means it may be different according to the search problem being considered. Since many transformation languages consider the input metamodel as un-changeable, it would imply writingadifferenttransformationM2SPforeveryconsidered meta-model MM. Clearly, this is undesirable. We propose a solution using multi-level transformations. A multi-leveltransformation is a
model transformation that takes as input the domain model M
and also the domain metamodel MM and that produces as
out-put the solver partial assignment. This transformation is imple-mentedusingreflection.Moredetailedexplanationsonthis multi-leveltransformationaregiventogetherwithanimplementationin
Section3.4.
It is importantto note that manysolvers do not separate the problemdefinitionandthepartialassignment:theyareusually ex-pressedusingthesamelanguage/code.Forthatreason,bothshare thesame“solverproblem” metamodel.When this isnot the case,
theprocessiseasilyadaptedby separatingthepartialassignment metamodelfromtheproblemdefinitionmetamodel.
(3) Engine program extraction: this task extracts the solver problemmodel into its parsable or executable format. Any clas-sicmodel-to-textormodel-to-codemodeling technologiescanbe usedhere.
(4)Solver execution: the generated solver file/program is exe-cutedinordertoobtainsolutions.Whenthesearchsucceeds(i.e., thereis atleastone solution),we obtain a solutioninthe solver exportformat.ThemostcommonareXMLorgrammar-basedtext files.
(5)Solutioninjection:thislasttaskconvertsthesolution(s) pro-ducedbythesolverasmodel(s)oftheoriginal searchmetamodel
MM.Itisnaturaltodecompose theoperation intotwosub-tasks: injectingthesolutionintothemodelingenvironmentbasedonthe solveroutputformat,thentransformingtoamodelconformingto theoriginalsearchmetamodelMM.Wehaveconsideredinthis ex-ampleprocessthattheenginegeneratesanXMLfile.Thereforewe firstdoastraightforwardinjectionoftheXMLsolutioninthe mod-eling environment. If the solver rather produces grammar-based files, thiscan be replacedby aclassic text-to-model parser-based injection.Thenwetransformtheoutputtoamodelconformingto
MM(M2SS inFig.2). Forthesamereasons astheM2SP transfor-mation,SS2Misamulti-leveltransformation:ittakesMMas addi-tionalinputandgeneratesamodelMs.Again,moredetailed expla-nationsonthisunusualmulti-leveltransformationwillbegivenin theexampleimplementation.
3.3.Implementationofthegenericpartoftheprocess
Thispartoftheimplementationregroupsallthemodelsearch softwareparts(UIandAPI)thataresolver-independent.Thisisof primary importanceso that other modeloperations,presented in
Section 4, can be defined independently from anysolver-specific implementation.TheimplementationisdistributedundertheEPL licenseasasetofEclipse pluginsthatareavailable fordownload attheMOS GitLab.1 It iscompletely modularandextensible: the alternativesolver-specificimplementationsarediscoveredthrough Eclipse’sextension pointmechanism.Thepluginsaredividedin4
maincomponents:
Fig. 4. Excerpt of the Alloy metamodel. 1. Launch configuration: creates a launch configuration to set up
therunningparameters,whicharetheinput andoutput mod-els,metamodelsandconstraints.
2. SolverChain: itisthemainAPI,whichprovides asetofclasses and extension pointsfor all the transformations of the chain, whichneedtobeexecutedinthechainorder.Whenthesolvers need additionalspecificparameters forexecution, they canbe forwardedthroughaproperty/valuelist,calledmodelsearch op-tions,andthenhandledbythetransformation.
3. Solutionexplorer:manyexistingsolversmayproducemorethan onesolutionasoutputaftertheexecutionofthetransformation chain, in other words, enabling severalexecutions of the 4th task(solverexecution).Thiscomponenttargetsthiskindof fea-ture:ittakestheresultfromthetransformationchainand nav-igates throughthegeneratedsolutions. Itdealswiththe com-mon fact that thesolvers mayproduce zero,one ormore so-lutions,andallows theusertocreate/browsethroughdifferent solutions untila satisfyingone isfound. Aninitial poolof so-lutions (ifany,andpossiblyjustthefirst) isconsidered. Ifthe underlyingsolverchainisincremental,itwillbeaskedto pro-duceadditionalsolutionsdynamicallywhenneeded.
4. Standalone launch:setofplug-instoenablethestandalone ex-ecution ofthechain,i.e.,fromcommand lineandwithoutthe needtolaunchEclipse.
TheSolverChain(2)containsthecoreimplementationofthe ap-proach.TheLaunchconfiguration(1),SolutionExplorer(3)and Stan-dalone launch (4) components compose the technical backup for theinteractionwithusers/developers.
3.4.Exampleimplementationofthesolver-specificpartusing alloy/SAT
Inordertohighlightthemainchallengesthatmayarisewhen implementing a solver chain, we provide an example using Al-loy/SATasthesolverlanguage/engine.In thefollowing,eachstep ofthe processimplementationisdetailedandinherentissuesare discussed.Additionally, the clearseparation in differentsteps
al-lowsamodularreuseofourimplementation.Tothisaim,the pre-sentedsoftwarechainisprovidedasasetoffreely-available inde-pendentEclipseplugins.Ifadifferentsolverwouldbeused,allthe stepsinthissectionshouldbeimplemented.2
3.4.1. Alloy/SAT
TheSAT paradigmhasclearlimitations:itrequiresa finiteset ofbooleanvariablesandonlyoffersalow-levelpredicatelanguage (only negation,disjunction andconjunctionaresupported). How-ever,Jackson (2000)introduced an expressive relationallanguage (Alloy)withabuilt-incompilation(KodKodengine)thatallowsthe useofmanyrecentSATsolvers.WewillthususeAlloyasour tar-getsearchenginelanguageinordertoeasethetransformation def-inition.
Alloy allows for expressing complex predicates using atoms (un-dividableelements),sets(ofatoms),relations,quantifiers (uni-versalorexistential),operatorsforrelationstraversal,etc.However, duetothepropertiesofSATproblems,Alloycannotbeconsidered asatruefirst-orderlogicsolver.Indeed,tobeabletotranslatethe problem into SAT, a scope needs to be given to each typed set, which limits the number ofatoms that can be contained in the set.
InAlloyevery elementiseitheranatom ora relation,butthe language is exclusively based on relations. A relation is a set of tuples,whichindicateshow atomsare related,withagivenarity. Indeed,thereisnonotionofaset:asetisrepresentedbyanatom, whichhasarelationthatmapstothecontentsoftheset.Themain artifactsthatwewillmanipulateintheAlloylanguageare:
• Signatures,declarationsofsets,forwhichthebodymaycontain fieldsasrelationstoothersignatures.Attributesaretreatedthe sameasanyrelation.Scalars,similartosignatures,aretreated assetsofatoms.Signaturesalsosupportaformofsingle inher-itance.
2 We have implemented in Kleiner et al. (2010) translation from the ILOG/CP solver. Despite being based on different concepts, it provided a high-level language abstracting the solver implementation, thus many of the transformation rules had similar structure.
Table 1
Excerpt of the mapping from ECORE concepts to Alloy concepts. ECORE concept Alloy concept
EPackage Module
EDataType ExternalType and ExternalModule
EClass Signature
EAttribute Field
EReference Field
EStructuralFeature multiplicity Multiplicity and/or Fact EReference containment Fact
EReference opposite Fact
• Facts,declarationsofpredicates,withquantifiersandan impor-tantnumberoflogical,scalarandsetoperatorsavailable. • Functions,whichare specificimplementations ofAlloy built-in
functions, such as max, min or plus. The functionsmay have adirecttransformationfromtheinput models,ormayneeda specifictransformation.
3.4.2. Alloymetamodelandextractor
WedevelopedametamodeloftheAlloylanguage,whichan ex-cerptisrepresentedinFig.4asanECOREdiagram(wehave omit-ted partofthereferences toimprovereadability). It isthe target metamodel for the generation ofthe problem definition (task 1) andthepartialassignment(task2).Thismetamodelshowsthatan AlloyprogramiscomposedbyaModule,whichiscomposedbya setofdeclarations.Thesedeclarationsmaybespecializedinto:(1) types,wherea Signature isa type, composedby Fields,(2) func-tions, withits corresponding parameters and(3)facts, which are used to express the problem constraints.These facts are written usingdifferentkindsofexpressions.
Wealsodevelopedan extractorallowing toproduceAlloy tex-tual files fromAlloy models (task 3). The generated fileshelp to prototype andtofind forerrorsin theintermediate models. Itis implementedusingtheAcceleotool3.Adifferentoptionwouldbe tousedirectlytheAlloyJavalibrary,withoutfilesgeneration.
3.4.3. Generationoftheproblemdefinition
We dividedtask1 intotwo transformations,respectively from ECORE andOCL,to our Alloy metamodel.They are fully declara-tiveandimplementedusingATL(JouaultandKurtev,2005),which isa frameworkandlanguagefordevelopingandexecutingmodel transformations,transformingsourcemodelsintotargetmodels.
The ECORE to Alloy (ecore2msalloy.atl) transformation aims at expressing the structuralconstraints of a metamodel.An excerpt ofthemappingispresentedinTable1.
Inthistransformation,ECOREclassesaremappedto Alloy sig-natures. Alloy has direct support for abstract and (single only) inheritance. ECORE attributes and references are mapped to Al-loy fields. Alloy’s fields only support four multiplicity declara-tions: lone (0–1), one (1–1), some (1-∗) and set (0-∗). Therefore, othermultiplicitylower/upperboundsareturnedinto correspond-ing cardinality facts. References properties are turned into facts (i.e., a predicatefor the containment or opposite constraint). Fi-nally,attribute’sdatatypesareturnedintothecorrespondingAlloy type.Alloydirectlysupportsbooleans,integersandstrings.Though strings have some basic support in Alloy, it comes with several limitations due to the fact that they are treated as scalars: any string usablevalue must be declared(i.e, Alloy willnever gener-ateastringvaluebyitself),andonlytheequalityoperationis sup-ported.This solver-specificlimitationwillbe further discussedin
Section3.5.
The OCL/Alloy transformation (oclmdtpivot2msalloy.atl) aims at expressingmetamodelinvariantsasAlloyfacts.Concretely,weuse
3 http://eclipse.org/acceleo .
Fig. 5. Principles of the multi-level transformation applied to the partial assign- ment generation.
theOCLparserofferedbytheEclipseprojectandrunthe transfor-mationontheresultingOCLPivot model.An excerptofthe map-pingispresentedinTable2,withthecorrespondingconcrete syn-tax.TheoutputAlloyexpressionisacompositionofconcepts;the rightcolumnshowsonlythetop-levelone.Wedonotmapthe en-tireOCLspecification, butonlythefeatures thataresupportedby theAlloyspecification.Inother words,theinputlanguage expres-siveness is limitedby the solver capabilities. While thismay be undesirable, a complete mapping would only be possible ifboth languageswouldhaveequivalentsemantics.
The combination of these two (ECORE/Alloy, OCL/Alloy)
transformations corresponds to the CMM2SP transformation in
Fig.2.
3.4.4. Generationofthepartialassignment
When themodel search chain is ran ona non-empty request
Mr, this model has to be turned into a partial assignment for thesolver. Here again,we developed arule-based transformation
implemented using ATL. The main difficulty is that the source
(search)metamodelMMisunknown tothetransformation devel-oper. However, the structuralsemantics ofthe model donot de-pendonthismetamodel:theyaresolelybasedonthefactthatthe modelcontainsobjects ofECORE classesandmayoptionallyhave their structural features (partially) defined. In other words, the typeofsolver instancesandconcepts thatare createddonot de-pendontheoriginalmetamodel.Thisallowstowrite metamodel-independentrulesinwhatwecalledmulti-leveltransformation.Its mainprinciplesareshowninFig.5.
The transformation (model2msalloy.atl) has three inputs: the (request)model,its (search) metamodel,andthe problem defini-tion conforming to the solver metamodel. The latter one is re-quiredsincethepartialassignmentisobviouslyrelatedtoits prob-lemdefinition.
The implementation of this transformation is done usingATL lazy and imperative rules and by accessing the metamodel and model elements using reflection. This is necessary because we
do not know the type of the input elements in advance. We
are not aware of any technique allowing to implement matched rules (declarative) and that are coupled with reflection, nor of any declarative transformation language supporting this specific matchingtogetherwithourrequirements.
Considerforinstancethenecessitytotransformaninputmodel element intoa Signature inAlloy. Since we donot knowthe do-main,wedevelopatransformationrulethattransformsanEObject
into a Signature. We list an excerpt of the transformation below withitsmainaspects.
Table 2
Excerpt of the mapping from OCL to Alloy.
OCL Pivot main concept [concrete syntax] Alloy main concept [concrete syntax] CollectionLiteralExp [Set“a”] SetExpression [“a”]
IteratorExp (collect) [source- > collect(exp)] NavigationExpression [source.exp]
IteratorExp (forall) [source- > forAll(i [: B]| P)] QuantificationExpression [all i:source | [i in B and] P] IteratorExp (exists) [source- > exists(i [: B]| P)] QuantificationExpression [some i:source | [i in B and] P] IteratorExp (one) [source- > one(i [: B]| P)] QuantificationExpression [one i:source | [i in B and] P] IteratorExp (any) [source- > any(i [: B]| P)] ComprehensionExpression [i:source | P]
IteratorExp (closure) [x- > closure(p)] NavigationExpression [(x. ∗p)] OperationCallExp (oclAsType) [x.oclAsType(T)] OperationExpression [x : > T] OperationCallExp (oclAsType) [x.oclIsTypeOf(T)] ComparisonExpression [x in T] OperationCallExp (includes) [x- > includes(y)] ComparisonExpression [y in x] OperationCallExp (union) [x- > union(y)] ComparisonExpression [x + y] OperationCallExp (size) [exp- > size()] SetCardinalityExpression [#exp] OperationCallExp (min) [A.i - > min()] IntegerSetFunctionExpression [min[A.i]] OperationCall (unknown) ExternalFunction
It contains 3rules, one forthe current element, one creating a navigationexpression andoneforthe specific datatype found. The Alloy language does not have dedicated constructs enabling the declaration of a partial assignment, i.e., it doesnot allow to directlydefinesetsofatoms(toaccountforexistingobjects)or re-lations tuples (to account for existing structuralfeatures values). However, thiscan be circumvented usingrespectively unique sig-naturesandfacts.
Singleton signaturesare sets that can only contain one atom. For each source object, we thus create a unique signature( mul-tiplicity equalsto 1)that extendsthe object’sclass corresponding signature(shownintheextendsassignment).Auniquenamehasto begeneratedforeachobject’ssignature,soweuseitsclassname followedbyanobjectcounter.
Wethen createfacts(CreateFactrule) toaccount forstructural features anditsvalues(this ruleisnot presentedatthe transfor-mation excerpt, since its implementation is simple). It receives a navigationexpressionthat dependsontheinput objecttype.But, for a given object, we do not know the names of its structural features,so itisnecessaryto createa loopover alltheattributes andtoobtaintheirvaluesthroughreflection(refGetValuemethod). Wecreateanequalitynavigationexpression:theleft sidehasthe object variable and its attribute name (EStructuralFeature2NavExp
rule); the rightside hasthe given attribute value, which can be anydatatype.Inthisexamplecode,we showtheconditional ex-pression foranInteger value(EInttype),wherewe calla specific lazy rule (EIntAttribute2EqualsExp). Eachkind ofattribute need to haveonelazyrule(e.g.,forEString,EBooleanorotherobjects).The samekindofloopisimplementedfortheobjectreferences.
Additionally,thetransformationacceptsa modelsearchoption thatallows tofreezestructuralfeaturesofobjects.Thisisrealized by creatingan additional constraint on the field for the object’s corresponding unique signature, which cardinality must then be equaltothenumberofactualvaluesintheoriginalstructural fea-ture.
Similarlytotask1,theresultingpartialassignmentisprocessed byourAlloyextractorwhichgeneratesitscorrespondingAlloyfile.
3.4.5. Solverexecution
Nowthattheproblemdefinitionandoptionallyapartial assign-ment havebeengenerated,we mayask thesolver engineto cal-culate solutions(if any).Forthis, we generatea masterAlloy file containingthe Alloy command tobe executed, andthe necessary imports to all previously generated files. The solver execution in Alloyneeds4modelsearchoptions:scope:theamountofused el-ements;SATsolver:theSATsolvertobeused,e.g.,SAT4J;Bitwidth: theintegersallowedrangeandgenerateasingle module:to gener-ateonlyoneAlloymodulewithallthespecifications.Ifanyscope was given, its class boundsare added to the command parame-tersas specifiedby the Alloylanguage. Otherwise, Alloy willuse
Fig. 6. Principles of the multi-level transformation applied to the solution model generation.
its defaultglobal bound. Depending on the used solver, its solv-ingcapacities maydifferaccordingtotheimplementation.For in-stance,a specific solvercould providesupportto (non)monotonic operations.
3.4.6. Generationofthesolutionmodel
Amodelsearchuserexpectstheoutput(s)asmodel(s) conform-ingtotheoriginalsearchmetamodelMM.Thegenerationofthese solutionmodel(s)correspondstotask5ofourexampleprocess.
TheAlloy/SATsolvermaygeneratemorethanonesolution, de-pending onthespecifiedmodels andconstraints.When this hap-pens,wetakethefirstgeneratedsolutiontogeneratethesolution model.However,theusermayiterateoveranyofthegenerated so-lutions,andgeneratethecorrespondingsolutionmodels.Eachtime thesolvergeneratesanewsolution,task5isdividedintotwo sub-tasks (asshowninFig.2). Firstwe useEMF’s built-in featuresto generateamodelconformingtoAlloy’sXMLschemametamodel.
Thesecondsubtask(SS2M)inFig.2isthetransformationofthe resulting model intoa solution model conformingto MM. Again, weimplementeditusingATL(MSAlloyInstance2Model.atl).Similarly to the partial assignment generation task, the difficulty here is that the target metamodelisunknown to thetransformation de-veloper. We therefore apply againthe multi-level transformation techniqueusedfortask2.Itsapplicationtothegenerationofa so-lutionmodel,independentlyfromaspecificsolver,isillustratedin
Fig.6.Itreceivesasparametersthesolversolutionmodelandalso themetamodeloftheoutputsolution,inordertodiscoverthetype oftheelementsthatneedtobegenerated.
We need to consider two types of elements from the input
model: atoms andrelations tuples. Atoms, when they belong to thesetofasignaturethatwasgeneratedfromaclass,yieldclass objects. Other atoms can be eitherdatatype values(which use a specificsignature)orbuilt-inelementsfromtheAlloyspecification. Relation tuples yield the assignment of an object’s structural featurevalue, whichnameistherelationname.Thefirstelement ofthetupleisalwaysanatom thatcorrespondstothesource ob-ject.Thesecondelementcanbeeitheraclassobjectatom(inthe caseofa referencetarget),oradatatype value atom (inthe case ofanattributevalue).
As a side implementation note, it can be noted that the first rulecreatesan objectwhosetypecanonlybe knownduringrule execution.Thesecond ruleassignsastructuralfeaturevaluetoan object created by another rule. ATL matched rules do not sup-port creating an object with a dynamically computed class, nor doesitsupport assigningpropertiesto objectscreatedinanother rule.ThereforeweagainusesomeATLimperativeconstructsinthe transformation.Tothebestofourknowledge,thereisnoexisting declarativetransformationlanguagesupportingthesefeatures.
Fig. 7. Class diagram metamodel for model search.
Fig. 8. HSM metamodel for model search.
3.5.Exampleandresults
To illustrate the model search process, we provide results
on two use cases: a class diagram (CD) generation example
(Macedo and Cunha, 2013) and a hierarchical state machines
(HSM) example (Macedo and Cunha, 2016), where the
specifi-cations were adapted from literature to be implemented in our framework.Inbothcases,thegoalistosetupasimplemetamodel andthentogenerateasolutionwithspecificpropertiesgivenbya setofconstraintswritteninOCL.Thereisonly onepossible solu-tionforagivennumberofclasses/states.Ourobjectivehereisnot to studyabsolute performance but rather the generalbehaviour: indeedourexampleAlloy/SATsolverchainonlyillustrates the ap-proachanddoesnotincludeanyspecialsolvingoptimization.
Weshow theclassdiagram metamodelinFig.7.Itstatesthat the generated solution will have only packages, classes and at-tributes.
TheadditionalOCLconstraintsfortheinstancesgenerationare shown below. The goal is to generate attributes with different nameswithingthesameclass,bynumericallyincreasingthename ofthe attributes. The complete Alloy program generatedfor this specificationislistedinAppendixA.
Weshow inFig.8the metamodelusedfortheHSM example. Themetamodel isformed bya rootstate machine,which canbe
formedby simpleorcomposed states.Theyare connectedby in-comingoroutgoingtransitions.Theircorrespondingconstraintsare illustratedinthefollowing.Theconstraintsaremorecomplexthan in the class diagram example, since they need to guarantee the nestedstructure,thestatemachineandtransitionnames,andthat transitionsneedtoconnecttooneongoingandoneoutgoingstate. Theexplanationofeachconstraintisdoneinthecodecomments.
Thesetwoexamplesareinjectedintothemodelsearchchainto beexecutedbythesolver.Notethatforeachexample,itis neces-sarytoinjectthemetamodelanditsinstances(partialassignment). Thegenericmulti-leveltransformationavoidshavingone transfor-mationCD2AlloyandanotheroneHSM2Alloy.
As inthe original example,we observethecomputational be-haviuor when gradually increasing the number of elements (i.e., instancesofthemetamodelclasses)intherequestedsolution,from 2to32(CD)or26(HSM)elements.Herewealwaysstartfromthe sameinitial model containingonly a rootelement. We first pro-vide experiments on the class diagram generation problem with differentglobalscopes(amandatoryparameterforAlloyandmost existingsolvers) toobserve theimpact onperformance. Then we
Fig. 9. Results on the generation problems.
compare results on the same problem using either the SAT4J or MiniSATback-end.
Inalltheseexperimentswe focusonthemodelfindingtimes, excluding the problem (resp. solution) generation (resp. extrac-tion).Indeed,duetoexponentialcombinatorialsearch,theformer isadecisivefactorintheoverallcomputationalbehaviour.The lat-ter, pseudo-linear in practice, soon becomesnegligible (plus the problemonlyneedstobegeneratedonce).Weprovidetheaverage valuesbasedon20runsofeachproblemona16GBXeon3.3Ghz linux computerusingAlloy 4.2. Resultsare summarizedinFig.9. The examplesandfull experimentsare available forreproduction inMOS(2018).
Thetopfigurepresentsresultswithdifferentscopesusing Min-iSATwitha fixed integerbitwidth(5).Theratio 2:1denotes that theglobal scopeis setto twice thenumberof requestedclasses. These results show that the scope has an important impact on thecomputationtimes.Indeed ahigherscope resultsin ahigher number of boolean variables in the generated SAT problem thus potentially inducinga highernumberofbranchesto explore (de-spitemitigationbysymmetrybreaking).Althoughasmallerscope is in general better for performance, our experience shows that choosingtherightscopeistediousandlargelyproblem-dependant. Similareffects canbe observedonproblemswithnumerical con-straints when varying the integer bitwidth (which defines the rangeof integervalues). Since Alloytranslates integers tosets of boolean(one foreachvalue), thisagainresultsin ahigher num-ber of variables andthus a similar combinatorialimpact. Finally, inmostofourexperiments,wecanobserveoccasionalgaps(resp.
peaks) causedbyspecific instancesbeingeasier(resp.harder) for thesolversbuilt-inoptimizations.
Thebottomfigureshowstheresultsforourstatemachines gen-erationexample.Wedefinedcomplexconstraintsthatmixinteger andsetcomputationsso thatthe hierarchysizefortopstates in-creases with the problemsize. We can indeed observe a higher computational cost than fortheclass diagrams generation exam-ple.
TheseexperimentsindicatethatAlloy/SATmaynotbethebest solverchoice fora numberofproblems,particularlythose involv-ingvariousnumericalconstraintsorthosewhereitishardtoguess theapproximatenumberofinstancesinthesolution.Thisconfirms theinterestofhavingasolver-agnosticmodelsearchapproach, al-lowinguserstoselectamethoddependingontheirproblem char-acteristics. We believe that, generally, model search would ben-efit from a solver that does not impose scope restrictions. Un-fortunately, efficient solvers which allow on-the-flyinstance cre-ation are not convincinglydemonstrated inthe literature.Finally, although this is more obvious on complex problems or on large scales,anexponentialbehaviourcanalwaysbeobservedwhenthe size oftheproblemgrows.This isexpectedfromacombinatorial solverbutlimitsusabilitywhenusingaSAT-basedsolverthatcan onlycopewithsmalltomediumsizeproblems(Jackson,2000).
4. Transformationassearch
Inthefollowingwepresentourgeneralizationofmodelsearch to model transformation/update operationsby considering multi-ple metamodels(sources and/or targets)together withthe trans-formationspecificationasasinglemodelsearchinput.This opera-tioniscalledtransformationassearch(TAS).Themainideaisto de-finethetransformation/updateasasetofrelationsandconstraints betweenelementsofthemetamodelsthataretoberelated(these may be calledweavings). All these artifactsare then unified into atransformationmetamodel.Byapplyingmodelsearchonthis uni-fiedmetamodel,amodelwhichcontainstargetmodel(s)iscreated. Amajorfeatureoftheapproachisthattheoperationswhichyield themodelsearchproblemarecompletelysolver-independent,thus allowing todirectly use anyunderlying model search implemen-tation.Additionally,sinceTASsolelyusesbasicmodelingelements
(metamodelsandconstraints),nospecifictransformationlanguage isintroduced. However, one could define a higher-level language toeasethe writingofspecifications(or useanexisting language) andthemimplementatranslationintoaweavingmetamodeland itsconstraints.
Anotherimportantfeatureisthattheoperationisinherently bi-directional and incremental: the same specification can be used to generate any (or extend previously existing) weaved models. Indeed,in aTAS operation,source/targetmetamodels are treated equally in the specification and only make sense once a given transformationscenario hasbeen requested. Inthe following,we willthuscalltheweavedmetamodelsinputmetamodelsinsteadof source/targetmetamodels.FinallyTASisnotrestrictedto
one-and-one scenarios: any numberof input metamodels can be weaved
withinasinglespecification.
Inthe next subsections,we first introduce arunning example andthreepossiblescenarios.WethenformallydefinetheTAS op-eration andthedifferentsteps involved, withillustrationson the first classical scenario (creation of a target model froma source model).We thenpresenthow TAScan be appliedtothe running exampleforthe twoother scenarios:reverse transformationsand updates.Finally,we describeourTAS implementationandprovide someexperimentalresults.
4.1. Runningexample
The chosen example is a transformation between a class
schema model (MMCS) and a relational schema model (MMRS), knownastheClass2Relationaltransformation.Wehavechosenthis usecaseasillustration becauseit iswell-known andrather sim-ple(allowingthereadertoquicklygrasptheinvolveddomain con-cepts) and has been studied in other works to demonstrate dif-ferentaspectsabouttransformationlanguages(suchasQVT,2011; Lawley and Steel, 2005, and others). The transformation input metamodelsarepresentedatbothsidesofFig.10(someelements havebeenomittedtoimprovereadability).
The first scenario is the traditional creation of a relational schema(thetargetmodel)fromaclassschema(thesourcemodel). The second scenario is the reverse transformation: creation of a classschemafromarelationalschema.Thethirdscenarioisan
Fig. 11. Source and target models from the running example (scenario 1) as in- stance diagrams.
date:bothmodelspre-exist,thentheclassschemaismodifiedand therelationalschemaneedstobeupdatedaccordingly.
We will apply the scenarios on a “Family” classschema illus-tratedatthetopofFig.11.Thebottompartisarelationalschema createdbythefirstscenario,andisalsothesourceforthesecond scenario.
4.2.Transformationassearchprocess
ThecompleteTASprocess isillustratedinFig.12.Itconsistsof threemainsteps:creatingthemodelsearch problem,runningthe search,then isolatingthe target modelsfromthesolution model. Creating the model search is itself composed of two subtasks: creatingthe search metamodel(i.e., the problemdefinition, here calledthe transformationmetamodel)andcreatingthesearch re-quest(i.e., thepartial assignment, herecalled the transformation request).Eachofthesetasksisformallydefinedanddetailedinthe followingalongwithitsillustrationonourexample’sfirstscenario.
4.2.1. Obtainingthetransformationmetamodelbyunification
The first step isto obtain a transformation metamodel,called
CMMT,by unificationoftheinput (
{
CMM0,...,CMMn}
) and weav-ing(CMMW) metamodels.Thispartofthe processisindependent fromthechosentransformationscenario.In ourexample,theseare respectivelytheclass schema struc-ture (left part of Fig. 10), the relational schema structure (right part),andasetofweavingelementsandconstraints(middlepart, constraintsare not shown in the Figure). The application of this operationtoour exampleisillustrated inFig.13. Itsresultis the wholeFig.10.
Metamodelunification isa simpleoperation,consistingmerely incopyingandcombiningtheinputsintoanewmetamodel. For-maldefinitionsofCMMWandCMMTaregivenbelow:
Definition 11 (weaving metamodel). We call weaving metamodel
between
{
CMM0,...,CMMn}
,aconstrainedmetamodelCMMW de-fined by CMMW=<MMW,CW>, where MMW and CW arere-spectively a set of metamodel elements and constraints that
define the weaving relationships between the elements of
{
CMM0,...,CMMn}
.InECORE,theweavingmetamodeltargetstheinput metamod-elselementsthroughtheuseofcross-modelreferences.
Definition12 (transformationmetamodel). LetCMMWbea weav-ing metamodel and
{
CMM0,...,CMMn}
the set of weaved meta-models.Wecalltransformationmetamodeltheconstrained meta-model CMMT defined by CMMT=<MMT,CT>, where MMT=MM0∪...∪MMn∪MMWandCT=Ci∪...∪Cn∪CW.Theoperation consistinginobtainingCMMTiscalledmetamodelunification.
Obviously,in ECORE,metamodel unification turnscross-model referencesinthe weavingmetamodelinto intra-modelreferences inthetransformationmetamodel.
4.2.2. Creatingthetransformationrequestbyunification
The next step is to define the transformation request (which willactasthemodelsearch request).Therequestdependsonthe chosen scenario,which is definedby settinga behaviouron each modelofthe input metamodels.Three behavioursaresupported:
generate, freeze and extend. These behaviours allow the selection ofa scenario byspecifying whichmodels are partof therequest andwhichshouldbe generated.Alsowhetherornot theycan be modified in the final solution. “generate” means that the model does not yet exist and should be created by the transformation. Inother words,itisatarget modelcreatedfromscratch.“freeze” means that the model exists andshould not be modified by the transformation.In other words,it isan immutable sourcemodel. Finally“extend” means themodelexists butmaybe modifiedby thetransformation.Inotherwords,itisbothasourceandatarget model.Thedifferentcombinationsofthesebehavioursgivebirthto thepotentialscenarios.Inourexample’sfirstscenario,theclassical Class2Relationaltransformation,theclassschemaissetto“freeze” whiletherelationalschemaissetto“generate”.
The transformation request is obtained by unification of all sourcemodelsandoptionallyaweavingmodel(thelatterisa pre-vioustransformationtraceandcanbeusedforupdatescenarios).
Definition13(transformationrequest). LetCMMTbea transforma-tion metamodelcreatedfroma setofinput (andweaving) meta-models S=
{
CMM0,...,CMMn,CMMW}
. Let s={
M0,...,Mp,MW}
be aset ofsource (andweaving) models (where∀
Mi∈s,Mi con-forms toCMMi∈S). Wecall transformationrequest forCMMT the modelMTr definedbyMTr =M0∪· · · ∪Mp∪MW.Theoperation con-sistinginobtainingMTiscalledmodelunification.
The definition above encompasses all scenarios to depict the unification.However,someofthemodelscanbeempty/absent, de-pendingonthescenario.Thismeanstheweavingmodelisoptional whendefiningonenewinstance,butitisalwaysusedorgenerated if not existing. In our example’s first scenario,there is only one source model and no previous trace, the transformation request thereforesimplyconsistsinacopyoftheclassschemamodel ele-ments,whichisthe“Family” classschemaatthetopofFig.11.
4.2.3. Runningmodelsearch
Thenextstepistorunmodelsearchonthepreviouslydefined problem. From Definition 10, a validmodel search request (here thetransformationrequest) mustbea partialmodelofthe search metamodel (here the transformation metamodel CMMT). For any TASproblem,thispropertyisensuredbythefollowingproposition:
Proposition 1. Let CMMT be a transformation metamodel. Any
transformation request for CMMT is a partial model of (or p−
con f ormsTo)CMMT.
Proof. FromDefinition9ofp− con formsTo,itresolvestofinding a relaxed metamodelCMMT
r =<MMTr,CrT>∈Rx
(
CMMT)
such thatMT
r conformsToCMMTr.From Definition7 ofconformance,this re-quiresthat(1)MT
r conformsToMMTr and(2)MrT∈C
(
MMTr)
. LetCMMTr betherelaxedmetamodelofCMMTsuchthatMMTr =
MMT and CT
con-Fig. 12. Transformation as search process.
Fig. 13. Obtaining the example transformation metamodel by unification.
straints).(2)isobviouslytruesincetherearenopredicatesto sat-isfy. (1)requires that MMT
r can be a referencemodel ofMTr, i.e., its graph GT
r contains all nodes (meta-elements) targeted by the graph gT
r ofMTr. LetS=
{
MM0,...,MMp,MMW}
be theinput and weaving metamodels. (1) is clearly true since on one hand, byDefinition 12 of CMMT we have
∀
MMi∈S, MMi⊂ MMT (in partic-ular Gi∈GT), and on the other hand MMTr =MMT (in particular
GT
r =GT).
In other words, since each input metamodel (as well as the weavingmetamodel)isasubsetofthetransformationmetamodel
and each source model conforms to an input metamodel, any
transformationrequestp− con formsTo to the latter.
Themodelsearchoperationextendsthetransformationrequest
MT
r intoasolutionmodelMsT thatconformstoCMMT(whenthere are solutions). Bysatisfyingweavingconstraints,search thus pro-duces a solutionmodel which containsboth source/targetmodel elementsand weavingmodel elements(thesecan be understood as the transformation traces). Additionally,model search ensures that models satisfy their own metamodel constraints, effectively preventingthecreation ofill-formedtarget models.Inour exam-ple’sfirstscenario,thesolutionmodel,withoutthetransformation trace,isshowninFig.11.
4.2.4. Obtainingthetargetmodelsandtransformationtraceby separation
The final step isto isolatethe target models containedinthe solutionmodelasindependentmodels.Thisoperation,thereverse ofmodelunification,issimilarlyasimpleoperation:foreachtarget metamodelMMj,itsufficestocopyallelementsfromMT
s thatare
associatedtoMMjinto anewmodel.The sametechniquecanbe appliedtoMMWinordertoobtainthetransformationtraceasan independentmodel.Forthelatter,inECORE,weaving’sintra-model referencesarethereforeturnedintocross-modelreferences target-ing thepreviously separatedtarget models orthe original source models.
Inourexample’sfirstscenario,asampletargetmodelresultis the“Family” relationalschemacomposed onlyoftheelements il-lustratedatthebottomofFig.11.
4.2.5. Applicationonotherscenarios
As previously mentioned, different scenarios are obtained by varyingthetransformationrequestthroughthepossible combina-tionsofmodelsbehaviours.
Forour example’s reversetransformation scenario, behaviours areexchanged,i.e.,theexistingrelationalschemaissetto“freeze” (source model) and the class schema is set to “generate” (target model).Byapplyingthesameprocess,aclassschemawillbe cre-ated.Notethatdependingonthetransformationspecifications,the operationisnot necessarilybijective sinceit isnoteven injective inthegeneralcase.Howevertheoriginalclassschemais necessar-ilyamongthepotentialsolutions.
Forour example’s update scenario, theclass schema is set to “freeze” whiletherelationalschemaissetto“extend”.Asa conse-quence,therelationalschemawillbeupdated tomaintain consis-tencywiththe classschemabased ontheweaving constraints.If theoriginal schemaswere obtainedbya transformation,itstrace can be provided, effectively forcing the transformation to main-tainprevious mappings.Ifatrace isnotprovided,TAS will recre-atemappingsforallelements.Thesemaybe differentonesifthe specificationsallow it, though againthe original mapping(if any existed)isnecessarilyamongthesolutions.
Otherscenariosarepossible.Bysettingbothmodelsto“freeze”, TAScheckswhetheritispossible tomap twogivenschemasand thepotential mappingisprovidedinthetransformationtrace. By settingtwo existingschemas to “extend”,itwill allowto recover consistencybymodifyingany(orboth)model(s).
Finally,wedonotpresentanexamplewithmorethantwo
in-put metamodels (which means more than one source or target
model)sinceitdoesnotintroduceanydifferencefortheTAS pro-cess:anynumberofinputmetamodelscanbeweavedbya specifi-cationwhileapplyingtheexactsameprocess.Inotherwords,TAS isnotlimitedtoone-and-onetransformations/updates.
Fig. 14. TAS launch configuration screenshot.
4.3.Implementation
Thetransformation/synchronization(UIandAPI)softwareparts implementthe completeTAS chainillustratedin Fig.12.Again,it isfreely distributed asa setof Eclipse pluginsunderEPL license (MOS,2018).
The input, illustrated on the runningexample asa UI screen-shot in Fig. 14, is a TAS specification: the weaving constrained metamodel,theinvolvedconstrainedmetamodels,theoptional in-putandtrace models,andfinally thechoice ofmodelbehaviours (whichdefinethescenariobeingrequested).
The TAS designer, i.e.,the useroftheframework that will ex-ecute a TAS operation, has to create a set of minimal artifacts forperforming model transformations, i.e., a TAS specification. It needstospecifythesourceandtargetmetamodelsandthe weav-ingmetamodel,tobeabletocreaterelationshipbetweenthe ele-ments.ThemetamodelsneedtobewritteninECORE.Inaddition, itisalso necessaryto createatleastone sourceortarget model, depending on the direction of the transformation. The 3rd sce-nario(synchronization)isalsointerestingforillustratingthe multi-leveltransformation. Consider the need to translate the instances ofthe Class andRelational metamodels into thesolver format: it isnotnecessarytodevelopClass2AlloyorRelational2Alloy transfor-mations.
Other artifactsmaybe created aswell, to obtain a more pre-cisespecification,suchastheOCLconstraintsoverthesourceand targetmetamodels.Finally,analreadyexistingweavingmodelmay alsobe setupasparameter, asinthesynchronizationscenario.It willenforcetheexistenceofthealreadycreatedrelationships.
Wehaveoptednottocreateanewtransformationlanguageor touseexistingones,such asATL orQVT. Thetransformationsare
createdonlyusingmodels/metamodelsandOCLconstraints. How-ever,these languagescould be integratedintothe framework, by developing thetransformations for the ATL orQVT specifications intoourModelSearchlayer.Toimplementthis,thetransformation languagewouldneedtohaveatransformationmodelanda meta-model.
The TAS specification is then translated into a Model Search
problem followingthe metamodel and request modelunification steps previously presented: the search metamodel (which yields the problem definition) is set to the generated transformation metamodel, andthe search root model (which yields the partial assignment)issetto thegeneratedtransformationrequest.These steps are implemented using EMF’s Java API. Additionally, when a model behaviour is setto “freeze”, two elementsare added to the resulting model search specification. First, the model search scope sets each class bound to the numberof corresponding in-stances in the frozen source models. However, this is not suf-ficient since structural features may still be modified. A second option is set, presented in Section3.4.4, which freezes attributes and references of the corresponding frozen parts of the root model.
Inorderto obtainthe output(s),ourTAS implementation pro-videsa solutionexplorer interfacethat embeds themodel search solutionsexplorer.Eachtimeanewsolutionisrequested,the un-derlying model search problemis solved usingthe chosen solver chain. As previously presented, the solution (if any) is separated to obtain the target models and the transformation trace. Again, thesesolver-independent steps are realized usingEMF’s Java API, similarly to (meta)modelunification. The currentimplementation savesalltheintermediatefilesgeneratedduringtheprocess,such asthesolverspecifications,thesolutionmodel,thetransformation modelandmetamodels,andothers.Thisenablesadetailed analy-sisofeachexecutionstepoftheTASchain.
4.4. Results
We provideresultson therunning exampleandan additional specificationtakenfromtheliterature.Experimentalconditionsare thesameastotheonespresentedinSection3.5.Similarly, wedo notaimatevaluatingabsoluteperformance(whichhighlydepends onthechosensolverchain)butratherfocusonthedifferences be-tweenscenarii,specificationsandprobleminstances.Thereforewe provide resultswith a fixed backend(Alloy/MiniSAT), scope ratio (3:1),andbitwidth(5).Alltheseexperimentsareavailablefor re-productioninMOS(2018).
4.4.1. Resultsontherunningexample
Scenarii, specifications and problem instances. We executed 3 dis-tinctscenarii:
• Theforwardtransformationpresentedin therunningexample (fromclasstorelational).Inthiscase, wesetto freezethe left modelandtogeneratetherightmodel,whichwillbegenerated fromscratch.
• Thereverse transformation(from relationalto class). We con-figuretofreezetherightmodelproducedfromscenario1,and weproduceanewleftmodel.
• A synchronizationscenario (propagation of changes from one model to another after adding one new element to the class metamodel).Wesetfreezetotheleftmodel,extendtotheright model, and provide the trace from the first scenario as the startingweavingmodel.
Thespecifications,that isthethreemetamodelsandtheir con-straints, are exactly the same for the three scenarii. In order to illustrate how transformations are specified in our approach, we
providebelowsome exampleconstraintsthatapply onthe trans-formationtogetherwithabriefexplanation.Theseconstraints, to-gether withtheinput metamodelsandmodelsare translatedinto anAlloyprogram.Thecompletelistofgeneratedconstraints,in Al-loy,arelistedinAppendixB.
• c.1: prevents a class from having several attributes with the samename.Appliestoany(sourceortarget)Classmodel; • c.2: specifies the cardinality of the link, i.e., that a Class is
linkedwithonlyoneTable;
• r.1:setsthetypeofaprimary keycolumnto”Integer”.Applies toany(sourceortarget)relationalmodel;
• c4r.1:weavedclassesandtablesmusthavethesamename; • c4r.2: for single-valued attributes, weaved attributes and
columnsmusthavethesameowner,i.e.,their containingClass
andTable;
• c4r.3:thesourcecolumnofanN-Nrelationshipmustbea for-eignkeytotheattribute’sowningclass.
Writing OCLconstraintsforTAS specificationsisverydifferent fromwritingclassicalrule-basedtransformations.Indeed,thegoal here is to narrowthe set of possible solutions to the acceptable ones by incrementally adding constraints. If one so wishes, it is possible touse adedicated language (suchasQVT-R) thatwould then be translatedto a weavingconstrained metamodel.Our ap-proach is very expressive, since the approach is not dependent of the top transformation language, but on the definition of the weavingmodels.Thechoiceofagiventransformationlanguage,or a subset of it, is a trade-off between expressiveness and usabil-ity. The iterative process of creating weaving specificationsoften showsthe modeler that source/targetmetamodelconstraints had notbeenfullyspecified,forinstancebyprovingthatbadly-formed modelscanbecreated.However,discussingthedetailsofthis im-plementationisoutofscopeofthispaper.
Finally, we provide experiments on two different problems whilegraduallyincreasingtheinstancessize:theinstanceswe pre-viously generatedusingmodelsearch;andthefamily-person cus-tom diagram depicted inFig. 11 forwhich we gradually add at-tributestooneclass.
Results. Fig.15summarizestheresultsforthissetofexperiments.
Fig. 15. Results on the running example.
First, we can obviously note the difference of magnitude be-tweenthedifferentscenarios.Forthegenerateddiagrams,scenario 1topsat18s,scenario2at113sandscenario3atonly6s.The lat-teriseasytoexplain.Indeed,whiletheglobalnumberoffinal el-ementsisthesame,mostofthemalreadyexistandareweavedin theoriginaltrace (thiscanbeseen bylookingattheinitial num-berofelements, i.e, thegivenpartial assignmentsize). Thus only theadded elementscreate search decisions resultingin a slower computationalincreasealong withtheproblemsize.Thismay in-dicate thatthe approach isparticularlyfitted forthe update sce-nario.Thedifferencesbetweenthefirst twoscenarios arethe