Broadcast `x` to an array with the shape (`ndim`, 2). A helper function for `pad` that prepares and validates arguments like `pad_width` for iteration in pairs. Parameters ---------- x : {None, scalar, array-like} The object to broadcast to the shape (`ndim`, 2).
(x, ndim, as_index=False)
| 456 | |
| 457 | |
| 458 | def _as_pairs(x, ndim, as_index=False): |
| 459 | """ |
| 460 | Broadcast `x` to an array with the shape (`ndim`, 2). |
| 461 | |
| 462 | A helper function for `pad` that prepares and validates arguments like |
| 463 | `pad_width` for iteration in pairs. |
| 464 | |
| 465 | Parameters |
| 466 | ---------- |
| 467 | x : {None, scalar, array-like} |
| 468 | The object to broadcast to the shape (`ndim`, 2). |
| 469 | ndim : int |
| 470 | Number of pairs the broadcasted `x` will have. |
| 471 | as_index : bool, optional |
| 472 | If `x` is not None, try to round each element of `x` to an integer |
| 473 | (dtype `np.intp`) and ensure every element is positive. |
| 474 | |
| 475 | Returns |
| 476 | ------- |
| 477 | pairs : nested iterables, shape (`ndim`, 2) |
| 478 | The broadcasted version of `x`. |
| 479 | |
| 480 | Raises |
| 481 | ------ |
| 482 | ValueError |
| 483 | If `as_index` is True and `x` contains negative elements. |
| 484 | Or if `x` is not broadcastable to the shape (`ndim`, 2). |
| 485 | """ |
| 486 | if x is None: |
| 487 | # Pass through None as a special case, otherwise np.round(x) fails |
| 488 | # with an AttributeError |
| 489 | return ((None, None),) * ndim |
| 490 | |
| 491 | x = np.array(x) |
| 492 | if as_index: |
| 493 | x = np.round(x).astype(np.intp, copy=False) |
| 494 | |
| 495 | if x.ndim < 3: |
| 496 | # Optimization: Possibly use faster paths for cases where `x` has |
| 497 | # only 1 or 2 elements. `np.broadcast_to` could handle these as well |
| 498 | # but is currently slower |
| 499 | |
| 500 | if x.size == 1: |
| 501 | # x was supplied as a single value |
| 502 | x = x.ravel() # Ensure x[0] works for x.ndim == 0, 1, 2 |
| 503 | if as_index and x < 0: |
| 504 | raise ValueError("index can't contain negative values") |
| 505 | return ((x[0], x[0]),) * ndim |
| 506 | |
| 507 | if x.size == 2 and x.shape != (2, 1): |
| 508 | # x was supplied with a single value for each side |
| 509 | # but except case when each dimension has a single value |
| 510 | # which should be broadcasted to a pair, |
| 511 | # e.g. [[1], [2]] -> [[1, 1], [2, 2]] not [[1, 2], [1, 2]] |
| 512 | x = x.ravel() # Ensure x[0], x[1] works |
| 513 | if as_index and (x[0] < 0 or x[1] < 0): |
| 514 | raise ValueError("index can't contain negative values") |
| 515 | return ((x[0], x[1]),) * ndim |