File: np_compat.py

package info (click to toggle)
spectral-cube 0.6.6-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,136 kB
  • sloc: python: 13,236; makefile: 154
file content (27 lines) | stat: -rw-r--r-- 900 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import numpy as np

def allbadtonan(function):
    """
    Wrapper of numpy's nansum etc.: for <=1.8, just return the function's
    results.  For >=1.9, any axes with all-nan values will have all-nan outputs
    in the collapsed version
    """
    def f(data, axis=None, keepdims=None):
        if keepdims is None:
            result = function(data, axis=axis)
        else:
            result = function(data, axis=axis, keepdims=keepdims)
        if hasattr(result, '__len__'):
            if axis is None:
                if np.all(np.isnan(data)):
                    return np.nan
                else:
                    return result
            if keepdims is None:
                nans = np.all(np.isnan(data), axis=axis)
            else:
                nans = np.all(np.isnan(data), axis=axis, keepdims=keepdims)
            result[nans] = np.nan
        return result

    return f