From 1fdae7496d487a795ff52db9443a7e8283aa7eae Mon Sep 17 00:00:00 2001 From: Stephan Hoyer Date: Sun, 29 Mar 2015 01:36:26 -0700 Subject: [PATCH] Implement dask.array.broadcast_to --- dask/array/__init__.py | 3 +- dask/array/chunk.py | 105 ++++++++++++++++++++++++++++ dask/array/core.py | 23 ++++++ dask/array/tests/test_array_core.py | 12 ++++ 4 files changed, 142 insertions(+), 1 deletion(-) diff --git a/dask/array/__init__.py b/dask/array/__init__.py index 1fa851d6b52..7a7ec415f00 100644 --- a/dask/array/__init__.py +++ b/dask/array/__init__.py @@ -2,7 +2,8 @@ from ..utils import ignoring from .core import (Array, stack, concatenate, tensordot, transpose, from_array, - choose, where, coarsen, constant, fromfunction, compute, unique, store) + choose, where, coarsen, broadcast_to, constant, fromfunction, compute, + unique, store) from .core import (arccos, arcsin, arctan, arctanh, arccosh, arcsinh, arctan2, ceil, copysign, cos, cosh, degrees, exp, expm1, fabs, floor, fmod, frexp, hypot, isinf, isnan, ldexp, log, log10, log1p, modf, radians, diff --git a/dask/array/chunk.py b/dask/array/chunk.py index 0fb11a61cd7..41167243ce4 100644 --- a/dask/array/chunk.py +++ b/dask/array/chunk.py @@ -9,6 +9,7 @@ from toolz import concat import numpy as np +from ..compatibility import builtins from ..utils import ignoring @@ -161,3 +162,107 @@ def trim(x, axes=None): axes = [axes.get(i, 0) for i in range(x.ndim)] return x[tuple(slice(ax, -ax if ax else None) for ax in axes)] + + +try: + from numpy import broadcast_to +except ImportError: # pragma: no cover + # broadcast_to will arrive in numpy v1.10. Until then, it is duplicated + # here: + + # Copyright (c) 2005-2015, NumPy Developers. + # All rights reserved. + + # Redistribution and use in source and binary forms, with or without + # modification, are permitted provided that the following conditions are + # met: + + # * Redistributions of source code must retain the above copyright + # notice, this list of conditions and the following disclaimer. + + # * Redistributions in binary form must reproduce the above + # copyright notice, this list of conditions and the following + # disclaimer in the documentation and/or other materials provided + # with the distribution. + + # * Neither the name of the NumPy Developers nor the names of any + # contributors may be used to endorse or promote products derived + # from this software without specific prior written permission. + + # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + def _maybe_view_as_subclass(original_array, new_array): + if type(original_array) is not type(new_array): + # if input was an ndarray subclass and subclasses were OK, + # then view the result as that subclass. + new_array = new_array.view(type=type(original_array)) + # Since we have done something akin to a view from original_array, we + # should let the subclass finalize (if it has it implemented, i.e., is + # not None). + if new_array.__array_finalize__: + new_array.__array_finalize__(original_array) + return new_array + + + def _broadcast_to(array, shape, subok, readonly): + shape = tuple(shape) if np.iterable(shape) else (shape,) + array = np.array(array, copy=False, subok=subok) + if not shape and array.shape: + raise ValueError('cannot broadcast a non-scalar to a scalar array') + if builtins.any(size < 0 for size in shape): + raise ValueError('all elements of broadcast shape must be non-' + 'negative') + broadcast = np.nditer( + (array,), flags=['multi_index', 'zerosize_ok', 'refs_ok'], + op_flags=['readonly'], itershape=shape, order='C').itviews[0] + result = _maybe_view_as_subclass(array, broadcast) + if not readonly and array.flags.writeable: + result.flags.writeable = True + return result + + + def broadcast_to(array, shape, subok=False): + """Broadcast an array to a new shape. + + Parameters + ---------- + array : array_like + The array to broadcast. + shape : tuple + The shape of the desired array. + subok : bool, optional + If True, then sub-classes will be passed-through, otherwise + the returned array will be forced to be a base-class array (default). + + Returns + ------- + broadcast : array + A readonly view on the original array with the given shape. It is + typically not contiguous. Furthermore, more than one element of a + broadcasted array may refer to a single memory location. + + Raises + ------ + ValueError + If the array is not compatible with the new shape according to NumPy's + broadcasting rules. + + Examples + -------- + >>> x = np.array([1, 2, 3]) + >>> np.broadcast_to(x, (3, 3)) # doctest: +SKIP + array([[1, 2, 3], + [1, 2, 3], + [1, 2, 3]]) + """ + return _broadcast_to(array, shape, subok=subok, readonly=True) diff --git a/dask/array/core.py b/dask/array/core.py index 0ad38787d37..52d707c6cd7 100644 --- a/dask/array/core.py +++ b/dask/array/core.py @@ -1270,6 +1270,29 @@ def coarsen(reduction, x, axes): return Array(merge(x.dask, dsk), name, blockdims=blockdims, dtype=dt) +@wraps(chunk.broadcast_to) +def broadcast_to(x, shape): + shape = tuple(shape) + ndim_new = len(shape) - x.ndim + if ndim_new < 0 or any(new != old + for new, old in zip(shape[ndim_new:], x.shape) + if old != 1): + raise ValueError('cannot broadcast shape %s to shape %s' + % (x.shape, shape)) + + name = next(names) + blockdims = (tuple((s,) for s in shape[:ndim_new]) + + tuple(bd if old > 1 else (new,) + for bd, old, new in zip(x.blockdims, x.shape, + shape[ndim_new:]))) + dsk = dict(((name,) + (0,) * ndim_new + key[1:], + (chunk.broadcast_to, key, + shape[:ndim_new] + + tuple(bd[i] for i, bd in zip(key[1:], blockdims[ndim_new:])))) + for key in core.flatten(x._keys())) + return Array(merge(dsk, x.dask), name, blockdims=blockdims, dtype=x.dtype) + + constant_names = ('constant-%d' % i for i in count(1)) diff --git a/dask/array/tests/test_array_core.py b/dask/array/tests/test_array_core.py index 0368751bcac..2d21fa19dc9 100644 --- a/dask/array/tests/test_array_core.py +++ b/dask/array/tests/test_array_core.py @@ -423,6 +423,18 @@ def test_coarsen(): coarsen(da.sum, d, {0: 2, 1: 4})) +def test_broadcast_to(): + x = np.random.randint(10, size=(5, 1, 6)) + a = from_array(x, blockshape=(3, 1, 3)) + + for shape in [(5, 4, 6), (2, 5, 1, 6), (3, 4, 5, 4, 6)]: + assert eq(chunk.broadcast_to(x, shape), + broadcast_to(a, shape)) + + assert raises(ValueError, lambda: broadcast_to(a, (2, 1, 6))) + assert raises(ValueError, lambda: broadcast_to(a, (3,))) + + def test_constant(): d = da.constant(2, blockdims=((2, 2), (3, 3))) assert d.blockdims == ((2, 2), (3, 3))