% Code to plot simulation results from sscfluids_directional_valve_dynamics
% Plot Description:
%
% The plots below show the valve opening area (orifice A-T) for ideal valve
% and valve with dynamics for different input force frequencies.

% Copyright 2017 The MathWorks, Inc.

% Reuse figure if it exists, else create new figure
if ~exist('h1_sscfluids_directional_valve_dynamics', 'var') || ...
        ~isgraphics(h1_sscfluids_directional_valve_dynamics, 'figure')
    h1_sscfluids_directional_valve_dynamics = figure('Name', 'sscfluids_directional_valve_dynamics');
end
% Prepare figure
figure(h1_sscfluids_directional_valve_dynamics)
h1_sscfluids_directional_valve_dynamics.Units = 'normalized';
clf(h1_sscfluids_directional_valve_dynamics)
h1_sscfluids_directional_valve_dynamics.Position=[0.41 0.4, 0.3, 0.5];
grid on
hold on

% Valve mechanical components
k_spring = 150; % [N/m]
D_damper = 5;   % [N/m/s]
valve_upper_limit = 8e-3;  % [m]
valve_lower_limit = -8e-3; % [m]
Mass = 0.1;     % [kg]

% Input force frequency vector
frequency_vec = [3, 15, 40];

n = length(frequency_vec);
simlog_handles = ones(n, 1);

% Make test run more quickly
set_param(bdroot, 'FastRestart', 'on')

for i=1:n
   
    frequency  = frequency_vec(i);
    time = 1/frequency*5*pi;
    set_param(bdroot,'StopTime', num2str(time));
    
    out=sim(bdroot);
    simlog=get(out, 'simlog_sscfluids_directional_valve_dynamics');
    
    % Get simulation results
    simlog_time = simlog.x4_Way_Directional_Valve_TL_Ideal.A.T.series.time;
    A_T_valve_area_ideal = simlog.x4_Way_Directional_Valve_TL_Ideal.orifice_A_T.orifice_area.series.values('m^2');
    A_T_valve_area_dynamic = simlog.x4_Way_Directional_Valve_TL_Dynamics.orifice_A_T.orifice_area.series.values('m^2');
    
    % Plot results
    simlog_handles(i) = subplot(n,1,i);
    plot(simlog_handles(i), simlog_time, A_T_valve_area_ideal, simlog_time, A_T_valve_area_dynamic)
    title(simlog_handles(i), ['Frequency = ', num2str(frequency), ' (rad/s)'])
    xlim([0 time])
    ylim([-0.2e-4 3.2e-4])
    grid on
end

set_param(bdroot, 'FastRestart', 'off')

ylabel(simlog_handles(2), 'Valve opening area A-T (m^2)')
xlabel(simlog_handles(3), 'Time (s)')
legend(simlog_handles(1), 'Without dynamics', 'With dynamics', 'Location','northeast')
hold off

% Remove temporary variables
clear simlog_time A_T_valve_area_ideal A_T_valve_area_dynamic ...
      B_T_valve_area_ideal B_T_valve_area_dynamic simlog_handles ...
      frequency_vec out simlog i n
  