-
Notifications
You must be signed in to change notification settings - Fork 0
/
s1s2peakdetect.m
4557 lines (3916 loc) · 243 KB
/
s1s2peakdetect.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
% -------------------------------------------------------
%
% s1s2peakdetect - CVAR-Seg main class
%
% Ver. 1.0.0
%
% Created: Mark Nothstein (25.02.2020)
% Last modified: Mark Nothstein (25.02.2020)
%
% Institute of Biomedical Engineering
% Karlsruhe Institute of Technology
%
% http://www.ibt.kit.edu
%
% Copyright 2000-2020 - All rights reserved.
%
% ------------------------------------------------------
%
% location(namein,sampleratein,xyzin,elin,cathin,timein)
% class storing geometric data.
%
% Expected input are unipolar positions of electrodes.
% Functionality to calc estimated bipolar positions, distance between
% catheter electrodes (uni or bipolar)
%
%
% Inputs:
% Required:
% 'signal_in_bi' array - (samples x value)
% 'samplerate' int - (samplerate Hz, e.g 1000)
% 'leads_in' cellarray ({'CS';'CS';...})
% 'elecs_in' cellarray ({'1-2';'2-3';...})
% 'type' 'bipolar','unipolar' (legacy -> only bipolar is supported)
% 'location' location class -> see classes folder
% 'map' map class -> see classes folder
% 'ECG' location class -> see classes folder
% Optional:
% 'signal_in_uni' array - (samples x value)
% 'leads_in_uni' cellarray ({'CS';'CS';...})
% 'elecs_in_uni' cellarray ({'1';'2';...})
% 'name' string
% 's1time' double
% 's2times' array double
% 'ERP' double
%The values s1time,s2time,ERP are never used and are only ment as a way to
%store all measurement data in one class
%
% Outputs:
% location class
%
%
% Example Usage:
% see run_cvar_bench
%
% Revision history:
classdef s1s2peakdetect < handle
properties
signal %struct storing signal_in_bi,bi etc..
signalflag
isfiltered
samplerate
leads
elecs
locations
map
ecg
stimchan
timeline
name
init
weight
threshold
guess_siglength_stim
variables
classcheck
S1_time
numof_stimuli_in_one_block
numof_S1_in_one_block
S1_blocknum
S1_blocknum_locs
s2_steps
s2_fs
erp_id
bad_aa_blocks
cv_plot
amp_plot
atrial_segments
signal_properties
nonstimchan_signal_properties
%manual method
manual_segments_stimchan_list % not tested or developed further
settings
end
methods
function obj = s1s2peakdetect(signal_in_bi,samplerate,leads_in,elecs_in,type,varargin)
%Constructs
p = inputParser;
addRequired(p,'signal_in_bi',@(x) ~isempty(x) && isnumeric(x));
addRequired(p,'samplerate',@(x) ~isempty(x) && isnumeric(x) && size(x,1)==1 && size(x,2)==1);
addRequired(p,'leads_in',@(x) ~isempty(x) && max(size(x))==min(size(signal_in_bi)) );
addRequired(p,'elecs_in',@(x) ~isempty(x) && max(size(x))==min(size(signal_in_bi)) );
addRequired(p,'type',@(x) ~isempty(x) && ischar(x));
addParameter(p,'signal_in_uni','',@(x) ~isempty(x) && isnumeric(x));
addParameter(p,'leads_in_uni',@(x) ~isempty(x) && max(size(x))==min(size(signal_in_uni)) );
addParameter(p,'elecs_in_uni',@(x) ~isempty(x) && max(size(x))==min(size(signal_in_uni)) );
addParameter(p,'name','',@(x) ischar(x) && ~isempty(x) );
addParameter(p,'s1time','',@(x) isnumeric(x) && ~isempty(x) );
addParameter(p,'s2times','',@(x) isnumeric(x) && ~isempty(x) );
addParameter(p,'ERP','',@(x) isnumeric(x) && ~isempty(x) && size(x,1)==1 && size(x,2)==1 );
addParameter(p,'location','',@(x) isa(x,'location') && ~isempty(x) );
addParameter(p,'map','',@(x) isa(x,'map') && ~isempty(x) );
addParameter(p,'ECG','',@(x) ~isempty(x) );
try
p.parse( signal_in_bi,samplerate,leads_in,elecs_in,type,varargin{:} );
catch MyError
rethrow(MyError);
end
%needed values
obj.signal.in_bi = p.Results.signal_in_bi;
obj.samplerate = p.Results.samplerate;
obj.leads.in = p.Results.leads_in;
obj.elecs.in = p.Results.elecs_in;
obj.signalflag = p.Results.type;
obj.locations = p.Results.location;
%optional values
obj.signal.in_uni = p.Results.signal_in_uni;
obj.leads.in_uni = p.Results.leads_in_uni;
obj.elecs.in_uni = p.Results.elecs_in_uni;
obj.name = p.Results.name;
obj.classcheck.ERP = p.Results.ERP;
obj.classcheck.s1time = p.Results.s1time;
%s2
if ~isempty(p.Results.s2times) && size(p.Results.s2times,1)<size(p.Results.s2times,2) %s2times given
obj.classcheck.s2times = p.Results.s2times';
elseif ~isempty(p.Results.s2times)
obj.classcheck.s2times = p.Results.s2times;
else
obj.classcheck.s2times = p.Results.s2times;
end
obj.map = p.Results.map;
obj.ecg.in = p.Results.ECG;
clear p varargin signal.in samplerate isunipolar leads_in
%settings
obj.settings.manualmode = 0;
obj.settings.ploton = 0;
if obj.settings.manualmode %since no check possible without plots
obj.settings.ploton = 1;
end
%initialization
obj.init.k = 0.01*obj.samplerate/1000; %high k means less peaks
obj.init.step_k = 0.01;
obj.init.lp_uni = 500; %change this once using unipolar
obj.init.hp_uni = 5;
obj.init.lp_bi = 250;
obj.init.hp_bi = 1;
obj.init.filt_order = 2;
obj.init.min_CV = 10; %units: mm/s
obj.init.s = 20; %units: mm
obj.init.highhp = 450; %used to find stimulipeaks, should be larger than 300! & lower than whatever filter set in init.lp
obj.init.S1_guess_good = false;
obj.init.S1_block_guess_good = false;
obj.init.foundS1_sequence = false;
obj.init.s1s2found = false;
obj.init.step_weighting_increase = 1; %dependant on your weighting scheme,for mine should be int!
%weighting factors
obj.weight.detected_in_stim_chan = 2; %detected peaks in stimchan most likely primarily stimulations
obj.weight.detected_in_chan = 1;
obj.weight.hp_detected_in_stim_chan = 20;
obj.weight.hp_detected_in_chan = 10;
obj.weight.dist = 100;
obj.weight.diff = 100;
obj.weight.amp = 100;
%thresholds
obj.threshold.deviation_S1_guess = 10; %units: samples, by how many samples the neighbour peaks are alowed to differ
obj.threshold.max_itterations_S1_guess = 100;
obj.threshold.max_neighbour = 5; %number of multiples of distancees that should be evaluated by histogram,e.g. 3*s1dist
obj.threshold.s1_block_guess_variance = 2; %programm guesses how many stimuli are in an s1 train. To test this we add and subtract a variance and test if result gets better or worse. eg guess is 6, variance is 3 we test (3 4 5 6 7 8 9)
obj.threshold.max_deviation_S1_block_guess = 100; %units: samples
obj.threshold.deviation_S1_block_guess = 0.08*obj.samplerate; %by how many samples the S1 guess is allowed to be wrong
obj.threshold.increase_S1_block_deviation= 2; %increments (units: samples) that the threshold should be lowered
obj.threshold.stimuluslength_fs = (0.002+0.015)*obj.samplerate; %most stimulus generators have an exponential capacitor decay of ~6ms (UHS30) or 15ms(UHS3000)
obj.threshold.stimuluslength_fs_deviation = round(obj.threshold.stimuluslength_fs * 0.5);
obj.threshold.ERP_ratio_perc = 0.2;
%variables changing
obj.variables.k = obj.init.k;
obj.variables.method_s1s2detect = 'wavelet';
%obj.start_detection
end
function start_detection(obj)
%starts detection with unfiltered bipolar navx signals
%baselineremoval
%===============
obj.getbipolarsignalsandleads();
obj.splitcatheters();
obj.getstimchannel();
if obj.settings.manualmode==1
obj.presegmentsignal();
else
obj.ecg.filt.ydata = obj.ecg.in.ydata;
end
obj.detectEKGpeaks();
%remove baselinedrift etc... Extreme filtering is done later on
%in each function depending on what it focusses on.
obj.prefilter_signals();
obj.guessS1time();
if obj.settings.ploton
obj.timeline.plotsupersegments(obj.signal.bi_stimchan(:,obj.stimchan.distant_el_id),0)
end
obj.high_lp_filt_weighting(obj.variables.k);
if obj.settings.ploton
obj.timeline.plotsupersegmentweights(obj.signal.bi_stimchan);
end
obj.guessblocklocations
obj.deletesegmentsoutsideblocks(); %dependant on perfect block detection!
obj.adddistanceweighting();
obj.addthresholdweighting;
obj.adddistanceweighting_old();
obj.findS1S2peaks();
if strcmp(obj.variables.method_s1s2detect,'wavelet')
obj.refine_segments();
end
obj.gets2times();
obj.checkVF()
obj.getPwavestats();
obj.decideStimTemplate();
obj.gets1activity();
obj.getatrialactivity(); %something goes wrong here!!!
obj.combine_segmented_sig();
obj.getatrialamplitudes();
obj.gets1activity_nonstimchan();
obj.getatrialactivity_nonstimchan();
obj.getatrialamplitudes_nonstimchan();
obj.detectERP(obj.threshold.ERP_ratio_perc);
%unipolar part
if ~isempty(obj.signal.in_uni)
obj.getatrialactivity_unipolar();
end
try
obj.getlocations();
catch %Here for now cause of benchmarkpaper
end
%obj.plotLassoCV_theo(); %not really needed/necessary
%obj.plotLassoCVRestitution_real();
%obj.plotLassoAMPRestitution();
end
function getbipolarsignalsandleads(obj)
%gets signals, leads end electrodenumber from input
%if falg 'unipolar' is given -> bipolar is calc from unipolar even if
%bipolar is given
%if
if strcmp(obj.signalflag,'unipolar')
[obj.signal.bi, obj.leads.bi, obj.elecs.bi] = uni2bip(obj.signal.in_uni,obj.leads.in,obj.elecs.in,0);
elseif strcmp(obj.signalflag,'bipolar')
obj.signal.bi = obj.signal.in_bi; %use singal instead of signal.in because a previous filtering can have occured
obj.leads.bi = obj.leads.in;
obj.elecs.bi = obj.elecs.in;
else
fprintf('Error. signaltype unknown.\n')
end
if size(obj.signal.bi,1)<size(obj.signal.bi,2) %rows should be time & columns electrodes
obj.signal.bi = obj.signal.bi';
end
if size(obj.leads.bi,1)<size(obj.leads.bi,2) %rows should be channels, columns nothing
obj.leads.bi = obj.leads.bi';
end
if size(obj.elecs.bi,1)<size(obj.elecs.bi,2) %rows should be channels, columns nothing
obj.elecs.bi = obj.elecs.bi';
end
end
function splitcatheters(obj)
[obj.signal.bi_split,obj.leads.bi_split,obj.elecs.bi_split,~] = splitcatheters(obj.signal.bi,obj.leads.bi,obj.elecs.bi,'navx');
if ~isempty(obj.signal.in_uni)
[obj.signal.uni_split,obj.leads.uni_split,obj.elecs.uni_split,~] = splitcatheters(obj.signal.in_uni,obj.leads.in_uni,obj.elecs.in_uni,'navx');
end
end
function getstimchannel(obj)
obj.stimchan = [];
obj.stimchan.exclude_chan = [];
if ~isempty(obj.name) %if name given try getting from name & from signal
stimchan = getstimchanfromsig(ECG_Baseline_Removal(obj.signal.bi,obj.samplerate,0.01,0.5),obj.leads.bi,obj.elecs.bi,obj.signalflag); %remove baseline so maximum can be compared
stimchan2 = getstimchanfromname(obj.name);
if ~isequal(stimchan.cath,stimchan2.cath) %if not the same use name, because signals can be tricky
fprintf('Stimchan found from signals does not match name of case, check this! Getting stimchan from name\n')
obj.stimchan = stimchan2;
obj.stimchan.size_chan = size(obj.leads.bi_split.(obj.stimchan.cath),1);
obj.stimchan.idpostsplit = find(contains(obj.elecs.bi_split.(obj.stimchan.cath),[num2str(obj.stimchan.el1) '-' num2str(obj.stimchan.el1+1)]));%find(contains(obj.leads.bi_split.SPI,[num2str(obj.stimchan.el1) num2str(obj.stimchan.el1+1)]));
%return
elseif ~isequal(stimchan.el1,stimchan2.el1) && ~isequal(stimchan.el2,stimchan2.el2)
fprintf('Stimelectrodes found from signals do not match the ones in name. Using name as default.\n')
obj.stimchan = stimchan2;
obj.stimchan.size_chan = size(obj.leads.bi_split.(obj.stimchan.cath),1);
obj.stimchan.idpostsplit = find(contains(obj.elecs.bi_split.SPI,[num2str(obj.stimchan.el1) '-' num2str(obj.stimchan.el1+1)]));
if isempty(obj.stimchan.idpostsplit)
obj.stimchan.idpostsplit = str2double(input('Stimechannel is not part of the signals, choose closest matching ID. (Dont count CS if SPI is stimchan)\n','s'));
end
else
obj.stimchan = stimchan;
end
clearvars stimchan2
else %if name not given, guess stimchan from signal %TODO not robust, needs more love (find bumps after stim in chan next)
obj.stimchan = getstimchanfromsig(obj.signal,obj.leads.in);
end
fprintf('Stimchan is: %s\nStimelectrodes are: %.0f and %.0f .\n',obj.stimchan.cath,obj.stimchan.el1,obj.stimchan.el2)
%create non-stimchan as well
obj.stimchan.non_stimchan = char(setdiff({'CS' 'SPI'},obj.stimchan.cath));
%create excludechannel. For Cs Stim only stimchan, for spiral
%also left & right neighbour
obj.stimchan.exclude_chan = [];
if strcmpi(obj.stimchan.cath,'cs')
left_of_stimchan = [];
right_of_stimchan = [];
else
if obj.stimchan.idpostsplit-1==0
left_of_stimchan = obj.stimchan.size_chan;
right_of_stimchan = obj.stimchan.idpostsplit+1;
elseif obj.stimchan.idpostsplit+1==obj.stimchan.size_chan+1
left_of_stimchan = obj.stimchan.idpostsplit;
right_of_stimchan = 1;
else
right_of_stimchan = obj.stimchan.idpostsplit + 1;
left_of_stimchan = obj.stimchan.idpostsplit - 1;
end
end
obj.stimchan.exclude_chan = unique([obj.stimchan.exclude_chan;obj.stimchan.idpostsplit;right_of_stimchan;left_of_stimchan]);
%find most opposite channel
possible_chan_ids = [1:obj.stimchan.size_chan];
non_excluded_ids = possible_chan_ids(~ismember(possible_chan_ids,obj.stimchan.exclude_chan));
furthest_id = min(diff(sort(non_excluded_ids)));
obj.stimchan.distant_el_id = furthest_id;
end
function detectEKGpeaks(obj)
% 1. Pon: Beginning of the P wave
% 2. Ppeak: Peak of the P wave
% 3. Poff: End of the P wave
% 4. QRSon: Beginning of the QRS complex
% 5. Qpeak: Q peak of the QRS complex
% 6. Rpeak: R peak of the QRS complex
% 7. Speak: S peak of the QRS complex
% 8. QRSoff: End of the QRS complex
% 9. Lpoint: The middle of the ST segment
% 10. Pon: Beginning of the T wave
% 11. Ppeak: Peak of the T wave
% 12. Poff: End of the T wave
% 13. Classification of each beat: 1: Normal beat; 2: Ventricular ectopic beat; 3; Supraventricualr ectopic beat; 20: Unclassified
obj.ecg.detection = Annotate_ECG_Multi(obj.ecg.in.ydata(:,1),obj.ecg.in.samplerate);
end
function presegmentsignal(obj)
f1 = figure;
figure(f1);
ax1 = axes;
plot(ax1,obj.signal.bi_split.(obj.stimchan.cath)(:,obj.stimchan.idpostsplit))
[x,~] = ginput(2);
if x(1)<x(2)
sig_trim_start = floor(x(1));
sig_trim_end = floor(x(2));
else
sig_trim_start = floor(x(2));
sig_trim_end = floor(x(1));
end
fieldnam = fieldnames(obj.signal.bi_split);
for i=1:numel(fieldnam)
if ~isempty(obj.signal.bi_split.(fieldnam{i}))
if sig_trim_end > size(obj.signal.bi_split.(fieldnam{i}),1)
sig_trim_end = size(obj.signal.bi_split.(fieldnam{i}),1);
end
if sig_trim_start < 1
sig_trim_start = 1;
end
obj.signal.bi_split.(fieldnam{i}) = obj.signal.bi_split.(fieldnam{i})(sig_trim_start:sig_trim_end,:);
end
end
%unipolar
if ~isempty(obj.signal.in_uni) %uni_split
fieldnam = fieldnames(obj.signal.uni_split);
for i=1:numel(fieldnam)
if ~isempty(obj.signal.uni_split.(fieldnam{i}))
if sig_trim_end > size(obj.signal.uni_split.(fieldnam{i}),1)
sig_trim_end = size(obj.signal.uni_split.(fieldnam{i}),1);
end
if sig_trim_start < 1
sig_trim_start = 1;
end
obj.signal.uni_split.(fieldnam{i}) = obj.signal.uni_split.(fieldnam{i})(sig_trim_start:sig_trim_end,:);
end
end
end
%ecg (might have differentsamplerate)
if ~isequal(size(obj.ecg.in.ydata,1),size(obj.signal.in_bi,1))
fprintf('Unequal ECG and signal samples\n')
end
upsampfactor = obj.ecg.in.samplerate/obj.samplerate;
if upsampfactor~=1
for i=1:size(obj.ecg.in.ydata,2)
new_vec_dat(:,i) = interp(obj.ecg.in.ydata(:,i),upsampfactor);
end
obj.ecg.in.ydata = new_vec_dat;
end
obj.ecg.filt.ydata = obj.ecg.in.ydata(sig_trim_start:sig_trim_end,:);
obj.signal.trimid = [sig_trim_start-1 sig_trim_end];
end
function prefilter_signals(obj)
%prefilter signals according to what you need here
%all signals are filtered, so you campare same things later
%======================
% Bipolar
%======================
obj.signal.bi_split_prefilt = obj.signal.bi_split; %in case no filtering is used take unfilt vals
allcath = fieldnames(obj.signal.bi_split);
for i=1:numel(allcath)
sig = obj.signal.bi_split.(allcath{i});
%add your filters here: in form: sig = filter(sig,samplerate,bla)
sig = ECG_High_Filter(sig,obj.samplerate,obj.init.hp_bi); %obj.init.hp_bi statt 1Hz
%sig = add_further_filters_her;
obj.signal.bi_split_prefilt.(allcath{i}) = sig;
end
%======================
% Unipolar
%======================
if ~isempty(obj.signal.in_uni)
obj.signal.uni_split_prefilt = obj.signal.uni_split;
allcath = fieldnames(obj.signal.uni_split);
for i=1:numel(allcath)
sig = obj.signal.uni_split.(allcath{i});
%add your filters here: in form: sig = filter(sig,samplerate,bla)
sig = ECG_High_Filter(sig,obj.samplerate,1);
sig = ECG_Baseline_Removal(sig,obj.samplerate,0.02,0.5); %windowlength without overlap should not be shorter than atrial signal!
obj.signal.uni_split_prefilt.(allcath{i}) = sig;
end
%=======================
% Delete channels at the shaft of the catheter of 12 and
% 22 electrode catheters
%=======================
%unipolar
if size(obj.signal.uni_split_prefilt.SPI,2) == 12 || size(obj.signal.uni_split_prefilt,2) == 22
obj.signal.uni_split.SPI = obj.signal.uni_split.SPI(:,1:end-2);
end
end
%bipolar
if size(obj.signal.bi_split_prefilt.SPI,2) == 11 || size(obj.signal.bi_split_prefilt,2) == 21
obj.signal.bi_split.SPI = obj.signal.bi_split.SPI(:,1:end-2);
end
end
function getwaveletinfo(obj,k)
allcath = fieldnames(obj.signal.bi_split_prefilt);
fieldidofstim = strcmp(obj.stimchan.cath,allcath);
stimcathname = (allcath(fieldidofstim));
obj.signal.bi_stimchan = obj.signal.bi_split_prefilt.(stimcathname{1});
stimchan_ids = 1:obj.stimchan.size_chan;
[coeff,score,latent,tsquared,explained,mu] = pca(obj.signal.bi_stimchan(:,stimchan_ids));
sig = score(:,1);
sig_bi_wavelet = method_wavelet(sig','WaveletShape','bior1.5','samplerate',obj.samplerate,'ThresholdFactor',k,'MinimumInaktivityLength',10,'MinimumAktivityLength',15,'Postprocessing','On'); %smaller k -> more peaks, thresh=k*std 10 or 12
[~,activseg_wavelet] = getActiveSegmentsFromNLEOInShortWindow(sig_bi_wavelet',obj.samplerate,0.1); %chose k higher for less (or thinner main) peaks here
activseg = repmat(activseg_wavelet,[obj.stimchan.size_chan 1]);
for i=1:obj.stimchan.size_chan
[channel_peaks_fs{i},~] = getpeaksfromActiveSegmentsNLEO(nleo(obj.signal.bi_stimchan(:,i),obj.samplerate,1,k),activseg{i},obj.samplerate); %active segment peaks to calc distances later
%get most common signallength
tmp = diff(activseg{i},1,2); %difference between start and endpoint of active segemnts gives length
[N,edges] = histcounts(tmp(tmp~=0));
[~,idx_max_signallength] = max(N); %max of histogramm
[~,idx_min_signallength] = min(N);
mean_signallength_val(i) = mean([edges(idx_max_signallength) edges(idx_max_signallength+1)]);
lowest_signallength_val(i) = edges(idx_min_signallength+1);
end
obj.signal_properties.mean_signallength_fs = floor(mean(mean_signallength_val)); %we will mostly use mean, because assumtion is, that stimuli are large part of signal and contribute mostly to mean
obj.signal_properties.lowest_signallength_fs = floor(mean(lowest_signallength_val));
obj.guess_siglength_stim = round(mean([obj.signal_properties.mean_signallength_fs obj.signal_properties.lowest_signallength_fs])); %mean siglength is mix of stim & atria & noise, min is probably minimal stim, take mean of the two as guess
obj.threshold.max_deviation_S1_block_guess = 2*obj.signal_properties.mean_signallength_fs;
obj.signal.activseg = [obj.signal.activseg activseg'];
obj.signal.channel_peaks_fs = [obj.signal.channel_peaks_fs channel_peaks_fs];
end
function getBezierinfo(obj,k)
allcath = fieldnames(obj.signal.bi_split_prefilt);
fieldidofstim = strcmp(obj.stimchan.cath,allcath);
stimcathname = (allcath(fieldidofstim));
obj.signal.bi_stimchan = obj.signal.bi_split_prefilt.(stimcathname{1});
obj.signal.bi_stimchan = obj.signal.bi_split_prefilt.(stimcathname{1});
%Bezier changes method
stepfcn = zeros(size(obj.signal.bi_stimchan,1),obj.stimchan.size_chan);
for i=1:obj.stimchan.size_chan
changes = findchangepts(obj.signal.bi_stimchan(:,i),'Statistic','linear','MinThreshold',0.6);
diff_changes = diff(changes);
threshold_ms = 10;
short_ids = find(diff_changes<threshold_ms*1000/obj.samplerate);
for ii=1:numel(diff_changes)
if diff_changes(ii)<threshold_ms*1000/obj.samplerate
stepfcn(changes(ii):changes(ii+1),i) = 1;
else
end
end
end
[~,activseg] = getActiveSegmentsFromNLEOInShortWindow(stepfcn,obj.samplerate,0.1); %chose k higher for less peaks here
for i=1:obj.stimchan.size_chan
[channel_peaks_fs{i},~] = getpeaksfromActiveSegmentsNLEO(nleo(obj.signal.bi_stimchan(:,1),obj.samplerate,1,k),activseg{i},obj.samplerate); %active segment peaks to calc distances later
%get most common signallength
tmp = diff(activseg{i},1,2); %difference between start and endpoint of active segemnts gives length
[N,edges] = histcounts(tmp(tmp~=0));
[~,idx_max_signallength] = max(N); %max of histogramm
[~,idx_min_signallength] = min(N);
mean_signallength_val(i) = mean([edges(idx_max_signallength) edges(idx_max_signallength+1)]);
lowest_signallength_val(i) = edges(idx_min_signallength+1);
end
obj.signal_properties.mean_signallength_fs = floor(mean(mean_signallength_val)); %we will mostly use mean, because assumtion is, that stimuli are large part of signal and contribute mostly to mean
obj.signal_properties.lowest_signallength_fs = floor(mean(lowest_signallength_val));
obj.guess_siglength_stim = round(mean([obj.signal_properties.mean_signallength_fs obj.signal_properties.lowest_signallength_fs])); %mean siglength is mix of stim & atria & noise, min is probably minimal stim, take mean of the two as guess
obj.threshold.max_deviation_S1_block_guess = 2*obj.signal_properties.mean_signallength_fs;
obj.signal.activseg = [obj.signal.activseg activseg'];
obj.signal.channel_peaks_fs = [obj.signal.channel_peaks_fs channel_peaks_fs];
end
function getnleoinfo(obj,k)
%Uses nleo on all signals, thresholding that dependant on the standard deviation given by k
%gets a step function and that gives active segments dependant on
%From there a guess of stimlength in samples is produced and a threshold by how many
%samples the S1 guess is allowed to differ from the inputtet
%value.
allcath = fieldnames(obj.signal.bi_split_prefilt);
fieldidofstim = strcmp(obj.stimchan.cath,allcath);
stimcathname = (allcath(fieldidofstim));
obj.signal.bi_stimchan = obj.signal.bi_split_prefilt.(stimcathname{1});
clearvars stimcathname fieldidofstim allcath
sig = obj.signal.bi_stimchan;
obj.signal.bi_nleo = nleo(sig,obj.samplerate,1,k); %k is completly useless here
[~,activseg] = getActiveSegmentsFromNLEOInShortWindow(obj.signal.bi_nleo,obj.samplerate,k); %chose k higher for less peaks here
chan_id = find(size(activseg)==obj.stimchan.size_chan);
if chan_id == 1 %columns should always be channels
activseg = activseg';
end
for i=1:obj.stimchan.size_chan
[channel_peaks_fs{i},~] = getpeaksfromActiveSegmentsNLEO(obj.signal.bi_nleo(:,i),activseg{i},obj.samplerate); %active segment peaks to calc distances later
%get most common signallength
tmp = diff(activseg{i},1,2); %difference between start and endpoint of active segemnts gives length
[N,edges] = histcounts(tmp(tmp~=0));
[~,idx_max_signallength] = max(N); %max of histogramm
[~,idx_min_signallength] = min(N);
mean_signallength_val(i) = mean([edges(idx_max_signallength) edges(idx_max_signallength+1)]);
%highest_signallength_val(i) = edges(idx_max_signallength+1); %+1 because we want lower edge of next bin to be sure to get the signals in those max bins as well
lowest_signallength_val(i) = edges(idx_min_signallength+1);
end
obj.signal_properties.mean_signallength_fs = floor(mean(mean_signallength_val)); %we will mostly use mean, because assumtion is, that stimuli are large part of signal and contribute mostly to mean
obj.signal_properties.lowest_signallength_fs = floor(mean(lowest_signallength_val));
obj.guess_siglength_stim = round(mean([obj.signal_properties.mean_signallength_fs obj.signal_properties.lowest_signallength_fs])); %mean siglength is mix of stim & atria & noise, min is probably minimal stim, take mean of the two as guess
obj.threshold.max_deviation_S1_block_guess = 2*obj.signal_properties.mean_signallength_fs;
obj.signal.activseg = [obj.signal.activseg activseg];
obj.signal.channel_peaks_fs = [obj.signal.channel_peaks_fs channel_peaks_fs];
end
function createthreshold_pre_dist(obj)
%change weighting scheme according to number of channels
num_of_chan = size(obj.signal.bi_stimchan,2);
%at least 50% of all nonstim chan haf to be hit and stimchan
%must have peak!
obj.threshold.pre_dist = (floor(0.5*(num_of_chan-1))*obj.weight.detected_in_chan+obj.weight.detected_in_stim_chan)+(floor(0.5*((num_of_chan-1)))*obj.weight.hp_detected_in_chan+obj.weight.hp_detected_in_stim_chan); %2 because we use NLEO & LP Filter, +weight.dist/2 because we want to be above that value but not include the distance weighted probably S1 peaks
end
function createthreshold_dist(obj)
%change weighting scheme according to number of channels
num_of_chan = size(obj.signal.bi_stimchan,2);
%at least 50% of all nonstim chan haf to be hit and stimchan
%must have peak!
obj.threshold.dist = (floor(0.5*(num_of_chan-1))*obj.weight.detected_in_chan...
+obj.weight.detected_in_stim_chan)+(floor(0.5*((num_of_chan-1)))*obj.weight.hp_detected_in_chan+obj.weight.hp_detected_in_stim_chan)...
+obj.weight.diff...
+obj.weight.amp-1; %2 because we use NLEO & LP Filter, +weight.dist/2 because we want to be above that value but not include the distance weighted probably S1 peaks
% +obj.weight.dist...
end
function clearunneededvars(obj)
obj.signal.work=[];
obj.signal.bi=[];
%obj.signal.bi_split=[];
obj.leads.bi=[];
end
function createtimeline(obj)
%Creates a timeline class wich is basically a cell array
%it is initiallised with the segments found in the sttimulation
%channel
timeline_all = timeline(); %initialises peaks fromm stimchan
weightvector = [obj.weight.detected_in_stim_chan,obj.weight.detected_in_chan,obj.weight.hp_detected_in_stim_chan,obj.weight.hp_detected_in_chan,obj.weight.dist];
thresholdvector = [obj.threshold.deviation_S1_guess];
timeline_all.initialize_weights(weightvector); %as of now weights are given as ids referring to this array
timeline_all.initialize_thresholds(thresholdvector);
timeline_all.initialize_stimchanid(obj.stimchan.idpostsplit);
for i=1:obj.stimchan.size_chan
if i == obj.stimchan.idpostsplit
timeline_all.addsegments(obj.signal.activseg{i}(:,1),obj.signal.activseg{i}(:,2),obj.signal.channel_peaks_fs{i},1,i,'NLEO');
else
timeline_all.addsegments(obj.signal.activseg{i}(:,1),obj.signal.activseg{i}(:,2),obj.signal.channel_peaks_fs{i},2,i,'NLEO')
end
end
timeline_all.createsegmentids();
timeline_all.createsupersegments(); % 2 is weightid for detection in another channel, second is threshold id
timeline_all.createsupersegmentids();
timeline_all.updateweight();
obj.timeline = timeline_all();
end
function crosscorrall(obj)
%crosscorrelating all supersegments with each other in
%within stimulation channel
obj.timeline.numofsupersegments;
cnt_g = 0;
similarlist = cell(0);
fi_cel=[];
fj_cel=[];
for i=1:obj.timeline.numofsupersegments
sig_o{i} = obj.signal.bi_stimchan((obj.timeline.supersegments{i,1}.min_fs:obj.timeline.supersegments{i,1}.max_fs));
for j=i+1:obj.timeline.numofsupersegments
l = obj.timeline.supersegments{i,1}.max_fs-obj.timeline.supersegments{i,1}.min_fs;
new_id_val = (obj.timeline.supersegments{j,1}.min_fs:obj.timeline.supersegments{j,1}.min_fs+l);
corc = corrcoef(obj.signal.bi_stimchan((obj.timeline.supersegments{i,1}.min_fs:obj.timeline.supersegments{i,1}.max_fs),obj.stimchan.idpostsplit),obj.signal.bi_stimchan(new_id_val,obj.stimchan.idpostsplit));
xc_d(i,j) = corc(1,2);
end
end
[t_r,t_c] = ind2sub(size(xc_d),find(xc_d>0.9));
t = [t_r t_c];
for ic = 1:obj.timeline.numofsupersegments
[r,c] = ind2sub(size(t),find(t==ic));
g{ic} = unique(t(r,:));
end
cnt_g = 1;
while 1
for ic = 1:size(g,2)
logicid(ic) = sum(ismember(g{cnt_g},g{ic}))>0;
end
cnt_g = cnt_g+1;
end
for ic = 1:obj.timeline.numofsupersegments
[r,c] = ind2sub(size(t),find(t==ic));
g = unique(t(r,:));
if isempty(g)
%nogroup{} = g;
else
if isempty(similarlist)
similarlist{1} = g;
else
for icel = 1:size(similarlist,1)
fi_cel(icel) = sum(ismember(g,similarlist{icel}))>0;
end
if sum(fi_cel)>1
ids = find(fi_cel==1);
comb_g = [];
for kk = 1:numel(ids)
comb_g = [comb_g; similarlist{ids(kk)}];
end
comb_g = unique(comb_g);
for kk = 1:numel(ids)
similarlist{ids(kk)} = [];
end
similarlist{end+1} = unique([comb_g;g]);
elseif sum(fi_cel)==1 %hit detected, add to group
similarlist{find(fi_cel==1)} = unique([similarlist{find(fi_cel==1)}; g]);
cnt_g =cnt_g+1;
fprintf('%d\n',cnt_g)
else %create new group
similarlist{end+1,1} = g;
end
end
end
end
end
function high_lp_filt_weighting(obj,k)
a = ECG_High_Filter(obj.signal.bi_stimchan,obj.samplerate,obj.init.highhp);
a2 = nleo(a,obj.samplerate,1,k);
[a2obj.signal,a2obj.activseg] = getActiveSegmentsFromNLEOInShortWindow(a2,obj.samplerate,k);
for i=1:size(a2obj.signal,2)
[highfrequ_peaks_fs{i},~] = getpeaksfromActiveSegmentsNLEO(a2,a2obj.activseg{i},obj.samplerate); %active segment peaks to calc distances later
end
for i=1:max(size(highfrequ_peaks_fs)) %channels
%cnt_j = 0;
if i==obj.stimchan.idpostsplit %stimchan
cnt_j=0;
for j=1:max(size(highfrequ_peaks_fs{i}))
%fprintf('i=%d,j=%d\n',i,j)
tmp = obj.timeline.checkifpeakfitsexistingsupersegment(highfrequ_peaks_fs{i}(j));
if isempty(tmp)
%superseg_ids{i}(cnt_j) = 0;
elseif sum(size(tmp))<2
fprintf('more than one segment hit\n');
else
cnt_j = cnt_j+1;
superseg_ids{i}(cnt_j) = tmp;
obj.timeline.addweight2supersegmentbyid(superseg_ids{i}(cnt_j),obj.weight.hp_detected_in_stim_chan)
end
end
else %otherchan
for j=1:max(size(highfrequ_peaks_fs{i}))
if isempty(highfrequ_peaks_fs{i})
tmp = [];
else
tmp = obj.timeline.checkifpeakfitsexistingsupersegment(highfrequ_peaks_fs{i}(j));
end
if isempty(tmp)
superseg_ids{i}(j)=NaN;
elseif sum(size(tmp))<2
fprintf('more than one segment hit\n');
else
%cnt_j = cnt_j+1;
superseg_ids{i}(j)=tmp;
end
%j=%d\n',i,j)
if ~isnan(superseg_ids{i}(j)) %only add weight for existing peaks
obj.timeline.addweight2supersegmentbyid(superseg_ids{i}(j),obj.weight.hp_detected_in_chan)
end
end
end
end
end
function getpeakdistancematrix(obj)
obj.timeline.update_numofsupersegments;
if ~isempty(obj.timeline.distance)
obj.timeline.distance = [];
end
cnt=0;
for i = 1:obj.timeline.numofsupersegments
for j = i+1:size(obj.timeline.supersegments,1)
cnt=cnt+1;
obj.timeline.distance(cnt,1) = i;
obj.timeline.distance(cnt,2) = j;
obj.timeline.distance(cnt,3) = abs(obj.timeline.supersegments{i}.peaks(1)-obj.timeline.supersegments{j}.peaks(1));
%using peaks, because for always same stimsignal NLEO
%peaks shouldnt differ to much -> better than using
%mean
end
end
end
function guessS1time(obj)
%use FFT to check if frequency < 300 has been filtered TODO
%FFT(obj.signal.bi_split.(obj.stimchan.cath),obj.samplerate)
obj.variables.k = obj.init.k - obj.init.step_k; %will be added in while loop again
itterations_S1_guess = 0;
obj.signal.channel_peaks_fs = [];
obj.signal.activseg = [];
while obj.init.S1_guess_good ~= true
obj.variables.k = obj.variables.k+obj.init.step_k;
obj.signal.channel_peaks_fs = [];
obj.signal.activseg = [];
%TODO allow for plot & manual change & check before running
%rest of script, since here width of segments is
%determined
if strcmpi(obj.variables.method_s1s2detect,'wavelet')
obj.getwaveletinfo(0.9); %use fixed value for now
elseif strcmpi(obj.variables.method_s1s2detect,'beziere')
obj.getBezierinfo(obj.variables.k);
else %standard is nleo
obj.getnleoinfo(obj.variables.k); %gets nleo of stimcatheter; higher k -> less peaks, because thresh = k*std(nleosig);
end
obj.clearunneededvars();
%try
obj.createtimeline(); %as of here supersegments get weighting
%obj.timeline.plotsupersegments(obj.signal.bi_stimchan(:,1),0)
obj.getpeakdistancematrix
for l = 1:obj.threshold.max_neighbour
logic_row_id = diff([obj.timeline.distance(:,1),obj.timeline.distance(:,2)],1,2)==l;
neighbour_dist_fs = obj.timeline.distance(logic_row_id,3);
%get maximum of histogramm to guess S1 distance
samplerate_round = round(obj.samplerate);
[N,edges] = histcounts(neighbour_dist_fs,samplerate_round);
%[N,edges] = histcounts(peaks_dist(peaks_dist~=0),2*obj.samplerate);
[val(l),idx] = max(N);
multiple_max_val = find(N==val(l));
if size(multiple_max_val,2) > 1
idx = multiple_max_val(end); %take last one as best guess
end
bin_cent(l) = mean([edges(idx) edges(idx+1)]);
%old code
%S1_guess(l,1) = bin_cent(l)/l;
end
%%
cnts1=0;
for ir=1:size(bin_cent,2)
for ic=ir+1:size(bin_cent,2)
[ismult(ir,ic),multfac(ir,ic)] = ismultiple(bin_cent(ir),bin_cent(ic),obj.threshold.deviation_S1_guess);
if ismult(ir,ic)==1
cnts1=cnts1+1;
S1_guess(cnts1) = max([bin_cent(ir),bin_cent(ic)]/multfac(ir,ic));
end
end
end
S1_check_sum = sum(ismult(:)); %subtr diagonal; always 1)
% for l = 1:length(bin_cent)
% remain(l,:) = mod(bin_cent,bin_cent(l));
% end
% for ir=1:size(remain,1)
% for ic=1:size(remain,2)
% if ic==ir
% remain(ir,ic) = nan;
% end
% end
% end
% figure
% histogram(remain,samplerate_round)
% %check 1: check neighbouring harmonics
% for i=1:obj.threshold.max_neighbour
% for j=1:obj.threshold.max_neighbour
% S1_check(i,j) = abs(S1_guess(i)-S1_guess(j));
% if i>j
% S1_check(i,j)=0;
% end
% end
% end
% S1_check2 = S1_check(S1_check~=0);
% S1_check_sum = S1_check2<=obj.threshold.deviation_S1_guess;%/100*mean(S1_guess);
%check 2: check mean stimlength:
if obj.timeline.getmediansiglength - obj.threshold.stimuluslength_fs <= obj.threshold.stimuluslength_fs_deviation
fprintf('mean stimulussignallength: %f ms',obj.timeline.getmeansiglength/obj.samplerate*1000)
obj.init.S1_guess_good=true;
S1_guess_final_exact_fs = obj.timeline.getmediansiglength;
end
if sum(S1_check_sum)>floor(obj.threshold.max_neighbour/2) %2 because we use 50% as right detection
%old code
%[id1 id2] = ind2sub([obj.threshold.max_neighbour obj.threshold.max_neighbour],find(min(S1_check2)==S1_check)); %get the two ids closest together
%S1_guess_final_exact_fs = S1_guess(id1(1)); %for now just take any found value
[v,c]=kmeans([1:length(S1_guess); S1_guess]',2);
most_common = mode(v);
%S1_guess_final_exact_fs = c(most_common,2);
S1_guess_final_exact_fs = S1_guess(find(v==most_common,1,'first'));
obj.init.S1_guess_good=true;
fprintf('S1 guess found: %f ms.\n',S1_guess_final_exact_fs/obj.samplerate*1000)%S1_guess_final_exact_fs/obj.samplerate
obj.S1_time = S1_guess_final_exact_fs;
else
obj.init.S1_guess_good=false;
itterations_S1_guess = itterations_S1_guess + 1;
fprintf('Trying new itteration of weighting.\n')
%will jump to beginning of while loop and increase k, allowing less
%peaks and hopefully reducing the error
end
if itterations_S1_guess == obj.threshold.max_itterations_S1_guess
fprintf('No good S1 guess could be obtained.\n')
return
end
%catch
%end
end %Trying to guess S1 while loop
%refining S1_variance threshold if new estimate is smaller
if 0.05*obj.S1_time < obj.threshold.deviation_S1_guess %TODO change this later by itterating through finer binning
obj.threshold.deviation_S1_guess = 0.05*obj.S1_time;
end
%obj.timeline.plotsupersegmentweights(obj.signal.bi_stimchan)
%compare against notated values
if ~isempty(obj.classcheck)
fprintf('Expected S1 is %d ms. \n',obj.classcheck.s1time)
variance_S1_time =round(abs(S1_guess_final_exact_fs/obj.samplerate*1000-obj.classcheck.s1time));
if variance_S1_time > 25 %25 is just a guess, set threshold however you deem fit
fprintf('Difference in S1 is %d ms. This value will be set manually to %d .\n',variance_S1_time,obj.classcheck.s1time)
fprintf('This could indicate bad signal quality. \n')
obj.S1_time = obj.classcheck.s1time/1000*obj.samplerate;
end
end
% %===PLOT for paper===
% f_temp = figure;
% histogram(obj.timeline.distance(:,3),samplerate_round);
% xlim([0 5000]);
% ylim([0 100])
% save_name = 'f_hist_noise';
% savefig(f_temp,['Pics/' save_name '.fig'])
% print(f_temp,['Pics/' save_name],'-dpng','-r400')
%
end
function getpointsinbetweenblocks(obj)