-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbwr.py
38 lines (29 loc) · 1.08 KB
/
bwr.py
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
import numpy as np
import pywt
def calc_baseline(signal):
"""
Original code: https://github.com/spebern/py-bwr
Calculate the baseline of signal.
Args:
signal (numpy 1d array): signal whose baseline should be calculated
Returns:
baseline (numpy 1d array with same size as signal): baseline of the signal
"""
ssds = np.zeros((3))
cur_lp = np.copy(signal)
iterations = 0
while True:
# Decompose 1 level
lp, hp = pywt.dwt(cur_lp, "db4")
# Shift and calculate the energy of detail/high pass coefficient
ssds = np.concatenate(([np.sum(hp ** 2)], ssds[:-1]))
# Check if we are in the local minimum of energy function of high-pass signal
if ssds[2] > ssds[1] and ssds[1] < ssds[0]:
break
cur_lp = lp[:]
iterations += 1
# Reconstruct the baseline from this level low pass signal up to the original length
baseline = cur_lp[:]
for _ in range(iterations):
baseline = pywt.idwt(baseline, np.zeros((len(baseline))), "db4")
return baseline[: len(signal)]