예제 #1
0
def _compile_model(model_folder: str, model_name: str,
                   compiler_options: Dict[str, str]):
    # Importing the antlr4 (generated modules) is rather slow. Avoid for this
    # ~100 ms startup overhead for cached models by importing only when
    # compiling.
    from pymoca import parser

    # Load folders
    tree = None
    for folder in [model_folder] + compiler_options['library_folders']:
        for root, dir, files in os.walk(folder, followlinks=True):
            for item in fnmatch.filter(files, "*.mo"):
                logger.info("Parsing {}".format(item))

                with open(os.path.join(root, item), 'r') as f:
                    if tree is None:
                        tree = parser.parse(f.read())
                    else:
                        tree.extend(parser.parse(f.read()))

    # Compile
    logger.info("Generating CasADi model")

    model = generator.generate(tree, model_name, compiler_options)
    if compiler_options['check_balanced']:
        model.check_balanced()

    model.simplify(compiler_options)

    if compiler_options['verbose']:
        model.check_balanced()

    model._post_checks()

    return model
예제 #2
0
파일: api.py 프로젝트: mdecourse/pymoca
def _compile_model(model_folder: str, model_name: str, compiler_options: Dict[str, str]):
    # Load folders
    tree = None
    for folder in [model_folder] + compiler_options.get('library_folders', []):
        for root, dir, files in os.walk(folder, followlinks=True):
            for item in fnmatch.filter(files, "*.mo"):
                logger.info("Parsing {}".format(item))

                with open(os.path.join(root, item), 'r') as f:
                    if tree is None:
                        tree = parser.parse(f.read())
                    else:
                        tree.extend(parser.parse(f.read()))

    # Compile
    logger.info("Generating CasADi model")

    model = generator.generate(tree, model_name, compiler_options)
    if compiler_options.get('check_balanced', True):
        model.check_balanced()

    model.simplify(compiler_options)

    if compiler_options.get('verbose', False):
        model.check_balanced()

    return model
예제 #3
0
파일: api.py 프로젝트: jgoppert/pymola
def _compile_model(model_folder: str, model_name: str, compiler_options: Dict[str, str]):
    # Load folders
    tree = None
    for folder in [model_folder] + compiler_options.get('library_folders', []):
        for root, dir, files in os.walk(folder, followlinks=True):
            for item in fnmatch.filter(files, "*.mo"):
                logger.info("Parsing {}".format(item))

                with open(os.path.join(root, item), 'r') as f:
                    if tree is None:
                        tree = parser.parse(f.read())
                    else:
                        tree.extend(parser.parse(f.read()))

    # Compile
    logger.info("Generating CasADi model")

    model = generator.generate(tree, model_name, compiler_options)
    if compiler_options.get('check_balanced', True):
        model.check_balanced()

    model.simplify(compiler_options)

    if compiler_options.get('verbose', False):
        model.check_balanced()

    model._post_checks()

    return model
예제 #4
0
    def test_modification_typo(self):
        with open(os.path.join(MODEL_DIR, 'ModificationTypo.mo'), 'r') as f:
            txt = f.read()

        for c in ["Wrong1", "Wrong2"]:
            with self.assertRaises(tree.ModificationTargetNotFound):
                ast_tree = parser.parse(txt)
                flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name=c))

        for c in ["Good1", "Good2"]:
            ast_tree = parser.parse(txt)
            flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name=c))
예제 #5
0
    def test_modification_typo(self):
        with open(os.path.join(MODEL_DIR, 'ModificationTypo.mo'), 'r') as f:
            txt = f.read()

        for c in ["Wrong1", "Wrong2"]:
            with self.assertRaises(tree.ModificationTargetNotFound):
                ast_tree = parser.parse(txt)
                flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name=c))

        for c in ["Good1", "Good2"]:
            ast_tree = parser.parse(txt)
            flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name=c))
예제 #6
0
파일: parse_test.py 프로젝트: vruge/pymoca
    def test_unit_type_array(self):
        txt = """
            model A
              parameter Integer x[2, 2] = {{1, 2}, {3, 4}};
              parameter Real y[2, 2] = {{1.0, 2.0}, {3.0, 4.0}};
            end A;
        """

        ast_tree = parser.parse(txt)

        class_name = 'A'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        # For the moment, we leave type conversions to the backends. We only want to
        # be sure that we read in the correct type in the parser.
        for i in range(2):
            for j in range(2):
                self.assertIsInstance(
                    flat_tree.classes['A'].symbols['x'].value.values[i].
                    values[j].value, int)
                self.assertIsInstance(
                    flat_tree.classes['A'].symbols['y'].value.values[i].
                    values[j].value, float)
예제 #7
0
    def test_inheritance_symbol_modifiers(self):
        with open(os.path.join(MODEL_DIR, 'Inheritance.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='Sub'))

        self.assertEqual(flat_tree.classes['Sub'].symbols['x'].max.value, 30.0)
예제 #8
0
    def test_extends_modification(self):
        with open(os.path.join(MODEL_DIR, 'ExtendsModification.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='MainModel'))

        self.assertEqual(flat_tree.classes['MainModel'].symbols['e.HQ.H'].min.name, "e.H_b")
예제 #9
0
파일: xml_test.py 프로젝트: wind1239/pymoca
    def test_simple_circuit(self):

        # compile to ModelicaXML
        with open(os.path.join(MODEL_DIR, 'SimpleCircuit.mo'), 'r') as f:
            txt = f.read()
        ast_tree = mo_parser.parse(txt)
        model_xml = generator.generate(ast_tree, 'SimpleCircuit')

        # save xml model to disk
        with open(os.path.join(GENERATED_DIR, 'SimpleCircuit.xml'), 'w') as f:
            f.write(model_xml)

        # load xml model
        model = xml_parser.parse(model_xml, verbose=False)
        print(model)

        # convert to ode
        model_ode = model.to_ode()  # type: model.HybridOde
        print(model_ode)

        # simulate
        data = sim_scipy.sim(model_ode, {
            'tf': 1,
            'dt': 0.001,
            'verbose': True
        })

        # plot
        analysis.plot(data, fields=['x', 'c', 'm'])
        plt.draw()
        plt.pause(0.1)
        plt.close()
예제 #10
0
    def test_function_pull(self):
        with open(os.path.join(MODEL_DIR, 'FunctionPull.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'Level1.Level2.Level3.Function5'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        # Check if all referenced functions are pulled in
        self.assertIn('Level1.Level2.Level3.f', flat_tree.classes)
        self.assertIn('Level1.Level2.Level3.TestPackage.times2', flat_tree.classes)
        self.assertIn('Level1.Level2.Level3.TestPackage.square', flat_tree.classes)
        self.assertNotIn('Level1.Level2.Level3.TestPackage.not_called', flat_tree.classes)

        # Check if the classes in the flattened tree have the right type
        self.assertEqual(flat_tree.classes['Function5'].type, 'model')

        self.assertEqual(flat_tree.classes['Level1.Level2.Level3.f'].type, 'function')
        self.assertEqual(flat_tree.classes['Level1.Level2.Level3.TestPackage.times2'].type, 'function')
        self.assertEqual(flat_tree.classes['Level1.Level2.Level3.TestPackage.square'].type, 'function')

        # Check whether input/output information of functions comes along properly
        func_t2 = flat_tree.classes['Level1.Level2.Level3.TestPackage.times2']
        self.assertIn("input", func_t2.symbols['x'].prefixes)
        self.assertIn("output", func_t2.symbols['y'].prefixes)

        # Check if built-in function call statement comes along properly
        func_f = flat_tree.classes['Level1.Level2.Level3.f']
        self.assertEqual(func_f.statements[0].right.operator, '*')
        # Check if user-specified function call statement comes along properly
        self.assertEqual(func_f.statements[0].right.operands[0].operator,
                         'Level1.Level2.Level3.TestPackage.times2')
예제 #11
0
    def test_deep_copy_timeout(self):
        with open(os.path.join(MODEL_DIR, 'DeepCopyTimeout.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        # Start a background thread which will run the flattening, such that
        # we can kill it if takes to long.
        # noinspection PyTypeChecker
        thread = threading.Thread(target=tree.flatten,
                                  args=(
                                      ast_tree,
                                      ast.ComponentRef(name='Test'),
                                  ))

        # Daemon threads automatically stop when the program stops (and do not
        # prevent the program from exiting)
        thread.setDaemon(True)
        thread.start()

        # Use a timeout of 5 seconds. We check every 100 ms sec, such that the
        # test is fast to succeed when everything works as expected.
        for i in range(50):
            time.sleep(0.1)
            if not thread.isAlive():
                return
        self.assertFalse(thread.isAlive(), msg='Timeout occurred')
예제 #12
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_inheritance_symbol_modifiers(self):
        with open(os.path.join(MODEL_DIR, 'Inheritance.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='Sub'))

        self.assertEqual(flat_tree.classes['Sub'].symbols['x'].max.value, 30.0)
예제 #13
0
 def test_duplicate_state(self):
     with open(os.path.join(MODEL_DIR, 'DuplicateState.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     print('AST TREE\n', ast_tree)
     flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='DuplicateState'))
     print('AST TREE FLAT\n', flat_tree)
     self.flush()
예제 #14
0
    def test_redeclare_nested(self):
        with open(
                os.path.join(MODEL_DIR, 'RedeclareNestedClass.mo.fail_parse'),
                'r') as f:
            txt = f.read()

        ast_tree = parser.parse(txt)
        self.assertIsNone(ast_tree)
예제 #15
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_extends_modification(self):
        with open(os.path.join(MODEL_DIR, 'ExtendsModification.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='MainModel'))

        self.assertEqual(
            flat_tree.classes['MainModel'].symbols['e.HQ.H'].min.name, "e.H_b")
예제 #16
0
 def test_estimator(self):
     with open(os.path.join(MODEL_DIR, './Estimator.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     print('AST TREE\n', ast_tree)
     flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='Estimator'))
     print('AST TREE FLAT\n', flat_tree)
     self.flush()
예제 #17
0
파일: parse_test.py 프로젝트: vdwees/pymoca
 def test_spring(self):
     with open(os.path.join(MODEL_DIR, 'Spring.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     print('AST TREE\n', ast_tree)
     flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='Spring'))
     print('AST TREE FLAT\n', flat_tree)
     self.flush()
예제 #18
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_redeclare_nested(self):
        with open(
                os.path.join(MODEL_DIR, 'RedeclareNestedClass.mo.fail_parse'),
                'r') as f:
            txt = f.read()

        with self.assertRaises(Exception):
            ast_tree = parser.parse(txt)
예제 #19
0
    def test_nested_classes(self):
        with open(os.path.join(MODEL_DIR, 'NestedClasses.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='C2'))

        self.assertEqual(flat_tree.classes['C2'].symbols['v1'].nominal.value, 1000.0)
        self.assertEqual(flat_tree.classes['C2'].symbols['v2'].nominal.value, 1000.0)
예제 #20
0
 def test_spring_system(self):
     with open(os.path.join(MODEL_DIR, 'SpringSystem.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     print('AST TREE\n', ast_tree)
     flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='SpringSystem'))
     print('AST TREE FLAT\n', flat_tree)
     self.flush()
예제 #21
0
    def test_inheritance(self):
        with open(os.path.join(MODEL_DIR, 'InheritanceInstantiation.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='C2'))

        self.assertEqual(flat_tree.classes['C2'].symbols['bcomp1.b'].value.value, 3.0)
        self.assertEqual(flat_tree.classes['C2'].symbols['bcomp3.a'].value.value, 1.0)
        self.assertEqual(flat_tree.classes['C2'].symbols['bcomp3.b'].value.value, 2.0)
예제 #22
0
 def test_bouncing_ball(self):
     with open(os.path.join(MODEL_DIR, 'BouncingBall.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     print('AST TREE\n', ast_tree)
     flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='BouncingBall'))
     print(flat_tree)
     print('AST TREE FLAT\n', flat_tree)
     self.flush()
예제 #23
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_nested_classes(self):
        with open(os.path.join(MODEL_DIR, 'NestedClasses.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='C2'))

        self.assertEqual(flat_tree.classes['C2'].symbols['v1'].nominal.value,
                         1000.0)
        self.assertEqual(flat_tree.classes['C2'].symbols['v2'].nominal.value,
                         1000.0)
예제 #24
0
파일: xml_test.py 프로젝트: wind1239/pymoca
    def test_bouncing_ball(self):

        # generate
        with open(os.path.join(MODEL_DIR, 'BouncingBall.mo'), 'r') as f:
            txt = f.read()
        ast_tree = mo_parser.parse(txt)
        generator.generate(ast_tree, 'BouncingBall')

        # parse
        example_file = os.path.join(MODEL_DIR, 'bouncing-ball.xml')
        model = xml_parser.parse_file(example_file, verbose=False)
        print(model)

        # convert to ode
        model_ode = model.to_ode()  # type: model.HybridOde
        model_ode.prop['x']['start'] = 1
        print(model_ode)

        # simulate
        data = sim_scipy.sim(model_ode, {
            'tf': 3.5,
            'dt': 0.01,
            'verbose': True
        })

        # plot
        analysis.plot(data, linewidth=0.5, marker='.', markersize=0.5)
        plt.draw()
        plt.pause(0.1)
        plt.close()

        # simulate in soft real-time
        do_realtime = False
        if do_realtime:
            print('\nsoft-realtime simulation')
            time_start = time.time()

            def realtime_callback(t, x, y, m, p, c):
                t_real = time.time() - time_start
                lag = t_real - t
                if abs(lag) > 0.1:
                    print("real: {:10f} > sim: {:10f}, lag: {:10f}".format(
                        t_real, t, lag))
                elif lag < 0:
                    time.sleep(-lag)

            data = sim_scipy.sim(model_ode, {
                'tf': 3.5,
                'dt': 0.01,
                'verbose': True
            },
                                 user_callback=realtime_callback)

        # plt.gca().set_ylim(-2, 2)
        self.flush()
예제 #25
0
    def test_parameter_modification_scope(self):
        with open(os.path.join(MODEL_DIR, 'ParameterScope.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'ScopeTest'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(flat_tree.classes['ScopeTest'].symbols['nc.p'].value.name, 'p')
예제 #26
0
    def test_extends_order(self):
        with open(os.path.join(MODEL_DIR, 'ExtendsOrder.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'P.M'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(flat_tree.classes['M'].symbols['at.m'].value.value, 0.0)
예제 #27
0
    def test_nested_symbol_modification(self):
        with open(os.path.join(MODEL_DIR, 'NestedSymbolModification.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'E'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(flat_tree.classes['E'].symbols['c.x'].nominal.value, 2.0)
예제 #28
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_redeclare_in_extends(self):
        with open(os.path.join(MODEL_DIR, 'RedeclareInExtends.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'ChannelZ'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertIn('down.Z', flat_tree.classes['ChannelZ'].symbols)
예제 #29
0
파일: parse_test.py 프로젝트: vdwees/pymoca
 def test_connector(self):
     with open(os.path.join(MODEL_DIR, 'Connector.mo'), 'r') as f:
         txt = f.read()
     # noinspection PyUnusedLocal
     ast_tree = parser.parse(txt)
     # states = ast_tree.classes['Aircraft'].states
     # names = sorted([state.name for state in states])
     # names_set = sorted(list(set(names)))
     # if names != names_set:
     #     raise IOError('{:s} != {:s}'.format(str(names), str(names_set)))
     self.flush()
예제 #30
0
    def test_redeclare_in_extends(self):
        with open(os.path.join(MODEL_DIR, 'RedeclareInExtends.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'ChannelZ'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertIn('down.Z', flat_tree.classes['ChannelZ'].symbols)
예제 #31
0
 def test_connector(self):
     with open(os.path.join(MODEL_DIR, 'Connector.mo'), 'r') as f:
         txt = f.read()
     # noinspection PyUnusedLocal
     ast_tree = parser.parse(txt)
     # states = ast_tree.classes['Aircraft'].states
     # names = sorted([state.name for state in states])
     # names_set = sorted(list(set(names)))
     # if names != names_set:
     #     raise IOError('{:s} != {:s}'.format(str(names), str(names_set)))
     self.flush()
예제 #32
0
    def test_extends_redeclareable(self):
        with open(os.path.join(MODEL_DIR, 'ExtendsRedeclareable.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'E'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertIn('z.y', flat_tree.classes['E'].symbols)
        self.assertEqual(flat_tree.classes['E'].symbols['z.y'].nominal.value, 2.0)
예제 #33
0
    def test_constant_references(self):
        with open(os.path.join(MODEL_DIR, 'ConstantReferences.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'b'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(flat_tree.classes['b'].symbols['m.p'].value.value, 2.0)
        self.assertEqual(flat_tree.classes['b'].symbols['M2.m.f'].value.value, 3.0)
예제 #34
0
    def test_custom_units(self):
        with open(os.path.join(MODEL_DIR, 'CustomUnits.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'A'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(flat_tree.classes['A'].symbols['dummy_parameter'].unit.value, "m/s")
        self.assertEqual(flat_tree.classes['A'].symbols['dummy_parameter'].value.value, 10.0)
예제 #35
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_extends_order(self):
        with open(os.path.join(MODEL_DIR, 'ExtendsOrder.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'P.M'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(flat_tree.classes['M'].symbols['at.m'].value.value,
                         0.0)
예제 #36
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_parameter_modification_scope(self):
        with open(os.path.join(MODEL_DIR, 'ParameterScope.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'ScopeTest'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(
            flat_tree.classes['ScopeTest'].symbols['nc.p'].value.name, 'p')
예제 #37
0
파일: parse_test.py 프로젝트: vruge/pymoca
    def test_redeclaration_scope_alternative(self):
        with open(os.path.join(MODEL_DIR, 'RedeclarationScopeAlternative.mo'),
                  'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'ChannelZ'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertIn('c.up.Z', flat_tree.classes['ChannelZ'].symbols)
        self.assertIn('c.down.A', flat_tree.classes['ChannelZ'].symbols)
예제 #38
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_inheritance(self):
        with open(os.path.join(MODEL_DIR, 'InheritanceInstantiation.mo'),
                  'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='C2'))

        self.assertEqual(
            flat_tree.classes['C2'].symbols['bcomp1.b'].value.value, 3.0)
        self.assertEqual(
            flat_tree.classes['C2'].symbols['bcomp3.a'].value.value, 1.0)
        self.assertEqual(
            flat_tree.classes['C2'].symbols['bcomp3.b'].value.value, 2.0)
예제 #39
0
    def test_extend_from_self(self):
        txt = """
        model A
          extends A;
        end A;"""

        ast_tree = parser.parse(txt)

        class_name = 'A'
        comp_ref = ast.ComponentRef.from_string(class_name)

        with self.assertRaisesRegex(Exception, "Cannot extend class 'A' with itself"):
            flat_tree = tree.flatten(ast_tree, comp_ref)
예제 #40
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_nested_symbol_modification(self):
        with open(os.path.join(MODEL_DIR, 'NestedSymbolModification.mo'),
                  'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'E'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(flat_tree.classes['E'].symbols['c.x'].nominal.value,
                         2.0)
예제 #41
0
 def test_estimator(self):
     with open(os.path.join(MODEL_DIR, 'Estimator.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     text = gen_sympy.generate(ast_tree, 'Estimator')
     with open(os.path.join(GENERATED_DIR, 'Estimator.py'), 'w') as f:
         f.write(text)
     from test.generated.Estimator import Estimator as Estimator
     e = Estimator()
     e.linearize_symbolic()
     e.linearize()
     # noinspection PyUnusedLocal
     res = e.simulate(x0=[1.0])
     self.flush()
예제 #42
0
파일: parse_test.py 프로젝트: vruge/pymoca
    def test_extend_from_self(self):
        txt = """
        model A
          extends A;
        end A;"""

        ast_tree = parser.parse(txt)

        class_name = 'A'
        comp_ref = ast.ComponentRef.from_string(class_name)

        with self.assertRaisesRegex(Exception,
                                    "Cannot extend class 'A' with itself"):
            flat_tree = tree.flatten(ast_tree, comp_ref)
예제 #43
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_extends_redeclareable(self):
        with open(os.path.join(MODEL_DIR, 'ExtendsRedeclareable.mo'),
                  'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'E'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertIn('z.y', flat_tree.classes['E'].symbols)
        self.assertEqual(flat_tree.classes['E'].symbols['z.y'].nominal.value,
                         2.0)
예제 #44
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_constant_references(self):
        with open(os.path.join(MODEL_DIR, 'ConstantReferences.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'b'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(flat_tree.classes['b'].symbols['m.p'].value.value,
                         2.0)
        self.assertEqual(flat_tree.classes['b'].symbols['M2.m.f'].value.value,
                         3.0)
예제 #45
0
 def test_estimator(self):
     with open(os.path.join(MODEL_DIR, 'Estimator.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     text = gen_sympy.generate(ast_tree, 'Estimator')
     with open(os.path.join(GENERATED_DIR, 'Estimator.py'), 'w') as f:
         f.write(text)
     from test.generated.Estimator import Estimator as Estimator
     e = Estimator()
     e.linearize_symbolic()
     e.linearize()
     # noinspection PyUnusedLocal
     res = e.simulate(x0=[1.0])
     self.flush()
예제 #46
0
 def test_quad(self):
     with open(os.path.join(MODEL_DIR, 'Quad.mo'), 'r') as f:
         txt = f.read()
     # noinspection PyUnusedLocal
     ast_tree = parser.parse(txt)
     text = gen_sympy.generate(ast_tree, 'Quad')
     with open(os.path.join(GENERATED_DIR, 'Quad.py'), 'w') as f:
         f.write(text)
     from test.generated.Quad import Quad as Quad
     e = Quad()
     e.linearize_symbolic()
     e.linearize()
     # noinspection PyUnusedLocal
     res = e.simulate()
     self.flush()
예제 #47
0
 def test_aircraft(self):
     with open(os.path.join(MODEL_DIR, 'Aircraft.mo'), 'r') as f:
         txt = f.read()
     # noinspection PyUnusedLocal
     ast_tree = parser.parse(txt)
     text = gen_sympy.generate(ast_tree, 'Aircraft')
     with open(os.path.join(GENERATED_DIR, 'Aircraft.py'), 'w') as f:
         f.write(text)
     from test.generated.Aircraft import Aircraft as Aircraft
     e = Aircraft()
     e.linearize_symbolic()
     e.linearize()
     # noinspection PyUnusedLocal
     res = e.simulate()
     self.flush()
예제 #48
0
 def test_aircraft(self):
     with open(os.path.join(MODEL_DIR, 'Aircraft.mo'), 'r') as f:
         txt = f.read()
     # noinspection PyUnusedLocal
     ast_tree = parser.parse(txt)
     text = gen_sympy.generate(ast_tree, 'Aircraft')
     with open(os.path.join(GENERATED_DIR, 'Aircraft.py'), 'w') as f:
         f.write(text)
     from test.generated.Aircraft import Aircraft as Aircraft
     e = Aircraft()
     e.linearize_symbolic()
     e.linearize()
     # noinspection PyUnusedLocal
     res = e.simulate()
     self.flush()
예제 #49
0
 def test_quad(self):
     with open(os.path.join(MODEL_DIR, 'Quad.mo'), 'r') as f:
         txt = f.read()
     # noinspection PyUnusedLocal
     ast_tree = parser.parse(txt)
     text = gen_sympy.generate(ast_tree, 'Quad')
     with open(os.path.join(GENERATED_DIR, 'Quad.py'), 'w') as f:
         f.write(text)
     from test.generated.Quad import Quad as Quad
     e = Quad()
     e.linearize_symbolic()
     e.linearize()
     # noinspection PyUnusedLocal
     res = e.simulate()
     self.flush()
예제 #50
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_custom_units(self):
        with open(os.path.join(MODEL_DIR, 'CustomUnits.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'A'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        self.assertEqual(
            flat_tree.classes['A'].symbols['dummy_parameter'].unit.value,
            "m/s")
        self.assertEqual(
            flat_tree.classes['A'].symbols['dummy_parameter'].value.value,
            10.0)
예제 #51
0
 def test_spring(self):
     with open(os.path.join(MODEL_DIR, 'SpringSystem.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='SpringSystem'))
     print(flat_tree)
     text = gen_sympy.generate(ast_tree, 'SpringSystem')
     with open(os.path.join(GENERATED_DIR, 'Spring.py'), 'w') as f:
         f.write(text)
     from test.generated.Spring import SpringSystem as SpringSystem
     e = SpringSystem()
     e.linearize_symbolic()
     e.linearize()
     # noinspection PyUnusedLocal
     res = e.simulate(x0=[1.0, 1.0])
     self.flush()
예제 #52
0
    def test_tree_lookup(self):
        with open(os.path.join(MODEL_DIR, 'TreeLookup.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        # The class we want to flatten. We first have to turn it into a
        # full-fledged ComponentRef.
        class_name = 'Level1.Level2.Level3.Test'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        # NOTE: We currently do not flatten the component ref in the final
        # tree's keys, so we use it once again to lookup the flattened class.
        self.assertIn('elem.tc.i', flat_tree.classes['Test'].symbols.keys())
        self.assertIn('elem.tc.a', flat_tree.classes['Test'].symbols.keys())
        self.assertIn('b',         flat_tree.classes['Test'].symbols.keys())
예제 #53
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_tree_lookup(self):
        with open(os.path.join(MODEL_DIR, 'TreeLookup.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        # The class we want to flatten. We first have to turn it into a
        # full-fledged ComponentRef.
        class_name = 'Level1.Level2.Level3.Test'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        # NOTE: We currently do not flatten the component ref in the final
        # tree's keys, so we use it once again to lookup the flattened class.
        self.assertIn('elem.tc.i', flat_tree.classes['Test'].symbols.keys())
        self.assertIn('elem.tc.a', flat_tree.classes['Test'].symbols.keys())
        self.assertIn('b', flat_tree.classes['Test'].symbols.keys())
예제 #54
0
 def test_spring(self):
     with open(os.path.join(MODEL_DIR, 'SpringSystem.mo'), 'r') as f:
         txt = f.read()
     ast_tree = parser.parse(txt)
     flat_tree = tree.flatten(ast_tree,
                              ast.ComponentRef(name='SpringSystem'))
     print(flat_tree)
     text = gen_sympy.generate(ast_tree, 'SpringSystem')
     with open(os.path.join(GENERATED_DIR, 'Spring.py'), 'w') as f:
         f.write(text)
     from test.generated.Spring import SpringSystem as SpringSystem
     e = SpringSystem()
     e.linearize_symbolic()
     e.linearize()
     # noinspection PyUnusedLocal
     res = e.simulate(x0=[1.0, 1.0])
     self.flush()
예제 #55
0
파일: parse_test.py 프로젝트: vdwees/pymoca
    def test_function_pull(self):
        with open(os.path.join(MODEL_DIR, 'FunctionPull.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        class_name = 'Level1.Level2.Level3.Function5'
        comp_ref = ast.ComponentRef.from_string(class_name)

        flat_tree = tree.flatten(ast_tree, comp_ref)

        # Check if all referenced functions are pulled in
        self.assertIn('Level1.Level2.Level3.f', flat_tree.classes)
        self.assertIn('Level1.Level2.Level3.TestPackage.times2',
                      flat_tree.classes)
        self.assertIn('Level1.Level2.Level3.TestPackage.square',
                      flat_tree.classes)
        self.assertNotIn('Level1.Level2.Level3.TestPackage.not_called',
                         flat_tree.classes)

        # Check if the classes in the flattened tree have the right type
        self.assertEqual(flat_tree.classes['Function5'].type, 'model')

        self.assertEqual(flat_tree.classes['Level1.Level2.Level3.f'].type,
                         'function')
        self.assertEqual(
            flat_tree.classes['Level1.Level2.Level3.TestPackage.times2'].type,
            'function')
        self.assertEqual(
            flat_tree.classes['Level1.Level2.Level3.TestPackage.square'].type,
            'function')

        # Check whether input/output information of functions comes along properly
        func_t2 = flat_tree.classes['Level1.Level2.Level3.TestPackage.times2']
        self.assertIn("input", func_t2.symbols['x'].prefixes)
        self.assertIn("output", func_t2.symbols['y'].prefixes)

        # Check if built-in function call statement comes along properly
        func_f = flat_tree.classes['Level1.Level2.Level3.f']
        self.assertEqual(func_f.statements[0].right.operator, '*')
        # Check if user-specified function call statement comes along properly
        self.assertEqual(func_f.statements[0].right.operands[0].operator,
                         'Level1.Level2.Level3.TestPackage.times2')
예제 #56
0
    def test_connector(self):
        with open(os.path.join(MODEL_DIR, 'Connector.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)
        # print(ast_tree)

        # noinspection PyUnusedLocal
        flat_tree = tree.flatten(ast_tree, ast.ComponentRef(name='Aircraft'))
        # print(flat_tree)

        # noinspection PyUnusedLocal
        walker = tree.TreeWalker()
        # noinspection PyUnusedLocal
        classes = ast_tree.classes
        # noinspection PyUnusedLocal
        root = ast_tree.classes['Aircraft']

        # instantiator = tree.Instantiator(classes=classes)
        # walker.walk(instantiator, root)
        # print(instantiator.res[root].symbols.keys())
        # print(instantiator.res[root])

        # print('INSTANTIATOR\n-----------\n\n')
        # print(instantiator.res[root])

        # connectExpander = tree.ConnectExpander(classes=classes)
        # walker.walk(connectExpander, instantiator.res[root])

        # print('CONNECT EXPANDER\n-----------\n\n')
        # print(connectExpander.new_class)

        # text = gen_sympy.generate(ast_tree, 'Aircraft')
        # print(text)
        # with open(os.path.join(MODEL_DIR, 'generated/Connect.py'), 'w') as f:
        #    f.write(text)

        # from generated.Connect import Aircraft as Aircraft
        # e = Aircraft()
        # res = e.simulate()
        self.flush()
예제 #57
0
    def test_deep_copy_timeout(self):
        with open(os.path.join(MODEL_DIR, 'DeepCopyTimeout.mo'), 'r') as f:
            txt = f.read()
        ast_tree = parser.parse(txt)

        # Start a background thread which will run the flattening, such that
        # we can kill it if takes to long.
        # noinspection PyTypeChecker
        thread = threading.Thread(target=tree.flatten, args=(ast_tree, ast.ComponentRef(name='Test'),))

        # Daemon threads automatically stop when the program stops (and do not
        # prevent the program from exiting)
        thread.setDaemon(True)
        thread.start()

        # Use a timeout of 5 seconds. We check every 100 ms sec, such that the
        # test is fast to succeed when everything works as expected.
        for i in range(50):
            time.sleep(0.1)
            if not thread.isAlive():
                return
        self.assertFalse(thread.isAlive(), msg='Timeout occurred')
예제 #58
0
파일: compiler.py 프로젝트: jgoppert/pymola
logging.basicConfig(level=logging.DEBUG if options.verbose else logging.INFO)

# Import rest of pymoca
from pymoca import parser, tree, ast

# Compile
if options.flatten_only:
    # Load folder
    _ast = None
    for root, dir, files in os.walk(model_folder, followlinks=True):
        for item in fnmatch.filter(files, "*.mo"):
            logger.info("Parsing {}".format(item))

            with open(os.path.join(root, item), 'r') as f:
                if _ast is None:
                    _ast = parser.parse(f.read())
                else:
                    _ast.extend(parser.parse(f.read()))

    logger.info("Flattening")

    _ast = tree.flatten(_ast, ast.ComponentRef.from_string(model_name))
    print(_ast)
else:
    # Set CasADi installation folder
    if options.casadi_folder is not None:
        sys.path.append(options.casadi_folder)

    from pymoca.backends.casadi.api import transfer_model
    import casadi as ca
예제 #59
0
    def test_redeclare_nested(self):
        with open(os.path.join(MODEL_DIR, 'RedeclareNestedClass.mo.fail_parse'), 'r') as f:
            txt = f.read()

        with self.assertRaises(Exception):
            ast_tree = parser.parse(txt)