Skip to content

Local field potential (LFP)

ephysiopy.common.ephys_generic.EEGCalcsGeneric(sig, fs)

Bases: object

Generic class for processing and analysis of EEG data

Parameters:

Name Type Description Default
sig ndarray

The signal (of the LFP data)

required
fs float

The sample rate

required

Methods:

Name Description
__add__

Adds two EEGCalcsGeneric objects together

apply_mask

Applies a mask to the signal

butterFilter

Filters self.sig with a butterworth filter with a bandpass filter

calcEEGPowerSpectrum

Calculates the power spectrum of self.sig

ifftFilter

Calculates the dft of signal and filters out the frequencies in

__add__(other)

Adds two EEGCalcsGeneric objects together

Parameters:

Name Type Description Default
other EEGCalcsGeneric

The other EEGCalcsGeneric object to add

required

Returns:

Type Description
EEGCalcsGeneric

A new EEGCalcsGeneric object with the combined sig and fs

apply_mask(mask) -> None

Applies a mask to the signal

Parameters:

Name Type Description Default
mask ndarray

The mask to be applied. For use with np.ma.MaskedArray's mask attribute

required
Notes

If mask is empty, the mask is removed The mask should be a list of tuples, each tuple containing the start and end times of the mask i.e. [(start1, end1), (start2, end2)] everything inside of these times is masked

butterFilter(low: float, high: float, order: int = 5) -> np.ndarray

Filters self.sig with a butterworth filter with a bandpass filter defined by low and high

Parameters:

Name Type Description Default
low float

the lower and upper bounds of the bandpass filter

required
high float

the lower and upper bounds of the bandpass filter

required
order int

the order of the filter

5

Returns:

Name Type Description
filt ndarray

the filtered signal

Notes

the signal is filtered in both the forward and reverse directions (scipy.signal.filtfilt)

calcEEGPowerSpectrum(**kwargs)

Calculates the power spectrum of self.sig

Returns:

Name Type Description
freqs ndaray

The frequencies at which the spectrogram was calculated

power ndarray

The power at the frequencies defined above

sm_power ndarray

The smoothed power

bandmaxpower float

The maximum power in the theta band

freqatbandmaxpower float

The frequency at which the power is maximum

ifftFilter(sig, freqs, fs=250)

Calculates the dft of signal and filters out the frequencies in freqs from the result and reconstructs the original signal using the inverse fft without those frequencies

Parameters:

Name Type Description Default
sig ndarray

the LFP signal to be filtered

required
freqs list

the frequencies to be filtered out

required
fs int

the sampling frequency of sig

250

Returns:

Name Type Description
fftRes ndarray

the filtered LFP signal

ephysiopy.common.phasecoding.LFPOscillations(sig, fs)

Bases: object

Does stuff with the LFP such as looking at nested oscillations (theta/ gamma coupling), the modulation index of such phenomena, filtering out certain frequencies in the LFP, getting the instantaneous phase and amplitude and so on

Methods:

Name Description
PAC_delay_estimate

Estimate the delay in the signal frequency coupling to the driver frequency

filterForLaser

Attempts to filter out frequencies from optogenetic experiments where

getFreqPhase

Uses the Hilbert transform to calculate the instantaneous phase and

get_comodulogram

Computes the comodulogram of phase-amplitude coupling

get_mean_resultant_vector

Calculates the mean phase at which the cluster emitted spikes

get_oscillatory_epochs

Uses the continuous wavelet transform to find epochs

get_theta_phase

Calculates the phase of theta at which a cluster emitted spikes

modulationindex

Calculates the modulation index of theta and gamma oscillations.

plot_cwt

Plots the continuous wavelet transform of the signal

plv

Computes the phase-amplitude coupling (PAC) of nested oscillations.

power_spectrum

Method used by eeg_power_spectra and intrinsic_freq_autoCorr.

spike_xy_phase_plot

Produces a plot of the phase of theta at which each spike was

theta_running

Returns metrics to do with the theta frequency/power and

PAC_delay_estimate(low_fq=8, low_fq_width=2, random_state=0, **kws)

Estimate the delay in the signal frequency coupling to the driver frequency

filterForLaser(sig=None, width=0.125, dip=15.0, stimFreq=6.66)

Attempts to filter out frequencies from optogenetic experiments where the frequency of laser stimulation was at 6.66Hz.

Parameters:

Name Type Description Default
sig array

The signal to be filtered. If None, uses the signal provided during initialization.

None
width float

The width of the filter (default is 0.125).

0.125
dip float

The dip of the filter (default is 15.0).

15.0
stimFreq float

The frequency of the laser stimulation (default is 6.66Hz).

6.66

Returns:

Type Description
array

The filtered signal.

getFreqPhase(sig, band2filter: list, ford=3) -> FreqPhase

Uses the Hilbert transform to calculate the instantaneous phase and amplitude of the time series in sig.

Parameters:

Name Type Description Default
sig array

The signal to be analysed.

required
band2filter list

The two frequencies to be filtered for.

required
ford int

The order for the Butterworth filter (default is 3).

3

Returns:

Type Description
tuple

A tuple containing the filtered signal, phase, amplitude, amplitude filtered, and instantaneous frequency.

get_comodulogram(low_freq_band=[1, 12], **kwargs)

Computes the comodulogram of phase-amplitude coupling between different frequency bands.

Parameters:

Name Type Description Default
low_freq_band list

The low frequency band - what the pactools module calls the "driver" frequency

[1, 12]
**kwargs dict

Additional keyword arguments.

{}

Returns:

Type Description
ndarray

The computed comodulogram.

Notes

This method is a placeholder and needs to be implemented.

get_mean_resultant_vector(spike_times: np.ndarray, **kws) -> np.ndarray

Calculates the mean phase at which the cluster emitted spikes and the length of the mean resultant vector.

Parameters:

Name Type Description Default
lfp_data
required
fs
required

Returns:

Type Description
tuple (float, float) - the mean resultant vector length and mean

mean resultant direction

Notes

For similar approach see Boccara et al., 2010. doi: 10.1038/nn.2602

get_oscillatory_epochs(out_window_size: float = 0.4, FREQ_BAND=(20, 90), **kwargs) -> np.ndarray

Uses the continuous wavelet transform to find epochs of high oscillatory power in the LFP

Parameters:

Name Type Description Default
out_window_size float

The size of the output window in seconds (default is 0.4).

0.4
FREQ_BAND tuple

The frequency band to look for oscillations in (default is (20, 90)).

(20, 90)
**kwargs dict

Additional keyword arguments: wavelet : str The wavelet to use for the continuous wavelet transform (default is "cmor1.0-1.0"). sd_threshold : float the threshold in standard deviations above the band mean power to capture oscillatory epochs

{}

Returns:

Type Description
dict

A dictionary where keys are the start and stop times of the oscillatory window and values are the bandpass filtered LFP signal in that window. The window is centred on the maximum power (amplitude ** 2) in that oscillatory window.

Notes

Uses a similar method to jun et al., but expands the window for candidate oscillatory windows in a better way

References

Jun et al., 2020, Neuron 107, 1095–1112 https://doi.org/10.1016/j.neuron.2020.06.023

get_theta_phase(cluster_times: np.ndarray, **kwargs)

Calculates the phase of theta at which a cluster emitted spikes and returns a fit to a vonmises distribution.

Parameters:

Name Type Description Default
cluster_times ndarray

The times the cluster emitted spikes in seconds.

required
Notes

kwargs can include: low_theta : int Low end for bandpass filter. high_theta : int High end for bandpass filter.

Returns:

Type Description
tuple

A tuple containing the phase of theta at which the cluster emitted spikes, the x values for the vonmises distribution, and the y values for the vonmises distribution.

modulationindex(sig=None, nbins=20, forder=2, thetaband=[6, 12], gammaband=[20, 90], plot=False) -> float

Calculates the modulation index of theta and gamma oscillations. Specifically, this is the circular correlation between the phase of theta and the power of gamma.

Parameters:

Name Type Description Default
sig array

The LFP signal. If None, uses the signal provided during initialization.

None
nbins int

The number of bins in the circular range 0 to 2*pi (default is 20).

20
forder int

The order of the Butterworth filter (default is 2).

2
thetaband list

The lower and upper bands of the theta frequency range (default is [6, 12]).

[6, 12]
gammaband list

The lower and upper bands of the gamma frequency range (default is [20, 90]).

[20, 90]
plot bool

Whether to plot the results (default is True).

False

Returns:

Type Description
float

The modulation index.

Notes

The modulation index is a measure of the strength of phase-amplitude coupling between theta and gamma oscillations.

plot_cwt(sig: np.ndarray, speed: np.ndarray, pos_sample_rate: float, start: float, stop: float, FREQ_BAND=(20, 90), **kwargs)

Plots the continuous wavelet transform of the signal

Parameters:

Name Type Description Default
sig ndarray

The signal to be analysed.

required
Pos PosCalcsGeneric

The position object containing speed and time information.

required
start float

The start time for the plot (in seconds).

required
stop float

The stop time for the plot (in seconds).

required
FREQ_BAND tuple

The frequency band to be highlighted (default is (20, 90)).

(20, 90)

plv(sig=None, forder=2, thetaband=[4, 8], gammaband=[30, 80], plot=True, **kwargs)

Computes the phase-amplitude coupling (PAC) of nested oscillations. More specifically this is the phase-locking value (PLV) between two nested oscillations in EEG data, in this case theta (default 4-8Hz) and gamma (defaults to 30-80Hz). A PLV of unity indicates perfect phase locking (here PAC) and a value of zero indicates no locking (no PAC).

Parameters:

Name Type Description Default
sig array

The LFP signal. If None, uses the signal provided during initialization.

None
forder int

The order of the Butterworth filter (default is 2).

2
thetaband list

The lower and upper bands of the theta frequency range (default is [4, 8]).

[4, 8]
gammaband list

The lower and upper bands of the gamma frequency range (default is [30, 80]).

[30, 80]
plot bool

Whether to plot the resulting binned up polar plot which shows the amplitude of the gamma oscillation found at different phases of the theta oscillation (default is True).

True
**kwargs dict

Additional keyword arguments.

{}

Returns:

Type Description
float

The value of the phase-amplitude coupling (PLV).

power_spectrum(eeg=None, plot=True, binWidthSecs=1 / 250, maxFreq=25, pad2pow=None, ymax=None, **kwargs) -> dict

Method used by eeg_power_spectra and intrinsic_freq_autoCorr. Signal in must be mean normalized already.

Parameters:

Name Type Description Default
eeg ndarray

The EEG signal to analyze.

None
plot bool

Whether to plot the resulting power spectrum (default is True).

True
binWidthSecs float

The bin width in seconds for the power spectrum.

1 / 250
maxFreq float

The upper limit of the power spectrum frequency range (default is 25).

25
pad2pow int

The power of 2 to pad the signal to (default is None).

None
ymax float

The maximum y-axis value for the plot (default is None).

None
**kwargs dict

Additional keyword arguments.

{}

Returns:

Type Description
dict

A dictionary containing the power spectrum and other related metrics. "maxFreq", (float) - frequency at which max power in theta band occurs "Power", (np.ndarray) - smoothed power values "Freqs", (np.ndarray) - frequencies corresponding to power values "s2n", - signal to noise ratio "Power_raw", (np.ndarray) - raw power values "k", (np.ndarray) - smoothing kernel "kernelLen", (float) - length of smoothing kernel "kernelSig", (float) - sigma of smoothing kernel "binsPerHz", (float) - bins per Hz in the power spectrum "kernelLen", (float) - length of the smoothing kernel

spike_xy_phase_plot(cluster: int, pos_data: PosCalcsGeneric, lfp_data: EEGCalcsGeneric, cluster_times: np.ndarray) -> plt.Axes

Produces a plot of the phase of theta at which each spike was emitted. Each spike is plotted according to the x-y location the animal was in when it was fired and the colour of the marker corresponds to the phase of theta at which it fired.

Parameters:

Name Type Description Default
cluster int

The cluster number.

required
pos_data PosCalcsGeneric

Position data object containing position and speed information.

required
phy_data TemplateModel

Phy data object containing spike times and clusters.

required
lfp_data EEGCalcsGeneric

LFP data object containing the LFP signal and sampling rate.

required

Returns:

Type Description
Axes

The matplotlib axes object with the plot.

theta_running(pos_data: PosCalcsGeneric, lfp_data: EEGCalcsGeneric, plot: bool = True, **kwargs) -> tuple[np.ma.MaskedArray, ...]

Returns metrics to do with the theta frequency/power and running speed/acceleration.

Parameters:

Name Type Description Default
pos_data PosCalcsGeneric

Position data object containing position and speed information.

required
lfp_data EEGCalcsGeneric

LFP data object containing the LFP signal and sampling rate.

required
plot bool

Whether to plot the results (default is True).

True
**kwargs dict

Additional keyword arguments: low_theta : float Lower bound of theta frequency (default is 6). high_theta : float Upper bound of theta frequency (defaultt is 12). low_speed : float Lower bound of running speed (data is masked below this value) high_speed : float Upper bound of running speed (data is masked above this value) nbins : int Number of bins into which to bin data (Same number for both speed and theta)

{}

Returns:

Type Description
tuple[MaskedArray, ...]

A tuple containing the results of the linear regression of running speed and theta frequency and masked arrays for speed and theta frequency.

Notes

The function calculates the instantaneous frequency of the theta band and interpolates the running speed to match the LFP data. It then creates a 2D histogram of theta frequency vs. running speed and overlays the mean points for each speed bin. The function also performs a linear regression to find the correlation between speed and theta frequency. This is performed against the binned (mean) frequency at each of the speed bins

See Also

scipy.stats.linregress

ephysiopy.common.phasecoding.get_cycle_labels(spike_phase: np.ndarray, min_allowed_min_spike_phase: float) -> tuple[np.ndarray, ...]

Get the cycle labels for a given phase array

Parameters:

Name Type Description Default
phase ndarray

The phases at which the spikes were fired.

required
min_allowed_min_spike_phase float

The minimum allowed phase for cycles to start.

required

Returns:

Type Description
ndarray

The cycle labels for the phase array

ephysiopy.common.phasecoding.get_phase_of_min_spiking(spkPhase: np.ndarray) -> float

Returns the phase at which the minimum number of spikes are fired

Parameters:

Name Type Description Default
spkPhase ndarray

The phase of the spikes

required

Returns:

Type Description
float

The phase in degrees at which the minimum number of spikes are fired

ephysiopy.common.phasecoding.get_bad_cycles(filtered_eeg: np.ndarray, negative_freqs: np.ndarray, cycle_labels: np.array, min_power_percent_threshold: float, min_theta: float, max_theta: float, lfp_fs: float) -> np.ndarray

Get the cycles that are bad based on their length and power

Parameters:

Name Type Description Default
filtered_eeg ndarray

The filtered EEG signal

required
negative_freqs ndarray

A boolean array indicating negative frequencies

required
cycle_labels ndarray

The cycle labels for the phase array

required
min_power_percent_threshold float

The minimum power percent threshold for rejecting cycles

required
min_theta float

The minimum theta frequency

required
max_theta float

The maximum theta frequency

required
lfp_fs float

The sampling frequency of the LFP signal

required

Returns:

Type Description
ndarray

A boolean array indicating bad cycles

ephysiopy.common.phasecoding.theta_filter_lfp(lfp: np.ndarray, fs: float, **kwargs)

Processes an LFP signal for theta cycles, filtering out bad cycles (low power, too long/ short etc) and applying labels to each cycle etc

ephysiopy.common.phasecoding.get_cross_wavelet(theta_phase: np.ndarray, theta_lfp: np.ndarray, gamma_lfp: np.ndarray, fs: float, **kwargs)

Get the cross wavelet transform between the theta and gamma LFP signals

ephysiopy.common.phasecoding.get_theta_cycle_spectogram(phase: np.ndarray, cycle_label: np.ndarray, filt_lfp: np.ndarray, lfp: np.ndarray, fs: float, **kwargs)

Get a spectrogram of the theta cycles in the LFP

ephysiopy.common.phasecoding.detect_oscillation_episodes(lfp: np.ndarray, fs: float)