function pwa_openloop
% open loop simulation of a pwa-sin-cos system
%
% M. Herceg, Automatic Control Laboratory, ETH Zurich, 2012, 2014
%
% requires MPT3

close all

%% printing parameters
label_font_size = 14;
tick_font_size = 10;
line_width = 0.8;
axeswidth=0.2;
% create folder for storing figures
mkdir('figures');
figure_name = ['.',filesep,'figures',filesep,'pwasincos_ol'];



%% 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');

% convert to PWA model
pwa_model = model.toPWA;

% set initial condition x(0) = [1 0]
x0 = [1; 0];
pwa_model.initialize(x0);

% simulate with zero input over 20 samples
horizon = 20;
data = pwa_model.simulate(zeros(1,horizon));

% sample time
Ts = 0.5; 
T = 0:Ts:horizon*Ts;

% find the local modes over which the pwa model evolved
xu = [data.X(:,1:size(data.U,2));data.U];
mode = pwa_model.domain.contains(xu);
[index_mode,c]=find(mode);


% plot the first state trajectory
subplot(2,1,1)
h1=plot(T,data.X(1,:),'k','linewidth',line_width);
grid on
hx1=xlabel('time');
hy1=ylabel('$x_1$');
set(gca,'YTickLabel',{''})
set(gca,'XTickLabel',{''})
set(gca,'LineWidth',axeswidth)
set(gca, 'FontSize', tick_font_size);
set(hx1, 'FontSize', label_font_size);
set(hy1, 'FontSize', label_font_size);


subplot(2,1,2)
h2=stairs(T,[index_mode(1); index_mode],'k','linewidth',line_width);
grid on
axis([T(1) T(end) 0 3]);
hx2=xlabel('time');
hy2=ylabel('mode');
set(gca,'YTickLabel',{''})
set(gca,'XTickLabel',{''})
set(hx2, 'FontSize', label_font_size);
set(hy2, 'FontSize', label_font_size);
set(gca, 'FontSize', tick_font_size);
set(gca,'LineWidth',axeswidth)


%% save book figure
saveas(gcf, [figure_name '_matlab'], 'fig');

laprint(gcf, [figure_name '_tex'],'scalefonts','off');

end