예제 #1
0
def assert_identical(a, b):
    """Like :py:func:`xarray.testing.assert_equal`, but also matches the
    objects' names and attributes.

    Raises an AssertionError if two objects are not identical.

    Parameters
    ----------
    a : xarray.Dataset, xarray.DataArray or xarray.Variable
        The first object to compare.
    b : xarray.Dataset, xarray.DataArray or xarray.Variable
        The second object to compare.

    See Also
    --------
    assert_equal, assert_allclose, Dataset.equals, DataArray.equals
    """
    __tracebackhide__ = True
    assert type(a) == type(b)
    if isinstance(a, Variable):
        assert a.identical(b), formatting.diff_array_repr(a, b, "identical")
    elif isinstance(a, DataArray):
        assert a.name == b.name
        assert a.identical(b), formatting.diff_array_repr(a, b, "identical")
    elif isinstance(a, (Dataset, Variable)):
        assert a.identical(b), formatting.diff_dataset_repr(a, b, "identical")
    else:
        raise TypeError(f"{type(a)} not supported by assertion comparison")
예제 #2
0
def assert_identical(a, b):
    """Like :py:func:`xarray.testing.assert_equal`, but also matches the
    objects' names and attributes.

    Raises an AssertionError if two objects are not identical.

    Parameters
    ----------
    a : xarray.Dataset, xarray.DataArray or xarray.Variable
        The first object to compare.
    b : xarray.Dataset, xarray.DataArray or xarray.Variable
        The second object to compare.

    See also
    --------
    assert_equal, assert_allclose, Dataset.equals, DataArray.equals
    """
    import xarray as xr
    __tracebackhide__ = True  # noqa: F841
    assert type(a) == type(b)  # noqa
    if isinstance(a, xr.Variable):
        assert a.identical(b), formatting.diff_array_repr(a, b, 'identical')
    elif isinstance(a, xr.DataArray):
        assert a.name == b.name
        assert a.identical(b), formatting.diff_array_repr(a, b, 'identical')
    elif isinstance(a, (xr.Dataset, xr.Variable)):
        assert a.identical(b), formatting.diff_dataset_repr(a, b, 'identical')
    else:
        raise TypeError('{} not supported by assertion comparison'
                        .format(type(a)))
예제 #3
0
def assert_equal(a, b):
    """Like :py:func:`numpy.testing.assert_array_equal`, but for xarray
    objects.

    Raises an AssertionError if two objects are not equal. This will match
    data values, dimensions and coordinates, but not names or attributes
    (except for Dataset objects for which the variable names must match).
    Arrays with NaN in the same location are considered equal.

    Parameters
    ----------
    a : xarray.Dataset, xarray.DataArray or xarray.Variable
        The first object to compare.
    b : xarray.Dataset, xarray.DataArray or xarray.Variable
        The second object to compare.

    See Also
    --------
    assert_identical, assert_allclose, Dataset.equals, DataArray.equals
    numpy.testing.assert_array_equal
    """
    __tracebackhide__ = True
    assert type(a) == type(b)
    if isinstance(a, (Variable, DataArray)):
        assert a.equals(b), formatting.diff_array_repr(a, b, "equals")
    elif isinstance(a, Dataset):
        assert a.equals(b), formatting.diff_dataset_repr(a, b, "equals")
    else:
        raise TypeError(f"{type(a)} not supported by assertion comparison")
예제 #4
0
def assert_equal(a, b):
    """Like :py:func:`numpy.testing.assert_array_equal`, but for xarray
    objects.

    Raises an AssertionError if two objects are not equal. This will match
    data values, dimensions and coordinates, but not names or attributes
    (except for Dataset objects for which the variable names must match).
    Arrays with NaN in the same location are considered equal.

    Parameters
    ----------
    a : xarray.Dataset, xarray.DataArray or xarray.Variable
        The first object to compare.
    b : xarray.Dataset, xarray.DataArray or xarray.Variable
        The second object to compare.

    See also
    --------
    assert_identical, assert_allclose, Dataset.equals, DataArray.equals,
    numpy.testing.assert_array_equal
    """
    import xarray as xr
    __tracebackhide__ = True  # noqa: F841
    assert type(a) == type(b)  # noqa
    if isinstance(a, (xr.Variable, xr.DataArray)):
        assert a.equals(b), formatting.diff_array_repr(a, b, 'equals')
    elif isinstance(a, xr.Dataset):
        assert a.equals(b), formatting.diff_dataset_repr(a, b, 'equals')
    else:
        raise TypeError('{} not supported by assertion comparison'
                        .format(type(a)))
예제 #5
0
def assert_allclose(a, b, rtol=1e-05, atol=1e-08, decode_bytes=True):
    """Like :py:func:`numpy.testing.assert_allclose`, but for xarray objects.

    Raises an AssertionError if two objects are not equal up to desired
    tolerance.

    Parameters
    ----------
    a : xarray.Dataset, xarray.DataArray or xarray.Variable
        The first object to compare.
    b : xarray.Dataset, xarray.DataArray or xarray.Variable
        The second object to compare.
    rtol : float, optional
        Relative tolerance.
    atol : float, optional
        Absolute tolerance.
    decode_bytes : bool, optional
        Whether byte dtypes should be decoded to strings as UTF-8 or not.
        This is useful for testing serialization methods on Python 3 that
        return saved strings as bytes.

    See also
    --------
    assert_identical, assert_equal, numpy.testing.assert_allclose
    """
    __tracebackhide__ = True
    assert type(a) == type(b)

    equiv = functools.partial(_data_allclose_or_equiv,
                              rtol=rtol,
                              atol=atol,
                              decode_bytes=decode_bytes)
    equiv.__name__ = "allclose"

    def compat_variable(a, b):
        a = getattr(a, "variable", a)
        b = getattr(b, "variable", b)

        return a.dims == b.dims and (a._data is b._data
                                     or equiv(a.data, b.data))

    if isinstance(a, Variable):
        allclose = compat_variable(a, b)
        assert allclose, formatting.diff_array_repr(a, b, compat=equiv)
    elif isinstance(a, DataArray):
        allclose = utils.dict_equiv(
            a.coords, b.coords, compat=compat_variable) and compat_variable(
                a.variable, b.variable)
        assert allclose, formatting.diff_array_repr(a, b, compat=equiv)
    elif isinstance(a, Dataset):
        allclose = a._coord_names == b._coord_names and utils.dict_equiv(
            a.variables, b.variables, compat=compat_variable)
        assert allclose, formatting.diff_dataset_repr(a, b, compat=equiv)
    else:
        raise TypeError("{} not supported by assertion comparison".format(
            type(a)))
예제 #6
0
    def test_diff_dataset_repr(self):
        ds_a = xr.Dataset(
            data_vars={
                "var1":
                (("x", "y"), np.array([[1, 2, 3], [4, 5, 6]], dtype="int64")),
                "var2": ("x", np.array([3, 4], dtype="int64")),
            },
            coords={
                "x": np.array(["a", "b"], dtype="U1"),
                "y": np.array([1, 2, 3], dtype="int64"),
            },
            attrs={
                "units": "m",
                "description": "desc"
            },
        )

        ds_b = xr.Dataset(
            data_vars={"var1": ("x", np.array([1, 2], dtype="int64"))},
            coords={
                "x": ("x", np.array(["a", "c"], dtype="U1"), {
                    "source": 0
                }),
                "label": ("x", np.array([1, 2], dtype="int64")),
            },
            attrs={"units": "kg"},
        )

        byteorder = "<" if sys.byteorder == "little" else ">"
        expected = dedent("""\
        Left and right Dataset objects are not identical
        Differing dimensions:
            (x: 2, y: 3) != (x: 2)
        Differing coordinates:
        L * x        (x) %cU1 'a' 'b'
        R * x        (x) %cU1 'a' 'c'
            source: 0
        Coordinates only on the left object:
          * y        (y) int64 1 2 3
        Coordinates only on the right object:
            label    (x) int64 1 2
        Differing data variables:
        L   var1     (x, y) int64 1 2 3 4 5 6
        R   var1     (x) int64 1 2
        Data variables only on the left object:
            var2     (x) int64 3 4
        Differing attributes:
        L   units: m
        R   units: kg
        Attributes only on the left object:
            description: desc""" % (byteorder, byteorder))

        actual = formatting.diff_dataset_repr(ds_a, ds_b, "identical")
        assert actual == expected
예제 #7
0
    def test_diff_dataset_repr(self):
        ds_a = xr.Dataset(data_vars={
            'var1': (('x', 'y'), np.array([[1, 2, 3], [4, 5, 6]],
                                          dtype='int64')),
            'var2': ('x', np.array([3, 4], dtype='int64'))
        },
                          coords={
                              'x': np.array(['a', 'b'], dtype='U1'),
                              'y': np.array([1, 2, 3], dtype='int64')
                          },
                          attrs={
                              'units': 'm',
                              'description': 'desc'
                          })

        ds_b = xr.Dataset(
            data_vars={'var1': ('x', np.array([1, 2], dtype='int64'))},
            coords={
                'x': ('x', np.array(['a', 'c'], dtype='U1'), {
                    'source': 0
                }),
                'label': ('x', np.array([1, 2], dtype='int64'))
            },
            attrs={'units': 'kg'})

        byteorder = '<' if sys.byteorder == 'little' else '>'
        expected = dedent("""\
        Left and right Dataset objects are not identical
        Differing dimensions:
            (x: 2, y: 3) != (x: 2)
        Differing coordinates:
        L * x        (x) %cU1 'a' 'b'
        R * x        (x) %cU1 'a' 'c'
            source: 0
        Coordinates only on the left object:
          * y        (y) int64 1 2 3
        Coordinates only on the right object:
            label    (x) int64 1 2
        Differing data variables:
        L   var1     (x, y) int64 1 2 3 4 5 6
        R   var1     (x) int64 1 2
        Data variables only on the left object:
            var2     (x) int64 3 4
        Differing attributes:
        L   units: m
        R   units: kg
        Attributes only on the left object:
            description: desc""" % (byteorder, byteorder))

        actual = formatting.diff_dataset_repr(ds_a, ds_b, 'identical')
        assert actual == expected
예제 #8
0
    def test_diff_dataset_repr(self):
        ds_a = xr.Dataset(
            data_vars={
                'var1': (('x', 'y'),
                         np.array([[1, 2, 3], [4, 5, 6]], dtype='int64')),
                'var2': ('x', np.array([3, 4], dtype='int64'))
            },
            coords={'x': np.array(['a', 'b'], dtype='U1'),
                    'y': np.array([1, 2, 3], dtype='int64')},
            attrs={'units': 'm', 'description': 'desc'}
        )

        ds_b = xr.Dataset(
            data_vars={'var1': ('x', np.array([1, 2], dtype='int64'))},
            coords={
                'x': ('x', np.array(['a', 'c'], dtype='U1'), {'source': 0}),
                'label': ('x', np.array([1, 2], dtype='int64'))
            },
            attrs={'units': 'kg'}
        )

        expected = dedent("""\
        Left and right Dataset objects are not identical
        Differing dimensions:
            (x: 2, y: 3) != (x: 2)
        Differing coordinates:
        L * x        (x) <U1 'a' 'b'
        R * x        (x) <U1 'a' 'c'
            source: 0
        Coordinates only on the left object:
          * y        (y) int64 1 2 3
        Coordinates only on the right object:
            label    (x) int64 1 2
        Differing data variables:
        L   var1     (x, y) int64 1 2 3 4 5 6
        R   var1     (x) int64 1 2
        Data variables only on the left object:
            var2     (x) int64 3 4
        Differing attributes:
        L   units: m
        R   units: kg
        Attributes only on the left object:
            description: desc""")

        actual = formatting.diff_dataset_repr(ds_a, ds_b, 'identical')
        assert actual == expected