Parcourir la source

sync my files after latest merge from upstream, cleaned up a bit, adapted code to new exceptions

Lucas Heer il y a 8 ans
Parent
commit
ec9b3d7dd6

+ 104 - 0
alc_io.py

@@ -0,0 +1,104 @@
+"""
+Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)
+
+Date:   Wed Apr  4 23:27:30 2018
+
+Model author: Lucas Heer
+Model name:   ALC_IO
+Model description:
+I/O Statechart for passing data to ALC
+"""
+
+from sccd.runtime.statecharts_core import *
+
+# package "ALC_IO"
+
+class ALC_IO(RuntimeClassBase):
+    def __init__(self, controller):
+        RuntimeClassBase.__init__(self, controller)
+        
+        self.semantics.big_step_maximality = StatechartSemantics.TakeMany
+        self.semantics.internal_event_lifeline = StatechartSemantics.Queue
+        self.semantics.input_event_lifeline = StatechartSemantics.FirstComboStep
+        self.semantics.priority = StatechartSemantics.SourceParent
+        self.semantics.concurrency = StatechartSemantics.Single
+        
+        # build Statechart structure
+        self.build_statechart_structure()
+        
+        # call user defined constructor
+        ALC_IO.user_defined_constructor(self)
+    
+    def user_defined_constructor(self):
+        pass
+    
+    def user_defined_destructor(self):
+        pass
+    
+    
+    # builds Statechart structure
+    def build_statechart_structure(self):
+        
+        # state <root>
+        self.states[""] = State(0, "", self)
+        
+        # state /init
+        self.states["/init"] = State(1, "/init", self)
+        
+        # state /finished
+        self.states["/finished"] = State(2, "/finished", self)
+        
+        # add children
+        self.states[""].addChild(self.states["/init"])
+        self.states[""].addChild(self.states["/finished"])
+        self.states[""].fixTree()
+        self.states[""].default_state = self.states["/init"]
+        
+        # transition /init
+        _init_0 = Transition(self, self.states["/init"], [self.states["/init"]])
+        _init_0.setAction(self._init_0_exec)
+        _init_0.setTrigger(Event("input", "inp"))
+        self.states["/init"].addTransition(_init_0)
+        _init_1 = Transition(self, self.states["/init"], [self.states["/finished"]])
+        _init_1.setTrigger(Event("terminate", "inp"))
+        self.states["/init"].addTransition(_init_1)
+        _init_2 = Transition(self, self.states["/init"], [self.states["/init"]])
+        _init_2.setAction(self._init_2_exec)
+        _init_2.setTrigger(Event("data_inp", "datap"))
+        self.states["/init"].addTransition(_init_2)
+    
+    def _init_0_exec(self, parameters):
+        value = parameters[0]
+        print(value)
+    
+    def _init_2_exec(self, parameters):
+        value = parameters[0]
+        print("SC: Got data {}".format(value))
+        self.big_step.outputEvent(Event("output", "outp", [value]))
+    
+    def initializeStatechart(self):
+        # enter default state
+        self.default_targets = self.states["/init"].getEffectiveTargetStates()
+        RuntimeClassBase.initializeStatechart(self)
+
+class ObjectManager(ObjectManagerBase):
+    def __init__(self, controller):
+        ObjectManagerBase.__init__(self, controller)
+    
+    def instantiate(self, class_name, construct_params):
+        if class_name == "ALC_IO":
+            instance = ALC_IO(self.controller)
+            instance.associations = {}
+        else:
+            raise Exception("Cannot instantiate class " + class_name)
+        return instance
+
+class Controller(ThreadsControllerBase):
+    def __init__(self, keep_running = None, behind_schedule_callback = None):
+        if keep_running == None: keep_running = True
+        if behind_schedule_callback == None: behind_schedule_callback = None
+        ThreadsControllerBase.__init__(self, ObjectManager(self), keep_running, behind_schedule_callback)
+        self.addInputPort("datap")
+        self.addInputPort("inp")
+        self.addOutputPort("outp")
+        self.object_manager.createInstance("ALC_IO", [])

+ 41 - 0
alc_io.xml

@@ -0,0 +1,41 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<diagram author="Lucas Heer" name="ALC_IO">
+    <description>
+        I/O Statechart for passing data to ALC
+    </description>
+
+    <inport name="datap"/>
+    <inport name="inp"/>
+    <outport name="outp"/>
+
+    <class name="ALC_IO" default="true">
+        <scxml initial="init">
+            <state id="init">
+                
+                <transition event="input" port="inp" target=".">
+                    <parameter name="value"/>
+                    <script>
+                        print(value)
+                    </script>
+                </transition>
+                <!-- <transition after="0.1" target="."/> -->
+                <transition event="terminate" port="inp" target="../finished"/>
+                <transition event="data_inp" port="datap" target=".">
+                    <parameter name="value"/>
+                    <script>
+                        print("SC: Got data {}".format(value))
+                    </script>
+                    <raise event="output" port="outp" scope="output">
+                        <parameter expr="value"/>
+                    </raise>
+                </transition>
+            </state>
+
+            <state id="finished">
+                <script>
+                    print("FINISHED SC")
+                </script>
+            </state>
+        </scxml>
+    </class>
+</diagram>

+ 48 - 0
evolution.py

@@ -0,0 +1,48 @@
+import wrappers.modelverse as mv
+
+
+def _get_nodes_with_type(model, typ):
+    """ Returns a list of nodes in model model with type typ """
+    all_nodes = mv.all_instances(model, "Node")
+    ret = [node for node in all_nodes if mv.read_attrs(model, node)["type"] == typ]
+    return ret
+
+def _get_all_models():
+    """ Returns a list of paths of all example- and instance models """
+    example_models = mv.model_list("models/example")
+    example_models_full = ["models/example/"+exm for exm in example_models]
+    instance_models = mv.model_list("models/instance")
+    instance_models_full = ["models/instance/"+m for m in instance_models]
+    return example_models_full + instance_models_full
+
+def retype_node(model, node, new_type, local):
+    """
+    Retype the node in model to new_type.
+    If local is true, the change only affects the single node.
+    If local is false, the change affects all nodes in all models.
+    """
+    if local:
+        mv.attr_assign(model, node, "type", new_type)
+    else:
+        node_type_old = mv.read_attrs(model, node)["type"]
+        all_models = _get_all_models()
+        for m in all_models:
+            nodes = _get_nodes_with_type(m, node_type_old)
+            for node in nodes:
+                mv.attr_assign(m, node, "type", new_type)
+
+
+def add_node(model, node_type, local):
+    """
+    Add a new node with ID node and type node_type to model model.
+    If local is true, the node is only added to the passed model.
+    If local is false, the node will be added to all models.
+    """
+    if local:
+        ID = mv.instantiate(model, "Node")
+        mv.attr_assign(model, ID, "type", node_type)
+    else:
+        all_models = _get_all_models()
+        for m in all_models:
+            ID = mv.instantiate(model, "Node")
+            mv.attr_assign(model, ID, "type", node_type)

+ 25 - 0
helpers.py

@@ -0,0 +1,25 @@
+import wrappers.modelverse as mv
+
+def upload_mm(name, filepath):
+    """
+    Upload a metamodel conforming to SimpleClassDiagrams
+    Read from text file at "filepath" and save under path "name"
+    Overwrite if already exists
+    """
+    try:
+        content = open(filepath).read()
+    except IOError:
+        print("Upload: Model \"{}\" cannot be found".format(filepath))
+        return False
+
+    try:
+        # add new model
+        mv.model_add(name, "formalisms/SimpleClassDiagrams", content)
+    except mv.UnknownError:  # why not ModelExists exception?
+        # update
+        mv.model_overwrite(name, content)
+    except Exception as e:
+        print("Upload: Failed, reason: {}".format(e))
+        return False
+
+    return True

+ 144 - 0
main.py

@@ -0,0 +1,144 @@
+import wrappers.modelverse as mv
+from verifyer import verify
+from evolution import retype_node
+
+
+def upload_graph_MM():
+    print("Uploading graph metamodel ...")
+    
+    try:
+        mv.model_delete("formalisms/graphMM")
+    except mv.UnknownLocation:
+        pass
+    
+    content = open("models/sketching/graphMM.mvc").read()
+    mv.model_add("formalisms/graphMM", "formalisms/SimpleClassDiagrams", content)
+
+def upload_example_models():
+    print("Uploading example models ...")
+    # clear all example models
+    try:
+        mv.model_delete("models/example")
+    except mv.UnknownLocation:
+        # folder does not exist, ignore
+        pass
+    content = open("models/sketching/example_model_1.mvc").read()
+    mv.model_add("models/example/ex1", "formalisms/graphMM", content)
+    mv.verify("models/example/ex1", "formalisms/graphMM")
+    
+    content = open("models/sketching/example_model_2.mvc").read()
+    mv.model_add("models/example/ex2", "formalisms/graphMM", content)
+    mv.verify("models/example/ex2", "formalisms/graphMM")
+
+def upload_instance_model():
+    print("Uploading instance model ...")
+    # clear all example models
+    try:
+        mv.model_delete("models/instance")
+    except mv.UnknownLocation:
+        # folder does not exist, ignore
+        pass
+    content = open("models/sketching/instance_model.mvc").read()
+    mv.model_add("models/instance/im1", "formalisms/graphMM", content)
+    mv.verify("models/instance/im1", "formalisms/graphMM")  
+
+
+def upload_rename_alc():
+    print("Loading rename ALC ...")
+    try:
+        mv.model_delete("models/graph_ops/rename")
+    except mv.UnknownLocation:
+        pass
+
+    mv.transformation_add_AL({"instance": "formalisms/graphMM"}, {"rename_out": "formalisms/graphMM"},
+                             "models/graph_ops/rename", open("models/lucas/rename.alc").read())
+
+
+def exec_rename_alc():
+    print("Executing rename ALC ...")
+    try:
+        mv.model_delete("models/rename_out")
+    except mv.UnknownLocation:
+        pass    
+
+    """
+    ctrl = Controller(keep_running=False)
+    thrd = Thread(target=ctrl.start)
+    thrd.daemon = True
+    thrd.start()
+    """
+    
+    mv.transformation_execute_AL("models/graph_ops/rename",
+                                 {"instance": "models/instance/im1"},
+                                 {"rename_out": "models/rename_out"})
+
+    """
+    # TODO: Wait until ALC is ready to accept input, maybe there is a way to wait for output events?
+    try:
+        while True:
+            # pass data to ALC via statechart
+            inp = raw_input("Input:")
+            ctrl.addInput(Event("data_inp", "datap", [inp]))
+    except KeyboardInterrupt:
+        ctrl.addInput(Event("terminate", "inp"))
+    print("Done")
+    """
+    
+"""
+def upload_verify_alc():
+    print("Loading verify ALC ...")
+    try:
+        mv.model_delete("models/graph_ops/verify")
+    except mv.UnknownError:
+        pass
+    mv.transformation_add_AL({"instance": "formalisms/graphMM"}, {"out": "formalisms/graphMM"},
+                             "models/graph_ops/verify", open("models/lucas/verify.alc").read())
+  
+
+def exec_verify_alc():
+    print("Executing verify ALC ...")
+    try:
+        mv.model_delete("models/verify_out")
+    except mv.UnknownError:
+        pass
+    
+    mv.transformation_execute_AL("models/graph_ops/verify",
+                                 {"instance": "models/instance/im1"},
+                                 {"out": "models/verify_out"})
+    
+"""
+
+
+def callback():
+    ID = mv.instantiate(None, "pn/Node")
+
+if __name__ == "__main__":
+    mv.init()
+    mv.login("admin", "admin")
+    upload_graph_MM()
+    upload_example_models()
+    upload_instance_model()
+    
+    """
+    print("Performing local rename ...")
+    mv.transformation_add_MANUAL({"gm":"formalisms/graphMM"}, {"gm":"formalisms/graphMM"}, "graph_ops/rename")
+    mv.transformation_execute_MANUAL("graph_ops/rename", {"gm":"models/example/ex1"}, {"gm":"models/example/ex1"}, 
+                                     callback=callback)
+    print(mv.element_list_nice("models/example/ex1"))
+    """
+    
+    """
+    print("Retyping node ...")
+    retype_node("models/example/ex1", "n2", "PesonalComputer", local=False)
+    
+    upload_rename_alc()
+    exec_rename_alc()
+    upload_verify_alc()
+    exec_verify_alc()
+    """
+    print("Verifying instance model ...")
+    ret = verify("models/instance/im1")
+    if not ret["OK"]:
+        print(ret["error"])
+    else:
+        print("Verify OK")

+ 32 - 0
models/sketching/example_model_1.mvc

@@ -0,0 +1,32 @@
+Model m1 {
+    descr = "Router-PC"
+    is_example = True
+}
+
+Node n1 {
+    type = "Router"
+}
+
+Node n2 {
+    type = "PC"
+}
+
+Node n3 {
+    type = "PC"
+}
+
+Node n4 {
+    type = "NAS"
+}
+
+Edge e1(n1, n2) {
+    directed = False
+}
+
+Edge e2(n1, n3) {
+    directed = False
+}
+
+Edge e3(n1, n4) {
+    directed = False
+}

+ 47 - 0
models/sketching/example_model_2.mvc

@@ -0,0 +1,47 @@
+Model m2 {
+    descr = "Router-AP"
+    is_example = True
+}
+
+Node n1 {
+    type = "Router"
+}
+
+Node n2 {
+    type = "AP"
+}
+
+Node n3 {
+    type = "Tablet"
+}
+
+Node n4 {
+    type = "Phone"
+}
+
+Node n5 {
+    type = "PC"
+}
+
+Attribute a1 {
+    key = "owner"
+    value = "Peter"
+}
+
+NodeAttribute na1(n5, a1) {}
+
+Edge e1(n1, n2) {
+    directed = False
+}
+
+Edge e2(n2, n3) {
+    directed = False
+}
+
+Edge e3(n2, n4) {
+    directed = False
+}
+
+Edge e4(n1, n5) {
+    directed = False
+}

+ 57 - 0
models/sketching/graphMM.mvc

@@ -0,0 +1,57 @@
+include "primitives.alh"
+
+SimpleAttribute String {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_string(value)):
+                    return "OK"!
+                else:
+                    return "String has a non-string value"!
+            $
+}
+
+SimpleAttribute Integer {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_int(value)):
+                    return "OK"!
+                else:
+                    return "Integer has a non-integer value"!
+            $
+}
+
+SimpleAttribute Boolean {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_boolean(value)):
+                    return "OK"!
+                else:
+                    return "Boolean has a non-boolean value"!
+            $
+}
+
+Class Model {
+    name = "Model"
+    descr : String
+    is_example : Boolean
+}
+
+Class Node {
+    name = "Node"
+    type : String
+}
+
+Association Edge(Node, Node) {
+    name = "Edge"
+    directed : Boolean
+}
+
+Class Attribute {
+    name = "Attribute"
+    key : String
+    value : String
+}
+
+Association NodeAttribute(Node, Attribute) {
+    name = "NodeAttribute"
+}

+ 53 - 0
models/sketching/instance_model.mvc

@@ -0,0 +1,53 @@
+Model m1 {
+    descr = "Model_1"
+    is_example = False
+}
+
+Node n1 {
+    type = "Router"
+}
+
+Node n2 {
+    type = "PC"
+}
+
+Attribute a1 {
+    key = "owner"
+    value = "Tom"
+}
+
+Attribute a2 {
+    key = "IP"
+    value = "192.1.1.1"
+}
+
+NodeAttribute na1(n2, a1) {}
+NodeAttribute na2(n1, a2) {}
+
+Node n3 {
+    type = "AP"
+}
+
+Node n4 {
+    type = "Phone"
+}
+
+Node n5 {
+    type = "Phone"
+}
+
+Edge e1(n1, n2) {
+    directed = False
+}
+
+Edge e2(n1, n3) {
+    directed = False
+}
+
+Edge e3(n3, n4) {
+    directed = False
+}
+
+Edge e4(n3, n5) {
+    directed = False
+}

+ 14 - 0
models/sketching/rename.alc

@@ -0,0 +1,14 @@
+include "primitives.alh"
+
+
+Boolean function main(model : Element):
+    Element value
+    String from_name
+    String to_name
+    from_name = "Router"
+    to_name = "DSL Router"
+    
+    log("Renaming from " + from_name + " to " + to_name)
+    
+    
+    return True!

+ 70 - 0
models/sketching/render/MM_consyntax.mvc

@@ -0,0 +1,70 @@
+include "primitives.alh"
+
+SimpleAttribute Integer {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_int(value)):
+                    return "OK"!
+                else:
+                    return "Integer has a non-integer value"!
+            $
+}
+
+SimpleAttribute String {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_string(value)):
+                    return "OK"!
+                else:
+                    return "String has a non-string value"!
+            $
+}
+
+SimpleAttribute Float {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_float(value)):
+                    return "OK"!
+                else:
+                    return "Float has a non-float value"!
+            $
+}
+
+
+Class Element {
+    name = "Element"
+    typeID : String
+}
+
+Class Icon : Element {
+    name = "Icon"
+    data : String
+    scale : Float
+}
+
+Class PrimitiveGroup : Element {
+    name = "PrimitiveGroup"
+}
+
+Class Primitive {
+    name = "Primitive"
+}
+
+Class Rectangle : Primitive {
+    name = "Rectangle"
+    x : Integer
+    y : Integer
+    width : Integer
+    height : Integer
+}
+
+Class Circle : Primitive {
+    name = "Circle"
+    x : Integer
+    y : Integer
+    radius : Integer
+}
+
+Association PrimitiveGroupPrimitive(PrimitiveGroup, Primitive) {
+    name = "PrimitiveGroupPrimitive"
+}

+ 47 - 0
models/sketching/render/MM_render.mvc

@@ -0,0 +1,47 @@
+include "primitives.alh"
+
+SimpleAttribute Integer {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_int(value)):
+                    return "OK"!
+                else:
+                    return "Integer has a non-integer value"!
+            $
+}
+
+SimpleAttribute String {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_string(value)):
+                    return "OK"!
+                else:
+                    return "String has a non-string value"!
+            $
+}
+
+
+Class GraphicalElement {
+    name = "GraphicalElement"
+    x : Integer
+    y : Integer
+}
+
+Class Symbol : GraphicalElement {
+    name = "Icon"
+    typeID : String
+    __asid : String
+}
+
+Class TextLabel : GraphicalElement {
+    name = "TextLabel"
+    text : String
+}
+
+Association ConnectingLine(Symbol, Symbol) {
+    name = "ConnectingLine"
+}
+
+Association SymbolTextLabel(Symbol, TextLabel) {
+    name = "SymbolTextLabel"
+}

+ 20 - 0
models/sketching/render/example_model.mvc

@@ -0,0 +1,20 @@
+Symbol sym1 {
+    typeID = "Router"
+}
+
+Symbol sym2 {
+    typeID = "PC"
+}
+
+Symbol sym3 {
+    typeID = "PC"
+}
+
+Attribute att1 {
+    key = "IP"
+    value = "192.168.0.1"
+}
+
+SymbolAttribute(sym1, att1) {}
+Link(sym1, sym2) {}
+Link(sym1, sym3) {}

+ 76 - 0
models/sketching/render/render_mapper.alc

@@ -0,0 +1,76 @@
+include "primitives.alh"
+include "modelling.alh"
+include "object_operations.alh"
+include "utils.alh"
+
+
+Boolean function main(model : Element):
+    Element elements
+    String class
+    String elem
+    String name
+    String symbol
+    String label
+    Integer xloc
+    String as_src
+    String as_dest
+    String link
+
+    Element symbols_dict
+    symbols_dict = dict_create()
+
+
+    // Clear model
+    elements = allInstances(model, "rendered/GraphicalElement")
+    while (set_len(elements) > 0):
+        class = set_pop(elements)
+        model_delete_element(model, class)
+
+    // render symbols
+    xloc = 0
+    elements = allInstances(model, "abstract/Symbol")
+    while (set_len(elements) > 0):
+        class = set_pop(elements)
+        name = read_attribute(model, class, "typeID")
+
+        symbol = instantiate_node(model, "rendered/Symbol", "")
+        instantiate_attribute(model, symbol, "x", xloc)
+        instantiate_attribute(model, symbol, "y", 0)
+        instantiate_attribute(model, symbol, "typeID", name)
+        instantiate_attribute(model, symbol, "__asid", list_read(string_split_nr(class, "/", 1), 1))
+        xloc = xloc + 200
+        dict_add(symbols_dict, class, symbol)
+
+    // abstract links between symbols to concrete connecting lines between icons
+    elements = allInstances(model, "abstract/Link")
+    while (set_len(elements) > 0):
+        class = set_pop(elements)
+        as_src = readAssociationSource(model, class)
+        as_dest = readAssociationDestination(model, class)
+
+        link = instantiate_link(model, "rendered/ConnectingLine", "", symbols_dict[as_src], symbols_dict[as_dest])
+
+    // render attributes to text labels
+    xloc = 0
+    elements = allInstances(model, "abstract/Attribute")
+    while (set_len(elements) > 0):
+        class = set_pop(elements)
+        name = cast_string(read_attribute(model, class, "key")) + "=" + cast_string(read_attribute(model, class, "value"))
+
+        label = instantiate_node(model, "rendered/TextLabel", "")
+        instantiate_attribute(model, label, "text", name)
+        instantiate_attribute(model, label, "x", xloc)
+        instantiate_attribute(model, label, "y", 80)
+        xloc = xloc + 200
+        dict_add(symbols_dict, class, label)
+
+    // abstract SymbolAttribute association to concrete IconTextLabel
+    elements = allInstances(model, "abstract/SymbolAttribute")
+    while (set_len(elements) > 0):
+        class = set_pop(elements)
+        as_src = readAssociationSource(model, class)
+        as_dest = readAssociationDestination(model, class)
+
+        instantiate_link(model, "rendered/SymbolTextLabel", "", symbols_dict[as_src], symbols_dict[as_dest])
+
+    return True!

+ 32 - 0
models/sketching/render/sketch_CS.mvc

@@ -0,0 +1,32 @@
+PrimitiveGroup pg1 {
+    typeID = "Router"
+}
+
+Rectangle r1 {
+    x = 0
+    y = 0
+    width = 80
+    height = 50
+}
+
+Circle c1 {
+    x = 10
+    y = 10
+    radius = 20
+}
+
+PrimitiveGroupPrimitive(pg1, r1) {}
+PrimitiveGroupPrimitive(pg1, c1) {}
+
+
+PrimitiveGroup pg2 {
+    typeID = "PC"
+}
+
+Circle c2 {
+    x = 0
+    y = 0
+    radius = 50
+}
+
+PrimitiveGroupPrimitive(pg2, c2) {}

+ 30 - 0
models/sketching/render/sketch_MM.mvc

@@ -0,0 +1,30 @@
+include "primitives.alh"
+
+SimpleAttribute String {
+    constraint = $
+            String function constraint(value : Element):
+                if (is_physical_string(value)):
+                    return "OK"!
+                else:
+                    return "String has a non-string value"!
+            $
+}
+
+Class Symbol {
+    name = "Symbol"
+    typeID : String
+}
+
+Class Attribute {
+    name = "Attribute"
+    key : String
+    value : String
+}
+
+Association SymbolAttribute (Symbol, Attribute) {
+    name = "SymbolAttribute"
+}
+
+Association Link (Symbol, Symbol) {
+    name = "Link"
+}

+ 16 - 0
models/sketching/verify.alc

@@ -0,0 +1,16 @@
+include "primitives.alh"
+include "services.alh"
+
+
+Boolean function main(model : Element):
+    String port
+    String ret
+
+    port = comm_connect("verify")
+    comm_set(port, "models/instance/im1")
+    
+    ret = comm_get(port)
+    log(ret)
+    comm_close(port)
+
+    return True!

+ 184 - 0
verifyer.py

@@ -0,0 +1,184 @@
+import wrappers.modelverse as mv
+
+
+class Edge(object):
+    """
+    Small helper class for association validation.
+    Stores an edge as a tuple of (source, dest)
+    """
+    def __init__(self, src, dest):
+        self.src = src
+        self.dest = dest
+    
+    def __eq__(self, other):
+        if other.src == self.src and other.dest == self.dest:
+            return True
+        return False
+    
+    def __repr__(self):
+        return "{}->{}".format(self.src, self.dest)
+
+
+class Attribute(object):
+    """
+    Helper class for attribute representation as key value pair
+    """
+    def __init__(self, key, val):
+        self.key = key
+        self.val = val
+    
+    def __eq__(self, other):
+        if other.key == self.key and other.val == self.val:
+            return True
+        return False
+    
+    def __repr__(self):
+        return "{}={}".format(self.key, self.val)
+
+# returns a list of attributes of a node with type node_type in a model
+def _get_attributes_of(node_type, model):
+    ret = []
+    node_attribute_links = mv.all_instances(model, "NodeAttribute")
+    for link in node_attribute_links:
+        src_node = mv.read_association_source(model, link)[0]
+        src_typ = mv.read_attrs(model, src_node)["type"]
+        if src_typ != node_type:
+            continue
+        attr_node_name = mv.read_association_destination(model, link)[0]
+        attr_dict = mv.read_attrs(model, attr_node_name)
+        attr = Attribute(attr_dict["key"], attr_dict["value"])
+        ret.append(attr)
+    return ret
+
+# returns the number of occurences of a node with type node_type in a model
+def _count_occurences(node_type, model):
+    ctr = 0
+    all_nodes = mv.all_instances(model, "Node")
+    for node in all_nodes:
+        typ = mv.read_attrs(model, node)["type"]
+        if typ == node_type:
+            ctr += 1
+    return ctr
+
+
+def verify(instance_model_path):
+    example_models = mv.model_list("models/example")
+    example_models_full = ["models/example/"+exm for exm in example_models]
+    
+    # 1. Check if all nodes in instance model are typed by a node in the example models
+    # For that, first get all available types from example models
+    print("Verify: checking node typing ...")
+    all_types = []
+    for exm in example_models_full:
+        all_nodes = mv.all_instances(exm, "Node")
+        for node in all_nodes:
+            typ = mv.read_attrs(exm, node)["type"]
+            if not typ in all_types:
+                all_types.append(typ)
+    #print("Verify: types found in example models: {}".format(all_types))
+
+    # Now, check for every element in instance model if it is a valid type
+    all_nodes = mv.all_instances(instance_model_path, "Node")
+    for node in all_nodes:
+        node_typ = mv.read_attrs(instance_model_path, node)["type"]
+        if node_typ not in all_types:
+            return {"OK":False, "error":"Type {} from instance model not in example models".format(node_typ)}
+
+    # 2. Check node cardinality: a node is mandatory in the instance model if it occurs in every
+    # example model. Additionally, it needs to occur at least n times if it occurs at least n times in every example model.
+    print("Verify: checking node multiplicity ...")
+    total_occurences = {k:[] for k in all_types}
+    for node, occ_list in total_occurences.iteritems():
+        for exm in example_models_full:
+            num_occ = _count_occurences(node, exm)
+            occ_list.append(num_occ)
+
+    elem_cardinality = {k:min(v) for k, v in total_occurences.iteritems()}
+    for el, min_occ in elem_cardinality.iteritems():
+        if not _count_occurences(el, instance_model_path) >= min_occ:
+            return {"OK":False, "error":"Node with type {} needs to occur at least {} times".format(el, min_occ)}
+    
+    # 3. Check attribute types: Is every attribute in instance model present in some example model?
+    print("Verify: checking attributes ...")
+    all_nodes = mv.all_instances(instance_model_path, "Node")
+    for node in all_nodes:
+        node_typ = mv.read_attrs(instance_model_path, node)["type"]
+        attrs = _get_attributes_of(node_typ, instance_model_path)
+        if len(attrs) == 0:
+            continue
+        #print("Attributes of node {} of type {} are: {}".format(node, node_typ, attrs))
+        # check example models for such an attribute key
+        for im_attribute in attrs:
+            found = False
+            for exm in example_models_full:
+                if found:
+                    break
+                exm_attrs = _get_attributes_of(node_typ, exm)
+                for exm_attr in exm_attrs:
+                    if exm_attr.key == im_attribute.key:
+                        #print("Found attribute {} in model {}".format(im_attribute, exm))
+                        found = True
+                        break
+            if not found:
+                return {"OK":False, "error":"Attribute {} not found in example models".format(im_attribute)}
+
+    # TODO: Attribute mandatory if present in all example model nodes
+    
+    
+    # 4. Associations
+    # Check multiplicity: an association needs to occur n>0 times if it occurs n>0 times in every example model
+    # Check assocation type validity as well
+    print("Verify: checking associations ...")
+    all_edges = {k:[] for k in example_models_full}
+    for exm in example_models_full:
+        all_nodes = mv.all_instances(exm, "Node")
+        for node in all_nodes:
+            node_typ = mv.read_attrs(exm, node)["type"]
+            out_associations = mv.read_outgoing(exm, node, "Edge")
+            for assoc in out_associations:
+                if assoc.startswith("__"):
+                    continue
+                target = mv.read_association_destination(exm, assoc)[0]
+                target_typ = mv.read_attrs(exm, target)["type"]
+                all_edges[exm].append(Edge(node_typ, target_typ))
+    
+    unique_edges = []
+    for edge_lst in all_edges.values():
+        for edge in edge_lst:
+            if not edge in unique_edges:
+                unique_edges.append(edge)
+    
+    edge_ctr = {k:[] for k in unique_edges}
+    for edge, ctr_lst in edge_ctr.iteritems():
+        for exm, edges in all_edges.iteritems():
+            ctr_lst.append(edges.count(edge))
+    
+    for k, v in edge_ctr.iteritems():
+        edge_ctr[k] = min(v)
+    
+    #print(edge_ctr)  # {Edge("AP", "Tablet"): 0, Edge("Router", "PC"): 1, ...}
+    
+    # check if mandatory edges are present in instance model
+    # first, get all edges in instance model
+    all_edges = mv.all_instances(instance_model_path, "Edge")
+    im_edges = []
+    for edge in all_edges:
+        if edge.startswith("__"):
+            continue
+        edge_src = mv.read_association_source(instance_model_path, edge)[0]
+        edge_dest = mv.read_association_destination(instance_model_path, edge)[0]
+        edge_src_typ = mv.read_attrs(instance_model_path, edge_src)["type"]
+        edge_dest_typ = mv.read_attrs(instance_model_path, edge_dest)["type"]
+        im_edges.append(Edge(edge_src_typ, edge_dest_typ))
+    
+    # Check if all edges in instance models are valid (connecting types correspond to example models)
+    for edge in im_edges:
+        if edge not in edge_ctr.keys():
+            return {"OK":False, "error":"Edge {} not valid according to example models".format(edge)}
+    
+    # now, check if for every mandatory edge, it occurs sufficiently enough
+    for edge, cnt in edge_ctr.iteritems():
+        if im_edges.count(edge) < cnt:
+            return {"OK":False, "error":"Edge {} needs to appear {} times in instance model".format(edge, cnt)}
+
+    return {"OK":True, "error":None}

+ 0 - 0
wrappers/__init__.py


+ 1 - 1
wrappers/modelverse_SCCD.py

@@ -1,7 +1,7 @@
 """
 Generated by Statechart compiler by Glenn De Jonghe, Joeri Exelmans, Simon Van Mierlo, and Yentl Van Tendeloo (for the inspiration)
 
-Date:   Fri Apr  6 10:27:34 2018
+Date:   Sat Apr  7 12:20:03 2018
 
 Model author: Yentl Van Tendeloo
 Model name:   MvK Server