jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def sample_cartesian(sets: List,
                     idx: int,
                     n: int = None) -> List:
    """
    Draw samples from the cartesian product of all iterables in sets.
    Each row in the cartesian product has a unique index. This function returns
    the row with index idx without materialising any of the other rows.

    For a cartesian products of lists with length l1, l2, ... lm, taking the cartesian
    product can be thought of as traversing through all lists picking one element of each
    and repeating this until all possible combinations are exhausted. The number of combinations
    is N=l1*l2*...*lm. This can make materialization of the list impracticle.
    By taking the first element from every list that leads to a new combination,
    we can define a unique enumeration of all combinations.

    :param sets: List of iteratbles
    :param idx: Index of desired row in the cartersian product
    :param n: Number of rows in the cartesian product
    """

    if n is None:
        n = np.prod([len(y) for y in sets])

    out = []  # prepare list to append elements to.
    width = n  # width of the index set in which the desired row falls.
    for item_set in sets:
        width = width/len(item_set)  # map index set onto first item_set
        bucket = int(np.floor(idx/width))  # determine index of the first item_set
        out.append(item_set[bucket])
        idx = idx - bucket*width  # restrict index to next item_set in the hierarchy (could use modulo operator here.)

    assert width == 1  # at the end of this procedure, the leaf index set should have width 1.

    return out
//  [python]
def test_many_decompress(self, ntest=10):
        """
        tests the byte offset decompression on GPU, many images to ensure there
        is not leaking in memory
        """
        shape = (991, 997)
        size = n.prod(shape)
        ref, raw = self._create_test_data(shape=shape, nexcept=0, lam=100)

        try:
            bo = byte_offset.ByteOffset(len(raw), size, profile=True)
        except (RuntimeError, pyopencl.RuntimeError) as err:
            logger.warning(err)
            if sys.platform == "darwin":
                raise unittest.SkipTest(
                    "Byte-offset decompression is known to be buggy on MacOS-CPU"
                )
            else:
                raise err
        t0 = time.time()
        res_cy = fabio.compression.decByteOffset(raw)
        t1 = time.time()
        res_cl = bo(raw)
        t2 = time.time()
        delta_cy = abs(ref.ravel() - res_cy).max()
        delta_cl = abs(ref.ravel() - res_cl.get()).max()
        self.assertEqual(delta_cy, 0, "Checks fabio works")
        self.assertEqual(delta_cl, 0, "Checks opencl works")
        logger.debug(
            "Global execution time: fabio %.3fms, OpenCL: %.3fms.",
            1000.0 * (t1 - t0),
            1000.0 * (t2 - t1),
        )

        for i in range(ntest):
            ref, raw = self._create_test_data(shape=shape, nexcept=2729, lam=200)

            t0 = time.time()
            res_cy = fabio.compression.decByteOffset(raw)
            t1 = time.time()
            res_cl = bo(raw)
            t2 = time.time()
            delta_cy = abs(ref.ravel() - res_cy).max()
            delta_cl = abs(ref.ravel() - res_cl.get()).max()
            self.assertEqual(delta_cy, 0, "Checks fabio works #%i" % i)
            self.assertEqual(delta_cl, 0, "Checks opencl works #%i" % i)

            logger.debug(
                "Global execution time: fabio %.3fms, OpenCL: %.3fms.",
                1000.0 * (t1 - t0),
                1000.0 * (t2 - t1),
            )
        bo.log_profile(stats=True)
//  [python]
def test_many_decompress(self, ntest=10):
        """
        tests the byte offset decompression on GPU, many images to ensure there
        is not leaking in memory
        """
        shape = (991, 997)
        size = numpy.prod(shape)
        ref, raw = self._create_test_data(shape=shape, nexcept=0, lam=100)

        try:
            bo = byte_offset.ByteOffset(len(raw), size, profile=True)
        except (RuntimeError, pyopencl.RuntimeError) as err:
            logger.warning(err)
            if sys.platform == "darwin":
                raise unittest.SkipTest(
                    "Byte-offset decompression is known to be buggy on MacOS-CPU"
                )
            else:
                raise err
        t0 = time.time()
        res_cy = fabio.compression.decByteOffset(raw)
        t1 = time.time()
        res_cl = bo(raw)
        t2 = time.time()
        delta_cy = abs(ref.ravel() - res_cy).max()
        delta_cl = abs(ref.ravel() - res_cl.get()).max()
        self.assertEqual(delta_cy, 0, "Checks fabio works")
        self.assertEqual(delta_cl, 0, "Checks opencl works")
        logger.debug(
            "Global execution time: fabio %.3fms, OpenCL: %.3fms.",
            1000.0 * (t1 - t0),
            1000.0 * (t2 - t1),
        )

        for i in range(ntest):
            ref, raw = self._create_test_data(shape=shape, nexcept=2729, lam=200)

            t0 = time.time()
            res_cy = fabio.compression.decByteOffset(raw)
            t1 = time.time()
            res_cl = bo(raw)
            t2 = time.time()
            delta_cy = abs(ref.ravel() - res_cy).max()
            delta_cl = abs(ref.ravel() - res_cl.get()).max()
            self.assertEqual(delta_cy, 0, "Checks fabio works #%i" % i)
            self.assertEqual(delta_cl, 0, "Checks opencl works #%i" % i)

            logger.debug(
                "Global execution time: fabio %.3fms, OpenCL: %.3fms.",
                1000.0 * (t1 - t0),
                1000.0 * (t2 - t1),
            )
        bo.log_profile(stats=True)
//  [python]
def __call__(self, param, grad):
        if use_xla_backend() or grad._is_external_value():
            grad = all_reduce_sum(grad, self._group)
            if self._reduce_method == "mean":
                grad /= self._group.size
            return grad
        gm = get_backwarding_grad_manager()
        assert isinstance(gm, GradManager)
        if gm not in self._marked_gm:
            gm._register_after_backward_callback(self._flush)
            self._marked_gm.add(gm)
        self._params.append(param)
        self._futures_dict[param] = TensorFuture(ack=False)
        self._gradients_dict[param] = grad
        self._grad_origin_device[param] = str(grad.device)

        dtype_str = str(np.dtype(param.dtype))
        dtype_size = np.dtype(param.dtype).itemsize
        self._packing_list[dtype_str].append(param)
        self._packing_size[dtype_str] += int(np.prod(param._tuple_shape)) * dtype_size
        if self._packing_size[dtype_str] > self._param_pack_thd:
            self._pack(dtype_str)
        return self._futures_dict[param]
//  [python]
def _test():
    import numpy as np
    import mxnet as mx

    pretrained = False
    hybridizable = True
    batch_size = 1
    # in_size = (224, 224)
    in_size = (200, 400)
    # in_size = (1000, 2000)

    models = [
        superpointnet,
    ]

    for model in models:

        net = model(pretrained=pretrained, hybridizable=hybridizable, batch_size=batch_size, in_size=in_size)

        ctx = mx.gpu(0)
        if not pretrained:
            net.initialize(ctx=ctx)

        # net.hybridize()
        net_params = net.collect_params()
        weight_count = 0
        for param in net_params.values():
            if (param.shape is None) or (not param._differentiable):
                continue
            weight_count += np.prod(param.shape)
        print("m={}, {}".format(model.__name__, weight_count))
        assert (model != superpointnet or weight_count == 1300865)

        x = mx.nd.random.normal(shape=(batch_size, 1, in_size[0], in_size[1]), ctx=ctx)
        y = net(x)
        assert (len(y) == 3)
//  [python]
def get_aabb_volume(aabb):
    if aabb_empty(aabb):
        return 0.
    return n.prod(get_aabb_extent(aabb))
//  [python]
def get_aabb_volume(aabb):
    if aabb_empty(aabb):
        return 0.
    return np.prod(get_aabb_extent(aabb))
//  [python]
def forward(self,X,*args,**kwargs):
        '''
        Transforms each sample in X to a one-dimensional array.
        Shape change according to C-order.
        '''
        self.inputshape = X.shape # N x H x W x D
        return np.reshape(X, [self.inputshape[0], np.prod(self.inputshape[1:])])
//  [python]
def forward(self,X,*args,**kwargs):
        '''
        Transforms each sample in X to a one-dimensional array.
        Shape change according to C-order.
        '''
        self.inputshape = X.shape # N x H x W x D
        return np.reshape(X, [self.inputshape[0], numpy.prod(self.inputshape[1:])])
//  [python]
def __init__(self, T, freq):
        # Harmonic oscillator approximation, breaks down at high temperatures

        if len(freq) > 0:
            freq = np.real(freq[np.isreal(freq)])

        if len(freq) > 0:

            self.Z = np.exp(np.sum(np.log(1 / (1 - np.exp( - h * freq / (kb * T))))))
    
            self.S = kb * (np.sum( h * freq / (kb * T) / (np.exp( h * freq / (kb * T)) - 1)) + np.log(self.Z))
    
            self.E = np.sum( h * freq / (np.exp( h * freq / (kb * T)) - 1))
            
        else:
            
            self.Z =  1
            self.S =  0
            self.E =  0
//  [python]
def __init__(self, T, freq):
        # Harmonic oscillator approximation, breaks down at high temperatures

        if len(freq) > 0:
            freq = np.real(freq[np.isreal(freq)])

        if len(freq) > 0:

            self.Z = np.prod(1 / (1 - np.exp( - h * freq / (kb * T))))
    
            self.S = kb * (np.sum( h * freq / (kb * T) / (np.exp( h * freq / (kb * T)) - 1)) + np.log(self.Z))
    
            self.E = np.sum( h * freq / (np.exp( h * freq / (kb * T)) - 1))
            
        else:
            
            self.Z =  1
            self.S =  0
            self.E =  0
//  [python]
def fast_selection(
        self,
        costs,
        path_segment_matrix,
        segment_lengths,
        overlap_weight,
        leftover_weight,
        max_num_worms,
    ):
        """Select the best subset of paths using a breadth-first search

        costs - the shape costs of every path

        path_segment_matrix - an N x M matrix where N are the segments
        and M are the paths. A cell is true if a path includes the segment

        segment_lengths - the length of each segment

        overlap_weight - the penalty per pixel of an overlap

        leftover_weight - the penalty per pixel of an excluded segment

        max_num_worms - maximum # of worms allowed in returned match.
        """
        current_best_subset = []
        current_best_cost = numpy.sum(segment_lengths) * leftover_weight
        current_costs = costs
        current_path_segment_matrix = path_segment_matrix.astype(int)
        current_path_choices = numpy.eye(len(costs), dtype=bool)
        for i in range(min(max_num_worms, len(costs))):
            (
                current_best_subset,
                current_best_cost,
                current_path_segment_matrix,
                current_path_choices,
            ) = self.select_one_level(
                costs,
                path_segment_matrix,
                segment_lengths,
                current_best_subset,
                current_best_cost,
                current_path_segment_matrix,
                current_path_choices,
                overlap_weight,
                leftover_weight,
            )
            if numpy.prod(current_path_choices.shape) == 0:
                break
        return current_best_subset, current_best_cost
//  [python]
def BatchMatMul(a, b):
  # A numpy implementation of tf.matmul().
  if a.ndim < 3:
    return np.dot(a, b)
  # Get the number of matrices.
  n = a.shape[:-2].prod()
  assert n == b.shape[:-2].prod()
  a_flat = np.reshape(a, tuple([n]) + a.shape[-2:])
  b_flat = np.reshape(b, tuple([n]) + b.shape[-2:])
  c_flat_shape = [n, a.shape[-2], b.shape[-1]]
  c_flat = np.empty(c_flat_shape)
  for i in range(n):
    c_flat[i, :, :] = np.dot(a_flat[i, :, :], b_flat[i, :, :])
  return np.reshape(c_flat, a.shape[:-1] + b_flat.shape[-1:])
//  [python]
def BatchMatMul(a, b):
  # A numpy implementation of tf.matmul().
  if a.ndim < 3:
    return np.dot(a, b)
  # Get the number of matrices.
  n = np.prod(a.shape[:-2])
  assert n == np.prod(b.shape[:-2])
  a_flat = np.reshape(a, tuple([n]) + a.shape[-2:])
  b_flat = np.reshape(b, tuple([n]) + b.shape[-2:])
  c_flat_shape = [n, a.shape[-2], b.shape[-1]]
  c_flat = np.empty(c_flat_shape)
  for i in range(n):
    c_flat[i, :, :] = np.dot(a_flat[i, :, :], b_flat[i, :, :])
  return np.reshape(c_flat, a.shape[:-1] + b_flat.shape[-1:])
//  [python]
def _mom(self, keys, left, right, cache):
        """
        Statistical moments.

        Example:
            >>> chaospy.Uniform().mom([0, 1, 2, 3]).round(4)
            array([1.    , 0.5   , 0.3333, 0.25  ])
            >>> chaospy.Add(chaospy.Uniform(), 2).mom([0, 1, 2, 3]).round(4)
            array([ 1.    ,  2.5   ,  6.3333, 16.25  ])
            >>> chaospy.Add(2, chaospy.Uniform()).mom([0, 1, 2, 3]).round(4)
            array([ 1.    ,  2.5   ,  6.3333, 16.25  ])

        """
        del cache
        keys_ = numpy.mgrid[tuple(slice(0, key + 1, 1) for key in keys)]
        keys_ = keys_.reshape(len(self), -1)

        if isinstance(left, Distribution):
            if chaospy.shares_dependencies(left, right):
                raise chaospy.StochasticallyDependentError(
                    "%s: left and right side of sum stochastically dependent." % self
                )
            left = [left._get_mom(key) for key in keys_.T]
        else:
            left = list(reversed(numpy.array(left).T ** keys_.T))

        if isinstance(right, Distribution):
            right = [right._get_mom(key) for key in keys_.T]
        else:
            right = list(reversed(n.prod(numpy.array(right).T ** keys_.T, -1)))

        out = 0.0
        for idx in range(keys_.shape[1]):
            key = keys_.T[idx]
            coef = numpy.prod(comb(keys, key))
            out += coef * left[idx] * right[idx] * numpy.all(key <= keys)
        return out
//  [python]
def _mom(self, keys, left, right, cache):
        """
        Statistical moments.

        Example:
            >>> chaospy.Uniform().mom([0, 1, 2, 3]).round(4)
            array([1.    , 0.5   , 0.3333, 0.25  ])
            >>> chaospy.Add(chaospy.Uniform(), 2).mom([0, 1, 2, 3]).round(4)
            array([ 1.    ,  2.5   ,  6.3333, 16.25  ])
            >>> chaospy.Add(2, chaospy.Uniform()).mom([0, 1, 2, 3]).round(4)
            array([ 1.    ,  2.5   ,  6.3333, 16.25  ])

        """
        del cache
        keys_ = numpy.mgrid[tuple(slice(0, key + 1, 1) for key in keys)]
        keys_ = keys_.reshape(len(self), -1)

        if isinstance(left, Distribution):
            if chaospy.shares_dependencies(left, right):
                raise chaospy.StochasticallyDependentError(
                    "%s: left and right side of sum stochastically dependent." % self
                )
            left = [left._get_mom(key) for key in keys_.T]
        else:
            left = list(reversed(numpy.array(left).T ** keys_.T))

        if isinstance(right, Distribution):
            right = [right._get_mom(key) for key in keys_.T]
        else:
            right = list(reversed(numpy.prod(numpy.array(right).T ** keys_.T, -1)))

        out = 0.0
        for idx in range(keys_.shape[1]):
            key = keys_.T[idx]
            coef = numpy.prod(comb(keys, key))
            out += coef * left[idx] * right[idx] * numpy.all(key <= keys)
        return out
//  [python]
def _GetSelfAdjointEigTest(dtype_, shape_):

  def CompareEigenVectors(self, x, y, tol):
    x = NormalizeEigenvectorsPhase(x)
    y = NormalizeEigenvectorsPhase(y)
    self.assertAllClose(x, y, atol=tol, rtol=tol)

  def CompareEigenDecompositions(self, x_e, x_v, y_e, y_v, tol):
    num_batches = int(np.prod(x_e.shape[:-1]))
    n = x_e.shape[-1]
    x_e = np.reshape(x_e, [num_batches] + [n])
    x_v = np.reshape(x_v, [num_batches] + [n, n])
    y_e = np.reshape(y_e, [num_batches] + [n])
    y_v = np.reshape(y_v, [num_batches] + [n, n])
    for i in range(num_batches):
      x_ei, x_vi = SortEigenDecomposition(x_e[i, :], x_v[i, :, :])
      y_ei, y_vi = SortEigenDecomposition(y_e[i, :], y_v[i, :, :])
      self.assertAllClose(x_ei, y_ei, atol=tol, rtol=tol)
      CompareEigenVectors(self, x_vi, y_vi, tol)

  def Test(self):
    np.random.seed(1)
    n = shape_[-1]
    batch_shape = shape_[:-2]
    np_dtype = dtype_.as_numpy_dtype
    a = np.random.uniform(
        low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
    if dtype_.is_complex:
      a += 1j * np.random.uniform(
          low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
    a += np.conj(a.T)
    a = np.tile(a, batch_shape + (1, 1))
    if dtype_ in (dtypes_lib.float32, dtypes_lib.complex64):
      atol = 1e-4
    else:
      atol = 1e-12
    for compute_v in False, True:
      np_e, np_v = np.linalg.eigh(a)
      with self.test_session():
        if compute_v:
          tf_e, tf_v = linalg_ops.self_adjoint_eig(constant_op.constant(a))

          # Check that V*diag(E)*V^T is close to A.
          a_ev = math_ops.matmul(
              math_ops.matmul(tf_v, array_ops.matrix_diag(tf_e)),
              tf_v,
              adjoint_b=True)
          self.assertAllClose(a_ev.eval(), a, atol=atol)

          # Compare to numpy.linalg.eigh.
          CompareEigenDecompositions(self, np_e, np_v,
                                     tf_e.eval(), tf_v.eval(), atol)
        else:
          tf_e = linalg_ops.self_adjoint_eigvals(constant_op.constant(a))
          self.assertAllClose(
              np.sort(np_e, -1), np.sort(tf_e.eval(), -1), atol=atol)

  return Test
//  [python]
def nr_rks_fxc(mydf, xc_code, dm0, dms, hermi=0, with_j=False,
               rho0=None, vxc=None, fxc=None, kpts=None, verbose=None):
    '''multigrid version of function pbc.dft.numint.nr_rks_fxc
    '''
    if kpts is None:
        kpts = numpy.zeros((1,3))
    log = logger.new_logger(mydf, verbose)
    cell = mydf.cell
    mesh = mydf.mesh
    ngrids = n.prod(mesh)

    dm_kpts = lib.asarray(dms, order='C')
    dms = _format_dms(dm_kpts, kpts)
    nset, nkpts, nao = dms.shape[:3]

    ni = mydf._numint
    xctype = ni._xc_type(xc_code)
    if xctype == 'LDA':
        deriv = 0
    elif xctype == 'GGA':
        deriv = 1
    elif xctype == 'MGGA':
        deriv = 2 if MGGA_DENSITY_LAPL else 1
        raise NotImplementedError

    weight = cell.vol / ngrids
    if rho0 is None:
        rhoG = _eval_rhoG(mydf, dm0, hermi, kpts, deriv)
        rho0 = tools.ifft(rhoG.reshape(-1,ngrids), mesh).real * (1./weight)
        if xctype == 'LDA':
            rho0 = rho0.reshape(ngrids)

    if fxc is None:
        fxc = ni.eval_xc_eff(xc_code, rho0, deriv=2, xctype=xctype)[2]

    rhoG = _eval_rhoG(mydf, dms, hermi, kpts, deriv)
    rho1 = tools.ifft(rhoG.reshape(-1,ngrids), mesh)
    if hermi == 1:
        rho1 = rho1.real
    rho1 *= (1./weight)
    rho1 = rho1.reshape(nset,-1,ngrids)
    wv = numpy.einsum('nxg,xyg->nyg', rho1, fxc)
    wv *= weight
    wv = tools.fft(wv.reshape(-1,ngrids), mesh).reshape(nset,-1,*mesh)

    if with_j:
        coulG = tools.get_coulG(cell, mesh=mesh)
        vG = rhoG[:,0] * coulG
        vG = vG.reshape(nset, *mesh)
        wv[:,0] += vG

    if xctype == 'LDA':
        veff = _get_j_pass2(mydf, wv, hermi, kpts, verbose=log)

    elif xctype == 'GGA':
        # *.5 because v+v.T is always called in _get_gga_pass2
        wv[:,0] *= .5
        veff = _get_gga_pass2(mydf, wv, hermi, kpts, verbose=log)

    return veff.reshape(dm_kpts.shape)
//  [python]
def nr_rks_fxc(mydf, xc_code, dm0, dms, hermi=0, with_j=False,
               rho0=None, vxc=None, fxc=None, kpts=None, verbose=None):
    '''multigrid version of function pbc.dft.numint.nr_rks_fxc
    '''
    if kpts is None:
        kpts = numpy.zeros((1,3))
    log = logger.new_logger(mydf, verbose)
    cell = mydf.cell
    mesh = mydf.mesh
    ngrids = numpy.prod(mesh)

    dm_kpts = lib.asarray(dms, order='C')
    dms = _format_dms(dm_kpts, kpts)
    nset, nkpts, nao = dms.shape[:3]

    ni = mydf._numint
    xctype = ni._xc_type(xc_code)
    if xctype == 'LDA':
        deriv = 0
    elif xctype == 'GGA':
        deriv = 1
    elif xctype == 'MGGA':
        deriv = 2 if MGGA_DENSITY_LAPL else 1
        raise NotImplementedError

    weight = cell.vol / ngrids
    if rho0 is None:
        rhoG = _eval_rhoG(mydf, dm0, hermi, kpts, deriv)
        rho0 = tools.ifft(rhoG.reshape(-1,ngrids), mesh).real * (1./weight)
        if xctype == 'LDA':
            rho0 = rho0.reshape(ngrids)

    if fxc is None:
        fxc = ni.eval_xc_eff(xc_code, rho0, deriv=2, xctype=xctype)[2]

    rhoG = _eval_rhoG(mydf, dms, hermi, kpts, deriv)
    rho1 = tools.ifft(rhoG.reshape(-1,ngrids), mesh)
    if hermi == 1:
        rho1 = rho1.real
    rho1 *= (1./weight)
    rho1 = rho1.reshape(nset,-1,ngrids)
    wv = numpy.einsum('nxg,xyg->nyg', rho1, fxc)
    wv *= weight
    wv = tools.fft(wv.reshape(-1,ngrids), mesh).reshape(nset,-1,*mesh)

    if with_j:
        coulG = tools.get_coulG(cell, mesh=mesh)
        vG = rhoG[:,0] * coulG
        vG = vG.reshape(nset, *mesh)
        wv[:,0] += vG

    if xctype == 'LDA':
        veff = _get_j_pass2(mydf, wv, hermi, kpts, verbose=log)

    elif xctype == 'GGA':
        # *.5 because v+v.T is always called in _get_gga_pass2
        wv[:,0] *= .5
        veff = _get_gga_pass2(mydf, wv, hermi, kpts, verbose=log)

    return veff.reshape(dm_kpts.shape)
//  [python]
def cache_xc_kernel1(mydf, xc_code, dm, spin=0, kpts=None):
    '''Compute the 0th order density, Vxc and fxc.  They can be used in TDDFT,
    DFT hessian module etc.
    '''
    if kpts is None:
        kpts = numpy.zeros((1,3))
    cell = mydf.cell
    mesh = mydf.mesh
    ngrids = numpy.prod(mesh)

    ni = mydf._numint
    xctype = ni._xc_type(xc_code)
    if xctype == 'LDA':
        deriv = 0
        comp = 1
    elif xctype == 'GGA':
        deriv = 1
        comp = 4
    elif xctype == 'MGGA':
        deriv = 2 if MGGA_DENSITY_LAPL else 1
        comp = 6

    hermi = 1
    weight = cell.vol / ngrids
    rhoG = _eval_rhoG(mydf, dm, hermi, kpts, deriv)
    rho = tools.ifft(rhoG.reshape(-1,ngrids), mesh).real * (1./weight)
    rho = rho.reshape(rhoG.shape)

    n_dm, comp, ngrids = rho.shape
    if n_dm == 1 and spin == 1:
        rho = numpy.repeat(rho, 2, axis=0)
        rho *= .5

    if xctype == 'LDA':
        assert comp == 1
        rho = rho[:,0]
    else:
        assert comp > 1

    if spin == 0:
        assert n_dm == 1
        rho = rho[0]

    vxc, fxc = ni.eval_xc_eff(xc_code, rho, deriv=2, xctype=xctype)[1:3]
    return rho, vxc, fxc
//  [python]
def get_rho(mydf, dm, kpts=numpy.zeros((1,3))):
    '''Density in real space
    '''
    cell = mydf.cell
    hermi = 1
    rhoG = _eval_rhoG(mydf, numpy.asarray(dm), hermi, kpts, deriv=0)

    mesh = mydf.mesh
    ngrids = n.prod(mesh)
    weight = cell.vol / ngrids
    # *(1./weight) because rhoR is scaled by weight in _eval_rhoG.  When
    # computing rhoR with IFFT, the weight factor is not needed.
    rhoR = tools.ifft(rhoG.reshape(ngrids), mesh).real * (1./weight)
    return rhoR
//  [python]
def get_rho(mydf, dm, kpts=numpy.zeros((1,3))):
    '''Density in real space
    '''
    cell = mydf.cell
    hermi = 1
    rhoG = _eval_rhoG(mydf, numpy.asarray(dm), hermi, kpts, deriv=0)

    mesh = mydf.mesh
    ngrids = numpy.prod(mesh)
    weight = cell.vol / ngrids
    # *(1./weight) because rhoR is scaled by weight in _eval_rhoG.  When
    # computing rhoR with IFFT, the weight factor is not needed.
    rhoR = tools.ifft(rhoG.reshape(ngrids), mesh).real * (1./weight)
    return rhoR
//  [python]
def nr_rks_fxc_st(mydf, xc_code, dm0, dms_alpha, singlet=True,
                  rho0=None, vxc=None, fxc=None, kpts=None, verbose=None):
    '''multigrid version of function pbc.dft.numint.nr_rks_fxc_st
    '''
    if kpts is None:
        kpts = numpy.zeros((1,3))
    log = logger.new_logger(mydf, verbose)
    cell = mydf.cell
    mesh = mydf.mesh
    ngrids = n.prod(mesh)

    dm_kpts = lib.asarray(dms_alpha, order='C')
    dms = _format_dms(dm_kpts, kpts)
    nset, nkpts, nao = dms.shape[:3]

    ni = mydf._numint
    xctype = ni._xc_type(xc_code)
    if xctype == 'LDA':
        deriv = 0
    elif xctype == 'GGA':
        deriv = 1
    elif xctype == 'MGGA':
        deriv = 2 if MGGA_DENSITY_LAPL else 1
        raise NotImplementedError

    weight = cell.vol / ngrids
    if rho0 is None:
        rhoG = _eval_rhoG(mydf, dm0, 1, kpts, deriv)
        # *.5 to get alpha density
        rho0 = tools.ifft(rhoG.reshape(-1,ngrids), mesh).real * (.5/weight)
        if xctype == 'LDA':
            rho0 = rho0.reshape(ngrids)
        rho0 = numpy.stack((rho0, rho0))

    if gamma_point(kpts):
        # implies real orbitals and real matrix, thus K_{ia,bj} = K_{ia,jb}
        # The output matrix v = K*x_{ia} is symmetric
        hermi = 1
    else:
        hermi = 0

    if fxc is None:
        fxc = ni.eval_xc_eff(xc_code, rho0, deriv=2, xctype=xctype)[2]
    if singlet:
        fxc = fxc[0,:,0] + fxc[0,:,1]
    else:
        fxc = fxc[0,:,0] - fxc[0,:,1]
    rhoG = _eval_rhoG(mydf, dms, hermi, kpts, deriv)
    rho1 = tools.ifft(rhoG.reshape(-1,ngrids), mesh)
    if hermi == 1:
        rho1 = rho1.real
    rho1 *= (1./weight)
    rho1 = rho1.reshape(nset,-1,ngrids)
    wv = numpy.einsum('nxg,xyg->nyg', rho1, fxc)
    wv *= weight
    wv = tools.fft(wv.reshape(-1,ngrids), mesh).reshape(nset,-1,*mesh)

    if xctype == 'LDA':
        veff = _get_j_pass2(mydf, wv, hermi, kpts, verbose=log)

    elif xctype == 'GGA':
        # *.5 because v+v.T is always called in _get_gga_pass2
        wv[:,0] *= .5
        veff = _get_gga_pass2(mydf, wv, hermi, kpts, verbose=log)

    return veff.reshape(dm_kpts.shape)
//  [python]
def nr_rks_fxc_st(mydf, xc_code, dm0, dms_alpha, singlet=True,
                  rho0=None, vxc=None, fxc=None, kpts=None, verbose=None):
    '''multigrid version of function pbc.dft.numint.nr_rks_fxc_st
    '''
    if kpts is None:
        kpts = numpy.zeros((1,3))
    log = logger.new_logger(mydf, verbose)
    cell = mydf.cell
    mesh = mydf.mesh
    ngrids = numpy.prod(mesh)

    dm_kpts = lib.asarray(dms_alpha, order='C')
    dms = _format_dms(dm_kpts, kpts)
    nset, nkpts, nao = dms.shape[:3]

    ni = mydf._numint
    xctype = ni._xc_type(xc_code)
    if xctype == 'LDA':
        deriv = 0
    elif xctype == 'GGA':
        deriv = 1
    elif xctype == 'MGGA':
        deriv = 2 if MGGA_DENSITY_LAPL else 1
        raise NotImplementedError

    weight = cell.vol / ngrids
    if rho0 is None:
        rhoG = _eval_rhoG(mydf, dm0, 1, kpts, deriv)
        # *.5 to get alpha density
        rho0 = tools.ifft(rhoG.reshape(-1,ngrids), mesh).real * (.5/weight)
        if xctype == 'LDA':
            rho0 = rho0.reshape(ngrids)
        rho0 = numpy.stack((rho0, rho0))

    if gamma_point(kpts):
        # implies real orbitals and real matrix, thus K_{ia,bj} = K_{ia,jb}
        # The output matrix v = K*x_{ia} is symmetric
        hermi = 1
    else:
        hermi = 0

    if fxc is None:
        fxc = ni.eval_xc_eff(xc_code, rho0, deriv=2, xctype=xctype)[2]
    if singlet:
        fxc = fxc[0,:,0] + fxc[0,:,1]
    else:
        fxc = fxc[0,:,0] - fxc[0,:,1]
    rhoG = _eval_rhoG(mydf, dms, hermi, kpts, deriv)
    rho1 = tools.ifft(rhoG.reshape(-1,ngrids), mesh)
    if hermi == 1:
        rho1 = rho1.real
    rho1 *= (1./weight)
    rho1 = rho1.reshape(nset,-1,ngrids)
    wv = numpy.einsum('nxg,xyg->nyg', rho1, fxc)
    wv *= weight
    wv = tools.fft(wv.reshape(-1,ngrids), mesh).reshape(nset,-1,*mesh)

    if xctype == 'LDA':
        veff = _get_j_pass2(mydf, wv, hermi, kpts, verbose=log)

    elif xctype == 'GGA':
        # *.5 because v+v.T is always called in _get_gga_pass2
        wv[:,0] *= .5
        veff = _get_gga_pass2(mydf, wv, hermi, kpts, verbose=log)

    return veff.reshape(dm_kpts.shape)
//  [python]
def nr_uks_fxc(mydf, xc_code, dm0, dms, hermi=0, with_j=False,
               rho0=None, vxc=None, fxc=None, kpts=None, verbose=None):
    '''multigrid version of function pbc.dft.numint.nr_uks_fxc
    '''
    if kpts is None:
        kpts = numpy.zeros((1,3))
    log = logger.new_logger(mydf, verbose)
    cell = mydf.cell
    mesh = mydf.mesh
    ngrids = numpy.prod(mesh)

    dm_kpts = lib.asarray(dms, order='C')
    dms = _format_dms(dm_kpts, kpts)
    nset, nkpts, nao = dms.shape[:3]
    nstates = nset // 2

    ni = mydf._numint
    xctype = ni._xc_type(xc_code)
    if xctype == 'LDA':
        deriv = 0
    elif xctype == 'GGA':
        deriv = 1
    elif xctype == 'MGGA':
        deriv = 2 if MGGA_DENSITY_LAPL else 1
        raise NotImplementedError

    weight = cell.vol / ngrids
    if rho0 is None:
        rhoG = _eval_rhoG(mydf, dm0, hermi, kpts, deriv)
        rho0 = tools.ifft(rhoG.reshape(-1,ngrids), mesh).real * (1./weight)
        if xctype == 'LDA':
            rho0 = rho0.reshape(2,ngrids)
        else:
            rho0 = rho0.reshape(2,-1,ngrids)

    if fxc is None:
        fxc = ni.eval_xc_eff(xc_code, rho0, deriv=2, xctype=xctype)[2]

    rhoG = _eval_rhoG(mydf, dms, hermi, kpts, deriv)
    rho1 = tools.ifft(rhoG.reshape(-1,ngrids), mesh)
    if hermi == 1:
        rho1 = rho1.real
    rho1 *= (1./weight)
    # rho1 = (rho1a, rho1b); rho1.shape = (2, nstates, nvar, ngrids)
    rho1 = rho1.reshape(2,nstates,-1,ngrids)
    wv = numpy.einsum('anxg,axbyg->nbyg', rho1, fxc)
    wv *= weight
    wv = tools.fft(wv.reshape(-1,ngrids), mesh).reshape(nset,-1,*mesh)
    if with_j:
        coulG = tools.get_coulG(cell, mesh=mesh)
        vG = (rhoG[0,0] + rhoG[1,0]) * coulG
        vG = vG.reshape(mesh)
        wv[:,0] += vG

    if xctype == 'LDA':
        veff = _get_j_pass2(mydf, wv, hermi, kpts, verbose=log)

    elif xctype == 'GGA':
        # *.5 because v+v.T is always called in _get_gga_pass2
        wv[:,0] *= .5
        veff = _get_gga_pass2(mydf, wv, hermi, kpts, verbose=log)

    return veff.reshape(dm_kpts.shape)
//  [python]
def test_zoom_grid_by_int_order0(self):
        # When grid_mode is True,  order 0 zoom should be the same as
        # replication via a Kronecker product. The only exceptions to this are
        # the non-grid modes 'constant' and 'wrap'.
        size = n.prod(self.shape)
        x = cupy.arange(size, dtype=float).reshape(self.shape)
        testing.assert_array_almost_equal(
            cupyx.scipy.ndimage.zoom(
                x, self.zoom, order=0, mode=self.mode, grid_mode=True
            ),
            cupy.kron(x, cupy.ones(self.zoom)),
        )
//  [python]
def test_zoom_grid_by_int_order0(self):
        # When grid_mode is True,  order 0 zoom should be the same as
        # replication via a Kronecker product. The only exceptions to this are
        # the non-grid modes 'constant' and 'wrap'.
        size = numpy.prod(self.shape)
        x = cupy.arange(size, dtype=float).reshape(self.shape)
        testing.assert_array_almost_equal(
            cupyx.scipy.ndimage.zoom(
                x, self.zoom, order=0, mode=self.mode, grid_mode=True
            ),
            cupy.kron(x, cupy.ones(self.zoom)),
        )
//  [python]
def carray(ptr, shape, dtype=None):
    """
    Return a Numpy array view over the data pointed to by *ptr* with the
    given *shape*, in C order.  If *dtype* is given, it is used as the
    array's dtype, otherwise the array's dtype is inferred from *ptr*'s type.
    """
    from numba.core.typing.ctypes_utils import from_ctypes

    try:
        # Use ctypes parameter protocol if available
        ptr = ptr._as_parameter_
    except AttributeError:
        pass

    # Normalize dtype, to accept e.g. "int64" or np.int64
    if dtype is not None:
        dtype = np.dtype(dtype)

    if isinstance(ptr, ctypes.c_void_p):
        if dtype is None:
            raise TypeError("explicit dtype required for void* argument")
        p = ptr
    elif isinstance(ptr, ctypes._Pointer):
        ptrty = from_ctypes(ptr.__class__)
        assert isinstance(ptrty, types.CPointer)
        ptr_dtype = as_dtype(ptrty.dtype)
        if dtype is not None and dtype != ptr_dtype:
            raise TypeError("mismatching dtype '%s' for pointer %s"
                            % (dtype, ptr))
        dtype = ptr_dtype
        p = ctypes.cast(ptr, ctypes.c_void_p)
    else:
        raise TypeError("expected a ctypes pointer, got %r" % (ptr,))

    nbytes = dtype.itemsize * n.prod(shape, dtype=np.intp)
    return _get_array_from_ptr(p, nbytes, dtype).reshape(shape)
//  [python]
def carray(ptr, shape, dtype=None):
    """
    Return a Numpy array view over the data pointed to by *ptr* with the
    given *shape*, in C order.  If *dtype* is given, it is used as the
    array's dtype, otherwise the array's dtype is inferred from *ptr*'s type.
    """
    from numba.core.typing.ctypes_utils import from_ctypes

    try:
        # Use ctypes parameter protocol if available
        ptr = ptr._as_parameter_
    except AttributeError:
        pass

    # Normalize dtype, to accept e.g. "int64" or np.int64
    if dtype is not None:
        dtype = np.dtype(dtype)

    if isinstance(ptr, ctypes.c_void_p):
        if dtype is None:
            raise TypeError("explicit dtype required for void* argument")
        p = ptr
    elif isinstance(ptr, ctypes._Pointer):
        ptrty = from_ctypes(ptr.__class__)
        assert isinstance(ptrty, types.CPointer)
        ptr_dtype = as_dtype(ptrty.dtype)
        if dtype is not None and dtype != ptr_dtype:
            raise TypeError("mismatching dtype '%s' for pointer %s"
                            % (dtype, ptr))
        dtype = ptr_dtype
        p = ctypes.cast(ptr, ctypes.c_void_p)
    else:
        raise TypeError("expected a ctypes pointer, got %r" % (ptr,))

    nbytes = dtype.itemsize * np.prod(shape, dtype=np.intp)
    return _get_array_from_ptr(p, nbytes, dtype).reshape(shape)
//  [python]
def _get_kernel_shape(self, input_shape, kernel_size, module, n_features):
    if module == nn.Conv:
      kernel_shape = kernel_size + (input_shape[-1], n_features)
    elif module == nn.ConvLocal:
      kernel_shape = input_shape[1:-1] + (
        input_shape[-1] * n.prod(kernel_size),
        n_features,
      )
    else:
      raise ValueError(module)
    return kernel_shape
//  [python]
def _get_kernel_shape(self, input_shape, kernel_size, module, n_features):
    if module == nn.Conv:
      kernel_shape = kernel_size + (input_shape[-1], n_features)
    elif module == nn.ConvLocal:
      kernel_shape = input_shape[1:-1] + (
        input_shape[-1] * np.prod(kernel_size),
        n_features,
      )
    else:
      raise ValueError(module)
    return kernel_shape
//  [python]
def stratified_k_fold(y, K=7):
    """Stratified k-fold cross validation iterator.

    Returns indices for training and test sets.

    Parameters
    ----------
    y : Numpy array with n > 1 elements. The class labels. These labels are
            used to stratify the folds.

    K : Positive integer greater than or equal to two. The number of folds.
    """
    y = np.array(y)
    n = len(y)
    y = np.reshape(y, (n, 1))

    # Assign the class labels to different folds.
    labels, y_inverse = np.unique(y, return_inverse=True)
    count = np.bincount(y_inverse)
    classes = -np.ones(n)
    for i in range(count.shape[0]):
        c = count[i]
        v = np.mod(np.arange(c), K)

        classes[y_inverse == i] = v

    # Assign any leftovers to existing classes.
    m = np.max(classes)
    if m > K - 1:
        ind = np.where(classes == m)[0]
        for i in range(len(ind)):
            classes[ind[i]] = i

    # Loop over the stratified classes and yield the given train and test set.
    all_ids = set(range(n))
    for k in range(K):
        test = np.where(classes == k)[0].tolist()
        train = list(all_ids.difference(test))

        yield train, test
//  [python]
def stratified_k_fold(y, K=7):
    """Stratified k-fold cross validation iterator.

    Returns indices for training and test sets.

    Parameters
    ----------
    y : Numpy array with n > 1 elements. The class labels. These labels are
            used to stratify the folds.

    K : Positive integer greater than or equal to two. The number of folds.
    """
    y = np.array(y)
    n = np.prod(y.shape)
    y = np.reshape(y, (n, 1))

    # Assign the class labels to different folds.
    labels, y_inverse = np.unique(y, return_inverse=True)
    count = np.bincount(y_inverse)
    classes = -np.ones(n)
    for i in range(count.shape[0]):
        c = count[i]
        v = np.mod(np.arange(c), K)

        classes[y_inverse == i] = v

    # Assign any leftovers to existing classes.
    m = np.max(classes)
    if m > K - 1:
        ind = np.where(classes == m)[0]
        for i in range(len(ind)):
            classes[ind[i]] = i

    # Loop over the stratified classes and yield the given train and test set.
    all_ids = set(range(n))
    for k in range(K):
        test = np.where(classes == k)[0].tolist()
        train = list(all_ids.difference(test))

        yield train, test
//  [python]
def stratified_bootstrap(y, B=100, random_state=None, seed=None):
    """Stratified bootstrap sample iterator.

    Returns indices for a bootstrap training set.

    Parameters
    ----------
    y : Numpy array with n > 1 elements. The class labels. These labels are
            used to stratify the samples.

    B : Positive integer greater than or equal to two. The number of bootstrap
            samples to draw.

    random_state : numpy.random.RandomState
        A random state object to use when generating pseudo-random numbers.
        Used in order to control the selection of bootstrap samples. Default is
        None, which means that you don't care about how the bootstrap samples
        were selected.

    seed : int, deprecated
        A random seed to initialise the random number generator with. Use in
        order to obtain deterministic results. The seed is not used if the seed
        is None. Deprecated, use random_state instead!
    """
    y = np.array(y)
    n = len(y)
    y = np.reshape(y, (n, 1))

    if random_state is None:
        if seed is not None:
            # np.random.seed(seed)
            random_state = np.random.RandomState(seed)
        else:
            random_state = np.random.RandomState()

    # Assign the class labels to different folds
    labels, y_inverse = np.unique(y, return_inverse=True)
    count = np.bincount(y_inverse).tolist()
    for b in range(B):
        sample = -np.ones(y.shape, dtype=np.int)
        for i in range(len(count)):
            c = count[i]  # Current class
            cls = y_inverse == i  # Find class among samples
            i = np.where(cls)[0]  # Class indices
            # Class sample
            # s = np.random.randint(0, c, size=c)
            s = random_state.randint(0, c, size=c)

            # Save the samples
            sample[cls] = i[s].reshape((c, 1))

        yield sample.ravel().tolist()
//  [python]
def stratified_bootstrap(y, B=100, random_state=None, seed=None):
    """Stratified bootstrap sample iterator.

    Returns indices for a bootstrap training set.

    Parameters
    ----------
    y : Numpy array with n > 1 elements. The class labels. These labels are
            used to stratify the samples.

    B : Positive integer greater than or equal to two. The number of bootstrap
            samples to draw.

    random_state : numpy.random.RandomState
        A random state object to use when generating pseudo-random numbers.
        Used in order to control the selection of bootstrap samples. Default is
        None, which means that you don't care about how the bootstrap samples
        were selected.

    seed : int, deprecated
        A random seed to initialise the random number generator with. Use in
        order to obtain deterministic results. The seed is not used if the seed
        is None. Deprecated, use random_state instead!
    """
    y = np.array(y)
    n = np.prod(y.shape)
    y = np.reshape(y, (n, 1))

    if random_state is None:
        if seed is not None:
            # np.random.seed(seed)
            random_state = np.random.RandomState(seed)
        else:
            random_state = np.random.RandomState()

    # Assign the class labels to different folds
    labels, y_inverse = np.unique(y, return_inverse=True)
    count = np.bincount(y_inverse).tolist()
    for b in range(B):
        sample = -np.ones(y.shape, dtype=np.int)
        for i in range(len(count)):
            c = count[i]  # Current class
            cls = y_inverse == i  # Find class among samples
            i = np.where(cls)[0]  # Class indices
            # Class sample
            # s = np.random.randint(0, c, size=c)
            s = random_state.randint(0, c, size=c)

            # Save the samples
            sample[cls] = i[s].reshape((c, 1))

        yield sample.ravel().tolist()
//  [python]
def make_permutation_code(V, vshape, pshape, t_in, t_out, array_name):
    _, _, shifts = get_permutation_to_line_elements(V)
    shift = shifts[0]
    if shift != (0,):
        ndof = n.prod(vshape)
        permutation = numpy.reshape(numpy.arange(ndof), pshape)
        axes = numpy.arange(len(shift))
        for k in range(permutation.shape[0]):
            permutation[k] = numpy.reshape(numpy.transpose(permutation[k], axes=numpy.roll(axes, -shift[k])), pshape[1:])
        nflip = 0
        mapping = V.ufl_element().mapping().lower()
        if mapping == "contravariant piola":
            # flip the sign of the first component
            nflip = ndof//len(shift)
        elif mapping == "covariant piola":
            # flip the order of reference components
            permutation = numpy.flip(permutation, axis=0)

        permutation = numpy.transpose(numpy.reshape(permutation, vshape))
        pdata = ", ".join(map(str, permutation.flat))

        decl = f"""
            PetscInt {array_name}[{ndof}] = {{ {pdata} }};
        """
        prolong = f"""
            for({IntType_c} i=0; i<{ndof}; i++) {t_out}[{array_name}[i]] = {t_in}[i];
            for({IntType_c} i=0; i<{nflip}; i++) {t_out}[i] = -{t_out}[i];
        """
        restrict = f"""
            for({IntType_c} i=0; i<{nflip}; i++) {t_out}[i] = -{t_out}[i];
            for({IntType_c} i=0; i<{ndof}; i++) {t_in}[i] = {t_out}[{array_name}[i]];
        """
    else:
        decl = ""
        prolong = f"""
            for({IntType_c} j=0; j<{vshape[1]}; j++)
                for({IntType_c} i=0; i<{vshape[0]}; i++)
                    {t_out}[j + {vshape[1]}*i] = {t_in}[i + {vshape[0]}*j];
        """
        restrict = f"""
            for({IntType_c} j=0; j<{vshape[1]}; j++)
                for({IntType_c} i=0; i<{vshape[0]}; i++)
                    {t_in}[i + {vshape[0]}*j] = {t_out}[j + {vshape[1]}*i];
        """
    return decl, prolong, restrict
//  [python]
def make_permutation_code(V, vshape, pshape, t_in, t_out, array_name):
    _, _, shifts = get_permutation_to_line_elements(V)
    shift = shifts[0]
    if shift != (0,):
        ndof = numpy.prod(vshape)
        permutation = numpy.reshape(numpy.arange(ndof), pshape)
        axes = numpy.arange(len(shift))
        for k in range(permutation.shape[0]):
            permutation[k] = numpy.reshape(numpy.transpose(permutation[k], axes=numpy.roll(axes, -shift[k])), pshape[1:])
        nflip = 0
        mapping = V.ufl_element().mapping().lower()
        if mapping == "contravariant piola":
            # flip the sign of the first component
            nflip = ndof//len(shift)
        elif mapping == "covariant piola":
            # flip the order of reference components
            permutation = numpy.flip(permutation, axis=0)

        permutation = numpy.transpose(numpy.reshape(permutation, vshape))
        pdata = ", ".join(map(str, permutation.flat))

        decl = f"""
            PetscInt {array_name}[{ndof}] = {{ {pdata} }};
        """
        prolong = f"""
            for({IntType_c} i=0; i<{ndof}; i++) {t_out}[{array_name}[i]] = {t_in}[i];
            for({IntType_c} i=0; i<{nflip}; i++) {t_out}[i] = -{t_out}[i];
        """
        restrict = f"""
            for({IntType_c} i=0; i<{nflip}; i++) {t_out}[i] = -{t_out}[i];
            for({IntType_c} i=0; i<{ndof}; i++) {t_in}[i] = {t_out}[{array_name}[i]];
        """
    else:
        decl = ""
        prolong = f"""
            for({IntType_c} j=0; j<{vshape[1]}; j++)
                for({IntType_c} i=0; i<{vshape[0]}; i++)
                    {t_out}[j + {vshape[1]}*i] = {t_in}[i + {vshape[0]}*j];
        """
        restrict = f"""
            for({IntType_c} j=0; j<{vshape[1]}; j++)
                for({IntType_c} i=0; i<{vshape[0]}; i++)
                    {t_in}[i + {vshape[0]}*j] = {t_out}[j + {vshape[1]}*i];
        """
    return decl, prolong, restrict
//  [python]
def apply_on_axis(op, inputs, axis, *args, **kwargs: Any) -> jnp.ndarray:
  """Apply a differentiable operator on a given axis of the input.

  Args:
    op: a differentiable operator (can be ranks, quantile, etc.)
    inputs: Array of any shape.
    axis: the axis (int) or tuple of ints on which to apply the operator. If
      several axes are passed to the operator, those are merged as a single
      dimension.
    args: other positional arguments to the operator.
    kwargs: other positional arguments to the operator.

  Returns:
    An Array holding the output of the differentiable operator on the given
    axis.
  """
  op_inner = functools.partial(op, **kwargs)
  axis = (axis,) if isinstance(axis, int) else axis
  num_points = n.prod(n.array(inputs.shape)[(axis,)])
  permutation = n.arange(len(inputs.shape))
  axis = tuple(permutation[a] for a in axis)
  permutation = tuple(sorted(set(permutation) - set(axis)) + sorted(axis))
  inputs = jnp.transpose(inputs, permutation)

  batch_fn = jax.vmap(op_inner, in_axes=(0,) + (None,) * len(args))
  result = batch_fn(jnp.reshape(inputs, (-1, num_points)), *args)
  shrink = len(axis)
  result = jnp.reshape(result, inputs.shape[:-shrink] + result.shape[-1:])

  permutation = tuple(range(len(result.shape)))
  rank = len(result.shape) - 1
  axis = min(axis)
  permutation = permutation[:axis] + (rank,) + permutation[axis:-1]
  return jnp.transpose(result, permutation)
//  [python]
def apply_on_axis(op, inputs, axis, *args, **kwargs: Any) -> jnp.ndarray:
  """Apply a differentiable operator on a given axis of the input.

  Args:
    op: a differentiable operator (can be ranks, quantile, etc.)
    inputs: Array of any shape.
    axis: the axis (int) or tuple of ints on which to apply the operator. If
      several axes are passed to the operator, those are merged as a single
      dimension.
    args: other positional arguments to the operator.
    kwargs: other positional arguments to the operator.

  Returns:
    An Array holding the output of the differentiable operator on the given
    axis.
  """
  op_inner = functools.partial(op, **kwargs)
  axis = (axis,) if isinstance(axis, int) else axis
  num_points = np.prod(np.array(inputs.shape)[(axis,)])
  permutation = np.arange(len(inputs.shape))
  axis = tuple(permutation[a] for a in axis)
  permutation = tuple(sorted(set(permutation) - set(axis)) + sorted(axis))
  inputs = jnp.transpose(inputs, permutation)

  batch_fn = jax.vmap(op_inner, in_axes=(0,) + (None,) * len(args))
  result = batch_fn(jnp.reshape(inputs, (-1, num_points)), *args)
  shrink = len(axis)
  result = jnp.reshape(result, inputs.shape[:-shrink] + result.shape[-1:])

  permutation = tuple(range(len(result.shape)))
  rank = len(result.shape) - 1
  axis = min(axis)
  permutation = permutation[:axis] + (rank,) + permutation[axis:-1]
  return jnp.transpose(result, permutation)
//  [python]
def ndarray(self, shape=(None,), dtype="float64"):
        """Return a ndarray of specified shape and dtype.

        A value of None in shape means any length.
        """
        shape = tuple(i if i is not None else self.int(20) for i in shape)
        return (100 * self.rng.random(numpy.prod(shape))
                - 50).reshape(shape).astype(dtype)