def setUpClass(cls):
        """
        Compile the test model.
        """
        #DAE with disc
        fpath_DISC = os.path.join(get_files_path(), 'Modelica', 
            'IfExpExamples.mo')
        cpath_DISC = 'IfExpExamples.IfExpExample2'
        
        fname_DISC = compile_jmu(cpath_DISC, fpath_DISC)
        
        #DAE test model
        fpath_DAE = os.path.join(get_files_path(), 'Modelica', 
            'Pendulum_pack_no_opt.mo')
        cpath_DAE = 'Pendulum_pack.Pendulum'

        fname_DAE = compile_jmu(cpath_DAE, fpath_DAE)
        
        #DAE with sens
        fpath_SENS = os.path.join(get_files_path(), 'Modelica', 
            'QuadTankSens.mop')
        cpath_SENS = 'QuadTankSens'
        
        fname_SENS = compile_jmu(cpath_SENS, fpath_SENS, compiler_options={"enable_variable_scaling":True})
        
        fpath = os.path.join(get_files_path(), 'Modelica', 'DoubleInput.mo')
        cpath = 'DoubleInput_Nominal'
        fname = compile_jmu(cpath, fpath, 
                    compiler_options={"enable_variable_scaling":True})
Ejemplo n.º 2
0
    def setUpClass(cls):
        """
        Compile the test model.
        """
        #DAE with disc
        fpath_DISC = os.path.join(get_files_path(), 'Modelica',
                                  'IfExpExamples.mo')
        cpath_DISC = 'IfExpExamples.IfExpExample2'

        fname_DISC = compile_jmu(cpath_DISC, fpath_DISC)

        #DAE test model
        fpath_DAE = os.path.join(get_files_path(), 'Modelica',
                                 'Pendulum_pack_no_opt.mo')
        cpath_DAE = 'Pendulum_pack.Pendulum'

        fname_DAE = compile_jmu(cpath_DAE, fpath_DAE)

        #DAE with sens
        fpath_SENS = os.path.join(get_files_path(), 'Modelica',
                                  'QuadTankSens.mop')
        cpath_SENS = 'QuadTankSens'

        fname_SENS = compile_jmu(
            cpath_SENS,
            fpath_SENS,
            compiler_options={"enable_variable_scaling": True})

        fpath = os.path.join(get_files_path(), 'Modelica', 'DoubleInput.mo')
        cpath = 'DoubleInput_Nominal'
        fname = compile_jmu(cpath,
                            fpath,
                            compiler_options={"enable_variable_scaling": True})
Ejemplo n.º 3
0
    def test_scaling(self):
        """
        This tests a simulation when scaling is ON and OFF.
        """
        jmu_name = compile_jmu("Englezos652", os.path.join(get_files_path()
                        ,"Modelica","Englezos652.mop"),
                        compiler_options={"enable_variable_scaling":False})

        # Load a model instance into Python
        model = JMUModel(jmu_name)

        # Get and set the options
        opts = model.simulate_options()
        opts['IDA_options']['atol'] = 1.0e-9
        opts['IDA_options']['rtol'] = 1.0e-9
        opts['IDA_options']['sensitivity'] = True
        opts['ncp'] = 400
        
        res_no_scale = model.simulate(final_time=1697000, options=opts)
        
        jmu_name = compile_jmu("Englezos652", os.path.join(get_files_path()
                        ,"Modelica","Englezos652.mop"),
                        compiler_options={"enable_variable_scaling":True})

        # Load a model instance into Python
        model = JMUModel(jmu_name)
        
        res_with_scale = model.simulate(final_time=1697000, options=opts)
        
        nose.tools.assert_almost_equal(res_with_scale['x1'][-1], 
                                       res_no_scale['x1'][-1], 4)
        
        nose.tools.assert_almost_equal(res_with_scale['dx1/dk1'][-1], 
                                       res_no_scale['dx1/dk1'][-1], 1)
    def test_scaling(self):
        """
        This tests a simulation when scaling is ON and OFF.
        """
        jmu_name = compile_jmu("Englezos652", os.path.join(get_files_path()
                        ,"Modelica","Englezos652.mop"),
                        compiler_options={"enable_variable_scaling":False})

        # Load a model instance into Python
        model = JMUModel(jmu_name)

        # Get and set the options
        opts = model.simulate_options()
        opts['IDA_options']['atol'] = 1.0e-9
        opts['IDA_options']['rtol'] = 1.0e-9
        opts['IDA_options']['sensitivity'] = True
        opts['ncp'] = 400
        
        res_no_scale = model.simulate(final_time=1697000, options=opts)
        
        jmu_name = compile_jmu("Englezos652", os.path.join(get_files_path()
                        ,"Modelica","Englezos652.mop"),
                        compiler_options={"enable_variable_scaling":True})

        # Load a model instance into Python
        model = JMUModel(jmu_name)
        
        res_with_scale = model.simulate(final_time=1697000, options=opts)
        
        nose.tools.assert_almost_equal(res_with_scale['x1'][-1], 
                                       res_no_scale['x1'][-1], 4)
        
        nose.tools.assert_almost_equal(res_with_scale['dx1/dk1'][-1], 
                                       res_no_scale['dx1/dk1'][-1], 1)
 def setUpClass(cls):
     model_file = os.path.join(get_files_path(), 'Modelica',
                               'NegatedAlias.mo')
     name = compile_fmu("NegatedAlias", model_file)
     model_file = os.path.join(get_files_path(), 'Modelica',
                               'ParameterAlias.mo')
     name = compile_fmu("ParameterAlias", model_file)
Ejemplo n.º 6
0
 def setUpClass(cls):
     """Sets up the test class."""
     # Compile the stationary initialization model into a JMU
     fpath1 = os.path.join(get_files_path(), 'Modelica', 'CSTRLib.mo')
     fpath2 = os.path.join(get_files_path(), 'Modelica', 'TestMinMax.mo')
     compile_jmu("CSTRLib.Components.Two_CSTRs_stat_init", fpath1)
     #compile_jmu("Tests.TestInvalidStart", fpath2)
     compile_jmu("TestMinMax.TestGuess", fpath2)
Ejemplo n.º 7
0
 def setUpClass(cls):
     """Sets up the test class."""
     # Compile the stationary initialization model into a JMU
     fpath1 = os.path.join(get_files_path(), 'Modelica', 'CSTRLib.mo')
     fpath2 = os.path.join(get_files_path(), 'Modelica', 'TestMinMax.mo')
     compile_jmu("CSTRLib.Components.Two_CSTRs_stat_init", fpath1)
     #compile_jmu("Tests.TestInvalidStart", fpath2)
     compile_jmu("TestMinMax.TestGuess", fpath2)
Ejemplo n.º 8
0
 def setUpClass(cls):
     """
     Sets up the test class.
     """
     cls.fpath_mc = os.path.join(get_files_path(), 'Modelica',
                                 'Pendulum_pack_no_opt.mo')
     cls.cpath_mc = "Pendulum_pack.Pendulum"
     cls.fpath_oc = os.path.join(get_files_path(), 'Modelica',
                                 'Pendulum_pack.mop')
     cls.cpath_oc = "Pendulum_pack.Pendulum_Opt"
Ejemplo n.º 9
0
 def setUp(self):
     """
     Sets up the test case.
     """
     self.cpath_vdp = "VDP_pack.VDP_Opt"
     self.fpath_vdp = os.path.join(get_files_path(),'Modelica','VDP.mop')
     self.cpath_minit = "must_initialize"
     self.fpath_minit = os.path.join(get_files_path(), 'Modelica', 'must_initialize.mo')
     self.fpath_rlc = os.path.join(get_files_path(),'Modelica','RLC_Circuit.mo')
     self.cpath_rlc = "RLC_Circuit"
     self.model_rlc = JMUModel(Test_init_assimulo.jmu_name)
Ejemplo n.º 10
0
 def setUp(self):
     """
     Sets up the test case.
     """
     self.cpath_vdp = "VDP_pack.VDP_Opt"
     self.fpath_vdp = os.path.join(get_files_path(),'Modelica','VDP.mop')
     self.cpath_minit = "must_initialize"
     self.fpath_minit = os.path.join(get_files_path(), 'Modelica', 'must_initialize.mo')
     self.fpath_rlc = os.path.join(get_files_path(),'Modelica','RLC_Circuit.mo')
     self.cpath_rlc = "RLC_Circuit"
     self.model_rlc = JMUModel(Test_init_assimulo.jmu_name)
Ejemplo n.º 11
0
 def setUpClass(cls):
     """
     Sets up the test class.
     """
     cls.mc = ModelicaCompiler()
     cls.oc = OptimicaCompiler()
     cls.jm_home = pym.environ['JMODELICA_HOME']
     cls.fpath_mc = os.path.join(get_files_path(), 'Modelica',
                                 'Pendulum_pack_no_opt.mo')
     cls.cpath_mc = "Pendulum_pack.Pendulum"
     cls.fpath_oc = os.path.join(get_files_path(), 'Modelica',
                                 'Pendulum_pack.mop')
     cls.cpath_oc = "Pendulum_pack.Pendulum_Opt"
Ejemplo n.º 12
0
 def setUpClass(cls):
     """
     Sets up the test class.
     """
     cls.mc = ModelicaCompiler()
     cls.oc = OptimicaCompiler()
     cls.jm_home = pym.environ['JMODELICA_HOME']        
     cls.fpath_mc = os.path.join(get_files_path(), 'Modelica', 
         'Pendulum_pack_no_opt.mo')
     cls.cpath_mc = "Pendulum_pack.Pendulum"
     cls.fpath_oc = os.path.join(get_files_path(), 'Modelica', 
         'Pendulum_pack.mop')
     cls.cpath_oc = "Pendulum_pack.Pendulum_Opt"
Ejemplo n.º 13
0
 def test_inlined_switches(self):
     """ Test a model that need in-lined switches to initialize. """
     path = os.path.join(get_files_path(), 'Modelica', 'event_init.mo')
     fmu_name = compile_fmu('Init', path)
     model = load_fmu(fmu_name)
     model.initialize()
     assert N.abs(model.get("x") - (-2.15298995))              < 1e-3
Ejemplo n.º 14
0
 def test_guid(self):
     from pymodelica import compile_fmu
     from pyfmi import load_fmu
     mo_file = os.path.join(get_files_path(), 'Modelica', "BouncingBall.mo")
     fmu = load_fmu(compile_fmu("BouncingBall", [mo_file]))
     guid = fmu.get_guid()
     assert guid == "e3b48aa15b4f281c119e2208b06a2582", "GUID was " + fmu.get_guid()
Ejemplo n.º 15
0
 def test_set_compiler_options(self):
     """ Test compiling with compiler options."""
     libdir = os.path.join(get_files_path(), 'MODELICAPATH_test', 'LibLoc1',
         'LibA')
     co = {"index_reduction":True, "equation_sorting":True}
     compile_fmu('RLC_Circuit', [os.path.join(path_to_mofiles,'RLC_Circuit.mo'), libdir],
         compiler_options = co)
Ejemplo n.º 16
0
    def setUpClass(cls):
        """Sets up the class."""
        fpath = os.path.join(get_files_path(), 'Modelica', 'CSTR.mop')
        cpath = "CSTR.CSTR_Init"

        compile_jmu(cpath, fpath, 
            compiler_options={'state_start_values_fixed':False})
Ejemplo n.º 17
0
 def setUpClass(cls):
     """Sets up the test class."""
     fpath_daeinit = os.path.join(get_files_path(), 'Modelica', 
         'DAEInitTest.mo')
     cpath_daeinit = "DAEInitTest"
     compile_jmu(cpath_daeinit, fpath_daeinit, 
         compiler_options={'state_start_values_fixed':True, 'variability_propagation':False})
Ejemplo n.º 18
0
 def setUpClass(cls):
     curr_dir = os.path.dirname(os.path.abspath(__file__));
     mofile = os.path.join(get_files_path(), 'Modelica', 'StaticOptimizationTest.mop')
     compile_jmu("StaticOptimizationTest.StaticOptimizationTest2", mofile)
     cls.model = JMUModel("StaticOptimizationTest_StaticOptimizationTest2.jmu")
     cls.nlp = NLPInitialization(cls.model,stat=1)
     cls.ipopt_nlp = InitializationOptimizer(cls.nlp)
    def test_order_input(self):
        """
        This tests that the inputs are sorted in an correct value reference order
        when being written to file.
        """
        fpath = os.path.join(get_files_path(), 'Modelica', 'OrderInputs.mop')
        cpath = 'OptimInputs'
        
        unames = ['u1', 'u_e2', 'u_h3', 'u_c4', 'u_p5']
        n = len(unames)

        uvalues = [1.,2.,3.,4.,5.]

        data = N.array([[0.,1.,2.,3.,4.,5.],
                 [1.,1.,2.,3.,4.,5.],
                 [2.,1.,2.,3.,4.,5.]])
        inputtuple = (unames,data)
        jmu_name = compile_jmu(cpath,fpath)
        
        model = JMUModel(jmu_name)
        res = model.simulate(0,2,input=inputtuple)
        
        nose.tools.assert_almost_equal(res["u1"][-1], 1.000000000, 3)
        nose.tools.assert_almost_equal(res["u_e2"][-1], 2.00000, 3)
        nose.tools.assert_almost_equal(res["u_h3"][-1], 3.00000, 3)
        nose.tools.assert_almost_equal(res["u_c4"][-1], 4.000000, 3)
        nose.tools.assert_almost_equal(res["u_p5"][-1], 5.000000, 3)
        
        nose.tools.assert_almost_equal(res["T.u1"][-1], 1.000000000, 3)
        nose.tools.assert_almost_equal(res["T.u_e2"][-1], 2.00000, 3)
        nose.tools.assert_almost_equal(res["T.u_h3"][-1], 3.00000, 3)
        nose.tools.assert_almost_equal(res["T.u_c4"][-1], 4.000000, 3)
        nose.tools.assert_almost_equal(res["T.u_p5"][-1], 5.000000, 3)
Ejemplo n.º 20
0
    def setUpClass(cls):
        """
        Compile the test model.
        """
        file_name = os.path.join(get_files_path(), 'Modelica', 'Reinit.mo')

        compile_fmu("Reinit.ReinitWriteback", file_name)
    def test_scaling_test_2(self):
        """
        This tests a simulation when scaling is ON and there are input variables
        that are not used.
        """
        jmu_name = compile_jmu("Englezos652_with_input", os.path.join(get_files_path()
                        ,"Modelica","Englezos652.mop"),
                        compiler_options={"enable_variable_scaling":False})

        # Load a model instance into Python
        model = JMUModel(jmu_name)

        # Get and set the options
        opts = model.simulate_options()
        opts['IDA_options']['atol'] = 1.0e-6
        opts['IDA_options']['rtol'] = 1.0e-6
        opts['IDA_options']['sensitivity'] = True
        opts['ncp'] = 400
        
        res = model.simulate(0,1697000/3, options=opts)
        
        x1 = res["x1"][-1]
        r1 = res["r1"][-1]
        u1 = res["u1"][-1]

        nose.tools.assert_almost_equal(x1, 0.45537058, 3)
        nose.tools.assert_almost_equal(r1, 5.3287e-8, 2)
        nose.tools.assert_almost_equal(u1, 0.00000, 3)
Ejemplo n.º 22
0
 def load_expected_data(self, name):
     """
     Load the expected data to use for assert_all_paths() and assert_all_end_values().
       name -  the file name of the results file, relative to files dir
     """
     path = os.path.join(get_files_path(), 'Results', name)
     self.expected = ResultDymolaTextual(path)
def test_update_dependent_parameter():
    file_path = os.path.join(get_files_path(), 'Modelica', 'TestWarmStart.mop')
    compiler_options={"eliminate_alias_parameters": True}
    op = transfer_optimization_problem("TestDependentParameter", file_path,
                                       compiler_options=compiler_options)

    solver = op.prepare_optimization()
    res = solver.optimize()

    assert solver.get('p') ==  1
    assert solver.get('q') == -1
    assert solver.get('r') == 1
    assert solver.get('s') == 1
    assert N.abs(res.final('x') - N.exp(-1)) < 1e-8

    solver.set('p', 2)

    assert solver.get('p') ==  2
    assert solver.get('q') == -2
    assert solver.get('r') ==  2
    assert solver.get('s') ==  4

    res = solver.optimize()

    assert solver.get('p') ==  2
    assert solver.get('q') == -2
    assert N.abs(res.final('x') - N.exp(-2)) < 1e-8
Ejemplo n.º 24
0
 def test_IO_error(self):
     """ Test that an IOError is raised if the model file is not found. """
     errorpath = os.path.join(get_files_path(), 'Modelica','NonExistingModel.mo')
     nose.tools.assert_raises(IOError, Test_Compiler.mc.compile_JMU, Test_Compiler.cpath_mc, [errorpath], '.')
     nose.tools.assert_raises(IOError, Test_Compiler.oc.compile_JMU, Test_Compiler.cpath_oc, [errorpath], '.')
     nose.tools.assert_raises(IOError, pym.compile_fmu, Test_Compiler.cpath_mc, errorpath, separate_process=True)
     nose.tools.assert_raises(IOError, pym.compile_jmu, Test_Compiler.cpath_oc, errorpath, separate_process=True)
Ejemplo n.º 25
0
    def test_get_column(self):
        """
        Test the get_column and get_data_matrix.
        """
        model_file = os.path.join(get_files_path(), 'Modelica',
                                  'RLC_Circuit.mo')
        compile_jmu('RLC_Circuit', model_file)
        model = JMUModel('RLC_Circuit.jmu')
        res = model.simulate()

        assert res.is_negated('resistor1.n.i')
        assert res.is_negated('capacitor.n.i')
        assert not res.is_variable('sine.freqHz')

        dataMatrix = res.data_matrix

        col = res.get_column('capacitor.v')

        nose.tools.assert_almost_equal(dataMatrix[0, col],
                                       res.initial('capacitor.v'), 5)
        nose.tools.assert_almost_equal(dataMatrix[-1, col],
                                       res.final('capacitor.v'), 5)

        nose.tools.assert_raises(VariableNotTimeVarying, res.get_column,
                                 'sine.freqHz')
def test_nlp_variable_indices():
    file_path = os.path.join(get_files_path(), 'Modelica', 'TestBackTracking.mop')
    op = transfer_optimization_problem("TestVariableTypes", file_path)

    n_e = 10

    opts = op.optimize_options()
    opts['n_e'] = n_e
    opts['variable_scaling'] = False
    opts['blocking_factors'] = BlockingFactors({'u_bf':[1]*n_e})

    res = op.optimize(options = opts)

    t = res['time']
    solver = res.get_solver()
    check_roundtrip(solver)
    check_solution(solver)
    xx = solver.collocator.primal_opt

    var_names = ['x', 'x2', 'w', 'w2', 'u_cont', 'u_bf', 'p']
    for name in var_names:
        inds, tv, i, k = solver.get_nlp_variable_indices(name)
        tinds = N.searchsorted((t[:-1]+t[1:])/2, tv)
        assert N.max(N.abs(t[tinds] - tv)) < 1e-12
        if name == 'u_bf':
            # workaround for the fact that res uses the left value of u_bf
            # at the discontinuity point, and back tracking uses the right
            tinds += 1
        assert N.max(N.abs(res[name][tinds] - xx[inds])) < 1e-12
Ejemplo n.º 27
0
 def test_compiler_error(self):
     """ Test that a CompilerError is raised if compilation errors are found in the model."""
     path = os.path.join(get_files_path(), 'Modelica',
                         'CorruptCodeGenTests.mo')
     cl = 'CorruptCodeGenTests.CorruptTest1'
     nose.tools.assert_raises(pym.compiler_exceptions.CompilerError,
                              pym.compile_fmu, cl, path)
Ejemplo n.º 28
0
 def test_inlined_switches(self):
     """ Test a model that need in-lined switches to initialize. """
     path = os.path.join(get_files_path(), 'Modelica', 'event_init.mo')
     fmu_name = compile_fmu('Init', path)
     model = load_fmu(fmu_name)
     model.initialize()
     assert N.abs(model.get("x") - (-2.15298995)) < 1e-3
Ejemplo n.º 29
0
 def test_compiler_modification_error(self):
     """ Test that a CompilerError is raised if compilation errors are found in the modification on the classname."""
     path = os.path.join(get_files_path(), 'Modelica', 'Diode.mo')
     err = pym.compiler_exceptions.CompilerError
     nose.tools.assert_raises(err, pym.compile_fmu, 'Diode(wrong_name=2)',
                              path)
     nose.tools.assert_raises(err, pym.compile_fmu, 'Diode(===)', path)
Ejemplo n.º 30
0
    def setup_class_base(cls,
                         mo_file,
                         class_name,
                         options={},
                         format='jmu',
                         target="me"):
        """
        Set up a new test model. Compiles the model. 
        Call this with proper args from setUpClass(). 
          mo_file     - the relative path from the files dir to the .mo file to compile
          class_name  - the qualified name of the class to simulate
          options     - a dict of options to set in the compiler, defaults to no options
          format      - either 'jmu' or 'fmu' depending on which format should be tested
        """
        global _model_name
        cls.mo_path = os.path.join(get_files_path(), 'Modelica', mo_file)

        if format == 'jmu':
            _model_name = compile_jmu(class_name,
                                      cls.mo_path,
                                      compiler_options=options)
        elif format == 'fmu':
            _model_name = compile_fmu(class_name,
                                      cls.mo_path,
                                      compiler_options=options,
                                      target=target)
        else:
            raise Exception("Format must be either 'jmu' or 'fmu'.")
Ejemplo n.º 31
0
 def setUpClass(cls):
     """
     Sets up the test class.
     """
     fpath = os.path.join(get_files_path(), 'Modelica', "DepPar.mo")
     cpath = "DepPar.DepPar1"
     cls.fmu_name = compile_fmu(cpath, fpath, version="1.0")
def test_duals():
    file_path = os.path.join(get_files_path(), 'Modelica', 'TestBackTracking.mop')
    op = transfer_optimization_problem("TestDuals", file_path)

    n_e = 10
    n_cp = 1

    opts = op.optimize_options()
    opts['n_e'] = n_e
    opts['n_cp'] = n_cp

    solver = op.prepare_optimization(options=opts)
    check_roundtrip(solver)
    solver.optimize()
    check_solution(solver)

    h = 1.0/n_e

    # Strange things seem to happen with the first two entries in the duals;
    # skip them in the comparison.
    # Interaction with initial constraints?
    l = solver.get_constraint_duals('path_ineq', tik=False)
    t, i, k = solver.get_constraint_points('path_ineq')
    l0 = t*h
    assert N.max(N.abs((l.ravel()-l0)[2:])) < 1e-12

    l = solver.get_bound_duals('y', tik=False)
    t, i, k = solver.get_variable_points('y')
    l0 = (t-2)*h
    assert N.max(N.abs((l.ravel()-l0)[2:])) < 1e-12
Ejemplo n.º 33
0
    def setup_class_base(cls,
                         mo_file,
                         class_name,
                         options={},
                         target="me",
                         version=None):
        """
        Set up a new test model. Compiles the model. 
        Call this with proper args from setUpClass(). 
          mo_file     - the relative path from the files dir to the .mo file to compile
          class_name  - the qualified name of the class to simulate
          options     - a dict of options to set in the compiler, defaults to no options
        """
        global _model_name
        cls.mo_path = os.path.join(get_files_path(), 'Modelica', mo_file)

        if version == None:
            _model_name = compile_fmu(class_name,
                                      cls.mo_path,
                                      compiler_options=options,
                                      target=target)
        else:
            _model_name = compile_fmu(class_name,
                                      cls.mo_path,
                                      compiler_options=options,
                                      target=target,
                                      version=version)
Ejemplo n.º 34
0
 def setUpClass(cls):
     curr_dir = os.path.dirname(os.path.abspath(__file__));
     mofile = os.path.join(get_files_path(), 'Modelica', 'StaticOptimizationTest.mop')
     compile_jmu("StaticOptimizationTest.StaticOptimizationTest2", mofile)
     cls.model = JMUModel("StaticOptimizationTest_StaticOptimizationTest2.jmu")
     cls.nlp = NLPInitialization(cls.model,stat=1)
     cls.ipopt_nlp = InitializationOptimizer(cls.nlp)
Ejemplo n.º 35
0
 def setUpClass(cls):
     model_file = os.path.join(get_files_path(), 'Modelica',
                               'NegatedAlias.mo')
     name = compile_fmu("NegatedAlias", model_file)
     name = compile_fmu("NegatedAlias",
                        model_file,
                        target="cs",
                        compile_to="NegatedAliasCS.fmu")
     name = compile_fmu("NegatedAlias",
                        model_file,
                        version=2.0,
                        target="cs",
                        compile_to="NegatedAliasCS2.fmu")
     model_file = os.path.join(get_files_path(), 'Modelica',
                               'ParameterAlias.mo')
     name = compile_fmu("ParameterAlias", model_file)
Ejemplo n.º 36
0
def test_realtime_mpc_cg():
    start_values = {'_start_px': 0, '_start_py': 0, '_start_l': 1,
                    '_start_vx': 0, '_start_vy': 0, '_start_der_l': 0,
                    '_start_tx': 0, '_start_ty': 0,
                    '_start_wx': 0, '_start_wy': 0}
    par_changes = ParameterChanges({1: {'lx_ref': 0.5,
                                        'ly_ref': 1.0,
                                        'lz_ref': -0.5}})
    ref = {'px': 0.346932431817,
           'py': 0.694178183248,
           'ul': 0.11764811976,
           'vx': 0.263449683258,
           'vy': 0.520923008414,
           'der_l': 0.237609752809,
           'tx': 0.153826374643,
           'ty': 0.29862921556,
           'wx': 1.20408324142,
           'wy': 2.20145775869,
           'ux': -0.0554289031676,
           'uy': -0.11787736265,
           'ul': 0.117369869311,
           'time': 2.0}
    
    path = os.path.join(get_files_path(), 'Modelica', 'crane.mop')
    mpc = MPCSimBase(path, 'Crane.Crane_MPC', 'Crane.Crane_MPC_Model',
                     0.2, 2, 2, start_values, {},
                     ['px', 'py', 'vx', 'vy', 'l', 'der_l', 'tx', 'ty', 'wx', 'wy'],
                     ['ux', 'uy', 'ul'], None,  par_changes)
    mpc.enable_codegen()
    results, _ = mpc.run()
    check_result(results, ref)
Ejemplo n.º 37
0
    def test_order_input(self):
        """
        This tests that the inputs are sorted in an correct value reference order
        when being written to file.
        """
        fpath = os.path.join(get_files_path(), 'Modelica', 'OrderInputs.mop')
        cpath = 'OptimInputs'

        unames = ['u1', 'u_e2', 'u_h3', 'u_c4', 'u_p5']
        n = len(unames)

        uvalues = [1., 2., 3., 4., 5.]

        data = N.array([[0., 1., 2., 3., 4., 5.], [1., 1., 2., 3., 4., 5.],
                        [2., 1., 2., 3., 4., 5.]])
        inputtuple = (unames, data)
        jmu_name = compile_jmu(cpath, fpath)

        model = JMUModel(jmu_name)
        res = model.simulate(0, 2, input=inputtuple)

        nose.tools.assert_almost_equal(res["u1"][-1], 1.000000000, 3)
        nose.tools.assert_almost_equal(res["u_e2"][-1], 2.00000, 3)
        nose.tools.assert_almost_equal(res["u_h3"][-1], 3.00000, 3)
        nose.tools.assert_almost_equal(res["u_c4"][-1], 4.000000, 3)
        nose.tools.assert_almost_equal(res["u_p5"][-1], 5.000000, 3)

        nose.tools.assert_almost_equal(res["T.u1"][-1], 1.000000000, 3)
        nose.tools.assert_almost_equal(res["T.u_e2"][-1], 2.00000, 3)
        nose.tools.assert_almost_equal(res["T.u_h3"][-1], 3.00000, 3)
        nose.tools.assert_almost_equal(res["T.u_c4"][-1], 4.000000, 3)
        nose.tools.assert_almost_equal(res["T.u_p5"][-1], 5.000000, 3)
Ejemplo n.º 38
0
def test_realtime_mpc_ia():
    start_values = {'_start_h1': 0, '_start_h2': 0,
                    '_start_h3': 0, '_start_h4': 0}
    ref = {'h1': 5.41158639648,
           'h2': 5.14179296558,
           'h3': 7.6831333579,
           'h4': 8.66958129138,
           'u1': 10.0,
           'u2': 10.0,
           'time': 5.0}
    mpc_opts = {'blocking_factors': BlockingFactors(
        {'u1': [1]*30, 'u2': [1]*30}, du_quad_pen = {'u1': 0.1, 'u2': 0.1})}
    
    path = os.path.join(get_files_path(), 'Modelica', 'quadtank.mop')
    mpc = MPCSimBase(path, 'QuadTank.QuadTank_MPC',
                     'QuadTank.QuadTank_MPC_Model', 1, 30, 5, 
                     start_values, {}, ['h1', 'h2', 'h3', 'h4'],
                     ['u1', 'u2'], mpc_options=mpc_opts)
    T = 1
    dt = 1
    mu = math.exp(-float(dt)/T)
    k = mpc.solver.op.get('k')
    A = mpc.solver.op.get('A')
    gamma = mpc.solver.op.get('gamma')
    B = k/A*dt*N.array([[gamma  , 0      ],
                        [0      , gamma  ],
                        [0      , 1-gamma],
                        [1-gamma, 0      ]])
    M = N.linalg.inv(B.T.dot(B)).dot(B.T)
    mpc.enable_integral_action(mu, M, u_e = [1.0, -1.0])
    results, _ = mpc.run()
    check_result(results, ref)
Ejemplo n.º 39
0
 def setUpClass(cls):
     """
     Sets up the test class.
     """
     # modified cstr xml
     modcstr = os.path.join(get_files_path(), 'XML','CSTR_CSTR_Opt_modified.xml')
     cls.md = xmlparser.ModelDescription(modcstr)
Ejemplo n.º 40
0
    def test_scaling_test_2(self):
        """
        This tests a simulation when scaling is ON and there are input variables
        that are not used.
        """
        jmu_name = compile_jmu(
            "Englezos652_with_input",
            os.path.join(get_files_path(), "Modelica", "Englezos652.mop"),
            compiler_options={"enable_variable_scaling": False})

        # Load a model instance into Python
        model = JMUModel(jmu_name)

        # Get and set the options
        opts = model.simulate_options()
        opts['IDA_options']['atol'] = 1.0e-6
        opts['IDA_options']['rtol'] = 1.0e-6
        opts['IDA_options']['sensitivity'] = True
        opts['ncp'] = 400

        res = model.simulate(0, 1697000 / 3, options=opts)

        x1 = res["x1"][-1]
        r1 = res["r1"][-1]
        u1 = res["u1"][-1]

        nose.tools.assert_almost_equal(x1, 0.45537058, 3)
        nose.tools.assert_almost_equal(r1, 5.3287e-8, 2)
        nose.tools.assert_almost_equal(u1, 0.00000, 3)
Ejemplo n.º 41
0
    def setUpClass(cls):
        """
        Sets up the test class.
        """
        fpath = os.path.join(get_files_path(), 'Modelica', 'VDP.mop')
        cpath = "VDP_pack.VDP_Opt_Min_Time"

        compile_jmu(cpath, fpath, compiler_options={'state_start_values_fixed':True})
Ejemplo n.º 42
0
 def test_compiler_error(self):
     """ Test that a CompilerError is raised if compilation errors are found in the model."""
     path = os.path.join(get_files_path(), 'Modelica','CorruptCodeGenTests.mo')
     cl = 'CorruptCodeGenTests.CorruptTest1'
     nose.tools.assert_raises(pym.compiler_exceptions.CompilerError, Test_Compiler.mc.compile_Unit, cl, [path], 'jmu', None, '.')
     nose.tools.assert_raises(pym.compiler_exceptions.CompilerError, Test_Compiler.oc.compile_Unit, cl, [path], 'jmu', None, '.')
     nose.tools.assert_raises(pym.compiler_exceptions.CompilerError, pym.compile_fmu, cl, path, separate_process=True)
     nose.tools.assert_raises(pym.compiler_exceptions.CompilerError, pym.compile_jmu, cl, path, separate_process=True)
Ejemplo n.º 43
0
 def test_ModelicaUtilities(self):
     """ 
     Test compiling a model with external functions using the functions in ModelicaUtilities.
     """
     fpath = path(get_files_path(), 'Modelica', "ExtFunctionTests.mo")
     cpath = "ExtFunctionTests.ExtFunctionTest3"
     jmu_name = compile_fmu(cpath, fpath)
     model = load_fmu(jmu_name)
Ejemplo n.º 44
0
    def setUpClass(cls):
        """Sets up the class."""
        fpath = os.path.join(get_files_path(), 'Modelica', 'CSTR.mop')
        cpath = "CSTR.CSTR_Init"

        compile_jmu(cpath,
                    fpath,
                    compiler_options={'state_start_values_fixed': False})
Ejemplo n.º 45
0
 def test_parameter_alias(self):
     """ Test simulate and write to file when model has parameter alias.
         (Test so that write to file does not crash.)
     """
     model_file = os.path.join(get_files_path(), 'Modelica', 'ParameterAlias.mo')
     compile_jmu('ParameterAlias', model_file)
     model = JMUModel('ParameterAlias.jmu')
     model.simulate()
Ejemplo n.º 46
0
 def test_set_compiler_options(self):
     """ Test compiling with compiler options."""
     libdir = os.path.join(get_files_path(), 'MODELICAPATH_test', 'LibLoc1',
         'LibA')
     co = {"index_reduction":True, "equation_sorting":True,
         "extra_lib_dirs":[libdir]}
     compile_fmu('RLC_Circuit', os.path.join(path_to_mofiles,'RLC_Circuit.mo'),
         compiler_options = co)
Ejemplo n.º 47
0
    def setUpClass(cls):
        """
        Sets up the test class.
        """
        fpath = os.path.join(get_files_path(), 'Modelica', 'CSTR.mop')
        cpath = "CSTR.CSTR_Init_Optimization"

        compile_jmu(cpath, fpath)
Ejemplo n.º 48
0
    def setUpClass(cls):
        """
        Sets up the test class.
        """
        # RLC model
        fpath_rlc = os.path.join(get_files_path(),'Modelica','RLC_Circuit.mo')
        cpath_rlc = "RLC_Circuit"

        cls.jmu_name = compile_jmu(cpath_rlc, fpath_rlc, compiler_options={'state_start_values_fixed':True})
    def setUpClass(cls):
        """
        Compile the test model.
        """
        file_name = os.path.join(get_files_path(), 'Modelica', 'noState.mo')

        _ex1_name = compile_fmu("NoState.Example1", file_name)
        _ex2_name = compile_fmu("NoState.Example2", file_name)
        _cc_name = compile_fmu("Modelica.Mechanics.Rotational.Examples.CoupledClutches")
Ejemplo n.º 50
0
 def setUpClass(cls):
     """
     Compile the test model.
     """
     # compile vdp
     fpath_vdp = os.path.join(get_files_path(), 'Modelica', 'VDP.mop')
     cpath_vdp = "VDP_pack.VDP_Opt_Min_Time"
     compile_jmu(cpath_vdp, fpath_vdp,
         compiler_options={'state_start_values_fixed':True}) 
Ejemplo n.º 51
0
 def setUpClass(cls):
     """
     Sets up the test class.
     """
     # VDP model
     fpath_vdp = os.path.join(get_files_path(),'Modelica','VDP.mop')
     cpath_vdp = "VDP_pack.VDP_Opt"
     
     cls.jmu_name = compile_jmu(cpath_vdp, fpath_vdp)
Ejemplo n.º 52
0
 def setUpClass(cls):
     """
     Compile the test model.
     """
     # compile cstr
     fpath_cstr = os.path.join(get_files_path(), 'Modelica', 'CSTR.mop')
     cpath_cstr = "CSTR.CSTR_Opt"
     compile_jmu(cpath_cstr, fpath_cstr, 
         compiler_options={'state_start_values_fixed':True})
Ejemplo n.º 53
0
 def setUpClass(cls):
     """
     Compile the test model.
     """
     # compile cstr
     fpath_cstr = os.path.join(get_files_path(), 'Modelica', 'CSTR.mop')
     cpath_cstr = "CSTR.CSTR_Init"
     compile_jmu(cpath_cstr, fpath_cstr,
         compiler_options={"enable_variable_scaling":True}) 
Ejemplo n.º 54
0
 def setUp(self):
     """Test setUp. Load the test model."""
     # Load models
     curr_dir = get_files_path()
     self.log_file_name = os.path.join(curr_dir, 'Data', 'test_KINsolver_options_log.txt')
     self.model = load_fmu('BouncingBounds.fmu', log_file_name=self.log_file_name)
     self.model.set_debug_logging(True)
     self.model.set_log_level(5)
     self.model.set('_log_level', 5)
Ejemplo n.º 55
0
 def test_optimize(self):
     """ Test the pyjmi.JMUModel.optimize function using all default parameters. """
     fpath_pend = os.path.join(get_files_path(), 'Modelica', 'Pendulum_pack.mop')
     cpath_pend = "Pendulum_pack.Pendulum_Opt"
     jmu_pend = compile_jmu(cpath_pend, fpath_pend,compiler_options={'state_start_values_fixed':True})
     pend = JMUModel(jmu_pend)
     
     res = pend.optimize()
     
     assert N.abs(res.final('cost') - 1.2921683e-01) < 1e-3
Ejemplo n.º 56
0
 def test_dependent_parameters(self):
     """ Test evaluation of dependent parameters. """
     path = os.path.join(get_files_path(), 'Modelica', 'DepPar.mo')
     jmu_name = compile_jmu('DepPar.DepPar1', path, 
         compiler_options={'state_start_values_fixed':True})
     model = JMUModel(jmu_name)
     
     assert (model.get('p1') == 1.0)
     assert (model.get('p2') == 2.0)
     assert (model.get('p3') == 6.0)
Ejemplo n.º 57
0
    def setUpClass(cls):
        cls.curr_dir = os.path.dirname(os.path.abspath(__file__));
        mofile = os.path.join(get_files_path(), 'Modelica', 
                'BlockingError.mop')

        m = compile_jmu("BlockingInitPack.M_init", mofile)
        cls.model = JMUModel(m)
        
        m = compile_jmu("BlockingInitPack.M_Opt",mofile)
        cls.opt_model = JMUModel(m)
    def setUpClass(cls):
        """
        Compile the test model.
        """
        file_name = os.path.join(get_files_path(), 'Modelica', 'EventIter.mo')

        compile_fmu("EventIter.EventInfiniteIteration1", file_name)
        compile_fmu("EventIter.EventInfiniteIteration2", file_name)
        compile_fmu("EventIter.EventInfiniteIteration3", file_name)
        compile_fmu("EventIter.EnhancedEventIteration1", file_name)
        compile_fmu("EventIter.EnhancedEventIteration2", file_name)
        compile_fmu("EventIter.SingularSystem1", file_name)
 def test_alias_variables(self):
     """
     This tests a simulation when there are alias in the sensitivity parameters.
     """
     #DAE with sens
     file_name = os.path.join(get_files_path(), 'Modelica', 
         'SensitivityTests.mop')
     model_name = 'SensitivityTests.SensTest1'
     
     jmu_name = compile_jmu(model_name, file_name)
     
     model = JMUModel(jmu_name)
     
     opts = model.simulate_options()
     
     opts['IDA_options']['sensitivity'] = True
     
     res = model.simulate(options=opts)
     
     x1 = res['dx1/da']
     #x2 = res['dx2/da']
     x3 = res['dx3/da']
     x4 = res['dx4/da']
     x5 = res['dx5/da']
     
     #nose.tools.assert_almost_equal(x2[-1], 0.000000, 4)
     nose.tools.assert_almost_equal(x3[-1], 1.000000, 4)
     nose.tools.assert_almost_equal(x4[-1], -1.000000,4)
     nose.tools.assert_almost_equal(x1[-1], x5[-1], 4)
     
     #The same test using continuous writing
     
     jmu_name = 'SensitivityTests_SensTest1.jmu'
     
     model = JMUModel(jmu_name)
     
     opts = model.simulate_options()
     
     opts['IDA_options']['sensitivity'] = True
     opts['report_continuously'] = True
     
     res = model.simulate(options=opts)
     
     x1 = res['dx1/da']
     #x2 = res['dx2/da']
     x3 = res['dx3/da']
     x4 = res['dx4/da']
     x5 = res['dx5/da']
     
     #nose.tools.assert_almost_equal(x2[-1], 0.000000, 4)
     nose.tools.assert_almost_equal(x3[-1], 1.000000, 4)
     nose.tools.assert_almost_equal(x4[-1], -1.000000,4)
     nose.tools.assert_almost_equal(x1[-1], x5[-1], 4)