% Code to plot simulation results from sh_testrig_segmented_pipeline
%% Plot Description:
%
% The plot below shows the pressure in each of the chambers in the
% segmented pipeline.  The orifice at the outlet of the pipeline closes
% suddenly, creating pressure waves within the pipeline (water hammer
% effect).

% Copyright 2015 The MathWorks, Inc.

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

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

% Get simulation results
simlog_t = simlog_sh_testrig_segmented_pipeline.Orifice.flow_rate.series.time;
simlog_orifS = simlog_sh_testrig_segmented_pipeline.Orifice.S.series.values('m');

temp_spids = simlog_sh_testrig_segmented_pipeline.Pipeline.childIds;
temp_chinds = find(~cellfun(@isempty,strfind(temp_spids,'chamber_')));
simlog_spchp = zeros(length(simlog_t),length(temp_chinds));
for temp_chi=1:length(temp_chinds)
    simlog_spchp(:,temp_chi) = eval(['simlog_sh_testrig_segmented_pipeline.Pipeline.' temp_spids{temp_chinds(temp_chi)} '.pressure.series.values(''Pa'');']); 
end

temp_orifInitO = str2num(get_param([bdroot '/Orifice'],'x_0'));
temp_orifw = str2num(get_param([bdroot '/Orifice'],'w'));
temp_orifori = str2num(get_param([bdroot '/Orifice'],'or'));
if(temp_orifori==2)
    temp_orifori = -1;
end

% Plot results
simlog_handles(1) = subplot(2, 1, 1);
plot(simlog_t, simlog_spchp, 'LineWidth', 1)
grid on
title(['Pressures in Segmented Pipeline Chambers 1-' num2str(length(temp_chinds))])
ylabel('Pressure (Pa)')

simlog_handles(2) = subplot(2, 1, 2);
plot(simlog_t, max((temp_orifInitO+simlog_orifS*temp_orifori)*temp_orifw,0), 'LineWidth', 1)
grid on
title('Orifice Opening')
ylabel('Opening (m^2)')
xlabel('Time (s)')

linkaxes(simlog_handles, 'x')

% Remove temporary variables
clear simlog_t simlog_spchp simlog_orifS simlog_handles
clear temp_chinds temp_orifInitO temp_orifw temp_orifAw temp_orifori temp_spids temp_chi
