def plotEEGPower(self, channel=0): """ Plots LFP power Parameters ---------- channel : int The channel from which to plot the power See Also ----- ephysiopy.common.ephys_generic.EEGCalcsGeneric.plotPowerSpectrum() """ from ephysiopy.common.ephys_generic import EEGCalcsGeneric if self.rawData is None: print("Loading raw data...") self.load(loadraw=True) from scipy import signal n_samples = np.shape(self.rawData[:, channel])[0] s = signal.resample(self.rawData[:, channel], int(n_samples / 3e4) * 500) E = EEGCalcsGeneric(s, 500) power_res = E.calcEEGPowerSpectrum() ax = self.makePowerSpectrum( power_res[0], power_res[1], power_res[2], power_res[3], power_res[4], ) plt.show() return ax
def plotEventEEG(self): from ephysiopy.common.ephys_generic import EEGCalcsGeneric if self.rawData is None: print("Loading raw data...") self.load(loadraw=True) E = EEGCalcsGeneric(self.rawData[:, 0], 3e4) event_ts = self.ttl_timestamps[2::2] # this is because some of the trials have two weird events logged at about 2-3 minutes in... E.plotEventEEG(event_ts)
def plotSpectrogram(self, nSeconds=30, secsPerBin=2, ax=None, ymin=0, ymax=250): from ephysiopy.common.ephys_generic import EEGCalcsGeneric if self.rawData is None: print("Loading raw data...") self.load(loadraw=True) # load first 30 seconds by default fs = 3e4 E = EEGCalcsGeneric(self.rawData[0:int(3e4*nSeconds),0], fs) nperseg = int(fs * secsPerBin) from scipy import signal freqs, times, Sxx = signal.spectrogram(E.sig, fs, nperseg=nperseg) Sxx_sm = Sxx from ephysiopy.common import binning R = binning.RateMap() Sxx_sm = R.blurImage(Sxx, (secsPerBin*2)+1) x, y = np.meshgrid(times, freqs) from matplotlib import colors if ax is None: plt.figure() ax = plt.gca() ax.pcolormesh(x, y, Sxx_sm, edgecolors='face', norm=colors.LogNorm()) ax.pcolormesh(x, y, Sxx_sm, edgecolors='face', norm=colors.LogNorm()) ax.set_xlim(times[0], times[-1]) ax.set_ylim(ymin, ymax) ax.set_xlabel('Time(s)') ax.set_ylabel('Frequency(Hz)')
def plotEEGPower(self, eeg_type="eeg", **kwargs): from ephysiopy.common.ephys_generic import EEGCalcsGeneric if "eeg" in eeg_type: E = EEGCalcsGeneric(self.EEG.sig, self.EEG.sample_rate) elif "egf" in eeg_type: E = EEGCalcsGeneric(self.EGF.sig, self.EGF.sample_rate) power_res = E.calcEEGPowerSpectrum() ax = self.makePowerSpectrum( power_res[0], power_res[1], power_res[2], power_res[3], power_res[4], **kwargs ) plot = True if "plot" in kwargs: plot = kwargs.pop("plot") if plot: plt.show() return ax
def plotSpectrogramByDepth(self, nchannels=384, nseconds=100, maxFreq=125, **kwargs): """ Plots a heat map spectrogram of the LFP for each channel. Line plots of power per frequency band and power on a subset of channels are also displayed to the right and above the main plot. Parameters ---------- nchannels : int The number of channels on the probe nseconds : int, optional How long in seconds from the start of the trial to do the spectrogram for (for speed). Default 100 maxFreq : int The maximum frequency in Hz to plot the spectrogram out to. Maximum 1250. Default 125 kwargs: legal values are: 'frequencies' and 'channels'; both are lists that denote which frequencies to show the mean power of along the length of the probe and, which channels to show the frequency spectra of. Notes ----- Should also allow kwargs to specify exactly which channels and / or frequency bands to do the line plots for """ import os lfp_file = os.path.join(self.path2LFPdata, "continuous.dat") status = os.stat(lfp_file) nsamples = int(status.st_size / 2 / nchannels) mmap = np.memmap(lfp_file, np.int16, "r", 0, (nchannels, nsamples), order="F") # Load the channel map # Assumes this is in the AP data location and that kilosort was run # channel_map = np.squeeze(np.load(os.path.join( # self.path2APdata, 'channel_map.npy'))) channel_map = np.arange(nchannels) lfp_sample_rate = 2500 data = np.array(mmap[channel_map, 0:nseconds * lfp_sample_rate]) from ephysiopy.common.ephys_generic import EEGCalcsGeneric E = EEGCalcsGeneric(data[0, :], lfp_sample_rate) E.calcEEGPowerSpectrum() # Select a subset of the full amount of data to display later spec_data = np.zeros(shape=(data.shape[0], len(E.sm_power[0::50]))) for chan in range(data.shape[0]): E = EEGCalcsGeneric(data[chan, :], lfp_sample_rate) E.calcEEGPowerSpectrum() spec_data[chan, :] = E.sm_power[0::50] x, y = np.meshgrid(E.freqs[0::50], channel_map) import matplotlib.colors as colors from matplotlib.pyplot import cm from mpl_toolkits.axes_grid1 import make_axes_locatable _, spectoAx = plt.subplots() if "cmap" in kwargs: cmap = kwargs["cmap"] else: cmap = "bone" spectoAx.pcolormesh( x, y, spec_data, edgecolors="face", cmap=cmap, norm=colors.LogNorm(), shading="nearest", ) if "minFreq" in kwargs: minFreq = kwargs["minFreq"] else: minFreq = 0 spectoAx.set_xlim(minFreq, maxFreq) spectoAx.set_ylim(channel_map[0], channel_map[-1]) spectoAx.set_xlabel("Frequency (Hz)") spectoAx.set_ylabel("Channel") divider = make_axes_locatable(spectoAx) channel_spectoAx = divider.append_axes("top", 1.2, pad=0.1, sharex=spectoAx) meanfreq_powerAx = divider.append_axes("right", 1.2, pad=0.1, sharey=spectoAx) plt.setp( channel_spectoAx.get_xticklabels() + meanfreq_powerAx.get_yticklabels(), visible=False, ) mn_power = np.mean(spec_data, 0) if "channels" in kwargs: channels = kwargs["channels"] cols = iter( cm.rainbow(np.linspace(0, 1, (len(kwargs["channels"]))))) else: channels = np.arange(0, spec_data.shape[0], 60) cols = iter(cm.rainbow(np.linspace(0, 1, (nchannels // 60) + 1))) for i in channels: c = next(cols) channel_spectoAx.plot( E.freqs[0::50], 10 * np.log10(spec_data[i, :] / mn_power), c=c, label=str(i), ) channel_spectoAx.set_ylabel("Channel power(dB)") channel_spectoAx.legend( bbox_to_anchor=(0.0, 1.02, 1.0, 0.102), loc="lower left", mode="expand", fontsize="x-small", ncol=4, ) if "frequencies" in kwargs: lower_freqs = kwargs["frequencies"] upper_freqs = lower_freqs[1::] inc = np.diff([lower_freqs[-2], lower_freqs[-1]]) upper_freqs = np.append(upper_freqs, lower_freqs[-1] + inc) else: freq_inc = 6 lower_freqs = np.arange(1, maxFreq - freq_inc, freq_inc) upper_freqs = np.arange(1 + freq_inc, maxFreq, freq_inc) cols = iter(cm.nipy_spectral(np.linspace(0, 1, len(upper_freqs)))) mn_power = np.mean(spec_data, 1) print(f"spec_data shape = {np.shape(spec_data)}") print(f"mn_power shape = {np.shape(mn_power)}") for freqs in zip(lower_freqs, upper_freqs): freq_mask = np.logical_and(E.freqs[0::50] > freqs[0], E.freqs[0::50] < freqs[1]) mean_power = 10 * np.log10( np.mean(spec_data[:, freq_mask], 1) / mn_power) c = next(cols) meanfreq_powerAx.plot( mean_power, channel_map, c=c, label=str(freqs[0]) + " - " + str(freqs[1]), ) meanfreq_powerAx.set_xlabel("Mean freq. band power(dB)") meanfreq_powerAx.legend( bbox_to_anchor=(0.0, 1.02, 1.0, 0.102), loc="lower left", mode="expand", fontsize="x-small", ncol=1, ) if "saveas" in kwargs: saveas = kwargs["saveas"] plt.savefig(saveas) plt.show()
def plotSpectrogramByDepth(self, nchannels=384, nseconds=100, maxFreq=125, **kwargs): """ Plots a heat map spectrogram of the LFP for each channel. Line plots of power per frequency band and power on a subset of channels are also displayed to the right and above the main plot. Parameters ---------- nchannels : int The number of channels on the probe nseconds : int, optional How long in seconds from the start of the trial to do the spectrogram for (for speed). Default 100 maxFreq : int The maximum frequency in Hz to plot the spectrogram out to. Maximum 1250. Default 125 Notes ----- Should also allow kwargs to specify exactly which channels and / or frequency bands to do the line plots for """ import os lfp_file = os.path.join(self.path2LFPdata, 'continuous.dat') status = os.stat(lfp_file) nsamples = int(status.st_size / 2 / nchannels) mmap = np.memmap(lfp_file, np.int16, 'r', 0, (nchannels, nsamples), order='F') # Load the channel map NB assumes this is in the AP data location and that kilosort was run there channel_map = np.squeeze(np.load(os.path.join(self.path2APdata, 'channel_map.npy'))) lfp_sample_rate = 2500 data = np.array(mmap[channel_map, 0:nseconds*lfp_sample_rate]) from ephysiopy.common.ephys_generic import EEGCalcsGeneric E = EEGCalcsGeneric(data[0, :], lfp_sample_rate) E.calcEEGPowerSpectrum() spec_data = np.zeros(shape=(data.shape[0], len(E.sm_power[0::50]))) for chan in range(data.shape[0]): E = EEGCalcsGeneric(data[chan, :], lfp_sample_rate) E.calcEEGPowerSpectrum() spec_data[chan, :] = E.sm_power[0::50] x, y = np.meshgrid(E.freqs[0::50], channel_map) import matplotlib.colors as colors from matplotlib.pyplot import cm from mpl_toolkits.axes_grid1 import make_axes_locatable _, spectoAx = plt.subplots() spectoAx.pcolormesh(x, y, spec_data, edgecolors='face', cmap='bone',norm=colors.LogNorm()) spectoAx.set_xlim(0, maxFreq) spectoAx.set_ylim(channel_map[0], channel_map[-1]) spectoAx.set_xlabel('Frequency (Hz)') spectoAx.set_ylabel('Channel') divider = make_axes_locatable(spectoAx) channel_spectoAx = divider.append_axes("top", 1.2, pad = 0.1, sharex=spectoAx) meanfreq_powerAx = divider.append_axes("right", 1.2, pad = 0.1, sharey=spectoAx) plt.setp(channel_spectoAx.get_xticklabels() + meanfreq_powerAx.get_yticklabels(), visible=False) mn_power = np.mean(spec_data, 0) cols = iter(cm.rainbow(np.linspace(0,1,(nchannels//60)+1))) for i in range(0, spec_data.shape[0], 60): c = next(cols) channel_spectoAx.plot(E.freqs[0::50], 10*np.log10(spec_data[i, :]/mn_power), c=c, label=str(i)) channel_spectoAx.set_ylabel('Channel power(dB)') channel_spectoAx.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', mode='expand', fontsize='x-small', ncol=4) freq_inc = 6 lower_freqs = np.arange(1, maxFreq-freq_inc, freq_inc) upper_freqs = np.arange(1+freq_inc, maxFreq, freq_inc) cols = iter(cm.nipy_spectral(np.linspace(0,1,len(upper_freqs)))) mn_power = np.mean(spec_data, 1) for freqs in zip(lower_freqs, upper_freqs): freq_mask = np.logical_and(E.freqs[0::50]>freqs[0], E.freqs[0::50]<freqs[1]) mean_power = 10*np.log10(np.mean(spec_data[:, freq_mask],1)/mn_power) c = next(cols) meanfreq_powerAx.plot(mean_power, channel_map, c=c, label=str(freqs[0]) + " - " + str(freqs[1])) meanfreq_powerAx.set_xlabel('Mean freq. band power(dB)') meanfreq_powerAx.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', mode='expand', fontsize='x-small', ncol=1) if 'saveas' in kwargs: saveas = kwargs['saveas'] plt.savefig(saveas) plt.show()
def basic_EEGCalcs(basic_eeg): sig, fs = basic_eeg return EEGCalcsGeneric(sig, fs)