Introduction to Neuroimaging Data#
In this tutorial we will learn the basics of the organization of data folders, and how to load, plot, and manipulate neuroimaging data in Python.
To introduce the basics of fMRI data structures, watch this short video by Martin Lindquist.
from IPython.display import YouTubeVideo
YouTubeVideo('OuRdQJMU5ro')
Software Packages#
There are many different software packages to analyze neuroimaging data. Most of them are open source and free to use (with the exception of BrainVoyager). The most popular ones (SPM, FSL, & AFNI) have been around a long time and are where many new methods are developed and distributed. These packages have focused on implementing what they believe are the best statistical methods, ease of use, and computational efficiency. They have very large user bases so many bugs have been identified and fixed over the years. There are also lots of publicly available documentation, listserves, and online tutorials, which makes it very easy to get started using these tools.
There are also many more boutique packages that focus on specific types of preprocessing step and analyses such as spatial normalization with ANTs, connectivity analyses with the conn-toolbox, representational similarity analyses with the rsaToolbox, and prediction/classification with pyMVPA.
Many packages have been developed within proprietary software such as Matlab (e.g., SPM, Conn, RSAToolbox, etc). Unfortunately, this requires that your university has site license for Matlab and many individual add-on toolboxes. If you are not affiliated with a University, you may have to pay for Matlab, which can be fairly expensive. There are free alternatives such as octave, but octave does not include many of the add-on toolboxes offered by matlab that may be required for a specific package. Because of this restrictive licensing, it is difficult to run matlab on cloud computing servers and to use with free online courses such as dartbrains. Other packages have been written in C/C++/C# and need to be compiled to run on your specific computer and operating system. While these tools are typically highly computationally efficient, it can sometimes be challenging to get them to install and work on specific computers and operating systems.
There has been a growing trend to adopt the open source Python framework in the data science and scientific computing communities, which has lead to an explosion in the number of new packages available for statistics, visualization, machine learning, and web development. pyMVPA was an early leader in this trend, and there are many great tools that are being actively developed such as nilearn, brainiak, neurosynth, nipype, fmriprep, and many more. One exciting thing is that these newer developments have built on the expertise of decades of experience with imaging analyses, and leverage changes in high performance computing. There is also a very tight integration with many cutting edge developments in adjacent communities such as machine learning with scikit-learn, tensorflow, and pytorch, which has made new types of analyses much more accessible to the neuroimaging community. There has also been an influx of younger contributors with software development expertise. You might be surprised to know that many of the popular tools being used had core contributors originating from the neuroimaging community (e.g., scikit-learn, seaborn, and many more).
For this course, I have chosen to focus on tools developed in Python as it is an easy to learn programming language, has excellent tools, works well on distributed computing systems, has great ways to disseminate information (e.g., jupyter notebooks, jupyter-book, etc), and is free! If you are just getting started, I would spend some time working with NiLearn and Brainiak, which have a lot of functionality, are very well tested, are reasonably computationally efficient, and most importantly have lots of documentation and tutorials to get started.
We will be using many packages throughout the course such as PyBids to navigate neuroimaging datasets, fmriprep to perform preprocessing, and nltools, which is a package developed in my lab, to do basic data manipulation and analysis. NLtools is built using many other toolboxes such as nibabel and nilearn, and we will also be using these frequently throughout the course.
BIDS: Brain Imaging Dataset Specification#
Recently, there has been growing interest to share datasets across labs and even on public repositories such as openneuro. In order to make this a successful enterprise, it is necessary to have some standards in how the data are named and organized. Historically, each lab has used their own idiosyncratic conventions, which can make it difficult for outsiders to analyze. In the past few years, there have been heroic efforts by the neuroimaging community to create a standardized file organization and naming practices. This specification is called BIDS for Brain Imaging Dataset Specification.
As you can imagine, individuals have their own distinct method of organizing their files. Think about how you keep track of your files on your personal laptop (versus your friend). This may be okay in the personal realm, but in science, it’s best if anyone (especially yourself 6 months from now!) can follow your work and know which files mean what by their titles.
Here’s an example of non-Bids versus BIDS dataset found in this paper:
Here are a few major differences between the two datasets:
In BIDS, files are in nifti format (not dicoms).
In BIDS, scans are broken up into separate folders by type of scan(functional versus anatomical versus diffusion weighted) for each subject.
In BIDS, JSON files are included that contain descriptive information about the scans (e.g., acquisition parameters)
Not only can using this specification be useful within labs to have a set way of structuring data, but it can also be useful when collaborating across labs, developing and utilizing software, and publishing data.
In addition, because this is a consistent format, it is possible to have a python package to make it easy to query a dataset. We recommend using pybids.
The dataset we will be working with has already been converted to the BIDS format (see download localizer tutorial).
You may need to install pybids to query the BIDS datasets using following command !pip install pybids
.
The BIDSLayout
#
Pybids is a package to help query and navigate a neuroimaging dataset that is in the BIDs format. At the core of pybids is the BIDSLayout
object. A BIDSLayout
is a lightweight Python class that represents a BIDS project file tree and provides a variety of helpful methods for querying and manipulating BIDS files. While the BIDSLayout initializer has a large number of arguments you can use to control the way files are indexed and accessed, you will most commonly initialize a BIDSLayout by passing in the BIDS dataset root location as a single argument.
Notice we are setting derivatives=True
. This means the layout will also index the derivatives sub folder, which might contain preprocessed data, analyses, or other user generated files.
from bids import BIDSLayout, BIDSValidator
import os
data_dir = '../data/localizer'
layout = BIDSLayout(data_dir, derivatives=True)
layout
BIDS Layout: ...thub/dartbrains/data/localizer | Subjects: 2 | Sessions: 0 | Runs: 0
When we initialize a BIDSLayout, all of the files and metadata found under the specified root folder are indexed. This can take a few seconds (or, for very large datasets, a minute or two). Once initialization is complete, we can start querying the BIDSLayout in various ways. The main query method is .get()
. If we call .get()
with no additional arguments, we get back a list of all the BIDS files in our dataset.
Let’s return the first 10 files
layout.get()[:10]
[<BIDSJSONFile filename='/Users/lukechang/Github/dartbrains/data/localizer/dataset_description.json'>,
<BIDSFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/.DS_Store'>,
<BIDSJSONFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/dataset_description.json'>,
<BIDSFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/logs/CITATION.bib'>,
<BIDSFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/logs/CITATION.html'>,
<BIDSFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/logs/CITATION.md'>,
<BIDSFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/logs/CITATION.tex'>,
<BIDSFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/sub-S01.html'>,
<BIDSFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/sub-S01/.DS_Store'>,
<BIDSJSONFile filename='/Users/lukechang/Github/dartbrains/data/localizer/derivatives/fmriprep/sub-S01/anat/sub-S01_desc-brain_mask.json'>]
As you can see, just a generic .get()
call gives us all of the files. We will definitely want to be a bit more specific. We can specify the type of data we would like to query. For example, suppose we want to return the first 10 subject ids.
layout.get(target='subject', return_type='id', scope='derivatives')[:10]
['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10']
Or perhaps, we would like to get the file names for the raw bold functional nifti images for the first 10 subjects. We can filter files in the raw
or derivatives
, using scope
keyword.scope='raw'
, to only query raw bold nifti files.
layout.get(target='subject', scope='raw', suffix='bold', return_type='file')[:10]
['/Users/lukechang/Github/dartbrains/data/localizer/sub-S01/func/sub-S01_task-localizer_bold.nii.gz',
'/Users/lukechang/Github/dartbrains/data/localizer/sub-S02/func/sub-S02_task-localizer_bold.nii.gz',
'/Users/lukechang/Github/dartbrains/data/localizer/task-localizer_bold.json']
When you call .get() on a BIDSLayout, the default returned values are objects of class BIDSFile. A BIDSFile is a lightweight container for individual files in a BIDS dataset.
Here are some of the attributes and methods available to us in a BIDSFile (note that some of these are only available for certain subclasses of BIDSFile; e.g., you can’t call get_image() on a BIDSFile that doesn’t correspond to an image file!):
.path: The full path of the associated file
.filename: The associated file’s filename (without directory)
.dirname: The directory containing the file
.get_entities(): Returns information about entities associated with this BIDSFile (optionally including metadata)
.get_image(): Returns the file contents as a nibabel image (only works for image files)
.get_df(): Get file contents as a pandas DataFrame (only works for TSV files)
.get_metadata(): Returns a dictionary of all metadata found in associated JSON files
.get_associations(): Returns a list of all files associated with this one in some way
Let’s explore the first file in a little more detail.
f = layout.get()[0]
f
<BIDSJSONFile filename='/Users/lukechang/Github/dartbrains/data/localizer/dataset_description.json'>
If we wanted to get the path of the file, we can use .path
.
f.path
'/Users/lukechang/Github/dartbrains/data/localizer/dataset_description.json'
Suppose we were interested in getting a list of tasks included in the dataset.
layout.get_task()
['localizer']
It looks like there is only one task associated with this dataset called localizer. Look at the Download Data page for more information about this task. We can query all of the files associated with this task. Let’s look at the first 10.
layout.get(task='localizer', suffix='bold', scope='raw')[:10]
[<BIDSImageFile filename='/Users/lukechang/Github/dartbrains/data/localizer/sub-S01/func/sub-S01_task-localizer_bold.nii.gz'>,
<BIDSImageFile filename='/Users/lukechang/Github/dartbrains/data/localizer/sub-S02/func/sub-S02_task-localizer_bold.nii.gz'>,
<BIDSJSONFile filename='/Users/lukechang/Github/dartbrains/data/localizer/task-localizer_bold.json'>]
Notice that there are nifti and event files. We can get the filename for the first particant’s functional run
f = layout.get(task='localizer')[0].filename
f
'sub-S01_task-localizer_desc-carpetplot_bold.svg'
If you want a summary of all the files in your BIDSLayout, but don’t want to have to iterate BIDSFile objects and extract their entities, you can get a nice bird’s-eye view of your dataset using the to_df()
method.
layout.to_df()
entity | path | datatype | extension | subject | suffix | task |
---|---|---|---|---|---|---|
0 | /Users/lukechang/Github/dartbrains/data/locali... | NaN | json | NaN | description | NaN |
1 | /Users/lukechang/Github/dartbrains/data/locali... | NaN | json | NaN | participants | NaN |
2 | /Users/lukechang/Github/dartbrains/data/locali... | NaN | tsv | NaN | participants | NaN |
3 | /Users/lukechang/Github/dartbrains/data/locali... | anat | nii.gz | S01 | T1w | NaN |
4 | /Users/lukechang/Github/dartbrains/data/locali... | func | nii.gz | S01 | bold | localizer |
... | ... | ... | ... | ... | ... | ... |
677 | /Users/lukechang/Github/dartbrains/data/locali... | NaN | NaN | NaN | NaN | NaN |
678 | /Users/lukechang/Github/dartbrains/data/locali... | NaN | NaN | NaN | NaN | NaN |
679 | /Users/lukechang/Github/dartbrains/data/locali... | NaN | NaN | NaN | NaN | NaN |
680 | /Users/lukechang/Github/dartbrains/data/locali... | NaN | NaN | NaN | NaN | NaN |
681 | /Users/lukechang/Github/dartbrains/data/locali... | NaN | NaN | NaN | NaN | NaN |
682 rows × 6 columns
Loading Data with Nibabel#
Neuroimaging data is often stored in the format of nifti files .nii
which can also be compressed using gzip .nii.gz
. These files store both 3D and 4D data and also contain structured metadata in the image header.
There is a very nice tool to access nifti data stored on your file system in python called nibabel. If you don’t already have nibabel installed on your computer it is easy via pip
. First, tell the jupyter cell that you would like to access the unix system outside of the notebook and then install nibabel using pip !pip install nibabel
. You only need to run this once (unless you would like to update the version).
nibabel objects can be initialized by simply pointing to a nifti file even if it is compressed through gzip. First, we will import the nibabel module as nib
(short and sweet so that we don’t have to type so much when using the tool). I’m also including a path to where the data file is located so that I don’t have to constantly type this. It is easy to change this on your own computer.
We will be loading an anatomical image from subject S01 from the localizer dataset. See this paper for more information about this dataset.
We will use pybids to grab subject S01’s T1 image.
import nibabel as nib
data = nib.load(layout.get(subject='S01', scope='derivatives', suffix='T1w', return_type='file', extension='nii.gz')[1])
If we want to get more help on how to work with the nibabel data object we can either consult the documentation or add a ?
.
data?
The imaging data is stored in either a 3D or 4D numpy array. Just like numpy, it is easy to get the dimensions of the data using shape
.
data.shape
(193, 229, 193)
Looks like there are 3 dimensions (x,y,z) that is the number of voxels in each dimension. If we know the voxel size, we could convert this into millimeters.
We can also directly access the data and plot a single slice using standard matplotlib functions.
%matplotlib inline
import matplotlib.pyplot as plt
plt.imshow(data.get_fdata()[:,:,50])
<matplotlib.image.AxesImage at 0x7fad486d8e90>
Try slicing different dimensions (x,y,z) yourself to get a feel for how the data is represented in this anatomical image.
We can also access data from the image header. Let’s assign the header of an image to a variable and print it to view it’s contents.
header = data.header
print(header)
<class 'nibabel.nifti1.Nifti1Header'> object, endian='<'
sizeof_hdr : 348
data_type : b''
db_name : b''
extents : 0
session_error : 0
regular : b'r'
dim_info : 0
dim : [ 3 193 229 193 1 1 1 1]
intent_p1 : 0.0
intent_p2 : 0.0
intent_p3 : 0.0
intent_code : none
datatype : float32
bitpix : 32
slice_start : 0
pixdim : [1. 1. 1. 1. 0. 0. 0. 0.]
vox_offset : 0.0
scl_slope : nan
scl_inter : nan
slice_end : 0
slice_code : unknown
xyzt_units : 2
cal_max : 0.0
cal_min : 0.0
slice_duration : 0.0
toffset : 0.0
glmax : 0
glmin : 0
descrip : b'xform matrices modified by FixHeaderApplyTransforms (niworkflows v1.1.12).'
aux_file : b''
qform_code : mni
sform_code : mni
quatern_b : 0.0
quatern_c : 0.0
quatern_d : 0.0
qoffset_x : -96.0
qoffset_y : -132.0
qoffset_z : -78.0
srow_x : [ 1. 0. 0. -96.]
srow_y : [ 0. 1. 0. -132.]
srow_z : [ 0. 0. 1. -78.]
intent_name : b''
magic : b'n+1'
Some of the important information in the header is information about the orientation of the image in space. This can be represented as the affine matrix, which can be used to transform images between different spaces.
data.affine
array([[ 1., 0., 0., -96.],
[ 0., 1., 0., -132.],
[ 0., 0., 1., -78.],
[ 0., 0., 0., 1.]])
We will dive deeper into affine transformations in the preprocessing tutorial.
Plotting Data with Nilearn#
There are many useful tools from the nilearn library to help manipulate and visualize neuroimaging data. See their documentation for an example.
In this section, we will explore a few of their different plotting functions, which can work directly with nibabel instances.
%matplotlib inline
from nilearn.plotting import view_img, plot_glass_brain, plot_anat, plot_epi
plot_anat(data)
<nilearn.plotting.displays.OrthoSlicer at 0x7fad5aeb0c10>
Nilearn plotting functions are very flexible and allow us to easily customize our plots
plot_anat(data, draw_cross=False, display_mode='z')
<nilearn.plotting.displays.ZSlicer at 0x7fad3114af10>
try to get more information how to use the function with ?
and try to add different commands to change the plot.
nilearn also has a neat interactive viewer called view_img
for examining images directly in the notebook.
view_img(data)
The view_img
function is particularly useful for overlaying statistical maps over an anatomical image so that we can interactively examine where the results are located.
As an example, let’s load a mask of the amygdala and try to find where it is located. We will download it from Neurovault using a function from nltools
.
from nltools.data import Brain_Data
amygdala_mask = Brain_Data('https://neurovault.org/media/images/1290/FSL_BAmyg_thr0.nii.gz').to_nifti()
view_img(amygdala_mask, data)
We can also plot a glass brain which allows us to see through the brain from different slice orientations. In this example, we will plot the binary amygdala mask.
plot_glass_brain(amygdala_mask)
<nilearn.plotting.displays.OrthoProjector at 0x7fad29aa88d0>
Manipulating Data with Nltools#
Ok, we’ve now learned how to use nibabel to load imaging data and nilearn to plot it.
Next we are going to learn how to use the nltools
package that tries to make loading, plotting, and manipulating data easier. It uses many functions from nibabel, nilearn, and other python libraries. The bulk of the nltools toolbox is built around the Brain_Data()
class. The concept behind the class is to have a similar feel to a pandas dataframe, which means that it should feel intuitive to manipulate the data.
The Brain_Data()
class has several attributes that may be helpful to know about. First, it stores imaging data in .data
as a vectorized features by observations matrix. Each image is an observation and each voxel is a feature. Space is flattened using nifti_masker
from nilearn. This object is also stored as an attribute in .nifti_masker
to allow transformations from 2D to 3D/4D matrices. In addition, a brain_mask is stored in .mask
. Finally, there are attributes to store either class labels for prediction/classification analyses in .Y
and design matrices in .X
. These are both expected to be pandas DataFrames
.
We will give a quick overview of basic Brain_Data operations, but we encourage you to see our documentation for more details.
Brain_Data basics#
To get a feel for Brain_Data
, let’s load an example anatomical overlay image that comes packaged with the toolbox.
from nltools.data import Brain_Data
from nltools.utils import get_anatomical
anat = Brain_Data(get_anatomical())
anat
nltools.data.brain_data.Brain_Data(data=(238955,), Y=0, X=(0, 0), mask=MNI152_T1_2mm_brain_mask.nii.gz, output_file=[])
To view the attributes of Brain_Data
use the vars()
function.
print(vars(anat))
{'mask': <nibabel.nifti1.Nifti1Image object at 0x7fad5cbd5d50>, 'nifti_masker': NiftiMasker(detrend=False, dtype=None, high_pass=None, low_pass=None,
mask_args=None,
mask_img=<nibabel.nifti1.Nifti1Image object at 0x7fad5cbd5d50>,
mask_strategy='background', memory=Memory(location=None),
memory_level=1, reports=True, sample_mask=None, sessions=None,
smoothing_fwhm=None, standardize=False, t_r=None,
target_affine=None, target_shape=None, verbose=0), 'data': array([1875., 2127., 2182., ..., 5170., 5180., 2836.], dtype=float32), 'Y': Empty DataFrame
Columns: []
Index: [], 'X': Empty DataFrame
Columns: []
Index: [], 'file_name': []}
Brain_Data
has many methods to help manipulate, plot, and analyze imaging data. We can use the dir()
function to get a quick list of all of the available methods that can be used on this class.
To learn more about how to use these tools either use the ?
function, or look up the function in the api documentation.
print(dir(anat))
['X', 'Y', '__add__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__rsub__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__weakref__', 'aggregate', 'align', 'append', 'apply_mask', 'astype', 'bootstrap', 'copy', 'data', 'decompose', 'detrend', 'distance', 'dtype', 'empty', 'extract_roi', 'file_name', 'filter', 'find_spikes', 'groupby', 'icc', 'iplot', 'isempty', 'mask', 'mean', 'median', 'multivariate_similarity', 'nifti_masker', 'plot', 'predict', 'predict_multi', 'r_to_z', 'randomise', 'regions', 'regress', 'scale', 'shape', 'similarity', 'smooth', 'standardize', 'std', 'sum', 'temporal_resample', 'threshold', 'to_nifti', 'transform_pairwise', 'ttest', 'upload_neurovault', 'write']
Ok, now let’s load a single subject’s functional data from the localizer dataset. We will load one that has already been preprocessed with fmriprep and is stored in the derivatives folder.
Loading data can be a little bit slow especially if the data need to be resampled to the template, which is set at \(2mm^3\) by default. However, once it’s loaded into the workspace it should be relatively fast to work with it.
sub = 'sub-S01'
data = Brain_Data(os.path.join(data_dir, 'derivatives', 'fmriprep', sub, 'func', f'{sub}_task-localizer_space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz'))
Here are a few quick basic data operations.
Find number of images in Brain_Data() instance
print(len(data))
128
Find the dimensions of the data (images x voxels)
print(data.shape())
(128, 238955)
We can use any type of indexing to slice the data such as integers, lists of integers, slices, or boolean vectors.
import numpy as np
print(data[5].shape())
print(data[[1,6,2]].shape())
print(data[0:10].shape())
index = np.zeros(len(data), dtype=bool)
index[[1,5,9, 16, 20, 22]] = True
print(data[index].shape())
(238955,)
(3, 238955)
(10, 238955)
(6, 238955)
Simple Arithmetic Operations#
Calculate the mean for every voxel over images
data.mean()
nltools.data.brain_data.Brain_Data(data=(238955,), Y=0, X=(0, 0), mask=MNI152_T1_2mm_brain_mask.nii.gz, output_file=[])
Calculate the standard deviation for every voxel over images
data.std()
nltools.data.brain_data.Brain_Data(data=(238955,), Y=0, X=(0, 0), mask=MNI152_T1_2mm_brain_mask.nii.gz, output_file=[])
Methods can be chained. Here we get the shape of the mean.
print(data.mean().shape())
(238955,)
Brain_Data instances can be added and subtracted
new = data[1]+data[2]
Brain_Data instances can be manipulated with basic arithmetic operations.
Here we add 10 to every voxel and scale by 2
data2 = (data + 10) * 2
Brain_Data instances can be copied
new = data.copy()
Brain_Data instances can be easily converted to nibabel instances, which store the data in a 3D/4D matrix. This is useful for interfacing with other python toolboxes such as nilearn
data.to_nifti()
<nibabel.nifti1.Nifti1Image at 0x7fad69f43d90>
Brain_Data instances can be concatenated using the append method
new = new.append(data[4])
Lists of Brain_Data
instances can also be concatenated by recasting as a Brain_Data
object.
print(type([x for x in data[:4]]))
type(Brain_Data([x for x in data[:4]]))
<class 'list'>
nltools.data.brain_data.Brain_Data
Any Brain_Data object can be written out to a nifti file.
data.write('Tmp_Data.nii.gz')
Images within a Brain_Data() instance are iterable. Here we use a list comprehension to calculate the overall mean across all voxels within an image.
[x.mean() for x in data]
[3632.536,
3639.0662,
3636.0562,
3631.1252,
3627.1565,
3631.0986,
3648.3137,
3657.7656,
3654.2615,
3658.1348,
3652.4163,
3647.3025,
3648.4019,
3651.63,
3648.55,
3648.7566,
3654.2322,
3655.227,
3650.0222,
3644.6763,
3645.765,
3645.0671,
3633.773,
3635.367,
3634.0962,
3637.7722,
3636.5322,
3643.0576,
3643.034,
3635.3635,
3644.4868,
3659.792,
3650.5303,
3642.4023,
3644.5435,
3638.261,
3638.7898,
3645.6985,
3641.1465,
3632.2185,
3624.994,
3628.2786,
3626.063,
3623.819,
3636.2058,
3628.5884,
3629.2664,
3622.4158,
3617.2485,
3609.94,
3620.9905,
3626.5645,
3631.9675,
3629.276,
3631.3801,
3625.395,
3621.5083,
3620.3164,
3625.705,
3626.373,
3623.368,
3630.5776,
3630.8086,
3626.8877,
3622.8083,
3618.6865,
3617.2358,
3615.7021,
3618.1902,
3622.9312,
3618.4065,
3611.3342,
3613.9846,
3630.378,
3630.0913,
3622.9004,
3613.8503,
3614.9832,
3622.9844,
3622.4487,
3619.9285,
3612.1162,
3614.8423,
3608.7314,
3614.767,
3609.9822,
3606.2117,
3602.921,
3602.1326,
3601.9211,
3611.0999,
3619.5076,
3616.9973,
3613.6519,
3607.4512,
3624.7017,
3628.3745,
3612.548,
3596.0322,
3581.2944,
3580.8047,
3584.3645,
3593.828,
3605.6892,
3608.284,
3622.2231,
3618.5674,
3613.901,
3607.047,
3598.3826,
3589.8098,
3588.8022,
3599.5337,
3603.5144,
3602.9685,
3611.66,
3611.8218,
3605.5686,
3593.0813,
3592.416,
3600.1592,
3612.8616,
3611.4583,
3619.375,
3613.787,
3599.9001,
3595.6265,
3597.0571]
Though, we could also do this with the mean
method by setting axis=1
.
data.mean(axis=1)
array([3632.536 , 3639.0662, 3636.0562, 3631.1252, 3627.1565, 3631.0986,
3648.3137, 3657.7656, 3654.2615, 3658.1348, 3652.4163, 3647.3025,
3648.4019, 3651.63 , 3648.55 , 3648.7566, 3654.2322, 3655.227 ,
3650.0222, 3644.6763, 3645.765 , 3645.0671, 3633.773 , 3635.367 ,
3634.0962, 3637.7722, 3636.5322, 3643.0576, 3643.034 , 3635.3635,
3644.4868, 3659.792 , 3650.5303, 3642.4023, 3644.5435, 3638.261 ,
3638.7898, 3645.6985, 3641.1465, 3632.2185, 3624.994 , 3628.2786,
3626.063 , 3623.819 , 3636.2058, 3628.5884, 3629.2664, 3622.4158,
3617.2485, 3609.94 , 3620.9905, 3626.5645, 3631.9675, 3629.276 ,
3631.3801, 3625.395 , 3621.5083, 3620.3164, 3625.705 , 3626.373 ,
3623.368 , 3630.5776, 3630.8086, 3626.8877, 3622.8083, 3618.6865,
3617.2358, 3615.7021, 3618.1902, 3622.9312, 3618.4065, 3611.3342,
3613.9846, 3630.378 , 3630.0913, 3622.9004, 3613.8503, 3614.9832,
3622.9844, 3622.4487, 3619.9285, 3612.1162, 3614.8423, 3608.7314,
3614.767 , 3609.9822, 3606.2117, 3602.921 , 3602.1326, 3601.9211,
3611.0999, 3619.5076, 3616.9973, 3613.6519, 3607.4512, 3624.7017,
3628.3745, 3612.548 , 3596.0322, 3581.2944, 3580.8047, 3584.3645,
3593.828 , 3605.6892, 3608.284 , 3622.2231, 3618.5674, 3613.901 ,
3607.047 , 3598.3826, 3589.8098, 3588.8022, 3599.5337, 3603.5144,
3602.9685, 3611.66 , 3611.8218, 3605.5686, 3593.0813, 3592.416 ,
3600.1592, 3612.8616, 3611.4583, 3619.375 , 3613.787 , 3599.9001,
3595.6265, 3597.0571], dtype=float32)
Let’s plot the mean to see how the global signal changes over time.
plt.plot(data.mean(axis=1))
[<matplotlib.lines.Line2D at 0x7fad6950e450>]
Notice the slow linear drift over time, where the global signal intensity gradually decreases. We will learn how to remove this with a high pass filter in future tutorials.
Plotting#
There are multiple ways to plot your data.
For a very quick plot, you can return a montage of axial slices with the .plot()
method. As an example, we will plot the mean of each voxel over time.
f = data.mean().plot()
There is an interactive .iplot()
method based on nilearn view_img
.
data.mean().iplot()
Brain_Data() instances can be converted to a nibabel instance and plotted using any nilearn plot method such as glass brain.
plot_glass_brain(data.mean().to_nifti())
<nilearn.plotting.displays.OrthoProjector at 0x7fad696d4890>
Ok, that’s the basics. Brain_Data
can do much more!
Check out some of our tutorials for more detailed examples.
We’ll be using this tool throughout the course.
Exercises#
For homework, let’s practice our skills in working with data.
Exercise 1#
A few subjects have already been preprocessed with fMRI prep.
Use pybids to figure out which subjects have been preprocessed.
Exercise 2#
One question we are often interested in is where in the brain do we have an adequate signal to noise ratio (SNR). There are many different metrics, here we will use temporal SNR, which the voxel mean over time divided by it’s standard deviation.
In Exercise 2, calculate the SNR for S01 and plot this so we can figure which regions have high and low SNR.
Exercise 3#
We are often interested in identifying outliers in our data. In this exercise, find any image that is outside 95% of all images based on global intensity (i.e., zscore greater than 2) from ‘S01’ and plot each one.