Broadcast an array to a new shape. Parameters ---------- x : array_like The array to broadcast. shape : tuple The shape of the desired array. chunks : tuple, optional If provided, then the result will use these chunks instead of the same chunks as
(x, shape, chunks=None, meta=None)
| 5104 | |
| 5105 | |
| 5106 | def broadcast_to(x, shape, chunks=None, meta=None): |
| 5107 | """Broadcast an array to a new shape. |
| 5108 | |
| 5109 | Parameters |
| 5110 | ---------- |
| 5111 | x : array_like |
| 5112 | The array to broadcast. |
| 5113 | shape : tuple |
| 5114 | The shape of the desired array. |
| 5115 | chunks : tuple, optional |
| 5116 | If provided, then the result will use these chunks instead of the same |
| 5117 | chunks as the source array. Setting chunks explicitly as part of |
| 5118 | broadcast_to is more efficient than rechunking afterwards. Chunks are |
| 5119 | only allowed to differ from the original shape along dimensions that |
| 5120 | are new on the result or have size 1 the input array. |
| 5121 | meta : empty ndarray |
| 5122 | empty ndarray created with same NumPy backend, ndim and dtype as the |
| 5123 | Dask Array being created (overrides dtype) |
| 5124 | |
| 5125 | Returns |
| 5126 | ------- |
| 5127 | broadcast : dask array |
| 5128 | |
| 5129 | See Also |
| 5130 | -------- |
| 5131 | :func:`numpy.broadcast_to` |
| 5132 | """ |
| 5133 | x = asarray(x) |
| 5134 | shape = tuple(shape) |
| 5135 | |
| 5136 | if meta is None: |
| 5137 | meta = meta_from_array(x) |
| 5138 | |
| 5139 | if x.shape == shape and (chunks is None or chunks == x.chunks): |
| 5140 | return x |
| 5141 | |
| 5142 | ndim_new = len(shape) - x.ndim |
| 5143 | if ndim_new < 0 or any( |
| 5144 | new != old for new, old in zip(shape[ndim_new:], x.shape) if old != 1 |
| 5145 | ): |
| 5146 | raise ValueError(f"cannot broadcast shape {x.shape} to shape {shape}") |
| 5147 | |
| 5148 | if chunks is None: |
| 5149 | chunks = tuple((s,) for s in shape[:ndim_new]) + tuple( |
| 5150 | bd if old > 1 else (new,) |
| 5151 | for bd, old, new in zip(x.chunks, x.shape, shape[ndim_new:]) |
| 5152 | ) |
| 5153 | else: |
| 5154 | chunks = normalize_chunks( |
| 5155 | chunks, shape, dtype=x.dtype, previous_chunks=x.chunks |
| 5156 | ) |
| 5157 | for old_bd, new_bd in zip(x.chunks, chunks[ndim_new:]): |
| 5158 | if old_bd != new_bd and old_bd != (1,): |
| 5159 | raise ValueError( |
| 5160 | "cannot broadcast chunks %s to chunks %s: " |
| 5161 | "new chunks must either be along a new " |
| 5162 | "dimension or a dimension of size 1" % (x.chunks, chunks) |
| 5163 | ) |