** For operational convenience, I’m designing a PyQt5-based GUI plugin tool for brain functional connectivity using mne 1.6.1 and mne_connectivity 0.5.0. The original program runs normally before Nuitka packaging, but after compilation, an error occurs when calling mne.io.RawArray(data, info). Where is the problem and how can it be solved?**
- MNE version: e.g. 1.6.1
- operating system: Windows 11
-the source code:
-- coding: utf-8 --
import sys
import os
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtCore import pyqtSlot, pyqtSignal
import numpy as np
import re
import mne
import mne_connectivity
from mne.beamformer import make_lcmv, apply_lcmv_epochs
from mne_connectivity import envelope_correlation
from mne_connectivity.viz import plot_sensors_connectivity
from mne_connectivity import spectral_connectivity_epochs
from mne.datasets import fetch_fsaverage
from gui import connectivity_analysis_gui
eeg_path = “D:\ERPMaster\Data3422.txt”
mri_path = “D:\ERPMaster\mne_data\data”
fsaverage_dir = “D:\ERPMaster\mne_data\fsaverage”
subjects_dir = “D:\ERPMaster\mne_data\data\MNE-brainstorm-data\bst_resting\subjects”
eeg_path = os.path.abspath(eeg_path)
mri_path = os.path.abspath(mri_path)
fsaverage_dir = os.path.abspath(fsaverage_dir)
subjects_dir = os.path.abspath(subjects_dir)
os.environ[‘MNE_DATA’] = os.path.dirname(fsaverage_dir)
def read_data_into_matrix(eeg_path, chan_n):
try:
data =
skip_rows = 65
float_pattern = re.compile(r’-?\d+.\d+')
with open(eeg_path, 'r') as file:
for _ in range(skip_rows):
next(file)
for line in file:
floats = float_pattern.findall(line)
data.extend(map(float, floats))
total_len = len(data)
if total_len % chan_n != 0 and total_len < chan_n:
raise ValueError(f"文件中的数据不足。")
data = data[:total_len]
sample_n = int(total_len / chan_n)
data_matrix = np.array(data).reshape((chan_n, sample_n))
return data_matrix
except Exception as e:
print(f"Error in read_data_into_matrix: {e}")
return None
def crop_the_data(eeg_path, chan_n, sfreq, crop_tmin, crop_tmax):
try:
data = read_data_into_matrix(eeg_path, chan_n)
if data is None:
print(f"Error: read_data_into_matrix returned None for path {eeg_path}")
return None
ch_names = ['Fp1', 'Fp2', 'PO5', 'PO6', 'Fpz', 'AF3', 'AF4', 'AF7', 'AF8', 'F1', 'F2', 'F3', 'F4', 'F5',
'F6', 'F7', 'F8', 'Fz', 'FC1', 'FC2', 'FC3', 'FC4', 'FC5', 'FC6', 'FCz', 'FT7', 'FT8', 'C1',
'C2', 'C3', 'C4', 'C5', 'C6', 'Cz', 'T7', 'T8', 'CP1', 'CP2', 'CP3', 'CP4', 'CP5', 'CP6',
'CPz', 'TP7', 'TP8', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'Pz', 'PO3', 'PO4',
'PO7', 'PO8', 'POz', 'O1', 'O2', 'Oz', 'HEOG', 'VEOG']
ch_types = ['eeg'] * 62 + ['eog'] * 2
info = mne.create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
info.set_montage('standard_1005')
info['description'] = 'My custom dataset'
scalings = {'eeg': 0.0001, 'eog': 0.0001}
raw = mne.io.RawArray(data, info)
raw.apply_function(lambda x: x * 1e-6, channel_wise=False)
print(raw.info)
print(raw.info['ch_names'])
raw.plot(n_channels=chan_n, scalings=scalings, title='Data from matrix', show=True, block=True)
raw.plot_sensors(ch_type='eeg', show_names='True')
eeg_data = raw.pick_types(meg=False, eeg=True, eog=False, exclude='bads')
eeg_data.crop(crop_tmin, crop_tmax)
eeg_data.filter(l_freq=1.0, h_freq=40.0)
nchan = eeg_data.info['nchan']
print(f"EEG channel number:{nchan}")
print(eeg_data.info)
print(eeg_data.info['ch_names'])
return eeg_data
except Exception as e:
print(f"Error in crop_the_data: {e}")
return None
def crop_the_data1(eeg_path, chan_n, sfreq, crop_tmin, crop_tmax):
try:
data = read_data_into_matrix(eeg_path, chan_n)
if data is None:
print(f"Error: read_data_into_matrix returned None for path {eeg_path}")
return None
ch_names = ['Fp1', 'Fp2', 'PO5', 'PO6', 'Fpz', 'AF3', 'AF4', 'AF7', 'AF8', 'F1', 'F2', 'F3', 'F4', 'F5',
'F6', 'F7', 'F8', 'Fz', 'FC1', 'FC2', 'FC3', 'FC4', 'FC5', 'FC6', 'FCz', 'FT7', 'FT8', 'C1',
'C2', 'C3', 'C4', 'C5', 'C6', 'Cz', 'T7', 'T8', 'CP1', 'CP2', 'CP3', 'CP4', 'CP5', 'CP6',
'CPz', 'TP7', 'TP8', 'P1', 'P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'Pz', 'PO3', 'PO4',
'PO7', 'PO8', 'POz', 'O1', 'O2', 'Oz', 'HEOG', 'VEOG']
ch_types = ['eeg'] * 62 + ['eog'] * 2
info = mne.create_info(ch_names=ch_names, ch_types=ch_types, sfreq=sfreq)
info.set_montage('standard_1005')
info['description'] = 'My custom dataset'
scalings = {'eeg': 0.0001, 'eog': 0.0001}
raw = mne.io.RawArray(data, info)
raw.apply_function(lambda x: x * 1e-6, channel_wise=False)
print(raw.info)
print(raw.info['ch_names'])
eeg_data = raw.pick_types(meg=False, eeg=True, eog=False, exclude='bads')
eeg_data.crop(crop_tmin, crop_tmax)
eeg_data.filter(l_freq=1.0, h_freq=40.0)
nchan = eeg_data.info['nchan']
print(f"EEG channel number:{nchan}")
print(eeg_data.info)
print(eeg_data.info['ch_names'])
return eeg_data
except Exception as e:
print(f"Error in crop_the_data1: {e}")
return None
def source_volume_connecitivity(eeg_data, mri_path, low, high):
try:
subjects_dir = os.path.join(mri_path, ‘MNE-brainstorm-data’, ‘bst_resting’, ‘subjects’)
subject1 = ‘bst_resting’
print(subjects_dir)
default_dir = os.path.dirname(mri_path)
print(default_dir)
fs_dir = fetch_fsaverage(default_dir, verbose=True)
subjects_dir = os.path.dirname(fs_dir)
subject = 'fsaverage'
trans = 'fsaverage'
bem = os.path.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')
print("bem file directory:", bem)
print(eeg_data.ch_names)
montage = mne.channels.make_standard_montage('standard_1005')
eeg_data.set_montage(montage)
eeg_data.set_eeg_reference(projection=True)
new_events = mne.make_fixed_length_events(eeg_data, id=1, duration=2.0, overlap=0.5)
raw1 = eeg_data.copy()
raw1.load_data().resample(80)
raw1.apply_proj()
cov = mne.compute_raw_covariance(raw1)
raw1.filter(low, high)
events = mne.make_fixed_length_events(raw1, duration=5.)
epochs = mne.Epochs(raw1, events=events, tmin=0, tmax=5.,
baseline=None, reject=dict(eeg=200e-6), preload=True)
data_cov = mne.compute_covariance(epochs)
del raw1
pos = 15.
subjects_dir1 = os.path.join(mri_path, 'MNE-brainstorm-data', 'bst_resting', 'subjects')
print(subjects_dir1)
fs_dir = fetch_fsaverage(default_dir, verbose=True)
subjects_dir = os.path.dirname(fs_dir)
subject = 'bst_resting'
trans = 'fsaverage'
bem = os.path.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')
src = mne.setup_volume_source_space('bst_resting', pos, bem=bem,
subjects_dir=subjects_dir1, verbose=True)
fwd = mne.make_forward_solution(epochs.info, trans, src, bem)
filters = make_lcmv(epochs.info, fwd, data_cov, 0.05, cov,
pick_ori='max-power', weight_norm='nai')
del fwd, data_cov, cov
epochs.apply_hilbert()
stcs = apply_lcmv_epochs(epochs, filters, return_generator=True)
corr = envelope_correlation(stcs, verbose=True)
del stcs, epochs, filters
corr = corr.combine()
degree = mne_connectivity.degree(corr, 0.15)
stc = mne.VolSourceEstimate(degree, [src[0]['vertno']], 0, 1, 'bst_resting')
lims = [75, 85, 95]
kwargs = dict(src=src, subject=subject1, subjects_dir=subjects_dir1,
initial_time=0, verbose=True)
stc.plot(mode='stat_map', clim=dict(kind='percent', pos_lims=lims), **kwargs)
except Exception as e:
print(f"Error in source_volume_connecitivity: {e}")
def source_connectivity_glass(eeg_data, mri_path, low, high):
try:
subjects_dir = os.path.join(mri_path, ‘MNE-brainstorm-data’, ‘bst_resting’, ‘subjects’)
subject1 = ‘bst_resting’
print(subjects_dir)
default_dir = os.path.dirname(mri_path)
print(default_dir)
fs_dir = fetch_fsaverage(default_dir, verbose=True)
subjects_dir = os.path.dirname(fs_dir)
subject = 'fsaverage'
trans = 'fsaverage'
bem = os.path.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')
print(eeg_data.ch_names)
montage = mne.channels.make_standard_montage('standard_1005')
eeg_data.set_montage(montage)
eeg_data.set_eeg_reference(projection=True)
new_events = mne.make_fixed_length_events(eeg_data, id=1, duration=2.0, overlap=0.5)
raw1 = eeg_data.copy()
raw1.load_data().resample(80)
raw1.apply_proj()
cov = mne.compute_raw_covariance(raw1)
raw1.filter(low, high)
events = mne.make_fixed_length_events(raw1, duration=5.)
epochs = mne.Epochs(raw1, events=events, tmin=0, tmax=5.,
baseline=None, reject=dict(eeg=200e-6), preload=True)
data_cov = mne.compute_covariance(epochs)
del raw1
pos = 15.
subjects_dir1 = os.path.join(mri_path, 'MNE-brainstorm-data', 'bst_resting', 'subjects')
print(subjects_dir1)
fs_dir = fetch_fsaverage(default_dir, verbose=True)
subjects_dir = os.path.dirname(fs_dir)
subject = 'bst_resting'
trans = 'fsaverage'
bem = os.path.join(fs_dir, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif')
src = mne.setup_volume_source_space('bst_resting', pos, bem=bem,
subjects_dir=subjects_dir1, verbose=True)
fwd = mne.make_forward_solution(epochs.info, trans, src, bem)
filters = make_lcmv(epochs.info, fwd, data_cov, 0.05, cov,
pick_ori='max-power', weight_norm='nai')
del fwd, data_cov, cov
epochs.apply_hilbert()
stcs = apply_lcmv_epochs(epochs, filters, return_generator=True)
corr = envelope_correlation(stcs, verbose=True)
del stcs, epochs, filters
corr = corr.combine()
degree = mne_connectivity.degree(corr, 0.15)
stc = mne.VolSourceEstimate(degree, [src[0]['vertno']], 0, 1, 'bst_resting')
brain = stc.plot(
src, clim=dict(kind='percent', lims=[75, 85, 95]), colormap='gnuplot',
subjects_dir=subjects_dir1, mode='glass_brain')
except Exception as e:
print(f"Error in source_connectivity_glass: {e}")
def brain_sensor_connectivity(eeg_data, low, high):
try:
print(eeg_data.ch_names)
montage = mne.channels.make_standard_montage('standard_1005')
eeg_data.set_montage(montage)
eeg_data.set_eeg_reference(projection=True)
new_events = mne.make_fixed_length_events(eeg_data, id=1, duration=2.0, overlap=0.5)
epochs = mne.Epochs(eeg_data, new_events)
event_id = 1
tmin, tmax = -0.2, 1.5
sfreq = eeg_data.info['sfreq']
tmin = 0.0
eeg_data.pick(['eeg'])
con = spectral_connectivity_epochs(
epochs, method='wpli', mode='multitaper', sfreq=sfreq, fmin=low, fmax=high,
faverage=True, tmin=tmin, mt_adaptive=False, n_jobs=1)
plot_sensors_connectivity(
epochs.info,
con.get_data(output='dense')[:, :, 0])
except Exception as e:
print(f"Error in brain_sensor_connectivity: {e}")
class QmyWidget(QWidget):
numberSignal = pyqtSignal(int)
def __init__(self, parent=None):
super().__init__(parent)
self.ui = connectivity_analysis_gui.Ui_Form()
self.ui.setupUi(self)
self.ui.eeg_path.setText(eeg_path)
self.ui.mri_path.setText(mri_path)
@pyqtSlot()
def on_btnElectrodeConn_clicked(self):
try:
s1 = self.ui.eeg_path.text()
eeg_path = str(s1)
print(eeg_path)
s3 = self.ui.ch_n.text()
chan_n = int(s3)
print(chan_n)
s4 = self.ui.sfreq.text()
sfreq = int(s4)
print(sfreq)
s5 = self.ui.crop_tmin.text()
crop_tmin = str(s5)
print(crop_tmin)
crop_tmin = float(crop_tmin[0:])
s6 = self.ui.crop_tmax.text()
crop_tmax = str(s6)
print(crop_tmax)
crop_tmax = float(crop_tmax[0:])
s7 = self.ui.low.text()
low = str(s7)
low = float(low[0:])
print(low)
s8 = self.ui.high.text()
high = str(s8)
high = float(high[0:])
print(high)
eeg_data = crop_the_data(eeg_path, chan_n, sfreq, crop_tmin, crop_tmax)
if eeg_data is not None:
brain_sensor_connectivity(eeg_data, low, high)
except Exception as e:
print(f"Error in on_btnElectrodeConn_clicked: {e}")
@pyqtSlot()
def on_btnGlassTrans_clicked(self):
try:
s1 = self.ui.eeg_path.text()
eeg_path = str(s1)
s2 = self.ui.mri_path.text()
mri_path = str(s2)
s3 = self.ui.ch_n.text()
chan_n = int(s3)
print(chan_n)
s4 = self.ui.sfreq.text()
sfreq = int(s4)
print(sfreq)
s5 = self.ui.crop_tmin.text()
crop_tmin = str(s5)
print(crop_tmin)
crop_tmin = float(crop_tmin[0:])
s6 = self.ui.crop_tmax.text()
crop_tmax = str(s6)
print(crop_tmax)
crop_tmax = float(crop_tmax[0:])
s7 = self.ui.low.text()
low = str(s7)
low = float(low[0:])
print(low)
s8 = self.ui.high.text()
high = str(s8)
high = float(high[0:])
print(high)
eeg_data = crop_the_data1(eeg_path, chan_n, sfreq, crop_tmin, crop_tmax)
if eeg_data is not None:
source_connectivity_glass(eeg_data, mri_path, low, high)
except Exception as e:
print(f"Error in on_btnGlassTrans_clicked: {e}")
@pyqtSlot()
def on_btnMRISlice_clicked(self):
try:
s1 = self.ui.eeg_path.text()
eeg_path = str(s1)
s2 = self.ui.mri_path.text()
mri_path = str(s2)
s3 = self.ui.ch_n.text()
chan_n = int(s3)
print(chan_n)
s4 = self.ui.sfreq.text()
sfreq = int(s4)
print(sfreq)
s5 = self.ui.crop_tmin.text()
crop_tmin = str(s5)
print(crop_tmin)
crop_tmin = float(crop_tmin[0:])
s6 = self.ui.crop_tmax.text()
crop_tmax = str(s6)
print(crop_tmax)
crop_tmax = float(crop_tmax[0:])
s7 = self.ui.low.text()
low = str(s7)
low = float(low[0:])
print(low)
s8 = self.ui.high.text()
high = str(s8)
high = float(high[0:])
print(high)
eeg_data = crop_the_data1(eeg_path, chan_n, sfreq, crop_tmin, crop_tmax)
if eeg_data is not None:
source_volume_connecitivity(eeg_data, mri_path, low, high)
except Exception as e:
print(f"Error in on_btnMRISlice_clicked: {e}")
if name == “main”:
app = QApplication(sys.argv)
myWindow = QmyWidget()
myWindow.show()
n = app.exec()
sys.exit(n)