Skip to content
This repository was archived by the owner on Aug 2, 2022. It is now read-only.

Commit c2687d9

Browse files
committed
Added a function to use the finite difference method for numerical signal differentiation.
1 parent b4c9f50 commit c2687d9

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

biosppy/signals/tools.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1301,3 +1301,56 @@ def find_intersection(x1=None,
13011301
values = np.mean(np.vstack((p1(roots), p2(roots))), axis=0)
13021302

13031303
return utils.ReturnTuple((roots, values), ('roots', 'values'))
1304+
1305+
1306+
def finite_difference(signal=None, weights=None):
1307+
"""Apply the Finite Difference method to compute derivatives.
1308+
1309+
Parameters
1310+
----------
1311+
signal : array
1312+
Signal to differentiate.
1313+
weights : list, array
1314+
Finite difference weight coefficients.
1315+
1316+
Returns
1317+
-------
1318+
index : array
1319+
Indices from `signal` for which the derivative was computed.
1320+
derivative : array
1321+
Computed derivative.
1322+
1323+
Notes
1324+
-----
1325+
* The method assumes central differences weights.
1326+
* The method accounts for the delay introduced by the method .
1327+
1328+
Raises
1329+
------
1330+
ValueError
1331+
If the number of weights is not odd.
1332+
1333+
"""
1334+
1335+
# check inputs
1336+
if signal is None:
1337+
raise TypeError("Please specify a signal to differentiate.")
1338+
1339+
if weights is None:
1340+
raise TypeError("Please specify the weight coefficients.")
1341+
1342+
N = len(weights)
1343+
if N % 2 == 0:
1344+
raise ValueError("Number of weights must be odd.")
1345+
1346+
# diff
1347+
derivative = ss.lfilter(weights, [1], signal)
1348+
1349+
# trim delay
1350+
D = N - 1
1351+
D2 = D // 2
1352+
1353+
index = np.arange(D2, len(signal) - D2, dtype='int')
1354+
derivative = derivative[D:]
1355+
1356+
return utils.ReturnTuple((index, derivative), ('index', 'derivative'))

0 commit comments

Comments
 (0)