Beispiel #1
0
def mpc_init(s, a):
    apm(s, a, 'clear all')
    apm_load(s, a, 'model.apm')
    csv_load(s, a, 'data.csv')
    apm_option(s, a, 'nlc.imode', 6)
    apm_option(s, a, 'nlc.nodes', 3)
    apm_option(s, a, 'nlc.web_plot_freq', 1)
    apm_info(s, a, 'FV', 'K')
    apm_info(s, a, 'FV', 'tau')
    apm_info(s, a, 'MV', 'u')
    apm_info(s, a, 'CV', 'y')
    # status, whether the optimizer can use it
    apm_option(s, a, 'K.status', 0)
    apm_option(s, a, 'tau.status', 0)
    apm_option(s, a, 'u.status', 1)
    apm_option(s, a, 'y.status', 1)
    # feedback status
    apm_option(s, a, 'K.fstatus', 1)
    apm_option(s, a, 'tau.fstatus', 1)
    apm_option(s, a, 'u.fstatus', 0)
    apm_option(s, a, 'y.fstatus', 1)
    # constraints
    apm_option(s, a, 'u.upper', 100)
    apm_option(s, a, 'u.lower', 0)
    # reference trajectory tuning
    apm_option(s, a, 'nlc.traj_init', 2)
    apm_option(s, a, 'nlc.traj_open', 0.5)
    apm_option(s, a, 'y.tau', 12)
    msg = 'Successful controller initialization'
    return msg
def apm_optimize(model_name, par_input, input_name, var_list, S_list,
                 flux_list, output_array, output_header, output_filename):
    ## connect to server and create model
    server, app = connect(model_name)
    ## designate parameters to change
    apm_info(server, app, 'FV', input_name)
    ## measure time required for optimization
    start_time = time.time()
    #### start optimization
    for i in range(len(par_input)):
        ## change external condition
        apm_meas(server, app, input_name, par_input[i])
        ## solve on APM server
        solver_output = apm(server, app, 'solve')
        res = apm_sol(server, app)
        if (not apm_tag(server, app, 'nlc.appstatus')):
            solver_output = apm(server, app, 'solve')
            res = apm_sol(server, app)
        ## save current optimization results
        print(res['growth_rate'], par_input[i],
              apm_tag(server, app, 'nlc.appstatus'))
        var = np.array([res[v] for v in var_list])
        S = np.array([res[s] for s in S_list])
        flux = np.array([res[f] for f in flux_list])
        output_array[i] = np.concatenate(
            ([par_input[i]], [res['growth_rate']], var, S, flux))
    ## stop the time
    print("--- %s seconds ---" % (time.time() - start_time))
    ## write results into csv file
    output_array = output_array[::-1]
    df = pd.DataFrame(output_array, columns=output_header)
    df.to_csv(path + output_filename + filename_suffix + '.csv', index=0)
    return df
def init_mhe(s,a):
    apm(s,a,'clear all')
    # load model and data files
    apm_load(s,a,'mhe.apm')
    csv_load(s,a,'mhe.csv')
    # classify variables
    apm_info(s,a,'FV','ua')
    apm_info(s,a,'MV','tc')
    apm_info(s,a,'SV','ca')
    apm_info(s,a,'CV','t')
    # options
    apm_option(s,a,'nlc.imode',5) # 5 = MHE
    apm_option(s,a,'nlc.ev_type',1) # 1 = l1-norm, 2 = sq_error
    apm_option(s,a,'nlc.nodes',3) # 3 = collocation nodes
    apm_option(s,a,'nlc.solver',3) # 3 = IPOPT
    # FV tuning
    apm_option(s,a,'ua.status',1) # estimate this parameter
    apm_option(s,a,'ua.fstatus',0) # no measurement (feedback status)
    apm_option(s,a,'ua.lower',10000) # lower bound
    apm_option(s,a,'ua.upper',100000) # upper bound
    # MV tuning
    apm_option(s,a,'tc.status',0) # don't estimate this parameter
    apm_option(s,a,'tc.fstatus',1) # measurement available (feedback status)
    # CV tuning
    apm_option(s,a,'t.status',1) # estimate this parameter
    apm_option(s,a,'t.fstatus',1) # measurement available (feedback status)
    apm_option(s,a,'t.meas_gap',0.1) # measurement deadband gap

    msg = 'MHE Initialized'
    return msg
Beispiel #4
0
def mhe_init():
    apm(s, b, 'clear all')

    # load model and data
    apm_load(s, b, 'model.apm')
    csv_load(s, b, 'mhe.csv')

    # configure MV / CV
    apm_info(s, b, 'FV', 'Kp')
    apm_info(s, b, 'FV', 'tau')
    apm_info(s, b, 'FV', 'zeta')
    apm_info(s, b, 'FV', 'TK_ss')
    apm_info(s, b, 'MV', 'Vin')
    apm_info(s, b, 'CV', 'TK')

    # dynamic estimation
    apm_option(s, b, 'nlc.imode', 5)
    apm_option(s, b, 'nlc.solver', 3)

    # tune FV
    apm_option(s, b, 'Kp.dmax', 0.05)
    apm_option(s, b, 'Kp.lower', 0.3)
    apm_option(s, b, 'Kp.upper', 0.4)
    apm_option(s, b, 'tau.dmax', 2.0)
    apm_option(s, b, 'tau.lower', 40.0)
    apm_option(s, b, 'tau.upper', 60.0)
    apm_option(s, b, 'zeta.dmax', 0.05)
    apm_option(s, b, 'zeta.lower', 1.3)
    apm_option(s, b, 'zeta.upper', 1.7)
    apm_option(s, b, 'TK_ss.dmax', 1.0)
    apm_option(s, b, 'TK_ss.lower', 290.0)
    apm_option(s, b, 'TK_ss.upper', 310.0)
    # turn on FVs as degrees of freedom
    apm_option(s, b, 'Kp.status', 1)
    apm_option(s, b, 'tau.status', 1)
    apm_option(s, b, 'zeta.status', 1)
    apm_option(s, b, 'TK_ss.status', 1)

    apm_option(s, b, 'Kp.fstatus', 0)
    apm_option(s, b, 'tau.fstatus', 0)
    apm_option(s, b, 'zeta.fstatus', 0)
    apm_option(s, b, 'TK_ss.fstatus', 0)

    # read Vin, don't let optimize use MV
    apm_option(s, b, 'Vin.status', 0)
    apm_option(s, b, 'Vin.fstatus', 1)
    # include CV in objective function
    apm_option(s, b, 'TK.status', 1)
    apm_option(s, b, 'TK.fstatus', 1)

    # web-viewer option, update every second
    apm_option(s, b, 'nlc.web_plot_freq', 1)

    msg = 'initialization complete'

    return msg
Beispiel #5
0
def mpc_init():
    apm(s, c, 'clear all')

    # load model and data
    apm_load(s, c, 'model.apm')
    csv_load(s, c, 'control.csv')

    # configure MV / CV
    apm_info(s, c, 'FV', 'Kp')
    apm_info(s, c, 'FV', 'tau')
    apm_info(s, c, 'FV', 'zeta')
    apm_info(s, c, 'FV', 'TK_ss')
    apm_info(s, c, 'MV', 'Vin')
    apm_info(s, c, 'CV', 'TK')

    # dynamic control
    apm_option(s, c, 'nlc.imode', 6)
    apm_option(s, c, 'nlc.solver', 3)
    apm_option(s, c, 'nlc.hist_hor', 600)

    # tune MV
    # delta MV movement penalty
    apm_option(s, c, 'Vin.dcost', 0.01)
    # penalize voltage use (energy savings)
    apm_option(s, c, 'Vin.cost', 0.01)
    # limit MV movement each cycle
    apm_option(s, c, 'Vin.dmax', 100)
    # MV limits
    apm_option(s, c, 'Vin.upper', 150)
    apm_option(s, c, 'Vin.lower', 0)

    # tune CV
    # how fast to reach setpoint
    apm_option(s, c, 'TK.tau', 10)
    # trajectory type
    apm_option(s, c, 'TK.tr_init', 2)

    # let optimizer use MV
    apm_option(s, c, 'Vin.status', 1)
    # include CV in objective function
    apm_option(s, c, 'TK.status', 1)

    # feedback status (whether we have measurements)
    apm_option(s, c, 'Vin.fstatus', 0)
    apm_option(s, c, 'TK.fstatus', 1)
    apm_option(s, c, 'Kp.fstatus', 1)
    apm_option(s, c, 'tau.fstatus', 1)
    apm_option(s, c, 'zeta.fstatus', 1)
    apm_option(s, c, 'TK_ss.fstatus', 1)

    # web-viewer option, update every second
    apm_option(s, c, 'nlc.web_plot_freq', 1)

    msg = 'initialization complete'

    return msg
Beispiel #6
0
def sim_init(s, a):
    apm(s, a, 'clear all')
    apm_load(s, a, 'process.apm')
    csv_load(s, a, 'process.csv')
    apm_option(s, a, 'nlc.imode', 4)
    apm_option(s, a, 'nlc.nodes', 3)
    apm_info(s, a, 'SV', 'y')
    apm_info(s, a, 'FV', 'u')
    apm_option(s, a, 'u.fstatus', 1)
    msg = 'Successful simulator initialization'
    return msg
def connect(model_name):
    ## connect to server
    server = 'http://byu.apmonitor.com'
    app = model_name
    apm(server, app, 'clear all')
    ## load model file
    apm_load(server, app, model_name + '.apm')
    ## select steady-state optimization
    apm_option(server, app, 'nlc.imode', 3)
    ## pption to select solver (1=APOPT, 2=BPOPT, 3=IPOPT)
    apm_option(server, app, 'nlc.solver', 3)
    ## change iteration and tolerance to get a more precise maximum
    apm_option(server, app, 'nlc.max_iter', 1000000)
    apm_option(server, app, 'nlc.max_time', 500)
    return server, app
Beispiel #8
0
def mpc(T_meas, params):
    # input new parameter values
    K = params[0]
    tau = params[1]
    zeta = params[2]
    TK_ss = params[3]
    apm_meas(s, c, 'Kp', K)
    apm_meas(s, c, 'tau', tau)
    apm_meas(s, c, 'zeta', zeta)
    apm_meas(s, c, 'TK_ss', TK_ss)

    # input measurement
    apm_meas(s, c, 'TK', T_meas)

    # solve MPC
    output = apm(s, c, 'solve')
    #print(output)

    # test for successful solution
    if (apm_tag(s, c, 'nlc.appstatus') == 1):
        # retrieve the first Vin value
        Vin = apm_tag(s, c, 'Vin.Newval')
    else:
        # display output for debugging
        print(output)
        # not successful, set voltage to zero
        Vin = 0

    return Vin
Beispiel #9
0
def mpc(s, a, inputs):
    sp = inputs[0]
    y_meas = inputs[1]
    apm_meas(s, a, 'y', y_meas)
    #   apm_meas(s,a,'k',k_pred)
    #   apm_meas(s,a,'tau',tau_pred)
    sphi = sp + 0.1
    splo = sp - 0.1
    apm_option(s, a, 'y.sphi', sphi)
    apm_option(s, a, 'y.splo', splo)
    apm_option(s, a, 'y.sp', sp)
    apm(s, a, 'solve')
    u = apm_tag(s, a, 'u.newval')
    y_pred = apm_tag(s, a, 'y.pred[1]')
    y_pred5 = apm_tag(s, a, 'y.pred[5]')
    return u, y_pred, y_pred5
Beispiel #10
0
def mhe(T_meas, Vin):
    params = np.empty(4)
    # input measurements
    apm_meas(s, b, 'TK', T_meas)
    apm_meas(s, b, 'Vin', Vin)

    # solve MPC
    output = apm(s, b, 'solve')
    #print(output)

    # test for successful solution
    if (apm_tag(s, b, 'nlc.appstatus') == 1):
        # retrieve the K and tau values

        # option #2 retrieval (apm_tag)
        Kp = apm_tag(s, b, 'Kp.Newval')
        tau = apm_tag(s, b, 'tau.Newval')
        zeta = apm_tag(s, b, 'zeta.Newval')
        TK_ss = apm_tag(s, b, 'TK_ss.Newval')
    else:
        # display output for debugging
        print(output)
        # not successful, set default parameters
        Kp = 0.359806899452
        tau = 47.7311112863
        zeta = 1.56206738412
        TK_ss = 300.0
    params[0] = Kp
    params[1] = tau
    params[2] = zeta
    params[3] = TK_ss

    return params
def change_par_opt(model_name, par, par_name):
    ## connect to server and create model
    server, app = connect(model_name)
    ## designate parameters to change
    apm_info(server, app, 'FV', par_name)
    apm_meas(server, app, par_name, par)
    ## solve on APM server
    solver_output = apm(server, app, 'solve')
    res = apm_sol(server, app)
    counter = 0
    while ((not apm_tag(server, app, 'nlc.appstatus')) and (counter < 10)):
        solver_output = apm(server, app, 'solve')
        res = apm_sol(server, app)
        counter += 1
        print(counter)

    return res['growth_rate'] * 1.0e-8 * res['rho']
def init_sim(s,a):
    apm(s,a,'clear all')
    # load model and data files
    apm_load(s,a,'sim.apm')
    csv_load(s,a,'sim.csv')
    # classify variables
    apm_info(s,a,'FV','ua')
    apm_info(s,a,'MV','tc')
    apm_info(s,a,'SV','ca')
    apm_info(s,a,'SV','t')
    # options
    apm_option(s,a,'nlc.imode',4) # 4 = simulation
    apm_option(s,a,'nlc.nodes',3) # 3 = collocation nodes
    apm_option(s,a,'nlc.solver',3) # 3 = IPOPT
    # MV tuning
    apm_option(s,a,'tc.fstatus',1) # measurement available (feedback status)
    msg = 'Simulator Initialized'
    return msg
Beispiel #13
0
def mhe_init():
    apm(s, b, 'clear all')

    # load model and data
    apm_load(s, b, 'mhe.apm')
    csv_load(s, b, 'mhe.csv')

    # configure MV / CV
    apm_info(s, b, 'FV', 'K')
    apm_info(s, b, 'FV', 'tau')
    apm_info(s, b, 'MV', 'Vin')
    apm_info(s, b, 'CV', 'TDegF')

    # dynamic estimation
    apm_option(s, b, 'nlc.imode', 5)
    apm_option(s, b, 'nlc.solver', 3)

    # tune FV
    apm_option(s, b, 'K.dmax', 0.1)
    apm_option(s, b, 'K.lower', 0.1)
    apm_option(s, b, 'K.upper', 0.5)
    apm_option(s, b, 'tau.dmax', 10.0)
    apm_option(s, b, 'tau.lower', 100.0)
    apm_option(s, b, 'tau.upper', 500.0)
    apm_option(s, b, 'K.status', 1)
    apm_option(s, b, 'tau.status', 1)
    apm_option(s, b, 'K.fstatus', 0)
    apm_option(s, b, 'tau.fstatus', 0)

    # read Vin, don't let optimize use MV
    apm_option(s, b, 'Vin.status', 0)
    apm_option(s, b, 'Vin.fstatus', 1)
    # include CV in objective function
    apm_option(s, b, 'TDegF.status', 1)
    apm_option(s, b, 'TDegF.fstatus', 1)

    # web-viewer option, update every second
    apm_option(s, b, 'nlc.web_plot_freq', 1)

    msg = 'initialization complete'

    return msg
Beispiel #14
0
def mpc(T_meas):
    # input measurement
    apm_meas(s, c, 'TK', T_meas)

    # solve MPC
    output = apm(s, c, 'solve')
    #print(output)

    # test for successful solution
    if (apm_tag(s, c, 'nlc.appstatus') == 1):
        # retrieve the first Vin value
        Vin = apm_tag(s, c, 'Vin.Newval')
    else:
        # display output for debugging
        print(output)
        # not successful, set voltage to zero
        Vin = 0

    return Vin
Beispiel #15
0
def mhe(T_meas, Vin):
    # input measurements
    apm_meas(s, b, 'TdegF', T_meas)
    apm_meas(s, b, 'Vin', Vin)

    # solve MPC
    output = apm(s, b, 'solve')
    #print(output)

    # test for successful solution
    if (apm_tag(s, b, 'nlc.appstatus') == 1):
        # retrieve the K and tau values

        # option #2 retrieval (apm_tag)
        K = apm_tag(s, b, 'K.Newval')
        tau = apm_tag(s, b, 'tau.Newval')
    else:
        # display output for debugging
        print(output)
        # not successful, set voltage to zero
        K = 0.25
        tau = 60.0

    return K, tau
Beispiel #16
0
def sim(s, a, u, K):
    apm_meas(s, a, 'u', u)
    apm_meas(s, a, 'k', K)
    apm(s, a, 'solve')
    y = apm_tag(s, a, 'y.model')
    return y
ax.set_yticks([-0.15, 0.0, 0.15])
ax.set_ylim([-0.16, 0.16])
ax.set_ylabel('sensitivity')
ax.set_xticklabels(labels)
plt.tight_layout()
sns.despine()
#plt.savefig( 'figure_7.pdf' )
plt.show()
#####################################################################################################################
#####################################################################################################################
#####################################################################################################################

#####################################################################################################################
#####################################################################################################################
#####################################################################################################################
'''
server = 'http://byu.apmonitor.com'
app = 'heterogeneous_production'
apm(server, app,'clear all')
apm_load(server, app, 'heterogeneous_production.apm')
apm_option(server,app,'nlc.imode',3)
apm_option(server,app,'nlc.solver',3)
apm_option(server,app,'nlc.max_iter',1000000)
apm_option(server,app,'nlc.max_time',500)
solver_output = apm(server,app,'solve')
res = apm_sol(server,app)
'''
'''
Ieff = np.array([ 7.0, 8.0, 10.0, 15.0, 20.0, 25.0, 27.5, 30.0, 40.0, 55.0, 70.0, 80.0, 90.0, 100.0, 110.0, 
				  130.0, 150.0, 170.0, 190.0, 220.0, 330.0, 440.0, 550.0, 660.0, 770.0, 880.0, 990.0, 1000.0, 
				  1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1620.0, 1630.0, 1639.0 ])
time = np.linspace(0,cycles*dt-dt,cycles) # time points

# allocate storage
Ca_meas = np.empty(cycles)
T_meas = np.empty(cycles)
UA_mhe = np.empty(cycles)
Ca_mhe = np.empty(cycles)
T_mhe = np.empty(cycles)

for i in range (0,cycles):
    
    ## Process
    # input Tc (jacket cooling temperature)
    apm_meas(s,a1,'Tc',Tc_meas[i])
    # solve process model, 1 time step
    output = apm(s,a1,'solve')
    # retrieve Ca and T measurements from the process
    Ca_meas[i] = apm_tag(s,a1,'Ca.model')
    T_meas[i] = apm_tag(s,a1,'T.model')
    
    ## Estimator
    # input process measurements, don't use Ca_meas
    # input Tc (jacket cooling temperature)
    apm_meas(s,a2,'Tc',Tc_meas[i])
    # input T (reactor temperature)
    apm_meas(s,a2,'T',T_meas[i])
    # solve process model, 1 time step
    output = apm(s,a2,'solve')
     # check if successful
    if (apm_tag(s,a2,'nlc.appstatus')==1):
        # retrieve solution
Beispiel #19
0
# Import
from apm import *

# Select server
s = 'http://byu.apmonitor.com'

##################################
# set up reactor simulator
##################################
a = 'reactor4'
# Clear previous application
apm(s, a, 'clear all')
# Load model file
apm_load(s, a, 'cstr.apm')
# Load time points for future predictions
csv_load(s, a, 'cstr.csv')
# APM Variable Classification
# class = FV, MV, SV, CV
#   F or FV = Fixed value - parameter may change to a new value every cycle
#   M or MV = Manipulated variable - independent variable over time horizon
#   S or SV = State variable - model variable for viewing
#   C or CV = Controlled variable - model variable for control
#Parameters
FVs = 'SP', 'Cooling_Temp', 'Flow', 'Feed_Conc', 'Feed_Temp'
MVs = '---'
#Variables
SVs = 'Concentration', '---'
CVs = 'Temperature', '---'
# Set up variable classifications for data flow
for x in FVs:
    apm_info(s, a, 'FV', x)
Beispiel #20
0
import sys

sys.path.append("../")

# Import
from apm import *

# Select server
server = "http://byu.apmonitor.com"

# Application name
app = "diabetic"

# Clear previous application
apm(server, app, "clear all")

# Load model file
apm_load(server, app, "diabetic.apm")

# Load time points for future predictions
csv_load(server, app, "diabetic.csv")

# Load replay replay data for local use
data = csv.reader(open("control.csv", "r"))
replay = []
for row in data:
    replay.append(row)
len_replay = len(replay)

# APM Variable Classification
# class = FV, MV, SV, CV
Beispiel #21
0
# Import APM package
from apm import *

# define server and application
s = 'http://byu.apmonitor.com'
a = 'drill'

# Clear prior application
apm(s,a,'clear all')

# Load model file
apm_load(s,a,'drilling.apm')

# Global settings
apm_option(s,a,'nlc.solver',1)
apm_option(s,a,'nlc.max_iter',30)

# Adjustable parameters
apm_info(s,a,'FV','Ro_a_1')
apm_info(s,a,'FV','f_a_2')
apm_info(s,a,'FV','Ro_a_2')
apm_info(s,a,'FV','f_a_3')
apm_info(s,a,'FV','Ro_a_3')
apm_info(s,a,'FV','f_a_4')
apm_info(s,a,'FV','Ro_a_4')
apm_info(s,a,'FV','f_a_5')
apm_info(s,a,'FV','Ro_a_5')
apm_info(s,a,'FV','f_a_6')
apm_info(s,a,'FV','Ro_a_6')
apm_info(s,a,'FV','f_a_7')
apm_info(s,a,'FV','Ro_a_7')
Beispiel #22
0
def apm_id(data, ni, nu, ny):
    fast = False  # switch "False" for solution analysis
    obj_scale = 1
    n = np.size(data, 0)
    p = np.size(data, 1)
    no = p - ni - 1
    if no <= 0:
        print('Data file needs at least 1 column for output data')
        return
    m = max(ny, nu)

    # first column is time
    time = data[:, 0].copy()
    dt = time[1] - time[0]

    # inputs are the next column(s)
    u_ss = data[0, 1:1 + ni].copy()
    u = data[:, 1:1 + ni].copy()

    # outputs are the final column(s)
    y_ss = data[0, 1 + ni:1 + ni + no].copy()
    y = data[:, 1 + ni:1 + ni + no].copy()

    for i in range(n):
        for j in range(ni):
            u[i, j] = u[i, j] - u_ss[j]
        for j in range(no):
            y[i, j] = y[i, j] - y_ss[j]

    fid = open('myModel.apm', 'w')
    fid.write('Objects\n')
    fid.write('  sum_a[1:no] = sum(%i)\n' % ny)
    fid.write('  sum_b[1:ni][1::no] = sum(%i)\n' % nu)
    fid.write('End Objects\n')
    fid.write('  \n')
    fid.write('Connections\n')
    fid.write('  a[1:ny][1::no] = sum_a[1::no].x[1:ny]\n')
    fid.write('  b[1:nu][1::ni][1:::no] = sum_b[1::ni][1:::no].x[1:nu]\n')
    fid.write('  sum_a[1:no] = sum_a[1:no].y\n')
    fid.write('  sum_b[1:ni][1::no] = sum_b[1:ni][1::no].y\n')
    fid.write('End Connections\n')
    fid.write('  \n')
    fid.write('Constants\n')
    fid.write('  n = %s\n' % str(n))
    fid.write('  ni = %s\n' % str(ni))
    fid.write('  no = %s\n' % str(no))
    fid.write('  ny = %s\n' % str(ny))
    fid.write('  nu = %s\n' % str(nu))
    fid.write('  m = %s\n' % str(m))
    fid.write('  \n')
    fid.write('Parameters\n')
    fid.write('  a[1:ny][1::no] = 0 !>= -1 <= 1\n')
    fid.write('  b[1:nu][1::ni][1:::no] = 0\n')
    fid.write('  c[1:no] = 0\n')
    fid.write('  u[1:n][1::ni]\n')
    fid.write('  y[1:m][1::no]\n')
    fid.write('  z[1:n][1::no]\n')
    fid.write('  \n')
    fid.write('Variables\n')
    fid.write('  y[m+1:n][1::no] = 0\n')
    fid.write('  sum_a[1:no] = 0 !<= 1\n')
    fid.write('  sum_b[1:ni][1::no] = 0\n')
    fid.write('  K[1:ni][1::no] = 0 !>=0 <= 10 \n')
    fid.write('  \n')
    fid.write('Equations\n')
    fid.write('  y[m+1:n][1::no] = a[1][1::no]*y[m:n-1][1::no]')
    for j in range(1, ni + 1):
        fid.write(' + b[1][%i][1::no]*u[m:n-1][%i]' % (
            j,
            j,
        ))
        for i in range(2, nu + 1):
            fid.write(' + b[%i][%i][1::no]*u[m-%i:n-%i][%i]' % (
                i,
                j,
                i - 1,
                i,
                j,
            ))
    for i in range(2, ny + 1):
        fid.write(' + a[%i][1::no]*y[m-%i:n-%i][1::no]' % (
            i,
            i - 1,
            i,
        ))
    fid.write('\n')
    fid.write('  K[1:ni][1::no] * (1 - sum_a[1::no]) = sum_b[1:ni][1::no]\n')
    fid.write('  minimize %e * (y[m+1:n][1::no] - z[m+1:n][1::no])^2\n' %
              obj_scale)
    fid.close()

    fid = open('myData.csv', 'w')
    for j in range(1, ni + 1):
        for i in range(1, n + 1):
            fid.write('u[%i][%i], %e\n' % (
                i,
                j,
                u[i - 1, j - 1],
            ))
    for k in range(1, no + 1):
        for i in range(1, n + 1):
            fid.write('z[%i][%i], %e\n' % (
                i,
                k,
                y[i - 1, k - 1],
            ))
    for k in range(1, no + 1):
        for i in range(1, n + 1):
            fid.write('y[%i][%i], %e\n' % (
                i,
                k,
                y[i - 1, k - 1],
            ))
    fid.close()

    s = 'http://byu.apmonitor.com'
    #s = 'http://127.0.0.1'
    a = 'apm_id'
    apm(s, a, 'clear all')
    apm_load(s, a, 'myModel.apm')
    csv_load(s, a, 'myData.csv')

    apm_option(s, a, 'nlc.solver', 3)
    apm_option(s, a, 'nlc.imode', 2)
    apm_option(s, a, 'nlc.max_iter', 100)

    for i in range(1, no + 1):
        name = 'c[' + str(i) + ']'
        apm_info(s, a, 'FV', name)
        apm_option(s, a, name + '.status', 0)
    for k in range(1, no + 1):
        for i in range(1, ny + 1):
            name = 'a[' + str(i) + '][' + str(k) + ']'
            apm_info(s, a, 'FV', name)
            apm_option(s, a, name + '.status', 1)
    for k in range(1, no + 1):
        for j in range(1, nu + 1):
            for i in range(1, nu + 1):
                name = 'b[' + str(i) + '][' + str(j) + '][' + str(k) + ']'
                apm_info(s, a, 'FV', name)
                apm_option(s, a, name + '.status', 1)
    output = apm(s, a, 'solve')

    # retrieve and visualize solution
    sol = apm_sol(s, a)
    ypred = np.empty((n, no))
    for j in range(no):
        for i in range(n):
            yn = 'y[' + str(i + 1) + '][' + str(j + 1) + ']'
            ypred[i, j] = sol[yn]

    if (not fast):
        # open web-viewer
        apm_web(s, a)

        import matplotlib.pyplot as plt
        plt.figure()
        plt.subplot(2, 1, 1)
        for i in range(ni):
            plt.plot(time, u[:, i] + u_ss[i])
        plt.subplot(2, 1, 2)
        for i in range(no):
            plt.plot(time, y[:, i] + y_ss[i], 'r-')
            plt.plot(time, ypred[:, i] + y_ss[i], 'b--')
        plt.show()

    success = apm_tag(s, a, 'nlc.appstatus')
    if success == 1:
        obj = apm_tag(s, a, 'nlc.objfcnval')
        if (not fast):
            print(output)
        print('Successful solution with objective: ' + str(obj))
    else:
        print(output)
        print('Unsuccessful, do not write sysa.apm')
        return

    alpha = np.empty((ny, no))
    beta = np.empty((nu, ni, no))
    gamma = np.empty((no))
    for j in range(1, no + 1):
        for i in range(1, ny + 1):
            name = 'a[' + str(i) + '][' + str(j) + ']'
            alpha[i - 1, j - 1] = apm_tag(s, a, name + '.newval')
    for k in range(1, no + 1):
        for j in range(1, ni + 1):
            for i in range(1, nu + 1):
                name = 'b[' + str(i) + '][' + str(j) + '][' + str(k) + ']'
                beta[i - 1, j - 1, k - 1] = apm_tag(s, a, name + '.newval')
    for i in range(1, no + 1):
        name = 'c[' + str(i) + ']'
        gamma[i - 1] = apm_tag(s, a, name + '.newval')

    name = 'sysa'
    fid = open('sysa.apm', 'w')
    fid.write('Objects\n')
    fid.write(' ' + name + ' = arx\n')
    fid.write('End Objects\n')
    fid.write('\n')
    fid.write('Connections\n')
    if ni == 1:
        fid.write('  u = ' + name + '.u\n')
    else:
        fid.write('  u[1:%i] = ' % (ni, ) + name + '.u[1:%i]\n' % (ni, ))
    if no == 1:
        fid.write('  y = ' + name + '.y\n')
    else:
        fid.write('  y[1:%i] = ' % (no, ) + name + '.y[1:%i]\n' % (no, ))
    fid.write('End Connections\n')
    fid.write('\n')
    fid.write('Model \n')
    fid.write('  Parameters \n')
    if ni == 1:
        fid.write('    u = 0\n')
    else:
        fid.write('    u[1:%i] = 0\n' % (ni, ))
    fid.write('  End Parameters \n')
    fid.write('\n')
    fid.write('  Variables \n')
    if no == 1:
        fid.write('    y = 0\n')
    else:
        fid.write('    y[1:%i] = 0\n' % (no, ))
    fid.write('  End Variables \n')
    fid.write('\n')
    fid.write('  Equations \n')
    fid.write('    ! add any additional equations here \n')
    fid.write('  End Equations \n')
    fid.write('End Model \n')
    fid.write('\n')
    fid.write('File ' + name + '.txt\n')
    fid.write('  %i      ! m=number of inputs\n' % (ni, ))
    fid.write('  %i      ! p=number of outputs\n' % (no, ))
    fid.write('  %i      ! nu=number of input terms\n' % (nu, ))
    fid.write('  %i      ! ny=number of output terms\n' % (ny, ))
    fid.write('End File\n')
    fid.write('\n')
    fid.write('! Alpha matrix (ny x p)\n')
    fid.write('File ' + name + '.alpha.txt \n')
    for i in range(1, ny + 1):
        for j in range(1, no + 1):
            fid.write('  ')
            if j <= no - 1:
                fid.write('%e , ' % (alpha[i - 1, j - 1], ))
            else:
                fid.write('%e ' % (alpha[i - 1, j - 1], ))  # no comma
        fid.write('\n')
    fid.write('End File \n')
    fid.write('\n')
    fid.write('! Beta matrix (p x (nu x m))\n')
    fid.write('File ' + name + '.beta.txt \n')
    for i in range(1, no + 1):
        for j in range(1, nu + 1):
            fid.write('  ')
            for k in range(1, ni + 1):
                if k <= ni - 1:
                    fid.write('%e , ' % (beta[j - 1, k - 1, i - 1], ))
                else:
                    fid.write('%e ' % (beta[j - 1, k - 1, i - 1], ))
            fid.write('\n')
    fid.write('End File \n')
    fid.write('\n')
    fid.write('! Gamma vector (p x 1)\n')
    fid.write('File ' + name + '.gamma.txt \n')
    for i in range(1, no + 1):
        fid.write('%e \n' % (gamma[i - 1], ))
    fid.write('End File \n')
    fid.close()

    msg = 'Created ARX (Auto-Regressive eXogenous inputs) Model: sysa.apm'
    print(msg)

    return ypred + y_ss
Beispiel #23
0
#testing non-linear objective function
#tutorial: http://apmonitor.com/wiki/index.php/Main/PythonApp

#import APMonitor as apm
from apm import *
import numpy as np
import matplotlib.pyplot as plt
from random import randint

#server
s = 'http://xps.apmonitor.com'
#application name + random number
a = 'demo' + str(randint(2,999))

#clear server
apm(s,a,'clear all')

#load model
apm_load(s,a,'nlp.apm')

#change the solver
#(1=APOPT ,2=BPOPT, 3=IPOPT)
apm_option(s,a,'nlc.solver',3)

#solve
output = apm(s,a,'solve') #send solve command to server
print(output)

#s = server, a = app
#retrieve solution
#(csv,solution) = apm_sol(s,a) #solution is an array
Beispiel #24
0
# Import
from apm import *

# Select server
server = 'http://byu.apmonitor.com'

# Set application name
app = str(random.randint(1,10000))

# Clear previous application
apm(server,app,'clear all')

# Load model file
apm_load(server,app,'distill.apm')

# Load time points for future predictions
csv_load(server,app,'horizon_ctl.csv')

# Load replay replay data for local use
data = csv.reader(open('replay_ctl.csv', 'r'))
replay = []
for row in data:
	replay.append(row)
len_replay = len(replay)

# APM Variable Classification
# class = FV, MV, SV, CV
#   F or FV = Fixed value - parameter may change to a new value every cycle
#   M or MV = Manipulated variable - independent variable over time horizon
#   S or SV = State variable - model variable for viewing
#   C or CV = Controlled variable - model variable for control
Beispiel #25
0
# initial parameters
n_iter = 150  # number of cycles
x = 37.727  # true value
# filtered bias update
alpha = 0.0951
# mhe tuning
horizon = 30

# Select server
server = 'http://byu.apmonitor.com'
# Application names
app1 = 'mhe1'
app2 = 'mhe2'
# Clear previous application
apm(server, app1, 'clear all')
apm(server, app2, 'clear all')
# Load model and horizon
apm_load(server, app1, 'valve.apm')
apm_load(server, app2, 'valve.apm')
horizon = 50
apm_option(server, app1, 'apm.ctrl_hor', 50)
apm_option(server, app1, 'apm.pred_hor', 50)
apm_option(server, app2, 'apm.ctrl_hor', 50)
apm_option(server, app2, 'apm.pred_hor', 50)
# Load classifications
apm_info(server, app1, 'FV', 'd')
apm_info(server, app2, 'FV', 'd')
apm_info(server, app1, 'CV', 'flow')
apm_info(server, app2, 'CV', 'flow')
# Options
Beispiel #26
0
import sys
sys.path.append("../")

# Import
from apm import *

# Select server
server = 'http://byu.apmonitor.com'

# Application name
app = 'nlc'

# Clear previous application
apm(server,app,'clear all')

# Load model file
apm_load(server,app,'model.apm')

# Load time points for future predictions
csv_load(server,app,'model.csv')

# Load replay replay data for local use
data = csv.reader(open('replay.csv', 'r'))
replay = []
for row in data:
	replay.append(row)
len_replay = len(replay)

# APM Variable Classification
# class = FV, MV, SV, CV
#   F or FV = Fixed value - parameter may change to a new value every cycle
Beispiel #27
0
import sys
sys.path.append("../")

from apm import *

# Select server
server = 'http://byu.apmonitor.com'

# Application name
app = 'mixed_integer'

# Clear previous application
apm(server,app,'clear all')

# Load model file
apm_load(server,app,'minlp.apm')

# Option to select solver (1=APOPT, 2=BPOPT, 3=IPOPT)
apm_option(server,app,'nlc.solver',1)

# Solve on APM server
apm(server,app,'solve')

# Retrieve results
print 'Results'
y = apm_sol(server,app)
print y

# Display Results in Web Viewer 
url = apm_web_var(server,app)
	
# Add APMonitor toolbox available from
# http://apmonitor.com/wiki/index.php/Main/PythonApp
from apm import *
import Tkinter, tkFileDialog

# server and application
s = 'http://byu.apmonitor.com'
a = 'regression'

# clear any prior application
apm(s, a, 'clear all')

# load model and data files
apm_load(s, a, 'model.apm')
root = Tkinter.Tk()
filename = tkFileDialog.askopenfilename()
csv_load(s, a, filename)

# configure parameters to estimate
apm_info(s, a, 'FV', 'a')
apm_info(s, a, 'FV', 'b')
apm_info(s, a, 'FV', 'c')
apm_option(s, a, 'a.status', 1)
apm_option(s, a, 'b.status', 1)
apm_option(s, a, 'c.status', 1)
apm_option(s, a, 'nlc.imode', 2)

# solve nonlinear regression
output = apm(s, a, 'solve')
print(output)
from apm import *

s = 'http://byu.apmonitor.com'
a = 'distill_sq_error'

apm(s,a,'clear all')
apm_load(s,a,'distill.apm')
csv_load(s,a,'data.csv')

apm_option(s,a,'nlc.imode',5)
apm_option(s,a,'nlc.max_iter',100)
apm_option(s,a,'nlc.nodes',2)
apm_option(s,a,'nlc.time_shift',0)
apm_option(s,a,'nlc.ev_type',2)

apm_info(s,a,'FV','hf')
apm_info(s,a,'FV','vf')
apm_info(s,a,'FV','tray_hol')
apm_info(s,a,'FV','condenser_hol')

apm_info(s,a,'CV','x[1]')
apm_info(s,a,'CV','np')

output = apm(s,a,'solve')
print(output)

apm_option(s,a,'hf.status',1)
apm_option(s,a,'vf.status',1)
apm_option(s,a,'tray_hol.status',1)
apm_option(s,a,'condenser_hol.status',1)
Beispiel #30
0
from apm import *

s = 'http://byu.apmonitor.com'
a = 'smr'

apm(s, a, 'clear all')

apm_load(s, a, 'mpc.apm')
csv_load(s, a, 'mpc.csv')

apm_option(s, a, 'nlc.imode', 6)

apm(s, a, 'solve')

apm_web(s, a)
from apm import * # load APM Toolbox
import numpy as np

# define server and application names
s = 'http://byu.apmonitor.com'
a = 'node_test'

sol = np.empty(5) # store 5 results
i = 0
for nodes in range(2,7):
    apm(s,a,'clear all') # clear prior application
    apm_load(s,a,'collocation.apm') # load model
    csv_load(s,a,'collocation.csv') # load data
    apm_option(s,a,'nlc.imode',4)   # imode = 4, simulation
    apm_option(s,a,'nlc.nodes',nodes) # nodes (2-6)
    apm(s,a,'solve') # solve problem
    y = apm_sol(s,a) # retrieve solution
    sol[i] = y['x'][-1] # store solution (last point)
    i += 1

print sol