function onlineMILP
% formulate MPC problem for a pwa-sin-cos system
%
% Example 15.1
% Two Mode System
% Francesco Borrelli Feb 2010
% M. Herceg, Automatic Control Laboratory, ETH Zurich, 2012, 2014
%
% requires MPT3


close all


%% core code
% compile and load hysdel model
file = which('bm99.hys');
if isempty(file)
    error('Please add the folder with the file "bm99.hys" to Matlab path.');
end
if ~isequal(fileparts(file),pwd)
    % copy the hysdel file to local directory if not present
    copyfile(file,pwd);
end
model = MLDSystem('bm99.hys');


% state penalty
model.x.penalty = InfNormFunction(eye(2));
% input penalty
model.u.penalty = InfNormFunction(1);
% activate terminal state constraint
model.x.with('terminalSet');
% equality constraints x_{N}=0
model.x.terminalSet = Polyhedron('Ae',eye(2),'be',zeros(2,1));
horizon = 3;
% online controller
ctrlonline = MPCController(model, horizon);

% extract the data to YALMIP
Y = ctrlonline.toYALMIP;

% formulate the optimization problem with x0 as parameters
problem = Opt(Y.constraints, Y.objective, Y.internal.parameters, Y.variables.u)

% extract the data
% min 0.5*u'*H*u + (pF*th+f)'*u + th'*Y*th + C*th + c
%          s.t.  A*u <= b  + pB*th
%                Ae*u = be + pE*th
%                lb  <= u <= ub

% extract the matrices by name
problem.pF
problem.f
problem.Y
problem.A
problem.b
problem.pB
problem.Ae
problem.be
problem.pE

% evaluate the online controller for an initial condition x0;
x0=[2;0.1];
U = ctrlonline.evaluate(x0)


end