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/supress warnings in reader tests #2689

Merged
merged 36 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
8f3704b
Use importlib.resources to read packaged data
pnuu Dec 12, 2023
66bc5b5
Use nanosecond precision times in MVIRI FIDUCEO tests
pnuu Dec 12, 2023
372e1c9
Filter out pyproj warnings
pnuu Dec 12, 2023
5b7bbe7
Suppress PROJ4 UserWarning on lost accuracy
pnuu Dec 13, 2023
e3160bf
Use modern chunk size setting in nwcsaf_nc reader
pnuu Dec 13, 2023
fbb4373
Use DataArray.drop_vars() instead of deprecated .drop()
pnuu Dec 13, 2023
43b2c20
Use datetime64[ns] for JMA HRIT readers
pnuu Dec 13, 2023
566ab73
Use datetime64[ns] in GOES imager netCDF reader tests
pnuu Dec 13, 2023
a574c51
Use datetime[ns] in SEVIRI HRIT tests
pnuu Dec 13, 2023
8b7c841
Use datetime[ns] in SEVIRI native tests
pnuu Dec 13, 2023
822f04b
Use datetime[ns] in SEVIRI netCDF4 tests
pnuu Dec 13, 2023
a50c44a
Fix mj2datetime64 usage after nanosecond update
pnuu Dec 13, 2023
399086e
Use datetime64[ns] in GOES imager EUM test
pnuu Dec 13, 2023
e450aed
Merge branch 'main' into reader-warnings
pnuu Dec 13, 2023
05a9a0b
Use .item() to get singleton array elements in GOES imager readers
pnuu Dec 13, 2023
71d842f
Use .item() to get singleton array elements in EUM reader base
pnuu Dec 13, 2023
6dd9c42
Fix/supress PROJ4 warnings
pnuu Dec 14, 2023
d82bc6c
Handle UserWarnings from unmatching header blocks and observation times
pnuu Dec 14, 2023
5a84efd
Fix deprecated proj string property
pnuu Dec 14, 2023
1225b07
Filter orbit polynomial warning in tests
pnuu Dec 14, 2023
88fe02c
Fix DeprecationWarning of empty Numpy array falsy with list support
pnuu Dec 14, 2023
0c2d5dd
Catch missing radiance adjustment warnings
pnuu Dec 14, 2023
1057aab
Fix expected proj string
pnuu Dec 14, 2023
e9e8518
Fix pytest.raises() to pytest.warns()
pnuu Dec 14, 2023
1b57de0
Handle more orbit polynomial warnings
pnuu Dec 14, 2023
bdbf3f9
Fix proj authority usage
pnuu Dec 14, 2023
d0dd78e
Suppress warning about missing DataArray coordinate in test data saving
pnuu Dec 14, 2023
8811914
Silence warning about PNG not having geolocation information
pnuu Dec 14, 2023
b2e9841
Use width and height attributes instead of x/y_size
pnuu Dec 14, 2023
b497415
Get number of lines/columns from .sizes attribute
pnuu Dec 14, 2023
7b56afa
Make HRPT navigation timezone ignorant
pnuu Dec 14, 2023
d0993fd
Convert floats and ints to match the nc.Variable datatype
pnuu Dec 14, 2023
2da1840
Move AreaDefinition.from_cf() PROJ warning suppression to Pyresample
pnuu Dec 14, 2023
24422ad
Use CRS objects for testing area equality
pnuu Dec 14, 2023
d8af768
Use CRS objects as much as possible instead of suppressing the warnings
pnuu Dec 14, 2023
850b46e
Add missing projection parameter
pnuu Dec 14, 2023
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
8 changes: 4 additions & 4 deletions satpy/readers/ahi_l2_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,8 @@ def __init__(self, filename, filename_info, filetype_info):
raise ValueError("File is not a full disk scene")

self.sensor = self.nc.attrs["instrument_name"].lower()
self.nlines = self.nc.dims["Columns"]
self.ncols = self.nc.dims["Rows"]
self.nlines = self.nc.sizes["Columns"]
self.ncols = self.nc.sizes["Rows"]
self.platform_name = self.nc.attrs["satellite_name"]
self.platform_shortname = filename_info["platform"]
self._meta = None
Expand All @@ -100,8 +100,8 @@ def get_dataset(self, key, info):
# Data has 'Latitude' and 'Longitude' coords, these must be replaced.
variable = variable.rename({"Rows": "y", "Columns": "x"})

variable = variable.drop("Latitude")
variable = variable.drop("Longitude")
variable = variable.drop_vars("Latitude")
variable = variable.drop_vars("Longitude")

variable.attrs.update(key.to_dict())
return variable
Expand Down
8 changes: 4 additions & 4 deletions satpy/readers/eum_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,14 @@ def timecds2datetime(tcds):

Works both with a dictionary and a numpy record_array.
"""
days = int(tcds["Days"])
milliseconds = int(tcds["Milliseconds"])
days = int(tcds["Days"].item())
milliseconds = int(tcds["Milliseconds"].item())
try:
microseconds = int(tcds["Microseconds"])
microseconds = int(tcds["Microseconds"].item())
except (KeyError, ValueError):
microseconds = 0
try:
microseconds += int(tcds["Nanoseconds"]) / 1000.
microseconds += int(tcds["Nanoseconds"].item()) / 1000.
except (KeyError, ValueError):
pass

Expand Down
8 changes: 4 additions & 4 deletions satpy/readers/fci_l2_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ def _construct_area_def(self, dataset_id):
# Construct area definition from standardized area definition.
stand_area_def = get_area_def(area_naming["area_id"])

if (stand_area_def.x_size != self.ncols) | (stand_area_def.y_size != self.nlines):
if (stand_area_def.width != self.ncols) | (stand_area_def.height != self.nlines):
raise NotImplementedError("Unrecognised AreaDefinition.")

mod_area_extent = self._modify_area_extent(stand_area_def.area_extent)
Expand All @@ -381,9 +381,9 @@ def _construct_area_def(self, dataset_id):
stand_area_def.area_id,
stand_area_def.description,
"",
stand_area_def.proj_dict,
stand_area_def.x_size,
stand_area_def.y_size,
stand_area_def.crs,
stand_area_def.width,
stand_area_def.height,
mod_area_extent)

return area_def
Expand Down
3 changes: 1 addition & 2 deletions satpy/readers/geocat.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
import numpy as np
from pyproj import Proj
from pyresample import geometry
from pyresample.utils import proj4_str_to_dict

from satpy.readers.netcdf_utils import NetCDF4FileHandler, netCDF4

Expand Down Expand Up @@ -274,7 +273,7 @@ def get_area_def(self, dsid):
area_name,
area_name,
area_name,
proj4_str_to_dict(proj),
proj,
lon.shape[1],
lon.shape[0],
area_extent=extents,
Expand Down
2 changes: 1 addition & 1 deletion satpy/readers/gms/gms5_vissr_l1b.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def _get_orbital_parameters(self):
}

def _get_time_parameters(self):
start_time = mjd2datetime64(self._mode_block["observation_time_mjd"])
start_time = mjd2datetime64(self._mode_block["observation_time_mjd"]).astype("datetime64[us]")
start_time = start_time.astype(dt.datetime).replace(second=0, microsecond=0)
end_time = start_time + dt.timedelta(
minutes=25
Expand Down
18 changes: 9 additions & 9 deletions satpy/readers/goes_imager_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,12 +615,12 @@ def __init__(self, filename, filename_info, filetype_info, geo_data=None):
mask_and_scale=False,
chunks={"xc": CHUNK_SIZE, "yc": CHUNK_SIZE})
self.sensor = "goes_imager"
self.nlines = self.nc.dims["yc"]
self.ncols = self.nc.dims["xc"]
self.nlines = self.nc.sizes["yc"]
self.ncols = self.nc.sizes["xc"]
self.platform_name = self._get_platform_name(
self.nc.attrs["Satellite Sensor"])
self.platform_shortname = self.platform_name.replace("-", "").lower()
self.gvar_channel = int(self.nc["bands"].values)
self.gvar_channel = int(self.nc["bands"].item())
self.sector = self._get_sector(channel=self.gvar_channel,
nlines=self.nlines,
ncols=self.ncols)
Expand Down Expand Up @@ -731,9 +731,9 @@ def _get_area_def_uniform_sampling(self, lon0, channel):
def start_time(self):
"""Start timestamp of the dataset."""
dt = self.nc["time"].dt
return datetime(year=int(dt.year), month=int(dt.month), day=int(dt.day),
hour=int(dt.hour), minute=int(dt.minute),
second=int(dt.second), microsecond=int(dt.microsecond))
return datetime(year=int(dt.year.item()), month=int(dt.month.item()), day=int(dt.day.item()),
hour=int(dt.hour.item()), minute=int(dt.minute.item()),
second=int(dt.second.item()), microsecond=int(dt.microsecond.item()))

@property
def end_time(self):
Expand Down Expand Up @@ -1087,7 +1087,7 @@ def get_dataset(self, key, info):

# Set proper dimension names
data = data.rename({"xc": "x", "yc": "y"})
data = data.drop("time")
data = data.drop_vars("time")

# Update metadata
self._update_metadata(data, ds_info=info)
Expand Down Expand Up @@ -1124,8 +1124,8 @@ def __init__(self, filename, filename_info, filetype_info):
mask_and_scale=False,
chunks={"xc": CHUNK_SIZE, "yc": CHUNK_SIZE})
self.sensor = "goes_imager"
self.nlines = self.nc.dims["yc"]
self.ncols = self.nc.dims["xc"]
self.nlines = self.nc.sizes["yc"]
self.ncols = self.nc.sizes["xc"]
self.platform_name = GOESNCBaseFileHandler._get_platform_name(
self.nc.attrs["Satellite Sensor"])
self.platform_shortname = self.platform_name.replace("-", "").lower()
Expand Down
7 changes: 4 additions & 3 deletions satpy/readers/hrit_jma.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,10 @@
def mjd2datetime64(mjd):
"""Convert Modified Julian Day (MJD) to datetime64."""
epoch = np.datetime64("1858-11-17 00:00")
day2usec = 24 * 3600 * 1E6
mjd_usec = (mjd * day2usec).astype(np.int64).astype("timedelta64[us]")
return epoch + mjd_usec
day2nsec = 24 * 3600 * 1E9
mjd_nsec = (mjd * day2nsec).astype(np.int64).astype("timedelta64[ns]")

return epoch + mjd_nsec


class HRITJMAFileHandler(HRITFileHandler):
Expand Down
4 changes: 2 additions & 2 deletions satpy/readers/hrpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def time_seconds(tc_array, year):
word = tc_array[:, 3]
msecs += word & 1023
return (np.datetime64(
str(year) + "-01-01T00:00:00Z", "s") +
str(year) + "-01-01T00:00:00", "s") +
msecs[:].astype("timedelta64[ms]") +
(day - 1)[:].astype("timedelta64[D]"))

Expand Down Expand Up @@ -224,7 +224,7 @@ def calibrate_solar_channel(self, data, key):
"""Calibrate a solar channel."""
from pygac.calibration import calibrate_solar
julian_days = ((np.datetime64(self.start_time)
- np.datetime64(str(self.year) + "-01-01T00:00:00Z"))
- np.datetime64(str(self.year) + "-01-01T00:00:00"))
/ np.timedelta64(1, "D"))
data = calibrate_solar(data, _get_channel_index(key), self.year, julian_days,
self.calibrator)
Expand Down
12 changes: 6 additions & 6 deletions satpy/readers/mirs.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"""Interface to MiRS product."""

import datetime
import importlib
import logging
import os
from collections import Counter
Expand All @@ -34,13 +35,12 @@
LOG = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

try:
# try getting setuptools/distribute's version of resource retrieval first
from pkg_resources import resource_string as get_resource_string
except ImportError:
from pkgutil import get_data as get_resource_string # type: ignore

#
def get_resource_string(mod_part, file_part):
"""Read resource string."""
ref = importlib.resources.files(mod_part).joinpath(file_part)
return ref.read_bytes()


# 'Polo' variable in MiRS files use these values for H/V polarization
POLO_V = 2
Expand Down
11 changes: 8 additions & 3 deletions satpy/readers/nwcsaf_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,11 @@

from satpy.readers.file_handlers import BaseFileHandler
from satpy.readers.utils import unzip_file
from satpy.utils import get_legacy_chunk_size
from satpy.utils import get_chunk_size_limit

logger = logging.getLogger(__name__)

CHUNK_SIZE = get_legacy_chunk_size()
CHUNK_SIZE = get_chunk_size_limit()

SENSOR = {"NOAA-19": "avhrr-3",
"NOAA-18": "avhrr-3",
Expand Down Expand Up @@ -347,8 +347,13 @@ def get_area_def(self, dsid):
@staticmethod
def _ensure_crs_extents_in_meters(crs, area_extent):
"""Fix units in Earth shape, satellite altitude and 'units' attribute."""
import warnings
if "kilo" in crs.axis_info[0].unit_name:
proj_dict = crs.to_dict()
with warnings.catch_warnings():
# The proj dict route is the only feasible way to modify the area, suppress the warning it causes
warnings.filterwarnings("ignore", category=UserWarning,
message="You will likely lose important projection information")
proj_dict = crs.to_dict()
proj_dict["units"] = "m"
if "a" in proj_dict:
proj_dict["a"] *= 1000.
Expand Down
2 changes: 1 addition & 1 deletion satpy/readers/satpy_cf_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def _existing_datasets(self, configured_datasets=None):
def fix_modifier_attr(self, ds_info):
"""Fix modifiers attribute."""
# Empty modifiers are read as [], which causes problems later
if "modifiers" in ds_info and not ds_info["modifiers"]:
if "modifiers" in ds_info and len(ds_info["modifiers"]) == 0:
ds_info["modifiers"] = ()
try:
try:
Expand Down
4 changes: 2 additions & 2 deletions satpy/readers/seviri_l1b_nc.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,8 @@ def get_metadata(self):
"h": 35785831.00,
"ssp_longitude": ssp_lon}

self.mda["number_of_lines"] = int(self.nc.dims["y"])
self.mda["number_of_columns"] = int(self.nc.dims["x"])
self.mda["number_of_lines"] = int(self.nc.sizes["y"])
self.mda["number_of_columns"] = int(self.nc.sizes["x"])

# only needed for HRV channel which is not implemented yet
# self.mda['hrv_number_of_lines'] = int(self.nc.dims['num_rows_hrv'])
Expand Down
4 changes: 2 additions & 2 deletions satpy/readers/smos_l2_wind.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,6 @@ def get_area_def(self, dsid):
description = "SMOS L2 Wind Equirectangular Projection"
area_id = "smos_eqc"
proj_id = "equirectangular"
proj_dict = {"init": self["/attr/geospatial_bounds_vertical_crs"]}
area_def = AreaDefinition(area_id, description, proj_id, proj_dict, width, height, area_extent, )
proj_str = self["/attr/geospatial_bounds_vertical_crs"]
area_def = AreaDefinition(area_id, description, proj_id, proj_str, width, height, area_extent, )
return area_def
10 changes: 5 additions & 5 deletions satpy/tests/reader_tests/test_ahi_hrit.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ def test_init(self):

# Check if scanline timestamps are there (dedicated test below)
assert isinstance(reader.acq_time, np.ndarray)
assert reader.acq_time.dtype == np.dtype("datetime64[ns]")

# Check platform
assert reader.platform == HIMAWARI8
Expand Down Expand Up @@ -305,22 +306,21 @@ def test_get_dataset(self, base_get_dataset):
def test_mjd2datetime64(self):
"""Test conversion from modified julian day to datetime64."""
from satpy.readers.hrit_jma import mjd2datetime64
assert mjd2datetime64(np.array([0])) == np.datetime64("1858-11-17", "us")
assert mjd2datetime64(np.array([40587.5])) == np.datetime64("1970-01-01 12:00", "us")
assert mjd2datetime64(np.array([0])) == np.datetime64("1858-11-17", "ns")
assert mjd2datetime64(np.array([40587.5])) == np.datetime64("1970-01-01 12:00", "ns")

def test_get_acq_time(self):
"""Test computation of scanline acquisition times."""
dt_line = np.arange(1, 11000+1).astype("timedelta64[s]")
acq_time_exp = np.datetime64("1970-01-01", "us") + dt_line

acq_time_exp = np.datetime64("1970-01-01", "ns") + dt_line
for platform in ["Himawari-8", "MTSAT-2"]:
# Results are not exactly identical because timestamps are stored in
# the header with only 6 decimals precision (max diff here: 45 msec).
mda = self._get_mda(platform=platform)
reader = self._get_reader(mda=mda)
np.testing.assert_allclose(reader.acq_time.astype(np.int64),
acq_time_exp.astype(np.int64),
atol=45000)
atol=45000000)

def test_start_time_from_filename(self):
"""Test that by default the datetime in the filename is returned."""
Expand Down
Loading