jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def make_ea(self, ea_partition=None):
        self._make_shared_1e()
        if self._made_shared_2e is False and ea_partition != 'mp':
            self._make_shared_2e()
            self._made_shared_2e = True

        cput0 = (logger.process_clock(), logger.perf_counter())
        log = logger.Logger(self.stdout, self.verbose)

        t1,t2,eris = self.t1, self.t2, self.eris
        kconserv = self.kconserv

        nkpts, nocc, nvir = t1.shape
        self._fimd.create_dataset('vovv', (nkpts,nkpts,nkpts,nvir,nocc,nvir,nvir), t1.dtype.char)
        self._fimd.create_dataset('vvvo', (nkpts,nkpts,nkpts,nvir,nvir,nvir,nocc), t1.dtype.char)
        self._fimd.create_dataset('vvvv', (nkpts,nkpts,nkpts,nvir,nvir,nvir,nvir), t1.dtype.char)

        # 3 or 4 virtuals
        self.Wvovv = imd.Wvovv(t1,t2,eris,kconserv, self._fimd['vovv'])
        if ea_partition == 'mp' and n.all(t1 == 0):
            self.Wvvvo = imd.Wvvvo(t1,t2,eris,kconserv, self._fimd['vvvo'])
        else:
            self.Wvvvv = imd.Wvvvv(t1,t2,eris,kconserv, self._fimd['vvvv'])
            self.Wvvvo = imd.Wvvvo(t1,t2,eris,kconserv,self.Wvvvv, self._fimd['vvvo'])
        self.made_ea_imds = True
        log.timer('EOM-CCSD EA intermediates', *cput0)
//  [python]
def make_ea(self, ea_partition=None):
        self._make_shared_1e()
        if self._made_shared_2e is False and ea_partition != 'mp':
            self._make_shared_2e()
            self._made_shared_2e = True

        cput0 = (logger.process_clock(), logger.perf_counter())
        log = logger.Logger(self.stdout, self.verbose)

        t1,t2,eris = self.t1, self.t2, self.eris
        kconserv = self.kconserv

        nkpts, nocc, nvir = t1.shape
        self._fimd.create_dataset('vovv', (nkpts,nkpts,nkpts,nvir,nocc,nvir,nvir), t1.dtype.char)
        self._fimd.create_dataset('vvvo', (nkpts,nkpts,nkpts,nvir,nvir,nvir,nocc), t1.dtype.char)
        self._fimd.create_dataset('vvvv', (nkpts,nkpts,nkpts,nvir,nvir,nvir,nvir), t1.dtype.char)

        # 3 or 4 virtuals
        self.Wvovv = imd.Wvovv(t1,t2,eris,kconserv, self._fimd['vovv'])
        if ea_partition == 'mp' and numpy.all(t1 == 0):
            self.Wvvvo = imd.Wvvvo(t1,t2,eris,kconserv, self._fimd['vvvo'])
        else:
            self.Wvvvv = imd.Wvvvv(t1,t2,eris,kconserv, self._fimd['vvvv'])
            self.Wvvvo = imd.Wvvvo(t1,t2,eris,kconserv,self.Wvvvv, self._fimd['vvvo'])
        self.made_ea_imds = True
        log.timer('EOM-CCSD EA intermediates', *cput0)
//  [python]
def test_low_bounds():
    """Test a binary threshold with a low bound"""

    numpy.random.seed(0)
    image = numpy.random.uniform(size=(20, 20))
    image[(image > 0.4) & (image < 0.6)] = 0.5
    expected = image > 0.7
    workspace, module = make_workspace(image)
    module.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL
    module.global_operation.value = centrosome.threshold.TM_OTSU
    module.threshold_range.min = 0.7
    module.run(workspace)
    output = workspace.image_set.get_image(OUTPUT_IMAGE_NAME)
    assert n.all(output.pixel_data == expected)
//  [python]
def test_low_bounds():
    """Test a binary threshold with a low bound"""

    numpy.random.seed(0)
    image = numpy.random.uniform(size=(20, 20))
    image[(image > 0.4) & (image < 0.6)] = 0.5
    expected = image > 0.7
    workspace, module = make_workspace(image)
    module.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL
    module.global_operation.value = centrosome.threshold.TM_OTSU
    module.threshold_range.min = 0.7
    module.run(workspace)
    output = workspace.image_set.get_image(OUTPUT_IMAGE_NAME)
    assert numpy.all(output.pixel_data == expected)
//  [python]
def test_high_bounds():
    """Test a binary threshold with a high bound"""

    numpy.random.seed(0)
    image = numpy.random.uniform(size=(40, 40))
    expected = image > 0.1
    workspace, module = make_workspace(image)
    module.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL
    module.global_operation.value = centrosome.threshold.TM_OTSU
    module.threshold_range.max = 0.1
    module.run(workspace)
    output = workspace.image_set.get_image(OUTPUT_IMAGE_NAME)
    assert n.all(output.pixel_data == expected)
//  [python]
def test_high_bounds():
    """Test a binary threshold with a high bound"""

    numpy.random.seed(0)
    image = numpy.random.uniform(size=(40, 40))
    expected = image > 0.1
    workspace, module = make_workspace(image)
    module.threshold_scope.value = cellprofiler.modules.threshold.TS_GLOBAL
    module.global_operation.value = centrosome.threshold.TM_OTSU
    module.threshold_range.max = 0.1
    module.run(workspace)
    output = workspace.image_set.get_image(OUTPUT_IMAGE_NAME)
    assert numpy.all(output.pixel_data == expected)
//  [python]
def all(a):
    return n.all(a)
//  [python]
def all(a):
    return numpy.all(a)
//  [python]
def calc_cpk(L:float, H:float, data:np.ndarray) -> tuple:
    '''return mean, sdev and Cpk of given data series, 
    discarding np.nan values'''
    if data.size == 0 or np.all(np.isnan(data)):
        return np.nan, np.nan, np.nan
    
    sdev = np.nanstd(data)
    mean = np.nanmean(data)
    
    if np.isnan(L) or np.isnan(H):
        return mean, sdev, np.nan
    
    T = H - L
    if sdev == 0:
        Cpk = np.inf
    else:
        U = (H + L)/2
        CP = T / (6 * sdev)
        # Ca = (mean - U) / (T/2)
        Cpk = CP - abs(mean - U)/(3 * sdev)
    return mean, sdev, Cpk
//  [python]
def is_equal(self, spktrain):
        """
        Return True if the SpikeTrain object is equal to one other SpikeTrain, i.e
        if they have same time parameters and same spikes_times

        Inputs:
            spktrain - A SpikeTrain object

        See also:
            time_parameters()
        """
        test = (self.time_parameters() == spktrain.time_parameters())
        return n.all(self.spike_times == spktrain.spike_times) and test
//  [python]
def is_equal(self, spktrain):
        """
        Return True if the SpikeTrain object is equal to one other SpikeTrain, i.e
        if they have same time parameters and same spikes_times

        Inputs:
            spktrain - A SpikeTrain object

        See also:
            time_parameters()
        """
        test = (self.time_parameters() == spktrain.time_parameters())
        return numpy.all(self.spike_times == spktrain.spike_times) and test
//  [python]
def test_threshold_otsu_full_mask():
    numpy.random.seed(73)

    data = numpy.random.rand(10, 10)

    mask = numpy.zeros_like(data, dtype=bool)

    workspace, module = make_workspace(data, mask=mask)

    image = workspace.image_set.get_image(INPUT_IMAGE_NAME)

    module.threshold_scope.value = cellprofiler.modules.threshold.TS_ADAPTIVE

    module.global_operation.value = centrosome.threshold.TM_OTSU

    module.two_class_otsu.value = cellprofiler.modules.threshold.O_TWO_CLASS

    module.adaptive_window_size.value = 3

    t_local, t_global, _, _, _ = module.get_threshold(image, workspace)

    t_local_expected = numpy.zeros_like(data)

    t_global_expected = 0.0

    numpy.testing.assert_array_equal(t_local, t_local_expected)

    assert n.all(t_global == t_global_expected)

    assert n.all(t_local == t_local_expected)
//  [python]
def test_threshold_otsu_full_mask():
    numpy.random.seed(73)

    data = numpy.random.rand(10, 10)

    mask = numpy.zeros_like(data, dtype=bool)

    workspace, module = make_workspace(data, mask=mask)

    image = workspace.image_set.get_image(INPUT_IMAGE_NAME)

    module.threshold_scope.value = cellprofiler.modules.threshold.TS_ADAPTIVE

    module.global_operation.value = centrosome.threshold.TM_OTSU

    module.two_class_otsu.value = cellprofiler.modules.threshold.O_TWO_CLASS

    module.adaptive_window_size.value = 3

    t_local, t_global, _, _, _ = module.get_threshold(image, workspace)

    t_local_expected = numpy.zeros_like(data)

    t_global_expected = 0.0

    numpy.testing.assert_array_equal(t_local, t_local_expected)

    assert numpy.all(t_global == t_global_expected)

    assert numpy.all(t_local == t_local_expected)
//  [python]
def set_weight(self, weight):
        """Set weight of each instance.

        Parameters
        ----------
        weight : list, numpy array or None
            Weight to be set for each data point.
        """
        if weight is not None and n.all(weight == 1):
            weight = None
        self.weight = weight
        if self.handle is not None and weight is not None:
            weight = list_to_1d_numpy(weight, name='weight')
            self.set_field('weight', weight)
//  [python]
def set_weight(self, weight):
        """Set weight of each instance.

        Parameters
        ----------
        weight : list, numpy array or None
            Weight to be set for each data point.
        """
        if weight is not None and np.all(weight == 1):
            weight = None
        self.weight = weight
        if self.handle is not None and weight is not None:
            weight = list_to_1d_numpy(weight, name='weight')
            self.set_field('weight', weight)
//  [python]
def test_main(self):
        with base.dygraph.guard(base.CPUPlace()):
            acc = paddle.metric.Accuracy(topk=self.topk, name=self.name)
            for _ in range(10):
                label, pred = self.random_pred_label()
                label_var = paddle.to_tensor(label)
                pred_var = paddle.to_tensor(pred)
                state = to_list(acc.compute(pred_var, label_var))
                acc.update(*[s.numpy() for s in state])
                res_m = acc.accumulate()
                res_f = accuracy(pred, label, self.topk)
                assert np.all(
                    np.isclose(
                        np.array(res_m, dtype='float64'),
                        np.array(res_f, dtype='float64'),
                        rtol=1e-3,
                    )
                ), f"Accuracy precision error: {res_m} != {res_f}"
                acc.reset()
                assert np.sum(acc.total) == 0
                assert np.sum(acc.count) == 0
//  [python]
def scale_quadrature(quad_func, order, lower, upper, **kwargs):
    """
    Scale quadrature rule designed for unit interval to an arbitrary interval.

    Args:
        quad_func (Callable):
            Function that creates quadrature abscissas and weights on the unit
            interval.
        order (int):
            The quadrature order passed to the quadrature function.
        lower (float):
            The new lower limit for the quadrature function.
        upper (float):
            The new upper limit for the quadrature function.
        kwargs (Any):
            Extra keyword arguments passed to `quad_func`.

    Returns:
        Same as ``quad_func(order, **kwargs)`` except scaled to a new interval.


    Examples:
        >>> def my_quad(order):
        ...     return (numpy.linspace(0, 1, order+1)[numpy.newaxis],
        ...             1./numpy.full(order+1, order+2))
        >>> my_quad(2)
        (array([[0. , 0.5, 1. ]]), array([0.25, 0.25, 0.25]))
        >>> scale_quadrature(my_quad, 2, lower=0, upper=2)
        (array([[0., 1., 2.]]), array([0.5, 0.5, 0.5]))
        >>> scale_quadrature(my_quad, 2, lower=-0.5, upper=0.5)
        (array([[-0.5,  0. ,  0.5]]), array([0.25, 0.25, 0.25]))

    """
    abscissas, weights = quad_func(order=order, **kwargs)
    assert n.all(abscissas >= 0) and n.all(abscissas <= 1)
    # assert numpy.sum(weights) <= 1 + 1e-10
    assert n.sum(weights > 0)
    weights = weights * (upper - lower)
    abscissas = (abscissas.T * (upper - lower) + lower).T
    return abscissas, weights
//  [python]
def scale_quadrature(quad_func, order, lower, upper, **kwargs):
    """
    Scale quadrature rule designed for unit interval to an arbitrary interval.

    Args:
        quad_func (Callable):
            Function that creates quadrature abscissas and weights on the unit
            interval.
        order (int):
            The quadrature order passed to the quadrature function.
        lower (float):
            The new lower limit for the quadrature function.
        upper (float):
            The new upper limit for the quadrature function.
        kwargs (Any):
            Extra keyword arguments passed to `quad_func`.

    Returns:
        Same as ``quad_func(order, **kwargs)`` except scaled to a new interval.


    Examples:
        >>> def my_quad(order):
        ...     return (numpy.linspace(0, 1, order+1)[numpy.newaxis],
        ...             1./numpy.full(order+1, order+2))
        >>> my_quad(2)
        (array([[0. , 0.5, 1. ]]), array([0.25, 0.25, 0.25]))
        >>> scale_quadrature(my_quad, 2, lower=0, upper=2)
        (array([[0., 1., 2.]]), array([0.5, 0.5, 0.5]))
        >>> scale_quadrature(my_quad, 2, lower=-0.5, upper=0.5)
        (array([[-0.5,  0. ,  0.5]]), array([0.25, 0.25, 0.25]))

    """
    abscissas, weights = quad_func(order=order, **kwargs)
    assert numpy.all(abscissas >= 0) and numpy.all(abscissas <= 1)
    # assert numpy.sum(weights) <= 1 + 1e-10
    assert numpy.sum(weights > 0)
    weights = weights * (upper - lower)
    abscissas = (abscissas.T * (upper - lower) + lower).T
    return abscissas, weights
//  [python]
if sys.version_info[0] > 2:
    basestring = str
    unicode = lambda x: str(x, 'ascii')

if __name__ == "__main__":
    # Show images specified on command line or all images in current directory
    from glob import glob
    from matplotlib import pyplot
    files = sys.argv[1:] if len(sys.argv) > 1 else glob('*.p*m')
    for fname in files:
        try:
            pam = NetpbmFile(fname)
            img = pam.asarray(copy=False)
            if False:
                pam.write('_tmp.pgm.out', pam=True)
                img2 = imread('_tmp.pgm.out')
                assert n.all(img == img2)
                imsave('_tmp.pgm.out', img)
                img2 = imread('_tmp.pgm.out')
                assert n.all(img == img2)
            pam.close()
        except ValueError as e:
            print(fname, e)
            continue
        _shape = img.shape
        if img.ndim > 3 or (img.ndim > 2 and img.shape[-1] not in (3, 4)):
            img = img[0]
        cmap = 'gray' if pam.maxval > 1 else 'binary'
        pyplot.imshow(img, cmap, interpolation='nearest')
        pyplot.title("%s %s %s %s" % (fname, unicode(pam.magicnum),
                                      _shape, img.dtype))
        pyplot.show()
//  [python]
if sys.version_info[0] > 2:
    basestring = str
    unicode = lambda x: str(x, 'ascii')

if __name__ == "__main__":
    # Show images specified on command line or all images in current directory
    from glob import glob
    from matplotlib import pyplot
    files = sys.argv[1:] if len(sys.argv) > 1 else glob('*.p*m')
    for fname in files:
        try:
            pam = NetpbmFile(fname)
            img = pam.asarray(copy=False)
            if False:
                pam.write('_tmp.pgm.out', pam=True)
                img2 = imread('_tmp.pgm.out')
                assert numpy.all(img == img2)
                imsave('_tmp.pgm.out', img)
                img2 = imread('_tmp.pgm.out')
                assert numpy.all(img == img2)
            pam.close()
        except ValueError as e:
            print(fname, e)
            continue
        _shape = img.shape
        if img.ndim > 3 or (img.ndim > 2 and img.shape[-1] not in (3, 4)):
            img = img[0]
        cmap = 'gray' if pam.maxval > 1 else 'binary'
        pyplot.imshow(img, cmap, interpolation='nearest')
        pyplot.title("%s %s %s %s" % (fname, unicode(pam.magicnum),
                                      _shape, img.dtype))
        pyplot.show()
//  [python]
def test_main(self):
        paddle.enable_static()

        main_prog = base.Program()
        startup_prog = base.Program()
        paddle.seed(1024)
        with base.program_guard(main_prog, startup_prog):
            pred = paddle.static.data(
                name='pred', shape=[None, self.class_num], dtype='float32'
            )
            label = paddle.static.data(
                name='label', shape=[None, 1], dtype='int64'
            )
            acc = paddle.metric.Accuracy(topk=self.topk, name=self.name)
            state = acc.compute(pred, label)

        exe = base.Executor(base.CPUPlace())
        compiled_main_prog = base.CompiledProgram(main_prog)

        for _ in range(10):
            label, pred = self.random_pred_label()
            state_ret = exe.run(
                compiled_main_prog,
                feed={'pred': pred, 'label': label},
                fetch_list=[s.name for s in to_list(state)],
                return_numpy=True,
            )
            acc.update(*state_ret)
            res_m = acc.accumulate()
            res_f = accuracy(pred, label, self.topk)
            assert np.all(
                np.isclose(np.array(res_m), np.array(res_f), rtol=1e-3)
            ), f"Accuracy precision error: {res_m} != {res_f}"
            acc.reset()
            assert np.sum(acc.total) == 0
            assert np.sum(acc.count) == 0

        paddle.disable_static()
//  [python]
def checkFeasibility(self, prime):
        # type: (np._ArrayLike) -> bool
        ''' check for a given parameter vector, e.g. a starting point, if it is within the LMI
        constraints '''

        print("Checking feasibility of a priori parameters...")
        replace = dict()
        idable_params = sorted(list(set(self.idf.model.identified_params).difference(self.delete_cols)))
        syms = self.idf.model.param_syms[idable_params]
        for i in range(len(syms)):
            p = syms[i]
            replace[p] = prime[idable_params][i]

        feasible = True
        for l in self.LMIs:
            const_inst = l.subs(replace).rhs
            if const_inst.shape[0] > 1:
                if not n.all(la.eig(np.asarray(const_inst).astype(float))[0] > 0):
                    # matrix needs to be positive definite
                    print("Constraint {} does not hold true for CAD params".format(l))
                    feasible = False
            else:
                if not l.subs(replace).rhs[0] > 0:
                    # single values > 0
                    print("Constraint {} does not hold true for CAD params".format(l))
                    feasible = False
        return feasible
//  [python]
def checkFeasibility(self, prime):
        # type: (np._ArrayLike) -> bool
        ''' check for a given parameter vector, e.g. a starting point, if it is within the LMI
        constraints '''

        print("Checking feasibility of a priori parameters...")
        replace = dict()
        idable_params = sorted(list(set(self.idf.model.identified_params).difference(self.delete_cols)))
        syms = self.idf.model.param_syms[idable_params]
        for i in range(len(syms)):
            p = syms[i]
            replace[p] = prime[idable_params][i]

        feasible = True
        for l in self.LMIs:
            const_inst = l.subs(replace).rhs
            if const_inst.shape[0] > 1:
                if not np.all(la.eig(np.asarray(const_inst).astype(float))[0] > 0):
                    # matrix needs to be positive definite
                    print("Constraint {} does not hold true for CAD params".format(l))
                    feasible = False
            else:
                if not l.subs(replace).rhs[0] > 0:
                    # single values > 0
                    print("Constraint {} does not hold true for CAD params".format(l))
                    feasible = False
        return feasible
//  [python]
def test_items(self):
        data = np.random.random((10, 11))
        v = Variable(["x", "y"], data)
        # test slicing
        assert_identical(v, v[:])
        assert_identical(v, v[...])
        assert_identical(Variable(["y"], data[0]), v[0])
        assert_identical(Variable(["x"], data[:, 0]), v[:, 0])
        assert_identical(Variable(["x", "y"], data[:3, :2]), v[:3, :2])
        # test array indexing
        x = Variable(["x"], np.arange(10))
        y = Variable(["y"], np.arange(11))
        assert_identical(v, v[x.values])
        assert_identical(v, v[x])
        assert_identical(v[:3], v[x < 3])
        assert_identical(v[:, 3:], v[:, y >= 3])
        assert_identical(v[:3, 3:], v[x < 3, y >= 3])
        assert_identical(v[:3, :2], v[x[:3], y[:2]])
        assert_identical(v[:3, :2], v[range(3), range(2)])
        # test iteration
        for n, item in enumerate(v):
            assert_identical(Variable(["y"], data[n]), item)
        with pytest.raises(TypeError, match=r"iteration over a 0-d"):
            iter(Variable([], 0))
        # test setting
        v.values[:] = 0
        assert np.alltrue(v.values == 0)
        # test orthogonal setting
        v[range(10), range(11)] = 1
        assert_array_equal(v.values, np.ones((10, 11)))
//  [python]
def test_items(self):
        data = np.random.random((10, 11))
        v = Variable(["x", "y"], data)
        # test slicing
        assert_identical(v, v[:])
        assert_identical(v, v[...])
        assert_identical(Variable(["y"], data[0]), v[0])
        assert_identical(Variable(["x"], data[:, 0]), v[:, 0])
        assert_identical(Variable(["x", "y"], data[:3, :2]), v[:3, :2])
        # test array indexing
        x = Variable(["x"], np.arange(10))
        y = Variable(["y"], np.arange(11))
        assert_identical(v, v[x.values])
        assert_identical(v, v[x])
        assert_identical(v[:3], v[x < 3])
        assert_identical(v[:, 3:], v[:, y >= 3])
        assert_identical(v[:3, 3:], v[x < 3, y >= 3])
        assert_identical(v[:3, :2], v[x[:3], y[:2]])
        assert_identical(v[:3, :2], v[range(3), range(2)])
        # test iteration
        for n, item in enumerate(v):
            assert_identical(Variable(["y"], data[n]), item)
        with pytest.raises(TypeError, match=r"iteration over a 0-d"):
            iter(Variable([], 0))
        # test setting
        v.values[:] = 0
        assert np.all(v.values == 0)
        # test orthogonal setting
        v[range(10), range(11)] = 1
        assert_array_equal(v.values, np.ones((10, 11)))
//  [python]
def regularize_steps(steps):
    out = numpy.array(steps)

    if isinstance(steps, dict) or not issubclass(out.dtype.type, numpy.integer):
        raise TypeError(
            "'files' argument's steps must be an iterable of integer offsets or start-stop pairs."
        )

    if len(out.shape) == 1:
        if len(out) == 0 or not numpy.alltrue(out[1:] >= out[:-1]):
            raise ValueError(
                "if 'files' argument's steps are (one-dimensional) offsets, they must be non-empty and monotonically increasing"
            )

    elif len(out.shape) == 2:
        if not (out.shape[1] == 2 and all(out[:, 1] >= out[:, 0])):
            raise ValueError(
                "if 'files' argument's steps are (two-dimensional) start-stop pairs, all stops must be greater than or equal to their corresponding starts"
            )

    else:
        raise TypeError(
            "'files' argument's steps must be an iterable of integer offsets or a list of pairs of integer starts and stops."
        )

    if len(out.shape) == 1:
        out = numpy.stack((out[:-1], out[1:]), axis=1)

    return out.tolist()
//  [python]
def regularize_steps(steps):
    out = numpy.array(steps)

    if isinstance(steps, dict) or not issubclass(out.dtype.type, numpy.integer):
        raise TypeError(
            "'files' argument's steps must be an iterable of integer offsets or start-stop pairs."
        )

    if len(out.shape) == 1:
        if len(out) == 0 or not numpy.all(out[1:] >= out[:-1]):
            raise ValueError(
                "if 'files' argument's steps are (one-dimensional) offsets, they must be non-empty and monotonically increasing"
            )

    elif len(out.shape) == 2:
        if not (out.shape[1] == 2 and all(out[:, 1] >= out[:, 0])):
            raise ValueError(
                "if 'files' argument's steps are (two-dimensional) start-stop pairs, all stops must be greater than or equal to their corresponding starts"
            )

    else:
        raise TypeError(
            "'files' argument's steps must be an iterable of integer offsets or a list of pairs of integer starts and stops."
        )

    if len(out.shape) == 1:
        out = numpy.stack((out[:-1], out[1:]), axis=1)

    return out.tolist()
//  [python]
def fill_diagonal(a, val, wrap=False):
    """Fills the main diagonal of the given array of any dimensionality.

    For an array `a` with ``a.ndim > 2``, the diagonal is the list of
    locations with indices ``a[i, i, ..., i]`` all identical. This function
    modifies the input array in-place, it does not return a value.

    Args:
        a (cupy.ndarray): The array, at least 2-D.
        val (scalar): The value to be written on the diagonal.
            Its type must be compatible with that of the array a.
        wrap (bool): If specified, the diagonal is "wrapped" after N columns.
            This affects only tall matrices.

    Examples
    --------
    >>> a = cupy.zeros((3, 3), int)
    >>> cupy.fill_diagonal(a, 5)
    >>> a
    array([[5, 0, 0],
           [0, 5, 0],
           [0, 0, 5]])

    .. seealso:: :func:`numpy.fill_diagonal`
    """
    # The followings are imported from the original numpy
    if a.ndim < 2:
        raise ValueError('array must be at least 2-d')
    end = None
    if a.ndim == 2:
        step = a.shape[1] + 1
        if not wrap:
            end = a.shape[1] * a.shape[1]
    else:
        if not numpy.alltrue(numpy.diff(a.shape) == 0):
            raise ValueError('All dimensions of input must be of equal length')
        step = 1 + numpy.cumprod(a.shape[:-1]).sum()

    a.flat[:end:step] = val
//  [python]
def fill_diagonal(a, val, wrap=False):
    """Fills the main diagonal of the given array of any dimensionality.

    For an array `a` with ``a.ndim > 2``, the diagonal is the list of
    locations with indices ``a[i, i, ..., i]`` all identical. This function
    modifies the input array in-place, it does not return a value.

    Args:
        a (cupy.ndarray): The array, at least 2-D.
        val (scalar): The value to be written on the diagonal.
            Its type must be compatible with that of the array a.
        wrap (bool): If specified, the diagonal is "wrapped" after N columns.
            This affects only tall matrices.

    Examples
    --------
    >>> a = cupy.zeros((3, 3), int)
    >>> cupy.fill_diagonal(a, 5)
    >>> a
    array([[5, 0, 0],
           [0, 5, 0],
           [0, 0, 5]])

    .. seealso:: :func:`numpy.fill_diagonal`
    """
    # The followings are imported from the original numpy
    if a.ndim < 2:
        raise ValueError('array must be at least 2-d')
    end = None
    if a.ndim == 2:
        step = a.shape[1] + 1
        if not wrap:
            end = a.shape[1] * a.shape[1]
    else:
        if not numpy.all(numpy.diff(a.shape) == 0):
            raise ValueError('All dimensions of input must be of equal length')
        step = 1 + numpy.cumprod(a.shape[:-1]).sum()

    a.flat[:end:step] = val
//  [python]
def inv(self, q_data, max_iterations=100, tollerance=1e-5):
        """
        Inverse Rosenblatt transformation.

        If possible the transformation is done analytically. If not possible,
        transformation is approximated using an algorithm that alternates
        between Newton-Raphson and binary search.

        Args:
            q_data (numpy.ndarray):
                Probabilities to be inverse. If any values are outside ``[0,
                1]``, error will be raised. ``q_data.shape`` must be compatible
                with distribution shape.
            max_iterations (int):
                If approximation is used, this sets the maximum number of
                allowed iterations in the Newton-Raphson algorithm.
            tollerance (float):
                If approximation is used, this set the error tolerance level
                required to define a sample as converged.

        Returns:
            (numpy.ndarray):
                Inverted probability values where
                ``out.shape == q_data.shape``.
        """
        logger = logging.getLogger(__name__)
        check_dependencies(self)
        q_data = numpy.asfarray(q_data)
        assert n.all((q_data >= 0) & (q_data <= 1)), "sanitize your inputs!"
        shape = q_data.shape
        q_data = q_data.reshape(len(self), -1)
        cache = {}
        x_data = numpy.zeros(q_data.shape)
        for idx in self._rotation:
            x_data[idx] = self._get_inv(q_data[idx], idx, cache)

        x_data = x_data.reshape(shape)
        return x_data
//  [python]
def inv(self, q_data, max_iterations=100, tollerance=1e-5):
        """
        Inverse Rosenblatt transformation.

        If possible the transformation is done analytically. If not possible,
        transformation is approximated using an algorithm that alternates
        between Newton-Raphson and binary search.

        Args:
            q_data (numpy.ndarray):
                Probabilities to be inverse. If any values are outside ``[0,
                1]``, error will be raised. ``q_data.shape`` must be compatible
                with distribution shape.
            max_iterations (int):
                If approximation is used, this sets the maximum number of
                allowed iterations in the Newton-Raphson algorithm.
            tollerance (float):
                If approximation is used, this set the error tolerance level
                required to define a sample as converged.

        Returns:
            (numpy.ndarray):
                Inverted probability values where
                ``out.shape == q_data.shape``.
        """
        logger = logging.getLogger(__name__)
        check_dependencies(self)
        q_data = numpy.asfarray(q_data)
        assert numpy.all((q_data >= 0) & (q_data <= 1)), "sanitize your inputs!"
        shape = q_data.shape
        q_data = q_data.reshape(len(self), -1)
        cache = {}
        x_data = numpy.zeros(q_data.shape)
        for idx in self._rotation:
            x_data[idx] = self._get_inv(q_data[idx], idx, cache)

        x_data = x_data.reshape(shape)
        return x_data
//  [python]
def test_bernoulli(input, inplace=False, p=None):
        p_numpy = input.numpy()
        if input.numel() > 0:
            p = p_numpy.mean() if p is None else p
        state = build_generator_state(input.context())
        generator = Generator(state)
        input_origin = np.copy(input.numpy())
        out = F.bernoulli(input, inplace, p, generator)
        if inplace is False and p is None:
            assert np.allclose(input_origin, input.numpy()) is True, \
                "input changed"
        out_numpy = out.numpy()

        assert np.all((out_numpy == 0) | (out_numpy == 1)), "bernoulli output must be 0 or 1"
        if out.numel() > 100:
            assert abs(out_numpy.mean() - p) < 1e-1, \
                "failed to execute bernoulli"
//  [python]
def mom(self, K, allow_approx=True, **kwargs):
        """
        Raw statistical moments.

        Creates non-centralized raw moments from the random variable. If
        analytical options can not be utilized, Monte Carlo integration
        will be used.

        Args:
            K (numpy.ndarray):
                Index of the raw moments. k.shape must be compatible with
                distribution shape.  Sampling scheme when performing Monte
                Carlo
            allow_approx (bool):
                Allow the moments to be calculated using quadrature integration
                if analytical approach fails. Raises error instead if false.
            kwargs (Any):
                Arguments passed to :func:`chaospy.approximate_moment` if
                approximation is used.

        Raises:
            chaospy.UnsupportedFeature:
                If analytical calculation is not possible and `allow_approx` is
                false.

        Returns:
            (numpy.ndarray):
                Shapes are related through the identity
                ``k.shape == dist.shape+k.shape``.
        """
        logger = logging.getLogger(__name__)
        K = numpy.asarray(K, dtype=int)
        assert n.all(K >= 0)
        shape = K.shape
        dim = len(self)

        if dim > 1:
            assert len(self) == shape[0]
            shape = shape[1:]

        size = int(K.size / dim)
        K = K.reshape(dim, size)
        try:
            out = [self._get_mom(kdata) for kdata in K.T]
            logger.debug("%s: moment calculated successfully", str(self))
        except chaospy.UnsupportedFeature:
            if allow_approx:
                logger.info(
                    "%s: has stochastic dependencies; "
                    "Approximating moments with quadrature.",
                    str(self),
                )
                out = [chaospy.approximate_moment(self, kdata) for kdata in K.T]
            else:
                out = [self._get_mom(kdata) for kdata in K.T]
        out = numpy.array(out)
        assert out.size == numpy.prod(shape), (out, shape)
        return out.reshape(shape)
//  [python]
def mom(self, K, allow_approx=True, **kwargs):
        """
        Raw statistical moments.

        Creates non-centralized raw moments from the random variable. If
        analytical options can not be utilized, Monte Carlo integration
        will be used.

        Args:
            K (numpy.ndarray):
                Index of the raw moments. k.shape must be compatible with
                distribution shape.  Sampling scheme when performing Monte
                Carlo
            allow_approx (bool):
                Allow the moments to be calculated using quadrature integration
                if analytical approach fails. Raises error instead if false.
            kwargs (Any):
                Arguments passed to :func:`chaospy.approximate_moment` if
                approximation is used.

        Raises:
            chaospy.UnsupportedFeature:
                If analytical calculation is not possible and `allow_approx` is
                false.

        Returns:
            (numpy.ndarray):
                Shapes are related through the identity
                ``k.shape == dist.shape+k.shape``.
        """
        logger = logging.getLogger(__name__)
        K = numpy.asarray(K, dtype=int)
        assert numpy.all(K >= 0)
        shape = K.shape
        dim = len(self)

        if dim > 1:
            assert len(self) == shape[0]
            shape = shape[1:]

        size = int(K.size / dim)
        K = K.reshape(dim, size)
        try:
            out = [self._get_mom(kdata) for kdata in K.T]
            logger.debug("%s: moment calculated successfully", str(self))
        except chaospy.UnsupportedFeature:
            if allow_approx:
                logger.info(
                    "%s: has stochastic dependencies; "
                    "Approximating moments with quadrature.",
                    str(self),
                )
                out = [chaospy.approximate_moment(self, kdata) for kdata in K.T]
            else:
                out = [self._get_mom(kdata) for kdata in K.T]
        out = numpy.array(out)
        assert out.size == numpy.prod(shape), (out, shape)
        return out.reshape(shape)
//  [python]
def test_bounding_zoom():
    bboxes = geohash.bounding_boxes(precision=1)
    assert len(bboxes) == 32

    zoom_in = geohash.transform(bboxes, precision=3)
    assert len(zoom_in) == 2**10 * 32
    assert n.all(
        n.sort(geohash.transform(zoom_in, precision=1)) == n.sort(
            bboxes))
//  [python]
def test_bounding_zoom():
    bboxes = geohash.bounding_boxes(precision=1)
    assert len(bboxes) == 32

    zoom_in = geohash.transform(bboxes, precision=3)
    assert len(zoom_in) == 2**10 * 32
    assert numpy.all(
        numpy.sort(geohash.transform(zoom_in, precision=1)) == numpy.sort(
            bboxes))
//  [python]
def test_lcth_algorithm_interpolate(self):
        lcthalgo = LowCloudHeightAlgorithm(**self.testinput)
        # originally obtained with np.random.random_integers
        cth = np.array(
              [[ 6.,  3., 10.,  7.,  4.],  # noqa: E201
               [ 6.,  9.,  2.,  6., 10.],  # noqa: E201
               [10.,  7.,  4.,  3.,  7.],  # noqa: E201
               [ 7.,  2.,  5.,  4.,  1.],  # noqa: E201
               [ 7.,  5.,  1.,  4.,  0.]])  # noqa: E201
        cth[cth > 7] = np.nan

        mask = np.array(
              [[ True,  True,  True, False,  True],  # noqa: E201
               [False, False, False, False, False],  # noqa: E201
               [ True,  True,  True,  True,  True],  # noqa: E201
               [False,  True,  True, False,  True],  # noqa: E201
               [False,  True, False,  True,  True]])  # noqa: E201
        result = lcthalgo.interpol_cth(cth, mask)
        self.assertEqual(result.shape, (5, 5))
        self.assertTrue(np.alltrue(np.isnan(result[mask])))
        self.assertGreaterEqual(np.sum(np.isnan(result)), np.sum(mask))
//  [python]
def test_lcth_algorithm_interpolate(self):
        lcthalgo = LowCloudHeightAlgorithm(**self.testinput)
        # originally obtained with np.random.random_integers
        cth = np.array(
              [[ 6.,  3., 10.,  7.,  4.],  # noqa: E201
               [ 6.,  9.,  2.,  6., 10.],  # noqa: E201
               [10.,  7.,  4.,  3.,  7.],  # noqa: E201
               [ 7.,  2.,  5.,  4.,  1.],  # noqa: E201
               [ 7.,  5.,  1.,  4.,  0.]])  # noqa: E201
        cth[cth > 7] = np.nan

        mask = np.array(
              [[ True,  True,  True, False,  True],  # noqa: E201
               [False, False, False, False, False],  # noqa: E201
               [ True,  True,  True,  True,  True],  # noqa: E201
               [False,  True,  True, False,  True],  # noqa: E201
               [False,  True, False,  True,  True]])  # noqa: E201
        result = lcthalgo.interpol_cth(cth, mask)
        self.assertEqual(result.shape, (5, 5))
        self.assertTrue(np.all(np.isnan(result[mask])))
        self.assertGreaterEqual(np.sum(np.isnan(result)), np.sum(mask))
//  [python]
def _single_optimal_block(x: Float64Array) -> tuple[float, float]:
    """
    Compute the optimal window length for a single series

    Parameters
    ----------
    x : ndarray
        The data to use in the optimal window estimation

    Returns
    -------
    stationary : float
        Estimated optimal window length for stationary bootstrap
    circular : float
        Estimated optimal window length for circular bootstrap
    """
    nobs = x.shape[0]
    eps = x - x.mean(0)
    b_max = np.ceil(min(3 * np.sqrt(nobs), nobs / 3))
    kn = max(5, int(np.log10(nobs)))
    m_max = int(np.ceil(np.sqrt(nobs))) + kn
    # Find first collection of kn autocorrelations that are insignificant
    cv = 2 * np.sqrt(np.log10(nobs) / nobs)
    acv = np.zeros(m_max + 1)
    abs_acorr = np.zeros(m_max + 1)
    opt_m: int | None = None
    for i in range(m_max + 1):
        v1 = eps[i + 1 :] @ eps[i + 1 :]
        v2 = eps[: -(i + 1)] @ eps[: -(i + 1)]
        cross_prod = eps[i:] @ eps[: nobs - i]
        acv[i] = cross_prod / nobs
        abs_acorr[i] = np.abs(cross_prod) / np.sqrt(v1 * v2)
        if i >= kn:
            if np.alltrue(abs_acorr[i - kn : i] < cv) and opt_m is None:
                opt_m = i - kn
    m = 2 * max(opt_m, 1) if opt_m is not None else m_max
    m = min(m, m_max)

    g = 0.0
    lr_acv = acv[0]
    for k in range(1, m + 1):
        lam = 1 if k / m <= 1 / 2 else 2 * (1 - k / m)
        g += 2 * lam * k * acv[k]
        lr_acv += 2 * lam * acv[k]
    d_sb = 2 * lr_acv**2
    d_cb = 4 / 3 * lr_acv**2
    b_sb = ((2 * g**2) / d_sb) ** (1 / 3) * nobs ** (1 / 3)
    b_cb = ((2 * g**2) / d_cb) ** (1 / 3) * nobs ** (1 / 3)
    b_sb = min(b_sb, b_max)
    b_cb = min(b_cb, b_max)
    return b_sb, b_cb
//  [python]
def _single_optimal_block(x: Float64Array) -> tuple[float, float]:
    """
    Compute the optimal window length for a single series

    Parameters
    ----------
    x : ndarray
        The data to use in the optimal window estimation

    Returns
    -------
    stationary : float
        Estimated optimal window length for stationary bootstrap
    circular : float
        Estimated optimal window length for circular bootstrap
    """
    nobs = x.shape[0]
    eps = x - x.mean(0)
    b_max = np.ceil(min(3 * np.sqrt(nobs), nobs / 3))
    kn = max(5, int(np.log10(nobs)))
    m_max = int(np.ceil(np.sqrt(nobs))) + kn
    # Find first collection of kn autocorrelations that are insignificant
    cv = 2 * np.sqrt(np.log10(nobs) / nobs)
    acv = np.zeros(m_max + 1)
    abs_acorr = np.zeros(m_max + 1)
    opt_m: int | None = None
    for i in range(m_max + 1):
        v1 = eps[i + 1 :] @ eps[i + 1 :]
        v2 = eps[: -(i + 1)] @ eps[: -(i + 1)]
        cross_prod = eps[i:] @ eps[: nobs - i]
        acv[i] = cross_prod / nobs
        abs_acorr[i] = np.abs(cross_prod) / np.sqrt(v1 * v2)
        if i >= kn:
            if np.all(abs_acorr[i - kn : i] < cv) and opt_m is None:
                opt_m = i - kn
    m = 2 * max(opt_m, 1) if opt_m is not None else m_max
    m = min(m, m_max)

    g = 0.0
    lr_acv = acv[0]
    for k in range(1, m + 1):
        lam = 1 if k / m <= 1 / 2 else 2 * (1 - k / m)
        g += 2 * lam * k * acv[k]
        lr_acv += 2 * lam * acv[k]
    d_sb = 2 * lr_acv**2
    d_cb = 4 / 3 * lr_acv**2
    b_sb = ((2 * g**2) / d_sb) ** (1 / 3) * nobs ** (1 / 3)
    b_cb = ((2 * g**2) / d_cb) ** (1 / 3) * nobs ** (1 / 3)
    b_sb = min(b_sb, b_max)
    b_cb = min(b_cb, b_max)
    return b_sb, b_cb
//  [python]
def test_lcth_algorithm_linreg(self):
        lcthalgo = LowCloudHeightAlgorithm(**self.testinput)
        # originally obtained with np.random.randint
        cth = np.array(
              [[6., 3., 7., 4., 6.],
               [9., 2., 6., 7., 4.],
               [3., 7., 7., 2., 5.],
               [4., 1., 7., 5., 1.],
               [4., 0., 9., 5., 8.]])
        ctt = np.array(
              [[276., 286., 286., 269., 287.],
               [287., 275., 274., 289., 289.],
               [274., 289., 278., 271., 282.],
               [279., 284., 262., 264., 278.],
               [266., 280., 268., 266., 277.]])
        cth[cth > 7] = np.nan
        mask = np.array(
              [[ True, False,  True,  True,  True],  # noqa: E201
               [ True, False,  True, False,  True],  # noqa: E201
               [ True,  True, False,  True, False],  # noqa: E201
               [ True, False,  True, False, False],  # noqa: E201
               [ True, False,  True,  True,  True]])  # noqa: E201
        result = lcthalgo.linreg_cth(cth, mask, ctt)
        self.assertEqual(result.shape, (5, 5))
        self.assertTrue(np.alltrue(np.isnan(result[mask])))
        self.assertEqual(np.sum(np.isnan(result)), np.sum(mask))
//  [python]
def test_lcth_algorithm_linreg(self):
        lcthalgo = LowCloudHeightAlgorithm(**self.testinput)
        # originally obtained with np.random.randint
        cth = np.array(
              [[6., 3., 7., 4., 6.],
               [9., 2., 6., 7., 4.],
               [3., 7., 7., 2., 5.],
               [4., 1., 7., 5., 1.],
               [4., 0., 9., 5., 8.]])
        ctt = np.array(
              [[276., 286., 286., 269., 287.],
               [287., 275., 274., 289., 289.],
               [274., 289., 278., 271., 282.],
               [279., 284., 262., 264., 278.],
               [266., 280., 268., 266., 277.]])
        cth[cth > 7] = np.nan
        mask = np.array(
              [[ True, False,  True,  True,  True],  # noqa: E201
               [ True, False,  True, False,  True],  # noqa: E201
               [ True,  True, False,  True, False],  # noqa: E201
               [ True, False,  True, False, False],  # noqa: E201
               [ True, False,  True,  True,  True]])  # noqa: E201
        result = lcthalgo.linreg_cth(cth, mask, ctt)
        self.assertEqual(result.shape, (5, 5))
        self.assertTrue(np.all(np.isnan(result[mask])))
        self.assertEqual(np.sum(np.isnan(result)), np.sum(mask))
//  [python]
def fit(self, X, y):
        """ train a model """
        assert n.all(n.in1d(y, [0, 1]))
        y_signed = 2 * y - 1
        n_samples = len(y)
        pred = n.zeros(n_samples, dtype='float')
        self.estimators = []

        for iteration in range(self.n_estimators):
            # using AdaLoss -> target = +-1, weights below,
            # result is well-aligned with RF behavior when capacity is zero
            ada_weight = n.exp(- y_signed * pred * self.compute_capacity(iteration))

            _indices = n.random.RandomState(iteration).randint(0, n_samples, size=n_samples)
            boost_weights = n.bincount(_indices, minlength=n_samples) * ada_weight

            tree = DecisionTreeRegressor(max_features='sqrt',
                                         max_depth=None,
                                         random_state=42 * iteration,
                                         max_leaf_nodes=self.max_leaf_nodes)
            tree.fit(X, y_signed, sample_weight=boost_weights)

            pred = self.encounter_contribution(pred, contribution=tree.predict(X), iteration=iteration)
            self.estimators.append(tree)

        return self
//  [python]
def fit(self, X, y):
        """ train a model """
        assert numpy.all(numpy.in1d(y, [0, 1]))
        y_signed = 2 * y - 1
        n_samples = len(y)
        pred = numpy.zeros(n_samples, dtype='float')
        self.estimators = []

        for iteration in range(self.n_estimators):
            # using AdaLoss -> target = +-1, weights below,
            # result is well-aligned with RF behavior when capacity is zero
            ada_weight = numpy.exp(- y_signed * pred * self.compute_capacity(iteration))

            _indices = numpy.random.RandomState(iteration).randint(0, n_samples, size=n_samples)
            boost_weights = numpy.bincount(_indices, minlength=n_samples) * ada_weight

            tree = DecisionTreeRegressor(max_features='sqrt',
                                         max_depth=None,
                                         random_state=42 * iteration,
                                         max_leaf_nodes=self.max_leaf_nodes)
            tree.fit(X, y_signed, sample_weight=boost_weights)

            pred = self.encounter_contribution(pred, contribution=tree.predict(X), iteration=iteration)
            self.estimators.append(tree)

        return self
//  [python]
def infer_shape(self, fgraph, node, i_shapes):
        from aesara.tensor.math import ceil, maximum

        # Note start, stop and step can be float numbers.
        start, stop, step = node.inputs

        def is_constant_value(var, value):
            try:
                v = get_scalar_constant_value(var)
                return n.all(v == value)
            except NotScalarConstantError:
                pass
            return False

        def upcast(var):
            if (
                var.dtype in integer_dtypes
                and
                # We do not want to cast uint64 to int64 as this can
                # loose information. If we upcast uint64 with int64,
                # this give float64. This is safer then checking for
                # uint64 in case we support [u]int128 or other in the
                # future.
                aes.upcast(var.dtype, "int64") == "int64"
            ):
                return cast(var, "int64")
            return var

        if is_constant_value(step, 1):
            if is_constant_value(start, 0):
                return [(cast(stop, "int64"),)]
            else:
                stop = upcast(stop)
                start = upcast(start)
                return [(maximum(cast(stop - start, "int64"), 0),)]
        else:
            stop = upcast(stop)
            start = upcast(start)
            return [
                (
                    maximum(
                        cast(ceil(cast((stop - start), "float64") / step), "int64"), 0
                    ),
                )
            ]