-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsignal.go
135 lines (103 loc) · 2.26 KB
/
signal.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
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
package dsp
import (
"errors"
"fmt"
"time"
)
type Signal struct {
// SampleRate is the sampling rate of the signal in Hz
SampleRate float64
// Store the signal values
Signal []float64
}
func (s *Signal) Sample(duration time.Duration) *Signal {
sample := make([]float64, 0)
for i := 0; i < int(s.SampleRate*duration.Seconds()); i++ {
sample = append(sample, s.Signal[i])
}
return &Signal{
SampleRate: s.SampleRate,
Signal: sample,
}
}
func (s *Signal) Split(split time.Duration) []*Signal {
sample := make([]float64, 0)
result := make([]*Signal, 0)
size := int(s.SampleRate * split.Seconds())
for i := 0; i < len(s.Signal); i++ {
sample = append(sample, s.Signal[i])
if i > 0 && i%size == 0 {
result = append(result, &Signal{
SampleRate: s.SampleRate,
Signal: sample,
})
sample = make([]float64, 0)
}
}
if len(sample) > 0 {
result = append(result, &Signal{
SampleRate: s.SampleRate,
Signal: sample,
})
}
return result
}
func (s *Signal) String() string {
return fmt.Sprintf("SampleRate: %vHz, Length: %v, Duration: %.1fs", s.SampleRate, len(s.Signal), s.Duration())
}
func (s *Signal) Length() int {
return len(s.Signal)
}
func (s *Signal) Duration() float64 {
duration := float64(len(s.Signal)) / s.SampleRate
return duration
}
func (s *Signal) Min() float64 {
if len(s.Signal) == 0 {
return 0
}
min := s.Signal[0]
for i := range s.Signal {
if s.Signal[i] < min {
min = s.Signal[i]
}
}
return min
}
func (s *Signal) Max() float64 {
if len(s.Signal) == 0 {
return 0
}
max := s.Signal[0]
for i := range s.Signal {
if s.Signal[i] > max {
max = s.Signal[i]
}
}
return max
}
// Normalize the signal between -1 and 1 and return a new signal
func (s *Signal) Normalize() (*Signal, error) {
input := s.Signal
if len(input) == 0 {
return &Signal{
SampleRate: s.SampleRate,
Signal: s.Signal,
}, nil
}
min := s.Min()
max := s.Max()
// We can't normalize a flat signal where min == max
if min == max {
return nil, errors.New("cannot normalize signal")
}
normalized := make([]float64, len(input))
for i := range input {
val := input[i]
normalized[i] = 2*((val-min)/(max-min)) - 1
}
return &Signal{
SampleRate: s.SampleRate,
Signal: normalized,
}, nil
}