-
Notifications
You must be signed in to change notification settings - Fork 2
/
COSMAS.m
1938 lines (1759 loc) · 94.2 KB
/
COSMAS.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% TODO copyright stuff
% TODO copy/mention licence of natsort and natsortfiles
classdef COSMAS
% COSMAS A matlab library for processing of optical mapping data
methods (Static )
%%%%% READING DATA %%%%%
function [imStack, avgTrace] = readFolder(folderName, varargin)
% a helper function returning a stack of images from folder with
% image sequence. Uses natsort to get natural ordering (this is useful when there are
% files 1.png, 2.png,...,10.png,11.png, which would get sorted as 1,10,11,2, in purely alphabetic sorting, which is not the right order of frames)
%
% IN:
% folderName is the folder containing a sequence of images
% corresponding to frames.
%
% varargin can contain a structure of parameters (called e.g. readerParameters), with the
% following fields:
% 1) readerParameters.extension - extension of images in the
% given folder.
% 2) readerParameters.fromTo - a 2-by-1 vector [from to],
% determining from which to which frame is the recording to be
% processed.
% 3) readerParameters.binningFactor - spatial binning parameter
% (must be a power of two) - binningFactor x binningFactor
% pixels are aggregated into a single one.
%
% OUT:
% imStack - the resulting 3D stack, where rows and columns
% correspond to frame rows and columns, and 3rd dimension to
% index of image in the sequence (i.e. time).
%
% avgTrace - a trace corresponding to spatially averaged stack.
%% Setting defaults, reading parameters, getting filenames to be read.
extension = '.tif';
fromTo = [];
binningFactor = 1;
if ~isempty(varargin)
readerParameters = varargin{1};
end
if (isfield(readerParameters, 'extension'))
extension = readerParameters.extension;
end
if (isfield(readerParameters, 'fromTo'))
fromTo = readerParameters.fromTo;
end
if (isfield(readerParameters, 'binningFactor'))
binningFactor = readerParameters.binningFactor;
end
fnames = dir([folderName '/*' extension]);
fnames = struct2cell(fnames);
fnames = fnames(1,:);
fnames = COSMAS.natsortfiles(fnames);
if isempty(fromTo)
fromTo = [1 length(fnames)];
end
%% Checking parameter correctness
assert(fromTo(1)>=1 & fromTo(2) <= length(fnames), 'Boundaries from-to the frame are incorrect. Fewer images are available than the boundaries ask for.')
assert(round(log2(binningFactor)) == log2(binningFactor), 'The binning factor must be a power of 2.')
%% Reading stack
im = imread([folderName '/' fnames{1}]);
nFrames = fromTo(2) - fromTo(1) + 1;
imStack = zeros(size(im,1)/binningFactor, size(im,2)/binningFactor, nFrames);
avgTrace = zeros(nFrames, 1);
iFrom = fromTo(1);
iTo = fromTo(2);
for iFrame = iFrom:iTo
img = imread([folderName '/' fnames{iFrame}]);
if (size(img,3) == 3)
img = rgb2gray(img);
end
if (binningFactor ~= 1)
img = COSMAS.binningVec(img, log2(binningFactor));
end
imStack(:,:,iFrame - iFrom + 1) = img;
avgTrace(iFrame - iFrom + 1) = nanmean(img(:));
end
end
function [imStack, varargout] = readTifStack(fname, varargin)
% returning a stack of images from a single tif stack.
% fname is the path to the file (including filename and extension).
%
% IN:
% varargin can contain a structure of parameters (called readerParameters), with the
% following fields:
% 1) readerParameters.fromTo - a 2-by-1 vector [from to],
% determining from which to which frame is the recording to be
% processed
% 2) readerParameters.binningFactor - spatial binning parameter
% (must be a power of two) - binningFactor x binningFactor
% pixels are aggregated into a single one.
%
% OUT:
% imStack - the resulting 3D stack.
%
% avgTrace - a trace corresponding to spatially averaged stack.
% often there is an annotation missing in TIFF stacks, giving
% annoying warnings, so we turn that off
warning('off', 'imageio:tifftagsread:noTypeFormatId');
warning('off', 'imageio:tifftagsread:expectedTagDataFormat');
info = imfinfo(fname);
warning('on', 'imageio:tifftagsread:noTypeFormatId');
warning('on', 'imageio:tifftagsread:expectedTagDataFormat');
nFramesTotal = numel(info);
fromTo = [];
binningFactor = 1;
if ~isempty(varargin)
readerParameters = varargin{1};
end
if (isfield(readerParameters, 'fromTo'))
fromTo = readerParameters.fromTo;
end
if (isfield(readerParameters, 'binningFactor'))
binningFactor = readerParameters.binningFactor;
end
if isempty(fromTo)
fromTo = [1 nFramesTotal];
end
%% Checking parameter correctness
assert(fromTo(1)>=1 & fromTo(2) <= nFramesTotal, 'Boundaries from-to the frame are incorrect. Fewer images are available than the boundaries ask for.')
assert(round(log2(binningFactor)) == log2(binningFactor), 'The binning factor must be a power of 2.')
%% Reading stack
nFrames = fromTo(2) - fromTo(1) + 1;
imStack = zeros(info(1).Height/binningFactor, info(1).Width/binningFactor, nFrames);
avgTrace = zeros(nFrames, 1);
iFrom = fromTo(1);
iTo = fromTo(2);
for iFrame = iFrom:iTo
img = imread(fname, iFrame, 'Info', info);
if (size(img,3) == 3)
img = rgb2gray(img);
end
if (binningFactor ~= 1)
img = COSMAS.binningVec(img, log2(binningFactor));
end
imStack(:,:,iFrame - iFrom + 1) = img;
avgTrace(iFrame - iFrom + 1) = nanmean(img(:));
end
varargout{1} = avgTrace;
%% NOTE: the way of reading Tif stacks above works fine and allows reading just the images between selected indices, but it can be quite slow for very large
% stacks (e.g. 2k frames) - in that case, a faster way (which
% nevertheless requires going through all the images until iTo)
% is the one below, available in non-ancient versions of
% Matlab. One issue there is that if the stack has more than
% 2^16 frames, this crashes because it uses 16bit counter that
% overflows :/
% tstack = Tiff([folderIn '/' fnameStack.name]);
% im = tstack.read();
% imStack = zeros(size(im, 1), size(im, 2),length(stackInfo));
% for i = 2:length(stackInfo)
% img = tstack.nextDirectory();
% if (binningFactor ~= 1)
% img = COSMAS.binningVec(img, log2(binningFactor));
% end
% imStack(:,:,i) = tstack.read();
% end
end
%%%%% ANALYSING DATA %%%%%
function [baseline, amplitude, duration, activationMaps, recoveryMaps, recordingClock] = analyseRegularPacing(imageStack, bcl, parameters)
% A function for processing stacks corresponding to
% recordings with multiple passes of a wave.
%
% IN
% imageStack - a stack representing the recording.
%
% bcl - basic cycle length of the recording (in frames).
%
% parameters - a structure with parameters:
%
% parameters.baselineDefinition - whether baseline of an
% activation (e.g. calcium transient) is taken as the first
% element in each segmented activation ('first'), or as the
% average of the first and last element ('firstlast').
%
% parameters.baselineSubtractionOrder - order of polynomial
% subtraction of signal baseline. Use -1 if no baseline
% subtraction is to be done (or just leave the parameter field
% undefined).
%
% parameters.durationLevel - level at which duration is
% extracted, scaled to 0-1. E.g., use 0.8 for APD80.
%
% parameters.objectDetection - when multiple activations are discovered in
% a single signal segment (while only one can be true calcium
% transient/action potential), this parameter determines how
% the correct activation is detected (hopefully :)). 'first' -
% first object found in the segment. 'largest' - the largest
% object is picked (with most frames). 'augmented' -
% information on derivative of the signal is used, see the
% publication. For voltage mapping with multiple wave passes,
% we recommend using 'augmented' (which is not great for calcium,
% given that there are no sharp upstrokes). Otherwise, 'largest'
% is usually more robust than 'first'.
%
% parameters.smoothingParameter - width of Savitzky-Golay
% filtering for signal smoothing. It should be an odd number
% (if an even number is given, 1 will be added). Given that 4th
% order smoothing is used, this parameter has to be at least 5
% when provided (when smaller, no filtering is done).
%
% parameters.spikesPointDown - if true, signal activation
% manifests as reduction in signal intensity (e.g. some voltage
% dyes), i.e., action potentials "point down". default =
% false.
%
% parameters.verbose - if true, the code reports when there is
% a problem with segmentation and/or processing of a pixel
% trace (which can happen when a pixel contains only noise, for
% example).
%
% parameters.waveProcessing – if 'perbeat', each wave is processed separately,
% and the output structures contain a map for each complete wave pass.
% If 'hybrid', a recording clock is used to chop the recording into sub-stacks, w
% hich are then averaged, and a single-wave processing is applied to this subsequently.
% The value 'hybrid' is good for very noisy recordings and activation mapping,
% but is not suggested to be used for APD mapping or amplitude measurements.
% If ‘hybrid’ is used, parameter.objectDetection should be set to ‘largest’.
% The default is ‘perbeat’.
%
% OUT:
% baseline - a structure describing signal baseline (e.g. bases
% of calcium transients
%
% amplitude - a structure describing signal amplitude
%
% duration - a structure describing signal duration (e.g. APD)
%
% activationMaps - a structure describing activation pattern in
% the recording (relative to recording clock; if you want to
% have minimum activation in 0, just subtract minimum of these maps)
%
% recoveryMaps - a structure describing recovery pattern (e.g.
% the time when APD80 is reached). Relative to the same clock
% as activationMaps
%
% recordingClock - the recording clock determining global
% synchronization of single segmented activations
%
% the structures baseline, amplitude, and duration have the
% following fields (shown for duration):
% duration.maps - a 3D stack where each slice corresponds to
% a map of the feature in a single wave pass
%
% duration.mapMean - the average of the previous maps
%
% duration.data - a vector of spatial averages of maps in duration.maps
%
% duration.dataMean = nanmean(duration.data) - the mean of
% the field data (i.e., this gives one number summarizing
% the whole recording)
%
% duration.mapMeanEven - mean map for even beats (useful for
% inspection of alternans).
%
% duration.mapMeanOdd - mean map for odd beats
%
% duration.dataMeanEven - spatial averages of even maps of
% the feature
%
% duration.dataMeanOdd - spatial averages of odd maps of the
% feature
%
% the structure activationMaps and recoveryMaps have the same
% fields, except the ones starting with 'data' (there is not
% much point in spatially averaged activation).
%% Reading and verifying parameters
spikesPointDown = false; % if spikes point down instead of up. This is relevant for finding diastole, and for extracting baseline of the signal
if (isfield(parameters, 'spikesPointDown'))
spikesPointDown = parameters.spikesPointDown;
end
baselineDefinition = 'first';
if (isfield(parameters, 'baselineDefinition'))
baselineDefinition = parameters.baselineDefinition;
end
assert(ismember(baselineDefinition,{'first','firstlast'}), 'baselineDefinition must be either first or firstlast');
objectDetection = 'largest';
if (isfield(parameters, 'objectDetection'))
objectDetection = parameters.objectDetection;
end
assert(ismember(objectDetection,{'augmented','first','largest'}), 'objectDetection must be either augmented, first or largest');
baselineSubtractionOrder = -1;
if (isfield(parameters, 'baselineSubtractionOrder'))
baselineSubtractionOrder = parameters.baselineSubtractionOrder;
end
smoothingParameter = 11;
if (isfield(parameters, 'smoothingParameter'))
smoothingParameter = parameters.smoothingParameter;
end
durationLevel = 0.75;
if (isfield(parameters, 'durationLevel'))
durationLevel = parameters.durationLevel;
end
verbose = false;
if (isfield(parameters, 'verbose'))
verbose = parameters.verbose;
end
assert(islogical(verbose), 'verbose parameter must be either true or false');
waveProcessing = 'perbeat';
if (isfield(parameters, 'waveProcessing'))
waveProcessing = parameters.waveProcessing;
end
assert(ismember(waveProcessing,{'perbeat','hybrid'}), 'waveProcessing must be perbeat or hybrid');
customComb = [];
if (isfield(parameters, 'customComb'))
customComb = parameters.customComb;
end
nRows = size(imageStack, 1);
nCols = size(imageStack, 2);
%% Getting global signal, from which we extract the recording "timer" that separates action potentials/calcium transients
% Unlike usual, we extract locations of peaks p1,p2,..., and then build a
% timer that starts at (p1+p2)/2, so peaks happen roughly at
% midpoint between the points in the timer
avgTrace = squeeze(mean(mean(imageStack,1),2));
if (baselineSubtractionOrder > 0)
[~, avgTrace] = COSMAS.smoothTrace(avgTrace, smoothingParameter, baselineSubtractionOrder);
else
avgTrace = COSMAS.smoothTrace(avgTrace, smoothingParameter);
end
if (spikesPointDown)
maxActivations = COSMAS.combGetMinima(avgTrace, bcl, [], customComb); % as a 2nd parameter, we pass a pair of empty vector (we don't vary the surroundings of comb tips here), and the custom comb, if provided.
else
maxActivations = COSMAS.combGetMinima(-avgTrace, bcl, [], customComb);
end
recordingClock = mean([maxActivations(1:end-1);maxActivations(2:end)]);
if (~isempty(customComb))
recordingClock = [1 recordingClock size(imageStack, 3)];
end
if(strcmp(waveProcessing, 'hybrid')) % hybrid processing, where the timer is used to chop the recording to smaller parts and it is then averaged and processed using singleWavePass
recordingClock = recordingClock(1):bcl:length(avgTrace);
% Now, we process all traces in the stack with smoothing
% and baseline subtraction, then chopping it to bcl-sized
% chunks and averaging them, before processing it as a
% single wave
for iRow = 1:nRows
for iCol = 1:nCols
% extracting and smoothing the trace
pixelTrace = squeeze(imageStack(iRow,iCol,:));
if (sum(isnan(pixelTrace))>0)
continue;
end
if (baselineSubtractionOrder > 0)
[~, traceSmoothed] = COSMAS.smoothTrace(pixelTrace, smoothingParameter, baselineSubtractionOrder);
else
traceSmoothed = COSMAS.smoothTrace(pixelTrace, smoothingParameter);
end
imageStack(iRow, iCol, :) = traceSmoothed;
end
end
stackAvg = zeros(nRows, nCols, bcl);
for iPass = 1:(length(recordingClock) - 1)
stackAvg = stackAvg + imageStack(:,:,recordingClock(iPass):(recordingClock(iPass+1)-1));
traces{iPass} = avgTrace(recordingClock(iPass):(recordingClock(iPass+1)-1));
end
stackAvg = stackAvg./(length(recordingClock) - 1);
[baseline, amplitude, duration, activationMaps, recoveryMaps] = COSMAS.analyseSinglePass(stackAvg, parameters);
return;
else % otherwise we do standard processing, beat per beat
mapsBaseline = nan(nRows, nCols, length(recordingClock)-1); % for each pixel, signal baseline in the i-th pass of the wave
mapsAmplitude = nan(nRows, nCols, length(recordingClock)-1); % for each pixel, signal amplitude in the i-th pass of the wave
mapsDuration = nan(nRows, nCols, length(recordingClock)-1); % for each pixel, duration in the i-th pass of the wave
mapsActivationTimes = nan(nRows, nCols, length(recordingClock)-1); % and activation times
mapsRecoveryTimes = nan(nRows, nCols, length(recordingClock)-1); % and activation times
% for each trace, we segment it using comb, and use local
% maxima to assign the found values using recordingClock. We
% don't want to use recordingClock or anything like that itself
% for segmentation of spikes/transients, as that does not give
% fine-enough information (e.g. in discordant alternans)
for iRow = 1:nRows
for iCol = 1:nCols
pixelTrace = squeeze(imageStack(iRow, iCol, :));
if (sum(isnan(pixelTrace))>0)
continue;
end
if (baselineSubtractionOrder > 0)
[~, traceSmoothed] = COSMAS.smoothTrace(pixelTrace, smoothingParameter, baselineSubtractionOrder);
else
traceSmoothed = COSMAS.smoothTrace(pixelTrace, smoothingParameter);
end
% For the trace, we extract properties between all its
% diastoles
if (spikesPointDown)
diastoles = COSMAS.combGetMinima(-traceSmoothed, bcl, [], customComb);
else
diastoles = COSMAS.combGetMinima(traceSmoothed, bcl, [], customComb);
end
% we also find minima/maxima of dv/dt that serve
% 'augmented' object detection(finding objects nearest peak
% diff(signal).
diffSignal = COSMAS.smoothTrace(diff(traceSmoothed), smoothingParameter);
if (spikesPointDown)
peakDiffs = COSMAS.combGetMinima(diffSignal, bcl, [], customComb);
else
peakDiffs = COSMAS.combGetMinima(-diffSignal, bcl, [], customComb);
end
for iStart = 1:(length(diastoles)-1)
timeStart = diastoles(iStart);
timeEnd = diastoles(iStart + 1);
iCenter = (timeStart + timeEnd)/2; % converting the peak within single activation transient to the global temporal coordinates.
iBin = sum(iCenter > recordingClock); % after how many elements of the recording clock does the location come?
if iBin<1 || iBin>=length(recordingClock) % before/after clock starts
continue
end
peakDiffActivation = peakDiffs(peakDiffs>=timeStart & peakDiffs<=timeEnd) - timeStart + 1; % we take the time of peak activation relative to timeStart
% single activation is extracted and processed
activationTrace = traceSmoothed(timeStart:timeEnd);
[saBaseline, saAmplitude, saDuration, saActivation, saRecovery] = COSMAS.processSingleActivation(activationTrace, spikesPointDown, baselineDefinition,durationLevel, objectDetection,recordingClock, timeStart, peakDiffActivation, verbose);
mapsBaseline(iRow, iCol, iBin) = saBaseline;
mapsAmplitude(iRow, iCol, iBin) = saAmplitude;
mapsDuration(iRow, iCol, iBin) = saDuration;
mapsActivationTimes(iRow, iCol, iBin) = saActivation;
mapsRecoveryTimes(iRow, iCol, iBin) = saRecovery;
end
end
end
%% Now we remove slices with empty entries in activation - this refers to some pixels having not enough information (e.g. not enough time at the end to contain a full action potential/CaT), so these slices are discarded.
nZerosInSlice = squeeze(sum(sum(mapsActivationTimes==0, 1), 2));
mapsBaseline = mapsBaseline(:, :, nZerosInSlice == 0);
mapsAmplitude = mapsAmplitude(:, :, nZerosInSlice == 0);
mapsDuration = mapsDuration(:, :, nZerosInSlice == 0);
mapsActivationTimes = mapsActivationTimes(:, :, nZerosInSlice == 0);
% returning baseline
baseline.maps = mapsBaseline;
baseline.mapMean = nanmean(mapsBaseline, 3);
baseline.data = squeeze(nanmean(nanmean(mapsBaseline, 1), 2));
baseline.dataMean = nanmean(baseline.data);
if (size(mapsBaseline, 3) > 1)
baseline.mapMeanEven = nanmean(mapsBaseline(:,:,2:2:end), 3);
baseline.mapMeanOdd = nanmean(mapsBaseline(:,:,1:2:end), 3);
baseline.dataMeanEven = squeeze(nanmean(baseline.data(2:2:end)));
baseline.dataMeanOdd = squeeze(nanmean(baseline.data(1:2:end)));
end
% returning amplitude
amplitude.maps = mapsAmplitude;
amplitude.mapMean = nanmean(mapsAmplitude, 3);
amplitude.data = squeeze(nanmean(nanmean(mapsAmplitude, 1), 2));
amplitude.dataMean = nanmean(amplitude.data);
if (size(mapsAmplitude, 3) > 1)
amplitude.mapMeanEven = nanmean(mapsAmplitude(:,:,2:2:end), 3);
amplitude.mapMeanOdd = nanmean(mapsAmplitude(:,:,1:2:end), 3);
amplitude.dataMeanEven = squeeze(nanmean(amplitude.data(2:2:end)));
amplitude.dataMeanOdd = squeeze(nanmean(amplitude.data(1:2:end)));
end
% returning duration
duration.maps = mapsDuration;
duration.mapMean = nanmean(mapsDuration, 3);
duration.data = squeeze(nanmean(nanmean(mapsDuration, 1), 2));
duration.dataMean = nanmean(duration.data);
if (size(mapsDuration, 3) > 1)
duration.mapMeanEven = nanmean(mapsDuration(:,:,2:2:end), 3);
duration.mapMeanOdd = nanmean(mapsDuration(:,:,1:2:end), 3);
duration.dataMeanEven = squeeze(nanmean(duration.data(2:2:end)));
duration.dataMeanOdd = squeeze(nanmean(duration.data(1:2:end)));
end
% returning data on activation maps
activationMaps.maps = mapsActivationTimes;
if (size(mapsActivationTimes, 3) > 1)
activationMaps.mapMean = nanmean(mapsActivationTimes, 3);
activationMaps.mapMeanEven = nanmean(mapsActivationTimes(:,:,2:2:end), 3);
activationMaps.mapMeanOdd = nanmean(mapsActivationTimes(:,:,1:2:end), 3);
end
% returning data on recovery maps
recoveryMaps.maps = mapsRecoveryTimes;
if (size(mapsRecoveryTimes, 3) > 1)
recoveryMaps.mapMean = nanmean(mapsRecoveryTimes, 3);
recoveryMaps.mapMeanEven = nanmean(mapsRecoveryTimes(:,:,2:2:end), 3);
recoveryMaps.mapMeanOdd = nanmean(mapsRecoveryTimes(:,:,1:2:end), 3);
end
% returning clock separating activations. This is filtered to
% remove elements corresponding to incompletely filled maps
% (i.e. usually this would be just the last map, when it's not
% completely filled because some pixels don't have a
% long-enough signal there)
clockFiltered = recordingClock;
slicesDeleted = find(nZerosInSlice>0);
if (~isempty(slicesDeleted))
clockFiltered(slicesDeleted + 1) = [];
end
recordingClock = clockFiltered;
end
end
function [baseline, amplitude, duration, activationMaps, recoveryMaps] = analyseSinglePass(imageStack, parameters)
% A function for processing stacks corresponding to
% recordings with single pass of a wave. Please see the
% documentation of COSMAS.analyseRegularPacing for the
% description of inputs/outputs.
%
% In the output structures, the only fields are mapMean and
% dataMean. This may look illogical (there is just one map per
% the recording, so why would one carry out averaging over slices,
% which is essentially identity?), but
% it's based on our experience that COSMAS users mainly use the
% outputs of this function in a similar way as they'd use
% mapMean/dataMean returned by analyseRegularPacing -
% therefore, calling the outputs the same means there is less
% code rewriting needed when one switches between
% analyseRegularPacing and analyseSinglePass.
spikesPointDown = false; % if spikes point down instead of up. This is relevant for finding diastole, and for extracting baseline of the signal
if (isfield(parameters, 'spikesPointDown'))
spikesPointDown = parameters.spikesPointDown;
end
baselineDefinition = 'first';
if (isfield(parameters, 'baselineDefinition'))
baselineDefinition = parameters.baselineDefinition;
end
assert(ismember(baselineDefinition,{'first','firstlast'}), 'baselineDefinition must be either first or firstlast');
objectDetection = 'largest';
if (isfield(parameters, 'objectDetection'))
objectDetection = parameters.objectDetection;
end
assert(ismember(objectDetection,{'augmented','first','largest'}), 'objectDetection must be either augmented, first or largest');
baselineSubtractionOrder = -1;
if (isfield(parameters, 'baselineSubtractionOrder'))
baselineSubtractionOrder = parameters.baselineSubtractionOrder;
end
smoothingParameter = 11;
if (isfield(parameters, 'smoothingParameter'))
smoothingParameter = parameters.smoothingParameter;
end
durationLevel = 0.75;
if (isfield(parameters, 'durationLevel'))
durationLevel = parameters.durationLevel;
end
verbose = false;
if (isfield(parameters, 'verbose'))
verbose = parameters.verbose;
end
assert(islogical(verbose), 'verbose parameter must be either true or false');
nRows = size(imageStack, 1);
nCols = size(imageStack, 2);
mapBaseline = nan(nRows, nCols);
mapAmplitude = nan(nRows, nCols);
mapDuration = nan(nRows, nCols);
mapActivationTimes = nan(nRows, nCols);
mapRecoveryTimes = nan(nRows, nCols);
for iRow = 1:nRows
for iCol = 1:nCols
pixelTrace = squeeze(imageStack(iRow, iCol, :));
% we smooth the trace, but do not perform baseline
% subtraction - that can cause a huge mess in
% single-wave traces
traceSmoothed = COSMAS.smoothTrace(pixelTrace, smoothingParameter);
if (sum(isnan(pixelTrace))>0)
continue;
end
timeStart = 1;
diffSignal = diff(traceSmoothed) + 1;
if (spikesPointDown)
[~ ,peakDiffActivation] = min(diffSignal);
else
[~, peakDiffActivation] = min(-diffSignal);
end
recordingClock = [0, inf]; % this is a fairly dummy value, making sure that the results are considered to belong to the first wave (out of 1 :)).
% single activation is extracted and processed
[saBaseline, saAmplitude, saDuration, saActivation, saRecovery] = COSMAS.processSingleActivation(traceSmoothed, spikesPointDown, baselineDefinition,durationLevel, objectDetection,recordingClock, timeStart, peakDiffActivation, verbose);
mapBaseline(iRow, iCol) = saBaseline;
mapAmplitude(iRow, iCol) = saAmplitude;
mapDuration(iRow, iCol) = saDuration;
mapActivationTimes(iRow, iCol) = saActivation;
mapRecoveryTimes(iRow, iCol) = saRecovery;
end
end
% returning baseline
baseline.mapMean = mapBaseline;
baseline.dataMean = nanmean(mapBaseline(:));
% returning amplitude
amplitude.mapMean = mapAmplitude;
amplitude.dataMean = nanmean(mapAmplitude(:));
% returning duration
duration.mapMean = mapDuration;
duration.dataMean = nanmean(mapDuration(:));
% returning data on activation maps
activationMaps.mapMean = mapActivationTimes;
% returning data on recovery maps
recoveryMaps.mapMean = mapRecoveryTimes;
end
%%%%% POSTPROCESSING %%%%%
function alternans = getAlternans(data, varargin)
% Extracts alternans quantity for a given feature (e.g. amplitude or duration).
% It can either work on a vector of numbers, giving alternans between odd/even values,
% or on a stack of multiple wave passes (giving spatial
% alternans map over odd/even slices).
%
% IN:
% data - either a vector of numbers or a stack of spatial maps
% of the feature on which alternans is to be measured (e.g.
% amplitude.maps produced by COSMAS.analyseRegularPacing).
%
% varargin - an optional parameter which may determine the method for alternans estimation. In
% both, average for even and odd values/slices is computed. Then,
% 'largerToSmaller' (default) measures ratio of larger to smaller, and
% 'sMAPE' does abs(odd-even)/(odd+even).
%
% OUT:
% alternans - if data is a vector, this gives a single number,
% if data is a stack of spatial maps, it produces a single
% spatial map.
method = 'largerToSmaller';
if (~isempty(varargin))
method = varargin{1};
end
assert(ismember(method, {'largerToSmaller', 'sMAPE'}), 'The parameter specifying the method must be either largerToSmaller or sMAPE.');
if (length(size(data))==2) % if we have a vector of numbers, we convert it to a stack so we can process everything the same way
data = COSMAS.traceToStack(data);
end
meanOdd = nanmean(data(:,:,1:2:end), 3);
meanEven = nanmean(data(:,:,2:2:end), 3);
maxMap = max(meanOdd,meanEven);
minMap = min(meanOdd,meanEven);
if (isequal(method, 'largerToSmaller'))
alternans = maxMap ./ minMap;
elseif (isequal(method, 'sMAPE'))
alternans = abs(meanOdd - meanEven)./(meanOdd + meanEven);
end
end
function cv = getCV(activationMap, XY, varargin)
% Analyse conduction velocity (CV) between pair (or pairs) of points.
% By default, this returns the CV in pixels per frame, but can also
% provide it in cm/s.
%
% IN:
% activationMap - a single activation map.
%
% XY - a matrix of size n-by-4 encoding pairs of points between which CV is measured using the provided activation map.
% Each row corresponds to an origin and target point (columns
% are: rowFrom, columnFrom, rowTo, columnTo).
%
% varargin may optionally contain a two-numbers parameter allowing specification of spatial (how many mm is a single pixel side) and temporal resolution (in frames per second). If not given, the output is in pixels/frame, otherwise in cm/s.
%
% OUT:
% cv - a vector of conduction velocities, one per row of XY.
nRows = size(XY, 1);
cv = zeros(nRows, 1);
for iRow = 1:nRows
fromRow = XY(iRow, 1);
fromCol = XY(iRow, 2);
toRow = XY(iRow, 3);
toCol = XY(iRow, 4);
distDiff = sqrt((fromRow - toRow)^2 + (fromCol - toCol)^2);
timeDiff = activationMap(toRow, toCol) - activationMap(fromRow, fromCol);
end
cv = distDiff/timeDiff;
% Potential rescaling to cm/s
if (~isempty(varargin))
assert(length(varargin{1})==2, 'the scaling vector must be a 2-by-1 or 1-by-2 vetor specifying how many mm is a single pixel and what is the temporal resolution (fps)');
distancePerPixel = varargin{1}(1);
fps = varargin{1}(2);
cv = (cv * distancePerPixel*fps)/10; % /10 is to convert mm/ms to cm/s
end
end
function xyuv = getLocalCV(activationMap, baylyNeighbourhood, varargin)
% Performs local estimation of CV using Bayly's method (doi: 10.1109/10.668746), producing a vector field and optionally its plot.
%
% IN:
% activationMap - activation map from which a vector field is
% obtained.
%
% baylyNeighbourhood - distance around a point that is
% considered when fitting the Bayly polynomial.
%
% varargin{1} - if defined, gives maximum length of a velocity
% vector (the longer ones are discarded).
%
% varargin{2} - if defined, contains the index of figure in
% which the CV field is drawn. If not defined, no figure is
% produced.
%
% varargin{3} - if defined, the output path of storage of
% varargin{2}.
%
% OUT:
% xyuv - a n-by-4 matrix, where n is number of pixels and columns correspond
% to x,y,u,v: x,y gives indices of row and column, with u,v
% corresponding to dx,dy. Mind that this is in row/column
% coordinates - if plotting via quiver (in standard x-y
% coordinates), this needs to be shuffled slightly, see the code
% at the end of the function.
maxDistance = Inf;
if (length(varargin)>=1)
maxDistance = varargin{1}; % maximum arrow length that is not discarded
end
figureNumber = [];
if (length(varargin)>=2)
figureNumber = varargin{2}; % maximum arrow length that is not discarded
end
foutName = [];
if (length(varargin)>=3)
foutName = varargin{3}; % maximum arrow length that is not discarded
end
%% Bayly CV estimation
nRows = size(activationMap, 1);
nCols = size(activationMap, 2);
[m,n] = ndgrid(1:nRows, 1:nCols);
Z = [m(:), n(:)];
activationTimes = activationMap(:); % same order of activation times as in Z.
xyuv = zeros(size(Z,1), 4);
for iPoint = 1:size(Z,1)
% for each point, find points nearby.
thisPoint = Z(iPoint,:);
distances = pdist2(thisPoint, Z);
whereNeighbours = find((distances>=0) & (distances<=baylyNeighbourhood));
locationsNeighbours = Z(whereNeighbours, :);
neighbourActivationTimes = activationTimes(whereNeighbours);
try
sf = fit([locationsNeighbours], neighbourActivationTimes, 'poly22');
catch
xyuv(iPoint, :) = [thisPoint(1), thisPoint(2), NaN, NaN]; % Massive vector that will be rejected
continue;
end
coeffs = coeffvalues(sf); %const, x, y, x2, xy, y2 ;
% IN PAPER: f, d, e, a, c, b
x = thisPoint(1);
y = thisPoint(2);
dx = coeffs(2)+2*coeffs(4)*x + coeffs(5)*y; % x
dy = coeffs(3)+2*coeffs(6)*y + coeffs(5)*x; % y
xyuv(iPoint, :) = [x, y, dx/(dx*dx+dy*dy), dy/(dx*dx+dy*dy)];
end
%% We get rid of dx,dy which are too long
arrowLengths = sqrt(xyuv(:,3).*xyuv(:,3) + xyuv(:,4).*xyuv(:,4));
xyuv(arrowLengths > maxDistance, 3) = NaN;
xyuv(arrowLengths > maxDistance, 4) = NaN;
%% Optional plotting of the quiver. Given that axes are
% different between x/y (and for Matlab row/columns, [1,1] is
% top left, while for common set of axes it is bottom left, so
% we do complement for the 2nd parameter in quiver and we flip
% the sign of the fourth parameter in quiver)
if (~isempty(figureNumber))
figure(figureNumber);
quiver(xyuv(:,2), 16-xyuv(:,1), xyuv(:,4), -xyuv(:,3), 0, 'k');
if (~isempty(foutName))
saveas(gcf, foutName);
end
end
end
function plotActivationMap(activationMap, varargin)
% This function plots a contour map of activation.
%
% IN:
% activationMap - a single activation map from which contours are
% obtained.
%
% varagin{1} - optionally, the index of figure used for this purpose may be given - if not
% specified, a new figure is opened and used.
%
% varargin{2} - optional parameter defining the
% 'levels' parameter of @contourf (basically, a contour line is
% drawn each varargin{2} ms).
figureNumber = [];
if (~isempty(varargin))
figureNumber = varargin{1};
assert(isnumeric(figureNumber), 'the second parameter (figure number) must be a positive integer');
assert(figureNumber > 0, 'the second parameter (figure number) must be a positive integer');
end
levelGranularity = 1;
if (length(varargin)>=2)
levelGranularity = varargin{2};
end
if isempty(figureNumber)
figure;
else
figure(figureNumber);
end
contourf(flipud(activationMap - min(min(activationMap))), 'levels', levelGranularity, 'ShowText', 'on');
set(gca,'XTick',[]);
set(gca,'YTick',[]);
end
%%%%% HELPER FUNCTIONS %%%%%
function imStackOut = applyMask(imStackIn, mask)
% This function may be used to apply a binary mask to each frame of a 3D stack, setting pixels-to-be-discarded to NaN.
% This may be useful to get rid of empty space around the image
% of the heart, space around a Petri dish for cultures, etc.
%
% IN:
% imStackIn - a 3D stack representing a recording.
%
% mask - a binary mask of the same size as a single frame of
% imStackIn. Where mask==0, the corresponding pixels are set to
% NaN.
%
% OUT:
% imStackOut - imStackIn where zero elements in mask are set to
% NaN for each frame.
imStackOut = imStackIn;
for iFrame = 1:size(imStackIn, 3)
frame = imStackIn(:,:,iFrame);
frame(mask==0) = NaN;
imStackOut(:,:,iFrame) = frame;
end
end
function binnedImage = binningVec(img, logfactor)
% A function which carries out spatial binning for an image
% (replacing each bin with the average of the pixels found in
% it).
%
% IN:
% img - an image to be spatially binned.
%
% logfactor - base-two logarithm of the binning factor - this must be a
% positive integer (i.e., logfactor of 1 leads to 2-by-2
% binning, 2 to 4-by4, 3 to 8-by-8, etc.). Note that while this
% helper function requires a logarithm of the binning factor,
% the data-reading functions readFolder and readTifStack take
% the binning factor directly, computing its logarithm
% internally, so that the user doesn't have to take care of
% that.
%
% OUT:
% binnedImage - the source image after spatial binning.
binnedImage = img;
for j = 1:logfactor % How many binnings
oddRows = double(binnedImage(1:2:end,:)); % A submatrix of blkimg of odd columns
evenRows = double(binnedImage(2:2:end,:)); % A submatrix of blkimg of even columns
rowBinned = (oddRows + evenRows) / 2;
oddCols = rowBinned(:, 1:2:end); % And similar thing done for rows
evenCols = rowBinned(:, 2:2:end);
binnedImage = (oddCols + evenCols)/2; % img binned by 2^j
end
end
function vectorMinima = combGetMinima(signalTrace, bcl, varargin)
% A function searching for minima in traces from cardiac preparations with known activation pattern.
% The function can be naturally also used to extract signal maxima when
% the source trace is inverted.
%
% IN:
% signalTrace - a vector containing signal, such as calcium transients or action potentials
% (e.g., intensity of a pixel in optical mapping, or an electrophysiological recording).
%
% bcl - the basic cycle length (number of frames between two activations).
%
% varargin{1} - The first optional parameter is the refinementWidth parameter for comb algorithm
% (in ms/samples - the radius of local search around comb
% teeth). Default is 10.
%
% varargin{2} - The second optional parameter is the custom comb that is used instead of the
% regularly placed one. It should be an increasing vector of
% numbers, where the first element determines the last possible
% position of the first minimum to be searched for, and the
% subsequent elements give further indices of minima. E.g.
% using [30 180, 330, 400] means that the algorithm will search
% for 3 minima that are 150 frames apart, and one that is
% further 100 frames after the last previous one, and the first
% minimum is to be placed between frame 1 and frame 30. See
% sampleScript_5_S1S2 for an example of custom comb. If this parameter is defined, then
% the parameter ‘bcl’ is not used within the code (it still has to be provided,
% but it can be any number).
%
%
% OUT:
% vectorMinima - the vector of local minima in the signal, which are
% approximately bcl ms (or samples) apart.
%% Default parameter initialization and processing of extra inputs.
refinementWidth = 10;
customComb = [];
if (numel(varargin) == 1) % 1st extra argument is the width of local search
if (~isempty(varargin{1}))
refinementWidth = varargin{1};
end
elseif (numel(varargin) == 2)
if (~isempty(varargin{1}))
refinementWidth = varargin{1};
end
if (~isempty(varargin{2}))
customComb = varargin{2};
end
end
%% Comb positioning