Validate an `axis` parameter, and normalize it to be positive. If `ndims` is known (i.e., not `None`), then check that `axis` is in the range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or `axis + ndims` (otherwise). If `ndims` is not known, and `axis` is positive, then ret
(axis, ndims)
| 4822 | |
| 4823 | |
| 4824 | def get_positive_axis(axis, ndims): |
| 4825 | """Validate an `axis` parameter, and normalize it to be positive. |
| 4826 | |
| 4827 | If `ndims` is known (i.e., not `None`), then check that `axis` is in the |
| 4828 | range `-ndims <= axis < ndims`, and return `axis` (if `axis >= 0`) or |
| 4829 | `axis + ndims` (otherwise). |
| 4830 | If `ndims` is not known, and `axis` is positive, then return it as-is. |
| 4831 | If `ndims` is not known, and `axis` is negative, then report an error. |
| 4832 | |
| 4833 | Args: |
| 4834 | axis: An integer constant |
| 4835 | ndims: An integer constant, or `None` |
| 4836 | |
| 4837 | Returns: |
| 4838 | The normalized `axis` value. |
| 4839 | |
| 4840 | Raises: |
| 4841 | ValueError: If `axis` is out-of-bounds, or if `axis` is negative and |
| 4842 | `ndims is None`. |
| 4843 | """ |
| 4844 | if not isinstance(axis, int): |
| 4845 | raise TypeError("axis must be an int; got %s" % type(axis).__name__) |
| 4846 | if ndims is not None: |
| 4847 | if 0 <= axis < ndims: |
| 4848 | return axis |
| 4849 | elif -ndims <= axis < 0: |
| 4850 | return axis + ndims |
| 4851 | else: |
| 4852 | raise ValueError("axis=%s out of bounds: expected %s<=axis<%s" % |
| 4853 | (axis, -ndims, ndims)) |
| 4854 | elif axis < 0: |
| 4855 | raise ValueError("axis may only be negative if ndims is statically known.") |
| 4856 | return axis |
| 4857 | |
| 4858 | |
| 4859 | # This op is intended to exactly match the semantics of numpy.repeat, with |
no test coverage detected