% Auhor: Dinesh Krishnamoorthy, Aug 2017. Norwegian University of Science
% and Technology, Norway. 
%
% Simulating 2 gas lifted well network with a riser manifold using CasADi
% symbolic framework. https://web.casadi.org/get/ 

clear
clc

% Import CasADi
addpath ('casadi-osx-matlabR2015a-v3.4.5')
import casadi.*

%% Set parameters, initial values, upper and lower bounds

% All the parameter values are defined inside this function
par = GasLiftRiser_Param;
n_w = par.n_w; % no. of wells;

% Load initial conditions
[dx0,z0,u0,lbx,lbz,lbu,ubx,ubz,ubu] = GasLiftRiser_Initialization_bounds(par);

par.tSim = 1; % simulation interval in seconds

F   = WellSimulator(par);

%initialize simulator
xf      = dx0;
zf      = z0;
Cost    = 0;

u_in = [1;1]; % input: gas lift injection rates

nIter = 1800; % 30 min simulation time

for sim_k = 1:nIter
    
    % integrate DAE system using IDAS integrator
    Fk = F('x0',xf,'z0',zf,'p',vertcat(u_in,par.GOR));
    
    % re-initialize simulator
    xf = full(Fk.xf);
    zf = full(Fk.zf);
    
    meas.w_to(sim_k) = zf(29);
    meas.w_tg(sim_k) = zf(30);
    meas.w_gl(sim_k,:) = u_in;
    
    
end

figure(1)
clf
subplot(311)
plot(meas.w_to)
title 'Total Oil rate [kg/s]'

subplot(312)
plot(meas.w_tg)
title 'Total Gas rate [kg/s]'

subplot(313)
plot(meas.w_gl)
title 'Gaslift Inj. rate [kg/s]'