U
    f»{j1 ã                   @   s¬  d Z ddlZddlZddlmZmZ ddlZddlmZ ddl	Z	ddl
Z
ddlZddlZddlmZ ddlZddlmZmZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlm Z m!Z! ddl"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l0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z> ddl?m@Z@ ddlAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZL ddlMmNZN ej Odd¡ZPej Odd¡ZQej OeQd¡ZRej OeQd¡ZSej OeQdd¡ZTej OeQd¡ZUej OeRd¡ZVeEeVdd�ZWeEeVdd�ZXeEeVdd�ZYej OeRd ¡ZZej OeRd!¡Z[ej OeRd"¡eXeWfZ\ej OeRd#¡ej OeUd$¡ej OeUd%¡fZ]e^e_d&œd'd(„Z`d)d*„ Zad+d,„ Zbded.d/„ZceIdfd1d2„ƒZdeFdgd3d4„ƒZedhd6d7„Zfd8d9„ Zgd:Zhdid<d=„Zid>d?„ ZjdjdAdB„ZkdCdD„ ZldEdF„ ZmdkdGdH„ZndldIdJ„ZodmdKdL„ZpdndMdN„ZqdOdP„ ZrdQdR„ ZseFdodSddTœdUdV„ƒZtdpdWdX„ZueFdqdSddTœdYdZ„ƒZveFdrd[d\„ƒZwd]d^„ Zxd_d`„ Zydadb„ ZzeIG dcdd„ dde{ƒƒZ|dS )sz3Coregistration between different coordinate frames.é    N)ÚglobÚiglob)Úreduceé   )Úread_fiducialsÚwrite_fiducialsÚ	read_info)ÚFIFF)ÚInfo)Ú_get_data_as_dict_from_dig)Ú_read_mri_infoÚget_mni_fiducialsÚestimate_head_mri_t)Ú
read_labelÚLabel)Úadd_source_space_distancesÚread_source_spacesÚwrite_source_spaces)Úread_surfaceÚwrite_surfaceÚ_normalize_vectorsÚcomplete_surface_infoÚdecimate_surfaceÚ_DistanceQuery)Úread_bem_surfacesÚwrite_bem_surfaces)ÚrotationÚ
rotation3dÚscalingÚtranslationÚ	TransformÚ_read_fs_xfmÚ_write_fs_xfmÚinvert_transformÚcombine_transformsÚ_quat_to_eulerÚ_fit_matched_pointsÚapply_transÚrot_to_quatÚ_angle_between_quats)Úmake_dig_montage)Ú
get_configÚget_subjects_dirÚloggerÚpformatÚverboseÚwarnÚhas_nibabelÚfill_docÚ_validate_typeÚ_check_subjectÚ_check_option)Ú_fiducial_coordsz	{raw_dir}z{subject}-trans.fifz{subjects_dir}ú	{subject}ÚbemÚmriÚ
transformsÚsurfz{subject}-{name}.fifÚhead©Únamezhead-sparseÚ	fiducialsz{head}-fiducials.fifz{subject}-{spacing}-src.fifúouter_skin.surfz{subject}-head-dense.fifz
lh.segheadzlh.smseghead)r>   Úreturnc                 C   s4   |   ¡ } | dkrdS | dkr dS | dks,t‚dS dS )z3Map a fiducial name to its index in the DigMontage.Úlpar   Únasionr   Úrpaé   N)ÚlowerÚAssertionErrorr=   © rH   úH/var/www/html/bwave/python/venv/lib/python3.8/site-packages/mne/coreg.pyÚ_map_fid_name_to_idxD   s    rJ   c                 C   s&   t  | t t  | ¡tj ¡dB ¡ dS )zMake a file writable.é€   N)ÚosÚchmodÚstatÚS_IMODEÚlstatÚST_MODE)ÚfnamerH   rH   rI   Ú_make_writableQ   s    rS   c                 C   sN   t j d¡rdS tj| dd�D ]*\}}}|| D ]}ttj ||¡ƒ q0qdS )zRecursively set writable.ÚwinNF)Útopdown)ÚsysÚplatformÚ
startswithrL   ÚwalkrS   ÚpathÚjoin)rZ   ÚrootÚdirsÚfilesÚfrH   rH   rI   Ú_make_writable_recursiveV   s
    r`   Fc                 C   s<   |rt nt}|D ]&}|j|| d�}tj |¡r|  S qdS )zFind a high resolution head.©Úsubjects_dirÚsubjectN)Ú_high_res_head_fnamesÚ_head_fnamesÚformatrL   rZ   Úexists)rc   rb   Úhigh_resÚfnamesrR   rZ   rH   rH   rI   Ú_find_head_bem_   s
    rj   ç{®Gáz„?c           	      C   s�   t | tƒrt| ƒ} t |tƒr*t|ƒ\}}ntj}dd„ | d D ƒ}t|ƒdkrXtdƒ‚n| ¡ }t	| d ƒ}t	||ƒ}t
|||d�}t|||ƒS )aë  Create a head-MRI transform by aligning 3 fiducial points.

    Parameters
    ----------
    %(info_not_none)s
    fiducials : str | list of dict
        Fiducials in MRI coordinate space (either path to a ``*-fiducials.fif``
        file or list of fiducials as returned by :func:`read_fiducials`.

    Returns
    -------
    trans : Transform
        The device-MRI transform.

    .. note:: The :class:`mne.Info` object fiducials must be in the
              head coordinate space.
    c                 S   s   h | ]}|d  ’qS )Úcoord_framerH   )Ú.0ÚdrH   rH   rI   Ú	<setcomp>‚   s     z'coregister_fiducials.<locals>.<setcomp>Údigr   z8info contains fiducials from different coordinate frames)Útol)Ú
isinstanceÚstrr   r   r	   ZFIFFV_COORD_MRIÚlenÚ
ValueErrorÚpopr6   Úfit_matched_pointsr    )	Úinfor?   rq   Zcoord_frame_toZframes_fromZcoord_frame_fromZcoords_fromZ	coords_toÚtransrH   rH   rI   Úcoregister_fiducialsi   s    



rz   c                 C   sŽ  t |dd�}| dkr.td| ƒ} | dkr.tdƒ‚tj | dd¡}tj |¡sVtd| ƒ‚d	D ].}tj ||¡}tj |¡sZtd
||f ƒ‚qZtj |d¡}||kr®td| ƒ‚n |sÎtj |¡rÎtdd|f ƒ‚t	 
d¡ |rètj |¡süt ||¡ t|ƒ tj tj t¡ddd¡}tj |d¡}	tj |	¡�s<t |	¡ t	 
d¡ tj |	d¡}
t|	ƒ dD ](}tj |
| ¡�s`t || |	¡ �q`dS )až  Create an average brain subject for subjects without structural MRI.

    Create a copy of fsaverage from the Freesurfer directory in subjects_dir
    and add auxiliary files from the mne package.

    Parameters
    ----------
    fs_home : None | str
        The freesurfer home directory (only needed if FREESURFER_HOME is not
        specified as environment variable).
    update : bool
        In cases where a copy of the fsaverage brain already exists in the
        subjects_dir, this option allows to only copy files that don't already
        exist in the fsaverage directory.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable
        (os.environ['SUBJECTS_DIR']) as destination for the new subject.
    %(verbose)s

    Notes
    -----
    When no structural MRI is available for a subject, an average brain can be
    substituted. Freesurfer comes with such an average brain model, and MNE
    comes with some auxiliary files which make coregistration easier.
    :py:func:`create_default_subject` copies the relevant
    files from Freesurfer into the current subjects_dir, and also adds the
    auxiliary files provided by MNE.
    T©Zraise_errorNZFREESURFER_HOMEz~FREESURFER_HOME environment variable not found. Please specify the fs_home parameter in your call to create_default_subject().ZsubjectsÚ	fsaveragez:fsaverage not found at %r. Is fs_home specified correctly?)Úlabelr9   r;   zNFreesurfer fsaverage seems to be incomplete: No directory named %s found in %sz·Your subjects_dir points to the freesurfer subjects_dir (%r). The default subject can not be created in the freesurfer installation directory; please specify a different subjects_dir.z~Can not create fsaverage because %r already exists in subjects_dir %r. Delete or rename the existing fsaverage subject folder.z6Copying fsaverage subject from freesurfer directory...Údatazfsaverage-%s.fifr8   z-Copying auxiliary fsaverage files from mne...)r?   r<   zinner_skull-bemry   )r,   r+   ru   rL   rZ   r[   rg   ÚIOErrorÚisdirr-   rx   ÚshutilÚcopytreer`   ÚdirnameÚ__file__ÚmkdirÚcopy)Zfs_homeÚupdaterb   r/   Zfs_srcr>   rƒ   ÚdestZsource_fnameZdest_bemZ
dest_fnamerH   rH   rI   Úcreate_default_subjectŽ   s^    
ÿÿÿýÿþÿ
ÿ

r‰   é
   c              
   C   sâ  ddl m} t | ¡} |  d¡|d  \}}}|  d¡| \}}}t |||¡}	t |||¡}
t |||¡}tj| |	|
|fdd�\}}t |¡\}}}|	| }|
| }|| }tj	|||f |d  }t
|dd�}| | ¡\}}t |¡}t t dgtj|t|ƒd�g¡¡}t|ƒt|ƒd	 k�s(t‚tƒ }t|ƒD ]p\}}| ||| ||d	  …  }t|ƒ�sx| tjgd
 ¡ n,| |t |||tj ƒdd…df ¡ ¡ �q6t |t¡ dd
¡}|t || ¡jd	d�|d k  }|S )aÿ  Decimate the number of points using a voxel grid.

    Create a voxel grid with a specified resolution and retain at most one
    point per voxel. For each voxel, the point closest to its center is
    retained.

    Parameters
    ----------
    pts : array, shape (n_points, 3)
        The points making up the head shape.
    res : scalar
        The resolution of the voxel space (side length of each voxel).

    Returns
    -------
    pts : array, shape = (n_points, 3)
        The decimated points.
    r   )Úcdistg       @F)ZbinsZdensityZcKDTree)Úmethod)Z	minlengthr   é   Néÿÿÿÿ©Zaxis)Zscipy.spatial.distancer‹   ÚnpÚasarrayÚminÚmaxZarangeZhistogramddZnonzeroZc_r   ÚqueryZargsortZcumsumÚconcatenateZbincountrt   rG   ÚlistÚ	enumerateÚappendÚinfZargminÚnewaxisÚarrayÚfloatÚreshapeÚabs)ÚptsÚresr‹   ZxminZyminZzminZxmaxZymaxZzmaxZxaxZyaxZzaxÚHÚ_ZxbinsZybinsZzbinsÚxÚyÚzZmidsÚtreeZmid_idxZsort_idxZboundsÚoutÚmiÚmidZuse_ptsrH   rH   rI   Ú_decimate_pointsã   s>    

ÿ
$ÿ"rª   c                 C   sÜ   | \}}}d}g }|rB|dd… \}}}	|  t|||	ƒ¡ |d7 }|rx|||d … \}}}	| dt|||	ƒ¡ |d7 }|dkrœ|| }
|  t|
|
|
ƒ¡ n0|dkrÌ|||d … \}}}	|  t|||	ƒ¡ ttj|ƒ}|S )z?Convert transformation parameters into a transformation matrix.r   Nr�   r   )r˜   r   Úinsertr   r   r   r�   Údot)Ú
param_infoÚparamsZ	do_rotateZdo_translateZdo_scaleÚiry   r£   r¤   r¥   ÚsrH   rH   rI   Ú_trans_from_params*  s&    
r±   Try   c	                 C   s  t  | ¡} t  |¡}| j|jkr4td | j|j¡ƒ‚|dk	r’t  || j¡}|jdksh|j| jd dfkr€td|j| jd f ƒ‚|dd…t j	f }t
|ƒt
|ƒt|ƒf}	~~~|	dk�r<t�r<t  | t¡} t  |t¡}|dk	rêt  |t¡}t| ||t
|	d ƒƒ\}
}t|
dd… ƒ|
dd…< |	d �r6t  |
|gf¡n|
}
nt| ||	||ƒ}
|dk	�s`|d	k�rjt|	|
ƒ}|dk	�ræt  | t  t| ƒdf¡f¡} t  | |j¡dd…dd…f }t  t j|| d dd
�¡}t  ||k¡�rætd| ƒ‚|dk�rô|
S |d	k�r|S td| ƒ‚dS )a³  Find a transform between matched sets of points.

    This minimizes the squared distance between two matching sets of points.

    Uses :func:`scipy.optimize.leastsq` to find a transformation involving
    a combination of rotation, translation, and scaling (in that order).

    Parameters
    ----------
    src_pts : array, shape = (n, 3)
        Points to which the transform should be applied.
    tgt_pts : array, shape = (n, 3)
        Points to which src_pts should be fitted. Each point in tgt_pts should
        correspond to the point in src_pts with the same index.
    rotate : bool
        Allow rotation of the ``src_pts``.
    translate : bool
        Allow translation of the ``src_pts``.
    scale : bool
        Number of scaling parameters. With False, points are not scaled. With
        True, points are scaled by the same factor along all axes.
    tol : scalar | None
        The error tolerance. If the distance between any of the matched points
        exceeds this value in the solution, a RuntimeError is raised. With
        None, no error check is performed.
    x0 : None | tuple
        Initial values for the fit parameters.
    out : 'params' | 'trans'
        In what format to return the estimate: 'params' returns a tuple with
        the fit parameters; 'trans' returns a transformation matrix of shape
        (4, 4).

    Returns
    -------
    trans : array, shape (4, 4)
        Transformation that, if applied to src_pts, minimizes the squared
        distance to tgt_pts. Only returned if out=='trans'.
    params : array, shape (n_params, )
        A single tuple containing the rotation, translation, and scaling
        parameters in that order (as applicable).
    z5src_pts and tgt_pts must have same shape (got {}, {})Nr   r   z3weights (shape=%s) must be None or have shape (%s,))©TTr   ©TTr   rE   r�   ry   r�   z#Error exceeds tolerance. Error = %rr®   z;Invalid out parameter: %r. Needs to be 'params' or 'trans'.)r�   Z
atleast_2dÚshaperu   rf   r‘   ÚdtypeÚndimÚsizerš   ÚboolÚintÚ_ALLOW_ANALITICALrœ   r&   r%   r•   Ú_generic_fitr±   ÚhstackÚonesrt   r¬   ÚTÚsqrtÚsumÚanyÚRuntimeError)Úsrc_ptsÚtgt_ptsÚrotateÚ	translateÚscalerq   Úx0r§   Úweightsr­   r£   r°   ry   Zest_ptsÚerrrH   rH   rI   rw   I  sZ    ,

 ÿÿ   
ÿ 



ÿrw   c           	         sð   ddl m} |d r0t ˆ t tˆ ƒdf¡f¡‰ |dkrV‡ ‡‡fdd„}|d krÔd}n~|dkr|‡ ‡‡fd	d„}|d krÔd
}nX|dkr¢‡ ‡‡fdd„}|d krÔd}n2|dkrÈ‡ ‡‡fdd„}|d krÔd}ntd| ƒ‚|||dd�\}}}}}|S )Nr   )Úleastsqr   )TFr   c                    sD   | \}}}t |||ƒ}t ˆ |j¡}ˆ| }ˆd k	r<|ˆ9 }| ¡ S ©N)r   r�   r¬   r¾   Úravel)r£   ÚrxÚryÚrzry   Úestrn   ©rÃ   rÄ   rÉ   rH   rI   Úerror­  s    
z_generic_fit.<locals>.error)r   r   r   r²   c           
         sj   | \}}}}}}t  t|||ƒt|||ƒ¡}t  ˆ |j¡d d …d d…f }ˆ| }	ˆd k	rb|	ˆ9 }	|	 ¡ S ©Nr�   )r�   r¬   r   r   r¾   rÍ   )
r£   rÎ   rÏ   rÐ   ÚtxÚtyÚtzry   rÑ   rn   rÒ   rH   rI   rÓ   ¸  s    )r   r   r   r   r   r   r³   c                    sz   | \}}}}}}}t tjt|||ƒt|||ƒt|||ƒfƒ}t ˆ |j¡d d …d d…f }	ˆ|	 }
ˆd k	rr|
ˆ9 }
|
 ¡ S rÔ   ©r   r�   r¬   r   r   r   r¾   rÍ   )r£   rÎ   rÏ   rÐ   rÕ   rÖ   r×   r°   ry   rÑ   rn   rÒ   rH   rI   rÓ   Ã  s    

þ)r   r   r   r   r   r   r   )TTr�   c              	      s~   | \	}}}}}}}}}	t tjt|||ƒt|||ƒt|||	ƒfƒ}
t ˆ |
j¡d d …d d…f }ˆ| }ˆd k	rv|ˆ9 }| ¡ S rÔ   rØ   )r£   rÎ   rÏ   rÐ   rÕ   rÖ   r×   ÚsxZsyÚszry   rÑ   rn   rÒ   rH   rI   rÓ   Ð  s    

þ)	r   r   r   r   r   r   r   r   r   zYThe specified parameter combination is not implemented: rotate=%r, translate=%r, scale=%rT)Zfull_output)Zscipy.optimizerË   r�   r¼   r½   rt   ÚNotImplementedError)	rÃ   rÄ   r­   rÉ   rÈ   rË   rÓ   r£   r¢   rH   rÒ   rI   r»   §  s4    

ÿÿr»   r|   c                    sž   t |dd�}tj || ¡}tj |d¡‰ |dkr„g }t ˆ ¡D ]B\}}}tj |ˆ ¡}t |d¡D ]}	tj ||	¡}
| |
¡ qbq>n‡ fdd„t	|ƒD ƒ}|S )as  Find paths to label files in a subject's label directory.

    Parameters
    ----------
    subject : str
        Name of the mri subject.
    pattern : str | None
        Pattern for finding the labels relative to the label directory in the
        MRI subject directory (e.g., "aparc/*.label" will find all labels
        in the "subject/label/aparc" directory). With None, find all labels.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable
        (sys.environ['SUBJECTS_DIR'])

    Returns
    -------
    paths : list
        List of paths relative to the subject's label directory
    Tr{   r}   Nz*.labelc                    s   g | ]}t j |ˆ ¡‘qS rH   )rL   rZ   Úrelpath)rm   rZ   ©Zlbl_dirrH   rI   Ú
<listcomp>  s     z%_find_label_paths.<locals>.<listcomp>)
r,   rL   rZ   r[   rY   rÜ   ÚfnmatchÚfilterr˜   r   )rc   Úpatternrb   Zsubject_dirÚpathsÚdirpathr¢   Ú	filenamesZrel_dirÚfilenamerZ   rH   rÝ   rI   Ú_find_label_pathså  s    ræ   c                    s>  t |dd�}i }ttg|d< g |d< tj td¡}d}t dd¡d	krR|d
d… }|D ]H}dD ]>}|| }|j|| |d�}	tj |	¡r^|d  	t
||d�¡ q^qVtj td¡}d}|D ]6}|j|| |d�}	tj |	¡r¶|d  	t
||d�¡ q¶~~~	~g  |d< }
tj|| d�}	tj |	¡�r(|
 	d¡ t
t|| dd�}t
t|| dd� dd¡}t|ƒD ]&}	t ||	¡}| d¡}|
 	|¡ �qX~
~	~~|�r˜g |d< n,t| |ƒ|d< t|d ƒdk�rÄtd|  ƒ‚g |d< tj td¡}	tj td¡}d}|D ]N}dD ]B}|| }|j|| |d�}	tj |	¡�rø|d  	t
||d�¡ �qø�qð~~~	~g |d< tj td¡}|j|| d�}	tj |	¡�rˆ|d  	|¡ ~~	g  |d< }tj|| d�}t t |¡d ¡}| d! }|D ]>}| |¡�rèd"|t|ƒd
…  }tj t|¡}	| 	|	¡ �qÄtj|| d�‰ t t ˆ ¡d#¡}‡ fd$d%„|D ƒ|d&< |S )'a8  Find all files of an mri relevant for source transformation.

    Parameters
    ----------
    subject : str
        Name of the mri subject.
    skip_fiducials : bool
        Do not scale the MRI fiducials. If False, an IOError will be raised
        if no fiducials file can be found.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable
        (sys.environ['SUBJECTS_DIR'])

    Returns
    -------
    paths : dict
        Dictionary whose keys are relevant file type names (str), and whose
        values are lists of paths.
    Tr{   r]   r;   z{name})ZinflatedÚwhiteÚorigZorig_avgZinflated_avgZinflated_preZpialZpial_avgZsmoothwmZ	white_avgZsegheadZ	smsegheadZ_MNE_FEW_SURFACESÚ ÚtrueNé   )zlh.zrh.©rb   rc   r>   r=   )zinner_skull.surfzouter_skull.surfr@   r8   ra   r<   ú*-bemú(.+)ú\ú\\r   Úfidr   z­No fiducials file found for %s. The fiducials file should be named {subject}/bem/{subject}-fiducials.fif. In order to scale an MRI without fiducials set skip_fiducials=True.Ú	duplicate)ZcurvZspherez
sphere.regzsphere.reg.avgr:   ztalairach.xfmÚsrcz	*-src.fifú-z{subject}-%sz*.mgzc                    s   g | ]}t j ˆ |¡‘qS rH   )rL   rZ   r[   )rm   r_   ©Zmri_dirrH   rI   rÞ   |  s     z#_find_mri_paths.<locals>.<listcomp>r9   )r,   Úbem_dirnameÚsurf_dirnamerL   rZ   r[   Úgetenvrf   rg   r˜   r.   Úhead_bem_fnameÚ	bem_fnameÚreplacer   ÚreÚmatchÚgroupÚ_find_fiducials_filesrt   r   Úmri_transforms_dirnamerß   rà   ÚlistdirrX   Úmri_dirname)rc   Úskip_fiducialsrb   râ   Z
surf_fnameZ
surf_namesZ	surf_nameÚhemir>   rZ   r8   Zbem_patternZ
re_patternrý   Zsurf_dup_namesZsurf_dup_nameZtransform_fnameró   Zbem_dirri   ÚprefixrR   rH   rõ   rI   Ú_find_mri_paths
  s¬     ÿ ÿ
 ÿÿ ÿ

ü ÿr  c                 C   sŽ   g }t j tj|| d�¡r$| t¡ tt|| dd�}tt|| dd� dd¡}t	|ƒD ]4}t
 ||¡}| d¡ | d¡}| tt|d	�¡ qT|S )
zFind fiducial files.ra   Ú*)rb   rc   r<   rî   rï   rð   r   r7   )r<   )rL   rZ   rg   Ú	fid_fnamerf   r˜   r.   Úfid_fname_generalrû   r   rü   rý   rþ   )rc   rb   rñ   rá   ÚregexrZ   rý   r<   rH   rH   rI   rÿ   �  s*    ÿ
 ÿ ÿ ÿrÿ   c                 C   s(   t |dd�}tt| |ƒp$t| |dd�ƒS )ae  Check whether a directory in subjects_dir is an mri subject directory.

    Parameters
    ----------
    subject : str
        Name of the potential subject/directory.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable.

    Returns
    -------
    is_mri_subject : bool
        Whether ``subject`` is an mri subject.
    Tr{   ©rh   )r,   r¸   rj   ©rc   rb   rH   rH   rI   Ú_is_mri_subject”  s    ÿr  c                 C   s6   t |dd�}t| |ƒsdS tj || d¡}tj |¡S )an  Check whether a directory in subjects_dir is a scaled mri subject.

    Parameters
    ----------
    subject : str
        Name of the potential subject/directory.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable.

    Returns
    -------
    is_scaled_mri_subject : bool
        Whether ``subject`` is a scaled mri subject.
    Tr{   FúMRI scaling parameters.cfg)r,   r  rL   rZ   r[   rg   )rc   rb   rR   rH   rH   rI   Ú_is_scaled_mri_subject¨  s
    
r  c                 C   s0   t |dd�}tj|| dd�}t|ƒ}tt|ƒƒS )aG  Check whether an mri subject has a file matching the bem pattern.

    Parameters
    ----------
    subject : str
        Name of the subject.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable.

    Returns
    -------
    has_bem_file : bool
        Whether ``subject`` has a bem file.
    Tr{   rí   rì   )r,   rú   rf   r   r¸   rt   )rc   rb   rá   ri   rH   rH   rI   Ú_mri_subject_has_bem¾  s    ÿr  c                 C   sÌ   t |dd�}tj || d¡}tj |¡s8td| |f ƒ‚t d| ¡ t 	¡ }| 
|¡ | dd¡}|dkrz| dd	¡}n:|d
kr¨| dd	¡}t dd„ | ¡ D ƒ¡}ntd| ƒ‚| dd¡||dœ}|S )aN  Read information from the cfg file of a scaled MRI brain.

    Parameters
    ----------
    subject : str
        Name of the scaled MRI subject.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable.

    Returns
    -------
    cfg : dict
        Dictionary with entries from the MRI's cfg file.
    Tr{   r  z?%r does not seem to be a scaled mri subject: %r does not exist.zReading MRI cfg file %súMRI ScalingÚn_paramsr   rÇ   r�   c                 S   s   g | ]}t |ƒ‘qS rH   )rœ   ©rm   r°   rH   rH   rI   rÞ   ò  s     z read_mri_cfg.<locals>.<listcomp>z%Invalid n_params value in MRI cfg: %iÚsubject_from)r  r  rÇ   )r,   rL   rZ   r[   rg   r   r-   rx   ÚconfigparserÚRawConfigParserÚreadÚgetintÚgetfloatÚgetr�   r›   Úsplitru   )rc   rb   rR   Úconfigr  rÇ   Z	scale_strr§   rH   rH   rI   Úread_mri_cfgÔ  s*    ÿ

 ÿr  c              	   C   sÔ   t  |¡}t  |¡s|jdkr$d}nd}t ¡ }| d¡ | dd|¡ | dd|¡ | ddt|ƒ¡ |dkr„| ddt|ƒ¡ n| ddd	 	d
d„ |D ƒ¡¡ | ddd¡ t
| dƒ�}| |¡ W 5 Q R X dS )aD  Write the cfg file describing a scaled MRI subject.

    Parameters
    ----------
    fname : str
        Target file.
    subject_from : str
        Name of the source MRI subject.
    subject_to : str
        Name of the scaled MRI subject.
    scale : float | array_like, shape = (3,)
        The scaling parameter.
    rH   r   r�   r  r  Ú
subject_tor  rÇ   ú c                 S   s   g | ]}t |ƒ‘qS rH   )rs   r  rH   rH   rI   rÞ     s     z%_write_mri_config.<locals>.<listcomp>ÚversionÚ1ÚwN)r�   r‘   Zisscalarr´   r  r  Úadd_sectionÚsetrs   r[   ÚopenÚwrite)rR   r  r  rÇ   r  r  rñ   rH   rH   rI   Ú_write_mri_configû  s    

r'  c                 C   s¤   t |dd�}|dk|dkkr$tdƒ‚|dkrZt| |ƒ}|d }|d }|dksRt‚|d }t |¡}|jd	ks||jd
 dkrŒtd|jf ƒ‚t	|ƒ}||||d	kfS )a`  Assemble parameters for scaling.

    Returns
    -------
    subjects_dir : str
        Subjects directory.
    subject_from : str
        Name of the source subject.
    scale : array
        Scaling factor, either shape=() for uniform scaling or shape=(3,) for
        non-uniform scaling.
    uniform : bool
        Whether scaling is uniform.
    Tr{   NzJNeed to provide either both subject_from and scale parameters, or neither.r  r  ©r   r�   rÇ   r   r   zQInvalid shape for scale parameer. Need scalar or array of length 3. Got shape %s.)
r,   Ú	TypeErrorr  rG   r�   Ú
atleast_1dr¶   r´   ru   rt   )r  r  rÇ   rb   Úcfgr  rH   rH   rI   Ú_scale_params  s     

þr,  Úraise©Ú
on_defectsr/   c                C   s¶   t | |||ƒ\}}}}tj|||d�}tj|| |d�}	tj |	¡rNtd|	 ƒ‚t||d�}
|
D ]H}|d  |9  < |s^t|d ƒdksŠt	‚|d  |  < t
|d ƒ q^t|	|
ƒ dS )a  Scale a bem file.

    Parameters
    ----------
    subject_to : str
        Name of the scaled MRI subject (the destination mri subject).
    bem_name : str
        Name of the bem file. For example, to scale
        ``fsaverage-inner_skull-bem.fif``, the bem_name would be
        "inner_skull-bem".
    subject_from : None | str
        The subject from which to read the source space. If None, subject_from
        is read from subject_to's config file.
    scale : None | float | array, shape = (3,)
        Scaling factor. Has to be specified if subjects_from is specified,
        otherwise it is read from subject_to's config file.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable.
    %(on_defects)s

        .. versionadded:: 1.0
    %(verbose)s
    rì   zFile already exists: %s©r/  ÚrrÚnnr   N)r,  rú   rf   rL   rZ   rg   r   r   rt   rG   r   r   )r  Úbem_namer  rÇ   rb   r/  r/   Úuniformró   ÚdstZsurfsr;   rH   rH   rI   Ú	scale_bem@  s$    ÿ
ÿÿr6  c              	   C   sì   t | |||ƒ\}}}}t|||ƒ}|s*dS t|dd�}tj ||d¡}tj || d¡}	|D ]Œ}
tj |	|
¡}|s~tj |¡r~qZtj |¡}tj |¡s t |¡ tj ||
¡}t	|ƒ}|j
| }t|j||j|j|j| d�}| |¡ qZdS )a*  Scale labels to match a brain that was previously created by scaling.

    Parameters
    ----------
    subject_to : str
        Name of the scaled MRI subject (the destination brain).
    pattern : str | None
        Pattern for finding the labels relative to the label directory in the
        MRI subject directory (e.g., "lh.BA3a.label" will scale
        "fsaverage/label/lh.BA3a.label"; "aparc/\*.label" will find all labels
        in the "fsaverage/label/aparc" directory). With None, scale all labels.
    overwrite : bool
        Overwrite any label file that already exists for subject_to (otherwise
        existing labels are skipped).
    subject_from : None | str
        Name of the original MRI subject (the brain that was scaled to create
        subject_to). If None, the value is read from subject_to's cfg file.
    scale : None | float | array_like, shape = (3,)
        Scaling parameter. If None, the value is read from subject_to's cfg
        file.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable.
    NTr{   r}   )rc   )r,  ræ   r,   rL   rZ   r[   rg   rƒ   Úmakedirsr   Úposr   ZverticesÚvaluesr  ÚcommentÚsave)r  rá   Ú	overwriter  rÇ   rb   r¢   râ   Zsrc_rootZdst_rootrR   r5  rƒ   ró   Zl_oldr8  Zl_newrH   rH   rI   Úscale_labelso  s6       ÿ

 ÿr=  c             
   C   sÐ  t |dd�}t| ||ƒ}
t |¡}|jdkr^t |d |d ¡rxt |d |d ¡rx|d }n|jdkrxtd|jf ƒ‚tj||d	�}t	j
 |¡r°|s¦td
||f ƒ‚t |¡ t d¡ |
d D ]}|j||d	�}t	 |¡ qÂt d¡ t	j
 |d¡}t|| ||ƒ t d¡ |
d D ]J}|j| |d	�}t	j
 |¡}|j||d	�}t|ƒ\}}t||| |ƒ �qt d¡ |
d D ]}t||| |||dd� �qvt d¡ |
d D ]l}|j| |d	�}t	j
 |¡}t|dd�\}}|D ]}|d | |d< �qØ|j||d	�}t|||ddd� �q¦t d¡ t	 tj||d�¡ |
d D ]"}t	j
 |¡}t||| ||ƒ �q:t d¡ |
d D ]Z}| d¡�rpt	 tj||d�¡ |
d D ]$}t	j
 |¡}t |||| ||ƒ �qœ �qÌ�qpt d ¡ |
d! D ].}|j| |d	�}|j||d	�}t !||¡ �qÞt d"¡ |
d# D ]&}t	j
 |¡}t"||| ||dd� �q t d$¡ t	 t	j
 ||d%¡¡ |�r~t#|| ||d&� t d'¡ |�rÌt	j
 || d%d(¡}t	j
 ||d%¡}t$|ƒD ]}t %||¡ �q¸d)S )*aâ  Create a scaled copy of an MRI subject.

    Parameters
    ----------
    subject_from : str
        Name of the subject providing the MRI.
    subject_to : str
        New subject name for which to save the scaled MRI.
    scale : float | array_like, shape = (3,)
        The scaling factor (one or 3 parameters).
    overwrite : bool
        If an MRI already exists for subject_to, overwrite it.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable.
    skip_fiducials : bool
        Do not scale the MRI fiducials. If False (default), an IOError will be
        raised if no fiducials file can be found.
    labels : bool
        Also scale all labels (default True).
    annot : bool
        Copy ``*.annot`` files to the new location (default False).
    %(on_defects)s

        .. versionadded:: 1.0
    %(verbose)s

    See Also
    --------
    scale_bem : Add a scaled BEM to a scaled MRI.
    scale_labels : Add labels to a scaled MRI.
    scale_source_space : Add a source space to a scaled MRI.

    Notes
    -----
    This function will automatically call :func:`scale_bem`,
    :func:`scale_labels`, and :func:`scale_source_space` based on expected
    filename patterns in the subject directory.
    Tr{   )r�   r   r   rE   )r   z*scale must have shape (3,) or (1,), got %sr  z+Subject directory for %s already exists: %rz create empty directory structurer]   zsave MRI scaling parametersr  zsurf files [in mm]r;   zBEM files [in m]r8   Fr.  zfiducials [in m]rñ   )r/   Úr)r<  r/   zMRIs [nibabel]ra   r9   Z
TransformszT1.mgzr:   zduplicate filesrò   zsource spacesró   zlabels [in m]r}   )r  rÇ   rb   zcopy *.annot filesz*.annotN)&r,   r  r�   r*  r´   Úiscloseru   Úsubject_dirnamerf   rL   rZ   rg   r   r�   Úrmtreer-   Údebugr7  r[   r'  Úrealpathr   r   r6  r   r   r…   r  ÚbasenameÚ
_scale_mriÚendswithr   Ú
_scale_xfmÚcopyfileÚscale_source_spacer=  r   r†   )r  r  rÇ   r<  rb   r  ÚlabelsZannotr/  r/   râ   rˆ   rƒ   Zdir_rR   ró   rŸ   Ztrir3  ZcframeÚptÚmri_nameZxfm_nameÚsrc_nameÚsrc_patternZdst_dirZsrc_filerH   rH   rI   Ú	scale_mri¦  s¾    *

(

ÿÿÿ




 ÿ



ÿ

ÿ  ÿ



 ÿ

ÿ
ÿrO  c                 C   sÔ  t | |||ƒ\}}}}| ¡ r(|}t}	n6t d|¡}
|
rLd |
 ¡ ¡}t}	nd}tj t	|¡}	|	j
|||d�}|	j
|| |d�}t|ƒ}t d||| ¡ t d|¡ d}|D � ]ü}| |d< |d	  |9  < d
D ]6}||krÌ|| d dd…  |dd…tjf 9  < qÌ|�rN|d dk	�r¨|d  |d 9  < |d | |d< |d | |d< qª|d  |  < t|d ƒ |d dk	�r”d}tt |d d ¡ƒ}qª|d dk	rªd}d}qª|�rÆt d¡ t|||ƒ t||ƒ dS )a¬  Scale a source space for an mri created with scale_mri().

    Parameters
    ----------
    subject_to : str
        Name of the scaled MRI subject (the destination mri subject).
    src_name : str
        Source space name. Can be a spacing parameter (e.g., ``'7'``,
        ``'ico4'``, ``'oct6'``) or a file name of a source space file relative
        to the bem directory; if the file name contains the subject name, it
        should be indicated as "{subject}" in ``src_name`` (e.g.,
        ``"{subject}-my_source_space-src.fif"``).
    subject_from : None | str
        The subject from which to read the source space. If None, subject_from
        is read from subject_to's config file.
    scale : None | float | array, shape = (3,)
        Scaling factor. Has to be specified if subjects_from is specified,
        otherwise it is read from subject_to's config file.
    subjects_dir : None | str
        Override the SUBJECTS_DIR environment variable.
    n_jobs : int
        Number of jobs to run in parallel if recomputing distances (only
        applies if scale is an array of length 3, and will not use more cores
        than there are source spaces).
    %(verbose)s

    Notes
    -----
    When scaling volume source spaces, the source (vertex) locations are
    scaled, but the reference to the MRI volume is left unchanged. Transforms
    are updated so that source estimates can be plotted on the original MRI
    volume.
    z(oct|ico|vol)-?(\d+)$rô   N)rb   rc   Úspacingz"scaling source space %s:  %s -> %szScale factor: %sFZsubject_his_idr1  )Z	vox_mri_tZ	src_mri_try   r�   Údistr   Znearest_distÚ
dist_limitr2  TÚnearestz.Recomputing distances, this might take a while)r,  ÚisdigitÚ	src_fnamerü   rý   r[   ÚgroupsrL   rZ   rö   rf   r   r-   rx   r�   rš   r   rœ   rž   r   r   )r  rM  r  rÇ   rb   Zn_jobsr/   r4  rP  rN  rý   ró   r5  ZsssZadd_distÚssÚkeyrR  rH   rH   rI   rI  1  s\    %ÿ
ÿÿ
ÿ
,
rI  c                 C   s´   t | |||ƒ\}}}}tƒ s(tdƒ dS ddl}t tj||d�|¡}t tj|| d�|¡}| |¡}	t	 
|	j ¡ ¡}
|
dddg  |9  < |	j |
¡ |	j ¡ |	_| |	|¡ dS )z#Scale an MRI by setting its affine.z3Skipping MRI scaling for %s, please install nibabelNr   ra   rE   r   )r,  r1   r0   ÚnibabelÚopr[   r  rf   Úloadr�   r›   ÚheaderZ	get_zoomsZ	set_zoomsZ
get_affineZ_affiner;  )r  Z	mri_fnamer  rÇ   rb   r¢   rY  Ú
fname_fromÚfname_toZimgZzoomsrH   rH   rI   rE  ‘  s8       ÿ ÿÿ ÿÿ
rE  c                 C   sl  t | |||ƒ\}}}}tƒ s dS tj tj||d�|¡}t tj|| d�|¡}t |¡s`t	|ƒ‚t 
t |¡¡s~t	t |¡ƒ‚t |¡}t|ƒdkr t |d¡n|}tddt|Ž ƒ}	t|ƒ\}
}|dksÐt	|ƒ‚t|dd�\}}}}}td	d
|
ƒ}~
t tj|| d�t |¡¡}t|dd�\}}}}}t|ƒ}~~ttt|t|	ƒd	dƒ|d	d	ƒ|d	d
ƒ}t||d |ƒ dS )zScale a transform.Nra   r   r�   r9   zMNI Transform FileÚmm)ZunitsZrasZmni_talry   )r,  r1   rL   rZ   r[   r   rf   rZ  ÚisfilerG   r€   rƒ   r�   r*  rt   Ztiler    r   r!   r   r  rD  r#   r$   r"   )r  Z	xfm_fnamerL  r  rÇ   rb   r¢   r]  r^  ÚSZxfmÚkindZ	F_mri_rasZ	F_ras_mniZ	T_mri_rasZ	T_ras_mriZ	T_ras_mnirH   rH   rI   rG  ©  sv       ÿ ÿþ ÿþ
 ÿÿ   ÿ  ý  ûÿrG  c                C   sŒ   t ƒ }| d k	rˆt | ¡rˆ|  d¡r6t| |dd�d }nRz0t| dd�d }|d  d	9  < t|dd
� W n  tk
r†   td|  ƒ‚Y nX |S )Nz.fifFr.  r   T)Zreturn_dictrE   r1  çü©ñÒMbP?)r†   z9Error loading surface from %s (see Terminal for details).)	ÚdictrZ  rg   rF  r   r   r   Ú	Exceptionru   )rå   r/  r8   rH   rH   rI   Ú_read_surfaceö  s*    
  ÿþÿÿ
rf  c                
   @   sÒ  e Zd ZdZdbddœdd„Zdd	„ Zd
d„ Zdd„ Zdd„ Zdcdd„Z	dd„ Z
dd„ Zdd„ Zdd„ Zdd„ Zdd„ Zedd „ ƒZed!d"„ ƒZed#d$„ ƒZed%d&„ ƒZed'd(„ ƒZed)d*„ ƒZed+d,„ ƒZed-d.„ ƒZed/d0„ ƒZed1d2„ ƒZed3d4„ ƒZed5d6„ ƒZed7d8„ ƒZd9d:„ Zed;d<„ ƒZed=d>„ ƒZ ed?d@„ ƒZ!dAdB„ Z"edCdD„ ƒZ#e$dddGdH„ƒZ%dIdJ„ Z&dKdL„ Z'e$dedNdO„ƒZ(edPdQ„ ƒZ)dRdS„ Z*dTdU„ Z+edVdW„ ƒZ,dXdY„ Z-dZd[„ Z.d\d]„ Z/d^d_„ Z0d`da„ Z1dS )fÚCoregistrationa.  Class for MRI<->head coregistration.

    Parameters
    ----------
    info : instance of Info | None
        The measurement info.
    %(subject)s
    %(subjects_dir)s
    %(fiducials)s
    %(on_defects)s

        .. versionadded:: 1.0

    Attributes
    ----------
    fiducials : instance of DigMontage
        A montage containing the MRI fiducials.
    trans : instance of Transform
        MRI<->Head coordinate transformation.

    See Also
    --------
    mne.scale_mri

    Notes
    -----
    Internal computation quantities parameters are in the following units:

    - rotation are in radians
    - translation are in m
    - scale are in scale proportion

    If using a scale mode, the :func:`~mne.scale_mri` should be used
    to create a surrogate MRI subject with the proper scale factors.
    NÚautor-  r0  c                C   s  t |td fdƒ || _t||ƒ| _t|dd�| _d | _|| _d | _	t
 dddddddddg	¡| _| jd d… | _| jdd… | _| jdd… | _d	| _d
| _d
| _d
| _d| _| jd | _d| _d| _d| _d| _d| _d| _d | _|  ¡  |  ¡  d | _|   |¡ |  !¡  d S )Nrx   Tr{   ç        ç      ð?r�   é   é	   é   gš™™™™™É?)rS  Úmatchedr   ç      $@)"r3   r
   Ú_infor4   Ú_subjectr,   Ú_subjects_dirÚ_scale_modeÚ_on_defectsZ
_rot_transr�   r›   Ú_default_parametersÚ	_rotationÚ_translationÚ_scaleZ_icp_iterationsÚ
_icp_angleÚ_icp_distanceÚ
_icp_scaleÚ_icp_fid_matchesÚ_icp_fid_matchÚ_lpa_weightÚ_nasion_weightÚ_rpa_weightÚ_hsp_weightÚ_eeg_weightÚ_hpi_weightÚ_extra_points_filterÚ_setup_digsÚ
_setup_bemÚ_fid_filenameÚ_setup_fiducialsÚreset)Úselfrx   rc   rb   r?   r/  rH   rH   rI   Ú__init__/  s<    ÿ
zCoregistration.__init__c              	   C   sÔ   | j d krFtt d¡t d¡t d¡t d¡t d¡t d¡d�| _nŠt| j d dd�| _tdddd	d
gdddddgƒD ]V\}}| j| d kr¬t d¡| j|< t| |dƒ qx|dkrxt | j| gt	¡| j|< qxd S )Nr(  )ÚhpiÚdig_ch_pos_locationÚhsprD   rC   rB   rp   F)rp   Zexclude_ref_channelrC   rB   rD   rŽ  rŒ  r  r~  r€  r�  rƒ  )r   r�   r   )rD   rC   rB   )
rp  rd  r�   ZzerosÚ	_dig_dictr   ÚzipÚsetattrr›   rœ   )rŠ  ÚkZw_atrrH   rH   rI   r…  T  s2    
ú
	þ  ÿÿzCoregistration._setup_digsc                 C   sü   t | j| jdd�}t | j| jdd�}|d krD|d krDtd| j› �ƒ‚|d k	rnt|| jd�| _t d|› �¡ n t|| jd�| _t d|› �¡ |d krèt	dt
| jd	 ƒ|f ƒ t| jd	 | jd
 dd�\}}tt||d�ddd�| _nt|| jd�| _d S )NTr  Fz-No standard head model was found for subject r0  z$Using high resolution head model in z#Using low resolution head model in zONo low-resolution head found, decimating high resolution mesh (%d vertices): %sr1  Útrisi   )Zn_triangles)r1  r“  )r†   r/   )rj   rq  rr  rÂ   rf  rt  Ú_bem_high_resr-   rx   r0   rt   r   r   rd  Ú_bem_low_res)rŠ  Zhigh_res_pathZlow_res_pathr1  r“  rH   rH   rI   r†  o  sL    
ÿ
ÿ ÿ ÿÿÿ
þ

  ÿ
 ÿzCoregistration._setup_bemc                 C   s  t |tttfƒ d }|dkrzt| j| jƒ}t|ƒdkrv|d j| j| jd�}t	 
d|› d�¡ t|ƒ\}}d}|| _nd}|dkržt	 
d¡ d	}t| j| jƒ}|d krªdn|}t|tƒrÂt|ƒ}n.t|tƒsÐt‚tj|d
 |d |d gtd�}|| _|| _|  ¡  d S )Nrh  r   ra   zUsing fiducials from: Ú.TZ	estimatedz$Estimating fiducials from fsaverage.FrB   rC   rD   )rµ   )r3   rs   rd  r–   rÿ   rq  rr  rt   rf   r-   rx   r   r‡  r   rr   r6   rG   r�   r›   rœ   Ú_fid_pointsZ_fid_accurateÚ_reset_fiducials)rŠ  ZfidsZfid_accurateZ	fid_filesZfid_filenamer¢   Z
fid_coordsrH   rH   rI   rˆ  “  s<    ÿ ÿ


ÿzCoregistration._setup_fiducialsc                 C   s,   t | jd | jd | jd dd�}|| _d S )Nr   r   rE   r9   )rB   rC   rD   rl   )r*   r—  r?   )rŠ  Zdig_montagerH   rH   rI   r˜  ¸  s    üzCoregistration._reset_fiducialsFc                 C   s0  |r|d kr| j }d}|d k	r4d}| j ¡ | _|| _d}|sF|d k	�r|d krT| j }d}| j  ¡ | _|| _ t| jŽ j| _t 	| jd d…d d…f |¡ | jd d…df< t
| j| jd ƒ| _t
| j| jd ƒ| _t
| j| jƒ| _t
| j| jd ƒ| _t| jŽ | _t |¡| jd d…df< |�s&|d k	�rŠ|d k�r6| j}| j ¡ | _|| _t d¡| _| jd d …d d…f  |9  < t
| j| jƒ| _|  ¡  |�r,| j | j¡d | _| j | j¡d | _| j | j¡d | _| j t
| j| jd	 ƒ¡d | _| j t
| j| jd
 ƒ¡d | _ | j t
| j| jd ƒ¡d | _!d S )NFTr�   rŒ  r�  rŽ  rë   r   rD   rC   rB   )"rw  rv  r†   Ú_last_rotationÚ_last_translationr   r¾   Ú_head_mri_tr�   r¬   r'   r�  Ú_transformed_dig_hpiÚ_transformed_dig_eegÚ_filtered_extra_pointsÚ_transformed_dig_extraÚ_transformed_orig_dig_extraZ_mri_head_tr›   rx  Ú_last_scaleÚeyeÚ
_mri_transÚ_processed_high_res_mri_pointsÚ _transformed_high_res_mri_pointsÚ_update_nearest_calcÚ_nearest_calcr”   Ú._nearest_transformed_high_res_mri_idx_orig_hspÚ)_nearest_transformed_high_res_mri_idx_hpiÚ)_nearest_transformed_high_res_mri_idx_eegZ)_nearest_transformed_high_res_mri_idx_rpaZ,_nearest_transformed_high_res_mri_idx_nasionZ)_nearest_transformed_high_res_mri_idx_lpa)rŠ  ÚrotÚtraÚscaÚforce_updateZrot_changedZtra_changedrH   rH   rI   Ú_update_paramsÁ  sŠ    ÿÿ ÿÿÿÿÿ
ÿÿÿÿÿÿÿÿÿÿÿÿÿÿzCoregistration._update_paramsc                 C   s
   || _ | S )aß  Select how to fit the scale parameters.

        Parameters
        ----------
        scale_mode : None | str
            The scale mode can be 'uniform', '3-axis' or disabled.
            Defaults to None.

            * 'uniform': 1 scale factor is recovered.
            * '3-axis': 3 scale factors are recovered.
            * None: do not scale the MRI.

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        ©rs  )rŠ  Z
scale_moderH   rH   rI   Úset_scale_modeý  s    zCoregistration.set_scale_modec                 C   s   || _ | jdd� | S )a+  Compensate for hair on the digitizer head shape.

        Parameters
        ----------
        value : float
            Move the back of the MRI head outwards by ``value`` (mm).

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        T©r®  )Ú
_grow_hairr¯  )rŠ  ÚvaluerH   rH   rI   Úset_grow_hair  s    zCoregistration.set_grow_hairc                 C   s   | j t |¡d� | S )a  Set the rotation parameter.

        Parameters
        ----------
        rot : array, shape (3,)
            The rotation parameter (in radians).

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        )r«  ©r¯  r�   r›   )rŠ  r«  rH   rH   rI   Úset_rotation#  s    zCoregistration.set_rotationc                 C   s   | j t |¡d� | S )a  Set the translation parameter.

        Parameters
        ----------
        tra : array, shape (3,)
            The translation parameter (in m.).

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        )r¬  r¶  )rŠ  r¬  rH   rH   rI   Úset_translation3  s    zCoregistration.set_translationc                 C   s   | j t |¡d� | S )zøSet the scale parameter.

        Parameters
        ----------
        sca : array, shape (3,)
            The scale parameter.

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        )r­  r¶  )rŠ  r­  rH   rH   rI   Ú	set_scaleC  s    zCoregistration.set_scalec                 C   s   t | j| j ƒ| _d S rÌ   )r   r¤  rx  r§  ©rŠ  rH   rH   rI   r¦  S  s    
ÿz#Coregistration._update_nearest_calcc                 C   s(   | j d kr| jd S | jd | j  S d S )NrŽ  )r„  r�  rº  rH   rH   rI   rž  W  s    

z%Coregistration._filtered_extra_pointsc                 C   s   t  | j| j| jf¡S rÌ   )r�   r•   rv  rw  rx  rº  rH   rH   rI   Ú_parameters^  s    zCoregistration._parametersc                 C   s   t  | j| j| jf¡S rÌ   )r�   r•   r™  rš  r¡  rº  rH   rH   rI   Ú_last_parametersb  s     ÿzCoregistration._last_parametersc              	   C   s|   t j | j| j ¡d }t  ttt| j	Ž d d…d d…f ƒtt| j
Ž d d…d d…f ƒƒ¡}d| j| j  | j }|||fS )Nç     @�@r�   éd   )r�   ÚlinalgÚnormrš  rw  Zrad2degr)   r(   r   rv  r™  rx  r¡  )rŠ  ÚmoveÚangleZpercsrH   rH   rI   Ú_changesg  s    þzCoregistration._changesc                 C   s   | j  t| j| jƒ¡d S )Nr   )r§  r”   r'   r›  rž  rº  rH   rH   rI   Ú)_nearest_transformed_high_res_mri_idx_hspp  s
    ÿÿz8Coregistration._nearest_transformed_high_res_mri_idx_hspc                 C   s   | j ot| jƒdkS ©Nr   ©Ú_has_mri_datart   rÄ  rº  rH   rH   rI   Ú_has_hsp_datau  s    ÿzCoregistration._has_hsp_datac                 C   s   | j ot| jƒdkS rÅ  )rÇ  rt   r©  rº  rH   rH   rI   Ú_has_hpi_dataz  s    ÿzCoregistration._has_hpi_datac                 C   s   | j ot| jƒdkS rÅ  )rÇ  rt   rª  rº  rH   rH   rI   Ú_has_eeg_data  s    ÿzCoregistration._has_eeg_datac                 C   sH   | j jtdƒ }|d tjks"t‚t |d ¡}t | jd ¡}|oF|S )NrB   Úidentr>  )	r?   rp   rJ   r	   ZFIFFV_POINT_LPArG   r�   rÁ   r�  ©rŠ  Z	mri_pointZhas_mri_dataZhas_head_datarH   rH   rI   Ú_has_lpa_data„  s
    zCoregistration._has_lpa_datac                 C   sH   | j jtdƒ }|d tjks"t‚t |d ¡}t | jd ¡}|oF|S )NrC   rË  r>  )	r?   rp   rJ   r	   ZFIFFV_POINT_NASIONrG   r�   rÁ   r�  rÌ  rH   rH   rI   Ú_has_nasion_dataŒ  s
    zCoregistration._has_nasion_datac                 C   sH   | j jtdƒ }|d tjks"t‚t |d ¡}t | jd ¡}|oF|S )NrD   rË  r>  )	r?   rp   rJ   r	   ZFIFFV_POINT_RPArG   r�   rÁ   r�  rÌ  rH   rH   rI   Ú_has_rpa_data”  s
    zCoregistration._has_rpa_datac                 C   s
   |   d¡S )NÚhigh©Ú_get_processed_mri_pointsrº  rH   rH   rI   r¤  œ  s    z-Coregistration._processed_high_res_mri_pointsc                 C   s
   |   d¡S )NÚlowrÑ  rº  rH   rH   rI   Ú_processed_low_res_mri_points   s    z,Coregistration._processed_low_res_mri_pointsc                 C   sŒ   |dkr| j n| j}|d  ¡ }| jrˆt|d ƒs6t‚d| j t | j¡ }|d d …df |d d …df k}||  |d | | 7  < |S )NrÓ  r1  r2  rc  rE   r   )	r•  r”  r†   r³  rt   rG   r�   r›   rx  )rŠ  r    r8   ZpointsZscaled_hair_distZhairrH   rH   rI   rÒ  ¤  s    
ÿ z(Coregistration._get_processed_mri_pointsc                 C   s   t | jƒdkS rÅ  )rt   r¥  rº  rH   rH   rI   rÇ  ¯  s    zCoregistration._has_mri_datac                 C   s   | j ot| jƒdkS rÅ  rÆ  rº  rH   rH   rI   Ú_has_dig_data³  s    ÿzCoregistration._has_dig_datac                 C   s&   | j | j }| j}tjj|| dd�S )NrŽ   r�   )r¥  r¨  r   r�   r¿  rÀ  ©rŠ  Ú
mri_pointsÚ
hsp_pointsrH   rH   rI   Ú_orig_hsp_point_distance¸  s
    ÿz'Coregistration._orig_hsp_point_distancec                 C   s.   |   ¡ }t |› dt |d ¡d›d�¡ d S )Nz median distance: iè  z6.2fú mm)Úcompute_dig_mri_distancesr-   rx   r�   Zmedian)rŠ  r  Zerrs_nearestrH   rH   rI   Ú_log_dig_mri_distance¿  s    z$Coregistration._log_dig_mri_distancec                 C   s
   | j  ¡ S )zŠGet the current scale factor.

        Returns
        -------
        scale : ndarray, shape (3,)
            The scale factors.
        )rx  r†   rº  rH   rH   rI   rÇ   Ä  s    	zCoregistration.scalerj  ro  c                 C   sv  t  d¡ |  d¡ | j}|dkr0t  d¡ d}|| _|| _|| _t | j	d | j	d | j	d f¡}t | j
jd	 d
 | j
jd d
 | j
jd d
 f¡}|||g}|d	kr´|| j9 }| j}	|	dd| … }	t|||	d||d�}
|d	k�r| j|
dd… |
dd… d� n`|
jdk�st‚t |
|
d gd g¡}
|
jdk�s@t‚| j|
dd… |
dd… |
dd… d� |  d¡ | S )a÷  Find rotation and translation to fit all 3 fiducials.

        Parameters
        ----------
        lpa_weight : float
            Relative weight for LPA. The default value is 1.
        nasion_weight : float
            Relative weight for nasion. The default value is 10.
        rpa_weight : float
            Relative weight for RPA. The default value is 1.
        %(verbose)s

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        zAligning using fiducialsZStartr�   z5Enforcing 1 scaling parameter for fit with fiducials.r   rB   rC   rD   r   r>  rE   Nrk  r®   )rÈ   r§   rÇ   rÉ   ©r«  r¬  é   rŽ   rl  ©r«  r¬  r­  zEnd  )r-   rx   rÜ  Ú_n_scale_paramsr~  r  r€  r�   Zvstackr�  r?   rp   rx  r»  rw   r¯  r·   rG   r•   )rŠ  Ú
lpa_weightÚnasion_weightÚ
rpa_weightr/   Ún_scale_paramsÚhead_ptsÚmri_ptsrÉ   rÈ   rÑ   rH   rH   rI   Úfit_fiducialsÏ  sH    


þþÿ


 ÿ
 (
zCoregistration.fit_fiducialsc              
   C   sî  t ƒ }t ƒ }t ƒ }| jr\| jdkr\| | j¡ | | j| j ¡ | t t	|d ƒ| j¡¡ dD ]¬}t
| d|› d�ƒr`| | j| ¡ | jdkr¾t|d�}| jj| d  d	d¡}| |¡ n*| jd
ksÌt‚| | jt
| d|f ƒ ¡ | t t	|d ƒt
| d| ƒ¡¡ q`| j�r`| jdk�r`| | jd ¡ | | j| j ¡ | t t	|d ƒ| j¡¡ | j�r²| jdk�r²| | jd ¡ | | j| j ¡ | t t	|d ƒ| j¡¡ t |¡}t |¡}t |¡}|dk�rä|| j9 }|||fS )Nr   rŽ   ©rB   rC   rD   Z_has_Ú_datarn  r=   r>  r   rS  z(_nearest_transformed_high_res_mri_idx_%sz
_%s_weightr�  rŒ  )r–   rÕ  r�  r˜   rž  r¤  rÄ  r�   Úfullrt   Úgetattrr�  r}  rJ   r?   rp   r�   rG   rÊ  r‚  rª  rÉ  rƒ  r©  r•   rx  )rŠ  rä  rå  ræ  rÉ   rX  ÚidxÚprH   rH   rI   Ú
_setup_icp	  s\    ÿ

ÿþÿÿÿÿ




zCoregistration._setup_icpc                 C   s   t d|| jƒ || _| S )aÄ  Set the strategy for fitting anatomical landmark (fiducial) points.

        Parameters
        ----------
        match : 'nearest' | 'matched'
            Alignment strategy; ``'nearest'`` aligns anatomical landmarks to
            any point on the head surface; ``'matched'`` aligns to the fiducial
            points in the MRI.

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        rý   )r5   r|  r}  )rŠ  rý   rH   rH   rI   Úset_fid_match3  s    zCoregistration.set_fid_matchrm  c
              	   C   sž  t  d¡ |  d¡ | j}
|| _|| _|| _|| _|| _|| _| j	}|dddddg|
 … }t
|ƒD �](}|  |
¡\}}}t|||
|d|d�}|
d	kr¶| j|dd
… |d
d… d� nx|
dk�rt t|ƒ|d gd  ¡}| j|dd
… |d
d… |dd… d� n(| j|dd
… |d
d… |dd… d� | j\}}}|  d|d d›d�¡ |dk	�rf|||ƒ || jkrd|| jkrdt|| jkƒrd �q�qd|  d¡ | S )a$  Find MRI scaling, translation, and rotation to match HSP.

        Parameters
        ----------
        n_iterations : int
            Maximum number of iterations.
        lpa_weight : float
            Relative weight for LPA. The default value is 1.
        nasion_weight : float
            Relative weight for nasion. The default value is 10.
        rpa_weight : float
            Relative weight for RPA. The default value is 1.
        hsp_weight : float
            Relative weight for HSP. The default value is 1.
        eeg_weight : float
            Relative weight for EEG. The default value is 1.
        hpi_weight : float
            Relative weight for HPI. The default value is 1.
        callback : callable | None
            A function to call on each iteration. Useful for status message
            updates. It will be passed the keyword arguments ``iteration``
            and ``n_iterations``.
        %(verbose)s

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        zAligning using ICPz	Start    Nrk  rÞ  rl  r®   )rÇ   rÈ   r§   rÉ   r   r�   rÝ  r   rŽ   rE   rß  z  ICP Z2dr  z	End      )r-   rx   rÜ  rà  r~  r  r€  r�  r‚  r»  Úrangerî  rw   r¯  r�   r›   r–   rÃ  ry  rz  Úallr{  )rŠ  Zn_iterationsrá  râ  rã  Z
hsp_weightZ
eeg_weightZ
hpi_weightÚcallbackr/   rä  rÑ   Ú	iterationrå  ræ  rÉ   rÂ  rÁ  rÇ   rH   rH   rI   Úfit_icpF  sD    !

  ÿ 
*(

ÿ
zCoregistration.fit_icpc                 C   s(   | j d krd}n| j dkr d}nd}|S )Nr   r4  r   r�   r°  )rŠ  rä  rH   rH   rI   rà  ‹  s    

zCoregistration._n_scale_paramsc                 C   sN   t |ƒ}|dkrdS | j|k}t | ¡}t d||¡ || _| jdd� | S )a�  Exclude head shape points that are far away from the MRI head.

        Parameters
        ----------
        distance : float
            Exclude all points that are further away from the MRI head than
            this distance (in m.). A value of distance <= 0 excludes nothing.

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        r   NzGCoregistration: Excluding %i head shape points with distance >= %.3f m.Tr²  )rœ   rÙ  r�   rÀ   r-   rx   r„  r¯  )rŠ  ÚdistanceÚmaskZ
n_excludedrH   rH   rI   Úomit_head_shape_points•  s    
 ÿz%Coregistration.omit_head_shape_pointsc                 C   s0   |   d¡\}}}t| j|ƒ}tjj|| dd�S )a  Compute distance between head shape points and MRI skin surface.

        Returns
        -------
        dist : array, shape (n_points,)
            The distance of the head shape points to the MRI skin surface.

        See Also
        --------
        mne.dig_mri_distances
        r   rŽ   r�   )rî  r'   r›  r�   r¿  rÀ  )rŠ  rØ  r×  r¢   rH   rH   rI   rÛ  ±  s    z(Coregistration.compute_dig_mri_distancesc                 C   s   t dd| jƒS )z1The head->mri :class:`~mne.transforms.Transform`.r<   r9   )r    r›  rº  rH   rH   rI   ry   Ã  s    zCoregistration.transc                 C   sT   d| _ |  | jdd… ¡ |  | jdd… ¡ |  | jdd… ¡ d| _|  ¡  | S )z®Reset all the parameters affecting the coregistration.

        Returns
        -------
        self : Coregistration
            The modified Coregistration object.
        ri  Nr�   rk  rl  )r³  r·  ru  r¸  r¹  r„  r¦  rº  rH   rH   rI   r‰  È  s    zCoregistration.resetc                 C   s€   t ƒ }dD ]^}t|d�}| jj| d  dd¡}t| j|ƒ}t| j| j| ƒ}t	j
 t	 || ¡¡||< q
t	 t| ¡ ƒ¡d S )Nrè  r=   r>  r   rŽ   r½  )rd  rJ   r?   rp   r�   r'   r£  r›  r�  r�   r¿  rÀ  rÍ   r›   r–   r9  )rŠ  rõ  rX  rì  rñ   Ztransformed_mriZtransformed_hsprH   rH   rI   Ú_get_fiducials_distanceØ  s    
 ÿÿ
z&Coregistration._get_fiducials_distancec                 C   s2   |   ¡ }d|d d›d|d d›d|d d›d�S )NzFiducials: r   ú.1fz, r   rE   rÚ  )rø  )rŠ  ÚdistsrH   rH   rI   Ú_get_fiducials_distance_strå  s    z*Coregistration._get_fiducials_distance_strc                 C   s*  t ƒ }t ƒ }| jdkrV| jrV| | j| j ¡ | | j¡ t|d ƒt|d ƒksVt‚| j	dkr | j
r | | j| j ¡ | | j¡ t|d ƒt|d ƒks t‚| jdkrê| jrê| | j| j ¡ | | j¡ t|d ƒt|d ƒksêt‚tdd„ |D ƒƒ�rd S t |¡}t |¡}tjj|| dd�S )Nr   rŽ   c                 s   s   | ]}t |ƒd kV  qdS )r   N)rt   )rm   ÚhrH   rH   rI   Ú	<genexpr>û  s     z5Coregistration._get_point_distance.<locals>.<genexpr>r�   )r–   r�  rÈ  r˜   r¥  rÄ  rŸ  rt   rG   r‚  rÊ  rª  r�  rƒ  rÉ  r©  rœ  rñ  r�   r•   r¿  rÀ  rÖ  rH   rH   rI   Ú_get_point_distanceé  s2    ÿÿÿ

z"Coregistration._get_point_distancec                 C   s¢   |   ¡ }|d krdS d| }t |¡}t |¡}dd„ d| jdkoF| jfd| jdkoX| jfd| jdkoj| j	ffD ƒ}d	 
|¡}t|ƒ› d
|› d|d›d|d›d�S )Nré   r½  c                 S   s   g | ]\}}|r|‘qS rH   rH   )rm   rb  ÚcheckrH   rH   rI   rÞ     s    üz:Coregistration._get_point_distance_str.<locals>.<listcomp>ZHSPr   ZEEGZHPIú+r  z: rù  u    Â± rÚ  )rþ  r�   ZmeanZstdr�  rÈ  r‚  rÊ  rƒ  rÉ  r[   rt   )rŠ  Zpoint_distancerú  Zav_distZstd_distÚkindsrH   rH   rI   Ú_get_point_distance_str  s    

þÿ
z&Coregistration._get_point_distance_str)Nrh  )NNNF)rj  ro  rj  N)	rm  rj  ro  rj  rj  rj  rj  NN)2Ú__name__Ú
__module__Ú__qualname__Ú__doc__r‹  r…  r†  rˆ  r˜  r¯  r±  rµ  r·  r¸  r¹  r¦  Úpropertyrž  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Û  ry   r‰  rø  rû  rþ  r  rH   rH   rH   rI   rg  	  sž   $ÿ%$%	  ÿ
<

















  ÿ9*           þD
	
rg  )F)rk   )NFNN)rŠ   )TTFNNry   N)r|   NN)N)N)N)N)NNN)NFNNN)FNFTF)NNNNN)}r  r  rß   r   r   rL   Úos.pathrZ   rZ  rN   rV   rü   r�   Ú	functoolsr   Únumpyr�   Úior   r   r   Zio.constantsr	   Zio.meas_infor
   Zio._digitizationr   Z_freesurferr   r   r   r}   r   r   Zsource_spacer   r   r   Zsurfacer   r   r   r   r   r   r8   r   r   r:   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   Zchannelsr*   Úutilsr+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   Zviz._3dr6   r[   Ztrans_fnamer@  rö   r  r   r÷   rú   rù   Zhead_sparse_fnamer  r	  rU  re   rd   rs   r¹   rJ   rS   r`   rj   rz   r‰   rª   r±   rº   rw   r»   ræ   r  rÿ   r  r  r  r  r'  r,  r6  r=  rO  rI  rE  rG  rf  Úobjectrg  rH   rH   rH   rI   Ú<module>   sÖ    @4þþ	

$  ÿT
G         þ
^>
%w



'"#  ÿ ÿ.    ÿ
7       þ þ       ÿ_M