Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show channel stats #462

Merged
merged 9 commits into from
Jan 27, 2025
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
- XDF reader now parses measurement date ([#470](https://github.com/cbrnr/mnelab/pull/470) by [Stefan Appelhoff](https://stefanappelhoff.com))
- Add support for loading custom montage files ([#468](https://github.com/cbrnr/mnelab/pull/468) by [Benedikt Klöckl](https://github.com/bkloeckl) and [Clemens Brunner](https://github.com/cbrnr))
- Add new filter dialog option for notch filter and improve UI ([#469](https://github.com/cbrnr/mnelab/pull/469) by [Benedikt Klöckl](https://github.com/bkloeckl))
- Add functionality to display channel stats ([#462](https://github.com/cbrnr/mnelab/pull/462) by [Benedikt Klöckl](https://github.com/bkloeckl))

### 🌀 Changed
- Change the append dialog appearance to include original indices used for identifying the data ([#449](https://github.com/cbrnr/mnelab/pull/449) by [Benedikt Klöckl](https://github.com/bkloeckl))
Expand Down
9 changes: 5 additions & 4 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,17 @@ classifiers = [
]
keywords = ["EEG", "MEG", "MNE", "GUI", "electrophysiology"]
dependencies = [
"mne >= 1.7.0",
"PySide6 >= 6.7.1",
"edfio >= 0.4.2",
"matplotlib >= 3.8.0",
"mne >= 1.7.0",
"numpy >= 2.0.0",
"scipy >= 1.14.1",
"pybv >= 0.7.4",
"pyobjc-framework-cocoa >= 10.0; platform_system=='Darwin'",
"pyxdf >= 1.16.4",
"pyobjc-framework-Cocoa >= 10.0; platform_system=='Darwin'",
"pyside6 >= 6.7.1",
"scipy >= 1.14.1",
]

dynamic = ["version"]

[project.optional-dependencies]
Expand Down
102 changes: 102 additions & 0 deletions src/mnelab/dialogs/channel_stats.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# © MNELAB developers
#
# License: BSD (3-clause)

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
QDialog,
QPushButton,
QTableWidget,
QTableWidgetItem,
QVBoxLayout,
)

from mnelab.utils import calculate_channel_stats


class SortableTableWidgetItem(QTableWidgetItem):
def __init__(self, value):
super().__init__(str(value))
self.value = value

def __lt__(self, other):
try:
return float(self.value) < float(other.value)
except ValueError:
return str(self.value) < str(other.value)


class ChannelStats(QDialog):
def __init__(self, parent, raw):
super().__init__(parent=parent)

# window
self.setWindowTitle("Channel Stats")
self.setMinimumSize(400, 300)
layout = QVBoxLayout(self)

# create table
self.table = QTableWidget(self)
self.table.setSortingEnabled(True)
layout.addWidget(self.table)

# populate table
self.populate_table(raw)
self.table.resizeColumnsToContents()

# add close button
close_button = QPushButton("Close")
close_button.clicked.connect(self.close)
layout.addWidget(close_button)

# calculate table width
table_width = self.table.verticalHeader().width()
table_width += sum(
self.table.columnWidth(i) for i in range(self.table.columnCount())
)
table_width += self.table.verticalScrollBar().width()
self.resize(table_width - 30, 550)
self.setLayout(layout)

def populate_table(self, raw):
cols, nchan = calculate_channel_stats(raw)
self.table.setColumnCount(9)
self.table.setRowCount(nchan)
self.table.setHorizontalHeaderLabels(
[
"Channel",
"Name",
"Type",
"Unit",
"Min",
"Q1",
"Mean",
"Median",
"Q3",
"Max",
]
)

for i in range(nchan):
item = QTableWidgetItem(str(i))
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(i, 0, item)

item = QTableWidgetItem(cols["name"][i])
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(i, 1, item)

item = QTableWidgetItem(cols["type"][i].upper())
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(i, 2, item)

item = QTableWidgetItem(cols["unit"][i])
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
self.table.setItem(i, 3, item)

for j, key in enumerate(["min", "Q1", "median", "Q3", "max"], start=4):
formatted_value = f"{cols[key][i]:.2f}"
item = QTableWidgetItem(formatted_value)
item.setFlags(item.flags() & ~Qt.ItemIsEditable)
item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.table.setItem(i, j, item)
13 changes: 13 additions & 0 deletions src/mnelab/mainwindow.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
from pyxdf import resolve_streams

from mnelab.dialogs import * # noqa: F403
from mnelab.dialogs.channel_stats import ChannelStats
from mnelab.io import writers
from mnelab.io.mat import parse_mat
from mnelab.io.npy import parse_npy
Expand Down Expand Up @@ -315,6 +316,10 @@ def __init__(self, model: Model):
self.show_history,
QKeySequence(Qt.CTRL | Qt.Key_Y),
)
self.actions["channel_stats"] = view_menu.addAction(
"&Channel Stats",
self.show_channel_stats,
)
self.actions["toolbar"] = view_menu.addAction("&Toolbar", self._toggle_toolbar)
self.actions["toolbar"].setCheckable(True)
self.actions["statusbar"] = view_menu.addAction(
Expand Down Expand Up @@ -542,6 +547,9 @@ def data_changed(self):
self.actions["epoch_data"].setEnabled(
enabled and events and self.model.current["dtype"] == "raw"
)
self.actions["channel_stats"].setEnabled(
enabled and self.model.current["dtype"] == "raw"
)
self.actions["drop_bad_epochs"].setEnabled(
enabled and events and self.model.current["dtype"] == "epochs"
)
Expand Down Expand Up @@ -1248,6 +1256,11 @@ def show_history(self):
dialog = HistoryDialog(self, "\n".join(self.model.history))
dialog.exec()

def show_channel_stats(self):
"""Show channel stats."""
dialog = ChannelStats(self, self.model.current["data"])
dialog.exec_()

def show_about(self):
"""Show About dialog."""
from . import __version__
Expand Down
8 changes: 7 additions & 1 deletion src/mnelab/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,10 @@

from mnelab.utils.dependencies import have
from mnelab.utils.syntax import PythonHighlighter
from mnelab.utils.utils import Montage, count_locations, image_path, natural_sort
from mnelab.utils.utils import (
Montage,
calculate_channel_stats,
count_locations,
image_path,
natural_sort,
)
32 changes: 32 additions & 0 deletions src/mnelab/utils/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
# License: BSD (3-clause)

import re
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path

import numpy as np
from mne import channel_type
from mne.channels import DigMontage
from mne.defaults import _handle_default


def count_locations(info):
Expand All @@ -33,6 +36,35 @@ def key(s):
return sorted(lst, key=key)


def calculate_channel_stats(raw):
# extract channel info
nchan = raw.info["nchan"]
data = raw.get_data()
cols = defaultdict(list)
cols["name"] = raw.ch_names
cols["type"] = [channel_type(raw.info, i) for i in range(nchan)]

# vectorized calculations
cols["min"], cols["Q1"], cols["median"], cols["Q3"], cols["max"] = np.percentile(
data, [0, 25, 50, 75, 100], axis=1
)
cols["mean"] = np.mean(data, axis=1)

# scaling and units
scalings = _handle_default("scalings")
units = _handle_default("units")
cols["unit"] = []
for i in range(nchan):
unit = units.get(cols["type"][i])
scaling = scalings.get(cols["type"][i], 1)
cols["unit"].append(unit if scaling != 1 else "")
if scaling != 1:
for col in ["min", "Q1", "mean", "median", "Q3", "max"]:
cols[col][i] *= scaling

return cols, nchan


@dataclass
class Montage:
montage: DigMontage
Expand Down