3
Xd&                @   s  d Z ddlZddlZddlmZmZmZmZm	Z	m
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)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Z,G dIdJ dJeZ-G dKdL dLeZ.G dMdN dNeZ/G dOdP dPeZ0G dQdR dReZ1G dSdT dTeZ2G dUdV dVeZ3G dWdX dXeZ4dYdZ Z5d[d\ Z6dS )]zThis script provides interfaces for BrainSuite command line tools.
Please see brainsuite.org for more information.

Author: Jason Wong
    N   )TraitedSpecCommandLineInputSpecCommandLineFiletraits	isdefinedc               @   s  e Zd ZeddddZedddddZed	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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Zedd ddZed!d"ddZe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d,S )-BseInputSpecTz-i %szinput MRI volume)	mandatoryargstrdesczXoutput brain-masked MRI volume. If unspecified, output file name will be auto generated.z-o %sF)r   r   
hash_filesgenfilezPsave smooth brain mask. If unspecified, output file name will be auto generated.z	--mask %s   zdiffusion constantz-d %f)
usedefaultr   r      zdiffusion iterationsz-n %dg{Gz?zedge detection constantz-s %f   z!radius of erosion/dilation filterz-r %fzdilate final maskz-pztrim brainstemz--trimzdiffusion filter outputz--adf %s)r   r   r   zedge map outputz	--edge %szsave detailed brain maskz
--hires %szcortex filez--cortex %sz verbosity level (0=silent)z-v %fzaretain original orientation(default behavior will auto-rotate input NII files to LPI orientation)z
--norotate)r   r   zshow timingz--timerN)__name__
__module____qualname__r   inputMRIFileoutputMRIVolumeoutputMaskFiler   FloatZdiffusionConstantIntZdiffusionIterationsZedgeDetectionConstantZradiusBoolZdilateFinalMaskZtrimoutputDiffusionFilteroutputEdgeMapoutputDetailedBrainMaskoutputCortexFileverbosityLevelZnoRotatetimer r"   r"   Y/var/www/html/virt/lib/python3.6/site-packages/nipype/interfaces/brainsuite/brainsuite.pyr	      sD   r	   c               @   sH   e Z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 )	BseOutputSpecz$path/name of brain-masked MRI volume)r   zpath/name of smooth brain maskz$path/name of diffusion filter outputzpath/name of edge map outputz path/name of detailed brain maskzpath/name of cortex fileN)
r   r   r   r   r   r   r   r   r   r   r"   r"   r"   r#   r$   F   s   




r$   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )Bsea  
    brain surface extractor (BSE)
    This program performs automated skull and scalp removal on T1-weighted MRI volumes.

    http://brainsuite.org/processing/surfaceextraction/bse/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> bse = brainsuite.Bse()
    >>> bse.inputs.inputMRIFile = example_data('structural.nii')
    >>> results = bse.run() #doctest: +SKIP

    Zbsec             C   sN   | j j }t|| r&tjj|| S ddd}||krJt| j j|| S d S )Nz.bse.nii.gzz.mask.nii.gz)r   r   )inputsgetr   ospathabspathgetFileNamer   )selfnamer&   fileToSuffixMapr"   r"   r#   _gen_filenamee   s    
zBse._gen_filenamec             C   s   t | S )N)	l_outputs)r,   r"   r"   r#   _list_outputst   s    zBse._list_outputsN)r   r   r   __doc__r	   
input_specr$   output_spec_cmdr/   r1   r"   r"   r"   r#   r%   O   s   r%   c               @   sh  e Zd Ze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	jdddZe	jdddddZe	jdddZ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(d)d*Ze	jd+dd,d-d*Ze	jd.d/d0d1ddZe	jd2d3d4d5d6ddZe	jd7d8dZe	jd9d:dZe	j
d;d<dZe	jd=d>dZ d?S )@BfcInputSpecTzinput skull-stripped MRI volumez-i %s)r
   r   r   z	mask filez-m %sF)r   r   r   zZoutput bias-corrected MRI volume. If unspecified, output file name will be auto generated.z-o %s)r   r   r   r   zsave bias field estimatez	--bias %sz!save bias field estimate (masked)z--maskedbias %szhistogram radius (voxels)z-r %d)r   r   zbias sample spacing (voxels)z-s %dzcontrol point spacing (voxels)z-c %dz$spline stiffness weighting parameterz-w %fellipseblockz|Options for type of histogram:

  * ``ellipse``: use ellipsoid for ROI histogram
  * ``block``:use block for ROI histogram

z%sz2iterative mode (overrides -r, -s, -c, -w settings)z	--iteratezlist of parameters z--schedule %sz>save iterative bias field estimates as <prefix>.n.field.nii.gzz--biasprefix %sz8save iterative corrected images as <prefix>.n.bfc.nii.gzz--prefix %sz'apply correction field to entire volumez--extrapolateg      ?zminimum allowed bias valuez-L %f)r   r   r   g      ?zmaximum allowed bias valuez-U %flowmediumhighzPreset options for bias_model

  * low: small bias model [0.95,1.05]
  * medium: medium bias model [0.90,1.10]
  * high: high bias model [0.80,1.20]

analyzeniftigzippedAnalyzegzippedNiftiz@Options for the format in which intermediate files are generatedzconvergence thresholdz--eps %fz:bias estimate convergence threshold (values > 0.1 disable)z	--beps %fzverbosity level (0=silent)z-v %dzdisplay timing informationz--timerN)!r   r   r   r   r   inputMaskFiler   outputBiasFieldoutputMaskedBiasFieldr   r   ZhistogramRadiusZbiasEstimateSpacingZcontrolPointSpacingr   ZsplineLambdaEnumhistogramTyper   ZiterativeModecorrectionScheduleFileStrZbiasFieldEstimatesOutputPrefixZcorrectedImagesOutputPrefixZcorrectWholeVolumeZminBiasZmaxBias	biasRangeintermediate_file_typeZconvergenceThresholdZ biasEstimateConvergenceThresholdr    r!   r"   r"   r"   r#   r6   x   sx   




r6   c               @   s4   e Zd ZeddZeddZeddZeddZdS )BfcOutputSpeczpath/name of output file)r   z#path/name of bias field output filez%path/name of masked bias field outputzpath/name of schedule fileN)r   r   r   r   r   rA   rB   rE   r"   r"   r"   r#   rI      s   


rI   c                   s<   e Zd ZdZeZeZdZdd Z	 fddZ
dd Z  ZS )	Bfca  
    bias field corrector (BFC)
    This program corrects gain variation in T1-weighted MRI.

    http://brainsuite.org/processing/surfaceextraction/bfc/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> bfc = brainsuite.Bfc()
    >>> bfc.inputs.inputMRIFile = example_data('structural.nii')
    >>> bfc.inputs.inputMaskFile = example_data('mask.nii')
    >>> results = bfc.run() #doctest: +SKIP

    Zbfcc             C   sL   | j j }t|| r&tjj|| S ddi}||krHt| j j|| S d S )Nr   z.bfc.nii.gz)r&   r'   r   r(   r)   r*   r+   r   )r,   r-   r&   r.   r"   r"   r#   r/      s    
zBfc._gen_filenamec                sn   |dkr|j ddd|  S |dkr:|j dddd	|  S |d
krZ|j ddddd|  S tt| j|||S )NrD   z	--ellipsez--block)r7   r8   rG   z--lowz--mediumz--high)r9   r:   r;   rH   z	--analyzez--niftiz--analyzegzz	--niftigz)r<   r=   r>   r?   )r   superrJ   _format_arg)r,   r-   specvalue)	__class__r"   r#   rL      s    zBfc._format_argc             C   s   t | S )N)r0   )r,   r"   r"   r#   r1     s    zBfc._list_outputs)r   r   r   r2   r6   r3   rI   r4   r5   r/   rL   r1   __classcell__r"   r"   )rO   r#   rJ      s   rJ   c               @   sz   e Z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j	dddZ
ejdddZejdddZejdddZdS )PvcInputSpecTzMRI filez-i %s)r
   r   r   zbrain mask filez-m %s)r   r   zKoutput label file. If unspecified, output file name will be auto generated.z-o %s)r   r   r   zoutput tissue fraction filez-f %szspatial prior strengthz-l %fzverbosity level (0 = silent)z-v %dz,use a three-class (CSF=0,GM=1,WM=2) labelingz-3ztime processingz--timerN)r   r   r   r   r   r@   outputLabelFileoutputTissueFractionFiler   r   ZspatialPriorr   	verbosityr   ZthreeClassFlagr!   r"   r"   r"   r#   rQ     s   
rQ   c               @   s    e Zd ZeddZeddZdS )PvcOutputSpeczpath/name of label file)r   z!path/name of tissue fraction fileN)r   r   r   r   rR   rS   r"   r"   r"   r#   rU   *  s   
rU   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )PvcaR  
    partial volume classifier (PVC) tool.
    This program performs voxel-wise tissue classification T1-weighted MRI.
    Image should be skull-stripped and bias-corrected before tissue classification.

    http://brainsuite.org/processing/surfaceextraction/pvc/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> pvc = brainsuite.Pvc()
    >>> pvc.inputs.inputMRIFile = example_data('structural.nii')
    >>> pvc.inputs.inputMaskFile = example_data('mask.nii')
    >>> results = pvc.run() #doctest: +SKIP

    Zpvcc             C   sN   | j j }t|| r&tjj|| S ddd}||krJt| j j|| S d S )Nz.pvc.label.nii.gzz.pvc.frac.nii.gz)rR   rS   )r&   r'   r   r(   r)   r*   r+   r   )r,   r-   r&   r.   r"   r"   r#   r/   G  s    
zPvc._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1   U  s    zPvc._list_outputsN)r   r   r   r2   rQ   r3   rU   r4   r5   r/   r1   r"   r"   r"   r#   rV   /  s   rV   c               @   s   e Z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ddddZe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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d)S )*CerebroInputSpecTzinput 3D MRI volumez-i %s)r
   r   r   zatlas MRI volumez
--atlas %szatlas labelingz--atlaslabels %szbrain mask filez-m %s)r   r   zUoutput cerebrum mask volume. If unspecified, output file name will be auto generated.z-o %s)r   r   r   zcoutput labeled hemisphere/cerebrum volume. If unspecified, output file name will be auto generated.z-l %sr   z0,1,2z-c %d)r   r   r   z,use centroids of data to initialize positionz--centroidszsave affine transform to file.z--air %szsave warp transform to file.z	--warp %szverbosity level (0=silent)z-v %dzlinear convergencez--linconv %fzwarp order (2,3,4,5,6,7,8)z--warplevel %dzwarp convergencez--warpconv %fzdon't remove temporary filesz--keepz,specify directory to use for temporary filesz--tempdir %sz2create a temporary directory within this directoryz--tempdirbase %sN)r   r   r   r   r   ZinputAtlasMRIFileZinputAtlasLabelFileZinputBrainMaskFileoutputCerebrumMaskFileoutputLabelVolumeFiler   r   ZcostFunctionr   ZuseCentroidsoutputAffineTransformFileoutputWarpTransformFilerT   r   ZlinearConvergenceZ	warpLabelZwarpConvergenceZkeepTempFilesrF   ZtempDirectoryZtempDirectoryBaser"   r"   r"   r#   rW   Y  s>   

rW   c               @   s4   e Zd ZeddZeddZeddZeddZdS )CerebroOutputSpeczpath/name of cerebrum mask file)r   zpath/name of label mask filez"path/name of affine transform filez path/name of warp transform fileN)r   r   r   r   rX   rY   rZ   r[   r"   r"   r"   r#   r\     s   


r\   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )Cerebroa  
    Cerebrum/cerebellum labeling tool
    This program performs automated labeling of cerebellum and cerebrum in T1 MRI.
    Input MRI should be skull-stripped or a brain-only mask should be provided.


    http://brainsuite.org/processing/surfaceextraction/cerebrum/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> cerebro = brainsuite.Cerebro()
    >>> cerebro.inputs.inputMRIFile = example_data('structural.nii')
    >>> cerebro.inputs.inputAtlasMRIFile = 'atlasMRIVolume.img'
    >>> cerebro.inputs.inputAtlasLabelFile = 'atlasLabels.img'
    >>> cerebro.inputs.inputBrainMaskFile = example_data('mask.nii')
    >>> results = cerebro.run() #doctest: +SKIP

    Zcerebroc             C   sR   | j j }t|| r&tjj|| S ddddd}||krNt| j j|| S d S )Nz.cerebrum.mask.nii.gzz.hemi.label.nii.gzz.warpz.air)rX   rY   r[   rZ   )r&   r'   r   r(   r)   r*   r+   r   )r,   r-   r&   r.   r"   r"   r#   r/     s    
zCerebro._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1     s    zCerebro._list_outputsN)r   r   r   r2   rW   r3   r\   r4   r5   r/   r1   r"   r"   r"   r#   r]     s   r]   c               @   s   e Zd ZeddddZeddddZe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Zej
dddddZejdddZej
dddZdS )CortexInputSpecTzhemisphere / lobe label volumez-h %s)r
   r   r   zOoutput structure mask. If unspecified, output file name will be auto generated.z-o %s)r   r   r   z#tissue fraction file (32-bit float)z-f %sg      I@z&tissue fraction threshold (percentage)z-p %f)r   r   r   zcompute WM/GM boundaryz-wzcompute GM/CSF boundaryz-g)r   r   z(include all subcortical areas in WM maskz-azverbosity levelz-v %dztiming functionz--timerN)r   r   r   r   inputHemisphereLabelFileoutputCerebrumMaskinputTissueFractionFiler   r   ZtissueFractionThresholdr   ZcomputeWGBoundaryZcomputeGCBoundaryZincludeAllSubcorticalAreasr   rT   r!   r"   r"   r"   r#   r^     s.   r^   c               @   s   e Zd ZeddZdS )CortexOutputSpeczpath/name of cerebrum mask)r   N)r   r   r   r   r`   r"   r"   r"   r#   rb     s   rb   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )CortexaC  
    cortex extractor
    This program produces a cortical mask using tissue fraction estimates
    and a co-registered cerebellum/hemisphere mask.

    http://brainsuite.org/processing/surfaceextraction/cortex/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> cortex = brainsuite.Cortex()
    >>> cortex.inputs.inputHemisphereLabelFile = example_data('mask.nii')
    >>> cortex.inputs.inputTissueFractionFile = example_data('tissues.nii.gz')
    >>> results = cortex.run() #doctest: +SKIP

    Zcortexc             C   s@   | j j }t|| r&tjj|| S |dkr<t| j jdS d S )Nr`   z.init.cortex.mask.nii.gz)r&   r'   r   r(   r)   r*   r+   r_   )r,   r-   r&   r"   r"   r#   r/     s    
zCortex._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1     s    zCortex._list_outputsN)r   r   r   r2   r^   r3   rb   r4   r5   r/   r1   r"   r"   r"   r#   rc     s   rc   c               @   sv   e Zd ZeddddZe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Z
ejdddZejdddZdS )ScrubmaskInputSpecTzinput structure mask filez-i %s)r
   r   r   zToutput structure mask file. If unspecified, output file name will be auto generated.z-o %s)r   r   r   r   zbackground fill thresholdz-b %d)r   r   r   r   zforeground trim thresholdz-f %dznumber of iterationsz-n %d)r   r   zverbosity (0=silent)z-v %dztiming functionz--timerN)r   r   r   r   r@   r   r   r   ZbackgroundFillThresholdZforegroundTrimThresholdZnumberIterationsrT   r   r!   r"   r"   r"   r#   rd     s   rd   c               @   s   e Zd ZeddZdS )ScrubmaskOutputSpeczpath/name of mask file)r   N)r   r   r   r   r   r"   r"   r"   r#   re     s   re   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )	Scrubmaska  
    ScrubMask tool
    scrubmask filters binary masks to trim loosely connected voxels that may
    result from segmentation errors and produce bumps on tessellated surfaces.

    http://brainsuite.org/processing/surfaceextraction/scrubmask/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> scrubmask = brainsuite.Scrubmask()
    >>> scrubmask.inputs.inputMaskFile = example_data('mask.nii')
    >>> results = scrubmask.run() #doctest: +SKIP

    Z	scrubmaskc             C   s@   | j j }t|| r&tjj|| S |dkr<t| j jdS d S )Nr   z.cortex.scrubbed.mask.nii.gz)r&   r'   r   r(   r)   r*   r+   r@   )r,   r-   r&   r"   r"   r#   r/   4  s    
zScrubmask._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1   @  s    zScrubmask._list_outputsN)r   r   r   r2   rd   r3   re   r4   r5   r/   r1   r"   r"   r"   r#   rf     s   rf   c               @   sv   e Zd ZeddddZeddddZejddd	d
dZejdddZ	ejdddddZ
ejdddZejdddZdS )TcaInputSpecTzinput mask volumez-i %s)r
   r   r   zLoutput mask volume. If unspecified, output file name will be auto generated.z-o %s)r   r   r   i	  zmaximum correction sizez-m %d)r   r   r   zminimum correction sizez-n %d)r   r      zforeground deltaz
--delta %dzverbosity (0 = quiet)z-v %dztiming functionz--timerN)r   r   r   r   r@   r   r   r   ZminCorrectionSizeZmaxCorrectionSizeZforegroundDeltarT   r   r!   r"   r"   r"   r#   rg   D  s   rg   c               @   s   e Zd ZeddZdS )TcaOutputSpeczpath/name of mask file)r   N)r   r   r   r   r   r"   r"   r"   r#   ri   V  s   ri   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )Tcaa  
    topological correction algorithm (TCA)
    This program removes topological handles from a binary object.

    http://brainsuite.org/processing/surfaceextraction/tca/

    Examples
    --------
    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> tca = brainsuite.Tca()
    >>> tca.inputs.inputMaskFile = example_data('mask.nii')
    >>> results = tca.run() #doctest: +SKIP

    Ztcac             C   s@   | j j }t|| r&tjj|| S |dkr<t| j jdS d S )Nr   z.cortex.tca.mask.nii.gz)r&   r'   r   r(   r)   r*   r+   r@   )r,   r-   r&   r"   r"   r#   r/   o  s    
zTca._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1   y  s    zTca._list_outputsN)r   r   r   r2   rg   r3   ri   r4   r5   r/   r1   r"   r"   r"   r#   rj   Z  s   
rj   c               @   s`   e Z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
ZdS )DewispInputSpecTz
input filez-i %s)r
   r   r   zEoutput file. If unspecified, output file name will be auto generated.z-o %s)r   r   r   rT   z-v %d)r   r   zsize thresholdz-t %dzmaximum number of iterationsz-n %dztime processingz--timerN)r   r   r   r   r@   r   r   r   rT   ZsizeThresholdZmaximumIterationsr   r!   r"   r"   r"   r#   rk   }  s   rk   c               @   s   e Zd ZeddZdS )DewispOutputSpeczpath/name of mask file)r   N)r   r   r   r   r   r"   r"   r"   r#   rl     s   rl   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )Dewispa  
    dewisp
    removes wispy tendril structures from cortex model binary masks.
    It does so based on graph theoretic analysis of connected components,
    similar to TCA. Each branch of the structure graph is analyzed to determine
    pinch points that indicate a likely error in segmentation that attaches noise
    to the image. The pinch threshold determines how many voxels the cross-section
    can be before it is considered part of the image.

    http://brainsuite.org/processing/surfaceextraction/dewisp/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> dewisp = brainsuite.Dewisp()
    >>> dewisp.inputs.inputMaskFile = example_data('mask.nii')
    >>> results = dewisp.run() #doctest: +SKIP

    Zdewispc             C   s@   | j j }t|| r&tjj|| S |dkr<t| j jdS d S )Nr   z.cortex.dewisp.mask.nii.gz)r&   r'   r   r(   r)   r*   r+   r@   )r,   r-   r&   r"   r"   r#   r/     s    
zDewisp._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1     s    zDewisp._list_outputsN)r   r   r   r2   rk   r3   rl   r4   r5   r/   r1   r"   r"   r"   r#   rm     s   
rm   c            
   @   s   e Zd ZeddddZeddddZe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j
ddd
Zejddd1dZej
ddd
Zejddd d!d"d2d#gd3d%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d0S )4DfsInputSpecTzinput 3D volumez-i %s)r
   r   r   zRoutput surface mesh file. If unspecified, output file name will be auto generated.z-o %s)r   r   r   z/shade surface model with data from image volumez-c %s)r   r   
   znumber of smoothing iterationsz-n %d)r   r   r   g      ?zsmoothing constantz-a %fg      @zcurvature weightingz-w %fzscaling percentilez-f %fztessellate non-zero voxelsz-nznonZeroTessellationspecialTessellation)r   r   xorzTo be used with specialTessellation. Set this value first, then set specialTessellation value.
Usage: tessellate voxels greater_than, less_than, or equal_to <tessellationThreshold>z%fgreater_than	less_thanequal_tozTo avoid throwing a UserWarning, set tessellationThreshold first. Then set this attribute.
Usage: tessellate voxels greater_than, less_than, or equal_to <tessellationThreshold>z%stessellationThresholdr   )r   r   rr   requirespositionz*zero-pad volume (avoids clipping at edges)z-zzdo not compute vertex normalsz--nonormalszsmooth vertices after coloringz--postsmoothzverbosity (0 = quiet)z-v %dztiming functionz--timerN)rp   rq   )rp   rq   )r   r   r   r   inputVolumeFileoutputSurfaceFileZinputShadingVolumer   r   ZsmoothingIterationsr   ZsmoothingConstantZcurvatureWeightingZscalingPercentiler   rp   rv   rC   rq   ZzeroPadFlagZnoNormalsFlagZpostSmoothFlagrT   r!   r"   r"   r"   r#   rn     sL   



rn   c               @   s   e Zd ZeddZdS )DfsOutputSpeczpath/name of surface file)r   N)r   r   r   r   r{   r"   r"   r"   r#   r|     s   r|   c                   s<   e Zd ZdZeZeZdZ fddZ	dd Z
dd Z  ZS )	Dfsa  
    Surface Generator
    Generates mesh surfaces using an isosurface algorithm.

    http://brainsuite.org/processing/surfaceextraction/inner-cortical-surface/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> dfs = brainsuite.Dfs()
    >>> dfs.inputs.inputVolumeFile = example_data('structural.nii')
    >>> results = dfs.run() #doctest: +SKIP

    dfsc                sd   |dkrdS |dkrP| j j}|jdjd| djd| djd| d|  S tt| j|||S )Nrv    rq   z-gt %fz-lt %fz-eq %f)rs   rt   ru   )r&   rv   r   joinrK   r}   rL   )r,   r-   rM   rN   	threshold)rO   r"   r#   rL     s    zDfs._format_argc             C   s@   | j j }t|| r&tjj|| S |dkr<t| j jdS d S )Nr{   z.inner.cortex.dfs)r&   r'   r   r(   r)   r*   r+   rz   )r,   r-   r&   r"   r"   r#   r/     s    
zDfs._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1     s    zDfs._list_outputs)r   r   r   r2   rn   r3   r|   r4   r5   rL   r/   r1   rP   r"   r"   )rO   r#   r}     s   
r}   c               @   s  e Zd ZeddddZeddddZejdd	d
Ze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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j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,d-dZejd.d/d
Zd0S )1PialmeshInputSpecTz
input filez-i %s)r
   r   r   zEoutput file. If unspecified, output file name will be auto generated.z-o %s)r   r   r   rT   z-v %d)r   r   z)floating point (32) tissue fraction imagez-f %sd   znumber of iterationsz-n %d)r   r   r   r   zsearch radiusz-r %fg?z	step sizez-s %fz#restrict growth to mask file regionz-m %srh   z maximum allowed tissue thicknessz--max %fg?ztissue thresholdz-t %fro   zoutput intervalz--interval %dz0prefix for exporting surfaces if interval is setz--prefix %sg?zapply Laplacian smoothingz--smooth %fzshow timingz--timerz#recompute normals at each iterationz--normg?zstrength of normal smoother.z--nc %fz strength of tangential smoother.z--tc %fN)r   r   r   r   inputSurfaceFiler{   r   r   rT   ra   ZnumIterationsr   ZsearchRadiusZstepSizer@   ZmaxThicknessZtissueThresholdZoutputIntervalrF   ZexportPrefixZlaplacianSmoothingr   r!   ZrecomputeNormalsZnormalSmootherZtangentSmootherr"   r"   r"   r#   r   "  s@   

r   c               @   s   e Zd ZeddZdS )PialmeshOutputSpeczpath/name of surface file)r   N)r   r   r   r   r{   r"   r"   r"   r#   r   T  s   r   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )PialmeshaA  
    pialmesh
    computes a pial surface model using an inner WM/GM mesh and a tissue fraction map.

    http://brainsuite.org/processing/surfaceextraction/pial/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> pialmesh = brainsuite.Pialmesh()
    >>> pialmesh.inputs.inputSurfaceFile = 'input_mesh.dfs'
    >>> pialmesh.inputs.inputTissueFractionFile = 'frac_file.nii.gz'
    >>> pialmesh.inputs.inputMaskFile = example_data('mask.nii')
    >>> results = pialmesh.run() #doctest: +SKIP

    Zpialmeshc             C   s@   | j j }t|| r&tjj|| S |dkr<t| j jdS d S )Nr{   z.pial.cortex.dfs)r&   r'   r   r(   r)   r*   r+   r   )r,   r-   r&   r"   r"   r#   r/   p  s    
zPialmesh._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1   z  s    zPialmesh._list_outputsN)r   r   r   r2   r   r3   r   r4   r5   r/   r1   r"   r"   r"   r#   r   X  s   
r   c               @   s   e Z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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 )HemisplitInputSpecTzinput surfacez-i %s)r
   r   r   zinput hemisphere label volumez-l %sz^output surface file, left hemisphere. If unspecified, output file name will be auto generated.z	--left %s)r   r   r   z_output surface file, right hemisphere. If unspecified, output file name will be auto generated.z
--right %sz=pial surface file -- must have same geometry as input surfacez-p %s)r   r   zcoutput pial surface file, left hemisphere. If unspecified, output file name will be auto generated.z-pl %szdoutput pial surface file, right hemisphere. If unspecified, output file name will be auto generated.z-pr %szverbosity (0 = silent)z-v %dztiming functionz--timerN)r   r   r   r   r   r_   outputLeftHemisphereoutputRightHemisphereZpialSurfaceFileoutputLeftPialHemisphereoutputRightPialHemispherer   r   rT   r   r!   r"   r"   r"   r#   r   ~  s0   r   c               @   s4   e Zd ZeddZeddZeddZeddZdS )HemisplitOutputSpeczpath/name of left hemisphere)r   zpath/name of right hemispherez!path/name of left pial hemispherez"path/name of right pial hemisphereN)r   r   r   r   r   r   r   r   r"   r"   r"   r#   r     s   


r   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )	Hemisplita  
    Hemisphere splitter
    Splits a surface object into two separate surfaces given an input label volume.
    Each vertex is labeled left or right based on the labels being odd (left) or even (right).
    The largest contour on the split surface is then found and used as the separation between left and right.

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> hemisplit = brainsuite.Hemisplit()
    >>> hemisplit.inputs.inputSurfaceFile = 'input_surf.dfs'
    >>> hemisplit.inputs.inputHemisphereLabelFile = 'label.nii'
    >>> hemisplit.inputs.pialSurfaceFile = 'pial.dfs'
    >>> results = hemisplit.run() #doctest: +SKIP

    Z	hemisplitc             C   sR   | j j }t|| r&tjj|| S ddddd}||krNt| j j|| S d S )Nz.left.inner.cortex.dfsz.left.pial.cortex.dfsz.right.inner.cortex.dfsz.right.pial.cortex.dfs)r   r   r   r   )r&   r'   r   r(   r)   r*   r+   r   )r,   r-   r&   r.   r"   r"   r#   r/     s    
zHemisplit._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1     s    zHemisplit._list_outputsN)r   r   r   r2   r   r3   r   r4   r5   r/   r1   r"   r"   r"   r#   r     s   r   c               @   s   e Zd Ze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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dS ) SkullfinderInputSpecTz
input filez-i %s)r
   r   r   z7A brain mask file, 8-bit image (0=non-brain, 255=brain)z-m %szoutput multi-colored label volume segmenting brain, scalp, inner skull & outer skull If unspecified, output file name will be auto generated.z-o %s)r   r   r   rT   z-v %d)r   r   z Lower threshold for segmentationz-l %dz Upper threshold for segmentationz-u %dz@if specified, generate surface files for brain, skull, and scalpz-s %szbackground label value (0-255)z--bglabel %dzscalp label value (0-255)z--scalplabel %dzskull label value (0-255)z--skulllabel %dzspace label value (0-255)z--spacelabel %dzbrain label value (0-255)z--brainlabel %dz3perform a final opening operation on the scalp maskz--finalOpeningN)r   r   r   r   r   r@   rR   r   r   rT   ZlowerThresholdZupperThresholdrF   ZsurfaceFilePrefixZbgLabelValueZscalpLabelValueZskullLabelValueZspaceLabelValueZbrainLabelValuer   ZperformFinalOpeningr"   r"   r"   r#   r     s8   




r   c               @   s   e Zd ZeddZdS )SkullfinderOutputSpeczpath/name of label file)r   N)r   r   r   r   rR   r"   r"   r"   r#   r     s   r   c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )Skullfindera  
    Skull and scalp segmentation algorithm.

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> from nipype.testing import example_data
    >>> skullfinder = brainsuite.Skullfinder()
    >>> skullfinder.inputs.inputMRIFile = example_data('structural.nii')
    >>> skullfinder.inputs.inputMaskFile = example_data('mask.nii')
    >>> results = skullfinder.run() #doctest: +SKIP

    Zskullfinderc             C   s@   | j j }t|| r&tjj|| S |dkr<t| j jdS d S )NrR   z.skullfinder.label.nii.gz)r&   r'   r   r(   r)   r*   r+   r   )r,   r-   r&   r"   r"   r#   r/     s    
zSkullfinder._gen_filenamec             C   s   t | S )N)r0   )r,   r"   r"   r#   r1     s    zSkullfinder._list_outputsN)r   r   r   r2   r   r3   r   r4   r5   r/   r1   r"   r"   r"   r#   r     s   
r   c               @   sF  e Zd ZejdddddZejejdddZej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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d5Zejd!ed"d#Zejd$ed%d#Zejd&e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d0d1dZejd2d3dZd4S )6SVRegInputSpecz'%s'Tr   zmAbsolute path and filename prefix of the subjects output from BrainSuite Cortical Surface Extraction Sequence)r   r
   rx   r   z%sa  Connect datasink out_file to dataSinkDelay to delay execution of SVReg until dataSink has finished sinking CSE outputs.For use with parallel processing workflows including Brainsuites Cortical Surface Extraction sequence (SVReg requires certain files from Brainsuite CSE, which must all be in the pathway specified by subjectFilePrefix. see http://brainsuite.org/processing/svreg/usage/ for list of required inputs )r   r   r   zOptional: Absolute Path and filename prefix of atlas files and labels to which the subject will be registered. If unspecified, SVRegwill use its own included atlas files)rx   r   r   z'-H %d'ziAssigns a number of iterations in the intensity registration step.if unspecified, performs 100 iterationsz'-r'z6Refine outputs at the expense of more processing time.z'-s'a  If surface registration was already performed at an earlier time and the user would not like to redo this step, then this flag may be used to skip ahead to the volumetric registration. Necessary input files will need to be present in the input directory called by the command.z'-p'zIf the p-harmonic volumetric registration was already performed at an earlier time and the user would not like to redo this step, then this flag may be used to skip ahead to the intensity registration and label transfer step.z'-cbm'zCan call a manually edited cerebrum mask to limit boundaries. Will use file: subbasename.cerebrum.mask.nii.gz Make sure to correctly replace your manually edited mask file in your input folder with the correct subbasename.z	'-cur %s'a  Used to take control of the curve matching process between the atlas and subject. One can specify the name of the .dfc file <sulname.dfc> and the sulcal numbers <#sul> to be used as constraints. example: curveMatchingInstructions = "subbasename.right.dfc 1 2 20"z'-C'zThe cerebrum mask <subbasename.cerebrum.mask.nii.gz> will be used for masking the final labels instead of the default pial surface mask. Every voxel will be labeled within the cerebrum mask regardless of the boundaries of the pial surface.z'-D %d'a  Cortical volume labels found in file output subbasename.svreg.label.nii.gz find its boundaries by using the pial surface then dilating by 1 voxel. Use this flag in order to control the number of pial surface mask dilation. (ie. -D 0 will assign no voxel dilation)z'-k'zAKeep the intermediate files after the svreg sequence is complete.
verbosity0
verbosity1
verbosity2z'-v0'zno messages will be reported)r   rr   r   z'-v1'zFmessages will be reported but not the iteration-wise detailed messagesz'v2'z<all the messages, including per-iteration, will be displayedz'-gui'z+Short messages instead of detailed messagesz'-m'z-Module name will be displayed in the messagesz'-t'z,Timestamps will be displayed in the messagesz'-S'z`Only surface registration and labeling will be performed. Volumetric processing will be skipped.z'-P'zoIf multiple CPUs are present on the system, the code will try to use multithreading to make the execution fast.z'-U'zUse single threaded mode.N)r   r   r   )r   r   r   r   rF   subjectFilePrefixListdataSinkDelayatlasFilePrefixr   Z
iterationsr   ZrefineOutputsZskipToVolumeRegZskipToIntensityRegZuseManualMaskFilecurveMatchingInstructionsZuseCerebrumMaskZpialSurfaceMaskDilationZkeepIntermediatesZ_XOR_verbosityr   r   r   ZshortMessagesZdisplayModuleNameZdisplayTimestampsZskipVolumetricProcessingZuseMultiThreadingZuseSingleThreadingr"   r"   r"   r#   r   !  s~   



r   c                   s(   e Zd ZdZeZdZ fddZ  ZS )SVRega   
    surface and volume registration (svreg)
    This program registers a subject's BrainSuite-processed volume and surfaces
    to an atlas, allowing for automatic labelling of volume and surface ROIs.

    For more information, please see:
    http://brainsuite.org/processing/svreg/usage/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> svreg = brainsuite.SVReg()
    >>> svreg.inputs.subjectFilePrefix = 'home/user/btestsubject/testsubject'
    >>> svreg.inputs.refineOutputs = True
    >>> svreg.inputs.skipToVolumeReg = False
    >>> svreg.inputs. keepIntermediates = True
    >>> svreg.inputs.verbosity2 = True
    >>> svreg.inputs.displayTimestamps = True
    >>> svreg.inputs.useSingleThreading = True
    >>> results = svreg.run() #doctest: +SKIP


    zsvreg.shc                sP   |dks|dks|dkr*|j tjj| S |dkr<|j d S tt| j|||S )Nr   r   r   r   r   )r   r(   r)   
expanduserrK   r   rL   )r,   r-   rM   rN   )rO   r"   r#   rL     s    
zSVReg._format_arg)	r   r   r   r2   r   r3   r5   rL   rP   r"   r"   )rO   r#   r     s   r   c            
   @   s  e Zd ZeddddgddZejddddgd	dZed
ddddZedddgdddZ	ej
ejdddddgdddZej
ej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jd)d*dZejd+d,dZejd-d.dZed/d0dZed1d2dZejd3d4d5d6d7dZejd3d8d9d:d5d;d<dZejd=d>dZejd?d@dZejdAdBdZejdCdDgdEdFZedGdHgdIdJZ ejdKdLdMgdNdOdPZ!ejdQdRdZ"ejdSdTdZ#edUdVdZ$edWdXdZ%ejdYdZd[d\d]d^dZ&ed_d`dZ'edadbdZ(ejdcdddZ)ejdedfdZ*ejdgdhdZ+ejdidjdZ,edkdldZ-edmdndZ.edodpdZ/ejdqdrdZ0ejdsdtdZ1edudvdZ2ejdwdxdZ3ej4dydzdZ5ejd{d|dZ6ejd}d~dZ7dS )BDPInputSpecz%sTr   noStructuralRegistrationzqSpecify absolute path to file produced by bfc. By default, bfc produces the file in the format: prefix.bfc.nii.gz)r   r
   rx   rr   r   z--no-structural-registrationbfcFileaQ  Allows BDP to work without any structural input. This can useful when one is only interested in diffusion modelling part of BDP. With this flag only fieldmap-based distortion correction is supported. outPrefix can be used to specify fileprefix of the output filenames. Change dwiMask to define region of interest for diffusion modelling.z--nii %sr   aw  Specifies the absolute path and filename of the input diffusion data in 4D NIfTI-1 format. The flag must be followed by the filename. Only NIfTI-1 files with extension .nii or .nii.gz are supported. Furthermore, either  bMatrixFile, or a combination of both bValueFile and diffusionGradientFile must be used to provide the necessary b-matrices/b-values and gradient vectors. )r   r
   rx   r   z	--bmat %sBVecBValPairr   a  Specifies the absolute path and filename of the file containing b-matrices for diffusion-weighted scans. The flag must be followed by the filename. This file must be a plain text file containing 3x3 matrices for each diffusion encoding direction. It should contain zero matrices corresponding to b=0 images. This file usually has ".bmat" as its extension, and can be used to provide BDP with the more-accurate b-matrices as saved by some proprietary scanners. The b-matrices specified by the file must be in the voxel coordinates of the input diffusion weighted image (NIfTI file). In case b-matrices are not known/calculated, bvec and .bval files can be used instead (see diffusionGradientFile and bValueFile). )r   r
   rr   rx   r   bMatrixFilez--bvec %s --bval %sa  Must input a list containing first the BVector file, then the BValue file (both must be absolute paths)
Example: bdp.inputs.BVecBValPair = ['/directory/subdir/prefix.dwi.bvec', '/directory/subdir/prefix.dwi.bval'] The first item in the list specifies the filename of the file containing b-values for the diffusion scan. The b-value file must be a plain-text file and usually has an extension of .bval
The second item in the list specifies the filename of the file containing the diffusion gradient directions (specified in the voxel coordinates of the input diffusion-weighted image)The b-vectors file must be a plain text file and usually has an extension of .bvec )Zminlenmaxlenr
   rx   rr   r   r   aY  For use in parallel processing workflows including Brainsuite Cortical Surface Extraction sequence. Connect datasink out_file to dataSinkDelay to delay execution of BDP until dataSink has finished sinking outputs. In particular, BDP may be run after BFC has finished. For more information see http://brainsuite.org/processing/diffusion/pipeline/)r   r   xzx-yzy-zzz-z--dir=%sa  Specifies the phase-encoding direction of the EPI (diffusion) images. It is same as the dominant direction of distortion in the images. This information is used to constrain the distortion correction along the specified direction. Directions are represented by any one of x, x-, y, y-, z or z-. "x" direction increases towards the right side of the subject, while "x-" increases towards the left side of the subject. Similarly, "y" and "y-" are along the anterior-posterior direction of the subject, and "z" & "z-" are along the inferior-superior direction. When this flag is not used, BDP uses "y" as the default phase-encoding direction. z--echo-spacing=%fzSets the echo spacing to t seconds, which is used for fieldmap-based distortion correction. This flag is required when using fieldmapCorrectionz--bval-ratio-threshold %fa  Sets a threshold which is used to determine b=0 images. When there are no diffusion weighted image with b-value of zero, then BDP tries to use diffusion weighted images with a low b-value in place of b=0 image. The diffusion images with minimum b-value is used as b=0 image only if the ratio of the maximum and minimum b-value is more than the specified threshold. A lower value of threshold will allow diffusion images with higher b-value to be used as b=0 image. The default value of this threshold is set to 45, if this trait is not set. z	--tensorsa  Estimates diffusion tensors using a weighted log-linear estimation and saves derived diffusion tensor parameters (FA, MD, axial, radial, L2, L3). This is the default behavior if no diffusion modeling flags are specified. The estimated diffusion tensors can be visualized by loading the saved ``*.eig.nii.gz`` file in BrainSuite. BDP reports diffusivity (MD, axial, radial, L2 and L3) in a unit which is reciprocal inverse of the unit of input b-value. z--FRACTzEstimates ODFs using the Funk-Radon and Cosine Transformation (FRACT). The outputs are saved in a separate directory with name "FRACT" and the ODFs can be visualized by loading the saved ".odf" file in BrainSuite. z--FRTa#  Estimates ODFs using Funk-Radon Transformation (FRT). The coefficient maps for ODFs are saved in a separate directory with name "FRT" and the ODFs can be visualized by loading the saved ".odf" file in BrainSuite. The derived generalized-FA (GFA) maps are also saved in the output directory. z --3dshore --diffusion_time_ms %fz;Estimates ODFs using 3Dshore. Pass in diffusion time, in msz--odf-lambda <L>zSets the regularization parameter, lambda, of the Laplace-Beltrami operator while estimating ODFs. The default value is set to 0.006 . This can be used to set the appropriate regularization for the input diffusion data. z--t1-mask %sa  Specifies the filename of the brain-mask file for input T1-weighted image. This mask can be same as the brain mask generated during BrainSuite extraction sequence. For best results, the mask should not include any extra-meningial tissues from T1-weighted image. The mask must be in the same coordinates as input T1-weighted image (i.e. should overlay correctly with input <fileprefix>.bfc.nii.gz file in BrainSuite). This mask is used for co-registration and defining brain boundary for statistics computation. The mask can be generated and/or edited in BrainSuite. In case outputDiffusionCoordinates is also used, this mask is first transformed to diffusion coordinate and the transformed mask is used for defining brain boundary in diffusion coordinates. When t1Mask is not set, BDP will try to use fileprefix>.mask.nii.gz as brain-mask. If <fileprefix>.mask.nii.gz is not found, then BDP will use the input <fileprefix>.bfc.nii.gz itself as mask (i.e. all non-zero voxels in <fileprefix>.bfc.nii.gz is assumed to constitute brain mask).  z--dwi-mask %saM  Specifies the filename of the brain-mask file for diffusion data. This mask is used only for co-registration purposes and can affect overall quality of co-registration (see t1Mask for definition of brain mask for statistics computation). The mask must be a 3D volume and should be in the same coordinates as input Diffusion file/data (i.e. should overlay correctly with input diffusion data in BrainSuite). For best results, the mask should include only brain voxels (CSF voxels around brain is also acceptable). When this flag is not used, BDP will generate a pseudo mask using first b=0 image volume and would save it as fileprefix>.dwi.RSA.mask.nii.gz. In case co-registration is not accurate with automatically generated pseudo mask, BDP should be re-run with a refined diffusion mask. The mask can be generated and/or edited in BrainSuite. ZMIZ	INVERSIONBDPz--rigid-reg-measure %sa  Defines the similarity measure to be used for rigid registration. Possible measures are "MI", "INVERSION" and "BDP". MI measure uses normalized mutual information based cost function. INVERSION measure uses simpler cost function based on sum of squared difference by exploiting the approximate inverse-contrast relationship in T1- and T2-weighted images. BDP measure combines MI and INVERSION. It starts with INVERSION measure and refines the result with MI measure. BDP is the default measure when this trait is not set.  zINVERSION-EPIzINVERSION-T1zINVERSION-BOTHz--dcorr-reg-method %sa  Defines the method for registration-based distortion correction. Possible methods are "MI", "INVERSION-EPI", "INVERSION-T1", INVERSION-BOTH", and "BDP". MI method uses normalized mutual information based cost-function while estimating the distortion field. INVERSION-based method uses simpler cost function based on sum of squared difference by exploiting the known approximate contrast relationship in T1- and T2-weighted images. T2-weighted EPI is inverted when INVERSION-EPI is used; T1-image is inverted when INVERSION-T1 is used; and both are inverted when INVERSION-BOTH is used. BDP method add the MI-based refinement after the correction using INVERSION-BOTH method. BDP is the default method when this trait is not set.  z--dcorr-regularization-wt %fa  Sets the (scalar) weighting parameter for regularization penalty in registration-based distortion correction. Set this trait to a single, non-negative number which specifies the weight. A large regularization weight encourages smoother distortion field at the cost of low measure of image similarity after distortion correction. On the other hand, a smaller regularization weight can result into higher measure of image similarity but with unrealistic and unsmooth distortion field. A weight of 0.5 would reduce the penalty to half of the default regularization penalty (By default, this weight is set to 1.0). Similarly, a weight of 2.0 would increase the penalty to twice of the default penalty.  z--no-distortion-correctionzSkips distortion correction completely and performs only a rigid registration of diffusion and T1-weighted image. This can be useful when the input diffusion images do not have any distortion or they have been corrected for distortion. z--no-nonuniformity-correctionzSkips intensity non-uniformity correction in b=0 image for registration-based distortion correction. The intensity non-uniformity correction does not affect any diffusion modeling. z--no-intensity-correctionfieldmapCorrectionMethodzDisables intensity correction when performing distortion correction. Intensity correction can change the noise distribution in the corrected image, but it does not affect estimated diffusion parameters like FA, etc. )r   rr   r   z--fieldmap-correction %sechoSpacinga  Use an acquired fieldmap for distortion correction. The fieldmap must have units of radians/second. Specify the filename of the fieldmap file. The field of view (FOV) of the fieldmap scan must cover the FOV of the diffusion scan. BDP will try to check the overlap of the FOV of the two scans and will issue a warning/error if the diffusion scan"s FOV is not fully covered by the fieldmap"s FOV. BDP uses all of the information saved in the NIfTI header to compute the FOV. If you get this error and think that it is incorrect, then it can be suppressed using the flag ignore-fieldmap-FOV. Neither the image matrix size nor the imaging grid resolution of the fieldmap needs to be the same as that of the diffusion scan, but the fieldmap must be pre-registred to the diffusion scan. BDP does NOT align the fieldmap to the diffusion scan, nor does it check the alignment of the fieldmap and diffusion scans. Only NIfTI files with extension of .nii or .nii.gz are supported. Fieldmap-based distortion correction also requires the echoSpacing. Also fieldmapCorrectionMethod allows you to define method for distortion correction. least squares is the default method. )r   rw   r   Z
pixelshiftZleastsqskipIntensityCorrz--fieldmap-correction-method %sa  Defines the distortion correction method while using fieldmap. Possible methods are "pixelshift" and "leastsq". leastsq is the default method when this flag is not used. Pixel-shift (pixelshift) method uses image interpolation to un-distort the distorted diffusion images. Least squares (leastsq) method uses a physical model of distortion which is more accurate (and more computationally expensive) than pixel-shift method.)rr   r   r   z--ignore-fieldmap-fovzSupresses the error generated by an insufficient field of view of the input fieldmap and continues with the processing. It is useful only when used with fieldmap-based distortion correction. See fieldmap-correction for a detailed explanation. z--fieldmap-smooth3=%fzApplies 3D Gaussian smoothing with a standard deviation of S millimeters (mm) to the input fieldmap before applying distortion correction. This trait is only useful with fieldmapCorrection. Skip this trait for no smoothing. z--transform-diffusion-volume %sa  This flag allows to define custom volumes in diffusion coordinate which would be transformed into T1 coordinate in a rigid fashion. The flag must be followed by the name of either a NIfTI file or of a folder that contains one or more NIfTI files. All of the files must be in diffusion coordinate, i.e. the files should overlay correctly with the diffusion scan in BrainSuite. Only NIfTI files with an extension of .nii or .nii.gz are supported. The transformed files are written to the output directory with suffix ".T1_coord" in the filename and will not be corrected for distortion, if any. The trait transformInterpolation can be used to define the type of interpolation that would be used (default is set to linear). If you are attempting to transform a label file or mask file, use "nearest" interpolation method with transformInterpolation. See also transformT1Volume and transformInterpolationz--transform-t1-volume %sa  Same as transformDiffusionVolume except that files specified must be in T1 coordinate, i.e. the files should overlay correctly with the input <fileprefix>.bfc.nii.gz files in BrainSuite. BDP transforms these data/images from T1 coordinate to diffusion coordinate. The transformed files are written to the output directory with suffix ".D_coord" in the filename. See also transformDiffusionVolume  and transformInterpolation. ZlinearZnearestZcubicZsplinez--transform-interpolation %szDefines the type of interpolation method which would be used while transforming volumes defined by transformT1Volume and transformDiffusionVolume. Possible methods are "linear", "nearest", "cubic" and "spline". By default, "linear" interpolation is used. z--transform-t1-surface %sa  Similar to transformT1Volume, except that this flag allows transforming surfaces (instead of volumes) in T1 coordinate into diffusion coordinate in a rigid fashion. The flag must be followed by the name of either a .dfs file or of a folder that contains one or more dfs files. All of the files must be in T1 coordinate, i.e. the files should overlay correctly with the T1-weighted scan in BrainSuite. The transformed files are written to the output directory with suffix D_coord" in the filename. z --transform-diffusion-surface %sa7  Same as transformT1Volume, except that the .dfs files specified must be in diffusion coordinate, i.e. the surface files should overlay correctly with the diffusion scan in BrainSuite. The transformed files are written to the output directory with suffix ".T1_coord" in the filename. See also transformT1Volume. z--transform-data-onlya  Skip all of the processing (co-registration, distortion correction and tensor/ODF estimation) and directly start transformation of defined custom volumes, mask and labels (using transformT1Volume, transformDiffusionVolume, transformT1Surface, transformDiffusionSurface, customDiffusionLabel, customT1Label). This flag is useful when BDP was previously run on a subject (or <fileprefix>) and some more data (volumes, mask or labels) need to be transformed across the T1-diffusion coordinate spaces. This assumes that all the necessary files were generated earlier and all of the other flags MUST be used in the same way as they were in the initial BDP run that processed the data. z--generate-statsa  Generate ROI-wise statistics of estimated diffusion tensor parameters. Units of the reported statistics are same as that of the estimated tensor parameters (see estimateTensors). Mean, variance, and voxel counts of white matter(WM), grey matter(GM), and both WM and GM combined are written for each estimated parameter in a separate comma-seperated value csv) file. BDP uses the ROI labels generated by Surface-Volume Registration (SVReg) in the BrainSuite extraction sequence. Specifically, it looks for labels saved in either fileprefix>.svreg.corr.label.nii.gz or <fileprefix>.svreg.label.nii.gz. In case both files are present, only the first file is used. Also see customDiffusionLabel and customT1Label for specifying your own ROIs. It is also possible to forgo computing the SVReg ROI-wise statistics and only compute stats with custom labels if SVReg label is missing. BDP also transfers (and saves) the label/mask files to appropriate coordinates before computing statistics. Also see outputDiffusionCoordinates for outputs in diffusion coordinate and forcePartialROIStats for an important note about field of view of diffusion and T1-weighted scans. z--generate-only-statsa  Skip all of the processing (co-registration, distortion correction and tensor/ODF estimation) and directly start computation of statistics. This flag is useful when BDP was previously run on a subject (or fileprefix>) and statistics need to be (re-)computed later. This assumes that all the necessary files were generated earlier. All of the other flags MUST be used in the same way as they were in the initial BDP run that processed the data. z--force-partial-roi-statsa=  The field of view (FOV) of the diffusion and T1-weighted scans may differ significantly in some situations. This may result in partial acquisitions of some ROIs in the diffusion scan. By default, BDP does not compute statistics for partially acquired ROIs and shows warnings. This flag forces computation of statistics for all ROIs, including those which are partially acquired. When this flag is used, number of missing voxels are also reported for each ROI in statistics files. Number of missing voxels are reported in the same coordinate system as the statistics file.  z--custom-diffusion-label %sa  BDP supports custom ROIs in addition to those generated by BrainSuite SVReg) for ROI-wise statistics calculation. The flag must be followed by the name of either a file (custom ROI file) or of a folder that contains one or more ROI files. All of the files must be in diffusion coordinate, i.e. the label files should overlay correctly with the diffusion scan in BrainSuite. These input label files are also transferred (and saved) to T1 coordinate for statistics in T1 coordinate. BDP uses nearest-neighborhood interpolation for this transformation. Only NIfTI files, with an extension of .nii or .nii.gz are supported. In order to avoid confusion with other ROI IDs in the statistic files, a 5-digit ROI ID is generated for each custom label found and the mapping of ID to label file is saved in the file fileprefix>.BDP_ROI_MAP.xml. Custom label files can also be generated by using the label painter tool in BrainSuite. See also customLabelXMLz--custom-t1-label %sa  Same as customDiffusionLabelexcept that the label files specified must be in T1 coordinate, i.e. the label files should overlay correctly with the T1-weighted scan in BrainSuite. If the trait outputDiffusionCoordinates is also used then these input label files are also transferred (and saved) to diffusion coordinate for statistics in diffusion coordinate. BDP uses nearest-neighborhood interpolation for this transformation. See also customLabelXML. z--custom-label-xml %sa  BrainSuite saves a descriptions of the SVReg labels (ROI name, ID, color, and description) in an .xml file brainsuite_labeldescription.xml). BDP uses the ROI ID"s from this xml file to report statistics. This flag allows for the use of a custom label description xml file. The flag must be followed by an xml filename. This can be useful when you want to limit the ROIs for which you compute statistics. You can also use custom xml files to name your own ROIs (assign ID"s) for custom labels. BrainSuite can save a label description in .xml format after using the label painter tool to create a ROI label. The xml file MUST be in the same format as BrainSuite"s label description file (see brainsuite_labeldescription.xml for an example). When this flag is used, NO 5-digit ROI ID is generated for custom label files and NO Statistics will be calculated for ROIs not identified in the custom xml file. See also customDiffusionLabel and customT1Label.z--output-subdir %sa  By default, BDP writes out all the output (and intermediate) files in the same directory (or folder) as the BFC file. This flag allows to specify a sub-directory name in which output (and intermediate) files would be written. BDP will create the sub-directory in the same directory as BFC file. <directory_name> should be the name of the sub-directory without any path. This can be useful to organize all outputs generated by BDP in a separate sub-directory. z--output-diffusion-coordinatea  Enables estimation of diffusion tensors and/or ODFs (and statistics if applicable) in the native diffusion coordinate in addition to the default T1-coordinate. All native diffusion coordinate files are saved in a seperate folder named "diffusion_coord_outputs". In case statistics computation is required, it will also transform/save all label/mask files required to diffusion coordinate (see generateStats for details). z--flag-conf-file %sa  Uses the defined file to specify BDP flags which can be useful for batch processing. A flag configuration file is a plain text file which can contain any number of BDP"s optional flags (and their parameters) separated by whitespace. Everything coming after # until end-of-line is treated as comment and is ignored. If a flag is defined in configuration file and is also specified in the command used to run BDP, then the later get preference and overrides the definition in configuration file. z--output-fileprefix %sa  Specifies output fileprefix when noStructuralRegistration is used. The fileprefix can not start with a dash (-) and should be a simple string reflecting the absolute path to desired location, along with outPrefix. When this flag is not specified (and noStructuralRegistration is used) then the output files have same file-base as the input diffusion file. This trait is ignored when noStructuralRegistration is not used. z--threads=%dzSets the number of parallel process threads which can be used for computations to N, where N must be an integer. Default value of N is  z--low-memoryzActivates low-memory mode. This will run the registration-based distortion correction at a lower resolution, which could result in a less-accurate correction. This should only be used when no other alternative is available. z--ignore-memorya  Deactivates the inbuilt memory checks and forces BDP to run registration-based distortion correction at its default resolution even on machines with a low amount of memory. This may result in an out-of-memory error when BDP cannot allocate sufficient memory. Nry   ry   )8r   r   r   r   r   r   r   r   ZinputDiffusionDatar   r   rF   r   r   rC   ZphaseEncodingDirectionr   r   ZbValRatioThresholdZestimateTensorsZestimateODF_FRACTZestimateODF_FRTZestimateODF_3DShoreZ	odfLambtaZt1MaskZdwiMaskZrigidRegMeasureZdcorrRegMeasureZdcorrWeightZskipDistortionCorrZskipNonuniformityCorrr   ZfieldmapCorrectionr   ZignoreFieldmapFOVZfieldmapSmoothZtransformDiffusionVolumeZtransformT1VolumeZtransformInterpolationZtransformT1SurfaceZtransformDiffusionSurfaceZtransformDataOnlyZgenerateStatsZ	onlyStatsZforcePartialROIStatsZcustomDiffusionLabelZcustomT1LabelZcustomLabelXMLZoutputSubdirZoutputDiffusionCoordinatesZflagConfigFileZ	outPrefixr   threadsZ	lowMemoryZignoreMemoryr"   r"   r"   r#   r     s`  
			
	r   c                   s(   e Zd ZdZeZdZ fddZ  ZS )r   av  
    BrainSuite Diffusion Pipeline (BDP) enables fusion of diffusion and
    structural MRI information for advanced image and connectivity analysis.
    It provides various methods for distortion correction, co-registration,
    diffusion modeling (DTI and ODF) and basic ROI-wise statistic. BDP is a
    flexible and diverse tool which supports wide variety of diffusion
    datasets.
    For more information, please see:

    http://brainsuite.org/processing/diffusion/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> bdp = brainsuite.BDP()
    >>> bdp.inputs.bfcFile = '/directory/subdir/prefix.bfc.nii.gz'
    >>> bdp.inputs.inputDiffusionData = '/directory/subdir/prefix.dwi.nii.gz'
    >>> bdp.inputs.BVecBValPair = ['/directory/subdir/prefix.dwi.bvec', '/directory/subdir/prefix.dwi.bval']
    >>> results = bdp.run() #doctest: +SKIP


    zbdp.shc                sD   |dkr|j |d |d f S |dkr0|j d S tt| j|||S )Nr   r   r   r   r   )r   rK   r   rL   )r,   r-   rM   rN   )rO   r"   r#   rL     s
    
zBDP._format_arg)	r   r   r   r2   r   r3   r5   rL   rP   r"   r"   )rO   r#   r     s   r   c               @   s   e Zd ZejddddZdS )ThicknessPVCInputSpecz%sTz5Absolute path and filename prefix of the subject data)r   r
   r   N)r   r   r   r   rF   r   r"   r"   r"   r#   r     s   r   c               @   s   e Zd ZdZeZdZdS )ThicknessPVCa:  
    ThicknessPVC computes cortical thickness using partial tissue fractions.
    This thickness measure is then transferred to the atlas surface to
    facilitate population studies. It also stores the computed thickness into
    separate hemisphere files and subject thickness mapped to the atlas
    hemisphere surfaces. ThicknessPVC is not run through the main SVReg
    sequence, and should be used after executing the BrainSuite and SVReg
    sequence.
    For more informaction, please see:

    http://brainsuite.org/processing/svreg/svreg_modules/

    Examples
    --------

    >>> from nipype.interfaces import brainsuite
    >>> thicknessPVC = brainsuite.ThicknessPVC()
    >>> thicknessPVC.inputs.subjectFilePrefix = 'home/user/btestsubject/testsubject'
    >>> results = thicknessPVC.run() #doctest: +SKIP

    zthicknessPVC.shN)r   r   r   r2   r   r3   r5   r"   r"   r"   r#   r     s   r   c             C   s:   t jj| }tjd}|j|d }t jjdj||fS )Nz[^.]+r   r   )r(   r)   basenameregexcompilefindallr*   r   )Z	inputNamesuffixZ	fullInputZdotRegexZinputNoExtensionr"   r"   r#   r+   	  s    
r+   c             C   s8   | j  j }x&|D ]}| j|}|d k	r|||< qW |S )N)r4   r'   r/   )r,   outputskeyr-   r"   r"   r#   r0     s    

r0   )7r2   r(   rer   baser   r   r   r   r   r   r	   r$   r%   r6   rI   rJ   rQ   rU   rV   rW   r\   r]   r^   rb   rc   rd   re   rf   rg   ri   rj   rk   rl   rm   rn   r|   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r+   r0   r"   r"   r"   r#   <module>   sf    
1	)];*+/ ''#)432&!,)"s)    $