-
Notifications
You must be signed in to change notification settings - Fork 422
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #786 from dopplershift/xarray-projections
Xarray + CF + CartoPy Projection Handling
- Loading branch information
Showing
15 changed files
with
683 additions
and
31 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
# Copyright (c) 2018 MetPy Developers. | ||
# Distributed under the terms of the BSD 3-Clause License. | ||
# SPDX-License-Identifier: BSD-3-Clause | ||
""" | ||
XArray Projection Handling | ||
========================== | ||
Use MetPy's XArray accessors to simplify opening a data file and plotting | ||
data on a map using CartoPy. | ||
""" | ||
import cartopy.feature as cfeature | ||
import matplotlib.pyplot as plt | ||
import xarray as xr | ||
|
||
# Ensure xarray accessors are available | ||
import metpy.io # noqa: F401 | ||
from metpy.testing import get_test_data | ||
|
||
ds = xr.open_dataset(get_test_data('narr_example.nc', as_file_obj=False)) | ||
data_var = ds.metpy.parse_cf('Temperature') | ||
|
||
x = data_var.x | ||
y = data_var.y | ||
im_data = data_var.isel(time=0).sel(isobaric=1000.) | ||
|
||
fig = plt.figure(figsize=(14, 14)) | ||
ax = fig.add_subplot(1, 1, 1, projection=data_var.metpy.cartopy_crs) | ||
|
||
ax.imshow(im_data, extent=(x.min(), x.max(), y.min(), y.max()), | ||
cmap='RdBu', origin='lower' if y[0] < y[-1] else 'upper') | ||
ax.coastlines(color='tab:green', resolution='10m') | ||
ax.add_feature(cfeature.LAKES.with_scale('10m'), facecolor='none', edgecolor='tab:blue') | ||
ax.add_feature(cfeature.RIVERS.with_scale('10m'), edgecolor='tab:blue') | ||
|
||
plt.show() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
# Copyright (c) 2018 MetPy Developers. | ||
# Distributed under the terms of the BSD 3-Clause License. | ||
# SPDX-License-Identifier: BSD-3-Clause | ||
"""Test the operation of MetPy's XArray accessors.""" | ||
|
||
import cartopy.crs as ccrs | ||
import numpy as np | ||
import pytest | ||
import xarray as xr | ||
|
||
# Get activate the xarray accessors | ||
import metpy.io # noqa: F401 | ||
from metpy.testing import assert_almost_equal, get_test_data | ||
from metpy.units import units | ||
|
||
|
||
@pytest.fixture | ||
def test_ds(): | ||
"""Provide an xarray dataset for testing.""" | ||
return xr.open_dataset(get_test_data('narr_example.nc', as_file_obj=False)) | ||
|
||
|
||
@pytest.fixture | ||
def test_var(): | ||
"""Provide a standard, parsed, variable for testing.""" | ||
ds = test_ds() | ||
return ds.metpy.parse_cf('Temperature') | ||
|
||
|
||
def test_projection(test_var): | ||
"""Test getting the proper projection out of the variable.""" | ||
crs = test_var.metpy.crs | ||
assert crs['grid_mapping_name'] == 'lambert_conformal_conic' | ||
|
||
assert isinstance(test_var.metpy.cartopy_crs, ccrs.LambertConformal) | ||
|
||
|
||
def test_no_projection(test_ds): | ||
"""Test getting the crs attribute when not available produces a sensible error.""" | ||
var = test_ds.lat | ||
with pytest.raises(AttributeError) as exc: | ||
var.metpy.crs | ||
|
||
assert 'not available' in str(exc.value) | ||
|
||
|
||
def test_units(test_var): | ||
"""Test unit handling through the accessor.""" | ||
arr = test_var.metpy.unit_array | ||
assert isinstance(arr, units.Quantity) | ||
assert arr.units == units.kelvin | ||
|
||
|
||
def test_convert_units(test_var): | ||
"""Test in-place conversion of units.""" | ||
test_var.metpy.convert_units('degC') | ||
|
||
# Check that variable metadata is updated | ||
assert test_var.attrs['units'] == 'degC' | ||
|
||
# Make sure we now get an array back with properly converted values | ||
assert test_var.metpy.unit_array.units == units.degC | ||
assert_almost_equal(test_var[0, 0, 0, 0], 18.44 * units.degC, 2) | ||
|
||
|
||
def test_radian_projection_coords(): | ||
"""Test fallback code for radian units in projection coordinate variables.""" | ||
proj = xr.DataArray(0, attrs={'grid_mapping_name': 'geostationary', | ||
'perspective_point_height': 3}) | ||
x = xr.DataArray(np.arange(3), | ||
attrs={'standard_name': 'projection_x_coordinate', 'units': 'radians'}) | ||
y = xr.DataArray(np.arange(2), | ||
attrs={'standard_name': 'projection_y_coordinate', 'units': 'radians'}) | ||
data = xr.DataArray(np.arange(6).reshape(2, 3), coords=(y, x), dims=('y', 'x'), | ||
attrs={'grid_mapping': 'fixedgrid_projection'}) | ||
ds = xr.Dataset({'data': data, 'fixedgrid_projection': proj}) | ||
|
||
# Check that the coordinates in this case are properly converted | ||
data_var = ds.metpy.parse_cf('data') | ||
assert data_var.coords['x'].metpy.unit_array[1] == 3 * units.meter | ||
assert data_var.coords['y'].metpy.unit_array[1] == 3 * units.meter | ||
|
||
|
||
def test_missing_grid_mapping(): | ||
"""Test falling back to implicit lat/lon projection.""" | ||
lon = xr.DataArray(-np.arange(3), | ||
attrs={'standard_name': 'longitude', 'units': 'degrees_east'}) | ||
lat = xr.DataArray(np.arange(2), | ||
attrs={'standard_name': 'latitude', 'units': 'degrees_north'}) | ||
data = xr.DataArray(np.arange(6).reshape(2, 3), coords=(lat, lon), dims=('y', 'x')) | ||
ds = xr.Dataset({'data': data}) | ||
|
||
data_var = ds.metpy.parse_cf('data') | ||
assert 'crs' in data_var.coords | ||
|
||
|
||
def test_missing_grid_mapping_var(): | ||
"""Test behavior when we can't find the variable pointed to by grid_mapping.""" | ||
x = xr.DataArray(np.arange(3), | ||
attrs={'standard_name': 'projection_x_coordinate', 'units': 'radians'}) | ||
y = xr.DataArray(np.arange(2), | ||
attrs={'standard_name': 'projection_y_coordinate', 'units': 'radians'}) | ||
data = xr.DataArray(np.arange(6).reshape(2, 3), coords=(y, x), dims=('y', 'x'), | ||
attrs={'grid_mapping': 'fixedgrid_projection'}) | ||
ds = xr.Dataset({'data': data}) | ||
|
||
with pytest.warns(UserWarning, match='Could not find'): | ||
ds.metpy.parse_cf('data') |
Oops, something went wrong.