jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def get_EAS(ks, C_base):
        # based on Ivo H.M. van Stokkum equation in doi:10.1016/j.bbabio.2004.04.011
        # c_l = sum_{j=1}^l  b_jl * exp(-k_j * t)
        # for j < l: b_jl = b_{j, l-1} * k_{l-1} / (k_l - k_j)
        n = ks.shape[0]
        # C = np.exp(-t[:, None] * ks[None, :])
        if n == 1:
            return C_base

        bjl = np.triu(np.ones((n, n)))  # make triangular upper matrix

        k_prod = np.array([np.prod(ks[:i]) for i in range(1,n)])  # products of rate constants

        k_mat = ks[None, :] - ks[:, None]  # differences between rate constants
        k_mat[k_mat == 0] = 1  # set zero differences to 1, because of calculation of products
        k_mat = np.array([np.prod(k_mat[i,:]) for i in range(n)])
        k_mat = k_mat.reshape(n,1)
        k_mat = np.concatenate((np.ones((n,1)),k_mat[:,0].reshape(n,1)),axis=1)
        k_mat[:, 1:] = k_prod / k_mat[:, 1:]  # combine with rate constants

        bjl *= k_mat

        return C_base.dot(bjl)
//  [python]
def get_EAS(ks, C_base):
        # based on Ivo H.M. van Stokkum equation in doi:10.1016/j.bbabio.2004.04.011
        # c_l = sum_{j=1}^l  b_jl * exp(-k_j * t)
        # for j < l: b_jl = b_{j, l-1} * k_{l-1} / (k_l - k_j)
        n = ks.shape[0]
        # C = np.exp(-t[:, None] * ks[None, :])
        if n == 1:
            return C_base

        bjl = np.triu(np.ones((n, n)))  # make triangular upper matrix

        k_prod = np.cumprod(ks[:-1])  # products of rate constants

        k_mat = ks[None, :] - ks[:, None]  # differences between rate constants
        k_mat[k_mat == 0] = 1  # set zero differences to 1, because of calculation of products
        k_mat = np.cumprod(k_mat, axis=1)  # make product of them
        k_mat[:, 1:] = k_prod / k_mat[:, 1:]  # combine with rate constants

        bjl *= k_mat

        return C_base.dot(bjl)
//  [python]
def build_indexers_from_product(list_lengths: tp.Sequence[int]) -> TNDArrayAny:
    '''
    Creates a 2D indexer array given a sequence of `list_lengths`

    This is equivalent to: ``np.array(list(itertools.product(*(map(range, list_lengths))))).T``
    except it scales incredibly well.

    It observes that the indexers for a product will look like this:

    Example:

    lengths: (3, 3, 3)
    result:
        [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2] # 0
        [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1] # 1
        [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2] # 2

    We can think of each depth level as repeating two parts: elements & groups.

    For depth 0, each element is repeated 6x, each group 1x
    For depth 1, each element is repeated 3x, each group 3x
    For depth 2, each element is repeated 1x, each group 6x

    We can take advantage of this clear pattern by using cumulative sums to
    determine what those repetitions are, and then apply them.
    '''
    padded_lengths = np.full(len(list_lengths) + 2, 1, dtype=DTYPE_INT_DEFAULT)
    padded_lengths[1:-1] = list_lengths

    all_group_reps = np.array([np.prod(padded_lengths[:i+1]) for i in range(len(padded_lengths)-2)])
    all_index_reps = np.array([np.prod(padded_lengths[len(padded_lengths)-1-i:]) for i in range(len(padded_lengths)-2)])[::-1]

    # Impl borrowed from pandas/core/reshape/util.py:cartesian_product
    result = np.array(
        [
            np.tile(
                    np.repeat(PositionsAllocator.get(list_length), repeats=all_index_reps[i]),
                    reps=np.prod(all_group_reps[i])
                    )
            for i, list_length
            in enumerate(list_lengths)
        ],
        dtype=DTYPE_INT_DEFAULT,
    )
    result.flags.writeable = False
    return result
//  [python]
def build_indexers_from_product(list_lengths: tp.Sequence[int]) -> TNDArrayAny:
    '''
    Creates a 2D indexer array given a sequence of `list_lengths`

    This is equivalent to: ``np.array(list(itertools.product(*(map(range, list_lengths))))).T``
    except it scales incredibly well.

    It observes that the indexers for a product will look like this:

    Example:

    lengths: (3, 3, 3)
    result:
        [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2] # 0
        [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1] # 1
        [0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2] # 2

    We can think of each depth level as repeating two parts: elements & groups.

    For depth 0, each element is repeated 6x, each group 1x
    For depth 1, each element is repeated 3x, each group 3x
    For depth 2, each element is repeated 1x, each group 6x

    We can take advantage of this clear pattern by using cumulative sums to
    determine what those repetitions are, and then apply them.
    '''
    padded_lengths = np.full(len(list_lengths) + 2, 1, dtype=DTYPE_INT_DEFAULT)
    padded_lengths[1:-1] = list_lengths

    all_group_reps = np.cumprod(padded_lengths)[:-2]
    all_index_reps = np.cumprod(padded_lengths[::-1])[-3::-1]

    # Impl borrowed from pandas/core/reshape/util.py:cartesian_product
    result = np.array(
        [
            np.tile(
                    np.repeat(PositionsAllocator.get(list_length), repeats=all_index_reps[i]),
                    reps=np.prod(all_group_reps[i])
                    )
            for i, list_length
            in enumerate(list_lengths)
        ],
        dtype=DTYPE_INT_DEFAULT,
    )
    result.flags.writeable = False
    return result
//  [python]
def test_cumprod(self):
        with pytest.raises(u.UnitsError):
            n.cumprod(self.q)
//  [python]
def test_cumprod(self):
        with pytest.raises(u.UnitsError):
            np.cumprod(self.q)
//  [python]
def maximum_position(input, labels=None, index=None):
    """
    Find the positions of the maximums of the values of an array at labels.

    For each region specified by `labels`, the position of the maximum
    value of `input` within the region is returned.

    Parameters
    ----------
    input : array_like
        Array_like of values.
    labels : array_like, optional
        An array of integers marking different regions over which the
        position of the maximum value of `input` is to be computed.
        `labels` must have the same shape as `input`. If `labels` is not
        specified, the location of the first maximum over the whole
        array is returned.

        The `labels` argument only works when `index` is specified.
    index : array_like, optional
        A list of region labels that are taken into account for finding the
        location of the maxima.  If `index` is None, the first maximum
        over all elements where `labels` is non-zero is returned.

        The `index` argument only works when `labels` is specified.

    Returns
    -------
    output : list of tuples of floats
        List of tuples of floats that specify the location of maxima of
        `input` over the regions determined by `labels` and whose index
        is in `index`.

        If `index` or `labels` are not specified, a tuple of floats is
        returned specifying the location of the ``first`` maximal value
        of `input`.

    See also
    --------
    label, minimum, median, maximum_position, extrema, sum, mean, variance,
    standard_deviation

    """
    dims = numpy.array(numpy.asarray(input).shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.array([1] + list(dims[:0:-1])).prod(axis=0)[::-1]

    result = _select(input, labels, index, find_max_positions=True)[0]

    if numpy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def maximum_position(input, labels=None, index=None):
    """
    Find the positions of the maximums of the values of an array at labels.

    For each region specified by `labels`, the position of the maximum
    value of `input` within the region is returned.

    Parameters
    ----------
    input : array_like
        Array_like of values.
    labels : array_like, optional
        An array of integers marking different regions over which the
        position of the maximum value of `input` is to be computed.
        `labels` must have the same shape as `input`. If `labels` is not
        specified, the location of the first maximum over the whole
        array is returned.

        The `labels` argument only works when `index` is specified.
    index : array_like, optional
        A list of region labels that are taken into account for finding the
        location of the maxima.  If `index` is None, the first maximum
        over all elements where `labels` is non-zero is returned.

        The `index` argument only works when `labels` is specified.

    Returns
    -------
    output : list of tuples of floats
        List of tuples of floats that specify the location of maxima of
        `input` over the regions determined by `labels` and whose index
        is in `index`.

        If `index` or `labels` are not specified, a tuple of floats is
        returned specifying the location of the ``first`` maximal value
        of `input`.

    See also
    --------
    label, minimum, median, maximum_position, extrema, sum, mean, variance,
    standard_deviation

    """
    dims = numpy.array(numpy.asarray(input).shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.cumprod([1] + list(dims[:0:-1]))[::-1]

    result = _select(input, labels, index, find_max_positions=True)[0]

    if numpy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def numpy_cumprod(a, dim):
    class CumprodFunc(jt.Function):
        def forward_code(self, np, data):
            a = data["inputs"][0]
            b = data["outputs"][0]
            out = np.cumprod(a, self.dim)
            np.copyto(b, out)

        def backward_code(self, np, data):
            a, b, dout = data["inputs"]
            out = data["outputs"][0]

            sdim = a.shape[self.dim]
            dim = (len(a.shape)+1)*[1]
            dim[self.dim+1] = sdim
            res = np.tile(np.expand_dims(b, self.dim+1), dim)
            dout = np.tile(np.expand_dims(dout, self.dim+1), dim)

            dim[self.dim]=sdim
            dim[self.dim+1]=1
            a = np.tile(np.expand_dims(a, self.dim), dim)
            res = res/a
            
            mask = np.tril(np.ones((sdim, sdim)))
            for i in range(self.dim):
                mask = np.expand_dims(mask, 0)
            for i in range(len(a.shape)-self.dim-2):
                mask = np.expand_dims(mask, -1)
            res = np.sum(mask*res*dout, self.dim)
            
            np.copyto(out, res)

        def execute(self, a, dim):
            self.save_vars = a
            self.dim = dim
            self.res = jt.numpy_code(
                a.shape,
                a.dtype,
                [a],
                self.forward_code,
            )
            return self.res

        def grad(self, grad_a):
            a = self.save_vars
            b = self.res
            return jt.numpy_code(
                a.shape,
                a.dtype,
                [a, b, grad_a],
                self.backward_code,
            )

    func = CumprodFunc()
    if dim<0:
        dim+=len(a.shape)
    return func(a, dim)
//  [python]
def strides_from_shape(shape:Tuple, dtype):
    lower_dims = np.array(shape+(1,))[1:]
    # use 'C' (row-major) ordering by default
    reverse_dim_prod = np.cumprod(lower_dims[::-1])[::-1]
    return tuple(reverse_dim_prod * type_size_in_bytes(dtype))
//  [python]
def find_slice_axis(shape, dtype, mb_threshold=100):
    mb = numpy.array(shape).cumprod() * calc_nbytes(dtype) / 1024**2
    axis = numpy.where(mb <= mb_threshold)[0]
    if axis.size:
        return axis[-1]
    else:
        return 0
//  [python]
def find_slice_axis(shape, dtype, mb_threshold=100):
    mb = numpy.cumprod(shape) * calc_nbytes(dtype) / 1024**2
    axis = numpy.where(mb <= mb_threshold)[0]
    if axis.size:
        return axis[-1]
    else:
        return 0
//  [python]
def onp_cumprod(x):
    a = n.cumprod(x)
    b = n.cumprod(x, axis=0)
    c = n.cumprod(x, axis=1)
    return a, b, c
//  [python]
def onp_cumprod(x):
    a = onp.cumprod(x)
    b = onp.cumprod(x, axis=0)
    c = onp.cumprod(x, axis=1)
    return a, b, c
//  [python]
def backtest(self, position, predict_time=5, begin_time=20100105, cost_coeff=0.003):
        # position: 权重dataframe  T日记录的是下一期的股票权重
        # predict_time：换仓周期
        # begin_time: 回测开始时间
        # cost_coeff：交易成本
        begin_pos = numpy.where(position.index >= begin_time)[0][0]
        exchange_id = numpy.arange(begin_pos - 1, self.nday, predict_time)
        exchange_times = len(exchange_id)  # 换仓次数

        ret_portfolio = numpy.zeros([self.nday])
        for i in range(exchange_times - 1):
            returns_here = self.pct_chg.values[exchange_id[i] + 1:exchange_id[i + 1] + 1, :]  # 持仓阶段每日的returns。
            weight_here = position.iloc[exchange_id[i], :]
            stock_ret = weight_here.values.reshape(1, len(weight_here)) * returns_here
            ret_portfolio[exchange_id[i] + 1:exchange_id[i + 1] + 1] = pandas.DataFrame(stock_ret).sum(axis=1).values

        ret_hedge = ret_portfolio - self.index_pct_chg_here.values
        ret_hedge = ret_hedge[begin_pos:]
        ret_hedge[0] = .0
        nav = pandas.DataFrame()
        nav["net_value"] = numpy.exp(numpy.cumsum(numpy.log(1+ret_hedge)))
        nav.index = position.index[begin_pos:]
        nav.index = nav.index.astype(str)
        nav.index = ['-'.join([each[0:4], each[4:6], each[6:]]) for each in nav.index]
        nav.index.name = "trade_date"

        return nav
//  [python]
def backtest(self, position, predict_time=5, begin_time=20100105, cost_coeff=0.003):
        # position: 权重dataframe  T日记录的是下一期的股票权重
        # predict_time：换仓周期
        # begin_time: 回测开始时间
        # cost_coeff：交易成本
        begin_pos = numpy.where(position.index >= begin_time)[0][0]
        exchange_id = numpy.arange(begin_pos - 1, self.nday, predict_time)
        exchange_times = len(exchange_id)  # 换仓次数

        ret_portfolio = numpy.zeros([self.nday])
        for i in range(exchange_times - 1):
            returns_here = self.pct_chg.values[exchange_id[i] + 1:exchange_id[i + 1] + 1, :]  # 持仓阶段每日的returns。
            weight_here = position.iloc[exchange_id[i], :]
            stock_ret = weight_here.values.reshape(1, len(weight_here)) * returns_here
            ret_portfolio[exchange_id[i] + 1:exchange_id[i + 1] + 1] = pandas.DataFrame(stock_ret).sum(axis=1).values

        ret_hedge = ret_portfolio - self.index_pct_chg_here.values
        ret_hedge = ret_hedge[begin_pos:]
        ret_hedge[0] = .0
        nav = pandas.DataFrame()
        nav["net_value"] = numpy.cumprod(1+ret_hedge)
        nav.index = position.index[begin_pos:]
        nav.index = nav.index.astype(str)
        nav.index = ['-'.join([each[0:4], each[4:6], each[6:]]) for each in nav.index]
        nav.index.name = "trade_date"

        return nav
//  [python]
def _trim_nan(x):
        """
        Removes all starting and trailing nan values from a 1D array and returns the new array and the number of NaNs
        removed per side.
        """
        mask_forward = np.cumprod(np.isnan(x)).astype(
            bool
        )  # cumprod will be one until the first non-Nan value
        x = x[~mask_forward]
        mask_backward = np.cumprod(np.isnan(x)[::-1])[::-1].astype(
            bool
        )  # Double reverse for a backwards cumprod
        x = x[~mask_backward]

        return x, np.sum(mask_forward.astype(int)), np.sum(mask_backward.astype(int))
//  [python]
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                self.assertRaises(ArithmeticError, cumprod, a)
                self.assertRaises(ArithmeticError, cumprod, a2, 1)
                self.assertRaises(ArithmeticError, cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype))
//  [python]
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                      np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                self.assertRaises(ArithmeticError, np.cumprod, a)
                self.assertRaises(ArithmeticError, np.cumprod, a2, 1)
                self.assertRaises(ArithmeticError, np.cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis=-1),
                                   np.array([1, 2, 20, 220,
                                             1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                                   np.array([[1, 2, 3, 4],
                                             [5, 12, 21, 36],
                                             [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis=-1),
                                   np.array([[1, 2, 6, 24],
                                             [5, 30, 210, 1890],
                                             [10, 30, 120, 600]], ctype))
//  [python]
def get_strides_f(shape: Sequence) -> object:
    """Get strides of a F like array, for numpy array need to multiply by itemsize

    Parameters
    ----------
    shape : tuple of int or iterable
      shape of the array
    Returns
    -------
    s :  tuple of int or iterable
      strides of the array

    Examples
    --------
    >>> get_strides_f((2, 3, 3))
    [1, 2, 6]

    References
    ----------
    https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html"""

    # $s_k = \Prod_{j=0}^{k-1} d_j$
    s = n.cumprod((1,) + shape[0:-1]).tolist()

    return s
//  [python]
def get_strides_f(shape: Sequence) -> object:
    """Get strides of a F like array, for numpy array need to multiply by itemsize

    Parameters
    ----------
    shape : tuple of int or iterable
      shape of the array
    Returns
    -------
    s :  tuple of int or iterable
      strides of the array

    Examples
    --------
    >>> get_strides_f((2, 3, 3))
    [1, 2, 6]

    References
    ----------
    https://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html"""

    # $s_k = \Prod_{j=0}^{k-1} d_j$
    s = numpy.cumprod((1,) + shape[0:-1]).tolist()

    return s
//  [python]
def get_ddpm_params(config):
  """Get betas and alphas --- parameters used in the original DDPM paper."""
  num_diffusion_timesteps = 1000
  # parameters need to be adapted if number of time steps differs from 1000
  beta_start = config.beta_min / config.num_scales
  beta_end = config.beta_max / config.num_scales
  betas = np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64)

  alphas = 1. - betas
  alphas_cumprod = np.array([np.prod(alphas[:i+1]) for i in range(len(alphas))])
  sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
  sqrt_1m_alphas_cumprod = np.sqrt(1. - alphas_cumprod)

  return {
    'betas': betas,
    'alphas': alphas,
    'alphas_cumprod': alphas_cumprod,
    'sqrt_alphas_cumprod': sqrt_alphas_cumprod,
    'sqrt_1m_alphas_cumprod': sqrt_1m_alphas_cumprod,
    'beta_min': beta_start * (num_diffusion_timesteps - 1),
    'beta_max': beta_end * (num_diffusion_timesteps - 1),
    'num_diffusion_timesteps': num_diffusion_timesteps
  }
//  [python]
def get_ddpm_params(config):
  """Get betas and alphas --- parameters used in the original DDPM paper."""
  num_diffusion_timesteps = 1000
  # parameters need to be adapted if number of time steps differs from 1000
  beta_start = config.beta_min / config.num_scales
  beta_end = config.beta_max / config.num_scales
  betas = np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64)

  alphas = 1. - betas
  alphas_cumprod = np.cumprod(alphas, axis=0)
  sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
  sqrt_1m_alphas_cumprod = np.sqrt(1. - alphas_cumprod)

  return {
    'betas': betas,
    'alphas': alphas,
    'alphas_cumprod': alphas_cumprod,
    'sqrt_alphas_cumprod': sqrt_alphas_cumprod,
    'sqrt_1m_alphas_cumprod': sqrt_1m_alphas_cumprod,
    'beta_min': beta_start * (num_diffusion_timesteps - 1),
    'beta_max': beta_end * (num_diffusion_timesteps - 1),
    'num_diffusion_timesteps': num_diffusion_timesteps
  }
//  [python]
def test_basic(self):
        ba = [1, 2, 10, 11, 6, 5, 4]
        ba2 = [[1, 2, 3, 4], [5, 6, 7, 9], [10, 3, 4, 5]]
        for ctype in [np.int16, np.uint16, np.int32, np.uint32,
                np.float32, np.float64, np.complex64, np.complex128]:
            a = np.array(ba, ctype)
            a2 = np.array(ba2, ctype)
            if ctype in ['1', 'b']:
                self.assertRaises(ArithmeticError, cumprod, a)
                self.assertRaises(ArithmeticError, cumprod, a2, 1)
                self.assertRaises(ArithmeticError, cumprod, a)
            else:
                assert_array_equal(np.cumprod(a, axis= -1),
                        np.array([1, 2, 20, 220, 1320, 6600, 26400], ctype))
                assert_array_equal(np.cumprod(a2, axis=0),
                        np.array([[ 1, 2, 3, 4], [ 5, 12, 21, 36],
                            [50, 36, 84, 180]], ctype))
                assert_array_equal(np.cumprod(a2, axis= -1),
                        np.array([[ 1, 2, 6, 24], [ 5, 30, 210, 1890],
                            [10, 30, 120, 600]], ctype))
//  [python]
def 累乘(序列,  轴=None,  数据类型=None,  输出=None):
		return cn_array(n.cumprod(a = 序列,  axis = 轴,  dtype = 数据类型,  out = 输出))
//  [python]
def 累乘(序列,  轴=None,  数据类型=None,  输出=None):
		return cn_array(numpy.cumprod(a = 序列,  axis = 轴,  dtype = 数据类型,  out = 输出))
//  [python]
def minimum_position(input, labels = None, index = None):
    """Find the positions of the minimums of the values of an array at labels.

    Labels must be None or an array of the same dimensions as the input.

    Index must be None, a single label or sequence of labels.  If
    none, all values where label is greater than zero are used.
    """

    dims = numpy.array(numpy.asarray(input).shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.array([1] + list(dims[:0:-1])).prod(axis=0)[::-1]

    result = _select(input, labels, index, find_min_positions=True)[0]

    if numpy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def minimum_position(input, labels = None, index = None):
    """Find the positions of the minimums of the values of an array at labels.

    Labels must be None or an array of the same dimensions as the input.

    Index must be None, a single label or sequence of labels.  If
    none, all values where label is greater than zero are used.
    """

    dims = numpy.array(numpy.asarray(input).shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.cumprod([1] + list(dims[:0:-1]))[::-1]

    result = _select(input, labels, index, find_min_positions=True)[0]

    if numpy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def maximum_position(input, labels=None, index=None):
    """Find the positions of the maximums of the values of an array at labels.

    For each region specified by `labels`, the position of the maximum
    value of `input` within the region is returned.

    Args:
        input (cupy.ndarray):
            Array of values. For each region specified by `labels`, the
            maximal values of `input` over the region is computed.
        labels (cupy.ndarray, optional): An array of integers marking different
            regions over which the position of the maximum value of `input` is
            to be computed. `labels` must have the same shape as `input`. If
            `labels` is not specified, the location of the first maximum over
            the whole array is returned.

            The `labels` argument only works when `index` is specified.
        index (array_like, optional): A list of region labels that are taken
            into account for finding the location of the maxima. If `index` is
            None, the ``first`` maximum over all elements where `labels` is
            non-zero is returned.

            The `index` argument only works when `labels` is specified.

    Returns:
        Tuple of ints or list of tuples of ints that specify the location of
        maxima of `input` over the regions determaxed by `labels` and  whose
        index is in `index`.

        If `index` or `labels` are not specified, a tuple of ints is returned
        specifying the location of the first maximal value of `input`.

    .. note::
        When `input` has multiple identical maxima within a labeled region,
        the coordinates returned are not guaranteed to match those returned by
        SciPy.

    .. seealso:: :func:`scipy.ndimage.maximum_position`
    """
    dims = numpy.asarray(input.shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.array([1] + list(dims[:0:-1])).prod(axis=0)[::-1]

    result = _select(input, labels, index, find_max_positions=True)[0]

    # have to transfer result back to the CPU to return index tuples
    if result.ndim == 0:
        result = int(result)
    else:
        result = cupy.asnumpy(result)

    if cupy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def maximum_position(input, labels=None, index=None):
    """Find the positions of the maximums of the values of an array at labels.

    For each region specified by `labels`, the position of the maximum
    value of `input` within the region is returned.

    Args:
        input (cupy.ndarray):
            Array of values. For each region specified by `labels`, the
            maximal values of `input` over the region is computed.
        labels (cupy.ndarray, optional): An array of integers marking different
            regions over which the position of the maximum value of `input` is
            to be computed. `labels` must have the same shape as `input`. If
            `labels` is not specified, the location of the first maximum over
            the whole array is returned.

            The `labels` argument only works when `index` is specified.
        index (array_like, optional): A list of region labels that are taken
            into account for finding the location of the maxima. If `index` is
            None, the ``first`` maximum over all elements where `labels` is
            non-zero is returned.

            The `index` argument only works when `labels` is specified.

    Returns:
        Tuple of ints or list of tuples of ints that specify the location of
        maxima of `input` over the regions determaxed by `labels` and  whose
        index is in `index`.

        If `index` or `labels` are not specified, a tuple of ints is returned
        specifying the location of the first maximal value of `input`.

    .. note::
        When `input` has multiple identical maxima within a labeled region,
        the coordinates returned are not guaranteed to match those returned by
        SciPy.

    .. seealso:: :func:`scipy.ndimage.maximum_position`
    """
    dims = numpy.asarray(input.shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.cumprod([1] + list(dims[:0:-1]))[::-1]

    result = _select(input, labels, index, find_max_positions=True)[0]

    # have to transfer result back to the CPU to return index tuples
    if result.ndim == 0:
        result = int(result)
    else:
        result = cupy.asnumpy(result)

    if cupy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def extrema(input, labels=None, index=None):
    """Calculate the minimums and maximums of the values of an array at labels,
    along with their positions.

    Args:
        input (cupy.ndarray): N-D image data to process.
        labels (cupy.ndarray, optional): Labels of features in input. If not
            None, must be same shape as `input`.
        index (int or sequence of ints, optional): Labels to include in output.
            If None (default), all values where non-zero `labels` are used.

    Returns:
        A tuple that contains the following values.

        **minimums (cupy.ndarray)**: Values of minimums in each feature.

        **maximums (cupy.ndarray)**: Values of maximums in each feature.

        **min_positions (tuple or list of tuples)**: Each tuple gives the N-D
        coordinates of the corresponding minimum.

        **max_positions (tuple or list of tuples)**: Each tuple gives the N-D
        coordinates of the corresponding maximum.

    .. seealso:: :func:`scipy.ndimage.extrema`
    """
    dims = numpy.array(input.shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.array([1] + list(dims[:0:-1])).prod(axis=0)[::-1]

    minimums, min_positions, maximums, max_positions = _select(
        input,
        labels,
        index,
        find_min=True,
        find_max=True,
        find_min_positions=True,
        find_max_positions=True,
    )

    if min_positions.ndim == 0:
        # scalar output case
        min_positions = min_positions.item()
        max_positions = max_positions.item()
        return (
            minimums,
            maximums,
            tuple((min_positions // dim_prod) % dims),
            tuple((max_positions // dim_prod) % dims),
        )

    # convert indexes to tuples on the host
    min_positions = cupy.asnumpy(min_positions)
    max_positions = cupy.asnumpy(max_positions)
    min_positions = [
        tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims
    ]
    max_positions = [
        tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims
    ]

    return minimums, maximums, min_positions, max_positions
//  [python]
def extrema(input, labels=None, index=None):
    """Calculate the minimums and maximums of the values of an array at labels,
    along with their positions.

    Args:
        input (cupy.ndarray): N-D image data to process.
        labels (cupy.ndarray, optional): Labels of features in input. If not
            None, must be same shape as `input`.
        index (int or sequence of ints, optional): Labels to include in output.
            If None (default), all values where non-zero `labels` are used.

    Returns:
        A tuple that contains the following values.

        **minimums (cupy.ndarray)**: Values of minimums in each feature.

        **maximums (cupy.ndarray)**: Values of maximums in each feature.

        **min_positions (tuple or list of tuples)**: Each tuple gives the N-D
        coordinates of the corresponding minimum.

        **max_positions (tuple or list of tuples)**: Each tuple gives the N-D
        coordinates of the corresponding maximum.

    .. seealso:: :func:`scipy.ndimage.extrema`
    """
    dims = numpy.array(input.shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.cumprod([1] + list(dims[:0:-1]))[::-1]

    minimums, min_positions, maximums, max_positions = _select(
        input,
        labels,
        index,
        find_min=True,
        find_max=True,
        find_min_positions=True,
        find_max_positions=True,
    )

    if min_positions.ndim == 0:
        # scalar output case
        min_positions = min_positions.item()
        max_positions = max_positions.item()
        return (
            minimums,
            maximums,
            tuple((min_positions // dim_prod) % dims),
            tuple((max_positions // dim_prod) % dims),
        )

    # convert indexes to tuples on the host
    min_positions = cupy.asnumpy(min_positions)
    max_positions = cupy.asnumpy(max_positions)
    min_positions = [
        tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims
    ]
    max_positions = [
        tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims
    ]

    return minimums, maximums, min_positions, max_positions
//  [python]
def minimum_position(input, labels=None, index=None):
    """Find the positions of the minimums of the values of an array at labels.

    For each region specified by `labels`, the position of the minimum
    value of `input` within the region is returned.

    Args:
        input (cupy.ndarray):
            Array of values. For each region specified by `labels`, the
            minimal values of `input` over the region is computed.
        labels (cupy.ndarray, optional): An array of integers marking different
            regions over which the position of the minimum value of `input` is
            to be computed. `labels` must have the same shape as `input`. If
            `labels` is not specified, the location of the first minimum over
            the whole array is returned.

            The `labels` argument only works when `index` is specified.
        index (array_like, optional): A list of region labels that are taken
            into account for finding the location of the minima. If `index` is
            None, the ``first`` minimum over all elements where `labels` is
            non-zero is returned.

            The `index` argument only works when `labels` is specified.

    Returns:
        Tuple of ints or list of tuples of ints that specify the location of
        minima of `input` over the regions determined by `labels` and  whose
        index is in `index`.

        If `index` or `labels` are not specified, a tuple of ints is returned
        specifying the location of the first minimal value of `input`.

    .. note::
        When `input` has multiple identical minima within a labeled region,
        the coordinates returned are not guaranteed to match those returned by
        SciPy.

    .. seealso:: :func:`scipy.ndimage.minimum_position`
    """
    dims = numpy.asarray(input.shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.array([1] + list(dims[:0:-1])).prod(axis=0)[::-1]

    result = _select(input, labels, index, find_min_positions=True)[0]

    # have to transfer result back to the CPU to return index tuples
    if result.ndim == 0:
        result = int(result)  # synchronize
    else:
        result = cupy.asnumpy(result)  # synchronize

    if cupy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def minimum_position(input, labels=None, index=None):
    """Find the positions of the minimums of the values of an array at labels.

    For each region specified by `labels`, the position of the minimum
    value of `input` within the region is returned.

    Args:
        input (cupy.ndarray):
            Array of values. For each region specified by `labels`, the
            minimal values of `input` over the region is computed.
        labels (cupy.ndarray, optional): An array of integers marking different
            regions over which the position of the minimum value of `input` is
            to be computed. `labels` must have the same shape as `input`. If
            `labels` is not specified, the location of the first minimum over
            the whole array is returned.

            The `labels` argument only works when `index` is specified.
        index (array_like, optional): A list of region labels that are taken
            into account for finding the location of the minima. If `index` is
            None, the ``first`` minimum over all elements where `labels` is
            non-zero is returned.

            The `index` argument only works when `labels` is specified.

    Returns:
        Tuple of ints or list of tuples of ints that specify the location of
        minima of `input` over the regions determined by `labels` and  whose
        index is in `index`.

        If `index` or `labels` are not specified, a tuple of ints is returned
        specifying the location of the first minimal value of `input`.

    .. note::
        When `input` has multiple identical minima within a labeled region,
        the coordinates returned are not guaranteed to match those returned by
        SciPy.

    .. seealso:: :func:`scipy.ndimage.minimum_position`
    """
    dims = numpy.asarray(input.shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.cumprod([1] + list(dims[:0:-1]))[::-1]

    result = _select(input, labels, index, find_min_positions=True)[0]

    # have to transfer result back to the CPU to return index tuples
    if result.ndim == 0:
        result = int(result)  # synchronize
    else:
        result = cupy.asnumpy(result)  # synchronize

    if cupy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def maximum_position(input, labels = None, index = None):
    """Find the positions of the maximums of the values of an array at labels.

    Labels must be None or an array of the same dimensions as the input.

    Index must be None, a single label or sequence of labels.  If
    none, all values where label is greater than zero are used.
    """

    dims = numpy.array(numpy.asarray(input).shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.array([1] + list(dims[:0:-1])).cumprod()[::-1]

    result = _select(input, labels, index, find_max_positions=True)[0]

    if numpy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def maximum_position(input, labels = None, index = None):
    """Find the positions of the maximums of the values of an array at labels.

    Labels must be None or an array of the same dimensions as the input.

    Index must be None, a single label or sequence of labels.  If
    none, all values where label is greater than zero are used.
    """

    dims = numpy.array(numpy.asarray(input).shape)
    # see numpy.unravel_index to understand this line.
    dim_prod = numpy.cumprod([1] + list(dims[:0:-1]))[::-1]

    result = _select(input, labels, index, find_max_positions=True)[0]

    if numpy.isscalar(result):
        return tuple((result // dim_prod) % dims)

    return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
//  [python]
def np_nancumprod(a):
    if not isinstance(a, types.Array):
        return

    if isinstance(a.dtype, (types.Boolean, types.Integer)):
        # dtype cannot possibly contain NaN
        return lambda a: n.cumprod(a)
    else:
        retty = a.dtype
        is_nan = get_isnan(retty)
        one = retty(1)

        def nancumprod_impl(a):
            out = np.empty(a.size, retty)
            c = one
            for idx, v in enumerate(a.flat):
                if ~is_nan(v):
                    c *= v
                out[idx] = c
            return out

        return nancumprod_impl
//  [python]
def np_nancumprod(a):
    if not isinstance(a, types.Array):
        return

    if isinstance(a.dtype, (types.Boolean, types.Integer)):
        # dtype cannot possibly contain NaN
        return lambda a: np.cumprod(a)
    else:
        retty = a.dtype
        is_nan = get_isnan(retty)
        one = retty(1)

        def nancumprod_impl(a):
            out = np.empty(a.size, retty)
            c = one
            for idx, v in enumerate(a.flat):
                if ~is_nan(v):
                    c *= v
                out[idx] = c
            return out

        return nancumprod_impl
//  [python]
def compute_volumetric_rendering_weights_with_alpha_numpy(alpha):
  density_exp = 1. - alpha
  density_exp_shifted = numpy.concatenate([numpy.ones_like(density_exp[..., :1]),
                                          density_exp[..., :-1]], axis=-1)
  trans = numpy.array([numpy.prod(density_exp_shifted[..., :i+1]) for i in range(density_exp_shifted.shape[-1])]).reshape(density_exp_shifted.shape)
  weights = alpha * trans
  return weights
//  [python]
def compute_volumetric_rendering_weights_with_alpha_numpy(alpha):
  density_exp = 1. - alpha
  density_exp_shifted = numpy.concatenate([numpy.ones_like(density_exp[..., :1]),
                                          density_exp[..., :-1]], axis=-1)
  trans = numpy.cumprod(density_exp_shifted, axis=-1)
  weights = alpha * trans
  return weights
//  [python]
def test_axis(self, arr, axis, dtype):
        a = numpy.array(arr, dtype=dtype)
        ia = dpnp.array(a)

        result = dpnp.cumprod(ia, axis=axis)
        expected = numpy.cumprod(a, axis=axis)
        assert_array_equal(expected, result)
//  [python]
def get_ddpm_params(config):
  num_diffusion_timesteps = 1000
  beta_start = config.model.beta_min / config.model.num_scales
  beta_end = config.model.beta_max / config.model.num_scales
  betas = np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64)

  alphas = 1. - betas
  alphas_cumprod = np.array([np.prod(alphas[:i+1]) for i in range(len(alphas))])
  sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
  sqrt_1m_alphas_cumprod = np.sqrt(1. - alphas_cumprod)

  return {
    'betas': betas,
    'alphas': alphas,
    'alphas_cumprod': alphas_cumprod,
    'sqrt_alphas_cumprod': sqrt_alphas_cumprod,
    'sqrt_1m_alphas_cumprod': sqrt_1m_alphas_cumprod,
    'beta_min': beta_start * (num_diffusion_timesteps - 1),
    'beta_max': beta_end * (num_diffusion_timesteps - 1),
    'num_diffusion_timesteps': num_diffusion_timesteps
  }
//  [python]
def get_ddpm_params(config):
  num_diffusion_timesteps = 1000
  beta_start = config.model.beta_min / config.model.num_scales
  beta_end = config.model.beta_max / config.model.num_scales
  betas = np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64)

  alphas = 1. - betas
  alphas_cumprod = np.cumprod(alphas, axis=0)
  sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
  sqrt_1m_alphas_cumprod = np.sqrt(1. - alphas_cumprod)

  return {
    'betas': betas,
    'alphas': alphas,
    'alphas_cumprod': alphas_cumprod,
    'sqrt_alphas_cumprod': sqrt_alphas_cumprod,
    'sqrt_1m_alphas_cumprod': sqrt_1m_alphas_cumprod,
    'beta_min': beta_start * (num_diffusion_timesteps - 1),
    'beta_max': beta_end * (num_diffusion_timesteps - 1),
    'num_diffusion_timesteps': num_diffusion_timesteps
  }
//  [python]
def test_usm_ndarray(self, sh, xp_in, xp_out, check):
        a = numpy.arange(-12, -2).reshape(sh)
        ia = xp_in.asarray(a)

        result = dpnp.cumprod(ia)
        expected = numpy.cumprod(a)
        assert_array_equal(expected, result)

        out = numpy.empty((10,))
        iout = xp_out.asarray(out)

        result = dpnp.cumprod(ia, out=iout)
        expected = numpy.cumprod(a, out=out)
        assert_array_equal(expected, result)
        assert (result is iout) is check
//  [python]
def sdft(self, samples):
        """
        Estimate the DFT matrix for the given sample array.

        Parameters
        ----------
        samples : ndarray, list, float
            Array of samples.

        Returns
        -------
        dfts : ndarray
            DFT matrix of shape (samples,frequencies).
        """

        samples = numpy.atleast_1d(samples)

        assert samples.ndim == 1, f'Expected 1D array (samples,), got {samples.shape}!'

        M = samples.size
        N = self.size

        m = self.offset
        n = numpy.arange(N)

        self.offset += M

        twiddles = self.twiddles_analysis[None, :]
        twiddles = numpy.repeat(twiddles, M + 1, axis=0)
        twiddles[0] **= m
        numpy.cumprod(twiddles, axis=0, out=twiddles)

        delayline = numpy.concatenate((self.delayline, samples))
        numpy.copyto(self.delayline, delayline[-(N * 2):])
        data = samples - delayline[:M]
        data = data[:, None] * twiddles[:-1]

        data[0] += self.accumulator
        numpy.cumsum(data, axis=0, out=data)
        numpy.copyto(self.accumulator, data[-1])
        data *= numpy.conj(twiddles[1:])

        dfts = self.convolve(data)

        return dfts / 2
//  [python]
def spherical_transform_sct(cls, samples, approx=False):
        """
        Map samples from the ``[0, 1]``-cube onto the hypersphere.

        Uses the SCT method described in section 1.5.3 of Fang and Wang (1994).
        """
        samples = np.asarray(samples)
        samples = samples[:, np.newaxis] if samples.ndim == 1 else samples
        n, d = samples.shape

        # inverse transform method (section 1.5.2)
        coords = np.empty_like(samples)
        for j in range(d):
            coords[:, j] = cls.spherical_coords_ppf(d - j, samples[:, j], approx=approx)

        # spherical coordinate transform
        mapped = np.ones((n, d + 1))
        i = np.ones(d)
        i[-1] = 2.0
        s = np.sin(i[np.newaxis, :] * np.pi * coords)
        c = np.cos(i[np.newaxis, :] * np.pi * coords)
        mapped[:, 1:] = np.array([np.prod(s[k,:j+1]) for k in range(n) for j in range(d)]) .reshape(n,d)
        mapped[:, :-1] *= c
        return mapped
//  [python]
def spherical_transform_sct(cls, samples, approx=False):
        """
        Map samples from the ``[0, 1]``-cube onto the hypersphere.

        Uses the SCT method described in section 1.5.3 of Fang and Wang (1994).
        """
        samples = np.asarray(samples)
        samples = samples[:, np.newaxis] if samples.ndim == 1 else samples
        n, d = samples.shape

        # inverse transform method (section 1.5.2)
        coords = np.empty_like(samples)
        for j in range(d):
            coords[:, j] = cls.spherical_coords_ppf(d - j, samples[:, j], approx=approx)

        # spherical coordinate transform
        mapped = np.ones((n, d + 1))
        i = np.ones(d)
        i[-1] = 2.0
        s = np.sin(i[np.newaxis, :] * np.pi * coords)
        c = np.cos(i[np.newaxis, :] * np.pi * coords)
        mapped[:, 1:] = np.cumprod(s, axis=1)
        mapped[:, :-1] *= c
        return mapped
//  [python]
def writeScalarXdmf_particles(self,ar,u,name,tCount=0,init=True):
        nPoints = numpy.prod(u.shape)

        Xdmf_NodesGlobal = nPoints
        attribute = SubElement(self.arGrid,"Attribute",{"Name":name,
                                                        "AttributeType":"Scalar",
                                                        "Center":"Node"})
        values    = SubElement(attribute,"DataItem",
                               {"Format":ar.dataItemFormat,
                                "DataType":"Float",
                                "Precision":"8",
                                "Dimensions":"%i" % (Xdmf_NodesGlobal,)})
        if ar.hdfFile is not None:
            values.text = ar.hdfFilename+":/"+name+"_p"+str(ar.rank)+"_t"+str(tCount)
            ar.create_dataset_async(name+"_p"+str(ar.rank)+"_t"+str(tCount), data = u.flat[:])
        else:
            numpy.savetxt(ar.textDataDir+"/"+name+str(tCount)+".txt",u.flat[:])
            SubElement(values,"xi:include",{"parse":"text","href":"./"+ar.textDataDir+"/"+name+str(tCount)+".txt"})