cosanlab / nltools

Python toolbox for analyzing imaging data
https://nltools.org
MIT License
120 stars 42 forks source link

make file_reader.onsets_to_dm compatible with BIDS events files #344

Open ljchang opened 4 years ago

ljchang commented 4 years ago

@ejolly It would be great if onsets_to_dm could automatically import a BIDS event file and create a design_matrix. It seems like it should be pretty straightforward to autodetect and read the condition names.

Here is an example events file from Pinel localizer task.

We just need to automatically find TR layout.get_tr() and run length from the functional run.

ljchang commented 4 years ago

Not sure the best way to do this, we could just make a bids_importer function for the file_reader module.

Here's a hacky 1st pass:

import nibabel as nib

def load_bids_events(layout, subject):
    '''Create a design_matrix instance from BIDS event file'''

    tr = layout.get_tr()
    n_tr = nib.load(layout.get(subject=subject, scope='raw', suffix='bold')[0].path).shape[-1]

    onsets = pd.read_csv(layout.get(subject=subject, suffix='events')[0].path, sep='\t')
    onsets.columns = ['Onset', 'Duration', 'Stim']
    return onsets_to_dm(onsets, sampling_freq=1/tr, run_length=n_tr)

dm = load_bids_events(layout, 'S01')

We will definitely want this to be more flexible. For sure we will want to be able to read multiple runs, potentially covariate files in derivatives, and possibly multiple subjects as a list.