3
d                 @   sF  d Z ddlmZ ddlZddlZddlZddlmZ ddlZ	ddl
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 dd	lmZmZ ejd
Zd(ddZdd Zdd Zd)ddZdd Z G dd deZ!G dd deZ"G dd deZ#G dd de!Z$G d d! d!e#Z%G d"d# d#e!Z&G d$d% d%e"Z'G d&d' d'e#Z(dS )*z
The modelgen module provides classes for specifying designs for individual
subject analysis of task-based fMRI experiments. In particular it also includes
algorithms for generating regressors for sparse and sparse-clustered acquisition
experiments.
    )deepcopyN)load   )BaseInterfaceTraitedSpecInputMultiPathtraitsFileBunchBaseInterfaceInputSpec	isdefined)ensure_list)normalize_mc_params)configloggingznipype.interface   c       	         s  ddl m  tjdddddddgtd}|dk	r@||dt|<  fd	d
}| t| }tjdt|d | d |d |  }tjddN |||d |d  ||d  |||d |d  ||d  |d   }W dQ R X tjdt|d |  d | }|| }|tj	| }|S )ab  
    python implementation of spm_hrf

    See ``spm_hrf`` for implementation details::

      % RT   - scan repeat time
      % p    - parameters of the response function (two gamma
      % functions)
      % defaults  (seconds)
      % p(0) - delay of response (relative to onset)       6
      % p(1) - delay of undershoot (relative to onset)    16
      % p(2) - dispersion of response                      1
      % p(3) - dispersion of undershoot                    1
      % p(4) - ratio of response to undershoot             6
      % p(5) - onset (seconds)                             0
      % p(6) - length of kernel (seconds)                 32
      %
      % hrf  - hemodynamic response function
      % p    - parameters of the response function

    The following code using ``scipy.stats.distributions.gamma``
    doesn't return the same result as the ``spm_Gpdf`` function::

        hrf = gamma.pdf(u, p[0]/p[2], scale=dt/p[2]) -
              gamma.pdf(u, p[1]/p[3], scale=dt/p[3])/p[4]

    Example
    -------
    >>> print(spm_hrf(2))
    [  0.00000000e+00   8.65660810e-02   3.74888236e-01   3.84923382e-01
       2.16117316e-01   7.68695653e-02   1.62017720e-03  -3.06078117e-02
      -3.73060781e-02  -3.08373716e-02  -2.05161334e-02  -1.16441637e-02
      -5.82063147e-03  -2.61854250e-03  -1.07732374e-03  -4.10443522e-04
      -1.46257507e-04]

    r   )gammaln   r          )dtypeNc                s6   t j|t j| |d t j|   ||    | S )Nr   )npexplog)xhl)r    </tmp/pip-build-7vycvbft/nipype/nipype/algorithms/modelgen.py<lambda>L   s   zspm_hrf.<locals>.<lambda>   ignore)divider         )
Zscipy.specialr   r   arrayfloatlenarangeintZerrstatesum)	ZRTPZfMRI_TpZ	_spm_Gpdfdtuhrfidxr   )r   r   spm_hrf!   s    %(4 r1   c             C   s   t j| dddf }t j|dddf }|t j|t jt jjt j|j|t j|j| }t jj|dt jdkr|dddf j }n|}|S )a-  Orthogonalize y_in with respect to x_in.

    >>> orth_expected = np.array([1.7142857142857144, 0.42857142857142883,                                   -0.85714285714285676])
    >>> err = np.abs(np.array(orth([1, 2, 3],[4, 5, 6]) - orth_expected))
    >>> all(err < np.finfo(float).eps)
    True

    Nr   r   r   i)	r   r%   dotZlinalginvTZnormr   tolist)Zx_inZy_inr   yr   r   r   orth]   s    
4r7   c                sN   ||krd |dkr |dkr | |dkr8|dkr8d|   fdd| D } | S )z
    Scale timings given input and output units (scans/secs).

    Parameters
    ----------
    timelist: list of times to scale
    input_units: 'secs' or 'scans'
    output_units: Ibid.
    time_repetition: float in seconds

    g      ?scanssecsc                s   g | ]}t jd  | gqS )g        )r   max).0t)_scalefactorr   r   
<listcomp>   s    z!scale_timings.<locals>.<listcomp>r   )Ztimelistinput_unitsoutput_unitstime_repetitionr   )r=   r   scale_timingsq   s    rB    Fc                s  g }x| D ]|}t |$}tj|ddd}dd |D }W dQ R X shdx|D ]}	|	jdi qRW ttfd	d|D }
tg g g g d
}x|
D ]fdd|D }dd |D }dd |D }|rtjtj	| fdd|D }fdd|D }|j
j |jj| |jj| y" fdd|D }|jj| W q tk
rz   |jjdgt|  Y qX qW |j| qW |S )a  
    Generate a subject_info structure from a list of BIDS .tsv event files.

    Parameters
    ----------
    bids_event_files : list of str
        Filenames of BIDS .tsv event files containing columns including:
        'onset', 'duration', and 'trial_type' or the `condition_column` value.
    condition_column : str
        Column of files in `bids_event_files` based on the values of which
        events will be sorted into different regressors
    amplitude_column : str
        Column of files in `bids_event_files` based on the values of which
        to apply amplitudes to events. If unspecified, all events will be
        represented with an amplitude of 1.

    Returns
    -------
    subject_info: list of Bunch

    T	)skipinitialspace	delimiterc             S   s   g | ]}d d |j  D qS )c             S   s   i | ]\}}||qS r   r   )r;   kvr   r   r   
<dictcomp>   s    z,bids_gen_info.<locals>.<listcomp>.<dictcomp>)items)r;   rowr   r   r   r>      s    z!bids_gen_info.<locals>.<listcomp>NZ_trial_typeZev0c                s   g | ]}|  qS r   r   )r;   i)condition_columnr   r   r>      s    )
conditionsonsets	durations
amplitudesc                s   g | ]}|  kr|qS r   r   )r;   rL   )	conditionrM   r   r   r>      s    c             S   s   g | ]}t |d  qS )onset)r&   )r;   rL   r   r   r   r>      s    c             S   s   g | ]}t |d  qS )duration)r&   )r;   rL   r   r   r   r>      s    c                s   g | ]}t j| qS r   )r   round)r;   rL   )decimalsr   r   r>      s    c                s   g | ]}t j| qS r   )r   rU   )r;   rL   )rV   r   r   r>      s    c                s   g | ]}t |  qS r   )r&   )r;   rL   )amplitude_columnr   r   r>      s    r   )opencsv
DictReaderupdatesortedsetr
   mathceillog10rN   appendrO   rP   rQ   KeyErrorr'   )Zbids_event_filesrM   rW   rA   infobids_event_filefZf_eventseventsrL   rN   runinfoZselected_eventsrO   rP   rQ   r   )rW   rR   rM   rV   r   bids_gen_info   s:    


 rh   c       	      C   s:  g }x.t | D ] \}}tg g g g d}x|D ]}tjj|\}}d|krd|jd|d  \}}nd|krz|jd\}}|jj| tjtj	|}|j
j|dddf j  |jd dkr|jj|dddf j  n|jjdg |jd dkr|jj|dddf j  q0t|d	 q0W |j| qW |S )
z;Generate subject_info structure from a list of event files.)rN   rO   rP   rQ   z.runz.run%03dr   z.txtNr   r   rQ   )	enumerater
   ospathsplitrN   ra   r   Z
atleast_2dloadtxtrO   r5   shaperP   rQ   delattr)	Zrun_event_filesrc   rL   event_filesrg   Z
event_file_nameZ
event_infor   r   r   gen_info   s(    
rs   c            	   @   s  e Zd ZeeddddgddZeejeddddddgddZ	eeddddddgd	dZ
ejd
dddZejddZeedddddZejddddddddZeedddddZeejejedded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d"S )#SpecifyModelInputSpecTsubject_inforp   rd   z~Bunch or List(Bunch) subject-specific condition information. see :ref:`nipype.algorithms.modelgen.SpecifyModel` or for details)	mandatoryxordesc)existsziList of event description files 1, 2 or 3 column format corresponding to onsets, durations and amplitudeszjTSV event file containing common BIDS fields: `onset`,`duration`, and categorization and amplitude columnsZ
trial_typezsColumn of the file passed to ``bids_event_file`` to the unique values of which events will be assignedto regressors)default_value
usedefaultrx   zbColumn of the file passed to ``bids_event_file`` according to which to assign amplitudes to events)rx   z>Realignment parameters returned by motion correction algorithmF)rx   copyfileZSPMZFSLZAFNIZFSFASTZNIPYzSource of motion parameters)r{   rx   z;Files containing scan outlier indices that should be tossedzNData files for model. List of 4D files or list of list of 3D files per session)rv   rx   r|   r9   r8   zTUnits of event onsets and durations (secs or scans). Output units are always in secs)rv   rx   zHigh-pass filter cutoff in secszLTime between the start of one volume to the start of  the next image volume.N)__name__
__module____qualname__r   r
   ru   r   Listr	   rp   rd   Strbids_condition_columnbids_amplitude_columnrealignment_parametersEnumparameter_sourceoutlier_filesZEitherfunctional_runsr?   Floathigh_pass_filter_cutoffrA   r   r   r   r   rt      sh   
rt   c               @   s   e Zd ZejddZdS )SpecifyModelOutputSpeczSession info for level1designs)rx   N)r}   r~   r   r   ZAnysession_infor   r   r   r   r   .  s   r   c               @   s<   e Zd ZdZeZeZdddZdddZ	dd Z
d	d
 ZdS )SpecifyModela
  
    Makes a model specification compatible with spm/fsl designers.

    The subject_info field should contain paradigm information in the form of
    a Bunch or a list of Bunch. The Bunch should contain the following
    information::

        [Mandatory]
        conditions : list of names
        onsets : lists of onsets corresponding to each condition
        durations : lists of durations corresponding to each condition. Should be
            left to a single 0 if all events are being modelled as impulses.

        [Optional]
        regressor_names : list of str
            list of names corresponding to each column. Should be None if
            automatically assigned.
        regressors : list of lists
            values for each regressor - must correspond to the number of
            volumes in the functional run
        amplitudes : lists of amplitudes for each event. This will be ignored by
            SPM's Level1Design.

        The following two (tmod, pmod) will be ignored by any Level1Design class
        other than SPM:

        tmod : lists of conditions that should be temporally modulated. Should
            default to None if not being used.
        pmod : list of Bunch corresponding to conditions
          - name : name of parametric modulator
          - param : values of the modulator
          - poly : degree of modulation

    Alternatively, you can provide information through event files.

    The event files have to be in 1, 2 or 3 column format with the columns
    corresponding to Onsets, Durations and Amplitudes and they have to have the
    name event_name.runXXX... e.g.: Words.run001.txt. The event_name part will
    be used to create the condition names.

    Examples
    --------
    >>> from nipype.algorithms import modelgen
    >>> from nipype.interfaces.base import Bunch
    >>> s = modelgen.SpecifyModel()
    >>> s.inputs.input_units = 'secs'
    >>> s.inputs.functional_runs = ['functional2.nii', 'functional3.nii']
    >>> s.inputs.time_repetition = 6
    >>> s.inputs.high_pass_filter_cutoff = 128.
    >>> evs_run2 = Bunch(conditions=['cond1'], onsets=[[2, 50, 100, 180]], durations=[[1]])
    >>> evs_run3 = Bunch(conditions=['cond1'], onsets=[[30, 40, 100, 150]], durations=[[1]])
    >>> s.inputs.subject_info = [evs_run2, evs_run3]

    >>> # Using pmod
    >>> evs_run2 = Bunch(conditions=['cond1', 'cond2'], onsets=[[2, 50], [100, 180]], durations=[[0], [0]], pmod=[Bunch(name=['amp'], poly=[2], param=[[1, 2]]), None])
    >>> evs_run3 = Bunch(conditions=['cond1', 'cond2'], onsets=[[20, 120], [80, 160]], durations=[[0], [0]], pmod=[Bunch(name=['amp'], poly=[2], param=[[1, 2]]), None])
    >>> s.inputs.subject_info = [evs_run2, evs_run3]

    Nc             C   s2  g }d}d| j j kr| j j}x.t|D ] \}}|j|tg d t| j jrft| j j|| d< t	|dox|j
dk	rxxt|j
D ]\}	}
|| d j|	t  |j
|	 || d |	 d< t|j|	 | j j|| j j}||| d |	 d	< t|j|	 | j j|| j j}||| d |	 d
< t	|drR|jrR|j|	 || d |	 d< t	|dr|jrt|j|	kr|j|	 || d |	 d< t	|dr|jrt|j|	kr|j|	 rg || d |	 d< xt|j|	 jD ]\}}|| d |	 d j|i  ||| d |	 d | d< |j|	 j| || d |	 d | d< |j|	 j| || d |	 d | d< qW qW g || d< t	|dr<|jdk	r<xt|jD ]\}}|| d j|tdg d t	|dr |jdk	r |j| || d | d< nd|d  || d | d< |j| || d | d< qW || || d< q*W |dk	r xt|D ]\}}|| }xt|jd D ]r}t|| d }|| d j|tdg d d|d  || d | d< |dd|f j || d | d< qW qdW |dk	r.x t|D ]\}}d}x`t|| d D ]L}t|j}t|dks`|d dkrttjd |d7 }n||d 7 }q6W xt|D ]\}}t|| d }|| d j|tdg d d|d  || d | d< t j!d|fd j || d | d< d|| d | d t"|< qW qW |S )zLGenerate a standard design matrix paradigm given information about each run.r9   r@   )condZhpfrN   Nr   rr   rS   rT   rQ   tmodpmodpolyparamZregress
regressorsrC   )rr   valregressor_nameszUR%dr   r   r8   z	Realign%dr   r#   zEYou are using 3D instead of 4D files. Are you sure this was intended?z	Outlier%d)#inputsr   r@   ri   insertdictr   r   r&   hasattrrN   rB   rO   r?   rA   rP   rQ   r   r'   r   rr   r   r   r   r   rangern   r5   r   r   ifloggerwarningr   zerosr)   )selfinfolistr   r   outliersZsessinfor@   rL   rc   Zcidr   Zscaled_onsetZscaled_durationjrr   rrpmccolZcolidxoutnumscansre   rn   Zscannor   r   r   _generate_standard_designv  s    

$
2 
0


(z&SpecifyModel._generate_standard_designc             C   sD  g }t | jjrDx2| jjD ]&}|jtjtdtj|| jjd qW g }t | jj	rxl| jj	D ]`}ytj|t
d}W n tk
r   |jg  Y q^X |jdkr|j|j g q^|j|j  q^W |dkr(t | jjr| jj}nFt | jjrt| jj}n,t | jjr(t| jj| jj| jj| jj}| j|| jj||d| _dS )z9Generate design specification for a typical fmri paradigmr   )func1daxisarrsource)r   N)r   r   r   )r   r   r   ra   r   apply_along_axisr   rm   r   r   r)   IOErrorsizer5   ru   rp   rs   rd   rh   r   r   rA   r   r   	_sessinfo)r   r   r   parfiler   filenameZ
outindicesr   r   r   _generate_design  sF    



zSpecifyModel._generate_designc             C   s   d| _ | j  |S ) N)Z_sessioninfor   )r   Zruntimer   r   r   _run_interface  s    zSpecifyModel._run_interfacec             C   s,   | j  j }t| ds| j  | j|d< |S )Nr   r   )_outputsgetr   r   r   )r   outputsr   r   r   _list_outputs  s
    

zSpecifyModel._list_outputs)NNN)N)r}   r~   r   __doc__rt   
input_specr   output_specr   r   r   r   r   r   r   r   r   2  s   ?
b
-r   c               @   s.   e Zd ZejddddZejdddddZdS )	SpecifySPMModelInputSpecFTz3Concatenate all runs to look like a single session.)r{   rx   r9   r8   z:Units of design event onsets and durations (secs or scans)N)r}   r~   r   r   Boolconcatenate_runsr   r@   r   r   r   r   r     s   r   c                   s.   e Zd ZdZeZdd Zd fdd	Z  ZS )SpecifySPMModela  Add SPM specific options to SpecifyModel

    Adds:

       - concatenate_runs
       - output_units

    Examples
    --------
    >>> from nipype.algorithms import modelgen
    >>> from nipype.interfaces.base import Bunch
    >>> s = modelgen.SpecifySPMModel()
    >>> s.inputs.input_units = 'secs'
    >>> s.inputs.output_units = 'scans'
    >>> s.inputs.high_pass_filter_cutoff = 128.
    >>> s.inputs.functional_runs = ['functional2.nii', 'functional3.nii']
    >>> s.inputs.time_repetition = 6
    >>> s.inputs.concatenate_runs = True
    >>> evs_run2 = Bunch(conditions=['cond1'], onsets=[[2, 50, 100, 180]], durations=[[1]])
    >>> evs_run3 = Bunch(conditions=['cond1'], onsets=[[30, 40, 100, 150]], durations=[[1]])
    >>> s.inputs.subject_info = [evs_run2, evs_run3]

    c          
   C   s  g }xbt | jjD ]R\}}t|tr.t|}n*t|ttfrPt|}|j	d }nt
d|j|| qW |d }xbt |d jD ]P\}}	t|d j| dkrt|	dkr|d j| t|d j|  |j|< qW xt |dd  D ]\}}
|
jrxt |
jD ]\}}	| jjdkr^tj|
j| | jjt|d|d    }|j| j|j  n8tj|
j| t|d|d   }|j| j|j  qW xt |
jD ]\}}	t|
j| dkrt|	dkr|j| j|
j| t|
j|   nHt|
j| t|	kr(|j| j|
j|  ntdj|d |d qW t|
dr|
jrx.t |
jD ] \}}	|j| j|
j|  qfW t|
d	r|
jrxNt |
jD ]@\}}	|	rx.t |	jD ] \}}|j| j| j| qW qW t|
d
r2|
jr2x.t |
jD ] \}}|j| j|
j|  qW t|d
 sJ|j rPg |_tjdt|f}d|dt|d| t|d|d  f< |jjt|j|j d  qW |g|fS )Nr#   z(Functional input not specified correctlyr   r   r9   zMismatch in number of onsets and                                           durations for run {0}, condition                                           {1}r   rQ   r   r   )ri   r   r   
isinstancelistr'   strbytesr   rn   	Exceptionr   rP   rO   r?   r   r%   rA   r*   extendr5   
ValueErrorformatr   rQ   r   r   r   r   )r   r   nscansrL   re   r   imginfooutr   r   rc   rO   keydatarH   Zonelistr   r   r   _concatenate_info>  sd    

"
$"
", z!SpecifySPMModel._concatenate_infoNc                s  t | jj s| jj r.tt| j|d d S t | jjrD| jj}nt| jj}| j	|\}}t
| jjg}g }t | jjrg }xT| jjD ]H}tjtdtj|| jjd}|s|jd| qtj|d |f|d< qW g }t | jjrg g}xt| jjD ]\}	}
ytj|
}W n, tk
r>   tjd|
 tjg }Y nX |jdkrtjd|
|t|d|	  |jtt|d|	  }|jdkr|d  tj|tdj g7  < q|d  tj|tdj 7  < qW | j ||||d| _!d S )	N)r   r   )r   r   r   r   r   zError reading outliers file %szfname=%s, out=%s, nscans=%d)r   )r   r   r   )"r   r   r   superr   r   ru   rs   rp   r   r   r   r   r   r   r   rm   r   r   concatenater   ri   r   r   r   r%   r   debugr*   Zastyper)   r5   r   r   )r   r   Z
concatlistr   r   r   r   r   r   rL   r   r   Zsumscans)	__class__r   r   r     sV    


""z SpecifySPMModel._generate_design)N)	r}   r~   r   r   r   r   r   r   __classcell__r   r   )r   r   r   #  s   Kr   c               @   s   e Zd ZejddddZejddddZejdd	Z	ejdd
ddZ
ejdgddZejddddZejddddZejdd	ZdS )SpecifySparseModelInputSpecr   Tz0Time in seconds to acquire a single image volume)rv   rx   r   z#Number of scan volumes in a cluster)r{   rx   zModel sparse events with hrf)rx   z&Treat each stimulus to be impulse-like)rx   r{   	model_hrfz=Create a temporal derivative in addition to regular regressor)requiresrx   zScale regressors by the peakg        z2Start of scanning relative to onset of run in secsz<Save plot of sparse design calculation (requires matplotlib)N)r}   r~   r   r   r   time_acquisitionZRangevolumes_in_clusterr   r   stimuli_as_impulsesuse_temporal_derivscale_regressors
scan_onset	save_plotr   r   r   r   r     s    r   c               @   s    e Zd ZeddZeddZdS )SpecifySparseModelOutputSpeczPNG file showing sparse design)rx   zSVG file showing sparse designN)r}   r~   r   r	   sparse_png_filesparse_svg_filer   r   r   r   r     s   
r   c                   sJ   e Zd ZdZeZeZdd Zdd Z	dd Z
d fd	d
	Zdd Z  ZS )SpecifySparseModela-  Specify a sparse model that is compatible with SPM/FSL designers [1]_.

    Examples
    --------
    >>> from nipype.algorithms import modelgen
    >>> from nipype.interfaces.base import Bunch
    >>> s = modelgen.SpecifySparseModel()
    >>> s.inputs.input_units = 'secs'
    >>> s.inputs.functional_runs = ['functional2.nii', 'functional3.nii']
    >>> s.inputs.time_repetition = 6
    >>> s.inputs.time_acquisition = 2
    >>> s.inputs.high_pass_filter_cutoff = 128.
    >>> s.inputs.model_hrf = True
    >>> evs_run2 = Bunch(conditions=['cond1'], onsets=[[2, 50, 100, 180]],
    ...                  durations=[[1]])
    >>> evs_run3 = Bunch(conditions=['cond1'], onsets=[[30, 40, 100, 150]],
    ...                  durations=[[1]])
    >>> s.inputs.subject_info = [evs_run2, evs_run3]  # doctest: +SKIP

    References
    ----------
    .. [1] Perrachione TK and Ghosh SS (2013) Optimized design and analysis of
       sparse-sampling fMRI experiments. Front. Neurosci. 7:55
       http://journal.frontiersin.org/Journal/10.3389/fnins.2013.00055/abstract

    c       $      C   s  d}t | jjr@| jjr@d}ddl}|jtjdd ddlj}t	t
j| jjd }| jjrvt	t
j| jjd }	n|}	| jj}
t
j| jjd }|||
  |
 |	|
  | }||	|
  }|	d }t
jt
j|d }t|d	kr|t
jt| }t
jt
j|d }tj|	tj||}||k rJ|| dkrJttj|t	|}|d	k r\td
tjd| t	t
j|| }t
jd||d }t
j|}t
j|}t | jjr| jjrt|d }d}| jjrzt
jt	d| }| jjrd|t	d| < t|	| }nd|t	d| t	d| < t | jjrn| jjrnt
j ||}d|j!  }tjd|j" |j!  tjd| xt#|D ]\}}t	t
j|| }|rt|d	kr|| ||< n|d ||< nd	||< |r|j$dd	d	 |j%|| | jjsH|| dkr|	|
 ||< t
jt	|| | }t
j ||dt| }||7 }d|dd< qW |r|j$dd	d |j%|| t | jjr| jjrt
j ||dt| }t | jj&r| jj&rt
j'dgt
j(|f}|r$|j$dd	d |j%|| t | jj&r$| jj&r$|j%|| t
j|}g }g } xt#t
j||
 D ]\}}!t	||!|  ||
 |	  | }"|"t
jt	|	|  }#t
j!|||#< |j)|t
j*||# |  t | jj&rJ| jj&rJ| j)|t
j*||# |  qJW t | jj&r| jj&rtjd t+|| } |rp|j$dd	d |j%|| |j$dd	d |j,t
jt||dd |j-d |j-d | r~|| gS |S dS )z?Generates a regressor for a sparse/clustered-sparse acquisitionFTr   NZ	executionZmatplotlib_backendi  g      $@r   zTime multiple less than 1 mszSetting dt = %d ms
gMbP?g      ?g      I@g     @@g       @zresponse sum: %.4f max: %.4fzreg_scale: %.4fr$   r   r#   z/orthoganlizing derivative w.r.t. main regressorg      ?)widthz
sparse.pngz
sparse.svgg     j@g     @@g     @@g     @@).r   r   r   
matplotlibZuser   r   Zmatplotlib.pyplotZpyplotr)   r   rU   rA   r   r   r   r%   r'   Zonesr^   gcdr&   r   r   rc   r_   r(   r   r   r1   r   r   Zconvolver:   r*   ri   ZsubplotZplotr   r   Zdiffr   Zmeanr7   barZsavefig)$r   Zi_onsetsZi_durationsZi_amplitudesr   Zbplotr   ZpltZTRZTAnvolZ	SCANONSETZ
total_timeZSILENCEr-   rP   rO   ZdttempZnptstimesZtimelineZ	timeline2r/   Z	reg_scaleZboxcarresponserL   r<   r0   ZstimdurZ	timederivregZregderivZtrialZ	scanstartZscanidxr   r   r   _gen_regress  s    










 
 



zSpecifySparseModel._gen_regressc             C   sz  g }g }xt |jD ]\}}t|dr8|jr8|j| }nd}|jt|| t|j| | jj	d| jj
}t|j| | jj	d| jj
}	| j||	||}
t| jjr| jjr|jt||
d  |jt||d  |jt||
d  q|jt||
 qW | jj}|dkrrxdt|d D ]T}tj|| |f}d|dd|f< |jt||j j  |jt|d|  qW ||fS )z1Converts condition information to full regressorsrQ   Nr9   r   Z_Dr   zT1effect_%d)ri   rN   r   rQ   r   r'   rB   rO   r   r?   rA   rP   r   r   r   r   r   r   r   Zravelr5   )r   rc   r   r   regnamesrL   r   rQ   Zscaled_onsetsZscaled_durationsZ	regressorr   Ztregr   r   r   _cond_to_regress  sB    


z#SpecifySparseModel._cond_to_regressc             C   s  t |}x
t|D  ]\}}d|| _d|| _d|| _|jrt| jj| }|jd }| j	||\}}t
|| dr|| jr|| jsdd tt|| jD || _ng || _g || _xJt|D ]>\}	}
t|| j}|| jj|||	  || jj||
 qW qW |S )zOGenerates condition information for sparse-clustered
        designs.

        Nr#   r   c             S   s   g | ]}d | qS )zR%dr   )r;   r   r   r   r   r>     s    zASpecifySparseModel._generate_clustered_design.<locals>.<listcomp>)r   ri   rN   rO   rP   r   r   r   rn   r   r   r   r   r   r'   r   )r   r   r   rL   rc   r   r   r   r   r   r   Zregidxr   r   r   _generate_clustered_design  s&    




$

z-SpecifySparseModel._generate_clustered_designNc                sB   t | jjr| jj}nt| jj}| j|}tt| j|d d S )N)r   )	r   r   ru   rs   rp   r   r   r   r   )r   r   Z
sparselist)r   r   r   r     s
    

z#SpecifySparseModel._generate_designc             C   sl   | j  j }t| ds| j  | j|d< t| jjrh| jjrhtj	j
tj d|d< tj	j
tj d|d< |S )Nr   r   z
sparse.pngr   z
sparse.svgr   )r   r   r   r   r   r   r   r   rj   rk   joingetcwd)r   r   r   r   r   r     s    

z SpecifySparseModel._list_outputs)N)r}   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )r   r   r     s    -r   )Nr   )rC   NF))r   copyr   rY   r^   rj   Znibabelr   numpyr   Zinterfaces.baser   r   r   r   r	   r
   r   r   Zutils.filemanipr   Z
utils.miscr   rC   r   r   	getLoggerr   r1   r7   rB   rh   rs   rt   r   r   r   r   r   r   r   r   r   r   r   <module>	   s0   (


<
6R d "