Switch to unified view

a b/featurebased-approach/subfunctions/stackbeats.m
1
function [M,RES] = stackbeats(signal,qrs,T_LENGTH,NB_BINS)
2
% Stack and wraps beats onto a matrix M
3
%  RES = time reference to resample from bins to time
4
%
5
% --
6
% ECG classification from single-lead segments using Deep Convolutional Neural 
7
% Networks and Feature-Based Approaches - December 2017
8
% 
9
% Released under the GNU General Public License
10
%
11
% Copyright (C) 2017  Fernando Andreotti, Oliver Carr
12
% University of Oxford, Insitute of Biomedical Engineering, CIBIM Lab - Oxford 2017
13
% fernando.andreotti@eng.ox.ac.uk
14
%
15
% 
16
% For more information visit: https://github.com/fernandoandreotti/cinc-challenge2017
17
% 
18
% Referencing this work
19
%
20
% Andreotti, F., Carr, O., Pimentel, M.A.F., Mahdi, A., & De Vos, M. (2017). 
21
% Comparing Feature Based Classifiers and Convolutional Neural Networks to Detect 
22
% Arrhythmia from Short Segments of ECG. In Computing in Cardiology. Rennes (France).
23
%
24
% Last updated : December 2017
25
% 
26
% This program is free software: you can redistribute it and/or modify
27
% it under the terms of the GNU General Public License as published by
28
% the Free Software Foundation, either version 3 of the License, or
29
% (at your option) any later version.
30
% 
31
% This program is distributed in the hope that it will be useful,
32
% but WITHOUT ANY WARRANTY; without even the implied warranty of
33
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
34
% GNU General Public License for more details.
35
% 
36
% You should have received a copy of the GNU General Public License
37
% along with this program.  If not, see <http://www.gnu.org/licenses/>.
38
39
% Parameter
40
if size(signal,1) < size(signal,2), signal = signal'; end
41
42
phase = FECGx_kf_PhaseCalc(qrs,length(signal));
43
ini_cycles = find(phase(2:end)<0&phase(1:end-1)>0)+1; % start of cycles
44
cycle_len = diff(ini_cycles); % distance between cycles
45
end_cycles = ini_cycles(1:end-1)+cycle_len-1; % start of cycles
46
meanPhase = linspace(-pi,pi,NB_BINS);
47
RES =  2.*round((median(cycle_len)+1)/2)-1;
48
% stacking cycles
49
cycle = arrayfun(@(x) interp1(phase(ini_cycles(x):end_cycles(x)),...
50
    signal(ini_cycles(x):end_cycles(x)),meanPhase,'spline'),...
51
    1:length(ini_cycles)-1,'UniformOutput',0);
52
M = cell2mat(cycle')';
53
54
% re-aligning beats
55
i = 1;
56
while i<=size(M,2)
57
    lag = finddelay(mean(M'),M(:,i)); % finds lag on the beat
58
    if abs(lag) > T_LENGTH    % only allows 20% shift
59
        M(:,i) = [];            % otherwise ignore beat
60
        continue
61
    end
62
    if size(M,2)>2 && lag < 0
63
        M(end-abs(lag):end,i) = 0;
64
    elseif size(M,2)>2
65
        M(1:lag,i) = 0;
66
    end
67
    M(:,i)=circshift(M(:,i),[-lag,1]);
68
    i = i+1;
69
end
70
71
72
end