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)
Пример #2
0
class TestIpoptException:
    """
    Check that an exception is thrown if Ipopt returns with return status != 0, 1, 6 (succeeded, acceptable, feasible point found)
    """
    @classmethod
    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}) 
    
    def setUp(self):
        """Test setUp. Load the test model."""   
        cpath_cstr = "CSTR.CSTR_Init"
        fname_cstr = cpath_cstr.replace('.','_',1)
        self.fname_cstr = fname_cstr   
        self.cstr = JMUModel(fname_cstr+'.jmu')

    @testattr(ipopt = True)
    def test_exception_thrown(self):
        """
        Test that an IpoptException is thrown if initialization fails.
        """
        opts = self.cstr.initialize_options()
        opts['IPOPT_options']['max_iter'] = 1
        try:
            self.cstr.initialize(options = opts)
        except IpoptException as e:
            assert str(e) == "Ipopt failed with return code: -1 Please see Ipopt documentation for more information."
        else:
            assert False, "No IpoptException thrown when initialization fails (running VDP with max_iter = 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)
Пример #4
0
class TestParameterAliasVector:
    """Tests IO"""
    @classmethod
    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)
    
    def setUp(self):
        """ 
        Setup test cases.
        """
        # Load the dynamic library and XML data
        self.fname = "CSTR_CSTR_Init_Optimization.jmu"
        self.mod = JMUModel(self.fname)
        
    @testattr(ipopt = True)
    def test_parameter_alias_is_vector(self):
        """
        Test for export and import the result file on Dymola textual format.
        """
        opts = self.mod.simulate_options()
        opts['ncp'] = 30
        res = self.mod.simulate(0,1,options=opts)
        Tc = res['cstr.Tc']
        nose.tools.assert_equal(N.size(Tc),31,"Wrong size of result vector")
Пример #5
0
    def setUp(self):
        """Test setUp. Load the test model."""
        # Load models
        self.model = JMUModel("CSTRLib_Components_Two_CSTRs_stat_init.jmu")
        self.problem = JMUAlgebraic(self.model)
        self.solver = KINSOL(self.problem)
        """
        self.model_test_start = JMUModel(self.invalidStart)
        self.problem_test_start = JMUAlgebraic(self.model_test_start)
        """

        self.model_test_minmax = JMUModel("TestMinMax_TestGuess.jmu")
        self.problem_test_minmax = JMUAlgebraic(self.model_test_minmax)

        # Set inputs for Stationary point A
        u1_0_A = 1
        u2_0_A = 1
        self.model.set('u1', u1_0_A)
        self.model.set('u2', u2_0_A)

        self.dx0 = N.zeros(6)
        self.x0 = N.array([
            200., 3.57359316e-02, 446.471014, 100., 1.79867213e-03, 453.258466
        ])
        self.w0 = N.array([100., 100., -48.1909])
Пример #6
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)
Пример #7
0
 def setUp(self):
     """ 
     Setup test cases.
     """
     # Load the dynamic library and XML data
     self.fname = "CSTR_CSTR_Init_Optimization.jmu"
     self.mod = JMUModel(self.fname)
    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)
Пример #9
0
    def test_scaled_input_continuous(self):
        """
        Tests that simulation of scaled input works for writing continuous.
        """
        # Load the dynamic library and XML data
        self.m_INPUT = JMUModel('DoubleInput_Nominal.jmu')

        t = N.linspace(0., 10., 100)
        u1 = N.cos(t)
        u2 = N.sin(t)
        u_traj = N.transpose(N.vstack((t, u1, u2)))

        opts = self.m_INPUT.simulate_options()
        opts['IDA_options']['atol'] = 1.0e-6
        opts['IDA_options']['rtol'] = 1.0e-6
        opts['IDA_options']['sensitivity'] = True
        #opts['IDA_options']['write_cont'] = True
        opts['ncp'] = 0

        res = self.m_INPUT.simulate(final_time=10,
                                    input=(['u1', 'u2'], u_traj),
                                    options=opts)

        nose.tools.assert_almost_equal(res.initial('u1'), 1.000000000, 3)
        nose.tools.assert_almost_equal(res.initial('u2'), 0.000000000, 3)
        nose.tools.assert_almost_equal(res.final('u1'), -0.839071529, 3)
        nose.tools.assert_almost_equal(res.final('u2'), -0.544021110, 3)
Пример #10
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')
Пример #11
0
class TestParameterAliasVector:
    """Tests IO"""
    @classmethod
    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)

    def setUp(self):
        """ 
        Setup test cases.
        """
        # Load the dynamic library and XML data
        self.fname = "CSTR_CSTR_Init_Optimization.jmu"
        self.mod = JMUModel(self.fname)

    @testattr(ipopt=True)
    def test_parameter_alias_is_vector(self):
        """
        Test for export and import the result file on Dymola textual format.
        """
        opts = self.mod.simulate_options()
        opts['ncp'] = 30
        res = self.mod.simulate(0, 1, options=opts)
        Tc = res['cstr.Tc']
        nose.tools.assert_equal(N.size(Tc), 31, "Wrong size of result vector")
Пример #12
0
class TestIpoptException:
    """
    Check that an exception is thrown if Ipopt returns with return status != 0, 1, 6 (succeeded, acceptable, feasible point found)
    """
    @classmethod
    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}) 
    
    def setUp(self):
        """Test setUp. Load the test model."""   
        cpath_vdp = "VDP_pack.VDP_Opt_Min_Time"
        fname_vdp = cpath_vdp.replace('.','_',1)
        self.fname_vdp = fname_vdp   
        self.vdp = JMUModel(fname_vdp+'.jmu')

    @testattr(ipopt = True)
    def test_exception_thrown(self):
        """
        Test that an IpoptException is thrown if optimization fails.
        """
        opts = self.vdp.optimize_options()
        opts['IPOPT_options']['max_iter'] = 1
        try:
            self.vdp.optimize(options = opts)
        except IpoptException as e:
            assert str(e) == "Ipopt failed with return code: -1 Please see Ipopt documentation for more information."
        else:
            assert False, "No IpoptException thrown when optimizing fails (running VDP with max_iter = 1)."
Пример #13
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)
Пример #14
0
 def test_no_events(self):
     """
     Tests that models containing events cannot be simulated with JMIDAESens.
     """
     self.m_DISC = JMUModel('IfExpExamples_IfExpExample2.jmu')
     opts = self.m_DISC.simulate_options()
     opts["IDA_options"]["sensitivity"] = True
     nose.tools.assert_raises(JMIModel_Exception,self.m_DISC.simulate, 0, 1,None,"AssimuloAlg", opts)
Пример #15
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()
Пример #16
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)
Пример #17
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
Пример #18
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
Пример #19
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)
Пример #20
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)
Пример #21
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)
Пример #22
0
    def test_p0(self):
        """
        This test that the correct number of parameters are found.
        """
        self.m_SENS = JMUModel('QuadTankSens.jmu')
        self.SENS = JMIDAESens(self.m_SENS)

        assert self.SENS._p_nbr == 4
        assert self.SENS._parameter_names[0] == 'a1'
        assert self.SENS._parameter_names[1] == 'a2'
        assert self.SENS._parameter_names[2] == 'a3'
        assert self.SENS._parameter_names[3] == 'a4'
Пример #23
0
    def test_input_simulation(self):
        """
        This tests that input simulation works.
        """
        self.m_SENS = JMUModel('QuadTankSens.jmu')
        self.SENS = JMIDAESens(self.m_SENS)
        
        path_result = os.path.join(get_files_path(), 'Results', 
                                'qt_par_est_data.mat')
        
        data = loadmat(path_result,appendmat=False)

        # Extract data series  
        t_meas = data['t'][6000::100,0]-60  
        u1 = data['u1_d'][6000::100,0]
        u2 = data['u2_d'][6000::100,0]
                
        # Build input trajectory matrix for use in simulation
        u_data = N.transpose(N.vstack((t_meas,u1,u2)))

        u_traj = TrajectoryLinearInterpolation(u_data[:,0], 
                            u_data[:,1:])

        input_object = (['u1','u2'], u_traj)
        
        qt_mod = JMIDAESens(self.m_SENS, input_object)

        qt_sim = IDA(qt_mod)

        #Store data continuous during the simulation, important when solving a 
        #problem with sensitivites.
        qt_sim.report_continuously = True 
            
        #Value used when IDA estimates the tolerances on the parameters
        qt_sim.pbar = qt_mod.p0 
            
        #Let Sundials find consistent initial conditions by use of 'IDA_YA_YDP_INIT'
        qt_sim.make_consistent('IDA_YA_YDP_INIT')
            
        #Simulate
        qt_sim.simulate(60) #Simulate 4 seconds with 400 communication points

        #write_data(qt_sim)

        res = ResultDymolaTextual('QuadTankSens_result.txt')
    
        dx1da1 = res.get_variable_data('dx1/da1')
        dx1da2 = res.get_variable_data('dx1/da2')
        dx4da1 = res.get_variable_data('dx4/da1')
        
        nose.tools.assert_almost_equal(dx1da2.x[0], 0.000000, 4)
        nose.tools.assert_almost_equal(dx1da2.x[-1], 0.00000, 4)
Пример #24
0
    def setUp(self):
        """Load the test model."""
        package_DAE = 'Pendulum_pack_Pendulum.jmu'
        package_DISC = 'IfExpExamples_IfExpExample2.jmu'
        package_INPUT = 'DoubleInput_Nominal.jmu'

        # Load the dynamic library and XML data
        self.m_DAE = JMUModel(package_DAE)
        self.m_DISC = JMUModel(package_DISC)
        self.m_INPUT = JMUModel(package_INPUT)

        # Creates the solvers
        self.DAE = JMIDAE(self.m_DAE)
        self.DISC = JMIDAE(self.m_DISC)
Пример #25
0
    def setUp(self):
        """Test setUp. Load the test model."""
        # Load the dynamic library and XML data
        cpath_daeinit = "DAEInitTest"
        fname_daeinit = cpath_daeinit.replace('.', '_', 1)
        self.dae_init_test = JMUModel(fname_daeinit + '.jmu')

        # This is to check that values set in the model prior to
        # creation of the NLPInitialization object are used as an
        # initial guess.
        self.dae_init_test.set('y1', 0.3)

        self.init_nlp = NLPInitialization(self.dae_init_test)
        self.init_nlp_ipopt = InitializationOptimizer(self.init_nlp)
    def setUp(self):
        """Load the test model."""
        package_DAE = 'Pendulum_pack_Pendulum.jmu'
        package_DISC = 'IfExpExamples_IfExpExample2.jmu'
        package_INPUT = 'DoubleInput_Nominal.jmu'

        # Load the dynamic library and XML data
        self.m_DAE = JMUModel(package_DAE)
        self.m_DISC = JMUModel(package_DISC)
        self.m_INPUT = JMUModel(package_INPUT)
        
        # Creates the solvers
        self.DAE = JMIDAE(self.m_DAE)
        self.DISC = JMIDAE(self.m_DISC)
Пример #27
0
 def setUp(self):
     """ 
     Setup test cases.
     """
     # Load the dynamic library and XML data
     self.fname = "VDP_pack_VDP_Opt_Min_Time.jmu"
     self.vdp = JMUModel(self.fname)
    def test_scaled_input_continuous(self):
        """
        Tests that simulation of scaled input works for writing continuous.
        """
        # Load the dynamic library and XML data
        self.m_INPUT = JMUModel('DoubleInput_Nominal.jmu')

        t = N.linspace(0.,10.,100) 
        u1 = N.cos(t)
        u2 = N.sin(t)
        u_traj = N.transpose(N.vstack((t,u1,u2)))
        
        opts = self.m_INPUT.simulate_options()
        opts['IDA_options']['atol'] = 1.0e-6
        opts['IDA_options']['rtol'] = 1.0e-6
        opts['IDA_options']['sensitivity'] = True
        #opts['IDA_options']['write_cont'] = True
        opts['ncp'] = 0
        
        res = self.m_INPUT.simulate(final_time=10, input=(['u1','u2'],u_traj),
                                    options=opts)
        
        nose.tools.assert_almost_equal(res.initial('u1'), 1.000000000, 3)
        nose.tools.assert_almost_equal(res.initial('u2'), 0.000000000, 3)
        nose.tools.assert_almost_equal(res.final('u1'), -0.839071529, 3)
        nose.tools.assert_almost_equal(res.final('u2'), -0.544021110, 3)
Пример #29
0
 def setUp(self):
     """Test setUp. Load the test model."""
     # Load models
     self.model = JMUModel("CSTRLib_Components_Two_CSTRs_stat_init.jmu")
     self.problem = JMUAlgebraic(self.model)
     self.solver = KINSOL(self.problem)
     
     """
     self.model_test_start = JMUModel(self.invalidStart)
     self.problem_test_start = JMUAlgebraic(self.model_test_start)
     """
     
     self.model_test_minmax = JMUModel("TestMinMax_TestGuess.jmu")
     self.problem_test_minmax = JMUAlgebraic(self.model_test_minmax)
     
     
     # Set inputs for Stationary point A
     u1_0_A = 1
     u2_0_A = 1
     self.model.set('u1',u1_0_A)
     self.model.set('u2',u2_0_A)
     
     self.dx0 = N.zeros(6)
     self.x0 = N.array([200., 3.57359316e-02, 446.471014, 100., 1.79867213e-03,453.258466])
     self.w0 = N.array([100., 100., -48.1909])
Пример #30
0
    def test_time_shift(self):
        """
        Test the time shift feature
        """
        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()

        time_shifted_fix = res['time'] + 11.

        res.result_data.shift_time(11.)

        time_shifted = res['time']

        assert max(N.abs(time_shifted_fix - time_shifted)) < 1e-6
Пример #31
0
 def setUp(self):
     """ 
     Setup test cases.
     """
     # Load the dynamic library and XML data
     self.fname = "CSTR_CSTR_Init_Optimization.jmu"
     self.mod = JMUModel(self.fname)
Пример #32
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_no_events(self):
     """
     Tests that models containing events cannot be simulated with JMIDAESens.
     """
     self.m_DISC = JMUModel('IfExpExamples_IfExpExample2.jmu')
     opts = self.m_DISC.simulate_options()
     opts["IDA_options"]["sensitivity"] = True
     nose.tools.assert_raises(JMIModel_Exception,self.m_DISC.simulate, 0, 1,None,"AssimuloAlg", opts)
Пример #34
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)
Пример #35
0
    def test_initialize_with_solverargs(self):
        """ Test the pyjmi.JMUModel.initialize function using all default parameters. """
        fpath_pend = os.path.join(get_files_path(), 'Modelica', 'Pendulum_pack.mop')
        cpath_pend = "Pendulum_pack.Pendulum"
        
        jmu_pend = compile_jmu(cpath_pend, fpath_pend)
        pend = JMUModel(jmu_pend)
        
        res = pend.initialize(options={'IPOPT_options':{'max_iter':1000}})

        assert N.abs(res.final('theta') - 0.1)              < 1e-3
        assert N.abs(res.final('dtheta') - 0.)              < 1e-3
        assert N.abs(res.final('x') - 0)                    < 1e-3
        assert N.abs(res.final('dx') - 0)                   < 1e-3
        assert N.abs(res.final('der(theta)') - 0)           < 1e-3
        assert N.abs(res.final('der(dtheta)') - 0.09983341) < 1e-3
        assert N.abs(res.final('der(x)') - 0)               < 1e-3
        assert N.abs(res.final('der(dx)') - 0)              < 1e-3
Пример #36
0
    def test_jac(self):
        """
        This tests the jacobian for simulation of sensitivites.
        """
        # Load the dynamic library and XML data
        self.m_SENS = JMUModel('QuadTankSens.jmu')

        model = self.m_SENS

        opts = model.simulate_options()
        opts['IDA_options']['sensitivity'] = True

        res = model.simulate(final_time=10, options=opts)

        prob = res.solver.problem

        assert res.solver.usejac == True
        assert prob.j == prob.jac
Пример #37
0
    def test_initialize_with_solverargs(self):
        """ Test the pyjmi.JMUModel.initialize function using all default parameters. """
        fpath_pend = os.path.join(get_files_path(), 'Modelica', 'Pendulum_pack.mop')
        cpath_pend = "Pendulum_pack.Pendulum"
        
        jmu_pend = compile_jmu(cpath_pend, fpath_pend)
        pend = JMUModel(jmu_pend)
        
        res = pend.initialize(options={'IPOPT_options':{'max_iter':1000}})

        assert N.abs(res.final('theta') - 0.1)              < 1e-3
        assert N.abs(res.final('dtheta') - 0.)              < 1e-3
        assert N.abs(res.final('x') - 0)                    < 1e-3
        assert N.abs(res.final('dx') - 0)                   < 1e-3
        assert N.abs(res.final('der(theta)') - 0)           < 1e-3
        assert N.abs(res.final('der(dtheta)') - 0.09983341) < 1e-3
        assert N.abs(res.final('der(x)') - 0)               < 1e-3
        assert N.abs(res.final('der(dx)') - 0)              < 1e-3
Пример #38
0
 def test_simulate_initialize_arg(self):
     """ Test pyjmi.JMUModel.simulate alg_arg 'initialize'. """
     # This test is built on that simulation without initialization fails.
     # Since simulation without initialization fails far down in Sundials
     # no "proper" exception is thrown which means that I can only test that
     # the general Exception is returned which means that the test is pretty
     # unspecific (the test will pass for every type of error thrown). Therefore,
     # I first test that running the simulation with default settings succeeds, so
     # at least one knows that the error has with initialization to do.
     name = compile_jmu(self.cpath_minit, self.fpath_minit)
     model = JMUModel(name)
     
     nose.tools.ok_(model.simulate())
     
     model = JMUModel(name)
     
     nose.tools.assert_raises(Exception,
                              model.simulate,
                              options={'initialize':False})
Пример #39
0
    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)
Пример #40
0
 def test_simulate_initialize_arg(self):
     """ Test pyjmi.JMUModel.simulate alg_arg 'initialize'. """
     # This test is built on that simulation without initialization fails.
     # Since simulation without initialization fails far down in Sundials
     # no "proper" exception is thrown which means that I can only test that
     # the general Exception is returned which means that the test is pretty
     # unspecific (the test will pass for every type of error thrown). Therefore,
     # I first test that running the simulation with default settings succeeds, so
     # at least one knows that the error has with initialization to do.
     name = compile_jmu(self.cpath_minit, self.fpath_minit)
     model = JMUModel(name)
     
     nose.tools.ok_(model.simulate())
     
     model = JMUModel(name)
     
     nose.tools.assert_raises(Exception,
                              model.simulate,
                              options={'initialize':False})
    def test_double_input(self):
        """
        This tests double input.
        """
        fpath = os.path.join(get_files_path(), 'Modelica', 'DoubleInput.mo')
        cpath = 'DoubleInput'

        # compile VDP
        fname = compile_jmu(cpath, fpath, 
                    compiler_options={'state_start_values_fixed':True})

        # Load the dynamic library and XML data
        dInput = JMUModel(fname)
        
        t = N.linspace(0.,10.,100) 
        u1 = N.cos(t)
        u2 = N.sin(t)
        u_traj = N.transpose(N.vstack((t,u1,u2)))
        
        res = dInput.simulate(final_time=10, input=(['u1','u2'],u_traj))
        
        nose.tools.assert_almost_equal(res.initial('u1'), 1.000000000, 3)
        nose.tools.assert_almost_equal(res.initial('u2'), 0.000000000, 3)
        nose.tools.assert_almost_equal(res.final('u1'), -0.839071529, 3)
        nose.tools.assert_almost_equal(res.final('u2'), -0.544021110, 3)
        
        #TEST REVERSE ORDER OF INPUT
        
        # Load the dynamic library and XML data
        dInput = JMUModel(fname)
        
        t = N.linspace(0.,10.,100) 
        u1 = N.cos(t)
        u2 = N.sin(t)
        u_traj = N.transpose(N.vstack((t,u2,u1)))
        
        res = dInput.simulate(final_time=10, input=(['u2','u1'],u_traj))
        
        nose.tools.assert_almost_equal(res.initial('u1'), 1.000000000, 3)
        nose.tools.assert_almost_equal(res.initial('u2'), 0.000000000, 3)
        nose.tools.assert_almost_equal(res.final('u1'), -0.839071529, 3)
        nose.tools.assert_almost_equal(res.final('u2'), -0.544021110, 3)
Пример #42
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)
Пример #43
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')
Пример #44
0
    def setUp(self):
        """Test setUp. Load the test model."""

        self.cstr = JMUModel("CSTR_CSTR_Opt.jmu")
        # Initialize the mesh
        n_e = 150 # Number of elements 
        hs = N.ones(n_e)*1./n_e # Equidistant points
        n_cp = 3; # Number of collocation points in each element
        
        # Create an NLP object
        self.nlp = ipopt.NLPCollocationLagrangePolynomials(
            self.cstr,n_e,hs,n_cp)
 def test_p0(self):
     """
     This test that the correct number of parameters are found.
     """
     self.m_SENS = JMUModel('QuadTankSens.jmu')
     self.SENS = JMIDAESens(self.m_SENS)
     
     assert self.SENS._p_nbr == 4
     assert self.SENS._parameter_names[0] == 'a1'
     assert self.SENS._parameter_names[1] == 'a2'
     assert self.SENS._parameter_names[2] == 'a3'
     assert self.SENS._parameter_names[3] == 'a4'
Пример #46
0
 def test_result(self):
     """ Test simulate and write to file when model has parameter alias.
         Also tests the methods is_variable and get_column in io.ResultDymolaTextual.
     """
     model_file = os.path.join(get_files_path(), 'Modelica', 'ParameterAlias.mo')
     compile_jmu('ParameterAlias', model_file)
     model = JMUModel('ParameterAlias.jmu')
     res = model.simulate()
     
     assert not res.is_variable('p2')
     assert not res.is_variable('x')
     assert not res.is_variable('p1')
     assert res.is_variable('der(y)')
     assert res.is_variable('y')
     
     assert res.get_column('der(y)') == 1
     assert res.get_column('y') == 2
     assert res.get_column('time') == 0
     
     assert res.is_negated('der(y)') == False
     assert res.is_negated('y') == False
    def test_input_simulation(self):
        """
        This tests that input simulation works.
        """
        self.m_SENS = JMUModel('QuadTankSens.jmu')
        self.SENS = JMIDAESens(self.m_SENS)
        
        path_result = os.path.join(get_files_path(), 'Results', 
                                'qt_par_est_data.mat')
        
        data = loadmat(path_result,appendmat=False)

        # Extract data series  
        t_meas = data['t'][6000::100,0]-60  
        u1 = data['u1_d'][6000::100,0]
        u2 = data['u2_d'][6000::100,0]
                
        # Build input trajectory matrix for use in simulation
        u_data = N.transpose(N.vstack((t_meas,u1,u2)))

        u_traj = TrajectoryLinearInterpolation(u_data[:,0], 
                            u_data[:,1:])

        input_object = (['u1','u2'], u_traj)
        
        qt_mod = JMIDAESens(self.m_SENS, input_object)

        qt_sim = IDA(qt_mod)

        #Store data continuous during the simulation, important when solving a 
        #problem with sensitivites.
        qt_sim.report_continuously = True 
            
        #Value used when IDA estimates the tolerances on the parameters
        qt_sim.pbar = qt_mod.p0 
            
        #Let Sundials find consistent initial conditions by use of 'IDA_YA_YDP_INIT'
        qt_sim.make_consistent('IDA_YA_YDP_INIT')
            
        #Simulate
        qt_sim.simulate(60) #Simulate 4 seconds with 400 communication points

        #write_data(qt_sim)

        res = ResultDymolaTextual('QuadTankSens_result.txt')
    
        dx1da1 = res.get_variable_data('dx1/da1')
        dx1da2 = res.get_variable_data('dx1/da2')
        dx4da1 = res.get_variable_data('dx4/da1')
        
        nose.tools.assert_almost_equal(dx1da2.x[0], 0.000000, 4)
        nose.tools.assert_almost_equal(dx1da2.x[-1], 0.00000, 4)
Пример #48
0
    def test_input_simulation_high_level(self):
        """
        This tests that input simulation works using high-level methods.
        """
        # Load the dynamic library and XML data
        self.m_SENS = JMUModel('QuadTankSens.jmu')

        model = self.m_SENS
        path_result = os.path.join(get_files_path(), 'Results',
                                   'qt_par_est_data.mat')

        data = loadmat(path_result, appendmat=False)

        # Extract data series
        t_meas = data['t'][6000::100, 0] - 60
        u1 = data['u1_d'][6000::100, 0]
        u2 = data['u2_d'][6000::100, 0]

        # Build input trajectory matrix for use in simulation
        u_data = N.transpose(N.vstack((t_meas, u1, u2)))

        input_object = (['u1', 'u2'], u_data)

        opts = model.simulate_options()
        opts['IDA_options']['sensitivity'] = True

        ##Store data continuous during the simulation, important when solving a
        ##problem with sensitivites. FIXED INTERNALLY
        opts['report_continuously'] = True

        res = model.simulate(final_time=60, input=input_object, options=opts)

        #Value used when IDA estimates the tolerances on the parameters
        #qt_sim.pbar = qt_mod.p0

        nose.tools.assert_almost_equal(res.initial('dx1/da2'), 0.000000, 4)
        nose.tools.assert_almost_equal(res.final('dx1/da2'), 0.00000, 4)
        nose.tools.assert_almost_equal(res.final("u1"), u1[-1], 4)
        nose.tools.assert_almost_equal(res.final("u2"), u2[-1], 4)
Пример #49
0
    def test_ordinary_dae(self):
        """
        This tests a simulation using JMIDAESens without any parameters.
        """
        self.m_DAE = JMUModel('Pendulum_pack_Pendulum.jmu')
        self.DAE = JMIDAESens(self.m_DAE)

        sim = IDA(self.DAE)

        sim.simulate(1.0)

        nose.tools.assert_almost_equal(sim.y_sol[-1][0], 0.15420124, 4)
        nose.tools.assert_almost_equal(sim.y_sol[-1][1], 0.11721253, 4)
    def test_double_input_with_function(self):
        """
        This tests double input with function.
        """
        fpath = os.path.join(get_files_path(), 'Modelica', 'DoubleInput.mo')
        cpath = 'DoubleInput'

        # compile VDP
        fname = compile_jmu(cpath, fpath, 
                    compiler_options={'state_start_values_fixed':True})

        # Load the dynamic library and XML data
        dInput = JMUModel(fname)

        def func(t):
            return N.array([N.cos(t),N.sin(t)])
        
        res = dInput.simulate(final_time=10, input=(['u1','u2'],func))

        nose.tools.assert_almost_equal(res.initial('u1'), 1.000000000, 3)
        nose.tools.assert_almost_equal(res.initial('u2'), 0.000000000, 3)
        nose.tools.assert_almost_equal(res.final('u1'), -0.839071529, 3)
        nose.tools.assert_almost_equal(res.final('u2'), -0.544021110, 3)
        
        #TEST REVERSE ORDER OF INPUT
        
        # Load the dynamic library and XML data
        dInput = JMUModel(fname)

        def func(t):
            return [N.sin(t),N.cos(t)]
        
        res = dInput.simulate(final_time=10, input=(['u2','u1'],func))

        nose.tools.assert_almost_equal(res.initial('u1'), 1.000000000, 3)
        nose.tools.assert_almost_equal(res.initial('u2'), 0.000000000, 3)
        nose.tools.assert_almost_equal(res.final('u1'), -0.839071529, 3)
        nose.tools.assert_almost_equal(res.final('u2'), -0.544021110, 3)
Пример #51
0
    def setUp(self):
        """Test setUp. Load the test model."""                    
        # Load the dynamic library and XML data
        cpath_daeinit = "DAEInitTest"
        fname_daeinit = cpath_daeinit.replace('.','_',1)
        self.dae_init_test = JMUModel(fname_daeinit+'.jmu')

        # This is to check that values set in the model prior to
        # creation of the NLPInitialization object are used as an
        # initial guess.
        self.dae_init_test.set('y1',0.3)
    
        self.init_nlp = NLPInitialization(self.dae_init_test)
        self.init_nlp_ipopt = InitializationOptimizer(self.init_nlp)
 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)
 def test_jac(self):
     """
     This tests the jacobian for simulation of sensitivites.
     """
     # Load the dynamic library and XML data
     self.m_SENS = JMUModel('QuadTankSens.jmu')
     
     model = self.m_SENS
     
     opts = model.simulate_options()
     opts['IDA_options']['sensitivity'] = True
     
     res = model.simulate(final_time=10, options=opts)
     
     prob = res.solver.problem
     
     assert res.solver.usejac == True
     assert prob.j == prob.jac
    def test_input_simulation_high_level(self):
        """
        This tests that input simulation works using high-level methods.
        """
        # Load the dynamic library and XML data
        self.m_SENS = JMUModel('QuadTankSens.jmu')
        
        model = self.m_SENS
        path_result = os.path.join(get_files_path(), 'Results', 
                                'qt_par_est_data.mat')
        
        data = loadmat(path_result,appendmat=False)

        # Extract data series  
        t_meas = data['t'][6000::100,0]-60  
        u1 = data['u1_d'][6000::100,0]
        u2 = data['u2_d'][6000::100,0]
                
        # Build input trajectory matrix for use in simulation
        u_data = N.transpose(N.vstack((t_meas,u1,u2)))

        input_object = (['u1','u2'], u_data)
        
        opts = model.simulate_options()
        opts['IDA_options']['sensitivity']=True
        
        ##Store data continuous during the simulation, important when solving a 
        ##problem with sensitivites. FIXED INTERNALLY
        opts['report_continuously']=True
        
        res = model.simulate(final_time=60, input=input_object, options=opts)

        #Value used when IDA estimates the tolerances on the parameters
        #qt_sim.pbar = qt_mod.p0 

        nose.tools.assert_almost_equal(res.initial('dx1/da2'), 0.000000, 4)
        nose.tools.assert_almost_equal(res.final('dx1/da2'), 0.00000, 4)
        nose.tools.assert_almost_equal(res.final("u1"), u1[-1], 4)
        nose.tools.assert_almost_equal(res.final("u2"), u2[-1], 4)
    def test_result_name_file(self):
        """
        Tests user naming of result file (JMIDAESens).
        """
        self.m_SENS = JMUModel('QuadTankSens.jmu')
        
        path_result = os.path.join(get_files_path(), 'Results', 
                                'qt_par_est_data.mat')
        
        data = loadmat(path_result,appendmat=False)

        # Extract data series  
        t_meas = data['t'][6000::100,0]-60  
        u1 = data['u1_d'][6000::100,0]
        u2 = data['u2_d'][6000::100,0]
                
        # Build input trajectory matrix for use in simulation
        u_data = N.transpose(N.vstack((t_meas,u1,u2)))

        input_object = (['u1','u2'], u_data)
        
        opts = self.m_SENS.simulate_options()
        opts['IDA_options']['sensitivity']=True
        
        res = self.m_SENS.simulate(options=opts)
        
        #Default name
        assert res.result_file == "QuadTankSens_result.txt"
        assert os.path.exists(res.result_file)
        
        self.m_SENS.reset()
        
        opts["result_file_name"] = "QuadTankSens_result_test.txt"
        
        res = self.m_SENS.simulate(options=opts)
                                    
        #User defined name
        assert res.result_file == "QuadTankSens_result_test.txt"
        assert os.path.exists(res.result_file)
Пример #56
0
class Test_init_ipopt:
    """ Class which contains ipopt tests for the init module. """
    
    @classmethod
    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)
        
    def setUp(self):
        """
        Sets up the test case.
        """
        self.model_vdp = JMUModel(Test_init_ipopt.jmu_name)

    @testattr(ipopt = True)
    def test_initialize(self):
        """ Test the pyjmi.JMUModel.initialize function using all default parameters. """
        fpath_pend = os.path.join(get_files_path(), 'Modelica', 'Pendulum_pack.mop')
        cpath_pend = "Pendulum_pack.Pendulum"
        
        jmu_pend = compile_jmu(cpath_pend, fpath_pend)
        pend = JMUModel(jmu_pend)
        
        res = pend.initialize()

        assert N.abs(res.final('theta') - 0.1)              < 1e-3
        assert N.abs(res.final('dtheta') - 0.)              < 1e-3
        assert N.abs(res.final('x') - 0)                    < 1e-3
        assert N.abs(res.final('dx') - 0)                   < 1e-3
        assert N.abs(res.final('der(theta)') - 0)           < 1e-3
        assert N.abs(res.final('der(dtheta)') - 0.09983341) < 1e-3
        assert N.abs(res.final('der(x)') - 0)               < 1e-3
        assert N.abs(res.final('der(dx)') - 0)              < 1e-3
        
    @testattr(ipopt = True)
    def test_initialize_with_solverargs(self):
        """ Test the pyjmi.JMUModel.initialize function using all default parameters. """
        fpath_pend = os.path.join(get_files_path(), 'Modelica', 'Pendulum_pack.mop')
        cpath_pend = "Pendulum_pack.Pendulum"
        
        jmu_pend = compile_jmu(cpath_pend, fpath_pend)
        pend = JMUModel(jmu_pend)
        
        res = pend.initialize(options={'IPOPT_options':{'max_iter':1000}})

        assert N.abs(res.final('theta') - 0.1)              < 1e-3
        assert N.abs(res.final('dtheta') - 0.)              < 1e-3
        assert N.abs(res.final('x') - 0)                    < 1e-3
        assert N.abs(res.final('dx') - 0)                   < 1e-3
        assert N.abs(res.final('der(theta)') - 0)           < 1e-3
        assert N.abs(res.final('der(dtheta)') - 0.09983341) < 1e-3
        assert N.abs(res.final('der(x)') - 0)               < 1e-3
        assert N.abs(res.final('der(dx)') - 0)              < 1e-3

    @testattr(ipopt = True)
    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
   

    @testattr(ipopt = True)
    def test_optimize_set_n_cp(self):
        """ Test the pyjmi.JMUModel.optimize function and setting n_cp in alg_args.
        """
        res = self.model_vdp.optimize(options={'n_cp':10})
        
        assert N.abs(res.final('cost') - 2.34602647e+01 ) < 1e-3
            
    @testattr(ipopt = True)
    def test_optimize_set_args(self):
        """Test the pyjmi.JMUModel.optimize function and setting some 
        algorithm and solver args.
        """
        res_file_name = 'test_optimize_set_result_mesh.txt'
        res = self.model_vdp.optimize(
            options={'result_mesh':'element_interpolation', 
                     'result_file_name':res_file_name,
                     'IPOPT_options':{'max_iter':100}})
        
        assert N.abs(res.final('cost') - 2.3469089e+01) < 1e-3


    @testattr(ipopt = True)
    def test_optimize_invalid_options(self):
        """ Test that the pyjmi.JMUModel.optimize function raises exception 
        for an invalid algorithm option.
        """
        nose.tools.assert_raises(UnrecognizedOptionError,
                                 self.model_vdp.optimize,
                                 options={'ne':10})