Browse Source

More functions for wrapper

Yentl Van Tendeloo 8 years ago
parent
commit
ca5e9e4770
1 changed files with 356 additions and 260 deletions
  1. 356 260
      wrappers/modelverse.py

+ 356 - 260
wrappers/modelverse.py

@@ -22,7 +22,7 @@ def _input(value):
         urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": taskname}))).read()
     else:
         value = json.dumps(value)
-        print("Set input: " + str(value))
+        #print("Set input: " + str(value))
         urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
 
 def _input_raw(value, taskname):
@@ -66,7 +66,7 @@ def _output(expected=None):
     try:
         global last_output
         last_output = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read())
-        print("Got output: " + str(last_output))
+        #print("Got output: " + str(last_output))
     except:
         raise UnknownError()
     if expected is not None and last_output != expected:
@@ -365,6 +365,8 @@ def model_render(model, mapper):
     if mode != 2:
         raise InvalidMode()
 
+    #TODO error handling!
+
     _input("model_render")
     _output()
     _input(model)
@@ -488,399 +490,493 @@ def admin_demote():
     raise NotImplementedError()
 
 # Actual operations on the model
-def element_list():
+def element_list(model_name):
     """Return a list of all IDs and the type of the element"""
     # return [(name1, type1), (name2, type2), ...]
     # raises UnknownError
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
-    _input("list_full")
-    lst = []
-    _output("List of all elements:")
-    while (_output() != "Please give your command."):
-        v = _last_output()
-        m, mm = v.split(":")
-        m = m.strip()
-        mm = mm.strip()
-        lst.append((m, mm))
-    return lst
 
-def types():
+    try:
+        _input("list_full")
+        lst = []
+        _output("List of all elements:")
+        while (_output() != "Please give your command."):
+            v = _last_output()
+            m, mm = v.split(":")
+            m = m.strip()
+            mm = mm.strip()
+            lst.append((m, mm))
+        return lst
+
+    finally:
+        model_exit()
+
+def types(model_name):
     """Return a list of all types usable in the model"""
     # return [type1, type2, ...]
     # raises UnknownError
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
-    _input("types")
-    _output("List of types:")
-    lst = []
-    while (_output() != "Please give your command."):
-        v = _last_output()
-        m, mm = v.split(":")
-        m = m.strip()
-        lst.append(m)
-    return lst
 
-def types_full():
+    try:
+        _input("types")
+        _output("List of types:")
+        lst = []
+        while (_output() != "Please give your command."):
+            v = _last_output()
+            m, mm = v.split(":")
+            m = m.strip()
+            lst.append(m)
+        return lst
+
+    finally:
+        model_exit()
+
+def types_full(model_name):
     """Return a list of full types usable in the model"""
     # return [(type1, typetype1), (type2, typetype2), ...]
     # raises UnknownError
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
-    _input("types")
-    _output("List of types:")
-    lst = []
-    while (_output() != "Please give your command."):
-        v = _last_output()
-        m, mm = v.split(":")
-        m = m.strip()
-        mm = mm.strip()
-        lst.append((m, mm))
-    return lst
 
-def read(ID):
+    try:
+        _input("types")
+        _output("List of types:")
+        lst = []
+        while (_output() != "Please give your command."):
+            v = _last_output()
+            m, mm = v.split(":")
+            m = m.strip()
+            mm = mm.strip()
+            lst.append((m, mm))
+        return lst
+
+    finally:
+        model_exit()
+
+def read(model_name, ID):
     """Return a tuple of information on the element: its type and source/target (None if not an edge)"""
     # return (type, (source, target))
     # raises UnknownError
     # raises UnknownIdentifier
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
-    _input("read")
-    _output("Element to read?")
-    _input(ID)
-    if _output() == "Unknown element; aborting":
-        _output("Please give your command.")
-        raise UnknownIdentifier()
-    elif _last_output() == "ID: " + str(ID):
-        t = _output().split(":")[1].strip()
-        if (not _output().startswith("Source:")):
-            rval = (t, None)
-        else:
-            src = _last_output().split(":")[1].strip()
-            trg = _output().split(":")[1].strip()
-            rval = (t, (src, trg))
-        while (_output() != "Please give your command."):
-            pass
-        return rval
 
-def read_attrs(ID):
+    try:
+        _input("read")
+        _output("Element to read?")
+        _input(ID)
+        if _output() == "Unknown element; aborting":
+            _output("Please give your command.")
+            raise UnknownIdentifier()
+        elif _last_output() == "ID: " + str(ID):
+            t = _output().split(":")[1].strip()
+            if (not _output().startswith("Source:")):
+                rval = (t, None)
+            else:
+                src = _last_output().split(":")[1].strip()
+                trg = _output().split(":")[1].strip()
+                rval = (t, (src, trg))
+            while (_output() != "Please give your command."):
+                pass
+            return rval
+
+    finally:
+        model_exit()
+
+def read_attrs(model_name, ID):
     """Return a dictionary of attribute value pairs"""
     # return {attr1: value1, attr2: value2, ...}
     # raises UnknownError
     # raises UnknownIdentifier
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
-    _input("read")
-    _output("Element to read?")
-    _input(ID)
-    if _output() == "Unknown element; aborting":
-        _output("Please give your command.")
-        raise UnknownIdentifier()
-    elif _last_output() == "ID: " + str(ID):
-        rval = {}
-        # Skip until attributes
-        while (_output() != "Attributes:"):
-            pass
-        while (_output() != "Please give your command."):
-            r = _last_output()
-            key, value = r.split(":")
-            _, value = value.split("=")
-            key = json.loads(key.strip())
-            value = value.strip()
-            value = None if value == "None" else json.loads(value)
-            rval[key] = value
-        return rval
-
-def instantiate(typename, edge=None, ID=""):
+
+    try:
+        _input("read")
+        _output("Element to read?")
+        _input(ID)
+        if _output() == "Unknown element; aborting":
+            _output("Please give your command.")
+            raise UnknownIdentifier()
+        elif _last_output() == "ID: " + str(ID):
+            rval = {}
+            # Skip until attributes
+            while (_output() != "Attributes:"):
+                pass
+            while (_output() != "Please give your command."):
+                r = _last_output()
+                key, value = r.split(":")
+                _, value = value.split("=")
+                key = json.loads(key.strip())
+                value = value.strip()
+                value = None if value == "None" else json.loads(value)
+                rval[key] = value
+            return rval
+    finally:
+        model_exit()
+
+def instantiate(model_name, typename, edge=None, ID=""):
     """Create a new instance of the specified typename, between the selected elements (if not None), and with the provided ID (if any)"""
     # return instantiated_ID
     # raises UnknownError
     # raises UnknownType
     # raises UnknownIdentifier
     # raises NotAnEdge
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
-    _input("instantiate")
-    if (_output() == "Permission denied"):
-        _output("Please give your command.")
-        raise PermissionDenied()
-    else:
-        _input(typename)
-        if (_output() == "Name of new element?"):
-            _input(ID)
-            if (_output() == "Element already exists; aborting"):
-                _output("Please give your command.")
-                raise ElementExists()
-
-            if (edge is not None) and (_last_output() == "Source name?"):
-                # Is an edge and we have data
-                _input(edge[0])
-                if _output() == "Destination name?":
-                    _input(edge[1])
-                    if _output() == "Instantiation successful!":
+
+    try:
+        _input("instantiate")
+        if (_output() == "Permission denied"):
+            _output("Please give your command.")
+            raise PermissionDenied()
+        else:
+            _input(typename)
+            if (_output() == "Name of new element?"):
+                _input(ID)
+                if (_output() == "Element already exists; aborting"):
+                    _output("Please give your command.")
+                    raise ElementExists()
+
+                if (edge is not None) and (_last_output() == "Source name?"):
+                    # Is an edge and we have data
+                    _input(edge[0])
+                    if _output() == "Destination name?":
+                        _input(edge[1])
+                        if _output() == "Instantiation successful!":
+                            ID = _output()
+                            _output("Please give your command.")
+                            return ID
+                        elif _last_output() == "Unknown destination; aborting":
+                            _output("Please give your command.")
+                            raise UnknownIdentifier()
+                        else:
+                            raise InterfaceMismatch(_last_output())
+                    elif _last_output() == "Unknown source; aborting":
+                        _output("Please give your command.")
+                        raise UnknownIdentifier()
+                    else:
+                        raise InterfaceMismatch(_last_output())
+                elif (edge is None) and (_last_output() != "Source name?"):
+                    # Is no edge and we don't have data
+                    if _last_output() == "Instantiation successful!":
                         ID = _output()
                         _output("Please give your command.")
                         return ID
-                    elif _last_output() == "Unknown destination; aborting":
-                        _output("Please give your command.")
-                        raise UnknownIdentifier()
                     else:
                         raise InterfaceMismatch(_last_output())
-                elif _last_output() == "Unknown source; aborting":
+                elif (edge is not None) and (_last_output() != "Source name?"):
+                    # Is no edge, but we have edge data to input: ERROR
+                    # Delete the element again
+                    ID = _last_output()
                     _output("Please give your command.")
-                    raise UnknownIdentifier()
-                else:
-                    raise InterfaceMismatch(_last_output())
-            elif (edge is None) and (_last_output() != "Source name?"):
-                # Is no edge and we don't have data
-                if _last_output() == "Instantiation successful!":
-                    ID = _output()
+                    delete_element(ID)
+                    raise NotAnEdge()
+                elif (edge is None) and (_last_output() == "Source name?"):
+                    # Is an edge, but we have no edge data to input: ERROR
+                    # Add an empty source, which is guaranteed not to be there
+                    _input("")
+                    _output("Unknown source; aborting")
                     _output("Please give your command.")
-                    return ID
-                else:
-                    raise InterfaceMismatch(_last_output())
-            elif (edge is not None) and (_last_output() != "Source name?"):
-                # Is no edge, but we have edge data to input: ERROR
-                # Delete the element again
-                ID = _last_output()
+                    raise NotAnEdge()
+
+            elif (_last_output() == "Permission denied"):
                 _output("Please give your command.")
-                delete_element(ID)
-                raise NotAnEdge()
-            elif (edge is None) and (_last_output() == "Source name?"):
-                # Is an edge, but we have no edge data to input: ERROR
-                # Add an empty source, which is guaranteed not to be there
-                _input("")
-                _output("Unknown source; aborting")
+                raise PermissionDenied()
+            elif (_last_output() == "Unknown type specified; aborting"):
                 _output("Please give your command.")
-                raise NotAnEdge()
+                raise UnknownType()
+            else:
+                raise InterfaceMismatch(_last_output())
 
-        elif (_last_output() == "Permission denied"):
-            _output("Please give your command.")
-            raise PermissionDenied()
-        elif (_last_output() == "Unknown type specified; aborting"):
-            _output("Please give your command.")
-            raise UnknownType()
-        else:
-            raise InterfaceMismatch(_last_output())
+    finally:
+        model_exit()
 
-def delete_element(ID):
+def delete_element(model_name, ID):
     """Delete the element with the given ID"""
     # return None
     # raises UnknownError
     # raises UnknownIdentifier
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
-    _input("delete")
-    if _output() == "What is the name of the element you want to delete?":
-        _input(ID)
-        if _output() == "Deleted!":
-            _output("Please give your command.")
-        elif _last_output() == "No such element; aborting":
+
+    try:
+        _input("delete")
+        if _output() == "What is the name of the element you want to delete?":
+            _input(ID)
+            if _output() == "Deleted!":
+                _output("Please give your command.")
+            elif _last_output() == "No such element; aborting":
+                _output("Please give your command.")
+                raise UnknownIdentifier()
+            else:
+                raise InterfaceMismatch(_last_output())
+        elif _last_output() == "Permission denied":
             _output("Please give your command.")
-            raise UnknownIdentifier()
+            raise PermissionDenied()
         else:
             raise InterfaceMismatch(_last_output())
-    elif _last_output() == "Permission denied":
-        _output("Please give your command.")
-        raise PermissionDenied()
-    else:
-        raise InterfaceMismatch(_last_output())
 
-def attr_assign(ID, attr, value):
+    finally:
+        model_exit()
+
+def attr_assign(model_name, ID, attr, value):
     """Assign a value to an attribute"""
     # return None
     # raises UnknownError
     # raises UnknownIdentifier
     # raises NoSuchAttribute
     # raises UnsupportedValue
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
 
-    _input("attr_add")
-    if _output() == "Which element do you want to assign an attribute to?":
-        _input(ID)
-        if _output() == "Which attribute do you wish to assign?":
-            _input(attr)
-            if _output() == "Value of attribute?":
-                _input(value)
-                _output("Added attribute!")
-                _output("Please give your command.")
-            elif _last_output() == "No such attribute!":
+    try:
+        _input("attr_add")
+        if _output() == "Which element do you want to assign an attribute to?":
+            _input(ID)
+            if _output() == "Which attribute do you wish to assign?":
+                _input(attr)
+                if _output() == "Value of attribute?":
+                    _input(value)
+                    _output("Added attribute!")
+                    _output("Please give your command.")
+                elif _last_output() == "No such attribute!":
+                    _output("Please give your command.")
+                    raise NoSuchAttribute()
+                else:
+                    raise InterfaceMismatch(_last_output())
+
+            elif _last_output() == "No such element!":
                 _output("Please give your command.")
-                raise NoSuchAttribute()
+                raise UnknownIdentifier()
             else:
                 raise InterfaceMismatch(_last_output())
 
-        elif _last_output() == "No such element!":
+        elif _last_output() == "Permission denied":
             _output("Please give your command.")
-            raise UnknownIdentifier()
+            raise PermissionDenied()
         else:
             raise InterfaceMismatch(_last_output())
 
-    elif _last_output() == "Permission denied":
-        _output("Please give your command.")
-        raise PermissionDenied()
-    else:
-        raise InterfaceMismatch(_last_output())
+    finally:
+        model_exit()
 
-def attr_assign_code(ID, attr, code):
+def attr_assign_code(model_name, ID, attr, code):
     """Assign a piece of Action Language code to the attribute"""
     # return None
     # raises UnknownError
     # raises UnknownIdentifier
     # raises NoSuchAttribute
     # raises UnsupportedValue
-    if mode != 3:
-        raise InvalidMode()
     try:
         compiled = _compile_AL(code)
     except Exception as e:
         raise CompilationError(e)
 
-    _input("attr_add")
-    if _output() == "Which element do you want to assign an attribute to?":
-        _input(ID)
-        if _output() == "Which attribute do you want to assign?":
-            _input(attr)
-            if _output() == "Waiting for code constructors...":
-                _input(compiled)
-                _output("Added attribute!")
-                _output("Please give your command.")
-            elif _last_output() == "No such attribute!":
+    model_modify(model_name)
+
+    if mode != 3:
+        raise InvalidMode()
+
+    try:
+        _input("attr_add")
+        if _output() == "Which element do you want to assign an attribute to?":
+            _input(ID)
+            if _output() == "Which attribute do you want to assign?":
+                _input(attr)
+                if _output() == "Waiting for code constructors...":
+                    _input(compiled)
+                    _output("Added attribute!")
+                    _output("Please give your command.")
+                elif _last_output() == "No such attribute!":
+                    _output("Please give your command.")
+                    raise NoSuchAttribute()
+                else:
+                    raise InterfaceMismatch(_last_output())
+
+            elif _last_output() == "No such element!":
                 _output("Please give your command.")
-                raise NoSuchAttribute()
+                raise UnknownIdentifier()
             else:
                 raise InterfaceMismatch(_last_output())
 
-        elif _last_output() == "No such element!":
+        elif _last_output() == "Permission denied":
             _output("Please give your command.")
-            raise UnknownIdentifier()
+            raise PermissionDenied()
         else:
             raise InterfaceMismatch(_last_output())
+    finally:
+        model_exit()
 
-    elif _last_output() == "Permission denied":
-        _output("Please give your command.")
-        raise PermissionDenied()
-    else:
-        raise InterfaceMismatch(_last_output())
-
-def attr_delete(ID, attr):
+def attr_delete(model_name, ID, attr):
     """Remove an attribute."""
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
-    _input("attr_del")
-    if _output() == "Which element do you want to remove an attribute of?":
-        _input(ID)
-        if _output() == "Which attribute do you want to delete?":
-            _input(attr)
-            if _output() == "Attribute deleted!":
-                _output("Please give your command.")
-            elif _last_output() == "No such attribute!":
+
+    try:
+        _input("attr_del")
+        if _output() == "Which element do you want to remove an attribute of?":
+            _input(ID)
+            if _output() == "Which attribute do you want to delete?":
+                _input(attr)
+                if _output() == "Attribute deleted!":
+                    _output("Please give your command.")
+                elif _last_output() == "No such attribute!":
+                    _output("Please give your command.")
+                    raise NoSuchAttribute()
+                else:
+                    raise InterfaceMismatch(_last_output())
+            elif _last_output() == "No such element!":
                 _output("Please give your command.")
-                raise NoSuchAttribute()
+                raise UnknownIdentifier()
             else:
                 raise InterfaceMismatch(_last_output())
-        elif _last_output() == "No such element!":
+        elif _last_output() == "Permission denied":
             _output("Please give your command.")
-            raise UnknownIdentifier()
+            raise PermissionDenied()
         else:
             raise InterfaceMismatch(_last_output())
-    elif _last_output() == "Permission denied":
-        _output("Please give your command.")
-        raise PermissionDenied()
-    else:
-        raise InterfaceMismatch(_last_output())
 
-def read_outgoing(ID, typename):
+    finally:
+        model_exit()
+
+def read_outgoing(model_name, ID, typename):
     """Returns a list of all outgoing associations of a specific type ("" = all)"""
     # return [name1, name2, ...]
     # raises UnknownError
     # raises UnknownIdentifier
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
 
-    _input("read_outgoing")
-    _output("Element to read from?")
-    _input(ID)
-    if _output() == "Type of outgoing edge (empty for all)?":
-        _input(typename)
-        lst = []
-        while (_output() != "Please give your command."):
-            lst.append(_last_output())
-        return lst
-    elif _last_output() == "Unknown element; aborting":
-        _output("Please give your command.")
-        raise UnknownIdentifier()
-    else:
-        raise InterfaceMismatch()
+    try:
+        _input("read_outgoing")
+        _output("Element to read from?")
+        _input(ID)
+        if _output() == "Type of outgoing edge (empty for all)?":
+            _input(typename)
+            lst = []
+            while (_output() != "Please give your command."):
+                lst.append(_last_output())
+            return lst
+        elif _last_output() == "Unknown element; aborting":
+            _output("Please give your command.")
+            raise UnknownIdentifier()
+        else:
+            raise InterfaceMismatch()
 
-def read_incoming(ID, typename):
+    finally:
+        model_exit()
+
+def read_incoming(model_name, ID, typename):
     """Returns a list of all incoming associations of a specific type ("" = all)"""
     # return [name1, name2, ...]
     # raises UnknownError
     # raises UnknownIdentifier
     # raises UnknownType
+    model_modify(model_name)
+
     if mode != 3:
         raise InvalidMode()
 
-    _input("read_incoming")
-    _output("Element to read from?")
-    _input(ID)
-    if _output() == "Type of incoming edge (empty for all)?":
-        _input(typename)
-        lst = []
-        while (_output() != "Please give your command."):
-            lst.append(_last_output())
-        return lst
-    elif _last_output() == "Unknown element; aborting":
-        _output("Please give your command.")
-        raise UnknownIdentifier()
-    else:
-        raise InterfaceMismatch()
+    try:
+        _input("read_incoming")
+        _output("Element to read from?")
+        _input(ID)
+        if _output() == "Type of incoming edge (empty for all)?":
+            _input(typename)
+            lst = []
+            while (_output() != "Please give your command."):
+                lst.append(_last_output())
+            return lst
+        elif _last_output() == "Unknown element; aborting":
+            _output("Please give your command.")
+            raise UnknownIdentifier()
+        else:
+            raise InterfaceMismatch()
+    finally:
+        model_exit()
 
-def read_association_source(ID):
+def read_association_source(model_name, ID):
     """Returns the source of an association."""
     # returns name
     # raises UnknownError
     # raises UnknownIdentifier
     # raises NotAnAssociation
-    _input("read_association_source")
-    _output("Association to read source of?")
-    _input(ID)
-    if _output() == "Read source:":
-        result = _output()
-        _output("Please give your command.")
-        return result
-    elif _last_output() == "Unknown element; aborting":
-        _output("Please give your command.")
-        raise UnknownIdentifier()
-    elif _last_output() == "Not an association; aborting":
-        _output("Please give your command.")
-        raise NotAnEdge()
-    else:
-        raise InterfaceMismatch(_last_output())
+    model_modify(model_name)
 
-def read_association_destination(ID):
+    if mode != 3:
+        raise InvalidMode()
+
+    try:
+        _input("read_association_source")
+        _output("Association to read source of?")
+        _input(ID)
+        if _output() == "Read source:":
+            result = _output()
+            _output("Please give your command.")
+            return result
+        elif _last_output() == "Unknown element; aborting":
+            _output("Please give your command.")
+            raise UnknownIdentifier()
+        elif _last_output() == "Not an association; aborting":
+            _output("Please give your command.")
+            raise NotAnEdge()
+        else:
+            raise InterfaceMismatch(_last_output())
+    finally:
+        model_exit()
+
+def read_association_destination(model_name, ID):
     """Returns the destination of an association."""
     # returns name
     # raises UnknownError
     # raises UnknownIdentifier
     # raises NotAnAssociation
-    _input("read_association_destination")
-    _output("Association to read destination of?")
-    _input(ID)
-    if _output() == "Read destination:":
-        result = _output()
-        _output("Please give your command.")
-        return result
-    elif _last_output() == "Unknown element; aborting":
-        _output("Please give your command.")
-        raise UnknownIdentifier()
-    elif _last_output() == "Not an association; aborting":
-        _output("Please give your command.")
-        raise NotAnEdge()
-    else:
-        raise InterfaceMismatch(_last_output())
+    model_modify(model_name)
+
+    if mode != 3:
+        raise InvalidMode()
+
+    try:
+        _input("read_association_destination")
+        _output("Association to read destination of?")
+        _input(ID)
+        if _output() == "Read destination:":
+            result = _output()
+            _output("Please give your command.")
+            return result
+        elif _last_output() == "Unknown element; aborting":
+            _output("Please give your command.")
+            raise UnknownIdentifier()
+        elif _last_output() == "Not an association; aborting":
+            _output("Please give your command.")
+            raise NotAnEdge()
+        else:
+            raise InterfaceMismatch(_last_output())
+    finally:
+        model_exit()
 
 def model_exit():
     """Leave model modify mode."""