a
    ˜¥»a)G  ã                	   @   sÂ   d dl Zd dlmZ d dlmZm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d„Zd#dd„Zdd„ Zdd„ Zdd„ Zdd„ ZddgZe	deƒZddd ddddddœd d!„ZdS )$é    N)Úcheck_random_state)ÚndtrÚndtri)Úrng_integers)Úmake_dataclassé   )ÚConfidenceInterval)Ú_broadcast_concatenatec                    s   ddœ‡ fdd„
}|S )zVectorize an n-sample statisticr   ©Úaxisc                    sN   ‡ fdd„|D ƒ}t  |¡d d… ‰t|ˆ ƒ}‡‡fdd„}t  |ˆ |¡d S )Nc                    s   g | ]}|j ˆ  ‘qS © )Úshape©Ú.0Úsampler
   r   úP/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/scipy/stats/_bootstrap.pyÚ
<listcomp>   ó    z9_vectorize_statistic.<locals>.stat_nd.<locals>.<listcomp>éÿÿÿÿc                    s   t  | ˆ ¡}ˆ|Ž S )N)ÚnpÚsplit)ÚzÚdata)Úsplit_indicesÚ	statisticr   r   Ústat_1d   s    z6_vectorize_statistic.<locals>.stat_nd.<locals>.stat_1dr   )r   Zcumsumr	   Zapply_along_axis)r   r   Úlengthsr   r   ©r   )r   r   r   Ústat_nd   s
    
z%_vectorize_statistic.<locals>.stat_ndr   )r   r   r   r   r   Ú_vectorize_statistic
   s    
r   c           	      c   sª   | j d }|p|}td||ƒD ]†}t||| ƒ}tj||ftd�}t |dd…||| …f d¡ t |¡}t |||f¡}||  	||d f¡}| d|f }|V  qdS )z=Jackknife resample the sample. Only one-sample stats for now.r   r   ©ZdtypeNFr   .)
r   ÚrangeÚminr   ZonesÚboolZfill_diagonalÚarangeÚbroadcast_toZreshape)	r   ÚbatchÚnÚbatch_nominalÚkÚbatch_actualÚjÚiÚ	resamplesr   r   r   Ú_jackknife_resample   s    
 
r.   c                 C   s,   | j d }t|d|||fƒ}| d|f }|S )zBootstrap resample the sample.r   r   .)r   r   )r   Ún_resamplesÚrandom_stater'   r,   r-   r   r   r   Ú_bootstrap_resample/   s    
r1   c                 C   s   | j | }| |k j|d�| S )z˜Vectorized, simplified `scipy.stats.percentileofscore`.

    Unlike `stats.percentileofscore`, the percentile returned is a fraction
    in [0, 1].
    r
   )r   Úsum)ÚaZscorer   ÚBr   r   r   Ú_percentile_of_score:   s    
r5   c                 C   s^   | j dd… }t ||¡}tj|tjd�}t |¡D ] \}}| | }t ||¡||< q4|d S )z9`np.percentile` with different percentile for each slice.Nr   r    r   )r   r   r%   Z
zeros_likeÚfloat64ZndenumerateÚ
percentile)Útheta_hat_bÚalphar   ZpercentilesÚindicesZalpha_iZtheta_hat_b_ir   r   r   Ú_percentile_along_axisD   s    r;   c                 C   sþ   | d }|||d�d }t ||dd�}t|ƒ}	g }
t||ƒD ]}|
 ||dd�¡ q<tj|
dd�}
|
jddd�}||
 d jdd�}d||
 d	 jdd�d
  }|| }t|ƒ}| }|	| }t|	|d||    ƒ}|	| }t|	|d||    ƒ}||fS )z(Bias-corrected and accelerated interval.r   r
   ).Nr   T)r   Zkeepdimsé   é   é   g      ø?r   )	r5   r   r.   Úappendr   ÚconcatenateÚmeanr2   r   )r   r   r   r9   r8   r&   r   Ú	theta_hatr7   Zz0_hatZtheta_hat_iZjackknife_sampleZtheta_hat_dotÚnumZdenZa_hatZz_alphaZz_1alphaZnum1Zalpha_1Znum2Zalpha_2r   r   r   Ú_bca_intervalR   s&    rD   c
              
   C   sð  |dvrt dƒ‚|st|ƒ}t|ƒ}
||
kr4t dƒ‚d}zt| ƒ}W n ty^   t dƒ‚Y n0 |dkrpt dƒ‚g }| D ]<}t |¡}|j|
 dkrœt dƒ‚t ||
d	¡}| 	|¡ qx|dvrÆt d
ƒ‚|�r"|d jd	 }|dd… D ]}|jd	 |kræd}t |ƒ‚qæd	||fdd„}t 
|¡g}t|ƒ}t|ƒ}||k�sF|dk�rNt dƒ‚|du �r^|}n$t|ƒ}||k�sz|dk�r‚t dƒ‚h d£}| ¡ }||v�rªt d|› �ƒ‚d}|�sÐ|dk�rÐ|dk�rÐt |ƒ‚t|	ƒ}	|||||
|||||	f
S )z5Input validation and standardization for `bootstrap`.>   FTz'`vectorized` must be `True` or `False`.z`axis` must be an integer.r   z%`data` must be a sequence of samples.z(`data` must contain at least one sample.r   zIeach sample in `data` must contain two or more observations along `axis`.r   z#`paired` must be `True` or `False`.NzIWhen `paired is True`, all samples must have the same length along `axis`c                    s    ‡ fdd„|D ƒ}||d|iŽS )Nc                    s   g | ]}|d ˆ f ‘qS ).r   r   ©r,   r   r   r   ž   r   z4_bootstrap_iv.<locals>.statistic.<locals>.<listcomp>r   r   )r,   r   r   Zunpaired_statisticr   rE   r   r   �   s    z _bootstrap_iv.<locals>.statisticz)`n_resamples` must be a positive integer.z+`batch` must be a positive integer or None.>   ÚbasicÚbcar7   z`method` must be in z;`method = 'BCa' is only available for one-sample statisticsrG   )Ú
ValueErrorr   ÚintÚlenÚ	TypeErrorr   Z
atleast_1dr   Zmoveaxisr?   r$   ÚfloatÚlowerr   )r   r   Ú
vectorizedÚpairedr   Úconfidence_levelr/   r&   Úmethodr0   Zaxis_intZ	n_samplesZdata_ivr   r'   ÚmessageZconfidence_level_floatZn_resamples_intZbatch_ivÚmethodsr   r   r   Ú_bootstrap_ivp   sh    




þrT   Úconfidence_intervalÚstandard_errorÚBootstrapResultTFgffffffî?i'  ZBCa)rN   rO   r   rP   r/   r&   rQ   r0   c                C   sp  t | |||||||||	ƒ
}
|
dd… \} }}}}|
dd… \}}}}}	g }|pP|}td||ƒD ]L}t||| ƒ}g }| D ]}t|||	d�}| |¡ qx| ||ddiŽ¡ q^tj|dd�}d| d	 }|d
krèt| |d|||d�}t}n|d| f}dd„ }|||d d ƒ}|||d d ƒ}|dk�rR|| ddiŽ}d	| | d	| |  }}t	t
||ƒtj|ddd�d�S )a$  
    Compute a two-sided bootstrap confidence interval of a statistic.

    When `method` is ``'percentile'``, a bootstrap confidence interval is
    computed according to the following procedure.

    1. Resample the data: for each sample in `data` and for each of
       `n_resamples`, take a random sample of the original sample
       (with replacement) of the same size as the original sample.

    2. Compute the bootstrap distribution of the statistic: for each set of
       resamples, compute the test statistic.

    3. Determine the confidence interval: find the interval of the bootstrap
       distribution that is

       - symmetric about the median and
       - contains `confidence_level` of the resampled statistic values.

    While the ``'percentile'`` method is the most intuitive, it is rarely
    used in practice. Two more common methods are available, ``'basic'``
    ('reverse percentile') and ``'BCa'`` ('bias-corrected and accelerated');
    they differ in how step 3 is performed.

    If the samples in `data` are  taken at random from their respective
    distributions :math:`n` times, the confidence interval returned by
    `bootstrap` will contain the true value of the statistic for those
    distributions approximately `confidence_level`:math:`\, \times \, n` times.

    Parameters
    ----------
    data : sequence of array-like
         Each element of data is a sample from an underlying distribution.
    statistic : callable
        Statistic for which the confidence interval is to be calculated.
        `statistic` must be a callable that accepts ``len(data)`` samples
        as separate arguments and returns the resulting statistic.
        If `vectorized` is set ``True``,
        `statistic` must also accept a keyword argument `axis` and be
        vectorized to compute the statistic along the provided `axis`.
    vectorized : bool, default: ``True``
        If `vectorized` is set ``False``, `statistic` will not be passed
        keyword argument `axis`, and is assumed to calculate the statistic
        only for 1D samples.
    paired : bool, default: ``False``
        Whether the statistic treats corresponding elements of the samples
        in `data` as paired.
    axis : int, default: ``0``
        The axis of the samples in `data` along which the `statistic` is
        calculated.
    confidence_level : float, default: ``0.95``
        The confidence level of the confidence interval.
    n_resamples : int, default: ``9999``
        The number of resamples performed to form the bootstrap distribution
        of the statistic.
    batch : int, optional
        The number of resamples to process in each vectorized call to
        `statistic`. Memory usage is O(`batch`*``n``), where ``n`` is the
        sample size. Default is ``None``, in which case ``batch = n_resamples``
        (or ``batch = max(n_resamples, n)`` for ``method='BCa'``).
    method : {'percentile', 'basic', 'bca'}, default: ``'BCa'``
        Whether to return the 'percentile' bootstrap confidence interval
        (``'percentile'``), the 'reverse' or the bias-corrected and accelerated
        bootstrap confidence interval (``'BCa'``).
        Note that only ``'percentile'`` and ``'basic'`` support multi-sample
        statistics at this time.
    random_state : {None, int, `numpy.random.Generator`,
                    `numpy.random.RandomState`}, optional

        If `seed` is ``None`` (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``RandomState`` instance is used,
        seeded with `seed`.
        If `seed` is already a ``Generator`` or ``RandomState`` instance then
        that instance is used.

        Pseudorandom number generator state used to generate resamples.

    Returns
    -------
    res : BootstrapResult
        An object with attributes:

        confidence_interval : ConfidenceInterval
            The bootstrap confidence interval as an instance of
            `collections.namedtuple` with attributes `low` and `high`.
        standard_error : float or ndarray
            The bootstrap standard error, that is, the sample standard
            deviation of the bootstrap distribution

    References
    ----------
    .. [1] B. Efron and R. J. Tibshirani, An Introduction to the Bootstrap,
       Chapman & Hall/CRC, Boca Raton, FL, USA (1993)
    .. [2] Nathaniel E. Helwig, "Bootstrap Confidence Intervals",
       http://users.stat.umn.edu/~helwig/notes/bootci-Notes.pdf
    .. [3] Bootstrapping (statistics), Wikipedia,
       https://en.wikipedia.org/wiki/Bootstrapping_(statistics)

    Examples
    --------
    Suppose we have sampled data from an unknown distribution.

    >>> import numpy as np
    >>> rng = np.random.default_rng()
    >>> from scipy.stats import norm
    >>> dist = norm(loc=2, scale=4)  # our "unknown" distribution
    >>> data = dist.rvs(size=100, random_state=rng)

    We are interested int the standard deviation of the distribution.

    >>> std_true = dist.std()      # the true value of the statistic
    >>> print(std_true)
    4.0
    >>> std_sample = np.std(data)  # the sample statistic
    >>> print(std_sample)
    3.9460644295563863

    We can calculate a 90% confidence interval of the statistic using
    `bootstrap`.

    >>> from scipy.stats import bootstrap
    >>> data = (data,)  # samples must be in a sequence
    >>> res = bootstrap(data, np.std, confidence_level=0.9,
    ...                 random_state=rng)
    >>> print(res.confidence_interval)
    ConfidenceInterval(low=3.57655333533867, high=4.382043696342881)

    If we sample from the distribution 1000 times and form a bootstrap
    confidence interval for each sample, the confidence interval
    contains the true value of the statistic approximately 900 times.

    >>> n_trials = 1000
    >>> ci_contains_true_std = 0
    >>> for i in range(n_trials):
    ...    data = (dist.rvs(size=100, random_state=rng),)
    ...    ci = bootstrap(data, np.std, confidence_level=0.9, n_resamples=1000,
    ...                   random_state=rng).confidence_interval
    ...    if ci[0] < std_true < ci[1]:
    ...        ci_contains_true_std += 1
    >>> print(ci_contains_true_std)
    875

    Rather than writing a loop, we can also determine the confidence intervals
    for all 1000 samples at once.

    >>> data = (dist.rvs(size=(n_trials, 100), random_state=rng),)
    >>> res = bootstrap(data, np.std, axis=-1, confidence_level=0.9,
    ...                 n_resamples=1000, random_state=rng)
    >>> ci_l, ci_u = res.confidence_interval

    Here, `ci_l` and `ci_u` contain the confidence interval for each of the
    ``n_trials = 1000`` samples.

    >>> print(ci_l[995:])
    [3.77729695 3.75090233 3.45829131 3.34078217 3.48072829]
    >>> print(ci_u[995:])
    [4.88316666 4.86924034 4.32032996 4.2822427  4.59360598]

    And again, approximately 90% contain the true value, ``std_true = 4``.

    >>> print(np.sum((ci_l < std_true) & (std_true < ci_u)))
    900

    `bootstrap` can also be used to estimate confidence intervals of
    multi-sample statistics, including those calculated by hypothesis
    tests. `scipy.stats.mood` perform's Mood's test for equal scale parameters,
    and it returns two outputs: a statistic, and a p-value. To get a
    confidence interval for the test statistic, we first wrap
    `scipy.stats.mood` in a function that accepts two sample arguments,
    accepts an `axis` keyword argument, and returns only the statistic.

    >>> from scipy.stats import mood
    >>> def my_statistic(sample1, sample2, axis):
    ...     statistic, _ = mood(sample1, sample2, axis=-1)
    ...     return statistic

    Here, we use the 'percentile' method with the default 95% confidence level.

    >>> sample1 = norm.rvs(scale=1, size=100, random_state=rng)
    >>> sample2 = norm.rvs(scale=2, size=100, random_state=rng)
    >>> data = (sample1, sample2)
    >>> res = bootstrap(data, my_statistic, method='basic', random_state=rng)
    >>> print(mood(sample1, sample2)[0])  # element 0 is the statistic
    -5.521109549096542
    >>> print(res.confidence_interval)
    ConfidenceInterval(low=-7.255994487314675, high=-4.016202624747605)

    The bootstrap estimate of the standard error is also available.

    >>> print(res.standard_error)
    0.8344963846318795

    Paired-sample statistics work, too. For example, consider the Pearson
    correlation coefficient.

    >>> from scipy.stats import pearsonr
    >>> n = 100
    >>> x = np.linspace(0, 10, n)
    >>> y = x + rng.uniform(size=n)
    >>> print(pearsonr(x, y)[0])  # element 0 is the statistic
    0.9962357936065914

    We wrap `pearsonr` so that it returns only the statistic.

    >>> def my_statistic(x, y):
    ...     return pearsonr(x, y)[0]

    We call `bootstrap` using ``paired=True``.
    Also, since ``my_statistic`` isn't vectorized to calculate the statistic
    along a given axis, we pass in ``vectorized=False``.

    >>> res = bootstrap((x, y), my_statistic, vectorized=False, paired=True,
    ...                 random_state=rng)
    >>> print(res.confidence_interval)
    ConfidenceInterval(low=0.9950085825848624, high=0.9971212407917498)

    Né   r   )r/   r0   r   r   r
   r   r>   rG   )r   r9   r8   r&   c                 S   s   t j| |dd�S )Nr   )r3   Úqr   )r   r7   )r3   rY   r   r   r   Úpercentile_funÂ  s    z!bootstrap.<locals>.percentile_funéd   rF   )Zddofr   )rU   rV   )rT   r!   r"   r1   r?   r   r@   rD   r;   rW   r   Zstd)r   r   rN   rO   r   rP   r/   r&   rQ   r0   Úargsr8   r(   r)   r*   Zresampled_datar   Zresampler9   ÚintervalrZ   Zci_lZci_urB   r   r   r   Ú	bootstrapÄ   sF     _þÿ
ÿ

ÿr^   )N)NN)Únumpyr   Zscipy._lib._utilr   Zscipy.specialr   r   r   Zdataclassesr   Ú_commonr   Zscipy.stats.statsr	   r   r.   r1   r5   r;   rD   rT   ÚfieldsrW   r^   r   r   r   r   Ú<module>   s&   


P
þ