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)
Пример #2
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)
Пример #3
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")
Пример #4
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)
Пример #5
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)
Пример #6
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")
    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_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)
Пример #9
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)
        
        opts = model.simulate_options()
        
        opts["IDA_options"]["sensitivity"] = True
        #opts["continuous_output"] = True #Should not be necessary
        
        res = model.simulate(0,2,input=inputtuple, options=opts)
        
        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)
    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)
        
        opts = model.simulate_options()
        
        opts["IDA_options"]["sensitivity"] = True
        #opts["continuous_output"] = True #Should not be necessary
        
        res = model.simulate(0,2,input=inputtuple, options=opts)
        
        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)
Пример #11
0
class Test_JMI_DAE_Sens:
    """
    This class tests pyjmi.simulation.assimulo.JMIDAESens
    """
    @classmethod
    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})

    def setUp(self):
        """Load the test model."""
        package_DAE = 'Pendulum_pack_Pendulum.jmu'
        package_SENS = 'QuadTankSens.jmu'
        package_DISC = 'IfExpExamples_IfExpExample2.jmu'
        package_INPUT = 'DoubleInput_Nominal.jmu'

        # Load the dynamic library and XML data
        #self.m_DAE = JMUModel('Pendulum_pack_Pendulum.jmu')
        #self.m_SENS = JMUModel('QuadTankSens.jmu')
        #self.m_DISC = JMUModel('IfExpExamples_IfExpExample2.jmu')
        #self.m_INPUT = JMUModel('DoubleInput_Nominal.jmu')

        # Creates the solvers
        #self.DAE = JMIDAESens(self.m_DAE)
        #self.SENS = JMIDAESens(self.m_SENS)

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

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

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

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

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

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

        opts = model.simulate_options()

        opts["IDA_options"]["sensitivity"] = True
        #opts["continuous_output"] = True #Should not be necessary

        res = model.simulate(0, 2, input=inputtuple, options=opts)

        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)

    @testattr(stddist=True)
    def test_input_simulation_high_level_switched_input(self):
        """
        This tests that input simulation works when using high-level methods
        and the inputs are not in JModelica order.
        """
        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, u2, u1)))

        input_object = (['u2', 'u1'], 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)

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

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

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

    @testattr(stddist=True)
    def test_scaled_input(self):
        """
        Tests that simulation of scaled input works.
        """
        # 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['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)

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

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

    @testattr(stddist=True)
    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)
Пример #12
0
class Test_init_assimulo:
    """ Class which contains assimulo tests for the init module. """
    
    @classmethod
    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 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)

    @testattr(assimulo = True)
    def test_simulate(self):
        """ Test the pyjmi.JMUModel.simulate function using all default parameters."""
        sim_res = self.model_rlc.simulate()
        
        assert N.abs(sim_res.final('resistor.v') - 0.138037041741) < 1e-3
        
    @testattr(assimulo = True)
    def test_simulate_set_argument(self):
        """ Test the pyjmi.JMUModel.simulate function and setting an 
        algorithm argument.
        """
        sim_res = self.model_rlc.simulate(final_time=30.0)
        
        assert N.abs(sim_res.final('resistor.v') - 0.159255008028) < 1e-3
        
    @testattr(assimulo = True)
    def test_simulate_set_probl_arg(self):
        """ Test that it is possible to set properties in assimulo and 
        that an exception is raised if the argument is invalid. 
        """
        opts = self.model_rlc.simulate_options()
        opts['IDA_options']['max_eIter']=100 
        opts['IDA_options']['maxh']=0.1
        sim_res = self.model_rlc.simulate(options = opts)
        
        opts = sim_res.options
        opts['IDA_options']['maxeter']=10
        nose.tools.assert_raises(InvalidSolverArgumentException,
                                 self.model_rlc.simulate,options=opts)
        
    @testattr(assimulo = True)
    def test_simulate_invalid_solver_arg(self):
        """ Test that the pyjmi.JMUModel.simulate function raises an exception for an 
            invalid solver argument.
        """
        opts = self.model_rlc.simulate_options()
        opts['IDA_options']['mxiter']=10
        nose.tools.assert_raises(InvalidSolverArgumentException,
                                 self.model_rlc.simulate, options=opts)

    @testattr(assimulo = True)
    def test_simulate_invalid_solver(self):
        """ Test that the pyjmi.JMUModel.optimize function raises exception 
        for an invalid solver.
        """
        opts = self.model_rlc.simulate_options()
        opts['solver']='IDAR'
        nose.tools.assert_raises(InvalidAlgorithmOptionException,
                                 self.model_rlc.simulate,options=opts)
    
    ### TEST IS OBSOLETE, JMUMODELS NO LONGERS SUPPORTS ODES
    #  
    #@testattr(assimulo=True)
    #def test_simulate_w_ode(self):
    #    """ Test jmodelica.simulate with ODE problem and setting solver 
    #    options."""
    #    jmu_name = compile_jmu(self.cpath_vdp, self.fpath_vdp, 
    #        compiler_options={'state_start_values_fixed':True},target='model')
    #    model = JMUModel(jmu_name)
    #    opts = model.simulate_options()
    #    opts['solver']='CVode'
    #    sim_res = model.simulate(final_time=20, options=opts)
    #    x1=sim_res['x1']
    #    x2=sim_res['x2']
    #    
    #    assert N.abs(x1[-1] + 0.736680243) < 1e-5
    #    assert N.abs(x2[-1] - 1.57833994) < 1e-5
    
    @testattr(assimulo=True)
    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})
Пример #13
0
class Test_init_assimulo:
    """ Class which contains assimulo tests for the init module. """
    
    @classmethod
    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 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)

    @testattr(stddist = True)
    def test_simulate(self):
        """ Test the pyjmi.JMUModel.simulate function using all default parameters."""
        sim_res = self.model_rlc.simulate()
        
        assert N.abs(sim_res.final('resistor.v') - 0.138037041741) < 1e-3
        
    @testattr(stddist = True)
    def test_simulate_set_argument(self):
        """ Test the pyjmi.JMUModel.simulate function and setting an 
        algorithm argument.
        """
        sim_res = self.model_rlc.simulate(final_time=30.0)
        
        assert N.abs(sim_res.final('resistor.v') - 0.159255008028) < 1e-3
        
    @testattr(stddist = True)
    def test_simulate_set_probl_arg(self):
        """ Test that it is possible to set properties in Assimulo and 
        that an exception is raised if the argument is invalid. 
        """
        opts = self.model_rlc.simulate_options()
        opts['IDA_options']['max_eIter']=100 
        opts['IDA_options']['maxh']=0.1
        sim_res = self.model_rlc.simulate(options = opts)
        
        opts = sim_res.options
        opts['IDA_options']['maxeter']=10
        nose.tools.assert_raises(InvalidSolverArgumentException,
                                 self.model_rlc.simulate,options=opts)
        
    @testattr(stddist = True)
    def test_simulate_invalid_solver_arg(self):
        """ Test that the pyjmi.JMUModel.simulate function raises an exception for an 
            invalid solver argument.
        """
        opts = self.model_rlc.simulate_options()
        opts['IDA_options']['mxiter']=10
        nose.tools.assert_raises(InvalidSolverArgumentException,
                                 self.model_rlc.simulate, options=opts)

    @testattr(stddist = True)
    def test_simulate_invalid_solver(self):
        """ Test that the pyjmi.JMUModel.optimize function raises exception 
        for an invalid solver.
        """
        opts = self.model_rlc.simulate_options()
        opts['solver']='IDAR'
        nose.tools.assert_raises(InvalidAlgorithmOptionException,
                                 self.model_rlc.simulate,options=opts)
    
    @testattr(stddist=True)
    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})
class Test_JMI_DAE_Sens:
    """
    This class tests pyjmi.simulation.assimulo.JMIDAESens
    """
    
    @classmethod
    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})
        
    def setUp(self):
        """Load the test model."""
        package_DAE = 'Pendulum_pack_Pendulum.jmu'
        package_SENS = 'QuadTankSens.jmu'
        package_DISC = 'IfExpExamples_IfExpExample2.jmu'
        package_INPUT = 'DoubleInput_Nominal.jmu'

        # Load the dynamic library and XML data
        #self.m_DAE = JMUModel('Pendulum_pack_Pendulum.jmu')
        #self.m_SENS = JMUModel('QuadTankSens.jmu')
        #self.m_DISC = JMUModel('IfExpExamples_IfExpExample2.jmu')
        #self.m_INPUT = JMUModel('DoubleInput_Nominal.jmu')

        # Creates the solvers
        #self.DAE = JMIDAESens(self.m_DAE)
        #self.SENS = JMIDAESens(self.m_SENS)
    
    @testattr(stddist = True)
    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)
    
    @testattr(stddist = True)
    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)
    
    @testattr(stddist = True)
    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)
    
    @testattr(stddist = True)
    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'
        
    @testattr(stddist = True)
    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)

    @testattr(stddist = True)
    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)
        
        opts = model.simulate_options()
        
        opts["IDA_options"]["sensitivity"] = True
        #opts["continuous_output"] = True #Should not be necessary
        
        res = model.simulate(0,2,input=inputtuple, options=opts)
        
        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)

    @testattr(stddist = True)
    def test_input_simulation_high_level_switched_input(self):
        """
        This tests that input simulation works when using high-level methods
        and the inputs are not in JModelica order.
        """
        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,u2,u1)))

        input_object = (['u2','u1'], 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)

    @testattr(stddist = True)
    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)
        
    @testattr(stddist = True)
    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
    
    @testattr(stddist = True)
    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)
    
    @testattr(stddist = True)
    def test_scaled_input(self):
        """
        Tests that simulation of scaled input works.
        """
        # 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['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)
        
        
    @testattr(stddist = True)
    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)

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