%% Signal Labeler Custom Functions
% This example stores and tests custom autolabeling functions to be used with Signal Labeler. Not meant to be published on its own.
%% Signal Collection

fs = 1000;
t = 0:1/fs:14-1/fs;
c = [chirp(t-1,0.1,17,2,'quadratic',1).*sin(2*pi*t/5);
    0.85*besselj(0,5*(sin(2*pi*(t+1.5).^2/20).^2)).*sin(2*pi*t/9)]';
tt = repmat(t,size(c,2),1)';

a = meanRMS(c,tt)
[b,tb] = transitions(c,tt);
b(1)
tb(1)

[d,td] = greaterThan(c,tt);
d(1)
td(1,:)

%
%% meanRMS Function

function [labelVals,labelLocs] = meanRMS(x,t,parentLabelVal,parentLabelLoc,varargin)
% Label signal with its mean RMS value as attribute

labelVals = mean(rms(x));
labelLocs = [];

end

%% transitions Function

function [labelVals,labelLocs] = transitions(x,t,parentLabelVal,parentLabelLoc,varargin)
% Label zero crossings as "rising" or "falling"

nchan = size(x,2);
t = t(:,1);

labelVals = cell(nchan,1);
labelLocs = cell(nchan,1);

for kj = 1:nchan

[~,ltup,utup] = risetime(x(:,kj),t,'StateLevels',0.1*[-1 1]);

ups = (utup+ltup)/2;
upc = repmat("rising",length(ups),1);

[~,ltdn,utdn] = falltime(x(:,kj),t,'StateLevels',0.1*[-1 1]);

dns = (utdn+ltdn)/2;
dnc = repmat("falling",length(dns),1);

labelVals{kj} = [upc;dnc];
labelLocs{kj} = [ups;dns];

end

labelVals = cat(1,labelVals{:});
labelLocs = cell2mat(labelLocs);

end

%% greaterThan Function

function [labelVals,labelLocs] = greaterThan(x,t,parentLabelVal,parentLabelLoc,varargin)
% Label regions with negative first channel and third channel larger than a given value

if nargin<5
    mx = 0.1;
else
    mx = varargin{1};
end

xr = x(:,1);
xx = x(:,2);
tt = t(:,1);

ss = signalMask(xx >= mx & xr < 0);
x = roimask(ss);

labelLocs = tt(x.ROILimits);
labelVals = logical(double(x.Value));

end

% Copyright 2020 The MathWorks, Inc.