Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve perf of xr.corr #6638

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions xarray/core/computation.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@

import numpy as np

from xarray.core.types import T_DataArray

from . import dtypes, duck_array_ops, utils
from .alignment import align, deep_align
from .common import zeros_like
Expand Down Expand Up @@ -1353,7 +1355,9 @@ def corr(da_a, da_b, dim=None):
return _cov_corr(da_a, da_b, dim=dim, method="corr")


def _cov_corr(da_a, da_b, dim=None, ddof=0, method=None):
def _cov_corr(
da_a: T_DataArray, da_b: T_DataArray, dim=None, ddof=0, method=None
) -> T_DataArray:
"""
Internal method for xr.cov() and xr.corr() so only have to
sanitize the input arrays once and we don't repeat code.
Expand All @@ -1372,11 +1376,9 @@ def _cov_corr(da_a, da_b, dim=None, ddof=0, method=None):
demeaned_da_b = da_b - da_b.mean(dim=dim)

# 4. Compute covariance along the given dim
# N.B. `skipna=False` is required or there is a bug when computing
# auto-covariance. E.g. Try xr.cov(da,da) for
# da = xr.DataArray([[1, 2], [1, np.nan]], dims=["x", "time"])
cov = (demeaned_da_a * demeaned_da_b).sum(dim=dim, skipna=True, min_count=1) / (
valid_count
# `fillna` is required since `.dot` has no NaN tolerance.
cov = (
demeaned_da_a.fillna(0.0).dot(demeaned_da_b.fillna(0.0), dims=dim) / valid_count
)

if method == "cov":
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/dataarray.py
Original file line number Diff line number Diff line change
Expand Up @@ -3399,8 +3399,8 @@ def imag(self) -> DataArray:
return self._replace(self.variable.imag)

def dot(
self, other: DataArray, dims: Hashable | Sequence[Hashable] | None = None
) -> DataArray:
self, other: T_DataArray, dims: Hashable | Sequence[Hashable] | None = None
) -> T_DataArray:
"""Perform dot product of two DataArrays along their shared dims.

Equivalent to taking taking tensordot over all shared dims.
Expand Down