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

Fix swath builtin coordinates not being used #1541

Merged
merged 5 commits into from
Feb 12, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
58 changes: 35 additions & 23 deletions satpy/readers/yaml_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -775,33 +775,45 @@ def _get_file_handlers(self, dsid):
def _make_area_from_coords(self, coords):
"""Create an appropriate area with the given *coords*."""
if len(coords) == 2:
lon_sn = coords[0].attrs.get('standard_name')
lat_sn = coords[1].attrs.get('standard_name')
if lon_sn == 'longitude' and lat_sn == 'latitude':
key = None
try:
key = (coords[0].data.name, coords[1].data.name)
sdef = self.coords_cache.get(key)
except AttributeError:
sdef = None
if sdef is None:
sdef = SwathDefinition(*coords)
sensor_str = '_'.join(self.info['sensors'])
shape_str = '_'.join(map(str, coords[0].shape))
sdef.name = "{}_{}_{}_{}".format(sensor_str, shape_str,
coords[0].attrs['name'],
coords[1].attrs['name'])
if key is not None:
self.coords_cache[key] = sdef
return sdef
else:
raise ValueError(
'Coordinates info object missing standard_name key: ' +
str(coords))
lats, lons = self._get_lons_lats_from_coords(coords)

sdef = self._make_swath_definition_from_lons_lats(lons, lats)
return sdef
elif len(coords) != 0:
raise NameError("Don't know what to do with coordinates " + str(
coords))

def _get_lons_lats_from_coords(self, coords):
"""Get lons and lats from the coords list."""
lons, lats = None, None
for coord in coords:
if coord.attrs.get('standard_name') == 'longitude':
lons = coord
elif coord.attrs.get('standard_name') == 'latitude':
lats = coord
if lons is None or lats is None:
raise ValueError('Missing longitude or latitude coordinate: ' + str(coords))
return lats, lons
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick, the return value is the opposite of the method name. Prefer lon, lats I think.


def _make_swath_definition_from_lons_lats(self, lons, lats):
"""Make a swath definition instance from lons and lats."""
key = None
try:
key = (lons.data.name, lats.data.name)
sdef = self.coords_cache.get(key)
except AttributeError:
sdef = None
if sdef is None:
sdef = SwathDefinition(lons, lats)
sensor_str = '_'.join(self.info['sensors'])
shape_str = '_'.join(map(str, lons.shape))
sdef.name = "{}_{}_{}_{}".format(sensor_str, shape_str,
lons.attrs.get('name', lons.name),
lats.attrs.get('name', lats.name))
if key is not None:
self.coords_cache[key] = sdef
return sdef

def _load_dataset_area(self, dsid, file_handlers, coords, **kwargs):
"""Get the area for *dsid*."""
try:
Expand Down
38 changes: 20 additions & 18 deletions satpy/tests/reader_tests/test_satpy_cf_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,14 @@
# satpy. If not, see <http://www.gnu.org/licenses/>.
"""Tests for the CF reader."""

import unittest
import os
import unittest
from contextlib import suppress
from datetime import datetime
import xarray as xr

import numpy as np
import xarray as xr

from satpy import Scene
from satpy.readers.satpy_cf_nc import SatpyCFFileHandler

Expand Down Expand Up @@ -85,25 +88,24 @@ def setUp(self):

def test_write_and_read(self):
"""Save a file with cf_writer and read the data again."""
# '{testin}-{sensor}-{start_time:%Y%m%d%H%M%S}-{end_time:%Y%m%d%H%M%S}.nc'
filename = 'testingcfwriter{:s}-viirs-mband-20201007075915-20201007080744.nc'.format(
datetime.utcnow().strftime('%Y%j%H%M%S'))
self.scene.save_datasets(writer='cf',
filename=filename,
header_attrs={'instrument': 'avhrr'},
engine='h5netcdf',
flatten_attrs=True,
pretty=True)
scn_ = Scene(reader='satpy_cf_nc',
filenames=[filename])
scn_.load(['image0', 'image1', 'lat'])
self.assertTrue(np.all(scn_['image0'].data == self.scene['image0'].data))
self.assertTrue(np.all(scn_['lat'].data == self.scene['lat'].data)) # lat loaded as dataset
self.assertTrue(np.all(scn_['image0'].coords['lon'] == self.scene['lon'].data)) # lon loded as coord
try:
os.remove(filename)
except PermissionError:
pass
self.scene.save_datasets(writer='cf',
filename=filename,
header_attrs={'instrument': 'avhrr'},
engine='h5netcdf',
flatten_attrs=True,
pretty=True)
scn_ = Scene(reader='satpy_cf_nc',
filenames=[filename])
scn_.load(['image0', 'image1', 'lat'])
self.assertTrue(np.all(scn_['image0'].data == self.scene['image0'].data))
self.assertTrue(np.all(scn_['lat'].data == self.scene['lat'].data)) # lat loaded as dataset
self.assertTrue(np.all(scn_['image0'].coords['lon'] == self.scene['lon'].data)) # lon loded as coord
finally:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, never seen a try without an except. So any exceptions raise before finally is kind of ignored with this approach? Instead of

except:
  pass

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, the exception isn't ignored, but 'finally' ensures its part of the code is executed before raising the exception.

with suppress(PermissionError):
os.remove(filename)

def test_fix_modifier_attr(self):
"""Check that fix modifier can handle empty list as modifier attribute."""
Expand Down
58 changes: 35 additions & 23 deletions satpy/tests/test_yaml_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
from satpy.readers.file_handlers import BaseFileHandler
from satpy.dataset import DataQuery
from satpy.tests.utils import make_dataid
import xarray as xr
import numpy as np


class FakeFH(BaseFileHandler):
Expand Down Expand Up @@ -504,41 +506,51 @@ def setUp(self):
'start_time': datetime(2000, 1, 1),
'end_time': datetime(2000, 1, 2),
})

def test_load_dataset_with_builtin_coords(self):
"""Test loading a dataset with builtin coordinates."""
fake_fh = FakeFH(None, None)
import xarray as xr
import numpy as np
lons = xr.DataArray(np.ones((2, 2)) * 2,
dims=['y', 'x'],
attrs={'standard_name': 'longitude',
'name': 'longitude'})
lats = xr.DataArray(np.ones((2, 2)) * 2,
dims=['y', 'x'],
attrs={'standard_name': 'latitude',
'name': 'latitude'})
data = xr.DataArray(np.ones((2, 2)),
coords={'longitude': lons,
'latitude': lats},
dims=['y', 'x'])
self.lons = xr.DataArray(np.ones((2, 2)) * 2,
dims=['y', 'x'],
attrs={'standard_name': 'longitude',
'name': 'longitude'})
self.lats = xr.DataArray(np.ones((2, 2)) * 2,
dims=['y', 'x'],
attrs={'standard_name': 'latitude',
'name': 'latitude'})
self.data = None

def _assign_array(dsid, *_args, **_kwargs):
if dsid['name'] == 'longitude':
return lons
return self.lons
elif dsid['name'] == 'latitude':
return lats
return self.lats

return data
return self.data

fake_fh.get_dataset.side_effect = _assign_array
self.reader.file_handlers = {'ftype1': [fake_fh]}

res = self.reader.load(['ch01'])
def test_load_dataset_with_builtin_coords(self):
"""Test loading a dataset with builtin coordinates."""
self.data = xr.DataArray(np.ones((2, 2)),
coords={'longitude': self.lons,
'latitude': self.lats},
dims=['y', 'x'])

self._check_area_for_ch01()

def test_load_dataset_with_builtin_coords_in_wrong_order(self):
"""Test loading a dataset with builtin coordinates in the wrong order."""
self.data = xr.DataArray(np.ones((2, 2)),
coords={'latitude': self.lats,
'longitude': self.lons},
dims=['y', 'x'])

self._check_area_for_ch01()

def _check_area_for_ch01(self):
res = self.reader.load(['ch01'])
assert 'area' in res['ch01'].attrs
np.testing.assert_array_equal(res['ch01'].attrs['area'].lons, lons)
np.testing.assert_array_equal(res['ch01'].attrs['area'].lats, lats)
np.testing.assert_array_equal(res['ch01'].attrs['area'].lons, self.lons)
np.testing.assert_array_equal(res['ch01'].attrs['area'].lats, self.lats)


class TestFileFileYAMLReaderMultipleFileTypes(unittest.TestCase):
Expand Down