jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def writeScalarXdmf_particles(self,ar,u,name,tCount=0,init=True):
        nPoints = numpy.cumprod(u.shape)[-1]

        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"})
//  [python]
def writeVectorXdmf_particles(self,ar,u,name,tCount=0,init=True):
        nPoints = u.shape[0]

        Xdmf_NodesGlobal = nPoints
        Xdmf_NumberOfComponents = u.shape[-1]
        attribute = SubElement(self.arGrid,"Attribute",{"Name":name,
                                                        "AttributeType":"Vector",
                                                        "Center":"Node"})
        values    = SubElement(attribute,"DataItem",
                               {"Format":ar.dataItemFormat,
                                "DataType":"Float",
                                "Precision":"8",
                                "Dimensions":"%i %i" % (Xdmf_NodesGlobal,3)})#force 3d vector since points 3d
        tmp = numpy.zeros((Xdmf_NodesGlobal,3),'d')
        tmp[:,:Xdmf_NumberOfComponents]=numpy.reshape(u.flat,(Xdmf_NodesGlobal,Xdmf_NumberOfComponents))

        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 = tmp)
        else:
            numpy.savetxt(ar.textDataDir+"/"+name+str(tCount)+".txt",tmp)
            SubElement(values,"xi:include",{"parse":"text","href":"./"+ar.textDataDir+"/"+name+str(tCount)+".txt"})
//  [python]
def writeVectorXdmf_particles(self,ar,u,name,tCount=0,init=True):
        nPoints = numpy.cumprod(u.shape)[-2]

        Xdmf_NodesGlobal = nPoints
        Xdmf_NumberOfComponents = u.shape[-1]
        attribute = SubElement(self.arGrid,"Attribute",{"Name":name,
                                                        "AttributeType":"Vector",
                                                        "Center":"Node"})
        values    = SubElement(attribute,"DataItem",
                               {"Format":ar.dataItemFormat,
                                "DataType":"Float",
                                "Precision":"8",
                                "Dimensions":"%i %i" % (Xdmf_NodesGlobal,3)})#force 3d vector since points 3d
        tmp = numpy.zeros((Xdmf_NodesGlobal,3),'d')
        tmp[:,:Xdmf_NumberOfComponents]=numpy.reshape(u.flat,(Xdmf_NodesGlobal,Xdmf_NumberOfComponents))

        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 = tmp)
        else:
            numpy.savetxt(ar.textDataDir+"/"+name+str(tCount)+".txt",tmp)
            SubElement(values,"xi:include",{"parse":"text","href":"./"+ar.textDataDir+"/"+name+str(tCount)+".txt"})
//  [python]
def strides_of(shape):
    """Calculate cumulative strides from per-dimension capacities.

    For example:

        [2, 3, 4] ==> [12, 4, 1]

    """
    temp = numpy.flipud(numpy.cumprod(numpy.flipud(list(shape)[1:])))
    return list(temp) + [1]
//  [python]
def estimate_f_map(
            S_ratio, R1, T2_free, delta_omega, omega_1_rms, 
            G, TR, duration, flip_angle, f0):
        
        shape = S_ratio.shape
        
        chunk_size = int(1e4)
        chunks_count = numpy.prod(shape) // chunk_size
        
        S_ratio = numpy.array_split(S_ratio.ravel(), chunks_count)
        R1 = numpy.array_split(R1.ravel(), chunks_count)
        T2_free = numpy.array_split(T2_free.ravel(), chunks_count)
        delta_omega = numpy.array_split(delta_omega.ravel(), chunks_count)
        omega_1_rms = numpy.array_split(omega_1_rms.ravel(), chunks_count)
        G = numpy.array_split(G.ravel(), chunks_count)
        
        # FIXME: dont' use fixed value
        with multiprocessing.Pool(4) as pool:
            f = pool.starmap(
                SinglePoint.estimate_f_map_worker,
                zip(
                    S_ratio, R1, T2_free, delta_omega, omega_1_rms, G,
                    itertools.repeat(TR, len(R1)), 
                    itertools.repeat(duration, len(R1)), 
                    itertools.repeat(flip_angle, len(R1)), 
                    itertools.repeat(f0, len(R1))))
        
        f = numpy.concatenate(f).reshape(shape)
        return f
//  [python]
def estimate_f_map(
            S_ratio, R1, T2_free, delta_omega, omega_1_rms, 
            G, TR, duration, flip_angle, f0):
        
        shape = S_ratio.shape
        
        chunk_size = int(1e4)
        chunks_count = numpy.cumprod(shape)[-1] // chunk_size
        
        S_ratio = numpy.array_split(S_ratio.ravel(), chunks_count)
        R1 = numpy.array_split(R1.ravel(), chunks_count)
        T2_free = numpy.array_split(T2_free.ravel(), chunks_count)
        delta_omega = numpy.array_split(delta_omega.ravel(), chunks_count)
        omega_1_rms = numpy.array_split(omega_1_rms.ravel(), chunks_count)
        G = numpy.array_split(G.ravel(), chunks_count)
        
        # FIXME: dont' use fixed value
        with multiprocessing.Pool(4) as pool:
            f = pool.starmap(
                SinglePoint.estimate_f_map_worker,
                zip(
                    S_ratio, R1, T2_free, delta_omega, omega_1_rms, G,
                    itertools.repeat(TR, len(R1)), 
                    itertools.repeat(duration, len(R1)), 
                    itertools.repeat(flip_angle, len(R1)), 
                    itertools.repeat(f0, len(R1))))
        
        f = numpy.concatenate(f).reshape(shape)
        return f
//  [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.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):
    """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.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 get_input_spec(self) -> InputSpec:
        xshape = self.config.dynamics.xshape
        if self.config.dynamics.group == 'U1':
            xdim = self.config.dynamics.xdim
            input_dims = {
                'xnet': {'x': [xdim, 2], 'v': [xdim, ]},
                'vnet': {'x': [xdim, ], 'v': [xdim, ]},
            }
        elif self.config.dynamics.group == 'SU3':
            xdim = np.prod(xshape[1:-2]) * 8
            input_dims = {
                'xnet': {'x': [xdim, ], 'v': [xdim, ]},
                'vnet': {'x': [xdim, ], 'v': [xdim, ]},
            }
        else:
            raise ValueError('Unexpected value for `config.dynamics.group`')

        return InputSpec(xshape=tuple(xshape), **input_dims)
//  [python]
def get_input_spec(self) -> InputSpec:
        xshape = self.config.dynamics.xshape
        if self.config.dynamics.group == 'U1':
            xdim = self.config.dynamics.xdim
            input_dims = {
                'xnet': {'x': [xdim, 2], 'v': [xdim, ]},
                'vnet': {'x': [xdim, ], 'v': [xdim, ]},
            }
        elif self.config.dynamics.group == 'SU3':
            xdim = np.cumprod(xshape[1:-2])[-1] * 8
            input_dims = {
                'xnet': {'x': [xdim, ], 'v': [xdim, ]},
                'vnet': {'x': [xdim, ], 'v': [xdim, ]},
            }
        else:
            raise ValueError('Unexpected value for `config.dynamics.group`')

        return InputSpec(xshape=tuple(xshape), **input_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.array([1] + list(dims[:0:-1])).cumprod()[::-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 update_core(self):
        gen_optimizer = self.get_optimizer('generator')
        dis_optimizer = self.get_optimizer('discriminator')
        gen = gen_optimizer.target
        dis = dis_optimizer.target
        xp = gen.xp

        for i in range(self.n_dis):
            batch = self.get_iterator('main').next()
            arrays = chainer.dataset.concat_examples(batch)
            if isinstance(arrays, (numpy.ndarray, cupy.ndarray)):
                x_real = chainer.Variable(xp.asarray(arrays))
                c = None
                batchsize = len(x_real)
            else:

                def make_x_real(arr):
                    x_real = []
                    subsample_batch = [1] + self.subsample_batch
                    stride = numpy.array(subsample_batch[:len(arr)]).cumprod()
                    for a, s in zip(arr, stride):
                        a = a[::s]
                        x_real.append(chainer.Variable(xp.asarray(a)))
                    return tuple(x_real)

                if arrays[-1].dtype == numpy.int32:
                    x_real = make_x_real(arrays[:-1])
                    c = chainer.Variable(xp.asarray(arrays[-1]))
                else:
                    x_real = make_x_real(arrays)
                    c = None
                batchsize = len(x_real[0])
            y_real = dis(x_real, c)

            z = gen.make_hidden(batchsize)
            x_fake = gen(z, c)
            y_fake = dis(x_fake, c)

            if i == 0:
                loss_gen = F.mean(F.softplus(-y_fake))
                gen.cleargrads()
                loss_gen.backward()
                gen_optimizer.update()
                chainer.report({'loss_gen': loss_gen})

            if isinstance(x_fake, tuple):
                for xf in x_fake:
                    xf.unchain_backward()
            else:
                x_fake.unchain_backward()

            if self.reg_type == 'fake':
                xd, yd = x_fake, y_fake
            elif self.reg_type == 'real':
                xd, yd = x_real, y_real
            else:
                raise TypeError
            xd = list(xd) if isinstance(xd, tuple) else [xd]
            dydxs = chainer.grad([yd], xd, enable_double_backprop=True)

            loss_gp = None
            for dydx in dydxs:
                loss = F.sum(F.square(dydx))
                if loss_gp is None:
                    loss_gp = loss
                else:
                    loss_gp += loss
            loss_gp = self.lam * loss_gp

            loss_dis = F.mean(F.softplus(-y_real)) + F.mean(F.softplus(y_fake))

            dis.cleargrads()
            loss_dis.backward()
            loss_gp.backward()
            dis_optimizer.update()
            dis.cleargrads()

            chainer.report({'loss_dis': loss_dis, 'loss_gp': loss_gp, 'g': F.mean(dydx)})
//  [python]
def update_core(self):
        gen_optimizer = self.get_optimizer('generator')
        dis_optimizer = self.get_optimizer('discriminator')
        gen = gen_optimizer.target
        dis = dis_optimizer.target
        xp = gen.xp

        for i in range(self.n_dis):
            batch = self.get_iterator('main').next()
            arrays = chainer.dataset.concat_examples(batch)
            if isinstance(arrays, (numpy.ndarray, cupy.ndarray)):
                x_real = chainer.Variable(xp.asarray(arrays))
                c = None
                batchsize = len(x_real)
            else:

                def make_x_real(arr):
                    x_real = []
                    subsample_batch = [1] + self.subsample_batch
                    stride = numpy.cumprod(subsample_batch[:len(arr)])
                    for a, s in zip(arr, stride):
                        a = a[::s]
                        x_real.append(chainer.Variable(xp.asarray(a)))
                    return tuple(x_real)

                if arrays[-1].dtype == numpy.int32:
                    x_real = make_x_real(arrays[:-1])
                    c = chainer.Variable(xp.asarray(arrays[-1]))
                else:
                    x_real = make_x_real(arrays)
                    c = None
                batchsize = len(x_real[0])
            y_real = dis(x_real, c)

            z = gen.make_hidden(batchsize)
            x_fake = gen(z, c)
            y_fake = dis(x_fake, c)

            if i == 0:
                loss_gen = F.mean(F.softplus(-y_fake))
                gen.cleargrads()
                loss_gen.backward()
                gen_optimizer.update()
                chainer.report({'loss_gen': loss_gen})

            if isinstance(x_fake, tuple):
                for xf in x_fake:
                    xf.unchain_backward()
            else:
                x_fake.unchain_backward()

            if self.reg_type == 'fake':
                xd, yd = x_fake, y_fake
            elif self.reg_type == 'real':
                xd, yd = x_real, y_real
            else:
                raise TypeError
            xd = list(xd) if isinstance(xd, tuple) else [xd]
            dydxs = chainer.grad([yd], xd, enable_double_backprop=True)

            loss_gp = None
            for dydx in dydxs:
                loss = F.sum(F.square(dydx))
                if loss_gp is None:
                    loss_gp = loss
                else:
                    loss_gp += loss
            loss_gp = self.lam * loss_gp

            loss_dis = F.mean(F.softplus(-y_real)) + F.mean(F.softplus(y_fake))

            dis.cleargrads()
            loss_dis.backward()
            loss_gp.backward()
            dis_optimizer.update()
            dis.cleargrads()

            chainer.report({'loss_dis': loss_dis, 'loss_gp': loss_gp, 'g': F.mean(dydx)})
//  [python]
def levinson_durbin_pacf(pacf, nlags=None):
    """
    Levinson-Durbin algorithm that returns the acf and ar coefficients.

    Parameters
    ----------
    pacf : array_like
        Partial autocorrelation array for lags 0, 1, ... p.
    nlags : int, optional
        Number of lags in the AR model.  If omitted, returns coefficients from
        an AR(p) and the first p autocorrelations.

    Returns
    -------
    arcoefs : ndarray
        AR coefficients computed from the partial autocorrelations.
    acf : ndarray
        The acf computed from the partial autocorrelations. Array returned
        contains the autocorrelations corresponding to lags 0, 1, ..., p.

    References
    ----------
    .. [1] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
        and forecasting. Springer.
    """
    pacf = array_like(pacf, "pacf")
    nlags = int_like(nlags, "nlags", optional=True)
    pacf = np.squeeze(np.asarray(pacf))

    if pacf[0] != 1:
        raise ValueError(
            "The first entry of the pacf corresponds to lags 0 "
            "and so must be 1."
        )
    pacf = pacf[1:]
    n = pacf.shape[0]
    if nlags is not None:
        if nlags > n:
            raise ValueError(
                "Must provide at least as many values from the "
                "pacf as the number of lags."
            )
        pacf = pacf[:nlags]
        n = pacf.shape[0]

    acf = np.zeros(n + 1)
    acf[1] = pacf[0]
    nu = np.ones(n)
    for i in range(n):
        nu[i] *= (1 - pacf[i]**2)
    arcoefs = pacf.copy()
    for i in range(1, n):
        prev = arcoefs[: -(n - i)].copy()
        arcoefs[: -(n - i)] = prev - arcoefs[i] * prev[::-1]
        acf[i + 1] = arcoefs[i] * nu[i - 1] + prev.dot(acf[1 : -(n - i)][::-1])
    acf[0] = 1
    return arcoefs, acf
//  [python]
def levinson_durbin_pacf(pacf, nlags=None):
    """
    Levinson-Durbin algorithm that returns the acf and ar coefficients.

    Parameters
    ----------
    pacf : array_like
        Partial autocorrelation array for lags 0, 1, ... p.
    nlags : int, optional
        Number of lags in the AR model.  If omitted, returns coefficients from
        an AR(p) and the first p autocorrelations.

    Returns
    -------
    arcoefs : ndarray
        AR coefficients computed from the partial autocorrelations.
    acf : ndarray
        The acf computed from the partial autocorrelations. Array returned
        contains the autocorrelations corresponding to lags 0, 1, ..., p.

    References
    ----------
    .. [1] Brockwell, P.J. and Davis, R.A., 2016. Introduction to time series
        and forecasting. Springer.
    """
    pacf = array_like(pacf, "pacf")
    nlags = int_like(nlags, "nlags", optional=True)
    pacf = np.squeeze(np.asarray(pacf))

    if pacf[0] != 1:
        raise ValueError(
            "The first entry of the pacf corresponds to lags 0 "
            "and so must be 1."
        )
    pacf = pacf[1:]
    n = pacf.shape[0]
    if nlags is not None:
        if nlags > n:
            raise ValueError(
                "Must provide at least as many values from the "
                "pacf as the number of lags."
            )
        pacf = pacf[:nlags]
        n = pacf.shape[0]

    acf = np.zeros(n + 1)
    acf[1] = pacf[0]
    nu = np.cumprod(1 - pacf ** 2)
    arcoefs = pacf.copy()
    for i in range(1, n):
        prev = arcoefs[: -(n - i)].copy()
        arcoefs[: -(n - i)] = prev - arcoefs[i] * prev[::-1]
        acf[i + 1] = arcoefs[i] * nu[i - 1] + prev.dot(acf[1 : -(n - i)][::-1])
    acf[0] = 1
    return arcoefs, acf
//  [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 = n.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 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 md(keys_and_counts):
    """Generate metadata dictionaries for the given metadata shape

    keys_and_counts - a collection of metadata keys and the dimension of
                        their extent. For instance [(M0, 2), (M1, 3)] generates
                        six dictionaries with two unique values of M0 and
                        three for M1
    """
    keys = [k for k, c in keys_and_counts]
    counts = numpy.array([c for k, c in keys_and_counts])
    divisors = numpy.hstack([[1], n.cumprod(counts[:-1])])

    return [
        dict(
            [(k, "k" + str(int(i / d) % c)) for k, d, c in zip(keys, divisors, counts)]
        )
        for i in range(numpy.prod(counts))
    ]
//  [python]
def md(keys_and_counts):
    """Generate metadata dictionaries for the given metadata shape

    keys_and_counts - a collection of metadata keys and the dimension of
                        their extent. For instance [(M0, 2), (M1, 3)] generates
                        six dictionaries with two unique values of M0 and
                        three for M1
    """
    keys = [k for k, c in keys_and_counts]
    counts = numpy.array([c for k, c in keys_and_counts])
    divisors = numpy.hstack([[1], numpy.cumprod(counts[:-1])])

    return [
        dict(
            [(k, "k" + str(int(i / d) % c)) for k, d, c in zip(keys, divisors, counts)]
        )
        for i in range(numpy.prod(counts))
    ]
//  [python]
def forward_expected(self, inputs):
        x, = inputs
        expected = numpy.cumprod(x, axis=self.axis)
        expected = force_array(expected)
        return expected,
//  [python]
def test_convertmma2mma(M, N, mma_pair, dtype, device):
    if is_hip():
        pytest.skip("test_mma2mma is not supported in HIP")

    src_layout, _ = mma_pair
    num_warps = n.cumprod(src_layout.warps_per_cta)[-1]

    def do_test(src_layout, dst_layout):
        layouts = f"""
        #src = {src_layout}
        #dst = {dst_layout}
        """

        conversion = f"""
        %12 = triton_gpu.convert_layout %9 : tensor<{M}x{N}xi32, #src> -> tensor<{M}x{N}xi32, #dst>
        %13 = triton_gpu.convert_layout %11 : tensor<{M}x{N}xf16, #src> -> tensor<{M}x{N}xf16, #dst>
        """

        ir = layouts + f"""
        module attributes {{"triton_gpu.num-warps" = {num_warps} : i32, "triton_gpu.num-ctas" = 1 : i32, "triton_gpu.threads-per-warp" = 32 : i32}} {{
        tt.func public @kernel_0d1d(%arg0: !tt.ptr<f16> {{tt.divisibility = 16 : i32}}, %arg1: !tt.ptr<f16> {{tt.divisibility = 16 : i32}}) {{
        %cst = arith.constant dense<{N}> : tensor<{M}x1xi32, #src>
        %0 = tt.make_range {{end = {M} : i32, start = 0 : i32}} : tensor<{M}xi32, #triton_gpu.slice<{{dim = 1, parent = #src}}>>
        %1 = tt.make_range {{end = {N} : i32, start = 0 : i32}} : tensor<{N}xi32, #triton_gpu.slice<{{dim = 0, parent = #src}}>>
        %2 = tt.splat %arg0 : !tt.ptr<f16> -> tensor<{M}x{N}x!tt.ptr<f16>, #src>
        %4 = tt.expand_dims %0 {{axis = 1 : i32}} : tensor<{M}xi32, #triton_gpu.slice<{{dim = 1, parent = #src}}>> -> tensor<{M}x1xi32, #src>
        %5 = arith.muli %4, %cst : tensor<{M}x1xi32, #src>
        %6 = tt.expand_dims %1 {{axis = 0 : i32}} : tensor<{N}xi32, #triton_gpu.slice<{{dim = 0, parent = #src}}>> -> tensor<1x{N}xi32, #src>
        %7 = tt.broadcast %6 : tensor<1x{N}xi32, #src> -> tensor<{M}x{N}xi32, #src>
        %8 = tt.broadcast %5 : tensor<{M}x1xi32, #src> -> tensor<{M}x{N}xi32, #src>
        %9 = arith.addi %8, %7 : tensor<{M}x{N}xi32, #src>
        %10 = tt.addptr %2, %9 : tensor<{M}x{N}x!tt.ptr<f16>, #src>, tensor<{M}x{N}xi32, #src>
        %11 = tt.load %10 : tensor<{M}x{N}x!tt.ptr<f16>, #src>
        %3 = tt.splat %arg1 : !tt.ptr<f16> -> tensor<{M}x{N}x!tt.ptr<f16>, #dst>
        """ + conversion + f"""
        %14 = tt.addptr %3, %12 : tensor<{M}x{N}x!tt.ptr<f16>, #dst>, tensor<{M}x{N}xi32, #dst>
        tt.store %14, %13 : tensor<{M}x{N}x!tt.ptr<f16>, #dst>
        tt.return
        }}
        }}
        """

        x = to_triton(numpy_random((M, N), dtype_str=dtype), device=device)
        z = torch.empty_like(x)

        with tempfile.NamedTemporaryFile(mode='w', suffix='.ttgir') as f:
            f.write(ir)
            f.flush()
            kernel = triton.compile(f.name)
        kernel[(1, 1, 1)](x.data_ptr(), z.data_ptr())

        assert torch.equal(z, x)

    do_test(mma_pair[0], mma_pair[1])
    do_test(mma_pair[1], mma_pair[0])
//  [python]
def test_convertmma2mma(M, N, mma_pair, dtype, device):
    if is_hip():
        pytest.skip("test_mma2mma is not supported in HIP")

    src_layout, _ = mma_pair
    num_warps = np.cumprod(src_layout.warps_per_cta)[-1]

    def do_test(src_layout, dst_layout):
        layouts = f"""
        #src = {src_layout}
        #dst = {dst_layout}
        """

        conversion = f"""
        %12 = triton_gpu.convert_layout %9 : tensor<{M}x{N}xi32, #src> -> tensor<{M}x{N}xi32, #dst>
        %13 = triton_gpu.convert_layout %11 : tensor<{M}x{N}xf16, #src> -> tensor<{M}x{N}xf16, #dst>
        """

        ir = layouts + f"""
        module attributes {{"triton_gpu.num-warps" = {num_warps} : i32, "triton_gpu.num-ctas" = 1 : i32, "triton_gpu.threads-per-warp" = 32 : i32}} {{
        tt.func public @kernel_0d1d(%arg0: !tt.ptr<f16> {{tt.divisibility = 16 : i32}}, %arg1: !tt.ptr<f16> {{tt.divisibility = 16 : i32}}) {{
        %cst = arith.constant dense<{N}> : tensor<{M}x1xi32, #src>
        %0 = tt.make_range {{end = {M} : i32, start = 0 : i32}} : tensor<{M}xi32, #triton_gpu.slice<{{dim = 1, parent = #src}}>>
        %1 = tt.make_range {{end = {N} : i32, start = 0 : i32}} : tensor<{N}xi32, #triton_gpu.slice<{{dim = 0, parent = #src}}>>
        %2 = tt.splat %arg0 : !tt.ptr<f16> -> tensor<{M}x{N}x!tt.ptr<f16>, #src>
        %4 = tt.expand_dims %0 {{axis = 1 : i32}} : tensor<{M}xi32, #triton_gpu.slice<{{dim = 1, parent = #src}}>> -> tensor<{M}x1xi32, #src>
        %5 = arith.muli %4, %cst : tensor<{M}x1xi32, #src>
        %6 = tt.expand_dims %1 {{axis = 0 : i32}} : tensor<{N}xi32, #triton_gpu.slice<{{dim = 0, parent = #src}}>> -> tensor<1x{N}xi32, #src>
        %7 = tt.broadcast %6 : tensor<1x{N}xi32, #src> -> tensor<{M}x{N}xi32, #src>
        %8 = tt.broadcast %5 : tensor<{M}x1xi32, #src> -> tensor<{M}x{N}xi32, #src>
        %9 = arith.addi %8, %7 : tensor<{M}x{N}xi32, #src>
        %10 = tt.addptr %2, %9 : tensor<{M}x{N}x!tt.ptr<f16>, #src>, tensor<{M}x{N}xi32, #src>
        %11 = tt.load %10 : tensor<{M}x{N}x!tt.ptr<f16>, #src>
        %3 = tt.splat %arg1 : !tt.ptr<f16> -> tensor<{M}x{N}x!tt.ptr<f16>, #dst>
        """ + conversion + f"""
        %14 = tt.addptr %3, %12 : tensor<{M}x{N}x!tt.ptr<f16>, #dst>, tensor<{M}x{N}xi32, #dst>
        tt.store %14, %13 : tensor<{M}x{N}x!tt.ptr<f16>, #dst>
        tt.return
        }}
        }}
        """

        x = to_triton(numpy_random((M, N), dtype_str=dtype), device=device)
        z = torch.empty_like(x)

        with tempfile.NamedTemporaryFile(mode='w', suffix='.ttgir') as f:
            f.write(ir)
            f.flush()
            kernel = triton.compile(f.name)
        kernel[(1, 1, 1)](x.data_ptr(), z.data_ptr())

        assert torch.equal(z, x)

    do_test(mma_pair[0], mma_pair[1])
    do_test(mma_pair[1], mma_pair[0])
//  [python]
def ravel_multi_index(multi_index: Tuple[DenseTensor, ...], dims: Tuple[int, ...]) -> DenseTensor:
    out = multi_index[-1].clone().detach()
    for ind, stride in zip(multi_index[-2::-1], n.cumprod(dims[:0:-1])):
        out += ind * stride
    return out
//  [python]
def ravel_multi_index(multi_index: Tuple[DenseTensor, ...], dims: Tuple[int, ...]) -> DenseTensor:
    out = multi_index[-1].clone().detach()
    for ind, stride in zip(multi_index[-2::-1], numpy.cumprod(dims[:0:-1])):
        out += ind * stride
    return out
//  [python]
def load_metadata(self):
        with h5py.File(self.filename) as f:
            self.indexed = f.attrs['indexed']
            self.is_empty = f.attrs['is_empty']
            self.is_sorted = f.attrs['is_sorted']
            self.input_names = list(f['synopsis/in_names'][...])
            self.output_names = list(f['synopsis/out_names'][...])
            self.input_types = list(f['synopsis/in_types'][...])
            self.indexes = {}
            for t in self.input_types:
                self.indexes[t] = list(f['synopsis/indexes/%s' % t][...])
            self.in_nb_levels = f['synopsis/in_nb_levels'][...]
            self.key_weights = numpy.concatenate([numpy.array(
                [1], dtype=numpy.uint64),
                numpy.array(numpy.cumprod(numpy.uint64(self.in_nb_levels))[:-1])])
            self.indexed_outputs = []
            if 'synopsis/indexed_outputs' in f:
                self.indexed_outputs = list(f['synopsis/indexed_outputs'][...])
                if 'synopsis/indexed_outputs_dims' in f:
                    self.indexed_outputs_dims = f[
                        'synopsis/indexed_outputs_dims'][...]
                for o in self.indexed_outputs:
                    self.indexes[o] = f['synopsis/indexes/%s' % o][...]
            # instantiate dbfun_compute object if there is code
            if 'code' in f:
                self.code = f.attrs['code']
                self.computer = dbfun_compute.DBfun_Compute(
                    self.code, self.input_names)
                # check that all input names are used
                if not(self.input_names == self.computer.input_names):
                    raise ValueError(
                        'Some input columns defined in the synopsis of file '
                        '%s are unused in the corresponding script %s' % (
                        self.filename, self.code))
//  [python]
def load_metadata(self):
        with h5py.File(self.filename) as f:
            self.indexed = f.attrs['indexed']
            self.is_empty = f.attrs['is_empty']
            self.is_sorted = f.attrs['is_sorted']
            self.input_names = list(f['synopsis/in_names'][...])
            self.output_names = list(f['synopsis/out_names'][...])
            self.input_types = list(f['synopsis/in_types'][...])
            self.indexes = {}
            for t in self.input_types:
                self.indexes[t] = list(f['synopsis/indexes/%s' % t][...])
            self.in_nb_levels = f['synopsis/in_nb_levels'][...]
            self.key_weights = numpy.concatenate([numpy.array(
                [1], dtype=numpy.uint64),
                numpy.cumprod(numpy.uint64(self.in_nb_levels))[:-1]])
            self.indexed_outputs = []
            if 'synopsis/indexed_outputs' in f:
                self.indexed_outputs = list(f['synopsis/indexed_outputs'][...])
                if 'synopsis/indexed_outputs_dims' in f:
                    self.indexed_outputs_dims = f[
                        'synopsis/indexed_outputs_dims'][...]
                for o in self.indexed_outputs:
                    self.indexes[o] = f['synopsis/indexes/%s' % o][...]
            # instantiate dbfun_compute object if there is code
            if 'code' in f:
                self.code = f.attrs['code']
                self.computer = dbfun_compute.DBfun_Compute(
                    self.code, self.input_names)
                # check that all input names are used
                if not(self.input_names == self.computer.input_names):
                    raise ValueError(
                        'Some input columns defined in the synopsis of file '
                        '%s are unused in the corresponding script %s' % (
                        self.filename, self.code))
//  [python]
def get_figure_nav(self):

        for item in os.listdir(self.out_path):
            print(item)
            if item.endswith("_nav.csv"):
                strategy_name = item[:-8]
                nav_portfolio = pandas.read_csv(os.path.join(self.out_path, item), index_col=0, header=0)
                nav_portfolio.index = [datetime.strptime(d, '%Y-%m-%d').date() for d in nav_portfolio.index]

                nav_bench = n.cumprod(1+self.index_pct_chg_here)
                nav_bench.index = [datetime.strptime(str(d), '%Y%m%d').date() for d in nav_bench.index]
                nav_portfolio["net_value_bench"] = nav_bench

                figsize = (6, 4)
                fig, ax = plt.subplots(figsize=figsize)
                ax.plot(nav_portfolio.index, nav_portfolio.net_value, 'b', label='nav_portfolio')
                ax.plot(nav_portfolio.index, nav_portfolio.net_value_bench, 'r', label='nav_bench')
                ax.legend(loc="best")
                plt.title("nav")
                plt.xticks(rotation=45)

                file_name = Path(self.out_path, strategy_name+".png")
                plt.savefig(file_name)
//  [python]
def get_figure_nav(self):

        for item in os.listdir(self.out_path):
            print(item)
            if item.endswith("_nav.csv"):
                strategy_name = item[:-8]
                nav_portfolio = pandas.read_csv(os.path.join(self.out_path, item), index_col=0, header=0)
                nav_portfolio.index = [datetime.strptime(d, '%Y-%m-%d').date() for d in nav_portfolio.index]

                nav_bench = numpy.cumprod(1+self.index_pct_chg_here)
                nav_bench.index = [datetime.strptime(str(d), '%Y%m%d').date() for d in nav_bench.index]
                nav_portfolio["net_value_bench"] = nav_bench

                figsize = (6, 4)
                fig, ax = plt.subplots(figsize=figsize)
                ax.plot(nav_portfolio.index, nav_portfolio.net_value, 'b', label='nav_portfolio')
                ax.plot(nav_portfolio.index, nav_portfolio.net_value_bench, 'r', label='nav_bench')
                ax.legend(loc="best")
                plt.title("nav")
                plt.xticks(rotation=45)

                file_name = Path(self.out_path, strategy_name+".png")
                plt.savefig(file_name)
//  [python]
def init_numpy(betas):
    # Use float64 for accuracy.
    betas = torch.DoubleTensor(betas)
    assert len(betas.shape) == 1, "betas must be 1-D"
    assert (betas > 0).all() and (betas <= 1).all()

    num_timesteps = int(betas.shape[0])

    alphas = 1.0 - betas
    alphas_cumprod = np.cumprod(alphas, axis=0)
    alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
    alphas_cumprod_next = np.append(alphas_cumprod[1:], 0.0)
    assert alphas_cumprod_prev.shape == (num_timesteps,)

    # calculations for diffusion q(x_t | x_{t-1}) and others
    np.sqrt(alphas_cumprod)
    np.sqrt(1.0 - alphas_cumprod)
    np.log(1.0 - alphas_cumprod)
    np.sqrt(1.0 / alphas_cumprod)
    np.sqrt(1.0 / alphas_cumprod - 1)

    # calculations for posterior q(x_{t-1} | x_t, x_0)
    posterior_variance = betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
    # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
    posterior_log_variance_clipped = (
        np.log(np.append(posterior_variance[1], posterior_variance[1:]))
        if len(posterior_variance) > 1
        else np.array([])
    )

    posterior_mean_coef1 = betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)
    posterior_mean_coef2 = (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod)

    return alphas_cumprod_prev, alphas_cumprod_next, posterior_mean_coef1, posterior_mean_coef2
//  [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.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.0 - 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.0 - 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.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.0 - betas
    alphas_cumprod = np.cumprod(alphas, axis=0)
    sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
    sqrt_1m_alphas_cumprod = np.sqrt(1.0 - 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 gaussian_init_numpy(betas):
    # Use float64 for accuracy.
    betas = np.array(betas, dtype=np.float64)
    assert len(betas.shape) == 1, "betas must be 1-D"
    assert (betas > 0).all() and (betas <= 1).all()

    num_timesteps = int(betas.shape[0])

    alphas = 1.0 - betas
    alphas_cumprod = np.array([np.prod(alphas[:i+1]) for i in range(num_timesteps)])
    alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
    alphas_cumprod_next = np.append(alphas_cumprod[1:], 0.0)
    assert alphas_cumprod_prev.shape == (num_timesteps,)

    # calculations for diffusion q(x_t | x_{t-1}) and others
    sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
    sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - alphas_cumprod)
    log_one_minus_alphas_cumprod = np.log(1.0 - alphas_cumprod)
    sqrt_recip_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod)
    sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod - 1)

    # calculations for posterior q(x_{t-1} | x_t, x_0)
    posterior_variance = betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
    # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
    posterior_log_variance_clipped = (
        np.log(np.append(posterior_variance[1], posterior_variance[1:]))
        if len(posterior_variance) > 1
        else np.array([])
    )

    posterior_mean_coef1 = betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)
    posterior_mean_coef2 = (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod)

    return (
        alphas_cumprod_prev,
        alphas_cumprod_next,
        sqrt_alphas_cumprod,
        sqrt_one_minus_alphas_cumprod,
        log_one_minus_alphas_cumprod,
        sqrt_recip_alphas_cumprod,
        sqrt_recipm1_alphas_cumprod,
        posterior_log_variance_clipped,
        posterior_mean_coef1,
        posterior_mean_coef2,
    )
//  [python]
def gaussian_init_numpy(betas):
    # Use float64 for accuracy.
    betas = np.array(betas, dtype=np.float64)
    assert len(betas.shape) == 1, "betas must be 1-D"
    assert (betas > 0).all() and (betas <= 1).all()

    num_timesteps = int(betas.shape[0])

    alphas = 1.0 - betas
    alphas_cumprod = np.cumprod(alphas, axis=0)
    alphas_cumprod_prev = np.append(1.0, alphas_cumprod[:-1])
    alphas_cumprod_next = np.append(alphas_cumprod[1:], 0.0)
    assert alphas_cumprod_prev.shape == (num_timesteps,)

    # calculations for diffusion q(x_t | x_{t-1}) and others
    sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
    sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - alphas_cumprod)
    log_one_minus_alphas_cumprod = np.log(1.0 - alphas_cumprod)
    sqrt_recip_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod)
    sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod - 1)

    # calculations for posterior q(x_{t-1} | x_t, x_0)
    posterior_variance = betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
    # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
    posterior_log_variance_clipped = (
        np.log(np.append(posterior_variance[1], posterior_variance[1:]))
        if len(posterior_variance) > 1
        else np.array([])
    )

    posterior_mean_coef1 = betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)
    posterior_mean_coef2 = (1.0 - alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - alphas_cumprod)

    return (
        alphas_cumprod_prev,
        alphas_cumprod_next,
        sqrt_alphas_cumprod,
        sqrt_one_minus_alphas_cumprod,
        log_one_minus_alphas_cumprod,
        sqrt_recip_alphas_cumprod,
        sqrt_recipm1_alphas_cumprod,
        posterior_log_variance_clipped,
        posterior_mean_coef1,
        posterior_mean_coef2,
    )
//  [python]
def indices_to_integers(shape, ii):
    '''
    indices_to_integers(shape, ii) yields an integer array whose values
      represent the columns of the index matrix ii (e.g., as returned by
      numpy.where or torch.where).

    The return value is always a numpy array.

    See also integers_to_indices().
    '''
    tr = np.roll(np.array([np.prod(shape[:i]) for i in range(len(shape)+1)]), 1)
    tr[0] = 1
    return np.dot(tr, asarray(ii))
//  [python]
def indices_to_integers(shape, ii):
    '''
    indices_to_integers(shape, ii) yields an integer array whose values
      represent the columns of the index matrix ii (e.g., as returned by
      numpy.where or torch.where).

    The return value is always a numpy array.

    See also integers_to_indices().
    '''
    tr = np.roll(np.cumprod(shape), 1)
    tr[0] = 1
    return np.dot(tr, asarray(ii))
//  [python]
def _get_strides(dims: Union[List[int], np.ndarray]) -> np.ndarray:
  """
  compute strides of `dims`.
  """
  return np.flip(np.append(1, np.array(list(itertools.accumulate(np.flip(dims[1::]))))))
//  [python]
def _get_strides(dims: Union[List[int], np.ndarray]) -> np.ndarray:
  """
  compute strides of `dims`.
  """
  return np.flip(np.append(1, np.cumprod(np.flip(dims[1::]))))
//  [python]
def integers_to_indices(shape, ii):
    '''
    integers_to_indices(shape, ii) yields an indices matrix whose columns
      represent the values of the integer vector ii (e.g., as returned by
      indices_to_integers).

    The return value is always a numpy array.

    See also integers_to_indices().
    '''
    tr = np.roll(np.array([np.prod(shape[:i+1]) for i in range(len(shape))]), 1)
    tr[0] = 1
    rr = np.zeros((len(shape), len(ii)), dtype=int)
    for (rrrow,shval) in zip(reversed(rr), reversed(tr)):
        rrrow[:] = np.floor_divide(ii, shval)
        ii = np.mod(ii, shval)
    return rr
//  [python]
def integers_to_indices(shape, ii):
    '''
    integers_to_indices(shape, ii) yields an indices matrix whose columns
      represent the values of the integer vector ii (e.g., as returned by
      indices_to_integers).

    The return value is always a numpy array.

    See also integers_to_indices().
    '''
    tr = np.roll(np.cumprod(shape), 1)
    tr[0] = 1
    rr = np.zeros((len(shape), len(ii)), dtype=int)
    for (rrrow,shval) in zip(reversed(rr), reversed(tr)):
        rrrow[:] = np.floor_divide(ii, shval)
        ii = np.mod(ii, shval)
    return rr
//  [python]
def _raveled_index(self, slice_index=None):
        # return an index array on the raveled array, which is formed by the current_slice
        # of this object
        extended_realshape = np.array([reduce(lambda x,y:x*y, (1,) + self._realshape_[:0:-1][i:]) for i in range(len(self._realshape_))])[::-1]
        ind = self._indices(slice_index)
        if ind.ndim < 2: ind = ind[:, None]
        return np.asarray(np.apply_along_axis(lambda x: np.sum(extended_realshape * x), 1, ind), dtype=int)
//  [python]
def _raveled_index(self, slice_index=None):
        # return an index array on the raveled array, which is formed by the current_slice
        # of this object
        extended_realshape = np.cumprod((1,) + self._realshape_[:0:-1])[::-1]
        ind = self._indices(slice_index)
        if ind.ndim < 2: ind = ind[:, None]
        return np.asarray(np.apply_along_axis(lambda x: np.sum(extended_realshape * x), 1, ind), dtype=int)