U
    f»{jÄ…  ã                   @   sD  d dl ZddlmZmZmZ ddlmZmZm	Z	m
Z
 ddlmZ ddlmZ ddlmZ ddlmZmZmZmZmZmZmZmZ dd	lmZ d
dlmZmZmZm Z m!Z!m"Z"m#Z#m$Z$ dd„ Z%dd„ Z&d2dd„Z'dd„ Z(dd„ Z)ed3dd„ƒZ*dd„ Z+ed4dd„ƒZ,ed5dd„ƒZ-ed6d'd(„ƒZ.d)d*„ Z/ed7d.d/„ƒZ0ed0d1„ ƒZ1dS )8é    Né   )ÚSourceEstimateÚ_BaseSourceEstimateÚ	_make_stc)Úcombine_xyzÚ_prepare_forwardÚ_check_referenceÚ_log_exp_var)Úis_fixed_orient)Úpick_channels_evoked)Údeactivate_proj)ÚloggerÚverboseÚ_check_depthÚ_check_optionÚsum_squaredÚ_validate_typeÚcheck_random_stateÚwarn)ÚDipoleé   )Úmixed_norm_solverÚiterative_mixed_norm_solverÚ_PhiÚtf_mixed_norm_solverÚiterative_tf_mixed_norm_solverÚ
norm_l2infÚnorm_epsilon_infÚgroups_norm2c                 C   s,   t d| ddgƒ | dkr(t|ƒr(tdƒ‚dS )zCheck pick_ori.Úpick_oriNÚvectorzOpick_ori="vector" cannot be combined with a fixed orientation forward solution.)r   r
   Ú
ValueError)r   Úforward© r#   ú^/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/inverse_sparse/mxne_inverse.pyÚ
_check_ori   s    r%   c           	      C   s2  d }t |tƒr$tjt |j¡dd�}t |¡}||krFtd||f ƒ‚|| }|| }t| ƒrbdnd}t t 	||dg¡j
¡}t|ƒ|jd krªtdt|ƒ|jd f ƒ‚t|jƒdkrÂ||9 }n||d d …d f 9 }||d d d …f 9 }|d k	�r(||k}|d d …|f }t |¡| }t d| ¡ |||fS )Nr   ©Úaxisz#weights_min > weights_max (%s > %s)é   z5weights do not have the correct dimension  (%d != %d)z#Reducing source space to %d sources)Ú
isinstancer   ÚnpÚmaxÚabsÚdatar!   r
   ÚravelZtileÚTÚlenÚshapeÚsumr   Úinfo)	r"   ÚgainÚsource_weightingÚweightsÚweights_minÚmaskZweights_maxÚn_dip_per_posÚ	n_sourcesr#   r#   r$   Ú_prepare_weights   s4    

ÿÿ

r;   c	              	   C   sp   t |dƒ}t| ||d|||fddi|—Ž\	} }	}
}}}}}}|d krJd }nt| |
|||ƒ\}
}}| |
|	|||fS )NZdepth_sparseÚautoZuse_cpsT)r   r   r;   )r"   r3   Ú	noise_covÚpcaÚdepthÚlooseÚrankr6   r7   Ú	gain_infor4   Ú_r5   Úwhitenerr8   r#   r#   r$   Ú_prepare_gain=   s"    
ÿÿÿ    ÿ
rE   c                 C   s   | || d d …d f 9 } | S ©Nr#   )ÚXr5   Ú
active_setr#   r#   r$   Ú_reapply_source_weightingM   s    rI   c              	      s  ‡ fdd„|d D ƒ}|  ¡ }t||d d�}|  ¡ }t ˆ d d |d d …f d d …|f |¡|_tƒ }tƒ }	|jd D ]"}
|
d r’| |
¡ qz|	 |
¡ qzt|ƒd	krð|j 	¡ � t
|d
dd�|jd< W 5 Q R X |jdd� |j|	ddd� | j|j8  _|S )Nc                    s   g | ]}ˆ d  d   |¡‘qS )ÚsolZ	row_names©Úindex)Ú.0Úc©r"   r#   r$   Ú
<listcomp>T   s     z%_compute_residual.<locals>.<listcomp>Úch_names)ÚincluderJ   r-   ZprojsZactiver   TF)Úcopyr   )r   )Zremove_existingr   )rS   r   r*   Údotr-   Úlistr3   Úappendr0   Z_unlockr   Z
apply_projZadd_proj)r"   ÚevokedrG   rH   r3   ÚselÚresidualZr_tmpZactive_projsZnon_active_projsÚpr#   rO   r$   Ú_compute_residualR   s(    .ÿr[   Fc              
   C   s  |d }d}	t |ƒs@|dkr0t d¡ t| ƒ} nd}	t |d¡}|sTt |¡d }
n|}
t |ƒrddnd	}|dkr~t |
| ¡}
|d
 }g }d}|D ]J}|t|d ƒ }|
||
k|
|k @  }||8 }|d | }|}| 	|¡ q’||
 }t
| ||j|||d d |	|d�S )NÚ	source_nnFr    z#combining the current components...T)éÿÿÿÿr(   r(   r   r   r(   ÚsrcÚvertnoZsubject_his_id)r    r\   )r
   r   r3   r   r*   ZreshapeÚwhereÚuniquer0   rV   r   Úkind)rG   rH   r"   ÚtminÚtstepÚactive_is_idxr   r   r\   r    Ú
active_idxr9   r^   ÚverticesZn_points_so_farZthis_srcZthis_n_points_so_farZthis_active_idxZthis_vertnor#   r#   r$   Ú_make_sparse_stcp   sJ    

ÿ     
 þrh   c                 C   sö  | j |j   kr$|j   kr$dks:n t| j |j |j fƒ‚|j| jd |jd fksXt‚| jd |jd kspt‚| |  ¡  jjddd�}tj||dk< || }| j|jks®t‚| | }|jd | jd ksÚt|j| jfƒ‚tjj	|dd�\}}}|jd dk�r|d d …||d d kf }|j
|  }	|j
| }
|j
| d d …d d …tjf | }tjj|ddd	�}d
||dk< || }tjj|	d d …tjf | dd�d }tjj|
d d …tjf | dd�d }d||  | }|j|jk�sòt|j|jfƒ‚|S )Nr   r   r   T)ÚkeepdimsF©Zfull_matricesg�íµ ÷Æ°>)r'   ri   ç      ð?r&   éd   )ÚndimÚAssertionErrorr1   ZconjÚrealr2   r*   ÚinfÚlinalgÚsvdr/   ÚnewaxisÚnorm)ÚMrG   r4   rt   ZM_estÚresÚUÚsrC   Zfit_orthZres_orthÚwZw_normZfit_backZres_backZgof_backr#   r#   r$   Ú
_split_gof—   s.    :$

"&&rz   c	              
   C   s†  ||t  | jd ¡  }	|s,t  |¡d }
n|}
|j|jd t|	ƒfksLt‚|jd t|
ƒ  krp| jd ksvn t‚t|| |ƒ}|jt|
ƒt|	ƒfksœt‚| jd t|
ƒdt|
ƒ fks¾t‚t|ƒrÊdnd}|dk�r2|
| }
t j|
dd�\}}| 	¡  |
| }
t|
ƒ|t|	ƒf|_| 
d¡}|dk  ¡ �s2t‚|jt|
ƒt|	ƒfk�sNt‚g }t|
ƒD �]$\}}|d | t jd d …f }|jt|	ƒdd�}| || |d | … }|dk�rè|d }|d	 | t jd d …f }|jt|	ƒdd�}n||d
 �rt  |d	 || |d | … j|¡}t jj|dd�}t  t|	ƒdf¡}|d d …|dkf ||dk  j||dk< | t|	||||| ƒ¡ �qZ|S )Nr   r   r(   T)Zreturn_indexrl   Ú	source_rrr&   r\   Zsurf_oriç        )r*   Zaranger1   r`   r0   rn   rz   r
   ra   Úsortr2   ÚallÚ	enumeraters   ÚrepeatrT   r/   rq   rt   ÚzerosrV   r   )rG   rH   r"   rc   rd   ru   Úgain_activere   r   Útimesrf   Z	gof_splitr9   rC   ZkeepÚdipolesÚkZi_dipZi_posZX_Ú	amplitudeZi_orir#   r#   r$   Ú_make_dipoles_sparseº   sT    *"




 
ÿÿ
ÿr‡   c                 C   s–  t  d¡ t| tƒr| g} t| tƒs4tdt| ƒ ƒ‚| d jd }| d jd | }t 	t
| ƒt
| d jƒf¡}tjdd„ |D ƒdd�}t
|d d ƒ}tƒ }tƒ }	tt
| ƒƒD ]¢}
t | |
 j| |
 jd k¡sÚtd	ƒ‚| |
 j||
< tj|| |
 jd kdd�}t |¡d d }||k �r8| |d d | ¡ q°|	 |d d ||  ¡ q°t |¡ t¡t |	¡ t¡g}t|||||jd
�}t  d¡ |S )ay  Convert a list of spatio-temporal dipoles into a SourceEstimate.

    Parameters
    ----------
    dipoles : Dipole | list of instances of Dipole
        The dipoles to convert.
    src : instance of SourceSpaces
        The source space used to generate the forward operator.
    %(verbose)s

    Returns
    -------
    stc : SourceEstimate
        The source estimate.
    z)Converting dipoles into a SourceEstimate.zODipoles must be an instance of Dipole or a list of instances of Dipole. Got %s!r   r   c                 S   s$   g | ]}|d  |d dd…f ‘qS )Zrrr_   Nr#   )rM   Z_srcr#   r#   r$   rP   	  s     z)make_stc_from_dipoles.<locals>.<listcomp>r&   r_   z9Only dipoles with fixed position over time are supported!)rg   rc   rd   Úsubjectú[done])r   r3   r)   r   rU   r!   Útyperƒ   r*   r�   r0   ÚconcatenateÚranger~   Úposr†   r`   rV   ÚarrayÚastypeÚintr   Z_subject)r„   r^   r   rc   rd   rG   r{   Zn_lh_pointsZ	lh_vertnoZ	rh_vertnoÚiÚidxrg   Zstcr#   r#   r$   Úmake_stc_from_dipolesî   sB    


þÿ
ÿ
ÿ
r“   Úsurer<   çš™™™™™é?é¸  ç-Cëâ6?é
   Tr|   c           4         sð  ddl m} t|dtfdƒ t|tƒr4td|dƒ n"d|  krHdk sVn td| ƒ‚|d	k rjtd
| ƒ‚|dkr~td| ƒ‚t|tjt	fƒs¦|dks¦tdt
|ƒ ƒ‚t|tƒrÖ|dkrÖt|tƒrÖ|dkrÖtd| ƒ‚d}tˆt	ƒsêˆg‰tˆd ƒ ˆd j‰ t‡ ‡fdd„td	tˆƒƒD ƒƒ�s,tdƒ‚t|ˆd j|||||||ƒ	\}}}}}}t||ƒ ‡ fdd„|d D ƒ‰tj‡fdd„ˆD ƒd	d�}t d¡ t ||¡}|
�r|j|dd�\}} }!t|
tƒ�st|
tƒ�r|dd…d|
…f }| d|
… } |!d|
… }!||  }|t|ƒ9 }t|ƒ�r(d	nd}"tt |j|¡|"dd�}#|#d9 }#||# }||# }|dk�rÊ|}$t|tƒ�r�|dk�r�tjdd d!d"�}$t|||$d	|||||"||	|||d#�\}%}&}'t d$|' ¡ nV|d	k�rút |||||||"|	|||d%�\}%}&}(n&t!|||||||"||	|||d&�\}%}&}(|
�r>t |%|!¡}%t ||!¡}|dd…|&f })|dk	�rxtj"t|ƒtd'�}*|&|*|< |*}&~*|& #¡ dk�ršt$d(ƒ t %|¡}+n2t&|%||&ƒ}%d	||dk< |)||&  })~t |)|%¡}+t	ƒ },t	ƒ }-d}.ˆD ]º}/|/j'd }0d)|/jd*  }1|%dd…|.|.t|/j'ƒ …f }2|�rPt(|2|&||0|1|dd…|.|.t|/j'ƒ …f |)ƒ}3nt)|2|&||0|1|d+�}3|, *|3¡ |.t|/j'ƒ7 }.|�rà|- *t+||/|2|&|ƒ¡ �qàt,||+d,d-� t d.¡ t|,ƒd	k�rÚ|,d }3|�rÞ|-d }-n|,}3|�rì|3|-f}3|3S )/aÎ  Mixed-norm estimate (MxNE) and iterative reweighted MxNE (irMxNE).

    Compute L1/L2 mixed-norm solution :footcite:`GramfortEtAl2012` or L0.5/L2
    :footcite:`StrohmeierEtAl2016` mixed-norm solution on evoked data.

    Parameters
    ----------
    evoked : instance of Evoked or list of instances of Evoked
        Evoked data to invert.
    forward : dict
        Forward operator.
    noise_cov : instance of Covariance
        Noise covariance to compute whitener.
    alpha : float | str
        Regularization parameter. If float it should be in the range [0, 100):
        0 means no regularization, 100 would give 0 active dipole.
        If ``'sure'`` (default), the SURE method from
        :footcite:`DeledalleEtAl2014` will be used.

        .. versionchanged:: 0.24
          The default was changed to ``'sure'``.
    %(loose)s
    %(depth)s
    maxit : int
        Maximum number of iterations.
    tol : float
        Tolerance parameter.
    active_set_size : int | None
        Size of active set increment. If None, no active set strategy is used.
    debias : bool
        Remove coefficient amplitude bias due to L1 penalty.
    time_pca : bool or int
        If True the rank of the concatenated epochs is reduced to
        its true dimension. If is 'int' the rank is limited to this value.
    weights : None | array | SourceEstimate
        Weight for penalty in mixed_norm. Can be None, a
        1d array with shape (n_sources,), or a SourceEstimate (e.g. obtained
        with wMNE, dSPM, or fMRI).
    weights_min : float
        Do not consider in the estimation sources for which weights
        is less than weights_min.
    solver : 'cd' | 'bcd' | 'auto'
        The algorithm to use for the optimization. 'cd' uses
        coordinate descent, and 'bcd' applies block coordinate descent.
        'cd' is only available for fixed orientation.
    n_mxne_iter : int
        The number of MxNE iterations. If > 1, iterative reweighting
        is applied.
    return_residual : bool
        If True, the residual is returned as an Evoked instance.
    return_as_dipoles : bool
        If True, the sources are returned as a list of Dipole instances.
    dgap_freq : int or np.inf
        The duality gap is evaluated every dgap_freq iterations. Ignored if
        solver is 'cd'.
    %(rank_none)s

        .. versionadded:: 0.18
    %(pick_ori)s
    sure_alpha_grid : array | str
        If ``'auto'`` (default), the SURE is evaluated along 15 uniformly
        distributed alphas between alpha_max and 0.1 * alpha_max. If array, the
        grid is directly specified. Ignored if alpha is not "sure".

        .. versionadded:: 0.24
    random_state : int | None
        The random state used in a random number generator for delta and
        epsilon used for the SURE computation. Defaults to None.

        .. versionadded:: 0.24
    %(verbose)s

    Returns
    -------
    stc : SourceEstimate | list of SourceEstimate
        Source time courses for each evoked data passed as input.
    residual : instance of Evoked
        The residual a.k.a. data not explained by the sources.
        Only returned if return_residual is True.

    See Also
    --------
    tf_mixed_norm

    References
    ----------
    .. footbibliography::
    r   )rq   ÚnumericÚalpha)r”   r|   rl   z@If not equal to "sure" alpha must be in [0, 100). Got alpha = %sr   zJMxNE has to be computed at least 1 time. Requires n_mxne_iter >= 1, got %dú8dgap_freq must be a positive integer. Got dgap_freq = %sr<   z?If not equal to "auto" sure_alpha_grid must be an array. Got %sr”   zFIf sure_alpha_grid is manually specified, alpha must be "sure". Got %sTc                 3   s   | ]}ˆ ˆ| j kV  qd S rF   )rQ   )rM   r‘   )Úall_ch_namesrW   r#   r$   Ú	<genexpr>œ  s   ÿzmixed_norm.<locals>.<genexpr>z2All the datasets must have the same good channels.c                    s   g | ]}ˆ   |¡‘qS r#   rK   ©rM   Úname©rœ   r#   r$   rP   ¥  s     zmixed_norm.<locals>.<listcomp>rQ   c                    s   g | ]}|j ˆ  ‘qS r#   )r-   )rM   Úe)rX   r#   r$   rP   ¦  s     r&   úWhitening data matrix.Frj   Nr(   )rS   ç{®Gáz„?r˜   é   )Únum)ÚsigmaÚrandom_stateÚn_mxne_iterÚmaxitÚtolÚn_orientÚactive_set_sizeÚdebiasÚsolverÚ	dgap_freqr   zSelected alpha: %s)r©   rª   r¬   r«   r­   r®   r¯   r   )r©   rª   r«   r¬   r­   r®   r¯   r   ©Zdtypez*No active dipoles found. alpha is too big.rk   Úsfreq©r   Ú )Úprefixr‰   )-Zscipyrq   r   Ústrr)   r   r!   r*   ZndarrayrU   rŠ   Ú	Exceptionr   rQ   r~   rŒ   r0   rE   r3   r%   r‹   r   rT   rr   Úboolr�   r   r
   r   r/   Z	geomspaceÚ_compute_mxne_surer   r   r�   r2   r   Z
zeros_likerI   rƒ   r‡   rh   rV   r[   r	   )4rW   r"   r=   rš   r@   r?   r©   rª   r¬   r­   Ztime_pcar6   r7   r®   r¨   Úreturn_residualÚreturn_as_dipolesr¯   rA   r   Zsure_alpha_gridr§   r   rq   r>   r4   rB   rD   r5   r8   ru   rw   rx   ZVhr9   Ú	alpha_maxÚ
alpha_gridrG   rH   Úbest_alpha_ÚEr‚   Úactive_set_tmpZ
M_estimateZoutsrY   Zcntr¡   rc   rd   ZXeÚoutr#   )rœ   rW   rX   r$   Ú
mixed_norm!  s^   _
ÿÿÿÿÿÿÿÿ

ÿ
       þ


          ü
       ü        ü

    ý     ÿ
ÿ


rÁ   c                 C   sÂ   t |ttfƒrt|ƒ }}n|\}}|  ¡ } t| jd ƒ}t|| ƒ}t|| ƒ}t |d ¡d|… }t |d ¡| d… }tj|t t	| j
ƒ| | ¡|f }|  j|ddd…f 9  _| S )z Window evoked (size in seconds).r±   r   N)r)   Úfloatr�   rS   r3   r*   ZhanningZr_Zonesr0   rƒ   r-   )rW   ÚsizeZlsizeZrsizer±   ZlhannZrhannÚwindowr#   r#   r$   Ú_window_evoked  s    $rÅ   é@   é   ç{®Gáz”?c           .         s  t | ƒ | j‰ | j}d|  kr(dk s6n td| ƒ‚d|  krJdksXn td| ƒ‚|d|  }|| }|dk r€td| ƒ‚|dkr”td| ƒ‚t |¡}t |¡}t|ƒt|ƒkrÈtd	||f ƒ‚t|| j||	|||||ƒ	\}}}}}}t||ƒ t	|ƒ�rdnd
}|dk	�rt
| |ƒ} ‡ fdd„|d D ƒ} | j|  }!t d¡ t ||!¡}!t |!jd | t¡ ¡ t¡}"|d d }#|"|# }$t|||$| jjd ƒ}%|t|!ƒ9 }t||!|%||ƒ}&|&d9 }&||& }||& }|dk�rt|!|||||||||||
d�\}'}(})n(t|!||||||||||||
d�\}'}(})|( ¡ dk�rBtdƒ‚|dd…|(f }*|dk	�r|tjt|ƒtd�}+|(|+|< |+}(~+t|'||(ƒ}'|*||(  }*|�rªt|| |'|(|ƒ},|�rÔt|'|(|| jd d|d  |!|*ƒ}-n"t |'|(|| jd d|d  |d�}-t d¡ |�r|-|,f}-|-S )am  Time-Frequency Mixed-norm estimate (TF-MxNE).

    Compute L1/L2 + L1 mixed-norm solution on time-frequency
    dictionary. Works with evoked data
    :footcite:`GramfortEtAl2013b,GramfortEtAl2011`.

    Parameters
    ----------
    evoked : instance of Evoked
        Evoked data to invert.
    forward : dict
        Forward operator.
    noise_cov : instance of Covariance
        Noise covariance to compute whitener.
    %(loose)s
    %(depth)s
    maxit : int
        Maximum number of iterations.
    tol : float
        Tolerance parameter.
    weights : None | array | SourceEstimate
        Weight for penalty in mixed_norm. Can be None or
        1d array of length n_sources or a SourceEstimate e.g. obtained
        with wMNE or dSPM or fMRI.
    weights_min : float
        Do not consider in the estimation sources for which weights
        is less than weights_min.
    pca : bool
        If True the rank of the data is reduced to true dimension.
    debias : bool
        Remove coefficient amplitude bias due to L1 penalty.
    wsize : int or array-like
        Length of the STFT window in samples (must be a multiple of 4).
        If an array is passed, multiple TF dictionaries are used (each having
        its own wsize and tstep) and each entry of wsize must be a multiple
        of 4. See :footcite:`BekhtiEtAl2016`.
    tstep : int or array-like
        Step between successive windows in samples (must be a multiple of 2,
        a divider of wsize and smaller than wsize/2) (default: wsize/2).
        If an array is passed, multiple TF dictionaries are used (each having
        its own wsize and tstep), and each entry of tstep must be a multiple
        of 2 and divide the corresponding entry of wsize. See
        :footcite:`BekhtiEtAl2016`.
    window : float or (float, float)
        Length of time window used to take care of edge artifacts in seconds.
        It can be one float or float if the values are different for left
        and right window length.
    return_residual : bool
        If True, the residual is returned as an Evoked instance.
    return_as_dipoles : bool
        If True, the sources are returned as a list of Dipole instances.
    alpha : float in [0, 100) or None
        Overall regularization parameter.
        If alpha and l1_ratio are not None, alpha_space and alpha_time are
        overridden by alpha * alpha_max * (1. - l1_ratio) and alpha * alpha_max
        * l1_ratio. 0 means no regularization, 100 would give 0 active dipole.
    l1_ratio : float in [0, 1] or None
        Proportion of temporal regularization.
        If l1_ratio and alpha are not None, alpha_space and alpha_time are
        overridden by alpha * alpha_max * (1. - l1_ratio) and alpha * alpha_max
        * l1_ratio. 0 means no time regularization a.k.a. MxNE.
    dgap_freq : int or np.inf
        The duality gap is evaluated every dgap_freq iterations.
    %(rank_none)s

        .. versionadded:: 0.18
    %(pick_ori)s
    n_tfmxne_iter : int
        Number of TF-MxNE iterations. If > 1, iterative reweighting is applied.
    %(verbose)s

    Returns
    -------
    stc : instance of SourceEstimate
        Source time courses.
    residual : instance of Evoked
        The residual a.k.a. data not explained by the sources.
        Only returned if return_residual is True.

    See Also
    --------
    mixed_norm

    References
    ----------
    .. footbibliography::
    r|   g      Y@z)alpha must be in [0, 100). Got alpha = %srk   z3l1_ratio must be in range [0, 1]. Got l1_ratio = %sr   zOTF-MxNE has to be computed at least 1 time. Requires n_tfmxne_iter >= 1, got %sr›   zWThe same number of window sizes and steps must be passed. Got tstep = %s and wsize = %sr(   Nc                    s   g | ]}ˆ   |¡‘qS r#   rK   rž   r    r#   r$   rP   ©  s     z!tf_mixed_norm.<locals>.<listcomp>rQ   r¢   r   r£   )Úwsizerd   r©   rª   r   r«   r¯   r­   )	rÉ   rd   Ún_tfmxne_iterr©   rª   r   r«   r¯   r­   r   z<No active dipoles found. alpha_space/alpha_time are too big.r°   r±   r²   r‰   )!r   rQ   r3   r!   r*   Z
atleast_1dr0   rE   r%   r
   rÅ   r-   r   rT   Úceilr1   r�   rÂ   r�   r   r   r   r   r   r2   r¶   r�   r·   rI   r[   r‡   rƒ   rh   ).rW   r"   r=   r@   r?   r©   rª   r6   r7   r>   r­   rÉ   rd   rÄ   r¹   rº   rš   Zl1_ratior¯   rA   r   rÊ   r   r3   Zalpha_spaceZ
alpha_timer4   rB   rD   r5   r8   r9   rX   ru   Zn_stepsZn_freqsZn_coefsÚphir»   rG   rH   r¾   r‚   r¿   rY   rÀ   r#   r    r$   Útf_mixed_norm"  sú    _ÿÿÿÿ

þ       þ




 
         ý          ý
    ÿ    
 þ    
þ
rÍ   c              	      s<  ‡
fdd„‰‡‡
fdd„‰d‡‡‡‡‡‡
‡‡fdd„	‰ ‡ ‡‡‡	fdd	„}d
d„ }t  tˆƒ¡}t|ƒ}d| | jd d  }|j| jŽ }|ˆ| ||ƒ\}}}t d¡ tt	||ƒƒD ]B\}\}}|||ˆ| |||ƒ||< |r´t dˆ| || f ¡ q´ˆt  
|¡ }|t  
|¡ }|t  
|¡ }||dd…f }|||fS )a›  Stein Unbiased Risk Estimator (SURE).

    Implements the finite-difference Monte-Carlo approximation
    of the SURE for Multi-Task LASSO.

    See reference :footcite:`DeledalleEtAl2014`.

    Parameters
    ----------
    M : array, shape (n_sensors, n_times)
        The data.
    gain : array, shape (n_sensors, n_dipoles)
        The gain matrix a.k.a. lead field.
    alpha_grid : array, shape (n_alphas,)
        The grid of alphas used to evaluate the SURE.
    sigma : float
        The true or estimated noise level in the data. Usually 1 if the data
        has been previously whitened using MNE whitener.
    n_mxne_iter : int
        The number of MxNE iterations. If > 1, iterative reweighting is
        applied.
    maxit : int
        Maximum number of iterations.
    tol : float
        Tolerance parameter.
    n_orient : int
        The number of orientation (1 : fixed or 3 : free or loose).
    active_set_size : int
        Size of active set increase at each iteration.
    debias : bool
        Debias source estimates.
    solver : 'cd' | 'bcd' | 'auto'
        The algorithm to use for the optimization.
    dgap_freq : int or np.inf
        The duality gap is evaluated every dgap_freq iterations.
    random_state : int | None
        The random state used in a random number generator for delta and
        epsilon used for the SURE computation.

    Returns
    -------
    X : array, shape (n_active, n_times)
        Coefficient matrix.
    active_set : array, shape (n_dipoles,)
        Array of indices of non-zero coefficients.
    best_alpha_ : float
        Alpha that minimizes the SURE.

    References
    ----------
    .. footbibliography::
    c                    s   t  t  t|  ¡ ˆ ƒ¡¡S rF   )r*   Úsqrtr   rS   ©ry   )r«   r#   r$   Úg$  s    z_compute_mxne_sure.<locals>.gc                    s   dt  ˆ | ƒˆ¡ ¡  S )Ng       @)r*   r€   r.   rÏ   )rÐ   r«   r#   r$   Úgprime'  s    z"_compute_mxne_sure.<locals>.gprimeNc           	         sb   |dkr2t |ˆ| ˆˆˆ ˆˆˆˆ||dd�\}}}n(t|ˆ| |ˆˆˆˆ ˆˆˆ|dd�\}}}||fS )Nr   F)
r©   rª   r¬   r«   r­   r®   r¯   Zactive_set_initÚX_initr   )	r©   rª   r«   r¬   r­   r®   r¯   Zweight_initr   )r   r   )	rš   ru   r¨   Zas_initrÒ   Úw_initrG   rH   rC   )r¬   r­   r¯   r4   r©   r«   r®   rª   r#   r$   Ú_run_solver*  s@             ü         üz'_compute_mxne_sure.<locals>._run_solverc                    sÜ  t  tˆƒ| jd |jd f¡}t  tˆƒ| jd |jd f¡}g g  }}|||  }t d¡ tˆƒD ]r\}	}
t d|
 ¡ ˆ |
|dƒ\}}ˆ |
|dƒ\}}|||	 |d d …f< |||	 |d d …f< | |¡ | |¡ qhˆdkrî|||fS | ¡ }| ¡ }t d¡ tˆƒD ]¼\}	}
t d|
 ¡ ||	  	¡ dk�rxˆ||	 ƒ}ˆ |
|ˆd |d�\}}|||	 |d d …f< |||	< ||	  	¡ dk�rˆ||	 ƒ}ˆ |
|ˆd |d�\}}|||	 |d d …f< |||	< �q|||fS d S )Nr   zWarm starting...z	alpha: %szFitting SURE on grid.r   )rÓ   )
r*   r�   r0   r1   r   r3   r   rV   rS   r2   )r4   ru   ÚepsÚdeltaZcoefs_grid_1_0Zcoefs_grid_2_0Úactive_setsZactive_sets_epsZM_epsÚjrš   rG   Za_setZX_epsZ	a_set_epsÚcoefs_grid_1Úcoefs_grid_2ry   Zw_eps)rÔ   r¼   rÑ   r¨   r#   r$   Ú_fit_on_grid:  sH      




ÿ
þ
z(_compute_mxne_sure.<locals>._fit_on_gridc                 S   sr   |j d |j d  }}|||   |  ¡ | }	tj |||   ¡d }
|
|| |d   }|d|	 |d  7 }|S )Nr   r   r   )r1   r2   r*   rq   rt   )Úcoef1Úcoef2r4   ru   r¦   rÖ   rÕ   Z	n_sensorsZn_timesZdofZdf_termr”   r#   r#   r$   Ú_compute_sure_valb  s    z-_compute_mxne_sure.<locals>._compute_sure_valr   r   g333333Ó?zComputing SURE values on grid.zalpha %s :: sure %s)NNN)r*   Úemptyr0   r   r1   Zrandnr   r3   r   ÚzipZargmin)ru   r4   r¼   r¦   r¨   r©   rª   r«   r¬   r­   r®   r¯   r§   r   rÛ   rÞ   Z	sure_pathÚrngrÕ   rÖ   rÙ   rÚ   r×   r‘   rÜ   rÝ   r½   rG   rH   r#   )rÔ   r¬   r¼   r­   r¯   rÐ   r4   rÑ   r©   r¨   r«   r®   rª   r$   r¸   ì  s<    8  ÿ(
      ÿr¸   )NN)FNN)FN)N)r”   r<   r•   r–   r—   r˜   TTNr|   r<   r   FFr˜   NNr<   NN)r<   r•   r–   r—   Nr|   TTrÆ   rÇ   rÈ   FFNNr˜   NNr   N)2Únumpyr*   Zsource_estimater   r   r   Zminimum_norm.inverser   r   r   r	   r"   r
   Zio.pickr   Zio.projr   Úutilsr   r   r   r   r   r   r   r   Zdipoler   Z
mxne_optimr   r   r   r   r   r   r   r   r%   r;   rE   rI   r[   rh   rz   r‡   r“   rÁ   rÅ   rÍ   r¸   r#   r#   r#   r$   Ú<module>   s–   ((   ÿ
     ÿ&#  þ32                                û p                                  ú J