Fish tacos for the weary soul

Heart Beat Detection script

21Feb/120

Here's a small script I wrote for detecting contractions (beats) in cardiac myocytes. The input is a series of timepoints vs sarcomere lengths. I first used a moving average to smooth the data and took the derivative to look for changes in value i.e. a contraction corresponds to decreasing moving average (detection is threshold based). The slew rate is calculated based off the estimated start/end contraction time points. Finally quality control is implemented using a scatter plot to show where the detected points are.

function [data] = beats3( )
%filter beats out

FileList = dir('*.TXT');
 N = size(FileList,1);

 for k = 1:N

    filename = FileList(k).name;
    disp(filename);

infile = load(filename);
values = infile(:,3); %pixel values
entries = size(values,1);
dt = infile(2,1)-infile(1,1);
beatcount = 1;
data = zeros(150,3); %cols max, min, slew
startb = 0; %flag
marker=[];
a = 1;
b = [1/10*ones(10,1)];
values2 = filter(b,a,values);%fwd difference
derivative = (values2(3:end)-values2(1:end-2))/(2*dt);%fwd difference
j=20;
thresh=-2;
pthresh=-thresh;
i=j+1;
while i<size(derivative,1)-j
    if (derivative(i)<thresh && startb == 0)
        startb = 1;
        beatmax  = max(values(i-j:i));
        data(beatcount,1)=beatmax;
        [temp,slewstart]=min(abs(.9*beatmax-values(i-j:i)));
        slewstart=slewstart-j+i;
        marker=[marker,slewstart];
        i=i+j;
    end
    if (startb == 1 && derivative(i)>pthresh)
        startb = 0;
        beatmin=min(values(i-j:i));
        data(beatcount,2)=beatmin;
        [temp,slewend]=min(abs(1.1*beatmin-values(i-j:i)));
        slewend=slewend-j+i;
        data(beatcount,3)=(slewend-slewstart)*dt;
        beatcount=beatcount+1;
        marker=[marker,slewend];
    end
    i=i+1;
end

data(all(data==0,2),:)=[]; %trim

figure();
hist(data(:,3),30);

%QC for threshold finding
figure();
hold on;
plot(1:entries,values2); 
scatter(marker,mean(values2)*ones(size(marker)));

 end
    

end

Attachment: