Perform bounds-checking for an indexer. -1 is allowed for indicating missing values. Parameters ---------- indices : ndarray n : int Length of the array being indexed. Raises ------ ValueError Examples -------- >>> validate_indices(np.arra
(indices: np.ndarray, n: int)
| 187 | |
| 188 | |
| 189 | def validate_indices(indices: np.ndarray, n: int) -> None: |
| 190 | """ |
| 191 | Perform bounds-checking for an indexer. |
| 192 | |
| 193 | -1 is allowed for indicating missing values. |
| 194 | |
| 195 | Parameters |
| 196 | ---------- |
| 197 | indices : ndarray |
| 198 | n : int |
| 199 | Length of the array being indexed. |
| 200 | |
| 201 | Raises |
| 202 | ------ |
| 203 | ValueError |
| 204 | |
| 205 | Examples |
| 206 | -------- |
| 207 | >>> validate_indices(np.array([1, 2]), 3) # OK |
| 208 | |
| 209 | >>> validate_indices(np.array([1, -2]), 3) |
| 210 | Traceback (most recent call last): |
| 211 | ... |
| 212 | ValueError: negative dimensions are not allowed |
| 213 | |
| 214 | >>> validate_indices(np.array([1, 2, 3]), 3) |
| 215 | Traceback (most recent call last): |
| 216 | ... |
| 217 | IndexError: indices are out-of-bounds |
| 218 | |
| 219 | >>> validate_indices(np.array([-1, -1]), 0) # OK |
| 220 | |
| 221 | >>> validate_indices(np.array([0, 1]), 0) |
| 222 | Traceback (most recent call last): |
| 223 | ... |
| 224 | IndexError: indices are out-of-bounds |
| 225 | """ |
| 226 | if len(indices): |
| 227 | min_idx = indices.min() |
| 228 | if min_idx < -1: |
| 229 | msg = f"'indices' contains values less than allowed ({min_idx} < -1)" |
| 230 | raise ValueError(msg) |
| 231 | |
| 232 | max_idx = indices.max() |
| 233 | if max_idx >= n: |
| 234 | raise IndexError("indices are out-of-bounds") |
| 235 | |
| 236 | |
| 237 | # ----------------------------------------------------------- |