% Code to plot simulation results from sh_testrig_pressure_compensator
%% Plot Description:
%
% This plot shows the behavior of the pressure compensator, which controls
% the pressure drop across Fixed Orifice 2.  As the downstream loads (variable orifices) are
% adjusted, the pressure drop across Fixed Orifice 2 stays constant at the
% set level in the pressure compensator.  When the pressure drop across the
% loads gets too high, the pressure drop across Fixed Orifice 2 then falls
% below the set level in the pressure compensator.

% Copyright 2015 The MathWorks, Inc.

% Generate simulation results if they don't exist
if ~exist('simlog_sh_testrig_pressure_compensator', 'var')
    sim('sh_testrig_pressure_compensator')
end

% Reuse figure if it exists, else create new figure
if ~exist('h1_sh_testrig_pressure_compensator', 'var') || ...
        ~isgraphics(h1_sh_testrig_pressure_compensator, 'figure')
    h1_sh_testrig_pressure_compensator = figure('Name', 'sh_testrig_pressure_compensator');
end
figure(h1_sh_testrig_pressure_compensator)
clf(h1_sh_testrig_pressure_compensator)

% Get simulation results
simlog_t = simlog_sh_testrig_pressure_compensator.Fixed_Orifice_1.p.series.time;
simlog_orif1p = simlog_sh_testrig_pressure_compensator.Fixed_Orifice_1.p.series.values('Pa');
simlog_orif2p = simlog_sh_testrig_pressure_compensator.Fixed_Orifice_2.p.series.values('Pa');
simlog_orifS = simlog_sh_testrig_pressure_compensator.Load_Orifice_1.S.series.values('m');

temp_fixOrif1A = str2num(get_param([bdroot '/Fixed Orifice 1'],'area'));
temp_fixOrif2A = str2num(get_param([bdroot '/Fixed Orifice 2'],'area'));

temp_orif1InitO = str2num(get_param([bdroot '/Load Orifice 1'],'x_0'));
temp_orif2InitO = str2num(get_param([bdroot '/Load Orifice 2'],'x_0'));
temp_orif1w = str2num(get_param([bdroot '/Load Orifice 1'],'w'));
temp_orif2w = str2num(get_param([bdroot '/Load Orifice 2'],'w'));

% Plot results
simlog_handles(1) = subplot(2, 1, 1);
plot(simlog_t, simlog_orif1p, 'LineWidth', 1)
hold on
plot(simlog_t, simlog_orif2p, 'LineWidth', 2,'LineStyle','--')
hold off
grid on
title('Pressure Drop across Fixed Orifices')
ylabel('Pressure (Pa)')
legend({'Fixed Orifice 1','Fixed Orifice 2'},'Location','NorthEast');

simlog_handles(2) = subplot(2, 1, 2);
plot(simlog_t, max((temp_orif1InitO+simlog_orifS)*temp_orif1w,0), 'LineWidth', 1);
hold on
plot(simlog_t, max((temp_orif2InitO+simlog_orifS)*temp_orif2w,0), 'LineWidth', 2,'LineStyle','--');
hold off
grid on
title('Load Orifice Area');
ylabel('Area (m^2)');
xlabel('Time (s)');
legend({'Load Orifice 1','Load Orifice 2'},'Location','NorthEast');

linkaxes(simlog_handles, 'x')

% Remove temporary variables
clear simlog_t simlog_handles
clear simlog_orif1p simlog_orif2p simlog_orifS
clear temp_orif1w temp_fixOrif1A temp_orif1InitO 
clear temp_orif2w temp_fixOrif2A temp_orif2InitO 
