CLMM icon indicating copy to clipboard operation
CLMM copied to clipboard

Improve validation tests for numpy.ndarray

Open m-aguena opened this issue 2 years ago • 2 comments

When the type of a variable is numpy.ndarray (usually from something like np.array(2)), the tests in validate_argument fail. This could be fixed by improving:

def _is_valid(arg, valid_type):
    if valid_type == "function":
        return callable(arg)
    if (valid_type in ("int_array", "float_array") and np.iterable(arg)):
        return isinstance(arg[0], _valid_types[valid_type])
    if isinstance(arg, np.ndarray):
        if (valid_type in (int, "int_array")):
            return arg.dtype.char in np.typecodes['AllInteger']
        if (valid_type in (float, "float_array")):
            return arg.dtype.char in np.typecodes['AllFloat']
        return False
    return isinstance(arg, _valid_types.get(valid_type, valid_type))

m-aguena avatar Jul 12 '23 16:07 m-aguena

Will isinstance(obj, collections.abc.Iterable) help? It behaves differently from np.iterable(obj) for the 0-d array case. See https://numpy.org/doc/stable/reference/generated/numpy.iterable.html.

hsinfan1996 avatar Jul 13 '23 01:07 hsinfan1996

@hsinfan1996, thanks for the suggestion. But I think there is an even simpler solution:

def _is_valid(arg, valid_type):
    if valid_type == "function":
        return callable(arg)    
    if valid_type == "int_array":
        return np.array(arg).dtype.char in np.typecodes['AllInteger']    
    if valid_type == "float_array":
        return np.array(arg).dtype.char in np.typecodes['AllFloat']+np.typecodes['AllInteger'] 
    return isinstance(arg, _valid_types.get(valid_type, valid_type))

m-aguena avatar Jul 13 '23 15:07 m-aguena