osl_ephys.source_recon.parcellation#

Functions to handle parcellation.

Functions#

load_parcellation_description(parcellation_file[, ...])

Load a parcellation description file.

load_parcellation(parcellation_file[, freesurfer, subject])

Load a parcellation file.

_find_package_file(filename)

_find_freesurfer_file(filename)

find_file(filename[, freesurfer])

Look for a parcellation file within the package.

guess_parcellation(data[, return_path])

Guess parcellation file from data.

vol_parcellate_timeseries(parcellation_file, ...)

Parcellate a voxel time series.

_get_parcel_timeseries(voxel_timeseries, ...[, method])

Calculate parcel timeseries.

surf_parcellate_timeseries(subject_dir, subject, stc, ...)

Save parcellated data as a fif file.

resample_parcellation(parcellation_file, voxel_coords)

Resample parcellation so that its voxel coords correspond (using nearest neighbour) to passed in voxel_coords.

local_orthogonalise(timeseries[, parcellation_file, ...])

Returns a local orthogonalisation of the timeseries, where the time series of local neighbours are regressed out with multiple linear regression.

symmetric_orthogonalise(timeseries[, ...])

Returns orthonormal matrix L which is closest to A, as measured by the Frobenius norm of (L-A). The orthogonal matrix is constructed from a singular

parcel_centers(parcellation_file[, freesurfer])

Get coordinates of parcel centers.

plot_parcellation(parcellation_file, **kwargs)

Plots a parcellation.

plot_psd(parc_ts, fs, parcellation_file, filename[, ...])

Plot PSD of each parcel time course.

plot_correlation(parc_ts, filename)

Plot correlation between parcel time courses.

_parcel_timeseries2nii(parcellation_file, ...[, ...])

Outputs parcel_timeseries_data as a niftii file using passed in parcellation.

convert2niftii(parc_data, parcellation_file, mask_file)

Convert parcellation to NIfTI.

convert2mne_raw(parc_data, raw[, parcel_names, ...])

Create and returns an MNE raw object that contains parcellated data.

convert2mne_epochs(parc_data, epochs[, parcel_names])

Create and returns an MNE Epochs object that contains parcellated data.

spatial_dist_adjacency(parcellation_file, dist[, verbose])

Compute adjacency from distances between parcels.

parcel_vector_to_voxel_grid(mask_file, ...[, freesurfer])

Takes a vector of parcel values and return a 3D voxel grid.

convert2source_estimate(subjects_dir, data[, parc, ...])

Convert parcellated data to a source estimate.

plot_source_topo(data_map[, parcellation_file, ...])

Plot a data map on a cortical surface. Wrapper for nilearn.plotting.plot_glass_brain.

Module Contents#

osl_ephys.source_recon.parcellation.load_parcellation_description(parcellation_file, freesurfer=False, subject=None)[source]#

Load a parcellation description file.

Parameters:
  • parcellation_file (str) – Path to parcellation file. Function will look for a xml file with same name but .xml extension.

  • freesurfer (bool, optional) – Is this a FreeSurfer parcellation?

  • subject (str) – Subject ID. Only needed for FreeSurfer parcellations.

Returns:

df – Dictionary with keys ‘index’, ‘label’, ‘x’, ‘y’, ‘z’ for each parcel.

Return type:

dict

osl_ephys.source_recon.parcellation.load_parcellation(parcellation_file, freesurfer=False, subject=None)[source]#

Load a parcellation file.

Parameters:
  • parcellation_file (str) – Path to parcellation file.

  • freesurfer (bool, optional) – Are we loading a FreeSurfer parcellation?

  • subject (str) – Subject ID. Only needed for FreeSurfer parcellations.

Returns:

parcellation – Parcellation.

Return type:

nibabel image or mne.Label

osl_ephys.source_recon.parcellation._find_package_file(filename)[source]#
osl_ephys.source_recon.parcellation._find_freesurfer_file(filename)[source]#
osl_ephys.source_recon.parcellation.find_file(filename, freesurfer=False)[source]#

Look for a parcellation file within the package.

Parameters:
  • filename (str) – Path to parcellation file to look for.

  • freesurfer (bool, optional) – Should we look in the freesurfer directory?

Returns:

filename – Path to parcellation file found.

Return type:

str

osl_ephys.source_recon.parcellation.guess_parcellation(data, return_path=False)[source]#

Guess parcellation file from data.

Parameters:
  • data (vector or matrix) – Data to guess parcellation from. first dimension is assumed to be parcels.

  • return_path (bool) – If True, return path to parcellation file, otherwise return filename.

Returns:

filename – Path to parcellation file.

Return type:

str

osl_ephys.source_recon.parcellation.vol_parcellate_timeseries(parcellation_file, voxel_timeseries, voxel_coords, method, working_dir)[source]#

Parcellate a voxel time series.

Parameters:
  • parcellation_file (str) – Parcellation file (or path to parcellation file).

  • voxel_timeseries (numpy.ndarray) – (nvoxels x ntpts) or (nvoxels x ntpts x ntrials) data to be parcellated. Data is assumed to be in same space as the parcellation (e.g. typically corresponds to the output from beamforming.transform_recon_timeseries).

  • voxel_coords (numpy.ndarray) – (nvoxels x 3) coordinates of voxel_timeseries in mm in same space as parcellation (e.g. typically corresponds to the output from beamforming.transform_recon_timeseries).

  • method (str) – 'pca' - take 1st PC in each parcel 'spatial_basis' - The parcel time-course for each spatial map is the 1st PC from all voxels, weighted by the spatial map. If the parcellation is unweighted and non-overlapping, ‘spatialBasis’ will give the same result as ‘PCA’ except with a different normalization.

  • working_dir (str) – Directory to put temporary file in. If None, attempt to use same directory as passed in parcellation.

Returns:

  • parcel_timeseries (numpy.ndarray) – nparcels x ntpts, or nparcels x ntpts x ntrials, parcellated data.

  • voxel_weightings (numpy.ndarray) – nvoxels x nparcels, Voxel weightings for each parcel, corresponds to parcel_data = voxel_weightings.T * voxel_data

  • voxel_assignments (bool numpy.ndarray) – nvoxels x nparcels, Boolean assignments indicating for each voxel the winner takes all parcel it belongs to.

osl_ephys.source_recon.parcellation._get_parcel_timeseries(voxel_timeseries, parcellation_asmatrix, method='spatial_basis')[source]#

Calculate parcel timeseries.

Parameters:
  • voxel_timeseries (numpy.ndarray) – (nvoxels x ntpts) or (nvoxels x ntpts x ntrials) and is assumed to be on the same grid as parcellation (typically output by beamforming.transform_recon_timeseries).

  • parcellation_asmatrix (numpy.ndarray) – (nvoxels x nparcels) and is assumed to be on the same grid as voxel_timeseries.

  • method (str) – 'pca' - take 1st PC of voxels 'spatial_basis' - The parcel time-course for each spatial map is the 1st PC from all voxels, weighted by the spatial map. If the parcellation is unweighted and non-overlapping, ‘spatialBasis’ will give the same result as ‘PCA’ except with a different normalization.

Returns:

  • parcel_timeseries (numpy.ndarray) – nparcels x ntpts, or nparcels x ntpts x ntrials

  • voxel_weightings (numpy.ndarray) – nvoxels x nparcels Voxel weightings for each parcel to compute parcel_timeseries from voxel_timeseries

  • voxel_assignments (bool numpy.ndarray) – nvoxels x nparcels Boolean assignments indicating for each voxel the winner takes all parcel it belongs to

osl_ephys.source_recon.parcellation.surf_parcellate_timeseries(subject_dir, subject, stc, method, parcellation_file)[source]#

Save parcellated data as a fif file.

Parameters:
  • subject_dir (str) – Path to subject directory.

  • subject (str) – Subject ID.

  • stc (mne.SourceEstimate) – Source estimate.

  • method (str) – Parcellation method. Can be ‘pca_flip’, ‘max’, ‘mean’, ‘mean_flip’, ‘auto’

  • parcellation_file (str) – Parcellation name.

osl_ephys.source_recon.parcellation.resample_parcellation(parcellation_file, voxel_coords, working_dir=None, freesurfer=False)[source]#

Resample parcellation so that its voxel coords correspond (using nearest neighbour) to passed in voxel_coords. Passed in voxel_coords and parcellation must be in the same space, e.g. MNI.

Used to make sure that the parcellation’s voxel coords are the same as the voxel coords for some timeseries data, before calling _get_parcel_timeseries.

Parameters:
  • parcellation_file (str) – Path to parcellation file. In same space as voxel_coords.

  • voxel_coords – (nvoxels x 3) coordinates in mm in same space as parcellation.

  • working_dir (str) – Dir to put temp file in. If None, attempt to use same dir as passed in parcellation.

  • freesurfer (bool) – If True, parcellation_file is a freesurfer parcellation. Otherwise, it is a nifti file.

Returns:

parcellation_asmatrix – (nvoxels x nparcels) resampled parcellation

Return type:

numpy.ndarray

osl_ephys.source_recon.parcellation.local_orthogonalise(timeseries, parcellation_file=None, dist=None, adjacency=None)[source]#

Returns a local orthogonalisation of the timeseries, where the time series of local neighbours are regressed out with multiple linear regression.

Parameters:
  • timeseries (numpy.ndarray) – (nparcels x ntpts) or (nparcels x ntpts x ntrials) data to orthoganlise. In the latter case, the ntpts and ntrials dimensions are concatenated.

  • parcellation_file (nifti parcellation file) – If None, adjacency must be provided.

  • dist (float) – Distance in mm to consider as neighbours. Must be provided together with parcellation file. If None, adjacency must be provided.

  • adjacency (numpy.ndarray) – nparcels x nparcels binary adjacency matrix.

Returns:

ortho_timeseries – (nparcels x ntpts) or (nparcels x ntpts x ntrials) orthoganalised data

Return type:

numpy.ndarray

osl_ephys.source_recon.parcellation.symmetric_orthogonalise(timeseries, maintain_magnitudes=False, compute_weights=False)[source]#

Returns orthonormal matrix L which is closest to A, as measured by the Frobenius norm of (L-A). The orthogonal matrix is constructed from a singular value decomposition of A.

If maintain_magnitudes is True, returns the orthogonal matrix L, whose columns have the same magnitude as the respective columns of A, and which is closest to A, as measured by the Frobenius norm of (L-A).

Parameters:
  • timeseries (numpy.ndarray) – (nparcels x ntpts) or (nparcels x ntpts x ntrials) data to orthoganlise. In the latter case, the ntpts and ntrials dimensions are concatenated.

  • maintain_magnitudes (bool) –

  • compute_weights (bool) –

Returns:

  • ortho_timeseries (numpy.ndarray) – (nparcels x ntpts) or (nparcels x ntpts x ntrials) orthoganalised data

  • weights (numpy.ndarray) – (optional output depending on compute_weights flag) weighting matrix such that, ortho_timeseries = timeseries * weights

References

Colclough, G. L., Brookes, M., Smith, S. M. and Woolrich, M. W., “A symmetric multivariate leakage correction for MEG connectomes,” NeuroImage 117, pp. 439-448 (2015)

osl_ephys.source_recon.parcellation.parcel_centers(parcellation_file, freesurfer=False)[source]#

Get coordinates of parcel centers.

Parameters:
  • parcellation_file (str) – Path to parcellation file.

  • freesurfer (bool) – Is the parcellation a FreeSurfer parcellation?

Returns:

coords – Coordinates of each parcel. Shape is (n_parcels, 3).

Return type:

np.ndarray

osl_ephys.source_recon.parcellation.plot_parcellation(parcellation_file, **kwargs)[source]#

Plots a parcellation.

Parameters:
  • parcellation_file (str) – Path to parcellation file.

  • kwargs (keyword arguments) – Keyword arguments to pass to nilearn.plotting.plot_markers.

osl_ephys.source_recon.parcellation.plot_psd(parc_ts, fs, parcellation_file, filename, freq_range=None, freesurfer=False)[source]#

Plot PSD of each parcel time course.

Parameters:
  • parc_ts (np.ndarray) – (parcels, time) or (parcels, time, epochs) time series.

  • fs (float) – Sampling frequency in Hz.

  • parcellation_file (str) – Path to parcellation file.

  • filename (str) – Output filename.

  • freq_range (list of len 2) – Low and high frequency in Hz.

  • freesurfer (bool) – Is the parcellation a FreeSurfer parcellation?

osl_ephys.source_recon.parcellation.plot_correlation(parc_ts, filename)[source]#

Plot correlation between parcel time courses.

Parameters:
  • parc_ts (np.ndarray) – (parcels, time) or (parcels, time, epochs) time series.

  • filename (str) – Output filename.

osl_ephys.source_recon.parcellation._parcel_timeseries2nii(parcellation_file, parcel_timeseries_data, voxel_weightings, voxel_assignments, voxel_coords, out_nii_fname=None, working_dir=None, times=None, method='assignments', freesurfer=False)[source]#

Outputs parcel_timeseries_data as a niftii file using passed in parcellation.

The parcellation and parcel_timeseries_data need to have the same number of parcels.

Parameters:
  • parcellation_file (str) – Path to parcellation file.

  • parcel_timeseries_data (numpy.ndarray) – Needs to be nparcels x ntpts

  • voxel_weightings (numpy.ndarray) – (nvoxels x nparcels) voxel weightings for each parcel to compute parcel_timeseries from voxel_timeseries.

  • voxel_assignments (bool numpy.ndarray) – (nvoxels x nparcels) boolean assignments indicating for each voxel the winner takes all parcel it belongs to.

  • voxel_coords (numpy.ndarray) – (nvoxels x 3) coordinates of voxel_timeseries in mm in same space as parcellation (e.g. typically corresponds to the output from beamforming.transform_recon_timeseries).

  • working_dir (str) – Directory name to put files in.

  • out_nii_fname (str) – Output name to put files in.

  • times (array) – (ntpts,) times points in seconds. Will assume that time points are regularly spaced. Used to set nii file up correctly.

  • method (str) – “weights” or “assignments”

  • freesurfer (bool) – If True, parcellation_file is a freesurfer parcellation. Otherwise, it is a nifti file.

Returns:

out_nii_fname – Output nii filename, will be output at spatial resolution of parcel_timeseries[‘voxel_coords’].

Return type:

str

osl_ephys.source_recon.parcellation.convert2niftii(parc_data, parcellation_file, mask_file, tres=1, tmin=0, freesurfer=False)[source]#

Convert parcellation to NIfTI.

Takes (nparcels) or (nvolumes x nparcels) parc_data and returns (xvoxels x yvoxels x zvoxels x nvolumes) niftii file containing parc_data on a volumetric grid.

Parameters:
  • parc_data (np.ndarray) – (nparcels) or (nvolumes x nparcels) parcel data.

  • parcellation_file (str) – Path to niftii parcellation file.

  • mask_file (str) – Path to niftii parcellation mask file.

  • tres (float) – Resolution of 4th dimension in secs

  • tmin (float) – Value of first time point in secs

  • freesurfer (bool) – If True, parcellation_file is a freesurfer parcellation. Otherwise, it is a nifti file.

Returns:

nii – (xvoxels x yvoxels x zvoxels x nvolumes) nib.Nifti1Image containing parc_data on a volumetric grid.

Return type:

nib.Nifti1Image

osl_ephys.source_recon.parcellation.convert2mne_raw(parc_data, raw, parcel_names=None, extra_chans='stim')[source]#

Create and returns an MNE raw object that contains parcellated data.

Parameters:
  • parc_data (np.ndarray) – (nparcels x ntpts) parcel data.

  • raw (mne.Raw) – mne.io.raw object that produced parc_data via source recon and parcellation. Info such as timings and bad segments will be copied from this to parc_raw.

  • parcel_names (list of str) – List of strings indicating names of parcels. If None then names are set to be parcel_0,…,parcel_{n_parcels-1}.

  • extra_chans (str or list of str) – Extra channels, e.g. ‘stim’ or ‘emg’, to include in the parc_raw object. Defaults to ‘stim’. stim channels are always added to parc_raw if they are present in raw.

Returns:

parc_raw – Generated parcellation in mne.Raw format.

Return type:

mne.Raw

osl_ephys.source_recon.parcellation.convert2mne_epochs(parc_data, epochs, parcel_names=None)[source]#

Create and returns an MNE Epochs object that contains parcellated data.

Parameters:
  • parc_data (np.ndarray) – (nparcels x ntpts x epochs) parcel data.

  • epochs (mne.Epochs) – mne.io.raw object that produced parc_data via source recon and parcellation. Info such as timings and bad segments will be copied from this to parc_raw.

  • parcel_names (list of str) – List of strings indicating names of parcels. If None then names are set to be parcel_0,…,parcel_{n_parcels-1}.

Returns:

parc_epo – Generated parcellation in :py:class: mne.Epochs` format.

Return type:

mne.Epochs

osl_ephys.source_recon.parcellation.spatial_dist_adjacency(parcellation_file, dist, verbose=False)[source]#

Compute adjacency from distances between parcels.

Parameters:
  • parcellation_file (str) – Path to parcellation file.

  • dist (float) – Maximum (geodesic) distance in mm for two parcels to within to be considered as neighbours.

  • verbose (bool) – Should we print the distance between parcels that are considered neighbours?

Returns:

adj_mat – (n_parcels, n_parcels) matrix of zeros (indicating not neighbours) and ones (indicating parcels are neighbours).

Return type:

np.ndarray

osl_ephys.source_recon.parcellation.parcel_vector_to_voxel_grid(mask_file, parcellation_file, vector, freesurfer=False)[source]#

Takes a vector of parcel values and return a 3D voxel grid.

Parameters:
  • mask_file (str) – Mask file for the voxel grid. Must be a NIFTI file.

  • parcellation_file (str) – Parcellation file. Must be a NIFTI file.

  • vector (np.ndarray) – Value at each parcel. Shape must be (n_parcels,).

  • freesurfer (bool) – If True, parcellation_file is a freesurfer parcellation. Otherwise, it is a nifti file.

Returns:

voxel_grid – Value at each voxel. Shape is (x, y, z), where x, y and z correspond to 3D voxel locations.

Return type:

np.ndarray

osl_ephys.source_recon.parcellation.convert2source_estimate(subjects_dir, data, parc=None, reference_brain='fsaverage')[source]#

Convert parcellated data to a source estimate.

Parameters:
  • subjects_dir (str) – Path to subjects directory.

  • data (mne.Evoked or mne.Epochs) – Data to convert.

  • parc (str) – Parcellation name.

  • reference_brain (str) – Reference brain. Default is ‘fsaverage’.

Returns:

stc – Source estimate.

Return type:

mne.SourceEstimate

osl_ephys.source_recon.parcellation.plot_source_topo(data_map, parcellation_file=None, mask_file='MNI152_T1_8mm_brain.nii.gz', axis=None, cmap=None, vmin=None, vmax=None, alpha=0.7, freesurfer=False)[source]#

Plot a data map on a cortical surface. Wrapper for nilearn.plotting.plot_glass_brain.

Parameters:
  • data_map (array_like) – Vector of data values to plot (nparc,)

  • parcellation_file (str) – Filepath of parcellation file to plot data on

  • mask_file (str) – Filepath of mask file to plot data on (Default value = ‘MNI152_T1_8mm_brain.nii.gz’)

  • axis ({None or axis handle}) – Axis to plot into (Default value = None)

  • cmap ({None or matplotlib colormap}) – Colormap to use for plotting (Default value = None)

  • vmin ({None or float}) – Minimum value for colormap (Default value = None)

  • vmax ({None or float}) – Maximum value for colormap (Default value = None)

  • alpha ({None or float}) – Alpha value for colormap (Default value = None)

  • freesurfer (bool) – If True, parcellation_file is a freesurfer parcellation. Otherwise, it is a nifti file.

Returns:

image – AxesImage object

Return type:

matplotlib.image.AxesImage