jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def doLogLikelihoodTest(complex_ll, complex_np,
                        simple_ll, simple_np,
                        significance_threshold=0.05):
    """perform log-likelihood test between model1 and model2.
    """

    assert complex_ll >= simple_ll, "log likelihood of complex model smaller than for simple model: %f > %f" % (
        complex_ll, simple_ll)

    chi = 2 * (complex_ll - simple_ll)
    df = complex_np - simple_np

    if df <= 0:
        raise ValueError("difference of degrees of freedom not larger than 0")

    p = scipy.stats.chi2.sf(chi, df)

    l = LogLikelihoodTest()

    l.mComplexLogLikelihood = complex_ll
    l.mSimpleLogLikelihood = simple_ll
    l.mComplexNumParameters = complex_np
    l.mSimpleNumParameters = simple_np
    l.mSignificanceThreshold = significance_threshold
    l.mProbability = p
    l.mChiSquaredValue = chi
    l.mDegreesFreedom = df

    if p < significance_threshold:
        l.mPassed = True
    else:
        l.mPassed = False

    return l
//  [python]
def doPearsonChiSquaredTest(p, sample_size, observed,
                            significance_threshold=0.05):
    """perform a pearson chi squared test.

    Given are p: the probability of the NULL hypothesis, the sample_size
    and the number of observed counts.

    For large sample sizes, this test is a continuous approximation to
    the binomial test.
    """
    e = float(p) * sample_size
    d = float(observed) - e
    chi = d * d / e
    df = 1

    result = ChiSquaredTest()

    result.mProbability = scipy.stats.chisqprob(chi, df)
    result.mDegreesFreedom = df
    result.mChiSquaredValue = chi
    result.mPassed = result.mProbability < significance_threshold
    result.mSignificance = getSignificance(result.mProbability)
    result.mSampleSize = sample_size
    result.mPhi = math.sqrt(result.mChiSquaredValue / result.mSampleSize)
    result.mObserved = observed
    result.mExpected = e
    return result
//  [python]
def doPearsonChiSquaredTest(p, sample_size, observed,
                            significance_threshold=0.05):
    """perform a pearson chi squared test.

    Given are p: the probability of the NULL hypothesis, the sample_size
    and the number of observed counts.

    For large sample sizes, this test is a continuous approximation to
    the binomial test.
    """
    e = float(p) * sample_size
    d = float(observed) - e
    chi = d * d / e
    df = 1

    result = ChiSquaredTest()

    result.mProbability = scipy.stats.chi2.sf(chi, df)
    result.mDegreesFreedom = df
    result.mChiSquaredValue = chi
    result.mPassed = result.mProbability < significance_threshold
    result.mSignificance = getSignificance(result.mProbability)
    result.mSampleSize = sample_size
    result.mPhi = math.sqrt(result.mChiSquaredValue / result.mSampleSize)
    result.mObserved = observed
    result.mExpected = e
    return result
//  [python]
def test_hotelling2():
    # Marginally, Hotelling's T^2(k) with m degrees of freedom
    # in the denominator satisfies
    # (m-k+1)/(mk) T^2 \sim  F_{k,m-k+1}.
    x = np.linspace(0.1,10,100)
    for dfn in range(6, 10):
        h = rft.Hotelling(k=dfn)(x)
        chi = rft.ChiSquared(dfn=dfn)(x)
        assert_almost_equal(h, chi)
        chi2 = scipy.stats.chi2.sf(x, dfn)
        assert_almost_equal(h, chi2)
        # XXX - p appears to be unused
        p = rft.spherical_search(dfn)
        for dfd in [40,50]:
            fac = (dfd-dfn+1.)/(dfd*dfn)
            h = rft.Hotelling(dfd=dfd,k=dfn)(x)
            f = scipy.stats.f.sf(x*fac, dfn, dfd-dfn+1)
            f2 = rft.FStat(dfd=dfd-dfn+1,dfn=dfn)(x*fac)
            assert_almost_equal(f2, f)
            assert_almost_equal(h, f)
//  [python]
def _convert_z_to_p(z):
    return s.chi2.sf(z**2,1)
//  [python]
def _convert_z_to_p(z):
    return ss.chi2.sf(z**2,1)
//  [python]
def doChiSquaredTest(matrix, significance_threshold=0.05):
    """perform chi-squared test on a matrix.
    """
    nrows, ncols = matrix.shape
    if nrows != 2 or ncols != 2:
        raise ValueError(
            "chi-square currently only implemented for 2x2 tables.")

    df = (nrows - 1) * (ncols - 1)

    row_sums = [matrix[x, :].sum() for x in range(nrows)]
    col_sums = [matrix[:, x].sum() for x in range(ncols)]
    sample_size = float(sum(row_sums))

    chi = 0.0
    for x in range(nrows):
        for y in range(ncols):
            expected = row_sums[x] * col_sums[y] / sample_size
            d = matrix[x, y] - expected
            chi += d * d / expected

    result = ChiSquaredTest()

    result.mProbability = scipy.stats.chisqprob(chi, df)
    result.mDegreesFreedom = df
    result.mChiSquaredValue = chi
    result.mPassed = result.mProbability < significance_threshold
    result.mSignificance = getSignificance(result.mProbability)
    result.mSampleSize = sample_size
    result.mPhi = math.sqrt(result.mChiSquaredValue / result.mSampleSize)
    return result
//  [python]
def doChiSquaredTest(matrix, significance_threshold=0.05):
    """perform chi-squared test on a matrix.
    """
    nrows, ncols = matrix.shape
    if nrows != 2 or ncols != 2:
        raise ValueError(
            "chi-square currently only implemented for 2x2 tables.")

    df = (nrows - 1) * (ncols - 1)

    row_sums = [matrix[x, :].sum() for x in range(nrows)]
    col_sums = [matrix[:, x].sum() for x in range(ncols)]
    sample_size = float(sum(row_sums))

    chi = 0.0
    for x in range(nrows):
        for y in range(ncols):
            expected = row_sums[x] * col_sums[y] / sample_size
            d = matrix[x, y] - expected
            chi += d * d / expected

    result = ChiSquaredTest()

    result.mProbability = scipy.stats.chi2.sf(chi, df)
    result.mDegreesFreedom = df
    result.mChiSquaredValue = chi
    result.mPassed = result.mProbability < significance_threshold
    result.mSignificance = getSignificance(result.mProbability)
    result.mSampleSize = sample_size
    result.mPhi = math.sqrt(result.mChiSquaredValue / result.mSampleSize)
    return result
//  [python]
def _conver_chisq_to_p(chisq):
    return s.chisqprob(chisq)
//  [python]
def _conver_chisq_to_p(chisq):
    return ss.chi2.sf(chisq,1)
//  [python]
def p(self):
        # Get the number of PCs (difference in number of parameters).
        return scipy.stats.chi2.sf(
            self.deviance_base - self.deviance_augmented,
            df=self.gene_obj.n_pcs
        )
//  [python]
def selection_coefficient(df_model, mut_type, pvalue=True):
    obs_key = 'OBS_{}'.format(mut_type)
    exp_key = 'EXP_{}'.format(mut_type)
    sel_key = 'SEL_{}'.format(mut_type)

    df_model[sel_key] = (df_model[obs_key] + 1e-16) / (df_model[exp_key] + 1e-16)

    if pvalue:
        pi_key = 'Pi_{}'.format(mut_type)
        pval_key = 'PVAL_{}_SEL'.format(mut_type)
        ll0 = scipy.stats.nbinom.logpmf(df_model[obs_key], df_model.ALPHA, 1 / (1 + df_model.THETA * df_model[pi_key]))
        ll1 = scipy.stats.nbinom.logpmf(df_model[obs_key], df_model.ALPHA, 1 / (1 + df_model.THETA * df_model[pi_key] * df_model[sel_key]))
        df_model[pval_key] = scipy.stats.chi2.sf(-2 * (ll0 - ll1), df=1)
//  [python]
def compare_lr_test(self, restricted):
        '''
        Likelihood ratio test to test whether restricted model is correct

        Parameters
        ----------
        restricted : Result instance
            The restricted model is assumed to be nested in the current model.
            The result instance of the restricted model is required to have two
            attributes, residual sum of squares, `ssr`, residual degrees of
            freedom, `df_resid`.

        Returns
        -------
        lr_stat : float
            likelihood ratio, chisquare distributed with df_diff degrees of
            freedom
        p_value : float
            p-value of the test statistic
        df_diff : int
            degrees of freedom of the restriction, i.e. difference in df between
            models

        Notes
        -----

        .. math:: D=-2\\log\\left(\\frac{\\mathcal{L}_{null}}
           {\\mathcal{L}_{alternative}}\\right)

        where :math:`\mathcal{L}` is the likelihood of the model. With :math:`D`
        distributed as chisquare with df equal to difference in number of
        parameters or equivalently difference in residual degrees of freedom

        TODO: put into separate function, needs tests
        '''
#        See mailing list discussion October 17,
        llf_full = self.llf
        llf_restr = restricted.llf
        df_full = self.df_resid
        df_restr = restricted.df_resid

        lrdf = (df_restr - df_full)
        lrstat = -2*(llf_restr - llf_full)
        lr_pvalue = stats.chi2.sf(lrstat, lrdf)

        return lrstat, lr_pvalue, lrdf
//  [python]
def asymptotic_pv(self, ts : float = None) -> float :
    """Asymptotic p-value corresponding
       to the test-statistic value

    Args:
      ts : an alternate test statistic value. If not `None`,
           the p-value is computed for this one, otherwise
           for the value returned by :meth:`value`.

    Returns:
      the asymptotic p-value
    """
    if ts == None : ts = self.value()
    return scipy.stats.chi2.sf(ts, self.npois())
//  [python]
def test_chi2cdf(self):
        xlist = numpy.linspace(0, 100, 500)
        slist = numpy.arange(1, 41, 1.5)
        for s, x in product(slist, xlist):
            self.assertAlmostEqual(scipy.stats.chi2.cdf(x, s, loc=0, scale=1), chi2cdf(x, s))
//  [python]
def test_chi2cdf(self):
        xlist = numpy.linspace(0, 100, 500)
        slist = numpy.arange(1, 41, 1.5)
        for s, x in product(slist, xlist):
            self.assertAlmostEqual(scipy.stats.chi2.sf(x, s), chi2sf(x, s))
//  [python]
def cl(self) -> float :
    """Return the CL value for the interval
    
    Returns:
      the CL value
    """
    return 1 - scipy.stats.chi2.sf(self.ts_level, 1)
//  [python]
def _distribution_test_pval(cls, x, y):
        '''
        P-value from the likelihood ratio test comparing the distribution of the abundances
        of two taxa (x and y). See docs for explanation of the test.
        '''
        assert len(x) == len(y)
        df = len(x) - 1
        return scipy.stats.chi2.sf(cls._D(x, y), df=df)
//  [python]
def symmetry(self, method="bowker"):
        """
        Test for symmetry of a joint distribution.

        This procedure tests the null hypothesis that the joint
        distribution is symmetric around the main diagonal, that is

        .. math::

        p_{i, j} = p_{j, i}  for all i, j

        Returns
        -------
        A bunch with attributes:

        statistic : float
            chisquare test statistic
        p-value : float
            p-value of the test statistic based on chisquare distribution
        df : int
            degrees of freedom of the chisquare distribution

        Notes
        -----
        The implementation is based on the SAS documentation. R includes
        it in `mcnemar.test` if the table is not 2 by 2.  However a more
        direct generalization of the McNemar test to larger tables is
        provided by the homogeneity test (TableSymmetry.homogeneity).

        The p-value is based on the chi-square distribution which requires
        that the sample size is not very small to be a good approximation
        of the true distribution. For 2x2 contingency tables the exact
        distribution can be obtained with `mcnemar`

        See Also
        --------
        mcnemar
        homogeneity
        """

        if method.lower() != "bowker":
            raise ValueError("method for symmetry testing must be 'bowker'")

        k = self.table.shape[0]
        upp_idx = np.triu_indices(k, 1)

        tril = self.table.T[upp_idx]   # lower triangle in column order
        triu = self.table[upp_idx]     # upper triangle in row order

        statistic = ((tril - triu)**2 / (tril + triu + 1e-20)).sum()
        df = k * (k-1) / 2.
        pvalue = stats.chi2.sf(statistic, df)

        b = _Bunch()
        b.statistic = statistic
        b.pvalue = pvalue
        b.df = df

        return b
//  [python]
def cl(self) :
    """Return the CL value for the contour
    
    Returns:
      the CL value
    """
    return 1 - scipy.stats.chi2.sf(self.ts_level, 2)
//  [python]
def _transition_matrix_symmetry(sequence):
    """Symmetry Test

    If significant, then then transition matrix is considered as asymmetric.

    Based on https://github.com/Frederic-vW/eeg_microstates
    """
    states = np.unique(sequence)
    n_states = len(states)
    n = len(sequence)
    f_ij = np.zeros((n_states, n_states))

    for t in range(n-1):
        i = sequence[t]
        j = sequence[t+1]
        f_ij[states == i, states == j] += 1.0

    T = 0.0
    for i, j in np.ndindex(f_ij.shape):
        if (i != j):
            f = f_ij[i, j] * f_ij[j, i]
            if (f > 0):
                T += (f_ij[i, j] * np.log((2. * f_ij[i, j]) / (f_ij[i, j] + f_ij[j, i])))

    out = {}
    out["Symmetry_t"] = T * 2.0
    out["Symmetry_df"] = n_states*(n_states-1)/2
    out["Symmetry_p"] = scipy.stats.chi2.cdf(out["Symmetry_t"], out["Symmetry_df"], loc=0, scale=1)
    return out
//  [python]
def _transition_matrix_symmetry(sequence):
    """Symmetry Test

    If significant, then then transition matrix is considered as asymmetric.

    Based on https://github.com/Frederic-vW/eeg_microstates
    """
    states = np.unique(sequence)
    n_states = len(states)
    n = len(sequence)
    f_ij = np.zeros((n_states, n_states))

    for t in range(n-1):
        i = sequence[t]
        j = sequence[t+1]
        f_ij[states == i, states == j] += 1.0

    T = 0.0
    for i, j in np.ndindex(f_ij.shape):
        if (i != j):
            f = f_ij[i, j] * f_ij[j, i]
            if (f > 0):
                T += (f_ij[i, j] * np.log((2. * f_ij[i, j]) / (f_ij[i, j] + f_ij[j, i])))

    out = {}
    out["Symmetry_t"] = T * 2.0
    out["Symmetry_df"] = n_states*(n_states-1)/2
    out["Symmetry_p"] = scipy.stats.chi2.sf(out["Symmetry_t"], out["Symmetry_df"], loc=0, scale=1)
    return out
//  [python]
def calculate_mswd_probability(mswd, dof):
    """
    replicates MassSpec's  StatsModule.ProbMSWD

    :param mswd:
    :param dof:
    :return:
    """
    return s.chi2.sf(mswd * dof, dof)
//  [python]
def calculate_mswd_probability(mswd, dof):
    """
    replicates MassSpec's  StatsModule.ProbMSWD

    :param mswd:
    :param dof:
    :return:
    """
    return chi2.sf(mswd * dof, dof)
//  [python]
def process(chrm, ref):
    results_del = pd.DataFrame(columns=['chr', 'start', 'end', 'sum of diflihood', 'del'])
    results_dup = pd.DataFrame(columns=['chr', 'start', 'end', 'sum of diflihood', 'dup'])

    difByChr_half, difByChr_dup = getDifByChr(chrm, ref)
    regions_half = local_max_subarray(difByChr_half, len(difByChr_half.index), 500000)

    regions_dup = local_max_subarray(difByChr_dup, len(difByChr_dup.index), 500000)

    for i in range(0, len(regions_half)):
        likelihood = regions_half[i][0]
        likelihood_chi_square = scipy.stats.chi2.sf(2*likelihood, 1)
        if likelihood_chi_square < 0.05:
            df = pd.DataFrame(
                [[chrm, regions_half[i][1], regions_half[i][2], likelihood, "DEL"]],
                columns=['chr', 'start', 'end', 'sum of diflihood', 'del']
            )
            results_del = results_del.append(df, ignore_index=True)

    for i in range(0, len(regions_dup)):
        likelihood = regions_dup[i][0]
        likelihood_chi_square = scipy.stats.chi2.sf(2*likelihood, 1)
        if likelihood_chi_square < 0.05:
            df = pd.DataFrame(
                [[chrm, regions_dup[i][1], regions_dup[i][2], likelihood, "DUP"]],
                columns=['chr', 'start', 'end', 'sum of diflihood', 'dup']
            )
            results_dup = results_dup.append(df, ignore_index=True)

    return {'results_del': results_del, 'results_dup': results_dup}
//  [python]
def do_ivw_heterogeneity_estimation_on_estimate_vector(self, estimation_vector):
        """
        Provides a heterogeneity estimation p value of an ivw estimation based on an estimation vector.

        :param estimation_vector: estimation vector of MR estimates.
        :return: a p value of heterogeneity.
        """
        if len(self.estimation_data) < 3:
            raise ValueError("Less than three estimates supplied, cannot do cochrans q heterogeneity analysis")

        ivw_estimate = self.do_ivw_estimation_on_estimate_vector(estimation_vector, save_intermediate=False)

        chi_sq_sum = 0.0
        for sub_estimate in estimation_vector:
            chi_sq_sum += (ivw_estimate[0] - sub_estimate[0]) **2 / sub_estimate[1] ** 2

        return scipy.stats.chi2.cdf(chi_sq_sum, len(estimation_vector) - 1)
//  [python]
def do_ivw_heterogeneity_estimation_on_estimate_vector(self, estimation_vector):
        """
        Provides a heterogeneity estimation p value of an ivw estimation based on an estimation vector.

        :param estimation_vector: estimation vector of MR estimates.
        :return: a p value of heterogeneity.
        """
        if len(self.estimation_data) < 3:
            raise ValueError("Less than three estimates supplied, cannot do cochrans q heterogeneity analysis")

        ivw_estimate = self.do_ivw_estimation_on_estimate_vector(estimation_vector, save_intermediate=False)

        chi_sq_sum = 0.0
        for sub_estimate in estimation_vector:
            chi_sq_sum += (ivw_estimate[0] - sub_estimate[0]) **2 / sub_estimate[1] ** 2

        return scipy.stats.chi2.sf(chi_sq_sum, len(estimation_vector) - 1)
//  [python]
def upperLimitsDeltaTS(confidence_level, one_sided=True, degrees_of_freedom=1):
    """

    """
    if not one_sided:
        confidence_level = 0.5*(confidence_level + 1.)
    ts_min = 0 # TS = Test Statistic
    ts_max = 5
    ts_steps = 1000
    x = np.linspace(ts_min, ts_max, int(ts_steps))
    y = (0.5 * scipy.stats.chi2.sf(x, degrees_of_freedom) - (1. - confidence_level))**2
    return x[np.argmin(y)]
//  [python]
def do_smr_estimate(self, exposure_tuple, outcome_tuple):
        """
        Determine SMR test effect and standard error.
        Identifies standard error of the estimate, based on on two variance terms

        :param exposure_data: Exposure estimates which must have the methods get_beta and get_z_score
        :param outcome_data: Outcome estimates which must have the methods get_beta and get_z_score
        :return: tuple of smr beta and smr se of the estimate.
        """

        z_score_exposure = exposure_tuple[0] / exposure_tuple[1]
        z_score_outcome = outcome_tuple[0] / outcome_tuple[1]


        # from SMR paper.
        t_stat = ((z_score_exposure ** 2) * (z_score_outcome ** 2)) \
                 / \
                 ((z_score_exposure ** 2) + (z_score_outcome ** 2))

        # this needs a check,
        # checked it with results from Zhy et al. see validate_SMR_estimates.py
        p_value = scipy.stats.chi2.sf(t_stat, 1)
        z_score = scipy.stats.norm.isf(p_value / 2)

        # also from Zhu et al.
        beta_smr = outcome_tuple[0] / exposure_tuple[0]
        se_smr = abs(beta_smr / z_score)

        return [beta_smr, se_smr, p_value]
//  [python]
def p_fa(
        threshold: npt.ArrayLike,
        N_nc: npt.ArrayLike,
        sigma2: npt.ArrayLike,
        complex: bool = True,
    ) -> npt.NDArray[np.float64]:
        r"""
        Computes the probability of false alarm $P_{FA}$.

        Arguments:
            threshold: The threshold $\gamma'$.
            N_nc: The number of samples $N_{NC}$ to non-coherently integrate.
            sigma2: The noise variance $\sigma^2$.
            complex: Indicates whether the signal is complex.

        Returns:
            The probability of false alarm $P_{FA}$.

        Notes:
            For real signals:

            $$P_{FA} = Q_{\chi_N^2}\left( \frac{\gamma'}{\sigma^2} \right)$$

            For complex signals:

            $$P_{FA} = Q_{\chi_{2N}^2}\left( \frac{\gamma'}{\sigma^2 / 2} \right)$$

        References:
            - Steven Kay, *Fundamentals of Statistical Signal Processing: Detection Theory*,
              Equation 5.2.
        """
        threshold = np.asarray(threshold)
        N_nc = np.asarray(N_nc)
        sigma2 = np.asarray(sigma2)

        if not complex:
            nu = N_nc  # Degrees of freedom
            p_fa = scipy.stats.chi2.sf(threshold / sigma2, nu)
        else:
            nu = 2 * N_nc  # Degrees of freedom
            p_fa = scipy.stats.chi2.sf(threshold / (sigma2 / 2), nu)

        return p_fa
//  [python]
def get_chi2_and_pvalue(ydata, yfit, ndf, sigma=None):
    """
    Gets reduced chi2 and p-value

    Parameters
    ----------
    ydata : np.ndarray
        Data points.
    yfit : np.ndarray
        Fit values corresponding to ydata array.
    sigma : np.ndarray
        Data errors. If sigma is not given, it takes the poisson case:
            sigma = sqrt(ydata)
    ndf : int
        Number of degrees of freedom
        (number of data points - number of parameters).

    Returns
    -------
    chi2 : float
        Reduced chi2 computed as:
            chi2 = [sum(ydata - yfit)**2 / sigma**2] / ndf
    pvalue : float
        Fit p-value.
    """

    if sigma is None:
        sigma = poisson_sigma(ydata)

    chi2   = np.sum(((ydata - yfit) / sigma)**2)
    pvalue = scipy.stats.chi2.cdf(chi2, ndf)

    return chi2 / ndf, pvalue
//  [python]
def get_chi2_and_pvalue(ydata, yfit, ndf, sigma=None):
    """
    Gets reduced chi2 and p-value

    Parameters
    ----------
    ydata : np.ndarray
        Data points.
    yfit : np.ndarray
        Fit values corresponding to ydata array.
    sigma : np.ndarray
        Data errors. If sigma is not given, it takes the poisson case:
            sigma = sqrt(ydata)
    ndf : int
        Number of degrees of freedom
        (number of data points - number of parameters).

    Returns
    -------
    chi2 : float
        Reduced chi2 computed as:
            chi2 = [sum(ydata - yfit)**2 / sigma**2] / ndf
    pvalue : float
        Fit p-value.
    """

    if sigma is None:
        sigma = poisson_sigma(ydata)

    chi2   = np.sum(((ydata - yfit) / sigma)**2)
    pvalue = scipy.stats.chi2.sf(chi2, ndf)

    return chi2 / ndf, pvalue
//  [python]
def lmm(X,y):

    K = X.dot(X.T)

    S, U = np.linalg.eigh(K)
    S=np.real(S)
    U=np.real(U)

    delta = 1.000
    sigma = S + delta * np.identity(S.shape[0])
    sigma_det = np.linalg.det(sigma)
    sigma_inverse = np.linalg.inv(sigma)

    p_values = []

    null_ll = compute_multi(ones, y, U, sigma_det, sigma_inverse)

    for i in range(X.shape[1]):
        X_temp = np.hstack((X[:,i].reshape(-1, 1), ones))
        snp_ll = compute_multi(X_temp, y, U, sigma_det, sigma_inverse)
        # print(snp_ll)
        pvalue = scipy.stats.chi2.sf(2*(snp_ll-null_ll),1.0)
        p_values.append(pvalue)
    
    qqplot(np.asarray(p_values), legend="LMM")
//  [python]
def run_model(X,y, covariates,legend=None):
    p_values = []
    null_ll = compute_ll(covariates, y)

    for i in range(X.shape[1]):
        X_temp = np.hstack((X[:,i].reshape(-1, 1), covariates))
        snp_ll = compute_ll(X_temp,y)
        pvalue = scipy.stats.chi2.sf(2*(snp_ll-null_ll),1.0)
        # neg_log_pvalue = pvalue
        p_values.append(pvalue)

    p_values = np.asarray(p_values)

    # fastlmm_qqplot(np.asarray(p_values), legend=legend)
    return p_values
//  [python]
def _run_categorical(
        data,
        formula,
        formula_restricted,
        family,
        use_t,
        report_categorical_betas
        # ) -> Dict:
    ) -> Generator[dict, None, None]:
        # Regress both models
        y, X = patsy.dmatrices(formula, data, return_type="dataframe", NA_action="drop")
        y = fix_names(y)
        X = fix_names(X)
        est = sm.GLM(y, X, family=family).fit(use_t=use_t)

        y_restricted, X_restricted = patsy.dmatrices(
            formula_restricted, data, return_type="dataframe", NA_action="drop"
        )
        y_restricted = fix_names(y_restricted)
        X_restricted = fix_names(X_restricted)
        est_restricted = sm.GLM(y_restricted, X_restricted, family=family).fit(
            use_t=use_t
        )
        # Check convergence
        if est.converged & est_restricted.converged:
            # Calculate Results
            lrdf = est_restricted.df_resid - est.df_resid
            lrstat = -2 * (est_restricted.llf - est.llf)
            lr_pvalue = scipy.stats.chi2.sf(lrstat, lrdf)
            if report_categorical_betas:
                param_names = set(est.bse.index) - set(est_restricted.bse.index)
                # The restricted model shouldn't have extra terms, unless there is some case we have overlooked
                assert len(set(est_restricted.bse.index) - set(est.bse.index)) == 0
                for param_name in param_names:
                    yield {
                        "Converged": True,
                        "Category": param_name,
                        "Beta": est.params[param_name],
                        "SE": est.bse[param_name],
                        "Beta_pvalue": est.pvalues[param_name],
                        "LRT_pvalue": lr_pvalue,
                        "pvalue": lr_pvalue,
                        "Diff_AIC": est.aic - est_restricted.aic,
                    }
            else:
                # Only return the LRT result
                yield {
                    "Converged": True,
                    "LRT_pvalue": lr_pvalue,
                    "pvalue": lr_pvalue,
                    "Diff_AIC": est.aic - est_restricted.aic,
                }
//  [python]
def simple_gaussian_fit(energies, dx=1, sigma_thr=4, allowed_p_val=1e-20):
    fit_range = [np.percentile(energies, 0.2), np.percentile(energies, 99.8)]

    hist, bins, var = get_hist(energies, range=fit_range, dx=dx)
    guess, bounds = simple_gaussian_guess(hist, bins, gauss_on_uniform)
    fit_range = [guess[0] - sigma_thr * guess[1], guess[0] + sigma_thr * guess[1]]

    energies_fit = energies[(energies > fit_range[0]) & (energies < fit_range[1])]
    pars, errs, cov = fit_unbinned(
        gauss_on_uniform.pdf_ext,
        energies_fit,
        guess=guess,
        bounds=bounds,
    )

    mu, mu_err = pars[0], errs[0]
    fwhm = pars[1] * 2 * np.sqrt(2 * np.log(2))
    fwhm_err = errs[1] * 2 * np.sqrt(2 * np.log(2))

    hist, bins, var = get_hist(energies_fit, range=fit_range, dx=dx)
    gof_pars = pars
    gof_pars[2] *= dx
    chisq, dof = goodness_of_fit(
        hist, bins, None, gauss_on_uniform.pdf_norm, gof_pars, method="Pearson"
    )
    p_val = scipy.stats.chi2.sf(chisq, dof + len(gof_pars))

    if (
        sum(sum(c) if c is not None else 0 for c in cov[2:, :][:, 2:]) == np.inf
        or sum(sum(c) if c is not None else 0 for c in cov[2:, :][:, 2:]) == 0
        or np.isnan(sum(sum(c) if c is not None else 0 for c in cov[2:, :][:, 2:]))
    ):
        log.debug("fit failed, cov estimation failed")
        fit_failed = True
    elif (np.abs(np.array(errs)[2:] / np.array(pars)[2:]) < 1e-7).any() or np.isnan(
        np.array(errs)[2:]
    ).any():
        log.debug("fit failed, parameter error too low")
        fit_failed = True
    elif p_val < allowed_p_val or np.isnan(p_val):
        log.debug("fit failed, parameter error too low")
        fit_failed = True
    else:
        fit_failed = False

    if fit_failed:
        log.debug("Returning values from guess")
        mu = guess[0]
        mu_err = 0
        fwhm = guess[1] * 2 * np.sqrt(2 * np.log(2))
        fwhm_err = 0

    results = {
        "pars": pars,
        "errors": errs,
        "covariance": cov,
        "mu": mu,
        "mu_err": mu_err,
        "fom": fwhm,
        "fom_err": fwhm_err,
        "chisq": chisq / dof,
        "p_val": p_val,
    }
    return results
//  [python]
async def logrank_test(secfxp, d1, d2, n1, n2):
    detot = secfxp(0)  # sum_j d1_j - d_j n1_j / n_j
    vtot = secfxp(0)   # sum_j (d_j n1_j / n_j) (n2_j / n_j) (n_j - d_j) / (n_j - 1)
    maxT = len(d1)
    for j in range(maxT):
        print(f'Progress ... {round(100*(j+1)/maxT)}%', end='\r')
        d_j = d1[j] + d2[j]
        n_j = n1[j] + n2[j]
        a = d_j * n1[j]
        b = n_j * (n_j - 1)
        c = 1/(n_j * b)  # NB: using only one fixed-point division /
        detot += d1[j] - a * b * c
        vtot += a * n2[j] * (n_j - d_j) * c
        await mpc.throttler(0.01, name=f'logrank_test@j={j}')
    chi = await mpc.output(detot**2 / vtot)
    p = scipy.stats.chi2.sf(chi, 1)
    return lifelines.statistics.StatisticalResult(p_value=p, test_statistic=chi)
//  [python]
def chi_squared_qf_weighted(
        subgroup,
        data,
        weighting_attribute,
        effective_sample_size=0,
        min_instances=5,
    ):
        import scipy.stats  # pylint:disable=import-outside-toplevel

        (
            instancesDataset,
            positivesDataset,
            instancesSubgroup,
            positivesSubgroup,
        ) = subgroup.get_base_statistics(data, weighting_attribute)
        if (instancesSubgroup < min_instances) or (
            (instancesDataset - instancesSubgroup) < 5
        ):
            return float("inf")
        if effective_sample_size == 0:
            effective_sample_size = derive_effective_sample_size(
                data[weighting_attribute]
            )
        # p_subgroup = positivesSubgroup / instancesSubgroup
        # p_dataset = positivesDataset / instancesDataset

        negatives_subgroup = instancesSubgroup - positivesSubgroup
        negatives_dataset = instancesDataset - positivesDataset
        positives_complement = positivesDataset - positivesSubgroup
        negatives_complement = negatives_dataset - negatives_subgroup
        val = scipy.stats.chi2_contingency(
            [
                [positivesSubgroup, positives_complement],
                [negatives_subgroup, negatives_complement],
            ],
            correction=True,
        )[0]
        return scipy.stats.chi2.cdf(val * effective_sample_size / instancesDataset, 1)
//  [python]
def chi_squared_qf_weighted(
        subgroup,
        data,
        weighting_attribute,
        effective_sample_size=0,
        min_instances=5,
    ):
        import scipy.stats  # pylint:disable=import-outside-toplevel

        (
            instancesDataset,
            positivesDataset,
            instancesSubgroup,
            positivesSubgroup,
        ) = subgroup.get_base_statistics(data, weighting_attribute)
        if (instancesSubgroup < min_instances) or (
            (instancesDataset - instancesSubgroup) < 5
        ):
            return float("inf")
        if effective_sample_size == 0:
            effective_sample_size = derive_effective_sample_size(
                data[weighting_attribute]
            )
        # p_subgroup = positivesSubgroup / instancesSubgroup
        # p_dataset = positivesDataset / instancesDataset

        negatives_subgroup = instancesSubgroup - positivesSubgroup
        negatives_dataset = instancesDataset - positivesDataset
        positives_complement = positivesDataset - positivesSubgroup
        negatives_complement = negatives_dataset - negatives_subgroup
        val = scipy.stats.chi2_contingency(
            [
                [positivesSubgroup, positives_complement],
                [negatives_subgroup, negatives_complement],
            ],
            correction=True,
        )[0]
        return scipy.stats.chi2.sf(val * effective_sample_size / instancesDataset, 1)
//  [python]
def get_summary(self, alpha = 0.95, precision=3):
        """ Providing the summary of the regression results:
                * standard errors
                * z-score 
                * p-value
        """
        
        # Flattening the coef 
        W_flat = self.weights.flatten()

        # calculating standard error 
        self.std_err  = np.sqrt(self.inv_Hessian.diagonal())/self.std_scale   

        # Confidence Intervals 
        alpha = scipy.stats.norm.ppf((1. + alpha) / 2.)
        lower_ci = np.round( W_flat - alpha * self.std_err, precision)
        upper_ci = np.round( W_flat + alpha * self.std_err, precision)
        z = np.round(W_flat / self.std_err , precision)
        p_values = np.round(2 * scipy.stats.norm.sf(np.abs(z)), precision)
        W = np.round(W_flat, precision)
        std_err = np.round(self.std_err, precision)
        
        # Creating summary
        df = np.c_[self.variables, W, std_err, 
                    lower_ci, upper_ci, z, p_values]
        df = pd.DataFrame(data = df,
                          columns = ['variables', 'coef', 'std. err', 
                                     'lower_ci', 'upper_ci',
                                     'z', 'p_values'])
        self.summary = df

        return df
//  [python]
def get_summary(self, alpha = 0.95, precision=3):
        """ Providing the summary of the regression results:
                * standard errors
                * z-score 
                * p-value
        """
        
        # Flattening the coef 
        W_flat = self.weights.flatten()

        # calculating standard error 
        self.std_err  = np.sqrt(self.inv_Hessian.diagonal())/self.std_scale   

        # Confidence Intervals 
        alpha = scipy.stats.norm.ppf((1. + alpha) / 2.)
        lower_ci = np.round( W_flat - alpha * self.std_err, precision)
        upper_ci = np.round( W_flat + alpha * self.std_err, precision)
        z = np.round(W_flat / self.std_err , precision)
        p_values = np.round(scipy.stats.chi2.sf( np.square(z), 1), precision)
        W = np.round(W_flat, precision)
        std_err = np.round(self.std_err, precision)
        
        # Creating summary
        df = np.c_[self.variables, W, std_err, 
                    lower_ci, upper_ci, z, p_values]
        df = pd.DataFrame(data = df,
                          columns = ['variables', 'coef', 'std. err', 
                                     'lower_ci', 'upper_ci',
                                     'z', 'p_values'])
        self.summary = df

        return df
//  [python]
def likelihood_test(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length,flag,id):
	print('testing'+str(id));
	if flag==0:
		return([1,0]);
	else:
		res=MLE_marginal_iteration(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length);
		if abs(res[1][2]-res[1][3])<=cutoff:
			print('1<=cutoff');print(res);print((res[1][2]-res[1][3]));
			#return([1-scipy.stats.norm.cdf(abs(res[1][2]-res[1][3]),cutoff,sqrt(res[1][4]+res[1][5])),res[0]]);
			return([1,0]);
		else:
			res_constrain=MLE_marginal_iteration_constrain(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length);
			print('2>cutoff');print(res);print(res_constrain);
			print(abs(res_constrain[0]-res[0]));print(pow(1-pow(res[1][6],2),2));print('2end');
			#print(abs(res_constrain[2]-res[2]));print('2end_marginal');			
			return([s.sf(2*(abs(res_constrain[0]-res[0]))/pow(1-pow(res[1][6],2),2),1),res[1][-1]]);
//  [python]
def likelihood_test(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length,flag,id):
	print('testing'+str(id));
	if flag==0:
		return([1,0]);
	else:
		res=MLE_marginal_iteration(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length);
		if abs(res[1][2]-res[1][3])<=cutoff:
			print('1<=cutoff');print(res);print((res[1][2]-res[1][3]));
			#return([1-scipy.stats.norm.cdf(abs(res[1][2]-res[1][3]),cutoff,sqrt(res[1][4]+res[1][5])),res[0]]);
			return([1,0]);
		else:
			res_constrain=MLE_marginal_iteration_constrain(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length);
			print('2>cutoff');print(res);print(res_constrain);
			print(abs(res_constrain[0]-res[0]));print(pow(1-pow(res[1][6],2),2));print('2end');
			#print(abs(res_constrain[2]-res[2]));print('2end_marginal');			
			return([scipy.stats.chi2.sf(2*(abs(res_constrain[0]-res[0]))/pow(1-pow(res[1][6],2),2),1),res[1][-1]]);
//  [python]
def likelihood_test(i1,s1,cov,time,risk,Lambda,event,effective_inclusion_length,effective_skipping_length,flag,id,beta_initial):
	#print('testing'+str(id));
	if flag==0:
		return([1,1]);
		#return([scipy.stats.uniform.rvs(0.1,0.9,1),1]);
	else:
		res=MLE_iteration(i1,s1,cov,time,risk,Lambda,event,effective_inclusion_length,effective_skipping_length,beta_initial);
		res_constrain=MLE_iteration_constrain(i1,s1,cov,time,risk,Lambda,event,effective_inclusion_length,effective_skipping_length,res[1][2]);
		#print('test');print(res);print(res_constrain);
		#return([1-scipy.stats.chi2.cdf(10*(abs(res_constrain[0]-res[0])),1)]);
		temp=1-scipy.stats.chi2.cdf(2*(res_constrain[0]-res[0]),1);
		if temp<=0.1:
			temp=0.5*temp;
		return([min(temp,1)]);
//  [python]
def likelihood_test(i1,s1,cov,time,risk,Lambda,event,effective_inclusion_length,effective_skipping_length,flag,id,beta_initial):
	#print('testing'+str(id));
	if flag==0:
		return([1,1]);
		#return([scipy.stats.uniform.rvs(0.1,0.9,1),1]);
	else:
		res=MLE_iteration(i1,s1,cov,time,risk,Lambda,event,effective_inclusion_length,effective_skipping_length,beta_initial);
		res_constrain=MLE_iteration_constrain(i1,s1,cov,time,risk,Lambda,event,effective_inclusion_length,effective_skipping_length,res[1][2]);
		#print('test');print(res);print(res_constrain);
		#return([1-scipy.stats.chi2.cdf(10*(abs(res_constrain[0]-res[0])),1)]);
		temp=scipy.stats.chi2.sf(2*(res_constrain[0]-res[0]),1);
		if temp<=0.1:
			temp=0.5*temp;
		return([min(temp,1)]);
//  [python]
def symmetry(self, method="bowker"):
        """
        Test for symmetry of a joint distribution.

        This procedure tests the null hypothesis that the joint
        distribution is symmetric around the main diagonal, that is

        .. math::

        p_{i, j} = p_{j, i}  for all i, j

        Returns
        -------
        Bunch
            A bunch with attributes

            * statistic : float
                chisquare test statistic
            * p-value : float
                p-value of the test statistic based on chisquare distribution
            * df : int
                degrees of freedom of the chisquare distribution

        Notes
        -----
        The implementation is based on the SAS documentation. R includes
        it in `mcnemar.test` if the table is not 2 by 2.  However a more
        direct generalization of the McNemar test to larger tables is
        provided by the homogeneity test (TableSymmetry.homogeneity).

        The p-value is based on the chi-square distribution which requires
        that the sample size is not very small to be a good approximation
        of the true distribution. For 2x2 contingency tables the exact
        distribution can be obtained with `mcnemar`

        See Also
        --------
        mcnemar
        homogeneity
        """

        if method.lower() != "bowker":
            raise ValueError("method for symmetry testing must be 'bowker'")

        k = self.table.shape[0]
        upp_idx = np.triu_indices(k, 1)

        tril = self.table.T[upp_idx]   # lower triangle in column order
        triu = self.table[upp_idx]     # upper triangle in row order

        statistic = ((tril - triu)**2 / (tril + triu + 1e-20)).sum()
        df = k * (k-1) / 2.
        pvalue = stats.chi2.sf(statistic, df)

        b = _Bunch()
        b.statistic = statistic
        b.pvalue = pvalue
        b.df = df

        return b
//  [python]
def test_chi2sf():
    xlist = np.linspace(0, 100, 500)
    slist = np.arange(1, 41, 1.5)
    for s, x in itertools.product(slist, xlist):
        assert_close(s.sf(x, s), chi2sf(x, s))
//  [python]
def test_chi2sf():
    xlist = np.linspace(0, 100, 500)
    slist = np.arange(1, 41, 1.5)
    for s, x in itertools.product(slist, xlist):
        assert_close(scipy.stats.chi2.sf(x, s), chi2sf(x, s))
//  [python]
def fit_energy_res_curve(fwhm_func, fwhm_peaks, fwhms, dfwhms):
        try:
            if len(fwhm_peaks) == 0:
                raise RuntimeError
            c_lin = cost.LeastSquares(fwhm_peaks, fwhms, dfwhms, fwhm_func.func)
            # c_lin.loss = "soft_l1"
            m = Minuit(c_lin, *fwhm_func.guess(fwhm_peaks, fwhms, dfwhms))
            bounds = fwhm_func.bounds(fwhms)
            for arg, val in enumerate(bounds):
                m.limits[arg] = val
            m.simplex()
            m.migrad()
            m.hesse()

            p_val = scipy.stats.chi2.cdf(m.fval, len(fwhm_peaks) - len(m.values))

            results = {
                "function": fwhm_func,
                "module": fwhm_func.__module__,
                "expression": fwhm_func.string_func("x"),
                "parameters": m.values,
                "uncertainties": m.errors,
                "cov": m.covariance,
                "csqr": (m.fval, len(fwhm_peaks) - len(m.values)),
                "p_val": p_val,
            }

            log.info(f'FWHM fit: {results["parameters"].to_dict()}')
            log.info("FWHM fit values:")
            log.info("\t   Energy   | FWHM (kev)  | Predicted (kev)")
            for i, (peak, fwhm, fwhme) in enumerate(zip(fwhm_peaks, fwhms, dfwhms)):
                log.info(
                    f"\t{i}".ljust(4)
                    + str(peak).ljust(9)
                    + f"| {fwhm:.2f}+-{fwhme:.2f}  ".ljust(5)
                    + f"| {fwhm_func.func(peak, *results['parameters']):.2f}".ljust(5)
                )
        except RuntimeError:
            pars, errs, cov = return_nans(fwhm_func.func)
            results = {
                "function": fwhm_func,
                "module": fwhm_func.__module__,
                "expression": fwhm_func.string_func("x"),
                "parameters": pars,
                "uncertainties": errs,
                "cov": cov,
                "csqr": (np.nan, np.nan),
                "p_val": 0,
            }
            log.error("FWHM fit failed to converge")
        return results
//  [python]
def fit_energy_res_curve(fwhm_func, fwhm_peaks, fwhms, dfwhms):
        try:
            if len(fwhm_peaks) == 0:
                raise RuntimeError
            c_lin = cost.LeastSquares(fwhm_peaks, fwhms, dfwhms, fwhm_func.func)
            # c_lin.loss = "soft_l1"
            m = Minuit(c_lin, *fwhm_func.guess(fwhm_peaks, fwhms, dfwhms))
            bounds = fwhm_func.bounds(fwhms)
            for arg, val in enumerate(bounds):
                m.limits[arg] = val
            m.simplex()
            m.migrad()
            m.hesse()

            p_val = scipy.stats.chi2.sf(m.fval, len(fwhm_peaks) - len(m.values))

            results = {
                "function": fwhm_func,
                "module": fwhm_func.__module__,
                "expression": fwhm_func.string_func("x"),
                "parameters": m.values,
                "uncertainties": m.errors,
                "cov": m.covariance,
                "csqr": (m.fval, len(fwhm_peaks) - len(m.values)),
                "p_val": p_val,
            }

            log.info(f'FWHM fit: {results["parameters"].to_dict()}')
            log.info("FWHM fit values:")
            log.info("\t   Energy   | FWHM (kev)  | Predicted (kev)")
            for i, (peak, fwhm, fwhme) in enumerate(zip(fwhm_peaks, fwhms, dfwhms)):
                log.info(
                    f"\t{i}".ljust(4)
                    + str(peak).ljust(9)
                    + f"| {fwhm:.2f}+-{fwhme:.2f}  ".ljust(5)
                    + f"| {fwhm_func.func(peak, *results['parameters']):.2f}".ljust(5)
                )
        except RuntimeError:
            pars, errs, cov = return_nans(fwhm_func.func)
            results = {
                "function": fwhm_func,
                "module": fwhm_func.__module__,
                "expression": fwhm_func.string_func("x"),
                "parameters": pars,
                "uncertainties": errs,
                "cov": cov,
                "csqr": (np.nan, np.nan),
                "p_val": 0,
            }
            log.error("FWHM fit failed to converge")
        return results
//  [python]
def likelihood_ratio_test(
    df,
    label_col,
    baseline_cols,
    cluster_cols):
  """Likelihood ratio test for significance of `cluster_cols`.

  Likelihood ratio test comparing the full model fit on the combination of
  `baseline_cols` and `cluster_cols` and the null model fit only on
  `baseline_cols`.

  Args:
    df: pd.Dataframe with data on which to fit logistic regression models.
    label_col: column to use for labels.
    baseline_cols: a list of column names in `df` corresponding to baseline
      features.
    cluster_cols: a list of column names in `df` corresponding to cluster
      quantitation features.

  Returns:
    p-value of likelihood ratio test between alternative hypothesis (with
    clusters) model and null hypothesis (without clusters) model.
  """
  lr_alt, _, _ = train_eval_lr(
      df_train=df,
      df_valid=df,
      label_col=label_col,
      baseline_cols=baseline_cols,
      cluster_cols=cluster_cols)
  lr_null, _, _ = train_eval_lr(
      df_train=df,
      df_valid=df,
      label_col=label_col,
      baseline_cols=baseline_cols,
      cluster_cols=[])

  def lrt(ll_alt, ll_null, k):
    test_stat = 2 * (ll_alt - ll_null)
    return scipy.stats.chi2.sf(test_stat, k)

  return lrt(lr_alt.llf, lr_null.llf, len(cluster_cols))
//  [python]
def variance_test(global_variance, local_vector):
    n = len(local_vector)
    q_value = ((n-1)*local_vector.var())/global_variance
    return scipy.stats.chi2.sf(q_value, n-1)
//  [python]
def variance_test(global_variance, local_vector):
    n = len(local_vector)
    q_value = ((n-1)*local_vector.var())/global_variance
    return sist.chi2.sf(q_value, n-1)
//  [python]
def likelihood_test(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length,flag,id):
    #print('testing'+str(id));
    if flag==0:
        return([1,0]);
    else:
        res=MLE_marginal_iteration(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length);
        #print(res)
        if abs(res[1][2]-res[1][3])<=cutoff:
            #print('1<=cutoff');#print(res);#print((res[1][2]-res[1][3]));
            #return([1-scipy.stats.norm.cdf(abs(res[1][2]-res[1][3]),cutoff,sqrt(res[1][4]+res[1][5])),res[0]]);
            return([1,0]);
        else:
            res_constrain=MLE_marginal_iteration_constrain(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length);
            #print('2>cutoff');#print(res);#print(res_constrain);
            #print(abs(res_constrain[0]-res[0]));#print(pow(1-pow(res[1][6],2),2));#print('2end');
            ##print(abs(res_constrain[2]-res[2]));#print('2end_marginal');            
            return([scipy.stats.chi2.cdf(2*(abs(res_constrain[0]-res[0]))/pow(1-pow(res[1][6],2),2),1),res[1][-1]]);
//  [python]
def likelihood_test(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length,flag,id):
    #print('testing'+str(id));
    if flag==0:
        return([1,0]);
    else:
        res=MLE_marginal_iteration(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length);
        #print(res)
        if abs(res[1][2]-res[1][3])<=cutoff:
            #print('1<=cutoff');#print(res);#print((res[1][2]-res[1][3]));
            #return([1-scipy.stats.norm.cdf(abs(res[1][2]-res[1][3]),cutoff,sqrt(res[1][4]+res[1][5])),res[0]]);
            return([1,0]);
        else:
            res_constrain=MLE_marginal_iteration_constrain(i1,i2,s1,s2,effective_inclusion_length,effective_skipping_length);
            #print('2>cutoff');#print(res);#print(res_constrain);
            #print(abs(res_constrain[0]-res[0]));#print(pow(1-pow(res[1][6],2),2));#print('2end');
            ##print(abs(res_constrain[2]-res[2]));#print('2end_marginal');            
            return([scipy.stats.chi2.sf(2*(abs(res_constrain[0]-res[0]))/pow(1-pow(res[1][6],2),2),1),res[1][-1]]);
//  [python]
def test_pdf_unity_area(self):
        from scipy.integrate import simps
        # PDF should integrate to one
        p = stats.genexpon.pdf(numpy.arange(0, 10, 0.01), 0.5, 0.5, 2.0)
        assert_almost_equal(simps(p, dx=0.01), 1, 1)
//  [python]
def test_pdf_unity_area(self):
        from scipy.integrate import simpson
        # PDF should integrate to one
        p = stats.genexpon.pdf(numpy.arange(0, 10, 0.01), 0.5, 0.5, 2.0)
        assert_almost_equal(simpson(p, dx=0.01), 1, 1)