Code covered by the BSD License  

Highlights from
Impulsive Noise Meter

image thumbnail
from Impulsive Noise Meter by Edward Zechmann
Calculates Impulsive noise metrics for hazardous acoustic noise assessent

[s, round_kind, round_digits]=Impulsive_Noise_Meter(filenamesin, fileout_txt, fileout_struct, save_struct, peak_identification_time, peak_metric_time, make_plot, save_plot, dB_scale, fig_format, Tool_Name, same_ylim, min_peak, ignore_threshold, plot_str,
function [s, round_kind, round_digits]=Impulsive_Noise_Meter(filenamesin, fileout_txt, fileout_struct, save_struct, peak_identification_time, peak_metric_time, make_plot, save_plot, dB_scale, fig_format, Tool_Name, same_ylim, min_peak, ignore_threshold, plot_str, Align_peaks, portrait_landscape, peak_alignment_tol, sod, Polarized_or_ICP )
% % Impulsive_Noise_Meter: Loads sound time records, finds Peaks, calculates impulsive sound metrics
% %
% % Syntax;
% %
% % [s, round_kind, round_digits]=Impulsive_Noise_Meter(filenamesin, fileout_txt, fileout_struct,
% % save_struct, peak_identification_time, peak_metric_time, make_plot,
% % save_plot, dB_scale, fig_format, Tool_Name, same_ylim, min_peak, ignore_threshold, plot_str,
% % Align_peaks, portrait_landscape, peak_alignment_tol,
% % sod, Polarized_or_ICP );
% %
% %
% % ********************************************************************
% %
% % Description
% %
% % The main program is Main_Sound which has dialog boxes for selecting
% % filenames and other setting all of the paratmeters.  For convenience
% % the best way to use Impulsive_Noise_Meter program is to type
% % "Main_Sound" at the comand line.
% %
% % The Impulsive_Noise_Meter program controls the data flow, and calls
% % other programs to plot the time records, identify the peaks, computes
% % metrics for impulsive noise.
% %
% % Then the program finds the impulsive peaks and identifies each peak
% % with a circle in each plot and numbers the odd peaks.
% %
% % Often several channels will be used to record the same impulsive noises
% % and it is useful to compare the same impulsive peaks. This program can
% % be set to select the corresponding peaks from all of the microphone
% % channels.
% %
% % The figures are saved to a file.
% %
% % The impulsive noise metrics are then calculated for each channel.
% % A statistical analysis is performed on the impulsive metrics and the
% % metrics and statistics are saved to a text file.
% %
% % Once all of the files have been processed and saved a copy of all the
% % data is saved to a matlab structure.
% %
% % Calculation of the MIL-STD_1474 B-duration assumes that the acoustic
% % time record has been corrected for the voltage inversion due to
% % polarization.  200 Volt polarized condenser microphones have voltage
% % inversion.  ICP microphones do not have voltage inversion.
% %
% %
% % The input and output variables are described in the respective
% % sections below.
% %
% %
% %
% % ********************************************************************
% %
% % Input Variables
% %
% % filenamesin={'Impulse.mat'};    % cell array of filenames to process.
% %                                 % default is uigetfile; a user windows
% %                                 % interface for slecting files.
% %
% % fileout_txt='test.txt';         % Filename to save data to a tab
% %                                 % delimited text file.
% %
% % fileout_struct='Mertics.mat';
% %                             % File name for the output Matlab Data
% %                             % structures file.
% %                             %
% %                             % default is 'data1_struct';
% %
% % save_struct=1;              % Boolean controls whether to save all
% %                             % data to a matlab structure.
% %                             %
% %                             % default is save_struct=1;
% %
% % peak_identification_time=1; % 1 seconds.  Time interval of data to
% %                             % identify each peak.  Only one peak can
% %                             % exist in each interval of this time
% %                             % length.
% %                             %
% %                             % default is peak_identification_time=1;
% %
% % peak_metric_time=1;         % 1 seconds.  Time interval of data to
% %                             % analyze each peak.  Amount of data for
% %                             % calculating metrics and Leqs.
% %                             %
% %                             % default is peak_metric_time=1;
% %
% % make_plot=1;                % 1 to make plots for each channel
% %                             % analyzed. otherwise will not make any
% %                             % plots.
% %
% % save_plot=1;                % 1 will save a plot.
% %                             % otherwise will not not save plots
% %                             % plots will not be saved if they are not
% %                             % made the file name of hte plot is the
% %                             % filename of the data file with the
% %                             % string '_peaks' appended at the end.
% %
% % dB_scale=0;                 % 1 use a dB scale to plot sound time record
% %                             % 0 use a linear scale to plot sound time record
% %                             %
% %                             % default is dB_scale=0; plot soudn tiem record in
% %                             % a linear scale such as Pascals.
% %
% % fig_format=[1,2,3,4,5,6];   % image format for saving the plot
% %                             % 1 pdf    default is 1 suggested
% %                             %          for simple documentation
% %                             % 2 fig
% %                             % 3 jpg  (200 dpi resolution)
% %                             % 4 eps2
% %                             % 5 tiff (200 dpi resolution)
% %                             % 6 tiff (no compression) suggested for
% %                             %         publications)
% %                             %
% %                             % default is fig_format=1; pdf format
% %
% % Tool_Name='Recip Saw';      % String which is the name of the tool
% %                             % or device under test.
% %                             % Typically should be 30 caracters or less.
% %                             %
% %                             % default is Tool_Name='';
% %
% % same_ylim=1;                % 1 sets all of the limits of the y-axes
% %                             % to the same values for each channel.
% %                             % The y-limits of the sound data is
% %                             % independent of the y-limits of the
% %                             % vibrations data.
% %                             %
% %                             % if same_ylim ~= 1 then the y-axis
% %                             % limits can be differenet values.
% %                             %
% %                             % default is same_ylim=1;
% %
% % min_peak=100;               % is the peak value in dB that is the
% %                             % minimum for being considered a peak.
% %
% % ignore_threshold=0; % 1 surpresses the threshold and other requirements
% %                     % for selecting peaks
% %                     % ignore_threshold=1; % generally will find more peaks.
% %                     %
% %                     % 0 is the default.  Returns typical number of
% %                     % peaks.
% %                     %
% %                     % default is ignore_threshold=0;
% %
% % plot_str={'Protected', 'Unprotected'};
% %                             % Add a string to each subaxes indicating the
% %                             % meaning of the data.  For hearing protector
% %                             % research one microphone is under the
% %                             % hearing protector so it is 'Protected'
% %                             % and the other microphone is exposed so it is
% %                             % 'Unprotected'.
% %
% % Align_peaks=1;              % Specifies which channel to align all of the
% %                             % peaks.  can be empty then all peaks are
% %                             % found independently.
% %
% % portrait_landscape=1;       % 1 is for Potrait
% %                             % Otherwise Landscape
% %
% % peak_alignment_tol=0.25;    % This input sets the fraction of the
% %                             % datapoints of num_pts_per_pk_intrl that
% %                             % a peak can be offset.  When aligning
% %                             % peaks, the channels are synchronized,
% %                             % but temorally the peaks may be
% %                             % misaligned by a few milliseconds.  The
% %                             % alignment tolerance allows the program to
% %                             % find the maximum peak within the
% %                             % alignment tolerance.
% %                             % default is 0.25.
% %
% % sod=0;              % 1 surpress outlier detection
% %                     % 0 find the outliers and remove them from the
% %                     % statistical analysis
% %                     %
% %                     % default is sod=1;
% %
% % Polarized_or_ICP=0; % 1 Multiplies the time record p by -1 to correct for the
% %                     % voltage inversion of polarized microphones.
% %                     % 0 does not alter the time record, p.
% %                     %      (ICP, IEPE, Deltatron microphones)
% %                     %
% %                     % default value is Polarized_or_ICP=0;
% %
% %
% % ********************************************************************
% %
% % Output Variables
% %
% % s       % Is a cell array of structures.
% %         %
% %         % Each File and variable has its own cell and inside that cell
% %         % is s structure containing the metrics and
% %         % a description of the metrics data.
% %         %
% %         % The cells are arranged by [File_number Variable_Number]
% %         % So the structures are accessed by
% %         %
% %         % s{file, var}.fieldname
% %         %
% %         % The structure inside each cell contains the following fields
% %         %
% %         % s{file, var}.filename is a char of the filename of the data
% %         %            file which was processed.
% %         %
% %         % s{file, var}.variable is a char of the vriable name of the
% %         %            variable within the filename of the data file
% %         %            which was processed.
% %         %
% %         % s{file, var}.metrics is a cell array of numeric array of
% %         %           metrics data for each identified impulsive peak
% %         %           for each channel.
% %         %
% %         %           size(s{1,1}.metrics)=[num_channels 1]
% %         %           size(s{1,1}.metrics{num_channel, 1})=[num_peaks, num_metrics]
% %         %
% %         % s{file, var}.stats_of_metrics contains seven descriptive
% %         %           statistical quantities for each metric and channel
% %         %           size(s{1,1}.stats_of_metrics)=[num_metrics num_channels num_stats]
% %         %
% %         %           The ststistical Quantities are
% %         %           Arithmetic Mean
% %         %           Robust Mean
% %         %           Standard Deviation
% %         %           95 Confidence Interval
% %         %           Median
% %         %           Index Median Value
% %         %           Minimum
% %         %           Maximum
% %         %
% %         % s{file, var}.metrics_description isd a cell array of strings
% %         %           which describe the metric and its units
% %         %
% %         %           s{1,1}.metrics_description{:, 1}  descriptive strings
% %         %           s{1,1}.metrics_description{:, 2}  units strings
% %         %
% %         % s{file, var}.stats_description is a cell array containing the
% %         %           description for each of the descriptive statistical
% %         %           quntities which are
% %         %           Arithmetic Mean
% %         %           Robust Mean
% %         %           Standard Deviation
% %         %           95 Confidence Interval
% %         %           Median
% %         %           Index Median Value
% %         %           Minimum
% %         %           Maximum
% %         %
% %         % s{file, var}.diff_chan is a row vector containing the channel
% %         %           numbers of the channels where the row vector is a
% %         %           paired ordering of channel numbers.
% %         %           Each pair contains a Primary channel and a Minus
% %         %           channel.
% %         %
% %         %           The mean of the metrics of the Minus channel are
% %         %           subtracted from the mean of the metrics of Primary
% %         %           channel.
% %         %           (For the peak values in (Pa) a ratio is computed.)
% %         %
% %         % s{file, var}.diff_metrics is a cell array containing numeric
% %         %           arrays of the differences in the mean metrics.
% %         %           size(s{1,1}.diff_metrics)=[num_peaks, num_metrics];
% %         %
% %         %           The mean of the metrics of the Minus channel are
% %         %           subtracted from the mean of the metrics of Primary
% %         %           channel.
% %         %           (For the peak values in (Pa) a ratio is computed.)
% %         %
% %         % s{file, var}.diff_stats_of_metrics is a numeric array of
% %         %           descriptive statistics for the diff_metrics.
% %         %
% %         %           size(s{1,1}.diff_stats_of_metrics)=[num_metrics num_pairs_diff_chan num_stats];
% %         %
% %         % s{file, var}.num_samples is a column vector of the number of
% %         %            in each channel.
% %
% %
% % round_kind=1;           % Array of values one element for the rta array
% %                         % and one element for each varargin array
% %                         % (see example)
% %                         % 1 round to specified number of significant
% %                         % digits
% %                         %
% %                         % 0 round to specified digits place
% %                         %
% %                         % default is round_kind=1;
% %
% % round_digits=3;         % Array of values one element for the rta array
% %                         % and one element for each varargin array
% %                         % (see example)% Type of rounding depends on round_kind
% %                         %
% %                         % if round_kind==1 number of significant digits
% %                         % if round_kind==0 specified digits place
% %                         %
% %                         % default is round_digits=3;
% %
% %
% % ********************************************************************
%
%
%
% Example='1';
%
% % Create a data file;
% Fs_SP=100000; fc=1000; td=1; tau=0.01; delay=0.1; A1=2; A2=20;
% [SP, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2);
% save('default_data_file.mat', 'SP', 'Fs_SP');
%
% % Make appropriate settings for analyzing the default data file.
%
% filenamesin={'default_data_file.mat'};
%                               % cell array of strings of filenames to
%                               % process.  These files can be matlab files
%                               % or wave files
%
% fileout_txt='fileout.txt';    % string filename to save data to a tab
%                               % delimited text file
%
% fileout_struct='fileout.mat'; % string filename to save data to a
%                               % matlab structure file
%
% save_struct=1;            % 1 save all data to a matlab structure
%                           % The structure contains all of the impulsive
%                           % noise data from each of the impulses in each
%                           % channel in each file.
%                           % 0 do not save data to a matlab
%                           % structure
%
% peak_identification_time=1;            % 1 seconds.  Time interval of data to
%                           % identify each peak.  Only one peak can
%                           % exist in each interval of this time
%                           % length.
%
% peak_metric_time=1;          % 1 seconds.  Time interval of data to
%                           % analyze each peak.  Amount of data for
%                           % calculating metrics and Leqs.
%
% make_plot=1;              % 1 to make plots for each channel analyzed.
%                           % otherwise will not make any plots
%
% save_plot=1;              % 1 will save a plot.
%                           % otherwise will not not save plots
%                           % plots will not be saved if they are not made
%                           % the file name of hte plot is the
%                           % filename of the data file with the string
%                           % '_peaks' appended at the end.
%
% dB_scale=0;         % 1 use a dB scale to plot sound time record
%                     % 0 use a linear scale to plot sound time record
%
% fig_format=[1,2,3,4,5,6]; % image format for saving the plot
%                           % 1 pdf    default is 1 suggested
%                           %          for simple documentation
%                           % 2 fig
%                           % 3 jpg  (200 dpi resolution)
%                           % 4 eps2
%                           % 5 tiff (200 dpi resolution)
%                           % 6 tiff (no compression) suggested for
%                           %         publications)
%
% Tool_Name='Hammer Drill'; % string input for the Name of the
%                           % test device.
%
% same_ylim=1;              % 1 will set all of the ylimits of each of the
%                           % channels to the same value.
%
% min_peak=100;             % (dB) is the peak value in dB that is the minimum
%                           % for being consiedered a peak.
%
% ignore_threshold=0;       % 1 surpresses the threshold and other requirements
%                           % for selecting peaks
%                           % ignore_threshold=1; % generally will find more peaks.
%                           %
%                           % 0 is the default.  Returns typical number of
%                           % peaks.
%                           %
%                           % default is ignore_threshold=0;
%
% plot_str={'Protected', 'Unprotected'};
%                           % Add a string to each subaxes indicating the
%                           % meaning of the data.  For hearing protector
%                           % research one microphone is under the
%                           % hearing protector so it is 'Protected'
%                           % and the other microphone is exposed so it is
%                           % 'Unprotected'.
%
% Align_peaks=1;            % Specifies which channel to align all of the
%                           % peaks.  Can be empty then all peaks are
%                           % found independently.
%
% portrait_landscape=1;     % 1 is for Portrait
%                           % Otherwise Landscape3
%
% peak_alignment_tol=0.25;
%                 % This input sets the fraction of the datapoints
%                 % of num_pts_per_pk_intrl that a peak can be offset.
%                 % When aligning peaks, the channels are
%                 % synchronized, but temorally the peaks may be
%                 % misaligned by a few milliseconds.  The
%                 % alignment tolerance allows the program to find
%                 % the maximum peak within the alignment
%                 % tolerance.
%                 %
%                 % default is peak_alignment_tol=0.25;
%                 %
%                 % Further explanation of peak_alignment_tol
%                 % One-half of the datapoints of num_pts_per_pk_intrl are
%                 % used for finding the index of the maximum sound
%                 % pressure amplitude.
%                 %
%                 % The impulsive peak is found by selecting the highest
%                 % sound pressure amplitude starting at the center of
%                 % the bin and working toward the maximum radius which
%                 % is one-half of teh data points for the impulse.
%
% sod=0;              % 1 surpress outlier detection
%                     % 0 find the outliers and remove them from the
%                     % statistical analysis
%                     % default is sod=1;
%
% Polarized_or_ICP=0; % 1 Multiplies the time record p by -1 to correct for the
%                     % voltage inversion of polarized microphones.
%                     % 0 does not alter the time record, p.
%                     %      (ICP, IEPE, Deltatron microphones)
%
% [s]=Impulsive_Noise_Meter(filenamesin, fileout_txt, fileout_struct, save_struct, peak_identification_time, peak_metric_time, make_plot, save_plot, dB_scale, fig_format, Tool_Name, same_ylim, min_peak, ignore_threshold, plot_str, Align_peaks, portrait_landscape, peak_alignment_tol, sod, Polarized_or_ICP );
%
%
% % ********************************************************************
%
%
%
% Example='2';
%
% % Simulate 8 impulses in 4 microphones with different time records
%
% Fs_SP=100000; fc=1000; td=1; tau=0.01; delay=0.1; A1=8; A2=21; rt=0.0005;
%
% [SP1, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2, rt);
% Fs_SP=100000; fc=1000; td=1; tau=0.1; delay=0.1; A1=2; A2=22;
% [SP2, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2, rt);
% Fs_SP=100000; fc=1000; td=1; tau=0.4; delay=0.1; A1=2; A2=17;
% [SP3, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2, rt);
% Fs_SP=100000; fc=2000; td=1; tau=0.1; delay=0.1; A1=8; A2=15;
% [SP4, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2, rt);
% SP=[[0.9*SP4 SP1 0.3*SP3 SP2 0.5*SP4 0.2*SP1 SP3 5*SP2];...
%     [SP1 0.7*SP4  10*SP2 SP3 0.4*SP2 0.5*SP3 SP1 1*SP4];...
%     [SP3 0.2*SP1  0.5*SP4 2*SP2 0.4*SP2 0.7*SP3 0.3*SP1 10*SP4];...
%     [SP1 0.7*SP2  0.3*SP3 SP4 0.4*SP1 10*SP2 SP3 1*SP4]];
%
% % Subtract the running mean value
% [SP]=sub_mean2(SP, Fs_SP, 5);
%
% % save the SP data variable to a matfile data file
%
% save('default_data_file.mat', 'SP', 'Fs_SP');
%
% % save the data to a wav file
%
% cf=1/(10*max(max(max(abs(SP)))));
% [pp, buf, buf, rdr]=sd_round(cf, 5);
% numstr=eval(['sprintf( ', ' ''%9.', num2str(rdr), 'f''', ', pp )']);
% fprintf(1, '%s\r\n', ['When Prompted use the calibration factor ', numstr]);
%
% wavwrite(cf*SP, Fs_SP, 16, 'default_data_file.wav');
%
% % Run the Main_Sound just respond to the prompts!
%
% Main_Sound;
%
%
%
% % ********************************************************************
%
%
% Example='3';
%
% Try to run the Impulsive_Noise_Meter from the Command Line
%
% Fs_SP=100000; fc=1000; td=1; tau=0.01; delay=0.1; A1=8; A2=21; rt=0.0005;
% [SP1, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2, rt);
% Fs_SP=100000; fc=1000; td=1; tau=0.1; delay=0.1; A1=2; A2=22;
% [SP2, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2, rt);
% Fs_SP=100000; fc=1000; td=1; tau=0.4; delay=0.1; A1=2; A2=17;
% [SP3, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2, rt);
% Fs_SP=100000; fc=2000; td=1; tau=0.1; delay=0.1; A1=8; A2=15;
% [SP4, t]=analytic_impulse(Fs_SP, fc, td, tau, delay, A1, A2, rt);
%  SP=[[0.9*SP4 SP1 0.3*SP3 SP2 0.5*SP4 0.2*SP1 SP3 5*SP2];...
%    [SP1 0.7*SP4  10*SP2 SP3 0.4*SP2 0.5*SP3 SP1 1*SP4];...
%    [SP3 0.2*SP1  0.5*SP4 2*SP2 0.4*SP2 0.7*SP3 0.3*SP1 10*SP4];...
%    [SP1 0.7*SP2  0.3*SP3 SP4 0.4*SP1 10*SP2 SP3 1*SP4]];
%
% simulate 8 impulses in 4 microphones with different time records
%
%
% % save the SP data variable to a matfile data file
%
% save('default_data_file.mat', 'SP', 'Fs_SP');
%
% % save the data to a wav file
%
% cf=1/(10*max(max(max(abs(SP)))));
% [pp, buf, buf, rdr]=sd_round(cf, 5);
% numstr=eval(['sprintf( ', ' ''%9.', num2str(rdr), 'f''', ', pp )']);
% fprintf(1, '%s\r\n', ['When Prompted use the calibration factor ', numstr]);
%
% wavwrite(cf*SP, Fs_SP, 16, 'default_data_file.wav');
%
% filenamesin={'default_data_file.mat', 'default_data_file.wav'};
% fileout_txt='fileout.txt';
% fileout_struct='fileout.mat';
% save_struct=1;
% peak_identification_time=0.5;
% peak_metric_time=0.1;
% make_plot=1;
% save_plot=1;
% dB_scale=1;
% fig_format=[1];
% Tool_Name='Hammer';
% same_ylim=1;
% min_peak=100;
% ignore_threshold=0;
% plot_str={'Protected', 'Unprotected'};
% Align_peaks=[];
% portrait_landscape=1;
% peak_alignment_tol=0.25;
% sod=0;
% Polarized_or_ICP=0;
%
% % [s]=Impulsive_Noise_Meter(filenamesin, fileout_txt, fileout_struct, save_struct, peak_identification_time, peak_metric_time, make_plot, save_plot, dB_scale, fig_format, Tool_Name, same_ylim, min_peak, ignore_threshold, plot_str, Align_peaks, portrait_landscape, peak_alignment_tol, sod, Polarized_or_ICP );
%
%
% % ********************************************************************
%
% Example='4';
%
% Try to analyze the Guns_example.wav using the command line with
% the Impulsive_Noise_Meter
%
% When prompted use a calibration factor of 0.000001
%
% Note that mic 2 does not have adequate dynamic resolution
%
% filenamesin={'Guns_example.wav'};
% fileout_txt='fileout.txt';
% fileout_struct='fileout.mat';
% save_struct=1;
% peak_identification_time=0.1;
% peak_metric_time=0.1;
% make_plot=1;
% save_plot=1;
% dB_scale=0;
% fig_format=[1];
% Tool_Name='Guns';
% same_ylim=1;
% min_peak=100;
% ignore_threshold=0;
% plot_str={'Unprotected', 'Protected'};
% Align_peaks=1;
% portrait_landscape=1;
% peak_alignment_tol=0.25;
% sod=0;
% Polarized_or_ICP=zeros(2, 1);
%
% [s, round_kind, round_digits]=Impulsive_Noise_Meter(filenamesin, fileout_txt, fileout_struct, save_struct, peak_identification_time, peak_metric_time, make_plot, save_plot, dB_scale, fig_format, Tool_Name, same_ylim, min_peak, ignore_threshold, plot_str, Align_peaks, portrait_landscape, peak_alignment_tol, sod, Polarized_or_ICP );
%
%
% % ********************************************************************
%
%
% Example='5';
%
% Run the Main_Sound and open the Guns_example.wav this time!
%
%
% Main_Sound;
%
%
% % ********************************************************************
% %
% % References:
% %
% %
% % ANSI S1.4-1983   American National Standard
% %                  Specificaitons for Sound Level Meters
% %
% % ANSI S1.6-1984   Preferred Frequencies, Frequency Levels, and Band
% %                  Numbers for Acoustical Measurements
% %
% % ANSI S1.43-1997  American National Standard
% %                  Specificaitons for Integrating-Averaging Sound Level
% %                  Meters
% %
% % ANSI S1.11-1986  American National Standard
% %                  Specification for Octave-band and Fractional-Octave-
% %                  band Analog and Digital Filters
% %
% % ANSI S3.44-1986  American National Standard
% %                  Determination of Occupational Noise Exposure and
% %                  Estimation of Noise Induced Hearing Impairment
% %
% %
% % Mil Standard 1474D, DEPARTMENT OF DEFENSE
% % DESIGN CRITERIA STANDARDm, NOISE LIMITS, 12 February 1997
% % www.silencertests.com/docs/mil-std-1474d.pdf
% %
% % Guido F. Smoorenburg, "Damage Risk Criteria for Impulsive
% % Noise," New Perspectives on Noise Induced Hearing Loss,
% % Raven Press, New York, pages(471-490) 1982
% %
% % ********************************************************************
% %
% %
% % Subprograms
% %
% % This program requires the Matlab Signal Processing Toolbox
% % This program contains code based on  oct3dsgn	by Christophe Couvreur	69
% %
% %
% %
% %
% % List of Dependent Subprograms for
% % Impulsive_Noise_Meter
% %
% % FEX ID# is the File ID on the Matlab Central File Exchange
% %
% %
% % Program Name   Author   FEX ID#
% %  1) A_duration		Edward L. Zechmann
% %  2) abcd_durations		Edward L. Zechmann
% %  3) ACdsgn		Edward L. Zechmann
% %  4) ACweight_time_filter		Edward L. Zechmann
% %  5) allstats		Duane Hanselman		NA
% %  6) analytic_impulse		Edward L. Zechmann
% %  7) B_duration		Edward L. Zechmann
% %  8) B_Duration_second_flucts		Edward L. Zechmann
% %  9) B_mil_1474D_duration		Edward L. Zechmann
% % 10) bessel_antialias		Edward L. Zechmann
% % 11) bessel_digital		Edward L. Zechmann
% % 12) bessel_down_sample		Edward L. Zechmann
% % 13) C_duration		Edward L. Zechmann
% % 14) calc_impuls_threshold_and_index		Edward L. Zechmann
% % 15) convert_double		Edward L. Zechmann
% % 16) D_duration		Edward L. Zechmann
% % 17) data_loader2		Edward L. Zechmann
% % 18) data_outliers3		Edward L. Zechmann
% % 19) file_extension		Edward L. Zechmann
% % 20) filter_settling_data3		Edward L. Zechmann
% % 21) find_previous_crossing		Edward L. Zechmann
% % 22) findextrema		Schuberth Schuberth		3586
% % 23) fix_YTick		Edward L. Zechmann
% % 24) genHyper		Ben Barrowes		6218
% % 25) geomean2		Edward L. Zechmann
% % 26) geospace		Edward L. Zechmann
% % 27) get_p_q2		Edward L. Zechmann
% % 28) kurtosis2		William Murphy
% % 29) Leq_all_calc		Edward L. Zechmann
% % 30) LMS_trim		Edward L. Zechmann
% % 31) LMSloc		Alexandros Leontitsis		801
% % 32) LMTSregor		Edward L. Zechmann
% % 33) localpeaks		Edward L. Zechmann
% % 34) m_round		Edward L. Zechmann
% % 35) match_height_and_slopes2		Edward L. Zechmann
% % 36) moving		Aslak Grinsted		8251
% % 37) nth_freq_band		Edward L. Zechmann
% % 38) Nth_oct_time_filter2		Edward L. Zechmann
% % 39) Nth_octdsgn		Edward L. Zechmann
% % 40) parseArgs		Malcolm Wood		10670
% % 41) peak_index		Edward L. Zechmann
% % 42) peak_threshhold_function		Edward L. Zechmann
% % 43) percentiles		Edward L. Zechmann
% % 44) plot_snd_vibs		Edward L. Zechmann
% % 45) plotpeaks		Edward L. Zechmann
% % 46) pow10_round		Edward L. Zechmann
% % 47) print_data_loader_configuration_table		Edward L. Zechmann
% % 48) print_outliers_indices		Edward L. Zechmann
% % 49) psuedo_box		Edward L. Zechmann
% % 50) rand_int		Edward L. Zechmann
% % 51) remove_filter_settling_data		Edward L. Zechmann
% % 52) resample_interp3		Edward L. Zechmann
% % 53) resample_plot		Edward L. Zechmann
% % 54) rise_time		Edward L. Zechmann
% % 55) rms_val		Edward L. Zechmann
% % 56) save_a_plot2_audiological		Edward L. Zechmann
% % 57) sd_round		Edward L. Zechmann
% % 58) snd_peak_metrics		Edward L. Zechmann
% % 59) sub_mean		Edward L. Zechmann
% % 60) sub_mean2		Edward L. Zechmann
% % 61) subaxis		Aslak Grinsted		3696
% % 62) t_alpha		Edward L. Zechmann
% % 63) t_confidence_interval		Edward L. Zechmann
% % 64) t_icpbf		Edward L. Zechmann
% % 65) tableGUI		Joaquim Luis		10045
% % 66) threshold_bin_peaks		Edward L. Zechmann
% %
% %
% % ********************************************************************
% %
% % Impulsive_Noise_Meter is Written by Edward L. Zechmann
% %
% %     date 10 August      2007
% %
% % modified 18 December    2007    Multitude of updates. brief list of
% %                                 major changes
% %                                 updated the a,b,c,d duration
% %                                 calculations
% %                                 added the data_outliers
% %                                 added data_loader
% %                                 added and updated sub_mean
% %                                 added geomean2
% %                                 updated plot_snd_vibs
% %                                 updated save_a_plot2_audiological
% %
% % modified 21 December    2007    Updated comments
% %
% % modified 27 December    2007    Updated peak finding process in
% %                                 localpeaks.m
% %                                 fixed pts_per_bin to 0.01 seconds worth
% %                                 of data points
% %
% % modified 27 December    2007    Updated peak finding process
% %                                 in localpeaks.m
% %                                 fixed pts_per_bin to 0.01 seconds
% %                                 worth of data points
% %
% % modified  8 January     2008    Updated data_loader2.  Loading matlab
% %                                 data files now prmpts the user to
% %                                 configure the variables.
% %                                 There is an option to use the same
% %                                 configuration for each data file.
% %
% % modified 21 February    2008    Updated comments.
% %
% % modified 26 February    2008    Modified the array_units, updated
% %                                 local_peaks.m, updated comments to
% %                                 several sub programs.
% %
% % modified 17 March       2008    Added peak_alignment_tol option for
% %                                 specifying the tolerance for aligning
% %                                 the peaks as a fraction of the
% %                                 peak_identification_time.
% %
% % modified 18 August      2008    Updated Comments.
% %                                 Added third oct linear peaks
% %
% % modified 19 August      2008    Added input variable percent1
% %                                 to specify threshold for
% %                                 identifying peaks
% %
% % modified 10 September   2008    Added optional method for finding
% %                                 impulsive Exhaust Noise
% %
% % modified 22 September   2008    Updated Comments.
% %
% % modified 10 December    2008    Upgraded the third octave band
% %                                 filtering programs and the A and C-
% %                                 weighting filter programs to include
% %                                 filter settling and resampling.
% %
% % modified 11 December    2008    Upgraded the A and C-
% %                                 weighting filter programs,
% %                                 to include iterative filtering.
% %                                 The filters are now very stable.
% %
% %                                 Removed filter coefficients from input
% %                                 and output;
% %                                 Peaks pressures and Levels are output.
% %
% % modified 16 December    2008    For the A and C weighting filters,
% %                                 Use convolution to make filter
% %                                 coefficients (b and a) into
% %                                 arrays from cell arrays .
% %
% % modified  5 January     2009    Added sub_mean to the Nth octave
% %                                 band filters and A and C weighting
% %                                 filters.
% %
% % modified 21 March       2009    Added the B-Mil-Std-1474-D-Duration
% %                                 Added the peak analysis time for
% %                                 calculating metrics.
% %                                 Added a flag to data_outliers3 to
% %                                 convert dB data to Pa before
% %                                 calculating mean and median values.
% %                                 Updated comments
% %
% % modified 22 March       2009    Added db_scale to select dB or linear
% %                                 scale for plotting the sound time
% %                                 record.
% %                                 Updated Comments.
% %
% % modified  6 October     2009    Updated comments
% %
% % modified  5 August      2010    Added resampling using Bessel
% %                                 antialiasing filter
% %                                 Updated Comments
% %
% % modified 10 August      2010    Added rise time
% %                                 Updated Comments
% %
% % modified 11 October     2010    Changed peak finder to peak_ix
% %                                 Updated comments.
% %
% % modified 11 February    2011    Updated to new method of finding peaks.
% %                                 Updated Comments.
% %
% %
% %
% % ********************************************************************
% %
% % Please Feel Free To Modify This Code
% %
% % See also: Continuous_Sound_and_Vibrations_Analysis, snd_peak_metrics, plot_peaks, local_peaks,
% %



if (nargin < 1 || isempty(filenamesin)) || ischar(filenamesin) || (~iscell(filenamesin) && numel(filenamesin) > 1)
    
    [filenamesin, pathname, filterindex] = uigetfile( {  '*.mat'; '*.wav'},  'Select the files To Process', 'MultiSelect', 'on');
    
    if isempty(filenamesin) || ischar(filenamesin) || (~iscell(filenamesin) && numel(filenamesin) > 1)
        
        % expecting a cell array of strings
        % if only one file is selected then it will be a character array or a
        % single string
        % convert into a cell array if necessary
        if ~isempty(filenamesin) && ischar(filenamesin) && isequal(exist(filenamesin, 'file'), 2)
            filenamesin={filenamesin};
        else
            if isempty(filenamesin)
                [filenamesin, pathname] = uigetfile( {  '*.mat';'*.wav'},  'Select the files To Process', 'MultiSelect', 'on');
            end
            if ischar(filenamesin) && isequal(exist(filenamesin, 'file'), 2)
                filenamesin={filenamesin};
            end
        end
        pathname=cd;
        cd(pathname);
    else
        cd( pathname);
    end
end

if ~iscell(filenamesin) || isempty(filenamesin) || length(filenamesin) < 1
    error('Must select at least 1 file to analyze');
end

if ~iscell(filenamesin) || isempty(filenamesin) || length(filenamesin) < 1
    error('Must select at least 1 file to analyze');
end

filenamesin=sort(filenamesin);




if (nargin < 2 || isempty(fileout_txt)) || ~ischar(fileout_txt)
    fileout_txt='data1.txt';
end

if (nargin < 3 || isempty(fileout_struct)) || ~ischar(fileout_struct)
    fileout_struct='data1_struct';
end

if (nargin < 4 || isempty(save_struct)) || ~isnumeric(save_struct)
    save_struct=1;
end

if (nargin < 5 || isempty(peak_identification_time)) || ~isnumeric(peak_identification_time)
    peak_identification_time=1;
end

if (nargin < 6 || isempty(peak_metric_time)) || ~isnumeric(peak_metric_time)
    peak_metric_time=1;
end

if (nargin < 7 || isempty(make_plot)) || ~isnumeric(make_plot)
    make_plot=1;
end

if (nargin < 8 || isempty(save_plot)) || ~isnumeric(save_plot)
    save_plot=1;
end

if nargin < 9 || isempty(dB_scale) || ~isnumeric(dB_scale)
    dB_scale=0;
end

if (nargin < 10 || isempty(fig_format)) || ~isnumeric(fig_format)
    fig_format=1;
end

if (nargin < 11 || ~ischar(Tool_Name))
    Tool_Name='Impulsive Noise';
end

if (nargin < 12 || isempty(same_ylim)) || ~isnumeric(same_ylim)
    same_ylim=1;
end

if (nargin < 13 || isempty(min_peak)) || ~isnumeric(min_peak)
    min_peak=100;
end

if (nargin < 14 || isempty(ignore_threshold)) || ~isnumeric(ignore_threshold)
    ignore_threshold=0;
end

if (nargin < 15 || ~iscell(plot_str))
    plot_str={'Unprotected', 'Protected'};
end

if (nargin < 16 || isempty(Align_peaks)) || ~isnumeric(Align_peaks) || logical(Align_peaks < 1)
    Align_peaks=[];
end

if (nargin < 17 || isempty(portrait_landscape)) || ~isnumeric(portrait_landscape)
    portrait_landscape=1;
end

if (nargin < 18 || isempty(peak_alignment_tol)) || ~isnumeric(peak_alignment_tol)
    peak_alignment_tol=0.25;
end

if nargin < 19 || isempty(sod) || ~isnumeric(sod)
    sod=1;
end

if nargin < 20 || isempty(Polarized_or_ICP) || ~isnumeric(Polarized_or_ICP)
    Polarized_or_ICP=0;
end


num_files=length(filenamesin);

% Make sure the .txt extension is added
[filename_base, ext]=file_extension(fileout_txt);
fileout_txt=[filename_base, '.txt'];

fid=fopen(fileout_txt, 'w');

filename=cell(num_files,1);
filenum_array=ones(num_files,1);

metrics={};
durations_array=cell(num_files,1);
other_stats2=cell(num_files,1);


% Variables may be called using eval
a=[];
b=[];
ba=[];
stat_str={'Arithmetic Mean', 'Robust Mean', 'Standard Deviation','95% Confidence Interval','Median Index','Median Value','Minimum','Maximum'};
num_stats=length(stat_str);

row_names={'Channel Number'};
row_unit='';
col_name='Peak Number';
%array_names={'Peak Level Linear', 'Peak Index',  'Peak Time',    'Peak Pres. Linear',    'Peak Pres. A-Weight', 'Peak Pres. C-Weight',   'Peak Level Linear ',   'Peak Level A-Weight )', 'Peak Level C-Weight ', 'LeqA', 'LeqA8', 'LeqC', 'LeqC8', 'Leq', 'Leq8', 'Time Span', 'Rise Time', 'A-Duration', 'B-Duration', 'C-Duration', 'D-Duration', 'Kurtosis'};
%array_units={'(dB)',              '(Indices)',    '(s)',          '(Pa)',                 '(Pa)',                 '(Pa)',                 '(dB)',                '(dBA)',                 '(dBC)',                '(dBA)','(dBA)', '(dBC)','(dBC)', '(dB)','(dB)', '(s)',       '(s)',       '(s)',        '(s)',        '(s)',        '(s)',        '(No units)'};
metrics={};
metric_str={};
metric_units={};
AHAAH_str={};
other_stats={};
md={};


% initialize the input configuration cell arrays for the wav files
% and the matlab data files
default_wav_settings_in={};
default_mat_config_in={};

% initialize the data set counter
e1=0;
s={};


for e6=1:num_files;
    
    
    SP=[];
    
    % load the data file
    [SP_var, vibs_var, Fs_SP_var, Fs_vibs_var, default_wav_settings_out, default_mat_config_out]=data_loader2(filenamesin{e6}, default_wav_settings_in, default_mat_config_in);
    % set the default wav file setttings
    % for configuring the channels
    default_wav_settings_in=default_wav_settings_out;
    default_mat_config_in=default_mat_config_out;
    
    if iscell(SP_var)
        num_vars=length(SP_var);
    else
        num_vars=1;
    end
    
    for e7=1:num_vars;
        
        if iscell(SP_var)
            if length(SP_var) >= e7
                SP=SP_var{e7};
            end
            
            if length(Fs_SP_var) >= e7
                Fs_SP=Fs_SP_var{e7};
            end
            
            % currently there is not any code for impulsive vibrations
            % analysis
            %if length(vibs_var) >= e7
            %    vibs=vibs_var{e7};
            %end
            %
            %if length(Fs_vibs_var) >= e7
            %    Fs_vibs=Fs_vibs_var{e7};
            %end
        else
            SP=SP_var;
            Fs_SP=Fs_SP_var;
            %vibs=vibs_var;
            %Fs_vibs=Fs_vibs_var;
        end
        
        % make sure that input data is double precision.
        [SP]=convert_double(SP);
        [Fs_SP]=convert_double(Fs_SP);
        
        
        [m1 n1]=size(SP);
        
        if m1 > n1
            SP=SP';
            [m1 n1]=size(SP);
        end
        
        % reinitialize the durations cell array
        metrics={};
        
        % increment the counter which counts all of the variables which
        % have been processed
        e1=e1+1;
        
        % sub_mean2 program interpolates to create a running average
        % pressure then subtracts the running average pressure
        if max(size(SP)) > 0
            [SP]=sub_mean2(SP, Fs_SP, 15);
        end
        
        % Currently this program does not contian any programs
        % specifically for impulsive vibrations.
        %
        %if max(size(vibs)) > 0
        %    [vibs]=vibs-mean(vibs, 2)*ones(1, size(vibs, 2));
        %end
        
        metrics={};
        
        if exist('SP','var') == 1 && length(SP) > 1
            
            filename1=filenamesin{e6};
            
            fprintf(1, '%s\r\n', ['Processing file ', num2str(e6), '   ', filename1, ' Variable ', num2str(e7) ]);
            % minimum peak preessure to be an impulsive noise
            
            num_pts_per_pk_intrl=floor(peak_identification_time*Fs_SP);
            
            if num_pts_per_pk_intrl < 1
                num_pts_per_pk_intrl=1;
            end
            
            if num_pts_per_pk_intrl > max(size(SP))
                num_pts_per_pk_intrl=max(size(SP));
            end
            
            
            pts_per_pk_metrics=floor(peak_metric_time*Fs_SP);
            
            
            % ************************************************************
            %
            % plotpeaks will run peak-ix which finds teh peaks
            % plot peaks will then plot the peaks on a figure window
            
            [h, h2, indices2]=plotpeaks(SP, Fs_SP, num_pts_per_pk_intrl, make_plot, Tool_Name, [filename1 ' var ', num2str(e7)], same_ylim, min_peak, ignore_threshold, plot_str, Align_peaks, peak_alignment_tol, dB_scale );
            
            % ************************************************************
            %
            % snd_peak_metrics will calculate the impulsive metrics
            % This program calculates all of the impulsive noise metrics
            N=3;
            min_f=20;
            max_f=20000;
            ear_model=ones(m1, 1);
            [metrics, metric_str, metric_units, AHAAH_str, round_kind, round_digits, dB_or_linear]=snd_peak_metrics(SP, Fs_SP, indices2, pts_per_pk_metrics, N, min_f, max_f, ear_model, Polarized_or_ICP);
            
            round_kind2=[1 round_kind];
            round_digits2=[3 round_digits];
            dB_or_linear=[1 dB_or_linear];
            
            % Get the number of metrics
            num_metrics=size(metrics{1, 1}, 2);
            
            % Get the number of channels
            % metrics is a cell array of size [num_channels, 1]
            % each cell within metrics contains a 2d array of metrics
            % of size {num_impulses, num_metrics}
            msd=size(metrics, 1);
            
            figure(1);
            for e2=1:length(h2);
                axes(h2(e2));
            end
            
            % Save the plot of the time rcords identifying the impulsive peaks
            % change the filename for each file and variable.
            if save_plot == 1
                for e2=1:length(fig_format);
                    save_a_plot2_audiological(fig_format(e2), [filename1(1:(length(filename1)-4)), '_peaks_var_', num2str(e7) ], portrait_landscape);
                end
            end
            
            fprintf(fid, 'filename\t%s\r\n', filename1);
            fprintf(fid, 'Variable\t%s\r\n', num2str(e7) );
            fprintf(fid, '\r\n');
            
            abs_metrics=[3 4 5];
            
            num_peaks=length(metrics{1}(:, 1));
            ba2=cell(msd, num_metrics);
            
            for e4=1:num_metrics;
                for e2=1:msd;
                    num_peaks=length(metrics{e2}(:, 1));
                    buf=ones(num_peaks, 1);
                    for e3=1:num_peaks;
                        buf(e3, 1)=metrics{e2,1}(e3, e4);
                    end
                    
                    ba2{e2, e4}=buf;
                    
                end
            end
            
            % use the data outliers program to statistically evaluate the data
            % Call data_outliers using the cell array format which allows
            % for a different number of peaks for each channel
            % print data to a file using the fid
            
            abs_rta=1;
            abs_other=[ 0 0 1 1 1 zeros(1, num_metrics-5)];
            
            metric_str2=cell(1, num_metrics+1);
            metric_units2=cell(1, num_metrics+1);
            
            metric_str2{1}=metric_str{6};
            metric_units2{1}=metric_units{6};
            
            for e4=1:num_metrics;
                metric_str2{e4+1}=metric_str{e4};
                metric_units2{e4+1}=metric_units{e4};
            end
            
            
            % Outliers are identified for all
            % metric arrays independently.
            dep_var=0;
            
            
            function_str='data_outliers3(dB_or_linear, ba2(1:msd,6), dep_var, round_kind2, round_digits2, abs_rta, abs_other, sod, fid, 1, row_names, row_unit, col_name, metric_str2, metric_units2';
            
            for e4=1:num_metrics;
                function_str=[function_str, ', ba2(1:msd, ', num2str(e4), ')'];
            end
            
            function_str=[function_str,' )'];
            
            [ptsa, nptsa, rt_stats, other_stats, rt_outlier_stats, other_outlier_stats]=eval(function_str);
            
            fprintf(fid, '\r\n');
            
            % These four lines of voided code are present to identify
            % data_outliers as a dependent function.
            void_call=0;
            if void_call
                data_outliers3(0);
            end
            
            
            % Print the same information from the data_outliers program,
            % but print the data horizontally.
            for e2=1:msd;
                sizedur=size(metrics{e2});
                fprintf(fid, ['Microphone Channel ' num2str(e2), ' \r\n']);
                fprintf(fid, '\tPeak Number\t');
                
                % Print the names of the metrics
                for e3=1:length(metric_str);
                    fprintf(fid, '%s\t', metric_str{e3});
                end
                
                fprintf(fid,'\r\n\t\t');
                
                % Print the units of the metrics
                for e3=1:length(metric_str);
                    fprintf(fid, '%s\t', metric_units{e3});
                end
                
                fprintf(fid,'\r\n');
                
                format_str='\t%i\t%i\t%f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%3.2f\t%f\t%f\t%f\t%f\t%f\t%3.2f';
                
                for e3=1:(num_metrics-20);
                    format_str=[format_str, '\t%f'];
                end
                
                format_str=[format_str, '\t\r\n'];
                fprintf(fid,'Data');
                fprintf(fid, format_str, [(1:sizedur(1))' metrics{e2}]');
                [m1, n11]=size(metrics{e2});
                fprintf(fid,'Descriptive Statistics');
                
                for e5=1:num_stats;
                    
                    buf2=zeros(1, n11);
                    for e4=1:n11;
                        buf2(1, e4)=other_stats(e4, e2, e5);
                    end
                    fprintf(fid, '\t%s', stat_str{e5});
                    fprintf(fid, format_str(5:end), buf2');
                    
                end
                fprintf(fid, '\r\n');
                
                % List the indices of the data outlier
                if ~isequal(sod, 1) && logical(numel(other_outlier_stats) >= max([n11*num_stats*msd, 1]))
                    fprintf(fid, '%s\t%s\t', 'Data Outliers', 'Microphone Indices');
                    
                    [fid]=print_outliers_indices(nptsa(e2, 2:end), fid);
                    
                    fprintf(fid, '\r\n');
                    fprintf(fid, '\r\n');
                    
                    for e5=1:num_stats;
                        
                        buf2=zeros(1, n11);
                        for e4=1:n11;
                            buf2(1, e4)=other_outlier_stats(e4, e2, e5);
                        end
                        fprintf(fid, '\t%s', stat_str{e5});
                        fprintf(fid, format_str(5:end), buf2');
                        
                    end
                    fprintf(fid, '\r\n');
                    
                end
                
                
            end
            
            fprintf(fid, '\r\n');
            fprintf(fid, '\r\n');
        end
        
        % md stands for "metrics description"
        md=cell(2, length(metric_str));
        
        for e2=1:length(metric_str);
            md{1, e2}=metric_str{e2};
            md{2, e2}=metric_units{e2};
        end
        
        % A cell array of data structures is formed to collect the data for each
        % file and each variable for each peak.
        s{e6, e7}.filename=filenamesin{e6};
        s{e6, e7}.variable=e7;
        s{e6, e7}.metrics=metrics;
        s{e6, e7}.stats_of_metrics=other_stats;
        s{e6, e7}.stats_of_outliers_metrics=other_outlier_stats;
        s{e6, e7}.metrics_description=md;
        s{e6, e7}.stats_description=stat_str;
        
    end
    
end

if save_struct == 1
    save(fileout_struct, 's');
end

fclose(fid);



Contact us at files@mathworks.com