jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_meshgrid(self):
        q1 = np.arange(3.) * u.m
        q2 = np.arange(5.) * u.s
        o1, o2 = np.meshgrid(q1, q2)
        e1, e2 = np.meshgrid(q1.value, q2.value)
        assert np.all(o1 == e1 * q1.unit)
        assert np.all(o2 == e2 * q2.unit)
//  [python]
def is_gray(self):
        """Return whether the colormap is grayscale."""
        if not self._isinit:
            self._init()
        return (np.alltrue(self._lut[:, 0] == self._lut[:, 1]) and
                np.alltrue(self._lut[:, 0] == self._lut[:, 2]))
//  [python]
def is_gray(self):
        """Return whether the colormap is grayscale."""
        if not self._isinit:
            self._init()
        return (np.all(self._lut[:, 0] == self._lut[:, 1]) and
                np.all(self._lut[:, 0] == self._lut[:, 2]))
//  [python]
def test_elemwise_empty():
    # test with 0 element
    a = tcn.shared_constructor(theano._asarray(numpy.random.rand(0, 0),
                                               dtype='float32'), 'a')

    b = tensor.fmatrix()

    f = pfunc([b], [], updates=[(a, a + b)], mode=mode_with_gpu)
    f2 = pfunc([b], [], updates=[(a, a + b)], mode=mode_without_gpu)

    a0 = a.get_value() * 1.0
    f(numpy.ones((0, 0), dtype='float32'))

    assert numpy.all(a0 + 1.0 == a.get_value())
//  [python]
def test_piecewise(self):
        x = np.linspace(-2.5, 2.5, 6) * u.m
        out = np.piecewise(x, [x < 0, x >= 0], [-1*u.s, 1*u.day])
        expected = np.piecewise(x.value, [x.value < 0, x.value >= 0],
                                [-1, 24*3600]) * u.s
        assert out.unit == expected.unit
        assert np.all(out == expected)

        out2 = np.piecewise(x, [x < 1 * u.m, x >= 0],
                            [-1*u.s, 1*u.day, lambda x: 1*u.hour])
        expected2 = np.piecewise(x.value, [x.value < 1, x.value >= 0],
                                 [-1, 24*3600, 3600]) * u.s
        assert out2.unit == expected2.unit
        assert np.all(out2 == expected2)

        out3 = np.piecewise(x, [x < 1 * u.m, x >= 0],
                            [0, 1*u.percent, lambda x: 1*u.one])
        expected3 = np.piecewise(x.value, [x.value < 1, x.value >= 0],
                                 [0, 0.01, 1]) * u.one
        assert out3.unit == expected3.unit
        assert np.all(out3 == expected3)

        with pytest.raises(TypeError):  # no Quantity in condlist.
            np.piecewise(x, [x], [0.])

        with pytest.raises(TypeError):  # no Quantity in condlist.
            np.piecewise(x.value, [x], [0.])
//  [python]
def test_lstsq(self):
        b = np.array([1., 2., 4.]) * u.m / u.s
        x, residuals, rank, s = np.linalg.lstsq(self.q, b, rcond=None)
        xx, residualsx, rankx, sx = np.linalg.lstsq(self.q.value, b.value,
                                                    rcond=None)
        xx <<= b.unit / self.q.unit
        residualsx <<= b.unit ** 2
        sx <<= self.q.unit

        assert_array_equal(x, xx)
        assert_array_equal(residuals, residualsx)
        assert_array_equal(s, sx)
        assert rank == rankx
        assert u.allclose(self.q @ x, b)

        # Also do one where we can check the answer...
        m = np.eye(3)
        b = np.arange(3) * u.m
        x, residuals, rank, s = np.linalg.lstsq(m, b, rcond=1.*u.percent)
        assert_array_equal(x, b)
        assert np.all(residuals == 0 * u.m**2)
        assert rank == 3
        assert_array_equal(s, np.array([1., 1., 1.]) << u.one)

        with pytest.raises(u.UnitsError):
            np.linalg.lstsq(m, b, rcond=1.*u.s)
//  [python]
def __iter__(self):
        # check if all distributions are given as lists
        # in this case we want to sample without replacement
        all_lists = np.all([not hasattr(v, "rvs")
                            for v in self.param_distributions.values()])
        rnd = check_random_state(self.random_state)

        if all_lists:
            # look up sampled parameter settings in parameter grid
            param_grid = ParameterGrid(self.param_distributions)
            grid_size = len(param_grid)

            if grid_size < self.n_iter:
                raise ValueError(
                    "The total space of parameters %d is smaller "
                    "than n_iter=%d." % (grid_size, self.n_iter)
                    + " For exhaustive searches, use GridSearchCV.")
            for i in sample_without_replacement(grid_size, self.n_iter,
                                                random_state=rnd):
                yield param_grid[i]

        else:
            # Always sort the keys of a dictionary, for reproducibility
            items = sorted(self.param_distributions.items())
            for _ in six.moves.range(self.n_iter):
                params = dict()
                for k, v in items:
                    if hasattr(v, "rvs"):
                        if sp_version < (0, 16):
                            params[k] = v.rvs()
                        else:
                            params[k] = v.rvs(random_state=rnd)
                    else:
                        params[k] = v[rnd.randint(len(v))]
                yield params
//  [python]
def test_elemwise0():

    a = tcn.shared_constructor(theano._asarray(numpy.random.rand(4, 4),
                                               dtype='float32'), 'a')

    b = tensor.fmatrix()

    f = pfunc([b], [], updates=[(a, a + b)], mode=mode_with_gpu)

    # check that we work inplace.
    assert (list(f.maker.fgraph.toposort()[1].op.destroy_map.items())
            == [(0, [0])])

    a0 = a.get_value() * 1.0
    f(numpy.ones((4, 4), dtype='float32'))

    assert n.all(a0 + 1.0 == a.get_value())
//  [python]
def test_elemwise0():

    a = tcn.shared_constructor(theano._asarray(numpy.random.rand(4, 4),
                                               dtype='float32'), 'a')

    b = tensor.fmatrix()

    f = pfunc([b], [], updates=[(a, a + b)], mode=mode_with_gpu)

    # check that we work inplace.
    assert (list(f.maker.fgraph.toposort()[1].op.destroy_map.items())
            == [(0, [0])])

    a0 = a.get_value() * 1.0
    f(numpy.ones((4, 4), dtype='float32'))

    assert numpy.all(a0 + 1.0 == a.get_value())
//  [python]
def test_elemwise_comparaison_cast():
    """
    test if an elemwise comparaison followed by a cast to float32 are
    pushed to gpu.
    """

    a = tensor.fmatrix()
    b = tensor.fmatrix()
    av = theano._asarray(numpy.random.rand(4, 4), dtype='float32')
    bv = numpy.ones((4, 4), dtype='float32')

    for g, ans in [(tensor.lt, av < bv), (tensor.gt, av > bv),
                   (tensor.le, av <= bv), (tensor.ge, av >= bv)]:

        f = pfunc([a, b], tensor.cast(g(a, b), 'float32'), mode=mode_with_gpu)

        out = f(av, bv)
        assert n.all(out == ans)
        assert any([isinstance(node.op, cuda.GpuElemwise)
                    for node in f.maker.fgraph.toposort()])
//  [python]
def test_elemwise_comparaison_cast():
    """
    test if an elemwise comparaison followed by a cast to float32 are
    pushed to gpu.
    """

    a = tensor.fmatrix()
    b = tensor.fmatrix()
    av = theano._asarray(numpy.random.rand(4, 4), dtype='float32')
    bv = numpy.ones((4, 4), dtype='float32')

    for g, ans in [(tensor.lt, av < bv), (tensor.gt, av > bv),
                   (tensor.le, av <= bv), (tensor.ge, av >= bv)]:

        f = pfunc([a, b], tensor.cast(g(a, b), 'float32'), mode=mode_with_gpu)

        out = f(av, bv)
        assert numpy.all(out == ans)
        assert any([isinstance(node.op, cuda.GpuElemwise)
                    for node in f.maker.fgraph.toposort()])
//  [python]
def find_clusters(X, n_clusters, rseed=2):
    rng = numpy.random.RandomState(rseed)
    i = rng.permutation(X.shape[0])[:n_clusters]
    centers = X[i]

    while True:
        labels = pairwise_distances_argmin(X, centers)
        new_centers = numpy.array([X[labels == i].mean(0)
                                for i in range(n_clusters)])
        if numpy.all(centers == new_centers):
            break
        centers = new_centers

    return centers, labels
//  [python]
def masked4d_array_to_kper_dict(m4d):
        assert m4d.ndim == 4
        kper_dict = {}
        for kper, arr in enumerate(m4d):
            if np.all(np.isnan(arr)):
                continue
            elif np.any(np.isnan(arr)):
                raise Exception("masked value found in array")
            kper_dict[kper] = arr.copy()
        return kper_dict
//  [python]
def test_elemwise_composite_float64():
    # test that we don't fuse composite elemwise with float64 somewhere inside
    # nvcc by default downcast them to float32. We would need to tell him not
    # to do so, but that possible only on some device.
    a = tensor.fmatrix()
    b = tensor.fmatrix()
    av = theano._asarray(numpy.random.rand(4, 4), dtype='float32')
    bv = numpy.ones((4, 4), dtype='float32')

    def get_all_basic_scalar(composite_op):
        l = []
        for i in composite_op.fgraph.toposort():
            if isinstance(i, theano.scalar.Composite):
                l += get_all_basic_scalar(i)
            else:
                l.append(i)
        return l
    for mode in [mode_with_gpu, mode_with_gpu.excluding('gpu_after_fusion'),
                 mode_with_gpu.excluding('elemwise_fusion')]:
        f = pfunc([a, b],
                  tensor.cast(tensor.lt(tensor.cast(a, 'float64') ** 2,
                                               b),
                                     'float32'), mode=mode)

        out = f(av, bv)
        assert n.all(out == ((av ** 2) < bv))
        for node in f.maker.fgraph.toposort():
            if isinstance(node.op, cuda.GpuElemwise):
                if isinstance(node.op.scalar_op, theano.scalar.Composite):
                    scals = get_all_basic_scalar(node.op.scalar_op)
                    for s in scals:
                        assert not any([i.type.dtype == 'float64'
                                        for i in s.inputs + s.outputs])
//  [python]
def test_elemwise_composite_float64():
    # test that we don't fuse composite elemwise with float64 somewhere inside
    # nvcc by default downcast them to float32. We would need to tell him not
    # to do so, but that possible only on some device.
    a = tensor.fmatrix()
    b = tensor.fmatrix()
    av = theano._asarray(numpy.random.rand(4, 4), dtype='float32')
    bv = numpy.ones((4, 4), dtype='float32')

    def get_all_basic_scalar(composite_op):
        l = []
        for i in composite_op.fgraph.toposort():
            if isinstance(i, theano.scalar.Composite):
                l += get_all_basic_scalar(i)
            else:
                l.append(i)
        return l
    for mode in [mode_with_gpu, mode_with_gpu.excluding('gpu_after_fusion'),
                 mode_with_gpu.excluding('elemwise_fusion')]:
        f = pfunc([a, b],
                  tensor.cast(tensor.lt(tensor.cast(a, 'float64') ** 2,
                                               b),
                                     'float32'), mode=mode)

        out = f(av, bv)
        assert numpy.all(out == ((av ** 2) < bv))
        for node in f.maker.fgraph.toposort():
            if isinstance(node.op, cuda.GpuElemwise):
                if isinstance(node.op.scalar_op, theano.scalar.Composite):
                    scals = get_all_basic_scalar(node.op.scalar_op)
                    for s in scals:
                        assert not any([i.type.dtype == 'float64'
                                        for i in s.inputs + s.outputs])
//  [python]
def isna(self) -> "TensorArray":
        """
        A 1-D array indicating if each value is missing.

        Returns
        -------
        na_values : Union[np.ndarray, ExtensionArray]
            In most cases, this should return a NumPy ndarray. For
            exceptional cases like ``SparseArray``, where returning
            an ndarray would be expensive, an ExtensionArray may be
            returned.

        Notes
        -----
        If returning an ExtensionArray, then

        * ``na_values._is_boolean`` should be True
        * `na_values` should implement :func:`ExtensionArray._reduce`
        * ``na_values.any`` and ``na_values.all`` should be implemented
        """
        if self._tensor.dtype.type is np.object_:
            # Avoid comparing with __eq__ because the elements of the tensor
            # may do something funny with that operation.
            return np.array(
                [self._tensor[i] is None for i in range(len(self))], dtype=bool
            )
        elif self._tensor.dtype.type is np.str_:
            return np.alltrue(self._tensor == "", axis=tuple(range(1, self._tensor.ndim)))
        else:
            return np.alltrue(
                np.isnan(self._tensor), axis=tuple(range(1, self._tensor.ndim))
            )
//  [python]
def isna(self) -> "TensorArray":
        """
        A 1-D array indicating if each value is missing.

        Returns
        -------
        na_values : Union[np.ndarray, ExtensionArray]
            In most cases, this should return a NumPy ndarray. For
            exceptional cases like ``SparseArray``, where returning
            an ndarray would be expensive, an ExtensionArray may be
            returned.

        Notes
        -----
        If returning an ExtensionArray, then

        * ``na_values._is_boolean`` should be True
        * `na_values` should implement :func:`ExtensionArray._reduce`
        * ``na_values.any`` and ``na_values.all`` should be implemented
        """
        if self._tensor.dtype.type is np.object_:
            # Avoid comparing with __eq__ because the elements of the tensor
            # may do something funny with that operation.
            return np.array(
                [self._tensor[i] is None for i in range(len(self))], dtype=bool
            )
        elif self._tensor.dtype.type is np.str_:
            return np.all(self._tensor == "", axis=tuple(range(1, self._tensor.ndim)))
        else:
            return np.all(
                np.isnan(self._tensor), axis=tuple(range(1, self._tensor.ndim))
            )
//  [python]
def _check_c(Pot, dxdv=False, dens=False):
    """
    Check whether a potential or list thereof has a C implementation.

    Parameters
    ----------
    Pot : Potential instance or list of such instances
        Potential instance or list of such instances to check.
    dxdv : bool, optional
        If True, check whether the potential has dxdv implementation.
    dens : bool, optional
        If True, check whether the potential has its density implemented in C.

    Returns
    -------
    bool
        True if a C implementation exists, False otherwise.

    Notes
    -----
    - 2014-02-17 - Written - Bovy (IAS)
    - 2017-07-01 - Generalized to dxdv, added general support for WrapperPotentials, and added support for planarPotentials.

    """
    Pot = flatten(Pot)
    from ..potential import linearPotential, planarForce

    if dxdv:
        hasC_attr = "hasC_dxdv"
    elif dens:
        hasC_attr = "hasC_dens"
    else:
        hasC_attr = "hasC"
    from .WrapperPotential import parentWrapperPotential

    if isinstance(Pot, list):
        return n.all(
            n.array([_check_c(p, dxdv=dxdv, dens=dens) for p in Pot], dtype="bool")
        )
    elif isinstance(Pot, parentWrapperPotential):
        return bool(Pot.__dict__[hasC_attr] * _check_c(Pot._pot))
    elif (
        isinstance(Pot, Force)
        or isinstance(Pot, planarForce)
        or isinstance(Pot, linearPotential)
    ):
        return Pot.__dict__[hasC_attr]
//  [python]
def _check_c(Pot, dxdv=False, dens=False):
    """
    Check whether a potential or list thereof has a C implementation.

    Parameters
    ----------
    Pot : Potential instance or list of such instances
        Potential instance or list of such instances to check.
    dxdv : bool, optional
        If True, check whether the potential has dxdv implementation.
    dens : bool, optional
        If True, check whether the potential has its density implemented in C.

    Returns
    -------
    bool
        True if a C implementation exists, False otherwise.

    Notes
    -----
    - 2014-02-17 - Written - Bovy (IAS)
    - 2017-07-01 - Generalized to dxdv, added general support for WrapperPotentials, and added support for planarPotentials.

    """
    Pot = flatten(Pot)
    from ..potential import linearPotential, planarForce

    if dxdv:
        hasC_attr = "hasC_dxdv"
    elif dens:
        hasC_attr = "hasC_dens"
    else:
        hasC_attr = "hasC"
    from .WrapperPotential import parentWrapperPotential

    if isinstance(Pot, list):
        return numpy.all(
            numpy.array([_check_c(p, dxdv=dxdv, dens=dens) for p in Pot], dtype="bool")
        )
    elif isinstance(Pot, parentWrapperPotential):
        return bool(Pot.__dict__[hasC_attr] * _check_c(Pot._pot))
    elif (
        isinstance(Pot, Force)
        or isinstance(Pot, planarForce)
        or isinstance(Pot, linearPotential)
    ):
        return Pot.__dict__[hasC_attr]
//  [python]
def umask_b64_encode(self, masked_array):
        # Unmask invalid data if present
        if masked_array.mask:
            masked_array.fill_value = 0
        image_array = masked_array.filled()
        if np.alltrue(np.where(image_array <= 1, True, False)):
            array = (image_array * 255).astype(np.uint8)
        else:
            array = image_array.astype(np.uint8)
        if not array.flags['C_CONTIGUOUS']:  # Needed for base64 encoding
            array = array.copy(order='c')
        if len(array.shape) == 2:  # In Case a grayscale Image
            array = np.stack((array, array, array), axis=-1)
        encoded_array = base64.b64encode(array)
        return encoded_array, array.shape[-1]
//  [python]
def umask_b64_encode(self, masked_array):
        # Unmask invalid data if present
        if masked_array.mask:
            masked_array.fill_value = 0
        image_array = masked_array.filled()
        if np.all(np.where(image_array <= 1, True, False)):
            array = (image_array * 255).astype(np.uint8)
        else:
            array = image_array.astype(np.uint8)
        if not array.flags['C_CONTIGUOUS']:  # Needed for base64 encoding
            array = array.copy(order='c')
        if len(array.shape) == 2:  # In Case a grayscale Image
            array = np.stack((array, array, array), axis=-1)
        encoded_array = base64.b64encode(array)
        return encoded_array, array.shape[-1]
//  [python]
_check('logical_or', lambda a, b: numpy.logical_or(a, function.Array.cast(b)), numpy.logical_or, numpy.array([False, True, True])[:,None], numpy.array([True, False])[None,:])
_check('bitwise_or-bool', lambda a, b: numpy.bitwise_or(a, function.Array.cast(b)), numpy.bitwise_or, numpy.array([False, True, True])[:,None], numpy.array([True, False])[None,:])
_check('logical_not', lambda a: numpy.logical_not(function.Array.cast(a)), numpy.logical_not, numpy.array([[False, True], [True, False], [True, True]]))
_check('invert-bool', lambda a: numpy.invert(function.Array.cast(a)), numpy.invert, numpy.array([[False, True], [True, False], [True, True]]))
_check('all-bool-all-axes', lambda a: n.all(function.Array.cast(a)), n.all, numpy.array([[False, True], [True, True]]))
//  [python]
_check('logical_or', lambda a, b: numpy.logical_or(a, function.Array.cast(b)), numpy.logical_or, numpy.array([False, True, True])[:,None], numpy.array([True, False])[None,:])
_check('bitwise_or-bool', lambda a, b: numpy.bitwise_or(a, function.Array.cast(b)), numpy.bitwise_or, numpy.array([False, True, True])[:,None], numpy.array([True, False])[None,:])
_check('logical_not', lambda a: numpy.logical_not(function.Array.cast(a)), numpy.logical_not, numpy.array([[False, True], [True, False], [True, True]]))
_check('invert-bool', lambda a: numpy.invert(function.Array.cast(a)), numpy.invert, numpy.array([[False, True], [True, False], [True, True]]))
_check('all-bool-all-axes', lambda a: numpy.all(function.Array.cast(a)), numpy.all, numpy.array([[False, True], [True, True]]))
//  [python]
def test_using_taps_sequence(self):
        # this test refers to a bug reported by Nicolas
        # Boulanger-Lewandowski June 6th
        x = theano.tensor.dvector()
        y, updates = theano.scan(lambda x: [x],
                                 sequences=dict(input=x, taps=[-1]),
                                 outputs_info=[None])
        inp = numpy.arange(5).astype('float64')
        rval = theano.function([x], y, updates=updates)(inp)
        assert numpy.all(rval == inp[:-1])
//  [python]
def test_computing_gradient(self):
        x1 = theano.tensor.scalar('x1')
        x2 = theano.shared(numpy.array([1, 2, 3, 4, 5]), name='x2')
        K = x2 * x1

        out, updates = theano.scan(lambda i, v: theano.tensor.grad(K[i], v),
                sequences=theano.tensor.arange(K.shape[0]),
                non_sequences=x1)
        f = theano.function([x1], out, allow_input_downcast=True)

        assert n.all(f(3.) != 0.)
//  [python]
def test_computing_gradient(self):
        x1 = theano.tensor.scalar('x1')
        x2 = theano.shared(numpy.array([1, 2, 3, 4, 5]), name='x2')
        K = x2 * x1

        out, updates = theano.scan(lambda i, v: theano.tensor.grad(K[i], v),
                sequences=theano.tensor.arange(K.shape[0]),
                non_sequences=x1)
        f = theano.function([x1], out, allow_input_downcast=True)

        assert numpy.all(f(3.) != 0.)
//  [python]
def test_reshape():

    a = tcn.CudaNdarrayType((False,))()
    b = tcn.CudaNdarrayType((False, False))()
    c = T.reshape(a, [2, 3])

    # basic
    f = theano.function([a], c, mode=mode_with_gpu)
    fv = f(cuda_ndarray.CudaNdarray(theano._asarray([0, 1, 2, 3, 4, 5],
                                                    dtype='float32')))
    topo = f.maker.fgraph.toposort()
    assert any([isinstance(node.op, B.GpuReshape) for node in topo])
    assert n.all(fv == n.asarray([[0, 1, 2], [3, 4, 5]]))

    # test that it works without inplace operations
    a_val = cuda_ndarray.CudaNdarray(theano._asarray([0, 1, 2, 3, 4, 5],
                                                     dtype='float32'))
    a_val_copy = cuda_ndarray.CudaNdarray(theano._asarray([0, 1, 2, 3, 4, 5],
                                                          dtype='float32'))
    b_val = cuda_ndarray.CudaNdarray(theano._asarray([[0, 1, 2], [3, 4, 5]],
                                                     dtype='float32'))

    f_sub = theano.function([a, b], c - b, mode=mode_with_gpu)
    topo = f_sub.maker.fgraph.toposort()
    assert any([isinstance(node.op, B.GpuReshape) for node in topo])
    assert n.all(f_sub(a_val, b_val) == 0.0)
    assert n.all(n.asarray(a_val) == n.asarray(a_val_copy))

    # test that it works with inplace operations
    a_val = theano._asarray([0, 1, 2, 3, 4, 5], dtype='float32')
    a_val_copy = theano._asarray([0, 1, 2, 3, 4, 5], dtype='float32')
    b_val = theano._asarray([[0, 1, 2], [3, 4, 5]], dtype='float32')

    f_sub = theano.function([a, b], c - b, mode=mode_with_gpu)
    topo = f_sub.maker.fgraph.toposort()
    assert any([isinstance(node.op, B.GpuReshape) for node in topo])
    assert n.all(f_sub(a_val, b_val) == 0.0)
    assert n.all(n.asarray(a_val) == n.asarray(a_val_copy))

    # verify gradient
    def just_vals(v):
        return T.Reshape(2)(v, theano._asarray([2, 3], dtype='int32'))
    utt.verify_grad(just_vals, [a_val])

    # Test for appropriate handling of -1 indices
    x = T.tensor3('x')
    reshp_val = n.array([[[1, 0], [0, 1]], [[0, 1], [1, 0]]], dtype='float32')
    f_reshp = theano.function([x], x.reshape((-1, 1, 1)), mode=mode_with_gpu)
    y = f_reshp(reshp_val)
    assert y.shape == (8, 1, 1)

    dim = T.scalar('dim_val', dtype='int32')
    f_reshp = theano.function(
        [x, dim],
        x.reshape((dim, dim, 1)),
        mode=mode_with_gpu
    )
    try:
        f_reshp(reshp_val, 4)
        raise('Only one -1 is accepted in the new shape')
    except ValueError:
        pass

    # Test zero dimensions are allowed
    x = T.vector('x')
    f_reshp = theano.function([x], x.reshape((0,100)), mode=mode_with_gpu)
    assert f_reshp(n.ndarray((0,), dtype='float32')).shape == (0,100)
//  [python]
def test_reshape():

    a = tcn.CudaNdarrayType((False,))()
    b = tcn.CudaNdarrayType((False, False))()
    c = T.reshape(a, [2, 3])

    # basic
    f = theano.function([a], c, mode=mode_with_gpu)
    fv = f(cuda_ndarray.CudaNdarray(theano._asarray([0, 1, 2, 3, 4, 5],
                                                    dtype='float32')))
    topo = f.maker.fgraph.toposort()
    assert any([isinstance(node.op, B.GpuReshape) for node in topo])
    assert numpy.all(fv == numpy.asarray([[0, 1, 2], [3, 4, 5]]))

    # test that it works without inplace operations
    a_val = cuda_ndarray.CudaNdarray(theano._asarray([0, 1, 2, 3, 4, 5],
                                                     dtype='float32'))
    a_val_copy = cuda_ndarray.CudaNdarray(theano._asarray([0, 1, 2, 3, 4, 5],
                                                          dtype='float32'))
    b_val = cuda_ndarray.CudaNdarray(theano._asarray([[0, 1, 2], [3, 4, 5]],
                                                     dtype='float32'))

    f_sub = theano.function([a, b], c - b, mode=mode_with_gpu)
    topo = f_sub.maker.fgraph.toposort()
    assert any([isinstance(node.op, B.GpuReshape) for node in topo])
    assert numpy.all(f_sub(a_val, b_val) == 0.0)
    assert numpy.all(numpy.asarray(a_val) == numpy.asarray(a_val_copy))

    # test that it works with inplace operations
    a_val = theano._asarray([0, 1, 2, 3, 4, 5], dtype='float32')
    a_val_copy = theano._asarray([0, 1, 2, 3, 4, 5], dtype='float32')
    b_val = theano._asarray([[0, 1, 2], [3, 4, 5]], dtype='float32')

    f_sub = theano.function([a, b], c - b, mode=mode_with_gpu)
    topo = f_sub.maker.fgraph.toposort()
    assert any([isinstance(node.op, B.GpuReshape) for node in topo])
    assert numpy.all(f_sub(a_val, b_val) == 0.0)
    assert numpy.all(numpy.asarray(a_val) == numpy.asarray(a_val_copy))

    # verify gradient
    def just_vals(v):
        return T.Reshape(2)(v, theano._asarray([2, 3], dtype='int32'))
    utt.verify_grad(just_vals, [a_val])

    # Test for appropriate handling of -1 indices
    x = T.tensor3('x')
    reshp_val = numpy.array([[[1, 0], [0, 1]], [[0, 1], [1, 0]]], dtype='float32')
    f_reshp = theano.function([x], x.reshape((-1, 1, 1)), mode=mode_with_gpu)
    y = f_reshp(reshp_val)
    assert y.shape == (8, 1, 1)

    dim = T.scalar('dim_val', dtype='int32')
    f_reshp = theano.function(
        [x, dim],
        x.reshape((dim, dim, 1)),
        mode=mode_with_gpu
    )
    try:
        f_reshp(reshp_val, 4)
        raise('Only one -1 is accepted in the new shape')
    except ValueError:
        pass

    # Test zero dimensions are allowed
    x = T.vector('x')
    f_reshp = theano.function([x], x.reshape((0,100)), mode=mode_with_gpu)
    assert f_reshp(numpy.ndarray((0,), dtype='float32')).shape == (0,100)
//  [python]
def max_err(self, _g_pt):
        """Return the biggest relative error between g_pt and self.gx"""

        g_pt = []
        for i in xrange(len(_g_pt)):
            if self.ndarray_mask[i]:
                g_pt.append(_g_pt[i])
            elif isinstance(_g_pt[i], numpy.ndarray):
                assert n.all(_g_pt[i] == 0)
        if len(g_pt) != len(self.gx):
            raise ValueError('argument has wrong number of elements',
                             len(g_pt))
        errs = []

        for i, (a, b) in enumerate(zip(g_pt, self.gx)):
            if a.shape != b.shape:
                raise ValueError('argument element %i has wrong shape %s' %
                                 (i, str((a.shape, b.shape))))
            vv = multiple_outputs_numeric_grad.abs_rel_err(a, b)
            errs.append(numpy.max(
                multiple_outputs_numeric_grad.abs_rel_err(a, b)))
        if n.all(n.isfinite(errs)):
            return numpy.max(errs), numpy.argmax(errs)
        else:
            return numpy.inf, 0
//  [python]
def max_err(self, _g_pt):
        """Return the biggest relative error between g_pt and self.gx"""

        g_pt = []
        for i in xrange(len(_g_pt)):
            if self.ndarray_mask[i]:
                g_pt.append(_g_pt[i])
            elif isinstance(_g_pt[i], numpy.ndarray):
                assert numpy.all(_g_pt[i] == 0)
        if len(g_pt) != len(self.gx):
            raise ValueError('argument has wrong number of elements',
                             len(g_pt))
        errs = []

        for i, (a, b) in enumerate(zip(g_pt, self.gx)):
            if a.shape != b.shape:
                raise ValueError('argument element %i has wrong shape %s' %
                                 (i, str((a.shape, b.shape))))
            vv = multiple_outputs_numeric_grad.abs_rel_err(a, b)
            errs.append(numpy.max(
                multiple_outputs_numeric_grad.abs_rel_err(a, b)))
        if numpy.all(numpy.isfinite(errs)):
            return numpy.max(errs), numpy.argmax(errs)
        else:
            return numpy.inf, 0
//  [python]
def test_while1(self):
        x = tensor.vector('x')

        def lambda_fn(x_t):
            return x_t + 1, theano.scan_module.until(x_t > 3)
        o, _ = theano.scan(lambda_fn, x)
        o2, _ = theano.scan(lambda x_t: x_t + 2, x)

        f = theano.function([x], [o, o2], mode=mode_with_opt)
        vx = numpy.zeros((50,), dtype=theano.config.floatX)
        vx[23] = 4
        out, out2 = f(vx)
        assert len(out) == 24
        assert n.all(out2 == vx + 2)
        lssc = [x for x in f.maker.fgraph.toposort()
                if isinstance(x.op, theano.scan_module.scan_op.Scan)]
        # One scan node gets optimnized out
        assert len(lssc) == 1
//  [python]
def test_while1(self):
        x = tensor.vector('x')

        def lambda_fn(x_t):
            return x_t + 1, theano.scan_module.until(x_t > 3)
        o, _ = theano.scan(lambda_fn, x)
        o2, _ = theano.scan(lambda x_t: x_t + 2, x)

        f = theano.function([x], [o, o2], mode=mode_with_opt)
        vx = numpy.zeros((50,), dtype=theano.config.floatX)
        vx[23] = 4
        out, out2 = f(vx)
        assert len(out) == 24
        assert numpy.all(out2 == vx + 2)
        lssc = [x for x in f.maker.fgraph.toposort()
                if isinstance(x.op, theano.scan_module.scan_op.Scan)]
        # One scan node gets optimnized out
        assert len(lssc) == 1
//  [python]
def test_seq_tap_bug_jeremiah(self):
        inp = numpy.arange(10).reshape(-1, 1).astype(theano.config.floatX)
        exp_out = numpy.zeros((10, 1)).astype(theano.config.floatX)
        exp_out[4:] = inp[:-4]

        def onestep(x, x_tm4):
            return x, x_tm4

        seq = tensor.matrix()
        initial_value = theano.shared(numpy.zeros((4, 1),
                                                  dtype=theano.config.floatX))
        outputs_info = [OrderedDict(
            [('initial', initial_value), ('taps', [-4])]), None]
        results, updates = theano.scan(fn=onestep,
                                       sequences=seq,
                                       outputs_info=outputs_info)

        f = theano.function([seq], results[1])
        assert n.all(exp_out == f(inp))
//  [python]
def test_seq_tap_bug_jeremiah(self):
        inp = numpy.arange(10).reshape(-1, 1).astype(theano.config.floatX)
        exp_out = numpy.zeros((10, 1)).astype(theano.config.floatX)
        exp_out[4:] = inp[:-4]

        def onestep(x, x_tm4):
            return x, x_tm4

        seq = tensor.matrix()
        initial_value = theano.shared(numpy.zeros((4, 1),
                                                  dtype=theano.config.floatX))
        outputs_info = [OrderedDict(
            [('initial', initial_value), ('taps', [-4])]), None]
        results, updates = theano.scan(fn=onestep,
                                       sequences=seq,
                                       outputs_info=outputs_info)

        f = theano.function([seq], results[1])
        assert numpy.all(exp_out == f(inp))
//  [python]
def test_least(dtype):
    s_data = np.arange(15, dtype=dtype).reshape(5, 3)
    t_data = np.arange(15, 30, dtype=dtype).reshape(5, 3)
    s = symbol('s', discover(s_data))
    t = symbol('t', discover(t_data))
    expr = least(s, t)
    result = compute(expr, {s: s_data, t: t_data})
    expected = np.minimum(s_data, t_data)
    assert n.all(result == expected)
//  [python]
def test_least(dtype):
    s_data = np.arange(15, dtype=dtype).reshape(5, 3)
    t_data = np.arange(15, 30, dtype=dtype).reshape(5, 3)
    s = symbol('s', discover(s_data))
    t = symbol('t', discover(t_data))
    expr = least(s, t)
    result = compute(expr, {s: s_data, t: t_data})
    expected = np.minimum(s_data, t_data)
    assert np.all(result == expected)
//  [python]
def test_least_mixed(dtype):
    s_data = np.array([2, 1], dtype=dtype)
    t_data = np.array([1, 2], dtype=dtype)
    s = symbol('s', discover(s_data))
    t = symbol('t', discover(t_data))
    expr = least(s, t)
    result = compute(expr, {s: s_data, t: t_data})
    expected = np.minimum(s_data, t_data)
    assert n.all(result == expected)
//  [python]
def test_least_mixed(dtype):
    s_data = np.array([2, 1], dtype=dtype)
    t_data = np.array([1, 2], dtype=dtype)
    s = symbol('s', discover(s_data))
    t = symbol('t', discover(t_data))
    expr = least(s, t)
    result = compute(expr, {s: s_data, t: t_data})
    expected = np.minimum(s_data, t_data)
    assert np.all(result == expected)
//  [python]
def test_greatest(dtype):
    s_data = np.arange(15, dtype=dtype).reshape(5, 3)
    t_data = np.arange(15, 30, dtype=dtype).reshape(5, 3)
    s = symbol('s', discover(s_data))
    t = symbol('t', discover(t_data))
    expr = greatest(s, t)
    result = compute(expr, {s: s_data, t: t_data})
    expected = np.maximum(s_data, t_data)
    assert n.all(result == expected)
//  [python]
def test_greatest(dtype):
    s_data = np.arange(15, dtype=dtype).reshape(5, 3)
    t_data = np.arange(15, 30, dtype=dtype).reshape(5, 3)
    s = symbol('s', discover(s_data))
    t = symbol('t', discover(t_data))
    expr = greatest(s, t)
    result = compute(expr, {s: s_data, t: t_data})
    expected = np.maximum(s_data, t_data)
    assert np.all(result == expected)
//  [python]
def test_greatest_mixed(dtype):
    s_data = np.array([2, 1], dtype=dtype)
    t_data = np.array([1, 2], dtype=dtype)
    s = symbol('s', discover(s_data))
    t = symbol('t', discover(t_data))
    expr = greatest(s, t)
    result = compute(expr, {s: s_data, t: t_data})
    expected = np.maximum(s_data, t_data)
    assert n.all(result == expected)
//  [python]
def test_greatest_mixed(dtype):
    s_data = np.array([2, 1], dtype=dtype)
    t_data = np.array([1, 2], dtype=dtype)
    s = symbol('s', discover(s_data))
    t = symbol('t', discover(t_data))
    expr = greatest(s, t)
    result = compute(expr, {s: s_data, t: t_data})
    expected = np.maximum(s_data, t_data)
    assert np.all(result == expected)
//  [python]
def test_borrow_bug_jeremiah(self):
        # This tests two things. The first is a bug occuring when scan wrongly
        # used the borrow flag. The second thing it that Scan's infer_shape()
        # method will be able to remove the Scan node from the graph in this
        # case.

        inp = numpy.arange(10).reshape(-1, 1).astype(theano.config.floatX)
        exp_out = numpy.zeros((10, 1)).astype(theano.config.floatX)
        exp_out[4:] = inp[:-4]

        def onestep(x, x_tm4):
            return x, x_tm4

        seq = tensor.matrix()
        initial_value = theano.shared(numpy.zeros((4, 1),
                                                  dtype=theano.config.floatX))
        outputs_info = [OrderedDict([('initial', initial_value),
                                     ('taps', [-4])]), None]
        results, _ = theano.scan(fn=onestep,
                                       sequences=seq,
                                       outputs_info=outputs_info)
        sharedvar = theano.shared(numpy.zeros((1, 1),
                                              dtype=theano.config.floatX))
        updates = OrderedDict([(sharedvar, results[0][-1:])])

        f = theano.function([seq], results[1], updates=updates)

        # This fails if scan uses wrongly the borrow flag
        assert n.all(exp_out == f(inp))

        # This fails if Scan's infer_shape() is unable to remove the Scan
        # node from the graph.
        f_infershape = theano.function([seq], results[1].shape,
                                       mode='FAST_RUN')
        scan_nodes_infershape = scan_nodes_from_fct(f_infershape)
        assert(len(scan_nodes_infershape) == 0)
//  [python]
def test_borrow_bug_jeremiah(self):
        # This tests two things. The first is a bug occuring when scan wrongly
        # used the borrow flag. The second thing it that Scan's infer_shape()
        # method will be able to remove the Scan node from the graph in this
        # case.

        inp = numpy.arange(10).reshape(-1, 1).astype(theano.config.floatX)
        exp_out = numpy.zeros((10, 1)).astype(theano.config.floatX)
        exp_out[4:] = inp[:-4]

        def onestep(x, x_tm4):
            return x, x_tm4

        seq = tensor.matrix()
        initial_value = theano.shared(numpy.zeros((4, 1),
                                                  dtype=theano.config.floatX))
        outputs_info = [OrderedDict([('initial', initial_value),
                                     ('taps', [-4])]), None]
        results, _ = theano.scan(fn=onestep,
                                       sequences=seq,
                                       outputs_info=outputs_info)
        sharedvar = theano.shared(numpy.zeros((1, 1),
                                              dtype=theano.config.floatX))
        updates = OrderedDict([(sharedvar, results[0][-1:])])

        f = theano.function([seq], results[1], updates=updates)

        # This fails if scan uses wrongly the borrow flag
        assert numpy.all(exp_out == f(inp))

        # This fails if Scan's infer_shape() is unable to remove the Scan
        # node from the graph.
        f_infershape = theano.function([seq], results[1].shape,
                                       mode='FAST_RUN')
        scan_nodes_infershape = scan_nodes_from_fct(f_infershape)
        assert(len(scan_nodes_infershape) == 0)
//  [python]
def setUpClass(cls):

        @onnx_op(op_type="Inverse")
        def inverse(x):
            # the user custom op implementation here:
            return numpy.linalg.inv(x)

        @onnx_op(op_type='All', inputs=[PyOp.dt_bool], outputs=[PyOp.dt_bool])
        def op_all(x):
            return n.all(x)

        @onnx_op(op_type='torchcustom::Add10')
        def op_add10(x):
            return x + 10
//  [python]
def setUpClass(cls):

        @onnx_op(op_type="Inverse")
        def inverse(x):
            # the user custom op implementation here:
            return numpy.linalg.inv(x)

        @onnx_op(op_type='All', inputs=[PyOp.dt_bool], outputs=[PyOp.dt_bool])
        def op_all(x):
            return numpy.all(x)

        @onnx_op(op_type='torchcustom::Add10')
        def op_add10(x):
            return x + 10
//  [python]
def points_in_triangle(tri, points, tol=1e-8):
    """
    Test if the points are inside the triangle.

    Input:
        tri - the triangle as a matrix where the rows are the xy points.
        points - the points as a matrix where the rows are the xy points.
    Returns a vector of boolean values.
    """
    # B is the transformation from xy to barycentric coordinates
    B = numpy.vstack([tri.T, numpy.ones(3)])

    vecs = numpy.vstack([points.T, numpy.ones((1, points.shape[0]))])

    # Convert the grid from XY locations to barycentric coordinates.
    # This will only fail of the triangle is degenerate.
    try:
        coords = numpy.linalg.solve(B, vecs)
    except Exception:
        return numpy.zeros(points.shape[0]).astype(bool)

    return numpy.all(coords >= -tol, axis=0)
//  [python]
def test_isotropic_hernquist_singler_is_atsingler():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    numpy.random.seed(10)
    samp = dfh.sample(R=1.3, z=0.0, n=100000)
    assert n.all(
        numpy.fabs(samp.r() - 1.3) < 1e-8
    ), "Sampling a spherical distribution function at a single r does not produce orbits at a single r"
    return None
//  [python]
def test_isotropic_hernquist_singler_is_atsingler():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    numpy.random.seed(10)
    samp = dfh.sample(R=1.3, z=0.0, n=100000)
    assert numpy.all(
        numpy.fabs(samp.r() - 1.3) < 1e-8
    ), "Sampling a spherical distribution function at a single r does not produce orbits at a single r"
    return None
//  [python]
def test_isotropic_hernquist_singlerphi_is_atsinglephi():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    numpy.random.seed(10)
    samp = dfh.sample(R=1.3, z=0.0, phi=numpy.pi - 0.3, n=100000)
    assert n.all(
        numpy.fabs(samp.phi() - numpy.pi + 0.3) < 1e-8
    ), "Sampling a spherical distribution function at a single r and phi oes not produce orbits at a single phi"
    return None
//  [python]
def test_isotropic_hernquist_singlerphi_is_atsinglephi():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    numpy.random.seed(10)
    samp = dfh.sample(R=1.3, z=0.0, phi=numpy.pi - 0.3, n=100000)
    assert numpy.all(
        numpy.fabs(samp.phi() - numpy.pi + 0.3) < 1e-8
    ), "Sampling a spherical distribution function at a single r and phi oes not produce orbits at a single phi"
    return None
//  [python]
def test_isotropic_hernquist_energyoutofbounds():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    assert n.all(
        n.fabs(dfh((n.arange(0.1, 10.0, 0.1),))) < 1e-8
    ), "Evaluating the isotropic Hernquist DF at E > 0 does not give zero"
    assert n.all(
        n.fabs(dfh((pot(0, 0) - 1e-4,))) < 1e-8
    ), "Evaluating the isotropic Hernquist DF at E < -GM/a does not give zero"
    return None
//  [python]
def test_isotropic_hernquist_energyoutofbounds():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    assert numpy.all(
        numpy.fabs(dfh((numpy.arange(0.1, 10.0, 0.1),))) < 1e-8
    ), "Evaluating the isotropic Hernquist DF at E > 0 does not give zero"
    assert numpy.all(
        numpy.fabs(dfh((pot(0, 0) - 1e-4,))) < 1e-8
    ), "Evaluating the isotropic Hernquist DF at E < -GM/a does not give zero"
    return None
//  [python]
def check_named_args(distfn, x, shape_args, defaults, meths):
    ## Check calling w/ named arguments.

    # check consistency of shapes, numargs and _parse signature
    signature = _getargspec(distfn._parse_args)
    npt.assert_(signature.varargs is None)
    npt.assert_(signature.keywords is None)
    npt.assert_(list(signature.defaults) == list(defaults))

    shape_argnames = signature.args[:-len(defaults)]  # a, b, loc=0, scale=1
    if distfn.shapes:
        shapes_ = distfn.shapes.replace(',', ' ').split()
    else:
        shapes_ = ''
    npt.assert_(len(shapes_) == distfn.numargs)
    npt.assert_(len(shapes_) == len(shape_argnames))

    # check calling w/ named arguments
    shape_args = list(shape_args)

    vals = [meth(x, *shape_args) for meth in meths]
    npt.assert_(n.all(n.isfinite(vals)))

    names, a, k = shape_argnames[:], shape_args[:], {}
    while names:
        k.update({names.pop(): a.pop()})
        v = [meth(x, *a, **k) for meth in meths]
        npt.assert_array_equal(vals, v)
        if 'n' not in k.keys():
            # `n` is first parameter of moment(), so can't be used as named arg
            npt.assert_equal(distfn.moment(1, *a, **k),
                             distfn.moment(1, *shape_args))

    # unknown arguments should not go through:
    k.update({'kaboom': 42})
    assert_raises(TypeError, distfn.cdf, x, **k)
//  [python]
def check_named_args(distfn, x, shape_args, defaults, meths):
    ## Check calling w/ named arguments.

    # check consistency of shapes, numargs and _parse signature
    signature = _getargspec(distfn._parse_args)
    npt.assert_(signature.varargs is None)
    npt.assert_(signature.keywords is None)
    npt.assert_(list(signature.defaults) == list(defaults))

    shape_argnames = signature.args[:-len(defaults)]  # a, b, loc=0, scale=1
    if distfn.shapes:
        shapes_ = distfn.shapes.replace(',', ' ').split()
    else:
        shapes_ = ''
    npt.assert_(len(shapes_) == distfn.numargs)
    npt.assert_(len(shapes_) == len(shape_argnames))

    # check calling w/ named arguments
    shape_args = list(shape_args)

    vals = [meth(x, *shape_args) for meth in meths]
    npt.assert_(np.all(np.isfinite(vals)))

    names, a, k = shape_argnames[:], shape_args[:], {}
    while names:
        k.update({names.pop(): a.pop()})
        v = [meth(x, *a, **k) for meth in meths]
        npt.assert_array_equal(vals, v)
        if 'n' not in k.keys():
            # `n` is first parameter of moment(), so can't be used as named arg
            npt.assert_equal(distfn.moment(1, *a, **k),
                             distfn.moment(1, *shape_args))

    # unknown arguments should not go through:
    k.update({'kaboom': 42})
    assert_raises(TypeError, distfn.cdf, x, **k)
//  [python]
def test_isotropic_hernquist_givenr_are_atgivenr():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    numpy.random.seed(10)
    r = numpy.linspace(0.1, 10.0, 1001)
    theta = numpy.random.uniform(size=len(r)) * numpy.pi
    # n should be ignored in the following
    samp = dfh.sample(R=r * numpy.sin(theta), z=r * numpy.cos(theta), n=100000)
    assert len(samp) == len(
        r
    ), "Length of sample with given r array is not equal to length of r"
    assert n.all(
        numpy.fabs(samp.r() - r) < 1e-8
    ), "Sampling a spherical distribution function at given r does not produce orbits at these given r"
    assert n.all(
        numpy.fabs(samp.R() - r * numpy.sin(theta)) < 1e-8
    ), "Sampling a spherical distribution function at given R does not produce orbits at these given R"
    assert n.all(
        numpy.fabs(samp.z() - r * numpy.cos(theta)) < 1e-8
    ), "Sampling a spherical distribution function at given z does not produce orbits at these given z"
    return None
//  [python]
def test_isotropic_hernquist_givenr_are_atgivenr():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = isotropicHernquistdf(pot=pot)
    numpy.random.seed(10)
    r = numpy.linspace(0.1, 10.0, 1001)
    theta = numpy.random.uniform(size=len(r)) * numpy.pi
    # n should be ignored in the following
    samp = dfh.sample(R=r * numpy.sin(theta), z=r * numpy.cos(theta), n=100000)
    assert len(samp) == len(
        r
    ), "Length of sample with given r array is not equal to length of r"
    assert numpy.all(
        numpy.fabs(samp.r() - r) < 1e-8
    ), "Sampling a spherical distribution function at given r does not produce orbits at these given r"
    assert numpy.all(
        numpy.fabs(samp.R() - r * numpy.sin(theta)) < 1e-8
    ), "Sampling a spherical distribution function at given R does not produce orbits at these given R"
    assert numpy.all(
        numpy.fabs(samp.z() - r * numpy.cos(theta)) < 1e-8
    ), "Sampling a spherical distribution function at given z does not produce orbits at these given z"
    return None
//  [python]
def test_anisotropic_hernquist_dMdE_betap05():
    pot = potential.HernquistPotential(amp=2.3, a=1.3)
    dfh = constantbetaHernquistdf(pot=pot, beta=0.5)
    tol = 1e-10

    def dMdE_betap05_analytic(E, dfh):
        if not hasattr(dfh, "_rphi"):
            dfh._rphi = dfh._setup_rphi_interpolator()
        rE = dfh._rphi(E)
        return 4.0 * numpy.pi**3.0 * rE**2.0 * dfh.fE(E)

    E = numpy.linspace(0.99 * pot(0, 0), pot(numpy.inf, 0) + 1e-6, 1001)
    assert n.all(
        n.fabs(dMdE_betap05_analytic(E, dfh) - dfh.dMdE(E)) < tol
    ), "Anisotropic Hernquist DF dMdE for beta=0.5 does not agree with analytic expression"
    return None