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 to xr dataset merge error with conflicting values in coordinate #2827

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 commits
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
8 changes: 6 additions & 2 deletions satpy/scene.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python

Check notice on line 1 in satpy/scene.py

View check run for this annotation

CodeScene Delta Analysis / CodeScene Cloud Delta Analysis (main)

ℹ Getting worse: Lines of Code in a Single File

The lines of code increases from 1295 to 1299, improve code health by reducing it to 600. The number of Lines of Code in a single file. More Lines of Code lowers the code health.
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2022 Satpy developers
#
Expand Down Expand Up @@ -1076,12 +1076,16 @@



def to_xarray_dataset(self, datasets=None):
def to_xarray_dataset(self, datasets=None, compat="minimal"):
"""Merge all xr.DataArrays of a scene to a xr.DataSet.

Parameters:
datasets (list):
List of products to include in the :class:`xarray.Dataset`
compat (Optional[str]):
Copy link
Member

Choose a reason for hiding this comment

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

The Optional type suggests this can be None, but that's not true is it?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Hah I think you are right I always thought optional does not mean it can be None rather if you do not provide it the default arg is used. Then I need to change it. I guess if one uses optional you have to check for none inside the function and then set the default. I think that's a little overhead and not very nice but is in accordance with the documentation of Optional.

Copy link
Member

Choose a reason for hiding this comment

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

Just make it "str" only and have the default be a string. No need for Optional or None checking.

How to compare variables with the same name for conflicts.
See :func:`xarray.merge` for possible options. Defaults to
"minimal" which drops conflicting variables.

Returns: :class:`xarray.Dataset`

Expand All @@ -1097,7 +1101,7 @@
mdata = combine_metadata(*tuple(i.attrs for i in dataarrays))
if mdata.get("area") is None or not isinstance(mdata["area"], SwathDefinition):
# either don't know what the area is or we have an AreaDefinition
ds = xr.merge(ds_dict.values())
ds = xr.merge(ds_dict.values(), compat=compat)
else:
# we have a swath definition and should use lon/lat values
lons, lats = mdata["area"].get_lonlats()
Expand Down
46 changes: 38 additions & 8 deletions satpy/tests/scene_tests/test_conversions.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@
"""Unit tests for Scene conversion functionality."""

import datetime as dt
from datetime import datetime

import numpy as np
import pytest
import xarray as xr
from dask import array as da
Expand Down Expand Up @@ -47,14 +49,6 @@
class TestSceneConversions:
"""Test Scene conversion to geoviews, xarray, etc."""

def test_to_xarray_dataset_with_empty_scene(self):
"""Test converting empty Scene to xarray dataset."""
scn = Scene()
xrds = scn.to_xarray_dataset()
assert isinstance(xrds, xr.Dataset)
assert len(xrds.variables) == 0
assert len(xrds.coords) == 0

def test_geoviews_basic_with_area(self):
"""Test converting a Scene to geoviews with an AreaDefinition."""
from pyresample.geometry import AreaDefinition
Expand Down Expand Up @@ -157,6 +151,42 @@
scn["var1"] = data_array
return scn

def test_to_xarray_dataset_with_conflicting_variables(self):
"""Test converting Scene with DataArrays with conflicting variables.

E.g. "acq_time" in the seviri_l1b_nc reader
"""
from pyresample.geometry import AreaDefinition
area = AreaDefinition("test", "test", "test",
{"proj": "geos", "lon_0": -95.5, "h": 35786023.0},
2, 2, [-200, -200, 200, 200])
scn = Scene()

acq_time_1 = ("y", [np.datetime64("1958-01-02 00:00:01"),
np.datetime64("1958-01-02 00:00:02")])
ds = xr.DataArray(da.zeros((2, 2), chunks=-1), dims=("y", "x"),
attrs={"start_time": datetime(2018, 1, 1), "area": area})
ds["acq_time"] = acq_time_1

scn["ds1"] = ds

acq_time_2 = ("y", [np.datetime64("1958-02-02 00:00:01"),
np.datetime64("1958-02-02 00:00:02")])
ds2 = ds.copy()
ds2["acq_time"] = acq_time_2

scn["ds2"] = ds2

# drop case (compat="minimal")
xrds = scn.to_xarray_dataset()
assert isinstance(xrds, xr.Dataset)
assert "acq_time" not in xrds.coords

xrds = scn.to_xarray_dataset(compat="override")
assert isinstance(xrds, xr.Dataset)
assert "acq_time" in xrds.coords
xr.testing.assert_equal(xrds["acq_time"], ds["acq_time"])

@pytest.fixture()
def multi_area_scn(self):
"""Define Scene with multiple area."""
Expand Down Expand Up @@ -210,6 +240,6 @@

def test_to_xarray_with_multiple_area_scene(self, multi_area_scn):
"""Test converting muiltple area Scene to xarray."""
# TODO: in future adapt for DataTree implementation

Check notice on line 243 in satpy/tests/scene_tests/test_conversions.py

View check run for this annotation

codefactor.io / CodeFactor

satpy/tests/scene_tests/test_conversions.py#L243

Unresolved comment '# TODO: in future adapt for DataTree implementation'. (C100)
with pytest.raises(ValueError, match="Datasets to be saved .* must have identical projection coordinates."):
_ = multi_area_scn.to_xarray()
Loading