3
dqm                 @   s   d Z ddlZddlmZmZmZmZmZmZm	Z	m
Z
mZmZ ddlmZ ddl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dS )zj
AFNI modeling interfaces.

Examples
--------
See the docstrings of the individual classes for examples.

    N   )
CommandLineInputSpecCommandLine	DirectoryTraitedSpectraits	isdefinedFileInputMultiPath	UndefinedStr   )BibTeX   )AFNICommandBaseAFNICommandAFNICommandInputSpecAFNICommandOutputSpecInfoc               @   s  e Zd ZeeddddddddZejd	d
dgdZejd	ddgdZ	ejdddZ
ejddddZeddddZejdddZejdddZe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/d0dZejeed1d2dZed3d4ddZejd5d6dZed7d8ddZ ed9d:ddZ!ejd;d<dZ"ejed=dd>ed?d@dAdBdZ#edCdDdZ$ejdEdFdZ%ejdGdHdZ&edIdJdZ'ejdKdLddMZ(ejdNdOdZ)ejdPdQdZ*ejdRdSdZ+ejdTdUdZ,ejdVdWdZ-ejdXdYdZgdZ.ejd[d\d]gdZ/ejd^d_d}dZ0ej1ejejdad@edbdd>edcd@ddded~dZ2ej1ejejdgd@edhd@didjdkgddmZ3ejdndodZ4ejdpdqddZ5ej1edsd@dtduddZ6ej1ejejdwd@edxd@dydzd{gddmZ7d|S )DeconvolveInputSpecT)existsa  filenames of 3D+time input datasets. More than one filename can be given and the datasets will be auto-catenated in time. You can input a 1D time series file here, but the time axis should run along the ROW direction, not the COLUMN direction as in the 'input1D' option.z	-input %sF r   )descargstrcopyfileseppositionz~check the dataset time series for initial saturation transients, which should normally have been excised before data analysis.z-sattrans)r   r   xorz-transsata  normally, if you input multiple datasets with 'input', then the separate datasets are taken to be separate image runs that get separate baseline models. Use this options if you want to have the program consider these to be all one big run.* If any of the input dataset has only 1 sub-brick, then this option is automatically invoked!* If the auto-catenation feature isn't used, then this option has no effect, no how, no way.z-noblock)r   r   zduse this value instead of the TR in the 'input' dataset. (It's better to fix the input using Refit.)z-force_TR %fr   )r   r   r   zJfilename of single (fMRI) .1D time series where time runs down the column.z-input1D %s)r   r   r   zUTR to use with 'input1D'. This option has no effect if you do not also use 'input1D'.z	-TR_1D %fz=use Legendre polynomials for null hypothesis (baseline model)z	-legendrezNuse power polynomials for null hypotheses. Don't do this unless you are crazy!z-nolegendrez"don't de-mean baseline time seriesz	-nodmbasez7de-mean baseline time series (default if 'polort' >= 0)z-dmbasez1use SVD instead of Gaussian elimination (default)z-svdz'use Gaussian elimination instead of SVDz-nosvdzXminimum rms error to reject reduced model (default = 0; don't use this option normally!)z
-rmsmin %fz'DON'T calculate matrix condition numberz-nocondz$print out the matrix singular valuesz	-singvalszpuse this to proceed even if the matrix has bad problems (e.g., duplicate columns, large condition number, etc.).z-GOFORIT %izcdon't consider all zero matrix columns to be the type of error that 'gotforit' is needed to ignore.z-allzero_OKz,set environmental variable to provided valuez-D%s=%szfilename of 3D mask dataset; only data time series from within the mask will be analyzed; results for voxels outside the mask will be set to zero.z-mask %szWbuild a mask automatically from input data (will be slow for long time series datasets)z	-automaskzbuild a mask from provided file, and use this mask for the purpose of reporting truncation-to float issues AND for computing the FDR curves. The actual results ARE not masked with this option (only with 'mask' or 'automask' options).z-STATmask %szfilename of censor .1D time series. This is a file of 1s and 0s, indicating which time points are to be included (1) and which are to be excluded (0).z
-censor %szFdegree of polynomial corresponding to the null hypothesis [default: 1]z
-polort %dfilename)r   r   label)r   zthis option lets you input a rectangular array of 1 or more baseline vectors from a file. This method is a fast way to include a lot of baseline regressors in one step. z-ortvec %s %szspecify name for saved X matrixz-x1D %sz(stop running after writing .xmat.1D filez	-x1D_stopzName for dataset in which to save the regression coefficients (no statistics). This dataset will be used in a -xrestore run [not yet implemented] instead of the bucket dataset, if possible.z-cbucket %szoutput statistics filez
-bucket %sz5run the program with provided number of sub-processesz-jobs %d)r   r   Znohashz$output F-statistic for each stimulusz-foutz*output the R^2 statistic for each stimulusz-routz(output the T-statistic for each stimulusz-toutz2output the sample variance (MSE) for each stimulusz-voutzADon't compute the statistic-vs-FDR curves for the bucket dataset.z-noFDRz+use global timing for stimulus timing filesz-global_timeslocal_timesz*use local timing for stimulus timing filesz-local_timesglobal_timesznumber of stimulus timing filesz-num_stimts %d   zk-th response modelzstimulus timing filemodelzEgenerate a response model from a set of stimulus times given in file.z-stim_times %d %s '%s'...   zk-th input stimuluszstimulus labelz+label for kth input stimulus (e.g., Label1)z-stim_label %d %s...
stim_times   )r   r   requiresr   zthis option means to subtract specified seconds from each time encountered in any 'stim_times' option. The purpose of this option is to make it simple to adjust timing files for the removal of images from the start of each imaging run.z-stim_times_subtract %fz0number of general linear tests (i.e., contrasts)z-num_glt %dr   zsymbolic general linear testz[general linear tests (i.e., contrasts) using symbolic conventions (e.g., '+Label1 -Label2')z-gltsym 'SYM: %s'...r   zk-th general linear testz	GLT labelz+general linear test (i.e., contrast) labelsz-glt_label %d %s...gltsymNi)8__name__
__module____qualname__r
   r	   in_filesr   Boolr   r   ZnoblockFloatZforce_TRZinput1DZTR_1DZlegendreZ
nolegendrenodmbaseZdmbaseZsvdZnosvdZrmsminZnocondZsingvalsIntgoforitZ
allzero_OKTupler   ZdnamemaskautomaskSTATmaskZcensorpolortZortvecx1Dx1D_stopcbucketout_fileZnum_threadsfoutrouttoutZvoutnofdrr#   r"   
num_stimtsListr'   Z
stim_labelZstim_times_subtractnum_gltr*   Z	glt_label rI   rI   >/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/afni/model.pyr   &   s   















r   c               @   s:   e Zd ZedddZedddZedddZeddZdS )	DeconvolveOutputSpeczoutput statistics fileT)r   r   z-automatical generated script to run 3dREMLfitzsave out X matrixz2output regression coefficients file (if generated))r   N)r0   r1   r2   r	   rA   reml_scriptr>   r@   rI   rI   rI   rJ   rK   	  s
   
rK   c                   sB   e Zd ZdZdZeZeZ fddZ	d
 fdd	Z
dd	 Z  ZS )
Deconvolvea%  Performs OLS regression given a 4D neuroimage file and stimulus timings

    For complete details, see the `3dDeconvolve Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dDeconvolve.html>`_

    Examples
    ========

    >>> from nipype.interfaces import afni
    >>> deconvolve = afni.Deconvolve()
    >>> deconvolve.inputs.in_files = ['functional.nii', 'functional2.nii']
    >>> deconvolve.inputs.out_file = 'output.nii'
    >>> deconvolve.inputs.x1D = 'output.1D'
    >>> stim_times = [(1, 'timeseries.txt', 'SPMG1(4)')]
    >>> deconvolve.inputs.stim_times = stim_times
    >>> deconvolve.inputs.stim_label = [(1, 'Houses')]
    >>> deconvolve.inputs.gltsym = ['SYM: +Houses']
    >>> deconvolve.inputs.glt_label = [(1, 'Houses')]
    >>> deconvolve.cmdline
    "3dDeconvolve -input functional.nii functional2.nii -bucket output.nii -x1D output.1D -num_stimts 1 -stim_times 1 timeseries.txt 'SPMG1(4)' -stim_label 1 Houses -num_glt 1 -gltsym 'SYM: +Houses' -glt_label 1 Houses"
    >>> res = deconvolve.run()  # doctest: +SKIP
    Z3dDeconvolvec                sJ   |dkr6x,t |D ] \}}|jdr|jd||< qW tt| j|||S )Nr*   zSYM: )	enumerate
startswithlstripsuperrM   _format_arg)selfnameZ
trait_specvaluenval)	__class__rI   rJ   rR   .  s
    
zDeconvolve._format_argNc                s   |d krg }t | jjr6t| jj r6t | jj| j_t | jjr`t| jj r`t | jj| j_t| jjstd| j_tt	| j
|S )Nz	Decon.nii)leninputsr'   r   rF   r*   rH   rA   rQ   rM   _parse_inputs)rS   skip)rX   rI   rJ   r[   6  s    zDeconvolve._parse_inputsc             C   s   | j  j }i }| jj|d< tj |d< t| jjrr| jjjds\tj	j
| jjd |d< qtj	j
| jj|d< n| jf ddi||d< t| jjrtj	j
| jj|d< | jf ddi||d< | jjr|d	= |d= ntj	j
| jj|d	< |S )
Nbasenamecwdz.xmat.1Dr>   suffixr@   z	.REML_cmdrL   rA   )output_specgetrZ   rA   osgetcwdr   r>   endswithpathabspathZ
_gen_fnamer@   r?   )rS   outputsZ_gen_fname_optsrI   rI   rJ   _list_outputsB  s     zDeconvolve._list_outputs)N)r0   r1   r2   __doc___cmdr   
input_specrK   r`   rR   r[   rh   __classcell__rI   rI   )rX   rJ   rM     s   rM   c               @   sL  e Zd ZeeddddddddZedd	dd
ZejdddgdZ	edddgdZ
eddddZejddddZeddddZeeddddddddZeedddddd Zeedddd!d"d Zejd#d$d Zejd%d&d'd(gd)Zed*ddd+d,Zejd-d.d(g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ejejedde eje e d9d:d Zed;d<d Z ed=d>d Z!ed?d@d Z"edAdBd Z#edCdDd Z$edEdFd Z%edGdHd Z&ejdIdJd Z'ejdKdLd Z(ejdMdNd Z)edOdPd Z*edQdRd Z+edSdTd Z,edUdVd Z-edWdXd Z.edYdZd Z/d[S )\RemlfitInputSpecT)r   zRead time series datasetz-input "%s"Fr   )r   r   	mandatoryr   r   zZthe design matrix file, which should have been output from Deconvolve via the 'x1D' optionz
-matrix %s)r   r   rn   zif no 'matrix' option is given, AND no 'matim' option, create a matrix with Legendre polynomial regressorsup to the specified order. The default value is 0, whichproduces a matrix with a single column of all onesz
-polort %dmatrix)r   r   r   zread a standard file as the matrix. You can use only Col as a name in GLTs with these nonstandard matrix input methods, since the other names come from the 'matrix' file. These mutually exclusive options are ignored if 'matrix' is used.z	-matim %szfilename of 3D mask dataset; only data time series from within the mask will be analyzed; results for voxels outside the mask will be set to zero.z-mask %s)r   r   r   z	-automaskzWbuild a mask automatically from input data (will be slow for long time series datasets))Z
usedefaultr   r   zfilename of 3D mask dataset to be used for the purpose of reporting truncation-to float issues AND for computing the FDR curves. The actual results ARE not masked with this option (only with 'mask' or 'automask' options).z-STATmask %sz3file containing columns to add to regression matrix)r   r   zfile(s) to add baseline model columns to the matrix with this option. Each column in the specified file(s) will be appended to the matrix. File(s) must have at least as many rows as the matrix does.z-addbase %s)r   r   r   r   a  similar to 'addbase' in concept, BUT each specified file must have an integer multiple of the number of slices in the input dataset(s); then, separate regression matrices are generated for each slice, with the first column of the file appended to the matrix for the first slice of the dataset, the second column of the file appended to the matrix for the first slice of the dataset, and so on. Intended to help model physiological noise in FMRI, or other effects you want to regress out that might change significantly in the inter-slice time intervals. This will slow the program down, and make it use a lot more memory (to hold all the matrix stuff).z-slibase %s)r   r   zsimilar to 'slibase', BUT each file much be in slice major order (i.e. all slice0 columns come first, then all slice1 columns, etc).z-slibase_sm %sa  write intermediate stuff to disk, to economize on RAM. Using this option might be necessary to run with 'slibase' and with 'Grid' values above the default, since the program has to store a large number of matrices for such a problem: two for every slice and for every (a,b) pair in the ARMA parameter grid. Temporary files are written to the directory given in environment variable TMPDIR, or in /tmp, or in ./ (preference is in that order)z-usetempzby default, baseline columns added to the matrix via 'addbase' or 'slibase' or 'dsort' will each have their mean removed (as is done in Deconvolve); this option turns this centering offz	-nodmbaseaddbasedsort)r   r   r)   z54D dataset to be used as voxelwise baseline regressorz	-dsort %s)r   r   r   r   zgif 'dsort' option is used, this command will output additional results files excluding the 'dsort' filez-dsort_nodsz$output F-statistic for each stimulusz-foutz*output the R^2 statistic for each stimulusz-routzoutput the T-statistic for each stimulus; if you use 'out_file' and do not give any of 'fout', 'tout',or 'rout', then the program assumes 'fout' is activated.z-toutz_do NOT add FDR curve data to bucket datasets; FDR curves can take a long time if 'tout' is usedz-noFDRzndo NOT add baseline (null hypothesis) regressor betas to the 'rbeta_file' and/or 'obeta_file' output datasets.z-noboutaC  read a symbolic GLT from input file and associate it with a label. As in Deconvolve, you can also use the 'SYM:' method to provide the definition of the GLT directly as a string (e.g., with 'SYM: +Label1 -Label2'). Unlike Deconvolve, you MUST specify 'SYM: ' if providing the GLT directly as a string instead of from a filez-gltsym "%s" %s...a0  output dataset for beta + statistics from the REML estimation; also contains the results of any GLT analysis requested in the Deconvolve setup, similar to the 'bucket' output from Deconvolve. This dataset does NOT get the betas (or statistics) of those regressors marked as 'baseline' in the matrix file.z	-Rbuck %sz+output dataset for REML variance parametersz-Rvar %sa>  output dataset for beta weights from the REML estimation, similar to the 'cbucket' output from Deconvolve. This dataset will contain all the beta weights, for baseline and stimulus regressors alike, unless the '-nobout' option is given -- in that case, this dataset will only get the betas for the stimulus regressors.z	-Rbeta %szoutput dataset for beta + statistics from the REML estimation, but ONLY for the GLTs added on the REMLfit command line itself via 'gltsym'; GLTs from Deconvolve's command line will NOT be included.z-Rglt %sz#ouput dataset for REML fitted modelz
-Rfitts %sz7output dataset for REML residuals = data - fitted modelz
-Rerrts %szadataset for REML residual, whitened using the estimated ARMA(1,1) correlation matrix of the noisez
-Rwherr %szturn off most progress messagesz-quietzZturns on more progress messages, including memory usage progress reports at various stagesz-verbziWith potential issues flagged in the design matrix, an attempt will nevertheless be made to fit the modelz-GOFORITz3dataset for OLSQ st.dev. parameter (kind of boring)z-Ovar %sz1dataset for beta weights from the OLSQ estimationz	-Obeta %sz6dataset for beta + statistics from the OLSQ estimationz	-Obuck %sz3dataset for beta + statistics from 'gltsym' optionsz-Oglt %szdataset for OLSQ fitted modelz
-Ofitts %sz0dataset for OLSQ residuals (data - fitted model)z
-Oerrts %sN)0r0   r1   r2   r
   r	   r3   ro   r   r7   r=   Zmatimr:   r4   r;   r<   rp   ZslibaseZ
slibase_smZusetempr6   rq   Z
dsort_nodsrB   rC   rD   rE   ZnoboutrG   ZEitherr9   r   r*   rA   var_file
rbeta_fileglt_file
fitts_file
errts_file
wherr_filequietZverbr8   ovarobetaobuckogltofittsoerrtsrI   rI   rI   rJ   rm   ^  s   




	

"



rm   c               @   s   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eddZ	ed	dZ
ed
dZeddZeddZeddZeddZeddZdS )RemlfitOutputSpeczDdataset for beta + statistics from the REML estimation (if generated)r   z3dataset for REML variance parameters (if generated)z@dataset for beta weights from the REML estimation (if generated)zFoutput dataset for beta weights from the REML estimation (if generatedzoutput dataset for beta + statistics from the REML estimation, but ONLY for the GLTs added on the REMLfit command line itself via 'gltsym' (if generated)z2ouput dataset for REML fitted model (if generated)zEoutput dataset for REML residuals = data - fitted model (if generatedzpdataset for REML residual, whitened using the estimated ARMA(1,1) correlation matrix of the noise (if generated)z1dataset for OLSQ st.dev. parameter (if generated)z@dataset for beta weights from the OLSQ estimation (if generated)zEdataset for beta + statistics from the OLSQ estimation (if generated)zAdataset for beta + statistics from 'gltsym' options (if generatedz,dataset for OLSQ fitted model (if generated)z>dataset for OLSQ residuals = data - fitted model (if generatedN)r0   r1   r2   r	   rA   rr   rs   rt   ru   rv   rw   ry   rz   r{   r|   r}   r~   rI   rI   rI   rJ   r   ;  s0   



r   c                   s6   e Zd ZdZdZeZeZd fdd	Z	dd Z
  ZS )	Remlfita|  Performs Generalized least squares time series fit with Restricted
    Maximum Likelihood (REML) estimation of the temporal auto-correlation
    structure.

    For complete details, see the `3dREMLfit Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dREMLfit.html>`_

    Examples
    ========

    >>> from nipype.interfaces import afni
    >>> remlfit = afni.Remlfit()
    >>> remlfit.inputs.in_files = ['functional.nii', 'functional2.nii']
    >>> remlfit.inputs.out_file = 'output.nii'
    >>> remlfit.inputs.matrix = 'output.1D'
    >>> remlfit.inputs.gltsym = [('SYM: +Lab1 -Lab2', 'TestSYM'), ('timeseries.txt', 'TestFile')]
    >>> remlfit.cmdline
    '3dREMLfit -gltsym "SYM: +Lab1 -Lab2" TestSYM -gltsym "timeseries.txt" TestFile -input "functional.nii functional2.nii" -matrix output.1D -Rbuck output.nii'
    >>> res = remlfit.run()  # doctest: +SKIP
    Z	3dREMLfitNc                s   |d krg }t t| j|S )N)rQ   r   r[   )rS   r\   )rX   rI   rJ   r[   }  s    zRemlfit._parse_inputsc             C   sN   | j  j }x<|j D ]0}t| jj | rtjj| jj | ||< qW |S )N)r`   ra   keysr   rZ   rb   re   rf   )rS   rg   keyrI   rI   rJ   rh     s
    zRemlfit._list_outputs)N)r0   r1   r2   ri   rj   rm   rk   r   r`   r[   rh   rl   rI   rI   )rX   rJ   r   c  s   r   c               @   s   e Zd ZedddddZedddddZejedd	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dddZdS )SynthesizeInputSpeczDRead the dataset output from 3dDeconvolve via the '-cbucket' option.z-cbucket %sFT)r   r   r   rn   z?Read the matrix output from 3dDeconvolve via the '-x1D' option.z
-matrix %szselected columns to synthesize)r   z
-select %sa  A list of selected columns from the matrix (and the corresponding coefficient sub-bricks from the cbucket). Valid types include 'baseline',  'polort', 'allfunc', 'allstim', 'all', Can also provide 'something' where something matches a stim_label from 3dDeconvolve, and 'digits' where digits are the numbers of the select matrix columns by numbers (starting at 0), or number ranges of the form '3..7' and '3-7'.)r   r   rn   Zsynz*output dataset prefix name (default 'syn')z
-prefix %s)Zname_templater   r   z0Don't compute the output, just check the inputs.z-dry)r   r   z]TR to set in the output.  The default value of TR is read from the header of the matrix file.z-TR %fZzeroZnbhrnonez-cenfill %szxDetermines how censored time points from the 3dDeconvolve run will be filled. Valid types are 'zero', 'nbhr' and 'none'.)r   r   N)r0   r1   r2   r	   r@   ro   r   rG   r   selectrA   r4   dry_runr5   ZTREnumZcenfillrI   rI   rI   rJ   r     s<   	
r   c               @   s$   e Zd ZdZdZeZeZdd Z	dS )
Synthesizea  Reads a '-cbucket' dataset and a '.xmat.1D' matrix from 3dDeconvolve,
       and synthesizes a fit dataset using user-selected sub-bricks and
       matrix columns.

    For complete details, see the `3dSynthesize Documentation.
    <https://afni.nimh.nih.gov/pub/dist/doc/program_help/3dSynthesize.html>`_

    Examples
    ========

    >>> from nipype.interfaces import afni
    >>> synthesize = afni.Synthesize()
    >>> synthesize.inputs.cbucket = 'functional.nii'
    >>> synthesize.inputs.matrix = 'output.1D'
    >>> synthesize.inputs.select = ['baseline']
    >>> synthesize.cmdline
    '3dSynthesize -cbucket functional.nii -matrix output.1D -select baseline'
    >>> syn = synthesize.run()  # doctest: +SKIP
    Z3dSynthesizec             C   sN   | j  j }x<|j D ]0}t| jj | rtjj| jj | ||< qW |S )N)r`   ra   r   r   rZ   rb   re   rf   )rS   rg   r   rI   rI   rJ   rh     s
    zSynthesize._list_outputsN)
r0   r1   r2   ri   rj   r   rk   r   r`   rh   rI   rI   rI   rJ   r     s
   r   )ri   rb   baser   r   r   r   r   r   r	   r
   r   r   Zexternal.duer   r   r   r   r   r   r   rK   rM   rm   r   r   r   r   rI   rI   rI   rJ   <module>   s   0	 d	L ^()3