MaskedArray compatibility decorators

Hello, I created 2 decorators for improve compatibility of "numpy.ma.MaskedArray" with functions that don't support them. This simply convert MaskedArray to classical ndarray with masked value converted to NaN, use the function, and reconvert to MaskedArray. @MaArrayToNaNKeepMask : Re-use the source mask on the output. @MaArrayToNaNFixInvalid : Replace invalid values by mask on the output. Source: import numpy as np def MaArrayToNaNKeepMask(func): """ MaArray to ndArray with nan decorator. Keep mask from originale ndArray. """ def wrapper(MaArray, *args, **kwargs): try: Mask = MaArray.mask fill = MaArray.fill_value return np.ma.masked_array(func(MaArray.filled(np.NaN),*args, **kwargs), mask=Mask, fill_value=fill) except: return func(MaArray, *args, **kwargs) return wrapper def MaArrayToNaNFixInvalid(func): """ MaArray to ndArray with nan decorator. Recreate mask from invalid points. """ def wrapper(MaArray, *args, **kwargs): try: fill = MaArray.fill_value return np.ma.fix_invalid(func(MaArray.filled(np.NaN), *args, **kwargs), fill_value=fill) except: return func(MaArray, *args, **kwargs) return wrapper Exemple: import skimage.transform @MaArrayToNaNFixInvalid def maresize(image, output_shape, order=1, mode='constant', cval=0, clip=True, preserve_range=True): return skimage.transform.resize(image, output_shape, order, mode, cval, clip, preserve_range) I think it may be usefull to include this directly on numpy. There is a lot of functions that don't work directly with MaskedArray.
participants (1)
-
J.Goutin