def test_corr(control_3d_NA): """Check autocorr results with scipy.""" ds = control_3d_NA.isel(x=5, y=5) lag = 1 actual = corr(ds, ds, lag=lag) expected = correlate(ds[:-lag], ds[lag:]) np.allclose(actual, expected)
def corr(x, y, dim='time', lag=0, return_p=False): """ Computes the Pearson product-momment coefficient of linear correlation. (See autocorr for autocorrelation/lag for one time series) This version calculates the effective degrees of freedom, accounting for autocorrelation within each time series that could fluff the significance of the correlation. NOTE: If lag is not zero, x predicts y. In other words, the time series for x is stationary, and y slides to the left. Or, y stays in place and x slides to the right. This function is written to accept a dataset of arbitrary number of dimensions (e.g., lat, lon, depth). Parameters ---------- x, y : xarray DataArray time series being correlated (can be multi-dimensional) dim : str (default 'time') Correlation dimension lag : int (default 0) Lag to apply to correlation, with x predicting y. return_p : boolean (default False) If true, return both r and p Returns ------- r : correlation coefficient p : p-value accounting for autocorrelation (if return_p True) References (for dealing with autocorrelation): ---------- 1. Wilks, Daniel S. Statistical methods in the atmospheric sciences. Vol. 100. Academic press, 2011. 2. Lovenduski, Nicole S., and Nicolas Gruber. "Impact of the Southern Annular Mode on Southern Ocean circulation and biology." Geophysical Research Letters 32.11 (2005). 3. Brady, R. X., Lovenduski, N. S., Alexander, M. A., Jacox, M., and Gruber, N.: On the role of climate modes in modulating the air-sea CO2 fluxes in Eastern Boundary Upwelling Systems, Biogeosciences Discuss., https://doi.org/10.5194/bg-2018-415, in review, 2018. """ return st.corr(x, y, dim=dim, lag=lag, return_p=return_p)
def test_corr_autocorr(PM_da_control_3d): res1 = corr(PM_da_control_3d, PM_da_control_3d, lag=1, return_p=True) res2 = autocorr(PM_da_control_3d, return_p=True) for i in [0, 1]: assert_allclose(res1[i], res2[i])