NCL (NCAR’s Command Language) has a useful function to calculate the [weighted/unweighted or centered/uncentered] pattern correlation. I’ve been trying to recreate this function in Python with no success.
Has anyone written a Python Function to calculate a weighted pattern correlation or have any thoughts to fix my function?
Below is my most recent attempt which doesn’t yield errors, but gives me a perfect pattern correlation between my datasets (which is not true). I’ve only included the part of the function that calculates the weighted pattern correlation for simplicity. Right now I am writing the function for the centered pattern correlation, but would include the option for uncentered when the weighting works.
Thank you in advance!
[import modules and read in data]
# Get spatial correlation (using the Pearson Correlation Coefficient) between model simulation and observational dataset
def get_spatial_correlation(model_path, obs_path, variable, time_slice, lat_slice, lon_slice, season=None, mask=None):
#[code to read in data, with options for seasonal subsetting or masking]
# Calculate weights
weights = np.cos(np.deg2rad(obs_data.lat))
# Calculate weighted means
obs_weighted_mean = (obs_climatology * weights).sum(dim=('lat', 'lon')) / weights.sum()
model_weighted_mean = (model_climatology * weights).sum(dim=('lat', 'lon')) / weights.sum()
# Calculate centered arrays
obs_centered = obs_climatology - obs_weighted_mean
model_centered = model_climatology - model_weighted_mean
# Calculate weighted standard deviations
obs_weighted_std = np.sqrt(((obs_centered * weights) ** 2).sum(dim=('lat', 'lon')) / weights.sum())
model_weighted_std = np.sqrt(((model_centered * weights) ** 2).sum(dim=('lat', 'lon')) / weights.sum())
# Calculate weighted covariance
weighted_cov = ((obs_centered * weights) * (model_centered * weights)).sum(dim=('lat', 'lon')) / weights.sum()
# Calculate weighted correlation coefficient
pattern_cor = weighted_cov / (obs_weighted_std * model_weighted_std)
pattern_cor = pattern_cor.round(2)
return pattern_cor