Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
135 lines (118 loc) · 5.36 KB
/
Copy pathutils.py
File metadata and controls
135 lines (118 loc) · 5.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import numpy as np
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt
import geopandas as gpd
import cartopy.crs as crs
from cartopy.feature import NaturalEarthFeature
import cartopy.io.shapereader as shpreader
import matplotlib.ticker as mticker
from matplotlib import gridspec
import time
import scipy.stats as stats
# import tensorflow as tf
# import tensorflow_probability as tfp
plt.rcParams['font.family'] = 'Myriad Pro'
# the Kling-Gupta Efficiency (KGE) score
def kge(true_, fit):
r = np.corrcoef(true_, fit)[0, 1]
alpha = np.std(fit, ddof = 1) / np.std(true_, ddof= 1)
beta = np.mean(fit) / np.mean(true_)
return 1 - np.sqrt((r - 1)**2 + (alpha - 1)**2 + (beta - 1)**2)
# the Nash-Sutcliffe Efficiency (NSE) score
def nse(true_, fit):
return 1 - np.sum((true_ - fit) ** 2) / np.sum((true_ - np.mean(true_)) ** 2)
# given prior info: mu_x, mu_y, kxx, kyy, kxy (derived from simulated rainfall)
# conditioned on some observation of x: xx_obs
# update the posterior distribution of y: mu_y, cov_y
def gp_infer(xx_obs, mu_x, kyx, kxx, mu_y, kyy, sn):
mu_y = mu_y + kyx @ np.linalg.inv(kxx + np.diag(sn**2)) @ (xx_obs - mu_x).T
kyy = kyy - kyx @ np.linalg.inv(kxx + np.diag(sn**2)) @ kyx.T
return mu_y.squeeze(), kyy
class sg_map_plotter:
def __init__(self, lons, lats, coastline) -> None:
self.lons = lons
self.lats = lats
self.coastline = coastline
return
def plot_(self, ax, data, cmap, vmax = -1, vmin = -1, hide_axis = [1, 1, 1, 1]):
self.coastline.plot(ax=ax, facecolor='none', edgecolor='black', linewidth=1)
basemap = ax.contourf(self.lons, self.lats, data, levels=np.linspace(vmin, vmax, 21), transform=crs.PlateCarree(), cmap=cmap, extend = 'max')
ax.set_extent([103.58, 104.12, 1.153, 1.502], crs=crs.PlateCarree())
gl = ax.gridlines(crs=crs.PlateCarree(), draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='--')
gl.xlocator = mticker.FixedLocator([103.5, 103.6, 103.7, 103.8, 103.9, 104.0, 104.1])
gl.ylocator = mticker.FixedLocator([1.1, 1.2, 1.3, 1.4, 1.5])
if hide_axis[0]:
gl.bottom_labels = False
if hide_axis[1]:
gl.top_labels = False
if hide_axis[2]:
gl.left_labels = False
if hide_axis[3]:
gl.right_labels = False
return
def plot_scatter(self, ax, loc, size = 25, facecolor = 'k', marker_type = 'D'):
ax.scatter(loc[:,0], loc[:,1], s = size, facecolors = facecolor, marker = marker_type, edgecolor = 'none')
return
class gp_interpolator:
def __init__(self, P, e0 = 300, thres = 1e-3) -> None:
# # of stations
self.p_ = P
# # see Peng & Albertson 2021 but a vector of initial local noise levels is used here
self.sn = e0 * np.ones(self.p_) # initial local noises
self.sn_thres = thres # a user-specified threshold for the noise level convergence
self.iter = 0 # iteration counter
return
def read_rainfall(self, obs, sim, mu_x = None, kxx = None):
# read observational rainfall in a matrix of N by P
# N = # of months, P = # of stations
self.rain_obs = obs
# for QoL, get simulated rainfall time series corresponding to their station-based counterparts
# the size of this matrix should also be N by P
self.wrf_sta = sim
# prepare the prior distribution
if mu_x is None:
self.mu_x = np.mean(self.wrf_sta, axis = 0)
else:
self.mu_x = mu_x
if kxx is None:
self.kxx = np.cov(self.wrf_sta.T, ddof = 1)
else:
self.kxx = kxx
return
def sn_converge(self):
sn0 = 9999 * np.ones(self.p_)
xx_obs = self.rain_obs
while np.mean((sn0 - self.sn)**2) / np.mean(self.sn**2) > self.sn_thres:
self.iter += 1
sn0 = self.sn
tmp_err = []
for j in range(self.p_):
# Create mask to exclude station j
mask = np.ones(self.p_, dtype=bool)
mask[j] = False
# Extract masked variables directly from stored values
tsn = self.sn[mask]
tmu_x = self.mu_x[mask]
tkxx = self.kxx[np.ix_(mask, mask)]
tkyx = self.kxx[j:j+1, mask]
tmu_y = self.mu_x[j]
tkyy = self.kxx[j, j]
txx_obs = xx_obs[:, mask]
fit_y, fit_kyy = gp_infer(xx_obs = txx_obs, mu_x = tmu_x, kyx = tkyx, kxx = tkxx,
mu_y = tmu_y, kyy = tkyy, sn = tsn)
tmp_err.append(np.sqrt(np.mean((xx_obs[:, j] - fit_y) ** 2)))
print(self.iter)
print(tmp_err)
self.sn = np.array(tmp_err)
return
def predict(self, yy, mu_y = None, kyy = None, kyx = None):
if mu_y is None:
mu_y = np.mean(yy[None, :], axis = 1).T
if kyy is None:
kyy = np.cov(yy.T, ddof = 1)
if kyx is None:
kyx = np.cov(yy.T, self.wrf_sta.T, ddof = 1)[:yy.shape[1], yy.shape[1]:]
post_mu_y, post_kyy = gp_infer(xx_obs = self.rain_obs, mu_x = self.mu_x, kyx = kyx,
kxx = self.kxx, mu_y = mu_y, kyy = kyy, sn = self.sn)
return post_mu_y, post_kyy