-
Notifications
You must be signed in to change notification settings - Fork 7
/
heartbeat.go
98 lines (73 loc) · 1.82 KB
/
heartbeat.go
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
package dsp
import (
"fmt"
"github.com/goccmack/godsp/peaks"
"math"
)
type RPeaks struct {
Indices []int
RPeakInterval []float64
HeartBeatsPerMinute []float64
}
func GetRPeaks(signal *Signal) RPeaks {
// Assume that the highest heart rate is 200 BPM
separator := signal.SampleRate / (200.0 / 60.0)
indices := peaks.Get(signal.Signal, int(separator))
rPeakInterval := make([]float64, 0)
bpm := make([]float64, 0)
previousTime := 0.0
// Calculate the r-peak interval
for i := range indices {
currentTime := float64(indices[i]) * (1.0 / signal.SampleRate)
t := currentTime - previousTime
rPeakInterval = append(rPeakInterval, t)
if t == 0 {
bpm = append(bpm, 0)
} else {
bpm = append(bpm, 60/t)
}
previousTime = currentTime
}
return RPeaks{
Indices: indices,
RPeakInterval: rPeakInterval,
HeartBeatsPerMinute: bpm,
}
}
func (r *RPeaks) IsRPeak(index int) bool {
for i := range r.Indices {
if r.Indices[i] == index {
return true
}
}
return false
}
func (r *RPeaks) Avg() int {
if len(r.HeartBeatsPerMinute) == 0 {
return 0
}
sum := 0.0
for i := range r.HeartBeatsPerMinute {
sum += r.HeartBeatsPerMinute[i]
}
return int(sum / float64(len(r.HeartBeatsPerMinute)))
}
func (r *RPeaks) Count() int {
return len(r.HeartBeatsPerMinute)
}
func (r *RPeaks) HeartRateVariabilityByRmssd() float64 {
totalSamples := len(r.RPeakInterval)
if totalSamples == 0 || totalSamples == 1 {
return 0
}
total := 0.0
for i := 0; i < totalSamples-1; i++ {
diff := (r.RPeakInterval[i+1] * 1000) - (r.RPeakInterval[i] * 1000)
total += diff * diff
}
result := math.Sqrt(total / float64(totalSamples-1))
return result
}
func (r *RPeaks) String() string {
return fmt.Sprintf("Total heart beats detected: %v, avg heart rate: %v BPM", r.Count(), r.Avg())
}