Ejemplo n.º 1
0
def setup():
    """ 
    Setup test module. Compile test model (only needs to be done once) and 
    set log level. 
    """
    oc = OptimicaCompiler()
    oc.set_boolean_option('state_start_values_fixed', True)
    OptimicaCompiler.set_log_level(OptimicaCompiler.LOG_ERROR)
    oc.compile_model(fpath, cpath, target='ipopt')
Ejemplo n.º 2
0
int = N.int32
N.int = N.int32

# set paths
jm_home = os.environ.get('JMODELICA_HOME')
path_to_examples = os.path.join(jm_home, "Python", "jmodelica", "examples")
path_to_tests = os.path.join(jm_home, "Python", "jmodelica", "tests")
# get a compiler
oc = OptimicaCompiler()

# compile VDP
model_vdp = os.path.join("files", "VDP.mo")
fpath_vdp = os.path.join(path_to_examples, model_vdp)
cpath_vdp = "VDP_pack.VDP_Opt"
fname_vdp = cpath_vdp.replace('.', '_', 1)
oc.set_boolean_option('state_start_values_fixed', True)
oc.compile_model(fpath_vdp, cpath_vdp, target='ipopt')

# constants used in TestJMIModel
eval_alg = jmi.JMI_DER_CPPAD
sparsity = jmi.JMI_DER_SPARSE
indep_vars = jmi.JMI_DER_ALL

# compile CSTR with alias variables elimination
model_cstr = os.path.join("files", "CSTR.mo")
fpath_cstr = os.path.join(path_to_examples, model_cstr)
cpath_cstr = "CSTR.CSTR_Opt"
fname_cstr = cpath_cstr.replace('.', '_', 1)
oc.set_boolean_option('eliminate_alias_variables', True)
oc.compile_model(fpath_cstr, cpath_cstr, target='ipopt')
Ejemplo n.º 3
0
from jmodelica.tests import testattr

from jmodelica.compiler import OptimicaCompiler
import jmodelica as jm

jm_home = jm.environ['JMODELICA_HOME']
path_to_examples = os.path.join('Python', 'jmodelica', 'examples')

model = os.path.join('files', 'Pendulum_pack.mo')
fpath = os.path.join(jm_home, path_to_examples, model)
cpath = "Pendulum_pack.Pendulum_Opt"

OptimicaCompiler.set_log_level(OptimicaCompiler.LOG_ERROR)
oc = OptimicaCompiler()
oc.set_boolean_option('state_start_values_fixed', True)


@testattr(stddist=True)
def test_optimica_compile():
    """
    Test that compilation is possible with optimicacompiler
    and that all obligatory files are created. 
    """

    # detect platform specific shared library file extension
    suffix = ''
    if sys.platform == 'win32':
        suffix = '.dll'
    elif sys.platform == 'darwin':
        suffix = '.dylib'
Ejemplo n.º 4
0
def run_demo(with_plots=True):
    """Demonstrate how to solve a dynamic optimization
    problem based on an inverted pendulum system."""

    oc = OptimicaCompiler()
    oc.set_boolean_option('state_start_values_fixed', True)

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

    # Comile the Optimica model first to C code and
    # then to a dynamic library
    oc.compile_model(curr_dir + "/files/Pendulum_pack.mo",
                     "Pendulum_pack.Pendulum_Opt",
                     target='ipopt')

    # Load the dynamic library and XML data
    pend = jmi.Model("Pendulum_pack_Pendulum_Opt")

    # Initialize the mesh
    n_e = 50  # Number of elements
    hs = N.ones(n_e) * 1. / n_e  # Equidistant points
    n_cp = 3
    # Number of collocation points in each element

    # Create an NLP object
    nlp = ipopt.NLPCollocationLagrangePolynomials(pend, n_e, hs, n_cp)

    # Create an Ipopt NLP object
    nlp_ipopt = ipopt.CollocationOptimizer(nlp)

    # Solve the optimization problem
    nlp_ipopt.opt_sim_ipopt_solve()

    # Write to file. The resulting file can also be
    # loaded into Dymola.
    nlp.export_result_dymola()

    # Load the file we just wrote to file
    res = jmodelica.io.ResultDymolaTextual(
        'Pendulum_pack_Pendulum_Opt_result.txt')

    # Extract variable profiles
    theta = res.get_variable_data('pend.theta')
    dtheta = res.get_variable_data('pend.dtheta')
    x = res.get_variable_data('pend.x')
    dx = res.get_variable_data('pend.dx')
    u = res.get_variable_data('u')

    cost = res.get_variable_data('cost')
    assert N.abs(cost.x[-1] - 1.2921683e-01) < 1e-3, \
           "Wrong value of cost function in pendulum.py"

    if with_plots:
        # Plot
        plt.figure(1)
        plt.clf()
        plt.subplot(211)
        plt.plot(theta.t, theta.x)
        plt.grid()
        plt.ylabel('th')

        plt.subplot(212)
        plt.plot(theta.t, theta.x)
        plt.grid()
        plt.ylabel('dth')
        plt.xlabel('time')
        plt.show()

        plt.figure(2)
        plt.clf()
        plt.subplot(311)
        plt.plot(x.t, x.x)
        plt.grid()
        plt.ylabel('x')

        plt.subplot(312)
        plt.plot(dx.t, dx.x)
        plt.grid()
        plt.ylabel('dx')
        plt.xlabel('time')

        plt.subplot(313)
        plt.plot(u.t, u.x)
        plt.grid()
        plt.ylabel('u')
        plt.xlabel('time')
        plt.show()
Ejemplo n.º 5
0
def run_demo(with_plots=True):
    """Optimal control of the quadruple tank process."""

    oc = OptimicaCompiler()
    oc.set_boolean_option('state_start_values_fixed', True)

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

    # Compile the Optimica model first to C code and
    # then to a dynamic library
    oc.compile_model(curr_dir + "/files/QuadTank.mo",
                     "QuadTank_pack.QuadTank_Opt",
                     target='ipopt')

    # Load the dynamic library and XML data
    qt = jmi.Model("QuadTank_pack_QuadTank_Opt")

    # Define inputs for operating point A
    u_A = N.array([2., 2])

    # Define inputs for operating point B
    u_B = N.array([2.5, 2.5])

    x_0 = N.ones(4) * 0.01

    def res(y, t):
        for i in range(4):
            qt.get_x()[i] = y[i]
        qt.jmimodel.ode_f()
        return qt.get_dx()[0:4]

    # Compute stationary state values for operating point A
    qt.set_u(u_A)
    #qt.getPI()[21] = u_A[0]
    #qt.getPI()[22] = u_A[1]

    t_sim = N.linspace(0., 2000., 500)
    y_sim = int.odeint(res, x_0, t_sim)

    x_A = y_sim[-1, :]

    if with_plots:
        # Plot
        plt.figure(1)
        plt.clf()
        plt.subplot(211)
        plt.plot(t_sim, y_sim[:, 0:4])
        plt.grid()

    # Compute stationary state values for operating point A
    qt.set_u(u_B)

    t_sim = N.linspace(0., 2000., 500)
    y_sim = int.odeint(res, x_0, t_sim)

    x_B = y_sim[-1, :]

    if with_plots:
        # Plot
        plt.figure(1)
        plt.subplot(212)
        plt.plot(t_sim, y_sim[:, 0:4])
        plt.grid()
        plt.show()

    qt.get_pi()[13] = x_A[0]
    qt.get_pi()[14] = x_A[1]
    qt.get_pi()[15] = x_A[2]
    qt.get_pi()[16] = x_A[3]

    qt.get_pi()[17] = x_B[0]
    qt.get_pi()[18] = x_B[1]
    qt.get_pi()[19] = x_B[2]
    qt.get_pi()[20] = x_B[3]
    qt.get_pi()[21] = u_B[0]
    qt.get_pi()[22] = u_B[1]

    # Solve optimal control problem

    # Initialize the mesh
    n_e = 50  # Number of elements
    hs = N.ones(n_e) * 1. / n_e  # Equidistant points
    n_cp = 3
    # Number of collocation points in each element

    # Create an NLP object
    nlp = ipopt.NLPCollocationLagrangePolynomials(qt, n_e, hs, n_cp)

    # Create an Ipopt NLP object
    nlp_ipopt = ipopt.CollocationOptimizer(nlp)

    #nlp_ipopt.opt_sim_ipopt_set_string_option("derivative_test","first-order")
    nlp_ipopt.opt_sim_ipopt_set_int_option("max_iter", 500)

    # Solve the optimization problem
    nlp_ipopt.opt_sim_ipopt_solve()

    # Write to file. The resulting file can also be
    # loaded into Dymola.
    nlp.export_result_dymola()

    # Load the file we just wrote to file
    res = jmodelica.io.ResultDymolaTextual(
        'QuadTank_pack_QuadTank_Opt_result.txt')

    # Extract variable profiles
    x1 = res.get_variable_data('x1')
    x2 = res.get_variable_data('x2')
    x3 = res.get_variable_data('x3')
    x4 = res.get_variable_data('x4')
    u1 = res.get_variable_data('u1')
    u2 = res.get_variable_data('u2')

    cost = res.get_variable_data('cost')

    assert N.abs(cost.x[-1] - 5.0333257e+02) < 1e-3, \
           "Wrong value of cost function in quadtank.py"

    if with_plots:
        # Plot
        plt.figure(2)
        plt.clf()
        plt.subplot(411)
        plt.plot(x1.t, x1.x)
        plt.grid()
        plt.ylabel('x1')

        plt.subplot(412)
        plt.plot(x2.t, x2.x)
        plt.grid()
        plt.ylabel('x2')

        plt.subplot(413)
        plt.plot(x3.t, x3.x)
        plt.grid()
        plt.ylabel('x3')

        plt.subplot(414)
        plt.plot(x4.t, x4.x)
        plt.grid()
        plt.ylabel('x4')
        plt.show()

        plt.figure(3)
        plt.clf()
        plt.subplot(211)
        plt.plot(u1.t, u1.x)
        plt.grid()
        plt.ylabel('u1')

        plt.subplot(212)
        plt.plot(u2.t, u2.x)
        plt.grid()
        plt.ylabel('u2')

    if __name__ == "__main__":
        run_demo()
Ejemplo n.º 6
0
def run_demo(with_plots=True):
    """Demonstrate how to solve a minimum time
    dynamic optimization problem based on a
    Van der Pol oscillator system."""

    oc = OptimicaCompiler()
    oc.set_boolean_option('state_start_values_fixed',True)

    curr_dir = os.path.dirname(os.path.abspath(__file__));
    
    # Compile the Optimica model first to C code and
    # then to a dynamic library
    oc.compile_model(curr_dir+"/files/VDP.mo",
                     "VDP_pack.VDP_Opt",
                     target='ipopt')

    # Load the dynamic library and XML data
    vdp=jmi.Model("VDP_pack_VDP_Opt")

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

    # Create an NLP object
    nlp = ipopt.NLPCollocationLagrangePolynomials(vdp,n_e,hs,n_cp)

    # Create an Ipopt NLP object
    nlp_ipopt = ipopt.CollocationOptimizer(nlp)

#    nlp_ipopt.opt_sim_ipopt_set_string_option("derivative_test","first-order")
    nlp_ipopt.opt_sim_ipopt_set_int_option("max_iter",500)

    # Solve the optimization problem
    nlp_ipopt.opt_sim_ipopt_solve()

    # Retreive the number of points in each column in the
    # result matrix
    n_points = nlp.opt_sim_get_result_variable_vector_length()

    # Write to file. The resulting file can also be
    # loaded into Dymola.
    nlp.export_result_dymola()
    
    # Load the file we just wrote to file
    res = jmodelica.io.ResultDymolaTextual('VDP_pack_VDP_Opt_result.txt')

    # Extract variable profiles
    x1=res.get_variable_data('x1')
    x2=res.get_variable_data('x2')
    u=res.get_variable_data('u')

    cost=res.get_variable_data('cost')
    
    assert N.abs(cost.x[-1] - 2.3469089e+01) < 1e-3, \
            "Wrong value of cost function in vdp.py"  

    if with_plots:
        # Plot
        plt.figure(1)
        plt.clf()
        plt.subplot(311)
        plt.plot(x1.t,x1.x)
        plt.grid()
        plt.ylabel('x1')
        
        plt.subplot(312)
        plt.plot(x2.t,x2.x)
        plt.grid()
        plt.ylabel('x2')
        
        plt.subplot(313)
        plt.plot(u.t,u.x)
        plt.grid()
        plt.ylabel('u')
        plt.xlabel('time')
        plt.show()
Ejemplo n.º 7
0
def run_demo(with_plots=True):
    """Demonstrate how to solve a dynamic optimization
    problem based on an inverted pendulum system."""

    oc = OptimicaCompiler()
    oc.set_boolean_option('state_start_values_fixed', True)

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

    # Comile the Optimica model first to C code and
    # then to a dynamic library
    oc.compile_model(curr_dir + "/files/Pendulum_pack.mo",
                     "Pendulum_pack.Pendulum_Opt",
                     target='ipopt')

    # Load the dynamic library and XML data
    pend = jmi.Model("Pendulum_pack_Pendulum_Opt")

    # Initialize the mesh
    n_e = 50  # Number of elements
    hs = N.ones(n_e) * 1. / n_e  # Equidistant points
    n_cp = 3
    # Number of collocation points in each element

    # Create an NLP object
    nlp = jmi.SimultaneousOptLagPols(pend, n_e, hs, n_cp)

    # Create an Ipopt NLP object
    nlp_ipopt = jmi.JMISimultaneousOptIPOPT(nlp.jmi_simoptlagpols)

    # Solve the optimization problem
    nlp_ipopt.opt_sim_ipopt_solve()

    # Retreive the number of points in each column in the
    # result matrix
    n_points = nlp.jmi_simoptlagpols.opt_sim_get_result_variable_vector_length(
    )
    n_points = n_points.value

    # Create result data vectors
    p_opt = N.zeros(1)
    t_ = N.zeros(n_points)
    dx_ = N.zeros(5 * n_points)
    x_ = N.zeros(5 * n_points)
    u_ = N.zeros(n_points)
    w_ = N.zeros(n_points)

    # Get the result
    nlp.jmi_simoptlagpols.opt_sim_get_result(p_opt, t_, dx_, x_, u_, w_)

    if with_plots:
        # Plot
        plt.figure(1)
        plt.clf()
        plt.subplot(211)
        plt.plot(t_, x_[n_points:2 * n_points])
        plt.grid()
        plt.ylabel('th')

        plt.subplot(212)
        plt.plot(t_, x_[n_points * 2:n_points * 3])
        plt.grid()
        plt.ylabel('dth')
        plt.xlabel('time')
        plt.show()

        plt.figure(2)
        plt.clf()
        plt.subplot(311)
        plt.plot(t_, x_[n_points * 3:n_points * 4])
        plt.grid()
        plt.ylabel('x')

        plt.subplot(312)
        plt.plot(t_, x_[n_points * 4:n_points * 5])
        plt.grid()
        plt.ylabel('dx')
        plt.xlabel('time')

        plt.subplot(313)
        plt.plot(t_, u_)
        plt.grid()
        plt.ylabel('u')
        plt.xlabel('time')
        plt.show()
Ejemplo n.º 8
0
#     You should have received a copy of the GNU Lesser General Public
#     License along with CasADi; if not, write to the Free Software
#     Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
#
#
# -*- coding: utf-8 -*-
import casadi
from jmodelica.compiler import OptimicaCompiler
from jmodelica.compiler import ModelicaCompiler

import matplotlib.pyplot as plt

import numpy as NP

oc = OptimicaCompiler()
oc.set_boolean_option('generate_xml_equations', True)
#oc.compile_model("VDP_Opt","VDP.mo")

#mc = ModelicaCompiler()
#mc.compile_model("VDP","VDP2.mo")

# Allocate a parser and load the xml
#parser = casadi.FMIParser('VDP_Opt.xml')

parser = casadi.FMIParser(
    '/home/janderss/dev/OPTICON-SOFTWARE/swig_interface/test/xml_files/VDP_pack_VDP_Opt.xml'
)

# Dump representation to screen
print "XML representation"
print parser
Ejemplo n.º 9
0
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}
    }
    """

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

    # Create a Modelica compiler instance
    mc = ModelicaCompiler()

    # Compile the stationary initialization model into a DLL
    mc.compile_model(curr_dir + "/files/DISTLib.mo",
                     "DISTLib.Binary_Dist_initial",
                     target='ipopt')

    # Load a model instance into Python
    init_model = jmi.Model("DISTLib_Binary_Dist_initial")

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

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

    # Set inputs for Stationary point A
    u1_0_A = 3.0
    init_model.set_value('u1', u1_0_A)

    # init_nlp_ipopt.init_opt_ipopt_set_string_option("derivative_test","first-order")
    #init_nlp_ipopt.init_opt_ipopt_set_int_option("max_iter",5)

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

    # 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_value('y' + str(i + 1))
        x_A[i] = init_model.get_value('x' + str(i + 1))
        print '(' + str(i + 1) + ', %f, %f)' % (x_A[i], y_A[i])

    # Set inputs for stationary point B
    u1_0_B = 3.0 - 1
    init_model.set_value('u1', u1_0_B)

    # init_nlp_ipopt.init_opt_ipopt_set_string_option("derivative_test","first-order")
    #init_nlp_ipopt.init_opt_ipopt_set_int_option("max_iter",5)

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

    # 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_value('y' + str(i + 1))
        x_B[i] = init_model.get_value('x' + str(i + 1))
        print '(' + str(i + 1) + ', %f, %f)' % (x_B[i], y_B[i])

    # ## Set up and solve an optimal control problem.

    # Create an OptimicaCompiler instance
    oc = OptimicaCompiler()

    # Generate initial equations for states even if fixed=false
    oc.set_boolean_option('state_start_values_fixed', True)

    # Compil the Model
    oc.compile_model(
        (curr_dir + "/files/DISTLib.mo", curr_dir + "/files/DISTLib_Opt.mo"),
        "DISTLib_Opt.Binary_Dist_Opt1",
        target='ipopt')

    # Load the dynamic library and XML data
    model = jmi.Model("DISTLib_Opt_Binary_Dist_Opt1")

    # Initialize the model with parameters

    # Initialize the model to stationary point A
    for i in range(N.size(x_A)):
        model.set_value('x' + str(i + 1) + '_0', x_A[i])

    # Set the target values to stationary point B
    model.set_value('u1_ref', u1_0_B)
    model.set_value('y1_ref', y_B[0])

    # 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

    # Create an NLP object representing the discretized problem
    nlp = ipopt.NLPCollocationLagrangePolynomials(model, n_e, hs, n_cp)

    # Create an Ipopt NLP object
    nlp_ipopt = ipopt.CollocationOptimizer(nlp)

    #nlp_ipopt.opt_sim_ipopt_set_string_option("derivative_test","first-order")

    # If the convergence is slow, may increase tolerance.
    #nlp_ipopt.opt_sim_ipopt_set_num_option("tol",0.0001)

    #Solve the optimization problem
    nlp_ipopt.opt_sim_ipopt_solve()

    # Write to file. The resulting file  can be
    # loaded into Dymola.
    nlp.export_result_dymola()

    # Load the file we just wrote
    res = jmodelica.io.ResultDymolaTextual(
        'DISTLib_Opt_Binary_Dist_Opt1_result.txt')

    # Extract variable profiles
    u1_res = res.get_variable_data('u1')
    u1_ref_res = res.get_variable_data('u1_ref')
    y1_ref_res = res.get_variable_data('y1_ref')

    x_res = []
    x_ref_res = []
    for i in range(N.size(x_B)):
        x_res.append(res.get_variable_data('x' + str(i + 1)))

    y_res = []
    for i in range(N.size(x_B)):
        y_res.append(res.get_variable_data('y' + str(i + 1)))

    # Plot the results
    if with_plots:
        plt.figure(1)
        plt.clf()
        plt.hold(True)
        plt.subplot(311)
        plt.title('Liquid composition')
        plt.plot(x_res[0].t, x_res[0].x)
        plt.ylabel('x1')
        plt.grid()
        plt.subplot(312)
        plt.plot(x_res[16].t, x_res[16].x)
        plt.ylabel('x17')
        plt.grid()
        plt.subplot(313)
        plt.plot(x_res[31].t, x_res[31].x)
        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(y_res[0].t, y_res[0].x)
        plt.plot(y1_ref_res.t, y1_ref_res.x, '--')
        plt.ylabel('y1')
        plt.grid()
        plt.subplot(312)
        plt.plot(y_res[16].t, y_res[16].x)
        plt.ylabel('y17')
        plt.grid()
        plt.subplot(313)
        plt.plot(y_res[31].t, y_res[31].x)
        plt.ylabel('y32')
        plt.grid()
        plt.xlabel('t [s]')
        plt.show()

        plt.figure(3)
        plt.clf()
        plt.hold(True)
        plt.plot(u1_res.t, u1_res.x)
        plt.ylabel('u')
        plt.plot(u1_ref_res.t, u1_ref_res.x, '--')
        plt.xlabel('t [s]')
        plt.title('Reflux ratio')
        plt.grid()
        plt.show()
Ejemplo n.º 10
0
def run_demo(with_plots=True):
    """Optimal control of the quadruple tank process."""

    oc = OptimicaCompiler()
    oc.set_boolean_option('state_start_values_fixed', True)

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

    # Compile the Optimica model first to C code and
    # then to a dynamic library
    oc.compile_model(curr_dir + "/files/QuadTank.mo",
                     "QuadTank_pack.QuadTank_Opt",
                     target='ipopt')

    # Load the dynamic library and XML data
    qt = jmi.Model("QuadTank_pack_QuadTank_Opt")

    # Define inputs for operating point A
    u_A = N.array([2., 2])

    # Define inputs for operating point B
    u_B = N.array([2.5, 2.5])

    x_0 = N.ones(4) * 0.01

    def res(y, t):
        for i in range(4):
            qt.get_x()[i] = y[i]
        qt.jmimodel.ode_f()
        return qt.get_dx()[0:4]

    # Compute stationary state values for operating point A
    qt.set_u(u_A)
    #qt.getPI()[21] = u_A[0]
    #qt.getPI()[22] = u_A[1]

    t_sim = N.linspace(0., 2000., 500)
    y_sim = int.odeint(res, x_0, t_sim)

    x_A = y_sim[-1, :]

    if with_plots:
        # Plot
        plt.figure(1)
        plt.clf()
        plt.subplot(211)
        plt.plot(t_sim, y_sim[:, 0:4])
        plt.grid()

    # Compute stationary state values for operating point A
    qt.set_u(u_B)

    t_sim = N.linspace(0., 2000., 500)
    y_sim = int.odeint(res, x_0, t_sim)

    x_B = y_sim[-1, :]

    if with_plots:
        # Plot
        plt.figure(1)
        plt.subplot(212)
        plt.plot(t_sim, y_sim[:, 0:4])
        plt.grid()
        plt.show()

    qt.get_pi()[13] = x_A[0]
    qt.get_pi()[14] = x_A[1]
    qt.get_pi()[15] = x_A[2]
    qt.get_pi()[16] = x_A[3]

    qt.get_pi()[17] = x_B[0]
    qt.get_pi()[18] = x_B[1]
    qt.get_pi()[19] = x_B[2]
    qt.get_pi()[20] = x_B[3]
    qt.get_pi()[21] = u_B[0]
    qt.get_pi()[22] = u_B[1]

    # Solve optimal control problem

    # Initialize the mesh
    n_e = 50  # Number of elements
    hs = N.ones(n_e) * 1. / n_e  # Equidistant points
    n_cp = 3
    # Number of collocation points in each element

    # Create an NLP object
    nlp = jmi.SimultaneousOptLagPols(qt, n_e, hs, n_cp)

    # Create an Ipopt NLP object
    nlp_ipopt = jmi.JMISimultaneousOptIPOPT(nlp.jmi_simoptlagpols)

    #nlp_ipopt.opt_sim_ipopt_set_string_option("derivative_test","first-order")
    nlp_ipopt.opt_sim_ipopt_set_int_option("max_iter", 500)

    # Solve the optimization problem
    nlp_ipopt.opt_sim_ipopt_solve()

    # Retreive the number of points in each column in the
    # result matrix
    n_points = nlp.jmi_simoptlagpols.opt_sim_get_result_variable_vector_length(
    )
    n_points = n_points.value

    # Create result data vectors
    p_opt = N.zeros(1)
    t_ = N.zeros(n_points)
    dx_ = N.zeros(5 * n_points)
    x_ = N.zeros(5 * n_points)
    u_ = N.zeros(2 * n_points)
    w_ = N.zeros(n_points)

    # Get the result
    nlp.jmi_simoptlagpols.opt_sim_get_result(p_opt, t_, dx_, x_, u_, w_)

    if with_plots:
        # Plot
        plt.figure(2)
        plt.clf()
        plt.subplot(411)
        plt.plot(t_, x_[0:n_points])
        plt.grid()
        plt.ylabel('x1')

        plt.subplot(412)
        plt.plot(t_, x_[n_points:n_points * 2])
        plt.grid()
        plt.ylabel('x2')

        plt.subplot(413)
        plt.plot(t_, x_[n_points * 2:n_points * 3])
        plt.grid()
        plt.ylabel('x3')

        plt.subplot(414)
        plt.plot(t_, x_[n_points * 3:n_points * 4])
        plt.grid()
        plt.ylabel('x4')
        plt.show()

        plt.figure(3)
        plt.clf()
        plt.subplot(211)
        plt.plot(t_, u_[0:n_points])
        plt.grid()
        plt.ylabel('u1')

        plt.subplot(212)
        plt.plot(t_, u_[n_points:n_points * 2])
        plt.grid()
        plt.ylabel('u2')

    if __name__ == "__main__":
        run_demo()
Ejemplo n.º 11
0
def run_demo(with_plots=True):
    """Demonstrate how to solve a simple
    parameter estimation problem."""

    oc = OptimicaCompiler()
    oc.set_boolean_option('state_start_values_fixed', True)

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

    # Compile the Optimica model first to C code and
    # then to a dynamic library
    oc.compile_model(curr_dir + "/files/ParameterEstimation_1.mo",
                     "ParEst.ParEst",
                     target='ipopt')

    # Load the dynamic library and XML data
    model = jmi.Model("ParEst_ParEst")

    # Retreive parameter and variable vectors
    pi = model.get_pi()
    x = model.get_x()
    dx = model.get_dx()
    u = model.get_u()
    w = model.get_w()

    # Set model input
    w[0] = 1

    # ODE right hand side
    # This can be done since DAE residuals 1 and 2
    # are written on simple "ODE" form: f(x,u)-\dot x = 0
    def F(xx, t):
        dx[0] = 0.  # Set derivatives to zero
        dx[1] = 0.
        x[0] = xx[0]  # Set states
        x[1] = xx[1]
        res = N.zeros(5)
        # Create residual vector
        model.jmimodel.dae_F(res)  # Evaluate DAE residual
        return N.array([res[1], res[2]])

    # Simulate model to get measurement data
    N_points = 100  # Number of points in simulation
    t0 = 0
    tf = 15
    t_sim = N.linspace(t0, tf, num=N_points)
    xx0 = N.array([0., 0.])
    xx = integr.odeint(F, xx0, t_sim)

    # Extract measurements
    N_points_meas = 11
    t_meas = N.linspace(t0, 10, num=N_points_meas)
    xx_meas = integr.odeint(F, xx0, t_meas)

    # Add measurement noice
    xx_meas[:, 0] = xx_meas[:, 0] + N.random.random(N_points_meas) * 0.2 - 0.1

    # Set parameters corresponding to measurement data in model
    pi[4:15] = t_meas
    pi[15:26] = xx_meas[:, 0]

    if with_plots:
        # Plot simulation
        plt.figure(1)
        plt.clf()
        plt.subplot(211)
        plt.plot(t_sim, xx[:, 0])
        plt.grid()
        plt.plot(t_meas, xx_meas[:, 0], 'x')
        plt.ylabel('x1')

        plt.subplot(212)
        plt.plot(t_sim, xx[:, 1])
        plt.grid()
        plt.ylabel('x2')
        plt.show()

    # Initialize the mesh
    n_e = 50  # Number of elements
    hs = N.ones(n_e) * 1. / n_e  # Equidistant points
    n_cp = 3
    # Number of collocation points in each element

    # Create an NLP object
    nlp = jmi.SimultaneousOptLagPols(model, n_e, hs, n_cp)

    # Create an Ipopt NLP object
    nlp_ipopt = jmi.JMISimultaneousOptIPOPT(nlp.jmi_simoptlagpols)

    #nlp_ipopt.opt_sim_ipopt_set_string_option("derivative_test","first-order")
    nlp_ipopt.opt_sim_ipopt_set_int_option("max_iter", 500)

    # Solve the optimization problem
    nlp_ipopt.opt_sim_ipopt_solve()

    # Retreive the number of points in each column in the
    # result matrix
    n_points = nlp.jmi_simoptlagpols.opt_sim_get_result_variable_vector_length(
    )
    n_points = n_points.value

    # Create optimization result data vectors
    p_opt = N.zeros(2)
    t_ = N.zeros(n_points)
    dx_ = N.zeros(2 * n_points)
    x_ = N.zeros(2 * n_points)
    u_ = N.zeros(n_points)
    w_ = N.zeros(4 * n_points)

    # Get the result
    nlp.jmi_simoptlagpols.opt_sim_get_result(p_opt, t_, dx_, x_, u_, w_)

    if with_plots:
        # Plot optimization result
        plt.figure(2)
        plt.clf()
        plt.subplot(211)
        plt.plot(t_, w_[n_points:2 * n_points])
        plt.plot(t_meas, xx_meas[:, 0], 'x')
        plt.grid()
        plt.ylabel('y')

        plt.subplot(212)
        plt.plot(t_, w_[0:n_points])
        plt.grid()
        plt.ylabel('u')
        plt.show()

        print("** Optimal parameter values: **")
        print("w = %f" % pi[0])
        print("z = %f" % pi[1])
Ejemplo n.º 12
0
def run_demo(with_plots=True):
    """Demonstrate how to solve a minimum time
    dynamic optimization problem based on a
    Van der Pol oscillator system."""

    oc = OptimicaCompiler()
    oc.set_boolean_option('state_start_values_fixed', True)

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

    # Compile the Optimica model first to C code and
    # then to a dynamic library
    oc.compile_model(curr_dir + "/files/VDP.mo",
                     "VDP_pack.VDP_Opt",
                     target='ipopt')

    # Load the dynamic library and XML data
    vdp = jmi.Model("VDP_pack_VDP_Opt")

    # Initialize the mesh
    n_e = 50  # Number of elements
    hs = N.ones(n_e) * 1. / n_e  # Equidistant points
    n_cp = 3
    # Number of collocation points in each element

    # Create an NLP object
    nlp = jmi.SimultaneousOptLagPols(vdp, n_e, hs, n_cp)

    # Create an Ipopt NLP object
    nlp_ipopt = jmi.JMISimultaneousOptIPOPT(nlp.jmi_simoptlagpols)

    #    nlp_ipopt.opt_sim_ipopt_set_string_option("derivative_test","first-order")
    nlp_ipopt.opt_sim_ipopt_set_int_option("max_iter", 500)

    # Solve the optimization problem
    nlp_ipopt.opt_sim_ipopt_solve()

    # Retreive the number of points in each column in the
    # result matrix
    n_points = nlp.jmi_simoptlagpols.opt_sim_get_result_variable_vector_length(
    )
    n_points = n_points.value

    # Create result data vectors
    p_opt = N.zeros(1)
    t_ = N.zeros(n_points)
    dx_ = N.zeros(3 * n_points)
    x_ = N.zeros(3 * n_points)
    u_ = N.zeros(n_points)
    w_ = N.zeros(n_points)

    # Get the result
    nlp.jmi_simoptlagpols.opt_sim_get_result(p_opt, t_, dx_, x_, u_, w_)

    if with_plots:
        # Plot
        plt.figure(1)
        plt.clf()
        plt.subplot(311)
        plt.plot(t_, x_[0:n_points])
        plt.grid()
        plt.ylabel('x1')

        plt.subplot(312)
        plt.plot(t_, x_[n_points:n_points * 2])
        plt.grid()
        plt.ylabel('x2')

        plt.subplot(313)
        plt.plot(t_, u_[0:n_points])
        plt.grid()
        plt.ylabel('u')
        plt.xlabel('time')
        plt.show()