API

Cardiac data

Denoising metrics for cardio recordings.

phys2denoise.metrics.cardiac.cardiac_phase(peaks, sample_rate, slice_timings, n_scans, t_r)[source]

Calculate cardiac phase from cardiac peaks.

Assumes that timing of cardiac events are given in same units as slice timings, for example seconds.

Parameters:
  • peaks (1D array_like) – Cardiac peak times, in seconds.

  • sample_rate (float) – Sample rate of physio, in Hertz.

  • slice_timings (1D array_like) – Slice times, in seconds.

  • n_scans (int) – Number of volumes in the imaging run.

  • t_r (float) – Sampling rate of the imaging run, in seconds.

Returns:

phase_card – Cardiac phase signal, of shape (n_scans,)

Return type:

array_like

phys2denoise.metrics.cardiac.heart_beat_interval(card, peaks, samplerate, window=6, central_measure='mean')[source]

Compute average heart beat interval (HBI) in a sliding window.

Parameters:
  • card (list or 1D numpy.ndarray) – Timeseries of recorded cardiac signal

  • peaks (list or 1D numpy.ndarray) – array of peak indexes for card.

  • samplerate (float) – Sampling rate for card, in Hertz.

  • window (float, optional) – Size of the sliding window, in seconds. Default is 6.

  • central_measure ("mean","average", "avg", "median", "mdn", string, optional) – Measure of the center used (mean or median). Default is “mean”.

Returns:

card_met – Heart Beats Interval or Heart Rate Variability timeseries. The first column is the raw metric, in seconds. The second column is the metric convolved with the CRF, cut to the length of the raw metric.

Return type:

2D numpy.ndarray

Notes

Heart beats interval (HBI) definition is taken from [1]_, and consists of the average of the time interval between two heart beats within a 6-seconds window. This metric should be convolved with an inverse of the cardiac response function before being included in a GLM.

IMPORTANT : The unit of measure has meaning, since it is based on seconds. Hence, zscoring might remove important quantifiable information.

See _cardiac_metrics for full implementation.

References

phys2denoise.metrics.cardiac.heart_rate(card, peaks, samplerate, window=6, central_measure='mean')[source]

Compute average heart rate (HR) in a sliding window.

We call this function HEART RATE, however note that if using a PPG recorded signal, it is more accurate to talk about PULSE RATE. See [2]_ for the differences and similarities between the two measures.

Parameters:
  • card (list or 1D numpy.ndarray) – Timeseries of recorded cardiac signal

  • peaks (list or 1D numpy.ndarray) – array of peak indexes for card.

  • samplerate (float) – Sampling rate for card, in Hertz.

  • window (float, optional) – Size of the sliding window, in seconds. Default is 6.

  • central_measure ("mean","average", "avg", "median", "mdn", string, optional) – Measure of the center used (mean or median). Default is “mean”.

Returns:

card_met – Heart Beats Interval or Heart Rate Variability timeseries. The first column is the raw metric, in Hertz. The second column is the metric convolved with the CRF, cut to the length of the raw metric.

Return type:

2D numpy.ndarray

Notes

Heart rate (HR) is taken from [1]_, and computed as the amounts of beats per minute. However, operationally, it is the average of the inverse of the time interval between two heart beats. This metric should be convolved with the cardiac response function before being included in a GLM.

IMPORTANT : The unit of measure has a meaning, since they it’s based on Hertz. Hence, zscoring might remove important quantifiable information.

See _cardiac_metrics for full implementation.

References

Annual International Conference of the IEEE Engineering in Medicine and Biology Society (EMBC), doi: 10.1109/EMBC.2016.7591347.

phys2denoise.metrics.cardiac.heart_rate_variability(card, peaks, samplerate, window=6, central_measure='mean')[source]

Compute average heart rate variability (HRV) in a sliding window.

We call this function HEART RATE variability, however note that if using a PPG recorded signal, it is more accurate to talk about PULSE RATE variability. See [1]_ for the differences and similarities between the two measures.

Parameters:
  • card (list or 1D numpy.ndarray) – Timeseries of recorded cardiac signal

  • peaks (list or 1D numpy.ndarray) – array of peak indexes for card.

  • samplerate (float) – Sampling rate for card, in Hertz.

  • window (float, optional) – Size of the sliding window, in seconds. Default is 6.

  • central_measure ("mean","average", "avg", "median", "mdn", string, optional) – Measure of the center used (mean or median). Default is “mean”.

Returns:

card_met – Heart Beats Interval or Heart Rate Variability timeseries. The first column is the raw metric, in Hertz. The second column is the metric convolved with the CRF, cut to the length of the raw metric.

Return type:

2D numpy.ndarray

Notes

Heart rate variability (HRV) is taken from [1]_, and computed as the amounts of beats per minute. However, operationally, it is the average of the inverse of the time interval between two heart beats. This metric should be convolved with the cardiac response function before being included in a GLM.

IMPORTANT : The unit of measure has a meaning, since they it’s based on Hertz. Hence, zscoring might remove important quantifiable information.

See _cardiac_metrics for full implementation.

References

Annual International Conference of the IEEE Engineering in Medicine and Biology Society (EMBC), doi: 10.1109/EMBC.2016.7591347.

Respiratory data

Denoising metrics for chest belt recordings.

phys2denoise.metrics.chest_belt.env(resp, samplerate, window=10)[source]

Calculate respiratory pattern variability across a sliding window.

Parameters:
  • resp ((X,) numpy.ndarray) – A 1D array with the respiratory belt time series.

  • samplerate (float) – Sampling rate for resp, in Hertz.

  • window (int, optional) – Size of the sliding window, in seconds. Default is 10.

Return type:

env_arr

Notes

This metric was first introduced in [1]_.

Across a sliding window, do the following: 1. Z-score respiratory belt signal 2. Calculate upper envelope 3. Calculate standard deviation of envelope

References

phys2denoise.metrics.chest_belt.respiratory_pattern_variability(resp, window)[source]

Calculate respiratory pattern variability.

Parameters:
  • resp (str or 1D numpy.ndarray) – Tiemseries representing respiration activity.

  • window (int) – Window length in samples.

Returns:

rpv_val – Respiratory pattern variability value.

Return type:

float

Notes

This metric was first introduced in [1]_.

  1. Z-score respiratory belt signal

  2. Calculate upper envelope

  3. Calculate standard deviation of envelope

References

phys2denoise.metrics.chest_belt.respiratory_phase(resp, sample_rate, n_scans, slice_timings, t_r)[source]

Calculate respiratory phase from respiratory signal.

Parameters:
  • resp (1D array_like) – Respiratory signal.

  • sample_rate (float) – Sample rate of physio, in Hertz.

  • n_scans – Number of volumes in the imaging run.

  • slice_timings – Slice times, in seconds.

  • t_r – Sample rate of the imaging run, in seconds.

Returns:

phase_resp – Respiratory phase signal, of shape (n_scans, n_slices).

Return type:

array_like

phys2denoise.metrics.chest_belt.respiratory_variance(resp, samplerate, window=6)[source]

Calculate respiratory variance.

Parameters:
  • resp ((X,) numpy.ndarray) – A 1D array with the respiratory belt time series.

  • samplerate (float) – Sampling rate for resp, in Hertz.

  • window (int, optional) – Size of the sliding window, in seconds. Default is 6.

Returns:

rv_out – Respiratory variance values. The first column is raw RV values, after normalization. The second column is RV values convolved with the RRF, after normalization.

Return type:

(X, 2) numpy.ndarray

Notes

Respiratory variance (RV) was introduced in [1]_, and consists of the standard deviation of the respiratory trace within a 6-second window.

This metric is often lagged back and/or forward in time and convolved with a respiratory response function before being included in a GLM. Regressors also often have mean and linear trends removed and are standardized prior to regressions.

References

Multimodal data

phys2denoise.multimodal.retroicor(physio, sample_rate, t_r, n_scans, slice_timings, n_harmonics, card=False, resp=False)

Compute RETROICOR regressors.

Parameters:
  • physio (array_like) – 1D array, whether cardiac or respiratory signal. If cardiac, the array is a set of peaks in seconds. If respiratory, the array is the actual respiratory signal.

  • sample_rate (float) – Physio sample rate, in Hertz.

  • t_r (float) – Imaging sample rate, in seconds.

  • n_scans (int) – Number of volumes in the imaging run.

  • slice_timings (array_like) – Slice times, in seconds.

  • n_harmonics (int) –

    ???

  • card (bool, optional) – Whether the physio data correspond to cardiac or repiratory signal.

  • resp (bool, optional) – Whether the physio data correspond to cardiac or repiratory signal.

Returns:

  • retroicor_regressors (list)

  • phase (array_like) – 2D array of shape (n_scans, n_slices)

Notes

RETROICOR regressors should be regressed from the imaging data before any other preprocessing, including slice-timing correction and motion correction.

References

Response functions

Miscellaneous utility functions for metric calculation.

phys2denoise.metrics.responses.crf(samplerate, time_length=32, onset=0.0, inverse=False)[source]

Calculate the cardiac response function using Chang, Cunningham and Glover’s definition.

Parameters:
  • samplerate (float) – Sampling rate of data, in seconds.

  • time_length (int, optional) – RRF kernel length, in seconds. Default is 32.

  • onset (float, optional) – Onset of the response, in seconds. Default is 0.

  • inverse (bool, optional) – If True, return the additive inverse of the CRF, i.e. the iCRF.

Returns:

crf – Cardiac or “heart” response function

Return type:

array-like

Notes

This cardiac response function was defined in [1]_, Appendix A.

The core code for this function comes from metco2, while several of the parameters, including time_length, and onset, are modeled on nistats’ HRF functions.

References

phys2denoise.metrics.responses.icrf(samplerate, time_length=32, onset=0.0)[source]

Calculate the inverse of the cardiac response function.

Parameters:
  • samplerate (float) – Sampling rate of data, in seconds.

  • time_length (int, optional) – RRF kernel length, in seconds. Default is 32.

  • onset (float, optional) – Onset of the response, in seconds. Default is 0.

  • inverse (bool, optional) – If True, return the additive inverse of the CRF, i.e. the iCRF.

Returns:

icrf – Inverse of cardiac or “heart” response function

Return type:

array-like

References

phys2denoise.metrics.responses.rrf(samplerate, time_length=50, onset=0.0)[source]

Calculate the respiratory response function using Chang and Glover’s definition.

Parameters:
  • samplerate (float) – Sampling rate of data, in seconds..

  • time_length (int, optional) – RRF kernel length, in seconds. Default is 50.

  • onset (float, optional) – Onset of the response, in seconds. Default is 0.

Returns:

rrf – respiratory response function

Return type:

array-like

Notes

This respiratory response function was defined in [1]_, Appendix A.

The core code for this function comes from metco2, while several of the parameters, including time_length, and onset, are modeled on nistats’ HRF functions.

References

Utilities

Miscellaneous utility functions for metric calculation.

phys2denoise.metrics.utils.apply_function_in_sliding_window(array, func, halfwindow, incomplete=True)[source]

Apply function f in a sliding window view of an array.

Windows are always considered as centered. This function can consider incomplete windows, i.e. those windows at the beginning and at the end of an array, so that the length of the output is the same as the length of the input. For the same reason, it will skip the very last window.

This is somewhat equivalent to pandas’ rolling function set with center=True, except for the incomplete windows.

Parameters:
  • array (list or numpy.ndarray) – Array to apply function in sliding windows to

  • func (function) – The bare function to be applied, e.g. np.mean

  • halfwindow (int) – Half of the window size to be applied

  • incomplete (bool, optional) – If True, return those windows that are smaller, i.e. at the beginning and at the end of array. If False, returns only complete windows.

Returns:

The result of the function on the given array.

Return type:

numpy.ndarray

phys2denoise.metrics.utils.apply_lags(arr1d, lags)[source]

Apply delays (lags) to an array.

Parameters:
  • arr1d ((X,) numpy.ndarray) – One-dimensional array to apply delays to.

  • lags ((Y,) tuple or int) – Delays, in the same units as arr1d, to apply to arr1d. Can be negative, zero, or positive integers.

Returns:

arr_with_lags – arr1d shifted according to lags. Each column corresponds to a lag.

Return type:

(X, Y) numpy.ndarray

phys2denoise.metrics.utils.convolve_and_rescale(array, func, rescale='rescale', pad=False)[source]

Convolve array by func and rescale the data.

Parameters:
  • array (list or numpy.ndarray) – Array to be convolved

  • func (list or numpy.ndarray) – The function to convolve array with

  • zscore (bool, optional.) – If True, array will be transformed to Zscores before the convolution. If False, raw array data will be taken to be convolved with the function.

  • rescale ("demean_rescale", "rescale", "zscore", "demean", or None, optional) – The rescaling operation used on array_combined`

  • pad (bool, optional) – If True, return a padded non-convolved metric together with the convolved one. If False, return both metrics at the lenght of input array.

Returns:

  • array_combined (numpy.ndarray) – One combined array (array and array convolved with func) rescaled or not

  • array_combined_padd (numpy.ndarray) – One combined array (array and array convolved with func), padded to the convolved data length, rescaled or not.

phys2denoise.metrics.utils.export_metric(metric, sample_rate, tr, fileprefix, ntp=None, ext='.1D', is_convolved=True, has_lags=False)[source]

Export the metric content, both in original sampling rate and resampled at the TR.

Parameters:
  • metric (list or numpy.ndarray) – Metric to be exported

  • sample_rate (int or float) – Original sampling rate of the metric

  • tr (int or float) – TR of functional data. Output will be also resampled to this value

  • fileprefix (str) – Filename prefix, including path where files should be stored

  • ntp (int or None, optional) – Number of timepoints to consider, if None, all will be automatically considered

  • ext (str, optional) – Extension of file, default “1D”

  • is_convolved (bool, optional.) – If True, metric contains convolved version already - default is True

  • has_lags (bool, optional.) – If True, metric contains lagged versions of itself - default is False

phys2denoise.metrics.utils.mirrorpad_1d(arr, buffer=250)[source]

Pad both sides of array with flipped values from array of length ‘buffer’.

Parameters:
  • arr

  • buffer

Return type:

arr_out

phys2denoise.metrics.utils.print_metric_call(metric, args)[source]

Log a message to describe how a metric is being called.

Parameters:
  • metric (function) – Metric function that is being called

  • args (dict) – Dictionary containing all arguments that are used to parametrise metric

Notes

Outcome

An info-level message for the logger.

phys2denoise.metrics.utils.rms_envelope_1d(arr, window=500)[source]

Conceptual translation of MATLAB 2017b’s envelope(X, x, ‘rms’) function.

Parameters:
  • arr

  • window

Returns:

rms_env – The upper envelope.

Return type:

numpy.ndarray

Notes

https://www.mathworks.com/help/signal/ref/envelope.html