L imBddlZddlmZddlmZddlmZddlm Z dZ dZ d Z d Z d Zd Zd Z ddZ ddZGddZdddZy)N)ndtribrentq)nchypergeom_fisher)ConfidenceIntervalc|ddkDr!|ddkDr|d|dz|d|dzz }|S|ddk(s|ddk(rtj}|Stj}|S)z Given a table [[a, b], [c, d]], compute a*d/(b*c). Return nan if the numerator and denominator are 0. Return inf if just the denominator is 0. )rrr)rrrr)rr)npnaninf)table oddsratios ]/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/stats/_odds_ratio.py_sample_odds_ratior s T{Q5;?$K%+-tuT{1JK  t U4[A-FF  FF cd}||}|dk(r|Sd}|dkDr)||z}||dkDr||z}||dkDr|}||z}n(||z}||dkr||z}||dkr||z }|}t|||d}|S)zC Solve func(nc) = 0. func must be an increasing function. g?rg@gvIh%<=)xtolr)funcncvaluefactorlohis r_solvers B HE z F qy f 2hl &LB2hl  BY f 2hl &LB2hl Y  b"5 )B Irc0tfd}|S)a For the given noncentral hypergeometric parameters x, M, n,and N (table[0,0], total, row 0 sum and column 0 sum, resp., of a 2x2 contingency table), find the noncentrality parameter of Fisher's noncentral hypergeometric distribution whose mean is x. c:tj|z SN)rmean)rMNnxs rz,_nc_hypergeom_mean_inverse..Cs-221aB?!Cr)r)r#r r"r!rs```` r_nc_hypergeom_mean_inverser%<s C DB Irc|d}|j}|dj}|dddfj}||||fS)Nr r)sum)rr#r r"r!s r_hypergeom_params_from_tabler(GsI d A A a A ad A aA:rct|tjk(rtjSt|\t fd}|S)z; Compute the upper end of the confidence interval. c>tj| zSr)rcdfrr r!alphar"r#s rr$z_ci_upper..\s#.221aArBBUJr)rr r r(rrr-rr r!r"r#s ` @@@@r _ci_upperr/QsC% BFF*vv -e4JAq!Q J KB Ircrt|dk(ryt|\tfd}|S)z; Compute the lower end of the confidence interval. rcBtjdz |z S)Nr)rsfr,s rr$z_ci_lower..is$-00Q1aDuLr)rr(rr.s ` @@@@r _ci_lowerr3`s7% A%-e4JAq!Q L MB Irct|\}}}}tj|||d\}}||k(ry||k(rtjSt ||||}|S)zJ Conditional MLE of the odds ratio for the 2x2 contingency table. rr)r(rsupportr r r%)rr#r r"r!rrrs r_conditional_oddsratior6msc.e4JAq!Q ' '1a 3FB BwBwvv #Aq!Q /B Irc|dk(r$dd|z z}t||}t||}||fS|dk(rd}t|d|z }||fSt|d|z }tj}||fS)zC Conditional exact confidence interval for the odds ratio. two-sided?rlessg)r3r/r r )rconfidence_level alternativer-loweruppers r_conditional_oddsratio_cir?s k!Q))*%'%' %<  %%5!56 %<%%5!56 %<rct|}tj|}tjd|z j }|dk(r%t |}tj }|||zz}nJ|dk(r$t |}|||zz }tj }n!t d|zdz}|||zz }|||zz}tj|tj|fS)Nrr:greaterr9)rr logsqrtr'rr exp) rr;r<rlog_orsezloglowloghighs r_sample_odds_ratio_cirJs"5)I VVI F !E' !Bf " #&&1R4-  ! " #!B$&& #&&, -!B$1R4- 66&>266'? **rc@eZdZdZdZdZ ddZ ddZ ddZy) OddsRatioResulta Result of `scipy.stats.contingency.odds_ratio`. See the docstring for `odds_ratio` for more details. Attributes ---------- statistic : float The computed odds ratio. * If `kind` is ``'sample'``, this is sample (or unconditional) estimate, given by ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``. * If `kind` is ``'conditional'``, this is the conditional maximum likelihood estimate for the odds ratio. It is the noncentrality parameter of Fisher's noncentral hypergeometric distribution with the same hypergeometric parameters as `table` and whose mean is ``table[0, 0]``. Methods ------- confidence_interval : Confidence interval for the odds ratio. c.||_||_||_yr_table_kind statistic)selfrOrPrQs r__init__zOddsRatioResult.__init__s  "rc"d|jdS)NzOddsRatioResult(statistic=))rQ)rRs r__repr__zOddsRatioResult.__repr__s+DNN+;1==rc|dvr td|dks|dkDr td|jdk(r|j||}|S|j||}|S)a Confidence interval for the odds ratio. Parameters ---------- confidence_level: float Desired confidence level for the confidence interval. The value must be given as a fraction between 0 and 1. Default is 0.95 (meaning 95%). alternative : {'two-sided', 'less', 'greater'}, optional The alternative hypothesis of the hypothesis test to which the confidence interval corresponds. That is, suppose the null hypothesis is that the true odds ratio equals ``OR`` and the confidence interval is ``(low, high)``. Then the following options for `alternative` are available (default is 'two-sided'): * 'two-sided': the true odds ratio is not equal to ``OR``. There is evidence against the null hypothesis at the chosen `confidence_level` if ``high < OR`` or ``low > OR``. * 'less': the true odds ratio is less than ``OR``. The ``low`` end of the confidence interval is 0, and there is evidence against the null hypothesis at the chosen `confidence_level` if ``high < OR``. * 'greater': the true odds ratio is greater than ``OR``. The ``high`` end of the confidence interval is ``np.inf``, and there is evidence against the null hypothesis at the chosen `confidence_level` if ``low > OR``. Returns ------- ci : ``ConfidenceInterval`` instance The confidence interval, represented as an object with attributes ``low`` and ``high``. Notes ----- When `kind` is ``'conditional'``, the limits of the confidence interval are the conditional "exact confidence limits" as described by Fisher [1]_. The conditional odds ratio and confidence interval are also discussed in Section 4.1.2 of the text by Sahai and Khurshid [2]_. When `kind` is ``'sample'``, the confidence interval is computed under the assumption that the logarithm of the odds ratio is normally distributed with standard error given by:: se = sqrt(1/a + 1/b + 1/c + 1/d) where ``a``, ``b``, ``c`` and ``d`` are the elements of the contingency table. (See, for example, [2]_, section 3.1.3.2, or [3]_, section 2.3.3). References ---------- .. [1] R. A. Fisher (1935), The logic of inductive inference, Journal of the Royal Statistical Society, Vol. 98, No. 1, pp. 39-82. .. [2] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology: Methods, Techniques, and Applications, CRC Press LLC, Boca Raton, Florida. .. [3] Alan Agresti, An Introduction to Categorical Data Analysis (second edition), Wiley, Hoboken, NJ, USA (2007). )r8r:rAz7`alternative` must be 'two-sided', 'less' or 'greater'.rr(confidence_level must be between 0 and 1 conditional) ValueErrorrP_conditional_odds_ratio_cirJ)rRr;r<cis rconfidence_intervalz#OddsRatioResult.confidence_intervals~B > >*+ + a #3a#7GH H :: &001A;OB ++,@B"be"Q%88rNgffffff?r8) __name__ __module__ __qualname____doc__rSrVr]r[rJrrrLrLs:0#>48(3L\;?/:9"6:*59rrLrY)kindc|dvr tdtj|}|jdk7rtd|jdtj|j tj std|j |jtj}tj|dkr tdd|jd vsd|jd vrt||tj }|S|d k(r t|}n t|}t||| }|S) a? Compute the odds ratio for a 2x2 contingency table. Parameters ---------- table : array_like of ints A 2x2 contingency table. Elements must be non-negative integers. kind : str, optional Which kind of odds ratio to compute, either the sample odds ratio (``kind='sample'``) or the conditional odds ratio (``kind='conditional'``). Default is ``'conditional'``. Returns ------- result : `~scipy.stats._result_classes.OddsRatioResult` instance The returned object has two computed attributes: statistic : float * If `kind` is ``'sample'``, this is sample (or unconditional) estimate, given by ``table[0, 0]*table[1, 1]/(table[0, 1]*table[1, 0])``. * If `kind` is ``'conditional'``, this is the conditional maximum likelihood estimate for the odds ratio. It is the noncentrality parameter of Fisher's noncentral hypergeometric distribution with the same hypergeometric parameters as `table` and whose mean is ``table[0, 0]``. The object has the method `confidence_interval` that computes the confidence interval of the odds ratio. See Also -------- scipy.stats.fisher_exact relative_risk :ref:`hypothesis_odds_ratio` : Extended example Notes ----- The conditional odds ratio was discussed by Fisher (see "Example 1" of [1]_). Texts that cover the odds ratio include [2]_ and [3]_. .. versionadded:: 1.10.0 References ---------- .. [1] R. A. Fisher (1935), The logic of inductive inference, Journal of the Royal Statistical Society, Vol. 98, No. 1, pp. 39-82. .. [2] Breslow NE, Day NE (1980). Statistical methods in cancer research. Volume I - The analysis of case-control studies. IARC Sci Publ. (32):5-338. PMID: 7216345. (See section 4.2.) .. [3] H. Sahai and A. Khurshid (1996), Statistics in Epidemiology: Methods, Techniques, and Applications, CRC Press LLC, Boca Raton, Florida. Examples -------- In epidemiology, individuals are classified as "exposed" or "unexposed" to some factor or treatment. If the occurrence of some illness is under study, those who have the illness are often classified as "cases", and those without it are "noncases". The counts of the occurrences of these classes gives a contingency table:: exposed unexposed cases a b noncases c d The sample odds ratio may be written ``(a/c) / (b/d)``. ``a/c`` can be interpreted as the odds of a case occurring in the exposed group, and ``b/d`` as the odds of a case occurring in the unexposed group. The sample odds ratio is the ratio of these odds. If the odds ratio is greater than 1, it suggests that there is a positive association between being exposed and being a case. Interchanging the rows or columns of the contingency table inverts the odds ratio, so it is important to understand the meaning of labels given to the rows and columns of the table when interpreting the odds ratio. Consider a hypothetical example where it is hypothesized that exposure to a certain chemical is associated with increased occurrence of a certain disease. Suppose we have the following table for a collection of 410 people:: exposed unexposed cases 7 15 noncases 58 472 The question we ask is "Is exposure to the chemical associated with increased risk of the disease?" Compute the odds ratio: >>> from scipy.stats.contingency import odds_ratio >>> res = odds_ratio([[7, 15], [58, 472]]) >>> res.statistic 3.7836687705553493 For this sample, the odds of getting the disease for those who have been exposed to the chemical are almost 3.8 times that of those who have not been exposed. We can compute the 95% confidence interval for the odds ratio: >>> res.confidence_interval(confidence_level=0.95) ConfidenceInterval(low=1.2514829132266785, high=10.363493716701269) The 95% confidence interval for the conditional odds ratio is approximately (1.25, 10.4). For a more detailed example, see :ref:`hypothesis_odds_ratio`. )rYsamplez)`kind` must be 'conditional' or 'sample'.)rpzInvalid shape z,. The input `table` must be of shape (2, 2).z3`table` must be an array of integers, but got type rz*All values in `table` must be nonnegative.r_rrNro)rZr asarrayshape issubdtypedtypeintegerastypeint64anyr'rLr rr6)rrmcresultrs r odds_ratior{Ds%b ,,DEE 5Aww&>!''3,,- - =="** -!!" +, , A vva!e}EFFAEEqEMQ!%%Q%-/!H  x&q) *1- ATY GF Mrrg)numpyr scipy.specialrscipy.optimizer_discrete_distnsr_commonrrrr%r(r/r3r6r?rJrLr{rlrrrsj!0'"D  .7;*5(37&1+,S9S9l,Nr