U
    f»{jB9  ã                   @   s‚   d dl Zd dlmZ d dlmZ ddlmZ d dd„Zd!dd„Z	dd„ Z
dd„ Zdd„ Zdd„ Zd"dd„Zd#dd„Zd$dd„ZdS )%é    N)Úreduce)Úascii_uppercaseé   )Ú_check_optionÚrelativec                 C   sl   t d|ddgƒ tj| ddd�}|dkrJ|dkr>|t |¡ n|}||7 }tj| dd�t || jd  ¡ S )aõ  Perform one-sample t-test.

    This is a modified version of :func:`scipy.stats.ttest_1samp` that avoids
    a (relatively) time-consuming p-value calculation, and can adjust
    for implausibly small variance values :footcite:`RidgwayEtAl2012`.

    Parameters
    ----------
    X : array
        Array to return t-values for.
    sigma : float
        The variance estimate will be given by ``var + sigma * max(var)`` or
        ``var + sigma``, depending on "method". By default this is 0 (no
        adjustment). See Notes for details.
    method : str
        If 'relative', the minimum variance estimate will be sigma * max(var),
        if 'absolute' the minimum variance estimate will be sigma.

    Returns
    -------
    t : array
        T-values, potentially adjusted using the hat method.

    Notes
    -----
    To use the "hat" adjustment method :footcite:`RidgwayEtAl2012`, a value
    of ``sigma=1e-3`` may be a reasonable choice.

    References
    ----------
    .. footbibliography::
    ÚmethodÚabsoluter   r   é   ©ÚaxisZddof©r   )r   ÚnpÚvarÚmaxÚmeanÚsqrtÚshape)ÚXÚsigmar   r   Úlimit© r   úS/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/stats/parametric.pyÚttest_1samp_no_p   s    !r   Tç        c              	   C   sP  t j| ddd�}t j|ddd�}| jd }|jd }|rv|| d }|d | |d |  | }	|	d| d|   }	nr|| }
|| }t jddd��2 |
| d |
d |d  |d |d    }W 5 Q R X t  t  |¡d|¡}|
| }	|dk�r|	|t  |	¡ 7 }	t  |	¡}t  | d¡t  |d¡ }t jddd�� t  	||¡}W 5 Q R X |S )	a­  Independent samples t-test without p calculation.

    This is a modified version of :func:`scipy.stats.ttest_ind`. It operates
    along the first axis. The ``sigma`` parameter provides an optional "hat"
    adjustment (see :func:`ttest_1samp_no_p` and :footcite:`RidgwayEtAl2012`).

    Parameters
    ----------
    a : array-like
        The first array.
    b : array-like
        The second array.
    equal_var : bool
        Assume equal variance. See :func:`scipy.stats.ttest_ind`.
    sigma : float
        The regularization. See :func:`ttest_1samp_no_p`.

    Returns
    -------
    t : array
        T values.

    References
    ----------
    .. footbibliography::
    r   r	   r
   g       @ç      ð?Úignore)ÚdivideÚinvalidr   )
r   r   r   ZerrstateÚwhereÚisnanr   r   r   r   )ÚaÚbZ	equal_varr   Zv1Zv2Zn1Zn2Údfr   Zvn1Zvn2ÚdenomÚdÚtr   r   r   Úttest_ind_no_p:   s*    

6

r&   c                  G   sò   t | ƒ}t dd„ | D ƒ¡}t |¡}tdd„ dd„ | D ƒƒ}dd„ | D ƒ}tdd„ |ƒd }d	d„ |D ƒ}||t|ƒ  }d
}	t| ƒD ]\}
}|	||
 ||
  7 }	qˆ|	|t|ƒ 8 }	||	 }|d }|| }|	t|ƒ }|t|ƒ }|| }|S )aÛ  Perform a 1-way ANOVA.

    The one-way ANOVA tests the null hypothesis that 2 or more groups have
    the same population mean. The test is applied to samples from two or
    more groups, possibly with differing sizes :footcite:`Lowry2014`.

    This is a modified version of :func:`scipy.stats.f_oneway` that avoids
    computing the associated p-value.

    Parameters
    ----------
    *args : array_like
        The sample measurements should be given as arguments.

    Returns
    -------
    F-value : float
        The computed F-value of the test.

    Notes
    -----
    The ANOVA test has important assumptions that must be satisfied in order
    for the associated p-value to be valid.

    1. The samples are independent
    2. Each sample is from a normally distributed population
    3. The population standard deviations of the groups are all equal. This
       property is known as homoscedasticity.

    If these assumptions are not true for a given set of data, it may still be
    possible to use the Kruskal-Wallis H-test (:func:`scipy.stats.kruskal`)
    although with some loss of power.

    The algorithm is from Heiman :footcite:`Heiman2002`, pp.394-7.

    References
    ----------
    .. footbibliography::
    c                 S   s   g | ]}t |ƒ‘qS r   )Úlen©Ú.0r    r   r   r   Ú
<listcomp>™   s     zf_oneway.<locals>.<listcomp>c                 S   s   | | S ©Nr   ©ÚxÚyr   r   r   Ú<lambda>›   ó    zf_oneway.<locals>.<lambda>c                 S   s   g | ]}t j|d  dd�‘qS )r   r   r   ©r   Úsumr(   r   r   r   r*   œ   s     c                 S   s   g | ]}t j|d d�‘qS )r   r   r1   r(   r   r   r   r*   �   s     c                 S   s   | | S r+   r   r,   r   r   r   r/   ž   r0   r   c                 S   s   g | ]}|d  ‘qS )r   r   )r)   Úsr   r   r   r*   Ÿ   s     r   r	   )r'   r   Úarrayr2   r   ÚfloatÚ	enumerate)ÚargsZ	n_classesZn_samples_per_classZ	n_samplesZ
ss_alldataZ	sums_argsZsquare_of_sums_alldataZsquare_of_sums_argsZsstotZssbnÚkÚ_ZsswnZdfbnZdfwnZmsbZmswÚfr   r   r   Úf_onewayp   s*    (
ÿr;   c                    sú  | t tƒkrtdƒ‚ttd| … ƒ‰ t|tƒr¸d|krHd|krHtdƒ‚npd|krbd|krbtdƒ‚nV|dkrpd}nHt |ƒd	ks„d|krŒ|g}n,d|kr | d¡}nd|krªntd
 |¡ƒ‚t|tƒrð‡ fdd„|D ƒ}t |ƒd	krðtd || ¡ƒ‚tt 	d|  d	 ¡ƒ}tƒ ‰|D ]X}t
|d	 | ƒ}| d	 t |d	k¡d  }‡ fdd„|D ƒ}| ¡  ˆ d |¡¡ �q|dk�s€t|tƒ�r†ˆ}n|}‡fdd„|D ƒ}	‡fdd„|	D ƒ‰t|tƒ�ròd|k�ròˆ | dd¡¡d	 }
ˆd|
… ‰|	d|
… }	|	ˆfS )zMap effects to indices.z)Maximum number of factors supported is 26NÚ*ú:z$Not "*" and ":" permitted in effectsú+z$Not "+" and ":" permitted in effectsÚallr	   z("{}" is not a valid option for "effects"c                    s   g | ]}|ˆ kr|‘qS r   r   ©r)   Úe©Úfactor_namesr   r   r*   Ç   s      z _map_effects.<locals>.<listcomp>zbEffect names: {} are not valid. They should the first `n_factors` ({}) characters from thealphabetr   r   c                    s   g | ]}ˆ | ‘qS r   r   r@   rB   r   r   r*   Ò   s     c                    s   g | ]}ˆ   |¡‘qS r   )Úindex©r)   Úsel©Únamesr   r   r*   Û   s     c                    s   g | ]}ˆ | ‘qS r   r   rE   rG   r   r   r*   Ü   s     )r'   r   Ú
ValueErrorÚlistÚ
isinstanceÚstrÚsplitÚformatr   ZarangeÚ_get_contrast_indicesr   ÚsortÚappendÚjoinrD   Úreplace)Ú	n_factorsÚeffectsZ	bad_namesÚindicesÚthis_effectÚcontrast_idxZ	this_codeZ	this_nameZeffects_Z	selectionZsel_indr   )rC   rH   r   Ú_map_effects®   sZ    


ÿ
 þ
rY   c                 C   s$   t  | |¡}t jdd„ |D ƒtd�S )z'Henson's factor coding, see num2binvec.c                 S   s   g | ]}t |ƒ‘qS r   )Úint)r)   Úir   r   r   r*   ì   s     z)_get_contrast_indices.<locals>.<listcomp>)Zdtype)r   Zbinary_reprr4   rZ   )Z
effect_idxrT   Zbinreprr   r   r   rO   é   s    rO   c                 c   sÐ   ddl m} g }t|ƒ}|D ]*}| t |dg¡|t |¡dd�g¡ q|D ]~}t|d |ƒ}|d ||d   }	td|ƒD ](}
||d |
  }t 	|	||
 | ¡}	q|tj
 |	¡}|| d  }|	||fV  qLdS )zSet up contrasts.r   )Údetrendr	   Zconstant)ÚtypeN)Zscipy.signalr\   r'   rQ   r   ZonesÚeyerO   ÚrangeZkronZlinalgZmatrix_rank)Ú
n_subjectsÚfactor_levelsÚeffect_picksr\   ÚscrT   Zn_levelsrW   rX   Úc_Z
i_contrastZthis_contrastÚdf1Údf2r   r   r   Ú_iter_contrastsï   s     ÿrg   úA*Bçš™™™™™©?c           
      C   sh   ddl m} tt|ƒ|ƒ\}}g }t| ||ƒD ] \}}}	| |||	ƒ |¡¡ q.t|ƒdkr`|S |d S )al  Compute F-value thresholds for a two-way ANOVA.

    Parameters
    ----------
    n_subjects : int
        The number of subjects to be analyzed.
    factor_levels : list-like
        The number of levels per factor.
    effects : str
        A string denoting the effect to be returned. The following
        mapping is currently supported:

            * ``'A'``: main effect of A
            * ``'B'``: main effect of B
            * ``'A:B'``: interaction effect
            * ``'A+B'``: both main effects
            * ``'A*B'``: all three effects

    pvalue : float
        The p-value to be thresholded.

    Returns
    -------
    F_threshold : list | float
        List of F-values for each effect if the number of effects
        requested > 2, else float.

    See Also
    --------
    f_oneway
    f_mway_rm

    Notes
    -----
    .. versionadded:: 0.10
    r   ©r:   r	   )Úscipy.statsr:   rY   r'   rg   rQ   Zisf)
r`   ra   rU   Zpvaluer:   rb   r9   ZF_thresholdre   rf   r   r   r   Úf_threshold_mway_rm	  s    &ÿrl   r?   Fc              	      s&  ddl m} d‰| jdkr4| dd…dd…tjf } nB| jdkrv| jdd… ‰|  | jd | jd t | jdd… ¡¡} tt	|ƒ|ƒ\}}| jd }| jd }	t 
| d¡} g g  }
}t|	||ƒD �]N\}}}t | |¡}tj|dd�dd…tjdd…f }tjtj|| dd�dd�}tjtj|| dd�dd�| ||  }|| }|
 |¡ |�r¤t d	d
„ |D ƒ¡}t dd
„ |D ƒ¡d |tjtj|| dd�dd�  }|‰ t |¡| t |¡|  }}|�râ‡ fdd
„||fD ƒ\}}|�rú|||ƒ |¡}n
t d¡}| |¡ q¾‡fdd
„|
|fD ƒS )a+  Compute M-way repeated measures ANOVA for fully balanced designs.

    Parameters
    ----------
    data : ndarray
        3D array where the first two dimensions are compliant
        with a subjects X conditions scheme where the first
        factor repeats slowest::

                        A1B1 A1B2 A2B1 A2B2
            subject 1   1.34 2.53 0.97 1.74
            subject ... .... .... .... ....
            subject k   2.45 7.90 3.09 4.76

        The last dimensions is thought to carry the observations
        for mass univariate analysis.
    factor_levels : list-like
        The number of levels per factor.
    effects : str | list
        A string denoting the effect to be returned. The following
        mapping is currently supported (example with 2 factors):

            * ``'A'``: main effect of A
            * ``'B'``: main effect of B
            * ``'A:B'``: interaction effect
            * ``'A+B'``: both main effects
            * ``'A*B'``: all three effects
            * ``'all'``: all effects (equals 'A*B' in a 2 way design)

        If list, effect names are used: ``['A', 'B', 'A:B']``.
    correction : bool
        The correction method to be employed if one factor has more than two
        levels. If True, sphericity correction using the Greenhouse-Geisser
        method will be applied.
    return_pvals : bool
        If True, return p-values corresponding to F-values.

    Returns
    -------
    F_vals : ndarray
        An array of F-statistics with length corresponding to the number
        of effects estimated. The shape depends on the number of effects
        estimated.
    p_vals : ndarray
        If not requested via return_pvals, defaults to an empty array.

    See Also
    --------
    f_oneway
    f_threshold_mway_rm

    Notes
    -----
    .. versionadded:: 0.10
    r   rj   )éÿÿÿÿr   Né   r	   r   c                 S   s   g | ]}t  |j|¡‘qS r   )r   ÚdotÚT)r)   Zy_r   r   r   r*   �  s     zf_mway_rm.<locals>.<listcomp>c                 S   s   g | ]}t  |¡‘qS r   )r   Útrace©r)   Zvvr   r   r   r*   �  s     c                    s(   g | ] }t  |d d d …f ˆ  d¡‘qS )Nr   )r   Úmaximum)r)   r$   )Úepsr   r   r*   ™  s     c              	      s*   g | ]"}t  t  ‡ fd d„|D ƒ¡¡‘qS )c                    s   g | ]}|  ˆ ¡‘qS r   )Úreshape)r)   Úv©Úout_reshaper   r   r*   ¢  s     z(f_mway_rm.<locals>.<listcomp>.<listcomp>)r   ZsqueezeZasarrayrr   rw   r   r   r*   ¢  s   ÿ)rk   r:   Úndimr   Znewaxisr   ru   ÚprodrY   r'   Zrollaxisrg   ro   r   r2   rQ   r4   ZzerosZsfÚempty)Údatara   rU   Z
correctionZreturn_pvalsr:   rb   r9   Zn_obsZn_replicationsZfvaluesZpvaluesrd   re   rf   r.   r!   ÚssZmseZfvalsrv   Zpvalsr   )rt   rx   r   Ú	f_mway_rm:  sR    9

  ÿ


ÿ"(
ÿ

ÿr~   çffffffî?c                 C   s^   |   d¡}t| ƒdk r,t |tj¡}||fS ddlm} | | d¡}|jj	|||| j
d d�S )z=Calculate the `ci`% parametric confidence interval for `arr`.r   r   )Ústats)ÚlocÚscaler"   )r   r'   r   Z	full_likeÚnanZscipyr€   Zsemr%   Úintervalr   )ZarrÚcir   r   r€   r   r   r   Ú_parametric_ci¦  s    
r†   )r   r   )Tr   )rh   ri   )r?   FT)r   )Únumpyr   Ú	functoolsr   Ústringr   Úutilsr   r   r&   r;   rY   rO   rg   rl   r~   r†   r   r   r   r   Ú<module>   s"   
)
6>;  ÿ
1    ÿ
l