% Code to plot simulation results from sscfluids_diesel_injection
%% Plot Description:
%
% This plot shows the extension of each injection pump as the cam shaft
% rotates. When the extension is zero, all of the fuel has been expelled
% from the pump. The firing order of the cylinders is 1-3-4-2.

% Copyright 2019 The MathWorks, Inc.

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

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

plotExtension(simlog_sscfluids_diesel_injection)



% Plot results for Injector 1
function plotExtension(simlog)

% Get model parameters
cam_stroke = evalin(get_param('sscfluids_diesel_injection', 'modelworkspace'), 'cam_stroke');

% Get simulation results
theta = simlog.Cam_Shaft.Parabolic_Cam_1.theta.series.values('rad');
P1 = simlog.Cam_Shaft.Parabolic_Cam_1.P.series.values('m');
P2 = simlog.Cam_Shaft.Parabolic_Cam_2.P.series.values('m');
P3 = simlog.Cam_Shaft.Parabolic_Cam_3.P.series.values('m');
P4 = simlog.Cam_Shaft.Parabolic_Cam_4.P.series.values('m');

% Extract data for one rotation
I = find(diff(theta) > 0, 1) - 1;
J = find(diff(theta) < 0, 1);
theta = theta(I:J);
P1 = P1(I:J);
P2 = P2(I:J);
P3 = P3(I:J);
P4 = P4(I:J);

% Plot results
plot(theta, P1 + 3*cam_stroke, 'LineWidth', 1)
hold on
plot(theta, P3 + 2*cam_stroke, 'LineWidth', 1)
plot(theta, P4 + 1*cam_stroke, 'LineWidth', 1)
plot(theta, P2 + 0*cam_stroke, 'LineWidth', 1)
hold off
xlim([0 2*pi])
set(gca, 'YTick', [3*cam_stroke 4*cam_stroke], 'YTickLabel', {'0', 'max'})
legend('Cylinder 1', 'Cylinder 3', 'Cylinder 4', 'Cylinder 2', 'Location', 'best')
xlabel('Cam Rotation (rad)')
ylabel('Extension (mm)')
title('Injection Pump Extension')

end