def three_event_channel(): stim_amp, stim_grad, stim_env = np.zeros((1, raw.n_times)), np.zeros( (1, raw.n_times)), np.zeros((1, raw.n_times)) for evt in spikes_df.values: if evt[1] == 'amp': stim_amp[0][evt[4]] = 1 elif evt[1] == 'grad': stim_grad[0][evt[4]] = 1 else: stim_env[0][evt[4]] = 1 raw.pick_channels([selected_channel]) info_amp = mne.create_info(['AMP'], raw.info['sfreq'], ['stim']) info_grad = mne.create_info(['GRAD'], raw.info['sfreq'], ['stim']) info_env = mne.create_info(['ENV'], raw.info['sfreq'], ['stim']) amp_raw = mne.io.RawArray(stim_amp, info_amp) grad_raw = mne.io.RawArray(stim_grad, info_grad) env_raw = mne.io.RawArray(stim_env, info_env) raw.load_data() raw.add_channels([amp_raw, grad_raw, env_raw], force_update_info=True) raw.reorder_channels([selected_channel, 'AMP', 'GRAD', 'ENV']) if original_sf > 1000: raw.resample(500) sp = Sleep(data=raw._data, sf=raw.info['sfreq'], channels=raw.info['ch_names'], downsample=None) sp.replace_detections('peak', peak_index) sp.replace_detections('spindle', spikes_index) sp.show() print('finish')
from scipy.io import loadmat from visbrain.gui import Sleep import numpy as np from scipy import signal import matplotlib.pyplot as plt # Load the matlab file : mat = loadmat('../data/ID08_57to65h.mat') info = loadmat('../data/ID08_info.mat') # Prepare the data : sf = float(info['fs']) data = mat['EEG'] channel_labels = ['ch00', 'ch20', 'ch40', 'ch60'] """ f, t, Sxx = signal.spectrogram(data, sf, nperseg=int(30*sf)) tvec = np.linspace(0, t[-1]/60/60, len(t)) plt.locator_params(axis='x', nbins=40) plt.pcolormesh(tvec, f, Sxx, vmin=0, vmax=20) plt.xlabel('Time [h]') plt.ylabel('Frequency [Hz]') plt.ylim(0, 30) plt.colorbar() plt.show() """ # Open the GUI : Sleep(data=data, sf=sf, channels=channel_labels).show()
scalp = np.zeros((1, raw.n_times)) for evt in scalp_epochs.values: scalp[0][250 * evt[0]:250 * evt[0] + 250] = 1 # raw.pick_channels(['LAH1']) info_depth = mne.create_info(['depth'], raw.info['sfreq'], ['stim']) info_scalp = mne.create_info(['scalp'], raw.info['sfreq'], ['stim']) depth_raw = mne.io.RawArray(depth, info_depth) scalp_raw = mne.io.RawArray(scalp, info_scalp) raw.load_data() raw.add_channels([depth_raw, scalp_raw], force_update_info=True) raw.reorder_channels([ 'EOG1', 'EOG2', 'C3', 'C4', 'PZ', 'RAH1', 'RAH2', 'RAH1-RAH2', 'LAH1', 'LAH2', 'LAH1-LAH2', 'depth', 'scalp' ]) sp = Sleep(data=raw._data, sf=raw.info['sfreq'], channels=raw.info['ch_names'], downsample=1000) # sp.replace_detections('spindle', spikes_index) sp.show() print('finish') # 396, 398, 402, 406, 416 - good depth detection # scalp: # 398- can't really see spikes on EOG, c3 pretty bad and somtime also c4 pz # 406- C3 pretty suck, somtime others # 415- wierd stuff, shitty scalp but ok depth detection, somtime all channels look the same (scalp+depth), why? # 416- very low amp scalp channels while spikes and the opposite, why? maybe cortex activity?
""" Basic configuration =================== This example demonstrate how to open Sleep. Two windows will then appear : * The first one ask a proper dataset (required) * The second one ask for an hypnogram (optional). If None, an empty one is used .. image:: ../../_static/examples/ex_basic_sleep.png """ from visbrain.gui import Sleep Sleep().show()
import numpy as np from visbrain.gui import Sleep from visbrain.io import download_file, path_to_visbrain_data # Download the file : download_file('sleep_edf.zip', unzip=True, astype='example_data') target_path = path_to_visbrain_data(folder='example_data') # Get data path : dfile = os.path.join(target_path, 'excerpt2.edf') # data hfile = os.path.join(target_path, 'Hypnogram_excerpt2.txt') # hypnogram cfile = os.path.join(target_path, 'excerpt2_config.txt') # GUI config # Define an instance of Sleep : sp = Sleep(data=dfile, hypno=hfile, config_file=cfile) ############################################################################### # Define new methods ############################################################################### ############################################################################### # Spindle function # ~~~~~~~~~~~~~~~~ ############################################################################### # # This function does NOT perform a real spindle detection. It's purpose is to # show how to replace the default detection behavior by a custom function. # It just highlights samples between [0, 100], [200, 300] and [400, 500].
from visbrain.io import download_file, path_to_visbrain_data from wonambi.detect.spindle import DetectSpindle, detect_Moelle2011 from wonambi.detect.slowwave import DetectSlowWave, detect_Massimini2004 # Download the file : download_file('sleep_edf.zip', unzip=True, astype='example_data') target_path = path_to_visbrain_data(folder='example_data') # Get data path : dfile = os.path.join(target_path, 'excerpt2.edf') # data hfile = os.path.join(target_path, 'Hypnogram_excerpt2.txt') # hypnogram cfile = os.path.join(target_path, 'excerpt2_config.txt') # GUI config # Define an instance of Sleep : sp = Sleep(data=dfile, hypno=hfile, config_file=cfile) ############################################################################### # Define new methods ############################################################################### ############################################################################### # Spindle function # ~~~~~~~~~~~~~~~~ # Define a DetectSpindle instance : opts_spin = DetectSpindle('Moelle2011') # Define the function to replace : def fcn_spindle(data, sf, time, hypno): # noqa
CH5 = data_out[5, :] CH6 = data_out[6, :] CH7 = data_out[7, :] events_xtrodes = xtrodes_ev['events']['event_time'][0][0] # data=xtrodes_data['data'] np.diff(events) #%%plottting CH3 = sp.signal.resample(CH3, int(len(CH3) / 4)) t_x = np.linspace(0, len(CH3) / 1000, len(CH3)) raw_fil_data = raw_fil._data t_EGI = np.linspace(0, len(raw_fil_data) / 1000, len(raw_fil_data)) plt.plot(t_x, CH3, t_EGI, raw_fil_data) #plt.plot(data_out[4,1:20000]) # let's plot 5sec # %%Displaying the Xtrodes signal in visbrain ''' # load EDF in to Sleep hfile=None # if there is no folder= 'C://Users//romar/Desktop/stas_ses_data' EDF_file='data_record_0.edf' path=os.path.join(folder,EDF_file) #cfg_file = '' Sleep(path).show() # %%Playing with Pandas ''' s = pd.Series(epochs.events, index=[np.linspace(0, 18, 19)])
""" Load REC files ============== This example demonstrate how to load a .rec file. Required dataset at : https://www.dropbox.com/s/hc18bgn2hlnmiph/sleep_edf.zip?dl=1 .. image:: ../../_static/examples/ex_load_rec.png """ import os from visbrain.gui import Sleep from visbrain.io import download_file, path_to_visbrain_data ############################################################################### # LOAD YOUR FILE ############################################################################### download_file('sleep_rec.zip', unzip=True, astype='example_data') target_path = path_to_visbrain_data(folder='example_data') dfile = os.path.join(target_path, '1.rec') # Open the GUI : Sleep(data=dfile).show()
""" Load a BrainVision file ======================= This example demonstrate how to load a BrainVision file. Required dataset at : https://www.dropbox.com/s/t2bo9ufvc3f8mbj/sleep_brainvision.zip?dl=1 .. image:: ../../_static/examples/ex_LoadBrainVision.png """ import os from visbrain.gui import Sleep from visbrain.io import download_file, path_to_visbrain_data ############################################################################### # LOAD YOUR FILE ############################################################################### # Download dataset : download_file("sleep_brainvision.zip", unzip=True, astype='example_data') target_path = path_to_visbrain_data(folder='example_data') dfile = os.path.join(target_path, 'sub-02.vhdr') hfile = os.path.join(target_path, 'sub-02.hyp') cfile = os.path.join(target_path, 'sub-02_config.txt') # Open the GUI : Sleep(data=dfile, hypno=hfile, config_file=cfile).show()
Required dataset at : https://www.dropbox.com/s/bmfc2u55xsejbaf/sleep_matlab.zip?dl=1 .. image:: ../../_static/examples/ex_LoadMatlab.png """ import os import numpy as np from scipy.io import loadmat from visbrain.gui import Sleep from visbrain.io import download_file, path_to_visbrain_data ############################################################################### # LOAD YOUR FILE ############################################################################### # Download matlab file : download_file("sleep_matlab.zip", unzip=True, astype='example_data') target_path = path_to_visbrain_data(folder='example_data') # Load the matlab file : mat = loadmat(os.path.join(target_path, 's2_sleep.mat')) # Get the data, sampling frequency and channel names : raw_data = mat['data'] raw_sf = float(mat['sf']) raw_channels = np.concatenate(mat['channels'].flatten()).tolist() raw_hypno = mat['hypno'].flatten() # Open the GUI : Sleep(data=raw_data, sf=raw_sf, channels=raw_channels, hypno=raw_hypno).show()
"""This file shows how to use YASA in combination with Visbrain. """ import numpy as np from visbrain.gui import Sleep from yasa import spindles_detect, sw_detect # Load the data and hypnogram data = np.load('data_full_6hrs_100Hz_Cz+Fz+Pz.npz').get('data') ch_names = ['Cz', 'Fz', 'Pz'] hypno = np.load('data_full_6hrs_100Hz_hypno.npz').get('hypno') # Initialize a Visbrain.gui.Sleep instance sl = Sleep(data=data, channels=ch_names, sf=100, hypno=hypno) # Define spindles function def fcn_spindle(data, sf, time, hypno): """Replace Visbrain built-in spindles detection by YASA algorithm. See http://visbrain.org/sleep.html#use-your-own-detections-in-sleep """ # Apply on the full recording # sp = spindles_detect(data, sf) # NREM sleep only sp = spindles_detect(data, sf, hypno=hypno) return (sp[['Start', 'End']].values * sf).astype(int) # Define slow-waves function def fcn_sw(data, sf, time, hypno): """Replace Visbrain built-in slow-wave detection by YASA algorithm. """
def load_and_score( datasets, tStart=None, tEnd=None, downSample=100.0, ds_method="interpolation", EMGdatapath=None, kwargs_sleep={}, ): """Load data and run visbrain's Sleep. Args: datasets (list(dict)): List of dictionaries specifying the data to load. Each of the dictionaries specifies the data loaded from a specific dataset. For each of the dictionaries, the following keys are recognized: binPath (str | pathlib.Path): Path to bin of recording (mandatory) datatype (str): 'SGLX' , 'TDT' or 'OpenEphys' (default 'SGLX') chanList (list(str) | None): List of loaded channels. All channels are loaded by default. (default None) - for SGLX data: `chanList` is interpreted as labels of channels, eg:: ["LF0;384", "LF1;385"] - for TDT data: Values in ChanList should be string formatted as follows:: [<score_name>-<channel_index>, ...] Where channels are 1-indexed, (IMPORTANT) not 0-indexed (for consistency with tdt methods), eg:: [LFPs-1, LFPs-2, EEGs-1, EEGs-94, EMGs-1] chanLabelsMap (dict | None): {<channel>: <new_label>} Mapping used to redefine arbitrary labels for each of the loaded channels in chanList. If there is no entry in chanLabelsMap for one of the channels, or if chanLabelsMap is None, the displayed channel label is the original label as obtained from the recording metadata. Keys are values from chanList. (default None) name (str | None): Name of the dataset. If specified, prepended to the channel labels displayed in Sleep. Kwargs: downSample (int | float | None): Frequency in Hz at which all the data is subsampled. No subsampling if None (default 100.0) ds_method (str): Method for resampling. Passed to ``resample.signal_resample``. 'poly' is more accurate, 'interpolation' is faster (default 'interpolation') tStart (float | None): Time in seconds from start of recording of first loaded sample. Default 0.0 tEnd (float | None): Time in seconds from start of recording of last loaded sample. Duration of recording in None. (default None) EMGdatapath (str or None): Path to an EMG data file created using the `emg_from_lfp` package (<https://github.com/csc-UW/emg_from_lfp>). If possible, the EMG data will be loaded, the required time segment extracted, resampled to match the desired sampling rate, and appended to the data passed to `Sleep` kwargs_sleep (dict): Dictionary to pass to the `Sleep` instance during init. (default {}) """ DERIVED_EMG_CHANLABEL = "derivedEMG" # Mandatory and optional keys of each of the dictionaries in `datasets` DATASET_DICT_MANDATORY = ["binPath"] DATASET_DICT_OPTIONAL = { "datatype": "SGLX", "chanList": None, "chanLabelsMap": None, "name": None, } ############ # Load data from multiple datasets if not datasets: raise ValueError(f"`datasets` config entry should be a non-empty list.") print(f"\nLoading data from N={len(datasets)} datasets:\n") all_data_list = [] all_sf = [] chanLabels = [] for i, dataset_dict in enumerate(datasets): print( f"\nLoading dataset #{i+1}/{len(datasets)} from" f" {dataset_dict['binPath']}" ) # Validate and set default values dataset_dict = validation.validate( dataset_dict, mandatory=DATASET_DICT_MANDATORY, optional=DATASET_DICT_OPTIONAL, prefix="Validating `datasets` list item: ", ) # Preload and downsample specific parts of the data data, sf, chanOrigLabels = load.loader_switch( dataset_dict["binPath"], datatype=dataset_dict["datatype"], chanList=dataset_dict["chanList"], downSample=downSample, ds_method=ds_method, tStart=tStart, tEnd=tEnd, ) # Relabel channels and verbose which channels are used labels = relabel_channels(chanOrigLabels, dataset_dict["chanLabelsMap"]) # Prepend name of dataset if dataset_dict["name"] is not None and len(dataset_dict["name"]) >= 1: labels = [dataset_dict["name"] + "," + l for l in labels] print_used_channels(chanOrigLabels, labels) all_data_list.append(data) all_sf.append(sf) chanLabels += labels # Check consistency of data from different datasets # TODO: Load duration of shortest dataset if tEnd is None assert len(set(all_sf)) <= 1 assert len(set([data.shape[1] for data in all_data_list])) <= 1 data = np.concatenate(all_data_list, axis=0) ############ # Load and append the EMG if EMGdatapath: print("\nLoading the EMG") tEnd = data.shape[1] / sf # Will fail if EMG is shorter EMG_data, _ = emg_from_lfp.load_emg( EMGdatapath, tStart=tStart, tEnd=tEnd, desired_length=data.shape[1], ) # Load, select time points of interest and resample print("Combining data and derivedEMG") # At this point the EMG and data should have same number of samples and # same sf data = np.concatenate((data, EMG_data), axis=0) chanLabels.append(DERIVED_EMG_CHANLABEL) ############ # Call Sleep with loaded data print("\nCalling Sleep") Sleep(data=data, channels=chanLabels, sf=sf, **kwargs_sleep).show()
from visbrain.gui import Sleep from visbrain.io import download_file, path_to_visbrain_data from visbrain.tests._tests_visbrain import _TestVisbrain # File to load : sleep_file = path_to_visbrain_data('excerpt2.edf', 'example_data') hypno_file = path_to_visbrain_data('Hypnogram_excerpt2.txt', 'example_data') # Download sleep file : if not os.path.isfile(sleep_file): download_file('sleep_edf.zip', unzip=True, astype='example_data') onset = np.array([100, 2000, 5000]) # Create Sleep application : sp = Sleep(data=sleep_file, hypno=hypno_file, axis=True, annotations=onset) class TestSleep(_TestVisbrain): """Test sleep.py.""" ########################################################################### # TOOLS ########################################################################### def test_reference_switch(self): """Test function reference_switch.""" for k in [2]: # range(3) sp._ToolsRefMeth.setCurrentIndex(k) sp._fcn_ref_switch() sp._fcn_ref_apply() sp._fcn_ref_chan_ignore()
.. image:: ../../_static/examples/ex_LoadMNE.png """ import os from mne import io from visbrain.gui import Sleep from visbrain.io import download_file, path_to_visbrain_data ############################################################################### # LOAD YOUR FILE ############################################################################### # Download dataset : download_file("sleep_brainvision.zip", unzip=True, astype='example_data') target_path = path_to_visbrain_data(folder='example_data') dfile = os.path.join(target_path, 'sub-02.vhdr') hfile = os.path.join(target_path, 'sub-02.hyp') # Read raw data using MNE-python : raw = io.read_raw_brainvision(vhdr_fname=dfile, preload=True) # Extract data, sampling frequency and channels names data, sf, chan = raw._data, raw.info['sfreq'], raw.info['ch_names'] # Now, pass all the arguments to the Sleep module : Sleep(data=data, sf=sf, channels=chan, hypno=hfile).show() # Alternatively, these steps can be done automatically by using the 'use_mne' # input argument of sleep # Sleep(data=dfile, hypno=hfile, use_mne=True).show()
stim_env[0][evt[4]] = 1 raw.pick_channels(['LAH1']) info_amp = mne.create_info(['AMP'], raw.info['sfreq'], ['stim']) info_grad = mne.create_info(['GRAD'], raw.info['sfreq'], ['stim']) info_env = mne.create_info(['ENV'], raw.info['sfreq'], ['stim']) amp_raw = mne.io.RawArray(stim_amp, info_amp) grad_raw = mne.io.RawArray(stim_grad, info_grad) env_raw = mne.io.RawArray(stim_env, info_env) raw.load_data() raw.add_channels([amp_raw, grad_raw, env_raw], force_update_info=True) # raw.reorder_channels([selected_channel, 'AMP', 'GRAD', 'ENV']) # if original_sf > 1000: # raw.resample(500) sp = Sleep(data=raw._data, sf=raw.info['sfreq'], channels=raw.info['ch_names'], downsample=None) sp.replace_detections('peak', peak_index) # sp.replace_detections('spindle', spikes_index) sp.show() print('finish') # edf = 'C:\\Lilach\\402_for_tag.edf' # # raw = mne.io.read_raw_edf(edf) # # data, sf, chan = raw.get_data(), raw.info['sfreq'], raw.info['ch_names'] # # Sleep(data=data, sf=sf, channels=chan, annotations=raw.annotations).show() # # print(1)
""" Load ELAN files =============== This example demonstrate how to load an ELAN file. Required dataset at : https://www.dropbox.com/s/95xvdqivpgk90hg/sleep_elan.zip?dl=1 .. image:: ../../_static/examples/ex_LoadElan.png """ import os from visbrain.gui import Sleep from visbrain.io import download_file, path_to_visbrain_data ############################################################################### # LOAD YOUR FILE ############################################################################### # Download dataset : download_file("sleep_elan.zip", unzip=True, astype='example_data') target_path = path_to_visbrain_data(folder='example_data') dfile = os.path.join(target_path, 'sub-02.eeg') hfile = os.path.join(target_path, 'sub-02.hyp') # Open the GUI : Sleep(data=dfile, hypno=hfile).show()