mirror of
https://github.com/YuTaoV5/YuEEG.git
synced 2025-09-26 23:09:24 +08:00
update new plot.py
This commit is contained in:
parent
1484e7f1f9
commit
03e338463c
2
.idea/YuEEG.iml
generated
2
.idea/YuEEG.iml
generated
@ -2,7 +2,7 @@
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="jdk" jdkName="SSVEP" jdkType="Python SDK" />
|
||||
<orderEntry type="jdk" jdkName="EEG" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
5
.idea/misc.xml
generated
5
.idea/misc.xml
generated
@ -1,4 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="SSVEP" project-jdk-type="Python SDK" />
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="EEG" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="EEG" project-jdk-type="Python SDK" />
|
||||
</project>
|
196
Software/neo_plot_only.py
Normal file
196
Software/neo_plot_only.py
Normal file
@ -0,0 +1,196 @@
|
||||
import sys
|
||||
import time
|
||||
import numpy as np
|
||||
import re
|
||||
from PyQt5 import QtWidgets, QtCore, QtGui
|
||||
import pyqtgraph as pg
|
||||
import serial
|
||||
import serial.tools.list_ports
|
||||
from scipy.signal import butter, lfilter, lfilter_zi
|
||||
|
||||
# 配置参数
|
||||
DATA_LENGTH = 2000 # 数据缓存长度
|
||||
PLOT_LENGTH = 750 # 显示数据长度
|
||||
UPDATE_INTERVAL = 30 # 界面刷新间隔(ms)
|
||||
SAMPLE_RATE = 500 # 采样率
|
||||
FILTER_CUTOFF = 45 # 低通滤波截止频率
|
||||
|
||||
|
||||
class SerialThread(QtCore.QThread):
|
||||
data_received = QtCore.pyqtSignal(str)
|
||||
|
||||
def __init__(self, com_port):
|
||||
super().__init__()
|
||||
self.com_port = com_port
|
||||
self.serial_port = None
|
||||
self.running = False
|
||||
|
||||
# 环形缓冲区初始化
|
||||
self.data_buffer = np.full((9, DATA_LENGTH), np.nan, dtype=np.float32)
|
||||
self.write_index = 0
|
||||
self.buffer_filled = False
|
||||
|
||||
# 滤波器初始化
|
||||
nyquist = 0.5 * SAMPLE_RATE
|
||||
self.filter_b, self.filter_a = butter(5, FILTER_CUTOFF / nyquist, btype='low')
|
||||
self.filter_zi = [lfilter_zi(self.filter_b, self.filter_a) for _ in range(9)]
|
||||
|
||||
def run(self):
|
||||
self.running = True
|
||||
try:
|
||||
self.serial_port = serial.Serial(self.com_port, baudrate=115200, timeout=1)
|
||||
self.serial_port.write(b'1') # 启动数据传输
|
||||
|
||||
while self.running:
|
||||
if self.serial_port.in_waiting:
|
||||
raw_data = self.serial_port.readline().decode('utf-8', errors='ignore').strip()
|
||||
self.data_received.emit(raw_data)
|
||||
|
||||
# 改进的正则表达式匹配
|
||||
if match := re.match(r'^Channel:(-?\d+\.?\d*,){8}-?\d+\.?\d*$', raw_data):
|
||||
values = list(map(float, raw_data.split('Channel:')[1].split(',')))
|
||||
self._update_buffer(values)
|
||||
finally:
|
||||
if self.serial_port and self.serial_port.is_open:
|
||||
self.serial_port.close()
|
||||
|
||||
def _update_buffer(self, values):
|
||||
for i in range(9):
|
||||
# 单样本滤波处理
|
||||
filtered, self.filter_zi[i] = lfilter(
|
||||
self.filter_b,
|
||||
self.filter_a,
|
||||
[values[i]],
|
||||
zi=self.filter_zi[i]
|
||||
)
|
||||
# 确保取出单个元素
|
||||
self.data_buffer[i, self.write_index % DATA_LENGTH] = filtered[0]
|
||||
|
||||
self.write_index += 1
|
||||
if self.write_index >= DATA_LENGTH:
|
||||
self.buffer_filled = True
|
||||
self.write_index %= DATA_LENGTH
|
||||
|
||||
def get_plot_data(self):
|
||||
if self.write_index < PLOT_LENGTH:
|
||||
return self.data_buffer[:, :self.write_index]
|
||||
|
||||
start = (self.write_index - PLOT_LENGTH) % DATA_LENGTH
|
||||
end = self.write_index % DATA_LENGTH
|
||||
|
||||
if start < end:
|
||||
return self.data_buffer[:, start:end]
|
||||
else:
|
||||
return np.hstack((self.data_buffer[:, start:], self.data_buffer[:, :end]))
|
||||
|
||||
def stop(self):
|
||||
self.running = False
|
||||
self.wait(2000)
|
||||
|
||||
|
||||
class ADCPlotter(QtWidgets.QMainWindow):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("YuEEG Data Viewer")
|
||||
self.setWindowIcon(QtGui.QIcon('./school_logo.ico'))
|
||||
|
||||
# 初始化UI
|
||||
self._setup_ui()
|
||||
|
||||
# 初始化串口线程
|
||||
if not (com_port := self._detect_com_port()):
|
||||
QtWidgets.QMessageBox.critical(self, "错误", "未检测到可用串口")
|
||||
sys.exit(1)
|
||||
|
||||
self.serial_thread = SerialThread(com_port)
|
||||
self.serial_thread.data_received.connect(self._append_serial_data)
|
||||
|
||||
# 启动线程和定时器
|
||||
self.serial_thread.start()
|
||||
self._start_timers()
|
||||
|
||||
def _setup_ui(self):
|
||||
self.central_widget = QtWidgets.QWidget()
|
||||
self.setCentralWidget(self.central_widget)
|
||||
layout = QtWidgets.QVBoxLayout(self.central_widget)
|
||||
|
||||
# 绘图区域
|
||||
self.plot_widget = pg.PlotWidget()
|
||||
self.plot_widget.setAntialiasing(True)
|
||||
self.plot_widget.useOpenGL(True)
|
||||
self.plot_widget.setLabel('bottom', 'Samples')
|
||||
self.plot_widget.setLabel('left', 'Amplitude')
|
||||
self.plot_widget.showGrid(x=True, y=True, alpha=0.3)
|
||||
layout.addWidget(self.plot_widget)
|
||||
|
||||
# 初始化曲线
|
||||
colors = ['#FF0000', '#00FF00', '#0000FF', '#00FFFF',
|
||||
'#FF00FF', '#FFFF00', '#FFFFFF', '#A0A0A0', '#FFA500']
|
||||
self.plots = []
|
||||
for i, color in enumerate(colors):
|
||||
plot = self.plot_widget.plot(pen=pg.mkPen(color, width=1.5))
|
||||
self.plots.append(plot)
|
||||
|
||||
# 图例
|
||||
self.legend = pg.LegendItem(offset=(70, 20))
|
||||
self.legend.setParentItem(self.plot_widget.getPlotItem())
|
||||
for i, plot in enumerate(self.plots):
|
||||
self.legend.addItem(plot, f'CH{i + 1}')
|
||||
|
||||
# 控制面板
|
||||
control_layout = QtWidgets.QHBoxLayout()
|
||||
self.checkboxes = [QtWidgets.QCheckBox(f"CH{i + 1}") for i in range(9)]
|
||||
for cb in self.checkboxes:
|
||||
cb.setChecked(True)
|
||||
control_layout.addWidget(cb)
|
||||
layout.addLayout(control_layout)
|
||||
self.checkboxes[0].setChecked(False)
|
||||
|
||||
def _start_timers(self):
|
||||
self.plot_timer = QtCore.QTimer()
|
||||
self.plot_timer.timeout.connect(self._update_plot)
|
||||
self.plot_timer.start(UPDATE_INTERVAL)
|
||||
|
||||
def _update_plot(self):
|
||||
data = self.serial_thread.get_plot_data()
|
||||
if data.size == 0:
|
||||
return
|
||||
|
||||
# 动态调整Y轴范围
|
||||
active_channels = [i for i, cb in enumerate(self.checkboxes) if cb.isChecked()]
|
||||
if not active_channels:
|
||||
return
|
||||
|
||||
visible_data = data[active_channels]
|
||||
y_min = np.nanmin(visible_data)
|
||||
y_max = np.nanmax(visible_data)
|
||||
if np.isnan(y_min) or np.isnan(y_max):
|
||||
return
|
||||
|
||||
margin = (y_max - y_min) * 0.1 or 1.0
|
||||
self.plot_widget.setYRange(y_min - margin, y_max + margin, padding=0)
|
||||
|
||||
# 更新曲线数据
|
||||
for i in active_channels:
|
||||
self.plots[i].setData(data[i])
|
||||
|
||||
def _append_serial_data(self, text):
|
||||
self.statusBar().showMessage(text[-200:], 2000)
|
||||
|
||||
def _detect_com_port(self):
|
||||
ports = serial.tools.list_ports.comports()
|
||||
for p in ports:
|
||||
if 'USB' in p.description:
|
||||
return p.device
|
||||
return None
|
||||
|
||||
def closeEvent(self, event):
|
||||
self.serial_thread.stop()
|
||||
event.accept()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app = QtWidgets.QApplication(sys.argv)
|
||||
window = ADCPlotter()
|
||||
window.show()
|
||||
sys.exit(app.exec_())
|
@ -1,271 +0,0 @@
|
||||
import sys
|
||||
import time
|
||||
from PyQt5 import QtWidgets, QtCore
|
||||
from collections import deque
|
||||
import pyqtgraph as pg
|
||||
import serial
|
||||
import serial.tools.list_ports
|
||||
import re
|
||||
import numpy as np
|
||||
from PyQt5.QtGui import QIcon
|
||||
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout
|
||||
from pyqtgraph import LegendItem
|
||||
from qfluentwidgets import LineEdit, PushButton, TextEdit, CheckBox
|
||||
from scipy.signal import welch, butter, filtfilt
|
||||
|
||||
# Set the length of the data pool to handle 750 samples (3 seconds of data at 250Hz)
|
||||
data_len = 2000
|
||||
|
||||
|
||||
class SerialThread(QtCore.QThread):
|
||||
data_received = QtCore.pyqtSignal(str) # Signal to send data back to the main thread
|
||||
|
||||
def __init__(self, com_port):
|
||||
super().__init__()
|
||||
self.com_port = com_port
|
||||
self.serial_port = serial.Serial(self.com_port, baudrate=115200, timeout=1)
|
||||
self.data_pool = [deque(maxlen=data_len) for _ in range(9)] # Data pool for each channel
|
||||
self.running = True
|
||||
|
||||
def run(self):
|
||||
self.serial_port.write(b'1') # Send '1' to start data transmission
|
||||
while self.running:
|
||||
if self.serial_port.in_waiting:
|
||||
try:
|
||||
raw_data = self.serial_port.readline().decode('utf-8').strip()
|
||||
if raw_data:
|
||||
# Emit the raw data to the main thread for display
|
||||
self.data_received.emit(raw_data)
|
||||
# print(f"{raw_data}")
|
||||
# Integrity check (matches 'Channel:' followed by 9 float values)
|
||||
match = re.match(r'Channel:([\d\.\-]+,){8}[\d\.\-]+', raw_data)
|
||||
if match:
|
||||
values = [float(x) for x in raw_data.split('Channel:')[1].split(',')]
|
||||
# Add data to the pool for each channel
|
||||
for i in range(9):
|
||||
self.data_pool[i].append(values[i])
|
||||
except:
|
||||
pass
|
||||
|
||||
def stop(self):
|
||||
self.running = False
|
||||
self.serial_port.close()
|
||||
|
||||
def send_data(self, data):
|
||||
self.serial_port.write(data.encode('utf-8') + b'\r\n') # 发送数据到串口
|
||||
|
||||
def get_latest_data(self, size):
|
||||
"""Return the latest 'size' data from the data pool for all channels."""
|
||||
if size > len(self.data_pool[0]):
|
||||
raise ValueError("Requested size is larger than the current data pool size.")
|
||||
|
||||
# Convert the latest 'size' elements from deque to numpy array for each channel
|
||||
return np.array([list(self.data_pool[i])[-size:] for i in range(9)])
|
||||
|
||||
|
||||
class ADCPlotter(QtWidgets.QMainWindow):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.setWindowTitle("YuEEG Data Viewer")
|
||||
self.setWindowIcon(QIcon('./school_logo.ico'))
|
||||
self.setGeometry(100, 100, 800, 750)
|
||||
# Detect available COM ports and connect to the first available one
|
||||
com_port = self.detect_com_port()
|
||||
print(f"Connected to: {com_port}")
|
||||
if not com_port:
|
||||
raise Exception("No available COM ports detected.")
|
||||
|
||||
# Main layout
|
||||
self.central_widget = QtWidgets.QWidget()
|
||||
self.setCentralWidget(self.central_widget)
|
||||
self.layout = QtWidgets.QVBoxLayout(self.central_widget)
|
||||
|
||||
# Set up PyQtGraph plot
|
||||
self.plot_widget = pg.PlotWidget()
|
||||
self.layout.addWidget(self.plot_widget)
|
||||
# Create a legend
|
||||
self.legend = LegendItem(offset=(30, -30)) # Position the legend in the plot area
|
||||
self.legend.setParentItem(self.plot_widget.graphicsItem())
|
||||
# Create colored plots with thicker lines for each channel
|
||||
self.colors = ['r', 'g', 'b', 'c', 'm', 'y', 'w', 'grey', 'orange']
|
||||
self.plot_data = []
|
||||
for i in range(9):
|
||||
plot_item = self.plot_widget.plot(pen=pg.mkPen(color=self.colors[i], width=2))
|
||||
self.plot_data.append(plot_item)
|
||||
self.legend.addItem(plot_item, f"Channel {i + 1}") # Add each plot to the legend with a label
|
||||
|
||||
# Add a QTextEdit widget to display the raw data received
|
||||
self.text_box = TextEdit(self)
|
||||
self.text_box.setReadOnly(True)
|
||||
|
||||
self.send_text = LineEdit()
|
||||
self.send_button = PushButton("Send")
|
||||
self.adc_button = PushButton("Normal")
|
||||
self.adc_button.clicked.connect(self.mod_switch)
|
||||
self.send_button.clicked.connect(self.send_data)
|
||||
sendV_layout = QHBoxLayout()
|
||||
sendV_layout.addWidget(self.adc_button)
|
||||
sendV_layout.addWidget(self.send_text)
|
||||
sendV_layout.addWidget(self.send_button)
|
||||
|
||||
self.layout.addWidget(self.text_box)
|
||||
self.layout.addLayout(sendV_layout)
|
||||
|
||||
# Add checkboxes for selecting channels to display
|
||||
self.checkboxes = []
|
||||
self.checkbox_layout = QHBoxLayout()
|
||||
for i in range(9):
|
||||
checkbox = CheckBox(f"通道{i + 1}")
|
||||
checkbox.setChecked(True) # All channels checked by default
|
||||
self.checkboxes.append(checkbox)
|
||||
self.checkbox_layout.addWidget(checkbox)
|
||||
|
||||
self.layout.addLayout(self.checkbox_layout)
|
||||
|
||||
# Create a thread to handle serial data reception
|
||||
self.serial_thread = SerialThread(com_port)
|
||||
self.serial_thread.data_received.connect(self.handle_serial_data)
|
||||
self.serial_thread.start()
|
||||
|
||||
# Timer to refresh plot every 20ms
|
||||
self.timer = QtCore.QTimer()
|
||||
self.timer.timeout.connect(self.update_plot)
|
||||
self.timer.start(100)
|
||||
self.beg = time.time()
|
||||
self.previous_psd = None
|
||||
|
||||
def send_data(self):
|
||||
data = self.send_text.text()
|
||||
self.serial_thread.send_data(data)
|
||||
|
||||
def mod_switch(self):
|
||||
if self.adc_button.text() == "Normal":
|
||||
self.serial_thread.send_data("3")
|
||||
self.adc_button.setText("Test")
|
||||
elif self.adc_button.text() == "Test":
|
||||
self.serial_thread.send_data("1")
|
||||
self.adc_button.setText("Normal")
|
||||
def detect_com_port(self):
|
||||
"""Automatically detect available COM ports, excluding virtual ports."""
|
||||
ports = list(serial.tools.list_ports.comports())
|
||||
for port in ports:
|
||||
if 'Bluetooth' not in port.description and 'Virtual' not in port.description:
|
||||
return port.device
|
||||
return None
|
||||
|
||||
def append_text_box(self, text):
|
||||
"""Append text to the text box, keeping only the last 10 lines."""
|
||||
current_text = self.text_box.toPlainText()
|
||||
lines = current_text.split('\n')
|
||||
|
||||
# Append new text
|
||||
lines.append(text)
|
||||
|
||||
# Keep only the last 10 lines
|
||||
if len(lines) > 10:
|
||||
lines = lines[-10:]
|
||||
|
||||
# Update the text box
|
||||
self.text_box.setPlainText('\n'.join(lines))
|
||||
# Move the cursor to the end
|
||||
# self.text_box.moveCursor(QtCore.QTextCursor.End)
|
||||
def check_psd(self, data, fs):
|
||||
threshold = 50
|
||||
if data is not None:
|
||||
psd_values = self.compute_psd(data, fs)
|
||||
current_psd_sum = np.sum(psd_values)
|
||||
if self.previous_psd is not None:
|
||||
# 比较当前PSD总和与上次总和的变化是否超过阈值
|
||||
if threshold < current_psd_sum - self.previous_psd < 500:
|
||||
print(f"发现向上突变,目前差值为:{(current_psd_sum - self.previous_psd)}")
|
||||
return True
|
||||
else:
|
||||
print(f"差值为:{current_psd_sum - self.previous_psd}")
|
||||
self.previous_psd = current_psd_sum
|
||||
def compute_psd(self, data, fs):
|
||||
# 定义感兴趣的频率范围
|
||||
low_freq = 3
|
||||
high_freq = 40
|
||||
|
||||
# 存储每个通道在3-40Hz的PSD值
|
||||
psd_values = []
|
||||
|
||||
for i in range(data.shape[0]):
|
||||
# 计算功率谱密度
|
||||
f, psd = welch(data[i, :], fs, nperseg=500)
|
||||
|
||||
# 只保留3到40Hz的频段
|
||||
freq_mask = (f >= low_freq) & (f <= high_freq)
|
||||
psd_in_band = psd[freq_mask]
|
||||
|
||||
# 计算3到40Hz频段内的PSD值(通过对频段内的PSD进行积分)
|
||||
psd_band_value = np.trapz(psd_in_band, f[freq_mask])
|
||||
|
||||
# 将结果存储起来
|
||||
psd_values.append(psd_band_value)
|
||||
return psd_values
|
||||
def handle_serial_data(self, raw_data):
|
||||
"""Handle data received from the serial thread."""
|
||||
self.append_text_box(raw_data)
|
||||
|
||||
# 定义 Buterworth 滤波器函数
|
||||
def apply_lowpass_filter(self, signal, cutoff_freq=50, sample_rate=500, order=5):
|
||||
nyquist_freq = 0.5 * sample_rate
|
||||
normalized_cutoff_freq = cutoff_freq / nyquist_freq
|
||||
b, a = butter(order, normalized_cutoff_freq, btype='low', analog=False)
|
||||
filtered_signal = filtfilt(b, a, signal)
|
||||
return filtered_signal
|
||||
|
||||
def update_plot(self):
|
||||
"""Update the plot based on the current data in the data pool."""
|
||||
try:
|
||||
# Fetch the latest 750 samples from the serial thread data pool
|
||||
latest_data = self.serial_thread.get_latest_data(data_len)
|
||||
|
||||
|
||||
# Update the plot for each channel
|
||||
for i in range(9):
|
||||
if self.checkboxes[i].isChecked(): # Only update if the channel is checked
|
||||
waveform = latest_data[i]
|
||||
filtered_waveform = self.apply_lowpass_filter(waveform)
|
||||
self.plot_data[i].setData(filtered_waveform)
|
||||
else:
|
||||
self.plot_data[i].setData([]) # Hide the waveform by clearing the data
|
||||
# self.plot_data[7].setData(latest_data[7])
|
||||
# Collect data from only the selected channels
|
||||
selected_data = [latest_data[i] for i in range(9) if self.checkboxes[i].isChecked()]
|
||||
|
||||
# If there is any selected data, calculate global min and max
|
||||
if selected_data:
|
||||
global_min = np.min([np.min(data) for data in selected_data])
|
||||
global_max = np.max([np.max(data) for data in selected_data])
|
||||
# Set Y-axis range based on global min/max values
|
||||
self.plot_widget.setYRange(global_min, global_max)
|
||||
else:
|
||||
global_min = -4.5
|
||||
global_max = 4.5
|
||||
# Set Y-axis range based on global min/max values
|
||||
self.plot_widget.setYRange(global_min, global_max)
|
||||
eeg_data = latest_data
|
||||
self.channel = [1, 2, 3, 4, 5, 6, 7, 8]
|
||||
eeg_data = np.array([eeg_data[i - 1] for i in self.channel])
|
||||
if time.time() - self.beg > 1:
|
||||
# psd_values = self.compute_psd(eeg_data, 500)
|
||||
# current_psd_sum = np.sum(psd_values)
|
||||
# print(f"psd:{current_psd_sum}")
|
||||
self.beg = time.time()
|
||||
except ValueError:
|
||||
pass # Skip plotting if not enough data is available
|
||||
|
||||
def closeEvent(self, event):
|
||||
"""Ensure the thread is stopped when the application is closed."""
|
||||
self.serial_thread.stop()
|
||||
self.serial_thread.wait()
|
||||
event.accept()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
app = QtWidgets.QApplication(sys.argv)
|
||||
main = ADCPlotter()
|
||||
main.show()
|
||||
sys.exit(app.exec_())
|
Loading…
Reference in New Issue
Block a user