0

I am trying to apply a formula I have found in a journal to my dataset.

To give a quick background/context of the formula, it is applied to a time series of heart rate data. Each data point in the heart rate time series represents an average of 30 collected measurements. The values of R(k) is used in hypnograms and is calculated as:

https://i.imgur.com/a/B8lVaeY

where the discrete time for every 1 min (starting from the first minute of the record and ending at the last one) is defined as k, 'Hk+i former' and 'Hk+i latter' are the heart rate values from the former and latter 30 seconds of the time interval (k+i) and i represents the movement inside the window (moving average) with the size 2q. q is an experimental value, lets say q=5.

I understand what is going on in the formula but am struggling to apply these maths to a numpy array.

Matt M
  • 47
  • 1
  • 5
  • You should show some code of what you have tried, with some sample data. Is Hk former and latter not just H_(k+i-1) and H_(k+i+1)? As that would represent the H value at one before and one after H_(k+i) – danielR9 Apr 22 '19 at 20:08

1 Answers1

0

The formula represents moving average over absolute difference between H_former and H_latter.

If you don't mind pandas, here is an example:

import numpy as np
import pandas as pd

# H_diff = H_former - H_latter
H_diff = np.arange(10, dtype=int)
# H_diff = array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
q = 2

# this line actually computes the MA
R = pd.Series(H_diff).abs().rolling(2*q+1, center=True).mean().values
# now R = array([nan, nan,  2.,  3.,  4.,  5.,  6.,  7., nan, nan])

If you prefer to stick with numpy only, there is an example in this question: How to calculate moving average using NumPy?

Marat
  • 15,215
  • 2
  • 39
  • 48