U
    f»{jL7  ã                   @   sö   d Z ddlmZ ddlZddlmZmZm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 ed(dd„ƒZed)dd„ƒZdd„ Zdd„ Zdd„ Zdd„ Zed*dd„ƒZed+dd„ƒZd d!„ Zd"d#„ Zd,d$d%„Z d&d'„ Z!dS )-z0Compute resolution matrix for linear estimators.é    )ÚdeepcopyNé   )Úpick_channels_forwardÚEvokedArrayÚSourceEstimate)ÚFIFF)ÚloggerÚverbose)Úconvert_forward_solution)Úapply_inverse)Ú_prepare_label_extraction)ÚLabelÚdSPMçÇqÇq¼?c                    s|   |}t | |ƒ}|d d ‰ ‡ fdd„|d d D ƒ}t||dd�}|d d	 }t||||d
�}	|	 |¡}
t d|
j ¡ |
S )a�  Compute resolution matrix for linear inverse operator.

    Parameters
    ----------
    forward : instance of Forward
        Forward Operator.
    inverse_operator : instance of InverseOperator
        Inverse operator.
    method : 'MNE' | 'dSPM' | 'sLORETA'
        Inverse method to use (MNE, dSPM, sLORETA).
    lambda2 : float
        The regularisation parameter.
    %(verbose)s

    Returns
    -------
    resmat: array, shape (n_orient_inv * n_dipoles, n_orient_fwd * n_dipoles)
        Resolution matrix (inverse operator times forward operator).
        The result of applying the inverse operator to the forward operator.
        If source orientations are not fixed, all source components will be
        computed (i.e. for n_orient_inv > 1 or n_orient_fwd > 1).
        The columns of the resolution matrix are the point-spread functions
        (PSFs) and the rows are the cross-talk functions (CTFs).
    ÚinfoÚbadsc                    s   g | ]}|ˆ kr|‘qS © r   )Ú.0Úc©Úbads_invr   úa/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/minimum_norm/resolution_matrix.pyÚ
<listcomp>6   s      z2make_inverse_resolution_matrix.<locals>.<listcomp>Úch_namesT)ÚorderedZsolÚdata)ÚmethodÚlambda2z*Dimensions of resolution matrix: %d by %d.)Ú_convert_forward_match_invr   Ú!_get_matrix_from_inverse_operatorÚdotr   r   Úshape)ÚforwardÚinverse_operatorr   r   r	   ÚinvÚfwdr   Z	leadfieldÚinvmatÚresmatr   r   r   Úmake_inverse_resolution_matrix   s    
 ÿ
r(   c	                 C   sþ   t |||ƒ |dkrd}t||ƒ}	|d d }
|d d }|
|g}|dkrP| j} g }g }|	D ]h}| dd…|f }|dk	r‚t||ƒ}d}|dk	r t||||ƒ\}}t||dd	d
�}| |¡ | |¡ q\t|ƒdkrÖ|}t|ƒdkræ|}|dk	rö||fS |S dS )a  Get point-spread (PSFs) or cross-talk (CTFs) functions.

    Parameters
    ----------
    resmat : array, shape (n_dipoles, n_dipoles)
        Forward Operator.
    src : Source Space
        Source space used to compute resolution matrix.
    %(idx_pctf)s
    func : str ('psf' | 'ctf')
        Whether to produce PSFs or CTFs. Defaults to psf.
    %(mode_pctf)s
    %(n_comp_pctf_n)s
    %(norm_pctf)s
    %(return_pca_vars_pctf)s
    %(verbose)s

    Returns
    -------
    %(stcs_pctf)s
    %(pca_vars_pctf)s
    TÚmaxr   Úvertnoé   ÚctfNç        ç      ð?)ÚtminZtstep)Ú_check_get_psf_ctf_paramsÚ_vertices_for_get_psf_ctfÚTÚ_normalise_psf_ctfÚ_summarise_psf_ctfr   ÚappendÚlen)r'   ÚsrcÚidxÚfuncÚmodeÚn_compÚnormÚreturn_pca_varsr	   Z	verts_allZ	vertno_lhZ	vertno_rhr*   ZstcsZpca_varsÚvertsÚfuncsZpca_varÚstcr   r   r   Ú_get_psf_ctfB   s<    

ÿ
rA   c                 C   s<   | dkr |dkr d|  }t |ƒ‚| dkr8|r8d}t |ƒ‚dS )z9Check input parameters of _get_psf_ctf() for consistency.)NÚsumÚmeanr+   zn_comp must be 1 for mode=%s.Úpcaz/SVD variances can only be returned if mode=pca.N)Ú
ValueError)r:   r;   r=   Úmsgr   r   r   r0   Ž   s    r0   c                 C   s�   t | d ƒtkrptd| |dddd�\}}g }|D ]<}t |ƒtkrXt |d |d f¡}n
t |¡}| |¡ q0nt | d ƒtkr†| }n| g}|S )z=Get vertices in source space for PSFs/CTFs in _get_psf_ctf().r   NrC   F)r@   Úlabelsr7   r:   Zallow_emptyZ
use_sparser+   )Útyper   r   ÚlistÚnpZconcatenateÚarrayr5   )r8   r7   Z
verts_labsÚ_r>   ÚvZ
this_vertsr   r   r   r1   ˜   s&        þ

r1   c                 C   sN   |dkr&t |  ¡  |   ¡ ƒ}| | } n$|dkrJtjj| dd�}| |  ¡  } | S )z&Normalise PSFs/CTFs in _get_psf_ctf().r)   r<   r   ©Zaxis)r)   ÚminrJ   Úlinalgr<   )r?   r<   ÚmaxvalÚnormsr   r   r   r3   ¸   s    
r3   c                 C   sZ  ddl m} d}|dkrvt tj| dd� tj| dd�¡}|dkr\t |¡}|| d… }n| ¡ }| dd…|f } nÜ|dkrÊtjj| dd�}	|dkr°t |	¡}|| d… }n|	 ¡ }| dd…|f } nˆ|dkrâtj	| dd�} np|d	krútj
| dd�} nX|d
k�rR|j| dd�\}
}}|
dd…d|…f } |�rR|| }d|d|…  | 	¡  }| |fS )z$Summarise PSFs/CTFs across vertices.r   )rP   NrQ   rN   r+   ZmaxnormrB   rC   rD   F)Zfull_matriceséd   )ZscipyrP   rJ   ÚmaximumrO   r)   ZargsortZargmaxr<   rB   rC   Zsvd)r?   r:   r;   r=   rP   Zs_varZabsvalsZsortidxZmaxidxrR   ÚuÚsrL   Ús2r   r   r   r4   Å   s6    "


r4   r+   Fc              
   C   s   t | ||d||||d�S )a²  Get point-spread (PSFs) functions for vertices.

    Parameters
    ----------
    resmat : array, shape (n_dipoles, n_dipoles)
        Forward Operator.
    src : instance of SourceSpaces
        Source space used to compute resolution matrix.
    %(idx_pctf)s
    %(mode_pctf)s
    %(n_comp_pctf_n)s
    %(norm_pctf)s
    %(return_pca_vars_pctf)s
    %(verbose)s

    Returns
    -------
    %(stcs_pctf)s
    %(pca_vars_pctf)s
    Zpsf©r9   r:   r;   r<   r=   ©rA   ©r'   r7   r8   r:   r;   r<   r=   r	   r   r   r   Úget_point_spreadï   s     ÿr[   c              
   C   s   t | ||d||||d�S )a¯  Get cross-talk (CTFs) function for vertices.

    Parameters
    ----------
    resmat : array, shape (n_dipoles, n_dipoles)
        Forward Operator.
    src : instance of SourceSpaces
        Source space used to compute resolution matrix.
    %(idx_pctf)s
    %(mode_pctf)s
    %(n_comp_pctf_n)s
    %(norm_pctf)s
    %(return_pca_vars_pctf)s
    %(verbose)s

    Returns
    -------
    %(stcs_pctf)s
    %(pca_vars_pctf)s
    r,   rX   rY   rZ   r   r   r   Úget_cross_talk
  s     ÿr\   c                 C   s`   t |ƒ}t | ƒ}|s\|s\|d d dk ¡  }|rH| d s\t| dd�} n| d r\t| dd�} | S )z»Ensure forward and inverse operators match.

    Inverse operator and forward operator must have same surface orientations,
    but can have different source orientation constraints.
    Zorient_priorr   r.   Úsurf_oriT)r]   F)Ú_check_fixed_oriÚallr
   )r%   r$   Úis_fixed_invZis_fixed_fwdZis_loose_invr   r   r   r   %  s    r   c              	   C   s8   t | d ƒ}| ¡ � d|d< | d |d< W 5 Q R X |S )zGet a usable dict.r   g     @�@ZsfreqZprojs)r   Z_unlock)r#   r   r   r   r   Ú_prepare_info?  s
    
ra   c                    s$  t || ƒ t| ƒ}|d ‰ tˆ ƒ}| d d }‡ fdd„|D ƒ}t |¡}t||dd�}	t| ƒ}
|
rjd}nd	}t|	| |||d
�}|j}tj	|||j
d d�}|j
dk�r|d  ¡ }|d  ¡ }|j}| |d |d  |d ¡}t ||d ¡söt‚t ||d ¡�st‚t dt|jƒ ¡ |S )aÙ  Get inverse matrix from an inverse operator.

    Currently works only for fixed/loose orientation constraints
    For loose orientation constraint, the CTFs are computed for the normal
    component (pick_ori='normal').

    Parameters
    ----------
    inverse_operator : instance of InverseOperator
        The inverse operator.
    forward : instance of Forward
        The forward operator.
    method : 'MNE' | 'dSPM' | 'sLORETA'
        Inverse methods (for apply_inverse).
    lambda2 : float
        The regularization parameter (for apply_inverse).

    Returns
    -------
    invmat : array, shape (n_dipoles, n_channels)
        Inverse matrix associated with inverse operator and specified
        parameters.
    r   r   r   c                    s   g | ]}ˆ   |¡‘qS r   )Úindex)r   Úch©Zch_names_invr   r   r   p  s     z5_get_matrix_from_inverse_operator.<locals>.<listcomp>r-   )r   r/   NZvector)r   r   Úpick_orir+   rN   é   )r   r+   )rf   r   r   r   é   zDimension of Inverse Matrix: %s)r   ra   r6   rJ   Úeyer   r^   r   r   ÚdeleteÚndimÚcopyr!   ZreshapeZarray_equalÚAssertionErrorr   r   Ústr)r#   r"   r   r   Zinfo_invZ	n_chs_invr   Zch_idx_badsZid_matZev_idr`   re   Z	invmat_opr&   Zv0o1Zv3o2r!   r   rd   r   r   K  s6    

 ÿr   c                 C   s   | d t jk}|S )z@Check if inverse or forward was computed for fixed orientations.Z
source_ori)r   ZFIFFV_MNE_FREE_ORI)ÚinstZis_fixedr   r   r   r^   ¡  s    r^   )r   r   N)N)Nr+   FFN)Nr+   FFN)r   r   )"Ú__doc__rk   r   ÚnumpyrJ   Ú r   r   r   Zio.constantsr   Úutilsr   r	   Zforward.forwardr
   Zminimum_normr   Zsource_estimater   Úlabelr   r(   rA   r0   r1   r3   r4   r[   r\   r   ra   r   r^   r   r   r   r   Ú<module>   sJ       ÿ. ÿK
 *    ÿ    ÿ  ÿ
V