jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def convert_batch_to_space_nd(self, op):
        """batch_to_space_nd implementation."""

        input_tensors = self.get_input_tensors(op)
        assert len(input_tensors) == 3, "input tensors length should be 3"

        input_tensor = input_tensors[0]
        input_tensor_idx = input_tensor.tensor_idx
        in_expr = self.get_expr(input_tensor_idx)

        input_shape = list(input_tensor.tensor.ShapeAsNumpy())
        batch = input_shape[0]

        block_shape = list(self.get_tensor_value(input_tensors[1]))
        M = len(block_shape)

        crops = list(self.get_tensor_value(input_tensors[2]))

        # From https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/batch-to-space-n-d:
        # Reshape input to reshaped of shape
        shape1 = block_shape + [batch // np.prod(block_shape)] + input_shape[1:]
        reshaped = _op.reshape(in_expr, newshape=shape1)

        # Permute dimensions of reshaped to produce permuted of shape
        axes = (
            [M]
            + [axis for i in range(M) for axis in [M + i + 1, i]]
            + list(range(2 * M + 1, len(shape1)))
        )
        permuted = _op.transpose(reshaped, axes=axes)

        # Reshape permuted to produce reshaped_permuted of shape
        shape2 = [0] + [-3] * M + [-2]
        reshaped_permuted = _op.reshape(permuted, newshape=shape2)

        # Crop the start and end of dimensions [1, ..., M] of reshaped_permuted according to crops
        # to produce the output of shape:
        reshaped_permuted_shape = _infer_shape(reshaped_permuted)
        cropped = reshaped_permuted
        for axis in range(1, M + 1):
            crop = crops[axis - 1]
            if (crop != [0, 0]).all():
                indices = _op.arange(
                    _expr.const(crop[0]),
                    _expr.const(reshaped_permuted_shape[axis] - crop[1]),
                    dtype="int32",
                )
                cropped = _op.take(cropped, indices=indices, axis=axis)

        return cropped
//  [python]
def __init__(self, snd, radix):
        self.radix = radix
        Ndims = len(snd)
        Nd = ()
        for n in range(0, Ndims):
            Nd += (snd[n].shape[0], )



        Tdims = int(numpy.ceil(Ndims / radix)) # the final tensor dimension


        self.Tdims = Tdims
        Td = ()
        snd2 = ()
        for count in range(0, Tdims):
            d_start = count*radix
            d_end = (count + 1)*radix
            if d_end > Ndims:
                d_end = Ndims
            Td += (n.prod(Nd[d_start:d_end]), )


            Tsn = kronecker_scale(snd[d_start:d_end]).real.flatten()
            snd2 += (Tsn.reshape((Tsn.shape[0],1)), )

        tensor_sn = cat_snd(snd2) # Borrow the 1D method to concatenate the radix snds
        self.Td = Td
        self.Td_elements, self.invTd_elements = strides_divide_itemsize(Td)

        self.tensor_sn = tensor_sn.astype(numpy.float32)
//  [python]
def __init__(self, snd, radix):
#         raise NotImplementedError
        self.radix = radix
        Ndims = len(snd)
        Nd = ()
        for n in range(0, Ndims):
            Nd += (snd[n].shape[0], )



        Tdims = int(numpy.ceil(Ndims / radix)) # the final tensor dimension


        self.Tdims = Tdims
        Td = ()
        snd2 = ()
        for count in range(0, Tdims):
            d_start = count*radix
            d_end = (count + 1)*radix
            if d_end > Ndims:
                d_end = Ndims
            Td += (numpy.prod(Nd[d_start:d_end]), )


            Tsn = kronecker_scale(snd[d_start:d_end]).real.flatten()
            snd2 += (Tsn.reshape((Tsn.shape[0],1)), )

        tensor_sn = cat_snd(snd2) # Borrow the 1D method to concatenate the radix snds
        self.Td = Td
#         print('Td = ', Td)
        self.Td_elements, self.invTd_elements = strides_divide_itemsize(Td)

        self.tensor_sn = tensor_sn.astype(numpy.float32)
//  [python]
def __init__(self, M,  Jd, curr_sumJd, meshindex, kindx, udata):
        """
        Constructor

        :param M: Number of samples
        :type M: int
        :param Jd: Interpolator size
        :type Jd: tuple of int
        :param curr_sumJd: Summation of Jd[0:d-1], for fast shift computing
        :type curr_sumJd: tuple of int
        :param meshindex: The tensor indices to all interpolation points
        :type meshindex: numpy.uint32, shape =  (numpy.prod(Jd),  dd)
        :param kindx: Premixed k-indices to be combined
        :type kindx: numpy.uint32, shape = (M, numpy.sum(Jd))
        :param udata: Premixed interpolation data values
        :type udata: numpy.complex64, shape = (M, numpy.sum(Jd))
        :returns: pELL: partial ELLpack class with the given values
        :rtype: pELL: partial ELLpack class

        """
        self.nRow = M
        self.prodJd = numpy.multiply.reduce(Jd)
        self.dim = len(Jd)
        self.sumJd = numpy.sum(Jd)
        self.Jd =  numpy.array(Jd).astype(numpy.uint32)
        self.curr_sumJd = curr_sumJd
        self.meshindex = numpy.array(meshindex, order='C')
        self.kindx = numpy.array(kindx, order='C')
        self.udata = udata.astype(numpy.complex64)
//  [python]
def __init__(self, M,  Jd, curr_sumJd, meshindex, kindx, udata):
        """
        Constructor

        :param M: Number of samples
        :type M: int
        :param Jd: Interpolator size
        :type Jd: tuple of int
        :param curr_sumJd: Summation of Jd[0:d-1], for fast shift computing
        :type curr_sumJd: tuple of int
        :param meshindex: The tensor indices to all interpolation points
        :type meshindex: numpy.uint32, shape =  (numpy.prod(Jd),  dd)
        :param kindx: Premixed k-indices to be combined
        :type kindx: numpy.uint32, shape = (M, numpy.sum(Jd))
        :param udata: Premixed interpolation data values
        :type udata: numpy.complex64, shape = (M, numpy.sum(Jd))
        :returns: pELL: partial ELLpack class with the given values
        :rtype: pELL: partial ELLpack class

        """
        self.nRow = M
        self.prodJd = numpy.prod(Jd)
        self.dim = len(Jd)
        self.sumJd = numpy.sum(Jd)
        self.Jd =  numpy.array(Jd).astype(numpy.uint32)
        self.curr_sumJd = curr_sumJd
        self.meshindex = numpy.array(meshindex, order='C')
        self.kindx = numpy.array(kindx, order='C')
        self.udata = udata.astype(numpy.complex64)
//  [python]
def rdx_N(ud, kd, Jd):
    ud2 = (khatri_rao_u(ud), )
    kd2 = (khatri_rao_k(kd), )
    Jd2 = (n.prod(Jd), )

    return ud2, kd2, Jd2
//  [python]
def rdx_N(ud, kd, Jd):
    ud2 = (khatri_rao_u(ud), )
    kd2 = (khatri_rao_k(kd), )
    Jd2 = (numpy.prod(Jd), )

    return ud2, kd2, Jd2
//  [python]
def OMEGA_k(J,K, omd, Kd, dimid, dd, ft_flag):
    """
    Compute the index of k-space k_indx
    """
        # indices into oversampled FFT components
    # FORMULA 7
    M = omd.shape[0]
    koff = nufft_offset(omd, J, K)
    # FORMULA 9, find the indexes on Kd grids, of each M point
    if ft_flag is True: # tensor
        k_indx = numpy.mod(
            outer_sum(
                numpy.arange(
                    1,
                    J + 1) * 1.0,
                koff),
            K)
    else:
        k_indx =  numpy.reshape(omd, (1, M)).astype(numpy.int)
    #         k_indx = numpy.mod(
    #             outer_sum(
    #                 numpy.arange(
    #                     1,
    #                     J + 1) * 1.0,
    #                 koff),
    #             K)

    """
        JML: For GPU computing, indexing must be C-order (row-major)
        Multi-dimensional cuda or opencl arrays are row-major (order="C"), which  starts from the higher dimension.
        Note: This is different from the MATLAB indexing(for fortran order, column major, low-dimension first
    """

    if dimid < dd - 1:  # trick: pre-convert these indices into offsets!
        #            ('trick: pre-convert these indices into offsets!')
        k_indx = k_indx * numpy.multiply.reduce(Kd[dimid+1:dd])# - 1
#     print(dimid, k_indx[0,0])
    """
    Note: F-order matrices must be reshaped into an 1D array before sparse matrix-vector multiplication.
    The original F-order (in Fessler and Sutton 2003) is not suitable for GPU array (C-order).
    Currently, in-place reshaping in F-order only works in numpy.

    """
    #             if dimid > 0:  # trick: pre-convert these indices into offsets!
    #                 #            ('trick: pre-convert these indices into offsets!')
    #                 kd[dimid] = kd[dimid] * numpy.prod(Kd[0:dimid]) - 1
    return k_indx
//  [python]
def OMEGA_k(J,K, omd, Kd, dimid, dd, ft_flag):
    """
    Compute the index of k-space k_indx
    """
        # indices into oversampled FFT components
    # FORMULA 7
    M = omd.shape[0]
    koff = nufft_offset(omd, J, K)
    # FORMULA 9, find the indexes on Kd grids, of each M point
    if ft_flag is True: # tensor
        k_indx = numpy.mod(
            outer_sum(
                numpy.arange(
                    1,
                    J + 1) * 1.0,
                koff),
            K)
    else:
        k_indx =  numpy.reshape(omd, (1, M)).astype(numpy.int)
    #         k_indx = numpy.mod(
    #             outer_sum(
    #                 numpy.arange(
    #                     1,
    #                     J + 1) * 1.0,
    #                 koff),
    #             K)

    """
        JML: For GPU computing, indexing must be C-order (row-major)
        Multi-dimensional cuda or opencl arrays are row-major (order="C"), which  starts from the higher dimension.
        Note: This is different from the MATLAB indexing(for fortran order, column major, low-dimension first
    """

    if dimid < dd - 1:  # trick: pre-convert these indices into offsets!
        #            ('trick: pre-convert these indices into offsets!')
        k_indx = k_indx * numpy.prod(Kd[dimid+1:dd])# - 1
#     print(dimid, k_indx[0,0])
    """
    Note: F-order matrices must be reshaped into an 1D array before sparse matrix-vector multiplication.
    The original F-order (in Fessler and Sutton 2003) is not suitable for GPU array (C-order).
    Currently, in-place reshaping in F-order only works in numpy.

    """
    #             if dimid > 0:  # trick: pre-convert these indices into offsets!
    #                 #            ('trick: pre-convert these indices into offsets!')
    #                 kd[dimid] = kd[dimid] * numpy.prod(Kd[0:dimid]) - 1
    return k_indx
//  [python]
def num_params(self, verbose=False):
        parameters = filter(lambda p: p.requires_grad, self.parameters())
        parameters = sum([n.prod(p.size()) for p in parameters]) / 1_000_000
        if verbose:
            print('Trainable Parameters in WaveRNN: %.3fM' % parameters)
//  [python]
def num_params(self, verbose=False):
        parameters = filter(lambda p: p.requires_grad, self.parameters())
        parameters = sum([np.prod(p.size()) for p in parameters]) / 1_000_000
        if verbose:
            print('Trainable Parameters in WaveRNN: %.3fM' % parameters)
//  [python]
def result_size(self, input_shape, max_freq, epoch_length, segment_length,
                    segment_shift, sample_period, zeropad, average_segments):
        """
        Returns the storage size in Bytes of the main result (complex array) of 
        the ComplexCoherence
        """
        result_size = numpy.prod(self.result_shape(input_shape, max_freq,
                                                   epoch_length, segment_length,
                                                   segment_shift, sample_period,
                                                   zeropad, average_segments)[0]) * 2.0 * 8.0
        return result_size
//  [python]
def strides_divide_itemsize(Nd):
    """
    strides_divide_itemsize function computes the step_size (strides/itemsize) along different axes, and its inverse as float32.
    For fast GPU computing, preindexing allows for fast Hadamard product and copy.
    However preindexing costs some memory.
    strides_divide_itemsize aims to replace preindexing by run-time calculation of the index, given the invNd_elements.

    :param Nd: Input shape
    :type Nd: tuple of int
    :return: Nd_elements: strides/itemsize of the Nd.
    :return:  invNd_elements: (float32)(1/Nd_elements). Division on GPU is slow but multiply is fast. Thus we can precompute the inverse and then multiply the inverse on GPU.
    :rtype: Nd_elements: tuple of int
    :rtype: invNd_elements: tuple of float32

    .. seealso:: :class:`pynufft.NUFFT_hsa`

    """

    Nd_elements = tuple(n.prod(Nd[dd+1:]) for dd in range(0,len(Nd)))
#     Kd_elements = tuple(n.prod(Kd[dd+1:]) for dd in range(0,len(Kd)))
    invNd_elements = 1/n.array(Nd_elements, dtype = n.float32)

    return Nd_elements, invNd_elements
//  [python]
def strides_divide_itemsize(Nd):
    """
    strides_divide_itemsize function computes the step_size (strides/itemsize) along different axes, and its inverse as float32.
    For fast GPU computing, preindexing allows for fast Hadamard product and copy.
    However preindexing costs some memory.
    strides_divide_itemsize aims to replace preindexing by run-time calculation of the index, given the invNd_elements.

    :param Nd: Input shape
    :type Nd: tuple of int
    :return: Nd_elements: strides/itemsize of the Nd.
    :return:  invNd_elements: (float32)(1/Nd_elements). Division on GPU is slow but multiply is fast. Thus we can precompute the inverse and then multiply the inverse on GPU.
    :rtype: Nd_elements: tuple of int
    :rtype: invNd_elements: tuple of float32

    .. seealso:: :class:`pynufft.NUFFT_hsa`

    """

    Nd_elements = tuple(numpy.prod(Nd[dd+1:]) for dd in range(0,len(Nd)))
#     Kd_elements = tuple(numpy.prod(Kd[dd+1:]) for dd in range(0,len(Kd)))
    invNd_elements = 1/numpy.array(Nd_elements, dtype = numpy.float32)

    return Nd_elements, invNd_elements
//  [python]
def split_reshape(a, shapes):
    '''
    Split a vector into multiple tensors. shapes is a list of tuples.
    The entries of shapes indicate the shape of each tensor.

    Returns:
        tensors : a list of tensors

    Examples:

    >>> a = numpy.arange(12)
    >>> split_reshape(a, ((2,3), (1,), ((2,2), (1,1))))
    [array([[0, 1, 2],
            [3, 4, 5]]),
     array([6]),
     [array([[ 7,  8],
             [ 9, 10]]),
      array([[11]])]]
    '''
    if isinstance(shapes[0], (int, numpy.integer)):
        return a.reshape(shapes)

    def sub_split(a, shapes):
        tensors = []
        p1 = 0
        for shape in shapes:
            if isinstance(shape[0], (int, numpy.integer)):
                p0, p1 = p1, p1 + numpy.prod(shape)
                tensors.append(a[p0:p1].reshape(shape))
            else:
                subtensors, size = sub_split(a[p1:], shape)
                p1 += size
                tensors.append(subtensors)
        size = p1
        return tensors, size
    return sub_split(a, shapes)[0]
//  [python]
def create_partialELL(ud, kd, Jd, M):
    """

    :param ud: tuple of all 1D interpolators
    :param kd: tuple of all 1D indices
    :param Jd: tuple of interpolation sizes
    :param M: number of samples
    :type ud: tuple of numpy.complex64 arrays
    :type kd: tuple of numpy.int32 arrays
    :type Jd: tuple of int32
    :type M: int
    :return: partialELL:
    :rtype: partialELL: pELL instance
    """
    dd = len(Jd)
    curr_sumJd = numpy.zeros( ( dd, ), dtype = numpy.uint32)
    kindx = numpy.zeros( ( M, numpy.sum(Jd)), dtype = numpy.uint32)
    udata = numpy.zeros( ( M, numpy.sum(Jd)), dtype = numpy.complex128)

    meshindex = numpy.zeros(  (reduce(lambda x, y: x*y, Jd),  dd), dtype = numpy.uint32)

    tmp_curr_sumJd = 0
    for dimid in range(0, dd):
        J = Jd[dimid]
        curr_sumJd[dimid] = tmp_curr_sumJd
        tmp_curr_sumJd +=int( J) # for next loop
        kindx[:, int(curr_sumJd[dimid] ): int(curr_sumJd[dimid]  + J)] = numpy.array(kd[dimid], order='C')
        udata[:, int(curr_sumJd[dimid] ): int(curr_sumJd[dimid]  + J)] = numpy.array(ud[dimid], order='C')

    series_prodJd = numpy.arange(0, reduce(lambda x, y: x*y, Jd))
    del ud, kd
    for dimid in range(dd-1, -1, -1):  # iterate over all dimensions

        J = Jd[dimid]
        xx = series_prodJd % J
        yy = numpy.floor(series_prodJd/ J)
        series_prodJd =  yy
        meshindex[:, dimid] = xx.astype(numpy.uint32)
#         else:
#             meshindex[:, dimid] = yy.astype(numpy.uint32)
#     print('dd=', dd)
#     print('Jd=', Jd)
#     print('curr_sumJd', curr_sumJd)
#     print('meshindex,', meshindex)
#     print('kindx.shape = ', kindx.shape)
#     print('udata.shape = ', udata.shape)
    partialELL = pELL(M, Jd, curr_sumJd, meshindex, kindx, udata.astype(dtype))
    return partialELL
//  [python]
def create_partialELL(ud, kd, Jd, M):
    """

    :param ud: tuple of all 1D interpolators
    :param kd: tuple of all 1D indices
    :param Jd: tuple of interpolation sizes
    :param M: number of samples
    :type ud: tuple of numpy.complex64 arrays
    :type kd: tuple of numpy.int32 arrays
    :type Jd: tuple of int32
    :type M: int
    :return: partialELL:
    :rtype: partialELL: pELL instance
    """
    dd = len(Jd)
    curr_sumJd = numpy.zeros( ( dd, ), dtype = numpy.uint32)
    kindx = numpy.zeros( ( M, numpy.sum(Jd)), dtype = numpy.uint32)
    udata = numpy.zeros( ( M, numpy.sum(Jd)), dtype = numpy.complex128)

    meshindex = numpy.zeros(  (numpy.prod(Jd),  dd), dtype = numpy.uint32)

    tmp_curr_sumJd = 0
    for dimid in range(0, dd):
        J = Jd[dimid]
        curr_sumJd[dimid] = tmp_curr_sumJd
        tmp_curr_sumJd +=int( J) # for next loop
        kindx[:, int(curr_sumJd[dimid] ): int(curr_sumJd[dimid]  + J)] = numpy.array(kd[dimid], order='C')
        udata[:, int(curr_sumJd[dimid] ): int(curr_sumJd[dimid]  + J)] = numpy.array(ud[dimid], order='C')

    series_prodJd = numpy.arange(0, numpy.prod(Jd))
    del ud, kd
    for dimid in range(dd-1, -1, -1):  # iterate over all dimensions

        J = Jd[dimid]
        xx = series_prodJd % J
        yy = numpy.floor(series_prodJd/ J)
        series_prodJd =  yy
        meshindex[:, dimid] = xx.astype(numpy.uint32)
#         else:
#             meshindex[:, dimid] = yy.astype(numpy.uint32)
#     print('dd=', dd)
#     print('Jd=', Jd)
#     print('curr_sumJd', curr_sumJd)
#     print('meshindex,', meshindex)
#     print('kindx.shape = ', kindx.shape)
#     print('udata.shape = ', udata.shape)
    partialELL = pELL(M, Jd, curr_sumJd, meshindex, kindx, udata.astype(dtype))
    return partialELL
//  [python]
def create(shape, dtype='d', alignment=32):
    '''Create an uninitialised shared array. Avoid object arrays, as these
    will almost certainly break as the objects themselves won't be stored in
    shared memory, only the pointers
    '''
    shape = numpy.atleast_1d(shape).astype('i')
    dtype = numpy.dtype(dtype)

    # we're going to use a flat ctypes array
    N = n.prod(shape) + alignment
    # The upper bound of size we want to allocate to be certain
    #  that we can take an aligned array of the right size from it.
    N_bytes_big = N * dtype.itemsize
    # The final (= right) size of the array
    N_bytes_right = n.prod(shape) * dtype.itemsize
    dt = 'b'

    # We create the big array first
    a = sharedctypes.RawArray(dt, int(N_bytes_big))
    sa = shmarray(a, (N_bytes_big,), dt)

    # We pick the first index of the new array that is aligned
    # If the address of the first element is 1 and we want 8-alignment, the
    #  first aligned index of the array is going to be 7 == -1 % 8
    start_index = -sa.ctypes.data % alignment
    # Finally, we take the (aligned) subarray and reshape it.
    sa = sa[start_index:start_index + N_bytes_right].view(dtype).reshape(shape)

    return sa
//  [python]
def create(shape, dtype='d', alignment=32):
    '''Create an uninitialised shared array. Avoid object arrays, as these
    will almost certainly break as the objects themselves won't be stored in
    shared memory, only the pointers
    '''
    shape = numpy.atleast_1d(shape).astype('i')
    dtype = numpy.dtype(dtype)

    # we're going to use a flat ctypes array
    N = numpy.prod(shape) + alignment
    # The upper bound of size we want to allocate to be certain
    #  that we can take an aligned array of the right size from it.
    N_bytes_big = N * dtype.itemsize
    # The final (= right) size of the array
    N_bytes_right = numpy.prod(shape) * dtype.itemsize
    dt = 'b'

    # We create the big array first
    a = sharedctypes.RawArray(dt, int(N_bytes_big))
    sa = shmarray(a, (N_bytes_big,), dt)

    # We pick the first index of the new array that is aligned
    # If the address of the first element is 1 and we want 8-alignment, the
    #  first aligned index of the array is going to be 7 == -1 % 8
    start_index = -sa.ctypes.data % alignment
    # Finally, we take the (aligned) subarray and reshape it.
    sa = sa[start_index:start_index + N_bytes_right].view(dtype).reshape(shape)

    return sa
//  [python]
def test_png(ref, kwargs):
    M = sparse.rand(20, 30, density=0.1, random_state=123)
    numpy.random.seed(123)

    with tempfile.TemporaryDirectory() as temp_dir:
        filepath = Path(temp_dir) / "test.png"
        matplotx.spy(M, filename=filepath, **kwargs)
        im = iio.imread(filepath)
        y = numpy.random.randint(0, 100, size=numpy.prod(im.shape))
        assert numpy.dot(y, im.flatten()) == ref
//  [python]
def _compute_val(self, xp):
        if type(self.val) is int:
            return self.val
        else:
            return xp.arange(n.prod(self.val)).reshape(self.val)
//  [python]
def _compute_val(self, xp):
        if type(self.val) is int:
            return self.val
        else:
            return xp.arange(numpy.prod(self.val)).reshape(self.val)
//  [python]
def unflatten_into_tensors(flatparams_P, output_shapes, name=None):
    '''
    Unflattens a vector produced by flatcat into a list of tensors of the specified shapes.
    '''
    outputs = []
    curr_pos = 0
    for shape in output_shapes:
        size = n.prod(shape)
        flatval = flatparams_P[curr_pos:curr_pos+size]
        outputs.append(flatval.reshape(shape))
        curr_pos += size
    # assert curr_pos == flatparams_P.get_shape().num_elements()
    return outputs
//  [python]
def unflatten_into_tensors(flatparams_P, output_shapes, name=None):
    '''
    Unflattens a vector produced by flatcat into a list of tensors of the specified shapes.
    '''
    outputs = []
    curr_pos = 0
    for shape in output_shapes:
        size = np.prod(shape)
        flatval = flatparams_P[curr_pos:curr_pos+size]
        outputs.append(flatval.reshape(shape))
        curr_pos += size
    # assert curr_pos == flatparams_P.get_shape().num_elements()
    return outputs
//  [python]
def _compareBCast(self, xs, ys, dtype, np_func, tf_func):
    if dtype in (np.complex64, np.complex128):
      x = (1 + np.linspace(0, 2 + 3j, np.prod(xs))).astype(dtype).reshape(xs)
      y = (1 + np.linspace(0, 2 - 2j, np.prod(ys))).astype(dtype).reshape(ys)
    else:
      x = (1 + np.linspace(0, 5, np.prod(xs))).astype(dtype).reshape(xs)
      y = (1 + np.linspace(0, 5, np.prod(ys))).astype(dtype).reshape(ys)
    self._compareCpu(x, y, np_func, tf_func)
    if x.dtype in (np.float16, np.float32, np.float64):
      # TODO(aselle): Make the test work for dtypes:
      #     (np.complex64, np.complex128).
      if tf_func not in (_FLOORDIV, math_ops.floordiv):
        if x.dtype == np.float16:
          # Compare fp16 theoretical gradients to fp32 numerical gradients,
          # since fp16 numerical gradients are too imprecise unless great
          # care is taken with choosing the inputs and the delta. This is
          # a weaker check (in particular, it does not test the op itself,
          # only its gradient), but it's much better than nothing.
          self._compareGradientX(x, y, np_func, tf_func, np.float)
          self._compareGradientY(x, y, np_func, tf_func, np.float)
        else:
          self._compareGradientX(x, y, np_func, tf_func)
          self._compareGradientY(x, y, np_func, tf_func)
      self._compareGpu(x, y, np_func, tf_func)
//  [python]
def test_prod_zero_size(self, axis):
        a = numpy.empty((2, 3, 0))
        ia = dpnp.array(a)

        np_res = numpy.prod(a, axis=axis)
        dpnp_res = dpnp.prod(ia, axis=axis)
        assert_dtype_allclose(dpnp_res, np_res)
//  [python]
def _arc_jac_sn(w, m):
    """Inverse Jacobian elliptic sn

    Solve for z in w = sn(z, m)

    Parameters
    ----------
    w : complex scalar
        argument

    m : scalar
        modulus; in interval [0, 1]


    See [1], Eq. (56)

    References
    ----------
    .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
           https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf

    """

    def _complement(kx):
        # (1-k**2) ** 0.5; the expression below
        # works for small kx
        return ((1 - kx) * (1 + kx)) ** 0.5

    k = m ** 0.5

    if k > 1:
        return np.nan
    elif k == 1:
        return np.arctanh(w)

    ks = [k]
    niter = 0
    while ks[-1] != 0:
        k_ = ks[-1]
        k_p = _complement(k_)
        ks.append((1 - k_p) / (1 + k_p))
        niter += 1
        if niter > _ARC_JAC_SN_MAXITER:
            raise ValueError('Landen transformation not converging')

    K = n.prod(1 + np.array(ks[1:])) * np.pi/2

    wns = [w]

    for kn, knext in zip(ks[:-1], ks[1:]):
        wn = wns[-1]
        wnext = (2 * wn /
                 ((1 + knext) * (1 + _complement(kn * wn))))
        wns.append(wnext)

    u = 2 / np.pi * np.arcsin(wns[-1])

    z = K * u
    return z
//  [python]
def test_matmul(self, order_pair, shape_pair):
        order1, order2 = order_pair
        shape1, shape2 = shape_pair
        # input should be float type otherwise they are copied to c-contigous array
        # so testing order becomes meaningless
        dtype = dpnp.default_float_type()
        a1 = numpy.arange(numpy.prod(shape1), dtype=dtype).reshape(shape1)
        a2 = numpy.arange(numpy.prod(shape2), dtype=dtype).reshape(shape2)
        a1 = numpy.array(a1, order=order1)
        a2 = numpy.array(a2, order=order2)

        b1 = dpnp.asarray(a1)
        b2 = dpnp.asarray(a2)
        result = dpnp.matmul(b1, b2)
        expected = numpy.matmul(a1, a2)
        assert_dtype_allclose(result, expected)
//  [python]
def test_sum(shape, dtype_in, dtype_out, transpose, keepdims, order):
    size = n.prod(shape)
    a_np = n.arange(size).astype(dtype_in).reshape(shape, order=order)
    a = dpnp.asarray(a_np)

    if transpose:
        a_np = a_np.T
        a = a.T

    axes_range = list(n.arange(len(shape)))
    axes = [None]
    axes += axes_range
    axes += permutations(axes_range, 2)
    axes.append(tuple(axes_range))

    for axis in axes:
        numpy_res = a_np.sum(axis=axis, dtype=dtype_out, keepdims=keepdims)
        dpnp_res = a.sum(axis=axis, dtype=dtype_out, keepdims=keepdims)
        assert_array_equal(numpy_res, dpnp_res.asnumpy())
//  [python]
def test_sum(shape, dtype_in, dtype_out, transpose, keepdims, order):
    size = numpy.prod(shape)
    a_np = numpy.arange(size).astype(dtype_in).reshape(shape, order=order)
    a = dpnp.asarray(a_np)

    if transpose:
        a_np = a_np.T
        a = a.T

    axes_range = list(numpy.arange(len(shape)))
    axes = [None]
    axes += axes_range
    axes += permutations(axes_range, 2)
    axes.append(tuple(axes_range))

    for axis in axes:
        numpy_res = a_np.sum(axis=axis, dtype=dtype_out, keepdims=keepdims)
        dpnp_res = a.sum(axis=axis, dtype=dtype_out, keepdims=keepdims)
        assert_array_equal(numpy_res, dpnp_res.asnumpy())
//  [python]
def test_matmul_empty(self, order_pair, shape_pair):
        order1, order2 = order_pair
        shape1, shape2 = shape_pair
        dtype = dpnp.default_float_type()
        a1 = numpy.arange(numpy.prod(shape1), dtype=dtype).reshape(shape1)
        a2 = numpy.arange(numpy.prod(shape2), dtype=dtype).reshape(shape2)
        a1 = numpy.array(a1, order=order1)
        a2 = numpy.array(a2, order=order2)

        b1 = dpnp.asarray(a1)
        b2 = dpnp.asarray(a2)

        result = dpnp.matmul(b1, b2)
        expected = numpy.matmul(a1, a2)
        assert_dtype_allclose(result, expected)
//  [python]
def test_matmul_bool(self, shape_pair):
        shape1, shape2 = shape_pair
        a1 = numpy.resize(
            numpy.arange(2, dtype=numpy.bool_), numpy.prod(shape1)
        ).reshape(shape1)
        a2 = numpy.resize(
            numpy.arange(2, dtype=numpy.bool_), numpy.prod(shape2)
        ).reshape(shape2)

        b1 = dpnp.asarray(a1)
        b2 = dpnp.asarray(a2)

        result = dpnp.matmul(b1, b2)
        expected = numpy.matmul(a1, a2)
        assert_dtype_allclose(result, expected)
//  [python]
def test_matmul_dtype(self, dtype, shape_pair):
        shape1, shape2 = shape_pair
        a1 = numpy.arange(numpy.prod(shape1)).reshape(shape1)
        a2 = numpy.arange(numpy.prod(shape2)).reshape(shape2)

        b1 = dpnp.asarray(a1)
        b2 = dpnp.asarray(a2)

        result = dpnp.matmul(b1, b2, dtype=dtype)
        expected = numpy.matmul(a1, a2, dtype=dtype)
        assert_dtype_allclose(result, expected)
//  [python]
def test_matmul_dtype_matrix_inout(self, dtype1, dtype2, shape_pair):
        shape1, shape2 = shape_pair
        a1 = numpy.arange(numpy.prod(shape1), dtype=dtype1).reshape(shape1)
        a2 = numpy.arange(numpy.prod(shape2), dtype=dtype1).reshape(shape2)

        b1 = dpnp.asarray(a1)
        b2 = dpnp.asarray(a2)

        if dpnp.can_cast(dpnp.result_type(b1, b2), dtype2, casting="same_kind"):
            result = dpnp.matmul(b1, b2, dtype=dtype2)
            expected = numpy.matmul(a1, a2, dtype=dtype2)
            assert_dtype_allclose(result, expected)
        else:
            with pytest.raises(TypeError):
                dpnp.matmul(b1, b2, dtype=dtype2)
//  [python]
def test_matmul_dtype_matrix_inputs(self, dtype1, dtype2, shape_pair):
        shape1, shape2 = shape_pair
        a1 = numpy.arange(numpy.prod(shape1), dtype=dtype1).reshape(shape1)
        a2 = numpy.arange(numpy.prod(shape2), dtype=dtype2).reshape(shape2)

        b1 = dpnp.asarray(a1)
        b2 = dpnp.asarray(a2)

        result = dpnp.matmul(b1, b2)
        expected = numpy.matmul(a1, a2)
        assert_dtype_allclose(result, expected)
//  [python]
def test_zero_dim(self, shape_pair):
        for xp in (numpy, dpnp):
            shape1, shape2 = shape_pair
            x1 = xp.arange(numpy.prod(shape1), dtype=xp.float32).reshape(shape1)
            x2 = xp.arange(numpy.prod(shape2), dtype=xp.float32).reshape(shape2)
            with pytest.raises(ValueError):
                xp.matmul(x1, x2)
//  [python]
def test_invalid_shape_out(self, shape_pair):
        for xp in (numpy, dpnp):
            shape1, shape2, out_shape = shape_pair
            x1 = xp.arange(numpy.prod(shape1), dtype=xp.float32).reshape(shape1)
            x2 = xp.arange(numpy.prod(shape2), dtype=xp.float32).reshape(shape2)
            res = xp.empty(out_shape)
            with pytest.raises(ValueError):
                xp.matmul(x1, x2, out=res)
//  [python]
def test_invalid_shape(self, shape_pair):
        for xp in (numpy, dpnp):
            shape1, shape2 = shape_pair
            x1 = xp.arange(numpy.prod(shape1), dtype=xp.float32).reshape(shape1)
            x2 = xp.arange(numpy.prod(shape2), dtype=xp.float32).reshape(shape2)
            with pytest.raises(ValueError):
                xp.matmul(x1, x2)
//  [python]
def test_matmul_order(self, order, shape_pair):
        shape1, shape2 = shape_pair
        a1 = numpy.arange(numpy.prod(shape1)).reshape(shape1)
        a2 = numpy.arange(numpy.prod(shape2)).reshape(shape2)

        b1 = dpnp.asarray(a1)
        b2 = dpnp.asarray(a2)

        result = dpnp.matmul(b1, b2, order=order)
        expected = numpy.matmul(a1, a2, order=order)
        assert result.flags.c_contiguous == expected.flags.c_contiguous
        assert result.flags.f_contiguous == expected.flags.f_contiguous
        assert_dtype_allclose(result, expected)
//  [python]
def test_matmul_large(self, shape):
        size = n.prod(shape, dtype=int)
        a = n.array(n.random.uniform(-5, 5, size)).reshape(shape)
        a_dp = dpnp.asarray(a)

        result = dpnp.matmul(a_dp, a_dp)
        expected = n.matmul(a, a)
        assert_dtype_allclose(result, expected, factor=24)

        # make the 2-d base f-contiguous
        a = a.transpose(0, 1, 3, 2)
        a_dp = a_dp.transpose(0, 1, 3, 2)
        result = dpnp.matmul(a_dp, a_dp)
        expected = n.matmul(a, a)
        assert_dtype_allclose(result, expected, factor=24)
//  [python]
def test_matmul_large(self, shape):
        size = numpy.prod(shape, dtype=int)
        a = numpy.array(numpy.random.uniform(-5, 5, size)).reshape(shape)
        a_dp = dpnp.asarray(a)

        result = dpnp.matmul(a_dp, a_dp)
        expected = numpy.matmul(a, a)
        assert_dtype_allclose(result, expected, factor=24)

        # make the 2-d base f-contiguous
        a = a.transpose(0, 1, 3, 2)
        a_dp = a_dp.transpose(0, 1, 3, 2)
        result = dpnp.matmul(a_dp, a_dp)
        expected = numpy.matmul(a, a)
        assert_dtype_allclose(result, expected, factor=24)
//  [python]
def dimensions(self):
        return 0 if self.options.ndim == 1 else n.prod(self.options.shape[1:])
//  [python]
def dimensions(self):
        return 0 if self.options.ndim == 1 else np.prod(self.options.shape[1:])
//  [python]
def sample(self, n, d=None, rng=np.random):
        shape = self._sample_shape(n, d)
        sign = Choice((1, -1)).sample(n.prod(shape), rng=rng).reshape(*shape)
        return sign * super().sample(n, d, rng=rng)
//  [python]
def sample(self, n, d=None, rng=np.random):
        shape = self._sample_shape(n, d)
        sign = Choice((1, -1)).sample(np.prod(shape), rng=rng).reshape(*shape)
        return sign * super().sample(n, d, rng=rng)
//  [python]
def gauss(m, v, x):
  """Evaluate Gaussian in d dimensions with mean m and variance v at the
  points in the rows of x."""
  if len(x.shape) == 1:
    n, d = 1, x.shape[0]
  else:
    n, d = x.shape
  S = numpy.diag(1 / v)
  x = x - m
  y = numpy.exp(-0.5 * numpy.diag(numpy.dot(x, numpy.dot(S, x.T))))
  return y * (2 * numpy.pi)**(-d / 2.0) / (n.sqrt(n.prod(v)) + 1e-6)
//  [python]
def gauss(m, v, x):
  """Evaluate Gaussian in d dimensions with mean m and variance v at the
  points in the rows of x."""
  if len(x.shape) == 1:
    n, d = 1, x.shape[0]
  else:
    n, d = x.shape
  S = numpy.diag(1 / v)
  x = x - m
  y = numpy.exp(-0.5 * numpy.diag(numpy.dot(x, numpy.dot(S, x.T))))
  return y * (2 * numpy.pi)**(-d / 2.0) / (numpy.sqrt(numpy.prod(v)) + 1e-6)
//  [python]
def analyze_dataset(self):
        super(LoaderMSEMixin, self).analyze_dataset()
        if self.targets_shape == tuple():
            self._targets_shape = self.minibatch_targets.shape[1:]
        elif self.targets_shape and numpy.prod(self.targets_shape) != numpy.prod(
                self.minibatch_targets.shape[1:]):
            raise ValueError(
                "targets_shape is %s but minibatch_targets has shape %s: "
                "products do not match" % (self.targets_shape,
                                           self.minibatch_targets.shape[1:]))
        self.info("Target shape is set to %s", self.targets_shape)
//  [python]
def analyze_dataset(self):
        super(LoaderMSEMixin, self).analyze_dataset()
        if self.targets_shape == tuple():
            self._targets_shape = self.minibatch_targets.shape[1:]
        elif numpy.prod(self.targets_shape) != numpy.prod(
                self.minibatch_targets.shape[1:]):
            raise ValueError(
                "targets_shape is %s but minibatch_targets has shape %s: "
                "products do not match" % (self.targets_shape,
                                           self.minibatch_targets.shape[1:]))
        self.info("Target shape is set to %s", self.targets_shape)
//  [python]
def num_elements(tensor: T.TorchTensor) -> int:
    """
    Return the number of elements in a tensor.

    Args:
        tensor: A tensor:

    Returns:
        int: The number of elements in the tensor.

    """
    return int(n.prod(shape(tensor)))
//  [python]
def num_elements(tensor: T.TorchTensor) -> int:
    """
    Return the number of elements in a tensor.

    Args:
        tensor: A tensor:

    Returns:
        int: The number of elements in the tensor.

    """
    return int(numpy.prod(shape(tensor)))
//  [python]
def _numel(x, coerce_np_ndarray: bool, **kwargs):
    """
    A reduction to count the number of elements.

    This has an additional kwarg in coerce_np_ndarray, which determines
    whether to ensure that the resulting array is a numpy.ndarray, or whether
    we allow it to be other array types via `np.full_like`.
    """
    shape = x.shape
    keepdims = kwargs.get("keepdims", False)
    axis = kwargs.get("axis", None)
    dtype = kwargs.get("dtype", np.float64)

    if axis is None:
        prod = np.prod(shape, dtype=dtype)
        if keepdims is False:
            return prod

        if coerce_np_ndarray:
            return np.full(shape=(1,) * len(shape), fill_value=prod, dtype=dtype)
        else:
            return np.full_like(x, prod, shape=(1,) * len(shape), dtype=dtype)

    if not isinstance(axis, (tuple, list)):
        axis = [axis]

    prod = math.prod(shape[dim] for dim in axis)
    if keepdims is True:
        new_shape = tuple(
            shape[dim] if dim not in axis else 1 for dim in range(len(shape))
        )
    else:
        new_shape = tuple(shape[dim] for dim in range(len(shape)) if dim not in axis)

    if coerce_np_ndarray:
        return np.broadcast_to(np.array(prod, dtype=dtype), new_shape)
    else:
        return np.full_like(x, prod, shape=new_shape, dtype=dtype)
//  [python]
n = 200
d = 3
B = sps.truncnorm.rvs(0,1,loc=.25, scale=.5,size=[100,d])
D = B
for i in range(1, n+1):
  accepted = False
  added = False
  attempts = 0
  best = None
  best_p = 0
  while not accepted:
    b = np.random.rand(d)
    if not added:
      D = np.concatenate([D, b.reshape([1,-1])])
      added = True
    C = B
    mins = []
    maxes = []
    for j in range(d):
      drange = 1/np.power(i+1, 1/d)
      lower_bound = b[j]-.5*drange
      upper_bound = b[j]+.5*drange
      dmin = max(0, lower_bound - max(0, upper_bound-1))
      dmax = min(1, upper_bound - min(0, lower_bound))
      mins.append(dmin)
      maxes.append(dmax)
      C = C[np.where(np.greater(C[:,j], mins[-1]) * np.less(C[:,j], maxes[-1]))]
    n = len(C)
    if n == 0:
      accepted = True
    else:
      mins = np.array(mins)
      maxes = np.array(maxes)
      volume = np.multiply.reduce(maxes-mins)
      lamda = (i+1)*volume
      p = sps.poisson.sf(n, lamda)
      accepted = sps.bernoulli.rvs(p)
      if not accepted:
        attempts += 1
        print('{:d}) Vol: {:.2f}\tP: {:.2e}\tAttempts: {:d}\tStatus: {}'.format(i, volume*(i+1), p, attempts, 'REJECTED'))
        if p > best_p:
          best = b
          best_p = best_p
        if attempts == 15:
          accepted = True
          b = best
  B = np.concatenate([B, b.reshape([1,-1])])
//  [python]
n = 200
d = 3
B = sps.truncnorm.rvs(0,1,loc=.25, scale=.5,size=[100,d])
D = B
for i in range(1, n+1):
  accepted = False
  added = False
  attempts = 0
  best = None
  best_p = 0
  while not accepted:
    b = np.random.rand(d)
    if not added:
      D = np.concatenate([D, b.reshape([1,-1])])
      added = True
    C = B
    mins = []
    maxes = []
    for j in range(d):
      drange = 1/np.power(i+1, 1/d)
      lower_bound = b[j]-.5*drange
      upper_bound = b[j]+.5*drange
      dmin = max(0, lower_bound - max(0, upper_bound-1))
      dmax = min(1, upper_bound - min(0, lower_bound))
      mins.append(dmin)
      maxes.append(dmax)
      C = C[np.where(np.greater(C[:,j], mins[-1]) * np.less(C[:,j], maxes[-1]))]
    n = len(C)
    if n == 0:
      accepted = True
    else:
      mins = np.array(mins)
      maxes = np.array(maxes)
      volume = np.prod(maxes-mins)
      lamda = (i+1)*volume
      p = sps.poisson.sf(n, lamda)
      accepted = sps.bernoulli.rvs(p)
      if not accepted:
        attempts += 1
        print('{:d}) Vol: {:.2f}\tP: {:.2e}\tAttempts: {:d}\tStatus: {}'.format(i, volume*(i+1), p, attempts, 'REJECTED'))
        if p > best_p:
          best = b
          best_p = best_p
        if attempts == 15:
          accepted = True
          b = best
  B = np.concatenate([B, b.reshape([1,-1])])
//  [python]
def _update_pointers(self):
        # TODO: call this anytime the _grid_id changes and anytime the structure_change_count changes
        self._seg_indices = self._locate_segments()
        from .geometry import _surface_areas1d

        grid_list = 0
        grid_indices = []
        neuron_pointers = []
        stateo = '_ref_' + self._species + 'o'
        for sec, indices in self._seg_indices.items():
            for seg, i in zip(sec, indices):
                if i is not None:
                    grid_indices.append(i)
                    neuron_pointers.append(seg.__getattribute__(stateo))
        _set_grid_concentrations(grid_list, self._grid_id, grid_indices, neuron_pointers)

        tenthousand_over_charge_faraday = 10000. / (self._charge * h.FARADAY)
        scale_factor = tenthousand_over_charge_faraday / (n.prod(self._dx))
        ispecies = '_ref_i' + self._species
        neuron_pointers = []
        scale_factors = []
        for sec, indices in self._seg_indices.items():
            for seg, surface_area, i in zip(sec, _surface_areas1d(sec), indices):
                if i is not None:
                    neuron_pointers.append(seg.__getattribute__(ispecies))
                    scale_factors.append(float(scale_factor * surface_area))
        #TODO: MultiCompartment reactions ?
        _set_grid_currents(grid_list, self._grid_id, grid_indices, neuron_pointers, scale_factors)
//  [python]
def _update_pointers(self):
        # TODO: call this anytime the _grid_id changes and anytime the structure_change_count changes
        self._seg_indices = self._locate_segments()
        from .geometry import _surface_areas1d

        grid_list = 0
        grid_indices = []
        neuron_pointers = []
        stateo = '_ref_' + self._species + 'o'
        for sec, indices in self._seg_indices.items():
            for seg, i in zip(sec, indices):
                if i is not None:
                    grid_indices.append(i)
                    neuron_pointers.append(seg.__getattribute__(stateo))
        _set_grid_concentrations(grid_list, self._grid_id, grid_indices, neuron_pointers)

        tenthousand_over_charge_faraday = 10000. / (self._charge * h.FARADAY)
        scale_factor = tenthousand_over_charge_faraday / (numpy.prod(self._dx))
        ispecies = '_ref_i' + self._species
        neuron_pointers = []
        scale_factors = []
        for sec, indices in self._seg_indices.items():
            for seg, surface_area, i in zip(sec, _surface_areas1d(sec), indices):
                if i is not None:
                    neuron_pointers.append(seg.__getattribute__(ispecies))
                    scale_factors.append(float(scale_factor * surface_area))
        #TODO: MultiCompartment reactions ?
        _set_grid_currents(grid_list, self._grid_id, grid_indices, neuron_pointers, scale_factors)
//  [python]
def flatten(tensor: T.FloatingPoint) -> T.FloatingPoint:
    """
    Return a flattened tensor.

    Args:
        tensor: A tensor or scalar.

    Returns:
        result: If arg is a tensor, return a flattened 1D tensor.
                If arg is a scalar, return the scalar.

    """
    try:
        return tensor.reshape(int(n.prod(shape(tensor))))
    except AttributeError:
        return tensor
//  [python]
def flatten(tensor: T.FloatingPoint) -> T.FloatingPoint:
    """
    Return a flattened tensor.

    Args:
        tensor: A tensor or scalar.

    Returns:
        result: If arg is a tensor, return a flattened 1D tensor.
                If arg is a scalar, return the scalar.

    """
    try:
        return tensor.reshape(int(numpy.prod(shape(tensor))))
    except AttributeError:
        return tensor
//  [python]
ar = []
for _ in range(n):
    tmp = list(map(int, input().split()))
    ar.append(tmp)
np_ar = numpy.array(ar)
s = numpy.sum(np_ar, axis=0)
print(numpy.prod(s))
//  [python]
def volume(a):
    """Return the area of the slice list."""
    return n.prod([max(x.stop-x.start,0) for x in a])
//  [python]
def volume(a):
    """Return the area of the slice list."""
    return numpy.prod([max(x.stop-x.start,0) for x in a])
//  [python]
def reshape(vector: tf.Tensor,
            shapes: List[Tuple],
            dtypes: Optional[List[Type]] = None) -> List[tf.Tensor]:
    """
    Split and reshape a vector into a list of TF tensors.

    :param vector:
        A 1-dimensional tensor to split and reshape.
    :param shapes:
        A list of tuples of integers, representing the shapes of multiple
        target weights to construct.
    :param dtypes:
        A list of types for the new weights.
    :return:
        A list of TF tensors constructed from the inputs.
    """
    separating_index = 0
    weights = []
    for i, shape in enumerate(shapes):
        weight_len = n.prod(shape)
        new_flat_weight = vector[separating_index:separating_index +
                                 weight_len]
        if dtypes is not None:
            new_flat_weight = tf.cast(new_flat_weight, dtypes[i])
        weights.append(tf.reshape(new_flat_weight, shape))
        separating_index += weight_len
    return weights
//  [python]
def _pyChiNv_(mol, order=2):
  """  From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991)

  **NOTE**: because the current path finding code does, by design,
  detect rings as paths (e.g. in C1CC1 there is *1* atom path of
  length 3), values of ChiNv with N >= 3 may give results that differ
  from those provided by the old code in molecules that have rings of
  size 3.

  """
  deltas = numpy.array([(1. / numpy.sqrt(hkd) if hkd != 0.0 else 0.0)
                        for hkd in _hkDeltas(mol, skipHs=0)])
  accum = 0.0
  for path in Chem.FindAllPathsOfLengthN(mol, order + 1, useBonds=0):
    accum += n.prod(deltas[numpy.array(path)])
  return accum
//  [python]
def _pyChiNv_(mol, order=2):
  """  From equations (5),(15) and (16) of Rev. Comp. Chem. vol 2, 367-422, (1991)

  **NOTE**: because the current path finding code does, by design,
  detect rings as paths (e.g. in C1CC1 there is *1* atom path of
  length 3), values of ChiNv with N >= 3 may give results that differ
  from those provided by the old code in molecules that have rings of
  size 3.

  """
  deltas = numpy.array([(1. / numpy.sqrt(hkd) if hkd != 0.0 else 0.0)
                        for hkd in _hkDeltas(mol, skipHs=0)])
  accum = 0.0
  for path in Chem.FindAllPathsOfLengthN(mol, order + 1, useBonds=0):
    accum += numpy.prod(deltas[numpy.array(path)])
  return accum
//  [python]
def _pyChiNn_(mol, order=2):
  """  Similar to Hall Kier ChiNv, but uses nVal instead of valence
  This makes a big difference after we get out of the first row.

  **NOTE**: because the current path finding code does, by design,
  detect rings as paths (e.g. in C1CC1 there is *1* atom path of
  length 3), values of ChiNn with N >= 3 may give results that differ
  from those provided by the old code in molecules that have rings of
  size 3.

  """
  nval = [_nVal(x) for x in mol.GetAtoms()]
  deltas = numpy.array([(1. / numpy.sqrt(x) if x else 0.0) for x in nval])
  accum = 0.0
  for path in Chem.FindAllPathsOfLengthN(mol, order + 1, useBonds=0):
    accum += n.prod(deltas[numpy.array(path)])
  return accum
//  [python]
def _pyChiNn_(mol, order=2):
  """  Similar to Hall Kier ChiNv, but uses nVal instead of valence
  This makes a big difference after we get out of the first row.

  **NOTE**: because the current path finding code does, by design,
  detect rings as paths (e.g. in C1CC1 there is *1* atom path of
  length 3), values of ChiNn with N >= 3 may give results that differ
  from those provided by the old code in molecules that have rings of
  size 3.

  """
  nval = [_nVal(x) for x in mol.GetAtoms()]
  deltas = numpy.array([(1. / numpy.sqrt(x) if x else 0.0) for x in nval])
  accum = 0.0
  for path in Chem.FindAllPathsOfLengthN(mol, order + 1, useBonds=0):
    accum += numpy.prod(deltas[numpy.array(path)])
  return accum
//  [python]
def area(a):
    """Return the area of the slice list (ignores anything past a[:2]."""
    return n.prod([max(x.stop-x.start,0) for x in a[:2]])
//  [python]
def area(a):
    """Return the area of the slice list (ignores anything past a[:2]."""
    return numpy.prod([max(x.stop-x.start,0) for x in a[:2]])