Ejemplo n.º 1
0
    def __init_subclass__(cls):
        """Initialize a subclass with a bound DataArray class."""
        if not cls._name:
            return

        if cls._name not in cls._dataarrayclasses:
            register_dataarray_accessor(cls._name)(cls)

        cls._dataarrayclasses[cls._name].insert(0, cls._dataarrayclass)
Ejemplo n.º 2
0
def patch(name='hvplot', extension='bokeh', logo=False):
    from . import hvPlot, post_patch

    try:
        import xarray as xr
    except:
        raise ImportError('Could not patch plotting API onto xarray. '
                          'xarray could not be imported.')

    xr.register_dataset_accessor(name)(hvPlot)
    xr.register_dataarray_accessor(name)(hvPlot)

    post_patch(extension, logo)
Ejemplo n.º 3
0
def _register_xarray_accessors_(dataarrays=None, datasets=None):
    """Silently register xarray accessors"""
    import xarray as xr
    with warnings.catch_warnings():
        warnings.simplefilter(
            "ignore",
            xr.core.extensions.AccessorRegistrationWarning)
        if dataarrays:
            for name, cls in dataarrays.items():
                xr.register_dataarray_accessor(name)(cls)
        if datasets:
            for name, cls in datasets.items():
                xr.register_dataset_accessor(name)(cls)
Ejemplo n.º 4
0
def dataarray_method(func: Callable) -> Callable:
    """Decorator to make a DataArray function available as a method."""

    class Accessor:
        def __init__(self, dataarray):
            self.dataarray = dataarray

        @wraps(func)
        def __call__(self, *args, **kwargs):
            return func(self.dataarray, *args, **kwargs)

    register_dataarray_accessor(func.__name__)(Accessor)
    return func
Ejemplo n.º 5
0
def patch(library, name='hvplot', extension=None, logo=False):
    """
    Patch library to support HoloViews based plotting API.
    """
    if not isinstance(library, list): library = [library]
    _patch_plot.__doc__ = hvPlot.__call__.__doc__
    patch_property = property(_patch_plot)
    if 'streamz' in library:
        try:
            import streamz.dataframe as sdf
        except ImportError:
            raise ImportError('Could not patch plotting API onto streamz. '
                              'Streamz could not be imported.')
        setattr(sdf.DataFrame, name, patch_property)
        setattr(sdf.DataFrames, name, patch_property)
        setattr(sdf.Series, name, patch_property)
        setattr(sdf.Seriess, name, patch_property)
    if 'pandas' in library:
        try:
            import pandas as pd
        except:
            raise ImportError('Could not patch plotting API onto pandas. '
                              'Pandas could not be imported.')
        setattr(pd.DataFrame, name, patch_property)
        setattr(pd.Series, name, patch_property)
    if 'dask' in library:
        try:
            import dask.dataframe as dd
        except:
            raise ImportError('Could not patch plotting API onto dask. '
                              'Dask could not be imported.')
        setattr(dd.DataFrame, name, patch_property)
        setattr(dd.Series, name, patch_property)
    if 'xarray' in library:
        try:
            import xarray as xr
        except:
            raise ImportError('Could not patch plotting API onto xarray. '
                              'xarray could not be imported.')
        xr.register_dataset_accessor(name)(hvPlot)
        xr.register_dataarray_accessor(name)(hvPlot)
    if 'intake' in library:
        try:
            import intake
        except:
            raise ImportError('Could not patch plotting API onto intake. '
                              'intake could not be imported.')
        setattr(intake.source.base.DataSource, name, patch_property)
    if extension and not getattr(_hv.extension, '_loaded', False):
        _hv.extension(extension, logo=logo)
Ejemplo n.º 6
0
def test_cf_dataarraycfaccessor():
    with warnings.catch_warnings():
        warnings.simplefilter("ignore",
                              xr.core.extensions.AccessorRegistrationWarning)
        xr.register_dataarray_accessor('cf')(cf.DataArrayCFAccessor)

    lon = xr.DataArray(range(5),
                       dims='xxx',
                       name='xxx',
                       attrs={'standard_name': 'longitude'})
    temp = xr.DataArray(range(20, 25),
                        dims='xxx',
                        coords={'xxx': lon},
                        name='temp')

    assert temp.cf.lon.name == 'xxx'
    assert temp.cf.lat is None
    assert temp.cf.lon.cf.name == "lon"
Ejemplo n.º 7
0
class XMetadata:
    def __init__(self, xarray_obj):
        # self._obj = xarray_obj
        self._metadata = Annotation(None)


class XDataset(XMetadata):
    def __init__(self, xarray_obj):
        super().__init__(xarray_obj)


class XDataArray(XMetadata):
    def __init__(self, xarray_obj):
        super().__init__(xarray_obj)


try:
    import xarray as xr

    xr.register_dataset_accessor("climetlab")(XDataset)
    xr.register_dataarray_accessor("climetlab")(XDataArray)
except Exception:
    pass


def init_metadata():
    # Dummy function so climetlab.__init__ loads that file
    # and the xarray accessors are registered
    pass
Ejemplo n.º 8
0
        da = self.dataArray
        for d in self.dataArray.dims:
            if d in coords:
                try:
                    da = da.sel({d: coords[d]})
                except (KeyError, IndexError):
                    interp_coords[d] = coords[d]
        kwargs['bounds_error'] = bounds_error
        return da.interp(**interp_coords, method=method, kwargs=kwargs)


class plot_xy_map():
    def __init__(self, dataArray):
        self.dataArray = dataArray

    def __call__(self, **kwargs):
        if ('x' in self.dataArray.coords and 'y' in self.dataArray.coords and 'x' not in kwargs and

                self.dataArray.squeeze().shape == (len(np.atleast_1d(self.dataArray.x)), len(np.atleast_1d(self.dataArray.y)))):
            kwargs['x'] = 'x'
        _PlotMethods(self.dataArray)(**kwargs)


if not hasattr(xr.DataArray(None), 'ilk'):
    xr.register_dataarray_accessor("ilk")(ilk)
    xr.register_dataarray_accessor("interp_all")(interp_all)
    xr.register_dataarray_accessor("sel_interp_all")(sel_interp_all)
    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        xr.register_dataarray_accessor('plot')(plot_xy_map)
Ejemplo n.º 9
0
def register_xarray_dataarray_method(method: callable):
    accessor_wrapper = make_accessor_wrapper(method)
    register_dataarray_accessor(method.__name__)(accessor_wrapper)

    return method
Ejemplo n.º 10
0
    def interp_pchip(self, dim, ix=100):
        return xr_interp_pchip(self._obj, dim=dim, ix=ix)

    @functools.wraps(xr_filter_wiener)
    def filter_wiener(self, dim, mysize=5, noise=1e-2):
        return xr_filter_wiener(self._obj, dim=dim, mysize=mysize, noise=noise)

    @functools.wraps(xr_filtfilt_butter)
    def filtfilt_butter(self, dim, N=2, Wn=0.4):
        return xr_filtfilt_butter(self._obj, dim=dim, N=N, Wn=Wn)

    @functools.wraps(xr_filtfilt_bessel)
    def filtfilt_bessel(self, dim, N=2, Wn=0.4):
        return xr_filtfilt_bessel(self._obj, dim=dim, N=N, Wn=Wn)

    @functools.wraps(xr_unispline)
    def unispline(self, dim, err=None, num_knots=11, ix=None):
        return xr_unispline(self._obj,
                            dim=dim,
                            err=err,
                            num_knots=num_knots,
                            ix=ix)

    @functools.wraps(xr_polyfit)
    def polyfit(self, dim, ix=None, deg=0.5, poly='chebyshev'):
        return xr_polyfit(self._obj, dim=dim, ix=ix, deg=deg, poly=poly)


xr.register_dataarray_accessor('xyz')(XYZPY)
xr.register_dataset_accessor('xyz')(XYZPY)
Ejemplo n.º 11
0
    def __call__(self, dataArray2, **kwargs):
        interp_coords = {
            d: dataArray2[d]
            for d in self.dataArray.dims if d in dataArray2
        }
        return self.dataArray.interp(**interp_coords, **kwargs)


class sel_interp_all():
    def __init__(self, dataArray):
        self.dataArray = dataArray

    def __call__(self, coords, method="linear", bounds_error=True, **kwargs):
        interp_coords = {}
        da = self.dataArray
        for d in self.dataArray.dims:
            if d in coords:
                try:
                    da = da.sel({d: coords[d]})
                except (KeyError, IndexError):
                    interp_coords[d] = coords[d]
        kwargs['bounds_error'] = bounds_error
        return da.interp(**interp_coords, method=method, kwargs=kwargs)


if not hasattr(xr.DataArray(), 'ilk'):
    xr.register_dataarray_accessor("ilk")(ilk)
    xr.register_dataarray_accessor("interp_all")(interp_all)
    xr.register_dataarray_accessor("sel_interp_all")(sel_interp_all)
Ejemplo n.º 12
0
def _register_xarray_helper():
    # pylint: disable=import-outside-toplevel
    import xarray as xr
    from .xarray_helper import XArrayHelper

    xr.register_dataarray_accessor('rm')(XArrayHelper)
Ejemplo n.º 13
0
        return xr_interp(self._obj, dim=dim, ix=ix, order=order)

    @functools.wraps(xr_interp_pchip)
    def interp_pchip(self, dim, ix=100):
        return xr_interp_pchip(self._obj, dim=dim, ix=ix)

    @functools.wraps(xr_filter_wiener)
    def filter_wiener(self, dim, mysize=5, noise=1e-2):
        return xr_filter_wiener(self._obj, dim=dim, mysize=mysize, noise=noise)

    @functools.wraps(xr_filtfilt_butter)
    def filtfilt_butter(self, dim, N=2, Wn=0.4):
        return xr_filtfilt_butter(self._obj, dim=dim, N=N, Wn=Wn)

    @functools.wraps(xr_filtfilt_bessel)
    def filtfilt_bessel(self, dim, N=2, Wn=0.4):
        return xr_filtfilt_bessel(self._obj, dim=dim, N=N, Wn=Wn)

    @functools.wraps(xr_unispline)
    def unispline(self, dim, err=None, num_knots=11, ix=None):
        return xr_unispline(self._obj, dim=dim, err=err,
                            num_knots=num_knots, ix=ix)

    @functools.wraps(xr_polyfit)
    def polyfit(self, dim, ix=None, deg=0.5, poly='chebyshev'):
        return xr_polyfit(self._obj, dim=dim, ix=ix, deg=deg, poly=poly)


xr.register_dataarray_accessor('xyz')(XYZPY)
xr.register_dataset_accessor('xyz')(XYZPY)
Ejemplo n.º 14
0
 def __init_subclass__(cls) -> None:
     """Initialize a subclass with a bound DataArray class."""
     cls._dataarrayclass._accessor = cls
     cls._name = "_accessor_" + uuid4().hex[:16]
     register_dataarray_accessor(cls._name)(cls)