示例#1
0
    def test_init(self):

        m = JMUModel(self.jn)

        # Create a new collocation object
        n_e = 30
        coll = NLPCollocationLagrangePolynomials(m, n_e, N.ones(n_e) / n_e, 3)

        # Initialize with optimization result
        coll.set_initial_from_dymola(self.res.result_data, N.array([]), 0, 1)

        # Write initial point to file
        coll.export_result_dymola('Init_res.txt')

        # Load result
        res_init = ResultDymolaTextual('Init_res.txt')

        # Load test fixture
        res_init_fix = ResultDymolaTextual(
            self.curr_dir + '/../files/Results/MinTimeInit_init_fix.txt')

        # Extract trajectories
        dx = res_init.get_variable_data('der(x)')
        dv = res_init.get_variable_data('der(v)')
        x = res_init.get_variable_data('x')
        v = res_init.get_variable_data('v')
        u = res_init.get_variable_data('u')

        dx_fix = res_init_fix.get_variable_data('der(x)')
        dv_fix = res_init_fix.get_variable_data('der(v)')
        x_fix = res_init_fix.get_variable_data('x')
        v_fix = res_init_fix.get_variable_data('v')
        u_fix = res_init_fix.get_variable_data('u')

        # Comparison tests
        N.testing.assert_array_almost_equal(dx_fix.x, dx.x)
        N.testing.assert_array_almost_equal(dv_fix.x, dv.x)
        N.testing.assert_array_almost_equal(x_fix.x, x.x)
        N.testing.assert_array_almost_equal(v_fix.x, v.x)
        N.testing.assert_array_almost_equal(u_fix.x, u.x)

        if False:
            plt.figure(1)
            plt.subplot(2, 1, 1)
            plt.plot(x.t, x.x, 'r')
            plt.hold(True)
            plt.plot(v.t, v.x, 'r')
            plt.grid(True)
            plt.subplot(2, 1, 2)
            plt.plot(u.t, u.x, 'r')
            plt.grid(True)
示例#2
0
    def test_init_opt_write_result(self):

        cpath_daeinit = "DAEInitTest"
        fname_daeinit = cpath_daeinit.replace('.', '_', 1)

        # self.init_nlp_ipopt.init_opt_ipopt_set_string_option("derivative_test","first-order")

        self.init_nlp_ipopt.init_opt_ipopt_solve()

        self.init_nlp.export_result_dymola()

        res = ResultDymolaTextual(fname_daeinit + "_result.txt")

        res_Z = N.array([
            5., -198.1585290151921, -0.2431975046920718, 3.0, 4.0, 1.0, 2197.0,
            5.0, -0.92009689684513785, 0.
        ])

        assert N.abs(res_Z[0] - res.get_variable_data("p").x[0]) < 1e-3
        assert N.abs(res_Z[1] - res.get_variable_data("der(x1)").x[0]) < 1e-3
        assert N.abs(res_Z[2] - res.get_variable_data("der(x2)").x[0]) < 1e-3
        assert N.abs(res_Z[3] - res.get_variable_data("x1").x[0]) < 1e-3
        assert N.abs(res_Z[4] - res.get_variable_data("x2").x[0]) < 1e-3
        assert N.abs(res_Z[5] - res.get_variable_data("u").x[0]) < 1e-3
        assert N.abs(res_Z[6] - res.get_variable_data("y1").x[0]) < 1e-3
        assert N.abs(res_Z[7] - res.get_variable_data("y2").x[0]) < 1e-3
        assert N.abs(res_Z[8] - res.get_variable_data("y3").x[0]) < 1e-3
示例#3
0
 def load_expected_data(self, name):
     """
     Load the expected data to use for assert_all_paths() and assert_all_end_values().
       name -  the file name of the results file, relative to files dir
     """
     path = os.path.join(get_files_path(), 'Results', name)
     self.expected = ResultDymolaTextual(path)
示例#4
0
 def run(self, cvode_options=None):
     """
     Run simulation and load result. 
     Call this from setUp() or within a test depending if all tests should run simulation.
     """
     self._run_and_write_data(cvode_options)
     self.data = ResultDymolaTextual(self.model_name[:-len('.jmu')] +
                                     '_result.txt')
示例#5
0
    def test_initialization_from_data(self):
        n_e = 50
        hs = N.ones(n_e) * 1. / n_e
        n_cp = 3

        nlp = NLPCollocationLagrangePolynomials(self.model, n_e, hs, n_cp)
        nlp.set_initial_from_dymola(self.expected, hs, 0, 1)
        nlp.export_result_dymola()
        self.data = ResultDymolaTextual(
            "NominalTests_NominalOptTest2_result.txt")
        self.assert_all_trajectories(['x', 'der(x)', 'u'])
示例#6
0
    def setUp(self):
        resfile = os.path.join(get_files_path(), 'Results', 
            'BlockingInitPack_M_init_result.txt')
        self.res_init = ResultDymolaTextual(resfile)

        self.n_e = 5 # Number of elements 
        self.hs = N.ones(self.n_e)*1./self.n_e # Equidistant points
        self.n_cp = 3; # Number of collocation points in each element

        # Blocking factors for control parametrization
        blocking_factors=N.ones(self.n_e,dtype=N.int)

        self.nlp = NLPCollocationLagrangePolynomials(self.opt_model,
            self.n_e,self.hs,self.n_cp,blocking_factors)

        self.nlp.set_initial_from_dymola(self.res_init, self.hs, 0., 10.)

        self.nlp.export_result_dymola("qwe.txt")

        self.res_init2 = ResultDymolaTextual('qwe.txt')
示例#7
0
    def test_input_simulation(self):
        """
        This tests that input simulation works.
        """
        self.m_SENS = JMUModel('QuadTankSens.jmu')
        self.SENS = JMIDAESens(self.m_SENS)
        
        path_result = os.path.join(get_files_path(), 'Results', 
                                'qt_par_est_data.mat')
        
        data = loadmat(path_result,appendmat=False)

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

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

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

        qt_sim = IDA(qt_mod)

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

        #write_data(qt_sim)

        res = ResultDymolaTextual('QuadTankSens_result.txt')
    
        dx1da1 = res.get_variable_data('dx1/da1')
        dx1da2 = res.get_variable_data('dx1/da2')
        dx4da1 = res.get_variable_data('dx4/da1')
        
        nose.tools.assert_almost_equal(dx1da2.x[0], 0.000000, 4)
        nose.tools.assert_almost_equal(dx1da2.x[-1], 0.00000, 4)
示例#8
0
 def test_set_initial_from_dymola(self):
     """ Test of 'jmi_opt_coll_set_initial_from_trajectory'.
 
     An optimization problem is solved and then the result
     is used to reinitialize the NLP. The variable profiles
     are then retrieved and a check is performed wheather
     they match.
     """
     
     # Solve the optimization problem
     self.nlp_ipopt.opt_coll_ipopt_solve()
 
     # Retreive the number of points in each column in the
     # result matrix
     n_points = self.nlp.opt_coll_get_result_variable_vector_length()
 
     # Create result data vectors
     p_opt = N.zeros(1)
     t_ = N.zeros(n_points)
     dx_ = N.zeros(2*n_points)
     x_ = N.zeros(2*n_points)
     u_ = N.zeros(n_points)
     w_ = N.zeros(0)
     
     # Get the result
     self.nlp.opt_coll_get_result(p_opt,t_,dx_,x_,u_,w_)
 
     # Write to file
     self.nlp.export_result_dymola()
 
     # Load the file we just wrote
     res = ResultDymolaTextual(self.fname_vdp+'_result.txt')
 
     self.nlp.set_initial_from_dymola(res,self.hs,0.,0.)
 
     # Create result data vectors
     p_opt_2 = N.zeros(1)
     t_2 = N.zeros(n_points)
     dx_2 = N.zeros(2*n_points)
     x_2 = N.zeros(2*n_points)
     u_2 = N.zeros(n_points)
     w_2 = N.zeros(0)
     
     # Get the result
     self.nlp.opt_coll_get_result(p_opt_2,t_2,dx_2,x_2,u_2,w_2)
 
 
     assert max(N.abs(p_opt-p_opt_2))<1e-3
     assert max(N.abs(dx_-dx_2))<1e-3
     assert max(N.abs(x_-x_2))<1e-3
     assert max(N.abs(u_-u_2))<1e-3
示例#9
0
    def get_complete_results(self):
        """
        Creates and returns the patched together resultfile from all 
        optimizations.
        """
        # Check if complete results have been saved
        if self.create_comp_result is False:
            raise  ValueError("'get_complete_results()' only works if" +\
                                "'create_comp_result' is True.")

        # Convert the complete restults lists to arrays
        self.res_t = N.array(self.res['t']).reshape([-1, 1])
        self.res_dx = N.array(self.res['dx']).reshape\
                                            ([-1, self.collocator.n_var['dx']])
        self.res_x = N.array(self.res['x']).reshape\
                                            ([-1, self.collocator.n_var['x']])
        self.res_u = N.array(self.res['u']).reshape\
                                            ([-1, self.collocator.n_var['u']])
        if self.collocator.n_var['w'] >= 1:
            self.res_w = N.array(self.res['w']).reshape\
                                            ([-1, self.collocator.n_var['w']])
        else:
            self.res_w = N.array(self.res['w'])
        res_p = N.array(0).reshape(-1)

        if len(self.eliminated_variables) == 0:
            self.res_elim_vars = N.ones([len(self.res['t']), 0])
        else:
            self.res_elim_vars = N.array(self.res['elim_vars']).reshape\
                                            ([-1, len(self.eliminated_variables)])
        res_p = N.array(0).reshape(-1)

        res = (self.res_t, self.res_dx, self.res_x, self.res_u, self.res_w,
               self.p_fixed, res_p, self.res_elim_vars)

        self.collocator.export_result_dymola(self._mpc_result_file_name,
                                             result=res)

        complete_res = ResultDymolaTextual(self._mpc_result_file_name)

        # Create and return result object
        self._result_object_complete = MPCAlgResult(
            self.op, self._mpc_result_file_name, self.collocator, complete_res,
            self.options, self.times, self._sample_nbr, self.sample_period)

        return self._result_object_complete
示例#10
0
        title = "LAPACK QR"
    else:
        raise ValueError
    uneliminable = []
    #~ uneliminable = ['plant.sigma']
    #~ uneliminable = ['plant.sigma', 'der(plant.evaporator.alpha)']
    caus_opts = sp.CausalizationOptions()
    caus_opts['linear_solver'] = linear_solver
    caus_opts['solve_blocks'] = True

    if source != "Modelica":
        raise ValueError
    class_name = "CombinedCycleStartup.Startup6Reference"
    file_paths = (os.path.join(get_files_path(), "CombinedCycle.mo"),
                  os.path.join(get_files_path(), "CombinedCycleStartup.mop"))
    init_res = ResultDymolaTextual('ccpp_init.txt')
    opts = {'generate_html_diagnostics': True}
    model = transfer_model(class_name, file_paths, compiler_options=opts)
    model = sp.BLTModel(model, caus_opts)

    # Get model variable vectors
    model.calculateValuesForDependentParameters()
    var_kinds = {
        'dx': model.DERIVATIVE,
        'x': model.DIFFERENTIATED,
        'w': model.REAL_ALGEBRAIC
    }
    mvar_vectors = {
        'dx':
        N.array([
            var for var in model.getVariables(var_kinds['dx'])
示例#11
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()
with_plots = True
with_plots = False
expand_to_sx = True
#~ expand_to_sx = False
caus_opts = sp.CausalizationOptions()
#~ caus_opts['plots'] = True
#~ caus_opts['draw_blt'] = True
#~ caus_opts['solve_blocks'] = True
#~ caus_opts['inline'] = False
#~ caus_opts['closed_form'] = True
caus_opts['dense_tol'] = 1e10
caus_opts['inline_solved'] = True

#~ sim_res = ResultDymolaTextual(os.path.join(get_files_path(), "vehicle_turn_dymola.txt"))
sim_res = ResultDymolaTextual("opt_result.txt")
start_time = 0.
final_time = sim_res.get_variable_data('time').t[-1]
ncp = 100
class_name = "Car"
file_paths = "turn.mop"
opts = {'generate_html_diagnostics': True, 'state_initial_equations': True}
model = transfer_model(class_name, file_paths, compiler_options=opts)
init_fmu = load_fmu(compile_fmu(class_name, file_paths, compiler_options=opts))

# Create input data
# This would have worked if one input was not constant...
#~ columns = [0]
#~ columns += [sim_res.get_column(input_var.getName()) for input_var in model.getVariables(model.REAL_INPUT)]
#~ input = sim_res.get_data_matrix()[:, columns]
示例#13
0
        opt_opts['IPOPT_options']['ma57_pivtol'] = 1e-4
        opt_opts['IPOPT_options']['ma27_pivtol'] = 1e-4
        opt_opts['IPOPT_options']['ma97_u'] = 1e-4
        opt_opts['IPOPT_options']['ma97_umax'] = 1e-2
        opt_opts['IPOPT_options']['ma57_automatic_scaling'] = "yes"
        opt_opts['IPOPT_options']['mu_strategy'] = "adaptive"
        if problem == "vehicle":
            std_dev[problem] = 0.1
            caus_opts = sp.CausalizationOptions()
            caus_opts['uneliminable'] = [
                'car.Fxf', 'car.Fxr', 'car.Fyf', 'car.Fyr'
            ]
            class_name = "Turn"
            file_paths = os.path.join(get_files_path(), "vehicle_turn.mop")
            init_res = LocalDAECollocationAlgResult(
                result_data=ResultDymolaTextual('vehicle_sol.txt'))
            opt_opts['init_traj'] = init_res
            opt_opts['nominal_traj'] = init_res
            opt_opts['IPOPT_options']['max_cpu_time'] = 30
            opt_opts['n_e'] = 60

            # Set blocking factors
            factors = {
                'delta_u': opt_opts['n_e'] / 2 * [2],
                'Twf_u': opt_opts['n_e'] / 4 * [4],
                'Twr_u': opt_opts['n_e'] / 4 * [4]
            }
            rad2deg = 180. / (2 * np.pi)
            du_bounds = {'delta_u': 2. / rad2deg}
            bf = BlockingFactors(factors, du_bounds=du_bounds)
            opt_opts['blocking_factors'] = bf
示例#14
0
 def setUp(self):
     self.ipopt_nlp.init_opt_ipopt_solve()
     self.nlp.export_result_dymola()
     self.res = ResultDymolaTextual(
         "StaticOptimizationTest_StaticOptimizationTest2_result.txt")
示例#15
0
        else:
            class_name = "Circuit"
            file_paths = "circuit.mo"
            opts = {
                'eliminate_alias_variables': True,
                'generate_html_diagnostics': True,
                'variability_propagation': False
            }
            model = transfer_model(class_name,
                                   file_paths,
                                   compiler_options=opts)
            ncp = 500 * model.get('omega')
            init_fmu = load_fmu(
                compile_fmu(class_name, file_paths, compiler_options=opts))
    elif problem == "vehicle":
        sim_res = ResultDymolaTextual(
            os.path.join(get_files_path(), "vehicle_turn_dymola.txt"))
        start_time = 0.
        final_time = sim_res.get_variable_data('time').t[-1]
        ncp = 500
        if source != "Modelica":
            raise ValueError
        class_name = "Car"
        file_paths = os.path.join(get_files_path(), "vehicle_turn.mop")
        opts = {'generate_html_diagnostics': True}
        model = transfer_model(class_name, file_paths, compiler_options=opts)
        init_fmu = load_fmu(
            compile_fmu(class_name, file_paths, compiler_options=opts))

        # Create input data
        # This would have worked if one input was not constant...
        #~ columns = [0]
示例#16
0
def run_demo(with_plots=True):
    """
    This example is about moving a cart with an attached pendulum from one
    position to another, while starting and ending in steady state and avoiding
    an ellipticla obstacle for the pendulum.

    This example is a part of the third lab in the course FRTN05 Nonlinear
    Control and Servo systems at the Department of Automatic Control at Lund
    University, Sweden. In the lab, the trajectories generated by this script
    are realized by tracking them with linear MPC.

    The model has 4 states: Cart position and velocity, pendulum angle and
    angular velocity. A nearly optimal initial guess has been precomputed and
    is used in this script.
    
    The problem was developed by Pontus Giselsson and is published in
    @InProceedings{mod09pg,
      author = "Giselsson, Pontus and {\AA}kesson, Johan and Robertsson, Anders",
      title = "Optimization of a Pendulum System using {Optimica} and {Modelica}",
      booktitle = "7th International Modelica Conference 2009",
      address = "Como, Italy",
      year = 2009,
      month = sep,
    }
    """
    # Create compiler and compile the pendulum model
    file_path = os.path.join(get_files_path(), "cart_pendulum.mop")
    pend_opt = transfer_optimization_problem("CartPendulum", file_path)

    # Define number of elements in the discretization grid and
    # number of collocation points in each element
    n_e = 150
    n_cp = 3

    # Initialize the optimization problem with precomputed initial guess
    result_file_path = os.path.join(get_files_path(),
                                    'cart_pendulum_result.txt')
    init_res = ResultDymolaTextual(result_file_path)

    # Solve the optimization problem
    opts = pend_opt.optimize_options()
    opts['IPOPT_options']['max_iter'] = 1000
    opts['IPOPT_options']['linear_solver'] = "mumps"
    opts['IPOPT_options']['tol'] = 1e-12
    opts['n_e'] = n_e
    opts['n_cp'] = n_cp
    opts['init_traj'] = init_res
    res = pend_opt.optimize(options=opts)

    # Extract variable profiles and plot the results
    a_ref = res['a_ref']
    x_p = res['x_p']
    y_p = res['y_p']
    t = res['time']

    if with_plots:
        plt.close(1)
        plt.figure(1)
        plt.plot(t, a_ref)
        plt.grid()
        plt.title('Input signal to process ($a_{ref}$)')
        plt.xlabel('Time (s)')
        plt.ylabel('Acceleration $m/s^2$')

        plt.close(2)
        plt.figure(2)
        plt.plot(x_p, y_p)
        plt.grid()
        plt.title('Pendulum end-point path and obstacle')
        plt.xlabel('x-coordinate (m)')
        plt.ylabel('y-coordinate (m)')

        x_obst = N.linspace(-0.35, -0.25)
        y_obst = N.sqrt(1 - ((x_obst + 0.3) / 0.05)**2) * 0.3 - 0.4

        x_track = N.linspace(-1.45, 0.1)
        y_track = N.zeros(N.size(x_track))

        plt.plot(x_obst, y_obst)
        plt.plot(x_track, y_track, '--')

        plt.show()
示例#17
0
            varis_str = ['$u_0$', '$u_1$', '$u_2$', '$u_L$', '$\dot i_L$', '$i_0$',
                         '$i_1$', '$i_2$', '$i_3$']
            edg_indices = [(0, 0), (1, 1), (1, 6), (2, 2), (2, 7), (3, 2), (3, 8),
                           (4, 3), (4, 4), (5, 0), (5, 1), (5, 2), (6, 1), (6, 2),
                           (6, 3), (7, 5), (7, 6), (8, 6), (8, 7), (8, 8)]
        else:
            caus_opts['tear_vars'] = ['i3']
            caus_opts['tear_res'] = [7]
            class_name = "Circuit"
            file_paths = "circuit.mo"
            opts = {'eliminate_alias_variables': False}
            op = transfer_optimization_problem(class_name, file_paths, compiler_options=opts, accept_model=True)
            opt_opts = op.optimize_options()
    elif problem == "vehicle":
        caus_opts['uneliminable'] = ['car.Fxf', 'car.Fxr', 'car.Fyf', 'car.Fyr']
        sim_res = ResultDymolaTextual(os.path.join(get_files_path(), "vehicle_turn_dymola.txt"))
        #~ sim_res = ResultDymolaTextual("vehicle_sol.txt")
        ncp = 500
        if source != "Modelica":
            raise ValueError
        class_name = "Turn"
        file_paths = os.path.join(get_files_path(), "vehicle_turn.mop")
        compiler_opts = {'generate_html_diagnostics': True}
        op = transfer_optimization_problem(class_name, file_paths, compiler_options=compiler_opts)

        opt_opts = op.optimize_options()
        opt_opts['IPOPT_options']['linear_solver'] = "ma57"
        opt_opts['IPOPT_options']['tol'] = 1e-9
        #~ opt_opts['IPOPT_options']['derivative_test'] = "only-second-order"
        #~ opt_opts['IPOPT_options']['hessian_approximation'] = "limited-memory"
        #~ opt_opts['order'] = "reverse"
示例#18
0
plt.rcParams.update({'text.usetex': False})
with_plots = True
#~ with_plots = False
blt = True
#~ blt = False
caus_opts = sp.CausalizationOptions()
#~ caus_opts['plots'] = True
#~ caus_opts['draw_blt'] = True
#~ caus_opts['solve_blocks'] = True
#~ caus_opts['ad_hoc_scale'] = True
#~ caus_opts['inline'] = False
#~ caus_opts['closed_form'] = True
#~ caus_opts['inline_solved'] = True

caus_opts['uneliminable'] = ['car.Fxf', 'car.Fxr', 'car.Fyf', 'car.Fyr']
sim_res = ResultDymolaTextual(
    os.path.join(get_files_path(), "vehicle_turn_dymola.txt"))
ncp = 500
class_name = "Turn"
file_paths = os.path.join(get_files_path(), "vehicle_turn.mop")
compiler_opts = {'generate_html_diagnostics': True}
op = transfer_optimization_problem(class_name,
                                   file_paths,
                                   compiler_options=compiler_opts)

opt_opts = op.optimize_options()
opt_opts['IPOPT_options']['linear_solver'] = "ma27"
opt_opts['IPOPT_options']['tol'] = 1e-9
opt_opts['IPOPT_options']['ma27_pivtol'] = 1e-4
opt_opts['IPOPT_options']['print_kkt_blocks_to_mfile'] = -1
opt_opts['IPOPT_options']['max_iter'] = 200
opt_opts['n_e'] = 37
def run_demo(with_plots=True):
    """
    This example solves the optimization problem from pyjmi.examples.ccpp using the Python-based symbolic elimination.
    """
    # Load initial gues
    init_path = os.path.join(get_files_path(), "ccpp_init.txt")
    init_res = LocalDAECollocationAlgResult(
        result_data=ResultDymolaTextual(init_path))

    # Compile model
    class_name = "CombinedCycleStartup.Startup6"
    file_paths = (os.path.join(get_files_path(), "CombinedCycle.mo"),
                  os.path.join(get_files_path(), "CombinedCycleStartup.mop"))
    compiler_options = {'equation_sorting': True, 'automatic_tearing': True}
    op = transfer_optimization_problem("CombinedCycleStartup.Startup6",
                                       file_paths, compiler_options)

    # Set elimination options
    elim_opts = EliminationOptions()
    elim_opts['ineliminable'] = ['plant.sigma']
    if with_plots:
        elim_opts['draw_blt'] = True

    # Eliminate algebraic variables
    op = BLTOptimizationProblem(op, elim_opts)

    # Set collocation options
    opt_opts = op.optimize_options()
    opt_opts['init_traj'] = init_res
    opt_opts['nominal_traj'] = init_res

    # Solve the optimal control problem
    opt_res = op.optimize(options=opt_opts)

    # Extract variable profiles
    opt_plant_p = opt_res['plant.p']
    opt_plant_sigma = opt_res['plant.sigma']
    opt_plant_load = opt_res['plant.load']
    opt_time = opt_res['time']

    # Plot the optimized trajectories
    if with_plots:
        plt.close(2)
        plt.figure(2)
        plt.subplot(3, 1, 1)
        plt.plot(opt_time, opt_plant_p * 1e-6)
        plt.ylabel('evaporator pressure [MPa]')
        plt.grid(True)
        plt.title('Optimized trajectories')

        plt.subplot(3, 1, 2)
        plt.plot(opt_time, opt_plant_sigma * 1e-6)
        plt.grid(True)
        plt.ylabel('turbine thermal stress [MPa]')

        plt.subplot(3, 1, 3)
        plt.plot(opt_time, opt_plant_load)
        plt.grid(True)
        plt.ylabel('input load [1]')
        plt.xlabel('time [s]')

    # Verify solution for testing purposes
    try:
        import casadi
    except:
        pass
    else:
        cost = float(opt_res.solver.solver_object.getOutput('f'))
        N.testing.assert_allclose(cost, 17492.465548193624, rtol=1e-5)