3
d                @   s$  d Z ddlZddljZddlmZ ddlZddlZddlZ	ddl
mZ ddlmZmZ ddlmZmZ dd	lmZ dd
lmZmZmZmZmZmZmZmZmZ ddlmZmZm Z m!Z!m"Z" ddl#m$Z$ dZ%ej&dZ'e"j( j)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Z0G dd deZ1G dd deZ2G d d! d!eZ3G d"d# d#eZ4G d$d% d%eZ5G d&d' d'eZ6G d(d) d)eZ7G d*d+ d+eZ8G d,d- d-ej9Z:G d.d/ d/eZ;G d0d1 d1eZ<G d2d3 d3e<Z=G d4d5 d5eZ>G d6d7 d7eZ?G d8d9 d9eZ@G d:d; d;eZAG d<d= d=eZBG d>d? d?eZCG d@dA dAeZDG dBdC dCeZEG dDdE dEeZFG dFdG dGeZGG dHdI dIeZHG dJdK dKeZIG dLdM dMeZJG dNdO dOeZKG dPdQ dQeZLG dRdS dSeZMG dTdU dUeZNG dVdW dWeZOG dXdY dYeZPG dZd[ d[eZQG d\d] d]eZRG d^d_ d_eZSG d`da daeZTG dbdc dceZUG ddde deeZVG dfdg dgeZWG dhdi dieZXG djdk dkeZYG dldm dmeZZG dndo doe Z[G dpdq dqeZ\G drds dse!Z]G dtdu due Z^G dvdw dweZ_G dxdy dye!Z`G dzd{ d{e ZaG d|d} d}eZbG d~d de!ZcG dd deZdG dd deZeG dd deZfG dd deZgG dd deZhG dd deZiG dd deZjG dd deZkG dd deZlG dd deZmG dd deZnG dd deZodS )z?Provides interfaces to various commands provided by FreeSurfer
    N)glob)load   )loggingLooseVersion)fname_presuffixcheck_depends   )FreeSurferSource)	TraitedSpecFiletraits	DirectoryInputMultiPathOutputMultiPathCommandLineCommandLineInputSpec	isdefined   )	FSCommandFSTraitedSpecFSTraitedSpecOpenMPFSCommandOpenMPInfo)copy2subjdirZrestructuredtextznipype.interfacec               @   sH   e Zd ZedddddZedddddZejd	d
dZ	ejdddZ
dS )ParseDICOMDirInputSpecTz--d %szpath to siemens dicom directory)existsargstr	mandatorydesczdicominfo.txtz--o %sz!file to which results are written)r   
usedefaultr   z--sortbyrunzassign run numbers)r   r   z--summarizez#only print out info for run leadersN)__name__
__module____qualname__r   	dicom_dirr   dicom_info_filer   BoolZ	sortbyrunZ	summarize r'   r'   I/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/freesurfer/preprocess.pyr   (   s   r   c               @   s   e Zd ZedddZdS )ParseDICOMDirOutputSpecTz&text file containing dicom information)r   r   N)r!   r"   r#   r   r%   r'   r'   r'   r(   r)   ;   s   r)   c               @   s$   e Zd ZdZdZeZeZdd Z	dS )ParseDICOMDira  Uses mri_parse_sdcmdir to get information from dicom directories

    Examples
    --------

    >>> from nipype.interfaces.freesurfer import ParseDICOMDir
    >>> dcminfo = ParseDICOMDir()
    >>> dcminfo.inputs.dicom_dir = '.'
    >>> dcminfo.inputs.sortbyrun = True
    >>> dcminfo.inputs.summarize = True
    >>> dcminfo.cmdline
    'mri_parse_sdcmdir --d . --o dicominfo.txt --sortbyrun --summarize'

    Zmri_parse_sdcmdirc             C   s6   | j  j }t| jjr2tjjtj | jj|d< |S )Nr%   )	output_specgetr   inputsr%   ospathjoingetcwd)selfoutputsr'   r'   r(   _list_outputsS   s
    zParseDICOMDir._list_outputsN)
r!   r"   r#   __doc___cmdr   
input_specr)   r+   r4   r'   r'   r'   r(   r*   ?   s
   r*   c            
   @   s   e Zd ZedddddZedddZejejej	ej	ej	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Zej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d"S )&UnpackSDICOMDirInputSpecTz-src %szdirectory with the DICOM files)r   r   r   r   z-targ %sz3top directory into which the files will be unpacked)r   r   z-run %d %s %s %srun_infoconfig
seq_configz:runno subdir format name : spec unpacking rules on cmdline)r   r   xorr   z-cfg %szspecify unpacking rules in file)r   r   r   r<   r   z
-seqcfg %sz)specify unpacking rules based on sequenceZfsfastZgenericz-%sz(unpack to specified directory structuresz-noinfodumpzdo not create infodump filez-scanonly %sz.only scan the directory and put result in file)r   r   r   z-log %szexplicilty set log filez-nspmzeropad %dz+set frame number zero padding width for SPMz-no-unpackerrz%do not try to unpack runs with errorsN)r9   r:   r;   )r9   r:   r;   )r9   r:   r;   )r!   r"   r#   r   
source_dir
output_dirr   TupleIntStrr9   r   r:   r;   EnumZdir_structurer&   Zno_info_dumpZ	scan_onlyZlog_fileZspm_zeropadZno_unpack_errr'   r'   r'   r(   r8   \   sV   

r8   c               @   s   e Zd ZdZdZeZdS )UnpackSDICOMDira.  Use unpacksdcmdir to convert dicom files

    Call unpacksdcmdir -help from the command line to see more information on
    using this command.

    Examples
    --------

    >>> from nipype.interfaces.freesurfer import UnpackSDICOMDir
    >>> unpack = UnpackSDICOMDir()
    >>> unpack.inputs.source_dir = '.'
    >>> unpack.inputs.output_dir = '.'
    >>> unpack.inputs.run_info = (5, 'mprage', 'nii', 'struct')
    >>> unpack.inputs.dir_structure = 'generic'
    >>> unpack.cmdline
    'unpacksdcmdir -generic -targ . -run 5 mprage nii struct -src .'
    ZunpacksdcmdirN)r!   r"   r#   r5   r6   r8   r7   r'   r'   r'   r(   rC      s   rC   c            0   @   s  e Z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j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jdddZejdddZejdddZejejejejdddZejejejejdddZejejejejdddZddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMg0ZejedNdOdZejejdPdQdRdSZejdTdUdZejdVdWdZejdXdYdZejdZd[dZejejejejd\d]dZ ejd^d_dZ!ejd`dadZ"ejdbdcdZ#ejejejejddddZ$ejejejejdeddZ%ejejejejdfddZ&ejedgdhdZ'ejejejejdidRdZ(ejdjdkdldmdndodZ)ejdpdqdrdsdtdudvdZ*ejdwdxdZ+ejdydzdZ,ejd{d|dZ-ejd}d~dZ.ejdddZ/e0ddddZ1ejdddZ2e0ddddZ3e0ddddZ4ej5dddZ6ejejejejdddZ7ejejejejdddZ8ejdddZ9ejejejdddZ:ejdddZ;ejdddZ<ejdddZ=ddddddddddddddddddgZ>dddddddgZ?eje>e? dddZ@eje>dddZAejdddZBejejejejdddZCejdddZDe0ddddddZEe0dddddōZFejdddZGejdddZHejdddZIejdddZJejdddZKej5dddZLe0ddddZMeje>e? dddZNejdddZOejdddZPejdddZQejdddZRejdddZSejejejejdddZTejdddZUejdddZVe0ddddZWejdddZXejdddZYejdddZZe0ddddZ[ejdddZ\e0dddZ]e0ddddZ^ejdddZ_ejdddZ`ejdddZadS )MRIConvertInputSpecz--read_onlyzread the input volume)r   r   z
--no_writezdo not write outputz	--in_infozdisplay input infoz
--out_infozdisplay output infoz
--in_statszdisplay input statsz--out_statszdisplay output statsz--in_matrixzdisplay input matrixz--out_matrixzdisplay output matrixz--in_i_size %dzinput i sizez--in_j_size %dzinput j sizez--in_k_size %dzinput k sizez--force_ras_goodz(use default when orientation info absentz--in_i_direction %f %f %fz)<R direction> <A direction> <S direction>z--in_j_direction %f %f %fz--in_k_direction %f %f %fZLAIZLIAZALIZAILZILAZIALZLASZLSAZALSZASLZSLAZSALZLPIZLIPZPLIZPILZILPZIPLZLPSZLSPZPLSZPSLZSLPZSPLZRAIZRIAZARIZAIRZIRAZIARZRASZRSAZARSZASRZSRAZSARZRPIZRIPZPRIZPIRZIRPZIPRZRPSZRSPZPRSZPSRZSRPZSPRz--in_orientation %szspecify the input orientationr   z--in_center %sz,<R coordinate> <A coordinate> <S coordinate>)maxlenr   r   z--sphinxz!change orientation info to sphinxz--out_i_count %dzsome count ?? in i directionz--out_j_count %dzsome count ?? in j directionz--out_k_count %dzsome count ?? in k directionz-voxsize %f %f %fzX<size_x> <size_y> <size_z> specify the size (mm) - useful for upsampling or downsamplingz--out_i_size %dzoutput i sizez--out_j_size %dzoutput j sizez--out_k_size %dzoutput k sizez--out_i_direction %f %f %fz--out_j_direction %f %f %fz--out_k_direction %f %f %fz--out_orientation %szspecify the output orientationz--out_center %f %f %fZucharshortintfloatz--out_data_type %sz(output data type <uchar|short|int|float>ZinterpolateZweightednearestZsinccubicz--resample_type %szB<interpolate|weighted|nearest|sinc|cubic> (default is interpolate)z--no_scale 1zdont rescale values for CORz
--nochangez.don't change type of input to that of templatez-tr %dz
TR in msecz-te %dz
TE in msecz-ti %dz!TI in msec (note upper case flag)Tz--autoalign %sztext file with autoalign matrix)r   r   r   z--unwarp_gradient_nonlinearityzunwarp gradient nonlinearityz--apply_transform %szapply xfm filez--apply_inverse_transform %sz%apply inverse transformation xfm filez--devolvexfm %sz
subject idz--crop %d %d %dz/<x> <y> <z> crop to 256 around center (x, y, z)z--cropsize %d %d %dz(<dx> <dy> <dz> crop to size <dx, dy, dz>z--cutends %dz remove ncut slices from the endsz--slice-crop %d %dz,s_start s_end : keep slices s_start to s_endz--slice-reversez'reverse order of slices, update vox2rasz--slice-bias %fzapply half-cosine bias fieldz	--fwhm %fzsmooth input volume by fwhm mmcormghmgzmincanalyze	analyze4dspmafnibrikbshortbfloatZsdtoutlineZotlZgdfnifti1niiniigzgeZgelxZlxZximgZsiemensZdicomZsiemens_dicomz--in_type %szinput file typez--out_type %szoutput file typez--asciiz(save output as ascii col>row>slice>framez--reorder %d %d %dzolddim1 olddim2 olddim3z--invert_contrast %fz!threshold for inversting contrastr	   z--input_volume %szFile to read/convert)r   r   positionr   r   z--output_volume %sr   z'output filename or True to generate one)r   r[   genfiler   z	--conformzGconform to 1mm voxel size in coronal slice direction with 256^3 or morez--conform_minzconform to smallest sizez--conform_size %szconform to size_in_mmz--cw256zconfrom to dimensions of 256^3z--parse_onlyzparse input onlyz--subject_name %szsubject name ???z--reslice_like %szreslice output to match filez--template_type %sztemplate file typez--splitz/split output frames into separate output files.z
--frame %dzkeep only 0-based frame numberz--mid-framezkeep only the middle framez
--nskip %dzskip the first n framesz
--ndrop %dzdrop the last n framesz--fsubsample %d %d %dz6start delta end : frame subsampling (end = -1 for end)z
--scale %fzinput intensity scale factorz--out-scale %dzoutput intensity scale factorz--in_like %szinput looks likez--fill_parcellationzfill parcellationz--smooth_parcellationzsmooth parcellationz--zero_outlineszzero outlinesz--color_file %sz
color filez--no_translatez???z--status %sz status file for DICOM conversionz--sdcmlist %sz"list of DICOM files for conversionz--template_infozdump info about templatez
--crop_gdfzapply GDF croppingz--zero_ge_z_offsetzzero ge z offset ???N)br!   r"   r#   r   r&   Z	read_onlyZno_writeZin_infoZout_infoZin_statsZ	out_statsZ	in_matrixZ
out_matrixr@   Z	in_i_sizeZ	in_j_sizeZ	in_k_sizeZ	force_rasr?   FloatZin_i_dirZin_j_dirZin_k_dirZ_orientationsrB   Zin_orientationListZ	in_centerZsphinxZout_i_countZout_j_countZout_k_countZvox_sizeZ
out_i_sizeZ
out_j_sizeZ
out_k_sizeZ	out_i_dirZ	out_j_dirZ	out_k_dirZout_orientationZ
out_centerZout_datatypeZresample_typeZno_scaleZ	no_changetrteZtir   Zautoalign_matrixZunwarp_gradientZapply_transformZapply_inv_transformrA   Zdevolve_transformZcrop_centerZ	crop_sizeZcut_endsZ
slice_cropZslice_reverseZ
slice_biasZfwhm
_filetypesZ_infiletypesin_typeout_typeasciiZreorderZinvert_contrastin_fileout_fileZconformZconform_minZconform_sizeZcw256Z
parse_onlyZsubject_nameZreslice_liketemplate_typesplitframeZmidframeZskip_nZdrop_nZframe_subsampleZin_scaleZ	out_scaleZin_likeZfill_parcellationZsmooth_parcellationZzero_outlinesZ
color_fileZno_translateZstatus_fileZ	sdcm_listZtemplate_infoZcrop_gdfZzero_ge_z_offsetr'   r'   r'   r(   rD      s*  
















rD   c               @   s   e Zd ZeeddddZdS )MRIConvertOutputSpecT)r   zconverted output file)r   N)r!   r"   r#   r   r   rh   r'   r'   r'   r(   rl     s   rl   c                   sh   e Zd ZdZdZeZeZe	dddddddd	d	d	d
d	dddZ
 fddZdd Zdd Zdd Z  ZS )
MRIConverta  use fs mri_convert to manipulate files

    .. note::
       Adds niigz as an output type option

    Examples
    --------

    >>> mc = MRIConvert()
    >>> mc.inputs.in_file = 'structural.nii'
    >>> mc.inputs.out_file = 'outfile.mgz'
    >>> mc.inputs.out_type = 'mgz'
    >>> mc.cmdline
    'mri_convert --out_type mgz --input_volume structural.nii --output_volume outfile.mgz'

    mri_convertrK   rL   rM   ZmncrS   rT   imgrU   rX   znii.gz)rK   rL   rM   rN   rR   rS   rT   rQ   rO   rP   rU   rW   rX   rY   c                s.   |dkr|dkr|j d S tt| j|||S )Nrd   re   ri   rY   rX   )rd   re   ri   )r   superrm   _format_arg)r2   namespecvalue)	__class__r'   r(   rq      s    
zMRIConvert._format_argc             C   sX   | j j}t|sLt| j jr0d| j| j j  }nd}t| j jtj |dd}tj	j
|S )Nz_out.z_out.nii.gzF)newpathsuffixuse_ext)r-   rh   r   re   filemapr   rg   r.   r1   r/   abspath)r2   outfilerw   r'   r'   r(   _get_outfilename&  s    zMRIConvert._get_outfilenamec       
      C   s|  | j  j }| j }t| jjr| jjrt| jjj}t	|dkrHd}n|d }|j
drn|jdd }d}nH|j
dr|jdd }d}n*dj|jdd d }d|jdd  }g }x(td|D ]}|j|d|  |  qW t| jjrp| jjdkrpt| jjj}t	|dkr"d}n|d }td
g }| j }x,t|D ] }	|jt|d|	d  d qHW |}||d< |S )Nr   r   z.mgzr   z.nii.gz.z%04drQ   rO   zGNot taking frame manipulations into account- please warn the developersz%03d)rw   rh   r^   r^   r^   )rQ   rO   r^   )r+   r,   r|   r   r-   rj   r   rg   shapelenendswithr0   rangeappendre   	Exceptionr   )
r2   r3   r{   sizetpZstemextidxoutfilesir'   r'   r(   r4   2  sB    

 zMRIConvert._list_outputsc             C   s   |dkr| j  S d S )Nrh   )r|   )r2   rr   r'   r'   r(   _gen_filename[  s    zMRIConvert._gen_filename)r!   r"   r#   r5   r6   rD   r7   rl   r+   dictry   rq   r|   r4   r   __classcell__r'   r'   )ru   r(   rm     s.   )rm   c               @   s   e Zd ZeddddZedddZejddddZej	d	d
Z
ejejejejdd
ZejdejdddZedddZejejdgddZejdgddZdS )DICOMConvertInputSpecTz1dicom directory from which to convert dicom files)r   r   r   z2directory in which subject directories are created)r   r   zS.%04dz#template for subject directory name)r    r   z*subject identifier to insert into template)r   z&defines the output fields of interfacerY   z(defines the type of output file producedz:File containing summary information from mri_parse_sdcmdir)r   r   
dicom_infoz-list of pulse sequence names to be converted.)requiresr   z(ignore volumes containing a single sliceN)r!   r"   r#   r   r$   base_output_dirr   rA   subject_dir_templateZAny
subject_idr`   r?   Zfile_mappingrB   rD   rc   re   r   r   seq_listr&   ignore_single_slicer'   r'   r'   r(   r   a  s2   

r   c               @   sD   e Zd ZdZdZeZdd Zdd Zdd Z	d	d
 Z
edd ZdS )DICOMConverta4  use fs mri_convert to convert dicom files

    Examples
    --------

    >>> from nipype.interfaces.freesurfer import DICOMConvert
    >>> cvt = DICOMConvert()
    >>> cvt.inputs.dicom_dir = 'dicomdir'
    >>> cvt.inputs.file_mapping = [('nifti', '*.nii'), ('info', 'dicom*.txt'), ('dti', '*dti.bv*')]

    rn   c             C   s   t tjjtjj| jjdS )z?validate fsl bet options
        if set to None ignore
        z*-1.dcm)r   r.   r/   rz   r0   r-   r$   )r2   r'   r'   r(   _get_dicomfiles  s    zDICOMConvert._get_dicomfilesc             C   s   | j j}t|s:tjj| j d \}}t|jdd }t| j jrR| j j| }| j j	}t|sntjj
d}tjj
tjj||}|S )zreturns output directoryr   -r}   )r-   r   r   r.   r/   rj   r   rG   r   r   rz   r0   )r2   Zsubjidr/   fnamebasediroutdirr'   r'   r(   _get_outdir  s    zDICOMConvert._get_outdirc                s   t j| jjtd}g }x|D ] | jjr| jjrnt d dkrt fdd| jjD r|j	t d  qt fdd| jjD r|j	t d  q|j	t d  qW |S )zReturns list of dicom series that should be converted.

        Requires a dicom info summary file generated by ``DicomDirInfo``

        )Zdtype   r   c                s   g | ]} d  j |qS )   )
startswith).0sn)sr'   r(   
<listcomp>  s    z*DICOMConvert._get_runs.<locals>.<listcomp>r	   c                s   g | ]} d  j |qS )r   )r   )r   r   )r   r'   r(   r     s    )
npZ
genfromtxtr-   r   objectr   r   rG   anyr   )r2   seqrunsr'   )r   r(   	_get_runs  s    
zDICOMConvert._get_runsc                s   i  x| j  D ]x}tjj|\}}tjj|\}}|jd}t|d }tj| jj	 }tjj
|dj
d|d |f |f}	||	f |< qW | jjr fdd| j D }
n fddt j D }
|
S )	z%Returns list of files to be convertedr   r   r}   z%s-%02dr   c                s   g | ]} | qS r'   r'   )r   r)ry   r'   r(   r     s    z.DICOMConvert._get_filelist.<locals>.<listcomp>c                s   g | ]} | qS r'   r'   )r   r   )ry   r'   r(   r     s    )r   r.   r/   rj   splitextrG   rm   ry   r-   re   r0   r   r   listkeys)r2   r   fheadr   r   Z	filepartsZrunnore   r{   filesr'   )ry   r(   _get_filelist  s    
zDICOMConvert._get_filelistc       	      C   s   | j   | j }g }tjj|s@dtjtj|f }|j	|g tjj
|d}tjj|svd| jj|f }|j	|g | j|}xF|D ]>\}}tjj|sd| j| j|tjj
||f }|j	|g qW dj
|S )zZ`command` plus any arguments (args)
        validates arguments and generates command linez$%s -c "import os; os.makedirs('%s')"zshortinfo.txtzdcmdir-info-mgh %s > %sz
%s%s %s %sz; )Z_check_mandatory_inputsr   r.   r/   r   opbasenamesys
executableextendr0   r-   r$   r   Z_cmd_prefixcmd)	r2   r   r   ZcmdstrZinfofiler   infiler{   Z
single_cmdr'   r'   r(   cmdline  s,    

zDICOMConvert.cmdlineN)r!   r"   r#   r5   r6   r   r7   r   r   r   r   propertyr   r'   r'   r'   r(   r     s   r   c               @   sJ   e Zd ZeddddddZeddddd	Zejejejejd
dddZ	dS )ResampleInputSpecTz-i %szfile to resampler	   )r   r   r   r   r[   z-o %szoutput filenamer   )r   r   r\   r[   z-vs %.2f %.2f %.2fztriplet of output voxel sizes)r   r   r   Nr]   r^   )
r!   r"   r#   r   rg   resampled_filer   r?   r_   Z
voxel_sizer'   r'   r'   r(   r     s   r   c               @   s   e Zd ZedddZdS )ResampleOutputSpecTzoutput filename)r   r   N)r!   r"   r#   r   r   r'   r'   r'   r(   r     s   r   c               @   s4   e Zd ZdZdZeZeZdd Z	dd Z
dd Zd	S )
Resamplea  Use FreeSurfer mri_convert to up or down-sample image files

    Examples
    --------

    >>> from nipype.interfaces import freesurfer
    >>> resampler = freesurfer.Resample()
    >>> resampler.inputs.in_file = 'structural.nii'
    >>> resampler.inputs.resampled_file = 'resampled.nii'
    >>> resampler.inputs.voxel_size = (2.1, 2.1, 2.1)
    >>> resampler.cmdline
    'mri_convert -vs 2.10 2.10 2.10 -i structural.nii -o resampled.nii'

    rn   c             C   s0   t | jjr| jj}nt| jjtj dd}|S )NZ	_resample)rv   rw   )r   r-   r   r   rg   r.   r1   )r2   r{   r'   r'   r(   r|     s
    
zResample._get_outfilenamec             C   s   | j  j }| j |d< |S )Nr   )r+   r,   r|   )r2   r3   r'   r'   r(   r4   &  s    zResample._list_outputsc             C   s   |dkr| j  S d S )Nr   )r|   )r2   rr   r'   r'   r(   r   +  s    zResample._gen_filenameN)r!   r"   r#   r5   r6   r   r7   r   r+   r|   r4   r   r'   r'   r'   r(   r   	  s   	r   c               @   s"  e Zd ZejdddddZejdddd	d
ddddddddddddddZejdddddZe	e
ddddd Ze
dd!d"d#d$Ze
dd%d"d&d$Zejd'd"d(gd)d*Zejd+d"d,gd-d*Zejd.d/d Zejd0d1d Zejd2d3d4d5Zejd6d7d Zejd8d9d Zejd:d;d Zejd<d3d=d5Zeje
ddej d>d3d?d5Ze
dd@dAdBZejdCdDdEdFdGd ZeddHdIdJddKZe	ejdLdMd ZejdNdOgdPZ ejdQdOgdPZ!ejdRdOgdPZ"ejdSdOgdPZ#ejdTdOgdPZ$ejdUdOgdPZ%ejdVdOgdPZ&ejdWdOgdPZ'ejdXdOgdPZ(ejdYdOgdPZ)ejdZdOgdPZ*ejd[dOgdPZ+ejd\dOgdPZ,ejd]dOgdPZ-ejd^dOgdPZ.ejd_dOgdPZ/ejd`dOgdPZ0ejdadOgdPZ1ejdbdOgdPZ2ejdcdOgdPZ3ejdddOgdPZ4ejdedOgdPZ5ejdfdOgdPZ6ejdgdOgdPZ7ejdhdOgdPZ8ejdidOgdPZ9djS )kReconAllInputSpecZ	recon_allz
-subjid %szsubject nameT)r   r   r    all
autorecon1
autorecon2zautorecon2-volonlyzautorecon2-perhemizautorecon2-inflate1zautorecon2-cpzautorecon2-wm
autorecon3zautorecon3-T2pialzautorecon-pialzautorecon-hemiZlocalGIZqcachez-%szprocess directiver   )r   r   r    r[   lhrhzhemisphere to processz-hemi %s)r   r   )r   z-i %s...zname of T1 file to process)r   r   z-T2 %sz5.3.0z"Convert T2 image to orig directory)r   r   min_verr   z	-FLAIR %sz%Convert FLAIR image to orig directoryz-T2pial	use_FLAIRz'Use T2 image to refine the pial surface)r   r   r<   r   z
-FLAIRpialuse_T2z*Use FLAIR image to refine the pial surfacez
-openmp %dz'Number of processors to use in parallelz	-parallelzEnable parallel executionz-hiresz6.0.0z0Conform to minimum voxel size (for voxels < 1mm))r   r   r   z-mpragezRAssume scan parameters are MGH MP-RAGE protocol, which produces darker gray matterz-bigventriclesz,For use in subjects with enlarged ventriclesz-brainstem-structureszSegment brainstem structuresz-hippocampal-subfields-T1z1segment hippocampal subfields using input T1 scanz-hippocampal-subfields-T2 %s %szmsegment hippocampal subfields using T2 scan, identified by ID (may be combined with hippocampal_subfields_T1)z
-expert %sz Set parameters using expert file)r   r   r   Zuseclean	overwritez	-xopts-%sz5Use, delete or overwrite existing expert options filez-sd %sFzpath to subjects directory)r   r   
hash_filesr   r\   z%szadditional parametersz#Flags to pass to talairach commandsexpert)r   r<   z'Flags to pass to mri_normalize commandsz'Flags to pass to mri_watershed commandsz)Flags to pass to mri_em_register commandsz*Flags to pass to mri_ca_normalize commandsz)Flags to pass to mri_ca_register commandsz)Flags to pass to mri_remove_neck commandsz&Flags to pass to mri_ca_label commandsz&Flags to pass to mri_segstats commandsz"Flags to pass to mri_mask commandsz%Flags to pass to mri_segment commandsz/Flags to pass to mri_edit_wm_with_aseg commandsz%Flags to pass to mri_pretess commandsz"Flags to pass to mri_fill commandsz(Flags to pass to mri_tessellate commandsz$Flags to pass to mri_smooth commandsz%Flags to pass to mri_inflate commandsz%Flags to pass to mris_sphere commandsz+Flags to pass to mris_fix_topology commandsz,Flags to pass to mris_make_surfaces commandsz'Flags to pass to mris_surf2vol commandsz'Flags to pass to mris_register commandsz%Flags to pass to mrisp_paint commandsz'Flags to pass to mris_ca_label commandsz/Flags to pass to mris_anatomical_stats commandsz(Flags to pass to mri_aparc2aseg commandsN):r!   r"   r#   r   rA   r   rB   	directivehemir   r   T1_filesZT2_fileZ
FLAIR_filer&   r   r   r@   ZopenmpparallelZhiresZmprageZbig_ventriclesZ	brainstemhippocampal_subfields_T1r?   hippocampal_subfields_T2r   xoptsr   subjects_dirflags	talairachmri_normalizemri_watershedmri_em_registermri_ca_normalizemri_ca_registermri_remove_neckmri_ca_labelmri_segstatsmri_maskmri_segmentmri_edit_wm_with_asegmri_pretessmri_fillmri_tessellatemris_smoothmris_inflatemris_spheremris_fix_topologymris_make_surfacesmris_surf2volmris_registermrisp_paintmris_ca_labelmris_anatomical_statsmri_aparc2asegr'   r'   r'   r(   r   1  s
  

r   c               @   s$   e Zd ZedddZejddZdS )ReconAllOutputSpecTzFreesurfer subjects directory.)r   r   z&Subject name for whom to retrieve data)r   N)r!   r"   r#   r   r   r   rA   r   r'   r'   r'   r(   r     s   r   c                   s  e Zd ZdZdZddgZeZeZ	dZ
dZddd	gg fd
dddgg fddgg fddgg fddddgg fgZej edk r2ddgg fddgg fddgg fdddd gg fd!d"gg fd#d$gg fd%d&d'd(gg fd)d*gg fd+d,gg fd-d.d/d0gg fd1d2gg fgZd3d4gg fd5d6gg fd7d8gg fd9d:gg fd;d<gg fd=d>d?d@dAgg fdBdCgg fdDdEdFdGdHgg fdIdJgg fg	ZdKdLgg fdMdNgg fdOdPgg fdQdRgg fdSdTgg fdUdVdWdXdYgg fdZd[gg fd\d]gg fd^d_gg fd`dagg fdbdcgg fdddagg fdedfgg fgZdgdhdidjgg fdkdlgg fdmdndogg fdpdqdrgg fdsdtdugg fgZnej edvk rddgg fddgg fddgg fd%d&d'd(gg fd)d*gg fd+d,gg fd-d.d/d0gg fd1d2gg fgZd3d4gg fd5d6gg fd7d8gg fd9d:gg fd;d<gg fd=dwd?d@dAgg fdBdCgg fdDdEdFgg fdxdydzdGdHgg fdIdJgg fg
ZdKdLgg fdMdNgg fdOdPgg fdQdRgg fdSdTgg fdUdVdWdXdYd>gg fd\d]gg fd^d_gg fd`dagg fdbd{gg fddd|gg fdZd[gg fgZdgdhdidjgg fd}d~gg fdmdndodgg fdd(gdngfdkdlgg fdpdqdrgg fdsdddfdgg fgZnddgg fddgg fddgg fd%d&d'dgg fd)d*gg fd+d,gg fd-d.d/d0gg fd1d2gg fgZd3d4gg fd5d6gg fd7d8gg fd9d:gg fd;dEd<gg fd=dwd?d@dAgg fdBdCgg fdDdEdFgg fdxdydzdGdHgg fdIdJgg fg
ZdKdLgg fdMdNgg fdOdPgg fdQdRgg fdSdTgg fdUdVdWdXdYd>gg fd\d]gg fd^d_gg fd`dagg fdbd{gg fddd|gg fdZd[dgg fgZdgdhdidjgg fd}d~gg fdmdndodgg fdd(gdngfdkdlgg fdpdqdrgg fdsdddfdddgg fgZdd eD Zdd eD Zee Zdd eD Zdd eD Zee Zee Zee Zee e Zd
dddddddddddddddddddddddddgZdd Zdd Zdd Z dd Z! fddZ"e# fddZ$dd Z%dd Z&e#dd Z'  Z(S )ReconAlla  Uses recon-all to generate surfaces and parcellations of structural data
    from anatomical images of a subject.

    Examples
    --------

    >>> from nipype.interfaces.freesurfer import ReconAll
    >>> reconall = ReconAll()
    >>> reconall.inputs.subject_id = 'foo'
    >>> reconall.inputs.directive = 'all'
    >>> reconall.inputs.subjects_dir = '.'
    >>> reconall.inputs.T1_files = 'structural.nii'
    >>> reconall.cmdline
    'recon-all -all -i structural.nii -subjid foo -sd .'
    >>> reconall.inputs.flags = "-qcache"
    >>> reconall.cmdline
    'recon-all -all -i structural.nii -qcache -subjid foo -sd .'
    >>> reconall.inputs.flags = ["-cw256", "-qcache"]
    >>> reconall.cmdline
    'recon-all -all -i structural.nii -cw256 -qcache -subjid foo -sd .'

    Hemisphere may be specified regardless of directive:

    >>> reconall.inputs.flags = []
    >>> reconall.inputs.hemi = 'lh'
    >>> reconall.cmdline
    'recon-all -all -i structural.nii -hemi lh -subjid foo -sd .'

    ``-autorecon-hemi`` uses the ``-hemi`` input to specify the hemisphere
    to operate upon:

    >>> reconall.inputs.directive = 'autorecon-hemi'
    >>> reconall.cmdline
    'recon-all -autorecon-hemi lh -i structural.nii -subjid foo -sd .'

    Hippocampal subfields can accept T1 and T2 images:

    >>> reconall_subfields = ReconAll()
    >>> reconall_subfields.inputs.subject_id = 'foo'
    >>> reconall_subfields.inputs.directive = 'all'
    >>> reconall_subfields.inputs.subjects_dir = '.'
    >>> reconall_subfields.inputs.T1_files = 'structural.nii'
    >>> reconall_subfields.inputs.hippocampal_subfields_T1 = True
    >>> reconall_subfields.cmdline
    'recon-all -all -i structural.nii -hippocampal-subfields-T1 -subjid foo -sd .'
    >>> reconall_subfields.inputs.hippocampal_subfields_T2 = (
    ... 'structural.nii', 'test')
    >>> reconall_subfields.cmdline
    'recon-all -all -i structural.nii -hippocampal-subfields-T1T2 structural.nii test -subjid foo -sd .'
    >>> reconall_subfields.inputs.hippocampal_subfields_T1 = False
    >>> reconall_subfields.cmdline
    'recon-all -all -i structural.nii -hippocampal-subfields-T2 structural.nii test -subjid foo -sd .'
    z	recon-alllocZaltkeyTFZ	motioncorzmri/rawavg.mgzzmri/orig.mgzr   zmri/orig_nu.mgzz!mri/transforms/talairach.auto.xfmzmri/transforms/talairach.xfmZnuintensitycorz
mri/nu.mgzZnormalizationz
mri/T1.mgzZ
skullstripz'mri/transforms/talairach_with_skull.ltazmri/brainmask.auto.mgzzmri/brainmask.mgzz6.0.0Zgcaregzmri/transforms/talairach.ltaZcanormzmri/norm.mgzZcaregzmri/transforms/talairach.m3zZcareginvz&mri/transforms/talairach.m3z.inv.x.mgzz&mri/transforms/talairach.m3z.inv.y.mgzz&mri/transforms/talairach.m3z.inv.z.mgzZrmneckzmri/nu_noneck.mgzz	skull-ltaz)mri/transforms/talairach_with_skull_2.ltaZcalabelzmri/aseg.auto_noCCseg.mgzzmri/aseg.auto.mgzzmri/aseg.mgzZnormalization2zmri/brain.mgzZmaskbfszmri/brain.finalsurfs.mgzsegmentationzmri/wm.seg.mgzzmri/wm.asegedit.mgzz
mri/wm.mgzfillzmri/filled.mgzZ
tessellatezsurf/lh.orig.nofixZsmooth1zsurf/lh.smoothwm.nofixZinflate1zsurf/lh.inflated.nofixZqspherezsurf/lh.qsphere.nofixZfixzsurf/lh.origZwhitezsurf/lh.whitezsurf/lh.curvzsurf/lh.areazlabel/lh.cortex.labelZsmooth2zsurf/lh.smoothwmZinflate2zsurf/lh.inflatedzsurf/lh.sulczsurf/lh.inflated.Hzsurf/lh.inflated.KZ	curvstatszstats/lh.curv.statsZspherezsurf/lh.sphereZsurfregzsurf/lh.sphere.regZjacobian_whitezsurf/lh.jacobian_whiteZavgcurvzsurf/lh.avg_curvZcortparczlabel/lh.aparc.annotZpialzsurf/lh.pialzsurf/lh.curv.pialzsurf/lh.area.pialzsurf/lh.thicknessZ
pctsurfconzsurf/lh.w-g.pct.mghZ	parcstatszstats/lh.aparc.statsZ	cortparc2zlabel/lh.aparc.a2009s.annotZ
parcstats2zstats/lh.aparc.a2009s.statsZ	cortparc3zlabel/lh.aparc.DKTatlas40.annotZ
parcstats3zlabel-exvivo-ecz label/lh.entorhinal_exvivo.labelZ
cortribbonzmri/lh.ribbon.mgzzmri/rh.ribbon.mgzzmri/ribbon.mgzZsegstatszstats/aseg.statsZ
aparc2asegzmri/aparc+aseg.mgzzmri/aparc.a2009s+aseg.mgzZwmparczmri/wmparc.mgzzstats/wmparc.statsZbalabelszlabel/BA.ctabzlabel/BA.thresh.ctabz7.0.0zsurf/lh.white.preaparcZcurvHKzsurf/lh.white.Hzsurf/lh.white.Kzlabel/lh.aparc.DKTatlas.annotzstats/lh.aparc.DKTatlas.statsZhyporelabelzmri/aseg.presurf.hypos.mgzzmri/aparc.DKTatlas+aseg.mgzZ	apas2asegzlabel/BA_exvivo.ctabzlabel/BA_exvivo.thresh.ctabz label/rh.entorhinal_exvivo.labelzmri/aseg.presurf.mgzzstats/lh.w-g.pct.statsz label/lh.perirhinal_exvivo.labelz label/rh.perirhinal_exvivo.labelc             C   s&   g | ]\}}}|d d |D |fqS )c             S   s   g | ]}|j d dqS )r   r   )replace)r   outr'   r'   r(   r     s    zReconAll.<listcomp>.<listcomp>r'   )r   stepoutsinsr'   r'   r(   r     s   zReconAll.<listcomp>c             C   s&   g | ]\}}}|d d |D |fqS )c             S   s&   g | ]}||j d dfD ]}|qqS )r   r   )r   )r   r   ofr'   r'   r(   r     s    zReconAll.<listcomp>.<listcomp>r'   )r   r   r   r   r'   r'   r(   r     s   c             C   s&   g | ]\}}}|d d |D |fqS )c             S   s   g | ]}|j d dqS )r   r   )r   )r   r   r'   r'   r(   r     s    zReconAll.<listcomp>.<listcomp>r'   )r   r   r   r   r'   r'   r(   r     s   c             C   s&   g | ]\}}}|d d |D |fqS )c             S   s&   g | ]}||j d dfD ]}|qqS )r   r   )r   )r   r   r   r'   r'   r(   r     s    zReconAll.<listcomp>.<listcomp>r'   )r   r   r   r   r'   r'   r(   r     s   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   c             C   s   t j S )N)r.   r1   )r2   r'   r'   r(   _gen_subjects_dir  s    zReconAll._gen_subjects_dirc             C   s   |dkr| j  S d S )Nr   )r   )r2   rr   r'   r'   r(   r     s    zReconAll._gen_filenamec             C   sx   t | jjr| jj}n| j }t | jjr4| jj}nd}| j j }|jt| jj	||dj
  | jj	|d< ||d< |S )zR
        See io.FreeSurferSource.outputs for the list of outputs returned
        Zboth)r   r   r   r   r   )r   r-   r   r   r   Z_outputsr,   updater
   r   r4   )r2   r   r   r3   r'   r'   r(   r4     s    

zReconAll._list_outputsc             C   s<   | j j}t|s| j }tjjtjj|| j jdr8dS dS )NmriTF)	r-   r   r   r   r.   r/   isdirr0   r   )r2   r   r'   r'   r(   _is_resuming  s    zReconAll._is_resumingc                s   |dkr| j  rd S |dkr,t| jjr,d S t|dkt| jjoF| jjfrb|jjdd}|| S |dkr|dkrt| jjst	d|d	| jj 7 }t|d
kt| jj
o| jj
dkfrd S tt| j|||S )Nr   r   r   ZT2ZT1T2r   zautorecon-hemiz8Directive 'autorecon-hemi' requires hemi input to be set r   )r   r   r-   r   r   r   r   r   r   
ValueErrorr   rp   r   rq   )r2   rr   Z
trait_specrt   r   )ru   r'   r(   rq     s.    

zReconAll._format_argc                s  t t| j}|| j 7 }| j s$|S | jj}t|s<| j }| jj	}t|sRg }n|dkrb| j
}n|dkrr| j}n|dkr| j}n|jdrt| jjr| jjdkr| j| j }q| j| j }n| j}n<|dkr| jjdkr| j}n| j}n|dk r| j}n| j}d}g }x|D ]\}}}	d	j|}
d
j|}||kr@qn|
|krRd}qtjj|| jj t fdd|D  fdd|	D r|j| nd}qW |r| j rtjd dS |ddj| 7 }tjd| |S )Nr   zautorecon2-volonlyzautorecon2-perhemir   r   zautorecon-hemir   Tz-{}z-no{}Fc                s   g | ]}t jj |qS r'   )r.   r/   r0   )r   r   )subj_dirr'   r(   r   _  s    z$ReconAll.cmdline.<locals>.<listcomp>c                s   g | ]}t jj |qS r'   )r.   r/   r0   )r   r   )r  r'   r(   r   `  s    z recon-all complete : Not runningzecho recon-all: nothing to dor   zresume recon-all : %s) rp   r   r   _prep_expert_filer   r-   r   r   r   r   _autorecon1_steps_autorecon2_volonly_steps_autorecon2_perhemi_stepsr   r   _autorecon2_lh_steps_autorecon2_rh_steps_autorecon2_steps_autorecon_lh_steps_autorecon_rh_steps_autorecon3_steps_stepsformatr.   r/   r0   r   r   r   	force_runifloggerinfo)r2   r   r   r   ZstepsZno_runr   r   r   infilesflagZnoflag)ru   )r  r(   r   (  sf    







zReconAll.cmdlinec          	   C   s   t | jjrdS g }x4| jD ]*}t| j|}t |r|jdj|| qW |g krVdS dj|}t | jj r~| j	 |kr~dS t
jjd}t|d}|j| W d Q R X dj|S )N z{} {}
z -xopts-usezexpert.optswz -expert {})r   r-   r   	_binariesgetattrr   r  r0   r   _get_expert_filer.   r/   rz   openwrite)r2   linesbinaryargscontentsZexpert_fnamefobjr'   r'   r(   r  n  s     
zReconAll._prep_expert_filec          	   C   sb   t | jjr| jj}n| j }tjj|| jjdd}tjj|sDdS t	|d
}|j
 S Q R X d S )Nscriptszexpert-optionsr  r   )r   r-   r   r   r.   r/   r0   r   r   r  read)r2   r   Z
xopts_filer  r'   r'   r(   r    s    
zReconAll._get_expert_filec             C   s   t j }|tdkr|jS d S )Nz0.0.0)r   looseversionr   vstring)r2   verr'   r'   r(   version  s    zReconAll.version))r!   r"   r#   r5   r6   Z_additional_metadatar   r7   r   r+   Z_can_resumer  r  r   r!  r   r  r  Z_autorecon3_lh_stepsZ_autorecon3_added_stepsr  r  r  Z_autorecon3_rh_stepsZ_autorecon3_perhemi_stepsr  r	  r
  r  r  r   r   r4   r   rq   r   r   r  r  r$  r   r'   r'   )ru   r(   r     s.  5







































































!Fr   c            	   @   sB  e Zd ZejddddZedddddZejd	d
ddddgddZ	eddddgddZ
ejddddddddZeddddZejddgdd Zejd!d"g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.d/d0d)Zejd1d2d)Zejejed3d4d)Zejejed5d6d7d8Zejejed9d:d)Zejejed;d<d)Zd=S )>BBRegisterInputSpecz--s %szfreesurfer subject idT)r   r   r   z--mov %szsource file to be registeredF)r   r   r   copyfilerQ   fslheaderz	--init-%sinit_reg_filez(initialize registration spm, fsl, header)r   r   r<   r   z--init-reg %szexisting registration fileinit)r   r   r   r<   r   t1t2ZboldZdtiz--%szcontrast type of imagez--int %sz/Intermediate image, e.g. in case of partial FOV)r   r   r   z
--frame %dreg_middle_framez&0-based frame index for 4D source file)r   r<   r   z--mid-frame	reg_framez'Register middle frame of 4D source filez--reg %szoutput registration file)r   r   r\   z	--spm-niiz/force use of nifti rather than analyze with SPM)r   r   z
--epi-maskz%mask out B0 regions in stages 1 and 2   	   r   z--%dz&number of transform degrees of freedomz--fsl-dof %dz1degrees of freedom for initial registration (FSL)z--fslmat %sz3write the transformation matrix in FSL FLIRT formatz--lta %sz5.2.0z-write the transformation matrix in LTA format)r   r   r   z--o %sz0output warped sourcefile either True or filenamez--initcost %sz%output initial registration cost fileN)r!   r"   r#   r   rA   r   r   source_filerB   r*  r)  Zcontrast_typeZintermediate_filer@   r.  r&   r-  out_reg_fileZ	spm_niftiZepi_maskZdofZfsldofEitherout_fsl_fileout_lta_fileregistered_fileinit_cost_filer'   r'   r'   r(   r%    s   


r%  c               @   s<   e Zd Zejddddddddgd	d
	ZeddddgdZdS )BBRegisterInputSpec6ZcoregZrrrQ   r'  r(  bestz	--init-%sr)  z;initialize registration with mri_coreg, spm, fsl, or header)r   r<   r   Tz--init-reg %szexisting registration filer*  )r   r   r   r<   N)r!   r"   r#   r   rB   r*  r   r)  r'   r'   r'   r(   r8    s   r8  c               @   sT   e Zd ZedddZedddZedddZedddZedddZedddZ	d	S )
BBRegisterOutputSpecTzOutput registration file)r   r   z$Output FLIRT-style registration filez"Output LTA-style registration filez%Output registration minimum cost filez%Output initial registration cost filez$Registered and resampled source fileN)
r!   r"   r#   r   r2  r4  r5  min_cost_filer7  r6  r'   r'   r'   r(   r:  
  s   r:  c                   sf   e Zd ZdZdZedej   k o.edk n  r:eZ	ne
Z	eZdd Z fddZd	d
 Z  ZS )
BBRegisteraq  Use FreeSurfer bbregister to register a volume to the Freesurfer anatomical.

    This program performs within-subject, cross-modal registration using a
    boundary-based cost function. It is required that you have an anatomical
    scan of the subject that has already been recon-all-ed using freesurfer.

    Examples
    --------

    >>> from nipype.interfaces.freesurfer import BBRegister
    >>> bbreg = BBRegister(subject_id='me', source_file='structural.nii', init='header', contrast_type='t2')
    >>> bbreg.cmdline
    'bbregister --t2 --init-header --reg structural_bbreg_me.dat --mov structural.nii --s me'

    Z
bbregisterz0.0.0z6.0.0c             C   st  | j  j }| j}t|jr.tj|j|d< n$|jrRd|j }t	|j|dd|d< t|j
rt|j
tr|t	|jdd|d< ntj|j
|d< t|jrt|jtrd|j }t	|j|dd}||d	< ntj|j|d	< t|jr$t|jtrd
|j }t	|j|dd}||d< ntj|j|d< t|jr`t|jtrP|d d |d< ntj|j|d< |d d |d< |S )Nr2  z_bbreg_%s.datF)rw   rx   Z_bbreg)rw   r6  z_bbreg_%s.ltar5  z_bbreg_%s.matr4  z	.initcostr7  z.mincostr;  )r+   r,   r-   r   r2  r   rz   r1  r   r   r6  
isinstanceboolr5  r4  r7  )r2   r3   Z_inrw   r5  r4  r'   r'   r(   r4   +  sB    







zBBRegister._list_outputsc                s2   |dkrt |tr| j | }tt| j|||S )Nr6  r4  r5  r7  )r6  r4  r5  r7  )r=  r>  r4   rp   r<  rq   )r2   rr   rs   rt   )ru   r'   r(   rq   ]  s       
zBBRegister._format_argc             C   s   |dkr| j  | S d S )Nr2  )r4   )r2   rr   r'   r'   r(   r   g  s    zBBRegister._gen_filename)r!   r"   r#   r5   r6   r   r   r!  r%  r7   r8  r:  r+   r4   rq   r   r   r'   r'   )ru   r(   r<    s   $2
r<  c               @   s~  e Zd ZeddddddZeddddZdDZeddedddZej	dedddZ
ejdddZej	deddgddZdEZeded dd!d"Zeded#dd$d"Zeded%dd&d"Zeded dd!d"Zeded'dd(d"Zeded)dd*d"Zej	ed+dd,d-Zej	ed+dd.d-Zejed/dd0d-Zej	d1d2d3Zejd4d5d6d7d8dZej	d9d:d3Zed;d<dZej	d=d>gd?d@Zej	dAd>gdBd@ZdCS )FApplyVolTransformInputSpecTz--mov %sFz"Input volume you wish to transform)r   r   r&  r   r   zOutput volumez--o %s)r   r   r\   target_filetal	fs_targetz	--targ %szOutput template volume)r   r   r<   r   r   z--talz,map to a sub FOV of MNI305 (with --reg only))r   r<   r   r   z--talres %.10fz#Resolution to sample when using tal)r   r   z--fstargreg_filez.use orig.mgz from subject in regfile as target)r   r<   r   r   r   lta_filelta_inv_filefsl_reg_filexfm_reg_file
reg_headermni_152_regsubjectz--reg %sz,tkRAS-to-tkRAS matrix   (tkregister2 format))r   r<   r   r   r   z--lta %szLinear Transform Array filez--lta-inv %szLTA, invertz--fsl %sz$fslRAS-to-fslRAS matrix (FSL format)z--xfm %sz,ScannerRAS-to-ScannerRAS matrix (MNI format)z--regheaderz*ScannerRAS-to-ScannerRAS matrix = identity)r<   r   r   r   ztarget MNI152 spacez--s %sz7set matrix = identity and use subject for any templateszsample from target to sourcez--inv)r   r   ZtrilinrI   rJ   z--interp %sz*Interpolation method (<trilin> or nearest)z+Do not resample; just change vox2ras matrixz--no-resamplez--m3z %szThis is the morph to be applied to the volume. Unless the morph is in mri/transforms (eg.: for talairach.m3z computed by reconall), you will need to specify the full path to this morph and use the --noDefM3zPath flag.z--noDefM3zPathm3z_filezTo be used with the m3z flag. Instructs the code not to look for them3z morph in the default location (SUBJECTS_DIR/subj/mri/transforms), but instead just use the path indicated in --m3z.)r   r   r   z--inv-morphzfCompute and use the inverse of the non-linear morph to resample the input volume. To be used by --m3z.N)r@  rA  rB  )rC  rD  rE  rF  rG  rH  rI  rJ  )r!   r"   r#   r   r1  transformed_fileZ	_targ_xorr@  r   r&   rA  r_   Ztal_resolutionrB  Z_reg_xorrC  rD  rE  rF  rG  rH  rI  rA   rJ  inverserB   ZinterpZno_resamplerK  Zno_ded_m3z_pathZinvert_morphr'   r'   r'   r(   r?  n  s   
       
	r?  c               @   s   e Zd ZedddZdS )ApplyVolTransformOutputSpecTz$Path to output file if used normally)r   r   N)r!   r"   r#   r   rL  r'   r'   r'   r(   rN    s   rN  c               @   s4   e Zd ZdZdZeZeZdd Z	dd Z
dd Zd	S )
ApplyVolTransforma  Use FreeSurfer mri_vol2vol to apply a transform.

    Examples
    --------

    >>> from nipype.interfaces.freesurfer import ApplyVolTransform
    >>> applyreg = ApplyVolTransform()
    >>> applyreg.inputs.source_file = 'structural.nii'
    >>> applyreg.inputs.reg_file = 'register.dat'
    >>> applyreg.inputs.transformed_file = 'struct_warped.nii'
    >>> applyreg.inputs.fs_target = True
    >>> applyreg.cmdline
    'mri_vol2vol --fstarg --reg register.dat --mov structural.nii --o struct_warped.nii'

    Zmri_vol2volc             C   sV   | j j}t|sR| j jdkr8| j jdkr.d}q@| j j}n| j j}t|tj	 dd}|S )NTzorig.mgzZ_warped)rv   rw   )
r-   rL  r   rM  rB  r@  r1  r   r.   r1   )r2   r{   srcr'   r'   r(   _get_outfile  s    
zApplyVolTransform._get_outfilec             C   s$   | j  j }tjj| j |d< |S )NrL  )r+   r,   r.   r/   rz   rQ  )r2   r3   r'   r'   r(   r4   %  s    zApplyVolTransform._list_outputsc             C   s   |dkr| j  S d S )NrL  )rQ  )r2   rr   r'   r'   r(   r   *  s    zApplyVolTransform._gen_filenameN)r!   r"   r#   r5   r6   r?  r7   rN  r+   rQ  r4   r   r'   r'   r'   r(   rO    s   rO  c               @   s   e Zd ZedddddZedddddZedd	dd
Zejej	ej	ej	dgdddZ
ej	ddgddZejddgddgdddZejddgddddZejdddd Zd!S )"SmoothInputSpecTzsource volumez--i %s)r   r   r   r   z'registers volume to surface anatomical z--reg %s)r   r   r   r   zoutput volumez--o %s)r   r   r\   	proj_fracz#average a long normal min max deltaz--projfrac-avg %.2f %.2f %.2f)r<   r   r   z/project frac of thickness a long surface normalproj_frac_avgz--projfrac %s)r   r<   r   g        rC  	num_iterszsurface FWHM in mmz	--fwhm %f)lowr   r   r<   r   r   r   surface_fwhmz--niters %dz$number of iterations instead of fwhm)rV  r<   r   r   r   z--vol-fwhm %fz#volume smoothing outside of surface)rV  r   r   N)r!   r"   r#   r   rg   rC  smoothed_filer   r?   r_   rT  rS  ZRangerW  rU  Zvol_fwhmr'   r'   r'   r(   rR  0  sB   rR  c               @   s   e Zd ZedddZdS )SmoothOutputSpecTzsmoothed input volume)r   r   N)r!   r"   r#   r   rX  r'   r'   r'   r(   rY  Z  s   rY  c               @   s,   e Zd ZdZdZeZeZdd Z	dd Z
dS )Smootha2  Use FreeSurfer mris_volsmooth to smooth a volume

    This function smoothes cortical regions on a surface and non-cortical
    regions in volume.

    .. note::
       Cortical voxels are mapped to the surface (3D->2D) and then the
       smoothed values from the surface are put back into the volume to fill
       the cortical ribbon. If data is smoothed with this algorithm, one has to
       be careful about how further processing is interpreted.

    Examples
    --------

    >>> from nipype.interfaces.freesurfer import Smooth
    >>> smoothvol = Smooth(in_file='functional.nii', smoothed_file = 'foo_out.nii', reg_file='register.dat', surface_fwhm=10, vol_fwhm=6)
    >>> smoothvol.cmdline
    'mris_volsmooth --i functional.nii --reg register.dat --o foo_out.nii --fwhm 10.000000 --vol-fwhm 6.000000'

    Zmris_volsmoothc             C   s:   | j  j }| jj}t|s.| j| jjdd}||d< |S )NZ_smooth)rw   rX  )r+   r,   r-   rX  r   
_gen_fnamerg   )r2   r3   r{   r'   r'   r(   r4   x  s    zSmooth._list_outputsc             C   s   |dkr| j  | S d S )NrX  )r4   )r2   rr   r'   r'   r(   r     s    zSmooth._gen_filenameN)r!   r"   r#   r5   r6   rR  r7   rY  r+   r4   r   r'   r'   r'   r(   rZ  ^  s   rZ  c               @   s  e Zd ZedddddZedddddZejdeddddd	Zejej	e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ddddZejej	edddZejej	edddZejej	edddZejej	edddZejej	edddZej	d d!gdd"d#Zejd$d%g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jd/d0dZejd1d2dZejd3d4dZejd5d6dZej	d7d8dZ ej	d9d:dZ!edd;d<dZ"edd=d>dZ#ej	d?d@dZ$ej	dAdBdZ%dCS )DRobustRegisterInputSpecTz--mov %szvolume to be registered)r   r   r   r   z--dst %sz"target volume for the registrationz--lta %sz*registration file; either True or filename)defaultr    r   r   z	--warp %sz)registered image; either True or filename)r   r   z--weights %sz/weights image to write; either True or filenamez--iscalez>estimate intensity scale (recommended for unnormalized images)z--transonlyz!find 3 parameter translation onlyz--transformzuse initial transform on source)r   r   r   z--halfmov %sz+write source volume mapped to halfway spacez--halfdst %sz+write target volume mapped to halfway spacez--halfweights %sz,write weights volume mapped to halfway spacez--halfmovlta %sz,write transform from source to halfway spacez--halfdstlta %sz,write transform from target to halfway spacez--satitoutlier_senszauto-detect good sensitivity)r   r<   r   r   z
--sat %.4f	auto_sensz"set outlier sensitivity explicitlyz--leastsquaresz-use least squares instead of robust estimatorz--noinitzskip transform initz--initorientz@use moments for initial orient (recommended for stripped brains)z
--maxit %dz%maximum # of times on each resolutionz--highit %dz$max # of times on highest resolutionz--epsit %.3fz$stop iterations when below thresholdz--subsample %dz.subsample if dimension is above threshold sizez--wlimit %.3fz"set maximal outlier limit in satitz	--vox2voxz*output vox2vox matrix (default is RAS2RAS)z	--nomultizwork on highest resolutionz--maskmov %sz image to mask source volume withz--maskdst %sz image to mask target volume withz--doubleprecz use double-precision intensitiesz--floattypezuse float intensitiesN)&r!   r"   r#   r   r1  r@  r   r3  r2  r&   r6  weights_fileZest_int_scaleZ
trans_onlyZin_xfm_filehalf_source	half_targhalf_weightshalf_source_xfmhalf_targ_xfmr_  r_   r^  Zleast_squaresZno_initZinit_orientr@   Zmax_iterationsZhigh_iterationsZiteration_threshZsubsample_threshZoutlier_limitZwrite_vo2voxZno_multiZmask_sourceZmask_targetZforce_doubleZforce_floatr'   r'   r'   r(   r\    s   








r\  c               @   sl   e Zd ZedddZedddZedddZedddZedddZedddZ	edd	dZ
edd
dZdS )RobustRegisterOutputSpecTzoutput registration file)r   r   z&output image with registration appliedzimage of weights usedz$source image mapped to halfway spacez$target image mapped to halfway spacez%weights image mapped to halfway spacez3transform file to map source image to halfway spacez3transform file to map target image to halfway spaceN)r!   r"   r#   r   r2  r6  r`  ra  rb  rc  rd  re  r'   r'   r'   r(   rf   	  s   
rf  c                   s4   e Zd ZdZdZeZeZ fddZ	dd Z
  ZS )RobustRegistera  Perform intramodal linear registration (translation and rotation) using
    robust statistics.

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import RobustRegister
    >>> reg = RobustRegister()
    >>> reg.inputs.source_file = 'structural.nii'
    >>> reg.inputs.target_file = 'T1.nii'
    >>> reg.inputs.auto_sens = True
    >>> reg.inputs.init_orient = True
    >>> reg.cmdline # doctest: +ELLIPSIS
    'mri_robust_register --satit --initorient --lta .../structural_robustreg.lta --mov structural.nii --dst T1.nii'

    References
    ----------
    Reuter, M, Rosas, HD, and Fischl, B, (2010). Highly Accurate Inverse
        Consistent Registration: A Robust Approach.  Neuroimage 53(4) 1181-96.

    Zmri_robust_registerc                s6   d	}||kr"t |tr"| j | }tt| j|||S )
Nr2  r6  r`  ra  rb  rc  rd  re  )r2  r6  r`  ra  rb  rc  rd  re  )r=  r>  r4   rp   rg  rq   )r2   rr   rs   rt   options)ru   r'   r(   rq   *	  s           zRobustRegister._format_argc             C   s   | j  j }tj }t| jj| jjd}tddddddddd}xft|j	 D ]V\}}t
| j|}|rN|dkrt||d  |d ||d d||< qNtjj|||< qNW |S )N)rP  trgrP  _robustreg.ltaF
_robustregT_robustweights_halfwayri  _halfweights_robustxfm.lta)r2  r6  r`  ra  rb  rc  rd  re  r   r   r	   )rw   rv   rx   )rP  rj  F)rP  rk  T)rP  rl  T)rP  rm  T)ri  rm  T)rP  rn  T)rP  ro  F)ri  ro  F)r+   r,   r.   r1   r   r-   r1  r@  r   itemsr  r   r/   rz   )r2   r3   cwdZpreficesZsufficesrr   Zsufftuprt   r'   r'   r(   r4   9	  s.    
zRobustRegister._list_outputs)r!   r"   r#   r5   r6   r\  r7   rf  r+   rq   r4   r   r'   r'   )ru   r(   rg  	  s   rg  c               @   sz   e Zd ZejedddddddZejejddZejej	d	dZ
ejejd
dZejeddddZedddddZdS )FitMSParamsInputSpecT)r   z%sr	   z,list of FLASH images (must be in mgh format))r   r[   r   r   z(list of TRs of the input files (in msec))r   z(list of TEs of the input files (in msec)z&list of flip angles of the input filesz4list of transform files to apply to each FLASH imager   zdirectory to store output in)r   r[   r\   r   Nr]   r^   )r!   r"   r#   r   r`   r   in_filesr@   tr_listr_   te_list	flip_listxfm_listr   out_dirr'   r'   r'   r(   rr  V	  s   rr  c               @   s0   e Zd ZedddZedddZedddZdS )FitMSParamsOutputSpecTz'image of estimated T1 relaxation values)r   r   z(image of estimated proton density valueszimage of estimated T2* valuesN)r!   r"   r#   r   t1_imagepd_imaget2star_imager'   r'   r'   r(   ry  j	  s   ry  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 )	FitMSParamsa}  Estimate tissue paramaters from a set of FLASH images.

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import FitMSParams
    >>> msfit = FitMSParams()
    >>> msfit.inputs.in_files = ['flash_05.mgz', 'flash_30.mgz']
    >>> msfit.inputs.out_dir = 'flash_parameters'
    >>> msfit.cmdline
    'mri_ms_fitparms  flash_05.mgz flash_30.mgz flash_parameters'

    Zmri_ms_fitparmsc                s   |dkrd}xt |D ]\}}t| jjrDdj|d| jj|  f}t| jjrjdj|d| jj|  f}t| jjrdj|d| jj|  f}t| jjrdj|d| jj|  f}dj||f}qW |S tt	| j
|||S )Nrs  r  r   z-tr %.1fz-te %.3fz-fa %.1fz-at %s)	enumerater   r-   rt  r0   ru  rv  rw  rp   r}  rq   )r2   rr   rs   rt   r   r   file)ru   r'   r(   rq   	  s    zFitMSParams._format_argc             C   sf   | j  j }t| jjs$| jd}n| jj}tjj|d|d< tjj|d|d< tjj|d|d< |S )Nrx  zT1.mgzrz  zPD.mgzr{  z
T2star.mgzr|  )	r+   r,   r   r-   rx  r   r.   r/   r0   )r2   r3   rx  r'   r'   r(   r4   	  s    zFitMSParams._list_outputsc             C   s   |dkrt j S d S )Nrx  )r.   r1   )r2   rr   r'   r'   r(   r   	  s    zFitMSParams._gen_filename)r!   r"   r#   r5   r6   rr  r7   ry  r+   rq   r4   r   r   r'   r'   )ru   r(   r}  q	  s   r}  c               @   s   e Zd ZejddddZejddddd	Zejdd
ddd	Zejddddd	Z	e
ddddddZe
ddddddZe
ddddZdS )SynthesizeFLASHInputSpecr   z-wz=use a fixed weighting to generate optimal gray/white contrast)r[   r   r   Tr	   z%.2fzrepetition time (in msec))r   r[   r   r   r   zflip angle (in degrees)   z%.3fzecho time (in msec)   z%szimage of T1 values)r   r   r[   r   r   r/  zimage of proton density valueszimage to write)r\   r   r   N)r!   r"   r#   r   r&   Zfixed_weightingr_   ra   
flip_anglerb   r   rz  r{  rh   r'   r'   r'   r(   r  	  s&   r  c               @   s   e Zd ZedddZdS )SynthesizeFLASHOutputSpecTzsynthesized FLASH acquisition)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   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 )SynthesizeFLASHa  Synthesize a FLASH acquisition from T1 and proton density maps.

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import SynthesizeFLASH
    >>> syn = SynthesizeFLASH(tr=20, te=3, flip_angle=30)
    >>> syn.inputs.t1_image = 'T1.mgz'
    >>> syn.inputs.pd_image = 'PD.mgz'
    >>> syn.inputs.out_file = 'flash_30syn.mgz'
    >>> syn.cmdline
    'mri_synthesize 20.00 30.00 3.000 T1.mgz PD.mgz flash_30syn.mgz'

    Zmri_synthesizec             C   sD   | j  j }t| jjr&| jj|d< n| jd| jj dd|d< |S )Nrh   zsynth-flash_%02d.mgzr  )rw   )r+   r,   r   r-   rh   r[  r  )r2   r3   r'   r'   r(   r4   	  s    zSynthesizeFLASH._list_outputsc             C   s   |dkr| j  d S d S )Nrh   )r4   )r2   rr   r'   r'   r(   r   	  s    zSynthesizeFLASH._gen_filenameN)r!   r"   r#   r5   r6   r  r7   r  r+   r4   r   r'   r'   r'   r(   r  	  s   
r  c               @   s   e Zd ZedddddZeddgdddd$dZej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ddddZeddddZejdd dZejd!d"dZd#S )(MNIBiasCorrectionInputSpecTz--i %sz>input volume. Input can be any format accepted by mri_convert.)r   r   r   r   z--o %srg   z	%s_outputFzAoutput volume. Output can be any format accepted by mri_convert. z;If the output format is COR, then the directory must exist.)r   name_sourcename_templater   keep_extensionr   r  z--n %dzRNumber of iterations to run nu_correct. Default is 4. This is the number of times zYthat nu_correct is repeated (ie, using the output from the previous run as the input for zGthe next). This is different than the -iterations option to nu_correct.)r    r   r   z--proto-iters %dzOPasses Np as argument of the -iterations flag of nu_correct. This is different zPthan the --n flag above. Default is not to pass nu_correct the -iterations flag.)r   r   z--distance %dzN3 -distance optionz--no-rescalezAdo not rescale so that global mean of output == input global meanz	--mask %szBbrainmask volume. Input can be any format accepted by mri_convert.)r   r   r   z
--uchar %sz1tal.xfm. Use mri_make_uchar instead of conformingz	--stop %fzJConvergence threshold below which iteration stops (suggest 0.01 to 0.0001)z--shrink %dz2Shrink parameter for finer sampling (default is 4)Nz|output volume. Output can be any format accepted by mri_convert. If the output format is COR, then the directory must exist.zNumber of iterations to run nu_correct. Default is 4. This is the number of times that nu_correct is repeated (ie, using the output from the previous run as the input for zNumber of iterations to run nu_correct. Default is 4. This is the number of times that nu_correct is repeated (ie, using the output from the previous run as the input for the next). This is different than the -iterations option to nu_correct.zPasses Np as argument of the -iterations flag of nu_correct. This is different than the --n flag above. Default is not to pass nu_correct the -iterations flag.)r!   r"   r#   r   rg   rh   r   r@   Z
iterationsZprotocol_iterationsZdistancer&   Z
no_rescalemask	transformr_   stopshrinkr'   r'   r'   r(   r  	  sN     r  c               @   s   e Zd ZedddZdS )MNIBiasCorrectionOutputSpecTzoutput volume)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   r   
  s   r  c               @   s   e Zd ZdZdZeZeZdS )MNIBiasCorrectionaL  Wrapper for nu_correct, a program from the Montreal Neurological Insitute (MNI)
    used for correcting intensity non-uniformity (ie, bias fields). You must have the
    MNI software installed on your system to run this. See [www.bic.mni.mcgill.ca/software/N3]
    for more info.

    mri_nu_correct.mni uses float internally instead of uchar. It also rescales the output so
    that the global mean is the same as that of the input. These two changes are linked and
    can be turned off with --no-float

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import MNIBiasCorrection
    >>> correct = MNIBiasCorrection()
    >>> correct.inputs.in_file = "norm.mgz"
    >>> correct.inputs.iterations = 6
    >>> correct.inputs.protocol_iterations = 1000
    >>> correct.inputs.distance = 50
    >>> correct.cmdline
    'mri_nu_correct.mni --distance 50 --i norm.mgz --n 6 --o norm_output.mgz --proto-iters 1000'

    References
    ----------
    [http://freesurfer.net/fswiki/mri_nu_correct.mni]
    [http://www.bic.mni.mcgill.ca/software/N3]
    [https://github.com/BIC-MNI/N3]

    zmri_nu_correct.mniN)	r!   r"   r#   r5   r6   r  r7   r  r+   r'   r'   r'   r(   r  $
  s   r  c            	   @   sb   e Zd ZeddddddZeddddddd	d
ZejdddZedddddZ	edddddZ
dS )WatershedSkullStripInputSpecz%sTr	   zinput volume)r   r   r   r[   r   zbrainmask.auto.mgzFr   zoutput volume)r   r   r   r[   r    r   z-T1z-specify T1 input volume (T1 grey value = 110))r   r   z-brain_atlas %sr  r  )r   r   r[   r   r   ZundocumentedNr]   r^   )r!   r"   r#   r   rg   rh   r   r&   r+  Zbrain_atlasr  r'   r'   r'   r(   r  F
  s   r  c               @   s   e Zd ZedddZdS )WatershedSkullStripOutputSpecFzskull stripped brain volume)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   r  Z
  s   r  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )WatershedSkullStripa  This program strips skull and other outer non-brain tissue and
    produces the brain volume from T1 volume or the scanned volume.

    The "watershed" segmentation algorithm was used to dertermine the
    intensity values for white matter, grey matter, and CSF.
    A force field was then used to fit a spherical surface to the brain.
    The shape of the surface fit was then evaluated against a previously
    derived template.

    The default parameters are: -w 0.82 -b 0.32 -h 10 -seedpt -ta -wta

    (Segonne 2004)

    Examples
    ========
    >>> from nipype.interfaces.freesurfer import WatershedSkullStrip
    >>> skullstrip = WatershedSkullStrip()
    >>> skullstrip.inputs.in_file = "T1.mgz"
    >>> skullstrip.inputs.t1 = True
    >>> skullstrip.inputs.transform = "transforms/talairach_with_skull.lta"
    >>> skullstrip.inputs.out_file = "brainmask.auto.mgz"
    >>> skullstrip.cmdline
    'mri_watershed -T1 transforms/talairach_with_skull.lta T1.mgz brainmask.auto.mgz'
    r   c             C   s$   | j  j }tjj| jj|d< |S )Nrh   )r+   r,   r.   r/   rz   r-   rh   )r2   r3   r'   r'   r(   r4   |
  s    z!WatershedSkullStrip._list_outputsN)
r!   r"   r#   r5   r6   r  r7   r  r+   r4   r'   r'   r'   r(   r  ^
  s
   r  c            	   @   sl   e Zd ZeddddddZedddgdd	dd
dZejdddZeddddZ	eddddZ
edddZdS )NormalizeInputSpecz%sTr	   zThe input file for Normalize)r   r   r   r[   r   r   rg   z%s_normFzThe output file for Normalize)r   r[   r  r  r   r  r   z-g %dz+use max intensity/mm gradient g (default=1))r   r   z-mask %sz!The input mask file for Normalize)r   r   r   z-aseg %sz$The input segmentation for Normalizez/Tranform file from the header of the input file)r   r   Nr]   r^   )r!   r"   r#   r   rg   rh   r   r@   Zgradientr  r   r  r'   r'   r'   r(   r  
  s,   
r  c               @   s   e Zd ZedddZdS )NormalizeOutputSpecFzThe output file for Normalize)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   r  
  s   r  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )	Normalizea  
    Normalize the white-matter, optionally based on control points. The
    input volume is converted into a new volume where white matter image
    values all range around 110.

    Examples
    ========
    >>> from nipype.interfaces import freesurfer
    >>> normalize = freesurfer.Normalize()
    >>> normalize.inputs.in_file = "T1.mgz"
    >>> normalize.inputs.gradient = 1
    >>> normalize.cmdline
    'mri_normalize -g 1 T1.mgz T1_norm.mgz'
    r   c             C   s$   | j  j }tjj| jj|d< |S )Nrh   )r+   r,   r.   r/   rz   r-   rh   )r2   r3   r'   r'   r(   r4   
  s    zNormalize._list_outputsN)
r!   r"   r#   r5   r6   r  r7   r  r+   r4   r'   r'   r'   r(   r  
  s
   r  c            	   @   s   e Zd ZeddddddZedddgdd	dd
dZeddddddZeddddddZeddddZedddZ	edddZ
dS )CANormalizeInputSpecz%sTr  zThe input file for CANormalize)r   r   r   r[   r   r   rg   z%s_normFzThe output file for CANormalize)r   r[   r  r  r   r  r   r   zThe atlas file in gca formatr	   zThe tranform file in lta formatz-mask %szSpecifies volume to use as mask)r   r   r   z-c %sz'File name for the output control points)r   r   z-long %sz1undocumented flag used in longitudinal processingNr  r^   r  r]   )r!   r"   r#   r   rg   rh   Zatlasr  r  control_pointsZ	long_filer'   r'   r'   r(   r  
  s>   
r  c               @   s$   e Zd ZedddZedddZdS )CANormalizeOutputSpecFzThe output file for Normalize)r   r   z'The output control points for NormalizeN)r!   r"   r#   r   rh   r  r'   r'   r'   r(   r  
  s   r  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )CANormalizea  This program creates a normalized volume using the brain volume and an
    input gca file.

    See Also
    --------
    For complete details, see the `FS Documentation
    <http://surfer.nmr.mgh.harvard.edu/fswiki/mri_ca_normalize>`__.

    Examples
    --------
    >>> from nipype.interfaces import freesurfer
    >>> ca_normalize = freesurfer.CANormalize()
    >>> ca_normalize.inputs.in_file = "T1.mgz"
    >>> ca_normalize.inputs.atlas = "atlas.nii.gz" # in practice use .gca atlases
    >>> ca_normalize.inputs.transform = "trans.mat" # in practice use .lta transforms
    >>> ca_normalize.cmdline
    'mri_ca_normalize T1.mgz atlas.nii.gz trans.mat T1_norm.mgz'

    r   c             C   s8   | j  j }tjj| jj|d< tjj| jj|d< |S )Nrh   r  )r+   r,   r.   r/   rz   r-   rh   r  )r2   r3   r'   r'   r(   r4     s    zCANormalize._list_outputsN)
r!   r"   r#   r5   r6   r  r7   r  r+   r4   r'   r'   r'   r(   r  
  s
   r  c               @   s   e Zd Zedddd"ddZedd#dddZeddd$d
dZe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ejdddZejdddZeeddd ddZd!S )&CARegisterInputSpecz%sTr   zThe input volume for CARegister)r   r   r   r[   r   r   z The output volume for CARegister)r   r[   r\   r   r	   zThe template file in gca format)r   r   r[   r   z-mask %szSpecifies volume to use as mask)r   r   r   z-invert-and-saver  zXInvert and save the .m3z multi-dimensional talaraich transform to x, y, and z .mgz files)r   r[   r   z-nobigventricleszNo big ventricles)r   r   z-T %sz!Specifies transform in lta formatz	-align-%sz#Specifies when to perform alignmentz
-levels %dzPdefines how many surrounding voxels will be used in interpolations, default is 6z-A %dz1undocumented flag used in longitudinal processingF)r   z-l %sNr  r^   r]   r  )r!   r"   r#   r   rg   rh   templater  r   r&   Zinvert_and_saveno_big_ventriclesr  Stringalignr@   ZlevelsAr   l_filesr'   r'   r'   r(   r    s:   

r  c               @   s   e Zd ZedddZdS )CARegisterOutputSpecFzThe output file for CARegister)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   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 )	
CARegistera  Generates a multi-dimensional talairach transform from a gca file and talairach.lta file

    See Also
    --------
    For complete details, see the `FS Documentation
    <http://surfer.nmr.mgh.harvard.edu/fswiki/mri_ca_register>`__

    Examples
    --------
    >>> from nipype.interfaces import freesurfer
    >>> ca_register = freesurfer.CARegister()
    >>> ca_register.inputs.in_file = "norm.mgz"
    >>> ca_register.inputs.out_file = "talairach.m3z"
    >>> ca_register.cmdline
    'mri_ca_register norm.mgz talairach.m3z'

    r   c                s2   |dkrt |dkr|jd tt| j|||S )Nr  r   zidentity.nofile)r   r   rp   r  rq   )r2   rr   rs   rt   )ru   r'   r(   rq   U  s    
zCARegister._format_argc             C   s   |dkrt jjdS d S )Nrh   ztalairach.m3z)r.   r/   rz   )r2   rr   r'   r'   r(   r[  Z  s    zCARegister._gen_fnamec             C   s$   | j  j }tjj| jj|d< |S )Nrh   )r+   r,   r.   r/   rz   r-   rh   )r2   r3   r'   r'   r(   r4   _  s    zCARegister._list_outputs)r!   r"   r#   r5   r6   r  r7   r  r+   rq   r[  r4   r   r'   r'   )ru   r(   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d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
je
je
jdddZeddddZeddddZdS )#CALabelInputSpecz%sr  TzInput volume for CALabel)r   r[   r   r   r   r   FzOutput file for CALabelr   zInput transform for CALabelr	   zInput template for CALabelz-r %szset input volume)r   r   r   z=input label intensities file(used in longitudinal processing)z-nobigventricleszNo big ventricles)r   r   z-alignzAlign CALabelz-prior %.1fzPrior for CALabelz-relabel_unlikely %d %.1fzVReclassify voxels at least some std devs from the mean using some size Gaussian windowz-l %szSUndocumented flag. Autorecon3 uses ../label/{hemisphere}.cortex.label as input filez-aseg %szHUndocumented flag. Autorecon3 uses ../mri/aseg.presurf.mgz as input fileNr  r^   r  r]   )r!   r"   r#   r   rg   rh   r  r  Zin_volZintensitiesr   r&   r  r  r_   Zpriorr?   r@   Zrelabel_unlikelylabelasegr'   r'   r'   r(   r  e  sZ   r  c               @   s   e Zd ZedddZdS )CALabelOutputSpecFzOutput volume from CALabel)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   r    s   r  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )CALabelam  Label subcortical structures based in GCA model.

    See Also
    --------
    For complete details, see the `FS Documentation
    <http://surfer.nmr.mgh.harvard.edu/fswiki/mri_ca_label>`__

    Examples
    --------
    >>> from nipype.interfaces import freesurfer
    >>> ca_label = freesurfer.CALabel()
    >>> ca_label.inputs.in_file = "norm.mgz"
    >>> ca_label.inputs.out_file = "out.mgz"
    >>> ca_label.inputs.transform = "trans.mat"
    >>> ca_label.inputs.template = "Template_6.nii" # in practice use .gcs extension
    >>> ca_label.cmdline
    'mri_ca_label norm.mgz trans.mat Template_6.nii out.mgz'

    r   c             C   s$   | j  j }tjj| jj|d< |S )Nrh   )r+   r,   r.   r/   rz   r-   rh   )r2   r3   r'   r'   r(   r4     s    zCALabel._list_outputsN)
r!   r"   r#   r5   r6   r  r7   r  r+   r4   r'   r'   r'   r(   r    s
   r  c            
   @   s   e Zd Zejddd(ddddZejdddd)dd
dZedd*ddddZ	e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g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&Zd'S )/MRIsCALabelInputSpecr   z%sr  TzSubject name or ID)r   r[   r    r   r   r   r   r  zHemisphere ('lh' or 'rh'))r   r[   r   r   r   zInput canonical surface file)r   r[   r   r   r   r	   zClassifier array input filez$implicit input {hemisphere}.smoothwm)r   r   r   z implicit input {hemisphere}.curvz implicit input {hemisphere}.sulcr   F
hemispherez%s.aparc.annotzAnnotated surface output file)r   r[   r   r  r  r   r  r   z-l %szSUndocumented flag. Autorecon3 uses ../label/{hemisphere}.cortex.label as input file)r   r   r   z-aseg %szHUndocumented flag. Autorecon3 uses ../mri/aseg.presurf.mgz as input filez-seed %dr  )r   r   z)Copies implicit inputs to node directory z'and creates a temp subjects_directory. zUse this when running as a node)r   Nr  r  r]   r^   zPCopies implicit inputs to node directory and creates a temp subjects_directory. zoCopies implicit inputs to node directory and creates a temp subjects_directory. Use this when running as a node)r!   r"   r#   r   r  r   rB   r  r   	canonsurf
classifiersmoothwmcurvsulcrh   r  r  r@   seedr&   copy_inputsr'   r'   r'   r(   r    sd   r  c               @   s   e Zd ZedddZdS )MRIsCALabelOutputSpecFzOutput volume from MRIsCALabel)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   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 )MRIsCALabelaV  
    For a single subject, produces an annotation file, in which each
    cortical surface vertex is assigned a neuroanatomical label.This
    automatic procedure employs data from a previously-prepared atlas
    file. An atlas file is created from a training set, capturing region
    data manually drawn by neuroanatomists combined with statistics on
    variability correlated to geometric information derived from the
    cortical model (sulcus and curvature). Besides the atlases provided
    with FreeSurfer, new ones can be prepared using mris_ca_train).

    Examples
    ========

    >>> from nipype.interfaces import freesurfer
    >>> ca_label = freesurfer.MRIsCALabel()
    >>> ca_label.inputs.subject_id = "test"
    >>> ca_label.inputs.hemisphere = "lh"
    >>> ca_label.inputs.canonsurf = "lh.pial"
    >>> ca_label.inputs.curv = "lh.pial"
    >>> ca_label.inputs.sulc = "lh.pial"
    >>> ca_label.inputs.classifier = "im1.nii" # in pracice, use .gcs extension
    >>> ca_label.inputs.smoothwm = "lh.pial"
    >>> ca_label.cmdline
    'mris_ca_label test lh lh.pial im1.nii lh.aparc.annot'
    r   c                s   | j jrtj | j _d|kr(| j j|d< t| | j jdd t| | j jddj| j j	d 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 )	Nr   Zsurf)folderz{0}.smoothwm)r  r   z{0}.curvz{0}.sulcr  )r-   r  r.   r1   r   r   r  r  r  r  r  r  r/   r0   r   r   makedirsrp   r  run)r2   r-   Z	label_dir)ru   r'   r(   r  +  s2    
zMRIsCALabel.runc             C   s>   | j  j }tjj| jj}tjj| jj| jj	d||d< |S )Nr  rh   )
r+   r,   r.   r/   r   r-   rh   r0   r   r   )r2   r3   Zout_basenamer'   r'   r(   r4   M  s
    zMRIsCALabel._list_outputs)r!   r"   r#   r5   r6   r  r7   r  r+   r  r4   r   r'   r'   )ru   r(   r    s   "r  c            	   @   st   e Zd ZedddddZeddddZeddd	gd
ddddZedddddZej	dddddddZ
ejddZdS )SegmentCCInputSpecz-aseg %sTz/Input aseg file to read from subjects directory)r   r   r   r   z2Required undocumented input {subject}/mri/norm.mgz)r   r   r   z-o %sFrg   z%s.auto.mgzz#Filename to write aseg including CC)r   r   r  r  r   r  r   z-lta %sz(Global filepath for writing rotation ltar   z%sr   zSubject name)r   r   r[   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   Nr^   zRIf 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   rg   in_normrh   out_rotationr   r  r   r&   r  r'   r'   r'   r(   r  V  s>   r  c               @   s$   e Zd ZedddZedddZdS )SegmentCCOutputSpecFz-Output segmentation uncluding corpus collosum)r   r   zOutput lta rotation fileN)r!   r"   r#   r   rh   r  r'   r'   r'   r(   r    s   r  c                   sN   e Zd ZdZdZeZeZ fddZ	dd Z
 fddZd fd
d	Z  ZS )	SegmentCCa  
    This program segments the corpus callosum into five separate labels in
    the subcortical segmentation volume 'aseg.mgz'. The divisions of the
    cc are equally spaced in terms of distance along the primary
    eigendirection (pretty much the long axis) of the cc. The lateral
    extent can be changed with the -T <thickness> parameter, where
    <thickness> is the distance off the midline (so -T 1 would result in
    the who CC being 3mm thick). The default is 2 so it's 5mm thick. The
    aseg.stats values should be volume.

    Examples
    ========
    >>> from nipype.interfaces import freesurfer
    >>> SegmentCC_node = freesurfer.SegmentCC()
    >>> SegmentCC_node.inputs.in_file = "aseg.mgz"
    >>> SegmentCC_node.inputs.in_norm = "norm.mgz"
    >>> SegmentCC_node.inputs.out_rotation = "cc.lta"
    >>> SegmentCC_node.inputs.subject_id = "test"
    >>> SegmentCC_node.cmdline
    'mri_cc -aseg aseg.mgz -o aseg.auto.mgz -lta cc.lta test'
    Zmri_ccc                s2   |dkrt jj|}|j| S tt| j|||S )Nrg   r  rh   )rg   r  rh   )r.   r/   r   r   rp   r  rq   )r2   rr   rs   rt   r   )ru   r'   r(   rq     s    
zSegmentCC._format_argc             C   s8   | j  j }tjj| jj|d< tjj| jj|d< |S )Nrh   r  )r+   r,   r.   r/   rz   r-   rh   r  )r2   r3   r'   r'   r(   r4     s    zSegmentCC._list_outputsc                sb   | j jrPtj | j _d|kr(| j j|d< x&| j j| j jgD ]}t| |dd q:W tt	| j
f |S )Nr   r   )r  )r-   r  r.   r1   r   rg   r  r   rp   r  r  )r2   r-   Zoriginalfile)ru   r'   r(   r    s    zSegmentCC.runNc       	         s   | j  }xdD ]}|| }tjj|stjj|}t| jjrVtjj| jj| jj	}ntjjtj
 | jj	}|dkrtjj|d|}n |dkrtjj|dd|}nd }|rtjj|rtjjtjj|stjtjj| tj|| qW tt| j||S )Nrh   r  r   Z
transforms)rh   r  )r4   r.   r/   isfiler   r   r-   r   r0   r   r1   r   dirnamer  shutilmoverp   r  aggregate_outputs)	r2   ZruntimeZneeded_outputsZpredicted_outputsrr   rh   Zout_baser  Zout_tmp)ru   r'   r(   r    s&    
zSegmentCC.aggregate_outputs)NN)r!   r"   r#   r5   r6   r  r7   r  r+   rq   r4   r  r  r   r'   r'   )ru   r(   r    s   	r  c               @   s0   e Zd Zedddd
ddZeddddddZd	S )SegmentWMInputSpecz%sTr	   zInput file for SegmentWM)r   r   r   r[   r   Fr   z*File to be written as output for SegmentWMNr]   r^   )r!   r"   r#   r   rg   rh   r'   r'   r'   r(   r    s   r  c               @   s   e Zd ZedddZdS )SegmentWMOutputSpecFz Output white matter segmentation)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   r    s   r  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )	SegmentWMa  
    This program segments white matter from the input volume.  The input
    volume should be normalized such that white matter voxels are
    ~110-valued, and the volume is conformed to 256^3.


    Examples
    ========
    >>> from nipype.interfaces import freesurfer
    >>> SegmentWM_node = freesurfer.SegmentWM()
    >>> SegmentWM_node.inputs.in_file = "norm.mgz"
    >>> SegmentWM_node.inputs.out_file = "wm.seg.mgz"
    >>> SegmentWM_node.cmdline
    'mri_segment norm.mgz wm.seg.mgz'
    r   c             C   s$   | j  j }tjj| jj|d< |S )Nrh   )r+   r,   r.   r/   rz   r-   rh   )r2   r3   r'   r'   r(   r4      s    zSegmentWM._list_outputsN)
r!   r"   r#   r5   r6   r  r7   r  r+   r4   r'   r'   r'   r(   r    s
   r  c               @   sb   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ddddddZej	dddZ
dS )EditWMwithAsegInputSpecz%sr  Tz$Input white matter segmentation file)r   r[   r   r   r   r   zInput brain/T1 filer	   zInput presurf segmentation filer   FzFile to be written as outputz-keep-inz#Keep edits as found in input volume)r   r   Nr  r  r]   r^   )r!   r"   r#   r   rg   Z
brain_fileZseg_filerh   r   r&   Zkeep_inr'   r'   r'   r(   r    s2   r  c               @   s   e Zd ZedddZdS )EditWMwithAsegOutputSpecFzOutput edited WM file)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   r  '  s   r  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )EditWMwithAsega  
    Edits a wm file using a segmentation

    Examples
    ========
    >>> from nipype.interfaces.freesurfer import EditWMwithAseg
    >>> editwm = EditWMwithAseg()
    >>> editwm.inputs.in_file = "T1.mgz"
    >>> editwm.inputs.brain_file = "norm.mgz"
    >>> editwm.inputs.seg_file = "aseg.mgz"
    >>> editwm.inputs.out_file = "wm.asegedit.mgz"
    >>> editwm.inputs.keep_in = True
    >>> editwm.cmdline
    'mri_edit_wm_with_aseg -keep-in T1.mgz norm.mgz aseg.mgz wm.asegedit.mgz'
    r   c             C   s$   | j  j }tjj| jj|d< |S )Nrh   )r+   r,   r.   r/   rz   r-   rh   )r2   r3   r'   r'   r(   r4   @  s    zEditWMwithAseg._list_outputsN)
r!   r"   r#   r5   r6   r  r7   r  r+   r4   r'   r'   r'   r(   r  +  s
   r  c            	   @   s   e Zd Zedddd'ddZejeddddd(dd	d
Zed)dddg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eddd*dgdd Zeddd+d"gd#d Zejd$d%dZd&S ),ConcatenateLTAInputSpecTz%sr   zmaps some src1 to dst1)r   r   r   r[   r   )r   zidentity.nofiler	   zmaps dst1(src2) to dst2)r   r[   r   r   r   Fin_lta1z	%s_concatz/the combined LTA maps: src1 to dst2 = LTA2*LTA1)r[   r   r   r  r  r  r   z-invert1z!invert in_lta1 before applying it)r   r   z-invert2z!invert in_lta2 before applying itz
-invertoutzinvert output LTAVOX2VOXRAS2RASz-out_type %dzset final LTA typez-tal %sr  tal_template_filez9if in_lta2 is talairach.xfm, specify source for talairach)r   r   r[   r   r   r  tal_source_filez;if in_lta2 is talairach.xfm, specify template for talairachz-subject %szset subject in output LTANr  r]   r^   r  r  )r!   r"   r#   r   r  r   r3  Zin_lta2rh   r&   Zinvert_1Zinvert_2Z
invert_outrB   re   r  r  rA   rJ  r'   r'   r'   r(   r  F  sN   r  c               @   s   e Zd ZedddZdS )ConcatenateLTAOutputSpecFz/the combined LTA maps: src1 to dst2 = LTA2*LTA1)r   r   N)r!   r"   r#   r   rh   r'   r'   r'   r(   r  ~  s   r  c                   s,   e Zd ZdZdZeZeZ fddZ	  Z
S )ConcatenateLTAa  Concatenates two consecutive LTA transformations into one overall
    transformation

    Out = LTA2*LTA1

    Examples
    --------
    >>> from nipype.interfaces.freesurfer import ConcatenateLTA
    >>> conc_lta = ConcatenateLTA()
    >>> conc_lta.inputs.in_lta1 = 'lta1.lta'
    >>> conc_lta.inputs.in_lta2 = 'lta2.lta'
    >>> conc_lta.cmdline
    'mri_concatenate_lta lta1.lta lta2.lta lta1_concat.lta'

    You can use 'identity.nofile' as the filename for in_lta2, e.g.:

    >>> conc_lta.inputs.in_lta2 = 'identity.nofile'
    >>> conc_lta.inputs.invert_1 = True
    >>> conc_lta.inputs.out_file = 'inv1.lta'
    >>> conc_lta.cmdline
    'mri_concatenate_lta -invert1 lta1.lta identity.nofile inv1.lta'

    To create a RAS2RAS transform:

    >>> conc_lta.inputs.out_type = 'RAS2RAS'
    >>> conc_lta.cmdline
    'mri_concatenate_lta -invert1 -out_type 1 lta1.lta identity.nofile inv1.lta'
    Zmri_concatenate_ltac                s*   |dkrddd| }t t| j|||S )Nre   r   r   )r  r  )rp   r  rq   )r2   rr   rs   rt   )ru   r'   r(   rq     s    zConcatenateLTA._format_arg)r!   r"   r#   r5   r6   r  r7   r  r+   rq   r   r'   r'   )ru   r(   r    s
   r  )pr5   r.   os.pathr/   r   r   r  r   numpyr   Znibabelr   r  r   r   Zutils.filemanipr   r   ior
   baser   r   r   r   r   r   r   r   r   r   r   r   r   r   utilsr   Z__docformat__	getLoggerr  r!  r"  Z	FSVersionr   r)   r*   r8   rC   rD   rl   rm   r   r   r   r   r   r   r+   r   r   r%  r8  r:  r<  r?  rN  rO  rR  rY  rZ  r\  rf  rg  rr  ry  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r'   r'   r'   r(   <module>   s   
,

7  Mh$k( =     -\	[ -*(zF3#7"$!) +'>BJ*Q!8