3
db                @   s  d Z ddlZddlmZ ddlmZ ddlmZ ddlZddl	m
Z
 ddlmZ dd	lmZmZ dd
l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  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Z0G d0d1 d1eZ1G d2d3 d3eZ2G d4d5 d5eZ3G d6d7 d7eZ4G d8d9 d9eZ5G d:d; d;eZ6G d<d= d=eZ7G d>d? d?eZ8G d@dA dAeZ9G dBdC dCeZ:G dDdE dEeZ;G dFdG dGeZ<G dHdI dIeZ=G dJdK dKeZ>G dLdM dMeZ?G dNdO dOeZ@G dPdQ dQeZAG dRdS dSeZBG dTdU dUeZCG dVdW dWeZDG dXdY dYeZEG dZd[ d[eZFG d\d] d]eZGG d^d_ d_eZHG d`da daeZIG dbdc dceZJG ddde deeZKG dfdg dgeZLG dhdi dieZMG djdk dkeZNG dldm dmeZOG dndo doeZPG dpdq dqeZQG drds dseZRG dtdu dueZSdvdw ZTdS )xzThe fsl module provides classes for interfacing with the `FSL
<http://www.fmrib.ox.ac.uk/fsl/index.html>`_ command line tools.  This
was written to work with FSL version 4.1.4.
    N)glob)rmtree)Template)load   )LooseVersion)simplify_listensure_list)human_order_sorted)BibTeX   )	Filetraits	isdefinedTraitedSpecBaseInterface	DirectoryInputMultiPathOutputMultiPathBaseInterfaceInputSpec   )
FSLCommandFSLCommandInputSpecInfoc               @   s  e Zd ZejdddZejdddZejej	ej
dej	ej
dejej	ej
dej	ej
ddd	ej	ej
d
ej	ej
dejej	ej
dej	 ej	ej
dej
ddddZej	ejej	ejejejejdddZejdddZejejejejej
dejejejejejejej
dejejejejejejejejej
dejejejejej
dejejejejejejej
dejejejejejejddZdS )Level1DesignInputSpecTzInterscan  interval (in secs))	mandatorydesczCSession specific information generated by ``modelgen.SpecifyModel``dgammaderivsgamma
gammasigma
gammadelayZcustomZbfcustompathnoneNzEname of basis function and options e.g., {'dgamma': {'derivs': True}}zwhich regressors to make orthogonal e.g., {1: {0:0,1:0,2:0}, 2: {0:1,1:1,2:0}} to make the second regressor in a 2-regressor model orthogonal to the first.)r   
usedefaultzOption to model serial correlations using an autoregressive estimator (order 1). Setting this option is only useful in the context of the fsf file. If you set this to False, you need to repeat this option for FILMGLS by setting autocorr_noestimate to True)r   r   TFa  List of contrasts with each contrast being a list of the form - [('name', 'stat', [condition list], [weight list], [session list])]. if session list is None or not provided, all sessions are used. For F contrasts, the condition list should contain previously defined T-contrasts.)r   )__name__
__module____qualname__r   Floatinterscan_intervalZAnysession_infoEitherDictEnumBoolStrbasesIntorthogonalizationmodel_serial_correlationsListTuple	contrasts r8   r8   =/tmp/pip-build-7vycvbft/nipype/nipype/interfaces/fsl/model.pyr   "   sn   







r   c               @   s6   e Zd ZeeddddZeejeddddZdS )Level1DesignOutputSpecT)existszFSL feat specification files)r   zcondition information filesN)	r&   r'   r(   r   r   	fsf_filesr   r5   ev_filesr8   r8   r8   r9   r:   z   s   r:   c               @   sH   e Zd ZdZeZeZdd Zdd Z	dd Z
dd	 Zd
d Zdd ZdS )Level1DesignaD  Generate FEAT specific files

    Examples
    --------

    >>> level1design = Level1Design()
    >>> level1design.inputs.interscan_interval = 2.5
    >>> level1design.inputs.bases = {'dgamma':{'derivs': False}}
    >>> level1design.inputs.session_info = 'session_info.npz'
    >>> level1design.run() # doctest: +SKIP

    c             C   sd   t |d}xL|D ]D}t|dkrB|jd|d |d |d f  q|jd|d   qW |j  d S )Nwtr   z	%f %f %f
r   r   r   z%f
)openlenwriteclose)selfevfnameevinfofir8   r8   r9   _create_ev_file   s    

"zLevel1Design._create_ev_filec	       1       C   s  i }	g }
|dkrd}n\|dkrry|d }W n t k
rF   d|d< Y nX y|d }W n t k
rp   d|d< Y nX td| d	 }td
}td}d}ddg}xdd:D ]Z}xRt|| D ]@\}}|d }|
j| tjj|d||t|
f }g }|d  d7  < |d  d7  < |dkrxt|d D ]\}}y,|d }t|dkrZ|| }n|d }W n t k
r~   d}Y nX t|d dkr|j|||d | |g n|j|||d d |g q0W ||d< |d |d< ||d< ||d< d|krd|d< d|krd|d< ytj	d |d< W n2 t k
rZ   |dkrNt
dnd |d< Y nX tt|jd!d"|d#< |d# r|
j|d$  |d  d7  < ||j|7 }n6|dkrd%d& |d' D }||j|d |||d(7 }|d)7 }||	|< | j|| qW qW xtd|d d D ]}|j|ddd*}xtd|d d D ]z}yt|| | }W n" t tttfk
r|   d}Y nX |dkr||kr||d) 7 }||j|||d*7 }|d)7 }qBW qW t|rtd+}td,}td-}td.} td/}!td0}"td1}#||j 7 }g }$x$t|D ]\}}%|$j|%d  q"W i }&g }'g }(xt|D ]v\}}%|%d d2kr|'j| xR|%d3 D ]:})|)d t|&j krg |&|)d < |&|)d  j| q~W n
|(j| qTW xld;D ]b}*xXt|D ]J\}}%|%d d2krq|(j|d }+||j|+|*|%d d67 }d},xtdt|
d D ]})|
|)d  jd$rh|*d5krhqB|,d },|
|)d  |%d3 kr|%d |%d3 j|
|)d   }-nd7}-||j|+|,|*|-d87 }|d)7 }qBW xb|'D ]Z}.d}/|%d |&j kr|.|&|%d  krd}/|| j|'j|.d |+|*|/d87 }|d)7 }qW qW qW ||!j 7 }xRt|D ]F\}}x:t|D ].\}0}||0krf||#j|d |0d d97 }qfW qTW ||"j 7 }||fS )<ac  Creates EV files from condition and regressor information.

        Parameters:
        -----------

        runinfo : dict
            Generated by `SpecifyModel` and contains information
            about events and other regressors.
        runidx  : int
            Index to run number
        ev_parameters : dict
            A dictionary containing the model parameters for the
            given design type.
        orthogonalization : dict
            A dictionary of dictionaries specifying orthogonal EVs.
        contrasts : list of lists
            Information on contrasts to be evaluated
        r   Zhrfr   r    r   r!      Zfeat_ev_z.tclzfeat_ev_none.tclzfeat_ev_ortho.tcl r   condregressnamezev_%s_%d_%d.txtr   onset
amplitudesduration	cond_fileev_numev_nametempfilt_ynZ	basisorthZ	basisfnumZFSLDIRZfsldirZflobsz!FSL environment variables not setz/usr/share/fslr   FtemporalderivTDc             S   s   g | ]
}|gqS r8   r8   ).0jr8   r8   r9   
<listcomp>   s    z1Level1Design._create_ev_files.<locals>.<listcomp>val)rS   rT   rU   rR   
)Zc0c1
orthogonalzfeat_contrast_header.tclzfeat_contrast_prolog.tclzfeat_contrast_element.tclzfeat_contrast_ftest_element.tclzfeat_contrastmask_header.tclzfeat_contrastmask_footer.tclzfeat_contrastmask_element.tclr%   r   realorig)cnumctypecnameg        )ra   elementrb   r[   )r]   c2)rL   rM   )r_   r`   )KeyErrorload_template	enumerateappendospathjoinrA   insertenviron	Exceptionintboolget
substituterI   range	TypeError
ValueError
IndexErrorr   listkeysindexendswith)1rD   cwdruninfoZrunidxev_parametersr3   r7   do_tempfilter	basis_keyZcondsevname_Zev_templateZev_noneZev_orthoZev_txtnum_evsfieldrH   rL   rN   rE   rF   rY   rO   rP   ampinitialr^   Zcontrast_headerZcontrast_prologZcontrast_elementZcontrast_ftest_elementZcontrastmask_headerZcontrastmask_footerZcontrastmask_elementZ	con_namesconZcon_mapZ	ftest_idxZ	ttest_idxcrb   Ztidxcountr[   ZfconidxZfvalkr8   r8   r9   _create_ev_files   s   



 









 
$

&zLevel1Design._create_ev_filesc             C   s   t |tr|g}|S )N)
isinstancedict)rD   r+   r8   r8   r9   _format_session_infoW  s    
z!Level1Design._format_session_infoc             C   s.   g }x$t |D ]\}}|j||d  qW |S )z-Returns functional files in the order of runsZscans)rh   rm   )rD   r+   
func_filesrH   infor8   r8   r9   _get_func_files\  s    zLevel1Design._get_func_filesc             C   s  t j }td}td}d}t| jjr4t| jj}t| jjj	 d }t
| jj| }| j| jj}| j|}	d}
d}t| jjrxBt| jjD ]2\}}|d dkr|
d7 }
q|d dkr|d7 }qW xt|D ]\}}d}|d tjkrd}| j||||| jj| jj||\}}t|	| }|j\}}}}|j|| jj|||d |d |
||d ||	| d}||7 }||jdd	7 }tt jj|d
| d}|j| |j  qW |S )Nzfeat_header_l1.tclzfeat_nongui.tclr   r   r$   r%   Zhpf)Zrun_numr*   Znum_vols	prewhitenr   Znum_evs_realZnum_tconZnum_fconZhigh_pass_filter_cutoffZ	temphp_ynZ	func_file)	overwritez	run%d.fsfw)rj   getcwdrg   r   inputsr4   rp   rx   r1   ry   r   r   r+   r   r7   rh   npinfr   r3   r   shapers   r*   r@   rk   rl   rB   rC   )rD   runtimer|   
fsf_headerZfsf_postscriptr   r   r~   r+   r   Zn_tconZn_fconrH   r   r   r   r   Zcond_txtZnimr   Z
timepointsfsf_txtrG   r8   r8   r9   _run_interfacec  sf    



zLevel1Design._run_interfacec          
   C   sH  | j  j }tj }g |d< g |d< t| jjj d }t| jj| }xt	| j
| jjD ]\}}|d jtjj|d|  |d j|g  g }xdD ]}xt	|| D ]\}	}
|
d }|j| tjj|d||t|f }|dkrtt|jd	d
|d< |d r|j|d  |d | jtjj|| qW qW q\W |S )Nr<   r=   r   z	run%d.fsfrL   rM   rN   zev_%s_%d_%d.txtr   FrV   rW   )rL   rM   )output_specrr   rj   r   rx   r   r1   ry   r   rh   r   r+   ri   rk   rl   rm   rA   rp   rq   )rD   outputsr|   r   r~   runnor}   r   r   rH   rL   rN   rE   r8   r8   r9   _list_outputs  s0    



(zLevel1Design._list_outputsN)r&   r'   r(   __doc__r   
input_specr:   r   rI   r   r   r   r   r   r8   r8   r8   r9   r>      s   	 =;r>   c               @   s   e Zd ZeddddddZdS )FEATInputSpecTz%sr   z)File specifying the feat design spec file)r;   r   argstrpositionr   N)r&   r'   r(   r   fsf_filer8   r8   r8   r9   r     s   r   c               @   s   e Zd ZeddZdS )FEATOutputSpecT)r;   N)r&   r'   r(   r   feat_dirr8   r8   r8   r9   r     s   r   c               @   s$   e Zd ZdZdZeZeZdd Z	dS )FEATz,Uses FSL feat to calculate first level statsZfeatc             C   s   | j  j }d}d |d< t| jjdp}|j }d|kr<d}xT|jdD ]F}|jddkrHy&|jd	d }tj	j
|r~||d< W qH   Y qHX qHW W d Q R X |d s|rttj	jtj dd |d< nttj	jtj dd |d< td| |S )NFr   rtzset fmri(inmelodic) 1Tr\   zset fmri(outputdir)r   "r   z*icar   z*featzOutputs from FEATmodel:)_outputsrr   r@   r   r   readsplitfindrj   rk   r;   r   rl   r   print)rD   r   Zis_icafptextlineZoutputdir_specr8   r8   r9   r     s*     
zFEAT._list_outputsN)
r&   r'   r(   r   _cmdr   r   r   r   r   r8   r8   r8   r9   r     s
   r   c               @   s<   e Zd ZedddddddZejedddddd	dd
ZdS )FEATModelInputSpecTz%sr   z)File specifying the feat design spec fileF)r;   r   r   r   r   copyfile)r;   z*Event spec files generated by level1designr   )r   r   r   r   r   N)r&   r'   r(   r   r   r   r5   r=   r8   r8   r8   r9   r     s   r   c               @   sF   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ZdS )	FEATModelOutpuSpecTz+Mat file containing ascii matrix for design)r;   r   z)Graphical representation of design matrixz-Graphical representation of design covariancez)Contrast file containing contrast vectors)r   N)	r&   r'   r(   r   design_filedesign_image
design_covcon_file	fcon_filer8   r8   r8   r9   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 )		FEATModelz0Uses FSL feat_model to generate design.mat filesZ
feat_modelc                sF   |dkr"t t| j||| j|S |dkr.dS t t| j|||S d S )Nr   r=   rK   )superr   _format_arg_get_design_root)rD   rN   
trait_specvalue)	__class__r8   r9   r     s    
zFEATModel._format_argc             C   s   t jj|\}}|jdd S )N.r   )rj   rk   r   )rD   infiler   fnamer8   r8   r9   r     s    zFEATModel._get_design_rootc             C   sL  | j  j }| jt| jj}ttjj	tj
 d| }t|dksLtd|d |d< ttjj	tj
 d| }t|dkstd|d |d< ttjj	tj
 d	| }t|dkstd
|d |d< ttjj	tj
 d| }t|dkstd|d |d< ttjj	tj
 d| }|rHt|dks<td|d |d< |S )Nz%s*.matr   z#No mat file generated by FEAT Modelr   r   z%s.pngz'No design image generated by FEAT Modelr   z
%s_cov.pngz+No covariance image generated by FEAT Modelr   z%s*.conz#No con file generated by FEAT Modelr   z%s*.ftsz#No fts file generated by FEAT Modelr   )r   rr   r   r   r   r   r   rj   rk   rl   r   rA   AssertionError)rD   r   rootr   r   r   r   r   r8   r8   r9   r     s&    zFEATModel._list_outputs)r&   r'   r(   r   r   r   r   r   r   r   r   r   __classcell__r8   r8   )r   r9   r     s   
r   c               @   s
  e Zd Zeddd4dddZedd5dddZejd	d
dd6dddZej	dddZ
ejdddZejddddZej	dddZddddddgZej	d ed!d"Z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+ed,d"Zej	d-d.dZed/d0dd1d2Zd3S )7FILMGLSInputSpecTr   z%szinput data file)r;   r   r   r   r   r   zdesign matrix file)r;   r   r   r   g     @@g        z%fr   	threshold)r   lowr   r   r#   r   z-sazSmooth auto corr estimates)r   r   z-ms %dzsusan mask sizer   z	-epith %dz5susan brightness threshold, otherwise it is estimated)r   r   r   z-vzoutput full dataautocorr_estimate_onlyfit_armodeltukey_windowmultitaper_productuse_pavaautocorr_noestimatez-acz)perform autocorrelation estimatation only)r   xorr   z-arzHfits autoregressive model - default is to use tukey with M=sqrt(numvols)z	-tukey %dz&tukey window size to estimate autocorrz-mt %dzGmultitapering with slepian tapers and num is the time-bandwidth productz-pavazestimates autocorr using PAVAz-noestzdo not estimate autocorrsz-output_pwdataz1output prewhitened data and average design matrixresultsz-rn %szdirectory to store results in)r   r#   r   Nr   r   )r&   r'   r(   r   in_filer   r   Ranger   r/   smooth_autocorrr2   	mask_sizebrightness_threshold	full_data_estimate_xorr   r   r   r   r   r   output_pwdatar   results_dirr8   r8   r8   r9   r   2  sd   r   c               @   s
  e Zd Zeddd5dddZedd6ddd	Zejd
ddd7dddZej	dddZ
ejdddZejddddZej	dddZdddddd gZej	d!ed"d#Z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,ed-d#Zej	d.d/dZed0d1dd2d3Zd4S )8FILMGLSInputSpec505Tr   z--in=%szinput data file)r;   r   r   r   r   r   z--pd=%szdesign matrix file)r;   r   r   r   g     @@g        z--thr=%fr   r   )r   r   r   r   r#   r   z--sazSmooth auto corr estimates)r   r   z--ms=%dzsusan mask sizer   z
--epith=%dz5susan brightness threshold, otherwise it is estimated)r   r   r   z-vzoutput full datar   r   r   r   r   r   z--acz'perform autocorrelation estimation only)r   r   r   z--arzHfits autoregressive model - default is to use tukey with M=sqrt(numvols)z
--tukey=%dz&tukey window size to estimate autocorrz--mt=%dzGmultitapering with slepian tapers and num is the time-bandwidth productz--pavazestimates autocorr using PAVAz--noestzdo not estimate autocorrsz--outputPWdataz1output prewhitened data and average design matrixr   z--rn=%szdirectory to store results in)r   r#   r   Nr   r   r   )r&   r'   r(   r   r   r   r   r   r   r/   r   r2   r   r   r   r   r   r   r   r   r   r   r   r   r   r8   r8   r8   r9   r   z  sn   r   c               @   s\   e Zd ZejddddddZedddd	Zedd
dd	Zej	dddddZ
edddd	ZdS )FILMGLSInputSpec507g     @@z--thr=%fr   Tr   )default_valuer   r   r#   r   z--con=%sz$contrast file containing T-contrasts)r;   r   r   z	--fcon=%sz$contrast file containing F-contrastsZ
volumetricsurfacez	--mode=%szType of analysis to be done)r   r   z--in2=%sz>input surface for autocorr smoothing in surface-based analysesNg     @r   )r&   r'   r(   r   r)   r   r   	tcon_filer   r.   moder   r8   r8   r8   r9   r     s    r   c               @   sr   e Zd Zeed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 )FILMGLSOutputSpecT)r;   z8Parameter estimates for each column of the design matrix)r   z9Model fit residual mean-squared error for each time point)r;   r   zdegrees of freedomz1summary of residuals, See Woolrich, et. al., 2001z)directory storing model estimation outputz1statistical corrections used within FILM modelingz#The FILM autocorrelation parameterszFILM run logfileN)r&   r'   r(   r   r   param_estimates
residual4ddof_filesigmasquaredsr   r   correctionsthresholdaclogfiler8   r8   r8   r9   r     s   


r   c               @   s   e Zd Zeed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eddddZeeddddZeeddddZeeddddZeeddddZeeddddZdS )FILMGLSOutputSpec507T)r;   z8Parameter estimates for each column of the design matrix)r   z9Model fit residual mean-squared error for each time point)r;   r   zdegrees of freedomz1summary of residuals, See Woolrich, et. al., 2001z)directory storing model estimation outputz#The FILM autocorrelation parameterszFILM run logfilez$Contrast estimates for each contrastz$Variance estimates for each contrastzz-stat file for each contrastzt-stat file for each contrastzf-stat file for each contrastzz-stat file for each F contrastN)r&   r'   r(   r   r   r   r   r   r   r   r   r   r   copesvarcopeszstatststatsfstatszfstatsr8   r8   r8   r9   r     s*   

r   c               @   sz   e Zd ZdZdZeZeZe	j
 r>ee	j
 edkr>eZeZn e	j
 r^ee	j
 edkr^eZdd Zdd Zd	d
 ZdS )FILMGLSa9  Use FSL film_gls command to fit a design matrix to voxel timeseries

    Examples
    --------

    Initialize with no options, assigning them when calling run:

    >>> from nipype.interfaces import fsl
    >>> fgls = fsl.FILMGLS()
    >>> res = fgls.run('in_file', 'design_file', 'thresh', rn='stats') #doctest: +SKIP

    Assign options through the ``inputs`` attribute:

    >>> fgls = fsl.FILMGLS()
    >>> fgls.inputs.in_file = 'functional.nii'
    >>> fgls.inputs.design_file = 'design.mat'
    >>> fgls.inputs.threshold = 10
    >>> fgls.inputs.results_dir = 'stats'
    >>> res = fgls.run() #doctest: +SKIP

    Specify options when creating an instance:

    >>> fgls = fsl.FILMGLS(in_file='functional.nii', design_file='design.mat', threshold=10, results_dir='stats')
    >>> res = fgls.run() #doctest: +SKIP

    Zfilm_glsz5.0.6z5.0.4c             C   s   d }t | jjrt| jjd}x^|j D ]R}|jdr(t|j d }g }x,t|D ] }|j	| j
d|d  |d qTW P q(W |j  |S )Nr   z	/NumWavesr   zpe%d.nii)r|   r   )r   r   r   r@   	readlines
startswithrp   r   rt   ri   
_gen_fnamerC   )rD   r|   filesr   r   ZnumpesrH   r8   r8   r9   _get_pe_files<  s    
 zFILMGLS._get_pe_filesc             C   s   d}d}t | jjrXt| jjd}x,|j D ] }|jdr,t|j d }P q,W |j  t | jj	rt| jj	d}x,|j D ] }|jdr|t|j d }P q|W |j  ||fS )Nr   r   z/NumContrastsr   r   r   )
r   r   r   r@   r   r   rp   r   rC   r   )rD   numtconsnumfconsr   r   r8   r8   r9   _get_numconsJ  s"    

zFILMGLS._get_numconsc             C   s(  | j  j }tj }tjj|| jj}||d< | j|}|rD||d< | j	d|d|d< tjj|d|d< | j	d|d|d	< | j	d
|d|d< t
j rtt
j tdk r| j	d|d|d< | j	dd|d|d< t
j ott
j tdkr$|}| j \}}d}g }	g }
g }g }xt|D ]v}|	j| j	d||  |d |
j| j	d||  |d |j| j	d||  |d |j| j	d||  |d qW |	r|	|d< |
|d< ||d< ||d< g }g }xJt|D ]>}|j| j	d||  |d |j| j	d||  |d qW |r$||d< ||d< |S ) Nr   r   z	res4d.nii)r|   r   dofr   zsigmasquareds.niir   zthreshac1.niir   z5.0.7zcorrections.niir   r   F)
change_extr|   z5.0.6r   z
cope%d.niizvarcope%d.niizzstat%d.niiztstat%d.niir   r   r   r   zfstat%d.niizzfstat%d.niir   r   )r   rr   rj   r   rk   rl   r   r   r   r   r   versionr   r   rt   ri   )rD   r   r|   r   Zpe_filespthr   r   base_contrastr   r   r   r   rH   r   r   r8   r8   r9   r   ]  s`    
zFILMGLS._list_outputsN)r&   r'   r(   r   r   r   r   r   r   r   r  r   r   r   r   r   r   r   r8   r8   r8   r9   r     s   r   c               @   s>   e Zd ZeedddddZeddddZej	dddd	Z
d
S )FEATRegisterInputSpecT)r;   zLower level feat dirs)r   r   z2image to register to (will be treated as standard))r;   r   r      zregistration degrees of freedom)r   r#   N)r&   r'   r(   r   r   	feat_dirsr   	reg_imager   r2   reg_dofr8   r8   r8   r9   r    s   r  c               @   s   e Zd ZedddZdS )FEATRegisterOutputSpecTzFSL feat specification file)r;   r   N)r&   r'   r(   r   r   r8   r8   r8   r9   r
    s   r
  c               @   s(   e Zd ZdZeZeZdd Zdd Z	dS )FEATRegisterz0Register feat directories to a specific standardc       
      C   s   t d}t d}t d}t| jj}|j|| jj| jjd}x:tt| jjD ]&\}}||j|d t	j
j|d7 }qNW ||j 7 }tt	j
jt	j dd}	|	j| |	j  |S )	Nzfeatreg_header.tclzfeat_nongui.tclzfeat_fe_featdirs.tcl)num_runsZregimageZregdofr   )r   rundirzregister.fsfr?   )rg   rA   r   r  rs   r  r	  rh   r	   rj   rk   abspathr@   rl   r   rB   rC   )
rD   r   r   Z
fsf_footerZfsf_dirsr  r   rH   r  rG   r8   r8   r9   r     s    "
zFEATRegister._run_interfacec             C   s.   | j  j }tjjtjjtj d|d< |S )Nzregister.fsfr   )r   rr   rj   rk   r  rl   r   )rD   r   r8   r8   r9   r     s    zFEATRegister._list_outputsN)
r&   r'   r(   r   r  r   r
  r   r   r   r8   r8   r8   r9   r    s
   r  c            	   @   s  e Zd ZedddddZeddddZeddd	dZedd
dddZedddddZedddddZ	eddddZ
edddddZej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jd*d+dZed,d-dd.Zd/S )0FLAMEOInputSpecTz--copefile=%szcope regressor data file)r;   r   r   r   z--varcopefile=%szvarcope weightings data file)r;   r   r   z--dofvarcopefile=%szdof data file for varcope dataz--maskfile=%sz	mask filez--designfile=%szdesign matrix filez--tcontrastsfile=%sz#ascii matrix specifying t-contrastsz--fcontrastsfile=%sz#ascii matrix specifying f-contrastsz--covsplitfile=%sz?ascii matrix specifying the groups the covariance is split intoZfeZolsZflame1Zflame12z--runmode=%szinference to perform)r   r   r   z--njumps=%dznumber of jumps made by mcmc)r   r   z--burnin=%dz0number of jumps at start of mcmc to be discardedz--sampleevery=%dznumber of jumps for each samplez	--fixmeanzfix mean for tfitz--inferoutlierszinfer outliers - not for fez--nopeoutputzdo not output pe filesz--sigma_dofs=%dzjsigma (in mm) to use for Gaussian smoothing the DOFs in FLAME 2. Default is 1mm, -1 indicates no smoothingz	--ioni=%dzGNumber of max iterations to use when inferring outliers. Default is 12.statsz--ld=%s)r   r#   N)r&   r'   r(   r   	cope_fileZvar_cope_fileZdof_var_cope_file	mask_filer   Z
t_con_file
f_con_fileZcov_split_filer   r.   Zrun_moder2   Zn_jumpsZburninZsample_everyr/   Zfix_meanZinfer_outliersZno_pe_outputsZ
sigma_dofsZoutlier_iterr   log_dirr8   r8   r8   r9   r    sh   

r  c               @   s   e Zd ZeeddddZeeddddZeeddddZeeddddZeeddddZ	eeddd	dZ
eeddd
dZeeddddZeeddddZeeddddZeeddddZeeddddZdS )FLAMEOOutputSpecT)r;   zGParameter estimates for each column of the design matrix for each voxel)r   z9Model fit residual mean-squared error for each time pointz$Contrast estimates for each contrastz$Variance estimates for each contrastzz-stat file for each contrastzt-stat file for each contrastzz stat file for each f contrastzf-stat file for each contrastz.mean random effect variances for each contrastz#temporal dof file for each contrastzweights file for each contrastz)directory storing model estimation outputN)r&   r'   r(   r   r   pesres4dr   	var_copesr   r   r   r   mrefvarstdofweightsr   	stats_dirr8   r8   r8   r9   r    s*   r  c                   sT   e Zd ZdZdZeZeZe	ddgde	ddgdgZ
 fddZd	d
 Z  ZS )FLAMEOa  Use FSL flameo command to perform higher level model fits

    Examples
    --------

    Initialize FLAMEO with no options, assigning them when calling run:

    >>> from nipype.interfaces import fsl
    >>> flameo = fsl.FLAMEO()
    >>> flameo.inputs.cope_file = 'cope.nii.gz'
    >>> flameo.inputs.var_cope_file = 'varcope.nii.gz'
    >>> flameo.inputs.cov_split_file = 'cov_split.mat'
    >>> flameo.inputs.design_file = 'design.mat'
    >>> flameo.inputs.t_con_file = 'design.con'
    >>> flameo.inputs.mask_file = 'mask.nii'
    >>> flameo.inputs.run_mode = 'fe'
    >>> flameo.cmdline
    'flameo --copefile=cope.nii.gz --covsplitfile=cov_split.mat --designfile=design.mat --ld=stats --maskfile=mask.nii --runmode=fe --tcontrastsfile=design.con --varcopefile=varcope.nii.gz'

    Zflameoz@article{BeckmannJenkinsonSmith2003,author={C.F. Beckmann, M. Jenkinson, and S.M. Smith},title={General multilevel linear modeling for group analysis in FMRI.},journal={NeuroImage},volume={20},pages={1052-1063},year={2003},}method)entrytagsa  @article{WoolrichBehrensBeckmannJenkinsonSmith2004,author={M.W. Woolrich, T.E. Behrens, C.F. Beckmann, M. Jenkinson, and S.M. Smith},title={Multilevel linear modelling for FMRI group analysis using Bayesian inference.},journal={NeuroImage},volume={21},pages={1732-1747},year={2004},}c                sJ   | j j}tj }tjtjj||tjr:ttjj|| t	t
| j|S )N)r   r  rj   r   accessrk   rl   F_OKr   r   r  r   )rD   r   r  r|   )r   r8   r9   r   n  s
    zFLAMEO._run_interfacec             C   st  | j  j }tjjtj | jj}tt	tjj|d}t
|dksLtd||d< tt	tjj|d}t
|dks~td|d |d< tt	tjj|d	}t
|dkstd
||d< tt	tjj|d}t
|dkstd||d< tt	tjj|d}t
|dkstd||d< t| jjrtt	tjj|d}t
|dks\td||d< tt	tjj|d}	t
|	dkstd|	|d< tt	tjj|d}
t
|
dkstd|
|d< tt	tjj|d}t
|dkstd||d< tt	tjj|d}t
|dks,td||d < tt	tjj|d!}t
|dks`td"||d#< ||d$< |S )%Nz
pe[0-9]*.*r   z'No pe volumes generated by FSL Estimater  zres4d.*z,No residual volume generated by FSL Estimater   r  zcope[0-9]*.*z*No cope volumes generated by FSL CEstimater   zvarcope[0-9]*.*z-No varcope volumes generated by FSL CEstimater  zzstat[0-9]*.*z+No zstat volumes generated by FSL CEstimater   zzfstat[0-9]*.*z,No zfstat volumes generated by FSL CEstimater   zfstat[0-9]*.*z+No fstat volumes generated by FSL CEstimater   ztstat[0-9]*.*z+No tstat volumes generated by FSL CEstimater   zmean_random_effects_var[0-9]*.*z2No mean random effects volumes generated by FLAMEOr  ztdof_t[0-9]*.*z$No T dof volumes generated by FLAMEOr  zweights[0-9]*.*z%No weight volumes generated by FLAMEOr  r  )r   rr   rj   rk   rl   r   r   r  r
   r   rA   r   r   r  )rD   r   r  r  r  r   r  r   r   r   r   Zmrefsr  r  r8   r8   r9   r   x  sN    zFLAMEO._list_outputs)r&   r'   r(   r   r   r  r   r  r   r   Z_referencesr   r   r   r8   r8   )r   r9   r  5  s   	

r  c               @   s   e Zd ZeddddddZeddddZeedd	d
ddddZedddddZedd
ddddZ	edd
dddddZ
ejddddZejdddZdS )ContrastMgrInputSpecTz%sr   z$contrast file containing T-contrasts)r;   r   r   r   r   z-f %sz$contrast file containing F-contrasts)r;   r   r   )r;   rK   Fz8Parameter estimates for each column of the design matrix)r   r   r   r   z2statistical corrections used within FILM modelling)r;   r   r   r   zdegrees of freedom)r;   r   r   r   r   r   z1summary of residuals, See Woolrich, et. al., 2001)r;   r   r   r   r   r   z-copez,contrast number to start labeling copes from)r   r   r   z
-suffix %sz\suffix to put on the end of the cope filename before the contrast number, default is nothing)r   r   Nr   r   )r&   r'   r(   r   r   r   r   r   r   r   r   r   r   contrast_numr0   suffixr8   r8   r8   r9   r#    sJ   r#  c               @   s   e Zd ZeeddddZeeddddZeeddddZeeddddZeeddddZ	eeddd	dZ
eeddd
dZdS )ContrastMgrOutputSpecT)r;   z$Contrast estimates for each contrast)r   z$Variance estimates for each contrastzz-stat file for each contrastzt-stat file for each contrastzf-stat file for each contrastzz-stat file for each F contrastzneff file ?? for each contrastN)r&   r'   r(   r   r   r   r   r   r   r   r   neffsr8   r8   r8   r9   r&    s   r&  c                   st   e Zd ZdZej r0eej edkr0ed dZe	Z
eZ fddZ fddZd	d
 Zdd Zdd Z  ZS )ContrastMgra  Use FSL contrast_mgr command to evaluate contrasts

    In interface mode this file assumes that all the required inputs are in the
    same location. This has deprecated for FSL versions 5.0.7+ as the necessary
    corrections file is no longer generated by FILMGLS.
    z5.0.7z'ContrastMgr is deprecated in FSL 5.0.7+Zcontrast_mgrc                s$   t t| j|}|jr | j| |S )N)r   r(  r   stderrZraise_exception)rD   r   )r   r8   r9   r      s    
zContrastMgr._run_interfacec                s@   |dkrdS |dkr(t jj|\}}|S tt| j|||S d S )Nr   r   r   rK   r   )r   r   r   )r   )rj   rk   r   r   r(  r   )rD   rN   r   r   rk   r   )r   r8   r9   r   	  s    zContrastMgr._format_argc             C   s   t jj|\}}|jdd S )Nr   r   )rj   rk   r   )rD   r   r   r   r8   r8   r9   r     s    zContrastMgr._get_design_rootc             C   s   d}d}t | jjrXt| jjd}x,|j D ] }|jdr,t|j d }P q,W |j  t | jj	rt| jj	d}x,|j D ] }|jdr|t|j d }P q|W |j  ||fS )Nr   r   z/NumContrastsr   r   r   )
r   r   r   r@   r   r   rp   r   rC   r   )rD   r   r   r   r   r8   r8   r9   r     s"    

zContrastMgr._get_numconsc             C   s  | j  j }tjj| jj\}}| j \}}d}t| jj	rD| jj	}g }g }g }	g }
g }xt
|D ]}|j| jd||  |d |j| jd||  |d |	j| jd||  |d |
j| jd||  |d |j| jd||  |d qbW |r$||d< ||d	< |	|d
< |
|d< ||d< g }g }xJt
|D ]>}|j| jd||  |d |j| jd||  |d q6W |r||d< ||d< |S )Nr   z
cope%d.nii)r|   zvarcope%d.niizzstat%d.niiztstat%d.niiz
neff%d.niir   r   r   r   r'  zfstat%d.niizzfstat%d.niir   r   )r   rr   rj   rk   r   r   r   r   r   r$  rt   ri   r   )rD   r   r  r   r   r   r  r   r   r   r   r'  rH   r   r   r8   r8   r9   r   )  sD     zContrastMgr._list_outputs)r&   r'   r(   r   r   r  r   DeprecationWarningr   r#  r   r&  r   r   r   r   r   r   r   r8   r8   )r   r9   r(    s   		r(  c               @   s   e Zd ZejddddZdS )L2ModelInputSpecr   Tznumber of copes to be combined)r   r   r   N)r&   r'   r(   r   r   	num_copesr8   r8   r8   r9   r+  P  s   r+  c               @   s0   e Zd ZedddZedddZedddZdS )L2ModelOutputSpecTzdesign matrix file)r;   r   zdesign contrast filezdesign group fileN)r&   r'   r(   r   
design_mat
design_con
design_grpr8   r8   r8   r9   r-  V  s   r-  c               @   s(   e Zd ZdZeZeZdd Zdd Z	dS )L2ModelzGenerate subject specific second level model

    Examples
    --------

    >>> from nipype.interfaces.fsl import L2Model
    >>> model = L2Model(num_copes=3) # 3 sessions

    c       
      C   s   t j }ddj| jjdddg}xt| jjD ]}|dg7 }q.W dj|}ddd	dd
dddg}dj|}ddj| jjddg}xt| jjD ]}|dg7 }qW dj|}|||d}xDtdddgD ]2\}}tt j	j||d}	|	j
||  |	j  qW |S )Nz/NumWaves   1z/NumPoints  {:d}z/PPheights  1rK   z/Matrix1r\   z/ContrastName1  group meanz/NumContrasts   1z/RequiredEffect     100)z
design.matz
design.conz
design.grpz
design.matz
design.conz
design.grpr?   )rj   r   formatr   r,  rt   rl   rh   r@   rk   rB   rC   )
rD   r   r|   mat_txtrH   con_txtgrp_txttxtrN   rG   r8   r8   r9   r   j  s>    


zL2Model._run_interfacec             C   sD   | j  j }x2t|j D ]"}tjjtj |jdd||< qW |S )Nr   r   )	r   rr   rx   ry   rj   rk   rl   r   replace)rD   r   r   r8   r8   r9   r     s    "zL2Model._list_outputsN)
r&   r'   r(   r   r+  r   r-  r   r   r   r8   r8   r8   r9   r1  \  s
   	.r1  c               @   s   e Zd Zejejejejejdejejejej	ejejejdejejejejd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ddZd	S )
MultipleRegressDesignInputSpecr$   r%   Ta  List of contrasts with each contrast being a list of the form - [('name', 'stat', [condition list], [weight list])]. if session list is None or not provided, all sessions are used. For F contrasts, the condition list should contain previously defined T-contrasts without any weight list.)r   r   z/dictionary containing named lists of regressorsz4list of group identifiers (defaults to single group))r   N)r&   r'   r(   r   r5   r,   r6   r0   r.   r)   r7   r-   
regressorsr2   groupsr8   r8   r8   r9   r9    s2   


r9  c               @   s<   e Zd ZedddZedddZedddZedddZdS )MultipleRegressDesignOutputSpecTzdesign matrix file)r;   r   zdesign t-contrast filezdesign f-contrast filezdesign group fileN)r&   r'   r(   r   r.  r/  Z
design_ftsr0  r8   r8   r8   r9   r<    s   r<  c               @   s(   e Zd ZdZeZeZdd Zdd Z	dS )MultipleRegressDesignaS  Generate multiple regression design

    .. note::
      FSL does not demean columns for higher level analysis.

    Please see `FSL documentation
    <http://www.fmrib.ox.ac.uk/fsl/feat5/detail.html#higher>`_
    for more details on model specification for higher level analysis.

    Examples
    --------

    >>> from nipype.interfaces.fsl import MultipleRegressDesign
    >>> model = MultipleRegressDesign()
    >>> model.inputs.contrasts = [['group mean', 'T',['reg1'],[1]]]
    >>> model.inputs.regressors = dict(reg1=[1, 1, 1], reg2=[2.,-4, 3])
    >>> model.run() # doctest: +SKIP

    c          	      s  t j }tjjj }t|}tjj|d  }tdd jjD }tdd jjD }d| d| g}g }	xt|D ]l}
t	j
jj|
 }t	jjj|
 }t	j|t	j|krt
t|t|g}nt|| }|	jd|  qzW |dd	j|	 g7 }|d
dg7 }x2t|D ]& |jd	j fdd|D  qW dj|d }g }d}i }xNtjjD ]>\}}|d dkrf|||< |d7 }|d||d f g7 }qfW |d| d| dd	jdd t|D  dd	jdd t|D  d
dg7 }xt|j D ]p}t	j|df}x@tjj| d D ](\}}
jj| d | ||j|
< q*W |jd	jdd |D  qW dj|d }d
}|r,d| d| d
dg}xztjjD ]j\}}|d dkrt	j|df}x(|d D ]}d||jjj| < qW |jd	jdd |D  qW dj|d }dd| d
dg}xBt|D ]6}tjjrp|djj|  g7 }n
|dg7 }qFW dj|d }||||d}xdt|j D ]T\}}d|kr|dkrʐq|jd d!}tt jj||d"}|j| |j  qW |S )#Nr   c             S   s   g | ]}|d  dkrd qS )r   r$   r8   )rX   r   r8   r8   r9   rZ     s    z8MultipleRegressDesign._run_interface.<locals>.<listcomp>c             S   s   g | ]}|d  dkrd qS )r   r%   r8   )rX   r   r8   r8   r9   rZ     s    z/NumWaves       %dz/NumPoints      %dz%ez/PPheights       rK   z/Matrixc                s    g | ]}d j j|    qS )z%e)r   r:  )rX   key)cidxrD   r8   r9   rZ     s    r\   r   r$   z/ContrastName%d   %sz/NumContrasts   %dz/PPheights          %sc             S   s   g | ]}d d qS )z%er   r8   )rX   rH   r8   r8   r9   rZ     s    z/RequiredEffect     %sc             S   s   g | ]}d d qS )z%.3fd   r8   )rX   rH   r8   r8   r9   rZ     s    r   r   c             S   s   g | ]}d | qS )z%er8   )rX   r[   r8   r8   r9   rZ     s    r%   c             S   s   g | ]}d | qS )z%dr8   )rX   r[   r8   r8   r9   rZ   $  s    z/NumWaves       1z%dr2  )z
design.matz
design.conz
design.ftsz
design.grpftsr   r   r?   )rj   r   sortedr   r:  ry   rA   sumr7   r   maxminsignabsri   rl   rt   rh   zerosrz   r   r;  rx   itemsr8  r@   rk   rB   rC   )rD   r   r|   regsZnwavesZnpointsZntconsnfconsr4  Z	ppheightsregZmaxregZminregZ	regheightr5  counterZtconmapZconidxr   idxZconvalsZregidxZfcon_txttconr6  rH   r7  r?  r[   filenamerG   r8   )r@  rD   r9   r     s    
"$  
z$MultipleRegressDesign._run_interfacec             C   sl   | j  j }tdd | jjD }xDt|j D ]4}d|krF|dkrFq0tjj	tj
 |jdd||< q0W |S )Nc             S   s   g | ]}|d  dkrd qS )r   r%   r8   )rX   r   r8   r8   r9   rZ   C  s    z7MultipleRegressDesign._list_outputs.<locals>.<listcomp>rB  r   r   r   )r   rr   rD  r   r7   rx   ry   rj   rk   rl   r   r8  )rD   r   rL  r   r8   r8   r9   r   A  s    "z#MultipleRegressDesign._list_outputsN)
r&   r'   r(   r   r9  r   r<  r   r   r   r8   r8   r8   r9   r=    s
   [r=  c               @   sD   e Zd ZedddddddZeddddd	ddZejd
dddZdS )SMMInputSpecTr   z
--sdf="%s"zstatistics spatial mapF)r;   r   r   r   r   r   r   z--mask="%s"z	mask filer   z--zfstatmodezenforces no deactivation class)r   r   r   N)	r&   r'   r(   r   Zspatial_data_filemaskr   r/   no_deactivation_classr8   r8   r8   r9   rR  K  s    rR  c               @   s*   e Zd ZeddZeddZeddZdS )SMMOutputSpecT)r;   N)r&   r'   r(   r   
null_p_mapactivation_p_mapdeactivation_p_mapr8   r8   r8   r9   rU  a  s   

rU  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )SMMa3  
    Spatial Mixture Modelling. For more detail on the spatial mixture modelling
    see Mixture Models with Adaptive Spatial Regularisation for Segmentation
    with an Application to FMRI Data; Woolrich, M., Behrens, T., Beckmann, C.,
    and Smith, S.; IEEE Trans. Medical Imaging, 24(1):1-11, 2005.
    zmm --ld=logdirc             C   s^   | j  j }| jddd|d< | jddd|d< t| jj sH| jj rZ| jddd|d< |S )	NZw1_meanZlogdir)basenamer|   rV  Zw2_meanrW  Zw3_meanrX  )r   rr   r   r   r   rT  )rD   r   r8   r8   r9   r   s  s    
zSMM._list_outputsN)
r&   r'   r(   r   r   rR  r   rU  r   r   r8   r8   r8   r9   rY  g  s
   rY  c               @   s  e Zd Zeedd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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-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	jd;d<dZ$e	j
d=d>dZ%edd?d@dZ&eddAdBdZ'eddCdDdZ(e	j)e	jdEdFdZ*e	j
dGdHdZ+eddIdJdZ,e	jdKdLdZ-e	j
dMdNdZ.eddOdPdZ/eddQdRdZ0eddSdTdZ1eddUdVdZ2e	j
dWdXdZ3e	j
dYdZdZ4e	j
d[d\dZ5e	j
d]d^dZ6e	j
d_d`dZ7e	j
dadbdZ8e	j
dcdddZ9e	jdedfdZ:e	j
dgdhdZ;diS )jMELODICInputSpecT)r;   z-i %sr   z4input file names (either single file name or a list),)r   r   r   r   sepz-o %szoutput directory name)r   r   genfilez-m %sz"file name of mask for thresholding)r;   r   r   z--nomaskzswitch off masking)r   r   z--update_maskzswitch off mask updatingz--nobetzswitch off BETz--bgthreshold=%fzcbrain/non-brain threshold used to mask non-brain voxels, as a percentage (only if --nobet selected)z-d %dzMdimensionality reduction into #num dimensions (default: automatic estimation)z--dimest=%szOuse specific dim. estimation technique: lap, bic, mdl, aic, mean (default: lap)z--sep_whitenzswitch on separate whiteningz--sep_vnz(switch off joined variance normalizationz--migpzswitch on MIGP data reductionz
--migpN %dznumber of internal Eigenmapsz--migp_shufflez)randomise MIGP file order (default: TRUE)z--migp_factor %dzMInternal Factor of mem-threshold relative to number of Eigenmaps (default: 2)z-n %dz2number of IC's to extract (for deflation approach)z-a %szPapproach for decomposition, 2D: defl, symm (default), 3D: tica (default), concatz--nl=%sz%nonlinearity: gauss, tanh, pow3, pow4z--vnz!switch off variance normalizationz--pbscz3switch off conversion to percent BOLD signal changez--covarweight=%fzLvoxel-wise weights for the covariance matrix (e.g. segmentation information)z--eps=%fzminimum error changez	--epsS=%fz5minimum error change for rank-1 approximation in TICAz
--maxit=%dz+maximum number of iterations before restartz--maxrestart=%dzmaximum number of restartsz--mmthresh=%fz+threshold for Mixture Model based inferencez--no_mmz'switch off mixture modelling on IC mapsz--ICs=%sz8filename of the IC components file for mixture modellingz--mix=%sz/mixing matrix for mixture modelling / filteringz
--smode=%sz-matrix of session modes for report generationz-f %dzcomponent numbers to removez--reportzgenerate Melodic web reportz--bgimage=%sz9specify background image for report (default: mean image)z--tr=%fzTR in secondsz
--logPowerz-calculate log of power for frequency spectrumz	--Tdes=%sz design matrix across time-domainz	--Tcon=%sz$t-contrast matrix across time-domainz	--Sdes=%sz#design matrix across subject-domainz	--Scon=%sz't-contrast matrix across subject-domainz--Oallzoutput everythingz--Ounmixzoutput unmixing matrixz--Ostatsz,output thresholded maps and probability mapsz--Opcazoutput PCA resultsz--Owhitez%output whitening/dewhitening matricesz--Oorigzoutput the original ICsz--Omeanzoutput mean volumez--report_maps=%sz2control string for spatial map images (see slicer)z--remove_derivz<removes every second entry in paradigm file (EV derivatives)N)<r&   r'   r(   r   r   in_filesr   out_dirrS  r   r/   Zno_maskZupdate_maskZno_betr)   Zbg_thresholdr2   Zdimr0   Zdim_estZ
sep_whitenZsep_vnZmigpZmigpNZmigp_shuffleZmigp_factorZnum_ICsZapproachZnon_linearityvar_normZpbscZ
cov_weightepsilonZepsilonSZmaxitZmax_restartZ	mm_threshZno_mmZICsZmixZsmoder5   Zrem_cmpreportZbg_imageZtr_secZ	log_powerZt_desZt_conZs_desZs_conZout_allZ	out_unmixZ	out_statsZout_pcaZ	out_whiteZout_origZout_meanZreport_mapsZremove_derivr8   r8   r8   r9   r[    s   












r[  c               @   s    e Zd ZeddZeddZdS )MELODICOutputSpecT)r;   N)r&   r'   r(   r   r`  
report_dirr8   r8   r8   r9   rd    s   
rd  c               @   s,   e Zd ZdZeZeZdZdd Z	dd Z
dS )MELODICak  Multivariate Exploratory Linear Optimised Decomposition into Independent
    Components

    Examples
    --------

    >>> melodic_setup = MELODIC()
    >>> melodic_setup.inputs.approach = 'tica'
    >>> melodic_setup.inputs.in_files = ['functional.nii', 'functional2.nii', 'functional3.nii']
    >>> melodic_setup.inputs.no_bet = True
    >>> melodic_setup.inputs.bg_threshold = 10
    >>> melodic_setup.inputs.tr_sec = 1.5
    >>> melodic_setup.inputs.mm_thresh = 0.5
    >>> melodic_setup.inputs.out_stats = True
    >>> melodic_setup.inputs.t_des = 'timeDesign.mat'
    >>> melodic_setup.inputs.t_con = 'timeDesign.con'
    >>> melodic_setup.inputs.s_des = 'subjectDesign.mat'
    >>> melodic_setup.inputs.s_con = 'subjectDesign.con'
    >>> melodic_setup.inputs.out_dir = 'groupICA.out'
    >>> melodic_setup.cmdline
    'melodic -i functional.nii,functional2.nii,functional3.nii -a tica --bgthreshold=10.000000 --mmthresh=0.500000 --nobet -o groupICA.out --Ostats --Scon=subjectDesign.con --Sdes=subjectDesign.mat --Tcon=timeDesign.con --Tdes=timeDesign.mat --tr=1.500000'
    >>> melodic_setup.run() # doctest: +SKIP


    Zmelodicc             C   sj   | j  j }t| jjr.tjj| jj|d< n| jd|d< t| jj	rf| jj	rftjj
|d d|d< |S )Nr`  rc  re  )r   rr   r   r   r`  rj   rk   r  _gen_filenamerc  rl   )rD   r   r8   r8   r9   r   9  s    zMELODIC._list_outputsc             C   s   |dkrt j S d S )Nr`  )rj   r   )rD   rN   r8   r8   r9   rg  C  s    zMELODIC._gen_filenameN)r&   r'   r(   r   r[  r   rd  r   r   r   rg  r8   r8   r8   r9   rf    s   
rf  c               @   sT   e Zd ZejdddgddZedddddZed	dd
gddZeddd
gddZ	dS )SmoothEstimateInputSpecz--dof=%dT
zstat_fileznumber of degrees of freedom)r   r   r   r   z	--mask=%szbrain mask volume)r   r;   r   r   z--res=%sr   zresidual-fit image file)r   r;   requiresr   z
--zstat=%szzstat image file)r   r;   r   r   N)
r&   r'   r(   r   r2   r   r   r  Zresidual_fit_fileri  r8   r8   r8   r9   rh  H  s   rh  c               @   s0   e Zd ZejddZejddZejddZdS )SmoothEstimateOutputSpecz%smoothness estimate sqrt(det(Lambda)))r   znumber of voxels in maskz?volume of resel, in voxels, defined as FWHM_x * FWHM_y * FWHM_zN)	r&   r'   r(   r   r)   dlhr2   volumereselsr8   r8   r8   r9   rk  Z  s   rk  c               @   s&   e Zd ZdZeZeZdZdddZ	dS )SmoothEstimatea	  Estimates the smoothness of an image

    Examples
    --------

    >>> est = SmoothEstimate()
    >>> est.inputs.zstat_file = 'zstat1.nii.gz'
    >>> est.inputs.mask_file = 'mask.nii'
    >>> est.cmdline
    'smoothest --mask=mask.nii --zstat=zstat1.nii.gz'

    Z	smoothestNc             C   sZ   | j  }|jjd}t|d j d |_t|d j d |_t|d j d |_|S )Nr\   r   r   r   )r   stdoutr   floatrl  rp   rm  rn  )rD   r   Zneeded_outputsr   rp  r8   r8   r9   aggregate_outputst  s    z SmoothEstimate.aggregate_outputs)NN)
r&   r'   r(   r   rh  r   rk  r   r   rr  r8   r8   r8   r9   ro  b  s
   ro  c               @   s  e Zd ZedddddZejddddZejej	edd	d
dZ
ejej	eddd
dZejej	eddd
dZejej	eddd
dZejej	eddd
dZejej	eddd
dZejej	eddd
dZejej	eddd
dZejdddg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(d)d*Zejd+d,d!Zej	d
dd-d.d*Zej	d
dd/d0d*Zej	d
dd1d2d*Zej	d
dd3d4d*Zed5d6d!Zed7d8d!Zejd9d:d!Z ed;d<d!Z!d=S )>ClusterInputSpecz--in=%sTzinput volume)r   r   r;   r   z--thresh=%.10fzthreshold for input volume)r   r   r   z--oindex=%sz'output of cluster index (in size order)F)r   r   Z
hash_filesz--othresh=%szthresholded imagez
--olmax=%szlocal maxima text filez--olmaxim=%szoutput of local maxima volumez
--osize=%sz!filename for output of size imagez	--omax=%sz filename for output of max imagez
--omean=%sz!filename for output of mean imagez--opvals=%sz&filename for image output of log pvalsz--pthresh=%.10frl  rm  zp-threshold for clusters)r   rj  r   z--peakdist=%.10fz?minimum distance between local maxima/minima, in mm (default 0))r   r   z	--cope=%szcope volumez--volume=%dznumber of voxels in the maskz--dlh=%.10fz'smoothness estimate = sqrt(det(Lambda))z--fractionalz:interprets the threshold as a fraction of the robust range)r#   r   r   z--connectivity=%dz'the connectivity of voxels (default 26)z--mmzuse mm, not voxel, coordinatesz--minzfind minima instead of maximaz
--no_tablez%suppresses printing of the table infoz--minclustersizez+prints out minimum significant cluster sizez--xfm=%szZfilename for Linear: input->standard-space transform. Non-linear: input->highres transformz--stdvol=%sz"filename for standard-space volumez--num=%dzno of local maxima to reportz--warpvol=%szfile contining warpfieldN)"r&   r'   r(   r   r   r   r)   r   r,   r/   out_index_fileout_threshold_fileout_localmax_txt_fileout_localmax_vol_fileout_size_fileout_max_fileout_mean_fileout_pval_fileZ
pthresholdZpeak_distancer  r2   rm  rl  Z
fractionalZconnectivityZuse_mmZfind_minZno_tableZminclustersizeZxfm_fileZstd_space_fileZ
num_maximaZwarpfield_filer8   r8   r8   r9   rs  }  s   


rs  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d
S )ClusterOutputSpecz'output of cluster index (in size order))r   zthresholded imagezlocal maxima text filezoutput of local maxima volumez!filename for output of size imagez filename for output of max imagez!filename for output of mean imagez&filename for image output of log pvalsN)r&   r'   r(   r   Z
index_fileZthreshold_fileZlocalmax_txt_fileZlocalmax_vol_fileZ	size_fileZmax_fileZ	mean_fileZ	pval_filer8   r8   r8   r9   r|    s   






r|  c            	       sJ   e Zd ZdZeZeZdZddddddd	d
dZ	dd Z
 fddZ  ZS )Clusteraz  Uses FSL cluster to perform clustering on statistical output

    Examples
    --------

    >>> cl = Cluster()
    >>> cl.inputs.threshold = 2.3
    >>> cl.inputs.in_file = 'zstat1.nii.gz'
    >>> cl.inputs.out_localmax_txt_file = 'stats.txt'
    >>> cl.inputs.use_mm = True
    >>> cl.cmdline
    'cluster --in=zstat1.nii.gz --olmax=stats.txt --thresh=2.3000000000 --mm'

    Zclusterrz   r   zlocalmax.txtZlocalmaxsizerE  ZmeanZpval)rt  ru  rv  rw  rx  ry  rz  r{  c             C   s   | j  j }xt| jj D ]v\}}|dd  }t| j|}t|rt|t	r|rd}|j
drdd}| j| jjd| |d||< qtjj|||< qW |S )N   Tz.txtFr   )r%  r  )r   rr   rx   filemaprJ  getattrr   r   r   rq   r{   r   r   rj   rk   r  )rD   r   r?  r%  ZoutkeyZinvalr  r8   r8   r9   r     s     

zCluster._list_outputsc                sT   |t | jj kr@t|tr2| j |dd   }n|}|j| S tt| j	|||S )Nr  )
rx   r  ry   r   rq   r   r   r   r}  r   )rD   rN   specr   r   )r   r8   r9   r   /  s    

zCluster._format_arg)r&   r'   r(   r   rs  r   r|  r   r   r  r   r   r   r8   r8   )r   r9   r}    s   r}  c               @   s   e Zd ZeeddddddddZedddddd	Zejdd
ddddZ	ejddddZ
edddddZedddddZejd
ddddZedddddddZdS )DualRegressionInputSpecT)r;   z%sr   r>  z;List all subjects' preprocessed, standard-space 4D datasets)r   r   r   r]  r   zR4D image containing spatial IC maps (melodic_IC) from the whole-group ICA analysis)r;   r   r   r   r   z%ir   zmWhether to variance-normalise the timecourses used as the stage-2 regressors; True is default and recommended)r   r   r#   r   z-1r   zDperform 1-sample group-mean test instead of generic permutation test)r   r   r   z>Design matrix for final cross-subject modelling with randomise)r;   r   r   r   r  zADesign contrasts for final cross-subject modelling with randomise   zoNumber of permutations for randomise; set to 1 for just raw tstat output, set to 0 to not run randomise at all.)r   r   r   r   outputrJ   z>This directory will be created to hold all output and logfiles)r   r#   r   r   r^  Nr   )r&   r'   r(   r   r   r_  Zgroup_IC_maps_4Dr   r/   des_normone_sample_group_meanr   r   r2   Zn_permr   r`  r8   r8   r8   r9   r  9  sZ   r  c               @   s   e Zd ZeddZdS )DualRegressionOutputSpecT)r;   N)r&   r'   r(   r   r`  r8   r8   r8   r9   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 )DualRegressiona  Wrapper Script for Dual Regression Workflow

    Examples
    --------

    >>> dual_regression = DualRegression()
    >>> dual_regression.inputs.in_files = ["functional.nii", "functional2.nii", "functional3.nii"]
    >>> dual_regression.inputs.group_IC_maps_4D = "allFA.nii"
    >>> dual_regression.inputs.des_norm = False
    >>> dual_regression.inputs.one_sample_group_mean = True
    >>> dual_regression.inputs.n_perm = 10
    >>> dual_regression.inputs.out_dir = "my_output_directory"
    >>> dual_regression.cmdline
    'dual_regression allFA.nii 0 -1 10 my_output_directory functional.nii functional2.nii functional3.nii'
    >>> dual_regression.run() # doctest: +SKIP

    Zdual_regressionc             C   s@   | j  j }t| jjr.tjj| jj|d< n| jd|d< |S )Nr`  )	r   rr   r   r   r`  rj   rk   r  rg  )rD   r   r8   r8   r9   r     s
    zDualRegression._list_outputsc             C   s   |dkrt j S d S )Nr`  )rj   r   )rD   rN   r8   r8   r9   rg    s    zDualRegression._gen_filenameN)r&   r'   r(   r   r  r   r  r   r   r   rg  r8   r8   r8   r9   r  x  s   r  c               @   s  e Zd ZeddddddZej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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/d0Zejd1d2d0Zejd3d4d0Zejd5d6d0Zejd7d8d0Zejd9d:d0Zejd;d<d0Z ejd=d>d0Z!ejd?d@d0Z"ejdAdBd0Z#dCS )DRandomiseInputSpecTz4D input filez-i %sr   )r;   r   r   r   r   	randomisez/the rootname that all generated files will havez-o "%s"r   )r   r   r   r#   zdesign matrix filez-d %sr   )r;   r   r   r   zt contrasts filez-t %sr   zf contrasts filez-f %s)r;   r   r   z
mask imagez-m %sz!exchangeability block labels filez-e %sz+demean data temporally before model fittingz-D)r   r   zDperform 1-sample group-mean test instead of generic permutation testz-1zBprint out how many unique permutations would be generated and exitz-qz9print out information required for parallel mode and exitz-Qz;output voxelwise (corrected and uncorrected) p-value imagesz-xz,carry out Threshold-Free Cluster Enhancementz-TzAcarry out Threshold-Free Cluster Enhancement with 2D optimisationz--T2zcalculate f-statistics onlyz--fonlyz*output raw ( unpermuted ) statistic imagesz-Rz:output permutation vector and null distribution text filesz-Pz-n %dz>number of permutations (default 5000, set to 0 for exhaustive))r   r   z	--seed=%dz1specific integer seed for random number generatorz-v %dz%use variance smoothing (std is in mm)z-c %.1fz$carry out cluster-based thresholdingz-C %.1fz)carry out cluster-mass-based thresholdingz-F %.2fz carry out f cluster thresholdingz-S %.2fz%carry out f cluster-mass thresholdingz--tfce_H=%.2fz!TFCE height parameter (default=2)z--tfce_E=%.2fz#TFCE extent parameter (default=0.5)z--tfce_C=%.2fz&TFCE connectivity (6 or 26; default=6)N)$r&   r'   r(   r   r   r   r0   	base_namer.  rP  ZfconrS  Zx_block_labelsr/   demeanr  Zshow_total_permsZshow_info_parallel_modevox_p_valuestfcetfce2DZf_onlyZraw_stats_imgsZp_vec_n_dist_filesr2   Znum_permseedZ
var_smoothr)   c_thresh	cm_thresh
f_c_threshf_cm_threshZtfce_HZtfce_EZtfce_Cr8   r8   r8   r9   r    sp   











r  c               @   s   e Zd Zej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ddZ	ejeddddZ
ejeddddZd	S )
RandomiseOutputSpecT)r;   zt contrast raw statistic)r   zf contrast raw statisticz%f contrast uncorrected p values filesz;t contrast FWE (Family-wise error) corrected p values filesz;f contrast FWE (Family-wise error) corrected p values filesN)r&   r'   r(   r   r5   r   tstat_filesfstat_files	t_p_files	f_p_filest_corrected_p_filesf_corrected_p_filesr8   r8   r8   r9   r    s   r  c               @   s$   e Zd ZdZdZeZeZdd Z	dS )	Randomisea  FSL Randomise: feeds the 4D projected FA data into GLM
    modelling and thresholding
    in order to find voxels which correlate with your model

    Example
    -------
    >>> import nipype.interfaces.fsl as fsl
    >>> rand = fsl.Randomise(in_file='allFA.nii', mask = 'mask.nii', tcon='design.con', design_mat='design.mat')
    >>> rand.cmdline
    'randomise -i allFA.nii -o "randomise" -d design.mat -t design.con -m mask.nii'

    r  c             C   s  | j  j }t| jd| jj |d< t| jd| jj |d< d}| jjsT| jjrZd}n8| jjrhd}n*| jj	sx| jj
r~d}n| jjs| jjrd	}|rt| jd
| jj|f |d< t| jd| jj|f |d< t| jd| jj|f |d< t| jd| jj|f |d< |S )Nz%s_tstat*.niir  z%s_fstat*.niir  Fr  ZvoxZclustereZclustermz%s_%s_p_tstat*r  z%s_%s_corrp_tstat*.niir  z%s_%s_p_fstat*.niir  z%s_%s_corrp_fstat*.niir  )r   rr   r   r   r   r  r  r  r  r  r  r  r  )rD   r   prefixr8   r8   r9   r   	  s4    zRandomise._list_outputsN)
r&   r'   r(   r   r   r  r   r  r   r   r8   r8   r8   r9   r  	  s
   r  c               @   s*  e Zd ZeddddddZed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d d!dZe	j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d0d1dZed2d3dZed4d5dZed6d7dZed8d9dZd:S )@GLMInputSpecTz-i %sr   z1input file name (text matrix or 3D/4D image file))r;   r   r   r   r   z%s_glmz-o %sr   z$filename for GLM parameter estimatesz (GLM betas)r   )Zname_templater   r   r   Zname_sourceZkeep_extensionz-d %sr   z-file name of the GLM design matrix (text timez, courses for temporal regression or an imagez file for spatial regression)z-c %szmatrix of t-statics contrasts)r;   r   r   z-m %sz&mask image file name if input is imagez--dof=%dzset degrees of freedomz explicitly)r   r   z
--des_normz%switch on normalization of the designz% matrix columns to unit std deviationz
--dat_normzEswitch on normalization of the data time series to unit std deviationz--vnz.perform MELODIC variance-normalisation on dataz--demeanz'switch on demeaining of design and dataz--out_cope=%sz1output file name for COPE (either as txt or imagez
--out_z=%sz4output file name for Z-stats (either as txt or imagez
--out_t=%sz4output file name for t-stats (either as txt or imagez
--out_p=%szGoutput file name for p-values of Z-stats (either as text file or image)z
--out_f=%sz.output file name for F-value of full model fitz--out_pf=%sz/output file name for p-value for full model fitz--out_res=%szoutput file name for residualsz--out_varcb=%sz&output file name for variance of COPEsz--out_sigsq=%sz9output file name for residual noise variance sigma-squarez--out_data=%sz'output file name for pre-processed dataz--out_vnscales=%sz?output file name for scaling factors for variance normalisationNz0filename for GLM parameter estimates (GLM betas)zYfile name of the GLM design matrix (text time courses for temporal regression or an imagezvfile name of the GLM design matrix (text time courses for temporal regression or an image file for spatial regression)z!set degrees of freedom explicitlyzJswitch on normalization of the design matrix columns to unit std deviation)r&   r'   r(   r   r   out_fileZdesignr7   rS  r   r2   r   r/   r  Zdat_normra  r  out_cope
out_z_name
out_t_name
out_p_name
out_f_nameout_pf_nameout_res_nameout_varcb_nameout_sigsq_nameout_data_nameout_vnscales_namer8   r8   r8   r9   r  9	  sv    








r  c               @   s   e Zd ZedddZeeddddZeeddddZeeddddZeeddddZ	eeddd	dZ
eeddd
dZeeddddZeeddddZeeddddZeeddddZeeddddZdS )GLMOutputSpecTz*file name of GLM parameters (if generated))r;   r   )r;   z9output file name for COPEs (either as text file or image))r   z;output file name for t-stats (either as text file or image)zGoutput file name for p-values of Z-stats (either as text file or image)z.output file name for F-value of full model fitz/output file name for p-value for full model fitzoutput file name for residualsz&output file name for variance of COPEsz9output file name for residual noise variance sigma-squarez!output file for preprocessed dataz?output file name for scaling factors for variance normalisationN)r&   r'   r(   r   r  r   r  out_zout_tout_pout_fout_pfout_res	out_varcb	out_sigsqout_dataout_vnscalesr8   r8   r8   r9   r  	  s8   r  c                   s,   e Zd ZdZdZeZeZ fddZ	  Z
S )GLMa  
    FSL GLM:

    Example
    -------
    >>> import nipype.interfaces.fsl as fsl
    >>> glm = fsl.GLM(in_file='functional.nii', design='maps.nii', output_type='NIFTI')
    >>> glm.cmdline
    'fsl_glm -i functional.nii -d maps.nii -o functional_glm.nii'

    Zfsl_glmc                sz  t t| j }t| jjr.tjj| jj|d< t| jj	rNtjj| jj	|d< t| jj
rntjj| jj
|d< t| jjrtjj| jj|d< t| jjrtjj| jj|d< t| jjrtjj| jj|d< t| jjrtjj| jj|d< t| jjrtjj| jj|d< t| jjr2tjj| jj|d	< t| jjrTtjj| jj|d
< t| jjrvtjj| jj|d< |S )Nr  r  r  r  r  r  r  r  r  r  r  )r   r  r   r   r   r  rj   rk   r  r  r  r  r  r  r  r  r  r  r  )rD   r   )r   r8   r9   r   	  s0    zGLM._list_outputs)r&   r'   r(   r   r   r  r   r  r   r   r   r8   r8   )r   r9   r  	  s
   r  c          	   C   sH   ddl m} |dtjjddd| }t|}t|j }W dQ R X |S )zLoad a template from the model_templates directory

    Parameters
    ----------
    name : str
        The name of the file to load

    Returns
    -------
    template : string.Template

    r   )resource_filenameZnipypeZ
interfacesZfslZmodel_templatesN)pkg_resourcesr  rj   rk   rl   r@   r   r   )rN   ZpkgrfZ
full_fnameZtemplate_filetemplater8   r8   r9   rg   	  s    
rg   )Ur   rj   r   shutilr   stringr   numpyr   Znibabelr   rK   r   Zutils.filemanipr   r	   Z
utils.miscr
   Zexternal.duer   baser   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-  r1  r9  r<  r=  rR  rU  rY  r[  rd  rf  rh  rk  ro  rs  r|  r}  r  r  r  r  r  r  r  r  r  rg   r8   r8   r8   r9   <module>   s   ,X  =
!,HN  L!{4^C(} .t=;$R8[+8