예제 #1
0
파일: UdmCliGen.py 프로젝트: ksmyth/UDM
if __name__ == "__main__":
    from optparse import OptionParser
    parser = OptionParser(usage="usage: %prog [options] input-uml.xml")
    parser.add_option("-o", "--output", dest="output", help="File or directory to output to.")
    parser.add_option("--impl_namespace", dest="impl_namespace")
    parser.add_option("--interface_namespace", dest="interface_namespace")
    (options, args) = parser.parse_args()
    if len(args) != 1:
        print parser.print_help()
        sys.exit()
    if options.impl_namespace:
        common.impl_namespace = options.impl_namespace + "."
    if options.interface_namespace:
        common.interface_namespace = options.interface_namespace + "."
    
    uml = udm.map_uml_names(udm.uml_diagram())
    dn = udm.SmartDataNetwork(udm.uml_diagram())
    dn.open(args[0], "")

    if options.output:
        if os.path.isdir(options.output):
            output = open(os.path.join(options.output, dn.root.name + ".cs"), "w")
        else:
            output = open(options.output, "w")
        # TODO: close this
    else:
        output = sys.stdout

    output.write("#pragma warning disable 0108\n"); # disable "'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended."

    def get_classes(dn):
예제 #2
0
#recursively print tree
def printTreeHelper(f, tree, numindents):
    total = 1
    indentation = ""
    if numindents != 0:
        for x in range(0, numindents):
            indentation = indentation + "\t"
    f.write("".join([indentation, tree.type.name, "\n"]))
    if len(tree.children()) != 0:
        for x in range(0, len(tree.children())):
            total += printTreeHelper(f, tree.children()[x], numindents + 1)
    return total


####################################################
#Finally, do some work

test_meta_dn = udm.SmartDataNetwork(udm.uml_diagram())
print "Reading xml meta model into udm..."
test_meta_dn.open(r"OpenFOAMPreProcessing.xml", "")
test_meta = udm.map_uml_names(test_meta_dn.root)
dn = udm.SmartDataNetwork(test_meta_dn.root)
print "Opening Model..."
dn.open(r"OpenFOAMExamples.mga", "")

print "Finding valid cases..."
processCases(dn.root, dn.root.name)

# print "Printing structure to file..."
# printTree("ModelStructure.txt",dn.root)
예제 #3
0
def invoke(focusObject, rootObject, componentParameters, dn=None, **kwargs):
    # output_dir = componentParameters['output_dir']
    import subprocess
    import udm
    from multiprocessing import cpu_count
    import threading
    import pythoncom
    CyPhyML = udm.map_uml_names(focusObject.type.parent)

    tb = focusObject
    if tb.type.name == 'ParametricExploration':
        tbrefs = tb.children(child_type=CyPhyML.TestBenchRef)
        if not tbrefs:
            raise ValueError('ParametricExploration must have a TestBenchRef')
        tb = tbrefs[0].ref

    tlsut = tb.children('TopLevelSystemUnderTest')
    if not tlsut:
        raise ValueError('TestBench has no TopLevelSystemUnderTest')
    tlsut = tlsut[0]
    design = tlsut.ref
    if design.type.name != 'DesignContainer':
        raise ValueError(
            'TopLevelSystemUnderTest must refer to a DesignContainer')

    if kwargs.get('ids'):
        cwcs = [
            dn.get_object_by_id(udm.GmeId2UdmId(id_))
            for id_ in kwargs.get('ids').split(',')
        ]
    elif kwargs.get('configuration_id'):
        cwcs = [
            cwc for cwc in dn.get_object_by_id(
                udm.GmeId2UdmId(kwargs.get('configuration_id'))).children(
                    child_type=CyPhyML.CWC)
        ]
    else:
        import pdb
        pdb.set_trace()
        cwcs = [
            cwc
            for config in design.children(child_type=CyPhyML.Configurations)
            for cwc in config.children(child_type=CyPhyML.CWC)
        ]

    # CyPhyMasterExe.exe "MGA=C:\Users\kevin\Documents\jolt-sketch\OpenMETA\Jolt.mga" "/@Testing/@Tron Coin Changer Detection" "/@DesignSpaces/@VendingMachine/@Exported-Configurations-at--09-12--16-38-52/@cfg1"
    master_exe_path = os.path.join(meta_path, 'bin', 'CyPhyMasterExe.exe')
    if not os.path.isfile(master_exe_path):
        master_exe_path = os.path.join(
            meta_path, r'src\CyPhyMasterExe\bin\Release\CyPhyMasterExe.exe')
    job_collection_id = str(uuid.uuid4())
    master_exe_args = [
        master_exe_path, "--no-job-collection-done", "--job-collection-id",
        job_collection_id,
        focusObject.convert_udm2gme().Project.ProjectConnStr,
        focusObject.convert_udm2gme().AbsPath
    ]
    cwc_paths = [cwc.convert_udm2gme().AbsPath for cwc in cwcs]
    cwc_paths.sort()
    messages = []
    lock = threading.Lock()
    messages_condition = threading.Condition()

    conn_str = focusObject.convert_udm2gme().Project.ProjectConnStr
    mga_dir = os.path.dirname(conn_str[len('MGA='):])
    results_metaresults = os.path.join(mga_dir, 'results',
                                       'results.metaresults.json')
    if not os.path.isfile(results_metaresults):
        try:
            os.makedirs(os.path.dirname(results_metaresults))
        except OSError as exception:
            if exception.errno != errno.EEXIST:
                raise
        with open(results_metaresults, 'w') as results:
            results.write(json.dumps({"Results": []}))

    test_jobmanager_running(mga_dir=mga_dir)

    def message(msg):
        with messages_condition:
            messages.append(msg)
            messages_condition.notify()

    def run_mi():
        try:
            while True:
                with lock:
                    if len(cwc_paths) == 0:
                        return
                    cwc_path = cwc_paths.pop()
                # message(cwc_path)
                args = master_exe_args + [cwc_path]
                try:
                    process = subprocess.Popen(args,
                                               stdout=subprocess.PIPE,
                                               stderr=subprocess.PIPE)
                    stdout, stderr = process.communicate()
                    if process.wait() != 0:
                        message(stderr)
                except Exception as e:
                    message(str(e))
        finally:
            message(None)

    threads = [threading.Thread(target=run_mi) for _ in range(cpu_count())]
    for thread in threads:
        thread.start()
    threads_done = 0
    while True:
        with messages_condition:
            pythoncom.PumpWaitingMessages()
            for msg in messages:
                if msg is None:
                    threads_done = threads_done + 1
                else:
                    log(msg)
            messages[:] = []
            if threads_done == len(threads):
                break
            messages_condition.wait(1)

    # start_pdb()
    args = [
        master_exe_path, "--job-collection-id", job_collection_id,
        "--send-job-collection-done"
    ]
    subprocess.check_call(args)
    log('Parallel Master Interpreter finished')
예제 #4
0
    def testudmpython(self):
        # need to open meta DN since it isn't compiled in
        test_meta_dn= udm.SmartDataNetwork(udm.uml_diagram())
        test_meta_dn.open(r"UdmPythonTestMeta.xml", "")
        self.assertEquals(test_meta_dn.root.name, "UdmPythonTestMeta")
        test_meta = udm.map_uml_names(test_meta_dn.root)

        dn = udm.SmartDataNetwork(test_meta_dn.root)
        if _platform == "linux" or _platform == "linux2" or _platform == "darwin":
            dn.open(r"UdmPythonTest.xml", "")
        else:
            dn.open(r"UdmPythonTestModel.mga", "")

        container = dn.root.children()[0]
        self.assertTrue(container)
        # get children by type
        self.assertEquals(get_names(container.children(child_type=test_meta.AtomB)), [ "cmproleA1", "cmproleA2", "cmproleB1" ]) # also accepts child_role, parent_role
        # get children by child's composition role
        self.assertEquals(get_names(container.cmproleA_role_children), [ "cmproleA1", "cmproleA2" ])
        self.assertEquals(container.children(child_role="cmproleA"), container.cmproleA_role_children)
        self.assertEquals(get_names(container.cmproleB_role_children), [ "cmproleB1"] )
        self.assertEquals(container.type, test_meta.Container)
        def first(container): return next(container.__iter__())
        cmproleA1 = first(filter(lambda x: x.name =="cmproleA1", container.children()))
        cmproleA2 = first(filter(lambda x: x.name =="cmproleA2", container.children()))
        self.assertEquals(cmproleA1.dstConnection, [cmproleA2])
        self.assertEquals(cmproleA1.adjacent(dst_role="dstConnection"), [cmproleA2])
        self.assertEquals(cmproleA1.adjacent(src_role="srcConnection"), [cmproleA2])
        self.assertEquals(cmproleA2.adjacent(dst_role="dstConnection"), [])
        self.assertEquals(cmproleA2.adjacent(src_role="srcConnection"), [])
        AtomA1 = first(filter(lambda x: x.name =="AtomA1", container.children()))
        self.assertEquals(AtomA1.boolattr, True)
        self.assertEquals(AtomA1.stringattr, "teststring")
        self.assertEquals(AtomA1.intattr, 42)
        AtomA1.intattr = 60
        self.assertEquals(AtomA1.intattr, 60)
        AtomA1.stringattr = "test123"
        self.assertEquals(AtomA1.stringattr, "test123")
        unicode_teststring = u'\xc1rv\xedzt\u0171r\u0151 t\xfck\xf6rf\xfar\xf3g\xe9p\U0001d11e\u0393\u03b1\u03b6\u03ad\u03b5\u03c2 \u03ba\u03b1\u1f76 \u03bc\u03c5\u03c1\u03c4\u03b9\u1f72\u03c2 \u03b4\u1f72\u03bd \u03b8\u1f70 \u03b2\u03c1\u1ff6 \u03c0\u03b9\u1f70 \u03c3\u03c4\u1f78 \u03c7\u03c1\u03c5\u03c3\u03b1\u03c6\u1f76 \u03be\u03ad\u03c6\u03c9\u03c4\u03bf\u0ca0_\u0ca0\u30a6\u30f0\u30ce\u30aa\u30af\u30e4\u30de \u30b1\u30d5\u30b3\u30a8\u30c6 \u30a2\u30b5\u30ad\u30e6\u30e1\u30df\u30b7 \u30f1\u30d2\u30e2\u30bb\u30b9\u30f3\u0421\u044a\u0435\u0448\u044c \u0436\u0435 \u0435\u0449\u0451 \u044d\u0442\u0438\u0445 \u043c\u044f\u0433\u043a\u0438\u0445 \u0444\u0440\u0430\u043d\u0446\u0443\u0437\u0441\u043a\u0438\u0445 \u0431\u0443\u043b\u043e\u043a \u0434\u0430 \u0432\u044b\u043f\u0435\u0439 \u0447\u0430\u044e'
        AtomA1.stringattr = unicode_teststring
        self.assertEquals(AtomA1.stringattr, unicode_teststring)
        
        
        # trying to access nonexistant attribute raises an exception
        try:
            self.assertFalse(container.nonexistantattribute)
        except RuntimeError as e:
            # the error message should include the type's name and attribute name
            self.assertTrue(str(e).find("Container") != -1)
            self.assertTrue(str(e).find("nonexistantattribute") != -1)
        else:
            self.fail("Expected an exception")

        uml = udm.map_uml_names(udm.uml_diagram())
        for o in udm.uml_diagram().children():
            if get_names(o.children(child_type=uml.CompositionChildRole)) == ['namespaces'] and get_names(o.children(child_type=uml.CompositionParentRole)) == ['parent']:
                break
        else:
            self.fail()
        namespaces = o.children(child_type=uml.CompositionChildRole)[0] # i.e. CompositionChildRole in Composition Diagram<>---Namespace
        self.assertEquals(namespaces.min, 0)
        self.assertEquals(namespaces.max, -1)
        self.assertTrue(namespaces.isNavigable)
        self.assertEquals(namespaces.target, uml.Namespace)
        self.assertEquals(namespaces.adjacent(dst_role="target"), uml.Namespace)
        self.assertEquals(namespaces.adjacent(dst_role="target", src_role="childRoles"), uml.Namespace)
        # if we don't specify dst_role, adjacent() returns a list
        self.assertEquals(namespaces.adjacent(), [uml.Namespace])
        self.assertEquals(namespaces.adjacent(src_role="childRoles"), [uml.Namespace])

        self.assertEquals(get_names(test_meta_dn.root.children()[0].adjacent(dst_role="subTypes")), []) # also accepts dst_role, association_class
        self.assertTrue(test_meta_dn.root.children()[0].name)
        self.assertTrue(test_meta_dn.root.children()[0].stereotype)
        self.assertEqual(test_meta.AtomA.name, "AtomA")
        self.assertEquals(test_meta.AtomA, test_meta.AtomA)
        self.assertNotEqual(test_meta.AtomA, test_meta.AtomB)
        self.assertNotEqual(test_meta_dn.root, udm.uml_diagram())
        self.assertNotEqual(test_meta_dn, udm.uml_diagram()) # disparate types
        self.assertNotEqual(udm.uml_diagram(), test_meta_dn) # disparate types
        self.assertTrue(test_meta.AtomA.__hash__() > 0)
        self.assertTrue(test_meta.AtomA)

        #KMS: BUG: childRole_role_children should return a singleton, not a list
        self.assertEquals(test_meta.AtomA.childRoles[0].parent.childRole_role_children[0].target, test_meta.AtomA)

        dn.close_no_update()
        test_meta_dn.close_no_update()
예제 #5
0
    q = []
    q.extend(start)
    while len(q) != 0:
        o = q.pop()
        q.extend(getter(o))
        yield o

if __name__ == '__main__':
    import shutil
    srcfile = sys.argv[1]
    destfile = os.path.splitext(srcfile)[0] + "_multiplied.mga"
    shutil.copy(srcfile, destfile)

    meta_dn = udm.SmartDataNetwork(udm.uml_diagram())
    meta_dn.open(os.path.join(os.path.dirname(__file__), r"CyPhyML_udm.xml"), "")
    meta = udm.map_uml_names(meta_dn.root)
    
    dn = udm.SmartDataNetwork(meta_dn.root)
    dn.open(destfile, "")
    
    q = [dn.root]
    while len(q) != 0:
        o = q.pop()
        q.extend(o.children())
        if o.is_instance:
            for (attrname, mult) in attr_map.items():
                try:
                    # i.e. o.Weight = o.archetype.Weight * 1000
                    o.__setattr__(attrname, o.archetype.__getattr__(attrname) * mult)
                except:
                    pass
import sys
import os
import six.moves.winreg as winreg
import six
try:
    import udm
except ImportError:
    with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
                        r"Software\META") as software_meta:
        meta_path, _ = winreg.QueryValueEx(software_meta, "META_PATH")
    sys.path.append(os.path.join(meta_path, 'bin'))
    import udm
import os.path

uml_diagram = udm.uml_diagram()
Uml = udm.map_uml_names(uml_diagram)


def print_uml_info(class_, print_=print, indent='', bases=None):
    if class_.type != Uml.Class:
        raise ValueError(
            'class_ must be a Uml.Class. Use .type to get the class of an object'
        )
    bases = bases or set()
    print_('{}Class {}'.format(indent, class_.name))
    if class_.association:
        print_('{}  {} --> {}'.format(indent,
                                      class_.association.children()[0].name,
                                      class_.association.children()[1].name))
    attributes = class_.children(child_type=Uml.Attribute)
    if attributes:
예제 #7
0
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.process.traversal import T
from gremlin_python.process.traversal import Order
from gremlin_python.process.traversal import Cardinality
from gremlin_python.process.traversal import Column
from gremlin_python.process.traversal import Direction
from gremlin_python.process.traversal import Operator
from gremlin_python.process.traversal import P
from gremlin_python.process.traversal import Pop
from gremlin_python.process.traversal import Scope
from gremlin_python.process.traversal import Barrier
from gremlin_python.process.traversal import Bindings
from gremlin_python.process.traversal import WithOptions

uml_diagram = udm.uml_diagram()
Uml = udm.map_uml_names(uml_diagram)


# This is the entry point
def invoke(focusObject, rootObject, componentParameters, **kwargs):
    log("Running elaborator")
    elaborate(focusObject)

    log(pprint.pformat(componentParameters))

    g = make_graph(focusObject)

    # Find the top 10 objects in the graph by degree centrality
    # Derived from Tinkerpop example: http://tinkerpop.apache.org/docs/current/recipes/#degree-centrality
    degrees = (g.V().project("v", "name", "degree").by().by("name").by(
        __.bothE().count()).order().by(__.select("degree"),