Esempio n. 1
0
    def test_par_est(self):
        """
        Test parameter estimation.
        """
        cost_ref = 1.1109779e-2
        u_norm_ref = 0.556018602

        model = self.model_illust
        op = self.op_illust_est_automatic

        # Simulate with nominal parameters
        n_meas = 16
        sim_res = model.simulate(input=('u', lambda t: -0.2 + N.sin(t)),
                                 final_time=4.,
                                 options={
                                     'ncp': n_meas,
                                     'CVode_options': {
                                         'rtol': 1e-10
                                     }
                                 })

        # Assemble external data by adding noise to simulation
        Q = N.diag([1., 1.])
        N.random.seed(1)
        t_meas = sim_res['time']
        sigma = 0.05
        x1_meas = sim_res['x1'] + sigma * N.random.randn(n_meas + 1)
        x2_meas = sim_res['x2'] + sigma * N.random.randn(n_meas + 1)
        u_meas = sim_res['u']
        data_x1 = N.vstack([t_meas, x1_meas])
        data_x2 = N.vstack([t_meas, x2_meas])
        data_u1 = N.vstack([t_meas, u_meas])
        quad_pen = OrderedDict()
        quad_pen['x1'] = data_x1
        quad_pen['x2'] = data_x2
        eliminated = OrderedDict()
        eliminated['u'] = data_u1
        external_data = ExternalData(Q=Q,
                                     quad_pen=quad_pen,
                                     eliminated=eliminated)

        # Eliminate
        blt_op = BLTOptimizationProblem(op)

        # Check remaining variables
        alg_vars = sorted([
            var.getName() for var in blt_op.getVariables(blt_op.REAL_ALGEBRAIC)
            if not var.isAlias()
        ])
        assert len(alg_vars) == 3

        # Set up options
        dae_opts = op.optimize_options()
        dae_opts['init_traj'] = sim_res
        dae_opts['nominal_traj'] = sim_res
        dae_opts['external_data'] = external_data
        blt_opts = blt_op.optimize_options()
        blt_opts['init_traj'] = sim_res
        blt_opts['nominal_traj'] = sim_res
        blt_opts['external_data'] = external_data

        # Optimize and check result
        res_dae = op.optimize(options=dae_opts)
        res_blt = blt_op.optimize(options=blt_opts)
        assert_results(res_dae, cost_ref, u_norm_ref, u_norm_rtol=1e-2)
        assert_results(res_blt, cost_ref, u_norm_ref, u_norm_rtol=1e-2)
        N.testing.assert_allclose([res_dae['p1'][0], res_dae['p3'][0]],
                                  [2.022765, 0.992965],
                                  rtol=2e-3)
        N.testing.assert_allclose([res_blt['p1'][0], res_blt['p3'][0]],
                                  [2.022765, 0.992965],
                                  rtol=2e-3)
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)