jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def test_shape(self):
        # test shape of return value depending on size parameter
        f = stats.norm.pdf
        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        u = np.sqrt(f(0))

        gen1 = ratio_uniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        gen2 = ratio_uniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        gen3 = ratio_uniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        r1, r2, r3 = gen1(3), gen2((3,)), gen3((3, 1))
        assert_equal(r1, r2)
        assert_equal(r2, r3.flatten())
        assert_equal(r1.shape, (3,))
        assert_equal(r3.shape, (3, 1))

        gen4 = ratio_uniforms(f, umax=u, vmin=-v, vmax=v, random_state=12)
        gen5 = ratio_uniforms(f, umax=u, vmin=-v, vmax=v, random_state=12)
        r4, r5 = gen4(size=(3, 3, 3)), gen5(size=27)
        assert_equal(r4.flatten(), r5)
        assert_equal(r4.shape, (3, 3, 3))

        gen6 = ratio_uniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        gen7 = ratio_uniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        gen8 = ratio_uniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        r6, r7, r8 = gen6(), gen7(1), gen8((1,))
        assert_equal(r6, r7)
        assert_equal(r7, r8)
//  [python]
def test_shape(self):
        # test shape of return value depending on size parameter
        f = stats.norm.pdf
        v = np.sqrt(f(np.sqrt(2))) * np.sqrt(2)
        u = np.sqrt(f(0))

        gen1 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        gen2 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        gen3 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        r1, r2, r3 = gen1.rvs(3), gen2.rvs((3,)), gen3.rvs((3, 1))
        assert_equal(r1, r2)
        assert_equal(r2, r3.flatten())
        assert_equal(r1.shape, (3,))
        assert_equal(r3.shape, (3, 1))

        gen4 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12)
        gen5 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=12)
        r4, r5 = gen4.rvs(size=(3, 3, 3)), gen5.rvs(size=27)
        assert_equal(r4.flatten(), r5)
        assert_equal(r4.shape, (3, 3, 3))

        gen6 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        gen7 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        gen8 = RatioUniforms(f, umax=u, vmin=-v, vmax=v, random_state=1234)
        r6, r7, r8 = gen6.rvs(), gen7.rvs(1), gen8.rvs((1,))
        assert_equal(r6, r7)
        assert_equal(r7, r8)
//  [python]
def test_betai(self):
        np.random.seed(12345)
        for i in range(10):
            a = np.random.rand() * 5.
            b = np.random.rand() * 200.
            assert_equal(stats.betai(a, b, 0.), 0.)
            assert_equal(stats.betai(a, b, 1.), 1.)
            assert_equal(stats.mstats.betai(a, b, 0.), 0.)
            assert_equal(stats.mstats.betai(a, b, 1.), 1.)
            x = np.random.rand()
            assert_almost_equal(stats.betai(a, b, x),
                                stats.mstats.betai(a, b, x), decimal=13)
//  [python]
def test_betai(self):
        np.random.seed(12345)
        for i in range(10):
            a = np.random.rand() * 5.
            b = np.random.rand() * 200.
            assert_equal(special.betainc(a, b, 0.), 0.)
            assert_equal(special.betainc(a, b, 1.), 1.)
            assert_equal(stats.mstats.betai(a, b, 0.), 0.)
            assert_equal(stats.mstats.betai(a, b, 1.), 1.)
            x = np.random.rand()
            assert_almost_equal(special.betainc(a, b, x),
                                stats.mstats.betai(a, b, x), decimal=13)
//  [python]
def _cdf(self, x, a, b):
        return s.betainc(a, b, x/(1.+x))
//  [python]
def _cdf(self, x, a, b):
        return special.betainc(a, b, x/(1.+x))
//  [python]
def attest_ind(a, b, dim=None):
    """ Return the t-test statistics on arrays a and b over the dim axis.
    Returns both the t statistic as well as the p-value
    """
#    dim = a.ndim - 1 if dim is None else dim
    x1, x2 = ma.mean(a, dim), ma.mean(b, dim)
    v1, v2 = ma.var(a, dim), ma.var(b, dim)
    n1, n2 = (a.shape[dim], b.shape[dim]) if dim is not None else (a.size, b.size)
    df = float(n1+n2-2)
    svar = ((n1-1)*v1+(n2-1)*v2) / df
    t = (x1-x2)/ma.sqrt(svar*(1.0/n1 + 1.0/n2))
    if t.ndim == 0:
        return (t, scipy.stats.betai(0.5*df,0.5,df/(df+t**2)) if t is not ma.masked and df/(df+t**2) <= 1.0 else ma.masked)
    else:
        prob = [scipy.stats.betai(0.5*df,0.5,df/(df+tsq)) if tsq is not ma.masked and df/(df+tsq) <= 1.0 else ma.masked  for tsq in t*t]
        return t, prob
//  [python]
def attest_ind(a, b, dim=None):
    """ Return the t-test statistics on arrays a and b over the dim axis.
    Returns both the t statistic as well as the p-value
    """
#    dim = a.ndim - 1 if dim is None else dim
    x1, x2 = ma.mean(a, dim), ma.mean(b, dim)
    v1, v2 = ma.var(a, dim), ma.var(b, dim)
    n1, n2 = (a.shape[dim], b.shape[dim]) if dim is not None else (a.size, b.size)
    df = float(n1+n2-2)
    svar = ((n1-1)*v1+(n2-1)*v2) / df
    t = (x1-x2)/ma.sqrt(svar*(1.0/n1 + 1.0/n2))
    if t.ndim == 0:
        return (t, scipy.special.betainc(0.5*df,0.5,df/(df+t**2)) if t is not ma.masked and df/(df+t**2) <= 1.0 else ma.masked)
    else:
        prob = [scipy.special.betainc(0.5*df,0.5,df/(df+tsq)) if tsq is not ma.masked and df/(df+tsq) <= 1.0 else ma.masked  for tsq in t*t]
        return t, prob
//  [python]
def _cdf(self, x, n, p):
        k = floor(x)
        return s.betainc(n, k+1, p)
//  [python]
def _cdf(self, x, n, p):
        k = floor(x)
        return special.betainc(n, k+1, p)
//  [python]
def check_sample_mean(sm,v,n, popmean):
    """
from stats.stats.ttest_1samp(a, popmean):
Calculates the t-obtained for the independent samples T-test on ONE group
of scores a, given a population mean.

Returns: t-value, two-tailed prob
"""
##    a = asarray(a)
##    x = np.mean(a)
##    v = np.var(a, ddof=1)
##    n = len(a)
    df = n-1
    svar = ((n-1)*v) / float(df)    #looks redundant
    t = (sm-popmean)/np.sqrt(svar*(1.0/n))
    prob = stats.betai(0.5*df,0.5,df/(df+t*t))

    #return t,prob
    assert prob>0.01, 'mean fail, t,prob = %f, %f, m,sm=%f,%f' % (t,prob,popmean,sm)
//  [python]
def check_sample_mean(sm,v,n, popmean):
    """
from stats.stats.ttest_1samp(a, popmean):
Calculates the t-obtained for the independent samples T-test on ONE group
of scores a, given a population mean.

Returns: t-value, two-tailed prob
"""
##    a = asarray(a)
##    x = np.mean(a)
##    v = np.var(a, ddof=1)
##    n = len(a)
    df = n-1
    svar = ((n-1)*v) / float(df)    #looks redundant
    t = (sm-popmean)/np.sqrt(svar*(1.0/n))
    prob = stats.special.betainc(0.5*df,0.5,df/(df+t*t))

    #return t,prob
    assert prob>0.01, 'mean fail, t,prob = %f, %f, m,sm=%f,%f' % (t,prob,popmean,sm)
//  [python]
def _betai(a, b, x):
    x = np.asanyarray(x)
    x = ma.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
    return s.betainc(a, b, x)
//  [python]
def _betai(a, b, x):
    x = np.asanyarray(x)
    x = ma.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
    return special.betainc(a, b, x)
//  [python]
def check_sample_mean(sm,v,n, popmean):
    """
from stats.stats.ttest_1samp(a, popmean):
Calculates the t-obtained for the independent samples T-test on ONE group
of scores a, given a population mean.

Returns: t-value, two-tailed prob
"""
##    a = asarray(a)
##    x = np.mean(a)
##    v = np.var(a, ddof=1)
##    n = len(a)
    df = n-1
    svar = ((n-1)*v) / float(df)    # looks redundant
    t = (sm-popmean)/np.sqrt(svar*(1.0/n))
    prob = stats.betai(0.5*df,0.5,df/(df+t*t))

    # return t,prob
    npt.assert_(prob > 0.01, 'mean fail, t,prob = %f, %f, m,sm=%f,%f' % (t,prob,popmean,sm))
//  [python]
def check_sample_mean(sm,v,n, popmean):
    """
from stats.stats.ttest_1samp(a, popmean):
Calculates the t-obtained for the independent samples T-test on ONE group
of scores a, given a population mean.

Returns: t-value, two-tailed prob
"""
##    a = asarray(a)
##    x = np.mean(a)
##    v = np.var(a, ddof=1)
##    n = len(a)
    df = n-1
    svar = ((n-1)*v) / float(df)    # looks redundant
    t = (sm-popmean)/np.sqrt(svar*(1.0/n))
    prob = stats.special.betainc(0.5*df,0.5,df/(df+t*t))

    # return t,prob
    npt.assert_(prob > 0.01, 'mean fail, t,prob = %f, %f, m,sm=%f,%f' % (t,prob,popmean,sm))
//  [python]
def test_betainc(self):
        btinc = s.betainc(1,1,.2)
        assert_almost_equal(btinc,0.2,8)
//  [python]
def test_betainc(self):
        btinc = special.betainc(1,1,.2)
        assert_almost_equal(btinc,0.2,8)
//  [python]
def _betai(a, b, x):
    x = np.asarray(x)
    x = np.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
    return s.betainc(a, b, x)
//  [python]
def _betai(a, b, x):
    x = np.asarray(x)
    x = np.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
    return special.betainc(a, b, x)
//  [python]
def aF_oneway(*args, **kwargs):
    dim = kwargs.get("dim", None)
    arrays = args
    means = [ma.mean(a, dim) for a in arrays]
    vars = [ma.var(a, dim) for a in arrays]
    lens = [ma.sum(ma.array(ma.ones(a.shape), mask=ma.asarray(a).mask), dim) for a in arrays]
    alldata = ma.concatenate(arrays, dim if dim is not None else 0)
    bign =  ma.sum(ma.array(ma.ones(alldata.shape), mask=alldata.mask), dim)
    sstot = ma.sum(alldata ** 2, dim) - (ma.sum(alldata, dim) ** 2) / bign
    ssbn = ma.sum([(ma.sum(a, dim) ** 2) / L for a, L in zip(arrays, lens)], dim)
#    print ma.sum(alldata, dim) ** 2 / bign, ssbn
    ssbn -= ma.sum(alldata, dim) ** 2 / bign
    sswn = sstot - ssbn
    dfbn = dfnum = float(len(args) - 1.0)
    dfwn = bign - len(args) # + 1.0
    F = (ssbn / dfbn) / (sswn / dfwn)
    if F.ndim == 0 and dfwn.ndim == 0:
        return (F,scipy.stats.betai(0.5 * dfwn, 0.5 * dfnum, dfwn/float(dfwn+dfnum*F)) if F is not ma.masked and dfwn/float(dfwn+dfnum*F) <= 1.0 \
                and dfwn/float(dfwn+dfnum*F) >= 0.0 else ma.masked)
    else:
        prob = [scipy.stats.betai(0.5 * dfden, 0.5 * dfnum, dfden/float(dfden+dfnum*f)) if f is not ma.masked and dfden/float(dfden+dfnum*f) <= 1.0 \
            and dfden/float(dfden+dfnum*f) >= 0.0 else ma.masked for dfden, f in zip (dfwn, F)]
        return F, prob
//  [python]
def aF_oneway(*args, **kwargs):
    dim = kwargs.get("dim", None)
    arrays = args
    means = [ma.mean(a, dim) for a in arrays]
    vars = [ma.var(a, dim) for a in arrays]
    lens = [ma.sum(ma.array(ma.ones(a.shape), mask=ma.asarray(a).mask), dim) for a in arrays]
    alldata = ma.concatenate(arrays, dim if dim is not None else 0)
    bign =  ma.sum(ma.array(ma.ones(alldata.shape), mask=alldata.mask), dim)
    sstot = ma.sum(alldata ** 2, dim) - (ma.sum(alldata, dim) ** 2) / bign
    ssbn = ma.sum([(ma.sum(a, dim) ** 2) / L for a, L in zip(arrays, lens)], dim)
#    print ma.sum(alldata, dim) ** 2 / bign, ssbn
    ssbn -= ma.sum(alldata, dim) ** 2 / bign
    sswn = sstot - ssbn
    dfbn = dfnum = float(len(args) - 1.0)
    dfwn = bign - len(args) # + 1.0
    F = (ssbn / dfbn) / (sswn / dfwn)
    if F.ndim == 0 and dfwn.ndim == 0:
        return (F,scipy.special.betainc(0.5 * dfwn, 0.5 * dfnum, dfwn/float(dfwn+dfnum*F)) if F is not ma.masked and dfwn/float(dfwn+dfnum*F) <= 1.0 \
                and dfwn/float(dfwn+dfnum*F) >= 0.0 else ma.masked)
    else:
        prob = [scipy.special.betainc(0.5 * dfden, 0.5 * dfnum, dfden/float(dfden+dfnum*f)) if f is not ma.masked and dfden/float(dfden+dfnum*f) <= 1.0 \
            and dfden/float(dfden+dfnum*f) >= 0.0 else ma.masked for dfden, f in zip (dfwn, F)]
        return F, prob
//  [python]
def test_betaincinv(self):
        y = special.betaincinv(2,4,.5)
        comp = s.betainc(2,4,y)
        assert_almost_equal(comp,.5,5)
//  [python]
def test_betaincinv(self):
        y = special.betaincinv(2,4,.5)
        comp = special.betainc(2,4,y)
        assert_almost_equal(comp,.5,5)
//  [python]
def betai(a, b, x):
    x = np.asanyarray(x)
    x = ma.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
    return s.betainc(a, b, x)
//  [python]
def betai(a, b, x):
    x = np.asanyarray(x)
    x = ma.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
    return special.betainc(a, b, x)
//  [python]
def ttest_1samp(a, popmean, axis=0):
    """
    Calculates the T-test for the mean of ONE group of scores.

    Parameters
    ----------
    a : array_like
        sample observation
    popmean : float or array_like
        expected value in null hypothesis, if array_like than it must have the
        same shape as `a` excluding the axis dimension
    axis : int or None, optional
        Axis along which to compute test. If None, compute over the whole
        array `a`.

    Returns
    -------
    statistic : float or array
        t-statistic
    pvalue : float or array
        two-tailed p-value

    Notes
    -----
    For more details on `ttest_1samp`, see `stats.ttest_1samp`.

    """
    a, axis = _chk_asarray(a, axis)
    if a.size == 0:
        return (np.nan, np.nan)

    x = a.mean(axis=axis)
    v = a.var(axis=axis, ddof=1)
    n = a.count(axis=axis)
    # force df to be an array for masked division not to throw a warning
    df = ma.asanyarray(n - 1.0)
    svar = ((n - 1.0) * v) / df
    with np.errstate(divide='ignore', invalid='ignore'):
        t = (x - popmean) / ma.sqrt(svar / n)
    prob = s.betai(0.5*df, 0.5, df/(df + t*t))

    return Ttest_1sampResult(t, prob)
//  [python]
def ttest_1samp(a, popmean, axis=0):
    """
    Calculates the T-test for the mean of ONE group of scores.

    Parameters
    ----------
    a : array_like
        sample observation
    popmean : float or array_like
        expected value in null hypothesis, if array_like than it must have the
        same shape as `a` excluding the axis dimension
    axis : int or None, optional
        Axis along which to compute test. If None, compute over the whole
        array `a`.

    Returns
    -------
    statistic : float or array
        t-statistic
    pvalue : float or array
        two-tailed p-value

    Notes
    -----
    For more details on `ttest_1samp`, see `stats.ttest_1samp`.

    """
    a, axis = _chk_asarray(a, axis)
    if a.size == 0:
        return (np.nan, np.nan)

    x = a.mean(axis=axis)
    v = a.var(axis=axis, ddof=1)
    n = a.count(axis=axis)
    # force df to be an array for masked division not to throw a warning
    df = ma.asanyarray(n - 1.0)
    svar = ((n - 1.0) * v) / df
    with np.errstate(divide='ignore', invalid='ignore'):
        t = (x - popmean) / ma.sqrt(svar / n)
    prob = special.betainc(0.5*df, 0.5, df/(df + t*t))

    return Ttest_1sampResult(t, prob)
//  [python]
def _logcdf(self, x, n, p):
        k = floor(x)
        k, n, p = np.broadcast_arrays(k, n, p)
        cdf = self._cdf(k, n, p)
        cond = cdf > 0.5
        def f1(k, n, p):
            return np.log1p(-s.betainc(k + 1, n, 1 - p))

        # do calc in place
        logcdf = cdf
        with np.errstate(divide='ignore'):
            logcdf[cond] = f1(k[cond], n[cond], p[cond])
            logcdf[~cond] = np.log(cdf[~cond])
        return logcdf
//  [python]
def _logcdf(self, x, n, p):
        k = floor(x)
        k, n, p = np.broadcast_arrays(k, n, p)
        cdf = self._cdf(k, n, p)
        cond = cdf > 0.5
        def f1(k, n, p):
            return np.log1p(-special.betainc(k + 1, n, 1 - p))

        # do calc in place
        logcdf = cdf
        with np.errstate(divide='ignore'):
            logcdf[cond] = f1(k[cond], n[cond], p[cond])
            logcdf[~cond] = np.log(cdf[~cond])
        return logcdf
//  [python]
def ttest_rel(a, b, axis=0):
    """
    Calculates the T-test on TWO RELATED samples of scores, a and b.

    Parameters
    ----------
    a, b : array_like
        The arrays must have the same shape.
    axis : int or None, optional
        Axis along which to compute test. If None, compute over the whole
        arrays, `a`, and `b`.

    Returns
    -------
    statistic : float or array
        t-statistic
    pvalue : float or array
        two-tailed p-value

    Notes
    -----
    For more details on `ttest_rel`, see `stats.ttest_rel`.

    """
    a, b, axis = _chk2_asarray(a, b, axis)
    if len(a) != len(b):
        raise ValueError('unequal length arrays')

    if a.size == 0 or b.size == 0:
        return Ttest_relResult(np.nan, np.nan)

    n = a.count(axis)
    df = ma.asanyarray(n-1.0)
    d = (a-b).astype('d')
    dm = d.mean(axis)
    v = d.var(axis=axis, ddof=1)
    denom = ma.sqrt(v / n)
    with np.errstate(divide='ignore', invalid='ignore'):
        t = dm / denom

    probs = s.betainc(0.5*df, 0.5, df/(df + t*t)).reshape(t.shape).squeeze()

    return Ttest_relResult(t, probs)
//  [python]
def ttest_rel(a, b, axis=0):
    """
    Calculates the T-test on TWO RELATED samples of scores, a and b.

    Parameters
    ----------
    a, b : array_like
        The arrays must have the same shape.
    axis : int or None, optional
        Axis along which to compute test. If None, compute over the whole
        arrays, `a`, and `b`.

    Returns
    -------
    statistic : float or array
        t-statistic
    pvalue : float or array
        two-tailed p-value

    Notes
    -----
    For more details on `ttest_rel`, see `stats.ttest_rel`.

    """
    a, b, axis = _chk2_asarray(a, b, axis)
    if len(a) != len(b):
        raise ValueError('unequal length arrays')

    if a.size == 0 or b.size == 0:
        return Ttest_relResult(np.nan, np.nan)

    n = a.count(axis)
    df = ma.asanyarray(n-1.0)
    d = (a-b).astype('d')
    dm = d.mean(axis)
    v = d.var(axis=axis, ddof=1)
    denom = ma.sqrt(v / n)
    with np.errstate(divide='ignore', invalid='ignore'):
        t = dm / denom

    probs = special.betainc(0.5*df, 0.5, df/(df + t*t)).reshape(t.shape).squeeze()

    return Ttest_relResult(t, probs)
//  [python]
def MakeCdf(self, steps=101):
        """Returns the CDF of this distribution."""
        xs = [i / (steps - 1.0) for i in range(steps)]
        ps = s.betainc(self.alpha, self.beta, xs)
        cdf = Cdf(xs, ps)
        return cdf
//  [python]
def MakeCdf(self, steps=101):
        """Returns the CDF of this distribution."""
        xs = [i / (steps - 1.0) for i in range(steps)]
        ps = special.betainc(self.alpha, self.beta, xs)
        cdf = Cdf(xs, ps)
        return cdf
//  [python]
def _cdf(self, x, a, b):
        y = (1 + x / np.sqrt(a + b + x ** 2)) * 0.5
        return s.betainc(a, b, y)
//  [python]
def _cdf(self, x, a, b):
        y = (1 + x / np.sqrt(a + b + x ** 2)) * 0.5
        return sc.betainc(a, b, y)
//  [python]
def incomplete_beta_function(alpha: float, beta: float, x: float):
    """
    Compute the incomplete beta function in log space.
    """
    normalization = beta_function(alpha, beta)
    return normalization * LogFloat.from_value(
        scipy.special.beta(alpha, beta, x))
//  [python]
def incomplete_beta_function(alpha: float, beta: float, x: float):
    """
    Compute the incomplete beta function in log space.
    """
    normalization = beta_function(alpha, beta)
    return normalization * LogFloat.from_value(
        scipy.special.betainc(alpha, beta, x))
//  [python]
def _logcdf(self, x, n, p):
        k = floor(x)
        cdf = self._cdf(k, n, p)
        cond = cdf > 0.5

        def f1(k, n, p):
            return np.log1p(-s.betainc(k + 1, n, 1 - p))

        def f2(k, n, p):
            return np.log(cdf)

        with np.errstate(divide='ignore'):
            return _lazywhere(cond, (x, n, p), f=f1, f2=f2)
//  [python]
def _logcdf(self, x, n, p):
        k = floor(x)
        cdf = self._cdf(k, n, p)
        cond = cdf > 0.5

        def f1(k, n, p):
            return np.log1p(-special.betainc(k + 1, n, 1 - p))

        def f2(k, n, p):
            return np.log(cdf)

        with np.errstate(divide='ignore'):
            return _lazywhere(cond, (x, n, p), f=f1, f2=f2)
//  [python]
def betai(a, b, x):
    """
    Returns the incomplete beta function.

    I_x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt)

    where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma
    function of a.

    The standard broadcasting rules apply to a, b, and x.

    Parameters
    ----------
    a : array_like or float > 0

    b : array_like or float > 0

    x : array_like or float
        x will be clipped to be no greater than 1.0 .

    Returns
    -------
    betai : ndarray
        Incomplete beta function.

    """
    x = np.asarray(x)
    x = np.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
    return s.betainc(a, b, x)
//  [python]
def betai(a, b, x):
    """
    Returns the incomplete beta function.

    I_x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt)

    where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma
    function of a.

    The standard broadcasting rules apply to a, b, and x.

    Parameters
    ----------
    a : array_like or float > 0

    b : array_like or float > 0

    x : array_like or float
        x will be clipped to be no greater than 1.0 .

    Returns
    -------
    betai : ndarray
        Incomplete beta function.

    """
    x = np.asarray(x)
    x = np.where(x < 1.0, x, 1.0)  # if x > 1 then return 1.0
    return special.betainc(a, b, x)
//  [python]
def impl(self, a, b, x):
        return s(a, b, x)
//  [python]
def impl(self, a, b, x):
        return scipy.special.betainc(a, b, x)
//  [python]
def MakeCdf(self, steps=101):
        """Returns the CDF of this distribution."""
        xs = [i / (steps - 1.0) for i in range(steps)]
        ps = [s.betainc(self.alpha, self.beta, x) for x in xs]
        cdf = Cdf(xs, ps)
        return cdf
//  [python]
def MakeCdf(self, steps=101):
        """Returns the CDF of this distribution."""
        xs = [i / (steps - 1.0) for i in range(steps)]
        ps = [special.betainc(self.alpha, self.beta, x) for x in xs]
        cdf = Cdf(xs, ps)
        return cdf
//  [python]
def test_betainc():
    a, b, x = pt.scalars("a", "b", "x")
    res = s.betainc(a, b, x)
    test_func = function([a, b, x], res, mode=Mode("py"))
    assert np.isclose(test_func(15, 10, 0.7), s.betainc(15, 10, 0.7))
//  [python]
def test_betainc():
    a, b, x = pt.scalars("a", "b", "x")
    res = betainc(a, b, x)
    test_func = function([a, b, x], res, mode=Mode("py"))
    assert np.isclose(test_func(15, 10, 0.7), sp.betainc(15, 10, 0.7))
//  [python]
def _calc_garbage_smart(V1, V2):
  S = len(V1.total_reads) # S
  evidence = np.nan * np.ones(S)

  for sidx in range(S):
    logP = [-np.log(V1.omega_v[sidx]), -np.log(V2.omega_v[sidx])]
    for V in (V1, V2):
      A, B = V.var_reads[sidx] + 1, V.ref_reads[sidx] + 1
      logP.append(util.log_N_choose_K(V.total_reads[sidx], V.var_reads[sidx]))
      # `betainc` (the beta distribution CDF) can sometimes return exactly
      # zero, depending on the parameters.
      logP.append(np.log(np.maximum(_EPSILON, s.betainc(A, B, V.omega_v[sidx]))))
      logP.append(scipy.special.betaln(A, B)) # Denormalization factor for beta
    evidence[sidx] = np.sum(logP)

  return evidence
//  [python]
def _calc_garbage_smart(V1, V2):
  S = len(V1.total_reads) # S
  evidence = np.nan * np.ones(S)

  for sidx in range(S):
    logP = [-np.log(V1.omega_v[sidx]), -np.log(V2.omega_v[sidx])]
    for V in (V1, V2):
      A, B = V.var_reads[sidx] + 1, V.ref_reads[sidx] + 1
      logP.append(util.log_N_choose_K(V.total_reads[sidx], V.var_reads[sidx]))
      # `betainc` (the beta distribution CDF) can sometimes return exactly
      # zero, depending on the parameters.
      logP.append(np.log(np.maximum(_EPSILON, scipy.special.betainc(A, B, V.omega_v[sidx]))))
      logP.append(scipy.special.betaln(A, B)) # Denormalization factor for beta
    evidence[sidx] = np.sum(logP)

  return evidence
//  [python]
def test_betainc_domain_errors(self, func, args):
        with special.errstate(domain='raise'):
            with pytest.raises(special.SpecialFunctionError, match='domain'):
                s.betainc(*args)
//  [python]
def test_betainc_domain_errors(self, func, args):
        with special.errstate(domain='raise'):
            with pytest.raises(special.SpecialFunctionError, match='domain'):
                special.betainc(*args)
//  [python]
def test_betainc_betaincinv(self, a, b, x, p):
        p1 = s.betainc(a, b, x)
        assert_allclose(p1, p, rtol=1e-15)
        x1 = s.betaincinv(a, b, p)
        assert_allclose(x1, x, rtol=5e-13)
//  [python]
def test_betainc_betaincinv(self, a, b, x, p):
        p1 = special.betainc(a, b, x)
        assert_allclose(p1, p, rtol=1e-15)
        x1 = special.betaincinv(a, b, p)
        assert_allclose(x1, x, rtol=5e-13)
//  [python]
def test_a1_b1(self):
        # betainc(1, 1, x) is x.
        x = np.array([0, 0.25, 1])
        assert_equal(s.betainc(1, 1, x), x)
        assert_equal(s.betaincinv(1, 1, x), x)
        assert_equal(s.betaincc(1, 1, x), 1 - x)
        assert_equal(s.betainccinv(1, 1, x), 1 - x)
//  [python]
def test_a1_b1(self):
        # betainc(1, 1, x) is x.
        x = np.array([0, 0.25, 1])
        assert_equal(special.betainc(1, 1, x), x)
        assert_equal(special.betaincinv(1, 1, x), x)
        assert_equal(special.betaincc(1, 1, x), 1 - x)
        assert_equal(special.betainccinv(1, 1, x), 1 - x)
//  [python]
def __init__(self, M_BH=1e3, M_NS=1.0, gamma=7 / 3, rho_sp=226, Lambda=-1):
        if gamma <= 1:
            raise ValueError("gamma must be greater than 1")
        self.M_BH = M_BH  # Solar mass
        self.M_NS = M_NS  # Solar mass
        self.gamma = gamma  # Slope of DM density profile
        self.rho_sp = rho_sp  # Solar mass/pc^3
        self.r_sp = (
            (3 - self.gamma)
            * (0.2 ** (3.0 - self.gamma))
            * self.M_BH
            / (2 * np.pi * self.rho_sp)
        ) ** (
            1.0 / 3.0
        )  # pc

        self.IDstr_model = f"gamma={gamma:.2f}_rhosp={rho_sp:.1f}"

        self.xi_init = 1 - s(gamma - 1 / 2, 3 / 2, 1 / 2)

        super().__init__(M_BH, M_NS, Lambda)
//  [python]
def __init__(self, M_BH=1e3, M_NS=1.0, gamma=7 / 3, rho_sp=226, Lambda=-1):
        if gamma <= 1:
            raise ValueError("gamma must be greater than 1")
        self.M_BH = M_BH  # Solar mass
        self.M_NS = M_NS  # Solar mass
        self.gamma = gamma  # Slope of DM density profile
        self.rho_sp = rho_sp  # Solar mass/pc^3
        self.r_sp = (
            (3 - self.gamma)
            * (0.2 ** (3.0 - self.gamma))
            * self.M_BH
            / (2 * np.pi * self.rho_sp)
        ) ** (
            1.0 / 3.0
        )  # pc

        self.IDstr_model = f"gamma={gamma:.2f}_rhosp={rho_sp:.1f}"

        self.xi_init = 1 - betainc(gamma - 1 / 2, 3 / 2, 1 / 2)

        super().__init__(M_BH, M_NS, Lambda)
//  [python]
def Betainc(a, b, x):
    """
    Complemented, incomplete gamma op.
    """
    return s.betainc(a, b, x),
//  [python]
def Betainc(a, b, x):
    """
    Complemented, incomplete gamma op.
    """
    return sp.special.betainc(a, b, x),
//  [python]
def corrcoef(mat):
    """Calculate correlation coefficient with p-values

    Calculate correlation coefficients along with p-values.

    Arguments:

        mat (ndarray): 2-D array [p×N] for which the correlation matrix is
            calculated

    Returns:

        (r, p) where r is a p×p matrix with the correlation coefficients,
        obtained with numpy.corrcoef, and p is 

    Attribution:
    
        this code, or an earlier version was posted by user 'jingchao' on
        Stack Overflow at 2014-7-3 at
        http://stackoverflow.com/a/24547964/974555 and is licensed under
        CC BY-SA 3.0.  This notice may not be removed.
    """
    r = numpy.corrcoef(mat)
    rf = r[numpy.triu_indices(r.shape[0], 1)]
    df = mat.shape[1] - 2
    ts = rf * rf * (df / (1 - rf * rf))
    pf = scipy.special.betainc(0.5 * df, 0.5, df / (df + ts))
    p = numpy.zeros(shape=r.shape)
    p[numpy.triu_indices(p.shape[0], 1)] = pf
    p[numpy.tril_indices(p.shape[0], -1)] = pf
    p[numpy.diag_indices(p.shape[0])] = numpy.ones(p.shape[0])
    return (r, p)
//  [python]
def beta_interpolation(start=0, end=1, scale=1, n=10, n_steps=None):
    if n_steps is None:
        n_steps = n
    if n_steps > n:
        n_steps = n
    if scale <= 0:
        scale = 0.0001
    if scale >= 1:
        scale = 0.9999

    alpha = 3 * scale
    beta = 3 - alpha
    x = np.linspace(0,1,n)
    values = s.betainc(alpha,beta,x)*(end-start)+start

    if n_steps is not None:
        return equalize_list(values, n_steps)
    else:
        return values
//  [python]
def beta_interpolation(start=0, end=1, scale=1, n=10, n_steps=None):
    if n_steps is None:
        n_steps = n
    if n_steps > n:
        n_steps = n
    if scale <= 0:
        scale = 0.0001
    if scale >= 1:
        scale = 0.9999

    alpha = 3 * scale
    beta = 3 - alpha
    x = np.linspace(0,1,n)
    values = scipy.special.betainc(alpha,beta,x)*(end-start)+start

    if n_steps is not None:
        return equalize_list(values, n_steps)
    else:
        return values
//  [python]
def cdf_(self, x: jnp.ndarray) -> jnp.ndarray:
        """
        The cumulative Normal probability distribution
        :param x: The input variable (Cx1)
        :return: The cumulative probability of the occurrence of the given variable Cx1
        """
        x = jnp.clip(a=x, a_min=jnp.finfo(float).eps, a_max=1.0)
        return scipy.special.betainc(a=self.alpha, b=self.beta, x=x)
//  [python]
def beta_cdf_warp(X, d, n, *args):
    r"""Warp inputs that are confined to the unit hypercube using the regularized incomplete beta function.
    
    Applies separately to each dimension, designed for use with
    :py:class:`WarpingFunction`.
    
    Assumes that your inputs `X` lie entirely within the unit hypercube [0, 1].
    
    Note that you may experience some issues with constraining and computing
    derivatives at :math:`x=0` when :math:`\alpha < 1` and at :math:`x=1` when
    :math:`\beta < 1`. As a workaround, try mapping your data to not touch the
    boundaries of the unit hypercube.
    
    Parameters
    ----------
    X : array, (`M`,)
        `M` inputs from dimension `d`.
    d : non-negative int
        The index (starting from zero) of the dimension to apply the warping to.
    n : non-negative int
        The derivative order to compute.
    *args : 2N scalars
        The remaining parameters to describe the warping, given as scalars.
        These are given as `alpha_i`, `beta_i` for each of the `D` dimensions.
        Note that these must ALL be provided for each call.
    
    References
    ----------
    .. [1] J. Snoek, K. Swersky, R. Zemel, R. P. Adams, "Input Warping for
       Bayesian Optimization of Non-stationary Functions" ICML (2014)
    """
    X = scipy.asarray(X)
    
    a = args[2 * d]
    b = args[2 * d + 1]
    
    if n == 0:
        return s.betainc(a, b, X)
    elif n == 1:
        # http://functions.wolfram.com/GammaBetaErf/BetaRegularized/20/01/01/
        return (1 - X)**(b - 1) * X**(a - 1) / scipy.special.beta(a, b)
    else:
        # http://functions.wolfram.com/GammaBetaErf/BetaRegularized/20/02/01/
        out = scipy.zeros_like(X)
        for k in range(0, n):
            out += (
                (-1.0)**(n - k) * scipy.special.binom(n - 1, k) *
                fixed_poch(1.0 - b, k) * fixed_poch(1.0 - a, n - k - 1.0) *
                (X / (1.0 - X))**k
            )
        return -(1.0 - X)**(b - 1.0) * X**(a - n) * out / scipy.special.beta(a, b)
//  [python]
def beta_cdf_warp(X, d, n, *args):
    r"""Warp inputs that are confined to the unit hypercube using the regularized incomplete beta function.
    
    Applies separately to each dimension, designed for use with
    :py:class:`WarpingFunction`.
    
    Assumes that your inputs `X` lie entirely within the unit hypercube [0, 1].
    
    Note that you may experience some issues with constraining and computing
    derivatives at :math:`x=0` when :math:`\alpha < 1` and at :math:`x=1` when
    :math:`\beta < 1`. As a workaround, try mapping your data to not touch the
    boundaries of the unit hypercube.
    
    Parameters
    ----------
    X : array, (`M`,)
        `M` inputs from dimension `d`.
    d : non-negative int
        The index (starting from zero) of the dimension to apply the warping to.
    n : non-negative int
        The derivative order to compute.
    *args : 2N scalars
        The remaining parameters to describe the warping, given as scalars.
        These are given as `alpha_i`, `beta_i` for each of the `D` dimensions.
        Note that these must ALL be provided for each call.
    
    References
    ----------
    .. [1] J. Snoek, K. Swersky, R. Zemel, R. P. Adams, "Input Warping for
       Bayesian Optimization of Non-stationary Functions" ICML (2014)
    """
    X = scipy.asarray(X)
    
    a = args[2 * d]
    b = args[2 * d + 1]
    
    if n == 0:
        return scipy.special.betainc(a, b, X)
    elif n == 1:
        # http://functions.wolfram.com/GammaBetaErf/BetaRegularized/20/01/01/
        return (1 - X)**(b - 1) * X**(a - 1) / scipy.special.beta(a, b)
    else:
        # http://functions.wolfram.com/GammaBetaErf/BetaRegularized/20/02/01/
        out = scipy.zeros_like(X)
        for k in range(0, n):
            out += (
                (-1.0)**(n - k) * scipy.special.binom(n - 1, k) *
                fixed_poch(1.0 - b, k) * fixed_poch(1.0 - a, n - k - 1.0) *
                (X / (1.0 - X))**k
            )
        return -(1.0 - X)**(b - 1.0) * X**(a - n) * out / scipy.special.beta(a, b)
//  [python]
def find_beta_params_dynamic(d, u10):
    """ Define auxiliary distribution taking into account
    kinetic energy of a d-dimensional HMC.
    Make exp(-d/2) quantile to be at u=0.1, and 95% quantile at u=0.5. """

    u50 = (u10 + 1) / 2.

    def minfunc(params):
        """ minimization function """
        alpha, beta = params
        q10 = s.betainc(alpha, beta, u10)
        q50 = s.betainc(alpha, beta, u50)
        return (q10 - np.exp(-d / 2))**2 + (q50 - 0.98)**2

    r = scipy.optimize.minimize(minfunc, [1.0, 10.0])
    alpha, beta = r.x
    print("Auxiliary Beta distribution(alpha=%.1f, beta=%.1f)" % (alpha, beta), u10)

    return alpha, beta
//  [python]
def find_beta_params_dynamic(d, u10):
    """ Define auxiliary distribution taking into account
    kinetic energy of a d-dimensional HMC.
    Make exp(-d/2) quantile to be at u=0.1, and 95% quantile at u=0.5. """

    u50 = (u10 + 1) / 2.

    def minfunc(params):
        """ minimization function """
        alpha, beta = params
        q10 = scipy.special.betainc(alpha, beta, u10)
        q50 = scipy.special.betainc(alpha, beta, u50)
        return (q10 - np.exp(-d / 2))**2 + (q50 - 0.98)**2

    r = scipy.optimize.minimize(minfunc, [1.0, 10.0])
    alpha, beta = r.x
    print("Auxiliary Beta distribution(alpha=%.1f, beta=%.1f)" % (alpha, beta), u10)

    return alpha, beta
//  [python]
def compute_analytic_prob_many(K, C, alpha, S, threshold=0.01):
  # prob_lt[i,j] = probability that component `i` of Dirichlet (parameterized
  # by `alpha_i`) will have value <= `mean` in every Dirichlet sample, if we
  # take `S_j` (independent) samples from that Dirichlet
  prob_lt = np.full((len(C), len(S)), np.nan)
  for cidx, c in enumerate(C):
    for sidx, s in enumerate(S):
      prob_lt[cidx,sidx] = s.betai(c*alpha, (K - c)*alpha, threshold)**s

  return prob_lt
//  [python]
def compute_analytic_prob_many(K, C, alpha, S, threshold=0.01):
  # prob_lt[i,j] = probability that component `i` of Dirichlet (parameterized
  # by `alpha_i`) will have value <= `mean` in every Dirichlet sample, if we
  # take `S_j` (independent) samples from that Dirichlet
  prob_lt = np.full((len(C), len(S)), np.nan)
  for cidx, c in enumerate(C):
    for sidx, s in enumerate(S):
      prob_lt[cidx,sidx] = scipy.special.betainc(c*alpha, (K - c)*alpha, threshold)**s

  return prob_lt
//  [python]
def modify_Lgrad(self, L, grad):
        u = (L - self.Lmin) / (self.L90 - self.Lmin)
        if u <= 0:
            logp = -np.inf
            u = 0.0
            dlogp_du = 1.0
            # print("L <= Lmin", L, self.Lmin)
        elif u > 1:
            u = 1.0
            p = 1.0
            logp = 0.0
            # print("L > L90", L, L90)
            return logp, 0 * grad
        else:
            # p = self.rv.cdf(u)
            p = scipy.special.betainc(self.alpha, self.beta, u)
            logp = np.log(p)
            B = p * self.C
            dlogp_du = u**(self.alpha - 1) * (1 - u)**(self.beta - 1) / B

        # convert gradient to flattened space
        tgrad = grad * dlogp_du * self.du_dL

        return logp, tgrad
//  [python]
def get_privunit_densities(d, gamma, p):
  """Compute the constants that the conditional density is proportional to.

  The conditional density of z (i.e., the output of the privunit) given x (i.e.,
  the input to the privunit) is proportional to c1 if the inner product between
  x and z is more than gamma and is proportional to c2 otherwise.

  Args:
    d: The number of dimensions.
    gamma: The best gamma.
    p : The probability with which an unit vector is sampled from the shaded
    spherical cap associated with the input (see the original paper).

  Returns:
    c1: The factor that the conditional density of z given x is proportional to
    if the inner product between x and z is more than gamma.
    c2: The factor that the conditional density of z given x is proportional to
    if the inner product between x and z is less than gamma.
  """
  c1 = 2 * p / (s.betainc((d - 1) / 2, 1 / 2, (1 - gamma**2)))
  c2 = 2 * (1 - p) / (2 - s.betainc((d - 1) / 2, 1 / 2, (1 - gamma**2)))
  return c1, c2
//  [python]
def get_privunit_densities(d, gamma, p):
  """Compute the constants that the conditional density is proportional to.

  The conditional density of z (i.e., the output of the privunit) given x (i.e.,
  the input to the privunit) is proportional to c1 if the inner product between
  x and z is more than gamma and is proportional to c2 otherwise.

  Args:
    d: The number of dimensions.
    gamma: The best gamma.
    p : The probability with which an unit vector is sampled from the shaded
    spherical cap associated with the input (see the original paper).

  Returns:
    c1: The factor that the conditional density of z given x is proportional to
    if the inner product between x and z is more than gamma.
    c2: The factor that the conditional density of z given x is proportional to
    if the inner product between x and z is less than gamma.
  """
  c1 = 2 * p / (sc.betainc((d - 1) / 2, 1 / 2, (1 - gamma**2)))
  c2 = 2 * (1 - p) / (2 - sc.betainc((d - 1) / 2, 1 / 2, (1 - gamma**2)))
  return c1, c2
//  [python]
def integral_func(phi, th1, n):
    """ Used in computing the continuous hypersphere cap intersection below. """
    return np.sin(phi)**(n-2) * scipy.special.betainc( (n-2)/2 , 1/2, 1-( (np.tan(th1))/(np.tan(phi)) )**2 )
//  [python]
def getm(d, gamma, p):
  """Get the parameter m (eq (15) in the paper) in the privunit mechanism."""
  alpha = (d - 1) / 2
  tau = (1 + gamma) / 2
  if d > 1000:
    # For large d, Stirling's formula is used to approximate eq (15).
    m = (d - 2) / (d - 1) * (1 - gamma**2)**alpha / (
        2 * np.sqrt(np.pi * (d - 3) / 2)) * (
            p / (1 - s.betainc(alpha, alpha, tau)) -
            (1 - p) / s.betainc(alpha, alpha, tau))
  else:
    # For small d, eq (15) is used directly
    m = ((1 - gamma**2)**alpha) * (
        (p / (s.betainc(alpha, alpha, 1) - s.betainc(alpha, alpha, tau))) -
        ((1 - p) / s.betainc(alpha, alpha, tau))) / (
            (2**(d - 2)) * (d - 1) * s.beta(alpha, alpha))
  return m
//  [python]
def getm(d, gamma, p):
  """Get the parameter m (eq (15) in the paper) in the privunit mechanism."""
  alpha = (d - 1) / 2
  tau = (1 + gamma) / 2
  if d > 1000:
    # For large d, Stirling's formula is used to approximate eq (15).
    m = (d - 2) / (d - 1) * (1 - gamma**2)**alpha / (
        2 * np.sqrt(np.pi * (d - 3) / 2)) * (
            p / (1 - sc.betainc(alpha, alpha, tau)) -
            (1 - p) / sc.betainc(alpha, alpha, tau))
  else:
    # For small d, eq (15) is used directly
    m = ((1 - gamma**2)**alpha) * (
        (p / (sc.betainc(alpha, alpha, 1) - sc.betainc(alpha, alpha, tau))) -
        ((1 - p) / sc.betainc(alpha, alpha, tau))) / (
            (2**(d - 2)) * (d - 1) * sc.beta(alpha, alpha))
  return m
//  [python]
def compute_analytic_prob_single(K):
  log_alpha_range = np.linspace(-5, 5, 11)
  alpha = 10**log_alpha_range
  #S = np.array([1] + list(np.linspace(10, 100, steps - 1)))
  S = np.array([1, 3, 10, 30, 100])

  mean = alpha / (K*alpha)
  # Prob for single sample. Relies on the beta being the marginal for a
  # Dirichlet component.
  prob_lt_ss = scipy.special.betainc(
    alpha,
    (K-1)*alpha,
    mean,
  )
  # prob_lt[i,j] = probability that component `i` of Dirichlet (parameterized
  # by `alpha_i`) will have value <= `mean` in every Dirichlet sample, if we
  # take `S_j` (independent) samples from that Dirichlet
  S_rows = np.dot(np.ones(len(log_alpha_range))[:,None], S[None,:])
  prob_cols = np.dot(prob_lt_ss[:,None], np.ones(len(S))[None,:])
  assert S_rows.shape == prob_cols.shape
  prob_lt = prob_cols**S_rows
  #prob_lt = np.hstack((alpha[:,None], (K-1)*alpha[:,None], prob_lt))
  return (alpha, S, prob_lt)
//  [python]
def betainc(a, b, x): return s.betainc(a, b, x).astype(x.dtype)
//  [python]
def betainc(a, b, x): return scipy.special.betainc(a, b, x).astype(x.dtype)
//  [python]
def testBetaincSanity(self):
    # This operation is only supported for float32 and float64.
    for dtype in self.numeric_types & {np.float32, np.float64}:
      # Sanity check a few identities:
      # - betainc(a, b, 0) == 0
      # - betainc(a, b, 1) == 1
      # - betainc(a, 1, x) == x ** a
      # Compare against the implementation in SciPy.
      a = np.array([.3, .4, .2, .2], dtype=dtype)
      b = np.array([1., 1., .4, .4], dtype=dtype)
      x = np.array([.3, .4, .0, .1], dtype=dtype)
      expected = s.betainc(a, b, x)
      self._testTernary(
          math_ops.betainc, a, b, x, expected, rtol=5e-6, atol=6e-6)
//  [python]
def testBetaincSanity(self):
    # This operation is only supported for float32 and float64.
    for dtype in self.numeric_types & {np.float32, np.float64}:
      # Sanity check a few identities:
      # - betainc(a, b, 0) == 0
      # - betainc(a, b, 1) == 1
      # - betainc(a, 1, x) == x ** a
      # Compare against the implementation in SciPy.
      a = np.array([.3, .4, .2, .2], dtype=dtype)
      b = np.array([1., 1., .4, .4], dtype=dtype)
      x = np.array([.3, .4, .0, .1], dtype=dtype)
      expected = sps.betainc(a, b, x)
      self._testTernary(
          math_ops.betainc, a, b, x, expected, rtol=5e-6, atol=6e-6)
//  [python]
def MakeCdf(self, steps=101):
        """Returns the CDF of this distribution."""
        xs = [i / (steps - 1.0) for i in xrange(steps)]
        ps = [scipy.special.betai(self.alpha, self.beta, x) for x in xs]
        cdf = Cdf(xs, ps)
        return cdf
//  [python]
def MakeCdf(self, steps=101):
        """Returns the CDF of this distribution."""
        xs = [i / (steps - 1.0) for i in xrange(steps)]
        ps = [scipy.special.betainc(self.alpha, self.beta, x) for x in xs]
        cdf = Cdf(xs, ps)
        return cdf
//  [python]
def cdf(self, x):
        """
        Cumulative distribution function.

        .. note:: Requires SciPy.

        Parameters
        ----------
        x : array_like
            Evaluation points in [0, 1].

        Returns
        -------
        cdf : array_like
            Probability that ``X <= x``.
        """
        from scipy.special import betainc  # pylint: disable=import-outside-toplevel

        sq_x = x * x
        return np.where(
            sq_x < 1.0, betainc(self.m / 2.0, self.n / 2.0, sq_x), np.ones_like(x)
        )
//  [python]
def testBetainc(self, sigma, rtol, atol):
    # This operation is only supported for float32 and float64.
    for dtype in self.numeric_types & {np.float32, np.float64}:
      # Randomly generate a, b, x in the numerical domain of betainc.
      # Compare against the implementation in SciPy.
      a = np.abs(np.random.randn(10, 10) * sigma).astype(dtype)  # in (0, infty)
      b = np.abs(np.random.randn(10, 10) * sigma).astype(dtype)  # in (0, infty)
      x = np.random.rand(10, 10).astype(dtype)  # in (0, 1)
      expected = s.betainc(a, b, x, dtype=dtype)
      self._testTernary(
          math_ops.betainc, a, b, x, expected, rtol=rtol, atol=atol)
//  [python]
def testBetainc(self, sigma, rtol, atol):
    # This operation is only supported for float32 and float64.
    for dtype in self.numeric_types & {np.float32, np.float64}:
      # Randomly generate a, b, x in the numerical domain of betainc.
      # Compare against the implementation in SciPy.
      a = np.abs(np.random.randn(10, 10) * sigma).astype(dtype)  # in (0, infty)
      b = np.abs(np.random.randn(10, 10) * sigma).astype(dtype)  # in (0, infty)
      x = np.random.rand(10, 10).astype(dtype)  # in (0, 1)
      expected = sps.betainc(a, b, x, dtype=dtype)
      self._testTernary(
          math_ops.betainc, a, b, x, expected, rtol=rtol, atol=atol)
//  [python]
def mean_truncated_beta_distribution(alpha):
  """Expectation of a truncated beta(alpha, alpha) distribution in [1/2, 1]."""
  return 1. - scipy.special.betai(alpha + 1, alpha, .5)
//  [python]
def mean_truncated_beta_distribution(alpha):
  """Expectation of a truncated beta(alpha, alpha) distribution in [1/2, 1]."""
  return 1. - scipy.special.betainc(alpha + 1, alpha, .5)
//  [python]
def _get_p_value(self) -> None:
        self.p_value = s.betainc(self.diff_df / 2, 0.5, self.x)
//  [python]
def _get_p_value(self) -> None:
        self.p_value = sc.betainc(self.diff_df / 2, 0.5, self.x)
//  [python]
def integral_separate_clusters(phi1, V1, V2, sidx, midx, logsub):
  logP = binom_logpmf_scalar(
    V1.var_reads[sidx],
    V1.total_reads[sidx],
    V1.omega_v[sidx]*phi1
  )
  lower = _make_lower(phi1, midx)
  upper = _make_upper(phi1, midx)

  A = V2.var_reads[sidx] + 1
  B = V2.ref_reads[sidx] + 1
  betainc_upper = s.betainc(A, B, V2.omega_v[sidx] * upper)
  betainc_lower = s.betainc(A, B, V2.omega_v[sidx] * lower)
  if np.isclose(betainc_upper, betainc_lower):
    return 0
  logP += np.log(betainc_upper - betainc_lower)
  logP -= logsub

  return np.exp(logP)
//  [python]
def integral_separate_clusters(phi1, V1, V2, sidx, midx, logsub):
  logP = binom_logpmf_scalar(
    V1.var_reads[sidx],
    V1.total_reads[sidx],
    V1.omega_v[sidx]*phi1
  )
  lower = _make_lower(phi1, midx)
  upper = _make_upper(phi1, midx)

  A = V2.var_reads[sidx] + 1
  B = V2.ref_reads[sidx] + 1
  betainc_upper = scipy.special.betainc(A, B, V2.omega_v[sidx] * upper)
  betainc_lower = scipy.special.betainc(A, B, V2.omega_v[sidx] * lower)
  if np.isclose(betainc_upper, betainc_lower):
    return 0
  logP += np.log(betainc_upper - betainc_lower)
  logP -= logsub

  return np.exp(logP)
//  [python]
def __init__(self, K=20, alpha_min=1, alpha_max=100, alpha_spacing=0.01):
        self.alphas = np.arange(alpha_min, alpha_max + alpha_spacing, alpha_spacing)
        self.beta_cdfs = []
        self.bs = np.linspace(0, 1, 1000)
        for alph in self.alphas:
            self.beta_cdfs.append(s.betainc(alph, K-1, self.bs))
        self.beta_cdfs = np.array(self.beta_cdfs)
        self.beta_cdfs_derivative = np.diff(self.beta_cdfs, axis=0) / alpha_spacing
        self.K = K
//  [python]
def __init__(self, K=20, alpha_min=1, alpha_max=100, alpha_spacing=0.01):
        self.alphas = np.arange(alpha_min, alpha_max + alpha_spacing, alpha_spacing)
        self.beta_cdfs = []
        self.bs = np.linspace(0, 1, 1000)
        for alph in self.alphas:
            self.beta_cdfs.append(scipy.special.betainc(alph, K-1, self.bs))
        self.beta_cdfs = np.array(self.beta_cdfs)
        self.beta_cdfs_derivative = np.diff(self.beta_cdfs, axis=0) / alpha_spacing
        self.K = K