|
12 | 12 | "create_diagonal",
|
13 | 13 | "expand_dims",
|
14 | 14 | "kron",
|
| 15 | + "pad", |
15 | 16 | "setdiff1d",
|
16 | 17 | "sinc",
|
17 | 18 | ]
|
@@ -538,3 +539,53 @@ def sinc(x: Array, /, *, xp: ModuleType | None = None) -> Array:
|
538 | 539 | xp.asarray(xp.finfo(x.dtype).eps, dtype=x.dtype, device=_compat.device(x)),
|
539 | 540 | )
|
540 | 541 | return xp.sin(y) / y
|
| 542 | + |
| 543 | + |
| 544 | +def pad( |
| 545 | + x: Array, |
| 546 | + pad_width: int, |
| 547 | + mode: str = "constant", |
| 548 | + *, |
| 549 | + xp: ModuleType | None = None, |
| 550 | + constant_values: bool | int | float | complex = 0, |
| 551 | +) -> Array: |
| 552 | + """ |
| 553 | + Pad the input array. |
| 554 | +
|
| 555 | + Parameters |
| 556 | + ---------- |
| 557 | + x : array |
| 558 | + Input array. |
| 559 | + pad_width : int |
| 560 | + Pad the input array with this many elements from each side. |
| 561 | + mode : str, optional |
| 562 | + Only "constant" mode is currently supported, which pads with |
| 563 | + the value passed to `constant_values`. |
| 564 | + xp : array_namespace, optional |
| 565 | + The standard-compatible namespace for `x`. Default: infer. |
| 566 | + constant_values : python scalar, optional |
| 567 | + Use this value to pad the input. Default is zero. |
| 568 | +
|
| 569 | + Returns |
| 570 | + ------- |
| 571 | + array |
| 572 | + The input array, |
| 573 | + padded with ``pad_width`` elements equal to ``constant_values``. |
| 574 | + """ |
| 575 | + if mode != "constant": |
| 576 | + msg = "Only `'constant'` mode is currently supported" |
| 577 | + raise NotImplementedError(msg) |
| 578 | + |
| 579 | + value = constant_values |
| 580 | + |
| 581 | + if xp is None: |
| 582 | + xp = array_namespace(x) |
| 583 | + |
| 584 | + padded = xp.full( |
| 585 | + tuple(x + 2 * pad_width for x in x.shape), |
| 586 | + fill_value=value, |
| 587 | + dtype=x.dtype, |
| 588 | + device=_compat.device(x), |
| 589 | + ) |
| 590 | + padded[(slice(pad_width, -pad_width, None),) * x.ndim] = x |
| 591 | + return padded |
0 commit comments