mikeio icon indicating copy to clipboard operation
mikeio copied to clipboard

DataArray apply and Numpy array container

Open jsmariegaard opened this issue 3 years ago • 5 comments

New method apply similar to methods in pandas and xarray for applying a mathematical function to all values in DataArray.

    >>> da.apply(np.sin)
    >>> da.apply(np.clip, 0.0, 1.0)
    >>> da.apply(lambda x: x**2 if x > 0 else 0)

jsmariegaard avatar Aug 27 '22 11:08 jsmariegaard

Would be even nicer if we could support this syntax;


da2 = np.sqrt(da)

I can't really figure out how this works, but somehow it calls the __array_ufunc__ function. https://github.com/pydata/xarray/blob/3d3b236df3f8f5982760e68e064eb0db2aacc4a2/xarray/core/arithmetic.py#L43

ecomodeller avatar Aug 29 '22 06:08 ecomodeller

Would be even nicer if we could support this syntax;

da2 = np.sqrt(da)

I can't really figure out how this works, but somehow it calls the __array_ufunc__ function. https://github.com/pydata/xarray/blob/3d3b236df3f8f5982760e68e064eb0db2aacc4a2/xarray/core/arithmetic.py#L43

Great idea! A hacky first attempt is now checked in.

Note also this medium write up about someone attempting something similar: https://towardsdatascience.com/wrapping-numpys-arrays-971e015e14bb

jsmariegaard avatar Aug 29 '22 11:08 jsmariegaard

image

jsmariegaard avatar Aug 29 '22 11:08 jsmariegaard

This seem like the proper reference https://numpy.org/devdocs/user/basics.dispatch.html#writing-custom-array-containers

ecomodeller avatar Aug 29 '22 18:08 ecomodeller

This PR will have to wait some weeks until we have time to do a proper implementation of Numpy array container such that a mikeio.DataArray can be considered truly array-like

jsmariegaard avatar Sep 09 '22 10:09 jsmariegaard