a
    BCCfE                     @   s   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d Z
d	d
 Zdd Zdd Zdd Zdd Zdd Zd!ddZd"ddZG dd dZdddd ZdS )#    N)ndtribrentq   )nchypergeom_fisher)ConfidenceIntervalc                 C   sd   | d dkr:| d dkr:| d | d  | d | d   }n&| d dksR| d dkrZt 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	oddsratio r   S/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/stats/_odds_ratio.py_sample_odds_ratio	   s    "r   c                 C   s   d}| |}|dkr|S d}|dkrP|| }| |dkrB|| }q,|}|| }n*||9 }| |dk rn||9 }qX|| }|}t | ||dd}|S )zC
    Solve func(nc) = 0.  func must be an increasing function.
    g      ?r   g       @gvIh%<=)Zxtolr   )funcncvaluefactorlohir   r   r   _solve   s$    


r   c                    s   t  fd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                    s   t  |  S N)r   meanr   MNnxr   r   <lambda>C       z,_nc_hypergeom_mean_inverse.<locals>.<lambda>)r   )r   r   r   r   r   r   r   r   _nc_hypergeom_mean_inverse<   s    r"   c                 C   s<   | d }|   }| d   }| d d df   }||||fS )Nr   r   )sum)r   r   r   r   r   r   r   r   _hypergeom_params_from_tableG   s
    r$   c                    s@   t | tjkrtjS t| \ t fdd}|S )z;
    Compute the upper end of the confidence interval.
    c                    s   t  |   S r   )r   Zcdfr   r   r   alphar   r   r   r   r    \   r!   z_ci_upper.<locals>.<lambda>)r   r	   r   r$   r   r   r&   r   r   r%   r   	_ci_upperQ   s
    r(   c                    s<   t | dkrdS t| \ t fdd}|S )z;
    Compute the lower end of the confidence interval.
    r   c                    s   t d  |  S )Nr   )r   Zsfr   r%   r   r   r    i   r!   z_ci_lower.<locals>.<lambda>)r   r$   r   r'   r   r%   r   	_ci_lower`   s
    r)   c                 C   sP   t | \}}}}t|||d\}}||kr0dS ||kr>tjS t||||}|S )zJ
    Conditional MLE of the odds ratio for the 2x2 contingency table.
    r   r   )r$   r   Zsupportr	   r   r"   )r   r   r   r   r   r   r   r   r   r   r   _conditional_oddsratiom   s    r*   ffffff?	two-sidedc                 C   sb   |dkr*dd|  }t | |}t| |}n0|dkrFd}t| d| }nt | d| }tj}||fS )zC
    Conditional exact confidence interval for the odds ratio.
    r,         ?r   lessg        )r)   r(   r	   r   )r   confidence_levelalternativer&   lowerupperr   r   r   _conditional_oddsratio_ci   s    
r3   c           	      C   s   t | }t|}td|   }|dkrJt|}tj }|||  }nL|dkrnt|}|||  }tj}n(td| d }|||  }|||  }t|t|fS )Nr   r.   greaterr-   )r   r	   logsqrtr#   r   r   exp)	r   r/   r0   r   Zlog_orsezZloglowZloghighr   r   r   _sample_odds_ratio_ci   s    
r:   c                   @   s>   e Zd ZdZdd Zdd Zddd	Zdd
dZd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                 C   s   || _ || _|| _d S r   _table_kind	statistic)selfr=   r>   r?   r   r   r   __init__   s    zOddsRatioResult.__init__c                 C   s   d| j  dS )NzOddsRatioResult(statistic=))r?   )r@   r   r   r   __repr__   s    zOddsRatioResult.__repr__r+   r,   c                 C   sP   |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).
        )r,   r.   r4   z7`alternative` must be 'two-sided', 'less' or 'greater'.r   r   (confidence_level must be between 0 and 1conditional)
ValueErrorr>   _conditional_odds_ratio_cir:   )r@   r/   r0   cir   r   r   confidence_interval   s    A
z#OddsRatioResult.confidence_intervalc                 C   sT   | j }d|jddv s&d|jddv r2dtjf}nt|||d}t|d |d dS )zE
        Confidence interval for the conditional odds ratio.
        r   Zaxisr   r/   r0   lowhigh)r=   r#   r	   r   r3   r   r@   r/   r0   r   rH   r   r   r   rG     s     z*OddsRatioResult._conditional_odds_ratio_cic                 C   sl   |dk s|dkrt d| j}d|jddv s>d|jddv rJdtjf}nt|||d}t|d |d dS )z@
        Confidence interval for the sample odds ratio.
        r   r   rD   rJ   rK   rL   )rF   r=   r#   r	   r   r:   r   rO   r   r   r   r:   0  s     z%OddsRatioResult._sample_odds_ratio_ciN)r+   r,   )r+   r,   )r+   r,   )	__name__
__module____qualname____doc__rA   rC   rI   rG   r:   r   r   r   r   r;      s     
N  
  r;   rE   )kindc                C   s   |dvrt dt| }|jdkr6t d|j dt|jtjsVt d|j |tj}t	|dk rxt dd|j
dd	v sd|j
d
d	v rt||tjd}|S |dkrt|}nt|}t|||d}|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

    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.
    .. [4] Berger, Jeffrey S. et al. "Aspirin for the Primary Prevention of
           Cardiovascular Events in Women and Men: A Sex-Specific
           Meta-analysis of Randomized Controlled Trials."
           JAMA, 295(3):306-313, :doi:`10.1001/jama.295.3.306`, 2006.

    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 import to understand the meaning of labels
    given to the rows and columns of the table when interpreting the
    odds ratio.

    In [4]_, the use of aspirin to prevent cardiovascular events in women
    and men was investigated. The study notably concluded:

        ...aspirin therapy reduced the risk of a composite of
        cardiovascular events due to its effect on reducing the risk of
        ischemic stroke in women [...]

    The article lists studies of various cardiovascular events. Let's
    focus on the ischemic stoke in women.

    The following table summarizes the results of the experiment in which
    participants took aspirin or a placebo on a regular basis for several
    years. Cases of ischemic stroke were recorded::

                          Aspirin   Control/Placebo
        Ischemic stroke     176           230
        No stroke         21035         21018

    The question we ask is "Is there evidence that the aspirin reduces the
    risk of ischemic stroke?"

    Compute the odds ratio:

    >>> from scipy.stats.contingency import odds_ratio
    >>> res = odds_ratio([[176, 230], [21035, 21018]])
    >>> res.statistic
    0.7646037659999126

    For this sample, the odds of getting an ischemic stroke for those who have
    been taking aspirin are 0.76 times that of those
    who have received the placebo.

    To make statistical inferences about the population under study,
    we can compute the 95% confidence interval for the odds ratio:

    >>> res.confidence_interval(confidence_level=0.95)
    ConfidenceInterval(low=0.6241234078749812, high=0.9354102892100372)

    The 95% confidence interval for the conditional odds ratio is
    approximately (0.62, 0.94).

    The fact that the entire 95% confidence interval falls below 1 supports
    the authors' conclusion that the aspirin was associated with a
    statistically significant reduction in ischemic stroke.
    )rE   samplez)`kind` must be 'conditional' or 'sample'.)   rV   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.rJ   r   r<   rU   )rF   r	   ZasarrayshapeZ
issubdtypeZdtypeintegerZastypeZint64anyr#   r;   r
   r   r*   )r   rT   cresultr   r   r   r   
odds_ratioD  s*     

 
r\   )r+   r,   )r+   r,   )numpyr	   Zscipy.specialr   Zscipy.optimizer   Z_discrete_distnsr   _commonr   r   r   r"   r$   r(   r)   r*   r3   r:   r;   r\   r   r   r   r   <module>   s(   "
  
  
 