如何将 Pearson 相关分析应用于 DataArray 的所有像素对作为相关矩阵?

How to apply a Pearson Correlation Analysis over all pairs of pixels of a DataArray as a Correlation Matrix?

我在生成具有维度('lon'、'lat'、'time')的单个 Netcdf 的相关矩阵(逐像素)时遇到了严重困难。我的最终目的是生成所谓的 Teleconnectivity Map。

这张地图由相关系数组成。每个像素都有一个值,表示在 DataArray 中所有像素对的相关矩阵中找到的最高相关值(在模块中)。

因此,为了创建我的 Teleconnectivity 地图,而不是遍历每个经度 ('lon') 和每个纬度 ('lat'),然后检查所有可能的相关组合幅度更高,我正在考虑应用 xr.apply_ufunction 和内部包装的相关函数。

尽管我付出了努力,但我仍然不了解 xr.apply_ufunc 幕后真正发生的事情。我所做的只是作为一个所有像素都等于 1(完美相关)的结果矩阵。

查看下面的代码:


import numpy as np

import xarray as xr

def correlation(x, y):

    return np.corrcoef(x, y)[0,0] # to return a single correlation index, instead of a matriz


def wrapped_correlation(da, x, coord='time'):
    """Finds the correlation along a given dimension of a dataarray."""


    from functools import partial

    fpartial = partial(correlation, x.values)

    return xr.apply_ufunc(fpartial, 
                          da, 
                          input_core_dims=[[coord]] , 
                          output_core_dims=[[]],
                          vectorize=True,
                          output_dtypes=[float]
                          )



# testing the wrapped correlation for a sample data:

ds = xr.tutorial.open_dataset('air_temperature').load()

# testing for a single point in space.

x = ds['air'].sel(dict(lon=1, lat=92), method='nearest')

# over all points in the DataArray

Corr_over_x = wrapped_correlation(ds['air'], x)

Corr_over_x# notice that the resultant DataArray is composed solely of ones (perfect correlation match). This is impossible. I would expect to have different values of correlation for each pixel in here

# if one would plot the data, I would be composed of a variety of correlation values (see example below):

Corr_over_x.plot()

这是气象学家和遥感研究的重要资产。它允许评估给定研究区域的潜在地球物理模式。

感谢您的宝贵时间,希望很快收到您的来信。

此致,

首先,您需要使用np.corrcoef(x, y)[0,1]。最后,你根本不需要使用 partial,见下文:

def correlation(x1, x2):

    return np.corrcoef(x1, x2)[0,1] # to return a single correlation index, instead of a matriz


def wrapped_correlation(da, x, coord='time'):
    """Finds the correlation along a given dimension of a dataarray."""

    return xr.apply_ufunc(correlation, 
                          da, 
                          x,
                          input_core_dims=[[coord],[coord]] , 
                          output_core_dims=[[]],
                          vectorize=True,
                          output_dtypes=[float]
                          )

我已经成功解决了我的问题。脚本变得有点长。尽管如此,它还是实现了它之前的预期。

代码改编自此reference

由于在这里显示片段太长,我将 link 发布到我的 Github 帐户,其中算法(组织在名为 Teleconnection_using_xarray_data 的包中)可以检查 here.

该软件包有两个模块,结果相似。

第一个模块 (teleconnection_with_connecting_pathways) 比第二个 (teleconnection_via_numpy) 慢,但它允许评估部分遥相关图之间的连接路径。

第二个,只有returns生成的遥相关图,没有连接线(geopandas-Linestrings),但速度要快得多。

随时合作。如果可能的话,我想结合这两个模块确保远程连接算法中的速度和路径分析。

此致,

菲利普·里尔