def cli(matfiles, savename, rec_type, infosrc): """ Convert brainstorm epochs to mne.Epochs object """ if infosrc: if rec_type is 'ds': from mne.io import read_raw_ctf as read_raw elif rec_type is 'fif': from mne.io import Raw as read_raw with nostdout(): raw_with_info = read_raw(infosrc) isFirst = True for fname in matfiles: with nostdout(): mat_epoch = sio.loadmat(fname) # click.echo(mat_epoch) if isFirst: data = mat_epoch['F'] times = mat_epoch['Time'] # print times[0,-1] isFirst = False else: data = np.dstack((data, mat_epoch['F'])) # click.echo(data.shape) data = data.transpose((2,0,1)) n_channels = data.shape[1] sfreq = times.shape[1] / (times[0,-1] + times[0,1]) if infosrc: if rec_type is 'ds': from mne.io import read_raw_ctf as read_raw elif rec_type is 'fif': from mne.io import Raw as read_raw with nostdout(): raw_with_info = read_raw(infosrc) good_info = raw_with_info.info # click.echo(len(good_info['ch_names'])) ch_types = [channel_type(good_info, idx) for idx in range(n_channels)] # click.echo(len(ch_types)) info = create_info(ch_names=good_info['ch_names'], sfreq=sfreq, ch_types=ch_types) else: ch_types='mag' info = create_info(n_channels, sfreq, ch_types) with nostdout(): epochs = EpochsArray(data, info) epochs.save(savename)
def test_filter_raw(self) -> None: from mne.io import read_raw from meeg_tools.utils.raw import filter_raw from meeg_tools.utils.config import settings settings["bandpass_filter"]["low_freq"] = 1 settings["bandpass_filter"]["high_freq"] = 30 raw = read_raw(fname=self.raw_file_path) raw_filtered = filter_raw(raw) assert raw_filtered.info["highpass"] == 1.0 assert raw_filtered.info["lowpass"] == 30.0 settings["bandpass_filter"]["low_freq"] = 5 settings["bandpass_filter"]["high_freq"] = 45 raw_filtered = filter_raw(raw) assert raw_filtered.info["highpass"] == 5.0 assert raw_filtered.info["lowpass"] == 45.0 assert raw.info["highpass"] != raw_filtered.info["highpass"] assert raw.info["lowpass"] != raw_filtered.info["lowpass"]
def read_raw_measurement(raw_file_path: str, **kwargs): """ Read raw EEG file from the given path. Parameters ---------- raw_file_path: the full path to the EEG file locs_file_path: the full path to the channel locations file (optional) Returns ------- Raw instance """ raw_file_path = Path(raw_file_path) extension = raw_file_path.suffixes try: raw = read_raw(str(raw_file_path), preload=False, verbose=True) except Exception as e: if ".edf" in str(e): raw = read_raw_edf(str(raw_file_path), preload=False, verbose=True) else: logger.error(f"Unsupported file type ({extension})") return # Session parameters raw_id = raw_file_path.stem raw.info.update(temp=raw_id) if not bool(raw.get_montage()): logger.info(f"Channel locations are missing from the file") try: path_to_locs = kwargs["locs_file_path"] raw = set_raw_montage_from_locs(raw=raw, path_to_locs=path_to_locs, show_montage=False) except Exception as e: logger.error(e) return raw logger.info(raw.info) return raw
def concat_raws_with_suffix(path_to_raw_files: str, suffix: str) -> Raw: """ Concatenates raw measurement files with a given suffix (e.g. ".vhdr") from a folder. File namings should follow an order e.g. the first part of the measurement is "eeg_1.vhdr" and the second part is "eeg_1_2.vhdr". Returns the concatenated instance as if it was a continuous measurement. Parameters ---------- path_to_raw_files: str The path to the folder where the raw files are located. suffix: str The name of the file extension (e.g. ".vhdr", ".edf") Returns ------- Raw instance """ raw_file_path = Path(path_to_raw_files) file_names_in_order = sorted( [f.stem for f in raw_file_path.rglob("*.*") if f.suffix == suffix]) files = [ str(f) for file_name in file_names_in_order for f in raw_file_path.rglob(f"{file_name}{suffix}") ] logger.info( f"Found {len(file_names_in_order)} files with {suffix} extension:\n" f"{', '.join(files)}") raws = [read_raw(file, preload=False, verbose=True) for file in files] raw = concatenate_raws(raws) # Session parameters raw_id = file_names_in_order[0] raw.info.update(temp=raw_id) logger.info(raw.info) return raw
def test_read_raw_supported(fname): """Test supported file types.""" read_raw(fname) read_raw(fname, verbose=False) raw = read_raw(fname, preload=True) assert "data loaded" in str(raw)
def test_read_raw_suggested(fname): """Test handling of unsupported file types with suggested alternatives.""" with pytest.raises(ValueError, match='Try reading'): read_raw(fname)
def test_read_raw_unsupported(fname): """Test handling of unsupported file types.""" with pytest.raises(ValueError, match='Unsupported file type'): read_raw(fname)
def __enter__(self) -> Raw: self.reader = read_raw(self.file.path) tmax = self.reader.n_times / self.reader.info["sfreq"] - 0.1 tmax = tmax if self.end > tmax else self.end self.reader.crop(self.begin, tmax) return self.reader
def setUp(self) -> None: self.raw_file_path = os.path.join(datasets.sample.data_path(), "MEG", "sample", "sample_audvis_raw.fif") self.raw = read_raw(fname=self.raw_file_path)
def __enter__(self) -> Raw: self.reader = read_raw(self.path) return self.reader
def setUp(self) -> None: self.raw_file_path = os.path.join(datasets.sample.data_path(), "MEG", "sample", "sample_audvis_raw.fif") self.raw = read_raw(fname=self.raw_file_path) self.epochs = create_epochs(self.raw).load_data().pick_types(eeg=True)
import numpy as np from mne.io import read_raw import matplotlib.pyplot as plt import time datasets = [] # need_channels=['FZ','FC1','FC2','C3','CZ','C4','CP1','CP2','P7','P3','PZ','P4','P8','O1','OZ','O2'] # need_channels=['Fz' for i in range(33)] need_channels = [ 'FP1', 'FPZ', 'FP2', 'AF3', 'AF4', 'F7', 'F5', 'F3', 'F1', 'FZ', 'F2', 'F4', 'F6', 'F8', 'FT7', 'FC5', 'FC3', 'FC1', 'FCZ', 'FC2', 'FC4', 'FC6', 'FT8', 'T7', 'C5', 'C3', 'C1', 'CZ', 'C2', 'C4', 'C6', 'T8', 'M1', 'TP7', 'CP5', 'CP3', 'CP1', 'CPZ', 'CP2', 'CP4', 'CP6', 'TP8', 'M2', 'P7', 'P5', 'P3', 'P1', 'PZ', 'P2', 'P4', 'P6', 'P8', 'PO7', 'PO5', 'PO3', 'POZ', 'PO4', 'PO6', 'PO8', 'CB1', 'O1', 'OZ', 'O2', 'CB2' ] data = read_raw("data/lgw.cnt", preload=True) datasets.insert(0, data) datasets.insert(1, deepcopy(data)) data = datasets[1] data.pick_channels(need_channels, ordered=True) # data.filter(1.0, 40.0) data, _ = data[:, :] print(data.shape) data = data.astype(np.float32).T data = np.ascontiguousarray(data) mbytes = BytesIO() mbytes.write(data) import socket import os #声明类型,生成socket链接对象 server = socket.socket()