
    _MhmB                         d dl Zd dlmZ d dlmZ ddlmZ ddlm	Z	 d Z
d Zd	 Zd
 Zd Zd Zd Z	 	 ddZ	 	 ddZ G d d          ZdddZdS )    N)ndtribrentq   )nchypergeom_fisher)ConfidenceIntervalc                     | d         dk    r0| d         dk    r$| d         | d         z  | d         | d         z  z  }n1| d         dk    s| d         dk    rt           j        }nt           j        }|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.
    )r   r   r   )r   r   r   r   )r   r   )npnaninf)table	oddsratios     W/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/stats/_odds_ratio.py_sample_odds_ratior   	   sv     T{Q5;??$K%+-tuT{1JK			t		U4[A--F		F	    c                 $   d} | |          }|dk    r|S d}|dk    r0||z  } | |          dk    r||z  } | |          dk    |}||z  }n/||z  } | |          dk     r||z  } | |          dk     ||z  }|}t          | ||d          }|S )zC
    Solve func(nc) = 0.  func must be an increasing function.
    g      ?r   g       @gvIh%<=)xtolr   )funcncvaluefactorlohis         r   _solver      s     
BDHHEzz	 Fqyy
fd2hhll&LB d2hhllBY
fd2hhll&LB d2hhllY 
b"5	)	)	)BIr   c                 8     t           fd          }|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                 8    t          j        |           z
  S N)r   mean)r   MNnxs    r   <lambda>z,_nc_hypergeom_mean_inverse.<locals>.<lambda>C   s    -21aB??!C r   )r   )r#   r    r"   r!   r   s   ```` r   _nc_hypergeom_mean_inverser%   <   s-     
CCCCCCC	D	DBIr   c                     | d         }|                                  }| d                                          }| d d df                                          }||||fS )Nr
   r   )sum)r   r#   r    r"   r!   s        r   _hypergeom_params_from_tabler(   G   sT     	dA		AaAaaadAaA:r   c                     t          |           t          j        k    rt          j        S t          |           \  t	          fd          }|S )z;
    Compute the upper end of the confidence interval.
    c                 <    t          j        |            z   S r   )r   cdfr   r    r!   alphar"   r#   s    r   r$   z_ci_upper.<locals>.<lambda>\   s#    .21aArBBBUJ r   )r   r   r   r(   r   r   r-   r   r    r!   r"   r#   s    ` @@@@r   	_ci_upperr/   Q   sd     %  BF**v-e44JAq!Q 
JJJJJJJJ	K	KBIr   c                     t          |           dk    rdS t          |           \  t          fd          }|S )z;
    Compute the lower end of the confidence interval.
    r   c                 @    t          j        dz
  |           z
  S )Nr   )r   sfr,   s    r   r$   z_ci_lower.<locals>.<lambda>i   s$    -0Q1aDDuL r   )r   r(   r   r.   s    ` @@@@r   	_ci_lowerr3   `   s^     %  A%%q-e44JAq!Q	LLLLLLLL	M	MBIr   c                     t          |           \  }}}}t          j        |||d          \  }}||k    rdS ||k    rt          j        S t          ||||          }|S )zJ
    Conditional MLE of the odds ratio for the 2x2 contingency table.
    r   r   )r(   r   supportr   r   r%   )r   r#   r    r"   r!   r   r   r   s           r   _conditional_oddsratior6   m   sm     .e44JAq!Q  '1a33FB 	BwwqBwwv	#Aq!Q	/	/BIr   ffffff?	two-sidedc                     |dk    r)dd|z
  z  }t          | |          }t          | |          }n;|dk    rd}t          | d|z
            }nt          | d|z
            }t          j        }||fS )zC
    Conditional exact confidence interval for the odds ratio.
    r8         ?r   lessg        )r3   r/   r   r   )r   confidence_levelalternativer-   loweruppers         r   _conditional_oddsratio_cir@      s    
 k!!Q))*%''%''			%%5!566 %%5!566%<r   c                    t          |           }t          j        |          }t          j        d| z                                            }|dk    r%t          |          }t          j         }|||z  z   }nO|dk    r$t          |          }|||z  z
  }t          j        }n%t          d|z  dz             }|||z  z
  }|||z  z   }t          j        |          t          j        |          fS )Nr   r;   greaterr:   )r   r   logsqrtr'   r   r   exp)	r   r<   r=   r   log_orsezloglowloghighs	            r   _sample_odds_ratio_cirK      s    "5))IVIF	!E'	!	!Bf"##&1R4-			!	!"##!B$& #&&,--!B$1R4-6&>>26'??**r   c                   B    e Zd ZdZd Zd Z	 	 d
dZ	 	 d
dZ	 	 d
dZd	S )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                 0    || _         || _        || _        d S r   _table_kind	statistic)selfrP   rQ   rR   s       r   __init__zOddsRatioResult.__init__   s     
"r   c                     d| j          dS )NzOddsRatioResult(statistic=))rR   )rS   s    r   __repr__zOddsRatioResult.__repr__   s    =DN====r   r7   r8   c                     |dvrt          d          |dk     s|dk    rt          d          | j        dk    r|                     ||          }n|                     ||          }|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).
        )r8   r;   rB   z7`alternative` must be 'two-sided', 'less' or 'greater'.r   r   (confidence_level must be between 0 and 1conditional)
ValueErrorrQ   _conditional_odds_ratio_cirK   )rS   r<   r=   cis       r   confidence_intervalz#OddsRatioResult.confidence_interval   s    B >>> * + + + a#3a#7#7GHHH:&&001A;OOBB++,<kJJB	r   c                     | j         }d|                    d          v sd|                    d          v rdt          j        f}nt	          |||          }t          |d         |d                   S )zE
        Confidence interval for the conditional odds ratio.
        r   axisr   r<   r=   lowhigh)rP   r'   r   r   r@   r   rS   r<   r=   r   r]   s        r   r\   z*OddsRatioResult._conditional_odds_ratio_ci  s     		q	!!!!Q%)))*;*;%;%; RVBB*5<L7BD D DB "be"Q%8888r   c                 "   |dk     s|dk    rt          d          | j        }d|                    d          v sd|                    d          v rdt          j        f}nt          |||          }t          |d         |d                   S )z@
        Confidence interval for the sample odds ratio.
        r   r   rY   r`   rb   rc   )r[   rP   r'   r   r   rK   r   rf   s        r   rK   z%OddsRatioResult._sample_odds_ratio_ci0  s    
 a#3a#7#7GHHH		q	!!!!Q%)))*;*;%;%; RVBB&u8H3>@ @ @B "be"Q%8888r   Nr7   r8   )	__name__
__module____qualname____doc__rT   rW   r^   r\   rK    r   r   rM   rM      s         0# # #> > > 48(3L L L L\ ;?/:9 9 9 9" 6:*59 9 9 9 9 9r   rM   rZ   )kindc                   |dvrt          d          t          j        |           }|j        dk    rt          d|j         d          t          j        |j        t          j                  st          d|j                   |                    t          j                  }t          j	        |dk               rt          d          d|
                    d	          v sd|
                    d
	          v rt          ||t          j                  }|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`.
    )rZ   samplez)`kind` must be 'conditional' or 'sample'.)   rq   zInvalid shape z,. The input `table` must be of shape (2, 2).z3`table` must be an array of integers, but got type r   z*All values in `table` must be nonnegative.r`   r   rO   rp   )r[   r   asarrayshape
issubdtypedtypeintegerastypeint64anyr'   rM   r   r   r6   )r   rn   cresultr   s        r   
odds_ratior|   D  sg   b ,,,DEEE

5Aw& ,!' , , , - - 	- ="*-- , +!"+ + , , 	,	A	va!e}} GEFFFAEEqEMMQ!%%Q%--// !HHHx&q))		*1--	ATYGGGFMr   rh   )numpyr   scipy.specialr   scipy.optimizer   _discrete_distnsr   _commonr   r   r   r%   r(   r/   r3   r6   r@   rK   rM   r|   rm   r   r   <module>r      s[             ! ! ! ! ! ! 0 0 0 0 0 0 ' ' ' ' ' '  "  D      
 
 
  . 7;*5   ( 37&1+ + + +,S9 S9 S9 S9 S9 S9 S9 S9l , N N N N N N Nr   