a
    BCCfC                     @  s8  d dl mZ d dlZd dlmZmZ d dlmZ 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	lmZ erd dlmZ d d
lmZmZ d dlmZmZ dgZeG dd dZdddddddddddZddddddddZddddddZddd dd d!d"d#d$Z d(dd ddddd%d&d'Z!dS ))    )annotationsN)	dataclassfield)TYPE_CHECKING)stats)minimize_scalar)ConfidenceInterval)check_random_state)_var)DecimalNumberSeedType)LiteralSequencedunnettc                   @  s  e Zd ZU dZded< ded< eddZded< eddZded	< eddZd
ed< eddZ	ded< eddZ
ded< eddZded< eddZded< eddZd
ed< eddZded< edddZded< edddZded< dd Zd&ddddd d!Zd'dd"d#d$d%ZdS )(DunnettResulta  Result object returned by `scipy.stats.dunnett`.

    Attributes
    ----------
    statistic : float ndarray
        The computed statistic of the test for each comparison. The element
        at index ``i`` is the statistic for the comparison between
        groups ``i`` and the control.
    pvalue : float ndarray
        The computed p-value of the test for each comparison. The element
        at index ``i`` is the p-value for the comparison between
        group ``i`` and the control.
    
np.ndarray	statisticpvalueF)repr'Literal['two-sided', 'less', 'greater']_alternative_rhoint_dffloat_std_mean_samples_mean_control
_n_samples
_n_controlr   _rngN)defaultr   zConfidenceInterval | None_cizDecimalNumber | None_ci_clc              
   C  s   | j d u r| jdd d| jd dd}t| jjD ]J}|d| d| j| d	| j| d	| j j| d	| j j| d	d
7 }q6|S )Nffffff?confidence_levelzDunnett's test (d   z.1fzW% Confidence Interval)
Comparison               Statistic  p-value  Lower CI  Upper CI
z	 (Sample z - Control) z>10.3f
)	r"   confidence_intervalr#   ranger   sizer   lowhigh)selfsi r1   R/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/stats/_multicomp.py__str__7   s    


zDunnettResult.__str__r$   MbP?r   )r&   tolreturnc                   s   d|   fdd}t |d|d}|j}|jdu sB|j|d krbtjd d|j   d	d
d |j tdj	 dj
   }t|S )aS  Allowance.

        It is the quantity to add/subtract from the observed difference
        between the means of observed groups and the mean of the control
        group. The result gives confidence limits.

        Parameters
        ----------
        confidence_level : float, optional
            Confidence level for the computed confidence interval.
            Default is .95.
        tol : float, optional
            A tolerance for numerical optimization: the allowance will produce
            a confidence within ``10*tol*(1 - confidence_level)`` of the
            specified level, or a warning will be emitted. Tight tolerances
            may be impractical due to noisy evaluation of the objective.
            Default is 1e-3.

        Returns
        -------
        allowance : float
            Allowance around the mean.
           c                   s4   t | } tjj| jjd}t|    S )Nrhodfr   alternativerng)nparray_pvalue_dunnettr   r   r   r    abs)r   Zsfalphar.   r1   r2   pvalue_from_statf   s    
z2DunnettResult._allowance.<locals>.pvalue_from_statZbrent)methodr5   F
   zComputation of the confidence interval did not converge to the desired level. The confidence level corresponding with the returned interval is approximately .   )
stacklevel)r   xsuccessZfunwarningswarnr   r=   sqrtr   r   r@   )r.   r&   r5   rC   resZcritical_value	allowancer1   rA   r2   
_allowanceJ   s    zDunnettResult._allowancer   )r&   r6   c                 C  s   | j dur|| jkr| j S d|  k r.dk s8n td| j|d}| j| j }|| }|| }| jdkr|tjgt	| }n| jdkrtj gt	| }|| _t
||d| _ | j S )	a_  Compute the confidence interval for the specified confidence level.

        Parameters
        ----------
        confidence_level : float, optional
            Confidence level for the computed confidence interval.
            Default is .95.

        Returns
        -------
        ci : ``ConfidenceInterval`` object
            The object has attributes ``low`` and ``high`` that hold the
            lower and upper bounds of the confidence intervals for each
            comparison. The high and low values are accessible for each
            comparison at index ``i`` for each group ``i``.

        Nr   r7   z)Confidence level must be between 0 and 1.r%   greaterless)r,   r-   )r"   r#   
ValueErrorrP   r   r   r   r=   inflenr   )r.   r&   rO   Z
diff_meansr,   r-   r1   r1   r2   r)      s$    

z!DunnettResult.confidence_interval)r$   r4   )r$   )__name__
__module____qualname____doc____annotations__r   r   r   r   r   r   r   r   r   r    r"   r#   r3   rP   r)   r1   r1   r1   r2   r      s&   
 ? r   	two-sided)r;   random_stateznpt.ArrayLiker   r   )samplescontrolr;   r\   r6   c                 G  st   t || ||d\}}}t||d\}}}	}
}t||||
|\}}}}t|||||d}t|||||||||
||dS )av  Dunnett's test: multiple comparisons of means against a control group.

    This is an implementation of Dunnett's original, single-step test as
    described in [1]_.

    Parameters
    ----------
    sample1, sample2, ... : 1D array_like
        The sample measurements for each experimental group.
    control : 1D array_like
        The sample measurements for the control group.
    alternative : {'two-sided', 'less', 'greater'}, optional
        Defines the alternative hypothesis.

        The null hypothesis is that the means of the distributions underlying
        the samples and control are equal. The following alternative
        hypotheses are available (default is 'two-sided'):

        * 'two-sided': the means of the distributions underlying the samples
          and control are unequal.
        * 'less': the means of the distributions underlying the samples
          are less than the mean of the distribution underlying the control.
        * 'greater': the means of the distributions underlying the
          samples are greater than the mean of the distribution underlying
          the control.
    random_state : {None, int, `numpy.random.Generator`}, optional
        If `random_state` is an int or None, a new `numpy.random.Generator` is
        created using ``np.random.default_rng(random_state)``.
        If `random_state` is already a ``Generator`` instance, then the
        provided instance is used.

        The random number generator is used to control the randomized
        Quasi-Monte Carlo integration of the multivariate-t distribution.

    Returns
    -------
    res : `~scipy.stats._result_classes.DunnettResult`
        An object containing attributes:

        statistic : float ndarray
            The computed statistic of the test for each comparison. The element
            at index ``i`` is the statistic for the comparison between
            groups ``i`` and the control.
        pvalue : float ndarray
            The computed p-value of the test for each comparison. The element
            at index ``i`` is the p-value for the comparison between
            group ``i`` and the control.

        And the following method:

        confidence_interval(confidence_level=0.95) :
            Compute the difference in means of the groups
            with the control +- the allowance.

    See Also
    --------
    tukey_hsd : performs pairwise comparison of means.

    Notes
    -----
    Like the independent-sample t-test, Dunnett's test [1]_ is used to make
    inferences about the means of distributions from which samples were drawn.
    However, when multiple t-tests are performed at a fixed significance level,
    the "family-wise error rate" - the probability of incorrectly rejecting the
    null hypothesis in at least one test - will exceed the significance level.
    Dunnett's test is designed to perform multiple comparisons while
    controlling the family-wise error rate.

    Dunnett's test compares the means of multiple experimental groups
    against a single control group. Tukey's Honestly Significant Difference Test
    is another multiple-comparison test that controls the family-wise error
    rate, but `tukey_hsd` performs *all* pairwise comparisons between groups.
    When pairwise comparisons between experimental groups are not needed,
    Dunnett's test is preferable due to its higher power.


    The use of this test relies on several assumptions.

    1. The observations are independent within and among groups.
    2. The observations within each group are normally distributed.
    3. The distributions from which the samples are drawn have the same finite
       variance.

    References
    ----------
    .. [1] Charles W. Dunnett. "A Multiple Comparison Procedure for Comparing
       Several Treatments with a Control."
       Journal of the American Statistical Association, 50:272, 1096-1121,
       :doi:`10.1080/01621459.1955.10501294`, 1955.

    Examples
    --------
    In [1]_, the influence of drugs on blood count measurements on three groups
    of animal is investigated.

    The following table summarizes the results of the experiment in which
    two groups received different drugs, and one group acted as a control.
    Blood counts (in millions of cells per cubic millimeter) were recorded::

    >>> import numpy as np
    >>> control = np.array([7.40, 8.50, 7.20, 8.24, 9.84, 8.32])
    >>> drug_a = np.array([9.76, 8.80, 7.68, 9.36])
    >>> drug_b = np.array([12.80, 9.68, 12.16, 9.20, 10.55])

    We would like to see if the means between any of the groups are
    significantly different. First, visually examine a box and whisker plot.

    >>> import matplotlib.pyplot as plt
    >>> fig, ax = plt.subplots(1, 1)
    >>> ax.boxplot([control, drug_a, drug_b])
    >>> ax.set_xticklabels(["Control", "Drug A", "Drug B"])  # doctest: +SKIP
    >>> ax.set_ylabel("mean")  # doctest: +SKIP
    >>> plt.show()

    Note the overlapping interquartile ranges of the drug A group and control
    group and the apparent separation between the drug B group and control
    group.

    Next, we will use Dunnett's test to assess whether the difference
    between group means is significant while controlling the family-wise error
    rate: the probability of making any false discoveries.
    Let the null hypothesis be that the experimental groups have the same
    mean as the control and the alternative be that an experimental group does
    not have the same mean as the control. We will consider a 5% family-wise
    error rate to be acceptable, and therefore we choose 0.05 as the threshold
    for significance.

    >>> from scipy.stats import dunnett
    >>> res = dunnett(drug_a, drug_b, control=control)
    >>> res.pvalue
    array([0.62004941, 0.0059035 ])  # may vary

    The p-value corresponding with the comparison between group A and control
    exceeds 0.05, so we do not reject the null hypothesis for that comparison.
    However, the p-value corresponding with the comparison between group B
    and control is less than 0.05, so we consider the experimental results
    to be evidence against the null hypothesis in favor of the alternative:
    group B has a different mean than the control group.

    )r]   r^   r;   r\   )r]   r^   r8   )r   r   r   r   r   r   r   r   r   r   r    )_iv_dunnett_params_dunnett_statistic_dunnettr?   r   )r^   r;   r\   r]   samples_Zcontrol_r<   r9   r:   Zn_group	n_samples	n_controlr   stdmean_controlmean_samplesr   r1   r1   r2   r      s0     

zSequence[npt.ArrayLike]z-tuple[list[np.ndarray], np.ndarray, SeedType]c           
      C  sz   t |}|dvrtdd}d}t|}dd | D }||g }|D ](}	|	jdkr\t||	jdk rFt|qF|||fS )z$Input validation for Dunnett's test.>   r[   rQ   rR   z4alternative must be 'less', 'greater' or 'two-sided'z,Control and samples groups must be 1D arraysz;Control and samples groups must have at least 1 observationc                 S  s   g | ]}t |qS r1   )r=   asarray.0sampler1   r1   r2   
<listcomp>x      z_iv_dunnett.<locals>.<listcomp>r7   )r	   rS   r=   rh   ndimr+   )
r]   r^   r;   r\   r<   Zndim_msgZ	n_obs_msgrb   Zsamples_controlrk   r1   r1   r2   r_   f  s     




r_   zlist[np.ndarray]r   z,tuple[np.ndarray, int, int, np.ndarray, int])r]   r^   r6   c           	      C  s   t dd | D }| }|j}|| }t| }|| d }|| d }dt |dddf |dddf   }t |d |||||fS )zSpecific parameters for Dunnett's test.

    Degree of freedom is the number of observations minus the number of groups
    including the control.
    c                 S  s   g | ]
}|j qS r1   )r+   ri   r1   r1   r2   rl     rm   z#_params_dunnett.<locals>.<listcomp>r7   N)r=   r>   sumr+   rU   rM   Zfill_diagonal)	r]   r^   rc   Zn_samplerd   nZn_groupsr:   r9   r1   r1   r2   r`     s    *r`   r   z0tuple[np.ndarray, float, np.ndarray, np.ndarray])r]   r^   r:   rc   rd   r6   c                 C  s   t |}t dd | D }|g|  }t |g|g}t dd t||D | }	t |	}
|| t d| d|   }||
 |
||fS )zcStatistic of Dunnett's test.

    Computation based on the original single-step test from [1].
    c                 S  s   g | ]}t |qS r1   )r=   meanri   r1   r1   r2   rl     rm   z&_statistic_dunnett.<locals>.<listcomp>c                 S  s"   g | ]\}}t ||d |j qS ))rq   )r
   r+   )rj   rk   rq   r1   r1   r2   rl     s   r7   )r=   rq   r>   Zconcatenatero   ziprM   )r]   r^   r:   rc   rd   rf   rg   Zall_samplesZ	all_meanss2re   zr1   r1   r2   ra     s    



ra   )r9   r:   r   r;   r<   r6   c                 C  s   | dd}tj| ||d}|dkrBt|}d|j|| d }n4|dkrbd|j|tj d }nd|jtj|d }t|S )zypvalue from the multivariate t-distribution.

    Critical values come from the multivariate student-t distribution.
    r7   )shaper:   seedr[   )Zlower_limitrQ   )Zreshaper   Zmultivariate_tr@   Zcdfr=   rT   Z
atleast_1d)r9   r:   r   r;   r<   Zmvtr   r1   r1   r2   r?     s    	r?   )N)"
__future__r   rK   dataclassesr   r   typingr   numpyr=   Zscipyr   Zscipy.optimizer   Zscipy.stats._commonr   Zscipy.stats._qmcr	   Zscipy.stats._stats_pyr
   Znumpy.typingZnptZscipy._lib._utilr   r   r   r   __all__r   r   r_   r`   ra   r?   r1   r1   r1   r2   <module>   s6      0  