Пример #1
0
def run_demo(with_plots=True):
    """
    An example on how to simulate a model using the DAE simulator. The result 
    can be compared with that of sim_rlc.py which has solved the same problem 
    using dymola. Also writes information to a file.
    """

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

    model_name = "RLC_Circuit"
    mofile = curr_dir + "/files/RLC_Circuit.mo"

    jmu_name = compile_jmu(model_name, mofile)
    model = JMUModel(jmu_name)
    init_res = model.initialize()

    (E_dae, A_dae, B_dae, F_dae, g_dae, state_names, input_names, algebraic_names, dx0, x0, u0, w0, t0) = linearize_dae(
        init_res.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)

    res1 = model.simulate()

    jmu_name = compile_jmu("RLC_Circuit_Linearized", mofile)
    lin_model = JMUModel(jmu_name)
    res2 = lin_model.simulate()

    c_v_1 = res1["capacitor.v"]
    i_p_i_1 = res1["inductor.p.i"]
    i_p1_i_1 = res1["inductor1.p.i"]
    t_1 = res1["time"]

    c_v_2 = res2["x[1]"]
    i_p_i_2 = res2["x[2]"]
    i_p1_i_2 = res2["x[3]"]
    t_2 = res2["time"]

    assert N.abs(res1.final("capacitor.v") - res2.final("x[1]")) < 1e-3

    if with_plots:
        p.figure(1)
        p.hold(True)
        p.subplot(311)
        p.plot(t_1, c_v_1)
        p.plot(t_2, c_v_2, "g")
        p.ylabel("c.v")
        p.legend(("original model", "linearized ODE"))
        p.grid()
        p.subplot(312)
        p.plot(t_1, i_p_i_1)
        p.plot(t_2, i_p_i_2, "g")
        p.ylabel("i.p.i")
        p.grid()
        p.subplot(313)
        p.plot(t_1, i_p1_i_1)
        p.plot(t_2, i_p1_i_2, "g")
        p.ylabel("i.p1.i")
        p.grid()
        p.show()
Пример #2
0
def run_demo(with_plots=True):
    """
    Demonstrate how to solve and calculate sensitivity for initial conditions.
    See "http://sundials.2283335.n4.nabble.com/Forward-sensitivities-for-  \
               initial-conditions-td3239724.html"
    """
    curr_dir = os.path.dirname(os.path.abspath(__file__));
    
    jmu_name = compile_jmu("LeadTransport", curr_dir+"/files/leadtransport.mop")
    model = JMUModel(jmu_name)
    
    opts = model.simulate_options()
    opts["IDA_options"]["sensitivity"] = True
    opts["IDA_options"]["rtol"] = 1e-7
    opts["IDA_options"]["suppress_sens"] = False #Use the sensitivity variablers
                                                 #in the error test.
    
    res = model.simulate(final_time=400, options=opts)

    # Extract variable profiles
    y1,y2,y3 = res['y1'], res["y2"], res["y3"]
    dy1p1,dy2p1,dy3p1 = res['dy1/dp1'], res['dy2/dp1'], res['dy3/dp1']
    dy1p2,dy2p2,dy3p2 = res['dy1/dp2'], res['dy2/dp2'], res['dy3/dp2']
    dy1p3,dy2p3,dy3p3 = res['dy1/dp3'], res['dy2/dp3'], res['dy3/dp3']
    t=res['time']
    
    assert N.abs(res.initial('dy1/dp1') - 1.000) < 1e-3
    assert N.abs(res.initial('dy1/dp2') - 1.000) < 1e-3
    assert N.abs(res.initial('dy2/dp2') - 1.000) < 1e-3 

    if with_plots:
        # Plot
        plt.figure(1)
        plt.clf()
        plt.subplot(221)
        plt.plot(t,y1,t,y2,t,y3)
        plt.grid()
        plt.legend(("y1","y2","y3"))
        
        plt.subplot(222)
        plt.plot(t,dy1p1,t,dy2p1,t,dy3p1)
        plt.grid()
        plt.legend(("dy1/dp1","dy2/dp1","dy3/dp1"))
        
        plt.subplot(223)
        plt.plot(t,dy1p2,t,dy2p2,t,dy3p2)
        plt.grid()
        plt.legend(("dy1/dp2","dy2/dp2","dy3/dp2"))
        
        plt.subplot(224)
        plt.plot(t,dy1p3,t,dy2p3,t,dy3p3)
        plt.grid()
        plt.legend(("dy1/dp3","dy2/dp3","dy3/dp3"))
        plt.suptitle("Lead transport through the body")
        plt.show()
Пример #3
0
def run_simulation_with_inputs(time, price, pv, bldg, plot = False):
    """
    This function runs a simulation that uses inputs data series
    """
    
    # get current directory
    curr_dir = os.path.dirname(os.path.abspath(__file__));
    
    # compile FMU
    path = os.path.join(curr_dir,"..","Models","ElectricalNetwork.mop")
    jmu_model = compile_jmu('ElectricNetwork.Network', path)

    # Load the model instance into Python
    model = JMUModel(jmu_model)
    
    # create input data series for price and current battery
    Npoints = len(time)
    
    # for the simulation no current flow
    Ibatt  = np.zeros(Npoints)
    
    # Build input trajectory matrix for use in simulation
    u = np.transpose(np.vstack((t_data, Ibatt, price, np.squeeze(pv[:,0]), np.squeeze(pv[:,1]), \
                                np.squeeze(pv[:,2]), np.squeeze(bldg[:,0]), np.squeeze(bldg[:,1]), np.squeeze(bldg[:,2]))))
    
    # Solve the DAE initialization system
    model.initialize()
    
    # Simulate
    res = model.simulate(input=(['Ibatt', 'price', 'pv1', 'pv2', 'pv3', 'bldg1', 'bldg2', 'bldg3'], u), start_time=0., final_time=24.0*3600.0)
    
    # Extract variable profiles
    Vs_init_sim = res['Vs']
    V1_init_sim = res['V1']
    V2_init_sim = res['V2']
    V3_init_sim = res['V3']
    E_init_sim = res['E']
    SOC_init_sim = res['SOC']
    Money_init_sim = res['Money']
    price_init_sim = res['price']
    t_init_sim = res['time']
    
    # plot results
    if plot:
        plotFunction(t_init_sim, Vs_init_sim, V1_init_sim, V2_init_sim, \
                 V3_init_sim, E_init_sim, SOC_init_sim, Money_init_sim, price_init_sim)
    
    return res
Пример #4
0
def run_simulation_with_inputs(time, price, pv, bldg, plot = False, usePV = True):
    """
    This function runs a simulation that uses inputs data series
    """
    
    # get current directory
    curr_dir = os.path.dirname(os.path.abspath(__file__));
    
    # compile FMU
    path = os.path.join(curr_dir,"..","Models","ElectricalNetwork.mop")
    jmu_model = compile_jmu('ElectricNetwork.ACnetwork', path)

    # Load the model instance into Python
    model = JMUModel(jmu_model)
    
    # create input data series for price and current battery
    Npoints = len(time)
    
    # for the simulation no power flow in the battery
    P  = np.zeros(Npoints)
    Q  = np.zeros(Npoints)
    
    # if pv panels are not used then remove power
    if usePV == False:
        pv = np.zeros(np.shape(pv))
    
    # Build input trajectory matrix for use in simulation
    u = np.transpose(np.vstack((t_data, P, Q, price, -np.squeeze(bldg[:,0]), -np.squeeze(bldg[:,1]), -np.squeeze(bldg[:,2]), \
                                np.squeeze(pv[:,0]), np.squeeze(pv[:,1]), np.squeeze(pv[:,2]))))
    
    # Solve the DAE initialization system
    model.initialize()
    
    # Simulate
    res = model.simulate(input=(['P_batt', 'Q_batt', 'price', 'P_bldg1', 'P_bldg2', 'P_bldg3', 'P_pv1', 'P_pv2', 'P_pv3'], u), start_time=0., final_time=24.0*3600.0)
    
    # Extract variable profiles
    if plot:
        plotFunction(res)
        
    return res
Пример #5
0
def run_simulation(plot = False):
    """
    This function runs a simple simulation without input data
    """
    
    # get current directory
    curr_dir = os.path.dirname(os.path.abspath(__file__));
    
    # compile FMU
    path = os.path.join(curr_dir,"..","Models","ElectricalNetwork.mop")
    jmu_model = compile_jmu('ElectricNetwork.NetworkSim', path)

    # Load the model instance into Python
    model = JMUModel(jmu_model)
  
    # Solve the DAE initialization system
    model.initialize()
    
    # Simulate
    res = model.simulate(start_time=0., final_time=24.0*3600.0)
    
    # Extract variable profiles
    Vs_init_sim = res['n.Vs']
    V1_init_sim = res['n.V1']
    V2_init_sim = res['n.V2']
    V3_init_sim = res['n.V3']
    E_init_sim = res['n.E']
    SOC_init_sim = res['n.SOC']
    Money_init_sim = res['n.Money']
    price_init_sim = res['n.price']
    t_init_sim = res['time']
    
    # plot results
    if plot:
        plotFunction(t_init_sim, Vs_init_sim, V1_init_sim, V2_init_sim, \
                 V3_init_sim, E_init_sim, SOC_init_sim, Money_init_sim, price_init_sim)
Пример #6
0
def run_demo(with_plots=True):
    """
    This example is based on the Hicks-Ray Continuously Stirred Tank Reactors 
    (CSTR) system. The system has two states, the concentration and the 
    temperature. The control input to the system is the temperature of the 
    cooling flow in the reactor jacket. The chemical reaction in the reactor is 
    exothermic, and also temperature dependent; high temperature results in high 
    reaction rate.
    
    The example demonstrates the following steps:
    
    1. How to solve a DAE initialization problem. The initialization model have 
       equations specifying that all derivatives should be identically zero, 
       which implies that a stationary solution is obtained. Two stationary 
       points, corresponding to different inputs, are computed. We call the 
       stationary points A and B respectively. point A corresponds to operating 
       conditions where the reactor is cold and the reaction rate is low, 
       whereas point B corresponds to a higher temperature where the reaction 
       rate is high.

       For more information about the DAE initialization algorithm, see
       http://www.jmodelica.org/page/10.

    2. How to generate an initial guess for a direct collocation method by means 
       of simulation. The trajectories resulting from simulation are used to 
       initialize the variables in the transcribed NLP.
       
    3. An optimal control problem is solved where the objective Is to transfer 
       the state of the system from stationary point A to point B. The challenge 
       is to ignite the reactor while avoiding uncontrolled temperature 
       increase. It is also demonstrated how to set parameter and variable 
       values in a model.

       More information about the simultaneous optimization algorithm can be 
       found at http://www.jmodelica.org/page/10.

    4. The optimization result is saved to file and then the important variables 
       are plotted.

    5. Simulate the system with the optimal control profile. This step is 
       important in order to verify that the approximation in the transcription 
       step is valid.
"""

    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"), 
        compiler_options={"enable_variable_scaling":True})
    
    # load the JMU
    init_model = JMUModel(jmu_name)
    
    # Set inputs for Stationary point A
    Tc_0_A = 250
    init_model.set('Tc',Tc_0_A)
        
    # Solve the DAE initialization system with Ipopt
    init_result = init_model.initialize()
    
    # Store stationary point A
    c_0_A = init_result['c'][0]
    T_0_A = init_result['T'][0]
    
    # 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
    init_model.set('Tc',Tc_0_B)
        
    # Solve the DAE initialization system with Ipopt
    init_result = init_model.initialize()
    # Store stationary point B
    c_0_B = init_result['c'][0]
    T_0_B = init_result['T'][0]

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

    # Compute initial guess trajectories by means of simulation
    # Compile the optimization initialization model
    jmu_name = compile_jmu("CSTR.CSTR_Init_Optimization", 
        os.path.join(curr_dir, "files", "CSTR.mop"))

    # Load the model
    init_sim_model = JMUModel(jmu_name)

    # Set model parameters
    init_sim_model.set('cstr.c_init',c_0_A)
    init_sim_model.set('cstr.T_init',T_0_A)
    init_sim_model.set('c_ref',c_0_B)
    init_sim_model.set('T_ref',T_0_B)
    init_sim_model.set('Tc_ref',Tc_0_B)

    res = init_sim_model.simulate(start_time=0.,final_time=150.)
    
    # Extract variable profiles
    c_init_sim=res['cstr.c']
    T_init_sim=res['cstr.T']
    Tc_init_sim=res['cstr.Tc']
    t_init_sim = res['time']

    # Plot the results
    if with_plots:
        plt.figure(1)
        plt.clf()
        plt.hold(True)
        plt.subplot(311)
        plt.plot(t_init_sim,c_init_sim)
        plt.grid()
        plt.ylabel('Concentration')

        plt.subplot(312)
        plt.plot(t_init_sim,T_init_sim)
        plt.grid()
        plt.ylabel('Temperature')

        plt.subplot(313)
        plt.plot(t_init_sim,Tc_init_sim)
        plt.grid()
        plt.ylabel('Cooling temperature')
        plt.xlabel('time')
        plt.show()

    # Solve the optimal control problem
    # Compile model
    jmu_name = compile_jmu("CSTR.CSTR_Opt", curr_dir+"/files/CSTR.mop")

    # Load model
    cstr = JMUModel(jmu_name)

    # Set reference values
    cstr.set('Tc_ref',Tc_0_B)
    cstr.set('c_ref',c_0_B)
    cstr.set('T_ref',T_0_B)

    # Set initial values
    cstr.set('cstr.c_init',c_0_A)
    cstr.set('cstr.T_init',T_0_A)

    n_e = 100 # Number of elements 

    # Set options
    opt_opts = cstr.optimize_options()
    opt_opts['n_e'] = n_e
    opt_opts['init_traj'] = res.result_data

    res = cstr.optimize(options=opt_opts)

    # Extract variable profiles
    c_res=res['cstr.c']
    T_res=res['cstr.T']
    Tc_res=res['cstr.Tc']
    time_res = res['time']

    c_ref=res['c_ref']
    T_ref=res['T_ref']
    Tc_ref=res['Tc_ref']

    assert N.abs(res.final('cost')/1.e7 - 1.8585429) < 1e-3  

    # Plot the results
    if with_plots:
        plt.figure(2)
        plt.clf()
        plt.hold(True)
        plt.subplot(311)
        plt.plot(time_res,c_res)
        plt.plot([time_res[0],time_res[-1]],[c_ref,c_ref],'--')
        plt.grid()
        plt.ylabel('Concentration')

        plt.subplot(312)
        plt.plot(time_res,T_res)
        plt.plot([time_res[0],time_res[-1]],[T_ref,T_ref],'--')
        plt.grid()
        plt.ylabel('Temperature')

        plt.subplot(313)
        plt.plot(time_res,Tc_res)
        plt.plot([time_res[0],time_res[-1]],[Tc_ref,Tc_ref],'--')
        plt.grid()
        plt.ylabel('Cooling temperature')
        plt.xlabel('time')
        plt.show()

    # Simulate to verify the optimal solution
    # Set up the input trajectory
    t = time_res 
    u = Tc_res
    u_traj = N.transpose(N.vstack((t,u)))
    
    # Compile the Modelica model to a JMU
    jmu_name = compile_jmu("CSTR.CSTR", curr_dir+"/files/CSTR.mop")

    # Load model
    sim_model = JMUModel(jmu_name)

    sim_model.set('c_init',c_0_A)
    sim_model.set('T_init',T_0_A)
    sim_model.set('Tc',u[0])

    res = sim_model.simulate(start_time=0.,final_time=150.,
        input=('Tc',u_traj))
    
    # Extract variable profiles
    c_sim=res['c']
    T_sim=res['T']
    Tc_sim=res['Tc']
    time_sim = res['time']

    # Plot the results
    if with_plots:
        plt.figure(3)
        plt.clf()
        plt.hold(True)
        plt.subplot(311)
        plt.plot(time_res,c_res,'--')
        plt.plot(time_sim,c_sim)
        plt.legend(('optimized','simulated'))
        plt.grid()
        plt.ylabel('Concentration')

        plt.subplot(312)
        plt.plot(time_res,T_res,'--')
        plt.plot(time_sim,T_sim)
        plt.legend(('optimized','simulated'))
        plt.grid()
        plt.ylabel('Temperature')

        plt.subplot(313)
        plt.plot(time_res,Tc_res,'--')
        plt.plot(time_sim,Tc_sim)
        plt.legend(('optimized','simulated'))
        plt.grid()
        plt.ylabel('Cooling temperature')
        plt.xlabel('time')
        plt.show()
Пример #7
0
def run_demo(with_plots=True):
    """
    This example demonstrates how to solve parameter estimation problmes.

    The data used in the example was recorded by Kristian Soltesz at the 
    Department of Automatic Control. 
    """
    
    curr_dir = os.path.dirname(os.path.abspath(__file__));

    # Load measurement data from file
    data = loadmat(curr_dir+'/files/qt_par_est_data.mat',appendmat=False)

    # Extract data series
    t_meas = data['t'][6000::100,0]-60
    y1_meas = data['y1_f'][6000::100,0]/100
    y2_meas = data['y2_f'][6000::100,0]/100
    y3_meas = data['y3_d'][6000::100,0]/100
    y4_meas = data['y4_d'][6000::100,0]/100
    u1 = data['u1_d'][6000::100,0]
    u2 = data['u2_d'][6000::100,0]
        
    # Plot measurements and inputs
    if with_plots:
        plt.figure(1)
        plt.clf()
        plt.subplot(2,2,1)
        plt.plot(t_meas,y3_meas)
        plt.title('x3')
        plt.grid()
        plt.subplot(2,2,2)
        plt.plot(t_meas,y4_meas)
        plt.title('x4')
        plt.grid()
        plt.subplot(2,2,3)
        plt.plot(t_meas,y1_meas)
        plt.title('x1')
        plt.xlabel('t[s]')
        plt.grid()
        plt.subplot(2,2,4)
        plt.plot(t_meas,y2_meas)
        plt.title('x2')
        plt.xlabel('t[s]')
        plt.grid()

        plt.figure(2)
        plt.clf()
        plt.subplot(2,1,1)
        plt.plot(t_meas,u1)
        plt.hold(True)
        plt.title('u1')
        plt.grid()
        plt.subplot(2,1,2)
        plt.plot(t_meas,u2)
        plt.title('u2')
        plt.xlabel('t[s]')
        plt.hold(True)
        plt.grid()

    # Build input trajectory matrix for use in simulation
    u = N.transpose(N.vstack((t_meas,u1,u2)))

    # compile FMU
    fmu_name = compile_fmu('QuadTankPack.Sim_QuadTank', 
        curr_dir+'/files/QuadTankPack.mop')

    # Load model
    model = load_fmu(fmu_name)
    
    # Simulate model response with nominal parameters
    res = model.simulate(input=(['u1','u2'],u),start_time=0.,final_time=60)

    # Load simulation result
    x1_sim = res['qt.x1']
    x2_sim = res['qt.x2']
    x3_sim = res['qt.x3']
    x4_sim = res['qt.x4']
    t_sim  = res['time']
    
    u1_sim = res['u1']
    u2_sim = res['u2']

    # Plot simulation result
    if with_plots:
        plt.figure(1)
        plt.subplot(2,2,1)
        plt.plot(t_sim,x3_sim)
        plt.subplot(2,2,2)
        plt.plot(t_sim,x4_sim)
        plt.subplot(2,2,3)
        plt.plot(t_sim,x1_sim)
        plt.subplot(2,2,4)
        plt.plot(t_sim,x2_sim)

        plt.figure(2)
        plt.subplot(2,1,1)
        plt.plot(t_sim,u1_sim,'r')
        plt.subplot(2,1,2)
        plt.plot(t_sim,u2_sim,'r')

    # Compile parameter optimization model
    jmu_name = compile_jmu("QuadTankPack.QuadTank_ParEst",
        curr_dir+"/files/QuadTankPack.mop")

    # Load the model
    qt_par_est = JMUModel(jmu_name)

    # Number of measurement points
    N_meas = N.size(u1,0)

    # Set measurement data into model
    for i in range(0,N_meas):
        qt_par_est.set("t_meas["+`i+1`+"]",t_meas[i])
        qt_par_est.set("y1_meas["+`i+1`+"]",y1_meas[i])
        qt_par_est.set("y2_meas["+`i+1`+"]",y2_meas[i])

    n_e = 30 # Numer of element in collocation algorithm

    # Get an options object for the optimization algorithm
    opt_opts = qt_par_est.optimize_options()
    # Set the number of collocation points
    opt_opts['n_e'] = n_e

    opt_opts['init_traj'] = res.result_data
    
    # Solve parameter optimization problem
    res = qt_par_est.optimize(options=opt_opts)

    # Extract optimal values of parameters
    a1_opt = res.final("qt.a1")
    a2_opt = res.final("qt.a2")

    # Print optimal parameter values
    print('a1: ' + str(a1_opt*1e4) + 'cm^2')
    print('a2: ' + str(a2_opt*1e4) + 'cm^2')

    assert N.abs(a1_opt*1.e6 - 2.6574) < 1e-3 
    assert N.abs(a2_opt*1.e6 - 2.7130) < 1e-3

    # Load state profiles
    x1_opt = res["qt.x1"]
    x2_opt = res["qt.x2"]
    x3_opt = res["qt.x3"]
    x4_opt = res["qt.x4"]
    u1_opt = res["qt.u1"]
    u2_opt = res["qt.u2"]
    t_opt  = res["time"]

    # Plot
    if with_plots:
        plt.figure(1)
        plt.subplot(2,2,1)
        plt.plot(t_opt,x3_opt,'k')
        plt.subplot(2,2,2)
        plt.plot(t_opt,x4_opt,'k')
        plt.subplot(2,2,3)
        plt.plot(t_opt,x1_opt,'k')
        plt.subplot(2,2,4)
        plt.plot(t_opt,x2_opt,'k')

    # Compile second parameter estimation model
    jmu_name = compile_jmu("QuadTankPack.QuadTank_ParEst2", 
        curr_dir+"/files/QuadTankPack.mop")

    # Load model
    qt_par_est2 = JMUModel(jmu_name)
    
    # Number of measurement points
    N_meas = N.size(u1,0)

    # Set measurement data into model
    for i in range(0,N_meas):
        qt_par_est2.set("t_meas["+`i+1`+"]",t_meas[i])
        qt_par_est2.set("y1_meas["+`i+1`+"]",y1_meas[i])
        qt_par_est2.set("y2_meas["+`i+1`+"]",y2_meas[i])
        qt_par_est2.set("y3_meas["+`i+1`+"]",y3_meas[i])
        qt_par_est2.set("y4_meas["+`i+1`+"]",y4_meas[i])

    # Solve parameter estimation problem
    res_opt2 = qt_par_est2.optimize(options=opt_opts)

    # Get optimal parameter values
    a1_opt2 = res_opt2.final("qt.a1")
    a2_opt2 = res_opt2.final("qt.a2")
    a3_opt2 = res_opt2.final("qt.a3")
    a4_opt2 = res_opt2.final("qt.a4")

    # Print optimal parameter values 
    print('a1:' + str(a1_opt2*1e4) + 'cm^2')
    print('a2:' + str(a2_opt2*1e4) + 'cm^2')
    print('a3:' + str(a3_opt2*1e4) + 'cm^2')
    print('a4:' + str(a4_opt2*1e4) + 'cm^2')

    assert N.abs(a1_opt2*1.e6 - 2.6579) < 1e-3, "Wrong value of parameter a1"  
    assert N.abs(a2_opt2*1.e6 - 2.7038) < 1e-3, "Wrong value of parameter a2"  
    assert N.abs(a3_opt2*1.e6 - 3.0031) < 1e-3, "Wrong value of parameter a3"  
    assert N.abs(a4_opt2*1.e6 - 2.9342) < 1e-3, "Wrong value of parameter a4"  

    # Extract state and input profiles
    x1_opt2 = res_opt2["qt.x1"]
    x2_opt2 = res_opt2["qt.x2"]
    x3_opt2 = res_opt2["qt.x3"]
    x4_opt2 = res_opt2["qt.x4"]
    u1_opt2 = res_opt2["qt.u1"]
    u2_opt2 = res_opt2["qt.u2"]
    t_opt2  = res_opt2["time"]

    # Plot
    if with_plots:
        plt.figure(1)
        plt.subplot(2,2,1)
        plt.plot(t_opt2,x3_opt2,'r')
        plt.subplot(2,2,2)
        plt.plot(t_opt2,x4_opt2,'r')
        plt.subplot(2,2,3)
        plt.plot(t_opt2,x1_opt2,'r')
        plt.subplot(2,2,4)
        plt.plot(t_opt2,x2_opt2,'r')
        plt.show()

    # Compute parameter standard deviations for case 1
    # compile JMU
    jmu_name = compile_jmu('QuadTankPack.QuadTank_Sens1',
                           curr_dir+'/files/QuadTankPack.mop')

    # Load model
    model = JMUModel(jmu_name)

    model.set('a1',a1_opt)
    model.set('a2',a2_opt)
    
    sens_opts = model.simulate_options()

    # Enable sensitivity computations
    sens_opts['IDA_options']['sensitivity'] = True
    #sens_opts['IDA_options']['atol'] = 1e-12

    # Simulate sensitivity equations
    sens_res = model.simulate(input=(['u1','u2'],u),start_time=0.,final_time=60, options = sens_opts)

    # Get result trajectories
    x1_sens = sens_res['x1']
    x2_sens = sens_res['x2']
    dx1da1 = sens_res['dx1/da1']
    dx1da2 = sens_res['dx1/da2']
    dx2da1 = sens_res['dx2/da1']
    dx2da2 = sens_res['dx2/da2']
    t_sens = sens_res['time']
    
    # Compute Jacobian

    # Create a trajectory object for interpolation
    traj=TrajectoryLinearInterpolation(t_sens,N.transpose(N.vstack((x1_sens,x2_sens,dx1da1,dx1da2,dx2da1,dx2da2))))

    # Jacobian
    jac = N.zeros((61*2,2))

    # Error vector
    err = N.zeros(61*2)

    # Extract Jacobian and error information
    i = 0
    for t_p in t_meas:
        vals = traj.eval(t_p)
        for j in range(2):
            for k in range(2):
                jac[i+j,k] = vals[0,2*j+k+2]
            err[i] = vals[0,0] - y1_meas[i/2]
            err[i+1] = vals[0,1] - y2_meas[i/2]
        i = i + 2

    # Compute estimated variance of measurement noice    
    v_err = N.sum(err**2)/(61*2-2)

    # Compute J^T*J
    A = N.dot(N.transpose(jac),jac)

    # Compute parameter covariance matrix
    P = v_err*N.linalg.inv(A)

    # Compute standard deviations for parameters
    sigma_a1 = N.sqrt(P[0,0])
    sigma_a2 = N.sqrt(P[1,1])

    print "a1: " + str(sens_res['a1']) + ", standard deviation: " + str(sigma_a1)
    print "a2: " + str(sens_res['a2']) + ", standard deviation: " + str(sigma_a2)

    # Compute parameter standard deviations for case 2
    # compile JMU
    jmu_name = compile_jmu('QuadTankPack.QuadTank_Sens2',
                           curr_dir+'/files/QuadTankPack.mop')

    # Load model
    model = JMUModel(jmu_name)

    model.set('a1',a1_opt2)
    model.set('a2',a2_opt2)
    model.set('a3',a3_opt2)
    model.set('a4',a4_opt2)
    
    sens_opts = model.simulate_options()

    # Enable sensitivity computations
    sens_opts['IDA_options']['sensitivity'] = True
    #sens_opts['IDA_options']['atol'] = 1e-12

    # Simulate sensitivity equations
    sens_res = model.simulate(input=(['u1','u2'],u),start_time=0.,final_time=60, options = sens_opts)

    # Get result trajectories
    x1_sens = sens_res['x1']
    x2_sens = sens_res['x2']
    x3_sens = sens_res['x3']
    x4_sens = sens_res['x4']
    
    dx1da1 = sens_res['dx1/da1']
    dx1da2 = sens_res['dx1/da2']
    dx1da3 = sens_res['dx1/da3']
    dx1da4 = sens_res['dx1/da4']

    dx2da1 = sens_res['dx2/da1']
    dx2da2 = sens_res['dx2/da2']
    dx2da3 = sens_res['dx2/da3']
    dx2da4 = sens_res['dx2/da4']

    dx3da1 = sens_res['dx3/da1']
    dx3da2 = sens_res['dx3/da2']
    dx3da3 = sens_res['dx3/da3']
    dx3da4 = sens_res['dx3/da4']

    dx4da1 = sens_res['dx4/da1']
    dx4da2 = sens_res['dx4/da2']
    dx4da3 = sens_res['dx4/da3']
    dx4da4 = sens_res['dx4/da4']
    t_sens = sens_res['time']
    
    # Compute Jacobian

    # Create a trajectory object for interpolation
    traj=TrajectoryLinearInterpolation(t_sens,N.transpose(N.vstack((x1_sens,x2_sens,x3_sens,x4_sens,
                                                                    dx1da1,dx1da2,dx1da3,dx1da4,
                                                                    dx2da1,dx2da2,dx2da3,dx2da4,
                                                                    dx3da1,dx3da2,dx3da3,dx3da4,
                                                                    dx4da1,dx4da2,dx4da3,dx4da4))))

    # Jacobian
    jac = N.zeros((61*4,4))

    # Error vector
    err = N.zeros(61*4)

    # Extract Jacobian and error information
    i = 0
    for t_p in t_meas:
        vals = traj.eval(t_p)
        for j in range(4):
            for k in range(4):
                jac[i+j,k] = vals[0,4*j+k+4]
            err[i] = vals[0,0] - y1_meas[i/4]
            err[i+1] = vals[0,1] - y2_meas[i/4]
            err[i+2] = vals[0,2] - y3_meas[i/4]
            err[i+3] = vals[0,3] - y4_meas[i/4]
        i = i + 4

    # Compute estimated variance of measurement noice    
    v_err = N.sum(err**2)/(61*4-4)

    # Compute J^T*J
    A = N.dot(N.transpose(jac),jac)

    # Compute parameter covariance matrix
    P = v_err*N.linalg.inv(A)

    # Compute standard deviations for parameters
    sigma_a1 = N.sqrt(P[0,0])
    sigma_a2 = N.sqrt(P[1,1])
    sigma_a3 = N.sqrt(P[2,2])
    sigma_a4 = N.sqrt(P[3,3])

    print "a1: " + str(sens_res['a1']) + ", standard deviation: " + str(sigma_a1)
    print "a2: " + str(sens_res['a2']) + ", standard deviation: " + str(sigma_a2)
    print "a3: " + str(sens_res['a3']) + ", standard deviation: " + str(sigma_a3)
    print "a4: " + str(sens_res['a4']) + ", standard deviation: " + str(sigma_a4)
Пример #8
0
def run_demo(with_plots=True):
    """
    This example demonstrates how to solve parameter estimation problmes.

    The data used in the example was recorded by Kristian Soltesz at the 
    Department of Automatic Control. 
    """

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

    # Load measurement data from file
    data = loadmat(curr_dir + '/files/qt_par_est_data.mat', appendmat=False)

    # Extract data series
    t_meas = data['t'][6000::100, 0] - 60
    y1_meas = data['y1_f'][6000::100, 0] / 100
    y2_meas = data['y2_f'][6000::100, 0] / 100
    y3_meas = data['y3_d'][6000::100, 0] / 100
    y4_meas = data['y4_d'][6000::100, 0] / 100
    u1 = data['u1_d'][6000::100, 0]
    u2 = data['u2_d'][6000::100, 0]

    # Plot measurements and inputs
    if with_plots:
        plt.figure(1)
        plt.clf()
        plt.subplot(2, 2, 1)
        plt.plot(t_meas, y3_meas)
        plt.title('x3')
        plt.grid()
        plt.subplot(2, 2, 2)
        plt.plot(t_meas, y4_meas)
        plt.title('x4')
        plt.grid()
        plt.subplot(2, 2, 3)
        plt.plot(t_meas, y1_meas)
        plt.title('x1')
        plt.xlabel('t[s]')
        plt.grid()
        plt.subplot(2, 2, 4)
        plt.plot(t_meas, y2_meas)
        plt.title('x2')
        plt.xlabel('t[s]')
        plt.grid()

        plt.figure(2)
        plt.clf()
        plt.subplot(2, 1, 1)
        plt.plot(t_meas, u1)
        plt.hold(True)
        plt.title('u1')
        plt.grid()
        plt.subplot(2, 1, 2)
        plt.plot(t_meas, u2)
        plt.title('u2')
        plt.xlabel('t[s]')
        plt.hold(True)
        plt.grid()

    # Build input trajectory matrix for use in simulation
    u = N.transpose(N.vstack((t_meas, u1, u2)))

    # compile FMU
    fmu_name = compile_fmu('QuadTankPack.Sim_QuadTank',
                           curr_dir + '/files/QuadTankPack.mop')

    # Load model
    model = load_fmu(fmu_name)

    # Simulate model response with nominal parameters
    res = model.simulate(input=(['u1', 'u2'], u), start_time=0., final_time=60)

    # Load simulation result
    x1_sim = res['qt.x1']
    x2_sim = res['qt.x2']
    x3_sim = res['qt.x3']
    x4_sim = res['qt.x4']
    t_sim = res['time']

    u1_sim = res['u1']
    u2_sim = res['u2']

    # Plot simulation result
    if with_plots:
        plt.figure(1)
        plt.subplot(2, 2, 1)
        plt.plot(t_sim, x3_sim)
        plt.subplot(2, 2, 2)
        plt.plot(t_sim, x4_sim)
        plt.subplot(2, 2, 3)
        plt.plot(t_sim, x1_sim)
        plt.subplot(2, 2, 4)
        plt.plot(t_sim, x2_sim)

        plt.figure(2)
        plt.subplot(2, 1, 1)
        plt.plot(t_sim, u1_sim, 'r')
        plt.subplot(2, 1, 2)
        plt.plot(t_sim, u2_sim, 'r')

    # Compile parameter optimization model
    jmu_name = compile_jmu("QuadTankPack.QuadTank_ParEst",
                           curr_dir + "/files/QuadTankPack.mop")

    # Load the model
    qt_par_est = JMUModel(jmu_name)

    # Number of measurement points
    N_meas = N.size(u1, 0)

    # Set measurement data into model
    for i in range(0, N_meas):
        qt_par_est.set("t_meas[" + ` i + 1 ` + "]", t_meas[i])
        qt_par_est.set("y1_meas[" + ` i + 1 ` + "]", y1_meas[i])
        qt_par_est.set("y2_meas[" + ` i + 1 ` + "]", y2_meas[i])

    n_e = 30  # Numer of element in collocation algorithm

    # Get an options object for the optimization algorithm
    opt_opts = qt_par_est.optimize_options()
    # Set the number of collocation points
    opt_opts['n_e'] = n_e

    opt_opts['init_traj'] = res.result_data

    # Solve parameter optimization problem
    res = qt_par_est.optimize(options=opt_opts)

    # Extract optimal values of parameters
    a1_opt = res.final("qt.a1")
    a2_opt = res.final("qt.a2")

    # Print optimal parameter values
    print('a1: ' + str(a1_opt * 1e4) + 'cm^2')
    print('a2: ' + str(a2_opt * 1e4) + 'cm^2')

    assert N.abs(a1_opt * 1.e6 - 2.6574) < 1e-3
    assert N.abs(a2_opt * 1.e6 - 2.7130) < 1e-3

    # Load state profiles
    x1_opt = res["qt.x1"]
    x2_opt = res["qt.x2"]
    x3_opt = res["qt.x3"]
    x4_opt = res["qt.x4"]
    u1_opt = res["qt.u1"]
    u2_opt = res["qt.u2"]
    t_opt = res["time"]

    # Plot
    if with_plots:
        plt.figure(1)
        plt.subplot(2, 2, 1)
        plt.plot(t_opt, x3_opt, 'k')
        plt.subplot(2, 2, 2)
        plt.plot(t_opt, x4_opt, 'k')
        plt.subplot(2, 2, 3)
        plt.plot(t_opt, x1_opt, 'k')
        plt.subplot(2, 2, 4)
        plt.plot(t_opt, x2_opt, 'k')

    # Compile second parameter estimation model
    jmu_name = compile_jmu("QuadTankPack.QuadTank_ParEst2",
                           curr_dir + "/files/QuadTankPack.mop")

    # Load model
    qt_par_est2 = JMUModel(jmu_name)

    # Number of measurement points
    N_meas = N.size(u1, 0)

    # Set measurement data into model
    for i in range(0, N_meas):
        qt_par_est2.set("t_meas[" + ` i + 1 ` + "]", t_meas[i])
        qt_par_est2.set("y1_meas[" + ` i + 1 ` + "]", y1_meas[i])
        qt_par_est2.set("y2_meas[" + ` i + 1 ` + "]", y2_meas[i])
        qt_par_est2.set("y3_meas[" + ` i + 1 ` + "]", y3_meas[i])
        qt_par_est2.set("y4_meas[" + ` i + 1 ` + "]", y4_meas[i])

    # Solve parameter estimation problem
    res_opt2 = qt_par_est2.optimize(options=opt_opts)

    # Get optimal parameter values
    a1_opt2 = res_opt2.final("qt.a1")
    a2_opt2 = res_opt2.final("qt.a2")
    a3_opt2 = res_opt2.final("qt.a3")
    a4_opt2 = res_opt2.final("qt.a4")

    # Print optimal parameter values
    print('a1:' + str(a1_opt2 * 1e4) + 'cm^2')
    print('a2:' + str(a2_opt2 * 1e4) + 'cm^2')
    print('a3:' + str(a3_opt2 * 1e4) + 'cm^2')
    print('a4:' + str(a4_opt2 * 1e4) + 'cm^2')

    assert N.abs(a1_opt2 * 1.e6 - 2.6579) < 1e-3, "Wrong value of parameter a1"
    assert N.abs(a2_opt2 * 1.e6 - 2.7038) < 1e-3, "Wrong value of parameter a2"
    assert N.abs(a3_opt2 * 1.e6 - 3.0031) < 1e-3, "Wrong value of parameter a3"
    assert N.abs(a4_opt2 * 1.e6 - 2.9342) < 1e-3, "Wrong value of parameter a4"

    # Extract state and input profiles
    x1_opt2 = res_opt2["qt.x1"]
    x2_opt2 = res_opt2["qt.x2"]
    x3_opt2 = res_opt2["qt.x3"]
    x4_opt2 = res_opt2["qt.x4"]
    u1_opt2 = res_opt2["qt.u1"]
    u2_opt2 = res_opt2["qt.u2"]
    t_opt2 = res_opt2["time"]

    # Plot
    if with_plots:
        plt.figure(1)
        plt.subplot(2, 2, 1)
        plt.plot(t_opt2, x3_opt2, 'r')
        plt.subplot(2, 2, 2)
        plt.plot(t_opt2, x4_opt2, 'r')
        plt.subplot(2, 2, 3)
        plt.plot(t_opt2, x1_opt2, 'r')
        plt.subplot(2, 2, 4)
        plt.plot(t_opt2, x2_opt2, 'r')
        plt.show()

    # Compute parameter standard deviations for case 1
    # compile JMU
    jmu_name = compile_jmu('QuadTankPack.QuadTank_Sens1',
                           curr_dir + '/files/QuadTankPack.mop')

    # Load model
    model = JMUModel(jmu_name)

    model.set('a1', a1_opt)
    model.set('a2', a2_opt)

    sens_opts = model.simulate_options()

    # Enable sensitivity computations
    sens_opts['IDA_options']['sensitivity'] = True
    #sens_opts['IDA_options']['atol'] = 1e-12

    # Simulate sensitivity equations
    sens_res = model.simulate(input=(['u1', 'u2'], u),
                              start_time=0.,
                              final_time=60,
                              options=sens_opts)

    # Get result trajectories
    x1_sens = sens_res['x1']
    x2_sens = sens_res['x2']
    dx1da1 = sens_res['dx1/da1']
    dx1da2 = sens_res['dx1/da2']
    dx2da1 = sens_res['dx2/da1']
    dx2da2 = sens_res['dx2/da2']
    t_sens = sens_res['time']

    # Compute Jacobian

    # Create a trajectory object for interpolation
    traj = TrajectoryLinearInterpolation(
        t_sens,
        N.transpose(
            N.vstack((x1_sens, x2_sens, dx1da1, dx1da2, dx2da1, dx2da2))))

    # Jacobian
    jac = N.zeros((61 * 2, 2))

    # Error vector
    err = N.zeros(61 * 2)

    # Extract Jacobian and error information
    i = 0
    for t_p in t_meas:
        vals = traj.eval(t_p)
        for j in range(2):
            for k in range(2):
                jac[i + j, k] = vals[0, 2 * j + k + 2]
            err[i] = vals[0, 0] - y1_meas[i / 2]
            err[i + 1] = vals[0, 1] - y2_meas[i / 2]
        i = i + 2

    # Compute estimated variance of measurement noice
    v_err = N.sum(err**2) / (61 * 2 - 2)

    # Compute J^T*J
    A = N.dot(N.transpose(jac), jac)

    # Compute parameter covariance matrix
    P = v_err * N.linalg.inv(A)

    # Compute standard deviations for parameters
    sigma_a1 = N.sqrt(P[0, 0])
    sigma_a2 = N.sqrt(P[1, 1])

    print "a1: " + str(
        sens_res['a1']) + ", standard deviation: " + str(sigma_a1)
    print "a2: " + str(
        sens_res['a2']) + ", standard deviation: " + str(sigma_a2)

    # Compute parameter standard deviations for case 2
    # compile JMU
    jmu_name = compile_jmu('QuadTankPack.QuadTank_Sens2',
                           curr_dir + '/files/QuadTankPack.mop')

    # Load model
    model = JMUModel(jmu_name)

    model.set('a1', a1_opt2)
    model.set('a2', a2_opt2)
    model.set('a3', a3_opt2)
    model.set('a4', a4_opt2)

    sens_opts = model.simulate_options()

    # Enable sensitivity computations
    sens_opts['IDA_options']['sensitivity'] = True
    #sens_opts['IDA_options']['atol'] = 1e-12

    # Simulate sensitivity equations
    sens_res = model.simulate(input=(['u1', 'u2'], u),
                              start_time=0.,
                              final_time=60,
                              options=sens_opts)

    # Get result trajectories
    x1_sens = sens_res['x1']
    x2_sens = sens_res['x2']
    x3_sens = sens_res['x3']
    x4_sens = sens_res['x4']

    dx1da1 = sens_res['dx1/da1']
    dx1da2 = sens_res['dx1/da2']
    dx1da3 = sens_res['dx1/da3']
    dx1da4 = sens_res['dx1/da4']

    dx2da1 = sens_res['dx2/da1']
    dx2da2 = sens_res['dx2/da2']
    dx2da3 = sens_res['dx2/da3']
    dx2da4 = sens_res['dx2/da4']

    dx3da1 = sens_res['dx3/da1']
    dx3da2 = sens_res['dx3/da2']
    dx3da3 = sens_res['dx3/da3']
    dx3da4 = sens_res['dx3/da4']

    dx4da1 = sens_res['dx4/da1']
    dx4da2 = sens_res['dx4/da2']
    dx4da3 = sens_res['dx4/da3']
    dx4da4 = sens_res['dx4/da4']
    t_sens = sens_res['time']

    # Compute Jacobian

    # Create a trajectory object for interpolation
    traj = TrajectoryLinearInterpolation(
        t_sens,
        N.transpose(
            N.vstack(
                (x1_sens, x2_sens, x3_sens, x4_sens, dx1da1, dx1da2, dx1da3,
                 dx1da4, dx2da1, dx2da2, dx2da3, dx2da4, dx3da1, dx3da2,
                 dx3da3, dx3da4, dx4da1, dx4da2, dx4da3, dx4da4))))

    # Jacobian
    jac = N.zeros((61 * 4, 4))

    # Error vector
    err = N.zeros(61 * 4)

    # Extract Jacobian and error information
    i = 0
    for t_p in t_meas:
        vals = traj.eval(t_p)
        for j in range(4):
            for k in range(4):
                jac[i + j, k] = vals[0, 4 * j + k + 4]
            err[i] = vals[0, 0] - y1_meas[i / 4]
            err[i + 1] = vals[0, 1] - y2_meas[i / 4]
            err[i + 2] = vals[0, 2] - y3_meas[i / 4]
            err[i + 3] = vals[0, 3] - y4_meas[i / 4]
        i = i + 4

    # Compute estimated variance of measurement noice
    v_err = N.sum(err**2) / (61 * 4 - 4)

    # Compute J^T*J
    A = N.dot(N.transpose(jac), jac)

    # Compute parameter covariance matrix
    P = v_err * N.linalg.inv(A)

    # Compute standard deviations for parameters
    sigma_a1 = N.sqrt(P[0, 0])
    sigma_a2 = N.sqrt(P[1, 1])
    sigma_a3 = N.sqrt(P[2, 2])
    sigma_a4 = N.sqrt(P[3, 3])

    print "a1: " + str(
        sens_res['a1']) + ", standard deviation: " + str(sigma_a1)
    print "a2: " + str(
        sens_res['a2']) + ", standard deviation: " + str(sigma_a2)
    print "a3: " + str(
        sens_res['a3']) + ", standard deviation: " + str(sigma_a3)
    print "a4: " + str(
        sens_res['a4']) + ", standard deviation: " + str(sigma_a4)
Пример #9
0
def run_demo(with_plots=True):
    """
    This example is based on the Hicks-Ray Continuously Stirred Tank Reactors 
    (CSTR) system. The system has two states, the concentration and the 
    temperature. The control input to the system is the temperature of the 
    cooling flow in the reactor jacket. The chemical reaction in the reactor is 
    exothermic, and also temperature dependent; high temperature results in high 
    reaction rate.
    
    The example demonstrates the following steps:
    
    1. How to solve a DAE initialization problem. The initialization model have 
       equations specifying that all derivatives should be identically zero, 
       which implies that a stationary solution is obtained. Two stationary 
       points, corresponding to different inputs, are computed. We call the 
       stationary points A and B respectively. point A corresponds to operating 
       conditions where the reactor is cold and the reaction rate is low, 
       whereas point B corresponds to a higher temperature where the reaction 
       rate is high.

       For more information about the DAE initialization algorithm, see
       http://www.jmodelica.org/page/10.

    2. How to generate an initial guess for a direct collocation method by means 
       of simulation. The trajectories resulting from simulation are used to 
       initialize the variables in the transcribed NLP.
       
    3. An optimal control problem is solved where the objective Is to transfer 
       the state of the system from stationary point A to point B. The challenge 
       is to ignite the reactor while avoiding uncontrolled temperature 
       increase. It is also demonstrated how to set parameter and variable 
       values in a model.

       More information about the simultaneous optimization algorithm can be 
       found at http://www.jmodelica.org/page/10.

    4. The optimization result is saved to file and then the important variables 
       are plotted.

    5. Simulate the system with the optimal control profile. This step is 
       important in order to verify that the approximation in the transcription 
       step is valid.
"""

    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"),
                           compiler_options={"enable_variable_scaling": True})

    # load the JMU
    init_model = JMUModel(jmu_name)

    # Set inputs for Stationary point A
    Tc_0_A = 250
    init_model.set('Tc', Tc_0_A)

    # Solve the DAE initialization system with Ipopt
    init_result = init_model.initialize()

    # Store stationary point A
    c_0_A = init_result['c'][0]
    T_0_A = init_result['T'][0]

    # 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
    init_model.set('Tc', Tc_0_B)

    # Solve the DAE initialization system with Ipopt
    init_result = init_model.initialize()
    # Store stationary point B
    c_0_B = init_result['c'][0]
    T_0_B = init_result['T'][0]

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

    # Compute initial guess trajectories by means of simulation
    # Compile the optimization initialization model
    jmu_name = compile_jmu("CSTR.CSTR_Init_Optimization",
                           os.path.join(curr_dir, "files", "CSTR.mop"))

    # Load the model
    init_sim_model = JMUModel(jmu_name)

    # Set model parameters
    init_sim_model.set('cstr.c_init', c_0_A)
    init_sim_model.set('cstr.T_init', T_0_A)
    init_sim_model.set('c_ref', c_0_B)
    init_sim_model.set('T_ref', T_0_B)
    init_sim_model.set('Tc_ref', Tc_0_B)

    res = init_sim_model.simulate(start_time=0., final_time=150.)

    # Extract variable profiles
    c_init_sim = res['cstr.c']
    T_init_sim = res['cstr.T']
    Tc_init_sim = res['cstr.Tc']
    t_init_sim = res['time']

    # Plot the results
    if with_plots:
        plt.figure(1)
        plt.clf()
        plt.hold(True)
        plt.subplot(311)
        plt.plot(t_init_sim, c_init_sim)
        plt.grid()
        plt.ylabel('Concentration')

        plt.subplot(312)
        plt.plot(t_init_sim, T_init_sim)
        plt.grid()
        plt.ylabel('Temperature')

        plt.subplot(313)
        plt.plot(t_init_sim, Tc_init_sim)
        plt.grid()
        plt.ylabel('Cooling temperature')
        plt.xlabel('time')
        plt.show()

    # Solve the optimal control problem
    # Compile model
    jmu_name = compile_jmu("CSTR.CSTR_Opt", curr_dir + "/files/CSTR.mop")

    # Load model
    cstr = JMUModel(jmu_name)

    # Set reference values
    cstr.set('Tc_ref', Tc_0_B)
    cstr.set('c_ref', c_0_B)
    cstr.set('T_ref', T_0_B)

    # Set initial values
    cstr.set('cstr.c_init', c_0_A)
    cstr.set('cstr.T_init', T_0_A)

    n_e = 100  # Number of elements

    # Set options
    opt_opts = cstr.optimize_options()
    opt_opts['n_e'] = n_e
    opt_opts['init_traj'] = res.result_data

    res = cstr.optimize(options=opt_opts)

    # Extract variable profiles
    c_res = res['cstr.c']
    T_res = res['cstr.T']
    Tc_res = res['cstr.Tc']
    time_res = res['time']

    c_ref = res['c_ref']
    T_ref = res['T_ref']
    Tc_ref = res['Tc_ref']

    assert N.abs(res.final('cost') / 1.e7 - 1.8585429) < 1e-3

    # Plot the results
    if with_plots:
        plt.figure(2)
        plt.clf()
        plt.hold(True)
        plt.subplot(311)
        plt.plot(time_res, c_res)
        plt.plot([time_res[0], time_res[-1]], [c_ref, c_ref], '--')
        plt.grid()
        plt.ylabel('Concentration')

        plt.subplot(312)
        plt.plot(time_res, T_res)
        plt.plot([time_res[0], time_res[-1]], [T_ref, T_ref], '--')
        plt.grid()
        plt.ylabel('Temperature')

        plt.subplot(313)
        plt.plot(time_res, Tc_res)
        plt.plot([time_res[0], time_res[-1]], [Tc_ref, Tc_ref], '--')
        plt.grid()
        plt.ylabel('Cooling temperature')
        plt.xlabel('time')
        plt.show()

    # Simulate to verify the optimal solution
    # Set up the input trajectory
    t = time_res
    u = Tc_res
    u_traj = N.transpose(N.vstack((t, u)))

    # Compile the Modelica model to a JMU
    jmu_name = compile_jmu("CSTR.CSTR", curr_dir + "/files/CSTR.mop")

    # Load model
    sim_model = JMUModel(jmu_name)

    sim_model.set('c_init', c_0_A)
    sim_model.set('T_init', T_0_A)
    sim_model.set('Tc', u[0])

    res = sim_model.simulate(start_time=0.,
                             final_time=150.,
                             input=('Tc', u_traj))

    # Extract variable profiles
    c_sim = res['c']
    T_sim = res['T']
    Tc_sim = res['Tc']
    time_sim = res['time']

    # Plot the results
    if with_plots:
        plt.figure(3)
        plt.clf()
        plt.hold(True)
        plt.subplot(311)
        plt.plot(time_res, c_res, '--')
        plt.plot(time_sim, c_sim)
        plt.legend(('optimized', 'simulated'))
        plt.grid()
        plt.ylabel('Concentration')

        plt.subplot(312)
        plt.plot(time_res, T_res, '--')
        plt.plot(time_sim, T_sim)
        plt.legend(('optimized', 'simulated'))
        plt.grid()
        plt.ylabel('Temperature')

        plt.subplot(313)
        plt.plot(time_res, Tc_res, '--')
        plt.plot(time_sim, Tc_sim)
        plt.legend(('optimized', 'simulated'))
        plt.grid()
        plt.ylabel('Cooling temperature')
        plt.xlabel('time')
        plt.show()