Source code for nnsa.preprocessing.detrending

import numpy as np

__all__ = [
    'detrend_poly',
]


[docs]def detrend_poly(y, order, x=None): """ Detrend y=f(x) with a polynomial of specified order. Can handle nan values (by ignoring the in the fit). Args: y (np.ndarray): 1D array with y values. order (int): order of the fitted polynomial. x (np.ndarray): optional array with x values (same shape as y). If not specified, x = np.arange(len(y)), assuming equidistant samples in y. Returns: y_detrend (np.ndarray): detrended signal. """ if order is None: return y y = np.asarray(y) if y.ndim != 1: raise ValueError('Got unexpected shape {}. x should be a 1D array.' .format(y.shape)) if x is not None: x = np.asarray(x) if x.shape != y.shape: raise ValueError('Shapes of `x` ({}) and `y` ({}) must be the same.' .format(x.shape, y.shape)) else: x = np.arange(len(y)) # Nan values to ignore in the fit. nan_mask = np.isnan(y) # Fit. fit = np.polyval(np.polyfit(x[~nan_mask], y[~nan_mask], deg=order), x) # Detrend. y_detrend = y - fit return y_detrend