PY-89

Validate a Named Array Contract

  • Medium
  • Array Contracts
  • Python

Task

Write validate_named_array(array, expected_shape, axis_names). array must be a NumPy array. expected_shape is a tuple of non-negative integers. The strings in axis_names declare the meaning of each axis; they must be non-empty, unique, and have one entry per expected axis.

Return a new dictionary with exactly these keys:

status, reason, shape, ndim, dtype, finite, axis_names

For an input array, shape is its shape tuple, ndim its integer dimension count, dtype is str(array.dtype), and axis_names is the supplied names as a tuple. finite is a Boolean when finiteness can be checked and None when the dtype is not numeric. A valid contract returns status == "ok" and reason is None; an invalid contract returns status == "invalid" and one of the reasons below.

Check failures in this order:

  1. a non-NumPy input: "not an ndarray";
  2. a dimension count different from len(expected_shape): "wrong dimensionality";
  3. a shape different from expected_shape: "wrong shape";
  4. a dtype that is not numeric (Boolean and object text are not numeric): "non-numeric dtype";
  5. any NaN, positive infinity, or negative infinity: "non-finite values";
  6. an axis-name count, empty name, or duplicate name problem: "invalid axis names".

The function checks that the axis declaration is well formed; it cannot prove whether a caller's word such as "sensors" honestly describes its data. Do not change the array or the supplied shape and names. Empty numeric arrays are finite and may be valid when their shape and declarations match.

Example

returns an "ok" record with shape (2, 2), dtype "float64", and finite=True. The same shape containing np.nan returns "non-finite values"; a one-dimensional array returns "wrong dimensionality".

Your implementation

You may import NumPy as np. Do not print or ask for input.