Skip to content

Commit

Permalink
Merge pull request #1392 from joleenf/iss1371
Browse files Browse the repository at this point in the history
Remove 1-D lat/lon variables from mimic reader's available datasets
  • Loading branch information
djhoese committed Oct 23, 2020
2 parents e99413a + 57aa58f commit 446e24e
Show file tree
Hide file tree
Showing 6 changed files with 589 additions and 592 deletions.
288 changes: 287 additions & 1 deletion satpy/enhancements/mimic.py

Large diffs are not rendered by default.

647 changes: 89 additions & 558 deletions satpy/etc/enhancements/mimic.yaml

Large diffs are not rendered by default.

16 changes: 0 additions & 16 deletions satpy/etc/readers/mimicTPW2_comp.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,3 @@ file_types:
file_patterns: ['comp{start_time:%Y%m%d.%H%M%S}.nc']
sensor: ['mimic']
platform_name: ['microwave']

datasets:
latArr:
name: 'latitude'
units: degrees_north
file_key: latArr
standard_name: latitude
coordinates: [ latitude ]
file_type: mimicTPW2_comp
lonArr:
name: 'longitude'
units: degrees_east
file_key: lonArr
standard_name: longitude
coordinates: [ longitude ]
file_type: mimicTPW2_comp
15 changes: 9 additions & 6 deletions satpy/readers/mimic_TPW2_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,14 @@

logger = logging.getLogger(__name__)


class MimicTPW2FileHandler(NetCDF4FileHandler):
"""NetCDF4 reader for MIMC TPW."""

def __init__(self, filename, filename_info, filetype_info):
"""Initialize the reader."""
super(MimicTPW2FileHandler, self).__init__(filename, filename_info, filetype_info)
super(MimicTPW2FileHandler, self).__init__(filename, filename_info,
filetype_info,
xarray_kwargs={"decode_times": False})

def available_datasets(self, configured_datasets=None):
"""Get datasets in file matching gelocation shape (lat/lon)."""
Expand Down Expand Up @@ -113,6 +114,7 @@ def get_dataset(self, ds_id, info):
data.rename({'lon': 'x'})
if 'lat' in data.dims:
data.rename({'lat': 'y'})

return data

def get_area_def(self, dsid):
Expand All @@ -130,11 +132,11 @@ def get_area_def(self, dsid):
upper_right_x = latlon[0][0][width-1]

area_extent = (lower_left_x, lower_left_y, upper_right_x, upper_right_y)
description = "MIMIC TPW Equirectangular Projection"
description = "MIMIC TPW WGS84"
area_id = 'mimic'
proj_id = 'equirectangular'
proj_dict = {'proj': 'longlat', 'datum': 'WGS84', 'ellps': 'WGS84', }
area_def = AreaDefinition(area_id, description, proj_id, proj_dict, width, height, area_extent, )
proj_id = 'World Geodetic System 1984'
projection = 'EPSG:4326'
area_def = AreaDefinition(area_id, description, proj_id, projection, width, height, area_extent, )
return area_def

def get_metadata(self, data, info):
Expand All @@ -148,6 +150,7 @@ def get_metadata(self, data, info):
'start_time': self.start_time,
'end_time': self.end_time,
})
metadata.update(self[info.get('file_key')].variable.attrs)

return metadata

Expand Down
192 changes: 192 additions & 0 deletions satpy/tests/reader_tests/test_mimic_TPW2_lowres.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Satpy developers
#
# This file is part of Satpy.
#
# Satpy is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# Satpy is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# Satpy. If not, see <http://www.gnu.org/licenses/>.
"""Module for testing the satpy.readers.tropomi_l2 module."""

import os
import unittest
import itertools
from unittest import mock
from datetime import datetime
import numpy as np
from satpy.tests.reader_tests.test_netcdf_utils import FakeNetCDF4FileHandler
import xarray as xr

DEFAULT_FILE_DTYPE = np.float32
DEFAULT_FILE_SHAPE = (721, 1440)
DEFAULT_DATE = datetime(2019, 6, 19, 13, 0)
DEFAULT_LAT = np.linspace(-90, 90, DEFAULT_FILE_SHAPE[0], dtype=DEFAULT_FILE_DTYPE)
DEFAULT_LON = np.linspace(-180, 180, DEFAULT_FILE_SHAPE[1], dtype=DEFAULT_FILE_DTYPE)
DEFAULT_FILE_FLOAT_DATA = np.arange(DEFAULT_FILE_SHAPE[0] * DEFAULT_FILE_SHAPE[1],
dtype=DEFAULT_FILE_DTYPE)
DEFAULT_FILE_DATE_DATA = np.clip(DEFAULT_FILE_FLOAT_DATA, 0, 1049)
DEFAULT_FILE_UBYTE_DATA = np.arange(DEFAULT_FILE_SHAPE[0] * DEFAULT_FILE_SHAPE[1],
dtype=np.ubyte)
float_variables = ['tpwGrid', 'tpwGridPrior', 'tpwGridSubseq', 'footGridPrior', 'footGridSubseq']
date_variables = ['timeAwayGridPrior', 'timeAwayGridSubseq']
ubyte_variables = ['satGridPrior', 'satGridSubseq']
file_content_attr = dict()


class FakeNetCDF4FileHandlerMimicLow(FakeNetCDF4FileHandler):
"""Swap-in NetCDF4 File Handler."""

def get_test_content(self, filename, filename_info, filetype_info):
"""Mimic reader input file content for lower resolution files."""
dt_s = filename_info.get('start_time', DEFAULT_DATE)
dt_e = filename_info.get('end_time', DEFAULT_DATE)

if filetype_info['file_type'] == 'mimicTPW2_comp':
file_content = {
'/attr/start_time': dt_s.strftime('%Y%m%d.%H%M%S'),
'/attr/end_time': dt_e.strftime('%Y%m%d.%H%M%S'),
'/attr/platform_shortname': 'aggregated microwave',
'/attr/sensor': 'mimic',
}
file_content['latArr'] = DEFAULT_LAT
file_content['latArr/shape'] = (DEFAULT_FILE_SHAPE[0],)
file_content['latArr/attr/units'] = 'degress_north'

file_content['lonArr'] = DEFAULT_LON
file_content['lonArr/shape'] = (DEFAULT_FILE_SHAPE[1],)
file_content['lonArr/attr/units'] = 'degrees_east'

file_content['/dimension/lat'] = DEFAULT_FILE_SHAPE[0]
file_content['/dimension/lon'] = DEFAULT_FILE_SHAPE[1]

for float_var in float_variables:
file_content[float_var] = DEFAULT_FILE_FLOAT_DATA.reshape(DEFAULT_FILE_SHAPE)
file_content['{}/shape'.format(float_var)] = DEFAULT_FILE_SHAPE
file_content_attr[float_var] = {"units": "mm"}
for date_var in date_variables:
file_content[date_var] = DEFAULT_FILE_DATE_DATA.reshape(DEFAULT_FILE_SHAPE)
file_content['{}/shape'.format(date_var)] = DEFAULT_FILE_SHAPE
file_content_attr[date_var] = {"units": "minutes"}
for ubyte_var in ubyte_variables:
file_content[ubyte_var] = DEFAULT_FILE_UBYTE_DATA.reshape(DEFAULT_FILE_SHAPE)
file_content['{}/shape'.format(ubyte_var)] = DEFAULT_FILE_SHAPE
file_content_attr[ubyte_var] = {"source_key": "Key: 0: None, 1: NOAA-N, 2: NOAA-P, 3: Metop-A, \
4: Metop-B, 5: SNPP, 6: SSMI-17, 7: SSMI-18"}

# convert to xarrays
for key, val in file_content.items():
if key == 'lonArr' or key == 'latArr':
file_content[key] = xr.DataArray(val)
elif isinstance(val, np.ndarray):
if val.ndim > 1:
file_content[key] = xr.DataArray(val, dims=('y', 'x'), attrs=file_content_attr[key])
else:
file_content[key] = xr.DataArray(val)
for key in itertools.chain(float_variables, ubyte_variables):
file_content[key].attrs['_FillValue'] = -999.0
file_content[key].attrs['name'] = key
file_content[key].attrs['file_key'] = key
file_content[key].attrs['file_type'] = self.filetype_info['file_type']
else:
msg = 'Wrong Test Reader for file_type {}'.format(filetype_info['file_type'])
raise AssertionError(msg)

return file_content


class TestMimicTPW2Reader(unittest.TestCase):
"""Test Mimic Reader."""

yaml_file = "mimicTPW2_comp.yaml"

def setUp(self):
"""Wrap NetCDF4 file handler with our own fake handler."""
from satpy.config import config_search_paths
from satpy.readers.mimic_TPW2_nc import MimicTPW2FileHandler
self.reader_configs = config_search_paths(os.path.join('readers', self.yaml_file))
# http://stackoverflow.com/questions/12219967/how-to-mock-a-base-class-with-python-mock-library
self.p = mock.patch.object(MimicTPW2FileHandler, '__bases__', (FakeNetCDF4FileHandlerMimicLow,))
self.fake_handler = self.p.start()
self.p.is_local = True

def tearDown(self):
"""Stop wrapping the NetCDF4 file handler."""
self.p.stop()

def test_init(self):
"""Test basic initialization of this reader."""
from satpy.readers import load_reader
r = load_reader(self.reader_configs)
loadables = r.select_files_from_pathnames([
'comp20190619.130000.nc',
])
self.assertEqual(len(loadables), 1)
r.create_filehandlers(loadables)
# make sure we have some files
self.assertTrue(r.file_handlers)

def test_load_mimic_float(self):
"""Load TPW mimic float data."""
from satpy.readers import load_reader
r = load_reader(self.reader_configs)
with mock.patch('satpy.readers.mimic_TPW2_nc.netCDF4.Variable', xr.DataArray):
loadables = r.select_files_from_pathnames([
'comp20190619.130000.nc',
])
r.create_filehandlers(loadables)
ds = r.load(float_variables)
self.assertEqual(len(ds), len(float_variables))
for d in ds.values():
self.assertEqual(d.attrs['platform_shortname'], 'aggregated microwave')
self.assertEqual(d.attrs['sensor'], 'mimic')
self.assertEqual(d.attrs['units'], 'mm')
self.assertIn('area', d.attrs)
self.assertIsNotNone(d.attrs['area'])

def test_load_mimic_timedelta(self):
"""Load TPW mimic timedelta data (data latency variables)."""
from satpy.readers import load_reader
r = load_reader(self.reader_configs)
with mock.patch('satpy.readers.mimic_TPW2_nc.netCDF4.Variable', xr.DataArray):
loadables = r.select_files_from_pathnames([
'comp20190619.130000.nc',
])
r.create_filehandlers(loadables)
ds = r.load(date_variables)
self.assertEqual(len(ds), len(date_variables))
for d in ds.values():
self.assertEqual(d.attrs['platform_shortname'], 'aggregated microwave')
self.assertEqual(d.attrs['sensor'], 'mimic')
self.assertEqual(d.attrs['units'], 'minutes')
self.assertIn('area', d.attrs)
self.assertIsNotNone(d.attrs['area'])
self.assertEqual(d.dtype, DEFAULT_FILE_DTYPE)

def test_load_mimic_ubyte(self):
"""Load TPW mimic sensor grids."""
from satpy.readers import load_reader
r = load_reader(self.reader_configs)
with mock.patch('satpy.readers.mimic_TPW2_nc.netCDF4.Variable', xr.DataArray):
loadables = r.select_files_from_pathnames([
'comp20190619.130000.nc',
])
r.create_filehandlers(loadables)
ds = r.load(ubyte_variables)
self.assertEqual(len(ds), len(ubyte_variables))
for d in ds.values():
self.assertEqual(d.attrs['platform_shortname'], 'aggregated microwave')
self.assertEqual(d.attrs['sensor'], 'mimic')
self.assertIn('source_key', d.attrs)
self.assertIn('area', d.attrs)
self.assertIsNotNone(d.attrs['area'])
self.assertEqual(d.dtype, np.uint8)
23 changes: 12 additions & 11 deletions satpy/tests/reader_tests/test_mimic_TPW2_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@
DEFAULT_LON = np.linspace(-180, 180, DEFAULT_FILE_SHAPE[1], dtype=DEFAULT_FILE_DTYPE)
DEFAULT_FILE_DATA = np.arange(DEFAULT_FILE_SHAPE[0] * DEFAULT_FILE_SHAPE[1],
dtype=DEFAULT_FILE_DTYPE).reshape(DEFAULT_FILE_SHAPE)
file_content_units = dict()


class FakeNetCDF4FileHandlerMimic(FakeNetCDF4FileHandler):
"""Swap-in NetCDF4 File Handler"""
"""Swap-in NetCDF4 File Handler."""

def get_test_content(self, filename, filename_info, filetype_info):
"""Mimic reader input file content"""
"""Mimic reader input file content."""
from xarray import DataArray
dt_s = filename_info.get('start_time', datetime(2019, 6, 19, 13, 0))
dt_e = filename_info.get('end_time', datetime(2019, 6, 19, 13, 0))
Expand All @@ -60,6 +62,7 @@ def get_test_content(self, filename, filename_info, filetype_info):

file_content['tpwGrid'] = DEFAULT_FILE_DATA
file_content['tpwGrid/shape'] = DEFAULT_FILE_SHAPE
file_content_units['tpwGrid'] = 'mm'

file_content['/dimension/lat'] = DEFAULT_FILE_SHAPE[0]
file_content['/dimension/lon'] = DEFAULT_FILE_SHAPE[1]
Expand All @@ -70,13 +73,9 @@ def get_test_content(self, filename, filename_info, filetype_info):
file_content[key] = DataArray(val)
elif isinstance(val, np.ndarray):
if val.ndim > 1:
file_content[key] = DataArray(val, dims=('y', 'x'))
file_content[key] = DataArray(val, dims=('y', 'x'), attrs={"units": file_content_units[key]})
else:
file_content[key] = DataArray(val)
file_content['tpwGrid'].attrs['_FillValue'] = -999.0
file_content['tpwGrid'].attrs['name'] = 'tpwGrid'
file_content['tpwGrid'].attrs['file_key'] = 'tpwGrid'
file_content['tpwGrid'].attrs['file_type'] = self.filetype_info['file_type']
else:
msg = 'Wrong Test Reader for file_type {}'.format(filetype_info['file_type'])
raise AssertionError(msg)
Expand All @@ -85,11 +84,12 @@ def get_test_content(self, filename, filename_info, filetype_info):


class TestMimicTPW2Reader(unittest.TestCase):
"""Test Mimic Reader"""
"""Test Mimic Reader."""

yaml_file = "mimicTPW2_comp.yaml"

def setUp(self):
"""Wrap NetCDF4 file handler with our own fake handler"""
"""Wrap NetCDF4 file handler with our own fake handler."""
from satpy.config import config_search_paths
from satpy.readers.mimic_TPW2_nc import MimicTPW2FileHandler
self.reader_configs = config_search_paths(os.path.join('readers', self.yaml_file))
Expand All @@ -99,7 +99,7 @@ def setUp(self):
self.p.is_local = True

def tearDown(self):
"""Stop wrapping the NetCDF4 file handler"""
"""Stop wrapping the NetCDF4 file handler."""
self.p.stop()

def test_init(self):
Expand All @@ -115,7 +115,7 @@ def test_init(self):
self.assertTrue(r.file_handlers)

def test_load_mimic(self):
"""Load Mimic data"""
"""Load Mimic data."""
from satpy.readers import load_reader
r = load_reader(self.reader_configs)
with mock.patch('satpy.readers.mimic_TPW2_nc.netCDF4.Variable', xr.DataArray):
Expand All @@ -129,4 +129,5 @@ def test_load_mimic(self):
self.assertEqual(d.attrs['platform_shortname'], 'aggregated microwave')
self.assertEqual(d.attrs['sensor'], 'mimic')
self.assertIn('area', d.attrs)
self.assertIn('units', d.attrs)
self.assertIsNotNone(d.attrs['area'])

0 comments on commit 446e24e

Please sign in to comment.