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)
| 5302 | |
| 5303 | |
| 5304 | def broadcast_to(x, shape, chunks=None, meta=None): |
| 5305 | """Broadcast an array to a new shape. |
| 5306 | |
| 5307 | Parameters |
| 5308 | ---------- |
| 5309 | x : array_like |
| 5310 | The array to broadcast. |
| 5311 | shape : tuple |
| 5312 | The shape of the desired array. |
| 5313 | chunks : tuple, optional |
| 5314 | If provided, then the result will use these chunks instead of the same |
| 5315 | chunks as the source array. Setting chunks explicitly as part of |
| 5316 | broadcast_to is more efficient than rechunking afterwards. Chunks are |
| 5317 | only allowed to differ from the original shape along dimensions that |
| 5318 | are new on the result or have size 1 the input array. |
| 5319 | meta : empty ndarray |
| 5320 | empty ndarray created with same NumPy backend, ndim and dtype as the |
| 5321 | Dask Array being created (overrides dtype) |
| 5322 | |
| 5323 | Returns |
| 5324 | ------- |
| 5325 | broadcast : dask array |
| 5326 | |
| 5327 | See Also |
| 5328 | -------- |
| 5329 | :func:`numpy.broadcast_to` |
| 5330 | """ |
| 5331 | x = asarray(x) |
| 5332 | shape = tuple(shape) |
| 5333 | |
| 5334 | if meta is None: |
| 5335 | meta = meta_from_array(x) |
| 5336 | |
| 5337 | if x.shape == shape and (chunks is None or chunks == x.chunks): |
| 5338 | return x |
| 5339 | |
| 5340 | ndim_new = len(shape) - x.ndim |
| 5341 | if ndim_new < 0 or any( |
| 5342 | new != old for new, old in zip(shape[ndim_new:], x.shape) if old != 1 |
| 5343 | ): |
| 5344 | raise ValueError(f"cannot broadcast shape {x.shape} to shape {shape}") |
| 5345 | |
| 5346 | if chunks is None: |
| 5347 | chunks = tuple((s,) for s in shape[:ndim_new]) + tuple( |
| 5348 | bd if old > 1 else (new,) |
| 5349 | for bd, old, new in zip(x.chunks, x.shape, shape[ndim_new:]) |
| 5350 | ) |
| 5351 | else: |
| 5352 | chunks = normalize_chunks( |
| 5353 | chunks, shape, dtype=x.dtype, previous_chunks=x.chunks |
| 5354 | ) |
| 5355 | for old_bd, new_bd in zip(x.chunks, chunks[ndim_new:]): |
| 5356 | if old_bd != new_bd and old_bd != (1,): |
| 5357 | raise ValueError( |
| 5358 | f"cannot broadcast chunks {x.chunks} to chunks {chunks}: " |
| 5359 | "new chunks must either be along a new " |
| 5360 | "dimension or a dimension of size 1" |
| 5361 | ) |