3
d                 @   s  d Z ddlZddlmZmZ ddl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 d
ZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd  d eZG d!d" d"eZG d#d$ d$eZG d%d& d&eZG d'd( d(eZ G d)d* d*eZ!G d+d, d,eZ"G d-d. d.eZ#G d/d0 d0e!Z$G d1d2 d2e#Z%G d3d4 d4eZ&G d5d6 d6eZ'G d7d8 d8eZ(G d9d: d:eZ)G d;d< d<eZ*G d=d> d>eZ+G d?d@ d@eZ,G dAdB dBeZ-G dCdD dDeZ.G dEdF dFeZ/G dGdH dHeZ0G dIdJ dJeZ1G dKdL dLeZ2G dMdN dNeZ3G dOdP dPeZ4dS )QzYThe freesurfer module provides basic functions for interfacing with
   freesurfer tools.
    N   )fname_presuffixsplit_filename   )TraitedSpecFiletraitsInputMultiPathOutputMultiPath	Directory	isdefined   )	FSCommandFSTraitedSpec)copy2subjdirZrestructuredtextc               @   sF  e Zd ZeddddZejddddZejdd	d
dddZ	ejdd9ddZ
ejdd:ddZejdd;ddZeddd<ddZeddd=ddZeedddd>d dZejd!d"d#Zejd$d%d#Zeejeddeddd&d'd#Zejd(d)d#Zejd*d+gd,dZejd-d.gd/dZejd0d1gd2dZejd3d4gd5dZejd6d7d#Zd8S )?MRISPreprocInputSpecz--out %sTzoutput filename)argstrgenfiledescz--target %sztarget subject name)r   	mandatoryr   lhrhz	--hemi %sz hemisphere for source and targetz	--meas %ssurf_measuresurf_measure_file	surf_areaz+Use subject/surf/hemi.surf_measure as input)r   xorr   z	--area %szDExtract vertex area from subject/surf/hemi.surfname to use as input.z	--s %s...subjects	fsgd_filesubject_filez)subjects from who measures are calculatedz	--fsgd %sz specify subjects using fsgd file)existsr   r   r   z--f %sz1file specifying subjects separated by white space)r   z
--is %s...z=file alternative to surfmeas, still requires list of subjectsz--srcfmt %szsource format)r   r   z--surfdir %sz'alternative directory (instead of surf)z--iv %s %s...z*list of volume measure and reg file tuplesz--projfrac %sz projection fraction for vol2surfz	--fwhm %f	num_itersz'smooth by fwhm mm on the target surfacez--niters %dfwhmz/niters : smooth by niters on the target surfacez--fwhm-src %fnum_iters_sourcez'smooth by fwhm mm on the source surfacez--niterssrc %dfwhm_sourcez/niters : smooth by niters on the source surfacez--smooth-cortex-onlyz,only smooth cortex (ie, exclude medial wall)N)r   r   r   )r   r   r   )r   r   r   )r   r   r   )r   r   r   )r   r   r   )__name__
__module____qualname__r   out_filer   StrtargetEnumhemir   r   Listr   r   r   r	   r   Zsource_formatsurf_dirTupleZvol_measure_fileFloatZ	proj_fracr!   Intr    r#   r"   BoolZsmooth_cortex_only r2   r2   D/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/freesurfer/model.pyr      s   

r   c               @   s   e Zd ZeddZdS )MRISPreprocOutputSpeczpreprocessed output file)r   N)r$   r%   r&   r   r'   r2   r2   r2   r3   r4   m   s   r4   c               @   s,   e Zd ZdZdZeZeZdd Z	dd Z
dS )MRISPreprocaW  Use FreeSurfer mris_preproc to prepare a group of contrasts for
    a second level analysis

    Examples
    --------
    >>> preproc = MRISPreproc()
    >>> preproc.inputs.target = 'fsaverage'
    >>> preproc.inputs.hemi = 'lh'
    >>> preproc.inputs.vol_measure_file = [('cont1.nii', 'register.dat'),                                            ('cont1a.nii', 'register.dat')]
    >>> preproc.inputs.out_file = 'concatenated_file.mgz'
    >>> preproc.cmdline
    'mris_preproc --hemi lh --out concatenated_file.mgz --target fsaverage --iv cont1.nii register.dat --iv cont1a.nii register.dat'

    Zmris_preprocc             C   sN   | j  j }| jj}||d< t|sJtjjtj d| jj	| jj
f |d< |S )Nr'   zconcat_%s_%s.mgz)output_specgetinputsr'   r   ospathjoingetcwdr+   r)   )selfoutputsoutfiler2   r2   r3   _list_outputs   s     zMRISPreproc._list_outputsc             C   s   |dkr| j  | S d S )Nr'   )r@   )r=   namer2   r2   r3   _gen_filename   s    zMRISPreproc._gen_filenameN)r$   r%   r&   __doc___cmdr   
input_specr4   r6   r@   rB   r2   r2   r2   r3   r5   q   s   
r5   c               @   sr   e Zd ZedddddZeeddd	d
dgddZeddgdZeddgdZe	j
ddddddZe	jddZdS )MRISPreprocReconAllInputSpecTz	--meas %sr   r   r   zfile necessary for surfmeas)r   r   r   r   )r   z--surfreg %slh_surfreg_targetrh_surfreg_targetz*lh and rh input surface registration files)r   requiresr   z)Implicit target surface registration filesurfreg_files)r   rI   
subject_idz--s %sr   r   r   z)subject from whom measures are calculated)r   
usedefaultr   r   zaIf running as a node, set this to True this will copy some implicit inputs to the node directory.)r   N)r   r   r   )r   r   r   rK   )r$   r%   r&   r   r   r	   rJ   rG   rH   r   StringrK   r1   copy_inputsr2   r2   r2   r3   rF      s,   rF   c                   s0   e Zd ZdZeZ fddZ fddZ  ZS )MRISPreprocReconAllaU  Extends MRISPreproc to allow it to be used in a recon-all workflow

    Examples
    --------
    >>> preproc = MRISPreprocReconAll()
    >>> preproc.inputs.target = 'fsaverage'
    >>> preproc.inputs.hemi = 'lh'
    >>> preproc.inputs.vol_measure_file = [('cont1.nii', 'register.dat'),                                            ('cont1a.nii', 'register.dat')]
    >>> preproc.inputs.out_file = 'concatenated_file.mgz'
    >>> preproc.cmdline
    'mris_preproc --hemi lh --out concatenated_file.mgz --s subject_id --target fsaverage --iv cont1.nii register.dat --iv cont1a.nii register.dat'

    c                s   | j jrtj | j _d|kr(| j j|d< t| j jr>| j j}nd}t| j jrxj| j jD ]^}tjj	|}t
| ||| |jdrt
| | j j||| j jd qXt
| | j j||| j jd qXW t| j jrt
| | j j| tt| jf |S )Nsubjects_dirsurfzlh.)rK   )r8   rN   r9   r<   rP   r   r-   rJ   r:   basenamer   
startswithrG   r)   rH   r   superrO   run)r=   r8   folderZsurfregrR   )	__class__r2   r3   rU      s6    

zMRISPreprocReconAll.runc                sl   |dkr.t jj|d }|j|jdjd S |dkrXt jj|}|j|jdjd S tt| j|||S )NrJ   r   zrh.zlh.r   )r9   r:   rR   r   lstriprT   rO   _format_arg)r=   rA   specvaluerR   )rW   r2   r3   rY      s    zMRISPreprocReconAll._format_arg)	r$   r%   r&   rC   rF   rE   rU   rY   __classcell__r2   r2   )rW   r3   rO      s   #rO   c               @   s  e Zd ZejddddZedddddZdZej	eddej
dddeddZeddeddZeedddddZejddddZejdddZeedddddZej	ejejejdd dZedd!dd%dZedd&d'd(Zejd)d*gd+dZed,d-gd.dZedd/gd0d1Zejd2d3d/gd4Zejd5d6d/gd4Zejd7d8d9d:Zejd7d;d<d:Zejd=d>dZejd?d@dZ eddAdBd(Z!eddCdDgdEdZ"ejdFdGgdHdZ#ejdIdJdZ$ejdKdLdZ%ejdMdNgdOdZ&ej'dPdQgdRdZ(ejdSdTdZ)ejdUdVdZ*ejdWdXdZ+ejdYdZdZ,ejd[d\d]gd^d_Z-ejd`daZ.ej
dbdcdddaZ/ejdeddfdgZ0ej	ej
dhdidjejdkdlej'ejdmdndZ1ej
dodpdqdrdsdZ2ej	ej'ej'dtdudZ3ejdvdwdZ4ejdxdydZ5ejdzd{dZ6ej	ejejejd|d}dZ7ejd~ddZ8ejdddZ9ejdddZ:ejdddZ;ejdddZ<ejdddZ=ejdddZ>ejdddZ?ejdddZ@ejdddZAejdddZBedddZCdS )GLMFitInputSpecz--glmdir %szsave outputs to dirT)r   r   r   zinput 4D filez--y %sF)r   r   r   copyfilefsgddesign
one_sample)r   ZdossZdodsz--fsgd %s %szfreesurfer descriptor file)r   r   r   z--X %szdesign matrix file)r   r   r   r   z	--C %s...zcontrast file)r   r   z--osgmcontrastz,construct X and C as a one-sample group meanz--no-contrasts-okz%do not fail if no contrasts specifiedz--pvr %s...zper-voxel regressorsz--selfreg %d %d %dz'self-regressor from index col row slicez--wls %sweight_file
weight_invweight_sqrtzweighted least squaresz--yffxvar %szfor fixed effects analysis)r   r   r   z--ffxdof %dfixed_fx_dof_filezdof for fixed effects analysisz--ffxdofdat %dfixed_fx_dofz-text file with dof for fixed effects analysisweighted_lsz#weight for each input at each voxel)r   r   r   z--w-invzinvert weights)r   r   r   z--w-sqrtzsqrt of weightsg        z	--fwhm %fzsmooth input by fwhm)lowr   r   z--var-fwhm %fzsmooth variance by fwhmz--no-mask-smoothzdo not mask when smoothingz--no-est-fwhmzturn off FWHM output estimationz	--mask %szbinary maskz
--label %scortexz use label as mask, surfaces onlyz--cortex
label_filez%use subjects ?h.cortex.label as labelz
--mask-invzinvert maskz--prunezCremove voxels that do not have a non-zero value at each frame (def)z
--no-pruneZprunethreshzdo not prunez--prune_thr %fZnoprunez#prune threshold. Default is FLT_MINz--logyz*compute natural log of y prior to analysisz--yhat-savezsave signal estimate (yhat)z--eres-savezsave residual error (eres)z
--eres-scmz?save residual error spatial correlation matrix (eres.scm). Big!z--surf %s %s %srK   r+   zanalysis is on a surface mesh)r   rI   r   zsubject id for surface geometry)r   r   r   zsurface hemispherewhitez(surface geometry name (e.g. white, pial))rL   r   Zpermzmc-fullzmc-zr   )minz--sim %s %d %f %sz nulltype nsim thresh csdbasenameabsposnegz--sim-sign %szabs, pos, or negz--uniform %f %fz,use uniform distribution instead of gaussianz--pcaz$perform pca/svd analysis on residualz--tar1z)compute and save temporal AR1 of residualz--save-condz2flag to save design matrix condition at each voxelz--voxdump %d %d %dzdump voxel GLM and exitz	--seed %dzused for synthesizing noisez--synthzreplace input with gaussianz--resynthtest %dztest GLM by resynthsisz--profile %dzniters : test speedz--perm-forcez=force perumtation test, even when design matrix is not orthogz	--diag %dzGdiag_no : set diagnositc levelz--diag-clusterz,save sig volume and exit from first sim loopz--debugzturn on debuggingz--checkoptsz/don't run anything, just check options and exitz--allowsubjrepzIallow subject names to repeat in the fsgd file (must appear before --fsgdz	--illcondz%allow ill-conditioned design matricesz--sim-done %sz$create file when simulation finishedN)r_   r`   ra   )ra   r_   r`   rb   )rc   rd   re   )Dr$   r%   r&   r   r(   glm_dirr   in_fileZ_design_xorr.   r*   r_   r`   r	   rb   r1   ra   Zno_contrast_okZper_voxel_regr0   Zself_regrh   Zfixed_fx_varrg   rf   rc   rd   re   Ranger!   Zvar_fwhmZno_mask_smoothZno_est_fwhm	mask_filerk   rj   Zinvert_maskpruneZno_pruner/   Zprune_threshZcompute_log_ysave_estimatesave_residualZsave_res_corr_mtxrQ   rK   r+   surf_geoZ
simulationZsim_signuniformpcaZcalc_AR1Z	save_condZvox_dumpseedZsynthZresynth_testZprofileZ
force_permZdiagZdiag_clusterdebugZ
check_optsZallow_repeated_subjectsZallow_ill_condZsim_done_filer2   r2   r2   r3   r]      s  











r]   c               @   s   e Zd ZedddZed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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dS )GLMFitOutputSpecTzoutput directory)r   r   zmap of regression coefficientszmap of residual error)r   zmap of residual error variancez(map of residual error standard deviationzmap of the estimated Y valuesz$map of the mask used in the analysisz#text file with estimated smoothnessz<text file with effective degrees-of-freedom for the analysisz*map of contrast of regression coefficientsz#map of regression contrast variancez'map of F-test significance (in -log10p)zmap of test statistic valuesz-map of spatial eigenvectors from residual PCAz.matrix of frame eigenvectors from residual PCAz(matrix singular values from residual PCAz&text file summarizing the residual PCAN)r$   r%   r&   r   rq   r   	beta_file
error_fileerror_var_fileerror_stddev_fileestimate_filert   	fwhm_filedof_filer
   
gamma_filegamma_var_filesig_file
ftest_filespatial_eigenvectorsframe_eigenvectorsZsingular_valuessvd_stats_filer2   r2   r2   r3   r}     s"   













r}   c                   s<   e Zd ZdZdZeZeZ fddZ	dd Z
dd Z  ZS )	GLMFitaA  Use FreeSurfer's mri_glmfit to specify and estimate a general linear model.

    Examples
    --------
    >>> glmfit = GLMFit()
    >>> glmfit.inputs.in_file = 'functional.nii'
    >>> glmfit.inputs.one_sample = True
    >>> glmfit.cmdline == 'mri_glmfit --glmdir %s --y functional.nii --osgm'%os.getcwd()
    True

    Z
mri_glmfitc                s8   |dkr$| j }|j|j|j|jf S tt| j|||S )NrQ   )r8   r   rK   r+   rx   rT   r   rY   )r=   rA   rZ   r[   Z_si)rW   r2   r3   rY     s    zGLMFit._format_argc                s>  | j  j }t| jjs"tj  ntjj| jj  |d< tjj	 d|d< tjj	 d|d< tjj	 d|d< tjj	 d|d	< tjj	 d
|d< tjj	 d|d< t| jj
r| jj
rtjj	 d|d< t| jjr| jjrtjj	 d|d< t| jjrVg }xn| jjD ]B}t|d d+kr8|jt|d  n|jtjj|d  qW nt| jjrt| jjrtdg} fdd|D |d<  fdd|D |d<  fdd|D |d<  fd d|D |d!< t| jjr:| jjr:tjj	 d"}tjj	|d#|d$< tjj	|d%|d&< tjj	|d'|d(< tjj	|d)|d*< |S ),Nrq   zbeta.mghr~   zrvar.mghr   zrstd.mghr   zmask.mghrt   zfwhm.datr   zdof.datr   zeres.mghr   zyhat.mghr   r   .mat.dat.mtx.conr   Zosgmc                s   g | ]}t jj |d qS )zsig.mgh)r9   r:   r;   ).0c)glmdirr2   r3   
<listcomp>  s    z(GLMFit._list_outputs.<locals>.<listcomp>r   c                s   g | ]}t jj |d qS )zF.mgh)r9   r:   r;   )r   r   )r   r2   r3   r     s    r   c                s   g | ]}t jj |d qS )z	gamma.mgh)r9   r:   r;   )r   r   )r   r2   r3   r     s    r   c                s   g | ]}t jj |d qS )zgammavar.mgh)r9   r:   r;   )r   r   )r   r2   r3   r      s    r   zpca-ereszv.mghr   zu.mtxr   z	sdiag.matZsingluar_valuesz	stats.datr   )r   r   r   r   )r6   r7   r   r8   rq   r9   r<   r:   abspathr;   rw   rv   rb   r   appendsplitra   rz   )r=   r>   Z	contrastsr   Zpcadirr2   )r   r3   r@     sD    
zGLMFit._list_outputsc             C   s   |dkrt j S d S )Nrq   )r9   r<   )r=   rA   r2   r2   r3   rB     s    zGLMFit._gen_filename)r$   r%   r&   rC   rD   r]   rE   r}   r6   rY   r@   rB   r\   r2   r2   )rW   r3   r     s   5r   c                   s   e Zd Z fddZ  ZS )OneSampleTTestc                s   t t| jf | d| j_d S )NT)rT   r   __init__r8   ra   )r=   kwargs)rW   r2   r3   r     s    zOneSampleTTest.__init__)r$   r%   r&   r   r\   r2   r2   )rW   r3   r     s   r   c               @   s  e Zd ZeddddddZejddgdd	Zejd
dgdd	ZejdddZ	ejdddZ
ejejdddZejdddZejdddZejdddgdd	ZeddddZejddd d!d"dZejejed#d$dZejd%d&dZejd'd(dZejd)d*dZejd+d,dZedd-d.d/Zedd0d1d/Zejd2d3dZejd4d5dZejd6d7dZejd8d9dZ ejd:d;dZ!ejd<d=dZ"ejd>d?dZ#ejd@dAdZ$dBS )CBinarizeInputSpecTz--i %sFzinput volume)r   r   r   r^   r   z--min %f
wm_ven_csfz
min thresh)r   r   r   z--max %fz
max threshz	--rmin %fz$compute min based on rmin*globalmean)r   r   z	--rmax %fz$compute max based on rmax*globalmeanz--match %d...zmatch instead of thresholdz--wmz1set match vals to 2 and 41 (aseg for cerebral WM)z--ventriclesz:set match vals those for aseg ventricles+choroid (not 4th)z	--wm+vcsfrm   maxz3WM and ventricular CSF, including choroid (not 4th)z--o %szbinary output volume)r   r   r   Zniiznii.gzZmgz zoutput file typez
--count %sz6save number of hits in ascii file (hits, ntotvox, pct)z--binval %dz+set vox within thresh to val (default is 1)z--binvalnot %dz+set vox outside range to val (default is 0)z--invzset binval=0, binvalnot=1z
--frame %sz)use 0-based frame of input (default is 0)z
--merge %szmerge with mergevol)r   r   r   z--mask maskvolzmust be within maskz--mask-thresh %fzset thresh for maskz--absz+take abs of invol first (ie, make unsigned)z--bincolz.set binarized voxel value to its column numberz--zero-edgeszzero the edge voxelsz--zero-slice-edgeszzero the edge slice voxelsz--dilate %dz!niters: dilate binarization in 3Dz--erode  %dz5nerode: erode binarization in 3D (after any dilation)z--erode2d %dz9nerode2d: erode binarization in 2D (after any 3D erosion)N)%r$   r%   r&   r   rr   r   r/   rm   r   ZrminZrmaxr,   r0   matchr1   ZwmZ
ventriclesr   binary_filer*   out_typeEither
count_fileZbin_valZbin_val_notinvertZframe_noZ
merge_filert   mask_threshrn   Zbin_col_numZ
zero_edgesZzero_slice_edgeZdilateerodeZerode2dr2   r2   r2   r3   r     sh   






r   c               @   s"   e Zd ZedddZeddZdS )BinarizeOutputSpecTzbinarized output volume)r   r   z$ascii file containing number of hits)r   N)r$   r%   r&   r   r   r   r2   r2   r2   r3   r   ^  s   r   c                   s<   e Zd ZdZdZeZeZdd Z	 fddZ
dd Z  ZS )	Binarizea  Use FreeSurfer mri_binarize to threshold an input volume

    Examples
    --------
    >>> binvol = Binarize(in_file='structural.nii', min=10, binary_file='foo_out.nii')
    >>> binvol.cmdline
    'mri_binarize --o foo_out.nii --i structural.nii --min 10.000000'

    Zmri_binarizec             C   s   | j  j }| jj}t|sft| jjrPt| jjtj	 dj
d| jjfdd}nt| jjtj	 dd}tjj||d< | jj}t|rt|tr|rt| jjdtj	 dd|d	< n||d	< |S )
N.Z_threshF)newpathsuffixuse_ext)r   r   r   z
_count.txt)r   r   r   r   )r6   r7   r8   r   r   r   r   rr   r9   r<   r;   r:   r   r   
isinstancebool)r=   r>   r?   r[   r2   r2   r3   r@   r  s.    

zBinarize._list_outputsc                sN   |dkr.t |tr | j | }n|}|j| S |dkr:dS tt| j|||S )Nr   r   r   )r   r   r@   r   rT   r   rY   )r=   rA   rZ   r[   fname)rW   r2   r3   rY     s    

zBinarize._format_argc             C   s   |dkr| j  | S d S )Nr   )r@   )r=   rA   r2   r2   r3   rB     s    zBinarize._gen_filename)r$   r%   r&   rC   rD   r   rE   r   r6   r@   rY   rB   r\   r2   r2   )rW   r3   r   c  s   	r   c            
   @   s   e Zd ZeeddddddZeddddZejd	d
ddddZ	ejdddddddddZ
ejdddddddddZejdddZejdd dZejd!d"dZejd#d$dZedd%d&d'Zejd(d)dZejd*d+dZejd,d-dZejd.d/dZedd0d1d'Zejd2d3dZejd4d5dZd6S )7ConcatenateInputSpecT)r   z%Individual volumes to be concatenatedz	--i %s...)r   r   r   zOutput volumez--o %s)r   r   r   rn   ro   rp   z--%sz3Take only pos or neg voxles from input, or take abs)r   r   sumvarZstdr   rm   Zmeanz@Compute the sum, var, std, max, min or mean of the input volumesavgZdiffz	diff-normz
diff-norm1z
diff-norm2z--paired-%sz Compute paired sum, avg, or diffz
--gmean %dz0create matrix to average Ng groups, Nper=Ntot/Ngz--mean-div-nz#compute mean/nframes (good for var)z--mul %fz$Multiply input volume by some amountz--add %fz#Add some amount to the input volumez--mtx %sz)Multiply input by an ascii matrix in file)r   r   r   z	--combinez0Combine non-zero values into single frame volumez--keep-datatypez/Keep voxelwise precision type (default is floatz--max-bonfcorz7Compute max and bonferroni correct (assumes -log10(ps))z--max-indexz6Compute the index of max voxel in concatenated volumesz	--mask %szMask input with a volumez--votez<Most frequent value at each voxel and fraction of occurancesz--sortz(Sort each voxel by ascending frame valueN)r$   r%   r&   r	   r   Zin_filesconcatenated_filer   r*   signstatsZpaired_statsr0   Zgmeanr1   Z
mean_div_nr/   Zmultiply_byZadd_valZmultiply_matrix_filecombineZ
keep_dtypeZmax_bonfcorZ	max_indexrt   Zvotesortr2   r2   r2   r3   r     sn   





r   c               @   s   e Zd ZedddZdS )ConcatenateOutputSpecTzPath/name of the output volume)r   r   N)r$   r%   r&   r   r   r2   r2   r2   r3   r     s   r   c               @   s,   e Zd ZdZdZeZeZdd Z	dd Z
dS )Concatenatea  Use Freesurfer mri_concat to combine several input volumes
    into one output volume.  Can concatenate by frames, or compute
    a variety of statistics on the input volumes.

    Examples
    --------
    Combine two input volumes into one volume with two frames

    >>> concat = Concatenate()
    >>> concat.inputs.in_files = ['cont1.nii', 'cont2.nii']
    >>> concat.inputs.concatenated_file = 'bar.nii'
    >>> concat.cmdline
    'mri_concat --o bar.nii --i cont1.nii --i cont2.nii'

    Z
mri_concatc             C   s:   | j  j }| jj}t|s d}tjjtj ||d< |S )Nzconcat_output.nii.gzr   )	r6   r7   r8   r   r   r9   r:   r;   r<   )r=   r>   r   r2   r2   r3   r@     s    zConcatenate._list_outputsc             C   s   |dkr| j  | S d S )Nr   )r@   )r=   rA   r2   r2   r3   rB     s    zConcatenate._gen_filenameN)r$   r%   r&   rC   rD   r   rE   r   r6   r@   rB   r2   r2   r2   r3   r     s   	r   c            	   @   s  e Zd ZdrZeddedddZejejej	dd	ejd
edddZ
ejejej	dd	ejdedddZedddsddZeddddZeddddZejdddZejdddZejdddZej	dd d!d"dZdtZedd&ed'd(Zejd)ed*d+Zedd,ed-d(Zejd.d/dZejd0d1dZejd2d3dZejd4d5dZejd6d7dZejd8d9dZ ejd:d;dZ!edd<d=dZ"ejd>d?dZ#ej	d@dAdBdCdDdEZ$ejdFdGgdHdIZ%ejdJdKdZ&ejdLdMdZ'ej	dNdOd!dPdZ(edQddRdSZ)ejdTdUdZ*ej	dVdWdXdYdEZ+ej,ejedZd[dZ-ej,ejed\d]dZ.ej,ejed^d_dZ/ejejd`dadZ0ejdbdcdZ1ejdddedZ2ejdfdgdZ3ejdhdidZ4edjdkdZ5ej	dldmdngdodpZ6dqS )uSegStatsInputSpecsegmentation_fileannot
surf_labelTz--seg %szsegmentation volume path)r   r   r   r   r   r   r   z--annot %s %s %sz,subject hemi parc : use surface parcellation)r   r   r   r   z--slabel %s %s %sz&subject hemi label : use surface labelz--sum %sr   z%Segmentation stats summary table file)r   r   positionr   z--pv %szCompensate for partial voluming)r   r   r   z--i %sz3Use the segmentation to report stats on this volumez
--frame %dz)Report stats on nth frame of input volume)r   r   z--mul %fzmultiply input by valz--snrz-save mean/std as extra column in output tableZsqrsqrtz--%sz/Compute either the sqr or the sqrt of the inputcolor_table_filedefault_color_tablegca_color_tablez	--ctab %sz"color table file with seg id names)r   r   r   r   z--ctab-defaultz+use $FREESURFER_HOME/FreeSurferColorLUT.txt)r   r   r   z--ctab-gca %szget color table from GCA (CMA)z
--id %s...z!Manually specify segmentation idsz--excludeid %dzExclude seg id from reportz--excl-ctxgmwmz&exclude cortical gray and white matterz--surf-wm-volzCompute wm volume from surfz--surf-ctx-volzCompute cortex volume from surfz
--nonemptyz"Only report nonempty segmentationsz--emptyz1Report on segmentations listed in the color tablez	--mask %szMask volume (same size as segz--maskthresh %fz'binarize mask with this threshold <0.5>rn   ro   rp   z--masksign %sz)Sign for mask threshold: pos, neg, or abs)r   z--maskframe %drt   z1Mask with this (0 based) frame of the mask volume)rI   r   z--maskinvertzInvert binarized mask volumez--maskerode %dzErode mask by some amountzbrain-vol-from-segZ	brainmaskzHCompute brain volume either with ``brainmask`` or ``brain-vol-from-seg``z--brainmask %szYLoad brain mask and compute the volume of the brain as the non-zero voxels in this volume)r   r   r   z--etivz$Compute ICV from talairach transformetivzold-etivz	--%s-onlyz4Compute etiv and exit.  Use ``etiv`` or ``old-etiv``z
--avgwf %sz2Save average waveform into file (bool or filename)z--avgwfvol %sz(Save as binary volume (bool or filename)z
--sfavg %szSave mean across space and timez--vox %sz:Replace seg with all 0s except at C R S (three int inputs)z--supratentzUndocumented input flagz--subcortgrayz)Compute volume of subcortical gray matterz--totalgrayz#Compute volume of total gray matterz--eulerzHWrite out number of defect holes in orig.nofix based on the euler numberz--in %s --in-intensity-name %sz Undocumented input norm.mgz fileZMRz--in-intensity-units %sin_intensityzIntensity units)r   rI   r   N)r   r   r   )r   r   r   )7r$   r%   r&   Z_xor_inputsr   r   r   r.   r(   r*   r   r   summary_fileZpartial_volume_filerr   r0   framer/   multiplyr1   Zcalc_snrZ
calc_powerZ_ctab_inputsr   r   r   r,   Z
segment_idZ
exclude_idZexclude_ctx_gm_wmZwm_vol_from_surfZcortex_vol_from_surfZnon_empty_onlyemptyrt   r   Z	mask_signZ
mask_frameZmask_invertZ
mask_erodeZ	brain_volbrainmask_filer   Z	etiv_onlyr   avgwf_txt_file
avgwf_filesf_avg_fileZvoxZ	supratentZ
subcort_gmZ
total_grayZeulerr   Zintensity_unitsr2   r2   r2   r3   r     s  














r   c               @   s6   e Zd ZedddZeddZeddZeddZdS )	SegStatsOutputSpecTz%Segmentation summary statistics table)r   r   z7Text file with functional statistics averaged over segs)r   z4Volume with functional statistics averaged over segsz<Text file with func statistics averaged over segs and framssN)r$   r%   r&   r   r   r   r   r   r2   r2   r2   r3   r     s   
r   c                   s<   e Zd ZdZdZeZeZdd Z	 fddZ
dd Z  ZS )	SegStatsa  Use FreeSurfer mri_segstats for ROI analysis

    Examples
    --------
    >>> import nipype.interfaces.freesurfer as fs
    >>> ss = fs.SegStats()
    >>> ss.inputs.annot = ('PWS04', 'lh', 'aparc')
    >>> ss.inputs.in_file = 'functional.nii'
    >>> ss.inputs.subjects_dir = '.'
    >>> ss.inputs.avgwf_txt_file = 'avgwf.txt'
    >>> ss.inputs.summary_file = 'summary.stats'
    >>> ss.cmdline
    'mri_segstats --annot PWS04 lh aparc --avgwf ./avgwf.txt --i functional.nii --sum ./summary.stats'

    Zmri_segstatsc             C   s  | j  j }t| jjr.tjj| jj|d< ntjjtj	 d|d< t
dddd}t| jjrrtjj| jj\}}t| jjrdj| jj}t| jjrdj| jj}x`t|j D ]P\}}t| j|}t|rt|trt||tj	 dd	||< qtjj|||< qW |S )
Nr   zsummary.statsz
_avgwf.txtz_avgwf.nii.gzz	sfavg.txt)r   r   r   _F)r   r   r   )r6   r7   r   r8   r   r9   r:   r   r;   r<   dictr   r   r   r   listitemsgetattrr   r   r   )r=   r>   Zsufficesr   srcrA   r   r[   r2   r2   r3   r@     s,    
zSegStats._list_outputsc                s   |d	kr,t |ts,tjj|s,tjjd|}|d
krZt |trL| j | }n|}|j| S |dkrtjj| j	j
jdd}|j||f S tt| j|||S )Nr   r   r   r   r   r   z.mgzr   )r   r   )r   r   r   )r   r   r9   r:   isabsr;   r@   r   rR   r8   r   replacerT   r   rY   )r=   rA   rZ   r[   r   Zintensity_name)rW   r2   r3   rY     s    


zSegStats._format_argc             C   s   |dkr| j  | S d S )Nr   )r@   )r=   rA   r2   r2   r3   rB     s    zSegStats._gen_filename)r$   r%   r&   rC   rD   r   rE   r   r6   r@   rY   rB   r\   r2   r2   )rW   r3   r     s   r   c               @   s   e Zd ZejddddddZeddddZeddd	Zeddd
dZ	eddddZ
eddddZeddddZeddddZeddddZeddddZeddd	ZejddZdS )SegStatsReconAllInputSpecrK   Tz--subject %szSubject id being processed)rL   r   r   r   zInput file mri/ribbon.mgz)r   r   r   zInput segmentation volume)r   r   zInput transform filezInput lh.orig.nofixzInput rh.orig.nofixz-Input file must be <subject_id>/surf/lh.whitez-Input file must be <subject_id>/surf/rh.whitez,Input file must be <subject_id>/surf/lh.pialz,Input file must be <subject_id>/surf/rh.pialzMandatory implicit input in 5.3zkIf running as a node, set this to True otherwise, this will copy the implicit inputs to the node directory.)r   N)r$   r%   r&   r   rM   rK   r   ribbonpresurf_seg	transformlh_orig_nofixrh_orig_nofixlh_whiterh_whitelh_pialrh_pialasegr1   rN   r2   r2   r2   r3   r     s4   r   c                   s4   e Zd ZdZeZeZ fddZ fddZ	  Z
S )SegStatsReconAlla  
    This class inherits SegStats and modifies it for use in a recon-all workflow.
    This implementation mandates implicit inputs that SegStats.
    To ensure backwards compatability of SegStats, this class was created.

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import SegStatsReconAll
    >>> segstatsreconall = SegStatsReconAll()
    >>> segstatsreconall.inputs.annot = ('PWS04', 'lh', 'aparc')
    >>> segstatsreconall.inputs.avgwf_txt_file = 'avgwf.txt'
    >>> segstatsreconall.inputs.summary_file = 'summary.stats'
    >>> segstatsreconall.inputs.subject_id = '10335'
    >>> segstatsreconall.inputs.ribbon = 'wm.mgz'
    >>> segstatsreconall.inputs.transform = 'trans.mat'
    >>> segstatsreconall.inputs.presurf_seg = 'wm.mgz'
    >>> segstatsreconall.inputs.lh_orig_nofix = 'lh.pial'
    >>> segstatsreconall.inputs.rh_orig_nofix = 'lh.pial'
    >>> segstatsreconall.inputs.lh_pial = 'lh.pial'
    >>> segstatsreconall.inputs.rh_pial = 'lh.pial'
    >>> segstatsreconall.inputs.lh_white = 'lh.pial'
    >>> segstatsreconall.inputs.rh_white = 'lh.pial'
    >>> segstatsreconall.inputs.empty = True
    >>> segstatsreconall.inputs.brain_vol = 'brain-vol-from-seg'
    >>> segstatsreconall.inputs.exclude_ctx_gm_wm = True
    >>> segstatsreconall.inputs.supratent = True
    >>> segstatsreconall.inputs.subcort_gm = True
    >>> segstatsreconall.inputs.etiv = True
    >>> segstatsreconall.inputs.wm_vol_from_surf = True
    >>> segstatsreconall.inputs.cortex_vol_from_surf = True
    >>> segstatsreconall.inputs.total_gray = True
    >>> segstatsreconall.inputs.euler = True
    >>> segstatsreconall.inputs.exclude_id = 0
    >>> segstatsreconall.cmdline
    'mri_segstats --annot PWS04 lh aparc --avgwf ./avgwf.txt --brain-vol-from-seg --surf-ctx-vol --empty --etiv --euler --excl-ctxgmwm --excludeid 0 --subcortgray --subject 10335 --supratent --totalgray --surf-wm-vol --sum ./summary.stats'

    c                s.   |dkr|j tjj| S tt| j|||S )Nr   )r   r9   r:   rR   rT   r   rY   )r=   rA   rZ   r[   )rW   r2   r3   rY   c  s    zSegStatsReconAll._format_argc                s  | j jrtj | j _d|kr*| j j|d< t| | j jdd t| | j jdd t| | j jdd t| | j j	dd t| | j j
dd t| | j jdd t| | j jd	d
 t| | j jd	d t| | j jd	d t| | j jtjjd	dd t| | j jd	 t| | j jd	 tt| jf |S )NrP   rQ   zlh.orig.nofixzrh.orig.nofixzlh.whitezrh.whitezlh.pialzrh.pialZmriz
ribbon.mgzzaseg.presurf.mgzzaseg.mgzZ
transformsztalairach.xfm)r8   rN   r9   r<   rP   r   r   r   r   r   r   r   r   r   r   r   r:   r;   r   r   rT   r   rU   )r=   r8   )rW   r2   r3   rU   h  s*    
zSegStatsReconAll.run)r$   r%   r&   rC   r   rE   r   r6   rY   rU   r\   r2   r2   )rW   r3   r   9  s
   %r   c            	   @   sX  e Zd ZeeddddDddd	d
ZedddEdFddddZedddGddddZej	ddHdddZ
edddddZedddIddZedddJd dZej	d!dKd"d#Zej	d$d%d&Zejd'd(d)d*d&Zejd+d,d&Zejejd-d.ejejejd/dLd0d1Zejd2d3d&Zejd4d5d6d7d&Zejd8d9d&Zed:dd;d<Zed=d>d&Zed?d@d&Zej	dAdBd&ZdCS )MLabel2VolInputSpecT)r   z--label %s...rk   
annot_fileseg_file
aparc_asegFzlist of label files)r   r   r^   r   r   z
--annot %srK   r+   zsurface annotation file)r   r   r   rI   r   r^   r   z--seg %szsegmentation file)r   r   r   r   r^   r   z--aparc+asegz'use aparc+aseg.mgz in subjectdir as seg)r   r   r   r   z	--temp %szoutput template volume)r   r   r   r   z--reg %sreg_file
reg_headeridentityz+tkregister style matrix VolXYZ = R*LabelXYZ)r   r   r   r   z--regheader %szlabel template volumez
--identityzset R=I)r   r   r   z--invertmtxzInvert the registration matrix)r   r   g        g      ?z--fillthresh %gzthresh : between 0 and 1z--labvoxvol %fz%volume of each label point (def 1mm3)rn   fracz--proj %s %f %f %fzproject along surface normal)r   rI   r   z--subject %sz
subject idr   r   z	--hemi %szhemisphere to use lh or rhz	--surf %szuse surface instead of whitez--o %szoutput volume)r   r   r   z	--hits %sz)file with each frame is nhits for a labelz--label-stat %sz&map the label stats field into the volz--native-vox2rasz5use native vox2ras xform instead of  tkregister-styleN)rk   r   r   r   )rk   r   r   r   )rK   r+   )rk   r   r   r   )rk   r   r   r   )r   r   r   )r   r   r   )r   r   r   )rK   r+   )r$   r%   r&   r	   r   rk   r   r   r   r1   r   Ztemplate_filer   r   r   Z
invert_mtxrs   Zfill_threshr/   Zlabel_voxel_volumer.   r*   projr(   rK   r+   surfacevol_label_fileZlabel_hit_fileZmap_label_statZnative_vox2rasr2   r2   r2   r3   r     s   




r   c               @   s   e Zd ZedddZdS )Label2VolOutputSpecTzoutput volume)r   r   N)r$   r%   r&   r   r   r2   r2   r2   r3   r     s   r   c               @   s,   e Zd ZdZdZeZeZdd Z	dd Z
dS )	Label2Volau  Make a binary volume from a Freesurfer label

    Examples
    --------
    >>> binvol = Label2Vol(label_file='cortex.label', template_file='structural.nii', reg_file='register.dat', fill_thresh=0.5, vol_label_file='foo_out.nii')
    >>> binvol.cmdline
    'mri_label2vol --fillthresh 0.5 --label cortex.label --reg register.dat --temp structural.nii --o foo_out.nii'

    Zmri_label2volc             C   s   | j  j }| jj}t|sxJd
D ]B}tt| j|r"t| j|}t|trT|d }tj	j
|\}}q"W t| jjrxd}t|dtj dd}||d	< |S )Nrk   r   r   r   zaparc+aseg.mgzz_vol.nii.gzF)r   r   r   r   )rk   r   r   )r6   r7   r8   r   r   r   r   r   r9   r:   r   r   r   r<   )r=   r>   r?   keyr:   r   r   r2   r2   r3   r@     s    

zLabel2Vol._list_outputsc             C   s   |dkr| j  | S d S )Nr   )r@   )r=   rA   r2   r2   r3   rB     s    zLabel2Vol._gen_filenameN)r$   r%   r&   rC   rD   r   rE   r   r6   r@   rB   r2   r2   r2   r3   r     s   	r   c            	   @   s   e Zd Zejej dddddddZedddd	Zed
ddddZ	eddddZ
eddddZejdddZejdddZejdddZeeddddd
dd dZdS )!MS_LDAInputSpecz-lda %sTr    z pair of class labels to optimize)r   r   Zminlenmaxlensepr   z
-weight %sz.filename for the LDA weights (input or output))r   r   r   Fz	-synth %sz*filename for the synthesized output volume)r   r   r   r   z	-label %szfilename of the label volume)r   r   r   z-mask %sz!filename of the brain mask volumez	-shift %dz1shift all values equal to the given value to zero)r   r   z-conformzBConform the input volumes (brain mask typically already conformed)z-Wz7Use the weights from a previously generated weight file)r   z%szlist of input FLASH imagesr   )r   r   r^   r   r   Nr   )r$   r%   r&   r   r,   r0   Z
lda_labelsr   rc   vol_synth_filerk   rt   shiftr1   Zconformuse_weightsr	   Zimagesr2   r2   r2   r3   r     sF   

r   c               @   s$   e Zd ZedddZedddZdS )MS_LDAOutputSpecTr   )r   r   N)r$   r%   r&   r   rc   r   r2   r2   r2   r3   r   1  s   r   c                   sD   e Zd ZdZdZeZeZdd Z	dd Z
 fddZd	d
 Z  ZS )MS_LDAa  Perform LDA reduction on the intensity space of an arbitrary # of FLASH images

    Examples
    --------
    >>> grey_label = 2
    >>> white_label = 3
    >>> zero_value = 1
    >>> optimalWeights = MS_LDA(lda_labels=[grey_label, white_label],                                 label_file='label.mgz', weight_file='weights.txt',                                 shift=zero_value, vol_synth_file='synth_out.mgz',                                 conform=True, use_weights=True,                                 images=['FLASH1.mgz', 'FLASH2.mgz', 'FLASH3.mgz'])
    >>> optimalWeights.cmdline
    'mri_ms_LDA -conform -label label.mgz -lda 2 3 -shift 1 -W -synth synth_out.mgz -weight weights.txt FLASH1.mgz FLASH2.mgz FLASH3.mgz'

    Z
mri_ms_LDAc             C   st   | j  j }t| jjr.tjj| jj|d< ntjj| jj|d< t| jj	 s\| jj	dkrptjj| jj
|d< |S )Nr   Frc   )_outputsr7   r   r8   Zoutput_synthr9   r:   r   r   r   rc   )r=   r>   r2   r2   r3   r@   L  s    zMS_LDA._list_outputsc             C   s&   t jjt jj| jjs"tjdd S )Nz;MS_LDA: use_weights must accompany an existing weights file)r9   r:   r   r   r8   rc   r   Z
TraitError)r=   r2   r2   r3   _verify_weights_file_existsV  s    z"MS_LDA._verify_weights_file_existsc                s6   |dkr"| j jdkr| j  ndS tt| j|||S )Nr   Tr   )r8   r   r   rT   r   rY   )r=   rA   rZ   r[   )rW   r2   r3   rY   \  s
    
zMS_LDA._format_argc             C   s   d S )Nr2   )r=   rA   r2   r2   r3   rB   e  s    zMS_LDA._gen_filename)r$   r%   r&   rC   rD   r   rE   r   r6   r@   r   rY   rB   r\   r2   r2   )rW   r3   r   6  s   
	r   c               @   s   e Zd ZejddddddZejddddd	d
ZeddddZ	eddddZ
eddddZeddddZedddddZejddddZeddgdddddZejddddddZejd$d!Zd"S )%Label2LabelInputSpecr   r   z	--hemi %sTzInput hemisphere)r   r   r   rK   z--trgsubject %szTarget subject)rL   r   r   r   z&Implicit input <hemisphere>.sphere.reg)r   r   r   z!Implicit input <hemisphere>.whitez--srclabel %szSource label)r   r   r   r   z--srcsubject %szSource subject namez--trglabel %ssource_labelz%s_convertedFzTarget label)r   Zname_sourceZname_templateZ
hash_filesZkeep_extensionr   r   volumez--regmethod %szRegistration method)rL   r   r   z'If running as a node, set this to True.z+This will copy the input files to the node z
directory.)r   NzRIf running as a node, set this to True.This will copy the input files to the node z\If running as a node, set this to True.This will copy the input files to the node directory.)r$   r%   r&   r   r*   
hemisphererM   rK   r   
sphere_regrl   source_sphere_regsource_whiter   source_subjectr'   Zregistration_methodr1   rN   r2   r2   r2   r3   r   i  sD   r   c               @   s   e Zd ZedddZdS )Label2LabelOutputSpecTzOutput label)r   r   N)r$   r%   r&   r   r'   r2   r2   r2   r3   r    s   r  c                   s4   e Zd ZdZdZeZeZdd Z	 fddZ
  ZS )Label2LabelaY  
    Converts a label in one subject's space to a label
    in another subject's space using either talairach or spherical
    as an intermediate registration space.

    If a source mask is used, then the input label must have been
    created from a surface (ie, the vertex numbers are valid). The
    format can be anything supported by mri_convert or curv or paint.
    Vertices in the source label that do not meet threshold in the
    mask will be removed from the label.

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import Label2Label
    >>> l2l = Label2Label()
    >>> l2l.inputs.hemisphere = 'lh'
    >>> l2l.inputs.subject_id = '10335'
    >>> l2l.inputs.sphere_reg = 'lh.pial'
    >>> l2l.inputs.white = 'lh.pial'
    >>> l2l.inputs.source_subject = 'fsaverage'
    >>> l2l.inputs.source_label = 'lh-pial.stl'
    >>> l2l.inputs.source_white = 'lh.pial'
    >>> l2l.inputs.source_sphere_reg = 'lh.pial'
    >>> l2l.cmdline
    'mri_label2label --hemi lh --trglabel lh-pial_converted.stl --regmethod surface --srclabel lh-pial.stl --srcsubject fsaverage --trgsubject 10335'
    Zmri_label2labelc             C   s2   | j  j }tjj| jj| jjd| jj|d< |S )Nlabelr'   )	r   r7   r9   r:   r;   r8   rP   rK   r'   )r=   r>   r2   r2   r3   r@     s    zLabel2Label._list_outputsc                s   | j jrtj | j _d|kr(| j j|d< | j j}t| | j jddj| t| | j j	ddj| t| | j j
ddj|| j jd t| | j jddj|| j jd tjj| j j| j jd}tjj|stj| tt| jf |S )NrP   rQ   z{0}.sphere.regz	{0}.white)rK   r  )r8   rN   r9   r<   rP   r  r   r  formatrl   r  r  r  r:   r;   rK   isdirmakedirsrT   r  rU   )r=   r8   r+   	label_dir)rW   r2   r3   rU     s2    
zLabel2Label.run)r$   r%   r&   rC   rD   r   rE   r  r6   r@   rU   r\   r2   r2   )rW   r3   r    s   
r  c               @   s   e Zd ZejddddddZejddddd	d
ZejddddZ	ejddddZ
eddddZejdddZejdddZeddddZejddZdS )Label2AnnotInputSpecr   r   z	--hemi %sTzInput hemisphere)r   r   r   rK   z--s %szSubject name/ID)rL   r   r   r   z	--l %s...zList of input label filesz--a %sz Name of the annotation to createzimplicit {hemisphere}.orig)r   r   r   z--maxstatwinnerz$Keep label with highest 'stat' value)r   r   z--noverbosez+Turn off overlap and stat override messagesz	--ctab %szEFile that defines the structure names, their indices, and their color)r   r   r   z3copy implicit inputs and create a temp subjects_dir)r   N)r$   r%   r&   r   r*   r  rM   rK   r,   Z	in_labels	out_annotr   origr1   Zkeep_maxZverbose_offZcolor_tablerN   r2   r2   r2   r3   r    s.   

r  c               @   s   e Zd ZedddZdS )Label2AnnotOutputSpecTzOutput annotation file)r   r   N)r$   r%   r&   r   r'   r2   r2   r2   r3   r    s   r  c                   s4   e Zd ZdZdZeZeZ fddZ	dd Z
  ZS )Label2Annota  
    Converts a set of surface labels to an annotation file

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import Label2Annot
    >>> l2a = Label2Annot()
    >>> l2a.inputs.hemisphere = 'lh'
    >>> l2a.inputs.subject_id = '10335'
    >>> l2a.inputs.in_labels = ['lh.aparc.label']
    >>> l2a.inputs.orig = 'lh.pial'
    >>> l2a.inputs.out_annot = 'test'
    >>> l2a.cmdline
    'mris_label2annot --hemi lh --l lh.aparc.label --a test --s 10335'
    Zmris_label2annotc                s   | j jrFtj | j _d|kr(| j j|d< t| | j jddj| j jd tj	j
| j j| j jd}tj	j|sttj| tt| jf |S )NrP   rQ   z{0}.orig)rV   rR   r  )r8   rN   r9   r<   rP   r   r  r	  r  r:   r;   rK   r
  r  rT   r  rU   )r=   r8   r  )rW   r2   r3   rU   )  s    
zLabel2Annot.runc             C   sR   | j  j }tjjt| jjt| jjdt| jj	d t| jj
 d |d< |S )Nr  r   z.annotr'   )r   r7   r9   r:   r;   strr8   rP   rK   r  r  )r=   r>   r2   r2   r3   r@   <  s    

&zLabel2Annot._list_outputs)r$   r%   r&   rC   rD   r  rE   r  r6   rU   r@   r\   r2   r2   )rW   r3   r    s   r  c               @   s   e Zd Zedddd&ddZedddd'dd	Zedddd(ddZej	ddddd)ddZ
ejddd*ddZej	dddddddd+dd	ZejddddZejddd Zed!dd"d#Zejd$dd Zd%S ),SphericalAverageInputSpecz%sTFr   zOutput filename)r   r   r   r   r   r   zAverage subject)r   r   r   r   r   r   zInput surface file)r   r   r   r   r   r   r      zInput hemisphere)r   r   r   r      zFilename from the average subject directory.
Example: to use rh.entorhinal.label as the input label filename, set fname to 'rh.entorhinal'
and which to 'label'. The program will then search for
``<in_average>/label/rh.entorhinal.label``Zcoordsr  valsZcurvarea   zNo documentationz-o %szOutput subject id)r   r   r   z	-erode %dZUndocumented)r   r   z-orig %szOriginal surface filename)r   r   r   z-t %.1fNr   i)r$   r%   r&   r   r'   r   
in_averagein_surfr   r*   r  rM   r   whichrK   r0   r   in_origr/   	thresholdr2   r2   r2   r3   r  G  s6   r  c               @   s   e Zd ZedddZdS )SphericalAverageOutputSpecFzOutput label)r   r   N)r$   r%   r&   r   r'   r2   r2   r2   r3   r"  p  s   r"  c                   s<   e Zd ZdZdZeZeZ fddZ	dd Z
dd Z  ZS )	SphericalAveragea  
    This program will add a template into an average surface.

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import SphericalAverage
    >>> sphericalavg = SphericalAverage()
    >>> sphericalavg.inputs.out_file = 'test.out'
    >>> sphericalavg.inputs.in_average = '.'
    >>> sphericalavg.inputs.in_surf = 'lh.pial'
    >>> sphericalavg.inputs.hemisphere = 'lh'
    >>> sphericalavg.inputs.fname = 'lh.entorhinal'
    >>> sphericalavg.inputs.which = 'label'
    >>> sphericalavg.inputs.subject_id = '10335'
    >>> sphericalavg.inputs.erode = 2
    >>> sphericalavg.inputs.threshold = 5
    >>> sphericalavg.cmdline
    'mris_spherical_average -erode 2 -o 10335 -t 5.0 label lh.entorhinal lh pial . test.out'

    Zmris_spherical_averagec                sT   |dks|dkr@t jj|}xdD ]}|j|d}q"W |j| S tt| j|||S )Nr   r  lh.rh.r   )r$  r%  )r9   r:   rR   r   r   rT   r#  rY   )r=   rA   rZ   r[   rQ   item)rW   r2   r3   rY     s    

zSphericalAverage._format_argc             C   sj   |dkrNt | jjd }tjj| jj|}tjj|sJtjjtj	j
d}|S |dkrb| j | S d S d S )Nr  z.EC_averageZFREESURFER_HOMEr'   )r  r8   r  r9   r:   r;   rP   r
  r   environr7   r@   )r=   rA   Zavg_subjectZavg_directoryZfs_homer2   r2   r3   rB     s    zSphericalAverage._gen_filenamec             C   s   | j  j }t| jjr.tjj| jj|d< nhtjj| jj	| jj
d}t| jjrttjj| jj}|jddd }nt| jjd }tjj|||d< |S )Nr'   r  r   Z_exvivo_z.labelz.EC_exvivo_average.label)r   r7   r   r8   r'   r9   r:   r   r;   rP   rK   r  rR   r   r  r  )r=   r>   Zout_dirrR   r2   r2   r3   r@     s    zSphericalAverage._list_outputs)r$   r%   r&   rC   rD   r  rE   r"  r6   rY   rB   r@   r\   r2   r2   )rW   r3   r#  t  s   r#  )5rC   r9   Zutils.filemanipr   r   baser   r   r   r	   r
   r   r   r   r   utilsr   Z__docformat__r   r4   r5   rF   rO   r]   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  r"  r#  r2   r2   r2   r3   <module>   sV   $	S%!@ 6RE>H$ .I'HV'/32M$3)