U
    f»{jwÏ ã                   @   s¾  d dl mZ d dlmZ d dlZd dlmZ d dlZ	ddl
mZ ddlmZmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZmZmZmZ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& ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z; ddl<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZO ddlPmQZQ ddlRmSZSmTZTmUZUmVZVmWZWmXZXmYZYmZZZm[Z[ ddddœZ\G dd„ de]ƒZ^dd„ Z_e@d}dd„ƒZ`e@d~dd„ƒZad d!„ Zbe@dd"d#„ƒZcd$d%„ Zdd&d'„ Zed(d)„ Zfe@d€d*d+„ƒZge@ddd,œd-d.„ƒZhd/d0„ Zid�d1d2„Zje@d‚d3d4„ƒZke@dƒdd8œd9d:„ƒZld„d<d=„Zme@d…dAdB„ƒZnd†dCdD„ZodEdF„ Zpd‡dHdI„Zqddd7di dfdJdK„ZrdLdM„ ZsdNdO„ ZtdPdQ„ ZudˆdRdS„ZvdTdU„ Zwd‰dWdX„Zxe@dŠdYdZ„ƒZye@d‹d[d\„ƒZze@dŒd^d_„ƒZ{d`da„ Z|dbZ}e@e	j~dfdd8œdcdd„ƒZdedf„ Z€eAdgdh„ ƒZ�didj„ Z‚d�dkdl„Zƒe@dŽdmdn„ƒZ„e@d�dodp„ƒZ…d�dsdt„Z†dudv„ Z‡d‘dwdx„Zˆe@d’dydz„ƒZ‰d{d|„ ZŠdS )“é    ©Údeepcopy)ÚpartialNé   )ÚFIFF)Úcreate_infoÚInfo)Údir_tree_find)Úfind_tagÚread_tag)Ú	fiff_open)
Ústart_blockÚ	end_blockÚ	write_intÚwrite_float_sparse_rcsÚwrite_stringÚwrite_float_matrixÚwrite_int_matrixÚwrite_coord_transÚstart_and_end_fileÚwrite_id)Úchannel_typeÚ_picks_to_idx)Úread_bem_surfacesÚConductorModel)Ú_get_img_fdata)Úread_surfaceÚ_create_surf_spacingÚ_get_ico_surfaceÚ_tessellate_sphere_surfÚ_get_surf_neighborsÚ_normalize_vectorsÚ_triangle_neighborsÚ	mesh_distÚcomplete_surface_infoÚ_compute_nearestÚfast_cross_3dÚ_CheckInside)Ú_get_mri_info_dataÚ_get_atlas_valuesÚread_freesurfer_lutÚget_mni_fiducialsÚ
_check_mri)Úget_subjects_dirÚcheck_fnameÚloggerÚverboseÚfill_docÚ_ensure_intÚcheck_versionÚ_get_call_lineÚwarnÚ_check_fnameÚ
_path_likeÚ_check_sphereÚ_validate_typeÚ_check_optionÚ_is_numericÚ_plÚ_suggestÚobject_sizeÚ
sizeof_fmt)Úparallel_func)	Úinvert_transformÚapply_transÚ_print_coord_transÚcombine_transformsÚ
_get_transÚ_coord_frame_nameÚ	TransformÚ_str_to_frameÚ_ensure_transÚvolumeÚsurfaceÚdiscrete)ÚvolÚsurfrL   c                	       s–   e Zd ZdZd‡ fdd„	Zedd„ ƒZeddd	„ƒZ‡ fd
d„Z	dd„ Z
edd„ ƒZdd„ Zdd„ Zdd„ Zedddœdd„ƒZed dd„ƒZ‡  ZS )!ÚSourceSpacesaä  Represent a list of source space.

    This class acts like a list of dictionaries containing the source
    space information, one entry in the list per source space type. See
    Notes for details.

    .. warning::
        This class should not be created or modified by the end user. Use
        :func:`mne.setup_source_space`, :func:`mne.setup_volume_source_space`,
        or :func:`mne.read_source_spaces` to create :class:`SourceSpaces`.

    Parameters
    ----------
    source_spaces : list
        A list of dictionaries containing the source space information.
    info : dict
        Dictionary with information about the creation of the source space
        file. Has keys 'working_dir' and 'command_line'.

    Attributes
    ----------
    kind : str
        The kind of source space, one of
        ``{'surface', 'volume', 'discrete', 'mixed'}``.
    info : dict
        Dictionary with information about the creation of the source space
        file. Has keys 'working_dir' and 'command_line'.

    See Also
    --------
    mne.setup_source_space : Setup a surface source space.
    mne.setup_volume_source_space : Setup a volume source space.
    mne.read_source_spaces : Read source spaces from a file.

    Notes
    -----
    Each element in SourceSpaces (e.g., ``src[0]``) is a dictionary. For
    example, a surface source space will have ``len(src) == 2``, one entry for
    each hemisphere. A volume source space will have ``len(src) == 1`` if it
    uses a single monolithic grid, or ``len(src) == len(volume_label)`` when
    created with a list-of-atlas-labels. A mixed source space consists of both
    surface and volumetric source spaces in a single SourceSpaces object.

    Each of those dictionaries can be accessed using standard Python
    :class:`python:dict` access using the string keys listed below (e.g.,
    ``src[0]['type'] == 'surf'``). The relevant key/value pairs depend on
    the source space type:

    **Relevant to all source spaces**

    The following are always present:

        id : int
            The FIF ID, either ``FIFF.FIFFV_MNE_SURF_LEFT_HEMI`` or
            ``FIFF.FIFFV_MNE_SURF_RIGHT_HEMI`` for surfaces, or
            ``FIFF.FIFFV_MNE_SURF_UNKNOWN`` for volume source spaces.
        type : str
            The type of source space, one of ``{'surf', 'vol', 'discrete'}``.
        np : int
            Number of vertices in the dense surface or complete volume.
        coord_frame : int
            The coordinate frame, usually ``FIFF.FIFFV_COORD_MRI``.
        rr : ndarray, shape (np, 3)
            The dense surface or complete volume vertex locations.
        nn : ndarray, shape (np, 3)
            The dense surface or complete volume normals.
        nuse : int
            The number of points in the subsampled surface.
        inuse : ndarray, shape (np,)
            An integer array defining whether each dense surface vertex is used
            (``1``) or unused (``0``).
        vertno : ndarray, shape (n_src,)
            The vertex numbers of the dense surface or complete volume that are
            used (i.e., ``np.where(src[0]['inuse'])[0]``).
        subject_his_id : str
            The FreeSurfer subject name.

    **Surface source spaces**

    Surface source spaces created using :func:`mne.setup_source_space` can have
    the following additional entries (which will be missing, or have values of
    ``None`` or ``0`` for volumetric source spaces):

        ntri : int
            Number of triangles in the dense surface triangulation.
        tris : ndarray, shape (ntri, 3)
            The dense surface triangulation.
        nuse_tri : int
            The number of triangles in the subsampled surface.
        use_tris : ndarray, shape (nuse_tri, 3)
            The subsampled surface triangulation.
        dist : scipy.sparse.csr_matrix, shape (n_src, n_src) | None
            The distances (euclidean for volume, along the cortical surface for
            surfaces) between source points.
        dist_limit : float
            The maximum distance allowed for inclusion in ``nearest``.
        pinfo : dict
            Information about the patch of cortex represented by a vertex in
            the subsampled surface.
        patch_inds : list of ndarray
            For each vertex in the subsampled surface, the indices of the
            vertices in the dense surface that it represents (i.e., is closest
            to of all subsampled indices).
        nearest : ndarray, shape (np,)
            For each vertex on the dense surface, this gives the vertex index
            on the subsampled surface that it's closest to.
        nearest_dist : ndarray, shape (np,)
            The distances corresponding to ``nearest``.

    **Volume source spaces**

    Volume source spaces created using :func:`mne.setup_volume_source_space`
    can have the following additional entries (which will be missing, or
    have values of ``None`` or ``0`` for surface source spaces):

        mri_width, mri_height, mri_depth : int
            The MRI dimensions (in voxels).
        neighbor_vert : ndarray
            The 26-neighborhood information for each vertex.
        interpolator : scipy.sparse.csr_matrix | None
            The linear interpolator to go from the subsampled volume vertices
            to the high-resolution volume.
        shape : tuple of int
            The shape of the subsampled grid.
        mri_ras_t : instance of :class:`~mne.transforms.Transform`
            The transformation from MRI surface RAS (``FIFF.FIFFV_COORD_MRI``)
            to MRI scanner RAS (``FIFF.FIFFV_MNE_COORD_RAS``).
        src_mri_t : instance of :class:`~mne.transforms.Transform`
            The transformation from subsampled source space voxel to MRI
            surface RAS.
        vox_mri_t : instance of :class:`~mne.transforms.Transform`
            The transformation from the original MRI voxel
            (``FIFF.FIFFV_MNE_COORD_MRI_VOXEL``) space to MRI surface RAS.
        mri_volume_name : str
            The MRI volume name, e.g. ``'subjects_dir/subject/mri/T1.mgz'``.
        seg_name : str
            The MRI atlas segmentation name (e.g., ``'Left-Cerebellum-Cortex'``
            from the parameter ``volume_label``).

    Source spaces also have some attributes that are accessible via ``.``
    access, like ``src.kind``.
    Nc                    sB   t |tdƒ tt| ƒ |¡ | j |d kr4tƒ | _n
t|ƒ| _d S )NÚsource_spaces)r9   ÚlistÚsuperrO   Ú__init__ÚkindÚdictÚinfo)ÚselfrP   rV   ©Ú	__class__© úO/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/source_space.pyrS   Ç   s    
zSourceSpaces.__init__c                 C   sÔ   t ƒ }t| ƒD ]B\}}t|td|f ƒ | | dd ¡¡ td|f |d dƒ qtdd„ |d d… D ƒƒrˆd}t|ƒdkr‚d	}q¨d
}n d}tdd„ |D ƒƒr¤d}nd}t	dd„ ||d … D ƒƒrÐt
d|f ƒ‚|S )Nzsource_spaces[%d]Útypezsource_spaces[%d]["type"]éÿÿÿÿ)rN   rL   rM   c                 s   s   | ]}|d kV  qdS ©rN   NrZ   ©Ú.0ÚkrZ   rZ   r[   Ú	<genexpr>Ù   s     z$SourceSpaces.kind.<locals>.<genexpr>é   rK   Úmixedr   c                 s   s   | ]}|d kV  qdS )rL   NrZ   r_   rZ   rZ   r[   rb   á   s     rL   rJ   c                 s   s   | ]}|d kV  qdS r^   rZ   r_   rZ   rZ   r[   rb   å   s     z"Invalid source space with kinds %s)rQ   Ú	enumerater9   rU   ÚappendÚgetr:   ÚallÚlenÚanyÚRuntimeError)rW   ÚtypesÚsiÚsZ
surf_checkrT   rZ   rZ   r[   rT   Ñ   s(    
 ÿzSourceSpaces.kindFc                 C   sr  ddl m} tƒ }d}	|dkr8tdd„ | D ƒƒr4dnd}t|tƒrN| |¡ n|r\| d¡ |dkrv| jd	krrdnd
}t|tƒrŒ| |¡ nx|d
kr | d¡ nd|dk	�rt|d tƒrðt	j
dt	jdt	jdi}
|D ]}| |
|d  ¡ qÒ|}	n|D ]}| |¡ qô|�r| d¡ | d d t	jk�r@d}|dk�rDtdƒ‚nd}tdddƒ}|||| j|||dddd|	| d�S )aè  Plot the source space.

        Parameters
        ----------
        head : bool
            If True, show head surface.
        brain : bool | str
            If True, show the brain surfaces. Can also be a str for
            surface type (e.g., 'pial', same as True). Default is None,
            which means 'white' for surface source spaces and False otherwise.
        skull : bool | str | list of str | list of dict | None
            Whether to plot skull surface. If string, common choices would be
            'inner_skull', or 'outer_skull'. Can also be a list to plot
            multiple skull surfaces. If a list of dicts, each dict must
            contain the complete surface info (such as you get from
            :func:`mne.make_bem_model`). True is an alias of 'outer_skull'.
            The subjects bem and bem/flash folders are searched for the 'surf'
            files. Defaults to None, which is False for surface source spaces,
            and True otherwise.
        subjects_dir : str | None
            Path to SUBJECTS_DIR if it is not set in the environment.
        trans : str | 'auto' | dict | None
            The full path to the head<->MRI transform ``*-trans.fif`` file
            produced during coregistration. If trans is None, an identity
            matrix is assumed. This is only needed when the source space is in
            head coordinates.
        %(verbose)s

        Returns
        -------
        fig : instance of Figure3D
            The figure.
        r   )Úplot_alignmentNc                 s   s   | ]}|d  dkV  qdS )r\   rN   NrZ   )r`   ÚssrZ   rZ   r[   rb     s   ÿz$SourceSpaces.plot.<locals>.<genexpr>ÚwhiteFÚbrainrK   TZouter_skullr   Zinner_skullZ
outer_skinÚidÚheadÚcoord_framez¦Source space is in head coordinates, but no head<->MRI transform was given. Please specify the full path to the appropriate *-trans.fif file as the "trans" parameter.Úmriç     @�@ÚeegrZ   )ÚtransÚsubjectÚsubjects_dirÚsurfacesru   Úmegrx   ÚdigZecogÚbemÚsrc)Zvizro   rQ   rj   Ú
isinstanceÚstrrf   rT   rU   r   ÚFIFFV_BEM_SURF_ID_BRAINZFIFFV_BEM_SURF_ID_SKULLZFIFFV_BEM_SURF_ID_HEADÚFIFFV_COORD_HEADÚ
ValueErrorr   Ú_subject)rW   rt   rr   Úskullr{   ry   r0   ro   r|   r   Z	skull_mapZ
this_skullrN   ru   rV   rZ   rZ   r[   Úploté   sl    $ÿÿ



  þ


        üzSourceSpaces.plotc                    s$   t ƒ j||Ž}t|tƒr t|ƒ}|S )zGet an item.)rR   Ú__getitem__r�   rQ   rO   )rW   ÚargsÚkwargsÚoutrX   rZ   r[   r‰   D  s    
zSourceSpaces.__getitem__c           	      C   s$  g }g }t | ƒD ]¶\}}|d }t| }|dkr`d|krL|d|d f 7 }q„|d|d f 7 }n$|dkr„|dt|ƒd	 |d
 f 7 }|d|d f 7 }|d	kr¸|dtt|d ƒƒ g7 }| d| ¡ q| j}|d k	ræ|d|f g7 }t| ƒ}|d k	�r|dt|ƒ› �g7 }dd 	|¡d 	|¡f S )Nr\   rM   Úseg_namez (%s)z
, shape=%sÚshaperN   z (%s), n_vertices=%ir   Únpz, n_used=%iÚnusez	%s coordsru   z<%s>z
subject %rú~z<SourceSpaces: [%s] %s>z, )
re   Ú_src_kind_dictÚ	_get_hemirF   Úintrf   r†   r>   r?   Újoin)	rW   Zss_reprÚextrarm   rp   Zss_typeÚrZsubjÚszrZ   rZ   r[   Ú__repr__K  s6    ÿ
 ÿzSourceSpaces.__repr__c                 C   s   | d   dd ¡S )Nr   Úsubject_his_id)rg   ©rW   rZ   rZ   r[   r†   f  s    zSourceSpaces._subjectc                 C   s   |   ¡ }||7 }t|ƒS )zCombine source spaces.)ÚcopyrO   )rW   ÚotherrŒ   rZ   rZ   r[   Ú__add__j  s    zSourceSpaces.__add__c                 C   s   t | ƒS )z˜Make a copy of the source spaces.

        Returns
        -------
        src : instance of SourceSpaces
            The copied source spaces.
        r   r›   rZ   rZ   r[   rœ   p  s    zSourceSpaces.copyc                 C   sp   t | j|ƒ}tƒ }| D ]N}dD ]4}||kr|| }t|ƒ}||kr|jjs|||< q| t ||ƒ¡ qt||ƒS )zMake a deepcopy.©ÚrrÚnn)r   rV   rQ   rs   ÚflagsZ	writeablerf   rO   )rW   ÚmemodictrV   rp   rn   ÚkeyÚarrÚid_rZ   rZ   r[   Ú__deepcopy__z  s    
zSourceSpaces.__deepcopy__©r0   c                C   s   t || |d� dS )z®Save the source spaces to a fif file.

        Parameters
        ----------
        fname : str
            File to write.
        %(overwrite)s
        %(verbose)s
        ©Ú	overwriteN)Úwrite_source_spaces)rW   Úfnamerª   r0   rZ   rZ   r[   ÚsaveŠ  s    zSourceSpaces.saveTrv   c
           )      C   s2  t ||ƒ t|ttfdƒ t|tƒr8td|dgdd� nt|ƒ}t|ƒ}zddl}
W n tk
rp   tdƒ‚Y nX t 	dd	„ | D ƒ¡}|t
jk ¡ rÆd
}|r²|r²|dkrÄtdƒ‚qô|dk	rôt d¡ n.|t
jk ¡ rìd}|dk	rôt d¡ ntdƒ‚t d¡ tƒ \}}tg g d�}| D ]R}|d dk�r:|d  |¡ n.|d dk�rX|d  |¡ ntd|d  ƒ‚�qt|d ƒdk�r†tdƒ‚|d d }d}|�rÐ|dk�r¸t|
 |d ¡ƒ}|d |d |d f}n|d }|�rè|d }n|d  }t|ƒ}|d! }|d
k�r*t|d
dƒd }t||d
|ƒ}n|}t |¡}t|d ƒD ]¾\}}d"|k�r^td#ƒ‚d$}|dk�sr|�rˆ||d"  }|�rˆ|}|dk�r¾t||d% |d&  ƒ}t| ¡  t ¡j!ƒ}n:|dk�rÒ||k}n&|d'k�sàt"‚|d( j#|d)d*� t¡}|||< �qD|d D �]j}d+}|d d,k�rZ|�s.�q|�r†t
j$d-t
j%d.i|d/  d0 }|| }n,|d d1k�slt"‚|�sv�q|�r†t d2¡ |dk�rš|d% }n(|d'k�s²|dk�s²t"‚|d% |d&  }t|d3 |ƒ}|j! ¡  t ¡\} }!}"t &| d|d d+ ¡f}#t &|!d|d+ d+ ¡}$t &|"d|d4 d+ ¡}%| |#k|!|$kB |"|%kB  '¡ }&|&dk�rht(|&› d5|d › d6�ƒ |||#|$|%f< �q|dk�r¢t||d7 |d8 |d7 d! ƒ}|d3  )¡ }'|'dd9…  d:9  < | *d;¡�rò|
 +¡ }(|( ,d<¡ |
j-||'|(d=�}n0| *d>¡�r| d?¡}|
j.j/ 0||'¡}ntd@ƒ‚|
 1||¡ dS )Aa0  Export source spaces to nifti or mgz file.

        Parameters
        ----------
        fname : str
            Name of nifti or mgz file to write.
        include_surfaces : bool
            If True, include surface source spaces.
        include_discrete : bool
            If True, include discrete source spaces.
        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).
        trans : dict, str, or None
            Either a transformation filename (usually made using mne_analyze)
            or an info dict (usually opened using read_trans()). If string, an
            ending of ``.fif`` or ``.fif.gz`` will be assumed to be in FIF
            format, any other ending will be assumed to be a text file with a
            4x4 transformation matrix (like the ``--trans`` MNE-C option.
            Must be provided if source spaces are in head coordinates and
            include_surfaces and mri_resolution are True.
        mri_resolution : bool | str
            If True, the image is saved in MRI resolution
            (e.g. 256 x 256 x 256), and each source region (surface or
            segmentation volume) filled in completely. If "sparse", only a
            single voxel in the high-resolution MRI is filled in for each
            source point.

            .. versionchanged:: 0.21.0
               Support for "sparse" was added.
        use_lut : bool
            If True, assigns a numeric value to each source space that
            corresponds to a color on the freesurfer lookup table.
        %(overwrite)s

            .. versionadded:: 0.19
        %(verbose)s

        Notes
        -----
        This method requires nibabel.
        Úmri_resolutionÚsparsezwhen mri_resolution is a string)r–   r   NzThis function requires nibabel.c                 S   s   g | ]}|d  ‘qS )ru   rZ   ©r`   rn   rZ   rZ   r[   Ú
<listcomp>Ö  s     z.SourceSpaces.export_volume.<locals>.<listcomp>rt   zŒtrans containing mri to head transform must be provided if mri_resolution and include_surfaces are true and surfaces are in head coordinatesz]trans is not needed and will not be used unless include_surfaces and mri_resolution are True.rv   zPtrans is not needed and will not be used unless sources are in head coordinates.zRAll sources must be in head coordinates or all sources must be in mri coordinates.zReading FreeSurfer lookup table)rJ   Úsurface_discreter\   rM   rJ   )rN   rL   r²   zUnrecognized source type: %s.z/Source spaces must contain at least one volume.TÚmri_fileÚ	mri_widthÚ	mri_depthÚ
mri_heightrŽ   Ú	vox_mri_tÚ	src_mri_tÚtor�   z9Volume sources should be segments, not the entire volume.ç      ð?r    ÚvertnoFÚinuseÚF)Úorderr   rN   ZLeftZRightrs   z-Cerebral-CortexrL   zIDiscrete sources do not have values on the lookup table. Defaulting to 1.ry   rc   ú zL vertices lay outside of volume space. Consider using a larger volume space.Ú	mri_ras_tÚfromé   rw   )z.niiz.nii.gzÚmm)Úheaderz.mgzÚfloat32zUnrecognized file extension)2r6   r9   Úboolr‚   r�   r:   ZnibabelÚImportErrorr�   Úarrayr   r„   rh   r…   r/   rV   ÚFIFFV_COORD_MRIr*   rU   rf   ri   r   ÚloadrA   rE   rD   Úzerosre   rB   ÚtupleÚroundÚastyper”   ÚTÚAssertionErrorÚreshapeÚFIFFV_MNE_SURF_LEFT_HEMIÚFIFFV_MNE_SURF_RIGHT_HEMIZclipÚsumr5   rœ   ÚendswithZNifti1HeaderZset_xyzt_unitsZNifti1ImageZ
freesurferZ	mghformatZMGHImager­   ))rW   r¬   Zinclude_surfacesZinclude_discreteÚdestry   r®   Zuse_lutrª   r0   ZnibZcoord_framesZcoordsÚlutÚ_Z	src_typesr€   Z	aseg_dataZshape3dZ	transformZ	fro_dst_tZ
head_mri_tZimgÚiiÚvsZuse_idr¦   ÚidxÚvalZ	surf_nameZuse_rrZsrf_voxZix_Ziy_Ziz_ZixZiyZizZn_diffZaffineÚhdrrZ   rZ   r[   Úexport_volume—  sö    0


ÿ



ÿ






  þýý





  
þ

zSourceSpaces.export_volume)N)FNNNNN)F)TTrv   NFTFN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rS   ÚpropertyrT   r0   rˆ   r‰   r™   r†   rž   rœ   r§   r­   rÞ   Ú__classcell__rZ   rZ   rX   r[   rO   7   s:    

    ÿZ

            ýrO   c                 C   sò   | d }|dkr$d| d< d| d< dS t  d¡ t |¡}|| }t |dd… |dd… k¡d d }tjdg|f }tj|t|ƒgf }tƒ }t||ƒD ] \}}	| 	t 
|||	… ¡¡ qš|| d< ||d  }
t |
| d	 ¡| d< t  d
¡ dS )a>  Patch information in a source space.

    Generate the patch information from the 'nearest' vector in
    a source space. For vertex in the source space it provides
    the list of neighboring vertices in the high resolution
    triangulation.

    Parameters
    ----------
    s : dict
        The source space.
    ÚnearestNÚpinfoÚ
patch_indsz!    Computing patch statistics...r   r]   r   r»   z    Patch information added...)r/   rV   r�   ÚargsortÚwhereÚr_ri   rQ   Úziprf   ÚsortÚsearchsorted)rn   rå   ZindnZnearest_sortedZstepsZstartiZstopiræ   ÚstartÚstopZpatch_vertsrZ   rZ   r[   Ú_add_patch_info�  s$    

&rð   Fc                 C   s~   t |tjƒ}t|ƒdkr tdƒ‚tƒ }|D ]8}t d¡ t| |ƒ}t d¡ |rXt	|ƒ | 
|¡ q*t dt|ƒ ¡ t|ƒS )až  Read the source spaces from a FIF file.

    Parameters
    ----------
    fid : file descriptor
        An open file descriptor.
    tree : dict
        The FIF tree structure if source is a file id.
    patch_stats : bool, optional (default False)
        Calculate and add cortical patch statistics to the surfaces.
    %(verbose)s

    Returns
    -------
    src : SourceSpaces
        The source spaces.
    r   zNo source spaces foundz    Reading a source space...ú
    [done]z    %d source spaces read)r	   r   ÚFIFFB_MNE_SOURCE_SPACEri   r…   rQ   r/   rV   Ú_read_one_source_spaceÚ_complete_source_space_inforf   rO   )ÚfidÚtreeÚpatch_statsr0   Úspacesr€   rn   ÚthisrZ   rZ   r[   Ú_read_source_spaces_from_tree·  s    


rú   c              	   C   sÔ   t | ddd�} t| ddƒ t| ƒ\}}}|�ž}t||||d�}| |jd< t|tjƒ}|rÆ|d }t|d	 ƒD ]X}	|d
 |	 j	}
|d
 |	 j
}t||ƒ}|
tjkr®|j|jd< ql|
tjkrl|j|jd< qlW 5 Q R X |S )aã  Read the source spaces from a FIF file.

    Parameters
    ----------
    fname : str
        The name of the file, which should end with -src.fif or
        -src.fif.gz.
    patch_stats : bool, optional (default False)
        Calculate and add cortical patch statistics to the surfaces.
    %(verbose)s

    Returns
    -------
    src : SourceSpaces
        The source spaces.

    See Also
    --------
    write_source_spaces, setup_source_space, setup_volume_source_space
    ÚreadT©rª   Ú
must_existúsource space)ú-src.fifú-src.fif.gzú_src.fifú_src.fif.gzz-fwd.fifz-fwd.fif.gzz_fwd.fifz_fwd.fif.gzz-inv.fifz-inv.fif.gzz_inv.fifz_inv.fif.gz)r÷   r0   r¬   r   ZnentÚ	directoryÚworking_dirÚcommand_line)r6   r.   r   rú   rV   r	   r   ÚFIFFB_MNE_ENVÚrangerT   Úposr   ÚFIFF_MNE_ENV_WORKING_DIRÚdataÚFIFF_MNE_ENV_COMMAND_LINE)r¬   r÷   r0   Úffrö   rØ   rõ   r€   ÚnodeÚprT   r  ÚtagrZ   rZ   r[   Úread_source_spacesÝ  s(    ÿ



r  c                 C   s  t ƒ }t| |tjƒ}|dkr,ttjƒ|d< nt|jƒ|d< t| |tjƒ}|dkrZtdƒ‚nRt|jƒ}|tj	krxd|d< n4|tj
krŒd|d< n |tjkr d|d< ntd| ƒ‚|d dk�rt| |tjƒ}|dk	rÞt|jƒ|d	< t| |tjƒ}|dk	rþ|j|d
< t|tjƒ}t|ƒdk�r tdƒ‚|d }|d D ]V}|jtjk�r0t| |jƒ}|j}|d tjk�rl||d< |d tjk�r0||d< �q0t| |tjƒ}|dk	�rÂ|j|d< |jjjdk�rÌ|d= n
t d¡ t| |tjƒ}|dk	�rî|j|d< t| |tjƒ}|dk	�rt|jƒ|d< t| |tjƒ}|dk	�r:t|jƒ|d< t| |tjƒ}|dk	�r`t|jƒ|d< t| |tjƒ}|dk	�r‚|j|d< t| |tj ƒ}|dk	�rê|j}	t| |tj!ƒ}d}
g }|	D ]&}| "|j|
|
| … ¡ |
|7 }
�qº||d< t| |tj#ƒ}|dk	�r|j|d< t| |tj$ƒ}|dk�r,tdƒ‚t|jƒ|d< t| |tj%ƒ}|dk�r„t| |tj&ƒ}|dk�rtd|d< nt|jƒ|d< n
|j|d< t| |tj'ƒ}|dk�r®tdƒ‚|jd |d< t| |tj(ƒ}|dk�rÜtd ƒ‚|j )t*j+¡|d!< |d! j,d |d k�rtd"ƒ‚t| |tj-ƒ}|dk�r.td#ƒ‚|j .¡ |d$< |d$ j,d |d k�r\td%ƒ‚|d dk�rät| |tj/ƒ}|dk�r´t| |tj0ƒ}|dk�r¤td&ƒ‚n|jd' |d(< n|jd' |d(< |d( j,d |d k�rìtd)ƒ‚nd|d(< t| |tj1ƒ}|dk�r.d|d*< t*j2|d* t*j3d+�|d,< d|d-< nvt|jƒ|d*< t| |tj4ƒ}|dk�r\td.ƒ‚|j )t*j3¡j5|d,< t|d, ƒ|d k�rŽtd/ƒ‚t* 6|d, ¡d |d-< t| |tj7ƒ}t| |tj8ƒ}|dk�sÔ|dk�ræd|d0< d|d1< n|j|d0< |jd' |d1< t| |tj9ƒ}t| |tj:ƒ}|dk�s.|dk�r@d|d2< d|d3< n|j|d2< |jj5|d3< t;|ƒ t| |tj<ƒ}t| |tj=ƒ}|dk�sŽ|dk�r d|d4< d|d5< n*|j|d4< |j|d5< |d4 |d4 j5 |d4< |d4 dk	�rât d6¡ t| |tj>ƒ}|dk�rd|d7< n
|j|d7< |S )8zRead one source space.Nrs   zUnknown source space typerN   r\   rM   rL   zUnknown source space type (%d)rŽ   r¸   r   z¬Can not find parent MRI location. The volume source space may have been made with an MNE version that is too old (<= 2.7.3). Consider updating and regenerating the inverse.r  rÁ   r·   r¹   rÀ   Úinterpolatorz'Interpolation matrix for MRI not found.r³   r´   r¶   rµ   Úmri_volume_nameÚneighbor_vertr�   zNumber of vertices not foundr�   Úntriz&Coordinate frame information not foundru   zVertex data not foundr    zVertex information is incorrectzVertex normals not foundr¡   z&Vertex normal information is incorrectzTriangulation not foundr   Útrisz&Triangulation information is incorrectr�   )Údtyper¼   r»   z$Source selection information missingz5Incorrect number of entries in source space selectionÚnuse_triÚuse_trisrå   Únearest_distÚdistÚ
dist_limitz!    Distance information added...rš   )?rU   r
   r   ÚFIFF_MNE_SOURCE_SPACE_IDr”   ÚFIFFV_MNE_SURF_UNKNOWNr
  ÚFIFF_MNE_SOURCE_SPACE_TYPEr…   ÚFIFFV_MNE_SPACE_SURFACEÚFIFFV_MNE_SPACE_VOLUMEÚFIFFV_MNE_SPACE_DISCRETEÚ FIFF_MNE_SOURCE_SPACE_VOXEL_DIMSrÌ   ZFIFF_COORD_TRANSr	   ÚFIFFB_MNE_PARENT_MRI_FILEri   rT   r   r  ZFIFFV_MNE_COORD_MRI_VOXELZFIFFV_MNE_COORD_RASÚ"FIFF_MNE_SOURCE_SPACE_INTERPOLATORÚsizer/   rV   ÚFIFF_MNE_SOURCE_SPACE_MRI_FILEÚFIFF_MRI_WIDTHÚFIFF_MRI_HEIGHTÚFIFF_MRI_DEPTHÚFIFF_MNE_FILE_NAMEÚ FIFF_MNE_SOURCE_SPACE_NNEIGHBORSÚFIFF_MNE_SOURCE_SPACE_NEIGHBORSrf   ÚFIFF_COMMENTÚFIFF_MNE_SOURCE_SPACE_NPOINTSZFIFF_BEM_SURF_NTRIÚFIFF_MNE_SOURCE_SPACE_NTRIÚFIFF_MNE_COORD_FRAMEÚFIFF_MNE_SOURCE_SPACE_POINTSrÎ   r�   Úfloat64rŽ   ÚFIFF_MNE_SOURCE_SPACE_NORMALSrœ   ZFIFF_BEM_SURF_TRIANGLESÚFIFF_MNE_SOURCE_SPACE_TRIANGLESÚFIFF_MNE_SOURCE_SPACE_NUSErË   Úint64ÚFIFF_MNE_SOURCE_SPACE_SELECTIONrÏ   ré   ÚFIFF_MNE_SOURCE_SPACE_NUSE_TRIÚ#FIFF_MNE_SOURCE_SPACE_USE_TRIANGLESÚFIFF_MNE_SOURCE_SPACE_NEARESTÚ"FIFF_MNE_SOURCE_SPACE_NEAREST_DISTrð   ÚFIFF_MNE_SOURCE_SPACE_DISTÚ FIFF_MNE_SOURCE_SPACE_DIST_LIMITÚFIFF_SUBJ_HIS_ID)rõ   rù   Úresr  Úsrc_typeZ
parent_mrirv   Údry   Ú
nneighborsÚoffsetÚ	neighborsÚnZtag1Ztag2rZ   rZ   r[   ró     s,   















































ró   c                 C   s¨  t  d¡ t | d ¡| d< | d | d dd…df dd…f }| d | d dd…df dd…f }| d | d dd…d	f dd…f }|| | d
 | d< t|| || ƒ| d< t| d ƒd | d< t  d¡ t  d¡ | d dk�rš| d | d dd…df dd…f }| d | d dd…df dd…f }| d | d dd…d	f dd…f }|| | d
 | d< t|| || ƒ| d< tjj| d dd�d | d< t  d¡ dS )zAdd more info on surface.z$    Completing triangulation info...r  Útri_arear    r  Nr   r   rc   g      @Útri_centÚtri_nng       @ú[done]z.    Completing selection triangulation info...r  r  Zuse_tri_centZ
use_tri_nn©ÚaxisZuse_tri_area)r/   rV   r�   rË   r&   r!   ÚlinalgÚnorm)rù   r0   Úr1Úr2Zr3rZ   rZ   r[   rô   ê  s$    
$$$

$$$rô   c                 C   s:   | d dd…df   ¡ }|dk r,ttjƒ}n
ttjƒ}|S )zÏReturn the hemisphere id for a source space.

    Parameters
    ----------
    src : dict
        The source space to investigate.

    Returns
    -------
    hemi : int
        Deduced hemisphere id.
    r    Nr   )rÔ   r”   r   rÒ   rÓ   )r€   ZxaveÚhemirZ   rZ   r[   Úfind_source_space_hemi  s
    
rQ  c           	      C   sP  |d d dkrt dƒS |d d |d d g}| jdkrvt |d | j¡}t |d |¡}||d< t g t¡|d< nÒ| jdkrÈt |d | j¡}t |d |¡t|d ƒ }t g t¡|d< ||d< n€| jd	k�r@t |d | j	j¡}t |d |¡}t |d | j
j¡}t |d |¡t|d ƒ }t ||f¡}||g}nt d
ƒ‚||fS )a‡  Find vertex numbers and indices from label.

    Parameters
    ----------
    label : Label
        Source space label.
    src : dict
        Source space.

    Returns
    -------
    vertices : list of length 2
        Vertex numbers for lh and rh.
    src_sel : array of int (len(idx) = len(vertices[0]) + len(vertices[1]))
        Indices of the selected vertices in sourse space.
    r   r\   rN   z4Labels are only supported with surface source spacesr»   r   ÚlhÚrhÚbothzUnknown hemisphere type)Ú	ExceptionrP  r�   Zintersect1dÚverticesrí   rÈ   r”   ri   rR  rS  Zhstack)	Úlabelr€   r»   Z
vertno_selZsrc_selZvertno_sel_lhZ
src_sel_lhZvertno_sel_rhZ
src_sel_rhrZ   rZ   r[   Úlabel_src_vertno_sel  s,    



rX  c                 C   s   dd„ | D ƒS )Nc                 S   s   g | ]}|d  ‘qS )r»   rZ   r°   rZ   rZ   r[   r±   J  s     z_get_vertno.<locals>.<listcomp>rZ   )r€   rZ   rZ   r[   Ú_get_vertnoI  s    rY  c                 C   sX   |D ]<}t  d¡ t| tjƒ t| ||ƒ t| tjƒ t  d¡ qt  dt|ƒ ¡ dS )zÇWrite the source spaces to a FIF file.

    Parameters
    ----------
    fid : file descriptor
        An open file descriptor.
    src : list
        The list of source spaces.
    %(verbose)s
    z    Write a source space...rñ   z    %d source spaces writtenN)r/   rV   r   r   rò   Ú_write_one_source_spacer   ri   )rõ   r€   r0   rn   rZ   rZ   r[   Ú_write_source_spaces_to_fidP  s    
r[  )rª   r0   c             	   C   sF   t |tdƒ t| ddƒ t| |d� t| ƒ�}t||ƒ W 5 Q R X dS )a]  Write source spaces to a file.

    Parameters
    ----------
    fname : str
        The name of the file, which should end with -src.fif or
        -src.fif.gz.
    src : instance of SourceSpaces
        The source spaces (as returned by read_source_spaces).
    %(overwrite)s
    %(verbose)s

    See Also
    --------
    read_source_spaces
    r€   rþ   )rÿ   r   r  r  r©   N)r9   rO   r.   r6   r   Ú_write_source_spaces)r¬   r€   rª   r0   rõ   rZ   rZ   r[   r«   e  s
    
r«   c                 C   s�   t | tjƒ |jrvt | tjƒ t| tjƒ |j dd ¡}|rJt| tj	|ƒ |j dd ¡}|rjt| tj
|ƒ t| tjƒ t| |ƒ t| tjƒ d S )Nr  r  )r   r   Z	FIFFB_MNErV   r  r   ZFIFF_BLOCK_IDrg   r   r	  r  r   r[  )rõ   r€   r
  rZ   rZ   r[   r\  €  s    
r\  c                 C   s   ddl m} |d dkr tj}n8|d dkr4tj}n$|d dkrHtj}ntd|d  ƒ‚t| tj|ƒ |d dkr„t| tj	|d ƒ | 
d	d
¡}|r¢t| tj|ƒ t| tj|d ƒ t| tj|d ƒ t| tj|d ƒ t| tj|d ƒ t| tj|d ƒ t| tj|d ƒ |d dk�rDt| tj|d ƒ t| tj|d d ƒ |d dk�rˆ|d d
k	�rˆt| tj|d ƒ t| tj|d d ƒ |d dk�rö| 
dd
¡}|d
k	�ræt dd„ |D ƒ¡}t |¡}t| tj|ƒ t| tj|ƒ t| |d ƒ t| tj|d ƒ t | tj!ƒ t| |d ƒ t| |d ƒ | 
dd
¡}	|	d
k	�rRt| tj"|	ƒ t#|ƒ\}
}}}| 
d¡}|d
k�rˆ| $||d f¡}t%| tj&|ƒ d|k�rÀ|d d
k	�rÀt| tj'|d ƒ t| tj(|
ƒ t| tj)|ƒ t| tj*|ƒ t+| tj!ƒ |d  d
k	�r(t| tj,|d  ƒ t| tj-|d! ƒ |d" d
k	�rr|d"  .¡ }|j/||j0d#�}t%| tj1|ƒ t| tj2|d$ ƒ |d dk�rœd%|k�rœt| tj3|d% ƒ d
S )&zWrite one source space.r   ©r¯   r\   rN   rM   rL   zUnknown source space type (%s)rs   rš   Nru   r�   r    r¡   r¼   r�   r  r  r   r  r  r  c                 S   s   g | ]}t |ƒ‘qS rZ   ©ri   )r`   rE  rZ   rZ   r[   r±   À  s     z+_write_one_source_space.<locals>.<listcomp>r¸   rŽ   rÀ   r·   r  r  r³   rå   r  r  )Úformatr  r�   )4Úscipyr¯   r   r  r   r!  r…   r   r  r  rg   r   r>  r0  r.  r   r1  r3  r7  r5  r/  r   r4  r8  r9  r�   rÈ   Úconcatenater+  r,  r   r"  r   r#  r*  Ú_src_vol_dimsÚ
csr_matrixr   r$  r&  r'  r(  r)  r   r:  r;  rœ   Ztriur_  r<  r=  r-  )rõ   rù   r0   r¯   r@  r
  r  rB  rD  r  r´   r¶   rµ   Únvoxr  ÚdistsrZ   rZ   r[   rZ  –  s”    
ÿ
ÿ




ÿÿÿÿrZ  c           	      C   sŒ  d}d|t | ƒ| f }t| tƒrÌ| dkr2d}d}qòt| tƒrÂ| dd… dkrÂ| dd… }| dd… }zt|ƒ}W n$ tk
r”   td||f ƒ‚Y nX |d	kr¢d
nd}||k rÊtd|||f ƒ‚qòt|ƒ‚n&d}t| d|ƒ}|dk ròtd|f ƒ‚|dk�rt d¡ d}d}npd||f }|d	k�r>t d| ¡ t	|ƒ}nB|dk�r`t d| ¡ t
|ƒ}n |dk�snt‚t d| ¡ |}||||fS )zCheck spacing parameter.z:a string with values "ico#", "oct#", "all", or an int >= 2z&"spacing" must be %s, got type %s (%r)rh   Ú NrÂ   ©ÚicoÚoctz)%s subdivision must be an integer, got %rrh  r   r   z$%s subdivision must be >= %s, got %sÚspacingrc   zspacing must be >= 2, got %dzInclude all verticesz%s = %sz Icosahedron subdivision grade %sri  zOctahedron subdivision grade %szApproximate spacing %s mm)r\   r�   r‚   r”   rU  r…   r2   r/   rV   r   r   rÐ   )	rj  r0   rl   Z	space_errÚstypeÚsvalZlimÚico_surfÚsrc_type_strrZ   rZ   r[   Ú_check_spacingú  sT    ÿ
ÿÿ






ro  Úoct6rq   Tr¨   c                   sB  dˆ |ˆˆ||f }t ˆdd�‰‡ ‡‡fdd„dD ƒ}t|ddgƒD ]*\}	}
|	d	k	rDt |	¡sDtd
|
|	f ƒ‚qDt d¡ t dˆ ¡ t dˆ  ¡ t dˆ ¡ t|ƒ\}}}}t d¡ ~t d¡ g }|dkròt dtddd�| f ¡ tddg|ƒD ]†\}
}	t d|	 ¡ |dk�r6t d|
ˆ ||f ¡ t	|	|
ˆ ||ˆƒ}t dt 
|	¡d |d |d |f ¡ | |¡ t d¡ �q tjtjg}t||ƒD ]T\}}| td	d	d	dd	d	d	|tjd �	¡ |d!  d"  < |d#= |d$= |d%= |d&= �qžt|tt ¡ |d'�ƒ}|�r4|d(k�rd)ntj}t||||d*� t d+¡ |S ),aH  Set up bilateral hemisphere surface-based source space with subsampling.

    Parameters
    ----------
    %(subject)s
    spacing : str
        The spacing to use. Can be ``'ico#'`` for a recursively subdivided
        icosahedron, ``'oct#'`` for a recursively subdivided octahedron,
        ``'all'`` for all points, or an integer to use approximate
        distance-based spacing (in mm).

        .. versionchanged:: 0.18
           Support for integers for distance-based spacing.
    surface : str
        The surface to use.
    %(subjects_dir)s
    add_dist : bool | str
        Add distance and patch information to the source space. This takes some
        time so precomputing it is recommended. Can also be 'patch' to only
        compute patch information (requires SciPy 1.3+).

        .. versionchanged:: 0.20
           Support for add_dist='patch'.
    %(n_jobs)s
        Ignored if ``add_dist=='patch'``.
    %(verbose)s

    Returns
    -------
    src : SourceSpaces
        The source space for each hemisphere.

    See Also
    --------
    setup_volume_source_space
    zXsetup_source_space(%s, spacing=%s, surface=%s, subjects_dir=%s, add_dist=%s, verbose=%s)T©Zraise_errorc              	      s    g | ]}t  ˆˆ d |ˆ ¡‘qS )rN   ©Úopr•   )r`   rP  ©rz   r{   rK   rZ   r[   r±   X  s   ÿz&setup_source_space.<locals>.<listcomp>)zlh.zrh.ZLHZRHNz Could not find the %s surface %sz;Setting up the source space with the following parameters:
zSUBJECTS_DIR = %szSubject      = %szSurface      = %srf  z$>>> 1. Creating the source space...
)rj  rh   z$Doing the %shedral vertex picking...ZicosaZoctarg  rR  rS  zLoading %s...rh   zMapping %s %s -> %s (%d) ...z-loaded %s %d/%d selected to source space (%s)r   r�   r�   rN   )	r  r  rå   r\   r  ræ   rç   rs   ru   r    rw   rF  rG  rH  Úneighbor_tri©r  r  Úpatchç        )r  Ún_jobsr0   z8You are now one step closer to computing the gain matrix)r-   rë   rs  ÚisfileÚIOErrorr/   rV   ro  rU   r   Úsplitrf   r   rÒ   rÓ   ÚupdaterÉ   rO   ÚosÚgetcwdr�   ÚinfÚadd_source_space_distances)rz   rj  rK   r{   Zadd_distry  r0   ÚcmdÚsurfsrN   rP  rk  rl  rm  rn  r€   rn   Zhemi_idsÚs_idr  rZ   rt  r[   Úsetup_source_space+  s|    (þÿÿ


ÿ

ÿÿÿ
   þ
 ÿ
r…  Úvolume_labelc                 C   sü   t |dd|f ƒ t|ddd�}t| tƒr0| g} t | tttf|ƒ t| tƒs¶| d¡sltd|t	 
|¡f ƒ‚tƒ \}}tƒ }| D ]0}||kr¤td||t||ƒf ƒ‚|| ||< q€|} |  ¡ D ]&\}}t |td	ƒ t |d
d|f ƒ q¾dd„ |  ¡ D ƒ} | S )Nú	path-likezmri when %s is not Nonerû   Trü   úaseg.mgzz5Must use a *aseg.mgz file unless %s is a dict, got %szGVolume %r not found in file %s. Double check FreeSurfer lookup table.%szvolume_label keyszint-likezvolume_labels[%r]c                 S   s   i | ]\}}|t |ƒ“qS rZ   )r2   )r`   ra   ÚvrZ   rZ   r[   Ú
<dictcomp>°  s      z(_check_volume_labels.<locals>.<dictcomp>)r9   r6   r�   r‚   rQ   rÌ   rU   rÕ   rk   rs  Úbasenamer*   r…   r=   Úitems)r†  rv   Únamer×   rØ   Zuse_volume_labelrW  r¦   rZ   rZ   r[   Ú_check_volume_labels—  s8    


ÿÿ
þÿrŽ  ç      @rx  Úmc              
      sv  t |ƒ}t|	ttttdfdƒ t|dtdfdƒ tˆdtdfdƒ |dk	rdt|tƒsdt|dddd	�}ˆdk	r†tˆtƒs†tˆddd
d	�‰|dk	ržˆdk	ržt	dƒ‚|dkrÈ| dk	rÈ|	dk	r¼d}nt
ˆ ƒrÈd}|dk	rît|| |ƒ}tˆ tƒrît	dƒ‚|	dk	�rt|	|ƒ}	|	dk�st|	tƒ�st‚t||d�}|dk	�r@t d|¡ n¸ˆdk	�r´tˆtƒ�rŠt‡fdd„dD ƒƒ�svtdƒ‚tˆddd� d}nt ˆ¡�s¢tdˆ ƒ‚ˆ}t d|¡ nDt dd|d  d|d  d|d  f ¡ t dd|d   f ¡ tˆ tƒ�r*t‡ fd!d„d"D ƒƒ�s$td#ƒ‚d}n0ztˆ ƒ‰ W n" tt	fk
�rX   t	d$ƒ‚Y nX tˆ tƒ�s†t d%|¡ t d&¡ t d'¡ tˆ tƒ�r¶t d(ˆ  ¡ t d)| ¡ ˆ d* ‰ |d+k�rÎt d,| ¡ tƒ }|dk	�rt d-| ¡ t d.¡ t d/| ¡ t||	dk	d0�}|d* }t d.¡ tˆ tƒ�s@tˆ ƒg}�nrt|tƒ�rvt|tjdd1�}t d2||d3 f ¡ �n$|dk	�r| d4¡dk�rt  d5d6„ |d7 D ƒ¡d }t!|ƒdk�rÂt	d8ƒ‚|d7 |d  }|d9 tjk�sæt‚|d: tj"k�rt	d;t#|d: ƒf ƒ‚t d<| ¡ n~ˆdk	�rxtˆtƒ�rDt$ˆdd=�d> }nˆ}t d?ˆ|d3 f ¡ t%|ƒ}|d@  dA9  < n"t dB¡ t|d  |dd … dC�}t&|ˆ ||||	||dD�}~t|tƒ�sÄt‚|	dk�sÔ|�rät!|ƒdk�sòn
t!|	ƒ�sòt‚|dk	�r|
�r*t'|ƒ n|d dE dFk�r*dG|d dE< |	dk�rLdH|d k�rL|d dH= |D ]}dI|k�rP|dI= �qPt(|| ƒ}|S )Ja  Set up a volume source space with grid spacing or discrete source space.

    Parameters
    ----------
    subject : str | None
        Subject to process. If None, the path to the MRI volume must be
        absolute to get a volume source space. If a subject name
        is provided the T1.mgz file will be found automatically.
        Defaults to None.
    pos : float | dict
        Positions to use for sources. If float, a grid will be constructed
        with the spacing given by ``pos`` in mm, generating a volume source
        space. If dict, pos['rr'] and pos['nn'] will be used as the source
        space locations (in meters) and normals, respectively, creating a
        discrete source space.

        .. note:: For a discrete source space (``pos`` is a dict),
                  ``mri`` must be None.
    mri : str | None
        The filename of an MRI volume (mgh or mgz) to create the
        interpolation matrix over. Source estimates obtained in the
        volume source space can then be morphed onto the MRI volume
        using this interpolator. If pos is a dict, this cannot be None.
        If subject name is provided, ``pos`` is a float or ``volume_label``
        are not provided then the ``mri`` parameter will default to 'T1.mgz'
        or ``aseg.mgz``, respectively, else it will stay None.
    sphere : ndarray, shape (4,) | ConductorModel | None
        Define spherical source space bounds using origin and radius given
        by (ox, oy, oz, rad) in ``sphere_units``.
        Only used if ``bem`` and ``surface`` are both None. Can also be a
        spherical ConductorModel, which will use the origin and radius.
        None (the default) uses a head-digitization fit.
    bem : path-like | None | ConductorModel
        Define source space bounds using a BEM file (specifically the inner
        skull surface) or a ConductorModel for a 1-layer of 3-layers BEM.
    surface : path-like | dict | None
        Define source space bounds using a FreeSurfer surface file. Can
        also be a dictionary with entries ``'rr'`` and ``'tris'``, such as
        those returned by :func:`mne.read_surface`.
    mindist : float
        Exclude points closer than this distance (mm) to the bounding surface.
    exclude : float
        Exclude points closer than this distance (mm) from the center of mass
        of the bounding surface.
    %(subjects_dir)s
    volume_label : str | dict | list | None
        Region(s) of interest to use. None (default) will create a single
        whole-brain source space. Otherwise, a separate source space will be
        created for each entry in the list or dict (str will be turned into
        a single-element list). If list of str, standard Freesurfer labels
        are assumed. If dict, should be a mapping of region names to atlas
        id numbers, allowing the use of other atlases.

        .. versionchanged:: 0.21.0
           Support for dict added.
    add_interpolator : bool
        If True and ``mri`` is not None, then an interpolation matrix
        will be produced.
    sphere_units : str
        Defaults to ``"m"``.

        .. versionadded:: 0.20
    single_volume : bool
        If True, multiple values of ``volume_label`` will be merged into a
        a single source space instead of occupying multiple source spaces
        (one for each sub-volume), i.e., ``len(src)`` will be ``1`` instead of
        ``len(volume_label)``. This can help conserve memory and disk space
        when many labels are used.

        .. versionadded:: 0.21
    %(verbose)s

    Returns
    -------
    src : SourceSpaces
        A :class:`SourceSpaces` object containing one source space for each
        entry of ``volume_labels``, or a single source space if
        ``volume_labels`` was not specified.

    See Also
    --------
    setup_source_space

    Notes
    -----
    Volume source spaces are related to an MRI image such as T1 and allow to
    visualize source estimates overlaid on MRIs and to morph estimates
    to a template brain for group analysis. Discrete source spaces
    don't allow this. If you provide a subject name the T1 MRI will be
    used by default.

    When you work with a source space formed from a grid you need to specify
    the domain in which the grid will be defined. There are three ways
    of specifying this:
    (i) sphere, (ii) bem model, and (iii) surface.
    The default behavior is to use sphere model
    (``sphere=(0.0, 0.0, 0.0, 90.0)``) if ``bem`` or ``surface`` is not
    ``None`` then ``sphere`` is ignored.
    If you're going to use a BEM conductor model for forward model
    it is recommended to pass it here.

    To create a discrete source space, ``pos`` must be a dict, ``mri`` must be
    None, and ``volume_label`` must be None. To create a whole brain volume
    source space, ``pos`` must be a float and 'mri' must be provided.

    To create a volume source space from label, ``pos`` must be a float,
    ``volume_label`` must be provided, and 'mri' must refer to a .mgh or .mgz
    file with values corresponding to the freesurfer lookup-table (typically
    ``aseg.mgz``).
    Nr†  r‡  r   rK   rû   Tzbem filename)rª   rý   r�  zsurface filenamez3Only one of "bem" and "surface" should be specifiedrˆ  zT1.mgzz_Cannot create interpolation matrix for discrete source space, mri must be None if pos is a dict)Úsphere_unitszBEM              : %sc                 3   s   | ]}|ˆ kV  qd S ©NrZ   ©r`   r¤   )rK   rZ   r[   rb   Q  s     z,setup_volume_source_space.<locals>.<genexpr>)r    r  z3surface, if dict, must have entries "rr" and "tris"F)rœ   r0   zdict()zsurface file "%s" not foundzBoundary surface file : %sz5Sphere                : origin at (%.1f %.1f %.1f) mméè  r   r   rc   z              radius  : %.1f mmrÂ   c                 3   s   | ]}|ˆ kV  qd S r’  rZ   r“  )r  rZ   r[   rb   c  s     rŸ   z(pos, if dict, must contain "rr" and "nn"z<pos must be a dict, or something that can be cast to float()zSource location file  : %szAssuming input in millimetersz!Assuming input in MRI coordinateszgrid                  : %.1f mmzmindist               : %.1f mmrw   rx  zExclude               : %.1f mmzMRI volume            : %srf  úReading %s...)r
  )r„  r0   z%Loaded inner skull from %s (%d nodes)r�   Z	is_spherec                 S   s   g | ]}|d  t jk‘qS )rs   )r   rƒ   )r`   rN   rZ   rZ   r[   r±   �  s   ÿz-setup_volume_source_space.<locals>.<listcomp>rƒ  z*Could not get inner skull surface from BEMrs   ru   z%BEM is not in MRI coordinates, got %szTaking inner skull from %s©Úreturn_dictr]   z*Loaded bounding surface from %s (%d nodes)r    çü©ñÒMbP?zSetting up the sphere...)ÚRÚr0)Úvol_infoÚsingle_volumer\   rM   rL   r�   Úvol_dims))r-   r9   r‚   rQ   rÌ   rU   r   r�   r6   r…   r;   r,   rŽ  rÐ   r8   r/   rV   rh   ÚKeyErrorr$   rs  rz  r{  ÚfloatÚ	TypeErrorr(   Ú_make_discrete_source_spacer   r   rƒ   rg   r�   ré   ri   rÉ   rF   r   r   Ú_make_volume_source_spaceÚ_add_interpolatorÚ_complete_vol_src)rz   r  rv   Zspherer   rK   ÚmindistÚexcluder{   r†  Zadd_interpolatorr‘  rœ  r0   Z
surf_extraZ	pos_extrar›  ÚsprN   Úwhichrn   rZ   )r  rK   r[   Úsetup_volume_source_space´  s   u  ÿÿÿ




 ÿ





ÿ
ÿ

ÿÿÿ

ÿ
      þ
ÿÿ





r©  c                 C   sH   | D ](}|  td d d d d d dd dd |d�¡ qt| tt ¡ dd�ƒ} | S )Nr   )rå   r  r  rç   r  ræ   r  r  r  r  rš   ÚNonerv  )r}  rU   rO   r~  r  )r§  rz   rn   rZ   rZ   r[   r¤  Ã  s         þ
r¤  c                 C   sž   |j dkst‚|jdkst‚|j|tjdd…f  }|j dksBt‚|jd dksTt‚|jd dksft‚tjtj|t 	d¡f tj| df f }t
dd	|ƒ}|S )
zCMake a transformation from MRI_VOXEL to MRI surface RAS (i.e. MRI).r   rÂ   Nrc   r   )r   rÂ   rº   Ú	mri_voxelrv   )ÚndimrÐ   r%  rÏ   r�   ZnewaxisrŽ   Zc_rê   rË   rG   )ÚmoveÚrasÚ
voxel_sizeZrotry   ÚtrZ   rZ   r[   Ú_make_voxel_ras_transÍ  s    (r±  rv   c                 C   s8  |t kr tdtt  ¡ ƒ|f ƒ‚t | }t | d t¡}t | d t¡}|j|j  kr`dkr¨n nD|jd |jd kr¨|jd |jd kr¨t 	|¡ 
¡ r¨t 	|¡ 
¡ s°tdƒ‚|jd }t|ƒ t tj|| dd�dk¡}|dkròtd	| ƒ‚t d
¡ t d| ¡ t|d||t |t¡t |¡||tjd�	}|S )a›  Use a discrete set of source locs/oris to make src space.

    Parameters
    ----------
    pos : dict
        Must have entries "rr" and "nn". Data should be in meters.
    coord_frame : str
        The coordinate frame in which the positions are given; default: 'mri'.
        The frame must be one defined in transforms.py:_str_to_frame

    Returns
    -------
    src : dict
        The source space.
    z'coord_frame must be one of %s, not "%s"r    r¡   rc   r   r   zV"rr" and "nn" must both be finite 2D arrays with the same number of rows and 3 columnsrJ  z"%d sources have zero length normalz&Positions (in meters) and orientationsz
%d sourcesrL   )	ru   r\   r�   r�   r¼   r»   r    r¡   rs   )rH   rž  rQ   Úkeysr�   rÈ   rŸ  r¬  rŽ   Úisfiniterh   rk   r!   rÔ   r/   rV   rU   Úonesr”   Úaranger   r  )r  ru   r    r¡   ÚnptsZnzr§  rZ   rZ   r[   r¡  Ú  s<    ÿ0ÿÿþ



   þr¡  c
           ;         sn  d| kr\t j| d dd�}
t j| d dd�}t j| d dd�}t jj| d | dd� ¡ }n4| d | d  }
| d | d  }| d  ¡ }| d }t dd|d  d|d  d|d	  f ¡ t d
d|  ¡ t d¡ t	d|
|ƒD ]&\}}}t d|d| d| f ¡ qät  
‡ fdd„|D ƒt¡}t  
‡ fdd„|
D ƒt¡}t d¡ t	d||ƒD ]0\}}}t d|d| ˆ  d| ˆ  f ¡ �qVt|| d ƒ}t  |¡}|d }|d }|| }t jt  |d	 |d	 d ¡t  |d |d d ¡t  |d |d d ¡dd�}|d	  ¡ |d  ¡ |d  ¡   }}}t  
|ˆ  |ˆ  |ˆ  g¡j}t|t  |df¡|t  |t¡d|tjtj|d�	}d|d dd…d	f< |d jd |k�sªt‚t d|d ¡ t jj|d | dd�}t  t  ||k ||k¡¡d }d|d |< |d  t|ƒ8  < t d|d d| d| ¡ d| k�rJt| |d|g|ƒ n~t  |d ¡d }t jj|d | | d  dd�| d |d   k}|d  | ¡ 8  < d|d || < t  |d ¡d |d!< ~~ t d"|d |f ¡ |dk�rüd#|d$< |g} �n¸|�s
t d%ƒ‚t!ƒ } |}!| "¡ D ]þ\}"}#tƒ }$d&D ]$}%|%|!k�r.|!|% }&|&|$t#|&ƒ< �q.t$|!|$ƒ}t%||d |d!  ƒ|#k}'|' ¡ }(t d'|(t&|(ƒ|"f ¡ |(dk�rÈt'd(t(|"ƒ› d)|#› d*ˆ d d+›d,�ƒ d|d |d! |'  < |d! |' |d!< |d  ¡ |d< |"|d$< ||d-< |  )|¡ �q~!t| ƒt|ƒk�s4t‚|	�r´| dd… D ]}d.| d d |d! < �qF| d }d/ *d0d1„ | D ƒ¡|d$< | dd… } t  |d ¡d |d!< t|d! ƒ|d< ~~|�sÂ| S t  |¡})t  +d2|ft¡}*|* ,d¡ ||d	 k||d k ||d k ||d k||d k||d	 k g}+| d|d| |g},t	|*dd3… |+|,ƒD ]\}-}.}/|)|. |/ |-|.< �qN||d	 k}0t  -|0||d k ¡}1|)|1 d | |*d3|1f< t  -|1||d k ¡}2|)|2 d | | |*d4|2f< t  -|0||d k ¡}1|)|1 | | |*d5|1f< t  -|0||d k¡}1t  -|1||d k ¡}2|)|2 d | | |*d6|2f< |)|1 d | |*d7|1f< t  -|1||d k¡}2|)|2 d | | |*d8|2f< t  -|0||d k¡}1|)|1 | | |*d9|1f< t  -|1||d k ¡}2|)|2 d | | |*d:|2f< t  -||d k ||d k ¡}0|)|0 d | |*d;|0f< ||d k}0t  -|0||d k ¡}1|)|1 d | |*d<|1f< t  -|0||d k¡}1|)|1 d | |*d=|1f< t  -||d k||d k ¡}0|)|0 d | | |*d>|0f< ||d	 k }0t  -|0||d k ¡}1|)|1 d | |*d?|1f< t  -|1||d k ¡}2|)|2 d | | |*d@|2f< t  -|0||d k ¡}1|)|1 | | |*dA|1f< t  -|0||d k¡}1t  -|1||d k ¡}2|)|2 d | | |*dB|2f< |)|1 d | |*dC|1f< t  -|1||d k¡}2|)|2 d | | |*dD|2f< t  -|0||d k¡}1|)|1 | | |*dE|1f< t  -|1||d k ¡}2|)|2 d | | |*dF|2f< t dG¡ |ˆ  }3ˆ t  d¡ }4t  .d¡}5t/|3|5|4ƒ}6|*}7| D ]¸}|7 ¡ }*d|*dd…t  0|d ¡f< |*j}8|* ¡ }*t  |*dk¡d }9t  0t  1|9|d! ¡¡}:d|*|9|: < |8|*_|*j}*|*|dH< |6|dI< || d |dJ< dKD ]}%|%|k�r
||% ||%< �q
�
qrt2| d dI dLƒ dMD ]&}%|%| d k�rBt2| d |% dNƒ �qB| S )Oz<Make a source space which covers the volume bounded by surf.r    r   rJ  r   rš  r™  z#Surface CM = (%6.1f %6.1f %6.1f) mmr”  rc   z1Surface fits inside a sphere with radius %6.1f mmzSurface extent:Zxyzz    %s = %6.1f ... %6.1f mmc                    sF   g | ]>}|d kr(t  t  |¡ˆ  ¡d nt  t  |¡ˆ  ¡ d ‘qS ©r   r   ©r�   ÚfloorÚabs©r`   r�  ©ÚgridrZ   r[   r±      s   ÿ ÿÿz-_make_volume_source_space.<locals>.<listcomp>c                    sF   g | ]>}|d kr(t  t  |¡ˆ  ¡d nt  t  |¡ˆ  ¡ d ‘qS r·  r¸  r»  r¼  rZ   r[   r±   "  s   ÿ ÿÿzGrid extent:Zij)ZindexingrÂ   rM   )	r�   r¡   r    r¼   r\   r�   ru   rs   rŽ   rº   r¡   Nz%d sources before omitting any.r�   Fr¼   zI%d sources after omitting infeasible sources not within %0.1f - %0.1f mm.r]   rw   r»   zc%d sources remaining after excluding the sources outside the surface and less than %6.1f mm inside.zthe whole brainr�   z7volume_label cannot be None unless do_neighbors is TruerŸ   z    Selected %d voxel%s from %sz)Found no usable vertices in volume label z (id=z
) using a z0.1fz mm gridr³   Tú+c                 s   s   | ]}|d  V  qdS )r�   NrZ   r°   rZ   rZ   r[   rb     s     z,_make_volume_source_space.<locals>.<genexpr>é   é   é   é   é	   é
   é   é   é   é   é   é   é   é   é   é   é   é   é   é   é   z Adjusting the neighborhood info.r  r¸   r�  )r´   r¶   rµ   r  r·   rÀ   zSource space : )r·   rÀ   zMRI volume : )3r�   ÚminÚmaxÚmeanrL  rM  rœ   r/   rV   rë   rÈ   r”   rÌ   ÚprodÚmeshgridrµ  ÚravelrÏ   rU   rË   r´  rÆ   r   rÉ   r  rŽ   rÐ   ré   Ú
logical_orri   Ú_filter_source_spacesrÔ   rk   rQ   rŒ  rs   r   r)   r<   r5   Úreprrf   r•   ÚemptyÚfillÚlogical_andÚeyer±  Zlogical_notÚin1drC   );rN   r½  r¦  r¥  rv   Zvolume_labelsZdo_neighborsry  r›  rœ  ZminsÚmaxsÚcmZmaxdistÚcÚmiÚmaZmaxnZminnÚnsr¶  ZnrowZncolZnplaner    ÚxÚyÚzr§  re  Zbadsr»   ZspsZorig_spr†  r¦   r£   r¤   r¥   ÚgoodZn_goodra   ÚneighZidxsÚoffsetsrE  rÛ   rC  Zidx1Zidx2Zidx3rš  r¯  r®  r¸   Z
neigh_origZ	old_shapeZchecksZremovesrZ   r¼  r[   r¢    s”    ÿÿ
ÿÿÿÿÿ
ÿ

 þ(
   ý  þ
ÿ
þ



ÿ
&


 
 
ÿ


r¢  c                 C   s   || |  || |   S r’  rZ   )ÚwidthÚheightÚjjÚkkÚpprZ   rZ   r[   Ú_vol_vertexõ  s    ró  c                    s0   ‡ fdd„dD ƒ\}}}|||t  |||g¡fS )Nc                    s   g | ]}ˆ d |› � ‘qS )Zmri_rZ   r“  ©rn   rZ   r[   r±   ú  s     z!_src_vol_dims.<locals>.<listcomp>)rî  rï  Údepth)r�   r×  )rn   ÚwÚhrA  rZ   rô  r[   rb  ù  s    rb  c                 C   s&  ddl m} t| d ƒ\}}}}t| d d t| d d ƒddƒ}t d¡ t | d d t	¡}| D ]}tj
||d |d	� qdt| d d
 |||f|d d|d�}	t|	|jƒs²t‚t| ƒD �]Z\}
}t| ƒdkrØ|	}�nt |	jjd tj¡}|d |	j |dd…< tj||d	� t ||	j ¡dk}|j|	jd fk�s>t‚t |	j¡}d|d< t |	j¡|dd…< d|dd… | < tj||d	� t |t |	j¡¡}|	j| }|	j| }|j|j  k�rÐ|d fk�sÖn t‚|j|||f|	jd�}||d< t dt|d jƒ||d f ¡ qºt d¡ dS )zCCompute a sparse matrix to interpolate the data into an MRI volume.r   r]  r·   r¸   r«  z#Setting up volume interpolation ...r�   r¼   )rŒ   r�  ry   r   )r¾   r¼   Nr]   ©rŽ   r  z    %d/%d nonzero values for %sr�   rI  )r`  r¯   rb  rD   rA   r/   rV   r�   rË   rÆ   rÚ  Ú_grid_interpr�   rc  rÐ   re   ri   Úindicesr%  r6  ÚcumsumÚdiffÚindptrrŽ   Z
empty_likeÚrepeatr
  )r§  r¯   r´   r¶   rµ   rd  Zcombo_transr¼   Zs_Úinterprm   rn   Zthis_interpZany_rý  Úmaskrú  r
  rZ   rZ   r[   r£  þ  sZ     þ

   þ

( ÿÿr£  c                 C   s  ddl m} t | t¡} t |t¡}t |tj¡}|jdkrTt |d ddddg¡sXt‚| j|j  krpdksvn t‚t 	|¡t 	| ¡f}|dkr¢t 
|d t¡}|jtks°t‚|j|d fksÄt‚t| ||||ƒ\}}}	t |¡}t |¡}t |	¡}	|j|||	f|d�}
|
S )	z=Compute a grid-to-grid linear or nearest interpolation given.r   r]  )é   r  rÂ   r   )rÂ   Nrø  )r`  r¯   r�   rÈ   r”   r2  rŽ   Úarray_equalrÐ   r×  r´  rÆ   r  Ú_grid_interp_jitra  rû  rc  )Ú
from_shapeÚto_shapery   r¾   r¼   r¯   rŽ   r
  rú  rý  rÿ  rZ   rZ   r[   rù  4  s.    &    ÿ



rù  c           0   
   C   s  |dkst ‚tƒ }tƒ }t |¡}t |d tj¡}|\}	}
}t d|
|	ftj¡}t |	¡|dd d …d d …f< t |
¡ 	d|
d¡|dd d …d d …f< d|dd d …d d …f< t 	|d|	|
 f¡}| \}}}t 
|¡}| d  	dd¡}t|ƒD �]"}||d< || d d… j}|dk�r¢t |¡ tj¡}t t tj|dkdd�tj||kdd�¡¡d }d||||
 |	  d < | t||f|| jžŽ ¡ | t t|ƒ¡¡ qêt |¡ tj¡}t t tj|dkdd�tj||kdd�¡¡d }t|ƒdk�röqê|| }|| }|dkj\}}}||k j\}}}|d d …df } |d d …df }!|d d …df }"t t| ƒd	ftj¡}#| d }$|!d }%|"d }&t t| ƒd	ft¡}'t||| |!|"ƒ|#d d …df< ||@ |@ |'d d …df< t|||$|!|"ƒ|#d d …df< ||@ |@ |'d d …df< t|||$|%|"ƒ|#d d …df< ||@ |@ |'d d …df< t||| |%|"ƒ|#d d …df< ||@ |@ |'d d …df< t||| |!|&ƒ|#d d …df< ||@ |@ |'d d …df< t|||$|!|&ƒ|#d d …d
f< ||@ |@ |'d d …d
f< t|||$|%|&ƒ|#d d …df< ||@ |@ |'d d …df< t||| |%|&ƒ|#d d …df< ||@ |@ |'d d …df< |d d …df |d d …df  tj¡ }(|d d …df |d d …df  tj¡ })|d d …df |d d …df  tj¡ }*d|( }+d|) },d|* }-t t|ƒd	ftj¡}.|+|, |- |.d d …df< |(|, |- |.d d …df< |(|) |- |.d d …df< |+|) |- |.d d …df< |+|, |* |.d d …df< |(|, |* |.d d …d
f< |(|) |* |.d d …df< |+|) |* |.d d …df< d|'|.dk< |' ¡ }/||#|'  |/|'< d|'|/jdd� < | |#|' ¡ |' d¡||||
 |	  d < | |.|' ¡ qê|||fS )Nr·  r   r  r   rÂ   rc   rJ  r]   rÂ  é   rÀ  rÁ  rº   F)rÐ   rQ   r�   r×  rË   Úint32rÝ  r2  rµ  rÑ   Zascontiguousarrayr  rÏ   rÍ   rÎ   ré   rß  rh   rf   ró  r´  ri   r¹  rÆ   rœ   rj   rÔ   )0r  r  ry   r¾   r¼   r
  rú  rd  rý  r´   r¶   rµ   Zr0__Zr0_rî  rï  rØ   râ  r  rš  ÚrxZkeepZrnrë  ZrnsZr0sZjj_gZkk_gZpp_gZjjp1_gZkkp1_gZppp1_grð  rñ  rò  ZvssZjjp1Zkkp1Zppp1r   ZxfZyfÚzfZomxfZomyfZomzfZthis_wZrow_maskrZ   rZ   r[   r  K  s®    

&


ÿÿÿÿ(((r  çê-�™—q=c                    s    t j‡ ‡fdd„|jD ƒdd�S )Nc                    s.   g | ]&}t  |d d… ˆ j¡|d  ˆk‘qS )Nr]   )r�   ÚdotrÏ   )r`   Úeq©ÚptsÚ	tolerancerZ   r[   r±   ¶  s   ÿz _pts_in_hull.<locals>.<listcomp>r   rJ  )r�   rh   Z	equations)r  Zhullr  rZ   r  r[   Ú_pts_in_hullµ  s
    ÿÿr  c                 C   s†  |d d t jkr"|dkr"tdƒ‚d}|d d t jkrJt|ƒ}|d7 }n0|d d t jkrf|d7 }n|d|d d  7 }t |¡ d	}|d
krœ|d| 7 }t |d ¡ t| ƒ}|D �]È}	t 	|	d ¡d }
|	d |
 }|	d t jkröt
|d |ƒ}|||ƒ}|  ¡ }d}|d
k�r¨t 	|¡d }|| }|jdk	�rntjj||j dd�|j|d  k}|| }|| }t| d |ddd�d }||d k }t |¡}d||| < d|	d |
|  < ~
|	d  || 8  < t 	|	d ¡d |	d< |dk�r&|g}||dk�r
ddgnddg7 }t dt|ƒ ¡ |dk�rl|g}||dk�rHdgndg7 }||g7 }t dt|ƒ ¡ || dkr¶t|	ƒ q¶|S ) zARemove all source space points closer than a given limit (in mm).r   ru   NzOSource spaces are in head coordinates and no coordinate transform was provided!zSource spaces are in zhead coordinates.zMRI coordinates.zunknown (%d) coordinates.z0Checking that the sources are inside the surfacerx  z and at least %6.1f mm awayz (will take a few...)r¼   r    ry   r]   rJ  rw   TZcKDTree)Zreturn_distsÚmethodr   Fr�   r»   rn   zthey arerf  zit iszO    %d source space point%s omitted because %s outside the inner skull surface.zK    %d source space point%s omitted because of the %6.1f-mm distance limit.)r   r„   rk   rA   rÉ   r/   rV   r'   r�   ré   rB   rÔ   Zinner_rrL  rM  rã  r%   rÌ   Ú_adjust_patch_info)rN   ÚlimitZ
mri_head_tr€   ry  r0   Zout_strZ	inv_transZcheck_insidern   r»   Zr1sZinsideZomit_outsideZ
omit_limitrÛ   Z	check_r1sr   re  ÚcloseÚextrasrZ   rZ   r[   rÛ  º  s~    






ÿ   ÿÿ

ÿ

ÿ
rÛ  c                 C   s.   |   d¡dk	r*| d dkr"tdƒ‚t| ƒ dS )z8Adjust patch information in place after vertex omission.rç   Nrå   zRCannot adjust patch information properly, please contact the mne-python developers)rg   rk   rð   )rn   r0   rZ   rZ   r[   r  	  s    r  rf  c                 C   sÜ   t d|dƒ d|f }t| ƒrVt| ƒ} t | ¡s<td|  ƒ‚t d|  ¡ t| dd�} t	| t
ƒsvtd|| t| ƒf ƒ‚|d	k	rØ| j|kr¼| jd
kr¼|dkr¨| d	d… } n|dkr¼| dd	… } | j|krØtd|| jf ƒ‚| S )zEnsure we have a source space.rT   )NrK   rJ   rd   rL   z2src must be a string or instance of SourceSpaces%sz Source space file "%s" not foundr•  Fr¨   z%s, got %s (type %s)Nrd   rK   rc   rJ   z)Source space must contain %s type, got %s)r:   r7   r‚   rs  rz  r{  r/   rV   r  r�   rO   r…   r\   rT   )r€   rT   r–   r0   ÚmsgrZ   rZ   r[   Ú_ensure_src	  s2      ÿ



ÿr  c                 C   sH   | j }|d kr$|}|d krDtdƒ‚n |d k	rD||krDtd||f ƒ‚|S )Nz1source space is too old, subject must be providedzPMismatch between provided subject "%s" and subject name "%s" in the source space)r†   r…   )r€   rz   Zsrc_subjectrZ   rZ   r[   Ú_ensure_src_subject,	  s    
þr  i(  c             
      sØ  ddl m} ddlm} t| ƒ} tˆƒ‰ˆdk r>tdˆf ƒ‚ˆdk}|r\tddƒs\tdƒ‚| j	dkrntd	ƒ‚t
t|ƒ\}‰}tƒ }tƒ }	|r’d
nd}
t d|
dˆ f ¡ tdd„ | D ƒƒ}|sØ|tkrØtd|f ƒ | D �]¢‰tˆd ˆd ƒ‰ |�rF|ˆ ˆd ddd�\}}}| | tj¡¡ |	 |¡ dD ]}dˆ|< �q4qÜ|‡ ‡‡‡fdd„t t tˆd ƒ¡|¡D ƒƒ}t dd„ |D ƒ¡}t dd„ |D ƒ¡}tj|dd�}t tˆd ƒ¡}|||f }|||f }| |¡ |	 |¡ t dd„ |D ƒ¡ ¡ }|dk}|| }t ˆd ˆd ¡\}}| ¡ | }| ¡ | }||||ffˆd ˆd ftjd�ˆd < t ˆgtj¡ˆd!< qÜtd"d„ |D ƒƒ�sÊt | ||	ƒD ]$\‰}}|ˆd#< |ˆd$< t!ˆƒ �q¢n
t d%¡ | S )&aè  Compute inter-source distances along the cortical surface.

    This function will also try to add patch info for the source space.
    It will only occur if the ``dist_limit`` is sufficiently high that all
    points on the surface are within ``dist_limit`` of a point in the
    source space.

    Parameters
    ----------
    src : instance of SourceSpaces
        The source spaces to compute distances for.
    dist_limit : float
        The upper limit of distances to include (in meters).
        Note: if limit < np.inf, scipy > 0.13 (bleeding edge as of
        10/2013) must be installed. If 0, then only patch (nearest vertex)
        information is added.
    %(n_jobs)s
        Ignored if ``dist_limit==0.``.
    %(verbose)s

    Returns
    -------
    src : instance of SourceSpaces
        The original source spaces, with distance information added.
        The distances are stored in src[n]['dist'].
        Note: this function operates in-place.

    Notes
    -----
    This function can be memory- and CPU-intensive. On a high-end machine
    (2012) running 6 jobs in parallel, an ico-5 (10242 per hemi) source space
    takes about 10 minutes to compute all distances (``dist_limit = np.inf``).
    With ``dist_limit = 0.007``, computing distances takes about 1 minute.

    We recommend computing distances once per source space and then saving
    the source space to disk, as the computed distances will automatically be
    stored along with the source space data for future use.
    r   )rc  ©Údijkstraz'dist_limit must be non-negative, got %sr`  z1.3z™scipy >= 1.3 is required to calculate patch information only, consider upgrading SciPy or using dist_limit=np.inf when running add_source_space_distancesrK   z3Currently all source spaces must be of surface typezpatch informationzsource space distanceszCalculating %s (limit=%s mm)...r”  c                 s   s   | ]}|d  V  qdS )r�   NrZ   r°   rZ   rZ   r[   rb   |	  s     z-add_source_space_distances.<locals>.<genexpr>zsComputing distances for %d source space points (in one hemisphere) will be very slow, consider using add_dist=Falser  r    r»   T)rú  Zmin_onlyZreturn_predecessors)r  r  Nc                 3   s    | ]}ˆˆ ˆd  |ˆƒV  qdS )r»   NrZ   ©r`   r—   ©Z	adjacencyr  Zp_funrn   rZ   r[   rb   Œ	  s   ÿc                 S   s   g | ]}|d  ‘qS )r   rZ   ©r`   ÚddrZ   rZ   r[   r±   �	  s     z.add_source_space_distances.<locals>.<listcomp>c                 S   s   g | ]}|d  ‘qS )rc   rZ   r  rZ   rZ   r[   r±   ‘	  s     rJ  c                 S   s   g | ]}|d  ‘qS )r   rZ   r  rZ   rZ   r[   r±   ™	  s     r�   )rŽ   r  r  r  c                 s   s   | ]}t  t  |¡¡V  qd S r’  )r�   rj   Úisinf)r`   ÚmdrZ   rZ   r[   rb   ¤	  s     rå   r  z2Not adding patch information, dist_limit too small)"Zscipy.sparserc  Úscipy.sparse.csgraphr  r  rŸ  r…   r3   rk   rT   r@   Ú_do_src_distancesrQ   r/   rV   rÕ  Ú_DIST_WARN_LIMITr5   r#   rf   rÎ   r�   rÅ   Zarray_splitrµ  ri   rÈ   Úargminra  rÙ  rØ  rj   rë   rð   )r€   r  ry  r0   rc  r  Z
patch_onlyÚparallelZ	min_distsZmin_idxsr  Zmax_nÚmin_distrØ   Úmin_idxr¤   rA  ÚmidxÚ	range_idxrÛ   ÚiÚjrZ   r  r[   r�  =	  sˆ    )ÿ
þ
  þ
ÿÿ


  ÿ

r�  c                 C   sf  ddl m} t||d�}d}tjt dt|ƒ|¡t|ƒf }t|ƒd }t t|ƒt|ƒftj¡}	t || j	d f¡}
t || j	d ftj
¡}t | j	d ¡}tt|dd… |dd… ƒƒD ]j\}\}}||||…  }|| |d�}tj|dd	�}|| ||< |||f |
|< |dd…|f |	||…< q¼tj|
dd	�}|
||f }
|||f }d|	|	tjk< |	||
fS )
z)Compute source space distances in chunks.r   r  )r  rÎ  r   Nr]   )rú  rJ  )r!  r  r   r�   rê   rµ  ri   rÝ  rÅ   rŽ   r  re   rë   r$  r€  )Úconr»   Zrun_indsr  r  ÚfuncÚ
chunk_sizeZlimsZn_chunksrA  r&  r'  r)  ZliÚl1Úl2rÛ   rŒ   r(  rZ   rZ   r[   r"  ¯	  s*     *r"  c              	   C   sh  ddl m} ddlm} t ||dd¡}||dd�}t| ƒdk rHtd	ƒ‚td
d„ | dd… D ƒƒrjtdƒ‚t	ƒ }t
dt| ƒƒD ]ä}| | d }	| | d | | d dd…f }
| | d }z(|d  |¡}t |d | ¡d }W n tk
rö   Y nX d| ¡ k�rd}| dd¡d }n(d| ¡ k�r@d}| dd¡d }nd}||	|
||||d�}| |¡ q~|S )a’  Return a list of Label of segmented volumes included in the src space.

    Parameters
    ----------
    src : instance of SourceSpaces
        The source space containing the volume regions.
    %(subject)s
    subjects_dir : str
        Freesurfer folder of the subjects.

    Returns
    -------
    labels_aseg : list of Label
        List of Label of segmented volumes included in src space.
    r   )ÚLabel)Úget_volume_labels_from_asegrv   rˆ  T)Zreturn_colorsrc   zNo vol src space in srcc                 s   s    | ]}t  |d  dk¡V  qdS )r\   rM   N)r�   rj   r°   rZ   rZ   r[   rb   ê	  s     z-get_volume_labels_from_src.<locals>.<genexpr>Nz$source spaces have to be of vol typer»   r    r�   r   éÿ   ÚleftrR  zLeft-rf  z-lhÚrightrS  zRight-z-rhrT  )rV  r  rP  r�  Úcolorrz   )rf  r1  Ú_freesurferr2  rs  r•   ri   r…   rj   rQ   r  Úindexr�   rÈ   ÚlowerÚreplacerf   )r€   rz   r{   r1  r2  Z
aseg_fnameZall_labels_asegZlabels_asegÚnrrV  r  Zroi_strÚindr6  rP  rW  rZ   rZ   r[   Úget_volume_labels_from_srcÍ	  sF     ÿ  þr=  c                 C   s`   | d dkrt dƒ‚| d tjkr0dd| d fS | d tjkrLdd| d fS td	| d  ƒ‚d
S )z+Get a hemisphere from a given source space.r\   rN   z$Only surface source spaces supportedrs   rR  r   rS  r   zunknown surface ID %sN)rk   r   rÒ   rÓ   r…   rô  rZ   rZ   r[   r“   

  s    r“   c                    s:  t  dˆ ||f ¡ ‡ ‡fdd„||fD ƒ}dd„ |D ƒ\}}|dk	rN||d< d|krlt|d |d ƒ|d< t t|d	 ƒt¡}	t | d t¡}
t|d	 |d	 | d
  ƒ}t| d
 |ƒD ]|\}}|	| �r$t	||ƒ}|}|t 
|	|  ¡d  }t|ƒdk�r
td| ƒ‚|d }t  d||f ¡ ||
|< d|	|< q¸|
S )z¨Get a nearest-neigbor vertex match for a given hemi src.

    The to_neighbor_tri can optionally be passed in to avoid recomputation
    if it's already available.
    z)Mapping %s %s -> %s (nearest neighbor)...c              	      s    g | ]}t  ˆ|d dˆ  ¡‘qS )rN   z%s.sphere.regrr  r°   ©rP  r{   rZ   r[   r±   !
  s   ÿz&_get_vertex_map_nn.<locals>.<listcomp>c                 S   s   g | ]}t |d d�d ‘qS )Tr–  r]   )r   r  rZ   rZ   r[   r±   #
  s     Nru  r  r�   r    r»   r   z'vertex %d would be used multiple times.zESource space vertex moved from %d to %d because of double occupation.T)r/   rV   r"   r�   rË   ri   r”   r%   rë   r    ré   rk   )Zfro_srcÚsubject_fromÚ
subject_torP  r{   Zto_neighbor_triÚregsZreg_froZreg_toZmorph_inuseÚbestr´  r‰  Úonerì  ÚwasrZ   r>  r[   Ú_get_vertex_map_nn
  s@    	ÿÿÿ

ÿÿ
rE  c                 C   sh  t | ƒ} t| |ƒ}t|dd�}tƒ }| D �]}t|ƒ\}}	}
t ||dd||f ¡}t d|f ¡ t	|ddd�d }t
|dd	� t||||||d
 ƒ}dD ]
}||= qœt ||d  ¡|d< t t|d ƒt¡|d< d|d |d < ||d  |d< |jt|d ƒt|d ƒddddd|
ddtj||d d d� | |¡ t d¡ q(tt ¡ tƒ d�}t||d�S )a”  Morph an existing source space to a different subject.

    .. warning:: This can be used in place of morphing source estimates for
                 multiple subjects, but there may be consequences in terms
                 of dipole topology.

    Parameters
    ----------
    src_from : instance of SourceSpaces
        Surface source spaces to morph.
    subject_to : str
        The destination subject.
    surf : str
        The brain surface to use for the new source space.
    subject_from : str | None
        The "from" subject. For most source spaces this shouldn't need
        to be provided, since it is stored in the source space itself.
    subjects_dir : str | None
        Path to SUBJECTS_DIR if it is not set in the environment.
    %(verbose)s

    Returns
    -------
    src : instance of SourceSpaces
        The morphed source spaces.

    Notes
    -----
    .. versionadded:: 0.10.0
    Trq  rN   z%s.%szReading destination surface %sF)r—  r0   r]   )rœ   ru  )ru  rF  rG  rH  r  r»   r    r¼   r  Nrw   )r�   r  rå   r  rç   ræ   r  rs   r  r\   ru   rš   r    z[done]
rv  )rV   )r  r  r-   rQ   r“   rs  r•   r/   rV   r   r$   rE  r�   rì   rË   ri   r”   r}  r   rÉ   rf   rU   r~  r  r4   rO   )Úsrc_fromr@  rN   r?  r{   r0   Zsrc_outZfrorP  rÛ   r¦   r¹   rB  r¤   rV   rZ   rZ   r[   Úmorph_source_spacesB
  sJ    "



 ÿ       
ü
rG  c                 C   s&  t |dd�}tƒ }tƒ }d}tdƒD ]Â\}	}
t||	 |||
|ƒ}|||	 d  }t || |	 ¡}| ||	 d | ¡ || }t t |¡| |	 ¡r¨t | |	 |¡ 	¡ s´t
d| ƒ‚t |¡}t |¡}||7 }| |¡ |t|ƒ7 }q$t |¡}t t |¡t tdd„ | D ƒƒ¡¡�st‚||fS )	aW  Get the reordering indices for a morphed source space.

    Parameters
    ----------
    vertices : list
        The vertices for the left and right hemispheres.
    src_from : instance of SourceSpaces
        The original source space.
    subject_from : str
        The source subject.
    subject_to : str
        The destination subject.
    %(subjects_dir)s
    %(verbose)s

    Returns
    -------
    data_idx : ndarray, shape (n_vertices,)
        The array used to reshape the data.
    from_vertices : list
        The right and left hemisphere vertex numbers for the "from" subject.
    Trq  r   )rR  rS  r»   zDCould not map vertices, perhaps the wrong subject "%s" was provided?c                 s   s   | ]}t |ƒV  qd S r’  r^  )r`   r‰  rZ   rZ   r[   rb   Å
  s     z,_get_morph_src_reordering.<locals>.<genexpr>)r-   rQ   re   rE  r�   rá  rf   r  rì   rh   rk   rè   ri   ra  rµ  rÔ   rÐ   )rV  rF  r?  r@  r{   r0   Zfrom_verticesZ	data_idxsrC  rÙ   rP  rB  Zfull_mappingZused_verticesZremaining_mappingZimplicit_mappingZdata_idxrZ   rZ   r[   Ú_get_morph_src_reordering‹
  s:     ÿÿÿ



ÿ
rH  Úexactçú~j¼t“X?c              
   C   sˆ  ddl m}m}m}m}m}	 ddlm}
 |dkrDd|krDtd| ƒ‚t	t
| |ƒƒD �]Ê\}\}}t| ¡ ƒt| ¡ ƒ }}|||t||A ƒƒ dD ]<}|| ||  }}|dkrÂt|ƒt|ƒ }}||||ƒ q’d	D ](}||ksè||krÔ||| || |ƒ qÔd
D ]¬}||k�s||k�r||k�s2t|› d�ƒ‚||k�sJt|› d�ƒ‚t |d j¡}|d |d  j}t|ƒdk�rd|k�r|	t t || ¡| ¡d|› d�d� �qdD ]t}|| dk�rÚ||| dk|ƒ nL|dk�rú||| || |ƒ n,|dk�rdnd}||| || d||d� �q´dD ].}||k�sF||k�r.||| || |ƒ �q.|�r8dD ]R}|| dk�rŽ||| dk|ƒ n*|dk�rœdnd}||| || ||d� �qhdD ]v}|| dk�ræ||| dk|ƒ nN|t|| ƒt|| ƒk|ƒ t
|| || ƒD ]\}}|t||kƒ|ƒ �q�qÀ|dk�rÖdD ]}||| || |d� �qFdD ]}||| || k|ƒ �qhdD ]H}|| dk	�rŠ||| j|| jƒ |t|d |d  jƒdkƒ �qŠqRt	||fƒD ]4\}}||d t |d  ¡d d!||||f ƒ �qâ|t|d ƒt|d ƒƒ t |d  |d  k¡}||d"kd#| ƒ |d$k �rÊt |d |d ¡}t |d |d ¡}|
|d% | |d% | ƒ}|tj|d&d'�t t|ƒ¡|d(d� |d) dk	�rð||d) j|d) jƒ n||d) dkƒ |t |d) |d) k¡d"kƒ qRd*D ]^}|dk�rJ|| j| |j| ƒ n6|| jk�rl|||jkd+| ƒ n|||jkd,| ƒ �q$dS )-zkCompare two source spaces.

    Note: this function is also used by forward/tests/test_make_forward.py
    r   )Úassert_allcloseÚassert_array_equalÚassert_equalÚassert_Úassert_array_less©ÚcdistrI  Zapproxzunknown mode %s)r�   r  r�   r\   rs   rs   )rš   )r  z in s1 but not s0r  Znointerpr˜  z > 0.1%)Úerr_msg)r¡   r    r  ru   r  Nr¡   g-Cëâ6?)ZrtolÚatolrR  )r�   )rå   r  rç   g�íµ ÷Æ°>)rS  rR  )ræ   )r¼   r»   r  )r  )r  r  r»   r¼   z6src%s[%s]["vertno"] != np.where(src%s[%s]["inuse"])[0]g®Gáz®ï?z	%s < 0.99rº   r    r   rJ  zmismatched vertnor  rv  z"%s" missingz"%s" should not exist)Znumpy.testingrK  rL  rM  rN  rO  Úscipy.spatial.distancerQ  rk   re   rë   Úsetr²  r‚   r”   rÐ   r�   r×  rŽ   r
  ri   ÚsqrtrÔ   rh   ré   rÖ  Z	setdiff1drÔ  rË   rV   )Zsrc0Zsrc1Úmoderå   Zdist_tolrK  rL  rM  rN  rO  rQ  rm   Ús0Ús1ÚaÚbr�  rE  ZdiffsrS  Úp1Zp2rÙ   rn   Z	agreementZv0Zv1re  rZ   rZ   r[   Ú_compare_source_spacesÉ
  s´     þ

ÿ
 ÿ

$
þÿ
 ÿ 
r]  c                 C   s’   t | ƒt |ƒkst‚t| |ƒD ]n\}}|d  d¡ t |ƒ|d< t |¡|d< d|d |d < t g gt¡|d< t dg¡|d< t|dd	� q| S )
z(Reset the list of source space vertices.r¼   r   r�   r»   r   r  r  Fr¨   )ri   rÐ   rë   rÞ  r�   rÈ   r”   r  )r€   rV  rn   r‰  rZ   rZ   r[   Ú_set_source_space_vertices4  s    r^  c                 C   sÐ   |d kr| d n|}|r¸|   d¡d k	r¸t t|ƒdf¡}tt | d |¡ƒD ]R\}}| d | || kslt‚tj| d | d | d |  d d …f dd�||< qL|tjj	|dd	d
� }n| d |d d …f }|S )Nr»   rç   rÂ   r¡   ræ   r   rJ  r]   T)rK  Zkeepdims)
rg   r�   rÝ  ri   re   rí   rÐ   rÔ   rL  rM  )rn   Zuse_cpsrV  r¡   Zvpr  rZ   rZ   r[   Ú_get_src_nnC  s    " ÿr_  c                    s  ddl m} t| tƒst‚t|tfdƒ | d d tjkrLt	|dd�\‰ }n
t
ddƒ‰ t ‡ fdd	„| D ƒ¡}t||d
dd�}g }d}	|D ]n}
t||
ƒdkrÚ|	dkr´t|d ddƒ}	| t|	|d |
 d dd… ƒ¡ qŠ| |d |
 d dd… ¡ qŠt |¡}|||ƒ}|S )a  Compute distances between vertices and sensors.

    Parameters
    ----------
    src : instance of SourceSpaces
        The object with vertex positions for which to compute distances to
        sensors.
    %(info)s Must contain sensor positions to which distances shall
        be computed.
    %(picks_good_data)s
    %(trans_not_none)s
    %(verbose)s

    Returns
    -------
    depth : array of shape (n_vertices, n_channels)
        The Euclidean distances of source space vertices with respect to
        sensors.
    r   rP  rV   ru   F)Ú
allow_nonert   c                    s(   g | ] }t ˆ |d  |d  t¡ ƒ‘qS )r    r¼   )rB   rÎ   rÆ   r°   ©Z	src_transrZ   r[   r±   t  s   ÿz/compute_distance_to_sensors.<locals>.<listcomp>r
  rZ   )r¦  N)ÚmagZgradZ
dev_head_tr}   ZchsÚlocrÂ   )rT  rQ  r�   rO   rÐ   r9   r   r   rÉ   rE   rG   r�   Zvstackr   r   rI   rf   rB   rÈ   )r€   rV   Zpicksry   r0   rQ  rØ   Zsrc_posZ
sensor_posZdev_to_headÚchZdepthsrZ   ra  r[   Úcompute_distance_to_sensorsR  s4    
þ ÿÿ 

re  c                 C   sž   t | ƒ} g }| D ]ˆ}|d dkr"q|d }|d }|d }i }|| |d< t t|ƒdt¡}t t|ƒ¡||< || |d< |d dk ¡ sŽt‚| |¡ q|S )	a¿  Get the decimated surfaces from a source space.

    Parameters
    ----------
    src : instance of SourceSpaces | path-like
        The source space with decimated surfaces.

    Returns
    -------
    surfaces : list of dict
        The decimated surfaces present in the source space. Each dict
        which contains 'rr' and 'tris' keys for vertices positions and
        triangle indices.

    Notes
    -----
    .. versionadded:: 1.0
    r\   rN   r    r  r»   r]   r  r   )	r  r�   Úfullri   r”   rµ  rh   rÐ   rf   )r€   r|   rn   r    r  r»   rp   ZreindexrZ   rZ   r[   Úget_decimated_surfaces�  s     rg  )FN)FN)N)N)N)N)rp  rq   NTN)r†  )Nr�  NNNNr�  rx  NNTr�  FN)N)rv   )r   N)r
  )NN)N)Nrf  N)N)rq   NNN)NN)rI  TrJ  )TN)NNN)‹rœ   r   Ú	functoolsr   r~  Úos.pathÚpathrs  Únumpyr�   Zio.constantsr   Zio.meas_infor   r   Zio.treer	   Zio.tagr
   r   Zio.openr   Zio.writer   r   r   r   r   r   r   r   r   r   Zio.pickr   r   r   r   r   Úfixesr   rK   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r7  r(   r)   r*   r+   r,   Úutilsr-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r%  r@   Z
transformsrA   rB   rC   rD   rE   rF   rG   rH   rI   r’   rQ   rO   rð   rú   r  ró   rô   rQ  rX  rY  r[  r«   r\  rZ  ro  r…  rŽ  r©  r¤  r±  r¡  r¢  ró  rb  r£  rù  r  r  rÛ  r  r  r  r#  r€  r�  r"  r=  r“   rE  rG  rH  r]  r^  r_  re  rg  rZ   rZ   rZ   r[   Ú<module>	   s   08T,ý    \(%1 \.
d0      ÿþk
                  û  


-   þ
 o6
j
  ÿKÿq
< ÿ
,    ÿH   ÿ=  ÿ
k
  ÿ<