Example #1
0
 def setUpClass(cls):
     curr_dir = os.path.dirname(os.path.abspath(__file__));
     mofile = os.path.join(get_files_path(), 'Modelica', 'StaticOptimizationTest.mop')
     compile_jmu("StaticOptimizationTest.StaticOptimizationTest2", mofile)
     cls.model = JMUModel("StaticOptimizationTest_StaticOptimizationTest2.jmu")
     cls.nlp = NLPInitialization(cls.model,stat=1)
     cls.ipopt_nlp = InitializationOptimizer(cls.nlp)
Example #2
0
    def setUp(self):
        """Test setUp. Load the test model."""
        # Load the dynamic library and XML data
        cpath_daeinit = "DAEInitTest"
        fname_daeinit = cpath_daeinit.replace('.', '_', 1)
        self.dae_init_test = JMUModel(fname_daeinit + '.jmu')

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

        self.init_nlp = NLPInitialization(self.dae_init_test)
        self.init_nlp_ipopt = InitializationOptimizer(self.init_nlp)
Example #3
0
    def init_mode(self, solver):
        """
        Initiates the new mode.
        """
        if self._initiate_problem:
            #Check wheter or not it involves event functions
            if self._g_nbr > 0:
                self._model.sw = [int(x) for x in solver.sw]
            if self._g0_nbr > 0:
                self._model.sw_init = [int(x) for x in self.switches_init]

            #Initiate using IPOPT
            init_nlp = NLPInitialization(self._model)
            init_nlp_ipopt = InitializationOptimizer(init_nlp)
            init_nlp_ipopt.init_opt_ipopt_solve()
            
            #Sets the calculated values
            solver.y = N.append(self._model.real_x,self._model.real_w)
            solver.yd = N.append(self._model.real_dx,[0]*len(self._model.real_w)) 
        else:
            self._model.sw = [int(x) for x in solver.sw]
            
            if self.log_events:
                self._log_initiate_mode = True #Logg f evaluations
                i = len(self._log_information) #Where to put the information
            try:
                solver.make_consistent('IDA_YA_YDP_INIT') #Calculate consistency
                self._log.debug(
                    ' Calculation of consistent initial conditions: True')
            except Sundials_Exception as data:
                print data
                print 'Failed to calculate initial conditions. Trying to continue...'
                self._log.debug(
                    ' Calculation of consistent initial conditions: True')
            
            self._log_initiate_mode = False #Stop logging f
Example #4
0
 def setUp(self):
     """Test setUp. Load the test model."""
     cpath = "CSTR.CSTR_Init"
     fname = cpath.replace('.', '_')
     cstr = JMUModel(fname + '.jmu')
     self.init_nlp = NLPInitialization(cstr)
Example #5
0
    def test_linearization(self):

        # Load the dynamic library and XML data
        model = JMUModel(fname + '.jmu')

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

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

        # Solve the DAE initialization system with Ipopt
        init_nlp_ipopt.init_opt_ipopt_solve()

        (E_dae,A_dae,B_dae,F_dae,g_dae,state_names,input_names,algebraic_names, \
         dx0,x0,u0,w0,t0) = linearize_dae(model)

        (A_ode, B_ode, g_ode, H_ode, M_ode,
         q_ode) = linear_dae_to_ode(E_dae, A_dae, B_dae, F_dae, g_dae)

        (A_ode2,B_ode2,g_ode2,H_ode2,M_ode2,q_ode2,state_names2,input_names2,algebraic_names2, \
         dx02,x02,u02,w02,t02) = linearize_ode(model)

        N.testing.assert_array_almost_equal(
            A_ode, A_ode2, err_msg="Error in linearization: A_ode.")
        N.testing.assert_array_almost_equal(
            B_ode, B_ode2, err_msg="Error in linearization: B_ode.")
        N.testing.assert_array_almost_equal(
            g_ode, g_ode2, err_msg="Error in linearization: g_ode.")
        N.testing.assert_array_almost_equal(
            H_ode, H_ode2, err_msg="Error in linearization: H_ode.")
        N.testing.assert_array_almost_equal(
            M_ode, M_ode2, err_msg="Error in linearization: M_ode.")
        N.testing.assert_array_almost_equal(
            q_ode, q_ode2, err_msg="Error in linearization: q_ode.")
        assert (state_names == state_names2) == True
        assert (input_names == input_names2) == True
        assert (algebraic_names == algebraic_names2) == True

        small = 1e-4
        assert (
            N.abs(A_ode -
                  N.array([[-0.00000000e+00, 1.00000000e+03, 6.00000000e+01],
                           [-0.00000000e+00, -1.66821993e-02, -1.19039519e+00],
                           [-0.00000000e+00, 3.48651310e-03, 2.14034026e-01]]))
            <= small).all() == True
        assert (N.abs(
            B_ode -
            N.array([[1.00000000e+02], [-0.00000000e+00], [3.49859575e-02]]))
                <= small).all() == True
        assert (N.abs(g_ode - N.array([[-0.], [-0.], [-0.]])) <=
                small).all() == True

        assert N.abs(
            E_dae - N.array(([[-1., 0., 0.], [0., -1., 0.], [0., 0., -1.]])) <=
            small).all() == True
        assert (N.abs(
            A_dae -
            N.array([[-0.00000000e+00, -1.00000000e+03, -6.00000000e+01],
                     [-0.00000000e+00, 1.66821993e-02, 1.19039519e+00],
                     [-0.00000000e+00, -3.48651310e-03, -2.14034026e-01]])) <=
                small).all() == True
        assert (N.abs(
            B_dae -
            N.array([[-1.00000000e+02], [-0.00000000e+00], [-3.49859575e-02]]))
                <= small).all() == True
        assert (N.abs(g_dae - N.array([[-0.], [-0.], [-0.]])) <=
                small).all() == True

        assert (state_names == ['cost', 'cstr.c', 'cstr.T']) == True
        assert (input_names == ['u']) == True
        assert (algebraic_names == []) == True
Example #6
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()