osl_ephys.source_recon.beamforming#

Beamforming.

Functions#

get_beamforming_filenames(subjects_dir, subject)

Get beamforming filenames.

make_lcmv(subjects_dir, subject, data[, chantypes, ...])

Compute LCMV spatial filter.

make_plots(subjects_dir, subject, filters, data)

Plot LCMV beamforming filters.

load_lcmv(subjects_dir, subject)

Load LCMV beamforming filters.

apply_lcmv(data, filters[, reject_by_annotation])

Apply a LCMV filter to an MNE Raw or Epochs object.

apply_lcmv_raw(raw, filters[, reject_by_annotation])

Modified version of mne.beamformer.apply_lcmv_raw.

get_recon_timeseries(subjects_dir, subject, coord_mni, ...)

Gets the reconstructed time series nearest to the passed coordinates in MNI space.

transform_recon_timeseries(subjects_dir, subject, ...)

Spatially resamples a (ndipoles x ntpts) array of reconstructed time courses (in head/polhemus space) to dipoles on the brain grid of the specified reference brain.

get_lcmv_weights(subjects_dir, subject[, ...])

Get LCMV beamformer weights.

get_leadfields(subjects_dir, subject[, ...])

Get leadfields from a forward model.

_make_lcmv(info, forward, data_cov[, reg, noise_cov, ...])

Compute LCMV spatial filter.

_compute_beamformer(G, Cm, reg, n_orient, weight_norm, ...)

Compute a spatial beamformer filter (LCMV or DICS).

_prepare_beamformer_input(info, forward[, label, ...])

Input preparation common for LCMV, DICS, and RAP-MUSIC.

voxel_timeseries(subjects_dir, subject, preproc_file, ...)

Get the voxel time series of beamformed data.

Module Contents#

osl_ephys.source_recon.beamforming.get_beamforming_filenames(subjects_dir, subject)[source]#

Get beamforming filenames.

Files will be in subjects_dir/subject/beamforming

Parameters:
  • subjects_dir (string) – Directory containing the subject directories.

  • subject (string) – Subject name.

Returns:

filenames – A dict of files.

Return type:

dict

osl_ephys.source_recon.beamforming.make_lcmv(subjects_dir, subject, data, chantypes=None, data_cov=None, noise_cov=None, reg=0, label=None, pick_ori='max-power-pre-weight-norm', rank='info', noise_rank='info', weight_norm='unit-noise-gain-invariant', reduce_rank=True, depth=None, inversion='matrix', verbose=None, save_filters=False)[source]#

Compute LCMV spatial filter.

Modified version of mne.beamformer.make_lcmv.

Parameters:
  • subjects_dir (str) – Directory to find subject directories in.

  • subject (str) – Subject name.

  • data (instance of mne.Raw | mne.Epochs) – The measurement data to specify the channels to include. Bad channels in info[‘bads’] are not used. Will also be used to calculate data_cov.

  • chantypes (list) – List of channel types to use to calculate the noise covariance. E.g. [‘eeg’], [‘mag’, ‘grad’], [‘eeg’, ‘mag’, ‘grad’].

  • data_cov (instance of mne.Covariance | None) – The noise covariance matrix used to whiten. If None will be computed from dat.

  • noise_cov (instance of mne.Covariance | None) – The noise covariance matrix used to whiten. If None will be computed from dat as a diagonal matrix with variances set to the average of all sensors of that type.

  • reg (float) – The regularization for the whitened data covariance.

  • label (instance of Label) – Restricts the LCMV solution to a given label.

  • pick_ori (None | 'normal' | 'max-power' | max-power-pre-weight-norm) – The source orientation to compute the beamformer in.

  • rank (dict | None | 'full' | 'info') –

    This controls the rank computation that can be read from the measurement info or estimated from the data. When a noise covariance is used for whitening, this should reflect the rank of that covariance, otherwise amplification of noise components can occur in whitening (e.g., often during source localization).

    None

    The rank will be estimated from the data after proper scaling of different channel types.

    'info'

    The rank is inferred from info. If data have been processed with Maxwell filtering, the Maxwell filtering header is used. Otherwise, the channel counts themselves are used. In both cases, the number of projectors is subtracted from the (effective) number of channels in the data. For example, if Maxwell filtering reduces the rank to 68, with two projectors the returned value will be 66.

    'full'

    The rank is assumed to be full, i.e. equal to the number of good channels. If a Covariance is passed, this can make sense if it has been (possibly improperly) regularized without taking into account the true data rank.

    dict

    Calculate the rank only for a subset of channel types, and explicitly specify the rank for the remaining channel types. This can be extremely useful if you already know the rank of (part of) your data, for instance in case you have calculated it earlier. This parameter must be a dictionary whose keys correspond to channel types in the data (e.g. ‘meg’, ‘mag’, ‘grad’, ‘eeg’), and whose values are integers representing the respective ranks. For example, {‘mag’: 90, ‘eeg’: 45} will assume a rank of 90 and 45 for magnetometer data and EEG data, respectively. The ranks for all channel types present in the data, but not specified in the dictionary will be estimated empirically. That is, if you passed a dataset containing magnetometer, gradiometer, and EEG data together with the dictionary from the previous example, only the gradiometer rank would be determined, while the specified magnetometer and EEG ranks would be taken for granted.

    The default is 'info'.

  • noise_rank (dict | None | 'full' | 'info') – This controls the rank computation that can be read from the measurement info or estimated from the data. When a noise covariance is used for whitening, this should reflect the rank of that covariance, otherwise amplification of noise components can occur in whitening (e.g., often during source localization).

  • weight_norm (None | 'unit-noise-gain' | 'unit-noise-gain-invariant' | 'nai') – The weight normalization scheme to use.

  • reduce_rank (bool) – Whether to reduce the rank by one during computation of the filter.

  • depth (None | float | dict) – How to weight (or normalize) the forward using a depth prior (see MNE docs).

  • inversion ('matrix' | 'single') – The inversion scheme to compute the weights.

  • save_filters (bool) – Should we save the LCMV beamforming filter?

Returns:

filters – Dictionary containing filter weights from LCMV beamformer. See MNE docs.

Return type:

instance of mne.beamformer.Beamformer

osl_ephys.source_recon.beamforming.make_plots(subjects_dir, subject, filters, data)[source]#

Plot LCMV beamforming filters.

Parameters:
  • subjects_dir (string) – Directory containing the subject directories.

  • subject (string) – Subject name.

  • filters (mne.beamformer.Beamformer) – Filters to plot.

  • data (mne.Raw or mne.Epochs) – Data used to create the filters.

Returns:

  • filters_cov_plot (str) – Path to covariance plot.

  • filters_svd_plot (str) – Path to eigenspectrum plot.

osl_ephys.source_recon.beamforming.load_lcmv(subjects_dir, subject)[source]#

Load LCMV beamforming filters.

Parameters:
  • subjects_dir (string) – Directory containing the subject directories.

  • subject (string) – Subject name.

Returns:

filters – Dictionary containing filter weights from LCMV beamformer. See MNE docs.

Return type:

instance of mne.beamformer.Beamformer

osl_ephys.source_recon.beamforming.apply_lcmv(data, filters, reject_by_annotation='omit')[source]#

Apply a LCMV filter to an MNE Raw or Epochs object.

Parameters:
  • data (instance of mne.io.Raw or mne.Epochs) – The data to apply the LCMV filter to.

  • filters (instance of mne.beamformer.Beamformer) – The LCMV filter to apply.

  • reject_by_annotation (str | list of str | None) – If string, the annotation description to use to reject epochs. If list of str, the annotation descriptions to use to reject epochs. If None, do not reject epochs.

Return type:

mne.SourceEstimate

osl_ephys.source_recon.beamforming.apply_lcmv_raw(raw, filters, reject_by_annotation='omit')[source]#

Modified version of mne.beamformer.apply_lcmv_raw.

Parameters:
  • raw (instance of mne.io.Raw) – The raw data to apply the LCMV filter to.

  • filters (instance of mne.beamformer.Beamformer) – The LCMV filter to apply.

  • reject_by_annotation (str | list of str | None) – If string, the annotation description to use to reject epochs. If list of str, the annotation descriptions to use to reject epochs. If None, do not reject epochs.

Return type:

mne.SourceEstimate

osl_ephys.source_recon.beamforming.get_recon_timeseries(subjects_dir, subject, coord_mni, recon_timeseries_head)[source]#

Gets the reconstructed time series nearest to the passed coordinates in MNI space.

Parameters:
  • subjects_dir (string) – Directory to find subject directories in.

  • subject (string) – Subject name.

  • coord_mni ((3,) numpy.ndarray) – 3D coordinate in MNI space to get timeseries for

  • recon_timeseries_head ((ndipoles, ntpts) np.array) – Reconstructed time courses in head (polhemus) space. Assumes that the dipoles are the same (and in the same order) as those in the forward model, rhino_files[‘fwd_model’].

Returns:

recon_timeseries – The timecourse in recon_timeseries_head nearest to coord_mni.

Return type:

numpy.ndarray

osl_ephys.source_recon.beamforming.transform_recon_timeseries(subjects_dir, subject, recon_timeseries, spatial_resolution=None, reference_brain='mni')[source]#

Spatially resamples a (ndipoles x ntpts) array of reconstructed time courses (in head/polhemus space) to dipoles on the brain grid of the specified reference brain.

Parameters:
  • subjects_dir (string) – Directory to find subject directories in.

  • subject (string) – Subject name.

  • recon_timeseries (numpy.ndarray) – (ndipoles, ntpts) or (ndipoles, ntpts, ntrials) of reconstructed time courses (in head (polhemus) space). Assumes that the dipoles are the same (and in the same order) as those in the forward model, rhino_files[‘fwd_model’]. Typically derive from the VolSourceEstimate’s output by MNE source recon methods, e.g. mne.beamformer.apply_lcmv, obtained using a forward model generated by RHINO.

  • spatial_resolution (int) – Resolution to use for the reference brain in mm (must be an integer, or will be cast to nearest int). If None, then the gridstep used in rhino_files[‘fwd_model’] is used.

  • reference_brain (string) – ‘mni’ indicates that the reference_brain is the stdbrain in MNI space. ‘mri’ indicates that the reference_brain is the subject’s sMRI in the scaled native/mri space. ‘unscaled_mri’ indicates that the reference_brain is the subject’s sMRI in unscaled native/mri space. Note that scaled/unscaled relates to the allow_smri_scaling option in coreg. If allow_scaling was False, then the unscaled MRI will be the same as the scaled MRI.

Returns:

  • recon_timeseries_out ((ndipoles, ntpts) numpy.ndarray) – Array of reconstructed time courses resampled on the reference brain grid.

  • reference_brain_fname (string) – File name of the requested reference brain at the requested spatial resolution, int(spatial_resolution) (with zero for background, and !=0 for brain).

  • coords_out ((3, ndipoles) numpy.ndarray) – Array of coordinates (in mm) of dipoles in recon_timeseries_out in “reference_brain” space.

osl_ephys.source_recon.beamforming.get_lcmv_weights(subjects_dir, subject, spatial_resolution=None, reference_brain='mni', verbose=None)[source]#

Get LCMV beamformer weights.

Parameters:
  • subjects_dir (str) – Directory to find subject directories in.

  • subject (str) – Subject name.

  • spatial_resolution (int) – Resolution to use for the reference brain in mm (must be an integer, or will be cast to nearest int). If None, then the gridstep used in rhino_files[‘fwd_model’] is used.

  • reference_brain (str) – ‘mni’ indicates that the reference_brain is the stdbrain in MNI space. ‘mri’ indicates that the reference_brain is the subject’s sMRI in the scaled native/mri space. ‘unscaled_mri’ indicates that the reference_brain is the subject’s sMRI in unscaled native/mri space. Note that Scaled/unscaled relates to the allow_smri_scaling option in coreg. If allow_scaling was False, then the unscaled MRI will be the same as the scaled MRI.

  • verbose (bool) – If True, print out more information.

Returns:

  • weights ((ndipoles, nsensors) numpy.ndarray) – Beamformer weights resampled on the reference brain grid.

  • coords ((3, ndipoles) numpy.ndarray) – Array of coordinates (in mm) of dipoles in weights in “reference_brain” space.

osl_ephys.source_recon.beamforming.get_leadfields(subjects_dir, subject, spatial_resolution=None, reference_brain='mni', orientation='max-dim', verbose=None)[source]#

Get leadfields from a forward model.

Parameters:
  • subjects_dir (str) – Directory to find subject directories in.

  • subject (str) – Subject name.

  • spatial_resolution (int) – Resolution to use for the reference brain in mm (must be an integer, or will be cast to nearest int). If None, then the gridstep used in rhino_files[‘fwd_model’] is used.

  • reference_brain (str) – ‘mni’ indicates that the reference_brain is the stdbrain in MNI space. ‘mri’ indicates that the reference_brain is the subject’s sMRI in the scaled native/mri space. ‘unscaled_mri’ indicates that the reference_brain is the subject’s sMRI in unscaled native/mri space. Note that Scaled/unscaled relates to the allow_smri_scaling option in coreg. If allow_scaling was False, then the unscaled MRI will be the same as the scaled MRI.

  • orientation (str) – How should we reduce the 3 leadfield dimensions into a scaler? Options: ‘l2-norm’ takes the L2 norm across the xyz dimensions. ‘max-dim’ takes the leadfield with the highest value across the xyz dimensions. ‘max-power’ projects the leadfield onto the eigenvector with the smallest eigenvalue, this is equivalent to the maximum power orientation.

  • verbose (bool) – If True, print out more information.

Returns:

  • leadfield ((nsensors, ndipoles) numpy.ndarray) – Lead fields resampled on the reference brain grid.

  • coords ((3, ndipoles) numpy.ndarray) – Array of coordinates (in mm) of dipoles in leadfield_out in “reference_brain” space.

osl_ephys.source_recon.beamforming._make_lcmv(info, forward, data_cov, reg=0.05, noise_cov=None, label=None, pick_ori=None, rank='info', noise_rank='info', weight_norm='unit-noise-gain-invariant', reduce_rank=False, depth=None, inversion='matrix', verbose=None)[source]#

Compute LCMV spatial filter.

Modified version of mne.beamformer._make_lcmv.

Parameters:
  • info (instance of mne.Info) – The measurement info to specify the channels to include.

  • forward (instance of mne.Forward) – The forward solution.

  • data_cov (instance of mne.Covariance) – The data covariance object.

  • reg (float) – The regularization for the whitened data covariance.

  • noise_cov (instance of mne.Covariance) – The noise covariance object.

  • label (instance of mne.Label) – Restricts the LCMV solution to a given label.

  • pick_ori (None | 'normal' | 'max-power' | max-power-pre-weight-norm) – The source orientation to compute the beamformer in.

  • rank (dict | None | 'full' | 'info') –

    This controls the rank computation that can be read from the measurement info or estimated from the data. When a noise covariance is used for whitening, this should reflect the rank of that covariance, otherwise amplification of noise components can occur in whitening (e.g., often during source localization).

    None

    The rank will be estimated from the data after proper scaling of different channel types.

    'info'

    The rank is inferred from info. If data have been processed with Maxwell filtering, the Maxwell filtering header is used. Otherwise, the channel counts themselves are used. In both cases, the number of projectors is subtracted from the (effective) number of channels in the data. For example, if Maxwell filtering reduces the rank to 68, with two projectors the returned value will be 66.

    'full'

    The rank is assumed to be full, i.e. equal to the number of good channels. If a Covariance is passed, this can make sense if it has been (possibly improperly) regularized without taking into account the true data rank.

    dict

    Calculate the rank only for a subset of channel types, and explicitly specify the rank for the remaining channel types. This can be extremely useful if you already know the rank of (part of) your data, for instance in case you have calculated it earlier. This parameter must be a dictionary whose keys correspond to channel types in the data (e.g. ‘meg’, ‘mag’, ‘grad’, ‘eeg’), and whose values are integers representing the respective ranks. For example, {‘mag’: 90, ‘eeg’: 45} will assume a rank of 90 and 45 for magnetometer data and EEG data, respectively. The ranks for all channel types present in the data, but not specified in the dictionary will be estimated empirically. That is, if you passed a dataset containing magnetometer, gradiometer, and EEG data together with the dictionary from the previous example, only the gradiometer rank would be determined, while the specified magnetometer and EEG ranks would be taken for granted.

    The default is 'info'.

  • noise_rank (dict | None | 'full' | 'info') – This controls the rank computation that can be read from the measurement info or estimated from the data. When a noise covariance is used for whitening, this should reflect the rank of that covariance, otherwise amplification of noise components can occur in whitening (e.g., often during source localization).

  • weight_norm (None | 'unit-noise-gain' | 'nai') – The weight normalization scheme to use.

  • reduce_rank (bool) – Whether to reduce the rank by one during computation of the filter.

  • depth (None | float | dict) – How to weight (or normalize) the forward using a depth prior (see Notes).

  • inversion ('matrix' | 'single') – The inversion scheme to compute the weights.

  • verbose (bool, str, int, or None) – If not None, override default verbose level (see mne.verbose).

Returns:

filters – Dictionary containing filter weights from LCMV beamformer. See MNE docs.

Return type:

instance of mne.beamformer.Beamformer

osl_ephys.source_recon.beamforming._compute_beamformer(G, Cm, reg, n_orient, weight_norm, pick_ori, reduce_rank, rank, inversion, nn, orient_std, whitener)[source]#

Compute a spatial beamformer filter (LCMV or DICS).

For more detailed information on the parameters, see the docstrings of make_lcmv and make_dics.

Modified version of mne.beamformer._compute_beamformer.

Parameters:
  • G ((n_dipoles, n_channels) numpy.ndarray) – The leadfield.

  • Cm ((n_channels, n_channels) numpy.ndarray) – The data covariance matrix.

  • reg (float) – Regularization parameter.

  • n_orient (int) – Number of dipole orientations defined at each source point

  • weight_norm (None | 'unit-noise-gain' | 'nai') – The weight normalization scheme to use.

  • pick_ori (None | 'normal' | 'max-power' | max-power-pre-weight-norm) – The source orientation to compute the beamformer in.

  • reduce_rank (bool) – Whether to reduce the rank by one during computation of the filter.

  • rank (dict | None | 'full' | 'info') – See compute_rank.

  • inversion ('matrix' | 'single') – The inversion scheme to compute the weights.

  • nn ((n_dipoles, 3) numpy.ndarray) – The source normals.

  • orient_std ((n_dipoles,) numpy.ndarray) – The std of the orientation prior used in weighting the lead fields.

  • whitener ((n_channels, n_channels) numpy.ndarray) – The whitener.

Returns:

W – The beamformer filter weights.

Return type:

(n_dipoles, n_channels) numpy.ndarray

osl_ephys.source_recon.beamforming._prepare_beamformer_input(info, forward, label=None, pick_ori=None, noise_cov=None, rank=None, pca=False, loose=None, combine_xyz='fro', exp=None, limit=None, allow_fixed_depth=True, limit_depth_chs=False)[source]#

Input preparation common for LCMV, DICS, and RAP-MUSIC.

Modified version of mne.beamformer._prepare_beamformer_input.

Parameters:
  • info (instance of mne.Info) – Measurement info

  • forward (instance of mne.Forward) – The forward solution.

  • label (instance of mne.Label | None) – Restricts the forward solution to a given label.

  • pick_ori (None | 'normal' | 'max-power' | 'vector' | 'max-power-pre-weight-norm') – The source orientation to compute the beamformer in.

  • noise_cov (instance of mne.Covariance | None) – The noise covariance.

  • rank (dict | None | 'full' | 'info') – See mne.compute_rank().

  • pca (bool) – If True, the rank of the forward is reduced to match the rank of the noise covariance matrix.

  • loose (float | None) – Value that weights the source variances of the dipole components defining the tangent space of the cortical surfaces. If None, no loose orientation constraint is applied.

  • combine_xyz (str) – How to combine the dipoles in the same locations of the forward model when picking normals. See mne.forward._pick_ori().

  • exp (float | None) – Exponent for the depth weighting. If None, no depth weighting is performed.

  • limit (float | None) – Limit on depth weighting factors. If None, no upper limit is applied.

  • allow_fixed_depth (bool) – If True, fixed depth weighting is allowed.

  • limit_depth_chs (bool) – If True, use only grad channels for depth weighting.

Returns:

  • is_free_ori (bool) – Whether the forward operator is free orientation.

  • info (instance of mne.Info) – Measurement info restricted to selected channels.

  • proj (array) – The SSP/PCA projector.

  • vertno (array) – The indices of the vertices corresponding to the source space.

  • G (array) – The forward operator restricted to selected channels.

  • whitener (array) – The whitener for the selected channels.

  • nn (array) – The normals of the source space.

  • orient_std (array) – The standard deviation of the orientation prior.

osl_ephys.source_recon.beamforming.voxel_timeseries(subjects_dir, subject, preproc_file, chantypes, freq_range=None, spatial_resolution=None, reference_brain='mni', reject_by_annotation=None)[source]#

Get the voxel time series of beamformed data.

Parameters:
  • subjects_dir (str) – Directory to find subject directories in.

  • subject (str) – Subject name.

  • preproc_file (str) – Path to the preprocessed fif file.

  • chantypes (list of str) – Channel types to use in beamforming.

  • freq_range (list) – Lower and upper band to bandpass filter before beamforming. If None, no filtering is done.

  • spatial_resolution (int) – Resolution for beamforming to use for the reference brain in mm (must be an integer, or will be cast to nearest int). If None, then the gridstep used in rhino_files[‘fwd_model’] is used.

  • reference_brain (str) – ‘mni’ indicates that the reference_brain is the stdbrain in MNI space. ‘mri’ indicates that the reference_brain is the subject’s sMRI in the scaled native/mri space. ‘unscaled_mri’ indicates that the reference_brain is the subject’s sMRI in unscaled native/mri space. Note that Scaled/unscaled relates to the allow_smri_scaling option in coreg. If allow_scaling was False, then the unscaled MRI will be the same as the scaled MRI.

  • reject_by_annotation (str) – Argument passed to .get_data() if the preproc file contains an MNE Raw object.

Returns:

  • voxel_data (np.ndarray) – Voxel time series in (voxels, time) format.

  • voxel_coords (np.ndarray) – Voxel coordinates in MNI space.