U
    f»{j[2  ã                   @   sd   d Z ddlZddlmZ ddlmZmZ edd	d
„ƒZdd„ Z	ddd„Z
dd„ Zdd„ Zdd„ ZdS )zÏCompute resolution metrics from resolution matrix.

Resolution metrics: localisation error, spatial extent, relative amplitude.
Metrics can be computed for point-spread and cross-talk functions (PSFs/CTFs).
é    Né   )ÚSourceEstimate)ÚloggerÚverboseÚpsfÚpeak_errç      à?c                 C   s®   d}||krt d| ƒ‚|dkr,t d| ƒ‚|dkrFt| |||d�}n4|dkrbt| ||||d�}n|d	krzt| |||d�}|d
 d }|d d }	||	g}
t||
ddd�}|S )aâ  Compute spatial resolution metrics for linear solvers.

    Parameters
    ----------
    resmat : array, shape (n_orient * n_vertices, n_vertices)
        The resolution matrix.
        If not a square matrix and if the number of rows is a multiple of
        number of columns (e.g. free or loose orientations), then the Euclidean
        length per source location is computed (e.g. if inverse operator with
        free orientations was applied to forward solution with fixed
        orientations).
    src : instance of SourceSpaces
        Source space object from forward or inverse operator.
    function : 'psf' | 'ctf'
        Whether to compute metrics for columns (point-spread functions, PSFs)
        or rows (cross-talk functions, CTFs) of the resolution matrix.
    metric : str
        The resolution metric to compute. Allowed options are:

        Localization-based metrics:

        - ``'peak_err'`` Peak localization error (PLE), Euclidean distance
          between peak and true source location.
        - ``'cog_err'`` Centre-of-gravity localisation error (CoG), Euclidean
          distance between CoG and true source location.

        Spatial-extent-based metrics:

        - ``'sd_ext'`` Spatial deviation
          (e.g. :footcite:`MolinsEtAl2008,HaukEtAl2019`).
        - ``'maxrad_ext'`` Maximum radius to 50%% of max amplitude.

        Amplitude-based metrics:

        - ``'peak_amp'`` Ratio between absolute maximum amplitudes of peaks
          per location and maximum peak across locations.
        - ``'sum_amp'`` Ratio between sums of absolute amplitudes.

    threshold : float
        Amplitude fraction threshold for spatial extent metric 'maxrad_ext'.
        Defaults to 0.5.
    %(verbose)s

    Returns
    -------
    resolution_metric : instance of SourceEstimate
        The resolution metric.

    Notes
    -----
    For details, see :footcite:`MolinsEtAl2008,HaukEtAl2019`.

    .. versionadded:: 0.20

    References
    ----------
    .. footbibliography::
    )r   Úcog_errÚsd_extÚ
maxrad_extÚpeak_ampÚsum_ampz "%s" is not a recognized metric.)r   Úctfz)Not a recognised resolution function: %s.)r   r	   )ÚfunctionÚmetric)r
   r   )r   r   Ú	threshold)r   r   r   Úvertnoé   g        g      ð?)ZtminZtstep)Ú
ValueErrorÚ_localisation_errorÚ_spatial_extentÚ_relative_amplituder   )ÚresmatÚsrcr   r   r   r   ZmetricsZresolution_metricÚ	vertno_lhÚ	vertno_rhr   © r   úb/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/minimum_norm/spatial_resolution.pyÚresolution_metrics   s6    >ÿÿ ÿÿÿr   c                 C   sÜ   t | ƒ} t|ƒ}d| }|dkr&| j} |dkrhdd„ | jD ƒ}||dd…f }|| }tjj|dd�}np|d	krØt |jd
 ¡}t|ƒD ]N\}	}
t	| dd…|	f jƒ}| 
|¡t |¡ }t t |
| d ¡¡||	< qˆ|S )a¬  Compute localisation error metrics for resolution matrix.

    Parameters
    ----------
    resmat : array, shape (n_orient * n_locations, n_locations)
        The resolution matrix.
        If not a square matrix and if the number of rows is a multiple of
        number of columns (i.e. n_orient>1), then the Euclidean length per
        source location is computed (e.g. if inverse operator with free
        orientations was applied to forward solution with fixed orientations).
    src : Source Space
        Source space object from forward or inverse operator.
    function : 'psf' | 'ctf'
        Whether to compute metrics for columns (point-spread functions, PSFs)
        or rows (cross-talk functions, CTFs).
    metric : str
        What type of localisation error to compute.

        - 'peak_err': Peak localisation error (PLE), Euclidean distance between
          peak and true source location, in centimeters.
        - 'cog_err': Centre-of-gravity localisation error (CoG), Euclidean
          distance between CoG and true source location, in centimeters.

    Returns
    -------
    locerr : array, shape (n_locations,)
        Localisation error per location (in cm).
    ç      Y@r   r   c                 S   s   g | ]}t |ƒ ¡ ‘qS r   )ÚabsZargmax©Ú.0Úcolr   r   r   Ú
<listcomp>š   s     z'_localisation_error.<locals>.<listcomp>Nr   ©Zaxisr	   r   r   )Ú_rectify_resolution_matrixÚ_get_src_locationsÚTÚnpZlinalgZnormÚemptyÚshapeÚ	enumerater    ÚdotÚsumÚsqrt)r   r   r   r   Ú	locationsZresmaxZmaxlocÚdifflocÚlocerrÚiiÚrrÚresvecZcogr   r   r   r   o   s"    r   c              	   C   s0  t |ƒ}d| }|dkr| j} t | jd ¡}|dkr®t|jd ƒD ]f}|||dd…f  }t |d d¡}	t| dd…|f ƒd }
t t t 	|	|
¡¡t |
¡ ¡||< qDn~|dk�r,t
| jƒD ]h\}}
t|
ƒ}
|
 ¡ }t |
|| k¡}||dd…f ||dd…f  }t t |d d¡ ¡ ¡||< qÂ|S )	aX  Compute spatial width metrics for resolution matrix.

    Parameters
    ----------
    resmat : array, shape (n_orient * n_dipoles, n_dipoles)
        The resolution matrix.
        If not a square matrix and if the number of rows is a multiple of
        number of columns (i.e. n_orient>1), then the Euclidean length per
        source location is computed (e.g. if inverse operator with free
        orientations was applied to forward solution with fixed orientations).
    src : Source Space
        Source space object from forward or inverse operator.
    function : 'psf' | 'ctf'
        Whether to compute metrics for columns (PSFs) or rows (CTFs).
    metric : str
        What type of width metric to compute.

        - 'sd_ext': spatial deviation (e.g. Molins et al.), in centimeters.
        - 'maxrad_ext': maximum radius to fraction threshold of max amplitude,
          in centimeters.

    threshold : float
        Amplitude fraction threshold for metric 'maxrad'. Defaults to 0.5.

    Returns
    -------
    width : array, shape (n_dipoles,)
        Spatial width metric per location.
    r   r   r   r
   r   Nr   r   )r'   r(   r)   r*   r+   Úranger.   r    r/   Úmultiplyr,   ÚmaxÚwhere)r   r   r   r   r   r0   Úwidthr3   r1   r2   r5   ZampsZ
thresh_idxZlocs_threshr   r   r   r   ª   s*    ÿ
  r   c           	      C   sp   |dkr| j } |dkr>t dd„ | j D ƒ¡}| ¡ }|| }n.|dkrlt dd„ | j D ƒ¡}| ¡ }|| }|S )a  Compute relative amplitude metrics for resolution matrix.

    Parameters
    ----------
    resmat : array, shape (n_orient * n_dipoles, n_dipoles)
        The resolution matrix.
        If not a square matrix and if the number of rows is a multiple of
        number of columns (i.e. n_orient>1), then the Euclidean length per
        source location is computed (e.g. if inverse operator with free
        orientations was applied to forward solution with fixed orientations).
    src : Source Space
        Source space object from forward or inverse operator.
    function : 'psf' | 'ctf'
        Whether to compute metrics for columns (PSFs) or rows (CTFs).
    metric : str
        Which amplitudes to use.

        - 'peak_amp': Ratio between absolute maximum amplitudes of peaks per
          location and maximum peak across locations.
        - 'sum_amp': Ratio between sums of absolute amplitudes.

    Returns
    -------
    relamp : array, shape (n_dipoles,)
        Relative amplitude metric per location.
    r   r   c                 S   s   g | ]}t |ƒ ¡ ‘qS r   )r    r8   r!   r   r   r   r$     s     z'_relative_amplitude.<locals>.<listcomp>r   c                 S   s   g | ]}t |ƒ ¡ ‘qS r   )r    r.   r!   r   r   r   r$     s     )r(   r)   Úarrayr8   )	r   r   r   r   ZmaxampsZ
maxmaxampsZrelampZsumampsZ
sumampsmaxr   r   r   r   ì   s    
r   c                 C   sZ   | d d }| d d }| d d |dd…f }| d d |dd…f }t  ||g¡}|S )z%Get source positions from src object.r   r   r   r4   N)r)   Zvstack)r   r   r   Zlocations_lhZlocations_rhr0   r   r   r   r'     s    r'   c                    sÒ   ˆj }|d |d ksÎ|d |d k r<td|d  |d ƒ‚t |d |d ¡rftd|d  |d ƒ‚|d |d  ‰ ‡ ‡fdd„tjd|d td�D ƒ}t |¡‰t d|d |d ˆj d ˆj d f ¡ ˆS )	a@  
    Ensure resolution matrix is square matrix.

    If resmat is not a square matrix, it is assumed that the inverse operator
    had free or loose orientation constraint, i.e. multiple values per source
    location. The Euclidean length for values at each location is computed to
    make resmat a square matrix.
    r   r   zONumber of target sources (%d) cannot be lower than number of input sources (%d)zTNumber of target sources (%d) must be a multiple of the number of input sources (%d)c              	      s>   g | ]6}t  ˆˆ | ˆ |d   …dd…f d jdd�¡‘qS )r   Nr   r   r%   )r)   r/   r.   )r"   Úi©Únsr   r   r   r$   B  s   ÿz._rectify_resolution_matrix.<locals>.<listcomp>)Zdtypez6Rectified resolution matrix from (%d, %d) to (%d, %d).)	r+   r   r)   ÚmodZarangeÚintr;   r   Úinfo)r   r+   Zresmatlr   r=   r   r&   *  s.    	ÿþþþÿ
ÿr&   )r   r   r   N)r   )Ú__doc__Únumpyr)   Ú r   Úutilsr   r   r   r   r   r   r'   r&   r   r   r   r   Ú<module>   s       ÿ^;
B0