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
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
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()
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()
def run_demo(with_plots=True): """ Static calibration of the quad tank model. """ curr_dir = os.path.dirname(os.path.abspath(__file__)) jmu_name = compile_jmu("QuadTank_pack.QuadTank_Static", curr_dir + "/files/QuadTank.mop") # Load static calibration model qt_static = JMUModel(jmu_name) # Set control inputs qt_static.set("u1", 2.5) qt_static.set("u2", 2.5) # Save nominal values a1_nom = qt_static.get("a1") a2_nom = qt_static.get("a2") init_res = qt_static.initialize(options={"stat": 1}) print "Optimal parameter values:" print "a1: %2.2e (nominal: %2.2e)" % (qt_static.get("a1"), a1_nom) print "a2: %2.2e (nominal: %2.2e)" % (qt_static.get("a2"), a2_nom) assert N.abs(qt_static.get("a1") - 7.95797110936e-06) < 1e-3 assert N.abs(qt_static.get("a2") - 7.73425542448e-06) < 1e-3
def run_demo(with_plots=True): """ Static calibration of the quad tank model. """ curr_dir = os.path.dirname(os.path.abspath(__file__)) jmu_name = compile_jmu("QuadTank_pack.QuadTank_Static", curr_dir + "/files/QuadTank.mop") # Load static calibration model qt_static = JMUModel(jmu_name) # Set control inputs qt_static.set("u1", 2.5) qt_static.set("u2", 2.5) # Save nominal values a1_nom = qt_static.get("a1") a2_nom = qt_static.get("a2") init_res = qt_static.initialize(options={'stat': 1}) print "Optimal parameter values:" print "a1: %2.2e (nominal: %2.2e)" % (qt_static.get("a1"), a1_nom) print "a2: %2.2e (nominal: %2.2e)" % (qt_static.get("a2"), a2_nom) assert N.abs(qt_static.get("a1") - 7.95797110936e-06) < 1e-3 assert N.abs(qt_static.get("a2") - 7.73425542448e-06) < 1e-3
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
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
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)
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)
def run_demo(with_plots=True, with_blocking_factors = False): """ Load change of a distillation column. The distillation column model is documented in the paper: @Article{hahn+02, title={An improved method for nonlinear model reduction using balancing of empirical gramians}, author={Hahn, J. and Edgar, T.F.}, journal={Computers and Chemical Engineering}, volume={26}, number={10}, pages={1379-1397}, year={2002} } Note: This example requires Ipopt with MA27. """ curr_dir = os.path.dirname(os.path.abspath(__file__)); # Compile the stationary initialization model into a JMU jmu_name = compile_jmu("DISTLib.Binary_Dist_initial", curr_dir+"/files/DISTLib.mo") # Load a model instance into Python init_model = JMUModel(jmu_name) # Set inputs for Stationary point A rr_0_A = 3.0 init_model.set('rr',rr_0_A) init_result = init_model.initialize() # Store stationary point A y_A = N.zeros(32) x_A = N.zeros(32) print(' *** Stationary point A ***') print '(Tray index, x_i_A, y_i_A)' for i in range(N.size(y_A)): y_A[i] = init_model.get('y['+ str(i+1) +']') x_A[i] = init_model.get('x['+ str(i+1) +']') print '(' + str(i+1) + ', %f, %f)' %(x_A[i], y_A[i]) # Set inputs for stationary point B rr_0_B = 2.0 init_model.set('rr',rr_0_B) init_result = init_model.initialize() # Store stationary point B y_B = N.zeros(32) x_B = N.zeros(32) print(' *** Stationary point B ***') print '(Tray index, x_i_B, y_i_B)' for i in range(N.size(y_B)): y_B[i] = init_model.get('y[' + str(i+1) + ']') x_B[i] = init_model.get('x[' + str(i+1) + ']') print '(' + str(i+1) + ', %f, %f)' %(x_B[i], y_B[i]) # Set up and solve an optimal control problem. # Compile the JMU jmu_name = compile_jmu("DISTLib_Opt.Binary_Dist_Opt1", (curr_dir+"/files/DISTLib.mo",curr_dir+"/files/DISTLib_Opt.mop"), compiler_options={'state_start_values_fixed':True}) # Load the dynamic library and XML data model = JMUModel(jmu_name) # Initialize the model with parameters # Initialize the model to stationary point A for i in range(N.size(x_A)): model.set('x_0[' + str(i+1) + ']', x_A[i]) # Set the target values to stationary point B model.set('rr_ref',rr_0_B) model.set('y1_ref',y_B[0]) n_e = 100 # Number of elements hs = N.ones(n_e)*1./n_e # Equidistant points n_cp = 3; # Number of collocation points in each element # Solve the optimization problem if with_blocking_factors: # Blocking factors for control parametrization blocking_factors=4*N.ones(n_e/4,dtype=N.int) opt_opts = model.optimize_options() opt_opts['n_e'] = n_e opt_opts['n_cp'] = n_cp opt_opts['hs'] = hs opt_opts['blocking_factors'] = blocking_factors opt_res = model.optimize(options=opt_opts) else: opt_res = model.optimize(options={'n_e':n_e, 'n_cp':n_cp, 'hs':hs}) # Extract variable profiles u1_res = opt_res['rr'] u1_ref_res = opt_res['rr_ref'] y1_ref_res = opt_res['y1_ref'] time = opt_res['time'] x_res = [] x_ref_res = [] for i in range(N.size(x_B)): x_res.append(opt_res['x[' + str(i+1) + ']']) y_res = [] for i in range(N.size(x_B)): y_res.append(opt_res['y[' + str(i+1) + ']']) if with_blocking_factors: assert N.abs(opt_res.final('cost')/1.e1 - 2.8549683) < 1e-3 else: assert N.abs(opt_res.final('cost')/1.e1 - 2.8527469) < 1e-3 # Plot the results if with_plots: plt.figure(1) plt.clf() plt.hold(True) plt.subplot(311) plt.title('Liquid composition') plt.plot(time, x_res[0]) plt.ylabel('x1') plt.grid() plt.subplot(312) plt.plot(time, x_res[16]) plt.ylabel('x17') plt.grid() plt.subplot(313) plt.plot(time, x_res[31]) plt.ylabel('x32') plt.grid() plt.xlabel('t [s]') plt.show() # Plot the results plt.figure(2) plt.clf() plt.hold(True) plt.subplot(311) plt.title('Vapor composition') plt.plot(time, y_res[0]) plt.plot(time, y1_ref_res, '--') plt.ylabel('y1') plt.grid() plt.subplot(312) plt.plot(time, y_res[16]) plt.ylabel('y17') plt.grid() plt.subplot(313) plt.plot(time, y_res[31]) plt.ylabel('y32') plt.grid() plt.xlabel('t [s]') plt.show() plt.figure(3) plt.clf() plt.hold(True) plt.plot(time, u1_res) plt.ylabel('u') plt.plot(time, u1_ref_res, '--') plt.xlabel('t [s]') plt.title('Reflux ratio') plt.grid() plt.show()
def run_demo(with_plots=True): """ Load change of a distillation column. The distillation column model is documented in the paper: @Article{hahn+02, title={An improved method for nonlinear model reduction using balancing of empirical gramians}, author={Hahn, J. and Edgar, T.F.}, journal={Computers and Chemical Engineering}, volume={26}, number={10}, pages={1379-1397}, year={2002} } Note: This example requires Ipopt with MA27. """ curr_dir = os.path.dirname(os.path.abspath(__file__)); # Compile the stationary initialization model into a JMU jmu_name = compile_jmu("JMExamples.Distillation.Distillation1Input_init", curr_dir+"/files/JMExamples.mo") # Load a model instance into Python init_model = JMUModel(jmu_name) # Set inputs for Stationary point A rr_0_A = 3.0 init_model.set('rr',rr_0_A) init_result = init_model.initialize() # Store stationary point A y_A = N.zeros(32) x_A = N.zeros(32) print(' *** Stationary point A ***') print '(Tray index, x_i_A, y_i_A)' for i in range(32): y_A[i] = init_result['y['+ str(i+1) +']'][0] x_A[i] = init_result['x['+ str(i+1) +']'][0] print '(' + str(i+1) + ', %f, %f)' %(x_A[i], y_A[i]) # Set inputs for stationary point B rr_0_B = 2.0 init_model.set('rr',rr_0_B) init_result = init_model.initialize() # Store stationary point B y_B = N.zeros(32) x_B = N.zeros(32) print(' *** Stationary point B ***') print '(Tray index, x_i_B, y_i_B)' for i in range(32): y_B[i] = init_result['y[' + str(i+1) + ']'][0] x_B[i] = init_result['x[' + str(i+1) + ']'][0] print '(' + str(i+1) + ', %f, %f)' %(x_B[i], y_B[i]) # Set up and solve an optimal control problem. # Compile the JMU jmu_name = compile_jmu("JMExamples_opt.Distillation1_opt", (curr_dir+"/files/JMExamples.mo",curr_dir+"/files/JMExamples_opt.mop"), compiler_options={'state_start_values_fixed':True}) # Load the dynamic library and XML data model = JMUModel(jmu_name) # Initialize the model with parameters # Initialize the model to stationary point A for i in range(32): model.set('x_init[' + str(i+1) + ']', x_A[i]) # Set the target values to stationary point B model.set('rr_ref',rr_0_B) model.set('x1_ref',x_B[0]) # Solve the optimization problem opts = model.optimize_options() opts['hs'] = N.ones(100)*1./100 # Equidistant points opts['n_e'] = 100 # Number of elements opts['n_cp'] = 3 # Number of collocation points in each element opt_res = model.optimize() # Extract variable profiles x1 = opt_res['x[1]'] x8 = opt_res['x[8]'] x16 = opt_res['x[16]'] x24 = opt_res['x[24]'] x32 = opt_res['x[32]'] y1 = opt_res['y[1]'] y8 = opt_res['y[8]'] y16 = opt_res['y[16]'] y24 = opt_res['y[24]'] y32 = opt_res['y[32]'] t = opt_res['time'] rr = opt_res['rr'] assert N.abs(opt_res.final('rr') - 2.0) < 1e-3 # Plot the results if with_plots: plt.figure() plt.subplot(1,2,1) plt.plot(t,x16,t,x32,t,x1,t,x8,t,x24) plt.title('Liquid composition') plt.grid(True) plt.ylabel('x') plt.subplot(1,2,2) plt.plot(t,y16,t,y32,t,y1,t,y8,t,y24) plt.title('Vapor composition') plt.grid(True) plt.ylabel('y') plt.xlabel('time') plt.show() plt.figure(3) plt.clf() plt.hold(True) plt.plot(t,rr) plt.ylabel('rr') plt.xlabel('t [s]') plt.title('Reflux ratio') plt.show()
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()
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()
def run_demo(with_plots=True): """ Distillation4 optimization model """ curr_dir = os.path.dirname(os.path.abspath(__file__)); # Compile the stationary initialization model into a JMU jmu_name = compile_jmu("JMExamples.Distillation.Distillation1Input_init", curr_dir+"/files/JMExamples.mo") # Load a model instance into Python init_model = JMUModel(jmu_name) # Set inputs for Stationary point A rr_0_A = 3.0 init_model.set('rr',rr_0_A) init_result = init_model.initialize() # Store stationary point A y_A = N.zeros(32) x_A = N.zeros(32) # print(' *** Stationary point A ***') print '(Tray index, x_i_A, y_i_A)' for i in range(32): y_A[i] = init_result['y['+ str(i+1) +']'][0] x_A[i] = init_result['x['+ str(i+1) +']'][0] print '(' + str(i+1) + ', %f, %f)' %(x_A[i], y_A[i]) # Set inputs for stationary point B rr_0_B = 2.0 init_model.set('rr',rr_0_B) init_result = init_model.initialize() # Store stationary point B y_B = N.zeros(32) x_B = N.zeros(32) # print(' *** Stationary point B ***') print '(Tray index, x_i_B, y_i_B)' for i in range(32): y_B[i] = init_result['y[' + str(i+1) + ']'][0] x_B[i] = init_result['x[' + str(i+1) + ']'][0] print '(' + str(i+1) + ', %f, %f)' %(x_B[i], y_B[i]) # Set up and solve the simulation problem. fmu_name1 = compile_fmu("JMExamples.Distillation.Distillation1Inputstep", curr_dir+"/files/JMExamples.mo") dist1 = load_fmu(fmu_name1) # Initialize the model with parameters # Initialize the model to stationary point A for i in range(32): dist1.set('x_init[' + str(i+1) + ']', x_A[i]) res = dist1.simulate(final_time=50) # Extract variable profiles x1 = res['x[1]'] x8 = res['x[8]'] x16 = res['x[16]'] x24 = res['x[24]'] x32 = res['x[32]'] y1 = res['y[1]'] y8 = res['y[8]'] y16 = res['y[16]'] y24 = res['y[24]'] y32 = res['y[32]'] t = res['time'] rr = res['rr'] print "t = ", repr(N.array(t)) print "x1 = ", repr(N.array(x1)) print "x8 = ", repr(N.array(x8)) print "x16 = ", repr(N.array(x16)) print "x32 = ", repr(N.array(x32)) if with_plots: # Plot plt.figure() plt.subplot(1,3,1) plt.plot(t,x16,t,x32,t,x1,t,x8,t,x24) plt.title('Liquid composition') plt.grid(True) plt.ylabel('x') plt.subplot(1,3,2) plt.plot(t,y16,t,y32,t,y1,t,y8,t,y24) plt.title('Vapor composition') plt.grid(True) plt.ylabel('y') plt.subplot(1,3,3) plt.plot(t,rr) plt.title('Reflux ratio') plt.grid(True) plt.ylabel('rr') plt.xlabel('time') plt.show()
def run_demo(with_plots=True): """ Distillation4 optimization model """ curr_dir = os.path.dirname(os.path.abspath(__file__)) # Compile the stationary initialization model into a JMU jmu_name = compile_jmu("JMExamples.Distillation.Distillation1Input_init", curr_dir + "/files/JMExamples.mo") # Load a model instance into Python init_model = JMUModel(jmu_name) # Set inputs for Stationary point A rr_0_A = 3.0 init_model.set('rr', rr_0_A) init_result = init_model.initialize() # Store stationary point A y_A = N.zeros(32) x_A = N.zeros(32) # print(' *** Stationary point A ***') print '(Tray index, x_i_A, y_i_A)' for i in range(32): y_A[i] = init_result['y[' + str(i + 1) + ']'][0] x_A[i] = init_result['x[' + str(i + 1) + ']'][0] print '(' + str(i + 1) + ', %f, %f)' % (x_A[i], y_A[i]) # Set inputs for stationary point B rr_0_B = 2.0 init_model.set('rr', rr_0_B) init_result = init_model.initialize() # Store stationary point B y_B = N.zeros(32) x_B = N.zeros(32) # print(' *** Stationary point B ***') print '(Tray index, x_i_B, y_i_B)' for i in range(32): y_B[i] = init_result['y[' + str(i + 1) + ']'][0] x_B[i] = init_result['x[' + str(i + 1) + ']'][0] print '(' + str(i + 1) + ', %f, %f)' % (x_B[i], y_B[i]) # Set up and solve the simulation problem. fmu_name1 = compile_fmu("JMExamples.Distillation.Distillation1Inputstep", curr_dir + "/files/JMExamples.mo") dist1 = load_fmu(fmu_name1) # Initialize the model with parameters # Initialize the model to stationary point A for i in range(32): dist1.set('x_init[' + str(i + 1) + ']', x_A[i]) res = dist1.simulate(final_time=50) # Extract variable profiles x1 = res['x[1]'] x8 = res['x[8]'] x16 = res['x[16]'] x24 = res['x[24]'] x32 = res['x[32]'] y1 = res['y[1]'] y8 = res['y[8]'] y16 = res['y[16]'] y24 = res['y[24]'] y32 = res['y[32]'] t = res['time'] rr = res['rr'] print "t = ", repr(N.array(t)) print "x1 = ", repr(N.array(x1)) print "x8 = ", repr(N.array(x8)) print "x16 = ", repr(N.array(x16)) print "x32 = ", repr(N.array(x32)) if with_plots: # Plot plt.figure() plt.subplot(1, 3, 1) plt.plot(t, x16, t, x32, t, x1, t, x8, t, x24) plt.title('Liquid composition') plt.grid(True) plt.ylabel('x') plt.subplot(1, 3, 2) plt.plot(t, y16, t, y32, t, y1, t, y8, t, y24) plt.title('Vapor composition') plt.grid(True) plt.ylabel('y') plt.subplot(1, 3, 3) plt.plot(t, rr) plt.title('Reflux ratio') plt.grid(True) plt.ylabel('rr') plt.xlabel('time') plt.show()
def run_demo(with_plots=True): """ This example is based on a system composed of two Continously Stirred Tank Reactors (CSTRs) in series. 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. For more information about the DAE initialization algorithm, see http://www.jmodelica.org/page/10. 2. An optimal control problem is solved where the objective is to transfer the state of the system from stationary point A to point B. Here, it is also demonstrated how to set parameter values in a model. More information about the simultaneous optimization algorithm can be found at http://www.jmodelica.org/page/10. 3. The optimization result is saved to file and then the important variables are plotted. """ curr_dir = os.path.dirname(os.path.abspath(__file__)); # Compile the stationary initialization model into a DLL jmu_name = compile_jmu("CSTRLib.Components.Two_CSTRs_stat_init", os.path.join(curr_dir, "files", "CSTRLib.mo")) # Load a JMU model instance init_model = JMUModel(jmu_name) # Set inputs for Stationary point A u1_0_A = 1 u2_0_A = 1 init_model.set('u1',u1_0_A) init_model.set('u2',u2_0_A) # Solve the DAE initialization system with Ipopt init_result = init_model.initialize() # Store stationary point A CA1_0_A = init_model.get('CA1') CA2_0_A = init_model.get('CA2') T1_0_A = init_model.get('T1') T2_0_A = init_model.get('T2') # Print some data for stationary point A print(' *** Stationary point A ***') print('u = [%f,%f]' % (u1_0_A,u2_0_A)) print('CAi = [%f,%f]' % (CA1_0_A,CA2_0_A)) print('Ti = [%f,%f]' % (T1_0_A,T2_0_A)) # Set inputs for stationary point B u1_0_B = 1.1 u2_0_B = 0.9 init_model.set('u1',u1_0_B) init_model.set('u2',u2_0_B) # Solve the DAE initialization system with Ipopt init_result = init_model.initialize() # Stationary point B CA1_0_B = init_model.get('CA1') CA2_0_B = init_model.get('CA2') T1_0_B = init_model.get('T1') T2_0_B = init_model.get('T2') # Print some data for stationary point B print(' *** Stationary point B ***') print('u = [%f,%f]' % (u1_0_B,u2_0_B)) print('CAi = [%f,%f]' % (CA1_0_B,CA2_0_B)) print('Ti = [%f,%f]' % (T1_0_B,T2_0_B)) ## Set up and solve an optimal control problem. # Compile the Model jmu_name = compile_jmu("CSTR2_Opt", [os.path.join(curr_dir, "files", "CSTRLib.mo"), os.path.join(curr_dir, "files", "CSTR2_Opt.mop")], compiler_options={'enable_variable_scaling':True, 'index_reduction':True}) # Load the dynamic library and XML data model = JMUModel(jmu_name) # Initialize the model with parameters # Initialize the model to stationary point A model.set('cstr.two_CSTRs_Series.CA1_0',CA1_0_A) model.set('cstr.two_CSTRs_Series.CA2_0',CA2_0_A) model.set('cstr.two_CSTRs_Series.T1_0',T1_0_A) model.set('cstr.two_CSTRs_Series.T2_0',T2_0_A) # Set the target values to stationary point B model.set('u1_ref',u1_0_B) model.set('u2_ref',u2_0_B) model.set('CA1_ref',CA1_0_B) model.set('CA2_ref',CA2_0_B) # Initialize the optimization 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 res = model.optimize( options={'n_e':n_e, 'hs':hs, 'n_cp':n_cp, 'blocking_factors':2*N.ones(n_e/2,dtype=N.int), 'IPOPT_options':{'tol':1e-4}}) # Extract variable profiles CA1_res=res['cstr.two_CSTRs_Series.CA1'] CA2_res=res['cstr.two_CSTRs_Series.CA2'] T1_res=res['cstr.two_CSTRs_Series.T1'] T2_res=res['cstr.two_CSTRs_Series.T2'] u1_res=res['cstr.two_CSTRs_Series.u1'] u2_res=res['cstr.two_CSTRs_Series.u2'] der_u2_res=res['der_u2'] CA1_ref_res=res['CA1_ref'] CA2_ref_res=res['CA2_ref'] u1_ref_res=res['u1_ref'] u2_ref_res=res['u2_ref'] cost=res['cost'] time=res['time'] assert N.abs(res.final('cost') - 1.4745648e+01) < 1e-3 # Plot the results if with_plots: plt.figure(1) plt.clf() plt.hold(True) plt.subplot(211) plt.plot(time,CA1_res) plt.plot([time[0],time[-1]],[CA1_ref_res, CA1_ref_res],'--') plt.ylabel('Concentration reactor 1 [J/l]') plt.grid() plt.subplot(212) plt.plot(time,CA2_res) plt.plot([time[0],time[-1]],[CA2_ref_res, CA2_ref_res],'--') plt.ylabel('Concentration reactor 2 [J/l]') plt.xlabel('t [s]') plt.grid() plt.show() plt.figure(2) plt.clf() plt.hold(True) plt.subplot(211) plt.plot(time,T1_res) plt.ylabel('Temperature reactor 1 [K]') plt.grid() plt.subplot(212) plt.plot(time,T2_res) plt.ylabel('Temperature reactor 2 [K]') plt.grid() plt.xlabel('t [s]') plt.show() plt.figure(3) plt.clf() plt.hold(True) plt.subplot(211) plt.plot(time,u2_res) plt.ylabel('Input 2') plt.plot([time[0],time[-1]],[u2_ref_res, u2_ref_res],'--') plt.grid() plt.subplot(212) plt.plot(time,der_u2_res) plt.ylabel('Derivative of input 2') plt.xlabel('t [s]') plt.grid() plt.show()
def run_demo(with_plots=True, with_blocking_factors=False): """ Load change of a distillation column. The distillation column model is documented in the paper: @Article{hahn+02, title={An improved method for nonlinear model reduction using balancing of empirical gramians}, author={Hahn, J. and Edgar, T.F.}, journal={Computers and Chemical Engineering}, volume={26}, number={10}, pages={1379-1397}, year={2002} } Note: This example requires Ipopt with MA27. """ curr_dir = os.path.dirname(os.path.abspath(__file__)) # Compile the stationary initialization model into a JMU jmu_name = compile_jmu("DISTLib.Binary_Dist_initial", curr_dir + "/files/DISTLib.mo") # Load a model instance into Python init_model = JMUModel(jmu_name) # Set inputs for Stationary point A rr_0_A = 3.0 init_model.set('rr', rr_0_A) init_result = init_model.initialize() # Store stationary point A y_A = N.zeros(32) x_A = N.zeros(32) print(' *** Stationary point A ***') print '(Tray index, x_i_A, y_i_A)' for i in range(N.size(y_A)): y_A[i] = init_model.get('y[' + str(i + 1) + ']') x_A[i] = init_model.get('x[' + str(i + 1) + ']') print '(' + str(i + 1) + ', %f, %f)' % (x_A[i], y_A[i]) # Set inputs for stationary point B rr_0_B = 2.0 init_model.set('rr', rr_0_B) init_result = init_model.initialize() # Store stationary point B y_B = N.zeros(32) x_B = N.zeros(32) print(' *** Stationary point B ***') print '(Tray index, x_i_B, y_i_B)' for i in range(N.size(y_B)): y_B[i] = init_model.get('y[' + str(i + 1) + ']') x_B[i] = init_model.get('x[' + str(i + 1) + ']') print '(' + str(i + 1) + ', %f, %f)' % (x_B[i], y_B[i]) # Set up and solve an optimal control problem. # Compile the JMU jmu_name = compile_jmu( "DISTLib_Opt.Binary_Dist_Opt1", (curr_dir + "/files/DISTLib.mo", curr_dir + "/files/DISTLib_Opt.mop"), compiler_options={'state_start_values_fixed': True}) # Load the dynamic library and XML data model = JMUModel(jmu_name) # Initialize the model with parameters # Initialize the model to stationary point A for i in range(N.size(x_A)): model.set('x_0[' + str(i + 1) + ']', x_A[i]) # Set the target values to stationary point B model.set('rr_ref', rr_0_B) model.set('y1_ref', y_B[0]) n_e = 100 # Number of elements hs = N.ones(n_e) * 1. / n_e # Equidistant points n_cp = 3 # Number of collocation points in each element # Solve the optimization problem if with_blocking_factors: # Blocking factors for control parametrization blocking_factors = 4 * N.ones(n_e / 4, dtype=N.int) opt_opts = model.optimize_options() opt_opts['n_e'] = n_e opt_opts['n_cp'] = n_cp opt_opts['hs'] = hs opt_opts['blocking_factors'] = blocking_factors opt_res = model.optimize(options=opt_opts) else: opt_res = model.optimize(options={'n_e': n_e, 'n_cp': n_cp, 'hs': hs}) # Extract variable profiles u1_res = opt_res['rr'] u1_ref_res = opt_res['rr_ref'] y1_ref_res = opt_res['y1_ref'] time = opt_res['time'] x_res = [] x_ref_res = [] for i in range(N.size(x_B)): x_res.append(opt_res['x[' + str(i + 1) + ']']) y_res = [] for i in range(N.size(x_B)): y_res.append(opt_res['y[' + str(i + 1) + ']']) if with_blocking_factors: assert N.abs(opt_res.final('cost') / 1.e1 - 2.8549683) < 1e-3 else: assert N.abs(opt_res.final('cost') / 1.e1 - 2.8527469) < 1e-3 # Plot the results if with_plots: plt.figure(1) plt.clf() plt.hold(True) plt.subplot(311) plt.title('Liquid composition') plt.plot(time, x_res[0]) plt.ylabel('x1') plt.grid() plt.subplot(312) plt.plot(time, x_res[16]) plt.ylabel('x17') plt.grid() plt.subplot(313) plt.plot(time, x_res[31]) plt.ylabel('x32') plt.grid() plt.xlabel('t [s]') plt.show() # Plot the results plt.figure(2) plt.clf() plt.hold(True) plt.subplot(311) plt.title('Vapor composition') plt.plot(time, y_res[0]) plt.plot(time, y1_ref_res, '--') plt.ylabel('y1') plt.grid() plt.subplot(312) plt.plot(time, y_res[16]) plt.ylabel('y17') plt.grid() plt.subplot(313) plt.plot(time, y_res[31]) plt.ylabel('y32') plt.grid() plt.xlabel('t [s]') plt.show() plt.figure(3) plt.clf() plt.hold(True) plt.plot(time, u1_res) plt.ylabel('u') plt.plot(time, u1_ref_res, '--') plt.xlabel('t [s]') plt.title('Reflux ratio') plt.grid() plt.show()
def run_demo(with_plots=True): """ This example is based on a system composed of two Continously Stirred Tank Reactors (CSTRs) in series. 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. For more information about the DAE initialization algorithm, see http://www.jmodelica.org/page/10. 2. An optimal control problem is solved where the objective is to transfer the state of the system from stationary point A to point B. Here, it is also demonstrated how to set parameter values in a model. More information about the simultaneous optimization algorithm can be found at http://www.jmodelica.org/page/10. 3. The optimization result is saved to file and then the important variables are plotted. """ curr_dir = os.path.dirname(os.path.abspath(__file__)) # Compile the stationary initialization model into a DLL jmu_name = compile_jmu("CSTRLib.Components.Two_CSTRs_stat_init", os.path.join(curr_dir, "files", "CSTRLib.mo")) # Load a JMU model instance init_model = JMUModel(jmu_name) # Set inputs for Stationary point A u1_0_A = 1 u2_0_A = 1 init_model.set('u1', u1_0_A) init_model.set('u2', u2_0_A) # Solve the DAE initialization system with Ipopt init_result = init_model.initialize() # Store stationary point A CA1_0_A = init_model.get('CA1') CA2_0_A = init_model.get('CA2') T1_0_A = init_model.get('T1') T2_0_A = init_model.get('T2') # Print some data for stationary point A print(' *** Stationary point A ***') print('u = [%f,%f]' % (u1_0_A, u2_0_A)) print('CAi = [%f,%f]' % (CA1_0_A, CA2_0_A)) print('Ti = [%f,%f]' % (T1_0_A, T2_0_A)) # Set inputs for stationary point B u1_0_B = 1.1 u2_0_B = 0.9 init_model.set('u1', u1_0_B) init_model.set('u2', u2_0_B) # Solve the DAE initialization system with Ipopt init_result = init_model.initialize() # Stationary point B CA1_0_B = init_model.get('CA1') CA2_0_B = init_model.get('CA2') T1_0_B = init_model.get('T1') T2_0_B = init_model.get('T2') # Print some data for stationary point B print(' *** Stationary point B ***') print('u = [%f,%f]' % (u1_0_B, u2_0_B)) print('CAi = [%f,%f]' % (CA1_0_B, CA2_0_B)) print('Ti = [%f,%f]' % (T1_0_B, T2_0_B)) ## Set up and solve an optimal control problem. # Compile the Model jmu_name = compile_jmu("CSTR2_Opt", [ os.path.join(curr_dir, "files", "CSTRLib.mo"), os.path.join(curr_dir, "files", "CSTR2_Opt.mop") ], compiler_options={ 'enable_variable_scaling': True, 'index_reduction': True }) # Load the dynamic library and XML data model = JMUModel(jmu_name) # Initialize the model with parameters # Initialize the model to stationary point A model.set('cstr.two_CSTRs_Series.CA1_0', CA1_0_A) model.set('cstr.two_CSTRs_Series.CA2_0', CA2_0_A) model.set('cstr.two_CSTRs_Series.T1_0', T1_0_A) model.set('cstr.two_CSTRs_Series.T2_0', T2_0_A) # Set the target values to stationary point B model.set('u1_ref', u1_0_B) model.set('u2_ref', u2_0_B) model.set('CA1_ref', CA1_0_B) model.set('CA2_ref', CA2_0_B) # Initialize the optimization 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 res = model.optimize( options={ 'n_e': n_e, 'hs': hs, 'n_cp': n_cp, 'blocking_factors': 2 * N.ones(n_e / 2, dtype=N.int), 'IPOPT_options': { 'tol': 1e-4 } }) # Extract variable profiles CA1_res = res['cstr.two_CSTRs_Series.CA1'] CA2_res = res['cstr.two_CSTRs_Series.CA2'] T1_res = res['cstr.two_CSTRs_Series.T1'] T2_res = res['cstr.two_CSTRs_Series.T2'] u1_res = res['cstr.two_CSTRs_Series.u1'] u2_res = res['cstr.two_CSTRs_Series.u2'] der_u2_res = res['der_u2'] CA1_ref_res = res['CA1_ref'] CA2_ref_res = res['CA2_ref'] u1_ref_res = res['u1_ref'] u2_ref_res = res['u2_ref'] cost = res['cost'] time = res['time'] assert N.abs(res.final('cost') - 1.4745648e+01) < 1e-3 # Plot the results if with_plots: plt.figure(1) plt.clf() plt.hold(True) plt.subplot(211) plt.plot(time, CA1_res) plt.plot([time[0], time[-1]], [CA1_ref_res, CA1_ref_res], '--') plt.ylabel('Concentration reactor 1 [J/l]') plt.grid() plt.subplot(212) plt.plot(time, CA2_res) plt.plot([time[0], time[-1]], [CA2_ref_res, CA2_ref_res], '--') plt.ylabel('Concentration reactor 2 [J/l]') plt.xlabel('t [s]') plt.grid() plt.show() plt.figure(2) plt.clf() plt.hold(True) plt.subplot(211) plt.plot(time, T1_res) plt.ylabel('Temperature reactor 1 [K]') plt.grid() plt.subplot(212) plt.plot(time, T2_res) plt.ylabel('Temperature reactor 2 [K]') plt.grid() plt.xlabel('t [s]') plt.show() plt.figure(3) plt.clf() plt.hold(True) plt.subplot(211) plt.plot(time, u2_res) plt.ylabel('Input 2') plt.plot([time[0], time[-1]], [u2_ref_res, u2_ref_res], '--') plt.grid() plt.subplot(212) plt.plot(time, der_u2_res) plt.ylabel('Derivative of input 2') plt.xlabel('t [s]') plt.grid() plt.show()