jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_nansum_axis_float16(self):
        # Note that the above test example overflows in float16. We use a
        # smaller array instead, just return if array is too large.
        if (numpy.prod(self.shape) > 24):
            return
        a = testing.shaped_arange(self.shape, dtype='e')
        a[:, 1] = cupy.nan
        sa = cupy.nansum(a, axis=1)
        b = testing.shaped_arange(self.shape, numpy, dtype='f')
        b[:, 1] = numpy.nan
        sb = numpy.nansum(b, axis=1)
        testing.assert_allclose(sa, sb.astype('e'))
//  [python]
def get_parts(config, offset):
    """
    Generate a (6,n) particles array based on the grid configuration
    and initial offset, returns a grid object containing the grid and
    the offset from which the array can be reconstructed
    """
    def get_part_grid_uniform(bnd, np, amp):
        x = [numpy.linspace(*b, n)*a for a, b, n in zip(amp, bnd, np)]
        try:
            g1, g2 = numpy.meshgrid(*x)
        except ValueError:
            g1, g2 = numpy.meshgrid(x, 0.0)
        return numpy.array([g1.flatten(), g2.flatten()])

    def get_part_grid_radial(bnd, np, amp):
        x = [numpy.linspace(*b, n) for b, n in zip(bnd, np)]
        g1, g2 = numpy.meshgrid(*x)
        g1r = amp[0]*numpy.cos(g2)*g1
        g2r = amp[1]*numpy.sin(g2)*g1
        return numpy.array([g1r.flatten(), g2r.flatten()])

    pind = config.planesi
    amp = config.amplitudes
    np = config.shape
    bnd = config.bounds
    gm = config.mode

    if gm is GridMode.CARTESIAN:
        g = get_part_grid_uniform(bnd, np, amp)
    elif gm is GridMode.RADIAL:
        g = get_part_grid_radial(bnd, np, amp)
    parts = numpy.zeros((6, reduce(lambda x, y: x*y, np)))
    parts[pind, :] = [g[i] for i in range(len(pind))]
    offset = numpy.array(offset) + config.shift_zero
    parts = (parts.T+offset).T
    return parts, grid(g, offset[pind])
//  [python]
def get_parts(config, offset):
    """
    Generate a (6,n) particles array based on the grid configuration
    and initial offset, returns a grid object containing the grid and
    the offset from which the array can be reconstructed
    """
    def get_part_grid_uniform(bnd, np, amp):
        x = [numpy.linspace(*b, n)*a for a, b, n in zip(amp, bnd, np)]
        try:
            g1, g2 = numpy.meshgrid(*x)
        except ValueError:
            g1, g2 = numpy.meshgrid(x, 0.0)
        return numpy.array([g1.flatten(), g2.flatten()])

    def get_part_grid_radial(bnd, np, amp):
        x = [numpy.linspace(*b, n) for b, n in zip(bnd, np)]
        g1, g2 = numpy.meshgrid(*x)
        g1r = amp[0]*numpy.cos(g2)*g1
        g2r = amp[1]*numpy.sin(g2)*g1
        return numpy.array([g1r.flatten(), g2r.flatten()])

    pind = config.planesi
    amp = config.amplitudes
    np = config.shape
    bnd = config.bounds
    gm = config.mode

    if gm is GridMode.CARTESIAN:
        g = get_part_grid_uniform(bnd, np, amp)
    elif gm is GridMode.RADIAL:
        g = get_part_grid_radial(bnd, np, amp)
    parts = numpy.zeros((6, numpy.prod(np)))
    parts[pind, :] = [g[i] for i in range(len(pind))]
    offset = numpy.array(offset) + config.shift_zero
    parts = (parts.T+offset).T
    return parts, grid(g, offset[pind])
//  [python]
def test_fft_kpq(nalpha):
    # Create regular grid.
    nmax = 2
    mesh = [2*nmax+1]*1
    grid, eigs = generate_fft_grid(mesh)
    
    qmax = 2*nmax
    qmesh = [2*qmax+1]*1
    qgrid, qeigs = generate_fft_grid(qmesh)

    # Create wavefunction
    nbasis = len(grid)
    
    numpy.random.seed(7)

    psi = get_random_wavefunction((nalpha,nalpha), nbasis)
    I = numpy.eye(nbasis, dtype=numpy.complex128)
    # print(I.shape)
    I = get_random_wavefunction((nalpha,nalpha), nbasis)
    # print(I.shape)
    # exit()

    # Select lowest energy states for trial
    trial = I[:,:nalpha].conj()
    trial.imag[:] = 0
    G, Gh = gab_mod(trial,psi[:,:nalpha])
    nqgrid = numpy.prod(qmesh)

    # # Check by direct convolution f(q) = \sum_G Psi[G+Q] Gh[G].
    print(grid.shape)
    fq_direct = numpy.zeros(nqgrid, dtype=numpy.complex128)
    for iq, q in enumerate(qgrid):
        Gtrace_direct = 0
        # for a in range(nalpha):
        # compute \sum_G f_G(q)
        for i, k in enumerate(grid):
            kpq = k+q
            ikpq = lookup(kpq, grid)
            if ikpq is not None:
                Gtrace_direct += trial[ikpq,0] * Gh[0,i]
        fq_direct[iq] = Gtrace_direct

    # Check by fft convolve
    # Compare to fq
    fq_conv = numpy.zeros(nqgrid, dtype=numpy.complex128)
    trial_pq = trial[:,0].copy()
    Gh_pq = Gh[0,:].copy()

    fq_conv += nqgrid*convolve(Gh_pq, numpy.flip(trial_pq), mesh)
    fq_conv = numpy.flip(fq_conv)

    import scipy.signal
    fq_conv_sc = numpy.flip(scipy.signal.fftconvolve(
            Gh_pq,numpy.flip(trial_pq)).ravel())

    import matplotlib.pyplot as pl
    pl.plot(fq_conv, label='fft')
    pl.plot(fq_conv_sc, label='fft_scipy')
    pl.plot(fq_direct, label='direct')
    # pl.plot(fq, label='from_gf')
    pl.legend()
    pl.show()
//  [python]
def plot_centroid_covariance_matrices_evolution(covariance_matrices,
                                                distribution, name=None):

    distribution = normalise_string(distribution)
    figure_name = "centroids_evolution-{}-covariance_matrices".format(
        distribution)
    figure_name = saving.build_figure_name(figure_name, name)

    y_label = _axis_label_for_symbol(
        symbol="\\Sigma",
        distribution=distribution,
        prefix="|",
        suffix="(y = k)|"
    )

    n_epochs, n_centroids, __, __ = covariance_matrices.shape
    determinants = numpy.empty([n_epochs, n_centroids])

    for e in range(n_epochs):
        for k in range(n_centroids):
            determinants[e, k] = numpy.prod(numpy.diag(
                covariance_matrices[e, k]))

    if determinants.all() > 0:
        line_range_ratio = numpy.empty(n_centroids)
        for k in range(n_centroids):
            determinants_min = determinants[:, k].min()
            determinants_max = determinants[:, k].max()
            line_range_ratio[k] = determinants_max / determinants_min
        range_ratio = line_range_ratio.max() / line_range_ratio.min()
        if range_ratio > 1e2:
            y_scale = "log"
        else:
            y_scale = "linear"

    centroids_palette = style.darker_palette(n_centroids)
    epochs = numpy.arange(n_epochs) + 1

    figure = pyplot.figure()
    axis = figure.add_subplot(1, 1, 1)
    seaborn.despine()

    for k in range(n_centroids):
        axis.plot(
            epochs,
            determinants[:, k],
            color=centroids_palette[k],
            label="$k = {}$".format(k)
        )

    axis.set_xlabel("Epochs")
    axis.set_ylabel(y_label)

    axis.set_yscale(y_scale)

    axis.legend(loc="best")

    return figure, figure_name
//  [python]
def fit(self, X, y, sample_weight=None):
        """Train a classifier and collect predictions for all possible combinations.

        :param X: pandas.DataFrame or numpy.array with data of shape [n_samples, n_features]
        :param y: array with labels of shape [n_samples]
        :param sample_weight: None or array of shape [n_samples] with weights of events
        :return: self
        """
        self.classes_ = numpy.unique(y)
        X, y, normed_weights = check_xyw(X, y, sample_weight=sample_weight, classification=True)
        X = to_pandas_dataframe(X)
        normed_weights = check_sample_weight(y, sample_weight=normed_weights, normalize_by_class=True, normalize=True)

        self.bin_edges = self._compute_bin_edges(X, normed_weights=normed_weights)
        self.check_dimensions(self.bin_edges)

        n_parameter_combinations = n.prod([len(bin_edge) + 1 for name, bin_edge in self.bin_edges.items()])

        transformed_data = self.transform(X)
        trained_estimator = clone(self.base_estimator)
        fit_params = {}
        if sample_weight is not None:
            fit_params['sample_weights'] = sample_weight
        trained_estimator.fit(transformed_data, y, **fit_params)

        all_lookup_indices = numpy.arange(int(n_parameter_combinations))
        all_combinations = self.convert_lookup_index_to_bins(all_lookup_indices)
        self._lookup_table = trained_estimator.predict_proba(all_combinations)

        if self.keep_trained_estimator:
            self.trained_estimator = trained_estimator

        return self
//  [python]
def fit(self, X, y, sample_weight=None):
        """Train a classifier and collect predictions for all possible combinations.

        :param X: pandas.DataFrame or numpy.array with data of shape [n_samples, n_features]
        :param y: array with labels of shape [n_samples]
        :param sample_weight: None or array of shape [n_samples] with weights of events
        :return: self
        """
        self.classes_ = numpy.unique(y)
        X, y, normed_weights = check_xyw(X, y, sample_weight=sample_weight, classification=True)
        X = to_pandas_dataframe(X)
        normed_weights = check_sample_weight(y, sample_weight=normed_weights, normalize_by_class=True, normalize=True)

        self.bin_edges = self._compute_bin_edges(X, normed_weights=normed_weights)
        self.check_dimensions(self.bin_edges)

        n_parameter_combinations = numpy.prod([len(bin_edge) + 1 for name, bin_edge in self.bin_edges.items()])

        transformed_data = self.transform(X)
        trained_estimator = clone(self.base_estimator)
        fit_params = {}
        if sample_weight is not None:
            fit_params['sample_weights'] = sample_weight
        trained_estimator.fit(transformed_data, y, **fit_params)

        all_lookup_indices = numpy.arange(int(n_parameter_combinations))
        all_combinations = self.convert_lookup_index_to_bins(all_lookup_indices)
        self._lookup_table = trained_estimator.predict_proba(all_combinations)

        if self.keep_trained_estimator:
            self.trained_estimator = trained_estimator

        return self
//  [python]
def candidate_weighting(self, window=2, stoplist=None, use_stems=False):
        """Candidate weight calculation as described in the YAKE paper.

        Args:
            stoplist (list): the stoplist for filtering candidates, defaults to
                the nltk stoplist.
            use_stems (bool): whether to use stems instead of lowercase words
                for weighting, defaults to False.
            window (int): the size in words of the window used for computing
                co-occurrence counts, defaults to 2.
        """

        # build the vocabulary
        self._vocabulary_building(use_stems=use_stems)

        # extract the contexts
        self._contexts_building(use_stems=use_stems, window=window)

        # compute the word features
        self._feature_extraction(stoplist=stoplist)

        # compute candidate weights
        for k, v in self.candidates.items():

            # use stems
            if use_stems:
                weights = [self.features[t]['weight'] for t in v.lexical_form]
                self.weights[k] = numpy.prod(weights)
                self.weights[k] /= len(v.offsets) * (1 + sum(weights))

            # use words
            else:
                lowercase_forms = [' '.join(t).lower() for t in v.surface_forms]
                for i, candidate in enumerate(lowercase_forms):
                    TF = lowercase_forms.count(candidate)

                    # computing differentiated weights for words and stopwords
                    # (vitordouzi change)
                    tokens = [t.lower() for t in v.surface_forms[i]]
                    prod_ = 1.
                    sum_ = 0.
                    for j, token in enumerate(tokens):
                        if self.features[token]['isstop']:
                            term_left = tokens[j-1]
                            term_right = tokens[j+1]
                            term_stop = token
                            prob_t1 = self.contexts[term_left][1].count(
                                term_stop) / self.features[term_left]['TF']
                            prob_t2 = self.contexts[term_stop][0].count(
                                term_right) / self.features[term_right]['TF']

                            prob = prob_t1 * prob_t2
                            prod_ *= (1 + (1 - prob))
                            sum_ -= (1 - prob)
                        else:
                            prod_ *= self.features[token]['weight']
                            sum_ += self.features[token]['weight']

                    self.weights[candidate] = prod_
                    self.weights[candidate] /= TF * (1 + sum_)
                    self.surface_to_lexical[candidate] = k
//  [python]
def test_fft_kmq(nalpha):
    # Create regular grid.
    nmax = 2
    mesh = [2*nmax+1]*1
    grid, eigs = generate_fft_grid(mesh)
    
    qmax = 2*nmax
    qmesh = [2*qmax+1]*1
    qgrid, qeigs = generate_fft_grid(qmesh)

    # Create wavefunction
    nbasis = len(grid)
    
    numpy.random.seed(7)

    psi = get_random_wavefunction((nalpha,nalpha), nbasis)
    I = numpy.eye(nbasis, dtype=numpy.complex128)
    # print(I.shape)
    I = get_random_wavefunction((nalpha,nalpha), nbasis)
    # print(I.shape)
    # exit()

    # Select lowest energy states for trial
    trial = I[:,:nalpha].conj()
    trial.imag[:] = 0
    
    G, Gh = gab_mod(trial,psi[:,:nalpha])
    nqgrid = numpy.multiply.reduce(qmesh)

    # # Check by direct convolution f(q) = \sum_G Psi[G+Q] Gh[G].
    print(grid.shape)
    fq_direct = numpy.zeros(nqgrid, dtype=numpy.complex128)
    for iq, q in enumerate(qgrid):
        Gtrace_direct = 0
        # for a in range(nalpha):
        # compute \sum_G f_G(q)
        for i, k in enumerate(grid):
            # kmq = q-k
            kmq = k-q
            ikmq = lookup(kmq, grid)
            # idx = numpy.argwhere(basis == q-k)
            # print(idx, ikmq)
            if ikmq is not None:
                Gtrace_direct += trial[i,0] * Gh[0,ikmq]
        fq_direct[iq] = Gtrace_direct
    print("trial[igmq,0] = {}".format(trial[:,0]))
    print("Gh[0,i] = {}".format(Gh[0,:]))
    # Check by fft convolve
    # Compare to fq
    fq_conv = numpy.zeros(nqgrid, dtype=numpy.complex128)
    trial_pq = trial[:,0].copy()
    Gh_pq = Gh[0,:].copy()

    # \sum_G f(G-Q) g(G)
    # -G-Q -> G'
    # \sum_G g(-G-Q) f(-G) = \sum_G g(G) f(G+Q)
    # trial_pq = numpy.conj(trial_pq)
    fq_conv += nqgrid*convolve(Gh_pq, numpy.flip(trial_pq), mesh)
    fq_conv = numpy.flip(fq_conv)

    import scipy.signal
    fq_conv_sc = numpy.flip(scipy.signal.fftconvolve(
            Gh_pq,numpy.flip(trial_pq)).ravel())

    # for i in range(qmesh[0]):
    #     target = fq_conv[i]
    #     print(numpy.abs(target))
    #     if (numpy.abs(target) > 1e-8):
    #         # print(target)
    #         idx = numpy.argwhere(numpy.abs(fq_direct - target) < 1e-8)
    #         # print(i, idx)


    import matplotlib.pyplot as pl
    pl.plot(fq_conv, label='fft')
    pl.plot(fq_conv_sc, label='fft_scipy')
    pl.plot(fq_direct, label='direct')
    # pl.plot(fq, label='from_gf')
    pl.legend()
    pl.show()
//  [python]
def test_fft_kmq(nalpha):
    # Create regular grid.
    nmax = 2
    mesh = [2*nmax+1]*1
    grid, eigs = generate_fft_grid(mesh)
    
    qmax = 2*nmax
    qmesh = [2*qmax+1]*1
    qgrid, qeigs = generate_fft_grid(qmesh)

    # Create wavefunction
    nbasis = len(grid)
    
    numpy.random.seed(7)

    psi = get_random_wavefunction((nalpha,nalpha), nbasis)
    I = numpy.eye(nbasis, dtype=numpy.complex128)
    # print(I.shape)
    I = get_random_wavefunction((nalpha,nalpha), nbasis)
    # print(I.shape)
    # exit()

    # Select lowest energy states for trial
    trial = I[:,:nalpha].conj()
    trial.imag[:] = 0
    
    G, Gh = gab_mod(trial,psi[:,:nalpha])
    nqgrid = numpy.prod(qmesh)

    # # Check by direct convolution f(q) = \sum_G Psi[G+Q] Gh[G].
    print(grid.shape)
    fq_direct = numpy.zeros(nqgrid, dtype=numpy.complex128)
    for iq, q in enumerate(qgrid):
        Gtrace_direct = 0
        # for a in range(nalpha):
        # compute \sum_G f_G(q)
        for i, k in enumerate(grid):
            # kmq = q-k
            kmq = k-q
            ikmq = lookup(kmq, grid)
            # idx = numpy.argwhere(basis == q-k)
            # print(idx, ikmq)
            if ikmq is not None:
                Gtrace_direct += trial[i,0] * Gh[0,ikmq]
        fq_direct[iq] = Gtrace_direct
    print("trial[igmq,0] = {}".format(trial[:,0]))
    print("Gh[0,i] = {}".format(Gh[0,:]))
    # Check by fft convolve
    # Compare to fq
    fq_conv = numpy.zeros(nqgrid, dtype=numpy.complex128)
    trial_pq = trial[:,0].copy()
    Gh_pq = Gh[0,:].copy()

    # \sum_G f(G-Q) g(G)
    # -G-Q -> G'
    # \sum_G g(-G-Q) f(-G) = \sum_G g(G) f(G+Q)
    # trial_pq = numpy.conj(trial_pq)
    fq_conv += nqgrid*convolve(Gh_pq, numpy.flip(trial_pq), mesh)
    fq_conv = numpy.flip(fq_conv)

    import scipy.signal
    fq_conv_sc = numpy.flip(scipy.signal.fftconvolve(
            Gh_pq,numpy.flip(trial_pq)).ravel())

    # for i in range(qmesh[0]):
    #     target = fq_conv[i]
    #     print(numpy.abs(target))
    #     if (numpy.abs(target) > 1e-8):
    #         # print(target)
    #         idx = numpy.argwhere(numpy.abs(fq_direct - target) < 1e-8)
    #         # print(i, idx)


    import matplotlib.pyplot as pl
    pl.plot(fq_conv, label='fft')
    pl.plot(fq_conv_sc, label='fft_scipy')
    pl.plot(fq_direct, label='direct')
    # pl.plot(fq, label='from_gf')
    pl.legend()
    pl.show()
//  [python]
def _load_layer_weights_nested_(model, weights, skip_mismatch=False, debug=False, prefix=""):
    for layer in model.layers:
        if len(layer.weights) == 0:
            continue
        if debug:
            print(">>>> Load layer weights:", "/".join([prefix, layer.name]) if prefix else layer.name, [ii.name for ii in layer.weights])
        if layer.name not in weights:
            if debug:
                print("Warning: {} not exists in provided h5 weights".format(layer.name))
            continue

        ss = weights[layer.name]
        if hasattr(layer, "layers"):  # nested
            dd = {}
            for weight_name in ss.attrs["weight_names"]:
                dd.setdefault("/".join(weight_name.split("/")[:-1]), []).append(ss[weight_name])
            _load_layer_weights_nested_(layer, dd, skip_mismatch=skip_mismatch, debug=debug, prefix=layer.name)
            continue

        if hasattr(ss, "attrs"):
            ss = [np.array(ss[ww]) for ww in ss.attrs["weight_names"]]
        elif hasattr(ss, "values"):
            ss = [np.array(ww) for ww in ss.values()]
        else:
            ss = [np.array(ww) for ww in ss]

        source_shape, target_shape = [ii.shape for ii in ss], [list(ii.shape) for ii in layer.weights]
        if debug:
            print("     [Before transpose] required weights: {}, provided: {}".format(target_shape, source_shape))
        if skip_mismatch and (len(source_shape) != len(target_shape) or any([np.multiply.reduce(ii) != np.multiply.reduce(jj) for ii, jj in zip(source_shape, target_shape)])):
            print("Warning: skip loading weights for layer: {}, required weights: {}, provided: {}".format(layer.name, target_shape, source_shape))
            continue

        if hasattr(layer, "set_weights_channels_last"):
            layer.set_weights_channels_last(ss)
        else:
            layer.set_weights(ss)
//  [python]
def _load_layer_weights_nested_(model, weights, skip_mismatch=False, debug=False, prefix=""):
    for layer in model.layers:
        if len(layer.weights) == 0:
            continue
        if debug:
            print(">>>> Load layer weights:", "/".join([prefix, layer.name]) if prefix else layer.name, [ii.name for ii in layer.weights])
        if layer.name not in weights:
            if debug:
                print("Warning: {} not exists in provided h5 weights".format(layer.name))
            continue

        ss = weights[layer.name]
        if hasattr(layer, "layers"):  # nested
            dd = {}
            for weight_name in ss.attrs["weight_names"]:
                dd.setdefault("/".join(weight_name.split("/")[:-1]), []).append(ss[weight_name])
            _load_layer_weights_nested_(layer, dd, skip_mismatch=skip_mismatch, debug=debug, prefix=layer.name)
            continue

        if hasattr(ss, "attrs"):
            ss = [np.array(ss[ww]) for ww in ss.attrs["weight_names"]]
        elif hasattr(ss, "values"):
            ss = [np.array(ww) for ww in ss.values()]
        else:
            ss = [np.array(ww) for ww in ss]

        source_shape, target_shape = [ii.shape for ii in ss], [list(ii.shape) for ii in layer.weights]
        if debug:
            print("     [Before transpose] required weights: {}, provided: {}".format(target_shape, source_shape))
        if skip_mismatch and (len(source_shape) != len(target_shape) or any([np.prod(ii) != np.prod(jj) for ii, jj in zip(source_shape, target_shape)])):
            print("Warning: skip loading weights for layer: {}, required weights: {}, provided: {}".format(layer.name, target_shape, source_shape))
            continue

        if hasattr(layer, "set_weights_channels_last"):
            layer.set_weights_channels_last(ss)
        else:
            layer.set_weights(ss)
//  [python]
def __init__(self, m, size, flags):
        (dtype, ctype) = flags.dtype()
        elsize = np.dtype(dtype).itemsize

        shape = size.to_numpy()
        steps = np.asarray([int(m['step']['p'][i]) for i in range(len(shape))], dtype=np.int64)

        ptr = m['data']
        # either we are default-constructed or sizes are zero
        if int(ptr) == 0 or reduce(lambda x, y: x * y, shape * steps) == 0:
            self.mat = np.array([])
            self.view = self.mat
            return

        # we don't want to show excess brackets
        if flags.channels() != 1:
            shape = np.append(shape, flags.channels())
            steps = np.append(steps, elsize)

        # get the length of contiguous array from data to the last element of the matrix
        length = 1 + np.sum((shape - 1) * steps) // elsize

        if dtype != np.float16:
            # read all elements into self.mat
            ctype = gdb.lookup_type(ctype)
            ptr = ptr.cast(ctype.array(length - 1).pointer()).dereference()
            self.mat = np.array([ptr[i] for i in range(length)], dtype=dtype)
        else:
            # read as uint16_t and then reinterpret the bytes as float16
            u16 = gdb.lookup_type('uint16_t')
            ptr = ptr.cast(u16.array(length - 1).pointer()).dereference()
            self.mat = np.array([ptr[i] for i in range(length)], dtype=np.uint16)
            self.mat = self.mat.view(np.float16)

        # numpy will do the heavy lifting of strided access
        self.view = np.lib.stride_tricks.as_strided(self.mat, shape=shape, strides=steps)
//  [python]
def __init__(self, m, size, flags):
        (dtype, ctype) = flags.dtype()
        elsize = np.dtype(dtype).itemsize

        shape = size.to_numpy()
        steps = np.asarray([int(m['step']['p'][i]) for i in range(len(shape))], dtype=np.int64)

        ptr = m['data']
        # either we are default-constructed or sizes are zero
        if int(ptr) == 0 or np.prod(shape * steps) == 0:
            self.mat = np.array([])
            self.view = self.mat
            return

        # we don't want to show excess brackets
        if flags.channels() != 1:
            shape = np.append(shape, flags.channels())
            steps = np.append(steps, elsize)

        # get the length of contiguous array from data to the last element of the matrix
        length = 1 + np.sum((shape - 1) * steps) // elsize

        if dtype != np.float16:
            # read all elements into self.mat
            ctype = gdb.lookup_type(ctype)
            ptr = ptr.cast(ctype.array(length - 1).pointer()).dereference()
            self.mat = np.array([ptr[i] for i in range(length)], dtype=dtype)
        else:
            # read as uint16_t and then reinterpret the bytes as float16
            u16 = gdb.lookup_type('uint16_t')
            ptr = ptr.cast(u16.array(length - 1).pointer()).dereference()
            self.mat = np.array([ptr[i] for i in range(length)], dtype=np.uint16)
            self.mat = self.mat.view(np.float16)

        # numpy will do the heavy lifting of strided access
        self.view = np.lib.stride_tricks.as_strided(self.mat, shape=shape, strides=steps)
//  [python]
def __decode_kernel(self, w: _Weights, shape: _Shape) -> NDArray[float64]:
        if isinstance(w, (int, float)):
            _shape = self.__get_kernel_shape(shape)
            return numpy.full(_shape, w, dtype=float64)
        elif isinstance(w, (Sequence, numpy.ndarray)):
            if all(isinstance(lst, (Sequence, numpy.ndarray)) for lst in w):
                ws = cast(TSequence[TSequence[float]], w)
                len0 = len(ws[0])
                # 2D list
                if not all(len(lst) == len0 for lst in ws):
                    raise SynapticConfigurationException(
                        "kernel_weights must be a 2D array with every row the"
                        " same length")
                return numpy.array(w, dtype=float64)
            else:
                # 1D list
                _shape = self.__get_kernel_shape(shape)
                return numpy.array(w, dtype=float64).reshape(_shape)
        elif isinstance(w, RandomDistribution):
            _shape = self.__get_kernel_shape(shape)
            return numpy.array(
                w.next(numpy.multiply.reduce(_shape)), dtype=float64).reshape(_shape)
        else:
            raise SynapticConfigurationException(
                f"Unknown combination of kernel_weights ({w}) and"
                f" kernel_shape ({shape})")
//  [python]
def __decode_kernel(self, w: _Weights, shape: _Shape) -> NDArray[float64]:
        if isinstance(w, (int, float)):
            _shape = self.__get_kernel_shape(shape)
            return numpy.full(_shape, w, dtype=float64)
        elif isinstance(w, (Sequence, numpy.ndarray)):
            if all(isinstance(lst, (Sequence, numpy.ndarray)) for lst in w):
                ws = cast(TSequence[TSequence[float]], w)
                len0 = len(ws[0])
                # 2D list
                if not all(len(lst) == len0 for lst in ws):
                    raise SynapticConfigurationException(
                        "kernel_weights must be a 2D array with every row the"
                        " same length")
                return numpy.array(w, dtype=float64)
            else:
                # 1D list
                _shape = self.__get_kernel_shape(shape)
                return numpy.array(w, dtype=float64).reshape(_shape)
        elif isinstance(w, RandomDistribution):
            _shape = self.__get_kernel_shape(shape)
            return numpy.array(
                w.next(numpy.prod(_shape)), dtype=float64).reshape(_shape)
        else:
            raise SynapticConfigurationException(
                f"Unknown combination of kernel_weights ({w}) and"
                f" kernel_shape ({shape})")
//  [python]
def setup(self):
        super().setup()
        in_dtype, = self.in_dtypes
        if in_dtype == 'float16':
            self.check_forward_options.update({'rtol': 1e-2, 'atol': 1e-2})
            self.check_backward_options.update({'rtol': 1e-2, 'atol': 1e-2})
            self.check_double_backward_options.update(
                {'rtol': 1e-2, 'atol': 1e-2})

        if (numpy.dtype(in_dtype).kind in ('float16, float32')
                and numpy.prod(self.shape) > 1000):
            pytest.skip('Skip large tests for float16/float32 dtypes')
//  [python]
def __invert__(self):
        try:
            arr = operator.inv(com._values_from_object(self))
            return self.__array_wrap__(arr)
        except Exception:

            # inv fails with 0 len
            if not n.prod(self.shape):
                return self

            raise
//  [python]
def __invert__(self):
        try:
            arr = operator.inv(com._values_from_object(self))
            return self.__array_wrap__(arr)
        except Exception:

            # inv fails with 0 len
            if not np.prod(self.shape):
                return self

            raise
//  [python]
def read_array_header(inputfile, header):
    f = inputfile
    array_header = {}

    array_header["sizeof(p[0])"] = struct.unpack('=1i', f.read(header["sizeof(int)"]))[0]
    ndim = struct.unpack('=1i', f.read(header["sizeof(int)"]))[0]
    array_header["ndim"] = ndim
    dim = struct.unpack('='+str(ndim)+'i', f.read(ndim*int(header["sizeof(int)"])))[0:ndim]
    array_header["dim"] = dim
    elements = reduce(lambda x, y: x*y, dim)

    cur_byte = f.tell()
    unread_byte = header["end_byte"] - cur_byte
    no_fields = unread_byte / (elements * header["sizeof(float)"])

    array_header["no_fields"] = no_fields

    return array_header
//  [python]
def read_array_header(inputfile, header):
    f = inputfile
    array_header = {}

    array_header["sizeof(p[0])"] = struct.unpack('=1i', f.read(header["sizeof(int)"]))[0]
    ndim = struct.unpack('=1i', f.read(header["sizeof(int)"]))[0]
    array_header["ndim"] = ndim
    dim = struct.unpack('='+str(ndim)+'i', f.read(ndim*int(header["sizeof(int)"])))[0:ndim]
    array_header["dim"] = dim
    elements = numpy.prod(dim)

    cur_byte = f.tell()
    unread_byte = header["end_byte"] - cur_byte
    no_fields = unread_byte / (elements * header["sizeof(float)"])

    array_header["no_fields"] = no_fields

    return array_header
//  [python]
def setup_method(self, method):
        # Classic XOR problem:
        # 2 features:
        # - negative product ==> class 1
        # - non-negative product ==> class 2
        feature_grid = numpy.mgrid[-5:5, -5:5]
        feature_matrix = numpy.concatenate(feature_grid.transpose())

        labels = (numpy.multiply.reduce(feature_matrix, axis=-1) >= 0).astype(numpy.uint32) + 1
        labels = labels.flat[:]

        unseen_data = [[1.5, 2.5], [-1.5, -2.5], [3.4, -4.0], [-1.2, 2.0]]
        expected_classes = (numpy.multiply.reduce(unseen_data, axis=-1) > 0).astype(numpy.uint32) + 1

        self.training_feature_matrix = feature_matrix
        self.training_labels = labels
        self.prediction_data = unseen_data
        self.expected_classes = expected_classes
//  [python]
def setup_method(self, method):
        # Classic XOR problem:
        # 2 features:
        # - negative product ==> class 1
        # - non-negative product ==> class 2
        feature_grid = numpy.mgrid[-5:5, -5:5]
        feature_matrix = numpy.concatenate(feature_grid.transpose())

        labels = (feature_matrix.prod(axis=-1) >= 0).astype(numpy.uint32) + 1
        labels = labels.flat[:]

        unseen_data = [[1.5, 2.5], [-1.5, -2.5], [3.4, -4.0], [-1.2, 2.0]]
        expected_classes = (numpy.prod(unseen_data, axis=-1) > 0).astype(numpy.uint32) + 1

        self.training_feature_matrix = feature_matrix
        self.training_labels = labels
        self.prediction_data = unseen_data
        self.expected_classes = expected_classes
//  [python]
def size(self):
        """
        Return an int representing the number of elements in this object.

        Return the number of rows if Series. Otherwise return the number of
        rows times number of columns if DataFrame.

        See Also
        --------
        ndarray.size

        Examples
        --------
        >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})
        >>> s.size
        3

        >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
        >>> df.size
        4
        """
        return self.shape[0] * self.shape[1] if len(self.shape) >1 else self.shape[0]
//  [python]
def size(self):
        """
        Return an int representing the number of elements in this object.

        Return the number of rows if Series. Otherwise return the number of
        rows times number of columns if DataFrame.

        See Also
        --------
        ndarray.size

        Examples
        --------
        >>> s = pd.Series({'a': 1, 'b': 2, 'c': 3})
        >>> s.size
        3

        >>> df = pd.DataFrame({'col1': [1, 2], 'col2': [3, 4]})
        >>> df.size
        4
        """
        return np.prod(self.shape)
//  [python]
def load_data(self):
        super(FullBatchImageLoader, self).load_data()

        # Allocate data
        required_mem = self.total_samples * n.prod(self.shape) * \
            n.dtype(self.source_dtype).itemsize
        if virtual_memory().available < required_mem:
            gb = 1.0 / (1000 * 1000 * 1000)
            self.critical("Not enough memory (free %.3f Gb, required %.3f Gb)",
                          virtual_memory().free * gb, required_mem * gb)
            raise MemoryError("Not enough memory")
        # Real allocation will still happen during the second pass
        self.create_originals(self.shape)
        self.original_label_values.mem = n.zeros(
            self.total_samples, n.float32)

        has_labels = self._fill_original_data()

        # Delete labels mem if no labels was extracted
        if n.prod(has_labels) == 0 and sum(has_labels) > 0:
            raise error.BadFormatError(
                "Some classes do not have labels while other do")
        if sum(has_labels) == 0:
            del self.original_labels[:]
//  [python]
def load_data(self):
        super(FullBatchImageLoader, self).load_data()

        # Allocate data
        required_mem = self.total_samples * numpy.prod(self.shape) * \
            numpy.dtype(self.source_dtype).itemsize
        if virtual_memory().available < required_mem:
            gb = 1.0 / (1000 * 1000 * 1000)
            self.critical("Not enough memory (free %.3f Gb, required %.3f Gb)",
                          virtual_memory().free * gb, required_mem * gb)
            raise MemoryError("Not enough memory")
        # Real allocation will still happen during the second pass
        self.create_originals(self.shape)
        self.original_label_values.mem = numpy.zeros(
            self.total_samples, numpy.float32)

        has_labels = self._fill_original_data()

        # Delete labels mem if no labels was extracted
        if numpy.prod(has_labels) == 0 and sum(has_labels) > 0:
            raise error.BadFormatError(
                "Some classes do not have labels while other do")
        if sum(has_labels) == 0:
            del self.original_labels[:]
//  [python]
def test_call_with_unaligned(self):
        '''Make sure the right thing happens with unaligned data.
        '''
        input_array = (numpy.random.randn(*self.input_array.shape)
                + 1j*numpy.random.randn(*self.input_array.shape))

        output_array = self.fft(
                input_array=byte_align(input_array.copy(), n=16)).copy()

        input_array = byte_align(input_array, n=16)
        output_array = byte_align(output_array, n=16)

        # Offset by one from 16 byte aligned to guarantee it's not
        # 16 byte aligned
        a = byte_align(input_array.copy(), n=16)
        a__ = empty_aligned(n.prod(a.shape)*a.itemsize+1, dtype='int8',
                            n=16)

        a_ = a__[1:].view(dtype=a.dtype).reshape(*a.shape)
        a_[:] = a

        # Create a different second array the same way
        b = byte_align(output_array.copy(), n=16)
        b__ = empty_aligned(n.prod(b.shape)*a.itemsize+1, dtype='int8',
                            n=16)

        b_ = b__[1:].view(dtype=b.dtype).reshape(*b.shape)
        b_[:] = a

        # Set up for the first array
        fft = FFTW(input_array, output_array)
        a_[:] = a
        output_array = fft().copy()

        # Check a_ is not aligned...
        self.assertRaisesRegex(ValueError, 'Invalid input alignment',
                self.fft.update_arrays, *(a_, output_array))

        # and b_ too
        self.assertRaisesRegex(ValueError, 'Invalid output alignment',
                self.fft.update_arrays, *(input_array, b_))

        # But it should still work with the a_
        fft(a_)

        # However, trying to update the output will raise an error
        self.assertRaisesRegex(ValueError, 'Invalid output alignment',
                self.fft.update_arrays, *(input_array, b_))

        # Same with SIMD off
        fft = FFTW(input_array, output_array, flags=('FFTW_UNALIGNED',))
        fft(a_)
        self.assertRaisesRegex(ValueError, 'Invalid output alignment',
                self.fft.update_arrays, *(input_array, b_))
//  [python]
def test_call_with_unaligned(self):
        '''Make sure the right thing happens with unaligned data.
        '''
        input_array = (numpy.random.randn(*self.input_array.shape)
                + 1j*numpy.random.randn(*self.input_array.shape))

        output_array = self.fft(
                input_array=byte_align(input_array.copy(), n=16)).copy()

        input_array = byte_align(input_array, n=16)
        output_array = byte_align(output_array, n=16)

        # Offset by one from 16 byte aligned to guarantee it's not
        # 16 byte aligned
        a = byte_align(input_array.copy(), n=16)
        a__ = empty_aligned(numpy.prod(a.shape)*a.itemsize+1, dtype='int8',
                            n=16)

        a_ = a__[1:].view(dtype=a.dtype).reshape(*a.shape)
        a_[:] = a

        # Create a different second array the same way
        b = byte_align(output_array.copy(), n=16)
        b__ = empty_aligned(numpy.prod(b.shape)*a.itemsize+1, dtype='int8',
                            n=16)

        b_ = b__[1:].view(dtype=b.dtype).reshape(*b.shape)
        b_[:] = a

        # Set up for the first array
        fft = FFTW(input_array, output_array)
        a_[:] = a
        output_array = fft().copy()

        # Check a_ is not aligned...
        self.assertRaisesRegex(ValueError, 'Invalid input alignment',
                self.fft.update_arrays, *(a_, output_array))

        # and b_ too
        self.assertRaisesRegex(ValueError, 'Invalid output alignment',
                self.fft.update_arrays, *(input_array, b_))

        # But it should still work with the a_
        fft(a_)

        # However, trying to update the output will raise an error
        self.assertRaisesRegex(ValueError, 'Invalid output alignment',
                self.fft.update_arrays, *(input_array, b_))

        # Same with SIMD off
        fft = FFTW(input_array, output_array, flags=('FFTW_UNALIGNED',))
        fft(a_)
        self.assertRaisesRegex(ValueError, 'Invalid output alignment',
                self.fft.update_arrays, *(input_array, b_))
//  [python]
def test_strided_slice_grad_grad():
    shape = (3, 2, 2)
    from tensorflow.python.ops.gen_array_ops import strided_slice_grad

    x = tf.reshape(tf.range(0, n.prod(shape), dtype=tf.float32), shape)
    y = strided_slice_grad(
        shape=tf.convert_to_tensor(shape),
        begin=tf.constant([0]),
        end=tf.constant([0], dtype=tf.int32),
        end_mask=1,
        strides=tf.constant([1]),
        dy=x,
    )
    y.set_shape(x.get_shape())
    vx, vy = session.run([x, y])
    print("vx, vy:", vx, vy)
    assert_almost_equal(vx, vy)
    dy = tf.reshape(tf.range(0, n.prod(shape), dtype=tf.float32) * 0.1 - 5.135, shape)
    (dx,) = tf.gradients(ys=[y], xs=[x], grad_ys=[dy])
    vdx, vdy = session.run([dx, dy])
    print("vdx, vdy:", vdx, vdy)
    assert_almost_equal(vdx, vdy)
//  [python]
def test_strided_slice_grad_grad():
    shape = (3, 2, 2)
    from tensorflow.python.ops.gen_array_ops import strided_slice_grad

    x = tf.reshape(tf.range(0, numpy.prod(shape), dtype=tf.float32), shape)
    y = strided_slice_grad(
        shape=tf.convert_to_tensor(shape),
        begin=tf.constant([0]),
        end=tf.constant([0], dtype=tf.int32),
        end_mask=1,
        strides=tf.constant([1]),
        dy=x,
    )
    y.set_shape(x.get_shape())
    vx, vy = session.run([x, y])
    print("vx, vy:", vx, vy)
    assert_almost_equal(vx, vy)
    dy = tf.reshape(tf.range(0, numpy.prod(shape), dtype=tf.float32) * 0.1 - 5.135, shape)
    (dx,) = tf.gradients(ys=[y], xs=[x], grad_ys=[dy])
    vdx, vdy = session.run([dx, dy])
    print("vdx, vdy:", vdx, vdy)
    assert_almost_equal(vdx, vdy)
//  [python]
def lstm_grad_kwargs():
    """
    :return: kwargs for check_lstm_grad_ops, some dummy input
    :rtype: dict[str]
    """

    def gen(shape, offset, factor=3.0):
        return numpy.sin(numpy.arange(numpy.prod(shape)) * factor + offset).reshape(shape).astype("float32")

    kwargs = lstm_kwargs()
    mask_bc = kwargs["mask"][:, :, None]
    assert mask_bc.shape == (kwargs["n_time"], kwargs["n_batch"], 1)
    kwargs["dy"] = gen((kwargs["n_time"], kwargs["n_batch"], kwargs["n_cells"]), offset=0.15) * mask_bc
    kwargs["dd"] = gen((kwargs["n_batch"], kwargs["n_cells"]), offset=17)
    return kwargs
//  [python]
def test_strided_slice_grad_and_back_grad():
    shape = (3, 2, 2)
    from tensorflow.python.ops.gen_array_ops import strided_slice_grad

    x = tf.reshape(tf.range(0, n.prod(shape), dtype=tf.float32), shape)
    x_ = x[0::1]
    y = strided_slice_grad(
        shape=tf.convert_to_tensor(shape),
        begin=tf.constant([0]),
        end=tf.constant([0], dtype=tf.int32),
        end_mask=1,
        strides=tf.constant([1]),
        dy=x_,
    )
    y.set_shape(x.get_shape())
    vx, vx_, vy = session.run([x, x_, y])
    print("vx, vx_, vy:", vx, vx_, vy)
    assert_almost_equal(vx, vx_)
    assert_almost_equal(vx, vy)
    dy = tf.reshape(tf.range(0, n.prod(shape), dtype=tf.float32) * 0.1 - 5.135, shape)
    (dx,) = tf.gradients(ys=[y], xs=[x], grad_ys=[dy])
    vdx, vdy = session.run([dx, dy])
    print("vdx, vdy:", vdx, vdy)
    assert_almost_equal(vdx, vdy)
//  [python]
def test_strided_slice_grad_and_back_grad():
    shape = (3, 2, 2)
    from tensorflow.python.ops.gen_array_ops import strided_slice_grad

    x = tf.reshape(tf.range(0, numpy.prod(shape), dtype=tf.float32), shape)
    x_ = x[0::1]
    y = strided_slice_grad(
        shape=tf.convert_to_tensor(shape),
        begin=tf.constant([0]),
        end=tf.constant([0], dtype=tf.int32),
        end_mask=1,
        strides=tf.constant([1]),
        dy=x_,
    )
    y.set_shape(x.get_shape())
    vx, vx_, vy = session.run([x, x_, y])
    print("vx, vx_, vy:", vx, vx_, vy)
    assert_almost_equal(vx, vx_)
    assert_almost_equal(vx, vy)
    dy = tf.reshape(tf.range(0, numpy.prod(shape), dtype=tf.float32) * 0.1 - 5.135, shape)
    (dx,) = tf.gradients(ys=[y], xs=[x], grad_ys=[dy])
    vdx, vdy = session.run([dx, dy])
    print("vdx, vdy:", vdx, vdy)
    assert_almost_equal(vdx, vdy)
//  [python]
def lstm_kwargs():
    """
    :return: kwargs for check_lstm_ops. some dummy input
    :rtype: dict[str]
    """
    kwargs = {
        "n_time": 3,
        "n_batch": 2,
        "n_in_dim": 1,
        "n_cells": 2,
        "mask": numpy.array([[1, 1, 0], [1, 0, 0]]).astype("float32").transpose(),
    }
    assert kwargs["mask"].shape == (kwargs["n_time"], kwargs["n_batch"])

    def gen(shape, offset):
        return numpy.sin(numpy.arange(numpy.multiply.reduce(shape)) + offset).reshape(shape).astype("float32")

    kwargs["x"] = gen((kwargs["n_time"], kwargs["n_batch"], kwargs["n_in_dim"]), offset=0.1)
    kwargs["h_0"] = gen((kwargs["n_batch"], kwargs["n_cells"]), offset=0.2)
    kwargs["c_0"] = gen((kwargs["n_batch"], kwargs["n_cells"]), offset=0.3)
    kwargs["W_f"] = numpy.ones((kwargs["n_in_dim"], kwargs["n_cells"] * 4), dtype="float32")
    kwargs["W_r"] = numpy.ones((kwargs["n_cells"], kwargs["n_cells"] * 4), dtype="float32")
    kwargs["b"] = -numpy.ones((kwargs["n_cells"] * 4,), dtype="float32")
    return kwargs
//  [python]
def lstm_kwargs():
    """
    :return: kwargs for check_lstm_ops. some dummy input
    :rtype: dict[str]
    """
    kwargs = {
        "n_time": 3,
        "n_batch": 2,
        "n_in_dim": 1,
        "n_cells": 2,
        "mask": numpy.array([[1, 1, 0], [1, 0, 0]]).astype("float32").transpose(),
    }
    assert kwargs["mask"].shape == (kwargs["n_time"], kwargs["n_batch"])

    def gen(shape, offset):
        return numpy.sin(numpy.arange(numpy.prod(shape)) + offset).reshape(shape).astype("float32")

    kwargs["x"] = gen((kwargs["n_time"], kwargs["n_batch"], kwargs["n_in_dim"]), offset=0.1)
    kwargs["h_0"] = gen((kwargs["n_batch"], kwargs["n_cells"]), offset=0.2)
    kwargs["c_0"] = gen((kwargs["n_batch"], kwargs["n_cells"]), offset=0.3)
    kwargs["W_f"] = numpy.ones((kwargs["n_in_dim"], kwargs["n_cells"] * 4), dtype="float32")
    kwargs["W_r"] = numpy.ones((kwargs["n_cells"], kwargs["n_cells"] * 4), dtype="float32")
    kwargs["b"] = -numpy.ones((kwargs["n_cells"] * 4,), dtype="float32")
    return kwargs
//  [python]
def test_tensor_array_strided_slice_grad_grad():
    shape = (3, 2, 2)
    from tensorflow.python.ops.gen_array_ops import strided_slice_grad

    x = tf.reshape(tf.range(0, n.prod(shape), dtype=tf.float32), shape)
    x_ = tf.TensorArray(dtype=tf.float32, size=shape[0], element_shape=shape[1:])
    for t in range(shape[0]):
        x_ = x_.write(index=t, value=x[t])
    x__ = x_.stack()
    y = strided_slice_grad(
        shape=tf.convert_to_tensor(shape),
        begin=tf.constant([0]),
        end=tf.constant([0], dtype=tf.int32),
        end_mask=1,
        strides=tf.constant([1]),
        dy=x__,
    )
    y.set_shape(x.get_shape())
    vx, vx__, vy = session.run([x, x__, y])
    print("vx, vx__, vy:", vx, vx__, vy)
    assert_almost_equal(vx, vx__)
    assert_almost_equal(vx, vy)
    dy = tf.reshape(tf.range(0, n.prod(shape), dtype=tf.float32) * 0.1 - 5.135, shape)
    (dx,) = tf.gradients(ys=[y], xs=[x], grad_ys=[dy])
    vdx, vdy = session.run([dx, dy])
    print("vdx, vdy:", vdx, vdy)
    assert_almost_equal(vdx, vdy)
//  [python]
def test_tensor_array_strided_slice_grad_grad():
    shape = (3, 2, 2)
    from tensorflow.python.ops.gen_array_ops import strided_slice_grad

    x = tf.reshape(tf.range(0, numpy.prod(shape), dtype=tf.float32), shape)
    x_ = tf.TensorArray(dtype=tf.float32, size=shape[0], element_shape=shape[1:])
    for t in range(shape[0]):
        x_ = x_.write(index=t, value=x[t])
    x__ = x_.stack()
    y = strided_slice_grad(
        shape=tf.convert_to_tensor(shape),
        begin=tf.constant([0]),
        end=tf.constant([0], dtype=tf.int32),
        end_mask=1,
        strides=tf.constant([1]),
        dy=x__,
    )
    y.set_shape(x.get_shape())
    vx, vx__, vy = session.run([x, x__, y])
    print("vx, vx__, vy:", vx, vx__, vy)
    assert_almost_equal(vx, vx__)
    assert_almost_equal(vx, vy)
    dy = tf.reshape(tf.range(0, numpy.prod(shape), dtype=tf.float32) * 0.1 - 5.135, shape)
    (dx,) = tf.gradients(ys=[y], xs=[x], grad_ys=[dy])
    vdx, vdy = session.run([dx, dy])
    print("vdx, vdy:", vdx, vdy)
    assert_almost_equal(vdx, vdy)
//  [python]
def opt_val(self, f: np.ndarray, y: np.ndarray, m: ComparisonGP, sqrt_nu: np.ndarray) -> float:
        """
        computes the acquisition function value by sampling

        :param f: latent function samples of the posterior
        :param y: observations from the latent functio (latent function values corrupted with noise)
        :param m: the model which posterior is used
        :param sqrt_nu: noise std for the observations
        :return: Sum of variances at the input
        """
        liks = np.zeros(f.shape[1])
        for i in range(f.shape[1]):  # Loop through each member being the batch winner (lower value better)
            mi = [k for k in range(f.shape[1]) if k is not i]  # select all indices but the batch winner
            prs = np.exp(np.sum(np.log(phi((f[:, mi] - y[:, i, None]) / sqrt_nu[None, mi])), axis=1))
            prs2 = prs**2
            liks[i] = (
                np.mean(prs2, axis=0) - np.mean(prs, axis=0) ** 2
            )  # Variance of p(y_i \leq y_j \forall i \neq j) weighted by p(y_i \leq y_j \forall i \neq j)
        return np.sum(liks)