U
    f»{jÎ÷ ã                	   @   sè  d dl Z d dlZd dlmZ d dlmZ d dlZddl	m
Z
 ddl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 dd
lmZ ddlmZ ddlmZmZmZm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZC ddlDmEZEmFZFmGZG ddlHmIZI ddlJmKZK dd„ ZLdd„ ZMdd„ ZNdd„ ZOdd„ ZPdd„ ZQd}dd „ZRd~d!d"„ZSdd$d%„ZTd&d'„ ZUG d(d)„ d)eIƒZVd*d+„ ZWe4G d,d-„ d-eVƒƒZXe4G d.d/„ d/eXƒƒZYG d0d1„ d1eVƒZZG d2d3„ d3eVƒZ[e4G d4d5„ d5e[ƒƒZ\e4G d6d7„ d7e[eZƒƒZ]e4G d8d9„ d9eZeXƒƒZ^G d:d;„ d;eVƒZ_e4G d<d=„ d=e_ƒƒZ`e4G d>d?„ d?eZe_ƒƒZad@dA„ ZbdBdC„ ZcdDdE„ Zde/d€dFdG„ƒZee/d�dHdI„ƒZfe/d‚dJdK„ƒZge/dƒdLdM„ƒZhe/d„dNdO„ƒZie/d…dPdQ„ƒZje/d†dRdS„ƒZke/d‡dTdU„ƒZle/dˆdVdW„ƒZme/d‰dXdY„ƒZndZd[„ Zod\d]„ d^d]„ d_d]„ eod`œZpe jqdadb„ ƒZrdcdd„ Zsdedf„ Ztdgdh„ Zudidj„ Zvdkdl„ Zwdmdn„ Zxdod#dpddqœdrds„Zye/dŠdpdduœdvdw„ƒZze/d‹d{d|„ƒZ{dS )Œé    N)ÚGeneratorTypeé   )Úrescale)Ú
Covariance)Ú	_get_peak)Úresample)Ú	_safe_svd)Ú_import_nibabelÚ_get_mri_info_dataÚ_get_atlas_valuesÚread_freesurfer_lut)ÚFIFF)Ú
pick_types)Úread_surfaceÚ_get_ico_surfaceÚ
mesh_edgesÚ_project_onto_surface)Ú_ensure_srcÚ_get_morph_src_reorderingÚ_ensure_src_subjectÚSourceSpacesÚ_get_src_nnÚ_check_volume_labels)Ú
_get_transÚapply_trans)Úget_subjects_dirÚ_check_subjectÚloggerÚverboseÚ_plÚ
_time_maskÚwarnÚcopy_function_doc_to_method_docÚfill_docÚ_check_optionÚ_validate_typeÚ_check_src_normalÚ_check_stc_unitsÚ_check_pandas_installedÚ_check_pandas_index_argumentsÚ_convert_timesÚ_ensure_intÚ_build_data_frameÚ_check_time_formatÚ
_path_likeÚ
sizeof_fmtÚobject_sizeÚ_check_fnameÚ_import_h5io_funcs)Úplot_source_estimatesÚplot_vector_source_estimatesÚplot_volume_source_estimates)Ú	TimeMixin)ÚInfoc              	   C   sT  t | dƒ�}| ¡ }W 5 Q R X tƒ }d}d}ttj|dd|d�ƒ|d< |d  d  < ||7 }ttj|dd|d�ƒ|d	< |d	  d  < ||7 }ttj|d
d|d�ƒ}||7 }tj|d
||d�|d< ||| 7 }ttj|d
d|d�ƒ}||7 }|�rt|ƒd d | ||  dk�rtdƒ‚tj|d|| |d�|d< |d  	||g¡j
|d< |S )zAux Function.Úrbr   é   ú>f4r   )ÚdtypeÚcountÚoffsetÚtminç     @�@Útstepú>u4Úverticeszincorrect stc file sizeÚdata)ÚopenÚreadÚdictÚfloatÚnpZ
frombufferÚintÚlenÚ
ValueErrorÚreshapeÚT)ÚfilenameÚfidÚbufÚstcr=   Z	num_bytesÚ
vertices_nZdata_n© rS   úR/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/source_estimate.pyÚ	_read_stc+   s@    ÿÿ
ÿ
ÿÿ
rU   c              	   C   sÄ   |  t | dƒ�¬}| tjd| dd� ¡ ¡ | tjd| dd� ¡ ¡ | tj|jd dd� ¡ ¡ | tj|dd� ¡ ¡ | tj|jd dd� ¡ ¡ | tj|jdd� ¡ ¡ W 5 Q R X dS )	an  Write an STC file.

    Parameters
    ----------
    filename : string
        The name of the STC file.
    tmin : float
        The first time point of the data in seconds.
    tstep : float
        Time between frames in seconds.
    vertices : array of integers
        Vertex indices (0 based).
    data : 2D array
        The data matrix (nvert * ntime).
    Úwbéè  r:   ©r;   r   rA   r   N)rD   ÚwriterH   ÚarrayÚtobytesÚshaperM   )rN   r>   r@   rB   rC   rO   rS   rS   rT   Ú
_write_stcY   s    r]   c                 C   sF   t j| t jdd� t j¡}t  |d d¡t  |d d¡ |d  }|S )zRead 3 byte integer from file.é   ©r;   r<   r   é   r   é   é   )rH   ÚfromfileÚuint8ÚastypeÚint32Z
left_shift)rO   rC   ÚoutrS   rS   rT   Ú_read_3y   s    (rh   c              	   C   sœ   t | ddd��„}| d¡ tt|ƒƒ}tj|tjd�}tj|tjd�}t|ƒD ](}t|ƒ||< tj	|ddd�d ||< qNt
ƒ }||d	< ||d
< W 5 Q R X |S )a†  Read a w file.

    w files contain activations or source reconstructions for a single time
    point.

    Parameters
    ----------
    filename : string
        The name of the w file.

    Returns
    -------
    data: dict
        The w structure. It has the following keys:
           vertices       vertex indices (0 based)
           data           The data matrix (nvert long)
    r8   r   )Ú	bufferingrb   rX   r:   r   r_   rB   rC   )rD   rE   rI   rh   rH   Úzerosrf   Úfloat32Úrangerc   rF   )rN   rO   rR   rB   rC   ÚiÚwrS   rS   rT   Ú_read_w‚   s    
ro   c                 C   sN   t jdt jd�}|d? d@ |d< |d? d@ |d< |d@ |d< |  | ¡ ¡ d	S )
zWrite 3 byte integer to file.r^   rX   r`   éÿ   r   ra   r   rb   N)rH   rj   rd   rY   r[   )rO   ÚvalZf_bytesrS   rS   rT   Ú_write_3ª   s
    rr   c              	   C   s–   t |ƒt |ƒkst‚t| dƒ�n}| tjdtjd� ¡ ¡ t |ƒ}t||ƒ t	|ƒD ]2}t||| ƒ | tj
t|| ƒdd� ¡ ¡ qTW 5 Q R X dS )a0  Write a w file.

    w files contain activations or source reconstructions for a single time
    point.

    Parameters
    ----------
    filename: string
        The name of the w file.
    vertices: array of int
        Vertex indices (0 based).
    data: 1D array
        The data array (nvert).
    rV   rb   rX   r:   N)rJ   ÚAssertionErrorrD   rY   rH   rj   rd   r[   rr   rl   rZ   rG   )rN   rB   rC   rO   rR   rm   rS   rS   rT   Ú_write_w³   s    
rt   c                 C   sv  | }t | ddƒ t| ddd�} d}t | ¡rÔ|  d¡r<d}n˜|  d	¡rtd
}|  d¡rb| dd… } qÔd|  }t|ƒ‚n`|  d¡r¬d}|  d¡rš| dd… } qÔd|  }t|ƒ‚n(|  d¡rÈd}| dd… } ntd| ƒ‚|dk�rždd„ | d | d fD ƒ}dd„ | d | d fD ƒ}t|ƒ�r,|dk�r,d
}nrt|ƒ�r<d}nbt | d ¡�rRd}nLt | d ¡�rpd}| d7 } n.t|ƒ�s„t|ƒ�r’td | ƒ‚ntd!| ƒ‚|dk�r|  d	¡�r¾t	| ƒ}nH|  d¡�rþt
| ƒ}|d" dd…tjf |d"< d#|d$< d#|d%< ntd&ƒ‚|d' g|d'< �nL|d
k�ržt	| d ƒ}t	| d ƒ}	|d$ |	d$ k�sPt‚|d% |	d% k�sft‚| ¡ }tj|d" |	d" f |d"< |d' |	d' g|d'< nÆ|dk�rt
| d ƒ}t
| d ƒ}	| ¡ }t tj|d" |	d" f ¡j|d"< |d' |	d' g|d'< d#|d$< d(|d%< d
}nP|dk�rdtƒ \}
}|
| d d)d*�}| d+d
¡}t|d' tjƒ�rd|d' g|d'< |dk�ræ|d' }td,d-„ |D ƒƒ�ræd.d„ |D ƒ}d/d„ t||ƒD ƒ}|d" tj|d0 t|d0 ƒ|d1  f  }||d'< ||d"< d2|k�rø||d2< |dk	�r$||d2 k�r$td3||d2 f ƒ‚|d4k�r4t}n"|d5k�rDt}n|d
k�sRt‚t}|d" jd6k �rl|j}|f |ŽS )7a³  Read a source estimate object.

    Parameters
    ----------
    fname : str
        Path to (a) source-estimate file(s).
    subject : str | None
        Name of the subject the source estimate(s) is (are) from.
        It is good practice to set this attribute to avoid combining
        incompatible labels and SourceEstimates (e.g., ones from other
        subjects). Note that due to file specification limitations, the
        subject name isn't saved to or loaded from files written to disk.

    Returns
    -------
    stc : SourceEstimate | VectorSourceEstimate | VolSourceEstimate | MixedSourceEstimate
        The source estimate object loaded from file.

    Notes
    -----
     - for volume source estimates, ``fname`` should provide the path to a
       single file named '*-vl.stc` or '*-vol.stc'
     - for surface source estimates, ``fname`` should either provide the
       path to the file corresponding to a single hemisphere ('*-lh.stc',
       '*-rh.stc') or only specify the asterisk part in these patterns. In any
       case, the function expects files for both hemisphere with names
       following this pattern.
     - for vector surface source estimates, only HDF5 files are supported.
     - for mixed source estimates, only HDF5 files are supported.
     - for single time point .w files, ``fname`` should follow the same
       pattern as for surface estimates, except that files are named
       '*-lh.w' and '*-rh.w'.
    ú	path-likeÚfnamerE   F)rv   Ú	overwriteZ
must_existN)ú-vl.stcú-vol.stcú-vl.wú-vol.wÚvolumez.stcÚsurface)ú-lh.stcú-rh.stciùÿÿÿzZInvalid .stc filename: %r; needs to end with hemisphere tag ('...-lh.stc' or '...-rh.stc')z.wrn   )ú-lh.wú-rh.wéûÿÿÿzTInvalid .w filename: %r; needs to end with hemisphere tag ('...-lh.w' or '...-rh.w')ú.h5Úh5éýÿÿÿzUnknown extension for file %sc                 S   s   g | ]}t  |¡‘qS rS   ©ÚopÚexists©Ú.0ÚfrS   rS   rT   Ú
<listcomp>  s   ÿz(read_source_estimate.<locals>.<listcomp>r   r~   c                 S   s   g | ]}t  |¡‘qS rS   r†   r‰   rS   rS   rT   rŒ     s   ÿr�   r€   ú-stc.h5z-stczHemisphere missing for %rz(SourceEstimate File(s) not found for: %rrC   g        r>   r@   z/Volume source estimate must end with .stc or .wrB   ç      ð?Ú	mnepython)ÚtitleÚsrc_typec                 s   s(   | ] }t  t  | t¡¡d k¡V  qdS ©r   N)rH   ÚanyÚdiffre   rI   ©rŠ   ÚvrS   rS   rT   Ú	<genexpr>V  s     z'read_source_estimate.<locals>.<genexpr>c                 S   s   g | ]}t  |¡‘qS rS   )rH   Zargsort)rŠ   ÚvertsrS   rS   rT   rŒ   W  s     c                 S   s   g | ]\}}|| ‘qS rS   rS   )rŠ   r˜   ÚidxrS   rS   rT   rŒ   X  s     r   r   ÚsubjectzHprovided subject name "%s" does not match subject name from the file "%s©r|   ÚdiscreteÚmixedr^   )r%   r1   r‡   rˆ   ÚendswithÚIOErrorÚRuntimeErrorÚallr“   rU   ro   rH   Únewaxisrs   ÚcopyZr_Z
atleast_2drM   r2   ÚpopÚ
isinstanceÚndarrayÚziprJ   ÚVolVectorSourceEstimateÚMixedVectorSourceEstimateÚVectorSourceEstimateÚndimÚ_scalar_class)rv   rš   Z	fname_argÚftypeÚerrZ	stc_existZw_existÚkwargsÚlhÚrhZ	read_hdf5Ú_rB   ZsidxrC   ÚklassrS   rS   rT   Úread_source_estimateÓ   sÐ    "



þ


þ


ÿÿ

ÿ




"


*

þ

r´   c                 C   sœ   d }| d kr†|d krt dƒ nt |ƒ t|tƒrBt|ƒdkrBd}qŒt|tjƒsdt|tƒrjt|ƒdkrjd}qŒt|tƒrŒt|ƒdkrŒd}n| j}|dks˜t‚|S )Nz6src should not be None for a robust guess of stc type.rb   r}   r   r|   r�   )r}   r|   r�   rœ   )r!   r¥   ÚlistrJ   rH   r¦   Úkindrs   )ÚsrcrB   Ú	warn_textr‘   rS   rS   rT   Ú_get_src_typep  s     

ÿr¹   Fc	                    s€  ‡ ‡fdd„}	|dkr|	ƒ n|}|r<|dkr<|dkr<t dƒ‚|dkrR|rLtnt}
n4|dkrh|rbtnt}
n|dkr~|rxtnt}
ntdƒ‚|�rntd	d
„ ˆ D ƒƒ}| j	d ||d fks¸t
‚t| ƒ|k�r|dksÒt
‚|j	|dfksät
‚| dd…tjf |dd…dd…tjf  } n^|  dd| j	d f¡} |j	|ddf|d dffk�sHt
‚t tj| |dd¡dddgd�| ¡} |
| ˆ |||d�S )zDGenerate a surface, vector-surface, volume or mixed source estimate.c                      s   t d ˆ ˆd�S )N)r·   rB   r¸   )r¹   rS   ©rB   r¸   rS   rT   Úguess_src_type‡  s    z!_make_stc.<locals>.guess_src_typeNr}   zNo source vectors supplied.r›   r�   zDvertices has to be either a list with one or more arrays or an arrayc                 s   s   | ]}t |ƒV  qd S ©N©rJ   r•   rS   rS   rT   r—   œ  s     z_make_stc.<locals>.<genexpr>r   r^   éÿÿÿÿrb   r   )Zaxes)rC   rB   r>   r@   rš   )r    rª   ÚSourceEstimater¨   ÚVolSourceEstimater©   ÚMixedSourceEstimaterK   Úsumr\   rs   rJ   rH   r¢   rL   ÚmatmulZ	transpose)rC   rB   r‘   r>   r@   rš   ZvectorZ	source_nnr¸   r»   ZKlassÚ
n_verticesrS   rº   rT   Ú	_make_stc„  sF    ,
ÿÿþ    ÿrÅ   c                 C   s�   d}t | ƒt |ƒkr,tdt | ƒt |ƒf ƒ‚t| jƒt|jƒkr`tdd„ t| j|jƒD ƒƒr`d}|sltdƒ‚| j|jkrŒtd| j|jf ƒ‚dS )	zCMake sure two SourceEstimates are compatible for arith. operations.FzCannot combine %s and %s.c                 s   s   | ]\}}t  ||¡V  qd S r¼   )rH   Úarray_equal)rŠ   ÚavZvvrS   rS   rT   r—   ·  s   ÿz1_verify_source_estimate_compat.<locals>.<genexpr>Tz`Cannot combine source estimates that do not have the same vertices. Consider using stc.expand().z>source estimates do not have the same subject names, %r and %rN)ÚtyperK   rJ   rB   r¡   r§   rš   )ÚaÚbÚcompatrS   rS   rT   Ú_verify_source_estimate_compat±  s    ÿ
ÿrÌ   c                   @   s(  e Zd ZdZedtdd„ƒZdd„ Zedud	d
„ƒZedvdd„ƒZ	edwddœdd„ƒZ
edxdddœdd„ƒZeeƒdyd!d"„ƒZed#d$„ ƒZed%d&„ ƒZd'd(„ Zedzd)d*„ƒZed{d,d-„ƒZed.d/„ ƒZejd0d/„ ƒZed1d2„ ƒZed3d4„ ƒZejd5d4„ ƒZed6d7„ ƒZejd8d7„ ƒZed9d:„ ƒZejd;d:„ ƒZd<d=„ Zd>d?„ Zd@dA„ ZdBdC„ ZdDdE„ ZdFdG„ Z dHdI„ Z!dJdK„ Z"dLdM„ Z#dNdO„ Z$dPdQ„ Z%dRdS„ Z&dTdU„ Z'dVdW„ Z(dXdY„ Z)dZd[„ Z*d\d]„ Z+d^d_„ Z,d`da„ Z-dbdc„ Z.ddde„ Z/dfdg„ Z0dhdi„ Z1djdk„ Z2dde3jfdldm„Z4d|dndo„Z5d}dpdq„Z6ed~ddœdrds„ƒZ7dS )Ú_BaseSourceEstimaterb   Nc           
      C   s,  t | dƒst| jjƒ‚t | dƒs,t| jjƒ‚t | dƒsBt| jjƒ‚d\}}t|tƒr¶t|ƒdkrhtdƒ‚|\}}d }|jd |jd krœtd	|j|jf ƒ‚|j	dkr¶td
|j	f ƒ‚t
|tdƒ | jd k	rðt|ƒ| jkrðtd| jt|ƒf ƒ‚dd„ |D ƒ}tdd„ |D ƒƒ�rtdƒ‚tdd„ |D ƒƒ}	|d k	�rà|j	| j| jd fk�rhtd|j| j| jjf ƒ‚|jd |	k�r”td|	› d|jd › d�ƒ‚| jdk�rÀ|jd dk�rÀtd|jf ƒ‚|j	| jd k�rà|dtjf }|| _|| _|| _|| _|| _|| _d| _d | _|  ¡  td |dd�| _d S )NÚ
_data_ndimÚ	_src_typeÚ
_src_count)NNrb   z(If data is a tuple it has to be length 2r   r   z6kernel (%s) and sens_data (%s) have invalid dimensionsz.The sensor data must have 2 dimensions, got %srB   z/vertices must be a list with %d entries, got %sc                 S   s   g | ]}t  |t j¡‘qS rS   )rH   rZ   Úint64r•   rS   rS   rT   rŒ   ß  s     z0_BaseSourceEstimate.__init__.<locals>.<listcomp>c                 s   s"   | ]}t  t  |¡d k¡V  qdS r’   )rH   r“   r”   r•   rS   rS   rT   r—   à  s     z/_BaseSourceEstimate.__init__.<locals>.<genexpr>z-Vertices must be ordered in increasing order.c                 S   s   g | ]}t |ƒ‘qS rS   r½   r•   rS   rS   rT   rŒ   ã  s     z.Data (shape %s) must have %s dimensions for %szNumber of vertices (z) and stc.data.shape[0] (z) must matchr^   zCData for VectorSourceEstimate must have shape[1] == 3, got shape %s.F©Úraise_error)Úhasattrrs   Ú	__class__Ú__name__r¥   ÚtuplerJ   rK   r\   r«   r%   rµ   rÐ   r“   rÂ   rÎ   rH   r¢   Ú_dataÚ_tminÚ_tsteprB   Ú_kernelÚ
_sens_dataÚ_kernel_removedÚ_timesÚ_update_timesr   rš   )
ÚselfrC   rB   r>   r@   rš   r   ZkernelZ	sens_dataZn_srcrS   rS   rT   Ú__init__Æ  sr    

þ
ÿ
ÿ
ÿÿÿÿÿz_BaseSourceEstimate.__init__c                 C   s¼   dt dd„ | jD ƒƒf }| jd k	r2|d| j 7 }|dd| j  7 }|dd| jd   7 }|d	d| j  7 }|d
| jf 7 }t dd„ | j| jg D ƒƒ}|dt|ƒ› �7 }dt	| ƒj
|f S )Nz%d verticesc                 s   s   | ]}t |ƒV  qd S r¼   r½   r•   rS   rS   rT   r—     s     z/_BaseSourceEstimate.__repr__.<locals>.<genexpr>z, subject : %sz, tmin : %s (ms)r?   z, tmax : %s (ms)r¾   z, tstep : %s (ms)z, data shape : %sc                 s   s   | ]}t |ƒV  qd S r¼   )r0   )rŠ   ÚxrS   rS   rT   r—   
  s     z, ~z	<%s | %s>)rÂ   rB   rš   r>   Útimesr@   r\   rC   r/   rÈ   rÖ   )rà   ÚsÚszrS   rS   rT   Ú__repr__  s    
z_BaseSourceEstimate.__repr__ÚabsFc           
      C   sl   | j dkr|  ¡ n| }| jdkr(tdƒ‚t|j| j|||ƒ\}}}	|sVt | j	¡| }|sd| j| }||fS )a6  Get location and latency of peak amplitude.

        Parameters
        ----------
        %(get_peak_parameters)s

        Returns
        -------
        pos : int
            The vertex exhibiting the maximum response, either ID or index.
        latency : float
            The latency in seconds.
        r^   r   z"Cannot find peaks with no vertices)
rÎ   Ú	magnitudeÚ_n_verticesr    r   rC   rã   rH   ÚconcatenaterB   )
rà   r>   ÚtmaxÚmodeÚvert_as_indexÚtime_as_indexrQ   Zvert_idxZtime_idxr²   rS   rS   rT   Úget_peak  s    
    ÿ

z_BaseSourceEstimate.get_peakÚautoc              	   C   s   t | |||d||d�S )aN  Extract label time courses for lists of labels.

        This function will extract one time course for each label. The way the
        time courses are extracted depends on the mode parameter.

        Parameters
        ----------
        %(labels_eltc)s
        %(src_eltc)s
        %(mode_eltc)s
        %(allow_empty_eltc)s
        %(verbose)s

        Returns
        -------
        %(label_tc_el_returns)s

        See Also
        --------
        extract_label_time_course : Extract time courses for multiple STCs.

        Notes
        -----
        %(eltc_mode_notes)s
        F)rì   Úreturn_generatorÚallow_emptyr   ©Úextract_label_time_course)rà   Úlabelsr·   rì   rò   r   rS   rS   rT   rô   )  s         þz-_BaseSourceEstimate.extract_label_time_course©Nr   ©r   c                C   s   t | j| j|dd�| _| S )aÆ  Baseline correct source estimate data.

        Parameters
        ----------
        %(baseline_stc)s
            Defaults to ``(None, 0)``, i.e. beginning of the the data until
            time point zero.
        %(verbose)s

        Returns
        -------
        stc : instance of SourceEstimate
            The baseline-corrected source estimate object.

        Notes
        -----
        Baseline correction can be done multiple times.
        F©r£   )r   rC   rã   )rà   Úbaseliner   rS   rS   rT   Úapply_baselineI  s    z"_BaseSourceEstimate.apply_baseliner„   ©rw   r   c             
   C   s~   t |dd�}|dkr&td| jjf ƒ‚tƒ \}}| d¡sB|d7 }t ||d�}||t| j| j| j	| j
| j| jd�ddd	� d
S )a  Save the full source estimate to an HDF5 file.

        Parameters
        ----------
        fname : str
            The file name to write the source estimate to, should end in
            '-stc.h5'.
        ftype : str
            File format to use. Currently, the only allowed values is "h5".
        %(overwrite)s

            .. versionadded:: 1.0
        %(verbose)s
        T©rv   rw   r„   z-%s objects can only be written as HDF5 files.rƒ   r�   )rB   rC   r>   r@   rš   r‘   r�   )r�   rw   N)r1   rK   rÕ   rÖ   r2   rž   rF   rB   rC   r>   r@   rš   rÏ   )rà   rv   r­   rw   r   r²   Z
write_hdf5rS   rS   rT   Úsave`  s&    ÿ


  þûz_BaseSourceEstimate.saveÚinflatedr°   é
   TrŽ   Úclassicé   Úblackrä   Úoct6Úverticalc               !   C   sJ   t | |||||||||	|
||||||||||||||||||||d�}|S )N)r}   ÚhemiÚcolormapÚ
time_labelÚsmoothing_stepsÚtransparentÚalphaÚtime_viewerÚsubjects_dirÚfigureÚviewsÚcolorbarÚclimÚcortexÚsizeÚ
backgroundÚ
foregroundÚinitial_timeÚ	time_unitÚbackendÚspacingr�   Úshow_tracesr·   Úvolume_optionsÚview_layoutÚadd_data_kwargsÚbrain_kwargsr   )r3   ) rà   rš   r}   r  r  r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r�   r  r·   r  r  r  r  r   ÚbrainrS   rS   rT   Úplot  sD                        õz_BaseSourceEstimate.plotc                 C   s
   d| j  S )zSample rate of the data.rŽ   )r@   ©rà   rS   rS   rT   Úsfreq˜  s    z_BaseSourceEstimate.sfreqc                 C   s   t dd„ | jD ƒƒS )Nc                 s   s   | ]}t |ƒV  qd S r¼   r½   r•   rS   rS   rT   r—   Ÿ  s     z2_BaseSourceEstimate._n_vertices.<locals>.<genexpr>©rÂ   rB   r   rS   rS   rT   ré   �  s    z_BaseSourceEstimate._n_verticesc                 C   s<   | j dk	s| jdk	r8d| _t | j | j¡| _d| _ d| _dS )z;Remove kernel and sensor space data and compute self._data.NT)rÛ   rÜ   rÝ   rH   ÚdotrØ   r   rS   rS   rT   Ú_remove_kernel_sens_data_¡  s
    z-_BaseSourceEstimate._remove_kernel_sens_data_c                 C   sj   t | j||| j|d�}| jt |¡d d  | _| jdk	rV| jdk	rV| jd|f | _n| jd|f | _| S )a½  Restrict SourceEstimate to a time interval.

        Parameters
        ----------
        tmin : float | None
            The first time point in seconds. If None the first present is used.
        tmax : float | None
            The last time point in seconds. If None the last present is used.
        %(include_tmax)s

        Returns
        -------
        stc : instance of SourceEstimate
            The cropped source estimate.
        )r!  Úinclude_tmaxr   N.)	r    rã   r!  rH   Úwherer>   rÛ   rÜ   rC   )rà   r>   rë   r%  ÚmaskrS   rS   rT   Úcrop©  s    ÿz_BaseSourceEstimate.cropÚboxcarc                 C   sR   |   ¡  d| j }| j}|jtjkr0| tj¡}t|||||d�| _d| | _| S )aÐ  Resample data.

        If appropriate, an anti-aliasing filter is applied before resampling.
        See :ref:`resampling-and-decimating` for more information.

        Parameters
        ----------
        sfreq : float
            New sample rate to use.
        npad : int | str
            Amount to pad the start and end of the data.
            Can also be "auto" to use a padding that will result in
            a power-of-two size (can be much faster).
        window : str | tuple
            Window to use in resampling. See :func:`scipy.signal.resample`.
        %(n_jobs)s
        %(verbose)s

        Returns
        -------
        stc : instance of SourceEstimate
            The resampled source estimate.

        Notes
        -----
        For some data, it may be more accurate to use npad=0 to reduce
        artifacts. This is dataset dependent -- check your data!

        Note that the sample rate of the original data is inferred from tstep.
        rŽ   )Ún_jobs)	r$  r@   rC   r;   rH   rk   re   Úfloat64r   )rà   r!  ZnpadZwindowr*  r   Zo_sfreqrC   rS   rS   rT   r   Ä  s    #

z_BaseSourceEstimate.resamplec                 C   s   | j dkr|  ¡  | j S )z$Numpy array of source estimate data.N)rØ   r$  r   rS   rS   rT   rC   ó  s    
z_BaseSourceEstimate.datac                 C   s|   t  |¡}| jd k	r2|j| jjkr2td| jj ƒ‚tdd„ | jD ƒƒ}|jd |krjtd|jd |f ƒ‚|| _|  ¡  d S )Nz%Data array should have %d dimensions.c                 s   s   | ]}t |ƒV  qd S r¼   r½   r•   rS   rS   rT   r—     s     z+_BaseSourceEstimate.data.<locals>.<genexpr>r   zRThe first dimension of the data array must match the number of vertices (%d != %d))	rH   ZasarrayrØ   r«   rK   rÂ   rB   r\   rß   )rà   ÚvalueZn_vertsrS   rS   rT   rC   ü  s    
ÿþc                 C   s*   | j dk	r| j jS | jjd | jjd fS )zShape of the data.Nr   r   )rØ   r\   rÛ   rÜ   r   rS   rS   rT   r\   
  s    
z_BaseSourceEstimate.shapec                 C   s   | j S )zThe first timestamp.)rÙ   r   rS   rS   rT   r>     s    z_BaseSourceEstimate.tminc                 C   s   t |ƒ| _|  ¡  d S r¼   )rG   rÙ   rß   ©rà   r,  rS   rS   rT   r>     s    
c                 C   s   | j S )z?The change in time between two consecutive samples (1 / sfreq).)rÚ   r   rS   rS   rT   r@     s    z_BaseSourceEstimate.tstepc                 C   s&   |dkrt dƒ‚t|ƒ| _|  ¡  d S )Nr   z.tstep must be greater than 0.)rK   rG   rÚ   rß   r-  rS   rS   rT   r@      s    
c                 C   s   | j S )zA timestamp for each sample.)rÞ   r   rS   rS   rT   rã   '  s    z_BaseSourceEstimate.timesc                 C   s   t dƒ‚d S )NzYou cannot write to the .times attribute directly. This property automatically updates whenever .tmin, .tstep or .data changes.)rK   r-  rS   rS   rT   rã   ,  s    c                 C   s,   | j | jt | jd ¡  | _d| jj_dS )z?Update the times attribute after changing tmin, tmax, or tstep.r¾   FN)r>   r@   rH   Úaranger\   rÞ   ÚflagsZ	writeabler   rS   rS   rT   rß   2  s    z!_BaseSourceEstimate._update_timesc                 C   s   |   ¡ }||7 }|S )zAdd source estimates.rø   ©rà   rÉ   rQ   rS   rS   rT   Ú__add__7  s    z_BaseSourceEstimate.__add__c                 C   s@   |   ¡  t|tƒr.t| |ƒ |  j|j7  _n|  j|7  _| S r¼   ©r$  r¥   rÍ   rÌ   rC   ©rà   rÉ   rS   rS   rT   Ú__iadd__=  s    

z_BaseSourceEstimate.__iadd__c                 C   s   |   ¡ }|t| jƒ }|S )z¯Make a summary stc file with mean over time points.

        Returns
        -------
        stc : SourceEstimate | VectorSourceEstimate
            The modified stc.
        )rÂ   rJ   rã   )rà   rg   rS   rS   rT   ÚmeanF  s    z_BaseSourceEstimate.meanc                 C   s\   | j }| j| j|jd   }| j| d }|| j }| j| j jddd�| j||| jd�}|S )z®Make a summary stc file with sum over time points.

        Returns
        -------
        stc : SourceEstimate | VectorSourceEstimate
            The modified stc.
        r¾   ç       @T©ÚaxisÚkeepdims©rB   r>   r@   rš   )rC   r>   r@   r\   rÕ   rÂ   rB   rš   )rà   rC   rë   r>   r@   Zsum_stcrS   rS   rT   rÂ   R  s    
  þz_BaseSourceEstimate.sumc                 C   s   |   ¡ }||8 }|S )zSubtract source estimates.rø   r0  rS   rS   rT   Ú__sub__c  s    z_BaseSourceEstimate.__sub__c                 C   s@   |   ¡  t|tƒr.t| |ƒ |  j|j8  _n|  j|8  _| S r¼   r2  r3  rS   rS   rT   Ú__isub__i  s    

z_BaseSourceEstimate.__isub__c                 C   s
   |   |¡S r¼   )Ú__div__r3  rS   rS   rT   Ú__truediv__r  s    z_BaseSourceEstimate.__truediv__c                 C   s   |   ¡ }|| }|S )zDivide source estimates.rø   r0  rS   rS   rT   r=  u  s    z_BaseSourceEstimate.__div__c                 C   s
   |   |¡S r¼   )Ú__idiv__r3  rS   rS   rT   Ú__itruediv__{  s    z _BaseSourceEstimate.__itruediv__c                 C   s@   |   ¡  t|tƒr.t| |ƒ |  j|j  _n|  j|  _| S r¼   r2  r3  rS   rS   rT   r?  ~  s    

z_BaseSourceEstimate.__idiv__c                 C   s   |   ¡ }||9 }|S )zMultiply source estimates.rø   r0  rS   rS   rT   Ú__mul__‡  s    z_BaseSourceEstimate.__mul__c                 C   s@   |   ¡  t|tƒr.t| |ƒ |  j|j9  _n|  j|9  _| S r¼   r2  r3  rS   rS   rT   Ú__imul__�  s    

z_BaseSourceEstimate.__imul__c                 C   s   |   ¡ }||C }|S r¼   rø   r0  rS   rS   rT   Ú__pow__–  s    z_BaseSourceEstimate.__pow__c                 C   s   |   ¡  |  j|C  _| S r¼   )r$  rC   r3  rS   rS   rT   Ú__ipow__›  s    z_BaseSourceEstimate.__ipow__c                 C   s   | | S r¼   rS   r3  rS   rS   rT   Ú__radd__   s    z_BaseSourceEstimate.__radd__c                 C   s   | | S r¼   rS   r3  rS   rS   rT   Ú__rsub__£  s    z_BaseSourceEstimate.__rsub__c                 C   s   | | S r¼   rS   r3  rS   rS   rT   Ú__rmul__¦  s    z_BaseSourceEstimate.__rmul__c                 C   s   | | S r¼   rS   r3  rS   rS   rT   Ú__rdiv__©  s    z_BaseSourceEstimate.__rdiv__c                 C   s"   |   ¡ }| ¡  | jd9  _|S )zNegate the source estimate.r¾   )r£   r$  rC   ©rà   rQ   rS   rS   rT   Ú__neg__¬  s    z_BaseSourceEstimate.__neg__c                 C   s   | S r¼   rS   r   rS   rS   rT   Ú__pos__³  s    z_BaseSourceEstimate.__pos__c                 C   s    |   ¡ }| ¡  t|jƒ|_|S )zìCompute the absolute value of the data.

        Returns
        -------
        stc : instance of _BaseSourceEstimate
            A version of the source estimate, where the data attribute is set
            to abs(self.data).
        )r£   r$  rç   rØ   rI  rS   rS   rT   Ú__abs__¶  s    	z_BaseSourceEstimate.__abs__c                 C   s   | d S )z¢Take the square root.

        Returns
        -------
        stc : instance of SourceEstimate
            A copy of the SourceEstimate with sqrt(data).
        g      à?rS   r   rS   rS   rT   ÚsqrtÄ  s    z_BaseSourceEstimate.sqrtc                 C   s
   t  | ¡S )z¦Return copy of source estimate instance.

        Returns
        -------
        stc : instance of SourceEstimate
            A copy of the source estimate.
        )r£   Údeepcopyr   rS   rS   rT   r£   Î  s    z_BaseSourceEstimate.copyc                 C   sÜ   |dkr| j }|dkr | jd }t ||| j |¡}t|ƒd }tj| jdd… |f | jj	d�}t
|ƒD ]B}| j|| k| j||d  k @ }	|| jd|	f dd�|d|f< qj|d |d  }
|  ¡ }||_|
|_ ||_|S )	a/  Return a source estimate object with data summarized over time bins.

        Time bins of ``width`` seconds. This method is intended for
        visualization only. No filter is applied to the data before binning,
        making the method inappropriate as a tool for downsampling data.

        Parameters
        ----------
        width : scalar
            Width of the individual bins in seconds.
        tstart : scalar | None
            Time point where the first bin starts. The default is the first
            time point of the stc.
        tstop : scalar | None
            Last possible time point contained in a bin (if the last bin would
            be shorter than width it is dropped). The default is the last time
            point of the stc.
        func : callable
            Function that is applied to summarize the data. Needs to accept a
            numpy.array as first input and an ``axis`` keyword argument.

        Returns
        -------
        stc : SourceEstimate | VectorSourceEstimate
            The binned source estimate.
        Nr¾   r   rX   .©r8  r   r6  )r>   rã   rH   r.  r@   rJ   Úemptyr\   rC   r;   rl   r£   rØ   )rà   ÚwidthZtstartZtstopÚfuncrã   ÚntrC   rm   r™   r>   rQ   rS   rS   rT   ÚbinØ  s     
"  z_BaseSourceEstimate.binc                 C   s  |dkrt ddƒ}| jdkr`| jdkr`| jr4tdƒ || j|d||…f ƒ}t|tƒr^|d }n¢|| jdd…||…f ƒ}t|tƒrŒ|d }|j}t	|ƒdkr¼| 
|d t |dd… ¡¡}t | j|dd…f |¡}t	|ƒdk�r|j
|jd f|dd… žŽ }|S )a   Get data after a linear (time) transform has been applied.

        The transform is applied to each source time course independently.

        Parameters
        ----------
        func : callable
            The transform to be applied, including parameters (see, e.g.,
            :func:`functools.partial`). The first parameter of the function is
            the input data. The first return value is the transformed data,
            remaining outputs are ignored. The first dimension of the
            transformed data has to be the same as the first dimension of the
            input data.
        idx : array | None
            Indicices of source time courses for which to compute transform.
            If None, all time courses are used.
        tmin_idx : int | None
            Index of first time point to include. If None, the index of the
            first time point is used.
        tmax_idx : int | None
            Index of the first time point not to include. If None, time points
            up to (and including) the last time point are included.

        Returns
        -------
        data_t : ndarray
            The transformed data.

        Notes
        -----
        Applying transforms can be significantly faster if the
        SourceEstimate object was created using "(kernel, sens_data)", for
        the "data" parameter as the transform is applied in sensor space.
        Inverse methods, e.g., "apply_inverse_epochs", or "apply_lcmv_epochs"
        do this automatically (if possible).
        Nz[Performance can be improved by not accessing the data attribute before calling this method..r   rb   r   )ÚslicerÛ   rÜ   rÝ   r!   rC   r¥   r×   r\   rJ   rL   rH   Úprodr#  )rà   rR  r™   Útmin_idxÚtmax_idxÚdata_tZsens_data_tZ
data_shaperS   rS   rT   Útransform_data  s(    %




ÿz"_BaseSourceEstimate.transform_datac                    sJ  dˆj  }t t|ˆ|ˆjd�¡d }ˆdkr4d}n|d }|dkrJd}	n|d d }	ˆj||||	d�‰ |dk	r´||tˆjƒk  }
||tˆjƒk tˆjƒ }ˆj|
 }ˆj| }nˆj}ˆj}||g‰|dkrÔdn|}ˆj | ‰ˆ j	dk�r"|�r‡ ‡‡‡fd	d
„t
ˆ jd ƒD ƒ}ntdƒ‚n$|�s,ˆnˆ ¡ }ˆ|_ˆ |_ˆ|_|S )aÓ  Apply linear transform.

        The transform is applied to each source time course independently.

        Parameters
        ----------
        func : callable
            The transform to be applied, including parameters (see, e.g.,
            :func:`functools.partial`). The first parameter of the function is
            the input data. The first two dimensions of the transformed data
            should be (i) vertices and (ii) time.  See Notes for details.
        idx : array | None
            Indices of source time courses for which to compute transform.
            If None, all time courses are used.
        tmin : float | int | None
            First time point to include (ms). If None, self.tmin is used.
        tmax : float | int | None
            Last time point to include (ms). If None, self.tmax is used.
        copy : bool
            If True, return a new instance of SourceEstimate instead of
            modifying the input inplace.

        Returns
        -------
        stcs : SourceEstimate | VectorSourceEstimate | list
            The transformed stc or, in the case of transforms which yield
            N-dimensional output (where N > 2), a list of stcs. For a list,
            copy must be True.

        Notes
        -----
        Transforms which yield 3D
        output (e.g. time-frequency transforms) are valid, so long as the
        first two dimensions are vertices and time.  In this case, the
        copy parameter must be True and a list of
        SourceEstimates, rather than a single instance of SourceEstimate,
        will be returned, one for each index of the 3rd dimension of the
        transformed data.  In the case of transforms yielding 2D output
        (e.g. filtering), the user has the option of modifying the input
        inplace (copy = False) or returning a new instance of
        SourceEstimate (copy = True) with the transformed data.

        Applying transforms can be significantly faster if the
        SourceEstimate object was created using "(kernel, sens_data)", for
        the "data" parameter as the transform is applied in sensor space.
        Inverse methods, e.g., "apply_inverse_epochs", or "apply_lcmv_epochs"
        do this automatically (if possible).
        r?   )r!  r   Nr¾   r   )r™   rW  rX  rb   c                    s2   g | ]*}t ˆ d d …d d …|f ˆˆˆjˆjƒ‘qS r¼   )r¿   r@   rš   )rŠ   rÉ   ©rY  rà   r>   r˜   rS   rT   rŒ   ¤  s
   þ ÿz1_BaseSourceEstimate.transform.<locals>.<listcomp>z@copy must be True if transformed data has more than 2 dimensions)rã   rH   r&  r    r!  rZ  rJ   Ú	lh_vertnoÚ	rh_vertnor«   rl   r\   rK   r£   rB   rC   r>   )rà   rR  r™   r>   rë   r£   rã   Zt_idxrW  rX  Zidx_lhZidx_rhZverts_lhZverts_rhÚstcsrS   r[  rT   Ú	transformQ  s@    2

ÿ

þ
z_BaseSourceEstimate.transformc                   s  t ƒ }ddg}ddg}t||ƒ}t||ƒ}| jj}	| j}
tƒ }dg}| jdk	rtddg}| dt	 
| j|	jd ¡f¡ t| |
|ƒ}
| d|
f¡ tƒ }dgt| jƒ }t| ttfƒrÂdd	g|dd
…< tt|| jƒƒD ]$\}\‰ }| ‡ fdd„|D ƒ¡ qÒt| |	d|||||dd�	}|S )a2  Export data in tabular structure as a pandas DataFrame.

        Vertices are converted to columns in the DataFrame. By default,
        an additional column "time" is added, unless ``index='time'``
        (in which case time values form the DataFrame's index).

        Parameters
        ----------
        %(index_df_evk)s
            Defaults to ``None``.
        %(scalings_df)s
        %(long_format_df_stc)s
        %(time_format_df)s

            .. versionadded:: 0.20
        %(verbose)s

        Returns
        -------
        %(df_return)s
        Útimerš   ÚmsÚ	timedeltaNr   ZVOLZLHZRHrb   c                    s   g | ]}d   ˆ |¡‘qS )z{}_{}©Úformat)rŠ   Zvert©r¶   rS   rT   rŒ   å  s     z5_BaseSourceEstimate.to_data_frame.<locals>.<listcomp>Úsource)Údefault_indexÚ	col_namesZcol_kind)r(   r)   r-   rC   rM   rã   rµ   rš   ÚappendrH   Úrepeatr\   r*   rJ   rB   r¥   Ú_BaseSurfaceSourceEstimateÚ_BaseMixedSourceEstimateÚ	enumerater§   Úextendr,   )rà   ÚindexZscalingsZlong_formatÚtime_formatr   ÚpdZvalid_index_argsZvalid_time_formatsrC   rã   Zmindexrg  rh  ÚkindsÚiiÚvertnoZdfrS   re  rT   Úto_data_frame³  s8    


ÿ þz!_BaseSourceEstimate.to_data_frame)NN)NNrç   FF)rð   FN)rö   )r„   )Nrþ   r°   rð   rð   rÿ   TrŽ   rð   NNrð   Trð   r   r  r  NNrä   rð   r  Nrð   NrŽ   r  NNN)NNT)rð   r)  NN)NNN)NNNF)NNFN)8rÖ   Ú
__module__Ú__qualname__rÎ   r   rá   ræ   r#   rï   rô   rú   rý   r"   r3   r  Úpropertyr!  ré   r$  r(  r   rC   Úsetterr\   r>   r@   rã   rß   r1  r4  r5  rÂ   r;  r<  r>  r=  r@  r?  rA  rB  rC  rD  rE  rF  rG  rH  rJ  rK  rL  rM  r£   rH   rT  rZ  r_  ru  rS   rS   rS   rT   rÍ   Â  sâ      ÿ;    ÿ    ÿ                                              ÷

  ÿ.








				

.
K
b    ÿþrÍ   c              	   C   s"  |dk  ¡ s|dk  ¡ r tdƒ‚t|dd�}tt ||d|d | ¡ƒ}|dkrV| }n\|dkrtt |d j	d ¡}n>t
|tƒr¦|jdkr”|d	kr”d
nd}|| d }nt |t¡}|d | dd…f j}tj|| d
d�t |¡ }	t t tj|d |dd…f |	 d d
d�¡¡}
||
 }
|
S )z%Find the center of mass on a surface.r   zUAll values must be non-negative and at least one must be non-zero, cannot compute COMTrÒ   ÚsurfÚ.Fr}   r±   r   rt  NrO  rb   )r¡   r“   rK   r   r   r‡   ÚjoinrH   r.  r\   r¥   r   r¶   rZ   rI   rM   rÂ   ZargminrM  r5  )rB   Úvaluesr  rz  rš   r  Úrestrict_verticesr™   ÚposZc_o_mÚvertexrS   rS   rT   Ú_center_of_massí  s2    
ÿ
ÿÿÿ
r�  c                       s„   e Zd ZdZdZdZedd„ ƒZedd„ ƒZedd	„ ƒZ	ed
d„ ƒZ
dd„ Zdd„ Zdd„ Zeddd„ƒZed‡ fdd„	ƒZ‡  ZS )rk  a¾  Abstract base class for surface source estimates.

    Parameters
    ----------
    data : array
        The data in source space.
    vertices : list of array, shape (2,)
        Vertex numbers corresponding to the data. The first element of the list
        contains vertices of left hemisphere and the second element contains
        vertices of right hemisphere.
    %(tmin)s
    %(tstep)s
    %(subject_optional)s
    %(verbose)s

    Attributes
    ----------
    subject : str | None
        The subject name.
    times : array of shape (n_times,)
        The time vector.
    vertices : list of array, shape (2,)
        Vertex numbers corresponding to the data. The first element of the list
        contains vertices of left hemisphere and the second element contains
        vertices of right hemisphere.
    data : array
        The data in source space.
    shape : tuple
        The shape of the data. A tuple of int (n_dipoles, n_times).
    r}   rb   c                 C   s   | j dt| jƒ… S )zLeft hemisphere data.N©rC   rJ   r\  r   rS   rS   rT   Úlh_data+  s    z"_BaseSurfaceSourceEstimate.lh_datac                 C   s   | j t| jƒd… S )zRight hemisphere data.Nr‚  r   rS   rS   rT   Úrh_data0  s    z"_BaseSurfaceSourceEstimate.rh_datac                 C   s
   | j d S )zLeft hemisphere vertno.r   ©rB   r   rS   rS   rT   r\  5  s    z$_BaseSurfaceSourceEstimate.lh_vertnoc                 C   s
   | j d S )zRight hemisphere vertno.r   r…  r   rS   rS   rT   r]  :  s    z$_BaseSurfaceSourceEstimate.rh_vertnoc                 C   sv   |j dkr| jd }n
| jd }t t ||j¡¡d }|| }|j dkrd| j|t| jd ƒ  }n
| j| }||fS )Nr°   r   r   r±   )r  rB   rH   ZnonzeroÚin1drC   rJ   )rà   ÚlabelZstc_verticesr™   rB   r}  rS   rS   rT   Ú_hemilabel_stc?  s    



z)_BaseSurfaceSourceEstimate._hemilabel_stcc                 C   s*  ddl m}m} t|||fdƒ |jdk	rT| jdk	rT|j| jkrTtd|j| jf ƒ‚|jdkr–|  |j¡\}}|  |j	¡\}}||g}t
 ||f¡}	nV|jdkrÀ|  |¡\}}	|t
 g t¡g}n,|jdksÎt‚|  |¡\}}	t
 g t¡|g}td	d
„ |D ƒƒdk�rtdƒ‚| j|	|| j| j| jd�}
|
S )a4  Get a source estimate object restricted to a label.

        SourceEstimate contains the time course of
        activation of all sources inside the label.

        Parameters
        ----------
        label : Label | BiHemiLabel
            The label (as created for example by mne.read_label). If the label
            does not match any sources in the SourceEstimate, a ValueError is
            raised.

        Returns
        -------
        stc : SourceEstimate | VectorSourceEstimate
            The source estimate restricted to the given label.
        r   )ÚLabelÚBiHemiLabelr‡  NzClabel and stc must have same subject names, currently "%s" and "%s"Úbothr°   r±   c                 S   s   g | ]}t |ƒ‘qS rS   r½   r•   rS   rS   rT   rŒ   {  s     z7_BaseSurfaceSourceEstimate.in_label.<locals>.<listcomp>r   z+No vertices match the label in the stc filer:  )r‡  r‰  rŠ  r%   rš   r    r  rˆ  r°   r±   rH   ÚvstackrZ   rI   rs   rÂ   rK   rÕ   r>   r@   )rà   r‡  r‰  rŠ  Zlh_vertZlh_valZrh_vertZrh_valrB   r}  Ú	label_stcrS   rS   rT   Úin_labelS  s8    
ÿÿÿ

 ÿz#_BaseSurfaceSourceEstimate.in_labelc           	      C   s  t |tƒstdƒ‚t| jƒt|ƒks,tdƒ‚|  ¡  tƒ }dg}tt| j|ƒƒD ]T\}\}}t	 
||¡}t	 ||¡}|| ¡ g7 }|t|ƒg7 }t	 |||¡| j|< qPdd„ t||dd… ƒD ƒ}t	 |¡}t	 t|ƒf| jjdd…  ¡}t	j| j||dd	�| _| S )
aç  Expand SourceEstimate to include more vertices.

        This will add rows to stc.data (zero-filled) and modify stc.vertices
        to include all vertices in stc.vertices and the input vertices.

        Parameters
        ----------
        vertices : list of array
            New vertices to add. Can also contain old values.

        Returns
        -------
        stc : SourceEstimate | VectorSourceEstimate
            The modified stc (note: method operates inplace).
        zvertices must be a listz2vertices must have the same length as stc.verticesr   c                 S   s   g | ]\}}|| ‘qS rS   rS   )rŠ   rs  r=   rS   rS   rT   rŒ   ¤  s     z5_BaseSurfaceSourceEstimate.expand.<locals>.<listcomp>Nr¾   r   rO  )r¥   rµ   Ú	TypeErrorrJ   rB   rK   r$  rm  r§   rH   Z	setdiff1dÚsearchsortedr£   Úinsertrê   rj   rC   r\   )	rà   rB   Z	insertersÚoffsetsÚviZv_oldZv_newZindsZnew_datarS   rS   rT   Úexpand‚  s$    

 z!_BaseSurfaceSourceEstimate.expandNc                 C   s\   | j dkrtdƒ‚t|dd�}t||ƒ}t| j||| j |ƒ\}}|  | j| || j| j	|¡S )aá  Get a source estimate from morphed source to the original subject.

        Parameters
        ----------
        src_orig : instance of SourceSpaces
            The original source spaces that were morphed to the current
            subject.
        subject_orig : str | None
            The original subject. For most source spaces this shouldn't need
            to be provided, since it is stored in the source space itself.
        %(subjects_dir)s
        %(verbose)s

        Returns
        -------
        stc : SourceEstimate | VectorSourceEstimate
            The transformed source estimate.

        See Also
        --------
        morph_source_spaces

        Notes
        -----
        .. versionadded:: 0.10.0
        Nzstc.subject must be setr}   re  )
rš   rK   r   r   r   rB   rÕ   rØ   r>   r@   )rà   Zsrc_origZsubject_origr  r   Zdata_idxrB   rS   rS   rT   Úto_original_srcª  s     

    ÿ  ÿz*_BaseSurfaceSourceEstimate.to_original_srcrç   Fc                    s¢   t d|dƒ d}|dk	rh|dkr2| j}| jg g}	nt| jd ƒ}| j}g | jg}	|  ||	| j| j	¡j
}
ntƒ j
}
|
|||||d�}|rž|rž|d | |d f}|S )a  Get location and latency of peak amplitude.

        Parameters
        ----------
        hemi : {'lh', 'rh', None}
            The hemi to be considered. If None, the entire source space is
            considered.
        %(get_peak_parameters)s

        Returns
        -------
        pos : int
            The vertex exhibiting the maximum response, either ID or index.
        latency : float | int
            The time point of the maximum response, either latency in seconds
            or index.
        r  )r°   r±   Nr   Nr°   )r>   rë   rì   rí   rî   r   )r$   rƒ  r\  rJ   rB   r„  r]  rÕ   r>   r@   rï   Úsuper)rà   r  r>   rë   rì   rí   rî   Zvertex_offsetrC   rB   Úmethrg   ©rÕ   rS   rT   rï   Ð  s.    
   ÿþz#_BaseSurfaceSourceEstimate.get_peak)NNN)NNNrç   FF)rÖ   rv  rw  Ú__doc__rÏ   rÐ   rx  rƒ  r„  r\  r]  rˆ  rŽ  r”  r   r•  r#   rï   Ú__classcell__rS   rS   r˜  rT   rk    s0   



/(    ÿ%    ÿrk  c                       sJ   e Zd ZdZeddddœ‡ fdd„ƒZeddd	„ƒZeddd„ƒZ‡  Z	S )r¿   a:  Container for surface source estimates.

    Parameters
    ----------
    data : array of shape (n_dipoles, n_times) | tuple, shape (2,)
        The data in source space. When it is a single array, the
        left hemisphere is stored in data[:len(vertices[0])] and the right
        hemisphere is stored in data[-len(vertices[1]):].
        When data is a tuple, it contains two arrays:

        - "kernel" shape (n_vertices, n_sensors) and
        - "sens_data" shape (n_sensors, n_times).

        In this case, the source space data corresponds to
        ``np.dot(kernel, sens_data)``.
    vertices : list of array, shape (2,)
        Vertex numbers corresponding to the data. The first element of the list
        contains vertices of left hemisphere and the second element contains
        vertices of right hemisphere.
    %(tmin)s
    %(tstep)s
    %(subject_optional)s
    %(verbose)s

    Attributes
    ----------
    subject : str | None
        The subject name.
    times : array of shape (n_times,)
        The time vector.
    vertices : list of array, shape (2,)
        The indices of the dipoles in the left and right source space.
    data : array of shape (n_dipoles, n_times)
        The data in source space.
    shape : tuple
        The shape of the data. A tuple of int (n_dipoles, n_times).

    See Also
    --------
    VectorSourceEstimate : A container for vector source estimates.
    VolSourceEstimate : A container for volume source estimates.
    MixedSourceEstimate : A container for mixed surface + volume source
                          estimates.
    rQ   FNrû   c          	         sl  t |dd�}td|dddgƒ | jdt| jƒ… }| jt| jƒ d… }|dkrÀt | j¡rdtdƒ‚t	 
d	¡ t |d
 |d�}t |d |d�}t|| j| j| j|d� t|| j| j| j|d� nž|dk�rD| jd dkràtdƒ‚t	 
d¡ t |d |d�}t |d |d�}t|| j|dd…df d� t|| j|dd…df d� n|dk�r^tƒ j||d� t	 
d¡ dS )af  Save the source estimates to a file.

        Parameters
        ----------
        fname : str
            The stem of the file name. The file names used for surface source
            spaces are obtained by adding "-lh.stc" and "-rh.stc" (or "-lh.w"
            and "-rh.w") to the stem provided, for the left and the right
            hemisphere, respectively.
        ftype : str
            File format to use. Allowed values are "stc" (default), "w",
            and "h5". The "w" format only supports a single time point.
        %(overwrite)s

            .. versionadded:: 1.0
        %(verbose)s
        Trü   r­   rQ   rn   r„   Nz™Cannot save complex-valued STC data in FIFF format; please set ftype='h5' to save in HDF5 format instead, or cast the data to real numbers before saving.úWriting STC to disk...r~   ©rw   r   ©r>   r@   rB   rC   r   z,w files can only contain a single time pointú!Writing STC to disk (w format)...r€   r�   r   ©rB   rC   ú[done])r1   r$   rC   rJ   r\  r]  rH   ZiscomplexobjrK   r   Úinfor]   r>   r@   r\   rt   r–  rý   )	rà   rv   r­   rw   r   rƒ  r„  Zfname_lZfname_rr˜  rS   rT   rý   )  s:    
 ÿ ÿ


zSourceEstimate.savec                 C   s  ddl m}m} ddlm} t||dƒ t|tdƒ t|tdƒ t| ƒ | j	dk 
¡ r^tdƒ ||d	d
d�}||||d	ddd
d	dd
dd
dd�\	}}	}	}	}	}	}	}}	|d d }|d }
|| j}t |d ¡}d|
 tj|| dd	d� }|  ¡ }dt | j	| j	 | ¡ |jdd…< |S )a—  Compute time-varying SNR in the source space.

        This function should only be used with source estimates with units
        nanoAmperes (i.e., MNE-like solutions, *not* dSPM or sLORETA).
        See also :footcite:`GoldenholzEtAl2009`.

        .. warning:: This function currently only works properly for fixed
                     orientation.

        Parameters
        ----------
        %(info_not_none)s
        fwd : instance of Forward
            The forward solution used to create the source estimate.
        cov : instance of Covariance
            The noise covariance used to estimate the resting cortical
            activations. Should be an evoked covariance, not empty room.
        %(verbose)s

        Returns
        -------
        snr_stc : instance of SourceEstimate
            The source estimate with the SNR computed.

        Notes
        -----
        We define the SNR in decibels for each source location at each
        time point as:

        .. math::

            {\rm SNR} = 10\log_10[\frac{a^2}{N}\sum_k\frac{b_k^2}{s_k^2}]

        where :math:`\\b_k` is the signal on sensor :math:`k` provided by the
        forward model for a source with unit amplitude, :math:`a` is the
        source amplitude, :math:`N` is the number of sensors, and
        :math:`s_k^2` is the noise variance on sensor :math:`k`.

        References
        ----------
        .. footbibliography::
        r   )Úconvert_forward_solutionÚForward)Ú_prepare_forwardÚfwdr¡  Úcovr   zhThis STC appears to be from free orientation, currently SNR function is valid only for fixed orientationTF)Zsurf_oriZforce_fixedNZfro)
ZfixedÚlooseZrankÚpcaÚuse_cpsÚexpZlimit_depth_chsZcombine_xyzZallow_fixed_depthÚlimitZsolrC   Údimr7  rÿ   )Úforwardr¢  r£  Zminimum_norm.inverser¤  r%   r7   r   r'   rC   r¡   r!   rM   rH   ZdiagrÂ   r£   Úlog10rØ   )rà   r¡  r¥  r¦  r   r¢  r£  r¤  ÚGr²   Z
n_channelsZb_k2Zs_k2ZscalingZsnr_stcrS   rS   rT   Úestimate_snr\  s@    ,          ý
$zSourceEstimate.estimate_snrÚspherec              	      sf  t |tƒstdt|ƒf ƒ‚t| j|ƒ}t | jdk ¡r@t	dƒ‚tj
| jdd�‰ t t| jd ƒ¡t t| jd ƒ¡t| jd ƒ g}|dkrÌt t ‡ fdd„|D ƒ¡¡d }t|ƒdksÄt	d	ƒ‚|d }td
|ddgƒ | j| }ˆ ||  ‰ ~t|ˆ ddg| ||||d�}tj
| jdd� t¡}	t 
|	t | jd ¡ ¡t 
|	¡ }
| j| j|
  }|||fS )a	
  Compute the center of mass of activity.

        This function computes the spatial center of mass on the surface
        as well as the temporal center of mass as in :footcite:`LarsonLee2013`.

        .. note:: All activity must occur in a single hemisphere, otherwise
                  an error is raised. The "mass" of each point in space for
                  computing the spatial center of mass is computed by summing
                  across time, and vice-versa for each point in time in
                  computing the temporal center of mass. This is useful for
                  quantifying spatio-temporal cluster locations, especially
                  when combined with :func:`mne.vertex_to_mni`.

        Parameters
        ----------
        subject : str | None
            The subject the stc is defined for.
        hemi : int, or None
            Calculate the center of mass for the left (0) or right (1)
            hemisphere. If None, one of the hemispheres must be all zeroes,
            and the center of mass will be calculated for the other
            hemisphere (useful for getting COM for clusters).
        restrict_vertices : bool | array of int | instance of SourceSpaces
            If True, returned vertex will be one from stc. Otherwise, it could
            be any vertex from surf. If an array of int, the returned vertex
            will come from that array. If instance of SourceSpaces (as of
            0.13), the returned vertex will be from the given source space.
            For most accuruate estimates, do not restrict vertices.
        %(subjects_dir)s
        surf : str
            The surface to use for Euclidean distance center of mass
            finding. The default here is "sphere", which finds the center
            of mass on the spherical surface to help avoid potential issues
            with cortical folding.

        Returns
        -------
        vertex : int
            Vertex of the spatial center of mass for the inferred hemisphere,
            with each vertex weighted by the sum of the stc across time. For a
            boolean stc, then, this would be weighted purely by the duration
            each vertex was active.
        hemi : int
            Hemisphere the vertex was taken from.
        t : float
            Time of the temporal center of mass (weighted by the sum across
            source vertices).

        See Also
        --------
        mne.Label.center_of_mass
        mne.vertex_to_mni

        References
        ----------
        .. footbibliography::
        zsurf must be a string, got %sr   z'Cannot compute COM with negative valuesr   rO  Nc                    s   g | ]}t  ˆ | ¡‘qS rS   ©rH   rÂ   )rŠ   r“  ©r}  rS   rT   rŒ   ç  s   ÿz1SourceEstimate.center_of_mass.<locals>.<listcomp>zCould not infer hemispherer  r°   r±   )r  rz  rš   r  r~  )r¥   Ústrr�  rÈ   r   rš   rH   r“   rC   rK   rÂ   r.  rJ   rB   r&  rZ   r$   r�  re   rG   r\   r>   r@   )rà   rš   r  r~  r  rz  Z	vert_indsrB   r€  ZmassesZt_indÚtrS   r³  rT   Úcenter_of_mass¢  sF    <
 ÿÿÿ
  
  ý$zSourceEstimate.center_of_mass)rQ   )N)NNFNr±  )
rÖ   rv  rw  r™  r   rý   r°  r#   r¶  rš  rS   rS   r˜  rT   r¿   ú  s   -2E    ÿr¿   c                       sV   e Zd ZdZed‡ fdd„	ƒZdd„ Zdd„ Zedd
d„ƒZ	e
eƒddd„ƒZ‡  ZS )Ú_BaseVectorSourceEstimater^   Nc                    s(   t | dƒst‚tƒ  ||||||¡ d S )Nr¬   )rÔ   rs   r–  rá   ©rà   rC   rB   r>   r@   rš   r   r˜  rS   rT   rá   ÿ  s    z"_BaseVectorSourceEstimate.__init__c                 C   s,   t jj| jdd�}|  || j| j| j| j¡S )zÌCompute magnitude of activity without directionality.

        Returns
        -------
        stc : instance of SourceEstimate
            The source estimate without directionality information.
        r   rO  )	rH   ÚlinalgÚnormrC   r¬   rB   r>   r@   rš   )rà   Zdata_magrS   rS   rT   rè     s        ÿz#_BaseVectorSourceEstimate.magnitudec                    s$   t  ‡ fdd„t|| jƒD ƒ¡}|S )Nc                    s   g | ]\}}t |ˆ |ƒ‘qS rS   )r   )rŠ   rä   r–   ©r©  rS   rT   rŒ     s     z>_BaseVectorSourceEstimate._get_src_normals.<locals>.<listcomp>)rH   rŒ  r§   rB   )rà   r·   r©  ÚnormalsrS   r»  rT   Ú_get_src_normals  s    
ÿz*_BaseVectorSourceEstimate._get_src_normalsTc                 C   sü  t |ttjfdƒ t |dtfdƒ t|tƒ�r–td|ddd� |dkrp|dkrVtdƒ‚td|ƒ |  	||¡}�n&|d	ks|t
‚| j}t | j¡sætd
| jjtjtjfƒ |jtjkr¸tjntj}| |¡}|jd d| jjd  ksæt
‚tjj|dd�\}}}|dd…dd…df }|dk�r<tj|dd…df jddd�}	n |  	||¡}
tj||
 ddd�}	|	j| jjd dfk�sxt
‚t |	¡}	d|	|	dk< ||	9 }td|j| jjd dfgƒ t |dd…tjf | j¡dd…df }|  || j| j| j| j¡}||fS )aY  Project the data for each vertex in a given direction.

        Parameters
        ----------
        directions : ndarray, shape (n_vertices, 3) | str
            Can be:

            - ``'normal'``
                Project onto the source space normals.
            - ``'pca'``
                SVD will be used to project onto the direction of maximal
                power for each source.
            - :class:`~numpy.ndarray`, shape (n_vertices, 3)
                Projection directions for each source.
        src : instance of SourceSpaces | None
            The source spaces corresponding to the source estimate.
            Not used when ``directions`` is an array, optional when
            ``directions='pca'``.
        %(use_cps)s
            Should be the same value that was used when the forward model
            was computed (typically True).

        Returns
        -------
        stc : instance of SourceEstimate
            The projected source estimate.
        directions : ndarray, shape (n_vertices, 3)
            The directions that were computed (or just used).

        Notes
        -----
        When using SVD, there is a sign ambiguity for the direction of maximal
        power. When ``src is None``, the direction is chosen that makes the
        resulting time waveform sum positive (i.e., have positive amplitudes).
        When ``src`` is provided, the directions are flipped in the direction
        of the source normals, i.e., outward from cortex for surface source
        spaces and in the +Z / superior direction for volume source spaces.

        .. versionadded:: 0.21
        Ú
directionsNr·   )Únormalr¨  zwhen str)Úextrar¿  z*If directions="normal", src cannot be Noner¨  zstc.data.dtyper¾   rb   F©Zfull_matricesr   r   Tr7  rŽ   zdirections.shaper^   ) r%   r´  rH   r¦   r   r¥   r$   rK   r&   r½  rs   rC   Z	isrealobjr;   Z	complex64Z
complex128rk   r+  Úviewr\   r¹  ZsvdrÂ   ÚrealÚsignrÃ   r¢   r¬   rB   r>   r@   rš   )rà   r¾  r·   r©  râ   r;   Úur²   r–   Zsignsr¼  Z	data_normrQ   rS   rS   rT   Úproject  s^    *ÿÿ


ÿÿ

 
  ÿ(    ÿz!_BaseVectorSourceEstimate.projectr°   Úhotrð   rÿ   çš™™™™™Ù?rŽ   Úlateralr   r  r  rä   r  c                  C   sD   t | |||||||||	|
|||||||||||||||||||d�S ©N)rš   r  r  r  r  r	  Úbrain_alphaÚoverlay_alphaÚvector_alphaÚscale_factorr  r  r  r  r  r  r  r  r  r  r  r  r  r·   r  r  r  r  r   )r4   ©rà   rš   r  r  r  r  r	  rË  rÌ  rÍ  rÎ  r  r  r  r  r  r  r  r  r  r  r  r  r  r·   r  r  r  r  r   rS   rS   rT   r  j  s@                      ôz_BaseVectorSourceEstimate.plot)NNNNN)NT)Nr°   rÇ  rð   rÿ   TrÈ  NrŽ   Nrð   NNrÉ  Trð   r   r  r  NNrä   rð   NrŽ   r  NNN)rÖ   rv  rw  rÎ   r   rá   rè   r½  r#   rÆ  r"   r4   r  rš  rS   rS   r˜  rT   r·  û  sL       ÿS                                          ÷r·  c                       sˆ   e Zd ZdZdZeeƒd%‡ fdd„	ƒZeeƒd&dd„ƒZ	e
d'dddœdd„ƒZe
ddœdd„ƒZe
d(ddd œd!d"„ƒZd)d#d$„Z‡  ZS )*Ú_BaseVolSourceEstimater|   NÚwhiter‹  rð   rÿ   Tçš™™™™™¹?Úaxialr   r  r  rä   r  rŽ   r  c                     sH   t ƒ j|||||||||	|
||||||||||||||||||||d�S )N)rš   r}   r  r  r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r�   r  r·   r  r  r  r  r   )r–  r  )rà   rš   r}   r  r  r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r�   r  r·   r  r  r  r  r   r˜  rS   rT   Úplot_3d‰  s@                       õz_BaseVolSourceEstimate.plot_3dÚstat_mapúT1.mgzc                 C   s:   | j dkr|  ¡ n| }t||||||||||	|
|||d�S )Nr^   )r·   rš   r  rì   Úbg_imgr  r  r  r	  Úshowr  Úinitial_posr   )rÎ   rè   r5   )rà   r·   rš   r  rì   r×  r  r  r  r	  rØ  r  rÙ  r   rC   rS   rS   rT   r  ¡  s"             ûz_BaseVolSourceEstimate.plotF©Úmri_resolutionr   c             
   C   s   t | |||d|||d�S )an  Extract label time courses for lists of labels.

        This function will extract one time course for each label. The way the
        time courses are extracted depends on the mode parameter.

        Parameters
        ----------
        %(labels_eltc)s
        %(src_eltc)s
        %(mode_eltc)s
        %(allow_empty_eltc)s
        %(mri_resolution_eltc)s
        %(verbose)s

        Returns
        -------
        %(label_tc_el_returns)s

        See Also
        --------
        extract_label_time_course : Extract time courses for multiple STCs.

        Notes
        -----
        %(eltc_mode_notes)s
        F)rì   rñ   rò   rÛ  r   ró   )rà   rõ   r·   rì   rò   rÛ  r   rS   rS   rT   rô   ¯  s         ýz0_BaseVolSourceEstimate.extract_label_time_courser÷   c          
      C   sÆ   t | jƒdkrtdƒ‚t|tdfdƒ t|tƒr8|g}nd| t|ƒi}t|||fdd�}t |ƒdksjt‚|d }|j}t	 
| jd |j¡}| j| | jd | g }}| j||| j| j| jd	�}	|	S )
a*  Get a source estimate object restricted to a label.

        SourceEstimate contains the time course of
        activation of all sources inside the label.

        Parameters
        ----------
        label : str | int
            The label to use. Can be the name of a label if using a standard
            FreeSurfer atlas, or an integer value to extract from the ``mri``.
        mri : str
            Path to the atlas to use.
        src : instance of SourceSpaces
            The volumetric source space. It must be a single, whole-brain
            volume.
        %(verbose)s

        Returns
        -------
        stc : VolSourceEstimate | VolVectorSourceEstimate
            The source estimate restricted to the given label.

        Notes
        -----
        .. versionadded:: 0.21.0
        r   zBThis method can only be used with whole-brain volume source spaceszint-liker‡  zVolume ID %sF)rÛ  r   r:  )rJ   rB   r    r%   r´  r¥   r+   Ú_volume_labelsrs   rH   r†  rC   rÕ   r>   r@   rš   )
rà   r‡  Úmrir·   r   Zvolume_labelrB   Zkeepr}  r�  rS   rS   rT   rŽ  Ò  s"    
 ÿz_BaseVolSourceEstimate.in_labelrÝ  Únifti1rû   c          
      C   sB   ddl }t|ddƒ t||d�}| j||||d�}	| |	|¡ dS )a%  Save a volume source estimate in a NIfTI file.

        Parameters
        ----------
        fname : str
            The name of the generated nifti file.
        src : list
            The list of source spaces (should all be of type volume).
        dest : 'mri' | 'surf'
            If 'mri' the volume is defined in the coordinate system of
            the original T1 image. If 'surf' the coordinate system
            of the FreeSurfer surface is used (Surface RAS).
        mri_resolution : bool
            It True the image is saved in MRI resolution.

            .. warning:: If you have many time points, the file produced can be
                         huge.
        format : str
            Either 'nifti1' (default) or 'nifti2'.

            .. versionadded:: 0.17
        %(overwrite)s

            .. versionadded:: 1.0
        %(verbose)s

            .. versionadded:: 1.0

        Returns
        -------
        img : instance Nifti1Image
            The image object.

        Notes
        -----
        .. versionadded:: 0.9.0
        r   Nru   rv   rü   )ÚdestrÛ  rd  )Znibabelr%   r1   Ú	as_volumerý   )
rà   rv   r·   rß  rÛ  rd  rw   r   ZnibZimgrS   rS   rT   Úsave_as_volume   s    (
ÿz%_BaseVolSourceEstimate.save_as_volumec                 C   s4   ddl m} | jdkr|  ¡ n| }||||d|d�S )a‰  Export volume source estimate as a nifti object.

        Parameters
        ----------
        src : instance of SourceSpaces
            The source spaces (should all be of type volume, or part of a
            mixed source space).
        dest : 'mri' | 'surf'
            If 'mri' the volume is defined in the coordinate system of
            the original T1 image. If 'surf' the coordinate system
            of the FreeSurfer surface is used (Surface RAS).
        mri_resolution : bool
            It True the image is saved in MRI resolution.

            .. warning:: If you have many time points, the file produced can be
                         huge.
        format : str
            Either 'nifti1' (default) or 'nifti2'.

        Returns
        -------
        img : instance of Nifti1Image
            The image object.

        Notes
        -----
        .. versionadded:: 0.9.0
        r   )Ú_interpolate_datar^   T)rÛ  Z	mri_spaceÚoutput)Zmorphrâ  rÎ   rè   )rà   r·   rß  rÛ  rd  râ  rC   rS   rS   rT   rà  /  s     ÿz _BaseVolSourceEstimate.as_volume)NrÑ  r‹  rð   rð   rÿ   TrÒ  rð   NNrÓ  Trð   r   r  r  NNrä   rð   r  Nrð   NrŽ   r  NNN)NNrÕ  rÖ  Trð   rð   rð   TNNN)rð   F)rÝ  FrÞ  )rÝ  FrÞ  )rÖ   rv  rw  rÏ   rÐ   r"   r3   rÔ  r5   r  r   rô   rŽ  rá  rà  rš  rS   rS   r˜  rT   rÐ  „  s~                                                 ÷                ý  ÿ þ"-  ÿ ÿ.  ÿrÐ  c                       s.   e Zd ZdZeddddœ‡ fdd„ƒZ‡  ZS )	rÀ   a   Container for volume source estimates.

    Parameters
    ----------
    data : array of shape (n_dipoles, n_times) | tuple, shape (2,)
        The data in source space. The data can either be a single array or
        a tuple with two arrays: "kernel" shape (n_vertices, n_sensors) and
        "sens_data" shape (n_sensors, n_times). In this case, the source
        space data corresponds to ``np.dot(kernel, sens_data)``.
    %(vertices_volume)s
    %(tmin)s
    %(tstep)s
    %(subject_optional)s
    %(verbose)s

    Attributes
    ----------
    subject : str | None
        The subject name.
    times : array of shape (n_times,)
        The time vector.
    %(vertices_volume)s
    data : array of shape (n_dipoles, n_times)
        The data in source space.
    shape : tuple
        The shape of the data. A tuple of int (n_dipoles, n_times).

    See Also
    --------
    SourceEstimate : A container for surface source estimates.
    VolVectorSourceEstimate : A container for volume vector source estimates.
    MixedSourceEstimate : A container for mixed surface + volume source
                          estimates.

    Notes
    -----
    .. versionadded:: 0.9.0
    rQ   FNrû   c                   s  t |dd�}td|dddgƒ |dkr<t| jƒdkr<tdƒ‚|dkrX| jjd	krXtd
ƒ‚|dkr¨t d¡ | 	d¡s||d7 }t ||d�}t
|| j| j| jd | jd� nd|dkrðt d¡ | 	d¡sÌ|d7 }t ||d�}t|| jd | jd� n|dk�rtƒ j|d|d� t d¡ dS )a½  Save the source estimates to a file.

        Parameters
        ----------
        fname : str
            The stem of the file name. The stem is extended with "-vl.stc"
            or "-vl.w".
        ftype : str
            File format to use. Allowed values are "stc" (default), "w",
            and "h5". The "w" format only supports a single time point.
        %(overwrite)s

            .. versionadded:: 1.0
        %(verbose)s
        Trü   r­   rQ   rn   r„   r   zVCan only write to .stc or .w if a single volume source space was used, use .h5 insteadÚcomplexz>Can only write non-complex data to .stc or .w, use .h5 insteadr›  )rx   ry   rx   rœ  r   r�  rž  )rz   r{   rz   rŸ  r   N)r1   r$   rJ   rB   rK   rC   r;   r   r¡  rž   r]   r>   r@   rt   r–  rý   )rà   rv   r­   rw   r   r˜  rS   rT   rý   |  s0    

 ÿ


zVolSourceEstimate.save)rQ   )rÖ   rv  rw  r™  r   rý   rš  rS   rS   r˜  rT   rÀ   S  s   'rÀ   c                   @   s&   e Zd ZdZeZeeƒddd„ƒZdS )r¨   aõ  Container for volume source estimates.

    Parameters
    ----------
    data : array of shape (n_dipoles, 3, n_times)
        The data in source space. Each dipole contains three vectors that
        denote the dipole strength in X, Y and Z directions over time.
    %(vertices_volume)s
    %(tmin)s
    %(tstep)s
    %(subject_optional)s
    %(verbose)s

    Attributes
    ----------
    subject : str | None
        The subject name.
    times : array of shape (n_times,)
        The time vector.
    %(vertices_volume)s
    data : array of shape (n_dipoles, n_times)
        The data in source space.
    shape : tuple
        The shape of the data. A tuple of int (n_dipoles, n_times).

    See Also
    --------
    SourceEstimate : A container for surface source estimates.
    VectorSourceEstimate : A container for vector source estimates.
    MixedSourceEstimate : A container for mixed surface + volume source
                          estimates.

    Notes
    -----
    .. versionadded:: 0.9.0
    Nr‹  rÇ  rð   rÿ   TrÈ  rŽ   rÓ  r   r  r  rä   r  c                  C   sF   t j| |||||||||	|
|||||||||||||||||||d�S rÊ  )r·  r  rÏ  rS   rS   rT   rÔ  Ó  s@                      ôzVolVectorSourceEstimate.plot_3d)Nr‹  rÇ  rð   rÿ   TrÈ  NrŽ   Nrð   NNrÓ  Trð   r   r  r  NNrä   rð   NrŽ   r  NNN)	rÖ   rv  rw  r™  rÀ   r¬   r"   r4   rÔ  rS   rS   rS   rT   r¨   ¨  s>   %                                          õr¨   c                   @   s   e Zd ZdZeZdS )rª   aÄ  Container for vector surface source estimates.

    For each vertex, the magnitude of the current is defined in the X, Y and Z
    directions.

    Parameters
    ----------
    data : array of shape (n_dipoles, 3, n_times)
        The data in source space. Each dipole contains three vectors that
        denote the dipole strength in X, Y and Z directions over time.
    vertices : list of array, shape (2,)
        Vertex numbers corresponding to the data. The first element of the list
        contains vertices of left hemisphere and the second element contains
        vertices of right hemisphere.
    %(tmin)s
    %(tstep)s
    %(subject_optional)s
    %(verbose)s

    Attributes
    ----------
    subject : str | None
        The subject name.
    times : array of shape (n_times,)
        The time vector.
    shape : tuple
        The shape of the data. A tuple of int (n_dipoles, n_times).

    See Also
    --------
    SourceEstimate : A container for surface source estimates.
    VolSourceEstimate : A container for volume source estimates.
    MixedSourceEstimate : A container for mixed surface + volume source
                          estimates.

    Notes
    -----
    .. versionadded:: 0.15
    N)rÖ   rv  rw  r™  r¿   r¬   rS   rS   rS   rT   rª   ï  s   (rª   c                       sF   e Zd ZdZdZed‡ fdd„	ƒZedd„ ƒZdd„ Z	d	d
„ Z
‡  ZS )rl  r�   Nc                    s:   t |tƒrt|ƒdk rtdƒ‚tƒ j||||||d� d S )Nrb   zHVertices must be a list of numpy arrays with one array per source space.)rB   r>   r@   rš   r   )r¥   rµ   rJ   rK   r–  rá   r¸  r˜  rS   rT   rá   %	  s     þz!_BaseMixedSourceEstimate.__init__c                 C   s   t dd„ | jd d… D ƒƒS )Nc                 s   s   | ]}t |ƒV  qd S r¼   r½   r•   rS   rS   rT   r—   1	  s     z8_BaseMixedSourceEstimate._n_surf_vert.<locals>.<genexpr>rb   r"  r   rS   rS   rT   Ú_n_surf_vert/	  s    z%_BaseMixedSourceEstimate._n_surf_vertc                 C   s@   | j dkrt}nt}|| jd| j… | jdd… | j| j| jƒS )zÀReturn the cortical surface source estimate.

        Returns
        -------
        stc : instance of SourceEstimate or VectorSourceEstimate
            The surface source estimate.
        r^   Nrb   )	rÎ   rª   r¿   rC   rå  rB   r>   r@   rš   ©rà   r³   rS   rS   rT   r}   3	  s    
   þz _BaseMixedSourceEstimate.surfacec                 C   s@   | j dkrt}nt}|| j| jd… | jdd… | j| j| jƒS )zÃReturn the volume surface source estimate.

        Returns
        -------
        stc : instance of VolSourceEstimate or VolVectorSourceEstimate
            The volume source estimate.
        r^   Nrb   )	rÎ   r¨   rÀ   rC   rå  rB   r>   r@   rš   ræ  rS   rS   rT   r|   C	  s    
   þz_BaseMixedSourceEstimate.volume)NNNNN)rÖ   rv  rw  rÏ   rÐ   r   rá   rx  rå  r}   r|   rš  rS   rS   r˜  rT   rl   	  s       ÿ	
rl  c                   @   s   e Zd ZdZdS )rÁ   a¼  Container for mixed surface and volume source estimates.

    Parameters
    ----------
    data : array of shape (n_dipoles, n_times) | tuple, shape (2,)
        The data in source space. The data can either be a single array or
        a tuple with two arrays: "kernel" shape (n_vertices, n_sensors) and
        "sens_data" shape (n_sensors, n_times). In this case, the source
        space data corresponds to ``np.dot(kernel, sens_data)``.
    vertices : list of array
        Vertex numbers corresponding to the data. The list contains arrays
        with one array per source space.
    %(tmin)s
    %(tstep)s
    %(subject_optional)s
    %(verbose)s

    Attributes
    ----------
    subject : str | None
        The subject name.
    times : array of shape (n_times,)
        The time vector.
    vertices : list of array
        Vertex numbers corresponding to the data. The list contains arrays
        with one array per source space.
    data : array of shape (n_dipoles, n_times)
        The data in source space.
    shape : tuple
        The shape of the data. A tuple of int (n_dipoles, n_times).

    See Also
    --------
    SourceEstimate : A container for surface source estimates.
    VectorSourceEstimate : A container for vector source estimates.
    VolSourceEstimate : A container for volume source estimates.
    VolVectorSourceEstimate : A container for Volume vector source estimates.

    Notes
    -----
    .. versionadded:: 0.9.0
    N)rÖ   rv  rw  r™  rS   rS   rS   rT   rÁ   T	  s   rÁ   c                   @   s   e Zd ZdZeZdS )r©   a  Container for volume source estimates.

    Parameters
    ----------
    data : array, shape (n_dipoles, 3, n_times)
        The data in source space. Each dipole contains three vectors that
        denote the dipole strength in X, Y and Z directions over time.
    vertices : list of array, shape (n_src,)
        Vertex numbers corresponding to the data.
    %(tmin)s
    %(tstep)s
    %(subject_optional)s
    %(verbose)s

    Attributes
    ----------
    subject : str | None
        The subject name.
    times : array, shape (n_times,)
        The time vector.
    vertices : array of shape (n_dipoles,)
        The indices of the dipoles in the source space.
    data : array of shape (n_dipoles, n_times)
        The data in source space.
    shape : tuple
        The shape of the data. A tuple of int (n_dipoles, n_times).

    See Also
    --------
    MixedSourceEstimate : A container for mixed surface + volume source
                          estimates.

    Notes
    -----
    .. versionadded:: 0.21.0
    N)rÖ   rv  rw  r™  rÁ   r¬   rS   rS   rS   rT   r©   ‚	  s   %r©   c                 C   sH   t | ƒdkst‚| d d ddd… }t |t¡}d|j| d d < |S )z!Get the volume source space mask.r   r   r\   Nr¾   Trt  )rJ   rs   rH   rj   ÚboolZflat)r·   r\   r'  rS   rS   rT   Ú_get_vol_mask°	  s
    rè  c                 C   s2   ddl m} t| ƒ}||jd|iŽ}t||ƒ}|S )Nr   )Úgrid_to_graphr'  )Zsklearn.feature_extractionré  rè  r\   Ú_get_adjacency_from_edges)r·   Ún_timesré  r'  ÚedgesÚ	adjacencyrS   rS   rT   Ú"_spatio_temporal_src_adjacency_vol¹	  s
    
rî  c                 C   sR  | d d d krt dƒ‚dd„ | D ƒ}t dgdd„ |D ƒ ¡d d… }t dd„ t|| |ƒD ƒ¡}t||ƒ}d	d„ t| |ƒD ƒ}td
d„ |D ƒƒ|jd | krªtdƒ‚dd„ |D ƒdd„ | D ƒkrÎtdƒ‚t |¡}dt	t
|ƒt |¡ ƒ t
|ƒ }|�rNtd| ƒ t ||¡}t |¡d }| ¡ }|| }|d d …|f }| ¡ }|S )Nr   Úuse_triszpThe source space does not appear to be an ico surface. adjacency cannot be extracted from non-ico source spaces.c                 S   s   g | ]}t  |d  ¡‘qS ©rï  )rH   Úunique©rŠ   rä   rS   rS   rT   rŒ   Ç	  s     z7_spatio_temporal_src_adjacency_surf.<locals>.<listcomp>c                 S   s   g | ]}t |ƒ‘qS rS   r½   )rŠ   Úu_vrS   rS   rT   rŒ   È	  s     r¾   c                 S   s&   g | ]\}}}t  ||d  ¡| ‘qS rð  )rH   r�  )rŠ   ró  rä   ÚoffrS   rS   rT   rŒ   É	  s   ÿc                 S   s    g | ]\}}t  ||d  ¡‘qS ©rt  )rH   r†  )rŠ   rä   rÅ  rS   rS   rT   rŒ   Î	  s     c                 s   s   | ]}|j V  qd S r¼   )r  )rŠ   rÅ  rS   rS   rT   r—   Ï	  s     z6_spatio_temporal_src_adjacency_surf.<locals>.<genexpr>z*Used vertices do not match adjacency shapec                 S   s   g | ]}t  |¡‘qS rS   r²  )rŠ   ÚmrS   rS   rT   rŒ   Ñ	  s     c                 S   s   g | ]}t |d  ƒ‘qS rõ  r½   rò  rS   rS   rT   rŒ   Ñ	  s     z-Vertex mask does not match number of verticeséd   z¸%0.1f%% of original source space vertices have been omitted, tri-based adjacency will have holes.
Consider using distance-based adjacency or morphing data to all source space vertices.)r    rH   Zcumsumrê   r§   Úspatio_temporal_tris_adjacencyrÂ   r\   rK   rG   rJ   r!   Útiler&  ÚtocsrÚtocoo)r·   rë  Z
used_vertsZoffsÚtrisrí  ZmasksÚmissingrS   rS   rT   Ú#_spatio_temporal_src_adjacency_surfÁ	  s4    "

ÿ
 
"ýrþ  c                 C   sT   | d d dkr0|dk	r$t d| ƒ‚t| |ƒ}n |dk	rFt| ||ƒ}n
t| |ƒ}|S )aK  Compute adjacency for a source space activation over time.

    Parameters
    ----------
    src : instance of SourceSpaces
        The source space. It can be a surface source space or a
        volume source space.
    n_times : int
        Number of time instants.
    dist : float, or None
        Maximal geodesic distance (in m) between vertices in the
        source space to consider neighbors. If None, immediate neighbors
        are extracted from an ico surface.
    %(verbose)s

    Returns
    -------
    adjacency : ~scipy.sparse.coo_matrix
        The adjacency matrix describing the spatio-temporal
        graph structure. If N is the number of vertices in the
        source space, the N first nodes in the graph are the
        vertices are time 1, the nodes from 2 to 2N are the vertices
        during time 2, etc.
    r   rÈ   ZvolNz4dist must be None for a volume source space. Got %s.)rK   rî  Úspatio_temporal_dist_adjacencyrþ  )r·   rë  Údistr   rí  rS   rS   rT   Úspatio_temporal_src_adjacencyä	  s    ÿ
r  c                 C   s,   t | ddƒ}t ||t |¡d  f¡}|S )a*  Get tris defined for a certain grade.

    Parameters
    ----------
    grade : int
        Grade of an icosahedral mesh.
    %(verbose)s

    Returns
    -------
    tris : list
        2-element list containing Nx3 arrays of tris, suitable for use in
        spatio_temporal_tris_adjacency.
    NFr   )Ú_get_ico_trisrH   rê   Úmax)Úgrader   rÉ   rü  rS   rS   rT   Úgrade_to_tris
  s    r  c                 C   sZ   ddl m} |r,t d¡ t t | ¡| ¡} t| ƒ}||j|j	d dd�  
¡ }t||ƒS )aÂ  Compute adjacency from triangles and time instants.

    Parameters
    ----------
    tris : array
        N x 3 array defining triangles.
    n_times : int
        Number of time points.
    remap_vertices : bool
        Reassign vertex indices based on unique values. Useful
        to process a subset of triangles. Defaults to False.
    %(verbose)s

    Returns
    -------
    adjacency : ~scipy.sparse.coo_matrix
        The adjacency matrix describing the spatio-temporal
        graph structure. If N is the number of vertices in the
        source space, the N first nodes in the graph are the
        vertices are time 1, the nodes from 2 to 2N are the vertices
        during time 2, etc.
    r   ©ÚsparsezReassigning vertex indices.Úcsrrc  )Úscipyr  r   r¡  rH   r�  rñ  r   Úeyer\   rû  rê  )rü  rë  Úremap_verticesr   r  rì  rS   rS   rT   rø  #
  s    
rø  c                 C   s°   ddl m} | d d dkr$tdƒ‚dd„ | D ƒ}|D ]6}t|tjƒrXtj ||dk< q6|j|jdk dk q6||ƒ}t |j|¡|jdd…< | 	¡ }| 
¡  | ¡ }t||ƒS )	a˜  Compute adjacency from distances in a source space and time instants.

    Parameters
    ----------
    src : instance of SourceSpaces
        The source space must have distances between vertices computed, such
        that src['dist'] exists and is useful. This can be obtained
        with a call to :func:`mne.setup_source_space` with the
        ``add_dist=True`` option.
    n_times : int
        Number of time points.
    dist : float
        Maximal geodesic distance (in m) between vertices in the
        source space to consider neighbors.
    %(verbose)s

    Returns
    -------
    adjacency : ~scipy.sparse.coo_matrix
        The adjacency matrix describing the spatio-temporal
        graph structure. If N is the number of vertices in the
        source space, the N first nodes in the graph are the
        vertices are time 1, the nodes from 2 to 2N are the vertices
        during time 2, etc.
    r   )Ú
block_diagr   NzVsrc must have distances included, consider using setup_source_space with add_dist=Truec                 S   s4   g | ],}|d  |d dd…f dd…|d f ‘qS )r   rt  NrS   rò  rS   rS   rT   rŒ   e
  s     z2spatio_temporal_dist_adjacency.<locals>.<listcomp>r¾   )Úscipy.sparser  r    r¥   rH   r¦   ÚinfrC   Z
less_equalrú  Zeliminate_zerosrû  rê  )r·   rë  r   r   Zsparse_block_diagÚblocksÚblockrì  rS   rS   rT   rÿ  F
  s    rÿ  c                 C   s   t | d|ƒS )a:  Compute adjacency for a source space activation.

    Parameters
    ----------
    src : instance of SourceSpaces
        The source space. It can be a surface source space or a
        volume source space.
    dist : float, or None
        Maximal geodesic distance (in m) between vertices in the
        source space to consider neighbors. If None, immediate neighbors
        are extracted from an ico surface.
    %(verbose)s

    Returns
    -------
    adjacency : ~scipy.sparse.coo_matrix
        The adjacency matrix describing the spatial graph structure.
    r   )r  ©r·   r   r   rS   rS   rT   Úspatial_src_adjacencyu
  s    r  c                 C   s   t | d|ƒS )a«  Compute adjacency from triangles.

    Parameters
    ----------
    tris : array
        N x 3 array defining triangles.
    remap_vertices : bool
        Reassign vertex indices based on unique values. Useful
        to process a subset of triangles. Defaults to False.
    %(verbose)s

    Returns
    -------
    adjacency : ~scipy.sparse.coo_matrix
        The adjacency matrix describing the spatial graph structure.
    r   )rø  )rü  r  r   rS   rS   rT   Úspatial_tris_adjacencyŒ
  s    r  c                 C   s   t | d|ƒS )a�  Compute adjacency from distances in a source space.

    Parameters
    ----------
    src : instance of SourceSpaces
        The source space must have distances between vertices computed, such
        that src['dist'] exists and is useful. This can be obtained
        with a call to :func:`mne.setup_source_space` with the
        ``add_dist=True`` option.
    dist : float
        Maximal geodesic distance (in m) between vertices in the
        source space to consider neighbors.
    %(verbose)s

    Returns
    -------
    adjacency : ~scipy.sparse.coo_matrix
        The adjacency matrix describing the spatial graph structure.
    r   )rÿ  r  rS   rS   rT   Úspatial_dist_adjacency¡
  s    r  c                    s¬   ddl m‰  ddlm} t| dd�} || d d | d d  | d d | d d  ƒ}ˆ j||ktd	�}‡ fd
d„|jD ƒ}ˆ  ˆ  	|d |g¡ˆ  	|j
|d g¡g¡}|S )a“  Get vertices on each hemisphere that are close to the other hemisphere.

    Parameters
    ----------
    src : instance of SourceSpaces
        The source space. Must be surface type.
    dist : float
        Maximal Euclidean distance (in m) between vertices in one hemisphere
        compared to the other to consider neighbors.
    %(verbose)s

    Returns
    -------
    adjacency : ~scipy.sparse.coo_matrix
        The adjacency matrix describing the spatial graph structure.
        Typically this should be combined (addititively) with another
        existing intra-hemispheric adjacency matrix, e.g. computed
        using geodesic distances.
    r   r  )Úcdistr}   re  Úrrrt  r   rX   c                    s   g | ]}ˆ j ||ftd �‘qS )rX   )Ú
csr_matrixrI   )rŠ   Únvr  rS   rT   rŒ   Ô
  s     z0spatial_inter_hemi_adjacency.<locals>.<listcomp>)r	  r  Úscipy.spatial.distancer  r   r  rI   r\   rŒ  ZhstackrM   )r·   r   r   r  ZadjZemptiesrS   r  rT   Úspatial_inter_hemi_adjacency¹
  s    ÿÿr  c                 C   sh  ddl m} | jd }t d| ¡ | jj}|t t 	|¡dd…df d|f¡ }| jddd…f |  
¡ }| jddd…f |  
¡ }|dk�r|t 	|d ¡dd…df  t 	|¡ddd…f   
¡ }	|t 	d|¡dd…df  t 	|¡ddd…f   
¡ }
t ||	|
f¡}t ||
|	f¡}tj| jj| d| |d   tjd�}||||ff|| fd d�}|S )	z3Given edges sparse matrix, create adjacency matrix.r   )Ú
coo_matrixz#-- number of adjacent vertices : %dNr   rb   rX   )r\   )r  r  r\   r   r¡  Úcolr  rH   rù  r.  ÚravelÚrowrê   ZonesrC   rÑ   )rì  rë  r   r  rÄ   ÚnnzZauxr  r  ÚoÚdrC   rí  rS   rS   rT   rê  Ú
  s.    
&
ÿÿÿÿrê  c                 C   s   t | ƒ}|s|d S |S dS )zGet triangles for ico surface.rü  N)r   )r  r   Zreturn_surfZicorS   rS   rT   r  ò
  s    r  c                 C   sZ   t |dd�\}}}t t |d d …df | ¡¡}tj |¡t t|ƒ¡ }|| |d  S )NFrÁ  r   )r   rH   rÄ  r#  r¹  rº  rM  rJ   )ÚfliprC   ÚUrä   ÚVrÄ  ÚscalerS   rS   rT   Ú	_pca_flipü
  s    r&  c                 C   s   t j|dd�S ©Nr   rO  ©rH   r5  ©r"  rC   rS   rS   rT   Ú<lambda>  ó    r*  c                 C   s   t j| | dd�S r'  r(  r)  rS   rS   rT   r*    r+  c                 C   s   t jt  |¡dd�S r'  )rH   r  rç   r)  rS   rS   rT   r*    r+  )r5  Ú	mean_flipr  Zpca_flipc              
   c   sX   dd„ | D ƒ}t | |ƒD ]\}}||d< qz
d V  W 5 t | |ƒD ]\}}||d< q@X d S )Nc                 S   s   g | ]}|d  ‘qS rõ  rS   rò  rS   rS   rT   rŒ     s     z'_temporary_vertices.<locals>.<listcomp>rt  )r§   )r·   rB   Zorig_verticesrä   r–   rS   rS   rT   Ú_temporary_vertices  s    

r-  c                 C   st   | d k	rp|d k	rpt |j| jdddd� t|| jdƒD ]:\}}}t ||d ¡  ¡ }|r4td|t	|ƒ|f ƒ‚q4d S )NFúsource space subjectústc.subject©rÓ   Z
first_kindZsecond_kind)ÚleftÚrightrt  zO%d/%d %s hemisphere stc vertices missing from the source space, likely mismatch)
r   Ú_subjectrš   r§   rB   rH   r†  rÂ   rK   rJ   )rQ   r·   rä   r–   r  Z	n_missingrS   rS   rT   Ú_check_stc_src  s       þþr4  c              
   C   sØ  ddl m} ddlm}m}m}	 t| |ƒ | dkr@dd„ |D ƒn| j}
dd„ |
D ƒ}tƒ }tƒ }tƒ }t	|ƒD �]\}}|r„|d	 n|j
}t|t| d	dƒd
ddd� t|t|ddƒd
ddd� |�r.t|tƒsÒt‚|d }|jd dkrü| |d ¡ d}n|dk�r| |jdd�¡}| |¡ | d¡ qnt|||	fd|f ƒ |jdk�r^|j|jg}n|g}tƒ }|D ]†}|jdk�r¢t |
d |j¡}t |
d |¡}nF|jdk�rÚt |
d |j¡}|d t |
d |¡ }ntd|j ƒ‚| |¡ �qnt |¡}d}t|ƒdk�r$| |j¡ d}n@|dk�rdt|| jƒ�$ |||dd… ƒdd…df }W 5 Q R X | |¡ | |¡ qnt|ƒ�rÐdt|ƒt |ƒ|f }|�sªt|ƒ‚n&|d7 }|dk�rÈt! "|¡ nt#|ƒ ||fS )z8Prepare indices and flips for extract_label_time_course.r   r  r   )Úlabel_sign_flipr‰  rŠ  Nc                 S   s   g | ]}|d  ‘qS rõ  rS   rò  rS   rS   rT   rŒ   4  s     z-_prepare_label_extraction.<locals>.<listcomp>c                 S   s   g | ]}t |ƒ‘qS rS   r½   )rŠ   ÚvnrS   rS   rT   rŒ   5  s     rš   Fzlabel.subjectr/  r0  r3  r.  r  Únamer5  rO  z
labels[%d]r‹  r°   r±   zlabel %s has invalid hemi©r5  r  rb   z=source space does not contain any vertices for %d label%s:
%sz 
Assigning all-zero time series.Úignore)$r	  r  r‡  r5  r‰  rŠ  r4  rB   rµ   rm  rš   r   Úgetattrr¥   rF   rs   r\   ri  r  r5  r%   r  r°   r±   rH   Zintersect1dr�  rK   r7  rê   rJ   r-  r   r   r¡  r!   )rQ   rõ   r·   rì   rò   Ú
use_sparser  r5  r‰  rŠ  rt  ÚnvertZ
label_flipÚlabel_vertidxZ
bad_labelsZlir‡  rš   ÚvertidxZ
sub_labelsZthis_vertidxZslabelZthis_verticesZ	this_flipÚmsgrS   rS   rT   Ú_prepare_label_extraction&  sŒ    
 
  þ 
  þ




(

ÿ

r@  c              	   C   sD   t | d d t dd„ tjdd„ | d d D ƒdd	iŽD ƒt¡jƒS )
Nr   Z	src_mri_tc                 S   s   g | ]}|j d d�‘qS )ÚF©Úorder)r  )rŠ   r!  rS   rS   rT   rŒ   �  s   ÿz_vol_src_rr.<locals>.<listcomp>c                 s   s   | ]}t  |¡V  qd S r¼   )rH   r.  rò  rS   rS   rT   r—   �  s     z_vol_src_rr.<locals>.<genexpr>r\   ZindexingZij)r   rH   rZ   ZmeshgridrG   rM   ©r·   rS   rS   rT   Ú_vol_src_rrŠ  s    
 ÿþÿûÿrE  c                    s$  ddl m‰  ˆjdkst‚ˆj‰d}tdƒ t|dttfd| ƒ t	|ƒrT|}d}n:t
|ƒd	krrtd
t
|ƒf ƒ‚|\}}d}t|dd| ƒ t d|f ¡ tt|ƒdd�}|d }t |¡‰ˆjjdk�rˆt ˆ¡ ‰ˆt ˆ¡k ¡ sötdƒ‚t ˆ¡ tj¡‰|�r*‡fdd„tƒ d  ¡ D ƒ}t||dd�}t|tƒ�sHt‚Š|d }ˆd  dd ¡}	|	d k�rttdƒ‚|d |	d  }}	tj||	dd��s tdƒ‚t‡fdd„dD ƒƒ}
|j }||
k�rÖtd ||
f ƒ‚|j!d!d"�}|�ržtƒ }d}ˆd d# }|j d t "|
¡k�st‚|j |j#t
ˆd d$ ƒfk�s:t‚|d d …ˆd d% f }| ¡ D ]@\}}||k}|| }| $t||ˆd&�¡ ||j d dk7 }�qZnlˆd d% ‰t%ˆƒ}Št&||ˆ ƒ‰‡‡fd'd(„| '¡ D ƒ}‡ ‡fd)d(„t(|| )¡ ƒD ƒ}t*d*d„ |D ƒƒ}t d+|t
|ƒf ¡ |S ),Nr   )r‰  r|   z! when using a volume source spacezuse volume atlas labelsru   rõ   Trb   z4labels, if list or tuple, must have length 2, got %sFz	labels[0]zReading atlas %s)rC   rC   r‹   z4Non-integer values present in atlas, cannot labelizec                    s   i | ]\}}|ˆ kr||“qS rS   rS   )rŠ   Úkr–   )Úatlas_valuesrS   rT   Ú
<dictcomp>²  s   ÿ z"_volume_labels.<locals>.<dictcomp>r   z	labels[1])r7  Ú	vox_mri_tzOCannot use volumetric atlas if no mri was supplied during source space creationÚtransg�íµ ÷Æ°>)ZatolzCatlas vox_mri_t does not match that used to create the source spacec                 3   s   | ]}ˆ d  d|  V  qdS )r   Zmri_NrS   )rŠ   rF  rD  rS   rT   r—   Ä  s     z!_volume_labels.<locals>.<genexpr>)rQ  ÚheightÚdepthz7atlas shape %s does not match source space MRI shape %srA  rB  Zinterpolatorr  rt  )r  r7  rš   c                    s   g | ]}ˆˆ |k ‘qS rS   rS   )rŠ   rq   )Ú
src_valuesrt  rS   rT   rŒ   Þ  s     z"_volume_labels.<locals>.<listcomp>c                    s    g | ]\}}ˆ |d |ˆd�‘qS )r°   )r  r7  rš   rS   )rŠ   r–   rq   )r‰  rš   rS   rT   rŒ   ß  s   ÿc                 s   s   | ]}t |ƒd kV  qdS r’   r½   r•   rS   rS   rT   r—   á  s     z?%d/%d atlas regions had at least one vertex in the source space)+r‡  r‰  r¶   rs   r3  r	   r%   rµ   r×   r.   rJ   rK   r   r¡  r
   r´  rH   rñ  r;   ÚisfiniteÚroundr¡   r    re   rÑ   r   Úitemsr   r¥   rF   ÚgetZallcloser\   r  rV  r  ri  rE  r   r}  r§   ÚkeysrÂ   )r·   rõ   rÛ  rÀ  rÝ  Zinfer_labelsZvol_infoZ
atlas_datarI  ZwantZ	src_shapeZatlas_shapeZ
out_labelsr  ÚinterprF  r–   r'  r  r  rB   rS   )r‰  rG  r·   rM  rš   rt  rT   rÜ  ”  s–    ÿ

ÿ
ÿÿ
ÿ"ÿ
ÿrÜ  c                   C   s   t t ¡ ƒdg S )Nrð   )ÚsortedÚ_label_funcsrR  rS   rS   rS   rT   Ú_get_default_label_modesç  s    rV  c                 C   s   t | ttfƒrdS tƒ S d S )N)r5  r  rð   )r¥   rÐ  r·  rV  )rQ   rS   rS   rT   Ú_get_allowed_label_modesë  s
    ÿrW  r5  T)rì   rò   rÛ  r   c                c   s(  ddl m} |d kr"|dkr"d}nt|tƒ |j}td|tƒ ƒ |dkr^t|tƒsX|g}d}	nt	|||ƒ}t
|ƒ}	t|ƒ}
|dkr’t|d	d … ƒnd}|
| }d  }}t| ƒD �]r\}}t|td
|f dƒ td|t|ƒdƒ t|ttfƒrþ|dkrødn|}n|dk�rdn|}|d k�rXt |j¡}t dd„ |D ƒ¡}t||||||	ƒ\}}t| }t|ƒt|jƒk�rttdƒ‚t||jƒD ]J\}}t|ƒt|ƒk�r²tdt|ƒt|ƒf ƒ‚t ||¡�s€tdƒ‚�q€t d||f ¡ tj|f|jjdd …  |jj d�}tt||ƒƒD ]¦\}\}}|d k	�rt||j!ƒ�rœ|�s>t"‚|jd |jjd k�sZt"‚t #|j|jjd df¡}|| }|jd f|jjdd …  |_n
|j| }|||ƒ||< �q|d | …  $¡ }t|d	d … ƒD ]@\}}|dk�rÚ|| }tj%|j||… dd�||
| < |}�qÚ|V  q®d S )Nr   r  r8  r}   rì   )r}   r�   Fr�   rb   zstcs[%d]zsource estimatez1when using a vector and/or volume source estimaterð   r5  r,  c                 S   s   g | ]}t |ƒ‘qS rS   r½   r•   rS   rS   rT   rŒ     s     z2_gen_extract_label_time_course.<locals>.<listcomp>z$stc not compatible with source spacezÎstc not compatible with source space. stc has %s time series but there are %s vertices in source space. Ensure you used src from the forward or inverse operator, as forward computation can exclude vertices.z0Extracting time courses for %d labels (mode: %s)r   rX   r¾   rO  )&r	  r  r%   r   r¶   r$   rV  r¥   rµ   rÜ  rç  rJ   rm  rÍ   rW  rÐ  r·  r£   rN  rB   rH   rZ   r@  rU  rK   r§   rÆ   r   r¡  rj   rC   r\   r;   r  rs   rL   rÂ   r5  )r^  rõ   r·   rì   rò   rÛ  r   r  r¶   r;  Zn_modeZn_meanZn_labelsrt  rR  ÚsirQ   r<  r=  Zsrc_flipr6  ÚsvnÚlabel_tcrm   r>  r"  Z	this_datar=   r  Zv2rS   rS   rT   Ú_gen_extract_label_time_courseó  s˜    

ÿ  þÿ
     ÿûÿÿ

ÿ

 r[  rð   rÚ  c          
      C   sT   t | tttfƒs | g} d}d}nd}t| |||||d�}	|sDt|	ƒ}	|sP|	d }	|	S )a  Extract label time course for lists of labels and source estimates.

    This function will extract one time course for each label and source
    estimate. The way the time courses are extracted depends on the mode
    parameter (see Notes).

    Parameters
    ----------
    stcs : SourceEstimate | list (or generator) of SourceEstimate
        The source estimates from which to extract the time course.
    %(labels_eltc)s
    %(src_eltc)s
    %(mode_eltc)s
    %(allow_empty_eltc)s
    return_generator : bool
        If True, a generator instead of a list is returned.
    %(mri_resolution_eltc)s
    %(verbose)s

    Returns
    -------
    %(label_tc_el_returns)s

    Notes
    -----
    %(eltc_mode_notes)s

    If encountering a ``ValueError`` due to mismatch between number of
    source points in the subject source space and computed ``stc`` object set
    ``src`` argument to ``fwd['src']`` or ``inv['src']`` to ensure the source
    space is the one actually used by the inverse to compute the source
    time courses.
    FT)rì   rò   rÛ  r   )r¥   rµ   r×   r   r[  )
r^  rõ   r·   rì   rò   rñ   rÛ  r   Zreturn_severalrZ  rS   rS   rT   rô   H  s$    &    þrô   ç{®Gáz„?rÂ   Úpialc           !         sÞ  ddl m}m} ddlm} tˆ |dƒ t|tdƒ t|dtfdƒ td|d	ƒ |dkrjt	ˆ j
d
d
d
d�}ˆ  ¡  |¡‰ t‡ fdd„|D ƒƒ}|tjhks¬tdt|ƒ› �ƒ‚ˆ  ¡ ‰t t ˆ¡jdd�¡d ‰‡ fdd„ˆD ƒ}t|ƒrôˆ  |¡ ‡‡fdd„ttˆƒƒD ƒ‰t|ddd
d�\}}t|ˆƒ‰tdˆdd�‰tˆd
d�‰ˆdk	�rh‡‡‡fdd„dD ƒ}|dk�r²tˆtddƒ tdd„ |D ƒƒ}t dd„ t||ƒD ƒ¡}d}n\ˆdk�rðt dd„ |D ƒ¡}|d d tjk�r
t||ƒ}nt d d„ t||ƒD ƒ¡}d
}t t!t"t#d!�}td"|j$t| %¡ ƒƒ ||j$ }t& 
d#tˆƒ› d$t'ˆƒ› d%t|ƒ› d&|j$› d'|› d(�¡ |�rª|j$dk�rªt& 
d)¡ t(ˆt |d*�d
d+d,�d- ‰|ˆƒ )¡ d. }t& 
d/|�rÊd0nd1› d2|d3›d4�¡ ||ˆƒ}|j*t|ƒtˆƒfk�st+‚t ||k d5¡¡d }t& 
d6t|ƒ› d7t|ƒ› d8�¡ t ,d9|| |  d¡}|d:k�r®t -|j*d ¡}tj.|dd�}|d;k�r’|||f nd9}| /d¡ ||||f< n,|d<k�rÚ|j0d5d
d=�}d9||dk< || }t tj|dd� ¡d }t|ƒ�r*t1d>t'|ƒ› d?d@ 2‡ fdAd„|D ƒ¡› �ƒ |ˆ j3 }|�rztj4t0dBd„ |D ƒƒtˆ j5ƒf|j6dC�}|||< dDd„ |D ƒ}n@|j$dk�sŠt+‚|}t|d dE ƒ} ||| k  ||| k |  g}|||ˆ j5d d9ˆ j
dF  ˆ|
dG�S )Ha…  Create a STC from ECoG, sEEG and DBS sensor data.

    Parameters
    ----------
    evoked : instance of Evoked
        The evoked data. Must contain ECoG, sEEG or DBS channels.
    %(trans)s
    subject : str
        The subject name.
    distance : float
        Distance (m) defining the activation "ball" of the sensor.
    mode : str
        Can be "sum" to do a linear sum of weights, "weighted" to make this
        a weighted sum, "nearest" to
        use only the weight of the nearest sensor, or "single" to
        do a distance-weight of the nearest sensor. Default is "sum".
        See Notes.

        .. versionchanged:: 0.24
           Added "weighted" option.
    project : bool
        If True, project the sensors to the nearest ``'pial`` surface
        vertex before computing distances. Only used when doing a
        surface projection.
    %(subjects_dir)s
    src : instance of SourceSpaces
        The source space.

        .. warning:: If a surface source space is used, make sure that
                     ``surface='pial'`` was used during construction,
                     or that you set ``surface='pial'`` here.
    %(picks_base)s good sEEG, ECoG, and DBS channels.

        .. versionadded:: 0.24
    surface : str | None
        The surface to use if ``src=None``. Default is the pial surface.
        If None, the source space surface will be used.

        .. versionadded:: 0.24.1
    %(verbose)s

    Returns
    -------
    stc : instance of SourceEstimate
        The surface source estimate. If src is None, a surface source
        estimate will be produced, and the number of vertices will equal
        the number of pial-surface vertices that were close enough to
        the sensors to take on a non-zero volue. If src is not None,
        a surface, volume, or mixed source estimate will be produced
        (depending on the kind of source space passed) and the
        vertices will match those of src (i.e., there may be me
        many all-zero values in stc.data).

    Notes
    -----
    For surface projections, this function projects the ECoG sensors to
    the pial surface (if ``project``), then the activation at each pial
    surface vertex is given by the mode:

    - ``'sum'``
        Activation is the sum across each sensor weighted by the fractional
        ``distance`` from each sensor. A sensor with zero distance gets weight
        1 and a sensor at ``distance`` meters away (or larger) gets weight 0.
        If ``distance`` is less than half the distance between any two
        sensors, this will be the same as ``'single'``.
    - ``'single'``
        Same as ``'sum'`` except that only the nearest sensor is used,
        rather than summing across sensors within the ``distance`` radius.
        As ``'nearest'`` for vertices with distance zero to the projected
        sensor.
    - ``'nearest'``
        The value is given by the value of the nearest sensor, up to a
        ``distance`` (beyond which it is zero).
    - ``'weighted'``
        The value is given by the same as ``sum`` but the total weight for
        each vertex is 1. (i.e., it's a weighted sum based on proximity).

    If creating a Volume STC, ``src`` must be passed in, and this
    function will project sEEG and DBS sensors to nearby surrounding vertices.
    Then the activation at each volume vertex is given by the mode
    in the same way as ECoG surface projections.

    .. versionadded:: 0.22
    r   )r  Úpdistr   )ÚEvokedÚevokedrì   Nr·   )rÂ   ÚsingleÚnearestÚweightedT)ZecogZseegZdbsc                 3   s    | ]}ˆ j d  | d V  qdS )ZchsÚcoord_frameN)r¡  )rŠ   Úpick©r`  rS   rT   r—   ç  s     z#stc_near_sensors.<locals>.<genexpr>z3Channels must be in the head coordinate frame, got rO  c                    s   g | ]}ˆ j | ‘qS rS   ©Zch_names©rŠ   r™   rf  rS   rT   rŒ   ò  s     z$stc_near_sensors.<locals>.<listcomp>c                    s   g | ]}|ˆ krˆ| ‘qS rS   rS   rh  )Únan_indsr  rS   rT   rŒ   õ  s      ÚheadrÝ  )Ú
allow_noneFrÒ   c                    s2   g | ]*}t t ˆˆ d |› dˆ› �¡ƒd d ‘qS )rz  r{  r   r?   )r   r‡   r|  )rŠ   r  )rš   r  r}   rS   rT   rŒ      s   þÿÿÿ)r°   r±   r}   zwhen src is Nonec                 S   s(   g | ] }t |t t|ƒ¡d tjd�‘qS )rz  )r  rt  rÈ   rd  )rF   rH   r.  rJ   r   ZFIFFV_COORD_MRI)rŠ   r  rS   rS   rT   rŒ     s   þÿc                 S   s   g | ]\}}||d   ‘qS rõ  rS   ©rŠ   Zs_rrrä   rS   rS   rT   rŒ   	  s     c                 S   s   g | ]}|d  |d  ‘qS )r  rt  rS   rò  rS   rS   rT   rŒ     s     rd  c                 S   s   g | ]\}}||d   ‘qS rõ  rS   rl  rS   rS   rT   rŒ     s     )r}   r|   r�   zsrc.kindzProjecting data from z sensorz onto ú z vertices: z modez#    Projecting sensors onto surface)r  rb  )Zproject_rrsÚmethodrb   rW   z    Minimum z
projected Ú zintra-sensor distance: z0.1fz mmr¾   z    z / z non-zero verticesrŽ   )ra  rb  ra  rc  )r9  ZChannelz missing in STC: z, c                 3   s   | ]}ˆ j | V  qd S r¼   rg  )rŠ   Úmirf  rS   rT   r—   A  s     c                 s   s   | ]}t |d  ƒV  qdS )rt  Nr½   rò  rS   rS   rT   r—   G  s     rX   c                 S   s   g | ]}|d    ¡ ‘qS rõ  rø   rò  rS   rS   rT   rŒ   J  s     rt  r!  )rš   r   )7r  r  r^  r`  r_  r%   r´  r   r$   r   r¡  r£   re  Úsetr   ZFIFFV_COORD_HEADr    rT  Z_get_channel_positionsrH   r&  Úisnanr“   rJ   Zdrop_channelsrl   r   r   r   r   rê   r§   rF   r¿   rÀ   rÁ   r¶   rR  r   r   r   Úminr\   rs   Úmaximumr.  ZargmaxÚfillrÂ   r!   r|  rC   rj   rã   r;   )!r`  rJ  rš   Zdistancerì   rÆ  r  r·   Zpicksr}   r   r  r^  r_  ÚframesZnan_chsr²   Zsurf_rrZrrsZkeep_allr³   Zmin_distÚdistsrB   rn   Zrange_r™   ÚvalsZnormsrý  Znz_datarC   r=   rS   )r`  ri  r  rš   r  r}   rT   Ústc_near_sensors„  sÈ    X


þ
ý
ÿ

ÿý
0ÿ
ÿÿÿ
 



,
þ
ÿ ÿry  )N)N)NNNNFNN)NN)N)FN)N)NN)FN)N)N)N)NF)rð   FF)r\  rÂ   TNNNr]  N)|Ú
contextlibr£   Úos.pathÚpathr‡   Útypesr   ÚnumpyrH   rù   r   r¦  r   r`  r   Úfilterr   Úfixesr   Z_freesurferr	   r
   r   r   Zio.constantsr   Zio.pickr   r}   r   r   r   r   Zsource_spacer   r   r   r   r   r   Z
transformsr   r   Úutilsr   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   Zvizr3   r4   r5   Zio.baser6   Zio.meas_infor7   rU   r]   rh   ro   rr   rt   r´   r¹   rÅ   rÌ   rÍ   r�  rk  r¿   r·  rÐ  rÀ   r¨   rª   rl  rÁ   r©   rè  rî  rþ  r  r  rø  rÿ  r  r  r  r  rê  r  r&  rU  Úcontextmanagerr-  r4  r@  rE  rÜ  rV  rW  r[  rô   ry  rS   rS   rS   rT   Ú<module>   s   h. 	(	 
 
        ÿ
-      1 s   
 PTÿFÿ04-ÿ-	#)  ÿ". 	
ü
d
S þU    ÿ þ;           þ