% Code to plot simulation results from sh_testrig_accumulator_gas
%% Plot Description:
%
% The plots below show two cycles of charging and discharging the
% accumulator.  While the orifice is closed, the supply pressure is
% increased, charging the accumulator.  The check valve holds the pressure
% in the accumulator as the supply pressure is dropped. The orifice opens,
% allowing the accumulator to discharge.  Once the accumulator is empty,
% the flow rate through the orifice stays steady at a lower value due to
% the lower supply pressure.  The orifice closes, and the cycle repeats.

% Copyright 2015 The MathWorks, Inc.

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

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

% Get simulation results
simlog_t = simlog_sh_testrig_accumulator_gas.Orifice.S.series.time;
simlog_accumq = simlog_sh_testrig_accumulator_gas.Gas_Charged_Accumulator.flow_rate.series.values('m^3/s');
simlog_orifq = simlog_sh_testrig_accumulator_gas.Orifice.flow_rate.series.values('m^3/s');
simlog_orifS = simlog_sh_testrig_accumulator_gas.Orifice.S.series.values('m');
simlog_srcp = simlog_sh_testrig_accumulator_gas.Pressure_Source.p.series.values('Pa');

% Plot results
simlog_handles(1) = subplot(2, 1, 1);
plot(simlog_t, simlog_accumq, 'LineWidth', 1)
hold on
plot(simlog_t, simlog_orifq, 'LineWidth', 1)
hold off
grid on
title('Flow Rates in System')
ylabel('Flow Rate (m^3/s)')
legend({'Accumulator','Orifice'},'Location','Best');

simlog_handles(2) = subplot(2, 1, 2);
[handles_Ax, handles_Line1, handles_Line2] = plotyy(simlog_t, simlog_srcp, simlog_t, simlog_orifS);
grid on
handles_Line1.LineWidth = 1;
handles_Line2.LineWidth = 1;
ylabel(handles_Ax(1), 'Pressure (Pa)') % left y-axis
ylabel(handles_Ax(2), 'Opening (m)') % right y-axis
set(handles_Ax(1),'YLim',[0 10e5])
title('System Inputs')
xlabel('Time (s)')
legend({'Source Pressure','Orifice Opening'},'Location','Best');

linkaxes([handles_Ax simlog_handles(1)], 'x')

% Remove temporary variables
clear simlog_t simlog_handles
clear simlog_accumq simlog_orifS simlog_orifq simlog_srcp
clear handles_Ax handles_Line2 handles_Line1 
