File size: 65,079 Bytes
8da08ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language"
"Biosensors","Cassey2016/PPG_Peak_Detection","main.m",".m","3040","58","% =========================================================================
% Below functions are the implementation for the comparison methods in
% paper:
% Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian, 
% Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson, 
% Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons, 
% David D. McManus, and Ki H. Chon. 2022. 
% ""A Real-Time PPG Peak Detection Method for Accurate Determination of 
% Heart Rate during Sinus Rhythm and Cardiac Arrhythmia"" 
% Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082 
%
% Please cite our paper if you used our implementation code. Thank you.
% Author: Dong Han (dong.han@uconn.edu), 01/31/2022.
% =========================================================================

% -------------------------------------------------------------------------
% Input: 
% PPG_raw_buffer: should be 30-sec segment.
% fs_PPG_raw: the sampling frequency of the PPG_raw_buffer.
% -------------------------------------------------------------------------
%% Preparation of PPG signal:
addpath('.\func')
[PPG_buffer,fs_PPG] = my_func_prep_PPG_buffer(PPG_raw_buffer,fs_PPG_raw);

%% Method 1: implemented method 1-a
V_max_flag = true; % true == upper peak detection.
addpath('.\method_01_and_02');
output_upper_Shin_2009 = my_peak_compare_Shin_2009(PPG_buffer,fs_PPG,V_max_flag); % Implementation of Shin 2009 paper.

%% Method 2: implemented method 1-b
V_max_flag = false; % false == lower peak detection.
output_lower_Shin_2009 = my_peak_compare_Shin_2009(PPG_buffer,fs_PPG,V_max_flag); % Implementation of Shin 2009 paper.

%% Method 3 & 4: implemented method 2, it has two output peaks in ""output_Elgendi_1_2013""
delta = 0.5; % it was 0.1 as mentioned in the paper. But I think 0.5 works better (0.5 is in the billauer's website).
addpath('.\method_03_and_04');
[output_Elgendi_1_2013] = my_Elgendi_2013_method_I_peakdet(PPG_buffer, delta, fs_PPG);

%% Method 5: first derivative and adaptive thresholding method in Li et al. [4] and Elgendi's paper [3]
abpsig = resample(PPG_buffer,fs_abpsig,fs_PPG_buffer); % upsampling it to 125 Hz.
addpath('.\method_05');
[output_Elgendi_2_2013] = my_func_ppg_peakdet_method_05_Elgendi_2013_method_II(abpsig,fs_abpsig);

%% Method 6: implemented method 4
fs_abp = 250; % Hz.
abp = resample(PPG_buffer,fs_abp,fs_PPG); % upsampling it to 125 Hz.
addpath('.\method_06');
[output_Elgendi_3_2013] = my_Elgendi_2013_method_III_peakdet(abp,fs_abp);
            
%% Method 7: event-related moving averages with dynamic threshold method in Elgendi et al.'s paper [3] 
addpath('.\method_07');
[output_Elgendi_4_2013] = my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV(-PPG_raw_buffer,fs_PPG_raw);

%% Method 8 & 9: peak detection on Stationary Wavelet Transform of PPG signal
fs_swt = 125; % Hz.
PPG_swt = resample(PPG_buffer,fs_swt,fs_PPG); % upsampling it to 125 Hz.
addpath('.\method_08_and_09');
[output_Vadrevu_1_2019,output_Vadrevu_2_2019] = my_Vadrevu_2019_peakdet(PPG_swt,fs_swt);","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","method_07/my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV.m",".m","6505","156","function output_Elgendi_4_2013 = my_func_ppg_peakdet_method_07_Elgendi_2013_method_IV(raw_PPG,fs_PPG)
% =========================================================================
% This is my implementation of the method IV in this paper:
% Elgendi, Mohamed, et al. 
% ""Systolic peak detection in acceleration photoplethysmograms measured from 
% emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585.
%
% Implemented by Dong Han on 03/02/2020.
%
% Please cite our paper if you used this code:
% Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian, 
% Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson, 
% Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons, 
% David D. McManus, and Ki H. Chon. 2022. 
% ""A Real-Time PPG Peak Detection Method for Accurate Determination of 
% Heart Rate during Sinus Rhythm and Cardiac Arrhythmia"" 
% Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082 
%
% Please cite our paper if you used our code. Thank you.
% =========================================================================
%% pre-processing - bandpass filtering
    [b, a] = butter(2,[0.5 8]/(fs_PPG/2)); % 2nd order bandpass filter 0.5-8Hz;
    filtered_PPG = filtfilt(b, a, raw_PPG); % zero-phase filter.
    filtered_PPG = filtered_PPG ./ std(filtered_PPG); % normalizing data is very important for my peak detection.
    filtered_PPG = filtered_PPG - mean(filtered_PPG);
    
    debugging_plot_flag = false; % only for plotting debugging figures. 
    
    % clip the signal by keeping the signal above zero.
    % I do not want to do this, so i will move all signal above zero.
    S_n = filtered_PPG;
% ---- Not following the paper to clip signal but move all signal above zero:
%     if min(S_n) < 0
%         Z_n = S_n - min(S_n); % elevate signal above zero.
%     else
%         % the minimum of S_n is still above zero, so do nothing.
%         Z_n = S_n;
%     end
% ---- Following the paper: only keep the positive value:
    Z_n = S_n;
    Z_n(Z_n < 0) = 0; 
%% pre-processing - squaring
    y_n = (Z_n).^2; % element-wise power.
%% feature extraction - generating potential blocks using two moving averages
    W_1 = round(0.111 * fs_PPG); % mentioned as the paper by brute-force search.
    % first moving average:
%     MA_peak = y_n; % for the beginning and ending signal, use the original signal.
%     for nn = 1+round(W_1/2):length(raw_PPG)-round(W_1/2)
%         temp_range = (nn-round(W_1/2)):(nn+round(W_1/2));
%         MA_peak(nn) = sum(y_n(temp_range))/W_1;
%     end
    MA_peak = movmean(y_n,W_1);
    
    % second moving average: 
    W_2 = round(0.667 * fs_PPG);
%     MA_beat = y_n;
%     for nn = 1+round(W_2/2):length(raw_PPG)-round(W_2/2)
%         temp_range = (nn-round(W_2/2)):(nn+round(W_2/2));
%         MA_beat(nn) = sum(y_n(temp_range))/W_2;
%     end
    MA_beat = movmean(y_n,W_2);
%% classification - thresholding
    beta = 0.02; % from the paper, by brute force search.
    z_bar = mean(y_n);
    alpha = beta * z_bar; % offset level.
    THR_1 = MA_beat + alpha;

    Blocks_Of_Interest = zeros(size(MA_peak)); % I initial it as zero.
    for nn = 1:length(MA_peak)
        if MA_peak(nn) > THR_1(nn) % I think it is THR_1(nn).
            Blocks_Of_Interest(nn) = 0.1;
        else
            % since I inital block of interest as zero, so I do not need to
            % assign zero again.
        end
    end
    
    % searh for onset and offset of each block.
    count_blocks = 0;
    block_onset = NaN(size(MA_peak));
    block_offset = NaN(size(MA_peak));
    if any(Blocks_Of_Interest > 0) % there is a block exist.
        for nn = 1:length(MA_peak)
            if nn == 1 && Blocks_Of_Interest(nn) > 0
               % the first point is a block;
               count_blocks = count_blocks + 1; % since the block start from zero, I have to add the counter first.
               block_onset(count_blocks,1) = nn;
            elseif nn == length(MA_peak) && Blocks_Of_Interest(nn) > 0
                % end with a block:
                % no need to add count_blocks;
                block_offset(count_blocks,1) = nn;
            else
                if nn > 1
                    if Blocks_Of_Interest(nn-1) == 0 && Blocks_Of_Interest(nn) > 0 % a jump means a new block.
                        count_blocks = count_blocks + 1;
                        block_onset(count_blocks,1) = nn;
                    elseif Blocks_Of_Interest(nn-1) > 0 && Blocks_Of_Interest(nn) == 0 % a drop means the end of previous block.
                        block_offset(count_blocks,1) = nn;
                    end
                end
            end
        end
    else
        % there is no block existed. Check why.
%        keyboard;
       HR_Elgendi_4_2013 = 0; % there is no peak location.
        S_peaks = 1;
    output_Elgendi_4_2013 = struct('filtered_PPG_Elgendi_4_2013',S_n,...
        'PPG_peak_loc_Elgendi_4_2013',S_peaks,...
        'HR_Elgendi_4_2013',HR_Elgendi_4_2013);
    return
    end
    
    block_onset(isnan(block_onset)) = []; % remove extra elements.
    block_offset(isnan(block_offset)) = []; % remove extra elements.
    if size(block_onset,1) ~= size(block_offset,1)
        % not same number of onset and offset, check here.
        keyboard;
    end
    
    if size(block_onset,1) ~= count_blocks
        keyboard;
    end
    S_peaks = NaN(count_blocks,1);
    THR_2 = W_1;
    
    for jj = 1:count_blocks
        block_idx = [block_onset(jj,1):block_offset(jj,1)];
        [~,I] = max(y_n(block_idx));
        S_peaks(jj,1) = block_onset(jj,1) + I - 1;
    end
    
    if debugging_plot_flag
        figure;
        plot(filtered_PPG);hold on;
        plot(S_peaks,y_n(S_peaks),'r.','markersize',10);
        plot(y_n);
        plot(MA_peak,'k:');
        plot(MA_beat,'r--');
        plot(THR_1,'g.-');
        plot(Blocks_Of_Interest*max(y_n)*10,'color',[0.5,0.5,0.5]); % grey color. I want to make block more obvious.
        
        legend('filtered PPG','peaks', 'squared PPG with clip to zero', 'MA peak', 'MA beat','THR 1', 'Blocks of Interest');
    end
    
    if isempty(S_peaks)
        HR_Elgendi_4_2013 = 0; % there is no peak location.
        S_peaks = 1;
    else
        HR_Elgendi_4_2013 = 60 * fs_PPG ./ diff(S_peaks); % calculate the HR.
    end
    
    output_Elgendi_4_2013 = struct('filtered_PPG_Elgendi_4_2013',S_n,...
        'PPG_peak_loc_Elgendi_4_2013',S_peaks,...
        'HR_Elgendi_4_2013',HR_Elgendi_4_2013);
end","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","method_01_and_02/my_peak_compare_Shin_2009.m",".m","21523","388","function [output_Shin_2009] = my_peak_compare_Shin_2009(raw_PPG,fs_PPG,V_max_flag)
% =========================================================================
% This function is the implementation of this paper:
% Shin, Hang Sik, Chungkeun Lee, and Myoungho Lee. 
% ""Adaptive threshold method for the peak detection of 
% photoplethysmographic waveform."" 
% Computers in biology and medicine 
% 39.12 (2009): 1145-1152.
% 
% Implemented by: Dong Han, on 02/10/2020.
%
% Please cite our paper if you used this code:
% Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian, 
% Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson, 
% Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons, 
% David D. McManus, and Ki H. Chon. 2022. 
% ""A Real-Time PPG Peak Detection Method for Accurate Determination of 
% Heart Rate during Sinus Rhythm and Cardiac Arrhythmia"" 
% Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082 
%
% Please cite our paper if you used our code. Thank you.
% =========================================================================
    debugging_plot_flag = false; % debugging plot. Can be false if don't want to plot anything.
%% Section 2.4 PPG frequency analysis and filtering.

    % (1): high pass >= 0.5 Hz.
    [b, a] = butter(6,[0.5 20]/(fs_PPG/2)); % bandpass filter 0.5-10Hz, changed from 0.5-20 to 0.5-9 Hz at 11/21/2018
    raw_PPG = filtfilt(b, a, raw_PPG); % -> AC component
    raw_PPG = raw_PPG ./ std(raw_PPG); % normalizing data is very important for my peak detection.
    raw_PPG = raw_PPG - mean(raw_PPG);
%% Section 2.5 & 2.6 Peak detection algorithm & Adaptive threshold detection

    % (1): bandpass filtering, no moving average filter or wavelet
    % decomposition.
    filtered_PPG = raw_PPG;
    Fs = fs_PPG;

    % % ===== interpolation to 1kHz of PPG: =====
    % x = 1:length(filtered_PPG);
    % v = filtered_PPG;
    % 
    % upsample_Fs = 250;
    % xq = 1:Fs/upsample_Fs:length(filtered_PPG);
    % vq1 = interp1(x,v,xq);
    % 
    % filtered_PPG = vq1;
    % Fs = upsample_Fs; % upsampled to 1000 Hz.

    % figure
    % plot(x,v,'o',xq,vq1,':.');
    % xlim([0 max(xq)]);
    % title('(Default) Linear Interpolation');

    % (2): V_max
    % slope_k: k-th slope amplitude;
    % s_r: slope changing rate (empirically: V_max = -0.6);
    % V_n_1: previous peak amplitude;
    % std_PPG: standard deviation of entire PPG signal;
    % Fs: sampling frequency.

    filtered_PPG = filtered_PPG(:);
    slope_k = NaN(size(filtered_PPG)); % should be a column vector.
    peak_loc = NaN(size(filtered_PPG)); % the array to store PPG peak index.
    pk_idx = 1; % the counter of peaks.
    %% Section 2.7: Peak Correction
    refractory_period = 0.6 * Fs; % sec * sampling frequency, initial refractory period is 0.6 sec.

    temp_win_left = round(0.15 * Fs); % sec * sampling frequency. This is the search region for local minima or maxima detection. chose 0.15 sec because 0.3 sec == 200 BPM.
    temp_win_right = round(0.15 * Fs);


    if V_max_flag % doing upper peak detection.
        s_r = -0.6; 
    else
        s_r = 0.6;%0.6; % not positive because my signal is zero mean.
        % I need to make all bottom signal positive, so I am moving them up.
    %     move_filter_amp = min(filtered_PPG) * (-1);
    %     filtered_PPG = filtered_PPG + move_filter_amp + std(raw_PPG); % move the lowest value more than zero.
    end


    slope_meet_PPG_flag = false; % mark if the slope meet PPG.
    slope_lower_PPG_flag = false; % mark if slope is lower than PPG, once PPG amp is lower than slope, mark it back.
    prev_slope = NaN; % First, I want to test not decreasing with PPG amplitude.
    if debugging_plot_flag % debugging plot
       figure;
       plot(filtered_PPG);
       hold on;
    end
    for kk = 1:length(filtered_PPG)
        % this is for debugging:
        if kk == 2
            my_stop = 1;
        end
        if kk == 1 % initial the slope value
            if V_max_flag
                slope_k(1,1) = 0.2 * max(filtered_PPG);
                std_PPG = std(filtered_PPG);
            else
                slope_k(1,1) = 0.2 * min(filtered_PPG); % since my signal is zero mean, I start from the negative amp. % I added what I moved.
                std_PPG = -std(filtered_PPG);
            end
    %         std_PPG = std(filtered_PPG);
            V_n_1 = slope_k(1,1);
        else
            if slope_meet_PPG_flag % slope has met PPG before.
                slope_k(kk,1) = filtered_PPG(kk,1);
                if V_max_flag % upper peak detection.
                    if kk < 2 % in the second point of signal
                        turn_point_flag = (slope_k(kk,1) < slope_k(kk-1,1)); % we met local maximum.
                    else
                        turn_point_flag = (slope_k(kk,1) < slope_k(kk-1,1)) & (slope_k(kk - 1,1) > slope_k(kk-2,1)); % we met local maximum.
                    end
                else
                    if kk < 2 % in the second point of signal
                        turn_point_flag = (slope_k(kk,1) > slope_k(kk-1,1)); % we met local minimum.
                    else
                        turn_point_flag = (slope_k(kk,1) > slope_k(kk-1,1)) & (slope_k(kk - 1,1) < slope_k(kk-2,1)); % we met local minimum.
                    end
                end

                if turn_point_flag % there is a turning point.
                    if pk_idx > 1 % not the first peak
                        % check local maxima or minima:
                        if (kk - temp_win_left) < 1
                            temp_left = 1;
                        else
                            temp_left = kk - temp_win_left;
                        end

                        if (kk + temp_win_right) > length(filtered_PPG)
                            temp_right = length(filtered_PPG);
                        else
                            temp_right = kk + temp_win_right;
                        end
                        temp_win = temp_left:temp_right;
                        local_m_check = filtered_PPG(temp_win);
                        if V_max_flag
                            temp_m_idx = find(local_m_check > slope_k(kk - 1,1)); % check if there is another maximum than detected, remember use k-1.
                        else
                            temp_m_idx = find(local_m_check < slope_k(kk - 1,1)); % check if there is another minimum than detected
                        end

                        if isempty(temp_m_idx) % there is no more max or min than this peak
                            if (kk - peak_loc(pk_idx-1,1) > refractory_period) % it is not the first peak, and the second peak is outside refractory period. It should be kk, because I have not assign the peak to the array.
                                peak_loc(pk_idx,1) = kk-1;
                                V_n_1 = filtered_PPG(peak_loc(pk_idx-1,1),1);% previous peak amplitude %slope_k(kk-1,1);
                                % update refractory period:
                                refractory_period = 0.6 * (kk - peak_loc(pk_idx-1,1)); % current index minus peak location. update the refractory peroid before updating the peak counting.
                                pk_idx = pk_idx + 1;

                                % reset slope meet flag:
                                slope_meet_PPG_flag = false;
                                slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs); 

                                % ---- for checking lower slope -------
                                temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs);
                                if V_max_flag
                                    if temp_slope_check > 0 % upper peaks should be decreasing with negative slope.
                                        temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
                                        slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
                                    end
                                else
                                    if temp_slope_check < 0 % upper peaks should be decreasing with negative slope.
                                        temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
                                        slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
                                    end
                                end
                                % -------------------------------------------
                                if V_max_flag
                                    temp_slope_below_PPG_flag = slope_k(kk,1) < filtered_PPG(kk,1); % upper peak detection, so slope below signal.
                                else
                                    temp_slope_below_PPG_flag = slope_k(kk,1) > filtered_PPG(kk,1); % lower peak detection, so slope above signal.
                                end
                                if temp_slope_below_PPG_flag % if slope is below PPG signal, we will reset slope value to PPG amplitude.
                                    slope_lower_PPG_flag = true; % slope is lower than PPG signal.
                                    prev_slope = slope_k(kk,1); % store the slope value now.
                                    slope_k(kk,1) = filtered_PPG(kk,1);
                                end
                                if debugging_plot_flag % debugging plot
                                    plot(kk,slope_k(kk,1),'r.');
                                end

                            else
                                if (kk - peak_loc(pk_idx-1,1) <= refractory_period) % it is because of the refractory period that cause the no peak. It should be kk, because I have not assign the peak to the array.                      
                                    slope_k(kk,1) = filtered_PPG(kk,1);% from the fig.3(c) in the paper, I see they are using the signal amplitude, not slope. 
                                    % no need to reset slope meet flag, waiting for
                                    % next turning point.
                                    if debugging_plot_flag % debugging plot
                                        plot(kk,slope_k(kk,1),'r.');
                                    end
                                end
                            end
                        else % there are more peaks higher then current kk peak.
                            if debugging_plot_flag % debugging plot
                                plot(kk,slope_k(kk,1),'r.');
                            end
                        end
                    else % the first peak, no need to check refractory period.
                                            % check local maxima or minima:
                        if (kk - temp_win_left) < 1
                            temp_left = 1;
                        else
                            temp_left = kk - temp_win_left;
                        end

                        if (kk + temp_win_right) > length(filtered_PPG)
                            temp_right = length(filtered_PPG);
                        else
                            temp_right = kk + temp_win_right;
                        end
                        temp_win = temp_left:temp_right;
                        local_m_check = filtered_PPG(temp_win);
                        if V_max_flag
                            temp_m_idx = find(local_m_check > slope_k(kk-1,1)); % check if there is another maximum than detected, always detect previous peak.
                        else
                            temp_m_idx = find(local_m_check < slope_k(kk-1,1)); % check if there is another minimum than detected
                        end

                        if isempty(temp_m_idx)
                            peak_loc(pk_idx,1) = kk-1;
                            if pk_idx > 1
                                V_n_1 = filtered_PPG(peak_loc(pk_idx-1,1),1);
                            else
                                V_n_1 = slope_k(kk-1,1);% previous peak amplitude %slope_k(kk-1,1);
                            end
                            pk_idx = pk_idx + 1;

                            % reset slope meet flag:
                            slope_meet_PPG_flag = false;
                            slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs); 
                            % ---- for checking lower slope -------
                            temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs);
                            if V_max_flag
                                if temp_slope_check > 0 % upper peaks should be decreasing with negative slope.
                                    temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
                                    slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
                                end
                            else
                                if temp_slope_check < 0 % upper peaks should be decreasing with negative slope.
                                    temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
                                    slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
                                end
                            end
                            % -------------------------------------------
                            if V_max_flag
                                temp_slope_below_PPG_flag = slope_k(kk,1) < filtered_PPG(kk,1); % upper peak detection, so slope below signal.
                            else
                                temp_slope_below_PPG_flag = slope_k(kk,1) > filtered_PPG(kk,1); % lower peak detection, so slope above signal.
                            end

                            if temp_slope_below_PPG_flag % if slope is below PPG signal, we will reset slope value to PPG amplitude.
                                slope_k(kk,1) = filtered_PPG(kk,1);
                            end
                                if debugging_plot_flag % debugging plot
                                    plot(kk,slope_k(kk,1),'r.');
                                end
                        else % there are more peaks higher then current kk peak.
                            if debugging_plot_flag % debugging plot
                                plot(kk,slope_k(kk,1),'r.');
                            end
                        end        
                        % no need to calculate refractory period, because there is only one peak, at least two peaks can give this correctly:
                    end
                else
                    % turning point did not meet, so keep decreasing or
                    % increasing the slope.
    %                 slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs); 
                    if debugging_plot_flag % debugging plot
                        plot(kk,slope_k(kk,1),'r.');
                    end
                end
            else % slope has not met PPG before. Keep decresing or increasing according to 'V_max_flag'.
    %             if slope_lower_PPG_flag % if there is a slope lower than PPG before:
    %                 slope_k(kk,1) = prev_slope;
    %             else
                    slope_k(kk,1) = slope_k(kk - 1,1) + s_r * ((V_n_1 + std_PPG) / Fs);
                            % ---- for checking lower slope -------
                            temp_slope_check = s_r * ((V_n_1 + std_PPG) / Fs);
                            if V_max_flag
                                if temp_slope_check > 0 % upper peaks should be decreasing with negative slope.
                                    temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
                                    slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
                                end
                            else
                                if temp_slope_check < 0 % upper peaks should be decreasing with negative slope.
                                    temp_slope_check = -s_r * ((V_n_1 + std_PPG) / Fs);%-temp_slope_check;
                                    slope_k(kk,1) = slope_k(kk - 1,1) + temp_slope_check;
                                end
                            end
                            % -------------------------------------------

    %             end
    %             if slope_k(kk,1) < filtered_PPG(kk,1) % if slope is below PPG signal, we will reset slope value to PPG amplitude.
    %                 slope_lower_PPG_flag = true; % slope is lower than PPG signal.
    %                 prev_slope = slope_k(kk,1); % store the slope value now.
    %                 slope_k(kk,1) = filtered_PPG(kk,1);
    %             elseif slope_k(kk,1) > filtered_PPG(kk,1) % slope is higher.
    %                 slope_lower_PPG_flag = false;
    %                 prev_slope = NaN; % reset the prev value.

    %             end

    %             if slope_lower_PPG_flag ~= 1 % if slope was not lower than PPG.
    %                 % -------------- Check if two lines will meet -----------------
    %                 PPG_x1 = kk - 1;
    %                 PPG_x2 = kk;
    %                 PPG_y1 = filtered_PPG(kk-1,1);
    %                 PPG_y2 = filtered_PPG(kk,1);
    %                 slope = s_r;
    %                 slope_y2 = slope_k(kk,1);
    %                 slope_y1 = slope_k(kk-1,1);
    %                 [meet_x] = my_slope_meet_PPG(PPG_x1,PPG_x2,PPG_y1,PPG_y2,slope,slope_y2,slope_y1);
    % 
    %                 slope_meet_PPG_flag = (ceil(meet_x) == kk);%(slope_k(kk,1) - filtered_PPG(kk,1)) < 0.1; % 0.3 is a testing value. %slope_k(kk,1) == filtered_PPG(kk,1) % slope meets the PPG signal.
    %             end
                if V_max_flag
                    slope_meet_PPG_flag = ((slope_k(kk,1) < filtered_PPG(kk,1)) & slope_k(kk - 1,1) > filtered_PPG(kk - 1,1));
                else
                    slope_meet_PPG_flag = ((slope_k(kk,1) > filtered_PPG(kk,1)) & slope_k(kk - 1,1) < filtered_PPG(kk - 1,1)); % lower peak use inverse amplitude.
                end
                % -------------------------------------------------------------
                % I found I cannot use equal, because the PPG sampling
                % frequency is not so high.
                if slope_meet_PPG_flag
                    slope_k(kk,1) = filtered_PPG(kk,1); % starts from the next index, slope == PPG amplitude.
                else
                    % don't need to do anything.
                    if slope_lower_PPG_flag ~= 1 % there was no slope lower than PPG before.
                        if V_max_flag
                            slope_lower_PPG_flag = ((slope_k(kk,1) < filtered_PPG(kk,1)) & slope_k(kk - 1,1) == filtered_PPG(kk - 1,1)); % beginning part has same amplitude, but the ending part slope is lower.
                        else
                            slope_lower_PPG_flag = ((slope_k(kk,1) > filtered_PPG(kk,1)) & slope_k(kk - 1,1) == filtered_PPG(kk - 1,1)); % lower peak use inverse amplitude.
                        end
                        if slope_lower_PPG_flag
                            prev_slope = slope_k(kk,1); % store the slope value now.
                            slope_k(kk,1) = filtered_PPG(kk,1); % starts from the next index, slope == PPG amplitude.
                        end
                    else % there was slope lower than PPG before.

                        if V_max_flag
                            temp_PPG_below_slope_flag = filtered_PPG(kk,1) < prev_slope; % upper peak detection, so PPG below slope.
                        else
                            temp_PPG_below_slope_flag = filtered_PPG(kk,1) > prev_slope; % lower peak detection, so PPG above slope.
                        end

                        if temp_PPG_below_slope_flag % PPG is lower than prev slope.
                            slope_k(kk,1) = prev_slope; % stop tracking PPG amp.
                            slope_lower_PPG_flag = false; % reset the lower PPG flag.
                            prev_slope = NaN;
                        else
                            slope_k(kk,1) = filtered_PPG(kk,1); % keep tracking PPG amp.
                        end
                    end
                end
                if debugging_plot_flag % debugging plot
                    plot(kk,slope_k(kk,1),'r.');
                end
            end
        end

    end
    % ================== IMPORTANT: clean up NaN value ========================
    peak_loc(isnan(peak_loc)) = []; % remove empty peak loc.
    if V_max_flag % doing upper peak detection.

    else
        % moving signal back.
    %     filtered_PPG = filtered_PPG - move_filter_amp - std(raw_PPG); % move the lowest value more than zero.
    %     slope_k = slope_k - move_filter_amp - std(raw_PPG); % move the slope as well.
    end

    if debugging_plot_flag % debugging plot
        plot(peak_loc,filtered_PPG(peak_loc),'ko');
    end

    if isempty(peak_loc)
        HR_Shin_2009 = 0; % there is no peak location.
        peak_loc = 1;
    else
        HR_Shin_2009 = 60 * Fs ./ diff(peak_loc); % calculate the HR.
    end

    output_Shin_2009 = struct('PPG_peak_loc_Shin_2009',peak_loc,...
        'slope_Shin_2009',slope_k,...
        'filtered_PPG_Shin_2009',filtered_PPG,...
        'HR_Shin_2009',HR_Shin_2009); 
end","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","method_05/my_func_ppg_peakdet_method_05_Elgendi_2013_method_II.m",".m","11993","412","function [output_Elgendi_2_2013] = my_func_ppg_peakdet_method_05_Elgendi_2013_method_II(raw_PPG,fs_PPG) 
% -------------------------------------------------------------------------
% This peak detection function was mentioned in this paper:
% Elgendi, Mohamed, et al. 
% ""Systolic peak detection in acceleration photoplethysmograms measured from 
% emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585.
% 
    [onsetp,peakp,dicron,abpsig] = delineator(raw_PPG,fs_PPG);
% -------------------------------------------------------------------------
    
    if isempty(peakp) % there is no peak detected:
        HR_Elgendi_2_2013 = 0; % there is no peak location.
        peakp = 1;
    else
        HR_Elgendi_2_2013 = 60 * fs_PPG ./ diff(peakp); % calculate the HR.
    end

    
    output_Elgendi_2_2013 = struct('PPG_peak_loc_Elgendi_2_2013',peakp,...
        'HR_Elgendi_2_2013',HR_Elgendi_2_2013,...
        'filtered_PPG_Elgendi_2_2013',abpsig);
end

function [onsetp,peakp,dicron,abpsig] = delineator(abpsig,abpfreq)
% Below was copied from Mathwords File Exchange ""Pulse Waveform Delineator"": 
% https://www.mathworks.com/matlabcentral/fileexchange/29484-pulse-waveform-delineator

% This program is intended to delineate the fiducial points of pulse waveforms
% Inputs:
%   abpsig: input as original pulse wave signals;
%   abpfreq: input as the sampling frequency;
% Outputs:
%   onsetp: output fiducial points as the beginning of each beat;
%   peakp: output fiducial points as systolic peaks;
%   dicron: output fiducial points as dicrotic notches;

% Its delineation is based on the self-adaptation in pulse waveforms, but
% not in the differentials.

% Reference:
%   BN Li, MC Dong & MI Vai (2010) 
%   On an automatic delineator for arterial blood pressure waveforms
%   Biomedical Signal Processing and Control 5(1) 76-81.

% LI Bing Nan @ University of Macau, Feb 2007
%   Revision 2.0.5, Apr 2009

%Initialization
peakIndex=0;
onsetIndex=0;
dicroIndex=0;
stepWin=2*abpfreq;
closeWin=floor(0.1*abpfreq);    %invalide for pulse beat > 200BPM

sigLen=length(abpsig);

peakp=[];
onsetp=[];
dicron=[];

%lowpass filter at first
coh=25;                     %cutoff frequency is 25Hz
coh=coh*2/abpfreq;
od=3;                       %3rd order bessel filter
[B,A]=besself(od,coh);
abpsig=filter(B,A,abpsig);
abpsig=10*abpsig;

abpsig=smooth(abpsig);

%Compute differentials
ttp=diff(abpsig);
diff1(2:sigLen)=ttp;
diff1(1)=diff1(2);
diff1=100*diff1;
clear ttp;
diff1=smooth(diff1);

if sigLen>12*abpfreq
    tk=10;
elseif sigLen>7*abpfreq
    tk=5;
elseif sigLen>4*abpfreq
    tk=2;
else
    tk=1;
end

%Seek avaerage threshold in original signal
if tk>1             %self-learning threshold with interval sampling
    tatom=floor(sigLen/(tk+2));
    for ji=1:tk       %search the slopes of abp waveforms
        sigIndex=ji*tatom;
        tempIndex=sigIndex+abpfreq;
        [tempMin,jk,tempMax,jl]=seeklocales(abpsig,sigIndex,tempIndex);
        tempTH(ji)=tempMax-tempMin;
    end
    abpMaxTH=mean(tempTH);
else
    [tempMin,jk,tempMax,jl]=seeklocales(abpsig,closeWin,sigLen);
    abpMaxTH=tempMax-tempMin;
end
clear j*;
clear t*;

abpMaxLT=0.4*abpMaxTH;

%Seek pulse beats by MinMax method
% diffIndex=1;
diffIndex=closeWin;             %Avoid filter distortion

while diffIndex<sigLen
    tempMin=abpsig(diffIndex);   %Initialization
    tempMax=abpsig(diffIndex);
    tempIndex=diffIndex;
    tpeakp=diffIndex;        %Avoid initial error
    tonsetp=diffIndex;      %Avoid initial error

    while tempIndex<sigLen
        %If no pulses within 2s, then adjust threshold and retry
        if (tempIndex-diffIndex)>stepWin
%             tempIndex=diffIndex-closeWin;
            tempIndex=diffIndex;
            abpMaxTH=0.6*abpMaxTH;
            if abpMaxTH<=abpMaxLT
                abpMaxTH=2.5*abpMaxLT;
            end
            break;
        end

        if (diff1(tempIndex-1)*diff1(tempIndex+1))<=0  %Candidate fiducial points
            if (tempIndex+5)<=sigLen
                jk=tempIndex+5;
            else
                jk=sigLen;
            end
            if (tempIndex-5)>=1
                jj=tempIndex-5;
            else
                jj=1;
            end

            %Artifacts of oversaturated or signal loss?
            if (jk-tempIndex)>=5
                for ttk=tempIndex:jk
                    if diff1(ttk)~=0
                        break;
                    end
                end
                if ttk==jk
                    break;          %Confirm artifacts
                end
            end

            if diff1(jj)<0          %Candidate onset
                if diff1(jk)>0
                    [tempMini,tmin,ta,tb]=seeklocales(abpsig,jj,jk);
                    if abs(tmin-tempIndex)<=2
                        tempMin=tempMini;
                        tonsetp=tmin;
                    end
                end
            elseif diff1(jj)>0      %Candidate peak
                if diff1(jk)<0
                    [tc,td,tempMaxi,tmax]=seeklocales(abpsig,jj,jk);
                    if abs(tmax-tempIndex)<=2
                        tempMax=tempMaxi;
                        tpeakp=tmax;
                    end
                end
            end

            if ((tempMax-tempMin)>0.4*abpMaxTH)   %evaluation
                if ((tempMax-tempMin)<2*abpMaxTH)
                    if tpeakp>tonsetp
                        %If more zero-crossing points, further refine!
                        ttempMin=abpsig(tonsetp);
                        ttonsetp=tonsetp;
                        for ttk=tpeakp:-1:(tonsetp+1)
                            if abpsig(ttk)<ttempMin
                                ttempMin=abpsig(ttk);
                                ttonsetp=ttk;
                            end
                        end
                        tempMin=ttempMin;
                        tonsetp=ttonsetp;
                            
                        if peakIndex>0
                            %If pulse period less than eyeclose, then artifact
                            if (tonsetp-peakp(peakIndex))<(3*closeWin)
                                %too many fiducial points, then reset
                                tempIndex=diffIndex;                                
                                abpMaxTH=2.5*abpMaxLT;
                                break;
                            end
                            
                            %If pulse period bigger than 2s, then artifact
                            if (tpeakp-peakp(peakIndex))>stepWin
                                peakIndex=peakIndex-1;
                                onsetIndex=onsetIndex-1;
                                if dicroIndex>0
                                    dicroIndex=dicroIndex-1;
                                end
                            end

                            if peakIndex>0
                                %new pulse beat
                                peakIndex=peakIndex+1;
                                peakp(peakIndex)=tpeakp;
                                onsetIndex=onsetIndex+1;
                                onsetp(onsetIndex)=tonsetp;

                                tf=onsetp(peakIndex)-onsetp(peakIndex-1);

                                to=floor(abpfreq./20);   %50ms
                                tff=floor(0.1*tf);
                                if tff<to
                                    to=tff;
                                end
                                to=peakp(peakIndex-1)+to;

                                te=floor(abpfreq./2);   %500ms
                                tff=floor(0.5*tf);
                                if tff<te
                                    te=tff;
                                end
                                te=peakp(peakIndex-1)+te;
                                % Dong added on 05/07/2020:
                                % For MIMIC III PACPVC 3_2, ii = 25.
                                if te > length(diff1)
                                    te = length(diff1);
                                end
                                tff=seekdicrotic(diff1(to:te));
                                if tff==0
                                    tff=te-peakp(peakIndex-1);
                                    tff=floor(tff/3);
                                end
                                dicroIndex=dicroIndex+1;
                                dicron(dicroIndex)=to+tff;

                                tempIndex=tempIndex+closeWin;
                                break;
                            end
                        end
                        
                        if  peakIndex==0   %new pulse beat
                            peakIndex=peakIndex+1;
                            peakp(peakIndex)=tpeakp;
                            onsetIndex=onsetIndex+1;
                            onsetp(onsetIndex)=tonsetp;

                            tempIndex=tempIndex+closeWin;
                            break;
                        end
                    end
                end
            end
        end

        tempIndex=tempIndex+1;      %step forward
    end

%     diffIndex=tempIndex+closeWin;    %for a new beat
    diffIndex=tempIndex+1;
end

if isempty(peakp),return;end
%Compensate the offsets of lowpass filter
sigLen=length(peakp);
for diffIndex=1:sigLen          %avoid edge effect
    tempp(diffIndex)=peakp(diffIndex)-od;
end
ttk=tempp(1);
if ttk<=0
    tempp(1)=1;
end 
clear peakp;
peakp=tempp;
clear tempp;

sigLen=length(onsetp);
for diffIndex=1:sigLen
    tempp(diffIndex)=onsetp(diffIndex)-od;
end
ttk=tempp(1);
if ttk<=0
    tempp(1)=1;
end 
clear onsetp;
onsetp=tempp;
clear tempp;

if isempty(dicron),return;end
sigLen=length(dicron);
for diffIndex=1:sigLen
    if dicron(diffIndex)~=0
        tempp(diffIndex)=dicron(diffIndex)-od;
    else
        tempp(diffIndex)=0;
    end
end
clear dicron;
dicron=tempp;
clear tempp;
end

function [mini,minip,maxi,maxip]=seeklocales(tempsig,tempbegin,tempend)
tempMin=tempsig(tempbegin);
tempMax=tempsig(tempbegin);
minip=tempbegin;
maxip=tempbegin;
for j=tempbegin:tempend
    if tempsig(j)>tempMax
        tempMax=tempsig(j);
        maxip=j;
    elseif tempsig(j)<tempMin
        tempMin=tempsig(j);
        minip=j;
    end
end

mini=tempMin;
maxi=tempMax;
end

function [dicron]=seekdicrotic(tempdiff)
izcMin=0;
izcMax=0;
itemp=3;
tempLen=length(tempdiff)-3;

dicron=0;

tempdiff=smooth(tempdiff);

while itemp<=tempLen
    if (tempdiff(itemp)*tempdiff(itemp+1))<=0
        if tempdiff(itemp-2)<0
            if tempdiff(itemp+2)>=0
                izcMin=izcMin+1;
                tzcMin(izcMin)=itemp;
            end
        end

%         if tempdiff(itemp-2)>0
%             if tempdiff(itemp+2)<=0
%                 izcMax=izcMax+1;
%                 tzcMax(izcMax)=itemp;
%             end
%         end
    end

    itemp=itemp+1;
end

if izcMin==0     %big inflection
    itemp=3;
    tempMin=tempdiff(itemp);
    itempMin=itemp;
    
    while itemp<tempLen
        if tempdiff(itemp)<tempMin
            tempMin=tempdiff(itemp);
            itempMin=itemp;
        end
        itemp=itemp+1;
    end

    itemp=itempMin+1;
    while itemp<tempLen
        if tempdiff(itemp+1)<=tempdiff(itemp-1)
            dicron=itemp;
            return;
        end
        itemp=itemp+1;
    end
elseif izcMin==1
    dicron=tzcMin(izcMin);
    return;
else
    itemp=tzcMin(1);
    tempMax=tempdiff(itemp);
    itempMax=itemp;
    
    while itemp<tempLen
        if tempdiff(itemp)>tempMax
            tempMax=tempdiff(itemp);
            itempMax=itemp;
        end
        itemp=itemp+1;
    end

    for itemp=izcMin:-1:1
        if tzcMin(itemp)<itempMax
            dicron=tzcMin(itemp);
            return;
        end
    end
end
end

function [diap]=seekdiap(tempabp)
diap=0;

[tt,ti]=max(tempabp);
if ti==0
    diap=floor(length(tempabp)./2);
else
    diap=ti;
end
end
","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","func/my_func_standardizing_PPG.m",".m","422","11","function PPG_buffer = my_func_standardizing_PPG(PPG_buffer)
% Standardizing PPG into zero-mean and uni-variance.
    var_sig_PPG = var(PPG_buffer);
    if var_sig_PPG == 0
        univar_sig_PPG = PPG_buffer;
    else
        univar_sig_PPG = sqrt(1/var_sig_PPG) * PPG_buffer;
    end
    zeromean_sig_PPG = univar_sig_PPG - mean(univar_sig_PPG);
    PPG_buffer = zeromean_sig_PPG; % univariance for PPG 30 sec segment
end","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","func/my_func_prep_PPG_buffer.m",".m","554","17","function [PPG_buffer,fs_PPG] = my_func_prep_PPG_buffer(PPG_raw_buffer,fs_PPG)
    % Resample PPG to 50 Hz.
    if fs_PPG ~= 50 % Hz
        PPG_down = resample(PPG_raw_buffer,50,fs_PPG);
        fs_PPG = 50;
    else
        PPG_down = PPG_raw_buffer;
    end

    PPG_buffer = PPG_down(:); % Make sure PPG is column vector
    % Standardizing PPG in sub-function.
    PPG_buffer = my_func_standardizing_PPG(PPG_buffer);

    % Filter signal.
    [b, a] = butter(6,[0.5 20]/(fs_PPG/2)); % Bandpass filter.
    PPG_buffer = filtfilt(b, a, PPG_buffer);
end","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","method_06/my_revise_run_wabp.m",".m","4330","109","function [r,ssf,my_avg0,A] = my_revise_run_wabp(abp,fs_abp)
% Below was copied from Erick Andres Perez Alday's Github repository 
% "" physionetchallenges / matlab-classifier-2020 "": 
% https://github.com/physionetchallenges/matlab-classifier-2020/blob/master/Tools/PhysioNet-Cardiovascular-Signal-Toolbox-master/Tools/BP_Tools/run_wabp.m
% WABP  ABP waveform onset detector.
%   r = run_wabp(abp) obtains the onset time (in samples) 
%       of each beat in the ABP waveform.
%
%   In:   ABP (125Hz sampled)
%   Out:  Onset sample time
% 
%   Usage:
%   - ABP waveform must have units of mmHg
%
%   Written by James Sun (xinsun@mit.edu) on Nov 19, 2005.  This ABP onset
%   detector is adapted from Dr. Wei Zong's wabp.c.
%
%   LICENSE:    
%       This software is offered freely and without warranty under 
%       the GNU (v3 or later) public license. See license file for
%       more information

% Dong changed: input should be 250 Hz for filtering.
%% Input checks
    % if nargin ~=1
    %     error('exactly 1 argment needed');
    % end

    if size(abp,2)~=1
        error('Input must be a <nx1> vector');
    end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    % scale physiologic ABP
    offset   = 1600;
    scale    = 20;
    Araw     = abp*scale-offset;

    % LPF
    A = filter([1 0 0 0 0 -2 0 0 0 0 1],[1 -2 1],Araw)/24+30;
    A = (A(4:end)+offset)/scale; % Takes care of 4 sample group delay

    % ------- Dong changed this: -------
    A = A ./ std(A); % normalizing data is very important for my peak detection.
    A = A - mean(A);

    % Slope-sum function
    dypos          = diff(A);
    dypos(dypos<0) = 0;
    % ssf            = [0; 0; conv(ones(16,1),dypos)];
    w = 16/125*fs_abp; % 125 Hz to 250 Hz.
    ssf            = [0; 0; conv(ones(w,1),dypos)];

    % Decision rule
    first_8sec = 8*fs_abp;
    % avg0       = sum(ssf(1:1000))/1000;   % average of 1st 8 seconds (1000 samples) of SSF
    avg0       = sum(ssf(1:first_8sec))/first_8sec;
    Threshold0 = 3*avg0;                  % initial decision threshold

    % ignoring ""learning period"" for now
    lockout    = 0;    % lockout >0 means we are in refractory
    timer      = 0;
    % z          = zeros(100000,1);
    z          = zeros(fs_abp*800,1);
    counter    = 0;

    % Dong: copied from wabp.c, 02/27/2020. % Dong change here. 02/27/2020.
    TmDEF = 0.25; %5;% Dong change here. 02/27/2020.
    max_min_thres = 0.1; %10;% Dong change here. 02/27/2020.
    my_avg0 = zeros(size(abp));% Dong change here. 02/27/2020.
    step_adjust_thres = 0.025; % it was 0.1 % Dong change here. 02/27/2020.
    % for t = 50:length(ssf)-17
    for t = round(0.4*fs_abp):length(ssf)-w-1
        lockout = lockout - 1;
        timer   = timer   + 1;      % Timer used for counting time after previous ABP pulse

        if (lockout<1) & (ssf(t)>avg0+TmDEF) %(ssf(t)>avg0+5)  % Not in refractory and SSF has exceeded threshold here % Dong change here. 02/27/2020.
            timer = 0;
            maxSSF = max(ssf(t:t+w));  % Find local max of SSF
            minSSF = min(ssf(t-w:t));  % Find local min of SSF
            if maxSSF > (minSSF + max_min_thres) %(minSSF + 10)% Dong change here. 02/27/2020.
                onset = 0.01*maxSSF ;  % Onset is at the time in which local SSF just exceeds 0.01*maxSSF

                tt       = t-w:t;
                dssf     = ssf(tt) - ssf(tt-1);
                BeatTime = find(dssf<onset,1,'last')+t-w-1;
                counter  = counter+1;

                if isempty(BeatTime)
                    counter = counter-1;
                else
                    z(counter) = BeatTime;
                end
                Threshold0 = Threshold0 + step_adjust_thres*(maxSSF - Threshold0);  % adjust threshold
                avg0 = Threshold0 / 3;        % adjust avg

                lockout = round(32/125*fs_abp);   % lock so prevent sensing right after detection (refractory period)
            end
        end

        if timer > round(312/125*fs_abp)  % Lower threshold if no pulse detection for a while
            Threshold0 = Threshold0 - 0.1; %Threshold0 - 1; % Dong change here. 02/27/2020.
            avg0       = Threshold0/3;
        end
        my_avg0(t,1) = avg0+TmDEF; % % Dong change here. 02/27/2020.
    end
    r = z(find(z))-2;
end","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","method_06/my_Elgendi_2013_method_III_peakdet.m",".m","1028","22","function [output_Elgendi_3_2013] = my_Elgendi_2013_method_III_peakdet(raw_PPG,fs_PPG)
% -------------------------------------------------------------------------
% This peak detection function was mentioned in this paper:
% Elgendi, Mohamed, et al. 
% ""Systolic peak detection in acceleration photoplethysmograms measured from 
% emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585.
% 
    [r,ssf,my_avg0,A] = my_revise_run_wabp(raw_PPG,fs_PPG);
% -------------------------------------------------------------------------
    if isempty(r)
        HR_Elgendi_3_2013 = 0; % there is no peak location.
        r = 1;
    else
        HR_Elgendi_3_2013 = 60 * fs_PPG ./ diff(r); % calculate the HR.
    end
    A = [A;0;0;0;]; % add zero
    A(1:6) = A(7); % first six plots are all high amplitude.
    output_Elgendi_3_2013 = struct('PPG_peak_loc_Elgendi_3_2013',r,...
        'HR_Elgendi_3_2013',HR_Elgendi_3_2013,...
        'filtered_PPG_Elgendi_3_2013',A,...
        'thres_Elgendi_3_2013',my_avg0);
end","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","method_03_and_04/my_Elgendi_2013_method_I_peakdet.m",".m","3762","111","function [output_Elgendi_1_2013] = my_Elgendi_2013_method_I_peakdet(raw_PPG, delta, fs_PPG)
% -------------------------------------------------------------------------
% Dong add this on 02/25/2020, based on this paper:
% Elgendi, Mohamed, et al. 
% ""Systolic peak detection in acceleration photoplethysmograms measured from 
% emergency responders in tropical conditions."" PLoS One 8.10 (2013): e76585.
% 
% (1): bandpass filter (0.5-8Hz)
    [b, a] = butter(6,[0.5 8]/(fs_PPG/2)); % bandpass filter 0.5-10Hz, changed from 0.5-20 to 0.5-9 Hz at 11/21/2018
    raw_PPG = filtfilt(b, a, raw_PPG); % -> AC component
    raw_PPG = raw_PPG ./ std(raw_PPG); % normalizing data is very important for my peak detection.
    raw_PPG = raw_PPG - mean(raw_PPG);
    
    debugging_plot_flag = false; % only for plotting debugging figures. 
% -------------------------------------------------------------------------
% Below code is copied from: http://billauer.co.il/peakdet.html
% PEAKDET Detect peaks in a vector
%        [MAXTAB, MINTAB] = PEAKDET(V, DELTA) finds the local
%        maxima and minima (""peaks"") in the vector V.
%        MAXTAB and MINTAB consists of two columns. Column 1
%        contains indices in V, and column 2 the found values.
%      
%        With [MAXTAB, MINTAB] = PEAKDET(V, DELTA, X) the indices
%        in MAXTAB and MINTAB are replaced with the corresponding
%        X-values.
%
%        A point is considered a maximum peak if it has the maximal
%        value, and was preceded (to the left) by a value lower by
%        DELTA.

% Eli Billauer, 3.4.05 (Explicitly not copyrighted).
% This function is released to the public domain; Any use is allowed.
    maxtab = [];
    mintab = [];

    raw_PPG = raw_PPG(:); % Just in case this wasn't a proper vector

    % if nargin < 3
      x = (1:length(raw_PPG))';
    % else 
    %   x = x(:);
    %   if length(raw_PPG)~= length(x)
    %     error('Input vectors v and x must have same length');
    %   end
    % end

    if (length(delta(:)))>1
      error('Input argument DELTA must be a scalar');
    end

    if delta <= 0
      error('Input argument DELTA must be positive');
    end

    mn = Inf; mx = -Inf;
    mnpos = NaN; mxpos = NaN;

    lookformax = 1;

    for i=1:length(raw_PPG)
      this = raw_PPG(i);
      if this > mx, mx = this; mxpos = x(i); end
      if this < mn, mn = this; mnpos = x(i); end

      if lookformax
        if this < mx-delta
          maxtab = [maxtab ; mxpos mx];
          mn = this; mnpos = x(i);
          lookformax = 0;
        end  
      else
        if this > mn+delta
          mintab = [mintab ; mnpos mn];
          mx = this; mxpos = x(i);
          lookformax = 1;
        end
      end
    end



    if isempty(maxtab)
        HR_Elgendi_1_max_2009 = 0; % there is no peak location.
        peak_loc_max = 1;
    else
        peak_loc_max = maxtab(:,1);
        HR_Elgendi_1_max_2009 = 60 * fs_PPG ./ diff(peak_loc_max); % calculate the HR.
    end

    if isempty(mintab)
        HR_Elgendi_1_min_2009 = 0; % there is no peak location.
        peak_loc_min = 1;
    else
        peak_loc_min = mintab(:,1);
        HR_Elgendi_1_min_2009 = 60 * fs_PPG ./ diff(peak_loc_min); % calculate the HR.
    end

    output_Elgendi_1_2013 = struct('filtered_PPG_Elgendi_1_2013',raw_PPG,...
        'PPG_peak_loc_Elgendi_1_max_2013',peak_loc_max,...
        'PPG_peak_loc_Elgendi_1_min_2013',peak_loc_min,...
        'HR_Elgendi_1_max_2013',HR_Elgendi_1_max_2009,...
        'HR_Elgendi_1_min_2013',HR_Elgendi_1_min_2009);


    if debugging_plot_flag % debugging plot
        figure;
        plot(x,raw_PPG);hold on;
        plot(peak_loc_max,raw_PPG(peak_loc_max),'ro');
        plot(peak_loc_min,raw_PPG(peak_loc_min),'go');
    end
end","MATLAB"
"Biosensors","Cassey2016/PPG_Peak_Detection","method_08_and_09/my_Vadrevu_2019_peakdet.m",".m","10598","329","function [output_Vadrevu_1_2019,output_Vadrevu_2_2019] = my_Vadrevu_2019_peakdet(PPG_buffer,fs_PPG)
% =========================================================================
% This is my implementation of this paper:
%
% Vadrevu, Simhadri, and M. Sabarimalai Manikandan. 
% ""A robust pulse onset and peak detection method for automated PPG signal 
% analysis system."" IEEE Transactions on Instrumentation and Measurement 
% 68.3 (2018): 807-817.
%
% Implemented by Dong Han on 05/03/2020.
%
% Please cite our paper if you used this code:
% Han, Dong, Syed K. Bashar, Jesús Lázaro, Fahimeh Mohagheghian, 
% Andrew Peitzsch, Nishat Nishita, Eric Ding, Emily L. Dickson, 
% Danielle DiMezza, Jessica Scott, Cody Whitcomb, Timothy P. Fitzgibbons, 
% David D. McManus, and Ki H. Chon. 2022. 
% ""A Real-Time PPG Peak Detection Method for Accurate Determination of 
% Heart Rate during Sinus Rhythm and Cardiac Arrhythmia"" 
% Biosensors 12, no. 2: 82. https://doi.org/10.3390/bios12020082 
%
% Please cite our paper if you used our code. Thank you.
% =========================================================================
    debug_flag = false; % decide to plot the paper figure or not.
    %% A. Stationary Wavelet Transform of PPG signal.

    % first, for the input length, you can know the maximum wavelet
    % decomposition level you can get:
    TYPE = '1D'; % extension method.
    MODE = 'zpd'; % zero extension.
    X = PPG_buffer;

    % based on your input signal length, you have to extend your input signal
    % to MATLAB suggested length.
    LEN = 45;%18; % 18 for fs_PPG 50, 45 for fs_PPG 125; for 30 sec input.
    YEXT = wextend(TYPE,MODE,X,LEN); % required by swt.
    sig = YEXT;
    % s = PPG_buffer;
    sLen = length(sig);
    wname = 'bior1.5';
    L = wmaxlev(sLen,wname);

    % [swa,swd] = swt(s,3,'bior1.5'); % the author mentioned wavelet biorthogonal 1.5 (bior1.5)
    [swa,swd] = swt(sig,L,wname); % the author mentioned wavelet biorthogonal 1.5 (bior1.5)
    s1 = swd(3,:) + swd(4,:); 
    s1 = s1(:); % make sure it is column vector.
    s2 = swd(5,:) + swd(6,:) + swd(7,:);
    s2 = s2(:); % make sure it is column vector.

    if debug_flag
        % if you want to debug the result.
        figure;
        t_plot = [1:length(sig)]'./fs_PPG; %
        subplot(5,1,1);
        plot(t_plot,sig);
        xlim([0 t_plot(end)])
        ylabel('Orig');
        title('Fig.3 in TIM 2019 paper');

        subplot(5,1,2)
        plot(t_plot,(swd(1,:) + swd(2,:)))
        xlim([0 t_plot(end)])
        ylabel('s_0');

        subplot(5,1,3);
        plot(t_plot,s1);
        xlim([0 t_plot(end)])
        ylabel('s_1');

        subplot(5,1,4);
        plot(t_plot,s2);
        xlim([0 t_plot(end)])
        ylabel('s_2');

        subplot(5,1,5);
        plot(t_plot,swa(7,:));
        xlim([0 t_plot(end)])
        ylabel('a_7');
    end
    %% B. Multiscale Sum and Products:
    p = s1 .* s2;
    p = p(:);

    if debug_flag
        % if you want to debug the result.
        figure;
        ax(1) = subplot(4,1,1);
        plot(t_plot,sig);
        xlim([0 t_plot(end)])
        ylabel('Orig');
        title('Fig.4 in TIM 2019 paper');

        ax(2) = subplot(4,1,2);
        p1 = swd(1,:) .* swd(2,:) .* swd(3,:) .* swd(4,:) .* swd(5,:) .* swd(6,:) .* swd(7,:); 
        plot(t_plot,p1);
        xlim([0 t_plot(end)])
        ylabel('p_1');

        ax(3) = subplot(4,1,3);
        p1 = swd(3,:) .* swd(4,:) .* swd(5,:) .* swd(6,:) .* swd(7,:); 
        plot(t_plot,p1);
        xlim([0 t_plot(end)])
        ylabel('p_2');

        ax(4) = subplot(4,1,4);
        plot(t_plot,p);
        xlim([0 t_plot(end)])
        ylabel('p');

        linkaxes(ax,'x');
    end
    %% C. Shannon Entropy Envelope Extraction
    eta = 0.01 + std(p);
    p_tilda = abs(p);
    p_tilda(p_tilda < eta) = 0;
    p_tilda = p_tilda(:);

    % normalize p_tilda:
    norm_p_tilda = (p_tilda - min(p_tilda)) ./ (max(p_tilda) - min(p_tilda));
    norm_p_tilda = norm_p_tilda(:);

    se = NaN(size(norm_p_tilda));

    for tttt = 1:size(norm_p_tilda,1)
        if norm_p_tilda(tttt) == 0
            % from MATLAB page: https://www.mathworks.com/help/wavelet/ref/wentropy.html
            %  log(0) = 0
            % 0log(0) = 0.
            se(tttt) = 0;
        else
            se(tttt) = -1 * norm_p_tilda(tttt) .* log(norm_p_tilda(tttt));
        end
    end

    % % method 1: CONV twice:
    filt_Len = floor(0.2 * fs_PPG); % 0.4 is better. 05/04/2020.
    % h = ones(filt_Len,1)/filt_Len;   % A third-order filter has length 4
    % s = conv(se,h,'same'); % return the same size as se
    % s = conv(s,h,'same'); % conv twice

    % method 2: FILTFILT.
    % for 4020, ii = 2, PPG is zero.
    if any(isnan(se))
        % any sample is NaN.
        new_se = se;
        new_se(isnan(new_se)) = [];
        if isempty(new_se)
            % nothing left after removing NaN.

                HR_Vadrevu_1_2019 = 0; % there is no peak location.
                onset_zx = 1;

                HR_Vadrevu_2_2019 = 0; % there is no peak location.
                peak_zx = 1;

                filter_PPG = PPG_buffer;
            output_Vadrevu_1_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,...
                'PPG_peak_loc_Vadrevu_1_2019',onset_zx,...
                'HR_Vadrevu_1_2019',HR_Vadrevu_1_2019);

                output_Vadrevu_2_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,...
                'PPG_peak_loc_Vadrevu_2_2019',peak_zx,...
                'HR_Vadrevu_2_2019',HR_Vadrevu_2_2019);
            return
        else
            % part of data is NaN, maybe I should fill zeros in it?
            keyboard;
        end
    end
    b = ones(filt_Len,1);
    a = -1;
    s = filtfilt(b, a, se); % -> AC component


    %% D. Pulse Peak and Onset Determination.
    % 1. Gaussian derivative kernel:
    sigma_1 = floor(0.05 * fs_PPG); % 0.05 mentioned in the paper.
    M = floor(2 * fs_PPG); % 2 mentioned in the paper.
    g = gausswin(M,sigma_1); % size should be 250 if Fs = 125.
    h_d = diff(g); % g(m+1) - g(m).
    z = conv(s,h_d,'same');

    % % My conv function did not work.
    % temp_z = zeros(size(s,1),1);
    % for nnnn = 1:size(s,1)
    %     for mmmm = 1:size(g,1)-1
    %         if (nnnn-mmmm+1 > 0)
    % %             h_d(mmmm) = g(mmmm+1) - g(mmmm);
    %         temp_z(nnnn) = temp_z(nnnn) + s(mmmm) * h_d(nnnn-mmmm+1);
    %         end
    %     end
    % end

    DownZCi = @(v) find(v(1:end-1) >= 0 & v(2:end) < 0); % Returns Down Zero-Crossing Indices. https://www.mathworks.com/matlabcentral/answers/267222-easy-way-of-finding-zero-crossing-of-a-function
    zx = DownZCi(z); % negative zero crossing point.

    % peak correction algorithm for onset:
    search_intv = floor(0.1 * fs_PPG / 2); % w/2
    onset_zx = NaN(size(zx));
    for zz = 1:size(zx,1)
        temp_zx = zx(zz);
        if temp_zx - search_intv > 0 % not exceed signal limit.
            if temp_zx + search_intv <= size(sig,1)
                temp_PPG = sig(temp_zx - search_intv : temp_zx + search_intv);
                [~,I] = min(temp_PPG);
                if isempty(I) ~= 1
                    adj_loc = temp_zx - search_intv + I - 1;
                else
                    % no local minimum.
                    adj_loc = temp_zx; 
                end
                onset_zx(zz) = adj_loc;
            else
                % right interval exceed signal length.
                onset_zx(zz) = zx(zz);
            end
        else
            % left interval exceed index 1.
            onset_zx(zz) = zx(zz);
        end
    end

    % find peak:
    peak_zx = NaN(size(onset_zx,1)-1,1); % one sample smaller.
    for zz = 2:size(onset_zx,1)
        temp_onset_1 = onset_zx(zz-1);
        temp_onset_2 = onset_zx(zz);
        temp_PPG = sig(temp_onset_1:temp_onset_2);
        [~,I] = max(temp_PPG);
        if isempty(I) ~= 1
           peak_zx(zz-1) = temp_onset_1 + I - 1; % peak is one sample size smaller.
        else
            peak_zx(zz-1) = onset_zx(zz);
        end
    end

    % prepare to output signal:
    filter_PPG = z(LEN+1:end-LEN);
    remove_left = find(onset_zx < LEN+1);
    if isempty(remove_left) ~= 1
        onset_zx(remove_left) = [];
    end
    remove_right = find(onset_zx > size(z,1) - LEN);
    if isempty(remove_right) ~= 1
        onset_zx(remove_right) = [];
    end
    onset_zx = onset_zx - LEN; % shifted.

    remove_left = find(peak_zx < LEN+1);
    if isempty(remove_left) ~= 1
        peak_zx(remove_left) = [];
    end
    remove_right = find(peak_zx > size(z,1) - LEN);
    if isempty(remove_right) ~= 1
        peak_zx(remove_right) = [];
    end
    peak_zx = peak_zx - LEN;

    if debug_flag
        % if you want to debug the result.
        figure;
        ax(1) = subplot(7,1,1);
        plot(t_plot,sig);
        xlim([0 t_plot(end)])
        ylabel('Orig');
        title('Fig.5 in TIM 2019 paper');

        ax(2) = subplot(7,1,2);
        plot(t_plot,p);
        xlim([0 t_plot(end)])
        ylabel('p');

        ax(3) = subplot(7,1,3);
        plot(t_plot,norm_p_tilda);
        xlim([0 t_plot(end)])
        ylabel('p_th');

        ax(4) = subplot(7,1,4);
        plot(t_plot,se);
        xlim([0 t_plot(end)])
        ylabel('se');

        ax(5) = subplot(7,1,5);
        plot(t_plot,s);
        xlim([0 t_plot(end)])
        ylabel('s');

        ax(6) = subplot(7,1,6);
        plot(t_plot,z);
        hold on;
        plot(t_plot(zx),z(zx),'ro');
        xlim([0 t_plot(end)]);
        ylabel('z');


        ax(7) = subplot(7,1,7);
        plot(t_plot,sig);
        hold on;
        plot(t_plot(onset_zx),sig(onset_zx),'go');
        plot(t_plot(peak_zx),sig(peak_zx),'ro');
        xlim([0 t_plot(end)])
        ylabel('orig with peak');

        linkaxes(ax,'x');
    end

    if isempty(onset_zx)
        HR_Vadrevu_1_2019 = 0; % there is no peak location.
        onset_zx = 1;
    else
        HR_Vadrevu_1_2019 = 60 * fs_PPG ./ diff(onset_zx); % calculate the HR.
    end
    
    if isempty(peak_zx)
        HR_Vadrevu_2_2019 = 0; % there is no peak location.
        peak_zx = 1;
    else
        HR_Vadrevu_2_2019 = 60 * fs_PPG ./ diff(peak_zx); % calculate the HR.
    end
    
    output_Vadrevu_1_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,...
        'PPG_peak_loc_Vadrevu_1_2019',onset_zx,...
        'HR_Vadrevu_1_2019',HR_Vadrevu_1_2019);

        output_Vadrevu_2_2019 = struct('filtered_PPG_Vadrevu_2019',filter_PPG,...
        'PPG_peak_loc_Vadrevu_2_2019',peak_zx,...
        'HR_Vadrevu_2_2019',HR_Vadrevu_2_2019);
    
end
","MATLAB"