Ejemplo n.º 1
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)
    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)
Ejemplo n.º 3
0
class Test_JMI_DAE:
    """
    This class tests pyjmi.simulation.assimulo.JMIDAE
    """
    @classmethod
    def setUpClass(cls):
        """
        Compile the test model.
        """
        #DAE test model
        fpath_DAE = os.path.join(get_files_path(), 'Modelica',
                                 'Pendulum_pack_no_opt.mo')
        cpath_DAE = 'Pendulum_pack.Pendulum'

        fname_DISC = compile_jmu(cpath_DAE, fpath_DAE)

        fpath_DISC = os.path.join(get_files_path(), 'Modelica',
                                  'IfExpExamples.mo')
        cpath_DISC = 'IfExpExamples.IfExpExample2'

        fname_DISC = compile_jmu(cpath_DISC, fpath_DISC)

        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_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)

    @testattr(stddist=True)
    def test_result_name_file(self):
        """
        Tests user naming of result file (JMIDAE).
        """
        res = self.m_DAE.simulate()

        #Default name
        assert res.result_file == "Pendulum_pack_Pendulum_result.txt"
        assert os.path.exists(res.result_file)

        res = self.m_DAE.simulate(
            options={
                "result_file_name": "Pendulum_pack_Pendulum_result_test.txt"
            })

        #User defined name
        assert res.result_file == "Pendulum_pack_Pendulum_result_test.txt"
        assert os.path.exists(res.result_file)

    @testattr(stddist=True)
    def test_eps(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.get/set_eps
        """
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_eps, 'Test')
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_eps, -1)
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_eps, 1)
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_eps, -1.0)

        self.DAE.eps = 1.0
        assert self.DAE.eps == 1.0
        self.DAE.eps = 10.0
        assert self.DAE.eps == 10.0

    @testattr(stddist=True)
    def test_max_eIteration(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.get/set_max_eIteration
        """
        nose.tools.assert_raises(JMIModel_Exception,
                                 self.DAE._set_max_eIteration, 'Test')
        nose.tools.assert_raises(JMIModel_Exception,
                                 self.DAE._set_max_eIteration, -1)
        nose.tools.assert_raises(JMIModel_Exception,
                                 self.DAE._set_max_eIteration, 1.0)
        nose.tools.assert_raises(JMIModel_Exception,
                                 self.DAE._set_max_eIteration, -1.0)

        self.DAE.max_eIter = 1
        assert self.DAE.max_eIter == 1
        self.DAE.max_eIter = 10
        assert self.DAE.max_eIter == 10

    @testattr(stddist=True)
    def test_check_eIter(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.check_eIter
        """
        self.DAE.eps = 1e-4

        b_mode = [1, -1, 0]
        a_mode = [-1, 1, 1]

        [eIter, iter] = self.DAE.check_eIter(b_mode, a_mode)

        assert iter == True
        assert eIter[0] == -1
        assert eIter[1] == 1
        assert eIter[2] == 1

        b_mode = [2, 5, 1]
        a_mode = [0, 2, 2]

        [eIter, iter] = self.DAE.check_eIter(b_mode, a_mode)

        assert iter == False
        assert eIter[0] == 0
        assert eIter[1] == 0
        assert eIter[2] == 0

    @testattr(stddist=True)
    def test_scaled_input(self):
        """
        Tests that simulation of scaled input works.
        """
        t = N.linspace(0., 10., 100)
        u1 = N.cos(t)
        u2 = N.sin(t)
        u_traj = N.transpose(N.vstack((t, u1, u2)))

        res = self.m_INPUT.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)

    @testattr(stddist=True)
    def test_event_switch(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.event_switch
        """
        solver = lambda x: 1
        solver.verbosity = 1
        solver.LOUD = 2
        solver.sw = [False, False, True]
        event_info = [1, 0, -1]

        self.DAE.event_switch(solver, event_info)

        assert solver.sw[0] == True
        assert solver.sw[1] == False
        assert solver.sw[2] == False

    @testattr(stddist=True)
    def test_f(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.f
        """
        test_x = N.array([1., 1., 1., 1.])
        test_dx = N.array([2., 2., 2., 2.])
        test_t = 2

        temp_f = self.DAE.res(test_t, test_x, test_dx)

        assert temp_f[0] == -1.0
        assert temp_f[2] == -1.0
        assert temp_f[3] == -2.0
        nose.tools.assert_almost_equal(temp_f[1], -1.158529, 5)

    @testattr(stddist=True)
    def test_g(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.g
        """
        pass  #DEPRECATED

        #temp_g = self.DISC.g(2.,[1.,2.],[2.,0],[0,0])
        #nose.tools.assert_almost_equal(temp_g[0], -0.429203, 5)
        #nose.tools.assert_almost_equal(temp_g[1], 1.141592, 5)

    @testattr(stddist=True)
    def test_g_adjust(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.g
        """
        pass  #DEPRECATED
        """
        self.DISC.eps = 2.0

        temp_g_adjust = self.DISC.g_adjust(2.,[1.,2.],[2.,0],[0,0])

        nose.tools.assert_almost_equal(temp_g_adjust[0], -2.429203, 5)
        nose.tools.assert_almost_equal(temp_g_adjust[1], -0.858407, 5)
        
        temp_g_adjust = self.DISC.g_adjust(2.,[1.,2.],[2.,0],[0,1])
        
        nose.tools.assert_almost_equal(temp_g_adjust[0], -2.429203, 5)
        nose.tools.assert_almost_equal(temp_g_adjust[1], 3.141592, 5)
        """

    @testattr(stddist=True)
    def test_init(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.__init__
        """
        assert self.m_DAE == self.DAE._model
        assert self.DAE.max_eIter == 50
        assert self.DAE.eps == 1e-9
        assert self.DAE.jac == self.DAE.j

        temp_y0 = N.append(self.m_DAE.real_x.copy(), self.m_DAE.real_w.copy())
        temp_yd0 = N.append(self.m_DAE.real_dx.copy(),
                            [0] * len(self.m_DAE.real_w))
        temp_algvar = [1.0] * len(self.m_DAE.real_x) + [0.0] * len(
            self.m_DAE.real_w)

        for i in range(len(temp_y0)):
            assert temp_y0[i] == self.DAE.y0[i]
            assert temp_yd0[i] == self.DAE.yd0[i]
            assert temp_algvar[i] == self.DAE.algvar[i]

        #Test discontiniuous system
        assert self.DISC._g_nbr == 2
        assert self.DISC.state_events == self.DISC.g_adjust

    @testattr(stddist=True)
    def test_reset(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.reset
        """
        self.DAE.t0 = 10.0
        self.DAE._model.real_x = N.array([2., 2., 2., 2.])
        self.DAE._model.real_dx = N.array([2., 2., 2., 2.])

        self.DAE.reset()

        assert self.DAE._model.t == 10.0
        assert self.DAE._model.real_x[0] != 2.0
        assert self.DAE._model.real_x[1] != 2.0
        assert self.DAE._model.real_x[2] != 2.0
        assert self.DAE._model.real_dx[0] != 2.0
        assert self.DAE._model.real_dx[1] != 2.0
        assert self.DAE._model.real_dx[2] != 2.0

        assert self.DAE.y0[0] == 0.1

    @testattr(stddist=True)
    def test_event_iteration(self):
        """
        This tests JMUs with event iteration (JModelica.org).
        """
        #DEPRECATED!
        pass
        """
        jmu_name = compile_jmu('EventIter.EventMiddleIter', os.path.join(path_to_mos,'EventIter.mo'))

        model = JMUModel(jmu_name)

        sim_res = model.simulate(final_time=10)

        x = sim_res['x']
        y = sim_res['y']
        z = sim_res['z']
        
        nose.tools.assert_almost_equal(x[0], 2.00000, 4)
        nose.tools.assert_almost_equal(x[-1], 10.000000, 4)
        nose.tools.assert_almost_equal(y[-1], 3.0000000, 4)
        nose.tools.assert_almost_equal(z[-1], 2.0000000, 4)
        
        jmu_name = compile_jmu('EventIter.EventStartIter', os.path.join(path_to_mos,'EventIter.mo'))
        
        model = JMUModel(jmu_name)

        sim_res = model.simulate(final_time=10)

        x = sim_res['x']
        y = sim_res['y']
        z = sim_res['z']
        
        nose.tools.assert_almost_equal(x[0], 1.00000, 4)
        nose.tools.assert_almost_equal(y[0], -1.00000, 4)
        nose.tools.assert_almost_equal(z[0], 1.00000, 4)
        nose.tools.assert_almost_equal(x[-1], -2.000000, 4)
        nose.tools.assert_almost_equal(y[-1], -1.0000000, 4)
        nose.tools.assert_almost_equal(z[-1], 4.0000000, 4)
        """

    @testattr(stddist=True)
    def test_j(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.j
        """

        test_x = N.array([1., 1., 1., 1.])
        test_dx = N.array([2., 2., 2., 2.])
        test_t = 2

        temp_j = self.DAE.j(0.1, test_t, test_x, test_dx)
        #print temp_j
        assert temp_j[0, 0] == -0.1
        assert temp_j[0, 1] == 1.0
        assert temp_j[1, 1] == -0.1
        nose.tools.assert_almost_equal(temp_j[1, 0], 0.5403023, 5)

    @testattr(stddist=True)
    def test_handle_event(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.handle_event
        """
        solver = lambda x: 1
        solver.verbosity = 1
        solver.NORMAL = solver.LOUD = 2
        solver.t_sol = [[1.0]]
        solver.y_sol = [[1., 1.]]
        solver.yd_sol = [[1., 1.]]
        solver.t = N.array(1.0)
        solver.y = N.array([1., 1.])
        solver.yd = N.array([1., 1.])
        solver.sw = [False, True]
        self.DISC.event_switch = lambda x, y: 1
        self.DISC.init_mode = lambda x: 1
        self.DISC.check_eIter = lambda x, y: [True, False]

        self.DISC.handle_event(solver, [1, 1])

        self.DISC.check_eIter = lambda x, y: [True, True]

        self.DISC.handle_event(solver, [1, 1])

    @testattr(stddist=True)
    def test_init_mode(self):
        """
        Tests pyjmi.simulation.assimulo.init_mode
        """
        solver = lambda x: 1
        solver.sw = [True, True]
        solver.make_consistent = lambda x: 1

        self.DISC.init_mode(solver)

        assert self.DISC._model.sw[0] == 1
        assert self.DISC._model.sw[1] == 1

    @testattr(stddist=True)
    def test_initiate(self):
        """
        Tests pyjmi.simulation.assimulo.initiate
        """
        #self.DAE.init_mode = lambda x:1
        #self.DAE.initiate('Test')

        #self.DISC.handle_event = lambda x,y:1
        #solver = lambda x:1
        #solver.switches = [False, False]

        #self.DISC.initiate(solver)

        #assert solver.switches[0] == True
        #assert solver.switches[1] == True
        pass

    """
    @testattr(stddist = True)
    def test_scaled_input(self):
        #This tests simulation with scaled input.
        fpath = os.path.join(get_files_path(), 'Modelica', 'VDP.mop')
        cpath = 'VDP_pack.VDP_scaled_input'
        
        # compile VDP
        jmu_name = compile_jmu(cpath, fpath, 
                    compiler_options={'enable_variable_scaling':True})

        # Load the dynamic library and XML data
        vdp = JMUModel(jmu_name)
        
        t = N.linspace(0.,10.,100) 
        u1 = N.cos(t)/10.0
        u_traj = N.transpose(N.vstack((t,u1)))
        
        res_scaled = vdp.simulate(final_time=10, input=(['u'],u_traj))
        
        # compile VDP
        jmu_name = compile_jmu(cpath, fpath, 
                    compiler_options={'enable_variable_scaling':False})

        # Load the dynamic library and XML data
        vdp = JMUModel(jmu_name)
        
        t = N.linspace(0.,10.,100) 
        u1 = N.cos(t)
        u_traj = N.transpose(N.vstack((t,u1)))
        
        res = vdp.simulate(final_time=10, input=(['u'],u_traj))
        
        nose.tools.assert_almost_equal(res["u"][0], res_scaled["u"][0], 3)
        nose.tools.assert_almost_equal(res["u"][-1], res_scaled["u"][-1], 3)
    """

    @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)
        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)

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

    @testattr(stddist=True)
    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)
Ejemplo n.º 4
0
def run_demo(with_plots=True):
    """ 
    Model predicitve control of the Hicks-Ray CSTR reactor. This example 
    demonstrates how to use the blocking factor feature of the collocation 
    algorithm.

    This example also shows how to use classes for initialization, simulation 
    and optimization directly rather than calling then through the high-level 
    classes 'initialialize', 'simulate' and 'optimize'.
    """

    curr_dir = os.path.dirname(os.path.abspath(__file__))

    # Compile the stationary initialization model into a JMU
    jmu_name = compile_jmu("CSTR.CSTR_Init",
                           os.path.join(curr_dir, "files", "CSTR.mop"))

    # Load a JMUModel instance
    init_model = JMUModel(jmu_name)

    # Create DAE initialization object.
    init_nlp = NLPInitialization(init_model)

    # Create an Ipopt solver object for the DAE initialization system
    init_nlp_ipopt = InitializationOptimizer(init_nlp)

    def compute_stationary(Tc_stat):
        init_model.set('Tc', Tc_stat)
        # Solve the DAE initialization system with Ipopt
        init_nlp_ipopt.init_opt_ipopt_solve()
        return (init_model.get('c'), init_model.get('T'))

    # Set inputs for Stationary point A
    Tc_0_A = 250
    c_0_A, T_0_A = compute_stationary(Tc_0_A)

    # Print some data for stationary point A
    print(' *** Stationary point A ***')
    print('Tc = %f' % Tc_0_A)
    print('c = %f' % c_0_A)
    print('T = %f' % T_0_A)

    # Set inputs for Stationary point B
    Tc_0_B = 280
    c_0_B, T_0_B = compute_stationary(Tc_0_B)

    # Print some data for stationary point B
    print(' *** Stationary point B ***')
    print('Tc = %f' % Tc_0_B)
    print('c = %f' % c_0_B)
    print('T = %f' % T_0_B)

    jmu_name = compile_jmu("CSTR.CSTR_Opt_MPC",
                           os.path.join(curr_dir, "files", "CSTR.mop"))

    cstr = JMUModel(jmu_name)

    cstr.set('Tc_ref', Tc_0_B)
    cstr.set('c_ref', c_0_B)
    cstr.set('T_ref', T_0_B)

    cstr.set('cstr.c_init', c_0_A)
    cstr.set('cstr.T_init', T_0_A)

    # Initialize the mesh
    n_e = 50  # 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
    # The length of the optimization interval is 50s and the
    # number of elements is 50, which gives a blocking factor
    # vector of 2*ones(n_e/2) to match the sampling interval
    # of 2s.
    nlp = ipopt.NLPCollocationLagrangePolynomials(cstr,
                                                  n_e,
                                                  hs,
                                                  n_cp,
                                                  blocking_factors=2 *
                                                  N.ones(n_e / 2, dtype=N.int))

    # Create an Ipopt NLP object
    nlp_ipopt = ipopt.CollocationOptimizer(nlp)

    nlp_ipopt.opt_coll_ipopt_set_int_option("max_iter", 500)

    h = 2.  # Sampling interval
    T_final = 180.  # Final time of simulation
    t_mpc = N.linspace(0, T_final, T_final / h + 1)
    n_samples = N.size(t_mpc)

    ref_mpc = N.zeros(n_samples)
    ref_mpc[0:3] = N.ones(3) * Tc_0_A
    ref_mpc[3:] = N.ones(n_samples - 3) * Tc_0_B

    cstr.set('cstr.c_init', c_0_A)
    cstr.set('cstr.T_init', T_0_A)

    # Compile the simulation model into a DLL
    jmu_name = compile_jmu("CSTR.CSTR",
                           os.path.join(curr_dir, "files", "CSTR.mop"))

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

    sim_model.set('c_init', c_0_A)
    sim_model.set('T_init', T_0_A)

    global cstr_mod
    global cstr_sim

    cstr_mod = JMIDAE(sim_model)  # Create an Assimulo problem
    cstr_sim = IDA(cstr_mod)  # Create an IDA solver

    i = 0

    if with_plots:
        plt.figure(4)
        plt.clf()

    for t in t_mpc[0:-1]:
        Tc_ref = ref_mpc[i]
        c_ref, T_ref = compute_stationary(Tc_ref)

        cstr.set('Tc_ref', Tc_ref)
        cstr.set('c_ref', c_ref)
        cstr.set('T_ref', T_ref)

        # Solve the optimization problem
        nlp_ipopt.opt_coll_ipopt_solve()

        # Write to file.
        nlp.export_result_dymola()

        # Load the file we just wrote to file
        res = ResultDymolaTextual('CSTR_CSTR_Opt_MPC_result.txt')

        # Extract variable profiles
        c_res = res.get_variable_data('cstr.c')
        T_res = res.get_variable_data('cstr.T')
        Tc_res = res.get_variable_data('cstr.Tc')

        # Get the first Tc sample
        Tc_ctrl = Tc_res.x[0]

        # Set the value to the model
        sim_model.set('Tc', Tc_ctrl)

        # Simulate
        cstr_sim.simulate(t_mpc[i + 1])

        t_T_sim = cstr_sim.t_sol

        # Set terminal values of the states
        cstr.set('cstr.c_init', cstr_sim.y[0])
        cstr.set('cstr.T_init', cstr_sim.y[1])
        sim_model.set('c_init', cstr_sim.y[0])
        sim_model.set('T_init', cstr_sim.y[1])

        if with_plots:
            plt.figure(4)
            plt.subplot(3, 1, 1)
            plt.plot(t_T_sim, N.array(cstr_sim.y_sol)[:, 0], 'b')

            plt.subplot(3, 1, 2)
            plt.plot(t_T_sim, N.array(cstr_sim.y_sol)[:, 1], 'b')

            if t_mpc[i] == 0:
                plt.subplot(3, 1, 3)
                plt.plot([t_mpc[i], t_mpc[i + 1]], [Tc_ctrl, Tc_ctrl], 'b')
            else:
                plt.subplot(3, 1, 3)
                plt.plot([t_mpc[i], t_mpc[i], t_mpc[i + 1]],
                         [Tc_ctrl_old, Tc_ctrl, Tc_ctrl], 'b')

        Tc_ctrl_old = Tc_ctrl

        i = i + 1

    assert N.abs(Tc_ctrl - 279.097186038194) < 1e-6
    assert N.abs(N.array(cstr_sim.y_sol)[:, 0][-1] - 350.89028563) < 1e-6
    assert N.abs(N.array(cstr_sim.y_sol)[:, 1][-1] - 283.15229948) < 1e-6

    if with_plots:
        plt.figure(4)
        plt.subplot(3, 1, 1)
        plt.ylabel('c')
        plt.plot([0, T_final], [c_0_B, c_0_B], '--')
        plt.grid()
        plt.subplot(3, 1, 2)
        plt.ylabel('T')
        plt.plot([0, T_final], [T_0_B, T_0_B], '--')
        plt.grid()
        plt.subplot(3, 1, 3)
        plt.ylabel('Tc')
        plt.plot([0, T_final], [Tc_0_B, Tc_0_B], '--')
        plt.grid()
        plt.xlabel('t')
        plt.show()
class Test_JMI_DAE:
    """
    This class tests pyjmi.simulation.assimulo.JMIDAE
    """
    @classmethod
    def setUpClass(cls):
        """
        Compile the test model.
        """
        #DAE test model
        fpath_DAE = os.path.join(get_files_path(), 'Modelica', 
            'Pendulum_pack_no_opt.mo')
        cpath_DAE = 'Pendulum_pack.Pendulum'

        fname_DISC = compile_jmu(cpath_DAE, fpath_DAE)
        
        fpath_DISC = os.path.join(get_files_path(), 'Modelica', 
            'IfExpExamples.mo')
        cpath_DISC = 'IfExpExamples.IfExpExample2'
        
        fname_DISC = compile_jmu(cpath_DISC, fpath_DISC)
        
        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_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)
        
    @testattr(stddist = True)
    def test_result_name_file(self):
        """
        Tests user naming of result file (JMIDAE).
        """
        res = self.m_DAE.simulate()
        
        #Default name
        assert res.result_file == "Pendulum_pack_Pendulum_result.txt"
        assert os.path.exists(res.result_file)
        
        res = self.m_DAE.simulate(options={"result_file_name":
                                    "Pendulum_pack_Pendulum_result_test.txt"})
                                    
        #User defined name
        assert res.result_file == "Pendulum_pack_Pendulum_result_test.txt"
        assert os.path.exists(res.result_file)
        
    
    @testattr(stddist = True) 
    def test_eps(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.get/set_eps
        """
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_eps, 'Test')
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_eps, -1)
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_eps, 1)
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_eps, -1.0)
        
        self.DAE.eps = 1.0
        assert self.DAE.eps == 1.0
        self.DAE.eps = 10.0
        assert self.DAE.eps == 10.0
    
    @testattr(stddist = True) 
    def test_max_eIteration(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.get/set_max_eIteration
        """
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_max_eIteration, 'Test')
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_max_eIteration, -1)
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_max_eIteration, 1.0)
        nose.tools.assert_raises(JMIModel_Exception, self.DAE._set_max_eIteration, -1.0)
        
        self.DAE.max_eIter = 1
        assert self.DAE.max_eIter == 1
        self.DAE.max_eIter = 10
        assert self.DAE.max_eIter == 10
    
    @testattr(stddist = True) 
    def test_check_eIter(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.check_eIter
        """
        self.DAE.eps = 1e-4
        
        b_mode = [1, -1, 0]
        a_mode = [-1, 1, 1]
        
        [eIter, iter] = self.DAE.check_eIter(b_mode, a_mode)
        
        assert iter == True
        assert eIter[0] == -1
        assert eIter[1] == 1
        assert eIter[2] == 1
        
        b_mode = [2, 5, 1]
        a_mode = [0, 2, 2]
        
        [eIter, iter] = self.DAE.check_eIter(b_mode, a_mode)
        
        assert iter == False
        assert eIter[0] == 0
        assert eIter[1] == 0
        assert eIter[2] == 0
    
    @testattr(stddist = True)
    def test_scaled_input(self):
        """
        Tests that simulation of scaled input works.
        """
        t = N.linspace(0.,10.,100) 
        u1 = N.cos(t)
        u2 = N.sin(t)
        u_traj = N.transpose(N.vstack((t,u1,u2)))
        
        res = self.m_INPUT.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)
        
    
    @testattr(stddist = True) 
    def test_event_switch(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.event_switch
        """
        solver = lambda x:1
        solver.verbosity = 1
        solver.LOUD = 2
        solver.sw = [False, False, True]
        event_info = [1, 0, -1]
        
        self.DAE.event_switch(solver,event_info)
        
        assert solver.sw[0] == True
        assert solver.sw[1] == False
        assert solver.sw[2] == False
    
    @testattr(stddist = True) 
    def test_f(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.f
        """
        test_x = N.array([1.,1.,1.,1.])
        test_dx = N.array([2.,2.,2.,2.])
        test_t = 2
        
        temp_f = self.DAE.res(test_t,test_x,test_dx)
        
        assert temp_f[0] == -1.0
        assert temp_f[2] == -1.0
        assert temp_f[3] == -2.0
        nose.tools.assert_almost_equal(temp_f[1], -1.158529, 5)
    
    @testattr(stddist = True) 
    def test_g(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.g
        """
        pass #DEPRECATED
        
        #temp_g = self.DISC.g(2.,[1.,2.],[2.,0],[0,0])
        #nose.tools.assert_almost_equal(temp_g[0], -0.429203, 5)
        #nose.tools.assert_almost_equal(temp_g[1], 1.141592, 5)
    
    @testattr(stddist = True) 
    def test_g_adjust(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.g
        """
        pass #DEPRECATED
        """
        self.DISC.eps = 2.0

        temp_g_adjust = self.DISC.g_adjust(2.,[1.,2.],[2.,0],[0,0])

        nose.tools.assert_almost_equal(temp_g_adjust[0], -2.429203, 5)
        nose.tools.assert_almost_equal(temp_g_adjust[1], -0.858407, 5)
        
        temp_g_adjust = self.DISC.g_adjust(2.,[1.,2.],[2.,0],[0,1])
        
        nose.tools.assert_almost_equal(temp_g_adjust[0], -2.429203, 5)
        nose.tools.assert_almost_equal(temp_g_adjust[1], 3.141592, 5)
        """
        
    @testattr(stddist = True) 
    def test_init(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.__init__
        """
        assert self.m_DAE == self.DAE._model
        assert self.DAE.max_eIter == 50
        assert self.DAE.eps == 1e-9
        assert self.DAE.jac == self.DAE.j
        
        temp_y0 = N.append(self.m_DAE.real_x.copy(), self.m_DAE.real_w.copy())
        temp_yd0 = N.append(self.m_DAE.real_dx.copy(),[0]*len(self.m_DAE.real_w))
        temp_algvar = [1.0]*len(self.m_DAE.real_x) + [0.0]*len(self.m_DAE.real_w)
        
        for i in range(len(temp_y0)):
            assert temp_y0[i] == self.DAE.y0[i]
            assert temp_yd0[i] == self.DAE.yd0[i]
            assert temp_algvar[i] == self.DAE.algvar[i]
            
        #Test discontiniuous system
        assert self.DISC._g_nbr == 2
        assert self.DISC.state_events == self.DISC.g_adjust
    
    @testattr(stddist = True) 
    def test_reset(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.reset
        """   
        self.DAE.t0 = 10.0
        self.DAE._model.real_x = N.array([2.,2.,2.,2.])
        self.DAE._model.real_dx = N.array([2.,2.,2.,2.])

        self.DAE.reset()
        
        assert self.DAE._model.t == 10.0
        assert self.DAE._model.real_x[0] != 2.0
        assert self.DAE._model.real_x[1] != 2.0
        assert self.DAE._model.real_x[2] != 2.0
        assert self.DAE._model.real_dx[0] != 2.0
        assert self.DAE._model.real_dx[1] != 2.0
        assert self.DAE._model.real_dx[2] != 2.0        
       
        assert self.DAE.y0[0] == 0.1

    @testattr(stddist = True)
    def test_event_iteration(self):
        """
        This tests JMUs with event iteration (JModelica.org).
        """
        #DEPRECATED!
        pass
        """
        jmu_name = compile_jmu('EventIter.EventMiddleIter', os.path.join(path_to_mos,'EventIter.mo'))

        model = JMUModel(jmu_name)

        sim_res = model.simulate(final_time=10)

        x = sim_res['x']
        y = sim_res['y']
        z = sim_res['z']
        
        nose.tools.assert_almost_equal(x[0], 2.00000, 4)
        nose.tools.assert_almost_equal(x[-1], 10.000000, 4)
        nose.tools.assert_almost_equal(y[-1], 3.0000000, 4)
        nose.tools.assert_almost_equal(z[-1], 2.0000000, 4)
        
        jmu_name = compile_jmu('EventIter.EventStartIter', os.path.join(path_to_mos,'EventIter.mo'))
        
        model = JMUModel(jmu_name)

        sim_res = model.simulate(final_time=10)

        x = sim_res['x']
        y = sim_res['y']
        z = sim_res['z']
        
        nose.tools.assert_almost_equal(x[0], 1.00000, 4)
        nose.tools.assert_almost_equal(y[0], -1.00000, 4)
        nose.tools.assert_almost_equal(z[0], 1.00000, 4)
        nose.tools.assert_almost_equal(x[-1], -2.000000, 4)
        nose.tools.assert_almost_equal(y[-1], -1.0000000, 4)
        nose.tools.assert_almost_equal(z[-1], 4.0000000, 4)
        """

    @testattr(stddist = True) 
    def test_j(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.j
        """
        
        test_x = N.array([1.,1.,1.,1.])
        test_dx = N.array([2.,2.,2.,2.])
        test_t = 2
        
        temp_j = self.DAE.j(0.1,test_t,test_x,test_dx)
        #print temp_j
        assert temp_j[0,0] == -0.1
        assert temp_j[0,1] == 1.0
        assert temp_j[1,1] == -0.1
        nose.tools.assert_almost_equal(temp_j[1,0], 0.5403023, 5)
    
    @testattr(stddist = True) 
    def test_handle_event(self):
        """
        Tests pyjmi.simulation.assimulo.JMIDAE.handle_event
        """
        solver = lambda x:1
        solver.verbosity = 1
        solver.NORMAL = solver.LOUD = 2
        solver.t_sol = [[1.0]]
        solver.y_sol = [[1.,1.]]
        solver.yd_sol = [[1.,1.]]
        solver.t = N.array(1.0)
        solver.y = N.array([1.,1.])
        solver.yd = N.array([1.,1.])
        solver.sw = [False,True]
        self.DISC.event_switch = lambda x,y:1
        self.DISC.init_mode = lambda x:1
        self.DISC.check_eIter = lambda x,y: [True,False]
        
        self.DISC.handle_event(solver, [1,1])
        
        self.DISC.check_eIter = lambda x,y: [True,True]
        
        self.DISC.handle_event(solver, [1,1])

    @testattr(stddist = True) 
    def test_init_mode(self):
        """
        Tests pyjmi.simulation.assimulo.init_mode
        """
        solver = lambda x:1
        solver.sw = [True, True]
        solver.make_consistent = lambda x:1
        
        self.DISC.init_mode(solver)
        
        assert self.DISC._model.sw[0] == 1
        assert self.DISC._model.sw[1] == 1
    
    @testattr(stddist = True) 
    def test_initiate(self):
        """
        Tests pyjmi.simulation.assimulo.initiate
        """
        #self.DAE.init_mode = lambda x:1
        #self.DAE.initiate('Test')
        
        #self.DISC.handle_event = lambda x,y:1
        #solver = lambda x:1
        #solver.switches = [False, False]
        
        #self.DISC.initiate(solver)

        #assert solver.switches[0] == True
        #assert solver.switches[1] == True
        pass
    """
    @testattr(stddist = True)
    def test_scaled_input(self):
        #This tests simulation with scaled input.
        fpath = os.path.join(get_files_path(), 'Modelica', 'VDP.mop')
        cpath = 'VDP_pack.VDP_scaled_input'
        
        # compile VDP
        jmu_name = compile_jmu(cpath, fpath, 
                    compiler_options={'enable_variable_scaling':True})

        # Load the dynamic library and XML data
        vdp = JMUModel(jmu_name)
        
        t = N.linspace(0.,10.,100) 
        u1 = N.cos(t)/10.0
        u_traj = N.transpose(N.vstack((t,u1)))
        
        res_scaled = vdp.simulate(final_time=10, input=(['u'],u_traj))
        
        # compile VDP
        jmu_name = compile_jmu(cpath, fpath, 
                    compiler_options={'enable_variable_scaling':False})

        # Load the dynamic library and XML data
        vdp = JMUModel(jmu_name)
        
        t = N.linspace(0.,10.,100) 
        u1 = N.cos(t)
        u_traj = N.transpose(N.vstack((t,u1)))
        
        res = vdp.simulate(final_time=10, input=(['u'],u_traj))
        
        nose.tools.assert_almost_equal(res["u"][0], res_scaled["u"][0], 3)
        nose.tools.assert_almost_equal(res["u"][-1], res_scaled["u"][-1], 3)
    """
    @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)
        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)

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

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