Resampling data#

Sometimes you may want to resample your data to a different sampling rate. We provide a utility class to do this. It wraps scipy.signal.resample and provides a standardized transform interface, so that it can be chained and used with other transforms in mobgap.

Below we show how to apply the method.

import matplotlib.pyplot as plt
from mobgap.data import LabExampleDataset
from mobgap.data_transform import Resample

Loading some example data#

example_data = LabExampleDataset()
ha_example_data = example_data.get_subset(cohort="HA")
single_test = ha_example_data.get_subset(
    participant_id="002", test="Test5", trial="Trial2"
)
data = single_test.data_ss

data.head()
acc_x acc_y acc_z gyr_x gyr_y gyr_z
time
2020-08-21 10:30:50.479000092+00:00 9.257165 0.031602 -2.604847 -0.1608 0.2119 -0.3052
2020-08-21 10:30:50.489000082+00:00 9.268460 0.017997 -2.594873 -0.2712 -0.0757 -0.4693
2020-08-21 10:30:50.499000072+00:00 9.272030 0.040954 -2.617060 0.1157 -0.0892 -0.2648
2020-08-21 10:30:50.509000063+00:00 9.262215 0.046100 -2.615381 -0.0091 -0.2005 -0.3278
2020-08-21 10:30:50.519000052+00:00 9.267278 0.070575 -2.585830 0.0524 -0.2733 -0.0965


Applying the resampling transform#

For this we need to create an instance of the Resample class with our target sampling rate.

Then we can perform the resampling operation by calling the transform method

resampled = resampler.transform(
    data, sampling_rate_hz=single_test.sampling_rate_hz
)

The results can be accessed via the transformed_data_ attribute. Here we only extract the gyro data.

gyr_x gyr_y gyr_z
time
2020-08-21 10:30:50.479000092+00:00 0.162794 0.456150 -0.145296
2020-08-21 10:30:50.529064144+00:00 0.211031 0.092460 -0.209048
2020-08-21 10:30:50.579128197+00:00 0.492423 0.205673 -0.293729
2020-08-21 10:30:50.629192249+00:00 0.762922 0.531404 -0.171300
2020-08-21 10:30:50.679256302+00:00 0.630536 0.585892 -0.241490


Note, that the resampled data still has a datetime index. This is, because the resampling operation attempts to resample the index as well, if the index is numeric or datetime. If you want to disable this behavior, you can set the attempt_index_resample parameter to False.

We will plot the resampled data together with the original data. As expected, the resampled data has much fewer samples (as we downsampled from 100 Hz to 20 Hz). However, you could use the same method to upsample your data.

fig, axs = plt.subplots(3, 1, sharex=True)
for ax, col in zip(axs, resampled_gyr.columns):
    ax.set_title(col)
    data[col].plot(ax=ax, label="Original", style=".")
    resampled_gyr[col].plot(ax=ax, label="Resampled", style=".")

axs[0].set_xlim(data.index[300], data.index[500])
axs[0].legend()
fig.show()
gyr_x, gyr_y, gyr_z

Total running time of the script: (0 minutes 1.336 seconds)

Estimated memory usage: 9 MB

Gallery generated by Sphinx-Gallery