-
Notifications
You must be signed in to change notification settings - Fork 56
/
test_interpolation.py
480 lines (412 loc) · 19.2 KB
/
test_interpolation.py
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import geocat.datafiles as gdf
import numpy as np
import numpy.testing as nt
import xarray as xr
import pytest
from geocat.comp import interp_multidim, interp_hybrid_to_pressure, interp_sigma_to_hybrid
# Global input data
# Open the netCDF data file "atmos.nc" and read in common variables
try:
ds_atmos = xr.open_dataset(gdf.get("netcdf_files/atmos.nc"),
decode_times=False)
except Exception:
ds_atmos = xr.open_dataset("test/atmos.nc", decode_times=False)
_hyam = ds_atmos.hyam
_hybm = ds_atmos.hybm
_p0 = 1000. * 100 # Pa
class Test_interp_hybrid_to_pressure:
# Expected output from above sample input
@pytest.fixture(scope="class")
def ds_out(self):
try:
return xr.open_dataset(
"vinth2p_output.nc"
) # Generated by running ncl_tests/vinth2p_test_conwomap_5.ncl on
# atmos.nc
except Exception:
return xr.open_dataset("test/vinth2p_output.nc")
# Sample input data
data = ds_atmos.U[0, :, :, :]
ps = ds_atmos.PS
pres3d = np.asarray([1000, 950, 800, 700, 600, 500, 400, 300, 200]) # mb
pres3d = pres3d * 100 # mb to Pa
def test_interp_hybrid_to_pressure_atmos(self, ds_out) -> None:
u_int = interp_hybrid_to_pressure(self.data,
self.ps[0, :, :],
_hyam,
_hybm,
p0=_p0,
new_levels=self.pres3d,
method="log")
uzon = u_int.mean(dim='lon')
nt.assert_array_almost_equal(ds_out.uzon, uzon, 5)
def test_interp_hybrid_to_pressure_atmos_4d(self, ds_out) -> None:
data_t = self.data.expand_dims("time")
u_int = interp_hybrid_to_pressure(data_t,
self.ps,
_hyam,
_hybm,
p0=_p0,
new_levels=self.pres3d,
method="log")
uzon = u_int.mean(dim='lon')
uzon_expected_t = ds_out.uzon.expand_dims("time")
nt.assert_array_almost_equal(uzon_expected_t, uzon, 5)
def test_interp_hybrid_to_pressure_atmos_wrong_method(self) -> None:
with pytest.raises(ValueError):
interp_hybrid_to_pressure(self.data,
self.ps[0, :, :],
_hyam,
_hybm,
p0=_p0,
new_levels=self.pres3d,
method="wrong_method")
class Test_interp_hybrid_to_pressure_extrapolate:
@pytest.fixture(scope="class")
def ds_ccsm(self):
# Open the netCDF data file with the input data
try:
return xr.open_dataset(
gdf.get("netcdf_files/ccsm35.h0.0021-01.demo.nc"),
decode_times=False)
except Exception:
return xr.open_dataset("test/ccsm35.h0.0021-01.demo.nc",
decode_times=False)
@pytest.fixture(scope="class")
def ds_out(self):
# Open the netCDF file with the output data from running vinth2p_ecmwf.ncl
try:
return xr.open_dataset("test/vinth2p_ecmwf_output.nc",
decode_times=False)
except Exception:
return xr.open_dataset("vinth2p_ecmwf_output.nc",
decode_times=False)
@pytest.fixture(scope="class")
def _hyam(self, ds_ccsm):
return ds_ccsm.hyam
@pytest.fixture(scope="class")
def _hybm(self, ds_ccsm):
return ds_ccsm.hybm
@pytest.fixture(scope="class")
def temp_in(self, ds_ccsm):
return ds_ccsm.T[:, :, :3, :2]
@pytest.fixture(scope="class")
def t_bot(self, ds_ccsm):
return ds_ccsm.TS[:, :3, :2]
@pytest.fixture(scope="class")
def geopotential_in(self, ds_ccsm):
return ds_ccsm.Z3[:, :, :3, :2]
@pytest.fixture(scope="class")
def humidity_in(self, ds_ccsm):
return ds_ccsm.Q[:, :, :3, :2] * 1000 # g/kg
@pytest.fixture(scope="class")
def press_in(self, ds_ccsm):
return ds_ccsm.PS[:, :3, :2]
@pytest.fixture(scope="class")
def phis(self, ds_ccsm):
return ds_ccsm.PHIS[:, :3, :2]
new_levels = np.asarray([500, 925, 950, 1000])
new_levels *= 100 # new levels in Pa
_p0 = 1000 * 100 # reference pressure in Pa
def test_interp_hybrid_to_pressure_interp_temp(self, temp_in, press_in,
_hyam, _hybm,
ds_out) -> None:
result = interp_hybrid_to_pressure(temp_in,
press_in,
_hyam,
_hybm,
p0=self._p0,
new_levels=self.new_levels,
method="linear")
result = result.transpose('time', 'plev', 'lat', 'lon')
result = result.assign_coords(dict(plev=self.new_levels / 100))
temp_interp_expected = ds_out.Tp.rename(lev_p='plev')
xr.testing.assert_allclose(temp_interp_expected, result)
def test_interp_hybrid_to_pressure_extrap_temp(self, temp_in, press_in,
_hyam, _hybm, t_bot, phis,
ds_out) -> None:
result = interp_hybrid_to_pressure(temp_in,
press_in,
_hyam,
_hybm,
p0=self._p0,
new_levels=self.new_levels,
method="linear",
extrapolate=True,
variable='temperature',
t_bot=t_bot,
phi_sfc=phis)
result = result.transpose('time', 'plev', 'lat', 'lon')
result = result.assign_coords(dict(plev=self.new_levels / 100))
temp_extrap_expected = ds_out.Tpx.rename(lev_p='plev')
xr.testing.assert_allclose(temp_extrap_expected, result)
def test_interp_hybrid_to_pressure_extrap_geopotential(
self, geopotential_in, press_in, _hyam, _hybm, t_bot, phis,
ds_out) -> None:
result = interp_hybrid_to_pressure(geopotential_in,
press_in,
_hyam,
_hybm,
p0=self._p0,
new_levels=self.new_levels,
method="linear",
extrapolate=True,
variable='geopotential',
t_bot=t_bot,
phi_sfc=phis)
result = result.transpose('time', 'plev', 'lat', 'lon')
result = result.assign_coords(dict(plev=self.new_levels / 100))
geopotential_extrap_expected = ds_out.Zpx.rename(lev_p='plev')
xr.testing.assert_allclose(geopotential_extrap_expected, result)
def test_interp_hybrid_to_pressure_extrap_other(self, humidity_in, press_in,
_hyam, _hybm, t_bot, phis,
ds_out) -> None:
result = interp_hybrid_to_pressure(humidity_in,
press_in,
_hyam,
_hybm,
p0=self._p0,
new_levels=self.new_levels,
method="linear",
extrapolate=True,
variable='other',
t_bot=t_bot,
phi_sfc=phis)
result = result.transpose('time', 'plev', 'lat', 'lon')
result = result.assign_coords(dict(plev=self.new_levels / 100))
humidity_extrap_expected = ds_out.Qpx.rename(lev_p='plev')
xr.testing.assert_allclose(humidity_extrap_expected, result)
def test_interp_hybrid_to_pressure_extrap_kwargs(self, humidity_in,
press_in, _hyam,
_hybm) -> None:
with pytest.raises(ValueError):
interp_hybrid_to_pressure(humidity_in,
press_in,
_hyam,
_hybm,
p0=self._p0,
new_levels=self.new_levels,
method="linear",
extrapolate=True)
def test_interp_hybrid_to_pressure_extrap_invalid_var(
self, humidity_in, press_in, _hyam, _hybm, t_bot, phis) -> None:
with pytest.raises(ValueError):
interp_hybrid_to_pressure(humidity_in,
press_in,
_hyam,
_hybm,
p0=self._p0,
new_levels=self.new_levels,
method="linear",
extrapolate=True,
variable=' ',
t_bot=t_bot,
phi_sfc=phis)
class Test_interp_sigma_to_hybrid:
@pytest.fixture(scope="class")
def ds_u(self):
# Open the netCDF data file "u.89335.1.nc" and read in input data
try:
return xr.open_dataset(
gdf.get("netcdf_files/u.89335.1_subset_time361.nc"),
decode_times=False)
except Exception:
return xr.open_dataset("test/u.89335.1_subset_time361.nc",
decode_times=False)
@pytest.fixture(scope="class")
def ds_ps(self):
# Open the netCDF data file "ps.89335.1.nc" and read in additional input
# data
try:
return xr.open_dataset(gdf.get("netcdf_files/ps.89335.1.nc"),
decode_times=False)
except Exception:
return xr.open_dataset("test/ps.89335.1.nc", decode_times=False)
@pytest.fixture(scope="class")
def ds_out(self):
# Expected output from above sample input
try:
return xr.open_dataset(
"sigma2hybrid_output.nc"
) # Generated by running ncl_tests/test_sigma2hybrid.ncl
except Exception:
return xr.open_dataset("test/sigma2hybrid_output.nc")
hyam = xr.DataArray([0.0108093, 0.0130731, 0.03255911, 0.0639471])
hybm = xr.DataArray([0.0108093, 0.0173664, 0.06069280, 0.1158237])
@pytest.fixture(scope="class")
def u(self, ds_u):
return ds_u.u[:, 0:3, 0:2]
@pytest.fixture(scope="class")
def ps(self, ds_ps):
return ds_ps.ps[361, 0:3, 0:2] * 100 # Pa
@pytest.fixture(scope="class")
def sigma(self, ds_ps):
return ds_ps.sigma
@pytest.fixture(scope="class")
def xh_expected(self, ds_out):
return ds_out.xh.transpose("ncl3", "ncl1", "ncl2") # Expected output
def test_interp_sigma_to_hybrid_1d(self, u, sigma, ps, xh_expected) -> None:
xh = interp_sigma_to_hybrid(u[:, 0, 0],
sigma,
ps[0, 0],
self.hyam,
self.hybm,
p0=_p0,
method="linear")
nt.assert_array_almost_equal(xh_expected[:, 0, 0], xh, 5)
def test_interp_sigma_to_hybrid_3d(self, u, sigma, ps, xh_expected) -> None:
xh = interp_sigma_to_hybrid(u,
sigma,
ps,
self.hyam,
self.hybm,
p0=_p0,
method="linear")
nt.assert_array_almost_equal(xh_expected, xh, 5)
def test_interp_sigma_to_hybrid_3d_transposed(self, u, sigma, ps,
xh_expected) -> None:
xh = interp_sigma_to_hybrid(u.transpose('ycoord', 'sigma', 'xcoord'),
sigma,
ps.transpose('ycoord', 'xcoord'),
self.hyam,
self.hybm,
p0=_p0,
method="linear")
nt.assert_array_almost_equal(
xh_expected.transpose('ncl2', 'ncl3', 'ncl1'), xh, 5)
def test_interp_sigma_to_hybrid_wrong_method(self, u, sigma, ps) -> None:
with pytest.raises(ValueError):
interp_sigma_to_hybrid(u,
sigma,
ps,
self.hyam,
self.hybm,
p0=_p0,
method="wrong_method")
class Test_interp_manually_calc:
@pytest.fixture(scope="class")
def test_input(self):
return xr.load_dataset(
gdf.get("netcdf_files/interpolation_test_input_data.nc"))
@pytest.fixture(scope="class")
def test_output(self):
return xr.load_dataset(
gdf.get("netcdf_files/interpolation_test_output_data.nc"))
def test_float32(self, test_input, test_output) -> None:
np.testing.assert_almost_equal(
test_output['normal'].values.astype(np.float32),
interp_multidim(xr.DataArray(
test_input['normal'].values.astype(np.float32),
dims=['lat', 'lon'],
coords={
'lat': test_input['normal']['lat'].values,
'lon': test_input['normal']['lon'].values,
}),
test_output['normal']['lat'].values,
test_output['normal']['lon'].values,
cyclic=True).values,
decimal=7)
def test_float64(self, test_input, test_output) -> None:
np.testing.assert_almost_equal(
test_output['normal'].values.astype(np.float64),
interp_multidim(
xr.DataArray(test_input['normal'].values.astype(np.float64),
dims=['lat', 'lon'],
coords={
'lat': test_input['normal']['lat'].values,
'lon': test_input['normal']['lon'].values,
}),
test_output['normal']['lat'].values,
test_output['normal']['lon'].values,
cyclic=True,
).values,
decimal=8,
)
def test_missing(self, test_input, test_output) -> None:
np.testing.assert_almost_equal(
test_output['missing'],
interp_multidim(
test_input['missing'],
test_output['normal']['lat'].values,
test_output['normal']['lon'].values,
cyclic=True,
).values,
decimal=8,
)
def test_nan(self, test_input, test_output) -> None:
np.testing.assert_almost_equal(
test_output['nan'],
interp_multidim(
test_input['nan'],
test_output['normal']['lat'].values,
test_output['normal']['lon'].values,
cyclic=True,
).values,
decimal=8,
)
def test_mask(self, test_input, test_output) -> None:
np.testing.assert_almost_equal(
test_output['mask'],
interp_multidim(
test_input['mask'],
test_output['normal']['lat'].values,
test_output['normal']['lon'].values,
cyclic=True,
).values,
decimal=8,
)
def test_2_nans(self, test_input, test_output) -> None:
np.testing.assert_almost_equal(
test_output['nan_2'],
interp_multidim(
test_input['nan_2'],
test_output['normal']['lat'].values,
test_output['normal']['lon'].values,
cyclic=True,
).values,
decimal=8,
)
def test_numpy(self, test_input, test_output) -> None:
np.testing.assert_almost_equal(
test_output['normal'].values,
interp_multidim(
test_input['normal'].values,
test_output['normal']['lat'].values,
test_output['normal']['lon'].values,
lat_in=test_input['normal']['lat'].values,
lon_in=test_input['normal']['lon'].values,
cyclic=True,
),
decimal=8)
def test_extrapolate(self, test_input, test_output) -> None:
np.testing.assert_almost_equal(test_output['normal'].values,
interp_multidim(
test_input['normal'],
test_output['normal']['lat'].values,
test_output['normal']['lon'].values,
cyclic=True,
fill_value='extrapolate',
),
decimal=8)
class Test_interp_larger_dataset:
@pytest.fixture(scope="class")
def test_input(self):
return xr.load_dataset(
gdf.get("netcdf_files/spherical_noise_input.nc"))['spherical_noise']
@pytest.fixture(scope="class")
def test_output(self):
return xr.load_dataset(gdf.get(
"netcdf_files/spherical_noise_output.nc"))['spherical_noise']
def test_10x(self, test_input, test_output) -> None:
data_xr = interp_multidim(test_input, test_output.coords['lat'],
test_output.coords['lon'])
np.testing.assert_almost_equal(
test_output,
data_xr.values,
decimal=8,
)
def test_chunked(self, test_input, test_output) -> None:
data_xr = interp_multidim(test_input.chunk(2),
test_output.coords['lat'],
test_output.coords['lon'])
np.testing.assert_almost_equal(test_output, data_xr.values, decimal=8)