12 Commits
Author SHA1 Message Date
tyler c566527f48 Update LICENSE 2026-08-31 22:44:42 -07:00
tyler 2fe6f42c48 actual final fixes for new version 2026-08-31 22:30:24 -07:00
tyler 71b6280cc2 fix to changelog 2026-08-31 22:06:05 -07:00
tyler f0b8266cf9 prepare for new version 2026-08-31 22:00:35 -07:00
tyler a9ea0efcb4 dark mode toggle + enhancements 2026-08-27 17:50:23 -07:00
tyler 83ab73a05a heart rate improvements 2026-08-25 14:04:41 -07:00
tyler 2fa3188296 improved heart rate calculations 2026-08-24 16:40:02 -07:00
tyler d9d5b6d940 typos and pylance 2026-08-23 00:12:22 -07:00
tyler e37275a1bb functional connectivity, pylance, and other improvements 2026-08-22 23:38:13 -07:00
tyler 19bd3f1279 pylance things 2026-08-21 00:57:15 -07:00
tyler 7a438b1798 unit testing and others 2026-08-21 00:12:29 -07:00
tyler 2f76622e52 file association fixes macOS 2026-08-13 14:34:51 -07:00
32 changed files with 4655 additions and 2161 deletions
+2
View File
@@ -182,3 +182,5 @@ cython_debug/
flares-* flares-*
*.flare *.flare
*.cfg *.cfg
tempCodeRunnerFile.py
*.pkl
+2 -2
View File
@@ -209,7 +209,7 @@ If you develop a new program, and you want it to be of the greatest possible use
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
flares flares
Copyright (C) 2025 tyler Copyright (C) 2025-2026 tyler
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
@@ -221,7 +221,7 @@ Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
flares Copyright (C) 2025 tyler flares Copyright (C) 2025-2026 tyler
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
+36
View File
@@ -1,3 +1,39 @@
# Version 1.7.0
- This is potentially a save-changing release due to adding more data into the save file. Please update your project files to ensure compatibility
- Renamed all instances of "Inter" to properly read as "Intra" and changed "Cross" to now read as "Inter"
- Changed RESAMPLE to only apply where it is required to avoid having Functional Connectivity analysis methods running on data that has been resampled
- Added parameters that appear when attempting to generate results from the Participant and Intra-Group Functional Connectivity viewers and removed the non-functional placeholder parameters
- Modified the Participant and Intra-Group Functional Connectivity analysis options to better perform their expected tasks. This remains as a BETA feature
- Removed the existing Intra-Group Functional Connectivity option and replaced it with two new ones: Beta-Series Correlation and Spectral Coherence (epochs)
- Updated the names of the methods provided for the Participant Functional Connectivity Viewer to better match the actions they perform
- Updated the warnings for the Functional Connectivity Viewers to better represent the challenges these analysis options now face
- Added basic unit testing to hopefully prevent any accidental processing changes from occurring in the future
- Added a new parameter to the PSP section on the right side of the screen: PSP_USE_HEART_RATE_BAND. This functions similarly to the existing SCI_USE_HEART_RATE_BAND
- Added description text to the Inter-Group and Intra-Group Brain and Image Viewers, as well as the Functional Connectivity windows to explain what output can be expected
- Added a new Preference option of Theme. Allows from selecting Auto (System default), Light, or Dark. Fixes [Issue 7](https://git.research.dezeeuw.ca/tyler/flares/issues/7)
- Removed image index 1 (Significance) from the Intra-Group Brain and Image Viewer as it is now provided more in depth with the Stats viewers
- Modified the timeout when waiting for the application to close while performing updates down to a reasonable number
- Modified the help messages for parameters in the SCI and PSP areas to better reflect how the parameters are used
- Modified the heart rate calculation to be more precise and correct when dealing with good data and not messy data
- Modified the heart rate calculation to not take only one channel in the data to use, but rather an average of channels. This still prefers short channels if they are present
- Fixed an issue where loading a project from a saved project file would not allow the data to be reprocessed with new parameters
- Fixed an issue where the "Hand" BIDS metadata value would not populate on bubbles correctly
- Fixed an issue where performing PSP could ignore the bad channels that were marked by SCI and SNR
- Fixed an issue where the heart rate calculation would disregard all calculations and fall back to an extremely rudimentary calculation
- Fixed an issue that could prevent log file generation while the application was in the middle of an update
- Fixed an issue where a rare crash could occur while the application was in the middle of an update
- Fixed an issue that could have passed multiple conditions when generating an Intra-Group Stats image
- Fixed an issue that could pass NaN values when attempting to collapse channels
- Fixed an issue that was causing the OLS model to always be used for brain images with multiple participants, and not the MixedLM model
- Fixed an issue that could cause the Wavelet filtering step to crash
- Fixed an issue where file associations appeared to work as intended but would not load the project on macOS and only open the application
- Fixed an issue where file associations would refuse to associate on macOS once they have attempted to be associated
- Fixed an issue where certain parameters would not enable or disable depending on other parameters when they should've
- Fixed an issue where not all widgets would close when attempting to close the application causing the application to crash
- Fixed an issue where events were not created correctly after the data had been resampled by the design matrix
# Version 1.6.0 # Version 1.6.0
- This is potentially a save-changing release due to adding more data into the save file, renaming existing data, and changing what part of the code saves data. Please update your project files to ensure compatibility - This is potentially a save-changing release due to adding more data into the save file, renaming existing data, and changing what part of the code saves data. Please update your project files to ensure compatibility
+3 -44
View File
@@ -10,15 +10,14 @@ License: GPL-3.0
# Built-in imports # Built-in imports
import os import os
import sys import sys
import plistlib
import subprocess import subprocess
from typing import Optional, Tuple from typing import Optional, Tuple
# External library imports # External library imports
from src.shared.shareddata import APP_NAME, PLATFORM_NAME from src.shared.shareddata import APP_NAME, PLATFORM_NAME
ELEVATION_FLAG = "--register_file_association_elevated"
ELEVATION_FLAG = "--register_file_association_elevated"
def register_file_association(ext: Optional[str] = None, def register_file_association(ext: Optional[str] = None,
@@ -27,7 +26,6 @@ def register_file_association(ext: Optional[str] = None,
bundle_id: Optional[str] = None, bundle_id: Optional[str] = None,
force_admin: bool = False, force_admin: bool = False,
) -> Tuple[bool, str]: ) -> Tuple[bool, str]:
""" """
Registers a custom file extension across Windows, Linux, and macOS. Registers a custom file extension across Windows, Linux, and macOS.
Handles non-admin Windows users by falling back to local user registry. Handles non-admin Windows users by falling back to local user registry.
@@ -337,45 +335,6 @@ def _register_macos(ext: str, app_name: str, bundle_id: str) -> Tuple[bool, str]
if not app_bundle_path.endswith(".app"): if not app_bundle_path.endswith(".app"):
return False, "Could not locate outer .app bundle." return False, "Could not locate outer .app bundle."
info_plist_path = os.path.join(app_bundle_path, "Contents", "Info.plist")
if not os.path.exists(info_plist_path):
return False, f"Info.plist not found at {info_plist_path}"
clean_ext = ext.lstrip('.')
uti = f"{bundle_id}.{clean_ext}"
try:
with open(info_plist_path, "rb") as f:
plist = plistlib.load(f)
# Tell macOS this app can open files with our UTI
doc_types = plist.get("CFBundleDocumentTypes", [])
if not any(uti in dt.get("LSItemContentTypes", []) for dt in doc_types):
doc_types.append({
"CFBundleTypeName": f"{app_name} Project File",
"CFBundleTypeRole": "Editor",
"LSHandlerRank": "Owner",
"LSItemContentTypes": [uti],
})
plist["CFBundleDocumentTypes"] = doc_types
# Declare the UTI itself (required — without this the type is unknown to LS)
exported_types = plist.get("UTExportedTypeDeclarations", [])
if not any(t.get("UTTypeIdentifier") == uti for t in exported_types):
exported_types.append({
"UTTypeIdentifier": uti,
"UTTypeDescription": f"{app_name} File",
"UTTypeConformsTo": ["public.data"],
"UTTypeTagSpecification": {"public.filename-extension": [clean_ext]},
})
plist["UTExportedTypeDeclarations"] = exported_types
with open(info_plist_path, "wb") as f:
plistlib.dump(plist, f)
except Exception as e:
return False, f"Failed to update Info.plist: {str(e)}"
try: try:
lsregister_path = ( lsregister_path = (
"/System/Library/Frameworks/CoreServices.framework/Frameworks/" "/System/Library/Frameworks/CoreServices.framework/Frameworks/"
@@ -385,9 +344,9 @@ def _register_macos(ext: str, app_name: str, bundle_id: str) -> Tuple[bool, str]
[lsregister_path, "-f", app_bundle_path], [lsregister_path, "-f", app_bundle_path],
check=True, capture_output=True, check=True, capture_output=True,
) )
return True, f"Registered {ext} with {app_bundle_path} via macOS Launch Services!" return True, f"Refreshed Launch Services registration for {app_bundle_path}."
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
stderr = e.stderr.decode(errors="ignore") if e.stderr else str(e) stderr = e.stderr.decode(errors="ignore") if e.stderr else str(e)
return False, f"macOS Launch Services registration failed: {stderr}" return False, f"macOS Launch Services refresh failed: {stderr}"
except Exception as e: except Exception as e:
return False, f"macOS Registration failed: {str(e)}" return False, f"macOS Registration failed: {str(e)}"
+1881 -562
View File
File diff suppressed because it is too large Load Diff
+50 -32
View File
@@ -1,6 +1,7 @@
""" """
Filename: flares_updater.py Filename: flares_updater.py
Description: FLARES updater executable Description: FLARES updater executable
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
@@ -13,26 +14,30 @@ import time
import shlex import shlex
import psutil import psutil
import shutil import shutil
import platform
import subprocess import subprocess
from typing import Union
from pathlib import Path
from datetime import datetime from datetime import datetime
PLATFORM_NAME = platform.system().lower() # External library imports
APP_NAME = "flares" from src.shared.shareddata import APP_NAME, PLATFORM_NAME
if PLATFORM_NAME == 'darwin': if PLATFORM_NAME == 'darwin':
LOG_FILE = os.path.join(os.path.dirname(sys.executable), f"../../../{APP_NAME}_updater.log") _log_path = os.path.join(os.path.dirname(sys.executable), f"../../../{APP_NAME}_updater.log")
else: else:
LOG_FILE = os.path.join(os.getcwd(), f"{APP_NAME}_updater.log") _log_path = os.path.join(os.getcwd(), f"{APP_NAME}_updater.log")
LOG_FILE = _log_path
def log(msg): def log(msg: str) -> None:
with open(LOG_FILE, "a", encoding="utf-8") as f: with open(LOG_FILE, "a", encoding="utf-8") as f:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"{timestamp} - {msg}\n") f.write(f"{timestamp} - {msg}\n")
def kill_all_processes_by_executable(exe_path): def kill_all_processes_by_executable(exe_path: Union[str, Path]) -> bool:
terminated_any = False terminated_any = False
exe_path = os.path.realpath(exe_path) exe_path = os.path.realpath(exe_path)
@@ -64,7 +69,7 @@ def kill_all_processes_by_executable(exe_path):
return terminated_any return terminated_any
def _terminate_process(proc): def _terminate_process(proc: psutil.Process) -> None:
try: try:
proc.terminate() proc.terminate()
proc.wait(timeout=10) proc.wait(timeout=10)
@@ -76,7 +81,7 @@ def _terminate_process(proc):
log(f"Process {proc.pid} killed.") log(f"Process {proc.pid} killed.")
def wait_for_unlock(path, timeout=100): def wait_for_unlock(path: Union[str, Path], timeout: Union[int, float] = 100) -> None:
start_time = time.time() start_time = time.time()
while time.time() - start_time < timeout: while time.time() - start_time < timeout:
try: try:
@@ -92,7 +97,7 @@ def wait_for_unlock(path, timeout=100):
log(f"Failed to delete after wait: {path}") log(f"Failed to delete after wait: {path}")
def delete_path(path): def delete_path(path: Union[str, Path]) -> None:
if os.path.exists(path): if os.path.exists(path):
try: try:
if os.path.isdir(path): if os.path.isdir(path):
@@ -105,7 +110,7 @@ def delete_path(path):
log(f"Error deleting {path}: {e}") log(f"Error deleting {path}: {e}")
def copy_update_files(src_folder, dest_folder, updater_name): def copy_update_files(src_folder: Union[str, Path], dest_folder: Union[str, Path], updater_name: str) -> None:
for item in os.listdir(src_folder): for item in os.listdir(src_folder):
if item.lower() == updater_name.lower(): if item.lower() == updater_name.lower():
log(f"Skipping updater executable: {item}") log(f"Skipping updater executable: {item}")
@@ -124,7 +129,7 @@ def copy_update_files(src_folder, dest_folder, updater_name):
log(f"Error copying {s} -> {d}: {e}") log(f"Error copying {s} -> {d}: {e}")
def copy_update_files_darwin(src_folder, dest_folder, updater_name): def copy_update_files_darwin(src_folder: Union[str, Path], dest_folder: Union[str, Path], updater_name: str) -> None:
updater_name = updater_name + ".app" updater_name = updater_name + ".app"
@@ -146,19 +151,33 @@ def copy_update_files_darwin(src_folder, dest_folder, updater_name):
log(f"Error copying {s} -> {d}: {e}") log(f"Error copying {s} -> {d}: {e}")
def remove_quarantine(app_path): def remove_quarantine(app_path: Union[str, Path]) -> bool:
"""Removes the macOS quarantine extended attribute from an application bundle using osascript.
Returns True on success, False on error or cancellation.
"""
clean_path: str = str(app_path)
escaped_path: str = shlex.quote(clean_path)
script = f''' script = f'''
do shell script "xattr -d -r com.apple.quarantine {shlex.quote(app_path)}" with administrator privileges with prompt "{APP_NAME} needs privileges to finish the update. (1/2)" do shell script "xattr -d -r com.apple.quarantine {escaped_path}" with administrator privileges with prompt "{APP_NAME} needs privileges to finish the update. (1/2)"
''' '''
try: try:
subprocess.run(['osascript', '-e', script], check=True) subprocess.run(["osascript", "-e", script], check=True)
print("✅ Quarantine attribute removed.") print("✅ Quarantine attribute removed.")
return True
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print("❌ Failed to remove quarantine attribute.") print("❌ Failed to remove quarantine attribute.")
print(e) print(e)
return False
def main(): def main():
main_exe: str = ""
app_dir: Path = Path()
bundle_dir: Path = Path()
parent_bundle_dir: Path = Path()
try: try:
log(f"[Updater] sys.argv: {sys.argv}") log(f"[Updater] sys.argv: {sys.argv}")
@@ -169,11 +188,10 @@ def main():
update_folder = sys.argv[1] update_folder = sys.argv[1]
main_exe = sys.argv[2] main_exe = sys.argv[2]
# Interesting naming convention main_exe_path = Path(main_exe).resolve()
parent_dir = os.path.dirname(os.path.abspath(main_exe)) app_dir = main_exe_path.parent
pparent_dir = os.path.dirname(parent_dir) bundle_dir = main_exe_path.parents[2]
ppparent_dir = os.path.dirname(pparent_dir) parent_bundle_dir = main_exe_path.parents[3]
pppparent_dir = os.path.dirname(ppparent_dir)
updater_name = os.path.basename(sys.argv[0]) updater_name = os.path.basename(sys.argv[0])
@@ -182,13 +200,13 @@ def main():
log(f"Main EXE: {main_exe}") log(f"Main EXE: {main_exe}")
log(f"Updater EXE: {updater_name}") log(f"Updater EXE: {updater_name}")
if PLATFORM_NAME == 'darwin': if PLATFORM_NAME == 'darwin':
log(f"Main App Folder: {ppparent_dir}") log(f"Main App Folder: {bundle_dir}")
# Kill all instances of main app # Kill all instances of main app
kill_all_processes_by_executable(main_exe) kill_all_processes_by_executable(main_exe)
# Wait until main_exe process is fully gone (polling) # Wait until main_exe process is fully gone (polling)
for _ in range(20): # wait max 10 seconds for _ in range(10): # wait max 10 seconds
running = False running = False
for proc in psutil.process_iter(['exe', 'cmdline']): for proc in psutil.process_iter(['exe', 'cmdline']):
try: try:
@@ -214,17 +232,17 @@ def main():
# Delete old version files # Delete old version files
if PLATFORM_NAME == 'darwin': if PLATFORM_NAME == 'darwin':
log(f'Attempting to delete {ppparent_dir}') log(f'Attempting to delete {bundle_dir}')
delete_path(ppparent_dir) delete_path(str(bundle_dir))
update_folder = os.path.join(sys.argv[1], f"{APP_NAME}-darwin") update_folder = os.path.join(sys.argv[1], f"{APP_NAME}-darwin")
copy_update_files_darwin(update_folder, pppparent_dir, updater_name) copy_update_files_darwin(update_folder, str(parent_bundle_dir), updater_name)
else: else:
delete_path(main_exe) delete_path(main_exe)
wait_for_unlock(os.path.join(parent_dir, "_internal")) wait_for_unlock(os.path.join(str(app_dir), "_internal"))
# Copy new files excluding the updater itself # Copy new files excluding the updater itself
copy_update_files(update_folder, parent_dir, updater_name) copy_update_files(update_folder, str(app_dir), updater_name)
except Exception as e: except Exception as e:
log(f"Something went wrong: {e}") log(f"Something went wrong: {e}")
@@ -236,13 +254,13 @@ def main():
log("Added executable bit") log("Added executable bit")
if PLATFORM_NAME == 'darwin': if PLATFORM_NAME == 'darwin':
os.chmod(ppparent_dir, 0o755) os.chmod(str(bundle_dir), 0o755)
log("Added executable bit") log("Added executable bit")
remove_quarantine(ppparent_dir) remove_quarantine(str(bundle_dir))
log(f"Removed the quarantine flag on {ppparent_dir}") log(f"Removed the quarantine flag on {bundle_dir}")
subprocess.Popen(['open', ppparent_dir, "--args", "--finish-update"]) subprocess.Popen(['open', str(bundle_dir), "--args", "--finish-update"])
else: else:
subprocess.Popen([main_exe, "--finish-update"], cwd=parent_dir) subprocess.Popen([main_exe, "--finish-update"], cwd=str(app_dir))
log("Relaunched main app.") log("Relaunched main app.")
except Exception as e: except Exception as e:
+153 -32
View File
@@ -19,6 +19,7 @@ from queue import Empty
from copy import deepcopy from copy import deepcopy
from pathlib import Path from pathlib import Path
from datetime import datetime from datetime import datetime
from functools import partial
from multiprocessing import Process, current_process, freeze_support, Queue, set_start_method from multiprocessing import Process, current_process, freeze_support, Queue, set_start_method
# External library imports # External library imports
@@ -28,8 +29,8 @@ from PySide6.QtWidgets import (
QApplication, QWidget, QMessageBox, QVBoxLayout, QHBoxLayout, QTextEdit, QScrollArea, QComboBox, QGridLayout, QSplitter, QDialogButtonBox, QHeaderView, QApplication, QWidget, QMessageBox, QVBoxLayout, QHBoxLayout, QTextEdit, QScrollArea, QComboBox, QGridLayout, QSplitter, QDialogButtonBox, QHeaderView,
QPushButton, QMainWindow, QLabel, QLineEdit, QGroupBox, QDialog, QMenu, QSpinBox, QTableWidget, QTableWidgetItem QPushButton, QMainWindow, QLabel, QLineEdit, QGroupBox, QDialog, QMenu, QSpinBox, QTableWidget, QTableWidgetItem
) )
from PySide6.QtCore import Signal, Qt, QTimer from PySide6.QtCore import QEvent, QObject, Signal, Qt, QTimer
from PySide6.QtGui import QAction, QFontMetrics, QKeySequence, QIcon from PySide6.QtGui import QAction, QActionGroup, QFontMetrics, QKeySequence, QIcon
from PySide6.QtSvgWidgets import QSvgWidget # needed to show svgs when app is not frozen from PySide6.QtSvgWidgets import QSvgWidget # needed to show svgs when app is not frozen
from file_ext_registration import register_file_association, ELEVATION_FLAG from file_ext_registration import register_file_association, ELEVATION_FLAG
@@ -64,6 +65,7 @@ show_welcome_dialog = false
first_startup = true first_startup = true
[Preferences] [Preferences]
theme = auto
2d_data_bypass = false 2d_data_bypass = false
incompatible_save_bypass = false incompatible_save_bypass = false
missing_events_bypass = false missing_events_bypass = false
@@ -129,10 +131,10 @@ SECTIONS = [
"params": [ "params": [
{"name": "SCI", "default": True, "type": bool, "advanced": False, "help": "Calculate and mark channels bad based on their Scalp Coupling Index. This metric calculates the quality of the connection between the optode and the scalp."}, {"name": "SCI", "default": True, "type": bool, "advanced": False, "help": "Calculate and mark channels bad based on their Scalp Coupling Index. This metric calculates the quality of the connection between the optode and the scalp."},
{"name": "SCI_USE_HEART_RATE_BAND", "default": True, "type": bool, "depends_on": [{"parent_name": "SCI"}, {"parent_name": "HEART_RATE"}], "advanced": False, "help": "Adjust the SCI frequency band using the participant's estimated heart rate."}, {"name": "SCI_USE_HEART_RATE_BAND", "default": True, "type": bool, "depends_on": [{"parent_name": "SCI"}, {"parent_name": "HEART_RATE"}], "advanced": False, "help": "Adjust the SCI frequency band using the participant's estimated heart rate."},
{"name": "SCI_LOW_FREQ", "default": 0.7, "type": float, "depends_on": "SCI_USE_HEART_RATE_BAND", "depends_value": False,"advanced": True, "help": "Lower frequency cutoff for SCI bandpass filtering (Hz)."}, {"name": "SCI_LOW_FREQ", "default": 0.7, "type": float, "depends_on": "SCI_USE_HEART_RATE_BAND", "depends_value": False,"advanced": True, "help": "Lower frequency bound for the signal band used in SCI calculation (Hz)."},
{"name": "SCI_HIGH_FREQ", "default": 1.5, "type": float, "depends_on": "SCI_USE_HEART_RATE_BAND", "depends_value": False, "advanced": True, "help": "Upper frequency cutoff for SCI bandpass filtering (Hz)."}, {"name": "SCI_HIGH_FREQ", "default": 1.5, "type": float, "depends_on": "SCI_USE_HEART_RATE_BAND", "depends_value": False, "advanced": True, "help": "Lower frequency bound for the signal band used in SCI calculation (Hz)."},
{"name": "SCI_TIME_WINDOW", "default": 3, "type": int, "depends_on": "SCI", "advanced": False, "help": "Duration of each independent SCI calculation window in seconds."}, {"name": "SCI_TIME_WINDOW", "default": 3, "type": int, "depends_on": "SCI", "advanced": False, "help": "Duration of each independent SCI calculation window in seconds."},
{"name": "SCI_THRESHOLD", "default": 0.6, "type": float, "depends_on": "SCI", "advanced": False, "help": "SCI threshold on a scale of 0-1. Channels below this value are marked bad."}, {"name": "SCI_THRESHOLD", "default": 0.6, "type": float, "depends_on": "SCI", "advanced": False, "help": "SCI threshold on a scale of 0-1. Channels below this value will be marked bad."},
] ]
}, },
{ {
@@ -150,10 +152,11 @@ SECTIONS = [
"title": "Peak Spectral Power", "title": "Peak Spectral Power",
"params": [ "params": [
{"name": "PSP", "default": True, "type": bool, "advanced": False, "help": "Calculate and mark channels bad based on their Peak Spectral Power. This metric calculates the amplitude or strength of the most prominent frequency component in a specified spectral range."}, {"name": "PSP", "default": True, "type": bool, "advanced": False, "help": "Calculate and mark channels bad based on their Peak Spectral Power. This metric calculates the amplitude or strength of the most prominent frequency component in a specified spectral range."},
{"name": "PSP_TIME_WINDOW", "default": 3, "type": int, "depends_on": "PSP", "advanced": False, "help": "Length of each independent PSP calculation window in seconds."}, {"name": "PSP_USE_HEART_RATE_BAND", "default": True, "type": bool, "depends_on": [{"parent_name": "PSP"}, {"parent_name": "HEART_RATE"}], "advanced": False, "help": "Adjust the PSP frequency band using the participant's estimated heart rate."},
{"name": "PSP_THRESHOLD", "default": 0.1, "type": float, "depends_on": "PSP", "advanced": False, "help": "Channels with average PSP values below this threshold will be marked as bad."}, {"name": "PSP_LOW_FREQ", "default": 0.7, "type": float, "depends_on": "PSP", "advanced": True, "help": "Lower frequency bound for the signal band used in PSP calculation (Hz)."},
{"name": "PSP_LOW_FREQ", "default": 0.7, "type": float, "depends_on": "PSP", "advanced": True, "help": "Lower frequency cutoff for PSP bandpass filtering (Hz)."}, {"name": "PSP_HIGH_FREQ", "default": 1.5, "type": float, "depends_on": "PSP", "advanced": True, "help": "Upper frequency bound for the signal band used in PSP calculation (Hz)."},
{"name": "PSP_HIGH_FREQ", "default": 1.5, "type": float, "depends_on": "PSP", "advanced": True, "help": "Upper frequency cutoff for PSP bandpass filtering (Hz)."}, {"name": "PSP_TIME_WINDOW", "default": 3, "type": int, "depends_on": "PSP", "advanced": False, "help": "Duration of each independent PSP calculation window in seconds."},
{"name": "PSP_THRESHOLD", "default": 0.1, "type": float, "depends_on": "PSP", "advanced": False, "help": "PSP threshold on a scale of 0-1. Channels below this value will be marked bad."},
] ]
}, },
{ {
@@ -242,10 +245,10 @@ SECTIONS = [
{"name": "H_TRANS_BANDWIDTH", "default": 0.002, "type": float, "depends_on": "FILTER", "advanced": True, "help": "Width of the upper transition band to prevent abrupt filter cutoff."}, {"name": "H_TRANS_BANDWIDTH", "default": 0.002, "type": float, "depends_on": "FILTER", "advanced": True, "help": "Width of the upper transition band to prevent abrupt filter cutoff."},
# {"name": "IIR_TYPE", "default": ["butterworth"], "type": list, "options": ["butterworth", "chebyshev1", "chebyshev2", "elliptic", "bessel"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "IIR", "advanced": True, "help": "IIR filter design."}, # {"name": "IIR_TYPE", "default": ["butterworth"], "type": list, "options": ["butterworth", "chebyshev1", "chebyshev2", "elliptic", "bessel"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "IIR", "advanced": True, "help": "IIR filter design."},
# {"name": "IIR_ORDER", "default": 4, "type": int, "depends_on": "FILTER_ALGORITHM", "depends_value": "IIR", "advanced": True, "help": "Order of the IIR filter."}, # {"name": "IIR_ORDER", "default": 4, "type": int, "depends_on": "FILTER_ALGORITHM", "depends_value": "IIR", "advanced": True, "help": "Order of the IIR filter."},
{"name": "FILTER_LENGTH", "default": "auto", "type": str, "depends_on": "FILTER_ALGORITHM", "depends_value": "FIR", "advanced": True, "help": "Length of the FIR filter. 'auto' allows automatic selection."}, {"name": "FILTER_LENGTH", "default": "auto", "type": str, "depends_on": "FILTER_ALGORITHM", "depends_value": "fir", "advanced": True, "help": "Length of the FIR filter. 'auto' allows automatic selection."},
{"name": "FILTER_PHASE", "default": ["zero"], "type": list, "options": ["zero", "zero-double", "minimum", "minimum-half", "linear"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "FIR", "advanced": True, "help": "Phase response of the FIR filter."}, {"name": "FILTER_PHASE", "default": ["zero"], "type": list, "options": ["zero", "zero-double", "minimum", "minimum-half", "linear"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "fir", "advanced": True, "help": "Phase response of the FIR filter."},
{"name": "FIR_WINDOW", "default": ["hamming"], "type": list, "options": ["hamming", "hann", "blackman"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "FIR", "advanced": True, "help": "Window function used when designing the FIR filter."}, {"name": "FIR_WINDOW", "default": ["hamming"], "type": list, "options": ["hamming", "hann", "blackman"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "fir", "advanced": True, "help": "Window function used when designing the FIR filter."},
{"name": "FIR_DESIGN", "default": ["firwin"], "type": list, "options": ["firwin", "firwin2"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "FIR", "advanced": True, "help": "Method used to design the FIR filter."}, {"name": "FIR_DESIGN", "default": ["firwin"], "type": list, "options": ["firwin", "firwin2"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "fir", "advanced": True, "help": "Method used to design the FIR filter."},
# {"name": "IIR_OUTPUT", "default": ["sos"], "type": list, "options": ["sos", "ba", "zpk"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "IIR", "advanced": True, "help": "Representation used for IIR filter coefficients."}, # {"name": "IIR_OUTPUT", "default": ["sos"], "type": list, "options": ["sos", "ba", "zpk"], "exclusive": True, "depends_on": "FILTER_ALGORITHM", "depends_value": "IIR", "advanced": True, "help": "Representation used for IIR filter coefficients."},
# {"name": "PASSBAND_RIPPLE", "default": 1.0, "type": float, "depends_on": "IIR_TYPE", "depends_value": ["chebyshev1", "elliptic"], "advanced": True, "help": "Maximum allowed ripple in the passband (dB)."}, # {"name": "PASSBAND_RIPPLE", "default": 1.0, "type": float, "depends_on": "IIR_TYPE", "depends_value": ["chebyshev1", "elliptic"], "advanced": True, "help": "Maximum allowed ripple in the passband (dB)."},
# {"name": "STOPBAND_ATTENUATION", "default": 40.0, "type": float, "depends_on": "IIR_TYPE", "depends_value": ["chebyshev2", "elliptic"], "advanced": True, "help": "Minimum attenuation in the stopband (dB)."}, # {"name": "STOPBAND_ATTENUATION", "default": 40.0, "type": float, "depends_on": "IIR_TYPE", "depends_value": ["chebyshev2", "elliptic"], "advanced": True, "help": "Minimum attenuation in the stopband (dB)."},
@@ -258,8 +261,8 @@ SECTIONS = [
"title": "Extracting Events", "title": "Extracting Events",
"params": [ "params": [
{"name": "EVENTS", "default": True, "type": bool, "advanced": True, "help": "Extract events from annotations for visualization and downstream event-based analysis."}, {"name": "EVENTS", "default": True, "type": bool, "advanced": True, "help": "Extract events from annotations for visualization and downstream event-based analysis."},
{"name": "EVENT_ID", "default": "auto", "type": str, "advanced": True, "help": "Controls how annotation descriptions are converted into event identifiers. Use 'auto' for automatic event detection."}, {"name": "EVENT_ID", "default": "auto", "type": str, "depends_on": "EVENTS", "advanced": True, "help": "Controls how annotation descriptions are converted into event identifiers. Use 'auto' for automatic event detection."},
{"name": "EVENT_REGEX", "default": r"^(?![Bb][Aa][Dd]|[Ee][Dd][Gg][Ee]).*$", "type": str, "advanced": True, "help": "Regular expression used to select which annotations are converted into events. By default, bad and edge annotations are ignored."}, {"name": "EVENT_REGEX", "default": r"^(?![Bb][Aa][Dd]|[Ee][Dd][Gg][Ee]).*$", "type": str, "depends_on": "EVENTS", "advanced": True, "help": "Regular expression used to select which annotations are converted into events. By default, bad and edge annotations are ignored."},
# {"name": "EVENT_CHUNK_DURATION", "default": 0.0, "type": float, "advanced": True, "help": "If provided, creates repeated events at this interval within longer annotations instead of only using annotation onset times."}, # {"name": "EVENT_CHUNK_DURATION", "default": 0.0, "type": float, "advanced": True, "help": "If provided, creates repeated events at this interval within longer annotations instead of only using annotation onset times."},
] ]
}, },
@@ -320,7 +323,7 @@ SECTIONS = [
BIDS_FIELD_MAP = { BIDS_FIELD_MAP = {
"BIDS - Age": "AGE", "BIDS - Age": "AGE",
"BIDS - Sex": "SEX", "BIDS - Sex": "SEX",
"BIDS - Hand": "HAND", "BIDS - Handedness": "HAND",
} }
@@ -489,6 +492,46 @@ class GroupAssignmentDialog(QDialog):
class CustomApplication(QApplication):
"""
macOS delivers a file-open request (double-clicking a registered
file, or dropping one on the Dock icon — whether the app is already
running or being launched fresh) as an Apple Event, which Qt exposes
as QEvent.Type.FileOpen. Windows/Linux never send this; they pass
the path as a normal argv argument, which startup_args.initial_file
already handles. Without this override, double-clicking a project
file on macOS launches the app but it never learns which file to open.
"""
file_open_requested = Signal(str)
def event(self, e: QEvent) -> bool:
if e.type() == QEvent.Type.FileOpen:
self.file_open_requested.emit(e.file())
return True
return super().event(e)
class ThemeChangeWatcher(QObject):
def __init__(self, main_window):
super().__init__()
self.main_window = main_window
self._theme_timer = QTimer(self)
self._theme_timer.setSingleShot(True)
self._theme_timer.setInterval(100)
self._theme_timer.timeout.connect(self._apply_theme)
def eventFilter(self, obj, event):
if event.type() == QEvent.Type.ApplicationPaletteChange:
# Restart the timer instead of updating immediately.
# Multiple palette-change events collapse into one update.
self._theme_timer.start()
return False
def _apply_theme(self):
print("OS theme changed")
self.main_window.update_theme()
class MainApplication(QMainWindow): class MainApplication(QMainWindow):
""" """
@@ -623,10 +666,10 @@ class MainApplication(QMainWindow):
self.left_v_splitter.setChildrenCollapsible(False) self.left_v_splitter.setChildrenCollapsible(False)
self.left_v_splitter.setMinimumWidth(460) self.left_v_splitter.setMinimumWidth(460)
top_left_container = QGroupBox("File information") self.top_left_container = QGroupBox("File Information")
top_left_container.setStyleSheet("QGroupBox { font-weight: bold; }") self.top_left_container.setStyleSheet("QGroupBox { font-weight: bold; }")
top_left_container.setMinimumHeight(240) self.top_left_container.setMinimumHeight(240)
top_left_layout = QHBoxLayout(top_left_container) top_left_layout = QHBoxLayout(self.top_left_container)
self.top_left_widget = QTextEdit() self.top_left_widget = QTextEdit()
self.top_left_widget.setReadOnly(True) self.top_left_widget.setReadOnly(True)
@@ -639,22 +682,25 @@ class MainApplication(QMainWindow):
font_metrics = QFontMetrics(self.font()) font_metrics = QFontMetrics(self.font())
label_width = max(font_metrics.horizontalAdvance(key.capitalize()) for key in self.meta_fields) + 10 label_width = max(font_metrics.horizontalAdvance(key.capitalize()) for key in self.meta_fields) + 10
self.meta_labels = {}
for key, field in self.meta_fields.items(): for key, field in self.meta_fields.items():
row_layout = QHBoxLayout() row_layout = QHBoxLayout()
row_layout.setContentsMargins(0, 0, 0, 0) row_layout.setContentsMargins(0, 0, 0, 0)
row_layout.setSpacing(0) row_layout.setSpacing(0)
label = QLabel(key.capitalize() + ":") label = QLabel(key.capitalize() + ":")
self.meta_labels[key] = label
label.setFixedWidth(label_width) label.setFixedWidth(label_width)
row_layout.addWidget(label) row_layout.addWidget(label)
row_layout.addWidget(field) row_layout.addWidget(field)
right_column_layout.addLayout(row_layout) right_column_layout.addLayout(row_layout)
field.textChanged.connect(self.sync_bubble_data) field.textChanged.connect(self.sync_bubble_data)
label_desc = QLabel('<a href="#">Why are these useful?</a>') self.label_desc = QLabel('<a href="#">Why are these useful?</a>')
label_desc.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction) self.label_desc.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
label_desc.linkActivated.connect(lambda: QMessageBox.information(None, f"Info - {APP_NAME.upper()} ", "Age: Used in determing the participants PPF. Also used to assist in creating groups.\nGender: Used to assist in creating groups.\nHand: Used to assist in creating groups.\nGroup: Used to split participants into groups for comparisons between them.")) self.label_desc.linkActivated.connect(lambda: QMessageBox.information(None, f"Info - {APP_NAME.upper()} ", "Age: Used in determing the participants PPF. Also used to assist in creating groups.\nGender: Used to assist in creating groups.\nHand: Used to assist in creating groups.\nGroup: Used to split participants into groups for comparisons between them."))
right_column_layout.addWidget(label_desc) right_column_layout.addWidget(self.label_desc)
right_column_layout.addStretch() right_column_layout.addStretch()
self.right_column_widget.hide() self.right_column_widget.hide()
top_left_layout.addWidget(self.right_column_widget, stretch=1) top_left_layout.addWidget(self.right_column_widget, stretch=1)
@@ -668,7 +714,7 @@ class MainApplication(QMainWindow):
self.scroll_area.setWidget(self.bubble_container) self.scroll_area.setWidget(self.bubble_container)
self.scroll_area.setMinimumHeight(200) self.scroll_area.setMinimumHeight(200)
self.left_v_splitter.addWidget(top_left_container) self.left_v_splitter.addWidget(self.top_left_container)
self.left_v_splitter.addWidget(self.scroll_area) self.left_v_splitter.addWidget(self.scroll_area)
self.right_container = QWidget() self.right_container = QWidget()
@@ -825,6 +871,31 @@ class MainApplication(QMainWindow):
self.pref_actions = {} self.pref_actions = {}
preferences_menu = menu_bar.addMenu("Preferences") preferences_menu = menu_bar.addMenu("Preferences")
theme_menu = preferences_menu.addMenu("Theme")
theme_group = QActionGroup(self)
theme_group.setExclusive(True)
# 4. Define actions for the submenu
theme_actions = [
("Auto", "", "auto", resource_path("icons/warning_off_24dp_1F1F1F.svg"), "theme_auto"),
("Light", "", "light", resource_path("icons/warning_off_24dp_1F1F1F.svg"), "theme_light"),
("Dark", "", "dark", resource_path("icons/warning_off_24dp_1F1F1F.svg"), "theme_dark"),
]
for name, shortcut, mode, icon, config_key in theme_actions:
# Use partial to pass 'mode' to self.theme_change_func on click
slot = partial(self.theme_change_func, mode)
action = make_action(name, shortcut, slot, icon=icon, checkable=True)
theme_menu.addAction(action)
theme_group.addAction(action)
self.pref_actions[config_key] = action
# Set default selection (e.g., Auto)
self.pref_actions["theme_auto"].setChecked(True)
preferences_actions = [ preferences_actions = [
("2D Data Bypass", "", self.is_2d_bypass_func, resource_path("icons/warning_off_24dp_1F1F1F.svg"), "2d_data_bypass"), ("2D Data Bypass", "", self.is_2d_bypass_func, resource_path("icons/warning_off_24dp_1F1F1F.svg"), "2d_data_bypass"),
("Incompatible Save Bypass", "", self.incompatable_save_bypass_func, resource_path("icons/warning_off_24dp_1F1F1F.svg"), "incompatible_save_bypass"), ("Incompatible Save Bypass", "", self.incompatable_save_bypass_func, resource_path("icons/warning_off_24dp_1F1F1F.svg"), "incompatible_save_bypass"),
@@ -851,6 +922,31 @@ class MainApplication(QMainWindow):
self.statusbar.showMessage("Ready") self.statusbar.showMessage("Ready")
def update_theme(self):
text = self.label_desc.text()
self.label_desc.setText("")
self.label_desc.setText(text)
widgets = [
self.label_desc,
self.top_left_widget,
self.right_column_widget,
self.top_left_container,
]
widgets.extend(self.meta_fields.values())
widgets.extend(self.meta_labels.values())
for widget in widgets:
widget.style().unpolish(widget)
widget.style().polish(widget)
widget.update()
for section in self.param_sections:
print("hi")
section.update_theme_colors()
def update_sections(self, index): def update_sections(self, index):
self.current_section_index = index self.current_section_index = index
@@ -1119,6 +1215,8 @@ class MainApplication(QMainWindow):
data_map["fig_bytes_dict"], data_map["fig_bytes_dict"],
data_map["contrast_results_dict"], data_map["contrast_results_dict"],
data_map["roi_channel_map_dict"], data_map["roi_channel_map_dict"],
data_map["fir_feature_dict"],
data_map["qc_dict"],
self.folding_bypass, self.folding_bypass,
] ]
@@ -1137,6 +1235,19 @@ class MainApplication(QMainWindow):
self.top_left_widget.paste() # Trigger paste self.top_left_widget.paste() # Trigger paste
self.statusbar.showMessage("Pasted from clipboard") # Show status message self.statusbar.showMessage("Pasted from clipboard") # Show status message
def theme_change_func(self, mode):
app = QApplication.instance()
style_hints = app.styleHints()
if mode == "auto":
style_hints.setColorScheme(Qt.ColorScheme.Unknown)
elif mode == "light":
style_hints.setColorScheme(Qt.ColorScheme.Light)
elif mode == "dark":
style_hints.setColorScheme(Qt.ColorScheme.Dark)
def _update_config_setting(self, group, key, value): def _update_config_setting(self, group, key, value):
"""Helper to update memory configuration and save to disk.""" """Helper to update memory configuration and save to disk."""
# configparser expects string values # configparser expects string values
@@ -1334,7 +1445,6 @@ class MainApplication(QMainWindow):
def apply_splitter_ratios(self): def apply_splitter_ratios(self):
"""Applies saved ratio positions to main_h_splitter and left_v_splitter.""" """Applies saved ratio positions to main_h_splitter and left_v_splitter."""
if hasattr(self, 'main_h_splitter'): if hasattr(self, 'main_h_splitter'):
print("Splitter actual width:", self.main_h_splitter.width())
total_width = self.main_h_splitter.width() total_width = self.main_h_splitter.width()
if total_width > 0: if total_width > 0:
left_w = int(total_width * self.main_h_ratio) left_w = int(total_width * self.main_h_ratio)
@@ -1836,7 +1946,7 @@ class MainApplication(QMainWindow):
if self.button3.isVisible(): if self.button3.isVisible():
msg = QMessageBox(self) msg = QMessageBox(self)
msg.setWindowTitle("Confirm - FLARES") msg.setWindowTitle("Confirm - FLARES")
msg.setText("Processing new data will clear the current analysis. Continue? (If you do not want this dialog box to appear, toggle 'Analysis Clearing Bypass' from the Preferences menu.)") msg.setText("Processing new data will clear the current analysis and close all other windows. Continue? (If you do not want this dialog box to appear, toggle 'Analysis Clearing Bypass' from the Preferences menu.)")
# Add the OK and Cancel buttons # Add the OK and Cancel buttons
msg.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel) msg.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
@@ -1857,6 +1967,13 @@ class MainApplication(QMainWindow):
for item in DATA_SCHEMA: for item in DATA_SCHEMA:
setattr(self, item["key"], {}) setattr(self, item["key"], {})
for bubble in self.bubble_widgets.values():
bubble.reset()
for widget in QApplication.topLevelWidgets():
if widget is not self and widget.isVisible():
widget.close()
self.button1.clicked.disconnect(self.on_run_task) self.button1.clicked.disconnect(self.on_run_task)
self.button1.setText("Cancel") self.button1.setText("Cancel")
self.button1.clicked.connect(self.cancel_task) self.button1.clicked.connect(self.cancel_task)
@@ -2182,10 +2299,11 @@ class MainApplication(QMainWindow):
return return
for widget in list(QApplication.topLevelWidgets()): for widget in list(QApplication.topLevelWidgets()):
if widget is not self: if widget is not self and widget.isWindow() and not isinstance(widget, QMenu):
if not widget.close(): try:
event.ignore() widget.close()
return except RuntimeError:
pass
if hasattr(self, 'loading_session_id'): if hasattr(self, 'loading_session_id'):
self.loading_session_id += 1 self.loading_session_id += 1
@@ -2648,11 +2766,14 @@ if __name__ == "__main__":
# Only run GUI in the main process # Only run GUI in the main process
if current_process().name == 'MainProcess': if current_process().name == 'MainProcess':
app = QApplication(sys.argv) app = CustomApplication(sys.argv)
finish_update_if_needed(PLATFORM_NAME, APP_NAME, cfg_path, startup_args.finish_update) finish_update_if_needed(PLATFORM_NAME, APP_NAME, cfg_path, startup_args.finish_update)
icon_ext = "icns" if PLATFORM_NAME == "darwin" else "ico" icon_ext = "icns" if PLATFORM_NAME == "darwin" else "ico"
app.setWindowIcon(QIcon(resource_path(f"icons/main.{icon_ext}"))) app.setWindowIcon(QIcon(resource_path(f"icons/main.{icon_ext}")))
window = MainApplication(file_to_open=startup_args.initial_file) window = MainApplication(file_to_open=startup_args.initial_file)
app.theme_watcher = ThemeChangeWatcher(window)
app.installEventFilter(app.theme_watcher)
app.file_open_requested.connect(window.project_manager.load_project)
window.setWindowIcon(QIcon(resource_path(f"icons/main.{icon_ext}"))) window.setWindowIcon(QIcon(resource_path(f"icons/main.{icon_ext}")))
window.show() window.show()
sys.exit(app.exec()) sys.exit(app.exec())
+712
View File
@@ -0,0 +1,712 @@
"""
Filename: main_unit_tests.py
Description: Unit tests for functionality validation
Author: Tyler de Zeeuw
License: GPL-3.0
"""
# Built-in imports
import os
import pickle
import configparser
from unittest.mock import MagicMock, patch
# External library imports
import pytest
from PySide6.QtWidgets import QApplication, QMenu
import main
from updater import LocalPendingUpdateCheckThread, UpdateCheckThread
'''
These test fluff currently. Very basic "Does the UI exist?" and not the functionality.
main_test.py::test_save_project_actions_pass_correct_ask_parameter
main_test.py::test_main_window_opens
main_test.py::test_file_recent_submenus_exist
main_test.py::test_view_reset_layout
main_test.py::test_preferences_actions[2D Data Bypass-2d_data_bypass]
main_test.py::test_preferences_actions[Incompatible Save Bypass-incompatible_save_bypass]
main_test.py::test_preferences_actions[Missing Events Bypass-missing_events_bypass]
main_test.py::test_preferences_actions[Analysis Clearing Bypass-analysis_clearing_bypass]
main_test.py::test_preferences_actions[Folding Bypass-folding_bypass]
main_test.py::test_preferences_actions[Show Advanced Parameters-advanced_parameters]
'''
# ---------------------- HELPERS ----------------------
def get_menu_by_title(menu_bar, title):
"""Return the first QMenu with the given title, or None."""
for menu in menu_bar.findChildren(QMenu):
if menu.title() == title:
return menu
return None
# ---------------------- FIXTURES ----------------------
@pytest.fixture(autouse=True)
def disable_updater_threads():
"""Stops updater threads from running asynchronously during qtbot teardown."""
with patch.object(UpdateCheckThread, "start", return_value=None), \
patch.object(LocalPendingUpdateCheckThread, "start", return_value=None):
yield
@pytest.fixture(autouse=True)
def setup_app_globals():
"""Initializes global configuration objects that main.py expects at runtime."""
main.cfg_path = os.path.join(os.getcwd(), f"{main.APP_NAME}.cfg")
main.file_cfg = configparser.ConfigParser()
main.ref_cfg = configparser.ConfigParser()
if hasattr(main, "config_init"):
main.config_init()
# ===================== FILE MENU =====================
def test_main_window_opens(qtbot):
"""Test 1: Verify MainApplication launches and becomes visible."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
assert window.isVisible()
def test_open_file_dialog_with_mne_mock(qtbot, tmp_path):
dummy_snirf = tmp_path / "test_data.snirf"
dummy_snirf.write_text("dummy content")
expected_path = os.path.normpath(str(dummy_snirf))
# Mock MNE Raw object returned by read_raw_snirf
mock_raw = MagicMock()
mock_raw.info = {"meas_date": "2026-01-01", "ch_names": ["S1_D1 760"], "dig": None}
mock_raw.ch_names = ["S1_D1 760"]
mock_raw.annotations = []
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
with patch("PySide6.QtWidgets.QFileDialog.getOpenFileName", return_value=(expected_path, "SNIRF Files (*.snirf)")), \
patch("mne.io.snirf.read_raw_snirf", return_value=mock_raw), \
patch("project_manager.source_detector_distances", return_value=[0.03]):
window.project_manager.open_file_dialog()
assert expected_path in window.selected_paths
assert expected_path in window.bubble_widgets
window.files_are_dirty = False
window.is_saved = True
def test_open_folder_dialog(qtbot, tmp_path):
"""Verify that open_folder_dialog recursively finds and loads all .snirf files."""
sub_dir = tmp_path / "sub_folder"
sub_dir.mkdir()
file1 = tmp_path / "root_file.snirf"
file2 = sub_dir / "nested_file.snirf"
ignored_file = tmp_path / "notes.txt"
file1.write_text("dummy snirf 1")
file2.write_text("dummy snirf 2")
ignored_file.write_text("text note")
folder_path = str(tmp_path)
expected_paths = {
os.path.normpath(str(file1)),
os.path.normpath(str(file2)),
}
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
with patch(
"PySide6.QtWidgets.QFileDialog.getExistingDirectory",
return_value=folder_path,
):
window.project_manager.open_folder_dialog()
loaded_paths = set(window.selected_paths)
assert expected_paths.issubset(loaded_paths)
assert os.path.normpath(str(ignored_file)) not in loaded_paths
window.files_are_dirty = False
window.is_saved = True
def test_load_project_dialog(qtbot, tmp_path):
"""Verify loading a valid pickled .flare project restores application state."""
project_file = tmp_path / "test_project.flare"
dummy_project_data = {
"version": "1.1.7",
"file_metadata": {"rel_sample.snirf": {"channels": 4}},
"file_parameters": {"rel_sample.snirf": {"AGE": "25", "SEX": "M", "HAND": "R", "GROUP": "A"}},
"roi_channel_map_dict": {},
"file_list": ["rel_sample.snirf"],
"progress_states": {"rel_sample.snirf": "completed"},
"current_ui_params": {},
}
with open(project_file, "wb") as f:
pickle.dump(dummy_project_data, f)
file_path = str(project_file)
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
if not hasattr(main, "DATA_SCHEMA"):
main.DATA_SCHEMA = []
with patch(
"PySide6.QtWidgets.QFileDialog.getOpenFileName",
return_value=(file_path, "FLARE Project (*.flare)"),
), patch("PySide6.QtWidgets.QMessageBox.information") as mock_info, patch.object(
window, "show_files_as_bubbles_from_list"
):
window.project_manager.load_project_dialog()
assert window.current_project_path == file_path
mock_info.assert_called_once()
def test_load_project_incompatible_version(qtbot, tmp_path):
"""Verify that a missing required key triggers an incompatibility error."""
invalid_file = tmp_path / "corrupt.flare"
incomplete_data = {
"file_metadata": {},
"file_parameters": {},
"roi_channel_map_dict": {},
}
with open(invalid_file, "wb") as f:
pickle.dump(incomplete_data, f)
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
with patch("PySide6.QtWidgets.QMessageBox.critical") as mock_critical, \
patch("PySide6.QtWidgets.QMessageBox.warning") as mock_warning:
window.project_manager.load_project(str(invalid_file))
assert mock_critical.called or mock_warning.called, "Expected a QMessageBox warning or critical popup."
assert len(getattr(window, "selected_paths", [])) == 0
def test_save_project_no_data_shows_warning(qtbot):
"""Verify saving an empty project triggers a 'no data to save' warning."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
with patch("PySide6.QtWidgets.QMessageBox.warning") as mock_warning:
window.project_manager.save_project(ask=True)
mock_warning.assert_called_once()
assert "no data" in mock_warning.call_args[0][2].lower()
def test_save_project_success(qtbot, tmp_path):
"""Verify saving a loaded project outputs a valid pickled .flare file."""
save_file_path = tmp_path / "test_project.flare"
dummy_snirf_path = str(tmp_path / "sample_subject.snirf")
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
# 1. Satisfy 'has_files' check
window.selected_paths = [dummy_snirf_path]
# 2. Add mock bubble widget so step 4 populates file_list
mock_bubble = MagicMock()
mock_bubble.file_path = dummy_snirf_path
mock_bubble.current_step = 0
window.bubble_widgets = {dummy_snirf_path: mock_bubble}
with patch("PySide6.QtWidgets.QFileDialog.getSaveFileName", return_value=(str(save_file_path), "FLARE Project (*.flare)")), \
patch("PySide6.QtWidgets.QMessageBox.information") as mock_info:
window.project_manager.save_project(ask=True)
# Wait for SaveProjectThread to finish writing to disk
qtbot.waitUntil(lambda: save_file_path.exists(), timeout=3000)
mock_info.assert_called_once()
# 3. Verify the saved payload structure
assert save_file_path.is_file()
with open(save_file_path, "rb") as f:
data = pickle.load(f)
assert "version" in data
# file_list contains relative paths normalized by sanitize()
assert "sample_subject.snirf" in data["file_list"]
# Reset dirty state so teardown completes cleanly
window.files_are_dirty = False
window.is_saved = True
def test_save_project_actions_pass_correct_ask_parameter(qtbot):
"""
Verify that the 'Save Project...' action calls save_project(ask=False)
and 'Save Project As...' calls save_project(ask=True).
"""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
file_menu = get_menu_by_title(window.menuBar(), "File")
assert file_menu is not None, "File menu not found"
save_action = next(a for a in file_menu.actions() if a.text() == "Save Project...")
save_as_action = next(a for a in file_menu.actions() if a.text() == "Save Project As...")
with patch.object(window.project_manager, 'save_project') as mock_save:
save_action.trigger()
mock_save.assert_called_once_with(ask=False)
mock_save.reset_mock()
save_as_action.trigger()
mock_save.assert_called_once_with(ask=True)
def test_file_exit(qtbot):
"""Verify that File → Exit calls QApplication.quit()."""
with patch.object(QApplication, 'quit') as mock_quit:
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
file_menu = get_menu_by_title(window.menuBar(), "File")
assert file_menu is not None, "File menu not found"
exit_action = next(a for a in file_menu.actions() if a.text() == "Exit")
exit_action.trigger()
mock_quit.assert_called_once()
def test_file_recent_submenus_exist(qtbot):
"""Verify that the 'Recent Files' and 'Recent Projects' submenus are created."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
file_menu = get_menu_by_title(window.menuBar(), "File")
assert file_menu is not None, "File menu not found"
recent_files_action = next((a for a in file_menu.actions() if a.text() == "Recent Files"), None)
assert recent_files_action is not None
recent_files_menu = recent_files_action.menu()
assert recent_files_menu is not None
recent_projects_action = next((a for a in file_menu.actions() if a.text() == "Recent Projects"), None)
assert recent_projects_action is not None
recent_projects_menu = recent_projects_action.menu()
assert recent_projects_menu is not None
# ===================== EDIT MENU =====================
def test_edit_cut(qtbot):
"""Verify Edit → Cut calls top_left_widget.cut()."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
edit_menu = get_menu_by_title(window.menuBar(), "Edit")
assert edit_menu is not None, "Edit menu not found"
cut_action = next(a for a in edit_menu.actions() if a.text() == "Cut")
with patch.object(window.top_left_widget, 'cut') as mock_cut:
cut_action.trigger()
mock_cut.assert_called_once()
def test_edit_copy(qtbot):
"""Verify Edit → Copy calls top_left_widget.copy()."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
edit_menu = get_menu_by_title(window.menuBar(), "Edit")
assert edit_menu is not None, "Edit menu not found"
copy_action = next(a for a in edit_menu.actions() if a.text() == "Copy")
with patch.object(window.top_left_widget, 'copy') as mock_copy:
copy_action.trigger()
mock_copy.assert_called_once()
def test_edit_paste(qtbot):
"""Verify Edit → Paste calls top_left_widget.paste()."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
edit_menu = get_menu_by_title(window.menuBar(), "Edit")
assert edit_menu is not None, "Edit menu not found"
paste_action = next(a for a in edit_menu.actions() if a.text() == "Paste")
with patch.object(window.top_left_widget, 'paste') as mock_paste:
paste_action.trigger()
mock_paste.assert_called_once()
# ===================== VIEW MENU =====================
def test_view_toggle_statusbar(qtbot):
"""Verify View → Toggle Status Bar toggles visibility and calls _update_config_setting."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
view_menu = get_menu_by_title(window.menuBar(), "View")
assert view_menu is not None, "View menu not found"
toggle_action = next(a for a in view_menu.actions() if a.text() == "Toggle Status Bar")
assert toggle_action.isCheckable() is True
# Initially checked (True in create_menu_bar)
assert toggle_action.isChecked() is True
assert window.statusbar.isVisible() is True
# Trigger once to hide
with patch.object(window, '_update_config_setting') as mock_update:
toggle_action.trigger()
assert not toggle_action.isChecked()
assert not window.statusbar.isVisible()
mock_update.assert_called_once_with("View", "status_bar", False)
# Trigger again to show
with patch.object(window, '_update_config_setting') as mock_update:
toggle_action.trigger()
assert toggle_action.isChecked() is True
assert window.statusbar.isVisible() is True
mock_update.assert_called_once_with("View", "status_bar", True)
def test_view_reset_layout(qtbot):
"""Verify View → Reset Window Layout calls apply_splitter_ratios."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
view_menu = get_menu_by_title(window.menuBar(), "View")
assert view_menu is not None, "View menu not found"
reset_action = next(a for a in view_menu.actions() if a.text() == "Reset Window Layout")
with patch.object(window, 'apply_splitter_ratios') as mock_apply:
reset_action.trigger()
mock_apply.assert_called_once()
# ===================== OPTIONS MENU =====================
def test_about_window_opens(qtbot):
"""Verify AboutWindow opens and prevents duplicate instances."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
assert getattr(window, "about", None) is None
window.about_window()
assert window.about is not None
assert window.about.isVisible() is True
first_instance = window.about
window.about_window()
assert window.about is first_instance
def test_user_guide_window_opens(qtbot):
"""Verify UserGuideWindow opens and prevents duplicate instances."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
assert getattr(window, "help", None) is None
window.user_guide()
assert window.help is not None
assert window.help.isVisible() is True
first_instance = window.help
window.user_guide()
assert window.help is first_instance
def test_show_update_changelog(qtbot):
"""Verify WelcomeDialog is instantiated and shown."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
with patch.object(main, "WelcomeDialog") as mock_dialog_cls:
mock_dialog_instance = MagicMock()
mock_dialog_cls.return_value = mock_dialog_instance
window.show_update_changelog()
mock_dialog_cls.assert_called_once_with(window, direct=False)
mock_dialog_instance.show.assert_called_once()
def test_group_metadata_no_data_shows_msgbox(qtbot):
"""Verify group_metadata triggers an information QMessageBox when file_metadata is empty."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
window.file_metadata = {}
with patch("PySide6.QtWidgets.QMessageBox.information") as mock_msgbox:
window.group_metadata()
mock_msgbox.assert_called_once()
assert "No Data" in mock_msgbox.call_args[0]
def test_group_metadata_with_data_applies_mappings(qtbot):
"""Verify group_metadata opens GroupAssignmentDialog and executes _apply_group_mappings on success."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
window.file_metadata = {"sub-01.snirf": {"age": "25"}}
mock_result = ("Age", {"sub-01.snirf": "GroupA"})
with patch.object(main.GroupAssignmentDialog, "run", return_value=mock_result), \
patch.object(window, "_apply_group_mappings") as mock_apply:
window.group_metadata()
mock_apply.assert_called_once_with({"sub-01.snirf": "GroupA"}, field_name="Age")
def test_manual_check_for_updates(qtbot):
"""Verify Options → Check for Updates triggers the updater method."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
options_menu = get_menu_by_title(window.menuBar(), "Options")
assert options_menu is not None, "Options menu not found"
update_action = next(a for a in options_menu.actions() if a.text() == "Check for Updates")
assert update_action is not None
assert update_action.isEnabled() is True
# Patch the updater's manual_check_for_updates method
with patch.object(window.updater, 'manual_check_for_updates') as mock_method:
update_action.trigger()
mock_method.assert_called_once()
def test_update_optode_positions_opens(qtbot):
"""Verify UpdateOptodesWindow opens and prevents duplicate instances."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
assert getattr(window, "optodes", None) is None
window.update_optode_positions()
assert window.optodes is not None
assert window.optodes.isVisible() is True
first_instance = window.optodes
window.update_optode_positions()
assert window.optodes is first_instance
def test_update_event_markers_opens(qtbot):
"""Verify UpdateEventsWindow opens and prevents duplicate instances."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
assert getattr(window, "events", None) is None
window.update_event_markers()
assert window.events is not None
assert window.events.isVisible() is True
first_instance = window.events
window.update_event_markers()
assert window.events is first_instance
def test_update_event_markers_blazes_opens(qtbot):
"""Verify UpdateEventsBlazesWindow opens and prevents duplicate instances."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
assert getattr(window, "events_blazes", None) is None
window.update_event_markers_blazes()
assert window.events_blazes is not None
assert window.events_blazes.isVisible() is True
first_instance = window.events_blazes
window.update_event_markers_blazes()
assert window.events_blazes is first_instance
def test_reset_to_default_configuration_user_cancels(qtbot):
"""Verify nothing is reset when the user clicks 'No' on the prompt."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
with patch("main.QMessageBox.question", return_value=main.QMessageBox.StandardButton.No), \
patch("main.open") as mock_open, \
patch.object(window, "sync_app_with_config") as mock_sync:
window.reset_to_default_configuration()
mock_open.assert_not_called()
mock_sync.assert_not_called()
def test_reset_to_default_configuration_success(qtbot):
"""Verify file write, widget resets, config sync, and singleShot timer call when confirmed."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
# Mock child ParamSection widgets
mock_section1 = MagicMock()
mock_section2 = MagicMock()
with patch("main.QMessageBox.question", return_value=main.QMessageBox.StandardButton.Yes), \
patch("main.open") as mock_open, \
patch("main.file_cfg") as mock_cfg, \
patch.object(window, "findChildren", return_value=[mock_section1, mock_section2]), \
patch.object(window, "sync_app_with_config") as mock_sync, \
patch.object(window, "update_sections") as mock_update, \
patch("main.QTimer.singleShot") as mock_timer:
window.reset_to_default_configuration()
# Check file overwrite and parser reload
mock_open.assert_called_once()
mock_cfg.read.assert_called_once_with(main.cfg_path)
# Check section UI resets and app syncing
mock_section1.reset_to_defaults.assert_called_once()
mock_section2.reset_to_defaults.assert_called_once()
mock_sync.assert_called_once()
mock_update.assert_called_once_with(0)
# Verify post-reset dialog singleShot queue
mock_timer.assert_called_once_with(100, window._show_reset_success_dialog)
def test_reset_to_default_configuration_file_error_fallback(qtbot):
"""Verify fallback to in-memory read_string when file writing raises an Exception."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
with patch("main.QMessageBox.question", return_value=main.QMessageBox.StandardButton.Yes), \
patch("main.open", side_effect=PermissionError("Access denied")), \
patch("main.file_cfg") as mock_cfg, \
patch.object(window, "sync_app_with_config"), \
patch.object(window, "update_sections"), \
patch("main.QTimer.singleShot"):
window.reset_to_default_configuration()
# Verify fallback read_string execution
mock_cfg.read_string.assert_called_once_with(main.DEFAULT_CONFIG)
def test_show_reset_success_dialog(qtbot):
"""Verify success dialog pops up and statusbar updates."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
window.statusbar = MagicMock()
with patch("main.QMessageBox.information") as mock_info:
window._show_reset_success_dialog()
mock_info.assert_called_once_with(
window,
"Reset Successful",
"All application settings have been successfully restored to their default values."
)
window.statusbar.showMessage.assert_called_once_with(
"All settings have been reset to their default values.", 5000
)
# ===================== PREFERENCES MENU =====================
@pytest.mark.parametrize("action_text, config_key", [
("2D Data Bypass", "2d_data_bypass"),
("Incompatible Save Bypass", "incompatible_save_bypass"),
("Missing Events Bypass", "missing_events_bypass"),
("Analysis Clearing Bypass", "analysis_clearing_bypass"),
("Folding Bypass", "folding_bypass"),
("Show Advanced Parameters", "advanced_parameters"),
])
def test_preferences_actions(qtbot, action_text, config_key):
"""
Verify each Preferences action toggles checked state and updates config.
Uses the current checked state as a starting point and verifies toggling.
"""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
pref_menu = get_menu_by_title(window.menuBar(), "Preferences")
assert pref_menu is not None, "Preferences menu not found"
action = next(a for a in pref_menu.actions() if a.text() == action_text)
assert action.isCheckable() is True
# Record the initial state
initial_checked = action.isChecked()
# Trigger once → state should toggle
with patch.object(window, '_update_config_setting') as mock_update:
action.trigger()
assert action.isChecked() == (not initial_checked)
mock_update.assert_called_once_with("Preferences", config_key, not initial_checked)
# Trigger again → should toggle back to initial
with patch.object(window, '_update_config_setting') as mock_update:
action.trigger()
assert action.isChecked() == initial_checked
mock_update.assert_called_once_with("Preferences", config_key, initial_checked)
# ===================== TERMINAL MENU =====================
def test_terminal_gui_opens(qtbot):
"""Verify TerminalWindow opens and prevents duplicate instances."""
window = main.MainApplication()
qtbot.addWidget(window)
window.show()
assert getattr(window, "terminal", None) is None
window.terminal_gui()
assert window.terminal is not None
assert window.terminal.isVisible() is True
first_instance = window.terminal
window.terminal_gui()
assert window.terminal is first_instance
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+43 -33
View File
@@ -6,40 +6,47 @@ Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
from __future__ import annotations
# Built-in imports # Built-in imports
import os import os
import sys import sys
import copy import copy
import pickle import pickle
import concurrent import concurrent
import configparser
from pathlib import Path, PurePosixPath from pathlib import Path, PurePosixPath
from typing import TYPE_CHECKING, Any, List, Optional, Union
# External library imports # External library imports
import pandas as pd import pandas as pd
from PySide6.QtWidgets import QMessageBox, QVBoxLayout, QFileDialog, QLabel, QDialog from PySide6.QtWidgets import QMessageBox, QVBoxLayout, QFileDialog, QLabel, QDialog, QWidget
from PySide6.QtCore import QThread, Signal, Qt, QTimer from PySide6.QtCore import QThread, Signal, Qt, QTimer
from PySide6.QtGui import QAction from PySide6.QtGui import QAction
from mne.io import read_raw_snirf from mne.io import read_raw_snirf # type: ignore
from mne.preprocessing.nirs import source_detector_distances from mne.preprocessing.nirs import source_detector_distances # type: ignore
from mne_nirs.channels import get_short_channels # type: ignore from mne_nirs.channels import get_short_channels # type: ignore
from src.shared.flaresbasewidget import ProgressBubble from src.shared.flaresbasewidget import ProgressBubble
from src.shared.shareddata import APP_NAME, CURRENT_VERSION, PLATFORM_NAME, DATA_SCHEMA from src.shared.shareddata import APP_NAME, CURRENT_VERSION, PLATFORM_NAME, DATA_SCHEMA
if TYPE_CHECKING:
from main import MainApplication
class SaveProjectThread(QThread): class SaveProjectThread(QThread):
finished_signal = Signal(str) finished_signal = Signal(str)
error_signal = Signal(str) error_signal = Signal(str)
def __init__(self, filename, project_data): def __init__(self, filename: str, project_data: dict[str, Any]) -> None:
super().__init__() super().__init__()
self.filename = filename self.filename = filename
self.project_data = project_data self.project_data = project_data
def run(self): def run(self) -> None:
try: try:
with open(self.filename, "wb") as f: with open(self.filename, "wb") as f:
pickle.dump(self.project_data, f) pickle.dump(self.project_data, f)
@@ -50,7 +57,7 @@ class SaveProjectThread(QThread):
class SavingOverlay(QDialog): class SavingOverlay(QDialog):
def __init__(self, parent=None): def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent) super().__init__(parent)
self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint) self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint)
self.setModal(True) self.setModal(True)
@@ -75,7 +82,11 @@ class ProjectManager:
- State baseline synchronization (dirty tracking) - State baseline synchronization (dirty tracking)
""" """
def __init__(self, app, file_cfg, cfg_path): def __init__(self,
app: MainApplication,
file_cfg: configparser.ConfigParser,
cfg_path: str,
) -> None:
self.app = app self.app = app
self.file_cfg = file_cfg self.file_cfg = file_cfg
self.cfg_path = cfg_path self.cfg_path = cfg_path
@@ -83,7 +94,7 @@ class ProjectManager:
# ========================================================================= # =========================================================================
# Path Utilities # Path Utilities
# ========================================================================= # =========================================================================
def get_safe_path(self, target_path, project_dir): def get_safe_path(self, target_path: Union[str, Path], project_dir: Union[str, Path]) -> str:
"""Converts an absolute file path to a relative path relative to project_dir.""" """Converts an absolute file path to a relative path relative to project_dir."""
try: try:
target = Path(target_path).resolve() target = Path(target_path).resolve()
@@ -96,7 +107,7 @@ class ProjectManager:
# ========================================================================= # =========================================================================
# File & Folder Opening Dialogs # File & Folder Opening Dialogs
# ========================================================================= # =========================================================================
def open_file_dialog(self): def open_file_dialog(self) -> None:
"""Opens dialog to pick a single .snirf file.""" """Opens dialog to pick a single .snirf file."""
file_path, _ = QFileDialog.getOpenFileName( file_path, _ = QFileDialog.getOpenFileName(
self.app, "Open File", "", "SNIRF Files (*.snirf);;All Files (*)" self.app, "Open File", "", "SNIRF Files (*.snirf);;All Files (*)"
@@ -104,14 +115,14 @@ class ProjectManager:
if file_path: if file_path:
self._load_files_into_pipeline([os.path.normpath(file_path)]) self._load_files_into_pipeline([os.path.normpath(file_path)])
def open_folder_dialog(self): def open_folder_dialog(self)-> None:
"""Recursively finds all .snirf files in a selected directory.""" """Recursively finds all .snirf files in a selected directory."""
folder_path = QFileDialog.getExistingDirectory(self.app, "Select Folder", "") folder_path = QFileDialog.getExistingDirectory(self.app, "Select Folder", "")
if folder_path: if folder_path:
snirf_files = [os.path.normpath(str(f)) for f in Path(folder_path).rglob("*.snirf")] snirf_files = [os.path.normpath(str(f)) for f in Path(folder_path).rglob("*.snirf")]
self._load_files_into_pipeline(snirf_files) self._load_files_into_pipeline(snirf_files)
def _load_files_into_pipeline(self, file_paths): def _load_files_into_pipeline(self, file_paths: List[str]) -> None:
"""Loads .snirf files into UI using chunked batches and background workers.""" """Loads .snirf files into UI using chunked batches and background workers."""
app = self.app app = self.app
if not file_paths: if not file_paths:
@@ -151,7 +162,7 @@ class ProjectManager:
# Queue chunked widget creation # Queue chunked widget creation
CHUNK_SIZE = 10 CHUNK_SIZE = 10
def process_chunk(file_queue): def process_chunk(file_queue: List[str]) -> None:
chunk = file_queue[:CHUNK_SIZE] chunk = file_queue[:CHUNK_SIZE]
remaining = file_queue[CHUNK_SIZE:] remaining = file_queue[CHUNK_SIZE:]
@@ -187,7 +198,7 @@ class ProjectManager:
process_chunk(new_files) process_chunk(new_files)
def add_files_to_project(self, file_paths): def add_files_to_project(self, file_paths: List[str]) -> None:
"""Adds file paths to the application state, creating bubble UI items.""" """Adds file paths to the application state, creating bubble UI items."""
app = self.app app = self.app
normalized_paths = [os.path.normpath(p) for p in file_paths] normalized_paths = [os.path.normpath(p) for p in file_paths]
@@ -220,7 +231,7 @@ class ProjectManager:
# ========================================================================= # =========================================================================
# Project Loading # Project Loading
# ========================================================================= # =========================================================================
def load_project_dialog(self): def load_project_dialog(self) -> None:
"""Prompts for a project file and loads it.""" """Prompts for a project file and loads it."""
app = self.app app = self.app
filename, _ = QFileDialog.getOpenFileName( filename, _ = QFileDialog.getOpenFileName(
@@ -229,7 +240,7 @@ class ProjectManager:
if filename: if filename:
self.load_project(filename) self.load_project(filename)
def load_project(self, filename): def load_project(self, filename: str) -> None:
"""Loads a .flare project file into the application.""" """Loads a .flare project file into the application."""
app = self.app app = self.app
try: try:
@@ -325,7 +336,7 @@ class ProjectManager:
has_data = any(len(getattr(app, item["key"], {})) > 0 for item in DATA_SCHEMA) has_data = any(len(getattr(app, item["key"], {})) > 0 for item in DATA_SCHEMA)
if hasattr(app, "button1"): if hasattr(app, "button1"):
app.button1.setVisible(not has_data) app.button1.setVisible(has_data)
if hasattr(app, "button3"): if hasattr(app, "button3"):
app.button3.setVisible(has_data) app.button3.setVisible(has_data)
@@ -343,7 +354,7 @@ class ProjectManager:
# ========================================================================= # =========================================================================
# Project Saving (Save / Save As) # Project Saving (Save / Save As)
# ========================================================================= # =========================================================================
def save_project(self, onCrash=False, ask=False): def save_project(self, onCrash: bool = False, ask: bool = False) -> None:
""" """
Saves the project to disk. Saves the project to disk.
- ask=False: Quick Save to self.app.current_project_path (prompts if unsaved). - ask=False: Quick Save to self.app.current_project_path (prompts if unsaved).
@@ -436,7 +447,7 @@ class ProjectManager:
current_params = app.config_dict[first_file] current_params = app.config_dict[first_file]
# 5. Build Serialized Payload # 5. Build Serialized Payload
project_data = { project_data: dict[str, Any] = {
item["key"]: getattr(app, item["key"], {}) for item in DATA_SCHEMA item["key"]: getattr(app, item["key"], {}) for item in DATA_SCHEMA
} }
project_data.update({ project_data.update({
@@ -448,7 +459,7 @@ class ProjectManager:
"current_ui_params": current_params, "current_ui_params": current_params,
}) })
def sanitize(obj): def sanitize(obj: Any) -> Any:
if isinstance(obj, Path): if isinstance(obj, Path):
return str(PurePosixPath(obj)) return str(PurePosixPath(obj))
elif isinstance(obj, dict): elif isinstance(obj, dict):
@@ -469,7 +480,7 @@ class ProjectManager:
app.save_thread = SaveProjectThread(filename, project_data) app.save_thread = SaveProjectThread(filename, project_data)
def _on_save_success(saved_file): def _on_save_success(saved_file: str) -> None:
if hasattr(app, "saving_overlay"): if hasattr(app, "saving_overlay"):
app.saving_overlay.close() app.saving_overlay.close()
@@ -483,7 +494,7 @@ class ProjectManager:
app, "Success", f"Project saved to:\n{saved_file}" app, "Success", f"Project saved to:\n{saved_file}"
) )
def _on_save_error(error_msg): def _on_save_error(error_msg: str) -> None:
if hasattr(app, "saving_overlay"): if hasattr(app, "saving_overlay"):
app.saving_overlay.close() app.saving_overlay.close()
if not onCrash: if not onCrash:
@@ -500,7 +511,7 @@ class ProjectManager:
QMessageBox.critical(app, "Error", f"Failed to save project:\n{e}") QMessageBox.critical(app, "Error", f"Failed to save project:\n{e}")
def update_recent_projects_menu(self): def update_recent_projects_menu(self) -> None:
"""Clears and rebuilds the Recent Projects submenu items.""" """Clears and rebuilds the Recent Projects submenu items."""
app = self.app app = self.app
if not hasattr(app, "recent_projects_menu"): if not hasattr(app, "recent_projects_menu"):
@@ -526,7 +537,7 @@ class ProjectManager:
) )
app.recent_projects_menu.addAction(action) app.recent_projects_menu.addAction(action)
def add_to_recent_projects(self, project_path): def add_to_recent_projects(self, project_path: str) -> None:
"""Adds a project path, moves it to the top, and hard caps at 10.""" """Adds a project path, moves it to the top, and hard caps at 10."""
raw_projects = self.file_cfg.get("File", "recent_projects", fallback="") raw_projects = self.file_cfg.get("File", "recent_projects", fallback="")
projects = [p.strip() for p in raw_projects.split(",") if p.strip()] projects = [p.strip() for p in raw_projects.split(",") if p.strip()]
@@ -546,7 +557,7 @@ class ProjectManager:
self.update_recent_projects_menu() self.update_recent_projects_menu()
def open_recent_project(self, project_path): def open_recent_project(self, project_path: str) -> None:
"""The slot that executes when a recent project entry is clicked.""" """The slot that executes when a recent project entry is clicked."""
if os.path.exists(project_path): if os.path.exists(project_path):
print(f"Opening recent project: {project_path}") print(f"Opening recent project: {project_path}")
@@ -577,7 +588,7 @@ class ProjectManager:
# ========================================================================= # =========================================================================
# Recent Files Operations # Recent Files Operations
# ========================================================================= # =========================================================================
def update_recent_files_menu(self): def update_recent_files_menu(self) -> None:
"""Clears and rebuilds the Recent Files submenu items.""" """Clears and rebuilds the Recent Files submenu items."""
app = self.app app = self.app
if not hasattr(app, "recent_files_menu"): if not hasattr(app, "recent_files_menu"):
@@ -600,7 +611,7 @@ class ProjectManager:
) )
app.recent_files_menu.addAction(action) app.recent_files_menu.addAction(action)
def add_to_recent_files(self, file_path): def add_to_recent_files(self, file_path: str) -> None:
"""Adds a path, moves it to the top, and hard caps the list at 10.""" """Adds a path, moves it to the top, and hard caps the list at 10."""
raw_files = self.file_cfg.get("File", "recent_files", fallback="") raw_files = self.file_cfg.get("File", "recent_files", fallback="")
files = [f.strip() for f in raw_files.split(",") if f.strip()] files = [f.strip() for f in raw_files.split(",") if f.strip()]
@@ -620,7 +631,7 @@ class ProjectManager:
self.update_recent_files_menu() self.update_recent_files_menu()
def open_recent_file(self, file_path): def open_recent_file(self, file_path: str) -> None:
"""The slot that executes when someone clicks a recent file entry.""" """The slot that executes when someone clicks a recent file entry."""
if os.path.exists(file_path): if os.path.exists(file_path):
print(f"Opening recent file: {file_path}") print(f"Opening recent file: {file_path}")
@@ -647,11 +658,11 @@ class ProjectManager:
# ========================================================================= # =========================================================================
# Baseline Synchronization & Dirty Checks # Baseline Synchronization & Dirty Checks
# ========================================================================= # =========================================================================
def sync_metadata_baseline(self): def sync_metadata_baseline(self) -> None:
"""Captures current file_metadata state as baseline.""" """Captures current file_metadata state as baseline."""
self.app.saved_file_metadata = copy.deepcopy(getattr(self.app, "file_metadata", {})) self.app.saved_file_metadata = copy.deepcopy(getattr(self.app, "file_metadata", {}))
def is_metadata_dirty(self): def is_metadata_dirty(self) -> bool:
"""Returns True if file metadata has been modified relative to saved baseline.""" """Returns True if file metadata has been modified relative to saved baseline."""
current_meta = getattr(self.app, "file_metadata", {}) current_meta = getattr(self.app, "file_metadata", {})
saved_meta = getattr(self.app, "saved_file_metadata", {}) saved_meta = getattr(self.app, "saved_file_metadata", {})
@@ -671,7 +682,7 @@ class ProjectManager:
return False return False
def reset_all_dirty_states(self): def reset_all_dirty_states(self) -> None:
"""Resets parameter, file, and metadata baselines after load/save.""" """Resets parameter, file, and metadata baselines after load/save."""
# 1. Sync file list baseline # 1. Sync file list baseline
self.app.saved_selected_paths = copy.deepcopy(getattr(self.app, "selected_paths", [])) self.app.saved_selected_paths = copy.deepcopy(getattr(self.app, "selected_paths", []))
@@ -692,7 +703,6 @@ class ProjectManager:
def _get_bids_demographics(snirf_path: str) -> dict[str, str]: def _get_bids_demographics(snirf_path: str) -> dict[str, str]:
"""Traverses the path of a SNIRF file to extract age/sex/hand from BIDS TSV files. """Traverses the path of a SNIRF file to extract age/sex/hand from BIDS TSV files.
'hand' is only included if a value is present and isn't 'n/a' (case-insensitive) - 'hand' is only included if a value is present and isn't 'n/a' (case-insensitive) -
@@ -708,7 +718,7 @@ def _get_bids_demographics(snirf_path: str) -> dict[str, str]:
if not sub_id: if not sub_id:
return {} return {}
def _row_to_dict(row) -> dict[str, str]: def _row_to_dict(row: pd.Series) -> dict[str, str]:
result = {} result = {}
for field in fields: for field in fields:
if field not in row: if field not in row:
@@ -756,7 +766,7 @@ def _get_bids_demographics(snirf_path: str) -> dict[str, str]:
def extract_metadata_worker(file_name): def extract_metadata_worker(file_name: str) -> dict[str, Any]:
"""Runs in the separate worker process. Returns a clean dict.""" """Runs in the separate worker process. Returns a clean dict."""
# 1. Use preload=False! We only need metadata. # 1. Use preload=False! We only need metadata.
+7
View File
@@ -0,0 +1,7 @@
src\analysis\participantfoldchannels.py 158
src\shared\flaresbasewidget.py 1001+
src\window\updateevents.py 83
flares.py 1001+
main_unit_tests.py 153
main.py 691
project_manager.py 113
-157
View File
@@ -1,157 +0,0 @@
"""
Filename: crossgroupbrainimage.py
Description: Logic for the Cross-Group Brain & Image analysis window
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw
License: GPL-3.0
"""
# Built-in Imports
from pathlib import Path
from typing import Any, cast
# External library imports
from mne.io.base import BaseRaw
import pandas as pd
from pandas import DataFrame
from flares import aggregate_fnirs_group_geometry, plot_2d_3d_contrasts_between_groups
from src.shared.flaresbasewidget import CrossGroupUIMixin, FlaresBaseWidget
from src.shared.shareddata import APP_NAME
PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
0: [
{
"key": "show_optodes",
"label": "Determine what is rendered above the brain. Valid values are 'sensors', 'labels', 'none', 'all'.",
"default": "all",
"type": str,
},
{
"key": "t_or_theta",
"label": "Specify if t values or theta values should be plotted. Valid values are 't', 'theta'",
"default": "theta",
"type": str,
},
{
"key": "show_text",
"label": "Display informative text on the top left corner about the contrast.",
"default": "True",
"type": bool,
},
{
"key": "brain_bounds",
"label": "Graph Upper/Lower Limit",
"default": "1.0",
"type": float,
},
{
"key": "is_3d",
"label": "Should we display the results in a 3D interactive window?",
"default": "True",
"type": bool,
}
],
}
class CrossGroupBrainImageWidget(CrossGroupUIMixin, FlaresBaseWidget):
def __init__(
self,
haemo_dict: dict[str | Path, BaseRaw],
df_ind_dict: dict[str, DataFrame],
design_matrix_dict: dict[str, DataFrame],
contrast_results_dict: dict[str, dict[str, Any]],
group_dict: dict[str, str],
) -> None:
super().__init__("CrossGroupBrainImage")
self.setWindowTitle(f"Cross-Group Brain & Image Viewer - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict
self.df_ind_dict = df_ind_dict
self.design_matrix_dict = design_matrix_dict
self.contrast_results_dict = contrast_results_dict
self.group_dict = group_dict
self.setup_cross_group_ui(["0 (Contrast Image)"])
def process_request(self):
request = self.get_common_request_data(PARAMETERIZED_INDEXES)
if request is None:
return
(selected_event, file_paths_a, file_paths_b, all_selected_paths, selected_indexes, raw_params) = request
param_values = cast(dict[int | str, dict[str, Any]], raw_params)
# Build group-level contrast DataFrames
def concat_group_contrasts(file_paths: list[str], event: str | None) -> pd.DataFrame:
group_df = pd.DataFrame()
for fp in file_paths:
print(f"Looking up contrast for: {fp}")
event_con_dict = self.contrast_results_dict.get(fp, {})
print("Available events for this file:", list(event_con_dict.keys()))
if event and event in event_con_dict:
df = event_con_dict[event]
print(f"Appending contrast df for event: {event}")
group_df = pd.concat([group_df, df], ignore_index=True)
else:
print(f"Event '{event}' not found for {fp}")
return group_df
print("Selected event:", selected_event)
print("File paths A:", file_paths_a)
print("File paths B:", file_paths_b)
contrast_df_a = concat_group_contrasts(file_paths_a, selected_event)
contrast_df_b = concat_group_contrasts(file_paths_b, selected_event)
print("contrast_df_a empty?", contrast_df_a.empty)
print("contrast_df_b empty?", contrast_df_b.empty)
all_raw_objs = [self.haemo_dict.get(fp) for fp in all_selected_paths if self.haemo_dict.get(fp)]
if len(all_raw_objs) > 1:
processed_raw = aggregate_fnirs_group_geometry(all_raw_objs)
elif len(all_raw_objs) == 1 and all_raw_objs[0] is not None:
processed_raw = all_raw_objs[0].copy()
processed_raw.pick(picks="hbo") # type: ignore
else:
processed_raw = None
# Visualizations
for idx in selected_indexes:
if idx == 0:
params = param_values.get(idx, {})
show_optodes = params.get("show_optodes", None)
t_or_theta = params.get("t_or_theta", None)
show_text = params.get("show_text", None)
brain_bounds = params.get("brain_bounds", None)
is_3d = params.get("is_3d", None)
if show_optodes is None or t_or_theta is None or show_text is None or brain_bounds is None or is_3d is None:
print(f"Missing parameters for index {idx}, skipping.")
continue
if not contrast_df_a.empty and not contrast_df_b.empty and processed_raw:
plot_2d_3d_contrasts_between_groups(
contrast_df_a,
contrast_df_b,
raw_haemo=processed_raw,
group_a_name=self.group_a_dropdown.currentText(),
group_b_name=self.group_b_dropdown.currentText(),
is_3d=is_3d,
t_or_theta=t_or_theta,
show_optodes=show_optodes,
show_text=show_text,
brain_bounds=brain_bounds
)
else:
print(f"No method defined for index {idx}")
-356
View File
@@ -1,356 +0,0 @@
"""
Filename: crossgroupstats.py
Description: Cross-Group stats analysis window
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw
License: GPL-3.0
"""
# Built-in imports
from pathlib import Path
from typing import Any, cast
# External library imports
import pandas as pd
from pandas import DataFrame
from mne.io.base import BaseRaw
from flares import run_cross_group_contrast_analysis, run_cross_group_laterality_analysis, run_cross_group_second_level_analysis
from src.shared.flaresbasewidget import CrossGroupUIMixin, FlaresBaseWidget
from src.shared.shareddata import APP_NAME
PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
0: [
{
"key": "p_threshold",
"label": "Significance threshold P-value (e.g. 0.05)",
"default": "0.05",
"type": float,
},
{
"key": "min_subjects",
"label": "Minimum number of participants to process",
"default": "3",
"type": int,
},
{
"key": "correction_method",
"label": "Correction method to utilize. Valid values are 'fdr_bh', 'None'",
"default": "fdr_bh",
"type": str,
},
{
"key": "target_chroma",
"label": "Which chroma to target. Valid values are 'hbo', 'hbr'",
"default": "hbo",
"type": str,
},
{
"key": "threshold_topo",
"label": "threshold_topo: TBD",
"default": False,
"type": bool,
}
],
1: [
{
"key": "p_threshold",
"label": "Significance threshold P-value (e.g. 0.05)",
"default": "0.05",
"type": float,
},
{
"key": "min_subjects",
"label": "Minimum number of participants to process",
"default": "3",
"type": int,
},
{
"key": "correction_method",
"label": "Correction method to utilize. Valid values are 'fdr_bh', 'None'",
"default": "None",
"type": str,
},
{
"key": "target_chroma",
"label": "Which chroma to target. Valid values are 'hbo', 'hbr'",
"default": "hbo",
"type": str,
},
{
"key": "roi_a",
"label": "ROI A (e.g. contralateral region name from regions.json)",
"default": [],
"type": list,
},
{
"key": "roi_b",
"label": "ROI B (e.g. ipsilateral region name from regions.json)",
"default": [],
"type": list,
}
],
2: [
{
"key": "p_value",
"label": "Significance threshold P-value (e.g. 0.05)",
"default": "0.05",
"type": float,
},
{
"key": "min_subjects",
"label": "Minimum number of participants to process",
"default": "3",
"type": int,
},
{
"key": "correction_method",
"label": "Correction method to utilize. Valid values are 'fdr_bh', 'None'",
"default": "fdr_bh",
"type": str,
},
{
"key": "target_chroma",
"label": "Which chroma to target. Valid values are 'hbo', 'hbr'",
"default": "hbo",
"type": str,
},
{
"key": "contrast_name",
"label": "Name of the contrast to use",
"default": [],
"type": list,
},
],
}
DESCRIPTION = """0. Raw ROI Comparison (run_cross_group_second_level_analysis)
\nCompares one ROI's raw response magnitude between two independent groups (e.g. control vs. target) for a given condition, using Welch's t-test. A significant result means the two populations differ in this ROI's response magnitude for this condition. It does not tell you whether that difference is a real, localized, task-specific effect or a generic between-population difference - different overall vascular reactivity, arousal, or skull/scalp optical properties can produce the exact same statistical signature, and two independently recruited groups (especially patients vs. healthy controls) are considerably more likely to differ this way than two subsets of one study population.
\nIf you expected a group difference and didn't find one, the most common cause is within-group heterogeneity swallowing a real between-group difference - a "target" population (e.g. a clinical group) is often more variable than a tightly-screened control group, and that added within-group variance directly weakens a between-group t-test even if the group means truly differ. Small per-group sample sizes compound this. It's also possible the true difference between your groups isn't in raw magnitude at all, but in spatial specificity or task-differentiation - which is exactly why the laterality and contrast-comparison methods exist alongside this one; a null result here doesn't rule those out.
\n\n1. Laterality Comparison (run_cross_group_laterality_analysis)
\nComputes each subject's own contralateral-minus-ipsilateral laterality index first, then compares those indices between the two groups with Welch's t-test. A significant result means the degree of spatial specificity/lateralization differs between the two populations - a claim about lateralization itself, harder to explain away as a generic population confound since person-level differences in overall reactivity largely cancel before the group comparison happens. It says nothing about overall response magnitude between groups (a group could have identical laterality but very different raw amplitude), and it only uses subjects who have both the contra and ipsi ROI valid, so it can lose subjects the raw-ROI comparison would have kept.
\nNon-significance here has two likely sources, and it's worth distinguishing them. First, the same covariance issue from the within-group paired test applies across a whole group: if contra/ipsi responses aren't well-correlated within subjects, the laterality index itself is noisier than either ROI alone, and that added noise now has to clear a between-group test on top of it - a double power cost at small N. Second, and more informative if true: the groups may genuinely have similar lateralization but differ in overall magnitude instead, in which case this test correctly returns null while method 4 (raw comparison) should be the one to look at.
\n\n2. Contrast Comparison (run_cross_group_contrast_analysis)
\nCompares a jointly-fit task contrast (e.g. Task A minus Task B, estimated together within each subject's GLM), aggregated to ROI level, between two independent groups. A significant result means one group differentiates between the two tasks more or less than the other does, at this specific ROI - with systemic noise cancelled at the model-fitting stage, the same benefit that makes the within-group version of this method the strongest of that trio. As with the within-group version, it does not by itself say where a difference is localized unless you compare sign/pattern across multiple ROIs - opposite-signed group differences across regions point to something spatially specific, same-signed differences everywhere point to a diffuse/non-specific group difference (e.g. one group simply has stronger contrast responses across the whole head).
\nIf this comes back non-significant despite an expected group difference, check first whether the underlying single-subject contrast estimates are noisy for either group - small per-group N means the joint contrast's precision depends on the same limited subject count as everything else, and a noisy input propagates all the way through the ROI aggregation. It's also possible for a real, localized sub-regional effect to get washed out by ROI averaging itself: if only part of an ROI's channels actually show the group difference while others don't, the inverse-variance-weighted average can dilute it toward null - in that case, a finer-grained ROI definition (splitting the region further) may recover the effect that a coarser ROI averaged away. Finally, FDR correction across every ROI tested reduces power exactly as it does everywhere else in this framework - a real but modest effect can fail to survive correction even when the raw p-value would have looked convincing on its own.
\n\n
\nWhy channels needed to be aggregated into ROIs: Testing every channel independently means paying a steep multiple-comparisons tax - with dozens of channels, FDR/Bonferroni correction demands very large effect sizes to call anything significant, and at small subject counts (n=5) essentially nothing survives even when a real, consistent effect exists. Collapsing channels into a handful of anatomically meaningful ROIs cuts the number of independent tests from a minimum of ~40 down to 2-8, which lets a genuinely present effect actually clear correction. It also matches the scientific question better: you have a hypothesis about regions (contralateral motor cortex, prefrontal cortex), not about individual source-detector pairs, so testing at the ROI level is testing the thing you actually believe in, using inverse-variance weighting so noisier channels contribute less to the region's combined estimate rather than diluting it equally.
\nWhy some analyses needed contrasts instead of raw values: A single condition's GLM beta is only ever measured relative to the model's implicit intercept, and that intercept absorbs whatever's happening for the rest of the recording - including systemic physiology (blood pressure, arousal, general vascular reactivity) that rises during almost any active task, not just the one you care about. Testing a raw "vs. zero" value can't tell a real, localized neural response apart from that shared full-head noise. A contrast - either a within-subject spatial subtraction (ROI A minus ROI B) or a jointly-fit task contrast (Condition A minus Condition B, estimated together in one GLM) cancels out whatever's common to both halves of the subtraction, leaving something closer to the actual differential signal.
\nWhy a minimum subject count is enforced: Every one of these tests is a t-test, and a t-test's ability to detect a real effect (its power) depends heavily on degrees of freedom - at n=5 (df=4), even a fairly large true effect can produce a middling p-value, and at n=2 (df=1) the test is barely meaningful at all regardless of the underlying data. The min_subjects floor exists to stop a channel or ROI from being silently tested (and potentially reported as significant or non-significant) on a sample too small for the resulting p-value to mean anything reliable - it's better to explicitly skip and flag an underpowered channel than to quietly produce a number that looks statistically legitimate but isn't backed by enough independent observations to trust."""
class CrossGroupStatsWidget(CrossGroupUIMixin, FlaresBaseWidget):
def __init__(
self,
haemo_dict: dict[str | Path, BaseRaw],
cha_dict: dict[str, DataFrame],
df_ind_dict: dict[str, DataFrame],
design_matrix_dict: dict[str, DataFrame],
contrast_results_dict: dict[str, dict[str, Any]],
roi_channel_map_dict: dict[str, dict[str, str]],
group_dict: dict[str, str],
) -> None:
super().__init__("CrossGroupStats")
self.setWindowTitle(f"Cross-Group Stats Viewer - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict
self.cha_dict = cha_dict
self.df_ind_dict = df_ind_dict
self.design_matrix_dict = design_matrix_dict
self.contrast_results_dict = contrast_results_dict
self.roi_channel_map_dict = roi_channel_map_dict
self.group_dict = group_dict
self.setup_cross_group_ui(["0 (Raw ROI Comparison)", "1 (Laterality Comparison)", "2 (Contrast Comparison)",], placeholder_text=DESCRIPTION)
def process_request(self):
request = self.get_common_request_data(PARAMETERIZED_INDEXES, self.df_ind_dict, self.contrast_results_dict)
if request is None:
return
(selected_event, file_paths_a, file_paths_b, _, selected_indexes, raw_params) = request
param_values = cast(dict[int | str, dict[str, Any]], raw_params)
valid_dfs = [df for df in self.df_ind_dict.values() if not df.empty]
if valid_dfs:
df_ind_combined = pd.concat(valid_dfs, ignore_index=True)
else:
df_ind_combined = pd.DataFrame()
valid_chas = [df for df in self.cha_dict.values() if not df.empty]
cha_combined = pd.concat(valid_chas, ignore_index=True) if valid_chas else pd.DataFrame()
sample_path = file_paths_a[0]
p_haemo = self.haemo_dict.get(sample_path)
# Visualizations
for idx in selected_indexes:
if idx == 0:
params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 3)
correction_method = params.get("correction_method", "fdr_bh")
target_chroma = params.get("target_chroma", "hbo")
threshold_topo = params.get("threshold_topo", False)
selected_roi_maps = {
fp: self.roi_channel_map_dict[fp]
for fp in (file_paths_a + file_paths_b)
if fp in self.roi_channel_map_dict
}
run_cross_group_second_level_analysis(
df_roi_all=df_ind_combined, # Individual stats dataframe
file_paths_a=file_paths_a,
file_paths_b=file_paths_b,
group_a_name=self.group_a_dropdown.currentText(),
group_b_name=self.group_b_dropdown.currentText(),
df_cha_all=cha_combined,
raw_haemo=p_haemo,
p_threshold=p_threshold,
min_subjects=min_subjects,
correction_method=correction_method,
target_chroma=target_chroma,
selected_event=selected_event,
roi_channel_maps=selected_roi_maps,
threshold_topo=threshold_topo # Shows the raw difference map (Unthresholded)
)
elif idx == 1:
if not selected_event:
print("Laterality comparison requires a specific event/condition "
"to be selected first.")
continue
params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 3)
correction_method = params.get("correction_method", "None")
target_chroma = params.get("target_chroma", "hbo")
roi_a: str = params.get("roi_a", "").strip()
roi_b: str = params.get("roi_b", "").strip()
if not roi_a or not roi_b:
print("Both a contralateral and ipsilateral ROI name must be specified.")
continue
if correction_method == "None":
correction_method = None
# Build each group's dataframe directly from the dict using
# the file-path lists as keys - no ID cleaning/matching needed.
def _build_group_df(
file_paths: list[str],
dict_source: dict[str, DataFrame]
) -> DataFrame:
valid_dfs = [
dict_source[fp] for fp in file_paths
if fp in dict_source and not dict_source[fp].empty
]
return pd.concat(valid_dfs, ignore_index=True) if valid_dfs else pd.DataFrame()
df_roi_a = _build_group_df(file_paths_a, self.df_ind_dict)
df_roi_b = _build_group_df(file_paths_b, self.df_ind_dict)
if df_roi_a.empty or df_roi_b.empty:
print("No ROI data (df_ind) found for one or both groups.")
continue
run_cross_group_laterality_analysis(
df_roi_all_a=df_roi_a,
df_roi_all_b=df_roi_b,
roi_pairs=(roi_a, roi_b),
condition=selected_event,
group_a_name=self.group_a_dropdown.currentText(),
group_b_name=self.group_b_dropdown.currentText(),
target_chroma=target_chroma,
min_subjects=min_subjects,
p_threshold=p_threshold,
correction_method=correction_method,
roi_contra_label=roi_a,
roi_ipsi_label=roi_b,
)
elif idx == 2:
params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 3)
correction_method = params.get("correction_method", "fdr_bh")
target_chroma = params.get("target_chroma", "hbo")
contrast_name = params.get("contrast_name", "")
if not contrast_name:
print("A contrast name must be specified.")
continue
# Build each group's channel-level contrast dataframe
# directly from contrast_results_dict, keyed by file path -
# same dict-key approach as the laterality patch, avoids
# any ID-string matching.
def _build_group_contrast_df(
file_paths: list[str],
contrast_dict: dict[str, dict[str, pd.DataFrame]],
name: str,
) -> pd.DataFrame:
all_rows: list[DataFrame] = []
for fp in file_paths:
condition_dfs = contrast_dict.get(fp)
if condition_dfs is None:
print(f" [MISSING] '{fp}' not found in contrast_results.")
continue
if name in condition_dfs:
df = condition_dfs[name].copy()
df["ID"] = fp
df["contrast_name"] = name
all_rows.append(df)
else:
print(f" [MISSING CONTRAST] '{name}' not available for '{fp}'.")
return pd.concat(all_rows, ignore_index=True) if all_rows else pd.DataFrame()
df_contrasts_a = _build_group_contrast_df(file_paths_a, self.contrast_results_dict, contrast_name)
df_contrasts_b = _build_group_contrast_df(file_paths_b, self.contrast_results_dict, contrast_name)
if df_contrasts_a.empty or df_contrasts_b.empty:
print("No contrast data found for one or both groups.")
continue
roi_maps_a = {
fp: self.roi_channel_map_dict[fp]
for fp in file_paths_a
if fp in self.roi_channel_map_dict
}
roi_maps_b = {
fp: self.roi_channel_map_dict[fp]
for fp in file_paths_b
if fp in self.roi_channel_map_dict
}
if not roi_maps_a or not roi_maps_b:
print("No channel-to-ROI mapping available for one or both groups.")
continue
run_cross_group_contrast_analysis(
df_contrasts_a=df_contrasts_a,
df_contrasts_b=df_contrasts_b,
contrast_name=contrast_name,
roi_channel_maps_a=roi_maps_a,
roi_channel_maps_b=roi_maps_b,
group_a_name=self.group_a_dropdown.currentText(),
group_b_name=self.group_b_dropdown.currentText(),
target_chroma=target_chroma,
min_subjects=min_subjects,
p_threshold=p_threshold,
correction_method=correction_method,
)
else:
print("no")
+77 -9
View File
@@ -9,7 +9,6 @@ License: GPL-3.0
# Built-in imports # Built-in imports
import os import os
from pathlib import Path
from typing import Any from typing import Any
# External library imports # External library imports
@@ -27,26 +26,33 @@ from src.shared.shareddata import APP_NAME
class ExportToCSVWidget(CSVUIMixin, FlaresBaseWidget): class ExportToCSVWidget(CSVUIMixin, FlaresBaseWidget):
def __init__( def __init__(
self, self,
haemo_dict: dict[str | Path, BaseRaw], haemo_dict: dict[str, BaseRaw],
cha_dict: dict[str, DataFrame], cha_dict: dict[str, DataFrame],
df_ind_dict: dict[str, DataFrame], df_ind_dict: dict[str, DataFrame],
design_matrix_dict: dict[str, DataFrame], design_matrix_dict: dict[str, DataFrame],
contrast_results_dict: dict[str, dict[str, Any]], contrast_results_dict: dict[str, dict[str, Any]],
group_dict: dict[str, str], group_dict: dict[str, str],
config_dict: dict[str, str], config_dict: dict[str, dict[str, Any]],
fir_feature_dict: dict[str, dict[str, Any]],
qc_dict: dict[str, dict[str, Any]],
) -> None: ) -> None:
super().__init__("ExportToCSV") super().__init__("ExportToCSV")
self.setWindowTitle(f"Export To CSV Viewer - {APP_NAME.upper()}") self.setWindowTitle(f"Export To CSV Viewer - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict self.haemo_dict = haemo_dict
self.cha_dict = cha_dict self.cha_dict = cha_dict
# self.df_ind = df_ind_dict self.df_ind_dict = df_ind_dict
# self.design_matrix = design_matrix_dict self.design_matrix = design_matrix_dict
# self.contrast_results_dict = contrast_results_dict self.contrast_results_dict = contrast_results_dict
# self.group = group_dict self.group_dict = group_dict
self.config_dict = config_dict self.config_dict = config_dict
self.fir_feature_dict = fir_feature_dict
self.qc_dict = qc_dict
self.setup_csv_ui(["0 (Export Data to CSV)", "1 (CSV for SPARKS)", "2 (Export Configuration to CSV)", "3 (Paragraph of Configuration)"]) self.setup_csv_ui(["0 (Export Data to CSV)", "1 (CSV for SPARKS)", "2 (Export Configuration to CSV)", "3 (Paragraph of Configuration)", "4 (Export FIR Waveform Features to CSV)",
"5 (Export Quality Control Metrics to CSV)",
"6 (Export Master Consolidated Matrix [All Participants into 1 CSV])"
])
def process_request(self): def process_request(self):
@@ -114,6 +120,68 @@ class ExportToCSVWidget(CSVUIMixin, FlaresBaseWidget):
magic_string = self.gen_magic_str(first_params) magic_string = self.gen_magic_str(first_params)
self.placeholder_label.setText(magic_string) self.placeholder_label.setText(magic_string)
# elif idx == 4:
# # FIR Waveform Features Export
# fir_data = self.fir_feature_dict.get(file_path)
# if fir_data and isinstance(fir_data, dict):
# names = fir_data.get("feature_names", [])
# vals = fir_data.get("features", [])
# chans = fir_data.get("feature_channels", [])
# fir_df = DataFrame({
# "Feature_Name": names,
# "Channel": chans if len(chans) == len(names) else ["N/A"] * len(names),
# "Value": vals
# })
# save_path = os.path.join(output_dir, f"{base_filename}_fir_features.csv")
# fir_df.to_csv(save_path, index=False)
# success_count += 1
# elif idx == 5:
# # Quality Control (QC) Metrics Export
# qc_data = self.qc_dict.get(file_path)
# if qc_data and isinstance(qc_data, dict):
# qc_df = DataFrame(list(qc_data.items()), columns=["Metric", "Value"])
# save_path = os.path.join(output_dir, f"{base_filename}_qc_metrics.csv")
# qc_df.to_csv(save_path, index=False)
# success_count += 1
# elif idx == 6:
# # Master Consolidated Matrix (1 single CSV combining all selected participants)
# save_path = os.path.join(output_dir, f"{APP_NAME}_master_consolidated.csv")
# if not os.path.exists(save_path):
# master_rows: list[dict[str, Any]] = []
# for fp in selected_file_paths:
# abs_path = os.path.abspath(fp)
# grp = self.group_dict.get(fp, "Unknown")
# row: dict[str, Any] = {"Participant": abs_path, "Group": grp}
# # QC Metrics
# qc_info = self.qc_dict.get(fp, {})
# if isinstance(qc_info, dict):
# for mk, mv in qc_info.items():
# row[f"QC_{mk}"] = mv
# # FIR Features
# fir_info = self.fir_feature_dict.get(fp, {})
# print("1")
# if isinstance(fir_info, dict):
# print("2")
# f_names = fir_info.get("feature_names", [])
# f_vals = fir_info.get("features", [])
# print("3")
# if len(f_names) == len(f_vals):
# print("4")
# for fn, fv in zip(f_names, f_vals):
# row[f"FIR_{fn}"] = fv
# master_rows.append(row)
# if master_rows:
# df_master = DataFrame(master_rows)
# df_master.to_csv(save_path, index=False)
# success_count += 1
else: else:
print(f"No method defined for index {idx}") print(f"No method defined for index {idx}")
@@ -134,7 +202,7 @@ class ExportToCSVWidget(CSVUIMixin, FlaresBaseWidget):
# win.show() # win.show()
def gen_magic_str(self, all_params): def gen_magic_str(self, all_params: dict[str, str]) -> str:
magic_str = "To start, the data was loaded into the application. " magic_str = "To start, the data was loaded into the application. "
if all_params['DOWNSAMPLE']: if all_params['DOWNSAMPLE']:
+72 -129
View File
@@ -7,52 +7,22 @@ Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
# Built-in Imports # Built-in imports
from pathlib import Path
from typing import Any, cast from typing import Any, cast
# External library imports # External library imports
from mne.io.base import BaseRaw
import pandas as pd import pandas as pd
from pandas import DataFrame from pandas import DataFrame
from mne import Annotations from flares import aggregate_fnirs_group_geometry, plot_2d_3d_contrasts_between_groups
from mne.io.base import BaseRaw
from flares import aggregate_fnirs_group_geometry, plot_fir_model_results, brain_3d_visualization
from src.shared.flaresbasewidget import InterGroupUIMixin, FlaresBaseWidget from src.shared.flaresbasewidget import InterGroupUIMixin, FlaresBaseWidget
from src.shared.shareddata import APP_NAME from src.shared.shareddata import APP_NAME
PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = { PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
0: [ 0: [
{
"key": "lower_bound",
"label": "Lower bound + <description>",
"default": "-0.3",
"type": float, # specify int here
},
{
"key": "upper_bound",
"label": "Upper bound + <description>",
"default": "0.8",
"type": float, # specify int here
}
],
1: [
{
"key": "p_value",
"label": "Significance threshold P-value (e.g. 0.05)",
"default": "0.05",
"type": float,
},
{
"key": "graph_bounds",
"label": "Graph Upper/Lower Limit",
"default": "3.0",
"type": float,
}
],
2: [
{ {
"key": "show_optodes", "key": "show_optodes",
"label": "Determine what is rendered above the brain. Valid values are 'sensors', 'labels', 'none', 'all'.", "label": "Determine what is rendered above the brain. Valid values are 'sensors', 'labels', 'none', 'all'.",
@@ -67,8 +37,8 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
}, },
{ {
"key": "show_text", "key": "show_text",
"label": "Display informative text on the top left corner. THIS DOES NOT WORK AND SHOULD BE LEFT AT FALSE", "label": "Display informative text on the top left corner about the contrast.",
"default": "False", "default": "True",
"type": bool, "type": bool,
}, },
{ {
@@ -76,132 +46,82 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
"label": "Graph Upper/Lower Limit", "label": "Graph Upper/Lower Limit",
"default": "1.0", "default": "1.0",
"type": float, "type": float,
},
{
"key": "is_3d",
"label": "Should we display the results in a 3D interactive window?",
"default": "True",
"type": bool,
} }
], ],
} }
DESCRIPTION = """\n1. Group Contrast 2D/3D (plot_2d_3d_contrasts_between_groups)
\nCompares two participant groups' contrast results (e.g. condition-vs-baseline effects) channel-by-channel, fitting a mixed-effects model with group, channel, and chromophore as factors. Produces BOTH directions of the contrast (Group A minus Group B, and Group B minus Group A) as separate plots, so the sign convention is explicit either way you read it.
\nis_3d controls the display: True renders a 3D weighted brain map per contrast direction (same rendering as intra method 1, but showing the between-group difference rather than a single group's estimate); False renders a 2D topographic map instead, which is faster and sometimes easier to read at a glance for a whole-head pattern.
\nA channel is only included if BOTH groups have at least min_participants_per_group (default 2) contributing participants for that channel - channels present in only one group, or with too few participants in either group to estimate within-group variance, are dropped before fitting. If this drops too many channels, check that both groups have enough participants with usable data for the selected event/channels.
\nAs with other mixed-effects models in this app, small participant counts can produce convergence warnings; when that happens, the model falls back to pooled OLS, which does not account for the repeated-measures structure of the data and may understate uncertainty - treat results run this way with extra caution.
"""
class InterGroupBrainImageWidget(InterGroupUIMixin, FlaresBaseWidget): class InterGroupBrainImageWidget(InterGroupUIMixin, FlaresBaseWidget):
def __init__( def __init__(
self, self,
haemo_dict: dict[str | Path, BaseRaw], haemo_dict: dict[str, BaseRaw],
cha_dict: dict[str, DataFrame],
df_ind_dict: dict[str, DataFrame], df_ind_dict: dict[str, DataFrame],
design_matrix_dict: dict[str, DataFrame], design_matrix_dict: dict[str, DataFrame],
contrast_results_dict: dict[str, dict[str, Any]], contrast_results_dict: dict[str, dict[str, Any]],
group_dict: dict[str, str] group_dict: dict[str, str],
) -> None: ) -> None:
super().__init__("InterGroupBrainImage") super().__init__("InterGroupBrainImage")
self.setWindowTitle(f"Inter-Group Brain & Image Viewer - {APP_NAME.upper()}") self.setWindowTitle(f"Inter-Group Brain & Image Viewer - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict self.haemo_dict = haemo_dict
self.cha_dict = cha_dict
self.df_ind_dict = df_ind_dict self.df_ind_dict = df_ind_dict
self.design_matrix_dict = design_matrix_dict self.design_matrix_dict = design_matrix_dict
self.contrast_results_dict = contrast_results_dict self.contrast_results_dict = contrast_results_dict
self.group_dict = group_dict self.group_dict = group_dict
self.setup_inter_group_ui(["0 (GLM Results)", "1 (Significance)", "2 (Brain Activity Visualization)",]) self.setup_inter_group_ui(["0 (Group Contrast 2D/3D)"], placeholder_text=DESCRIPTION)
def process_request(self): def process_request(self):
request = self.get_common_request_data(PARAMETERIZED_INDEXES) request = self.get_common_request_data(PARAMETERIZED_INDEXES)
if request is None: if request is None:
return return
(selected_event, selected_file_paths, selected_indexes, raw_params) = request (selected_event, file_paths_a, file_paths_b, all_selected_paths, selected_indexes, raw_params) = request
param_values = cast(dict[int | str, dict[str, Any]], raw_params) param_values = cast(dict[int | str, dict[str, Any]], raw_params)
all_cha = pd.DataFrame() # Build group-level contrast DataFrames
for file_path in selected_file_paths: def concat_group_contrasts(file_paths: list[str], event: str | None) -> pd.DataFrame:
haemo_obj = self.haemo_dict.get(file_path) group_df = pd.DataFrame()
for fp in file_paths:
if haemo_obj is None: print(f"Looking up contrast for: {fp}")
continue event_con_dict = self.contrast_results_dict.get(fp, {})
print("Available events for this file:", list(event_con_dict.keys()))
if selected_event: if event and event in event_con_dict:
raw_annotations = getattr(haemo_obj, "annotations", None) df = event_con_dict[event]
print(f"Appending contrast df for event: {event}")
if raw_annotations is not None: group_df = pd.concat([group_df, df], ignore_index=True)
annotations = cast(Annotations, raw_annotations)
descriptions = cast(list[str], list(annotations.description))
participant_events: set[str] = set(descriptions)
else: else:
participant_events: set[str] = set() print(f"Event '{event}' not found for {fp}")
return group_df
if selected_event not in participant_events: print("Selected event:", selected_event)
print(f"Skipping {self.participant_map[file_path]}: Event '{selected_event}' not found.") print("File paths A:", file_paths_a)
continue print("File paths B:", file_paths_b)
cha_df = self.cha_dict.get(file_path) contrast_df_a = concat_group_contrasts(file_paths_a, selected_event)
if cha_df is not None: contrast_df_b = concat_group_contrasts(file_paths_b, selected_event)
all_cha = pd.concat([all_cha, cha_df], ignore_index=True)
# Pass the necessary arguments to each method print("contrast_df_a empty?", contrast_df_a.empty)
file_path = selected_file_paths[0] print("contrast_df_b empty?", contrast_df_b.empty)
p_haemo = self.haemo_dict.get(file_path)
p_design_matrix = self.design_matrix_dict.get(file_path)
df_group = pd.DataFrame() all_raw_objs = [self.haemo_dict.get(fp) for fp in all_selected_paths if self.haemo_dict.get(fp)]
if selected_file_paths:
for file_path in selected_file_paths:
df = self.df_ind_dict.get(file_path)
if df is not None:
df_group = pd.concat([df_group, df], ignore_index=True)
for idx in selected_indexes:
if idx == 0:
params = param_values.get(idx, {})
lower_bound = params.get("lower_bound", None)
upper_bound = params.get("upper_bound", None)
if lower_bound is None or upper_bound is None:
print(f"Missing parameters for index {idx}, skipping.")
continue
plot_fir_model_results(df_group, p_haemo, p_design_matrix, selected_event, lower_bound, upper_bound)
elif idx == 1:
params = param_values.get(idx, {})
p_val = params.get("p_value", None)
graph_bounds = params.get("graph_bounds", None)
if p_val is None or graph_bounds is None:
print(f"Missing parameters for index {idx}, skipping.")
continue
all_contrasts: list[DataFrame] = []
for fp in selected_file_paths:
condition_dfs = self.contrast_results_dict.get(fp, {})
if selected_event in condition_dfs:
df = condition_dfs[selected_event].copy()
df["ID"] = fp
all_contrasts.append(df)
if not all_contrasts:
print("No contrast data found for selected participants and event.")
return
# TODO: look at intergroupstats and figure out what to do
_ = pd.concat(all_contrasts, ignore_index=True)
#flares.run_second_level_analysis(df_contrasts, p_haemo, p_val, graph_bounds)
elif idx == 2:
params = param_values.get(idx, {})
show_optodes = params.get("show_optodes", None)
t_or_theta = params.get("t_or_theta", None)
show_text = params.get("show_text", None)
brain_bounds = params.get("brain_bounds", None)
if show_optodes is None or t_or_theta is None or show_text is None or brain_bounds is None:
print(f"Missing parameters for index {idx}, skipping.")
continue
all_raw_objs = [self.haemo_dict.get(fp) for fp in selected_file_paths if self.haemo_dict.get(fp)]
if len(all_raw_objs) > 1: if len(all_raw_objs) > 1:
processed_raw = aggregate_fnirs_group_geometry(all_raw_objs) processed_raw = aggregate_fnirs_group_geometry(all_raw_objs)
@@ -211,10 +131,33 @@ class InterGroupBrainImageWidget(InterGroupUIMixin, FlaresBaseWidget):
else: else:
processed_raw = None processed_raw = None
brain_3d_visualization(processed_raw, all_cha, selected_event, t_or_theta=t_or_theta, show_optodes=show_optodes, show_text=show_text, brain_bounds=brain_bounds) # Visualizations
for idx in selected_indexes:
if idx == 0:
params = param_values.get(idx, {})
show_optodes = params.get("show_optodes", None)
t_or_theta = params.get("t_or_theta", None)
show_text = params.get("show_text", None)
brain_bounds = params.get("brain_bounds", None)
is_3d = params.get("is_3d", None)
elif idx == 3: if show_optodes is None or t_or_theta is None or show_text is None or brain_bounds is None or is_3d is None:
pass print(f"Missing parameters for index {idx}, skipping.")
continue
if not contrast_df_a.empty and not contrast_df_b.empty and processed_raw:
plot_2d_3d_contrasts_between_groups(
contrast_df_a,
contrast_df_b,
raw_haemo=processed_raw,
group_a_name=self.group_a_dropdown.currentText(),
group_b_name=self.group_b_dropdown.currentText(),
is_3d=is_3d,
t_or_theta=t_or_theta,
show_optodes=show_optodes,
show_text=show_text,
brain_bounds=brain_bounds
)
else: else:
print(f"No method defined for index {idx}") print(f"No method defined for index {idx}")
@@ -1,83 +0,0 @@
"""
Filename: intergroupfunctionalconnectivity.py
Description: Logic for the Inter-Group Functional Connectivity analysis window
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw
License: GPL-3.0
"""
# Built-in imports
from pathlib import Path
from typing import Any, cast
# External library imports
from PySide6.QtWidgets import QMessageBox
from mne.io.base import BaseRaw
from flares import run_group_functional_connectivity
from src.shared.flaresbasewidget import InterGroupUIMixin, FlaresBaseWidget
from src.shared.shareddata import APP_NAME
PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
0: [
{
"key": "n_lines",
"label": "<Description>",
"default": "20",
"type": int,
},
{
"key": "vmin",
"label": "<Description>",
"default": "0.9",
"type": float,
},
],
}
class InterGroupFunctionalConnectivityWidget(InterGroupUIMixin, FlaresBaseWidget):
def __init__(
self,
haemo_dict: dict[str | Path, BaseRaw],
group_dict: dict[str, str],
config_dict: dict[str, str]
) -> None:
super().__init__("InterGroupFunctionalConnectivity")
self.setWindowTitle(f"Inter-Group Functional Connectivity Viewer [BETA] - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict
#self.group_dict = group_dict
self.config_dict = config_dict
QMessageBox.warning(self, f"Warning - {APP_NAME.upper()}", f"Functional Connectivity is still in development and the results should currently be taken with a grain of salt. "
"By clicking OK, you accept that the images generated may not be factual.")
self.setup_inter_group_ui(["0 (Betas)",])
def process_request(self):
request = self.get_common_request_data(PARAMETERIZED_INDEXES)
if request is None:
return
(selected_event, selected_file_paths, selected_indexes, raw_params) = request
param_values = cast(dict[int | str, dict[str, Any]], raw_params)
for idx in selected_indexes:
if idx == 0:
params = param_values.get(idx, {})
n_lines = params.get("n_lines", None)
vmin = params.get("vmin", None)
if n_lines is None or vmin is None:
print(f"Missing parameters for index {idx}, skipping.")
continue
run_group_functional_connectivity(self.haemo_dict, self.config_dict, selected_file_paths, selected_event, 50, 0.5)
else:
print(f"No method defined for index {idx}")
+132 -180
View File
@@ -8,17 +8,15 @@ License: GPL-3.0
""" """
# Built-in imports # Built-in imports
from pathlib import Path
from typing import Any, cast from typing import Any, cast
# External library imports # External library imports
import pandas as pd import pandas as pd
from pandas import DataFrame from pandas import DataFrame
from mne import Annotations
from mne.io.base import BaseRaw from mne.io.base import BaseRaw
from flares import run_roi_paired_contrast_analysis, run_roi_second_level_analysis, aggregate_channel_contrasts_to_roi from flares import run_inter_group_contrast_analysis, run_inter_group_laterality_analysis, run_inter_group_second_level_analysis
from src.shared.flaresbasewidget import InterGroupUIMixin, FlaresBaseWidget from src.shared.flaresbasewidget import InterGroupUIMixin, FlaresBaseWidget
from src.shared.shareddata import APP_NAME from src.shared.shareddata import APP_NAME
@@ -34,7 +32,7 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
{ {
"key": "min_subjects", "key": "min_subjects",
"label": "Minimum number of participants to process", "label": "Minimum number of participants to process",
"default": "5", "default": "3",
"type": int, "type": int,
}, },
{ {
@@ -50,10 +48,10 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
"type": str, "type": str,
}, },
{ {
"key": "graph_bounds", "key": "threshold_topo",
"label": "Graph Upper/Lower Limit", "label": "threshold_topo: TBD",
"default": "0.0", "default": False,
"type": float, "type": bool,
} }
], ],
1: [ 1: [
@@ -66,7 +64,7 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
{ {
"key": "min_subjects", "key": "min_subjects",
"label": "Minimum number of participants to process", "label": "Minimum number of participants to process",
"default": "5", "default": "3",
"type": int, "type": int,
}, },
{ {
@@ -104,7 +102,7 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
{ {
"key": "min_subjects", "key": "min_subjects",
"label": "Minimum number of participants to process", "label": "Minimum number of participants to process",
"default": "5", "default": "3",
"type": int, "type": int,
}, },
{ {
@@ -125,31 +123,19 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
"default": [], "default": [],
"type": list, "type": list,
}, },
{
"key": "weighted",
"label": "Use inverse-variance weighting to minimize noisy channels",
"default": True,
"type": bool,
},
{
"key": "graph_bounds",
"label": "Graph Upper/Lower Limit",
"default": "0.0",
"type": float,
},
], ],
} }
DESCRIPTION = """0. ROI vs. Zero (run_roi_second_level_analysis) DESCRIPTION = """0. Raw ROI Comparison (run_inter_group_second_level_analysis)
\nTests whether one ROI's response during one condition reliably differs from zero across subjects - a one-sample t-test on each subject's ROI-averaged theta. A significant result means the region's signal during this condition is consistently non-zero across your sample, not just noise. It does not tell you whether the response is localized/specific to this region, or whether it reflects real neural activity versus systemic physiology (blood pressure, arousal) shared across the whole head during any active task - a single-condition "vs. zero" test can't distinguish those two explanations on its own. \nCompares one ROI's raw response magnitude between two independent groups (e.g. control vs. target) for a given condition, using Welch's t-test. A significant result means the two populations differ in this ROI's response magnitude for this condition. It does not tell you whether that difference is a real, localized, task-specific effect or a generic between-population difference - different overall vascular reactivity, arousal, or skull/scalp optical properties can produce the exact same statistical signature, and two independently recruited groups (especially patients vs. healthy controls) are considerably more likely to differ this way than two subsets of one study population.
\nIf you expected significance here and didn't get it, likely causes include: the sample size is simply small relative to between-subject variability in true response magnitude or HRF shape (individual differences in timing/amplitude inflate the variance a t-test divides by); the ROI's channel composition differs slightly across subjects (missing channels get down-weighted or excluded from the inverse-variance average, diluting a real signal); FDR correction across many ROIs is suppressing a modest true effect that would clear an uncorrected threshold; or the condition itself may not reliably engage this region the way you assumed (worth checking the single-subject/individual-level results for this ROI before concluding the group effect isn't there). \nIf you expected a group difference and didn't find one, the most common cause is within-group heterogeneity swallowing a real between-group difference - a "target" population (e.g. a clinical group) is often more variable than a tightly-screened control group, and that added within-group variance directly weakens a between-group t-test even if the group means truly differ. Small per-group sample sizes compound this. It's also possible the true difference between your groups isn't in raw magnitude at all, but in spatial specificity or task-differentiation - which is exactly why the laterality and contrast-comparison methods exist alongside this one; a null result here doesn't rule those out.
\n\n1. Paired ROI Contrast (run_roi_paired_contrast_analysis) \n\n1. Laterality Comparison (run_inter_group_laterality_analysis)
\nFor one condition, subtracts each subject's ROI_A response from their ROI_B response, then tests whether that per-subject difference is reliably non-zero. A significant result is a genuine spatial contrast - the two regions respond differently from each other during this specific condition, with shared systemic noise partially cancelling in the subtraction. It says nothing about whether the condition produced meaningful activity at all (only a relative difference between two places), and its power depends entirely on ROI_A and ROI_B varying together across subjects - an assumption that isn't guaranteed. \nComputes each subject's own contralateral-minus-ipsilateral laterality index first, then compares those indices between the two groups with Welch's t-test. A significant result means the degree of spatial specificity/lateralization differs between the two populations - a claim about lateralization itself, harder to explain away as a generic population confound since person-level differences in overall reactivity largely cancel before the group comparison happens. It says nothing about overall response magnitude between groups (a group could have identical laterality but very different raw amplitude), and it only uses subjects who have both the contra and ipsi ROI valid, so it can lose subjects the raw-ROI comparison would have kept.
\nIf this test underperforms a plain ROI-vs-zero result, which can occur, the most likely explanation is that ROI_A and ROI_B's noise isn't well-correlated across your subjects. The math is variance(A - B) = variance(A) + variance(B) - 2·covariance(A,B): subtraction only helps when the shared/systemic component is large relative to independent noise in each region. If the two regions are picking up largely independent noise sources (motion artifact affecting one side more, different channel quality, etc.), subtracting adds variance rather than removing it, and can turn a detectable single-ROI effect into an underpowered paired one. Small sample size makes this worse, since the covariance itself is poorly estimated with few subjects. \nNon-significance here has two likely sources, and it's worth distinguishing them. First, the same covariance issue from the within-group paired test applies across a whole group: if contra/ipsi responses aren't well-correlated within subjects, the laterality index itself is noisier than either ROI alone, and that added noise now has to clear a between-group test on top of it - a double power cost at small N. Second, and more informative if true: the groups may genuinely have similar lateralization but differ in overall magnitude instead, in which case this test correctly returns null while method 4 (raw comparison) should be the one to look at.
\n\n2. Joint Contrast, ROI-Aggregated (aggregate_channel_contrasts_to_roi + one-sample test) \n\n2. Contrast Comparison (run_inter_group_contrast_analysis)
\nUses a contrast fit jointly within each subject's GLM (Condition A minus Condition B, estimated together), then aggregates that per-channel contrast to ROI level using inverse-variance weighting, and tests it against zero across subjects. A significant result means the two conditions produce reliably different responses at this ROI, with systemic noise largely cancelled at the model-fitting stage itself - the most statistically efficient of the three within-group methods, since the correlation between conditions is handled natively rather than inferred afterward. It does not tell you where the difference is localized on its own - for that, compare the sign/pattern across multiple ROIs: opposite signs across regions indicates a real, spatially-specific effect, while the same sign everywhere suggests diffuse/systemic noise rather than localized activity (as seen when comparing a real task-vs-task contrast against a task-vs-inert-marker contrast). \nCompares a jointly-fit task contrast (e.g. Task A minus Task B, estimated together within each subject's GLM), aggregated to ROI level, between two independent groups. A significant result means one group differentiates between the two tasks more or less than the other does, at this specific ROI - with systemic noise cancelled at the model-fitting stage, the same benefit that makes the within-group version of this method the strongest of that trio. As with the within-group version, it does not by itself say where a difference is localized unless you compare sign/pattern across multiple ROIs - opposite-signed group differences across regions point to something spatially specific, same-signed differences everywhere point to a diffuse/non-specific group difference (e.g. one group simply has stronger contrast responses across the whole head).
\nIf this comes back non-significant despite expecting an effect, first check whether the two conditions are actually similar enough in their neural engagement of this ROI that a small or genuinely near-zero contrast is the correct answer - not every ROI should differentiate every pair of tasks, and a null result here can be the right result. Beyond that: FDR correction across every ROI in your regions file can suppress a real but modest contrast; the inverse-variance weighting can be destabilized if a few channels within the ROI have very noisy or near-zero t-statistics (their standard error estimate becomes huge or unstable); and - as always - small subject counts limit the achievable degrees of freedom regardless of how clean the underlying per-channel estimates are. \nIf this comes back non-significant despite an expected group difference, check first whether the underlying single-subject contrast estimates are noisy for either group - small per-group N means the joint contrast's precision depends on the same limited subject count as everything else, and a noisy input propagates all the way through the ROI aggregation. It's also possible for a real, localized sub-regional effect to get washed out by ROI averaging itself: if only part of an ROI's channels actually show the group difference while others don't, the inverse-variance-weighted average can dilute it toward null - in that case, a finer-grained ROI definition (splitting the region further) may recover the effect that a coarser ROI averaged away. Finally, FDR correction across every ROI tested reduces power exactly as it does everywhere else in this framework - a real but modest effect can fail to survive correction even when the raw p-value would have looked convincing on its own.
\n\n \n\n
\nWhy channels needed to be aggregated into ROIs: Testing every channel independently means paying a steep multiple-comparisons tax - with dozens of channels, FDR/Bonferroni correction demands very large effect sizes to call anything significant, and at small subject counts (n=5) essentially nothing survives even when a real, consistent effect exists. Collapsing channels into a handful of anatomically meaningful ROIs cuts the number of independent tests from a minimum of ~40 down to 2-8, which lets a genuinely present effect actually clear correction. It also matches the scientific question better: you have a hypothesis about regions (contralateral motor cortex, prefrontal cortex), not about individual source-detector pairs, so testing at the ROI level is testing the thing you actually believe in, using inverse-variance weighting so noisier channels contribute less to the region's combined estimate rather than diluting it equally. \nWhy channels needed to be aggregated into ROIs: Testing every channel independently means paying a steep multiple-comparisons tax - with dozens of channels, FDR/Bonferroni correction demands very large effect sizes to call anything significant, and at small subject counts (n=5) essentially nothing survives even when a real, consistent effect exists. Collapsing channels into a handful of anatomically meaningful ROIs cuts the number of independent tests from a minimum of ~40 down to 2-8, which lets a genuinely present effect actually clear correction. It also matches the scientific question better: you have a hypothesis about regions (contralateral motor cortex, prefrontal cortex), not about individual source-detector pairs, so testing at the ROI level is testing the thing you actually believe in, using inverse-variance weighting so noisier channels contribute less to the region's combined estimate rather than diluting it equally.
\nWhy some analyses needed contrasts instead of raw values: A single condition's GLM beta is only ever measured relative to the model's implicit intercept, and that intercept absorbs whatever's happening for the rest of the recording - including systemic physiology (blood pressure, arousal, general vascular reactivity) that rises during almost any active task, not just the one you care about. Testing a raw "vs. zero" value can't tell a real, localized neural response apart from that shared full-head noise. A contrast - either a within-subject spatial subtraction (ROI A minus ROI B) or a jointly-fit task contrast (Condition A minus Condition B, estimated together in one GLM) cancels out whatever's common to both halves of the subtraction, leaving something closer to the actual differential signal. \nWhy some analyses needed contrasts instead of raw values: A single condition's GLM beta is only ever measured relative to the model's implicit intercept, and that intercept absorbs whatever's happening for the rest of the recording - including systemic physiology (blood pressure, arousal, general vascular reactivity) that rises during almost any active task, not just the one you care about. Testing a raw "vs. zero" value can't tell a real, localized neural response apart from that shared full-head noise. A contrast - either a within-subject spatial subtraction (ROI A minus ROI B) or a jointly-fit task contrast (Condition A minus Condition B, estimated together in one GLM) cancels out whatever's common to both halves of the subtraction, leaving something closer to the actual differential signal.
@@ -157,9 +143,10 @@ DESCRIPTION = """0. ROI vs. Zero (run_roi_second_level_analysis)
class InterGroupStatsWidget(InterGroupUIMixin, FlaresBaseWidget): class InterGroupStatsWidget(InterGroupUIMixin, FlaresBaseWidget):
def __init__( def __init__(
self, self,
haemo_dict: dict[str | Path, BaseRaw], haemo_dict: dict[str, BaseRaw],
cha_dict: dict[str, DataFrame], cha_dict: dict[str, DataFrame],
df_ind_dict: dict[str, DataFrame], df_ind_dict: dict[str, DataFrame],
design_matrix_dict: dict[str, DataFrame], design_matrix_dict: dict[str, DataFrame],
@@ -178,7 +165,7 @@ class InterGroupStatsWidget(InterGroupUIMixin, FlaresBaseWidget):
self.roi_channel_map_dict = roi_channel_map_dict self.roi_channel_map_dict = roi_channel_map_dict
self.group_dict = group_dict self.group_dict = group_dict
self.setup_inter_group_ui(["0 (ROI vs. Zero)", "1 (Paired ROI Contrast)", "2 (Joint Contrast, ROI-Aggregated)"], placeholder_text=DESCRIPTION) self.setup_inter_group_ui(["0 (Raw ROI Comparison)", "1 (Laterality Comparison)", "2 (Contrast Comparison)",], placeholder_text=DESCRIPTION)
def process_request(self): def process_request(self):
@@ -186,218 +173,183 @@ class InterGroupStatsWidget(InterGroupUIMixin, FlaresBaseWidget):
if request is None: if request is None:
return return
(selected_event, selected_file_paths, selected_indexes, raw_params) = request (selected_event, file_paths_a, file_paths_b, _, selected_indexes, raw_params) = request
param_values = cast(dict[int | str, dict[str, Any]], raw_params) param_values = cast(dict[int | str, dict[str, Any]], raw_params)
all_cha = DataFrame() valid_dfs = [df for df in self.df_ind_dict.values() if not df.empty]
for file_path in selected_file_paths: if valid_dfs:
haemo_obj = self.haemo_dict.get(file_path) df_ind_combined = pd.concat(valid_dfs, ignore_index=True)
if haemo_obj is None:
continue
if selected_event:
raw_annotations = getattr(haemo_obj, "annotations", None)
if raw_annotations is not None:
annotations = cast(Annotations, raw_annotations)
descriptions = cast(list[str], list(annotations.description))
participant_events: set[str] = set(descriptions)
else: else:
participant_events: set[str] = set() df_ind_combined = pd.DataFrame()
if selected_event not in participant_events: valid_chas = [df for df in self.cha_dict.values() if not df.empty]
print(f"Skipping {self.participant_map[file_path]}: Event '{selected_event}' not found.") cha_combined = pd.concat(valid_chas, ignore_index=True) if valid_chas else pd.DataFrame()
continue
sample_path = file_paths_a[0]
p_haemo = self.haemo_dict.get(sample_path)
# Visualizations
cha_df = self.cha_dict.get(file_path)
if cha_df is not None:
all_cha = pd.concat([all_cha, cha_df], ignore_index=True)
file_path = selected_file_paths[0]
p_haemo = self.haemo_dict.get(file_path)
# Concatenate individual ROI stats (df_ind) for all chosen subjects
df_group = DataFrame()
if selected_file_paths:
for file_path in selected_file_paths:
df = self.df_ind_dict.get(file_path)
if df is not None:
df_group = pd.concat([df_group, df], ignore_index=True)
for idx in selected_indexes: for idx in selected_indexes:
if idx == 0: if idx == 0:
params = param_values.get(idx, {}) params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05) p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 5) min_subjects = params.get("min_subjects", 3)
correction_method = params.get("correction_method", "fdr_bh") correction_method = params.get("correction_method", "fdr_bh")
target_chroma = params.get("target_chroma", "hbo") target_chroma = params.get("target_chroma", "hbo")
graph_bounds = params.get("graph_bounds", 0.0) threshold_topo = params.get("threshold_topo", False)
if correction_method == "None": selected_roi_maps = {
correction_method = None fp: self.roi_channel_map_dict[fp]
for fp in (file_paths_a + file_paths_b)
if fp in self.roi_channel_map_dict
}
if df_group.empty: run_inter_group_second_level_analysis(
print("No ROI data (df_ind) found for selected participants.") df_roi_all=df_ind_combined, # Individual stats dataframe
continue file_paths_a=file_paths_a,
file_paths_b=file_paths_b,
# Filter down to the selected experimental event/condition group_a_name=self.group_a_dropdown.currentText(),
if selected_event: group_b_name=self.group_b_dropdown.currentText(),
if 'Condition' in df_group.columns: df_cha_all=cha_combined,
df_filtered = df_group[df_group['Condition'] == selected_event]
else:
print("Warning: 'Condition' column not found in ROI data.")
df_filtered = df_group
else:
df_filtered = df_group
if df_filtered.empty:
print(f"No ROI data matches the condition '{selected_event}'.")
continue
all_cha_filtered = DataFrame()
if not all_cha.empty:
if selected_event and 'Condition' in all_cha.columns:
all_cha_filtered = all_cha[all_cha['Condition'] == selected_event]
else:
all_cha_filtered = all_cha
run_roi_second_level_analysis(
df_roi_all=df_filtered,
df_cha_all=all_cha_filtered,
raw_haemo=p_haemo, raw_haemo=p_haemo,
p_threshold=p_threshold, p_threshold=p_threshold,
min_subjects=min_subjects, min_subjects=min_subjects,
correction_method=correction_method, correction_method=correction_method,
target_chroma=target_chroma, target_chroma=target_chroma,
graph_bounds=graph_bounds if graph_bounds > 0.0 else None, selected_event=selected_event,
roi_channel_maps=selected_roi_maps,
threshold_topo=threshold_topo # Shows the raw difference map (Unthresholded)
) )
elif idx == 1: elif idx == 1:
params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 5)
correction_method = params.get("correction_method", "None")
target_chroma = params.get("target_chroma", "hbo")
roi_a = params.get("roi_a", "").strip()
roi_b = params.get("roi_b", "").strip()
if not selected_event: if not selected_event:
print("Paired ROI contrast requires a specific event/condition " print("Laterality comparison requires a specific event/condition "
"to be selected - pick one from the Event dropdown first.") "to be selected first.")
continue continue
if df_group.empty: params = param_values.get(idx, {})
print("No ROI data (df_ind) found for selected participants.") p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 3)
correction_method = params.get("correction_method", "None")
target_chroma = params.get("target_chroma", "hbo")
roi_a: str = params.get("roi_a", "").strip()
roi_b: str = params.get("roi_b", "").strip()
if not roi_a or not roi_b:
print("Both a contralateral and ipsilateral ROI name must be specified.")
continue continue
if correction_method == "None": if correction_method == "None":
correction_method = None correction_method = None
if not roi_a or not roi_b: # Build each group's dataframe directly from the dict using
print("Both ROI A and ROI B must be specified.") # the file-path lists as keys - no ID cleaning/matching needed.
def _build_group_df(
file_paths: list[str],
dict_source: dict[str, DataFrame]
) -> DataFrame:
valid_dfs = [
dict_source[fp] for fp in file_paths
if fp in dict_source and not dict_source[fp].empty
]
return pd.concat(valid_dfs, ignore_index=True) if valid_dfs else pd.DataFrame()
df_roi_a = _build_group_df(file_paths_a, self.df_ind_dict)
df_roi_b = _build_group_df(file_paths_b, self.df_ind_dict)
if df_roi_a.empty or df_roi_b.empty:
print("No ROI data (df_ind) found for one or both groups.")
continue continue
print(min_subjects) run_inter_group_laterality_analysis(
run_roi_paired_contrast_analysis( df_roi_all_a=df_roi_a,
df_roi_all=df_group, df_roi_all_b=df_roi_b,
roi_pairs=(roi_a, roi_b), roi_pairs=(roi_a, roi_b),
condition=selected_event, condition=selected_event,
group_a_name=self.group_a_dropdown.currentText(),
group_b_name=self.group_b_dropdown.currentText(),
target_chroma=target_chroma, target_chroma=target_chroma,
min_subjects=min_subjects, min_subjects=min_subjects,
p_threshold=p_threshold, p_threshold=p_threshold,
correction_method=correction_method, correction_method=correction_method,
roi_a_label=roi_a, roi_contra_label=roi_a,
roi_b_label=roi_b, roi_ipsi_label=roi_b,
) )
elif idx == 2: elif idx == 2:
params = param_values.get(idx, {}) params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05) p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 5) min_subjects = params.get("min_subjects", 3)
correction_method = params.get("correction_method", "fdr_bh") correction_method = params.get("correction_method", "fdr_bh")
target_chroma = params.get("target_chroma", "hbo") target_chroma = params.get("target_chroma", "hbo")
contrast_name = params.get("contrast_name", "") contrast_name = params.get("contrast_name", "")
weighted = params.get("weighted", True)
graph_bounds = params.get("graph_bounds", 0.0)
if not selected_event:
print("Joint contrast ROI analysis requires a specific contrast "
"to be selected from the Event dropdown first.")
continue
if not contrast_name: if not contrast_name:
print("Contrast name must be specified.") print("A contrast name must be specified.")
continue continue
# Build each group's channel-level contrast dataframe
# directly from contrast_results_dict, keyed by file path -
# same dict-key approach as the laterality patch, avoids
# any ID-string matching.
def _build_group_contrast_df(
file_paths: list[str],
contrast_dict: dict[str, dict[str, pd.DataFrame]],
name: str,
) -> pd.DataFrame:
all_contrasts: list[DataFrame] = [] all_rows: list[DataFrame] = []
for fp in selected_file_paths: for fp in file_paths:
condition_dfs = self.contrast_results_dict.get(fp) condition_dfs = contrast_dict.get(fp)
if condition_dfs is None: if condition_dfs is None:
print(f" [MISSING] '{fp}' not found in contrast_results.") print(f" [MISSING] '{fp}' not found in contrast_results.")
continue continue
if contrast_name in condition_dfs: if name in condition_dfs:
df = condition_dfs[contrast_name].copy() df = condition_dfs[name].copy()
df["ID"] = fp df["ID"] = fp
df["contrast_name"] = contrast_name df["contrast_name"] = name
all_contrasts.append(df) all_rows.append(df)
else: else:
print(f" [MISSING CONTRAST] '{contrast_name}' not " print(f" [MISSING CONTRAST] '{name}' not available for '{fp}'.")
f"available for {self.participant_map.get(fp, fp)}.") return pd.concat(all_rows, ignore_index=True) if all_rows else pd.DataFrame()
if not all_contrasts: df_contrasts_a = _build_group_contrast_df(file_paths_a, self.contrast_results_dict, contrast_name)
print(f"No contrast data found for '{contrast_name}' " df_contrasts_b = _build_group_contrast_df(file_paths_b, self.contrast_results_dict, contrast_name)
f"across selected participants.")
if df_contrasts_a.empty or df_contrasts_b.empty:
print("No contrast data found for one or both groups.")
continue continue
df_contrasts = pd.concat(all_contrasts, ignore_index=True) roi_maps_a = {
selected_roi_maps = {
fp: self.roi_channel_map_dict[fp] fp: self.roi_channel_map_dict[fp]
for fp in selected_file_paths for fp in file_paths_a
if fp in self.roi_channel_map_dict if fp in self.roi_channel_map_dict
} }
if not selected_roi_maps: roi_maps_b = {
print("No channel-to-ROI mapping available for selected participants.") fp: self.roi_channel_map_dict[fp]
for fp in file_paths_b
if fp in self.roi_channel_map_dict
}
if not roi_maps_a or not roi_maps_b:
print("No channel-to-ROI mapping available for one or both groups.")
continue continue
try: run_inter_group_contrast_analysis(
roi_theta = aggregate_channel_contrasts_to_roi( df_contrasts_a=df_contrasts_a,
df_contrasts, df_contrasts_b=df_contrasts_b,
roi_channel_maps=selected_roi_maps, contrast_name=contrast_name,
weighted=weighted, roi_channel_maps_a=roi_maps_a,
) roi_channel_maps_b=roi_maps_b,
group_a_name=self.group_a_dropdown.currentText(),
except Exception as e: group_b_name=self.group_b_dropdown.currentText(),
print(f"Failed to aggregate contrasts to ROI: {e}")
continue
if roi_theta.empty:
print("No ROI-level contrast values could be computed "
"(check regions.json channel names against this montage).")
continue
# TODO: Come back to this
# df_cha_all intentionally omitted (None): the topography
# section of run_roi_second_level_analysis expects
# single-condition Condition values in df_cha_all, which
# doesn't semantically match a contrast name - skip it here
# rather than pass mismatched data.
run_roi_second_level_analysis(
df_roi_all=roi_theta,
df_cha_all=None,
raw_haemo=p_haemo,
p_threshold=p_threshold,
min_subjects=min_subjects,
correction_method=correction_method,
target_chroma=target_chroma, target_chroma=target_chroma,
graph_bounds=graph_bounds if graph_bounds > 0.0 else None, min_subjects=min_subjects,
p_threshold=p_threshold,
correction_method=correction_method,
) )
else: else:
print(f"No method defined for index {idx}") print("no")
+185
View File
@@ -0,0 +1,185 @@
"""
Filename: intragroupbrainimage.py
Description: Logic for the Intra-Group Brain & Image analysis window
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw
License: GPL-3.0
"""
# Built-in imports
from typing import Any, cast
# External library imports
import pandas as pd
from pandas import DataFrame
from mne import Annotations
from mne.io.base import BaseRaw
from flares import aggregate_fnirs_group_geometry, plot_fir_model_results, brain_3d_visualization
from src.shared.flaresbasewidget import IntraGroupUIMixin, FlaresBaseWidget
from src.shared.shareddata import APP_NAME
PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
0: [
{
"key": "lower_bound",
"label": "Lower bound + <description>",
"default": "-0.3",
"type": float, # specify int here
},
{
"key": "upper_bound",
"label": "Upper bound + <description>",
"default": "0.8",
"type": float, # specify int here
}
],
1: [
{
"key": "show_optodes",
"label": "Determine what is rendered above the brain. Valid values are 'sensors', 'labels', 'none', 'all'.",
"default": "all",
"type": str,
},
{
"key": "t_or_theta",
"label": "Specify if t values or theta values should be plotted. Valid values are 't', 'theta'",
"default": "theta",
"type": str,
},
{
"key": "show_text",
"label": "Display informative text on the top left corner. THIS DOES NOT WORK AND SHOULD BE LEFT AT FALSE",
"default": "False",
"type": bool,
},
{
"key": "brain_bounds",
"label": "Graph Upper/Lower Limit",
"default": "1.0",
"type": float,
}
],
}
DESCRIPTION = """0. FIR Model Results (plot_fir_model_results)
\nCURRENTLY NON-FUNCTIONAL. This method requires per-FIR-delay Condition rows (e.g. "Tapping_delay_3") to plot the shape of the evoked response over time. The dataframe it receives (df_ind_dict) has already had delay information collapsed away upstream in generate_roi_results, regardless of HRF model setting - so this will always fail with an empty-data error. Needs an uncollapsed, per-delay ROI dataframe threaded through separately before it can work again.
\n1. Brain Activity Visualization (brain_3d_visualization)
\nRenders a single group's (or single participant's) channel-level GLM estimates (t or theta values) as a 3D weighted brain map. Fits a mixed-effects model across participants (falling back to OLS for a single participant) to get one estimate per channel, then displays it on a template brain surface with optional optode/sensor overlay.
\nUses collapsed (non-FIR-delay) condition data - shows the overall magnitude of the response per channel, not its time course. Geometry for multi-participant views is averaged across participants' actual optode positions where available; channels or optodes missing valid 3D coordinates for every participant are silently excluded from the map.
"""
class IntraGroupBrainImageWidget(IntraGroupUIMixin, FlaresBaseWidget):
def __init__(
self,
haemo_dict: dict[str, BaseRaw],
cha_dict: dict[str, DataFrame],
df_ind_dict: dict[str, DataFrame],
design_matrix_dict: dict[str, DataFrame],
contrast_results_dict: dict[str, dict[str, Any]],
group_dict: dict[str, str]
) -> None:
super().__init__("IntraGroupBrainImage")
self.setWindowTitle(f"Intra-Group Brain & Image Viewer - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict
self.cha_dict = cha_dict
self.df_ind_dict = df_ind_dict
self.design_matrix_dict = design_matrix_dict
self.contrast_results_dict = contrast_results_dict
self.group_dict = group_dict
self.setup_intra_group_ui(["0 (GLM Results)", "1 (Brain Activity Visualization)"], placeholder_text=DESCRIPTION)
def process_request(self):
request = self.get_common_request_data(PARAMETERIZED_INDEXES)
if request is None:
return
(selected_event, selected_file_paths, selected_indexes, raw_params) = request
param_values = cast(dict[int | str, dict[str, Any]], raw_params)
all_cha = pd.DataFrame()
for file_path in selected_file_paths:
haemo_obj = self.haemo_dict.get(file_path)
if haemo_obj is None:
continue
if selected_event:
raw_annotations = getattr(haemo_obj, "annotations", None)
if raw_annotations is not None:
annotations = cast(Annotations, raw_annotations)
descriptions = cast(list[str], list(annotations.description))
participant_events: set[str] = set(descriptions)
else:
participant_events: set[str] = set()
if selected_event not in participant_events:
print(f"Skipping {self.participant_map[file_path]}: Event '{selected_event}' not found.")
continue
cha_df = self.cha_dict.get(file_path)
if cha_df is not None:
all_cha = pd.concat([all_cha, cha_df], ignore_index=True)
# Pass the necessary arguments to each method
file_path = selected_file_paths[0]
p_haemo = self.haemo_dict.get(file_path)
p_design_matrix = self.design_matrix_dict.get(file_path)
df_group = pd.DataFrame()
if selected_file_paths:
for file_path in selected_file_paths:
df = self.df_ind_dict.get(file_path)
if df is not None:
df_group = pd.concat([df_group, df], ignore_index=True)
for idx in selected_indexes:
if idx == 0:
params = param_values.get(idx, {})
lower_bound = params.get("lower_bound", None)
upper_bound = params.get("upper_bound", None)
if lower_bound is None or upper_bound is None:
print(f"Missing parameters for index {idx}, skipping.")
continue
plot_fir_model_results(df_group, p_haemo, p_design_matrix, selected_event, lower_bound, upper_bound)
elif idx == 1:
params = param_values.get(idx, {})
show_optodes = params.get("show_optodes", None)
t_or_theta = params.get("t_or_theta", None)
show_text = params.get("show_text", None)
brain_bounds = params.get("brain_bounds", None)
if show_optodes is None or t_or_theta is None or show_text is None or brain_bounds is None:
print(f"Missing parameters for index {idx}, skipping.")
continue
all_raw_objs = [self.haemo_dict.get(fp) for fp in selected_file_paths if self.haemo_dict.get(fp)]
if len(all_raw_objs) > 1:
processed_raw = aggregate_fnirs_group_geometry(all_raw_objs)
elif len(all_raw_objs) == 1 and all_raw_objs[0] is not None:
processed_raw = all_raw_objs[0].copy()
processed_raw.pick(picks="hbo") # type: ignore
else:
processed_raw = None
brain_3d_visualization(processed_raw, all_cha, selected_event, t_or_theta=t_or_theta, show_optodes=show_optodes, show_text=show_text, brain_bounds=brain_bounds)
else:
print(f"No method defined for index {idx}")
@@ -0,0 +1,138 @@
"""
Filename: intragroupfunctionalconnectivity.py
Description: Logic for the Intra-Group Functional Connectivity analysis window
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw
License: GPL-3.0
"""
# Built-in imports
from typing import Any, cast
# External library imports
from PySide6.QtWidgets import QMessageBox
from mne import Epochs
from mne.io.base import BaseRaw
from flares import run_group_functional_connectivity_betas, run_group_functional_connectivity_epochs
from src.shared.flaresbasewidget import IntraGroupUIMixin, FlaresBaseWidget
from src.shared.shareddata import APP_NAME
PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
0: [ # Beta-Series Correlation
{"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
{"key": "vmin", "label": "Minimum |r| to display (group average)", "default": "0.5", "type": float},
{"key": "drift_model", "label": "Drift model", "default": "cosine", "type": list, "options": ["cosine", "polynomial"]},
{"key": "drift_order", "label": "Drift order", "default": "1", "type": int},
{"key": "hrf_model", "label": "HRF model", "default": "glover", "type": list, "options": ["glover", "spm", "fir"]},
{"key": "apply_gsr", "label": "Apply Global Signal Regression", "default": "True", "type": bool},
{"key": "resample_freq", "label": "Resample rate before GLM fit (Hz) - lower is much faster", "default": "4.0", "type": float},
{"key": "alpha", "label": "FDR significance threshold (group-level)", "default": "0.05", "type": float},
{"key": "min_participants", "label": "Minimum participants required to run the group test", "default": "3", "type": int},
],
1: [ # Spectral Coherence
{"key": "method", "label": "Connectivity method", "default": "wpli2_debiased", "type": list, "options": ["coh", "pli", "wpli2_debiased"]},
{"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
{"key": "vmin", "label": "Minimum |r| to display (group average)", "default": "0.5", "type": float},
{"key": "fmin", "label": "Lower frequency bound (Hz)", "default": "0.04", "type": float},
{"key": "fmax", "label": "Upper frequency bound (Hz)", "default": "0.2", "type": float},
{"key": "alpha", "label": "FDR significance threshold (group-level)", "default": "0.05", "type": float},
{"key": "min_participants", "label": "Minimum participants required to run the group test", "default": "3", "type": int},
],
}
DESCRIPTION = """0. Beta-Series Correlation (run_group_functional_connectivity_betas)
\nFor each selected participant, resamples to resample_freq (default 4 Hz - well above what's needed to resolve trial-level GLM amplitudes, but far cheaper than running the fit at full acquisition rate) and computes trial-level GLM betas per channel, correlating them within-subject WITHOUT thresholding at the individual level. Those raw per-subject correlation matrices are Fisher-Z transformed and combined across the group using a one-sample t-test (against zero) per channel pair, then FDR-corrected (q < alpha) across all pairs. A significant connection means the group, on average, shows consistent trial-evoked co-activation between two channels - not that every individual participant showed it.
\nRequires at least min_participants (default 3, more is stronger) participants with usable data - each needs enough trials of the selected event to compute their own beta series. Participants with channel sets that don't overlap with the rest of the group are excluded from the shared channel set before analysis.
\nWith a small number of participants and many channel pairs, FDR correction is often the limiting factor even when there's a real underlying effect - check the p-value histogram and top-pairs report generated alongside the main plot: a cluster of small (but not FDR-significant) p-values well below what's expected by chance suggests a real but underpowered effect, worth revisiting with more participants, rather than a true null result.
\n1. Spectral Coherence (run_group_functional_connectivity_epochs)
\nFor each selected participant, computes spectral connectivity between HbO channels using the selected method: coherence ('coh'), Phase Lag Index ('pli'), or debiased weighted PLI squared ('wpli2_debiased', default). PLI/wPLI-family methods discount zero-lag contributions to connectivity, making them substantially more robust to shared systemic/vascular signal (which tends to hit multiple channels near-simultaneously) than plain coherence - recommended over 'coh' unless you have a specific reason to want raw coherence. Raw per-subject matrices are combined across the group the same way as the Beta-Series method: Fisher-Z, one-sample t-test per channel pair, FDR correction.
\nfmin must satisfy at least 5 full oscillation cycles within your epoch length (epoch_duration x fmin >= 5) for a reliable estimate - if it doesn't, the analysis will refuse to run with an error stating the minimum viable fmin for your epoch length, rather than silently producing an unreliable result. Shorter epochs require a higher fmin, which moves you out of the classic 0.04-0.2 Hz "low-frequency oscillation" band used in longer resting-state recordings - this is a real trade-off in what the analysis measures, not just a technical constraint.
\nSame minimum-participant, channel-alignment, and underpowered-vs-null-result caveats apply as the Beta-Series method above.
"""
class IntraGroupFunctionalConnectivityWidget(IntraGroupUIMixin, FlaresBaseWidget):
def __init__(
self,
haemo_dict: dict[str, BaseRaw],
epochs_dict: dict[str, Epochs],
group_dict: dict[str, str],
) -> None:
super().__init__("IntraGroupFunctionalConnectivity")
self.setWindowTitle(f"Intra-Group Functional Connectivity Viewer [BETA] - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict
self.epochs_dict = epochs_dict
self.group_dict = group_dict
QMessageBox.warning(self, f"Warning - {APP_NAME.upper()}", f"Functional Connectivity is still in beta. While the results are now almost finalized, the processing is slow and it WILL hang the application for HOURS.")
self.setup_intra_group_ui(["0 (Beta-Series Correlation)", "1 (Spectral Coherence)"], placeholder_text=DESCRIPTION)
def process_request(self):
request = self.get_common_request_data(PARAMETERIZED_INDEXES)
if request is None:
return
(selected_event, selected_file_paths, selected_indexes, raw_params) = request
param_values = cast(dict[int | str, dict[str, Any]], raw_params)
for idx in selected_indexes:
params = param_values.get(idx, {})
if idx == 0:
n_lines = params.get("n_lines", 20)
vmin = params.get("vmin", 0.5)
drift_model = params.get("drift_model", "cosine")
drift_order = params.get("drift_order", 1)
hrf_model = params.get("hrf_model", "glover")
apply_gsr = params.get("apply_gsr", True)
resample_freq = params.get("resample_freq", 4.0)
alpha = params.get("alpha", 0.05)
min_participants = params.get("min_participants", 3)
run_group_functional_connectivity_betas(
self.haemo_dict,
selected_file_paths,
selected_event,
n_lines,
vmin,
drift_model=drift_model,
drift_order=drift_order,
hrf_model=hrf_model,
apply_gsr=apply_gsr,
resample_freq=resample_freq,
alpha=alpha,
min_participants=min_participants,
)
elif idx == 1:
method = params.get("method", "wpli2_debiased")
n_lines = params.get("n_lines", 20)
vmin = params.get("vmin", 0.5)
fmin = params.get("fmin", 0.04)
fmax = params.get("fmax", 0.2)
alpha = params.get("alpha", 0.05)
min_participants = params.get("min_participants", 3)
run_group_functional_connectivity_epochs(
self.epochs_dict,
selected_file_paths,
event_name=selected_event,
n_lines=n_lines,
vmin=vmin,
fmin=fmin,
method=method,
fmax=fmax,
alpha=alpha,
min_participants=min_participants,
)
else:
print(f"No method defined for index {idx}")
+400
View File
@@ -0,0 +1,400 @@
"""
Filename: intragroupstats.py
Description: Logic for the Intra-Group Stats analysis window
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw
License: GPL-3.0
"""
# Built-in imports
from typing import Any, cast
# External library imports
import pandas as pd
from pandas import DataFrame
from mne import Annotations
from mne.io.base import BaseRaw
from flares import run_roi_paired_contrast_analysis, run_roi_second_level_analysis, aggregate_channel_contrasts_to_roi
from src.shared.flaresbasewidget import IntraGroupUIMixin, FlaresBaseWidget
from src.shared.shareddata import APP_NAME
PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
0: [
{
"key": "p_threshold",
"label": "Significance threshold P-value (e.g. 0.05)",
"default": "0.05",
"type": float,
},
{
"key": "min_subjects",
"label": "Minimum number of participants to process",
"default": "5",
"type": int,
},
{
"key": "correction_method",
"label": "Correction method to utilize. Valid values are 'fdr_bh', 'None'",
"default": "fdr_bh",
"type": str,
},
{
"key": "target_chroma",
"label": "Which chroma to target. Valid values are 'hbo', 'hbr'",
"default": "hbo",
"type": str,
},
{
"key": "graph_bounds",
"label": "Graph Upper/Lower Limit",
"default": "0.0",
"type": float,
}
],
1: [
{
"key": "p_threshold",
"label": "Significance threshold P-value (e.g. 0.05)",
"default": "0.05",
"type": float,
},
{
"key": "min_subjects",
"label": "Minimum number of participants to process",
"default": "5",
"type": int,
},
{
"key": "correction_method",
"label": "Correction method to utilize. Valid values are 'fdr_bh', 'None'",
"default": "None",
"type": str,
},
{
"key": "target_chroma",
"label": "Which chroma to target. Valid values are 'hbo', 'hbr'",
"default": "hbo",
"type": str,
},
{
"key": "roi_a",
"label": "ROI A (e.g. contralateral region name from regions.json)",
"default": [],
"type": list,
},
{
"key": "roi_b",
"label": "ROI B (e.g. ipsilateral region name from regions.json)",
"default": [],
"type": list,
}
],
2: [
{
"key": "p_value",
"label": "Significance threshold P-value (e.g. 0.05)",
"default": "0.05",
"type": float,
},
{
"key": "min_subjects",
"label": "Minimum number of participants to process",
"default": "5",
"type": int,
},
{
"key": "correction_method",
"label": "Correction method to utilize. Valid values are 'fdr_bh', 'None'",
"default": "fdr_bh",
"type": str,
},
{
"key": "target_chroma",
"label": "Which chroma to target. Valid values are 'hbo', 'hbr'",
"default": "hbo",
"type": str,
},
{
"key": "contrast_name",
"label": "Name of the contrast to use",
"default": [],
"type": list,
},
{
"key": "weighted",
"label": "Use inverse-variance weighting to minimize noisy channels",
"default": True,
"type": bool,
},
{
"key": "graph_bounds",
"label": "Graph Upper/Lower Limit",
"default": "0.0",
"type": float,
},
],
}
DESCRIPTION = """0. ROI vs. Zero (run_roi_second_level_analysis)
\nTests whether one ROI's response during one condition reliably differs from zero across subjects - a one-sample t-test on each subject's ROI-averaged theta. A significant result means the region's signal during this condition is consistently non-zero across your sample, not just noise. It does not tell you whether the response is localized/specific to this region, or whether it reflects real neural activity versus systemic physiology (blood pressure, arousal) shared across the whole head during any active task - a single-condition "vs. zero" test can't distinguish those two explanations on its own.
\nIf you expected significance here and didn't get it, likely causes include: the sample size is simply small relative to between-subject variability in true response magnitude or HRF shape (individual differences in timing/amplitude inflate the variance a t-test divides by); the ROI's channel composition differs slightly across subjects (missing channels get down-weighted or excluded from the inverse-variance average, diluting a real signal); FDR correction across many ROIs is suppressing a modest true effect that would clear an uncorrected threshold; or the condition itself may not reliably engage this region the way you assumed (worth checking the single-subject/individual-level results for this ROI before concluding the group effect isn't there).
\n\n1. Paired ROI Contrast (run_roi_paired_contrast_analysis)
\nFor one condition, subtracts each subject's ROI_A response from their ROI_B response, then tests whether that per-subject difference is reliably non-zero. A significant result is a genuine spatial contrast - the two regions respond differently from each other during this specific condition, with shared systemic noise partially cancelling in the subtraction. It says nothing about whether the condition produced meaningful activity at all (only a relative difference between two places), and its power depends entirely on ROI_A and ROI_B varying together across subjects - an assumption that isn't guaranteed.
\nIf this test underperforms a plain ROI-vs-zero result, which can occur, the most likely explanation is that ROI_A and ROI_B's noise isn't well-correlated across your subjects. The math is variance(A - B) = variance(A) + variance(B) - 2·covariance(A,B): subtraction only helps when the shared/systemic component is large relative to independent noise in each region. If the two regions are picking up largely independent noise sources (motion artifact affecting one side more, different channel quality, etc.), subtracting adds variance rather than removing it, and can turn a detectable single-ROI effect into an underpowered paired one. Small sample size makes this worse, since the covariance itself is poorly estimated with few subjects.
\n\n2. Joint Contrast, ROI-Aggregated (aggregate_channel_contrasts_to_roi + one-sample test)
\nUses a contrast fit jointly within each subject's GLM (Condition A minus Condition B, estimated together), then aggregates that per-channel contrast to ROI level using inverse-variance weighting, and tests it against zero across subjects. A significant result means the two conditions produce reliably different responses at this ROI, with systemic noise largely cancelled at the model-fitting stage itself - the most statistically efficient of the three within-group methods, since the correlation between conditions is handled natively rather than inferred afterward. It does not tell you where the difference is localized on its own - for that, compare the sign/pattern across multiple ROIs: opposite signs across regions indicates a real, spatially-specific effect, while the same sign everywhere suggests diffuse/systemic noise rather than localized activity (as seen when comparing a real task-vs-task contrast against a task-vs-inert-marker contrast).
\nIf this comes back non-significant despite expecting an effect, first check whether the two conditions are actually similar enough in their neural engagement of this ROI that a small or genuinely near-zero contrast is the correct answer - not every ROI should differentiate every pair of tasks, and a null result here can be the right result. Beyond that: FDR correction across every ROI in your regions file can suppress a real but modest contrast; the inverse-variance weighting can be destabilized if a few channels within the ROI have very noisy or near-zero t-statistics (their standard error estimate becomes huge or unstable); and - as always - small subject counts limit the achievable degrees of freedom regardless of how clean the underlying per-channel estimates are.
\n\n
\nWhy channels needed to be aggregated into ROIs: Testing every channel independently means paying a steep multiple-comparisons tax - with dozens of channels, FDR/Bonferroni correction demands very large effect sizes to call anything significant, and at small subject counts (n=5) essentially nothing survives even when a real, consistent effect exists. Collapsing channels into a handful of anatomically meaningful ROIs cuts the number of independent tests from a minimum of ~40 down to 2-8, which lets a genuinely present effect actually clear correction. It also matches the scientific question better: you have a hypothesis about regions (contralateral motor cortex, prefrontal cortex), not about individual source-detector pairs, so testing at the ROI level is testing the thing you actually believe in, using inverse-variance weighting so noisier channels contribute less to the region's combined estimate rather than diluting it equally.
\nWhy some analyses needed contrasts instead of raw values: A single condition's GLM beta is only ever measured relative to the model's implicit intercept, and that intercept absorbs whatever's happening for the rest of the recording - including systemic physiology (blood pressure, arousal, general vascular reactivity) that rises during almost any active task, not just the one you care about. Testing a raw "vs. zero" value can't tell a real, localized neural response apart from that shared full-head noise. A contrast - either a within-subject spatial subtraction (ROI A minus ROI B) or a jointly-fit task contrast (Condition A minus Condition B, estimated together in one GLM) cancels out whatever's common to both halves of the subtraction, leaving something closer to the actual differential signal.
\nWhy a minimum subject count is enforced: Every one of these tests is a t-test, and a t-test's ability to detect a real effect (its power) depends heavily on degrees of freedom - at n=5 (df=4), even a fairly large true effect can produce a middling p-value, and at n=2 (df=1) the test is barely meaningful at all regardless of the underlying data. The min_subjects floor exists to stop a channel or ROI from being silently tested (and potentially reported as significant or non-significant) on a sample too small for the resulting p-value to mean anything reliable - it's better to explicitly skip and flag an underpowered channel than to quietly produce a number that looks statistically legitimate but isn't backed by enough independent observations to trust."""
class IntraGroupStatsWidget(IntraGroupUIMixin, FlaresBaseWidget):
def __init__(
self,
haemo_dict: dict[str, BaseRaw],
cha_dict: dict[str, DataFrame],
df_ind_dict: dict[str, DataFrame],
design_matrix_dict: dict[str, DataFrame],
contrast_results_dict: dict[str, dict[str, Any]],
roi_channel_map_dict: dict[str, dict[str, str]],
group_dict: dict[str, str],
) -> None:
super().__init__("IntraGroupStats")
self.setWindowTitle(f"Intra-Group Stats Viewer - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict
self.cha_dict = cha_dict
self.df_ind_dict = df_ind_dict
self.design_matrix_dict = design_matrix_dict
self.contrast_results_dict = contrast_results_dict
self.roi_channel_map_dict = roi_channel_map_dict
self.group_dict = group_dict
self.setup_intra_group_ui(["0 (ROI vs. Zero)", "1 (Paired ROI Contrast)", "2 (Joint Contrast, ROI-Aggregated)"], placeholder_text=DESCRIPTION)
def process_request(self):
request = self.get_common_request_data(PARAMETERIZED_INDEXES, self.df_ind_dict, self.contrast_results_dict)
if request is None:
return
(selected_event, selected_file_paths, selected_indexes, raw_params) = request
param_values = cast(dict[int | str, dict[str, Any]], raw_params)
all_cha = DataFrame()
for file_path in selected_file_paths:
haemo_obj = self.haemo_dict.get(file_path)
if haemo_obj is None:
continue
if selected_event:
raw_annotations = getattr(haemo_obj, "annotations", None)
if raw_annotations is not None:
annotations = cast(Annotations, raw_annotations)
descriptions = cast(list[str], list(annotations.description))
participant_events: set[str] = set(descriptions)
else:
participant_events: set[str] = set()
if selected_event not in participant_events:
print(f"Skipping {self.participant_map[file_path]}: Event '{selected_event}' not found.")
continue
cha_df = self.cha_dict.get(file_path)
if cha_df is not None:
all_cha = pd.concat([all_cha, cha_df], ignore_index=True)
file_path = selected_file_paths[0]
p_haemo = self.haemo_dict.get(file_path)
# Concatenate individual ROI stats (df_ind) for all chosen subjects
df_group = DataFrame()
if selected_file_paths:
for file_path in selected_file_paths:
df = self.df_ind_dict.get(file_path)
if df is not None:
df_group = pd.concat([df_group, df], ignore_index=True)
for idx in selected_indexes:
if idx == 0:
params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 5)
correction_method = params.get("correction_method", "fdr_bh")
target_chroma = params.get("target_chroma", "hbo")
graph_bounds = params.get("graph_bounds", 0.0)
if correction_method == "None":
correction_method = None
if not selected_event:
print("Warning: No event condition selected for ROI analysis.")
continue
if df_group.empty:
print("No ROI data (df_ind) found for selected participants.")
continue
# Filter down to the selected experimental event/condition
if selected_event:
if 'Condition' in df_group.columns:
df_filtered = df_group[df_group['Condition'] == selected_event]
else:
print("Warning: 'Condition' column not found in ROI data.")
df_filtered = df_group
else:
df_filtered = df_group
if df_filtered.empty:
print(f"No ROI data matches the condition '{selected_event}'.")
continue
all_cha_filtered = DataFrame()
if not all_cha.empty:
if selected_event and 'Condition' in all_cha.columns:
all_cha_filtered = all_cha[all_cha['Condition'] == selected_event]
else:
all_cha_filtered = all_cha
run_roi_second_level_analysis(
df_roi_all=df_filtered,
condition=selected_event,
df_cha_all=all_cha_filtered,
raw_haemo=p_haemo,
p_threshold=p_threshold,
min_subjects=min_subjects,
correction_method=correction_method,
target_chroma=target_chroma,
graph_bounds=graph_bounds if graph_bounds > 0.0 else None,
)
elif idx == 1:
params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 5)
correction_method = params.get("correction_method", "None")
target_chroma = params.get("target_chroma", "hbo")
roi_a = params.get("roi_a", "").strip()
roi_b = params.get("roi_b", "").strip()
if not selected_event:
print("Paired ROI contrast requires a specific event/condition "
"to be selected - pick one from the Event dropdown first.")
continue
if df_group.empty:
print("No ROI data (df_ind) found for selected participants.")
continue
if correction_method == "None":
correction_method = None
if not roi_a or not roi_b:
print("Both ROI A and ROI B must be specified.")
continue
run_roi_paired_contrast_analysis(
df_roi_all=df_group,
roi_pairs=(roi_a, roi_b),
condition=selected_event,
target_chroma=target_chroma,
min_subjects=min_subjects,
p_threshold=p_threshold,
correction_method=correction_method,
roi_a_label=roi_a,
roi_b_label=roi_b,
)
elif idx == 2:
params = param_values.get(idx, {})
p_threshold = params.get("p_threshold", 0.05)
min_subjects = params.get("min_subjects", 5)
correction_method = params.get("correction_method", "fdr_bh")
target_chroma = params.get("target_chroma", "hbo")
contrast_name = params.get("contrast_name", "")
weighted = params.get("weighted", True)
graph_bounds = params.get("graph_bounds", 0.0)
if not selected_event:
print("Joint contrast ROI analysis requires a specific contrast "
"to be selected from the Event dropdown first.")
continue
if not contrast_name:
print("Contrast name must be specified.")
continue
all_contrasts: list[DataFrame] = []
for fp in selected_file_paths:
condition_dfs = self.contrast_results_dict.get(fp)
if condition_dfs is None:
print(f" [MISSING] '{fp}' not found in contrast_results.")
continue
if contrast_name in condition_dfs:
df = condition_dfs[contrast_name].copy()
df["ID"] = fp
df["contrast_name"] = contrast_name
all_contrasts.append(df)
else:
print(f" [MISSING CONTRAST] '{contrast_name}' not "
f"available for {self.participant_map.get(fp, fp)}.")
if not all_contrasts:
print(f"No contrast data found for '{contrast_name}' "
f"across selected participants.")
continue
df_contrasts = pd.concat(all_contrasts, ignore_index=True)
selected_roi_maps = {
fp: self.roi_channel_map_dict[fp]
for fp in selected_file_paths
if fp in self.roi_channel_map_dict
}
if not selected_roi_maps:
print("No channel-to-ROI mapping available for selected participants.")
continue
try:
roi_theta = aggregate_channel_contrasts_to_roi(
df_contrasts,
roi_channel_maps=selected_roi_maps,
weighted=weighted,
)
except Exception as e:
print(f"Failed to aggregate contrasts to ROI: {e}")
continue
if roi_theta.empty:
print("No ROI-level contrast values could be computed "
"(check regions.json channel names against this montage).")
continue
run_roi_second_level_analysis(
df_roi_all=roi_theta,
condition=contrast_name,
df_cha_all=None,
raw_haemo=p_haemo,
p_threshold=p_threshold,
min_subjects=min_subjects,
correction_method=correction_method,
target_chroma=target_chroma,
graph_bounds=graph_bounds if graph_bounds > 0.0 else None,
)
else:
print(f"No method defined for index {idx}")
+1 -2
View File
@@ -8,7 +8,6 @@ License: GPL-3.0
""" """
# Built-in imports # Built-in imports
from pathlib import Path
from typing import Any, cast from typing import Any, cast
# External library imports # External library imports
@@ -69,7 +68,7 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
class ParticipantBrainViewerWidget(ParticipantUIMixin, FlaresBaseWidget): class ParticipantBrainViewerWidget(ParticipantUIMixin, FlaresBaseWidget):
def __init__( def __init__(
self, self,
haemo_dict: dict[str | Path, BaseRaw], haemo_dict: dict[str, BaseRaw],
cha_dict: dict[str, DataFrame], cha_dict: dict[str, DataFrame],
) -> None: ) -> None:
+83 -94
View File
@@ -6,11 +6,16 @@ Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
# Built-in Imports
import os import os
from pathlib import Path
import time import time
import traceback import traceback
from multiprocessing import Process, current_process, Manager from multiprocessing import Process, current_process, Manager
from typing import Any, Dict, List, Optional, Tuple, Union
# External library imports
from matplotlib.backend_bases import Event
import numpy as np import numpy as np
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@@ -18,25 +23,27 @@ import matplotlib.image as mpimg
from matplotlib.figure import Figure from matplotlib.figure import Figure
from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qtagg import FigureCanvasQTAgg as FigureCanvas
from PySide6.QtWidgets import QFrame, QGridLayout, QHBoxLayout, QLabel, QProgressBar, QPushButton, QScrollArea, QSizePolicy, QWidget, QDialog, QVBoxLayout from PySide6.QtWidgets import QFrame, QGridLayout, QHBoxLayout, QLabel, QLayout, QProgressBar, QPushButton, QScrollArea, QSizePolicy, QWidget, QDialog, QVBoxLayout
from PySide6.QtCore import QThread, Qt, QSize, QTimer from PySide6.QtCore import QThread, Qt, QSize, QTimer, QObject, Signal
from PySide6.QtGui import QPixmap, QImage from PySide6.QtGui import QCloseEvent, QMouseEvent, QPixmap, QImage
from pandas import DataFrame
from mne.io.base import BaseRaw
from src.shared.flaresbasewidget import FlaresBaseWidget from src.shared.flaresbasewidget import FlaresBaseWidget
from src.shared.shareddata import APP_NAME, resource_path from src.shared.shareddata import APP_NAME, resource_path
class MultiProgressDialog(QDialog): class MultiProgressDialog(QDialog):
def __init__(self, parent=None): def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent) super().__init__(parent)
self.setWindowTitle("fOLD Analysis Progress") self.setWindowTitle("fOLD Analysis Progress")
self.setFixedWidth(400) self.setFixedWidth(400)
self.setWindowModality(Qt.WindowModality.NonModal) self.setWindowModality(Qt.WindowModality.NonModal)
self.layout = QVBoxLayout(self) self.main_layout = QVBoxLayout(self)
self.bars = {} self.bars: Dict[str, QProgressBar] = {}
self.allow_closing = False self.allow_closing = False
def add_participant(self, label, total_steps): def add_participant(self, label: Any, total_steps: Union[int, float, str]) -> None:
clean_key = str(label).strip() clean_key = str(label).strip()
label_widget = QLabel(f"Analyzing {clean_key}...") label_widget = QLabel(f"Analyzing {clean_key}...")
pbar = QProgressBar() pbar = QProgressBar()
@@ -44,16 +51,17 @@ class MultiProgressDialog(QDialog):
pbar.setMaximum(int(total_steps)) # Ensure this is a strict integer pbar.setMaximum(int(total_steps)) # Ensure this is a strict integer
pbar.setValue(0) pbar.setValue(0)
self.layout.addWidget(label_widget) self.main_layout.addWidget(label_widget)
self.layout.addWidget(pbar) self.main_layout.addWidget(pbar)
self.bars[label] = pbar self.bars[clean_key] = pbar
def update_bar(self, label, value): def update_bar(self, label: Any, value: Union[int, float, str]) -> None:
if label in self.bars: clean_key = str(label).strip()
if clean_key in self.bars:
# Force integers to prevent QProgressBar from breaking or flickering # Force integers to prevent QProgressBar from breaking or flickering
self.bars[label].setValue(int(value)) self.bars[clean_key].setValue(int(value))
def closeEvent(self, event): def closeEvent(self, event: QCloseEvent) -> None:
if self.allow_closing: if self.allow_closing:
event.accept() event.accept()
else: else:
@@ -64,8 +72,13 @@ class MultiProgressDialog(QDialog):
self.close() self.close()
def single_participant_worker(
file_path: str,
raw_data: Any,
result_queue: Any,
progress_queue: Any,
) -> None:
def single_participant_worker(file_path, raw_data, result_queue, progress_queue):
""" Runs inside its own dedicated process """ """ Runs inside its own dedicated process """
p_name = os.path.basename(file_path) p_name = os.path.basename(file_path)
try: try:
@@ -81,8 +94,7 @@ def single_participant_worker(file_path, raw_data, result_queue, progress_queue)
progress_queue.put(f"ERROR: {p_name} - {str(e)}") progress_queue.put(f"ERROR: {p_name} - {str(e)}")
def get_landmark_color_map() -> Dict[str, Tuple[float, float, float, float]]:
def get_landmark_color_map():
"""Generates the unified 40-color map for fOLD landmarks.""" """Generates the unified 40-color map for fOLD landmarks."""
landmarks = [ landmarks = [
"1 - Primary Somatosensory Cortex", "2 - Primary Somatosensory Cortex", "1 - Primary Somatosensory Cortex", "2 - Primary Somatosensory Cortex",
@@ -116,7 +128,15 @@ class StaticChannelCanvas(FigureCanvas):
"""The Pop-up Window Canvas. """The Pop-up Window Canvas.
Renders the interactive pie chart on the left, and a matching PNG image on the right. Renders the interactive pie chart on the left, and a matching PNG image on the right.
""" """
def __init__(self, channel_name, data_list, color_map, image_path=None, parent=None): def __init__(
self,
channel_name: str,
data_list: List[Dict[str, Any]],
color_map: Dict[str, Union[str, Tuple[float, float, float, float]]],
image_path: Optional[str] = None,
parent: Optional[QWidget] = None,
) -> None:
self.fig = Figure(figsize=(11.0, 5.5)) self.fig = Figure(figsize=(11.0, 5.5))
self.ax = self.fig.subplots(1, 2) self.ax = self.fig.subplots(1, 2)
@@ -194,7 +214,7 @@ class StaticChannelCanvas(FigureCanvas):
self.mpl_connect('motion_notify_event', self._on_hover) self.mpl_connect('motion_notify_event', self._on_hover)
def _on_hover(self, event): def _on_hover(self, event: Event) -> None:
try: try:
# FIX: Only track mouse events when hovering over the LEFT axis frame containing the pie chart # FIX: Only track mouse events when hovering over the LEFT axis frame containing the pie chart
if event.inaxes != self.ax[0]: if event.inaxes != self.ax[0]:
@@ -231,10 +251,10 @@ class StaticChannelCanvas(FigureCanvas):
self.draw_idle() self.draw_idle()
except Exception as err: except Exception as err:
print("[ERROR] Internal failure inside _on_hover loop:") print(f"[ERROR] Internal failure inside _on_hover loop: {err}")
traceback.print_exc() traceback.print_exc()
def _explode_wedge(self, index_to_expand): def _explode_wedge(self, index_to_expand: int) -> None:
changed = False changed = False
for idx, wedge in enumerate(self.wedges): for idx, wedge in enumerate(self.wedges):
if idx == index_to_expand: if idx == index_to_expand:
@@ -252,7 +272,7 @@ class StaticChannelCanvas(FigureCanvas):
if changed: if changed:
self.draw_idle() self.draw_idle()
def _reset_wedges(self): def _reset_wedges(self) -> None:
changed = False changed = False
for wedge in self.wedges: for wedge in self.wedges:
if wedge.center != (0.0, 0.0): if wedge.center != (0.0, 0.0):
@@ -274,7 +294,7 @@ class StandaloneLegendDialog(QWidget):
layout.setContentsMargins(10, 10, 10, 10) layout.setContentsMargins(10, 10, 10, 10)
# Reuse your exact card creation method to render inside the popup window # Reuse your exact card creation method to render inside the popup window
legend_card = canvas_engine.create_legend_card(title_prefix, self) legend_card = canvas_engine.create_legend_card(title_prefix)
layout.addWidget(legend_card) layout.addWidget(legend_card)
@@ -381,7 +401,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
self.mpl_connect('button_press_event', self._on_canvas_click) self.mpl_connect('button_press_event', self._on_canvas_click)
def create_matrix_card(self, title_prefix, layout_to_attach_to): def create_matrix_card(self, title_prefix: str, layout_to_attach_to: QLayout) -> QFrame:
"""Wraps the channel matrix layout inside a responsive, matching hover-stylized card frame.""" """Wraps the channel matrix layout inside a responsive, matching hover-stylized card frame."""
# 1. Create matching styled container card frame # 1. Create matching styled container card frame
card_frame = QFrame() card_frame = QFrame()
@@ -422,7 +442,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
layout_to_attach_to.addWidget(card_frame) layout_to_attach_to.addWidget(card_frame)
return card_frame return card_frame
def _on_canvas_click(self, event): def _on_canvas_click(self, event: Any) -> None:
# CASE 1: Whitespace Clicked -> Open full 25-matrix in fullscreen window # CASE 1: Whitespace Clicked -> Open full 25-matrix in fullscreen window
if event.inaxes is None: if event.inaxes is None:
self._open_fullscreen_grid() self._open_fullscreen_grid()
@@ -473,7 +493,8 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
self._fullscreen_refs = [w for w in self._fullscreen_refs if w.isVisible()] self._fullscreen_refs = [w for w in self._fullscreen_refs if w.isVisible()]
self._fullscreen_refs.append(fullscreen_window) self._fullscreen_refs.append(fullscreen_window)
def _calculate_total_brodmann_profile(self, channels_data):
def _calculate_total_brodmann_profile(self, channels_data: Dict[str, Any]):
"""Sums and normalizes the specificity profile across all channels.""" """Sums and normalizes the specificity profile across all channels."""
totals = {} totals = {}
num_channels = len(channels_data) num_channels = len(channels_data)
@@ -553,7 +574,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
self._open_popups.append(popup) self._open_popups.append(popup)
def create_total_summary_card(self, title_prefix, layout_to_attach_to): def create_total_summary_card(self, title_prefix: str, layout_to_attach_to: QLayout) -> QFrame:
"""Generates a highly compact, clickable embedded card on the main window showing aggregated data.""" """Generates a highly compact, clickable embedded card on the main window showing aggregated data."""
# 1. Calculate the normalized profile data payload using the instance's own data # 1. Calculate the normalized profile data payload using the instance's own data
summary_data = self._calculate_total_brodmann_profile(self.channels_data) summary_data = self._calculate_total_brodmann_profile(self.channels_data)
@@ -609,7 +630,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
card_layout.addWidget(summary_canvas) card_layout.addWidget(summary_canvas)
card_layout.addStretch(0) card_layout.addStretch(0)
def handle_card_click(event): def handle_card_click(event: QMouseEvent) -> None:
# Only trigger expansion if it's a primary left-click action # Only trigger expansion if it's a primary left-click action
if event.button() == Qt.MouseButton.LeftButton: if event.button() == Qt.MouseButton.LeftButton:
self._open_expanded_summary_window(title_prefix, summary_data) self._open_expanded_summary_window(title_prefix, summary_data)
@@ -626,7 +647,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
def create_legend_card(self, title_prefix, layout_to_attach_to): def create_legend_card(self, title_prefix: str) -> QFrame:
card = QFrame() card = QFrame()
card.setStyleSheet("QFrame { background-color: #ffffff; border-radius: 8px; border: 1px solid #e9ecef; }") card.setStyleSheet("QFrame { background-color: #ffffff; border-radius: 8px; border: 1px solid #e9ecef; }")
@@ -686,7 +707,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
return card return card
def _open_expanded_summary_window(self, title_prefix, summary_data): def _open_expanded_summary_window(self, title_prefix: str, summary_data: List[Any]) -> None:
"""Pops open a beautifully scaled, independent large window when the card is clicked.""" """Pops open a beautifully scaled, independent large window when the card is clicked."""
popup = QWidget(None) popup = QWidget(None)
popup.setWindowTitle(f"Grand Total Profile Details - {title_prefix}") popup.setWindowTitle(f"Grand Total Profile Details - {title_prefix}")
@@ -719,16 +740,18 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
self._summary_popups.append(popup) self._summary_popups.append(popup)
from PySide6.QtCore import QObject, Signal
from multiprocessing import Manager, Process
class ProcessOrchestrator(QObject): class ProcessOrchestrator(QObject):
# Fires when Manager + Processes are completely ready # Fires when Manager + Processes are completely ready
# Emits: (manager_instance, result_queue, progress_queue, active_processes_list) # Emits: (manager_instance, result_queue, progress_queue, active_processes_list)
setup_finished = Signal(object, object, object, list) setup_finished = Signal(object, object, object, list)
setup_failed = Signal(str) setup_failed = Signal(str)
def __init__(self, selected_files, haemo_dict, worker_func): def __init__(self,
selected_files,
haemo_dict: dict[str, BaseRaw],
worker_func
):
super().__init__() super().__init__()
self.selected_files = selected_files self.selected_files = selected_files
self.haemo_dict = haemo_dict self.haemo_dict = haemo_dict
@@ -758,7 +781,12 @@ class ProcessOrchestrator(QObject):
class ParticipantFoldChannelsWidget(FlaresBaseWidget): class ParticipantFoldChannelsWidget(FlaresBaseWidget):
def __init__(self, haemo_dict, cha_dict): def __init__(
self,
haemo_dict: dict[str | Path, BaseRaw],
cha_dict: dict[str, DataFrame]
) -> None:
super().__init__("ParticipantFoldChannels") super().__init__("ParticipantFoldChannels")
self.setWindowTitle(f"Participant Fold Channels Viewer - {APP_NAME.upper()}") self.setWindowTitle(f"Participant Fold Channels Viewer - {APP_NAME.upper()}")
self.haemo_dict = haemo_dict self.haemo_dict = haemo_dict
@@ -773,9 +801,9 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
self.participant_map[file_path] = short_label self.participant_map[file_path] = short_label
self.participant_dropdown_items.append(display_label) self.participant_dropdown_items.append(display_label)
self.layout = QVBoxLayout(self) self.main_layout = QVBoxLayout(self)
self.top_bar = QHBoxLayout() self.top_bar = QHBoxLayout()
self.layout.addLayout(self.top_bar) self.main_layout.addLayout(self.top_bar)
self.participant_dropdown = self._create_multiselect_dropdown(self.participant_dropdown_items) self.participant_dropdown = self._create_multiselect_dropdown(self.participant_dropdown_items)
self.participant_dropdown.currentIndexChanged.connect(self.update_participant_dropdown_label) self.participant_dropdown.currentIndexChanged.connect(self.update_participant_dropdown_label)
@@ -803,11 +831,10 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
self.scroll_area.setWidgetResizable(True) self.scroll_area.setWidgetResizable(True)
self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded) self.scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
self.scroll_area.setStyleSheet("QScrollArea { border: none; background-color: #f1f3f5; }") self.scroll_area.setStyleSheet("QScrollArea { border: none; }")
# 2. Create the central canvas widget that inside the scroll block # 2. Create the central canvas widget that inside the scroll block
self.scroll_content_widget = QWidget() self.scroll_content_widget = QWidget()
self.scroll_content_widget.setStyleSheet("background-color: #f1f3f5;")
# 3. Establish the strict 3-column layout grid engine # 3. Establish the strict 3-column layout grid engine
self.grid_layout = QGridLayout(self.scroll_content_widget) self.grid_layout = QGridLayout(self.scroll_content_widget)
@@ -829,7 +856,7 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
self.scroll_area.setWidget(self.scroll_content_widget) self.scroll_area.setWidget(self.scroll_content_widget)
# Add the self.scroll_area widget to your root layout view frame panel # Add the self.scroll_area widget to your root layout view frame panel
self.layout.addWidget(self.scroll_area) self.main_layout.addWidget(self.scroll_area)
self.thumb_size = QSize(280, 180) self.thumb_size = QSize(280, 180)
self.showMaximized() self.showMaximized()
@@ -889,7 +916,14 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
self.orchestrator_thread.start() self.orchestrator_thread.start()
print(f"After 4: {datetime.now()}") print(f"After 4: {datetime.now()}")
def on_orchestration_success(self, manager, result_queue, progress_queue, active_processes): def on_orchestration_success(
self,
manager: Any,
result_queue: Any,
progress_queue: Any,
active_processes: List[Any]
) -> None:
""" Executed on the Main GUI Thread once background process setup finishes """ """ Executed on the Main GUI Thread once background process setup finishes """
self.manager = manager self.manager = manager
self.result_queue = result_queue self.result_queue = result_queue
@@ -902,15 +936,15 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
self.result_timer.timeout.connect(self.check_parallel_results) self.result_timer.timeout.connect(self.check_parallel_results)
self.result_timer.start() self.result_timer.start()
def on_orchestration_failed(self, error_msg):
def on_orchestration_failed(self, error_msg: str) -> None:
""" Fallback handler if Windows permissions or pickling fails in background """ """ Fallback handler if Windows permissions or pickling fails in background """
if hasattr(self, 'multi_progress'): if hasattr(self, 'multi_progress'):
self.multi_progress.close() self.multi_progress.close()
print(f"[CRITICAL FAILURE] Background Orchestration Failed:\n{error_msg}") print(f"[CRITICAL FAILURE] Background Orchestration Failed:\n{error_msg}")
def check_parallel_results(self) -> None:
def check_parallel_results(self):
# Check for progress/completion signals # Check for progress/completion signals
while not self.progress_queue.empty(): while not self.progress_queue.empty():
@@ -991,8 +1025,7 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
legend_title = "Grand Total Brodmann Mapping Profile" legend_title = "Grand Total Brodmann Mapping Profile"
legend_card = global_canvas.create_legend_card( legend_card = global_canvas.create_legend_card(
title_prefix=legend_title, title_prefix=legend_title
layout_to_attach_to=self.scroll_content_widget.layout()
) )
def handle_legend_click(event): def handle_legend_click(event):
@@ -1007,51 +1040,7 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
self.grid_layout.addWidget(legend_card, row, col) self.grid_layout.addWidget(legend_card, row, col)
def add_images_to_grid(self, result_dict: Dict[str, Dict[str, Any]]) -> None:
# def add_images_to_grid(self, result_dict):
# """
# result_dict format: { file_path: {"main": bytes, "legend": bytes} }
# """
# for file_path, images in result_dict.items():
# if self.grid_layout.count() == 0 and "legend" in images:
# self._add_legend_to_grid(images["legend"])
# # Create a container for this participant's results
# container = QFrame()
# container.setFrameShape(QFrame.StyledPanel)
# vbox = QVBoxLayout(container)
# participant_label = self.participant_map.get(file_path, os.path.basename(file_path))
# title = QLabel(f"<b>{participant_label}</b>")
# title.setAlignment(Qt.AlignCenter)
# vbox.addWidget(title)
# # We primarily want to show the 'main' plot in the grid
# if "main" in images:
# pixmap = self._bytes_to_pixmap(images["main"])
# img_label = QLabel()
# # Scale it to fit the thumbnail size defined in __init__
# img_label.setPixmap(pixmap.scaled(
# self.thumb_size,
# Qt.KeepAspectRatio,
# Qt.SmoothTransformation
# ))
# img_label.setAlignment(Qt.AlignCenter)
# # Optional: Click to open full size
# img_label.mousePressEvent = lambda e, p=pixmap, t=participant_label: self._open_full_size(p, t)
# vbox.addWidget(img_label)
# # Determine grid position (row-major order)
# count = self.grid_layout.count()
# row = count // 3 # 3 columns wide
# col = count % 3
# self.grid_layout.addWidget(container, row, col)
def add_images_to_grid(self, result_dict):
color_map = get_landmark_color_map() color_map = get_landmark_color_map()
for file_path, channels_data in result_dict.items(): for file_path, channels_data in result_dict.items():
@@ -1091,12 +1080,12 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
self.grid_layout.addWidget(summary_card, row, col) self.grid_layout.addWidget(summary_card, row, col)
def _bytes_to_pixmap(self, png_bytes): def _bytes_to_pixmap(self, png_bytes: bytes) -> QPixmap:
"""Converts raw bytes from the multiprocess queue to a QPixmap.""" """Converts raw bytes from the multiprocess queue to a QPixmap."""
image = QImage.fromData(png_bytes) image = QImage.fromData(png_bytes)
return QPixmap.fromImage(image) return QPixmap.fromImage(image)
def _open_full_size(self, pixmap, title): def _open_full_size(self, pixmap: QPixmap, title: str) -> None:
"""Simple popup to view the image at a readable scale.""" """Simple popup to view the image at a readable scale."""
view = QDialog(self) view = QDialog(self)
view.setWindowTitle(f"Full View - {title}") view.setWindowTitle(f"Full View - {title}")
@@ -1106,7 +1095,7 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
layout.addWidget(label) layout.addWidget(label)
view.show() view.show()
def _add_legend_to_grid(self, legend_bytes): def _add_legend_to_grid(self, legend_bytes: bytes) -> None:
"""Helper to put the legend in the first slot.""" """Helper to put the legend in the first slot."""
container = QFrame() container = QFrame()
container.setStyleSheet("background-color: #f9f9f9; border: 1px solid #ccc;") container.setStyleSheet("background-color: #f9f9f9; border: 1px solid #ccc;")
+116 -96
View File
@@ -7,16 +7,13 @@ Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
# Built-in Imports # Built-in imports
from pathlib import Path
from typing import Any, cast from typing import Any, cast
# External library imports # External library imports
from PySide6.QtWidgets import QMessageBox from PySide6.QtWidgets import QMessageBox
from pandas import DataFrame from mne import Annotations, Epochs
from mne import Annotations
from mne.io.base import BaseRaw from mne.io.base import BaseRaw
from flares import functional_connectivity_betas, functional_connectivity_envelope, functional_connectivity_spectral_epochs, functional_connectivity_spectral_time from flares import functional_connectivity_betas, functional_connectivity_envelope, functional_connectivity_spectral_epochs, functional_connectivity_spectral_time
@@ -25,73 +22,66 @@ from src.shared.shareddata import APP_NAME
PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = { PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
0: [ 0: [ # Spectral Coherence
{ {"key": "method", "label": "Connectivity method", "default": "wpli2_debiased", "type": list, "options": ["coh", "pli", "wpli2_debiased"]},
"key": "n_lines", {"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
"label": "<Description>", {"key": "vmin", "label": "Minimum coherence value to display", "default": "0.3", "type": float},
"default": "20", {"key": "fmin", "label": "Lower frequency bound (Hz)", "default": "0.04", "type": float},
"type": int, {"key": "fmax", "label": "Upper frequency bound (Hz)", "default": "0.2", "type": float},
},
{
"key": "vmin",
"label": "<Description>",
"default": "0.9",
"type": float,
},
], ],
1: [ 1: [ # Envelope Correlation
{ {"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
"key": "n_lines", {"key": "vmin", "label": "Minimum correlation value to display", "default": "0.9", "type": float},
"label": "<Description>", {"key": "fmin", "label": "Band-pass lower frequency (Hz)", "default": "0.04", "type": float},
"default": "20", {"key": "fmax", "label": "Band-pass upper frequency (Hz)", "default": "0.2", "type": float},
"type": int, {"key": "orthogonalize", "label": "Orthogonalize (reduce signal leakage between channels)", "default": "False", "type": bool},
}, {"key": "absolute", "label": "Use absolute value (discard anti-correlation sign)", "default": "True", "type": bool},
{
"key": "vmin",
"label": "<Description>",
"default": "0.9",
"type": float,
},
], ],
2: [ 2: [ # Beta-Series Correlation
{ {"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
"key": "n_lines", {"key": "drift_model", "label": "Drift model", "default": "cosine", "type": list, "options": ["cosine", "polynomial"]},
"label": "<Description>", {"key": "drift_order", "label": "Drift order", "default": "1", "type": int},
"default": "20", {"key": "hrf_model", "label": "HRF model", "default": "glover", "type": list, "options": ["glover", "spm", "fir"]},
"type": int, {"key": "apply_gsr", "label": "Apply Global Signal Regression", "default": "True", "type": bool},
}, {"key": "resample_freq", "label": "Resample rate before GLM fit (Hz) - lower is much faster", "default": "4.0", "type": float},
{ {"key": "min_effect_size", "label": "Minimum |r| to display", "default": "0.7", "type": float},
"key": "vmin", {"key": "alpha", "label": "FDR significance threshold", "default": "0.05", "type": float},
"label": "<Description>",
"default": "0.9",
"type": float,
},
], ],
3: [ 3: [ # Time-Resolved Spectral Coherence
{ {"key": "method", "label": "Connectivity method", "default": "wpli", "type": list, "options": ["coh", "pli", "wpli"]},
"key": "n_lines", {"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
"label": "<Description>", {"key": "vmin", "label": "Minimum coherence value to display", "default": "0.3", "type": float},
"default": "20", {"key": "fmin", "label": "Lower frequency bound (Hz)", "default": "0.04", "type": float},
"type": int, {"key": "fmax", "label": "Upper frequency bound (Hz)", "default": "0.2", "type": float},
}, {"key": "n_freqs", "label": "Number of frequency bins", "default": "10", "type": int},
{ {"key": "cycles_multiplier", "label": "Cycles per frequency (window length control)", "default": "2.0", "type": float},
"key": "vmin",
"label": "<Description>",
"default": "0.9",
"type": float,
},
], ],
} }
DESCRIPTION = """0. Spectral Coherence (functional_connectivity_spectral_epochs)
\nTests for connectivity between channel pairs using the selected method: coherence ('coh'), Phase Lag Index ('pli'), or debiased weighted PLI squared ('wpli2_debiased', default). PLI/wPLI-family methods discount zero-lag contributions, making them substantially more robust to shared systemic/vascular signal (which tends to hit multiple channels near-simultaneously) than plain coherence - recommended over 'coh' unless you have a specific reason to want raw coherence.
\nfmin must satisfy at least 5 full oscillation cycles within your epoch length (epoch_duration x fmin >= 5) for a reliable estimate - if it doesn't, this will refuse to run with an error stating the minimum viable fmin for your epoch length, rather than silently producing an unreliable result. Note that different methods have very different typical value ranges (coherence commonly 0.3-1.0; wPLI/wPLI2-debiased often much lower, sometimes 0.1-0.4) - vmin needs to be recalibrated when switching methods, or real connections may not render.
\n1. Envelope Correlation (functional_connectivity_envelope)
\nExtracts the Hilbert amplitude envelope from bandpass-filtered signals to measure slow amplitude power correlations across time within epoched data. A significant result indicates that the overall energy profiles or activation magnitudes of two regions co-vary over time, independent of sub-second phase locking. Its power is heavily degraded if epoch lengths are too short to capture multiple complete cycles at fmin - same cycle-count requirement as the Spectral Coherence method above, though this method does not currently enforce it automatically.
\nUncorrected global motion or systemic arterial pressure shifts can globally inflate envelope correlations across the whole head - consider this alongside orthogonalize/absolute when interpreting results.
\n2. Beta-Series Correlation (functional_connectivity_betas)
\nFits a GLM to estimate trial-by-trial activation magnitudes (betas), optionally applies Global Signal Regression (GSR) to strip head-wide systemic noise, and correlates those beta series across trials with FDR (q < alpha) and effect-size thresholding. A significant connection means that when Region A responds more strongly on a given trial, Region B also responds more strongly. Not subject to the epoch-length/frequency-resolution constraint that affects the spectral methods above, since no spectral estimation is involved.
\nRequires at least 4 (ideally 15+) repeated trials of the selected event. hrf_model='fir' is far more computationally expensive than 'glover'/'spm' (a separate regressor column per FIR delay per trial) - if this method is slow to the point of appearing frozen, check hrf_model is not set to 'fir' before assuming something is broken.
\n3. Time-Resolved Spectral Coherence (functional_connectivity_spectral_time)
\nSame connectivity methods as Spectral Coherence above ('coh'/'pli'/'wpli' - note: 'wpli2_debiased' is NOT available for this method, unlike the epochs-based one), but tracks how connectivity evolves over multiple frequency bins across the trial duration rather than a single averaged value. Same fmin/epoch-length cycle-count requirement as method 0 applies and is enforced the same way.
\nMore computationally expensive than method 0 due to the additional frequency/time resolution - if timing matters, prefer method 0 unless the time-resolved view is specifically needed.
"""
class ParticipantFunctionalConnectivityWidget(ParticipantUIMixin, FlaresBaseWidget): class ParticipantFunctionalConnectivityWidget(ParticipantUIMixin, FlaresBaseWidget):
def __init__( def __init__(
self, self,
haemo_dict: dict[str | Path, BaseRaw], haemo_dict: dict[str, BaseRaw],
epochs_dict: dict[str, DataFrame], epochs_dict: dict[str, Epochs],
) -> None: ) -> None:
super().__init__("ParticipantFunctionalConnectivity") super().__init__("ParticipantFunctionalConnectivity")
@@ -99,11 +89,12 @@ class ParticipantFunctionalConnectivityWidget(ParticipantUIMixin, FlaresBaseWidg
self.haemo_dict = haemo_dict self.haemo_dict = haemo_dict
self.epochs_dict = epochs_dict self.epochs_dict = epochs_dict
QMessageBox.warning(self, f"Warning - {APP_NAME.upper()}", f"Functional Connectivity is still in development and the results should currently be taken with a grain of salt. " QMessageBox.warning(self, f"Warning - {APP_NAME.upper()}", f"Functional Connectivity is still in beta. While the results are now almost finalized, the processing is slow and it WILL hang the application for minutes.")
"By clicking OK, you accept that the images generated may not be factual.")
self.setup_participant_ui(["0 (Spectral Connectivity Epochs)", "1 (Envelope Correlation)", "2 (Betas)", "3 (Spectral Connectivity Epochs)",])
self.setup_participant_ui(
["0 (Spectral Coherence)", "1 (Envelope Correlation)", "2 (Beta-Series Correlation)", "3 (Time-Resolved Spectral Coherence)"],
placeholder_text=DESCRIPTION
)
def process_request(self): def process_request(self):
request = self.get_common_request_data(PARAMETERIZED_INDEXES) request = self.get_common_request_data(PARAMETERIZED_INDEXES)
@@ -119,7 +110,7 @@ class ParticipantFunctionalConnectivityWidget(ParticipantUIMixin, FlaresBaseWidg
haemo_obj = self.haemo_dict.get(file_path) haemo_obj = self.haemo_dict.get(file_path)
epochs_obj = self.epochs_dict.get(file_path) epochs_obj = self.epochs_dict.get(file_path)
if haemo_obj is None: if haemo_obj is None or epochs_obj is None:
continue continue
if selected_event: if selected_event:
@@ -137,46 +128,75 @@ class ParticipantFunctionalConnectivityWidget(ParticipantUIMixin, FlaresBaseWidg
continue continue
for idx in selected_indexes: for idx in selected_indexes:
if idx == 0:
params = param_values.get(idx, {}) params = param_values.get(idx, {})
n_lines = params.get("n_lines", None) if idx == 0:
vmin = params.get("vmin", None) method = params.get("method", "wpli2_debiased")
n_lines = params.get("n_lines", 20)
vmin = params.get("vmin", 0.9)
fmin = params.get("fmin", 0.04)
fmax = params.get("fmax", 0.2)
if n_lines is None or vmin is None: functional_connectivity_spectral_epochs(epochs=epochs_obj, n_lines=n_lines, vmin=vmin, fmin=fmin, fmax=fmax, method=method)
print(f"Missing parameters for index {idx}, skipping.")
continue
functional_connectivity_spectral_epochs(epochs_obj, n_lines, vmin)
elif idx == 1: elif idx == 1:
params = param_values.get(idx, {}) n_lines = params.get("n_lines", 20)
n_lines = params.get("n_lines", None) vmin = params.get("vmin", 0.9)
vmin = params.get("vmin", None) fmin = params.get("fmin", 0.04)
fmax = params.get("fmax", 0.2)
orthogonalize = params.get("orthogonalize", False)
absolute = params.get("absolute", True)
if n_lines is None or vmin is None: functional_connectivity_envelope(
print(f"Missing parameters for index {idx}, skipping.") epochs=epochs_obj,
continue n_lines=n_lines,
functional_connectivity_envelope(epochs_obj, n_lines, vmin) vmin=vmin, fmin=fmin,
fmax=fmax,
orthogonalize=orthogonalize,
absolute=absolute,
)
elif idx == 2: elif idx == 2:
params = param_values.get(idx, {}) n_lines = params.get("n_lines", 20)
n_lines = params.get("n_lines", None) drift_model = params.get("drift_model", "cosine")
vmin = params.get("vmin", None) drift_order = params.get("drift_order", 1)
hrf_model = params.get("hrf_model", "glover")
apply_gsr = params.get("apply_gsr", True)
min_effect_size = params.get("min_effect_size", 0.7)
alpha = params.get("alpha", 0.05)
resample_freq = params.get("resample_freq", 4.0)
if n_lines is None or vmin is None: functional_connectivity_betas(
print(f"Missing parameters for index {idx}, skipping.") raw_hbo=haemo_obj,
continue n_lines=n_lines,
functional_connectivity_betas(haemo_obj, n_lines, vmin, selected_event) event_name=selected_event,
drift_model=drift_model,
drift_order=drift_order,
hrf_model=hrf_model,
apply_gsr=apply_gsr,
min_effect_size=min_effect_size,
alpha=alpha,
resample_freq=resample_freq,
)
elif idx == 3: elif idx == 3:
params = param_values.get(idx, {}) method = params.get("method", "wpli")
n_lines = params.get("n_lines", None) n_lines = params.get("n_lines", 20)
vmin = params.get("vmin", None) vmin = params.get("vmin", 0.9)
fmin = params.get("fmin", 0.04)
fmax = params.get("fmax", 0.2)
n_freqs = params.get("n_freqs", 10)
cycles_multiplier = params.get("cycles_multiplier", 2.0)
if n_lines is None or vmin is None: functional_connectivity_spectral_time(
print(f"Missing parameters for index {idx}, skipping.") epochs=epochs_obj,
continue n_lines=n_lines,
functional_connectivity_spectral_time(epochs_obj, n_lines, vmin) vmin=vmin,
fmin=fmin,
fmax=fmax,
n_freqs=n_freqs,
cycles_multiplier=cycles_multiplier,
method=method
)
else: else:
print(f"No method defined for index {idx}") print(f"No method defined for index {idx}")
+1 -2
View File
@@ -7,7 +7,7 @@ Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
# Built-in Imports # Built-in imports
import os.path as op import os.path as op
from pathlib import Path from pathlib import Path
from datetime import datetime from datetime import datetime
@@ -24,7 +24,6 @@ from src.shared.shareddata import APP_NAME
class ParticipantImageViewerWidget(FlaresBaseWidget): class ParticipantImageViewerWidget(FlaresBaseWidget):
def __init__( def __init__(
self, self,
haemo_dict: dict[str, BaseRaw], haemo_dict: dict[str, BaseRaw],
+33 -16
View File
@@ -14,7 +14,7 @@ import pandas as pd
from pandas import DataFrame from pandas import DataFrame
from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QGridLayout, QHBoxLayout, QLabel, QLineEdit, QListView, QMessageBox, QPushButton, QScrollArea, QSizePolicy, QVBoxLayout, QWidget, QFrame, QSpinBox, QFileDialog from PySide6.QtWidgets import QApplication, QComboBox, QDialog, QGridLayout, QHBoxLayout, QLabel, QLineEdit, QListView, QMessageBox, QPushButton, QScrollArea, QSizePolicy, QVBoxLayout, QWidget, QFrame, QSpinBox, QFileDialog
from PySide6.QtGui import QStandardItemModel, QStandardItem, QPixmap, QIntValidator, QDoubleValidator from PySide6.QtGui import QPalette, QStandardItemModel, QStandardItem, QPixmap, QIntValidator, QDoubleValidator
from PySide6.QtCore import QEvent, QPoint, QSize, QTimer, Qt, Signal from PySide6.QtCore import QEvent, QPoint, QSize, QTimer, Qt, Signal
from src.shared.shareddata import APP_NAME, PIPELINE_STAGES from src.shared.shareddata import APP_NAME, PIPELINE_STAGES
@@ -323,10 +323,10 @@ class ParamSection(QWidget):
self._updating_checkstates = False self._updating_checkstates = False
# Title label # Title label
title_label = QLabel(section_data["title"]) self.title_label = QLabel(section_data["title"])
title_label.setStyleSheet("font-weight: bold; font-size: 14px; margin-top: 10px; margin-bottom: 5px;") self.title_label.setStyleSheet("font-weight: bold; font-size: 14px; margin-top: 10px; margin-bottom: 5px;")
layout.addWidget(title_label) layout.addWidget(self.title_label)
self.header_widgets.append(title_label) self.header_widgets.append(self.title_label)
# Horizontal line # Horizontal line
line = QFrame() line = QFrame()
@@ -444,6 +444,10 @@ class ParamSection(QWidget):
self.update_dependencies() self.update_dependencies()
def update_theme_colors(self):
self.title_label.style().unpolish(self.title_label)
self.title_label.style().polish(self.title_label)
def is_different(self, val_a, val_b, param_type=None): def is_different(self, val_a, val_b, param_type=None):
"""Compares two parameter values to determine if they differ.""" """Compares two parameter values to determine if they differ."""
type_str = str(param_type).lower() type_str = str(param_type).lower()
@@ -890,6 +894,7 @@ class ProgressBubble(QWidget):
border-radius: 10px; border-radius: 10px;
padding: 8px 12px; padding: 8px 12px;
background-color: #e0f0ff; background-color: #e0f0ff;
color: #000000;
} }
""") """)
@@ -985,6 +990,13 @@ class ProgressBubble(QWidget):
self.spinner_idx += 1 self.spinner_idx += 1
self._update_label_text() self._update_label_text()
def reset(self):
"""Resets the bubble's visual state, progress bars, timers, and labels back to initial state."""
# Reset progress metrics and visual rectangles back to white
self.current_step = 0
for rect in self.rects:
rect.setStyleSheet("background-color: white; border: 1px solid gray;")
class FlaresBaseWidget(QWidget): class FlaresBaseWidget(QWidget):
def __init__(self, caller): def __init__(self, caller):
@@ -1346,11 +1358,11 @@ class FlaresBaseWidget(QWidget):
self.update_participant_dropdown_label(combo=target_combo) self.update_participant_dropdown_label(combo=target_combo)
class CrossGroupUIMixin: class InterGroupUIMixin:
participant_map: dict[str, str] participant_map: dict[str, str]
def setup_cross_group_ui( def setup_inter_group_ui(
self, self,
index_texts: Sequence[str], index_texts: Sequence[str],
placeholder_text: str = "" placeholder_text: str = ""
@@ -1678,9 +1690,9 @@ class CSVUIMixin:
class InterGroupUIMixin: class IntraGroupUIMixin:
def setup_inter_group_ui( def setup_intra_group_ui(
self, self,
index_texts: Sequence[str], index_texts: Sequence[str],
placeholder_text: str = "" placeholder_text: str = ""
@@ -1877,7 +1889,8 @@ class InterGroupUIMixin:
class ParticipantUIMixin: class ParticipantUIMixin:
def setup_participant_ui( def setup_participant_ui(
self, self,
index_texts: Sequence[str] index_texts: Sequence[str],
placeholder_text: str = ""
) -> None: ) -> None:
# Create mappings: file_path -> participant label and dropdown display text # Create mappings: file_path -> participant label and dropdown display text
@@ -1890,9 +1903,9 @@ class ParticipantUIMixin:
self.participant_map[file_path] = short_label self.participant_map[file_path] = short_label
self.participant_dropdown_items.append(display_label) self.participant_dropdown_items.append(display_label)
self.layout = QVBoxLayout(self) self.main_layout = QVBoxLayout(self)
self.top_bar = QHBoxLayout() self.top_bar = QHBoxLayout()
self.layout.addLayout(self.top_bar) self.main_layout.addLayout(self.top_bar)
self.participant_dropdown = self._create_multiselect_dropdown(self.participant_dropdown_items) self.participant_dropdown = self._create_multiselect_dropdown(self.participant_dropdown_items)
self.participant_dropdown.currentIndexChanged.connect(self.update_participant_dropdown_label) self.participant_dropdown.currentIndexChanged.connect(self.update_participant_dropdown_label)
@@ -1917,12 +1930,16 @@ class ParticipantUIMixin:
self.top_bar.addWidget(self.image_index_dropdown) self.top_bar.addWidget(self.image_index_dropdown)
self.top_bar.addWidget(self.submit_button) self.top_bar.addWidget(self.submit_button)
self.scroll = QScrollArea() self.scroll_area = QScrollArea()
self.scroll.setWidgetResizable(True) self.scroll_area.setWidgetResizable(True)
self.scroll_content = QWidget() self.scroll_content = QWidget()
self.grid_layout = QGridLayout(self.scroll_content) self.grid_layout = QGridLayout(self.scroll_content)
self.scroll.setWidget(self.scroll_content) self.scroll_area.setWidget(self.scroll_content)
self.layout.addWidget(self.scroll) self.placeholder_label = QLabel(placeholder_text)
self.grid_layout.addWidget(self.placeholder_label, 0, 0)
self.placeholder_label.setWordWrap(True)
self.placeholder_label.setScaledContents(True)
self.main_layout.addWidget(self.scroll_area)
self.thumb_size = QSize(280, 180) self.thumb_size = QSize(280, 180)
self.showMaximized() self.showMaximized()
+4 -2
View File
@@ -13,7 +13,7 @@ import sys
import platform import platform
CURRENT_VERSION = "1.6.0" CURRENT_VERSION = "1.6.1"
APP_NAME = "flares" APP_NAME = "flares"
APP_NAME_EXPANDED = "fNIRS Lightweight Analysis, Research, & Evaluation Suite" APP_NAME_EXPANDED = "fNIRS Lightweight Analysis, Research, & Evaluation Suite"
API_URL = f"https://git.research.dezeeuw.ca/api/v1/repos/tyler/{APP_NAME}/releases" API_URL = f"https://git.research.dezeeuw.ca/api/v1/repos/tyler/{APP_NAME}/releases"
@@ -64,7 +64,9 @@ DATA_SCHEMA = [
{"key": "config_dict", "help": "Dict[file_path, dict]: Processing configuration parameters"}, {"key": "config_dict", "help": "Dict[file_path, dict]: Processing configuration parameters"},
{"key": "fig_bytes_dict", "help": "Dict[file_path, dict]: Serialized figure data"}, {"key": "fig_bytes_dict", "help": "Dict[file_path, dict]: Serialized figure data"},
{"key": "contrast_results_dict", "help": "Dict[file_path, dict]: Calculated contrast statistical results"}, {"key": "contrast_results_dict", "help": "Dict[file_path, dict]: Calculated contrast statistical results"},
{"key": "roi_channel_map_dict", "help": "Dict[file_path, dict]: Calculated contrast statistical results"}, {"key": "roi_channel_map_dict", "help": "Dict[file_path, dict]: ROI channel mappings"},
{"key": "fir_feature_dict", "help": "Dict[file_path, dict]: Extracted FIR waveform features (features, names, channels)"},
{"key": "qc_dict", "help": "Dict[file_path, dict]: Quality control metrics"},
{"key": "valid_dict", "help": "Dict[file_path, bool]: Boolean validity status per file"} {"key": "valid_dict", "help": "Dict[file_path, bool]: Boolean validity status per file"}
] ]
+52 -4
View File
@@ -8,11 +8,13 @@ License: GPL-3.0
""" """
# Built-in imports # Built-in imports
import sys
from pathlib import Path
from typing import Any, Callable from typing import Any, Callable
# External library imports # External library imports
from PySide6.QtWidgets import QWidget, QVBoxLayout, QTextEdit, QLineEdit from PySide6.QtWidgets import QWidget, QVBoxLayout, QTextEdit, QLineEdit, QMainWindow
from PySide6.QtCore import Qt, QThread, Signal from PySide6.QtCore import QProcess, Qt, QThread, Signal
from file_ext_registration import register_file_association, is_windows_admin from file_ext_registration import register_file_association, is_windows_admin
from src.shared.shareddata import API_URL, API_URL_SECONDARY, APP_NAME, CURRENT_VERSION, PLATFORM_NAME from src.shared.shareddata import API_URL, API_URL_SECONDARY, APP_NAME, CURRENT_VERSION, PLATFORM_NAME
@@ -55,6 +57,8 @@ class TerminalWindow(QWidget):
layout.addWidget(self.input_line) layout.addWidget(self.input_line)
self.setLayout(layout) self.setLayout(layout)
self._process: QProcess | None = None
self.commands: dict[str, Callable[..., Any]] = { self.commands: dict[str, Callable[..., Any]] = {
"hello": self.cmd_hello, "hello": self.cmd_hello,
"help": self.cmd_help, "help": self.cmd_help,
@@ -62,6 +66,7 @@ class TerminalWindow(QWidget):
"about": self.cmd_about, "about": self.cmd_about,
"assoc": self.cmd_assoc, "assoc": self.cmd_assoc,
"update": self.cmd_update, "update": self.cmd_update,
"utest": self.cmd_utest,
} }
self._pending_assoc_confirmation: bool = False self._pending_assoc_confirmation: bool = False
@@ -107,7 +112,8 @@ class TerminalWindow(QWidget):
return "Hello from the terminal!" return "Hello from the terminal!"
def cmd_help(self, *args: Any) -> str: def cmd_help(self, *args: Any) -> str:
return f"Available commands: {', '.join(self.commands.keys())}" available_cmds = [cmd for cmd in self.commands.keys() if cmd != "utest"]
return f"Available commands: {', '.join(available_cmds)}"
def cmd_version(self, *args: Any) -> str: def cmd_version(self, *args: Any) -> str:
return f"{APP_NAME.upper()} is running version {CURRENT_VERSION}." return f"{APP_NAME.upper()} is running version {CURRENT_VERSION}."
@@ -118,7 +124,7 @@ class TerminalWindow(QWidget):
def cmd_update(self, *args: Any) -> str: def cmd_update(self, *args: Any) -> str:
main_win = self.parent() main_win = self.parent()
if not isinstance(main_win, QWidget): if not isinstance(main_win, QMainWindow):
return "[Error] Main window context not found." return "[Error] Main window context not found."
self.updater = UpdateManager( self.updater = UpdateManager(
@@ -164,3 +170,45 @@ class TerminalWindow(QWidget):
def _on_assoc_result(self, ok: bool, msg: str) -> None: def _on_assoc_result(self, ok: bool, msg: str) -> None:
self.output_area.append(msg) self.output_area.append(msg)
self._assoc_worker = None self._assoc_worker = None
def cmd_utest(self, *args: Any) -> str | None:
"""Executes a specific pre-defined python script non-blockingly."""
if self._process and self._process.state() != QProcess.ProcessState.NotRunning:
return "[Error] A process is already running."
target_script = Path("main_unit_tests.py")
if not target_script.exists():
return f"[Error] Target script not found at: {target_script}"
self._process = QProcess(self)
# Stream stdout and stderr live to output_area
self._process.readyReadStandardOutput.connect(self._handle_stdout)
self._process.readyReadStandardError.connect(self._handle_stderr)
self._process.finished.connect(self._handle_process_finished)
# Use current Python interpreter executable. Works when packaged?
python_executable = sys.executable
self.output_area.append(f"Starting {target_script.name}...")
self._process.start(python_executable, [str(target_script)])
return None
def _handle_stdout(self) -> None:
if self._process:
raw_bytes = bytes(self._process.readAllStandardOutput().data())
data = raw_bytes.decode("utf-8")
if data.strip():
self.output_area.append(data.strip())
def _handle_stderr(self) -> None:
if self._process:
raw_bytes = bytes(self._process.readAllStandardError().data())
data = raw_bytes.decode("utf-8")
if data.strip():
self.output_area.append(f"[Error] {data.strip()}")
def _handle_process_finished(self, exit_code: int, exit_status: QProcess.ExitStatus) -> None:
self.output_area.append(f"Process finished with code {exit_code}.")
self._process = None
+88 -90
View File
@@ -6,19 +6,19 @@ Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
# Built-in imports
import os import os
import json import json
from enum import Enum, auto from enum import Enum, auto
from datetime import datetime from typing import Any, List, Optional, cast
import numpy as np
# External library imports
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QComboBox, QHBoxLayout, QMessageBox, QFileDialog from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QComboBox, QHBoxLayout, QMessageBox, QFileDialog
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
from mne import Annotations from mne import Annotations
from mne.io import read_raw_snirf from mne.io import read_raw_snirf #type: ignore
from mne_nirs.io import write_raw_snirf from mne_nirs.io import write_raw_snirf #type: ignore
from src.shared.shareddata import APP_NAME from src.shared.shareddata import APP_NAME
@@ -29,7 +29,7 @@ class EventUpdateMode(Enum):
class UpdateEventsWindow(QWidget): class UpdateEventsWindow(QWidget):
def __init__(self, parent=None, mode=EventUpdateMode.WRITE_SNIRF, caller=None): def __init__(self, parent: Optional[QWidget]=None, mode=EventUpdateMode.WRITE_SNIRF, caller=None):
super().__init__(parent, Qt.WindowType.Window) super().__init__(parent, Qt.WindowType.Window)
self.mode = mode self.mode = mode
@@ -91,7 +91,7 @@ class UpdateEventsWindow(QWidget):
help_btn_a = QPushButton("?") help_btn_a = QPushButton("?")
help_btn_a.setFixedWidth(25) help_btn_a.setFixedWidth(25)
help_btn_a.setToolTip(help_text_a) help_btn_a.setToolTip(help_text_a)
help_btn_a.clicked.connect(lambda _, text=help_text_a: self.show_help_popup(text)) help_btn_a.clicked.connect(lambda: self.show_help_popup(help_text_a))
file_a_layout.addWidget(help_btn_a) file_a_layout.addWidget(help_btn_a)
# Container for label + line_edit + browse button with tooltip # Container for label + line_edit + browse button with tooltip
@@ -114,7 +114,7 @@ class UpdateEventsWindow(QWidget):
help_btn_b = QPushButton("?") help_btn_b = QPushButton("?")
help_btn_b.setFixedWidth(25) help_btn_b.setFixedWidth(25)
help_btn_b.setToolTip(help_text_b) help_btn_b.setToolTip(help_text_b)
help_btn_b.clicked.connect(lambda _, text=help_text_b: self.show_help_popup(text)) help_btn_b.clicked.connect(lambda: self.show_help_popup(help_text_b))
file_b_layout.addWidget(help_btn_b) file_b_layout.addWidget(help_btn_b)
file_b_container = QWidget() file_b_container = QWidget()
@@ -136,7 +136,7 @@ class UpdateEventsWindow(QWidget):
help_btn_suffix = QPushButton("?") help_btn_suffix = QPushButton("?")
help_btn_suffix.setFixedWidth(25) help_btn_suffix.setFixedWidth(25)
help_btn_suffix.setToolTip(help_text_suffix) help_btn_suffix.setToolTip(help_text_suffix)
help_btn_suffix.clicked.connect(lambda _, text=help_text_suffix: self.show_help_popup(text)) help_btn_suffix.clicked.connect(lambda: self.show_help_popup(help_text_suffix))
suffix_layout.addWidget(help_btn_suffix) suffix_layout.addWidget(help_btn_suffix)
suffix_container = QWidget() suffix_container = QWidget()
@@ -157,7 +157,7 @@ class UpdateEventsWindow(QWidget):
help_btn_suffix = QPushButton("?") help_btn_suffix = QPushButton("?")
help_btn_suffix.setFixedWidth(25) help_btn_suffix.setFixedWidth(25)
help_btn_suffix.setToolTip(help_text_suffix) help_btn_suffix.setToolTip(help_text_suffix)
help_btn_suffix.clicked.connect(lambda _, text=help_text_suffix: self.show_help_popup(text)) help_btn_suffix.clicked.connect(lambda: self.show_help_popup(help_text_suffix))
suffix2_layout.addWidget(help_btn_suffix) suffix2_layout.addWidget(help_btn_suffix)
suffix2_container = QWidget() suffix2_container = QWidget()
@@ -177,7 +177,7 @@ class UpdateEventsWindow(QWidget):
help_btn_snirf_events = QPushButton("?") help_btn_snirf_events = QPushButton("?")
help_btn_snirf_events.setFixedWidth(25) help_btn_snirf_events.setFixedWidth(25)
help_btn_snirf_events.setToolTip(help_text_snirf_events) help_btn_snirf_events.setToolTip(help_text_snirf_events)
help_btn_snirf_events.clicked.connect(lambda _, text=help_text_snirf_events: self.show_help_popup(text)) help_btn_snirf_events.clicked.connect(lambda: self.show_help_popup(help_text_snirf_events))
snirf_events_layout.addWidget(help_btn_snirf_events) snirf_events_layout.addWidget(help_btn_snirf_events)
snirf_events_container = QWidget() snirf_events_container = QWidget()
@@ -199,13 +199,13 @@ class UpdateEventsWindow(QWidget):
self.setLayout(layout) self.setLayout(layout)
def show_help_popup(self, text): def show_help_popup(self, text: str) -> None:
msg = QMessageBox(self) msg = QMessageBox(self)
msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}") msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}")
msg.setText(text) msg.setText(text)
msg.exec() msg.exec()
def browse_file_a(self): def browse_file_a(self) -> None:
file_path, _ = QFileDialog.getOpenFileName(self, "Select SNIRF File", "", "SNIRF Files (*.snirf)") file_path, _ = QFileDialog.getOpenFileName(self, "Select SNIRF File", "", "SNIRF Files (*.snirf)")
if file_path: if file_path:
self.line_edit_file_a.setText(file_path) self.line_edit_file_a.setText(file_path)
@@ -235,7 +235,7 @@ class UpdateEventsWindow(QWidget):
self.combo_snirf_events.clear() self.combo_snirf_events.clear()
self.combo_snirf_events.setEnabled(False) self.combo_snirf_events.setEnabled(False)
def browse_file_b(self): def browse_file_b(self) -> None:
file_path, _ = QFileDialog.getOpenFileName(self, "Select BORIS File", "", "BORIS project Files (*.boris)") file_path, _ = QFileDialog.getOpenFileName(self, "Select BORIS File", "", "BORIS project Files (*.boris)")
if file_path: if file_path:
self.line_edit_file_b.setText(file_path) self.line_edit_file_b.setText(file_path)
@@ -252,16 +252,14 @@ class UpdateEventsWindow(QWidget):
except (json.JSONDecodeError, FileNotFoundError, KeyError) as e: except (json.JSONDecodeError, FileNotFoundError, KeyError) as e:
QMessageBox.warning(self, "Error", f"Failed to parse BORIS file:\n{e}") QMessageBox.warning(self, "Error", f"Failed to parse BORIS file:\n{e}")
def extract_boris_observation_keys(self, data): def extract_boris_observation_keys(self, data: dict[str, Any]) -> List[str]:
if "observations" not in data: if "observations" not in data:
raise KeyError("Missing 'observations' key in BORIS file.") raise KeyError("Missing 'observations' key in BORIS file.")
observations = data["observations"] observations = cast(dict[str, Any], data["observations"])
if not isinstance(observations, dict):
raise TypeError("'observations' must be a dictionary.")
return list(observations.keys()) return list(observations.keys())
def on_observation_selected(self): def on_observation_selected(self):
selected_obs = self.combo_suffix.currentText() selected_obs = self.combo_suffix.currentText()
if not selected_obs or not hasattr(self, 'boris_data'): if not selected_obs or not hasattr(self, 'boris_data'):
@@ -288,11 +286,11 @@ class UpdateEventsWindow(QWidget):
self.combo_events.addItems(event_entries) self.combo_events.addItems(event_entries)
self.combo_events.setEnabled(bool(event_entries)) self.combo_events.setEnabled(bool(event_entries))
def clear_files(self): def clear_files(self) -> None:
self.line_edit_file_a.clear() self.line_edit_file_a.clear()
self.line_edit_file_b.clear() self.line_edit_file_b.clear()
def go_action(self): def go_action(self) -> None:
file_a = self.line_edit_file_a.text() file_a = self.line_edit_file_a.text()
suffix = "flare" suffix = "flare"
@@ -451,7 +449,7 @@ class UpdateEventsWindow(QWidget):
save_path += ".json" save_path += ".json"
# Build JSON dict # Build JSON dict
json_data = { json_data: dict[str, Any] = {
"observation": selected_obs, "observation": selected_obs,
"snirf_anchor": {"label": snirf_label, "time": snirf_anchor_time}, "snirf_anchor": {"label": snirf_label, "time": snirf_anchor_time},
"boris_anchor": {"label": boris_label, "time": boris_anchor_time}, "boris_anchor": {"label": boris_label, "time": boris_anchor_time},
@@ -468,79 +466,79 @@ class UpdateEventsWindow(QWidget):
QMessageBox.critical(self, "Error", f"Failed to write JSON:\n{e}") QMessageBox.critical(self, "Error", f"Failed to write JSON:\n{e}")
def update_optode_positions(self, file_a, file_b, save_path): # def update_optode_positions(self, file_a, file_b, save_path):
fiducials = {} # fiducials = {}
ch_positions = {} # ch_positions = {}
# Read the lines from the optode file # # Read the lines from the optode file
with open(file_b, 'r') as f: # with open(file_b, 'r') as f:
for line in f: # for line in f:
if line.strip(): # if line.strip():
# Split by the semicolon and convert to meters # # Split by the semicolon and convert to meters
ch_name, coords_str = line.split(":") # ch_name, coords_str = line.split(":")
coords = np.array(list(map(float, coords_str.strip().split()))) * 0.001 # coords = np.array(list(map(float, coords_str.strip().split()))) * 0.001
# The key we have is a fiducial # # The key we have is a fiducial
if ch_name.lower() in ['lpa', 'nz', 'rpa']: # if ch_name.lower() in ['lpa', 'nz', 'rpa']:
fiducials[ch_name.lower()] = coords # fiducials[ch_name.lower()] = coords
# The key we have is a source or detector # # The key we have is a source or detector
else: # else:
ch_positions[ch_name.upper()] = coords # ch_positions[ch_name.upper()] = coords
# Create montage with updated coords in head space # # Create montage with updated coords in head space
initial_montage = make_dig_montage(ch_pos=ch_positions, nasion=fiducials.get('nz'), lpa=fiducials.get('lpa'), rpa=fiducials.get('rpa'), coord_frame='head') # type: ignore # initial_montage = make_dig_montage(ch_pos=ch_positions, nasion=fiducials.get('nz'), lpa=fiducials.get('lpa'), rpa=fiducials.get('rpa'), coord_frame='head') # type: ignore
# Read the SNIRF file, set the montage, and write it back # # Read the SNIRF file, set the montage, and write it back
# TODO: Bad! read_raw_snirf doesnt release memory properly! Should be spawned in a seperate process and killed once completed # # TODO: Bad! read_raw_snirf doesnt release memory properly! Should be spawned in a seperate process and killed once completed
raw = read_raw_snirf(file_a, preload=True) # raw = read_raw_snirf(file_a, preload=True)
raw.set_montage(initial_montage) # raw.set_montage(initial_montage)
write_raw_snirf(raw, save_path) # write_raw_snirf(raw, save_path)
def _apply_events_to_snirf(self, raw, new_annotations, save_path): # def _apply_events_to_snirf(self, raw, new_annotations, save_path):
raw.set_annotations(new_annotations) # raw.set_annotations(new_annotations)
write_raw_snirf(raw, save_path) # write_raw_snirf(raw, save_path)
def _write_event_mapping_json( # def _write_event_mapping_json(
self, # self,
file_a, # file_a,
file_b, # file_b,
selected_obs, # selected_obs,
snirf_anchor, # snirf_anchor,
boris_anchor, # boris_anchor,
time_shift, # time_shift,
mapped_events, # mapped_events,
save_path # save_path
): # ):
payload = { # payload = {
"source": { # "source": {
"called_from": self.caller, # "called_from": self.caller,
"snirf_file": os.path.basename(file_a), # "snirf_file": os.path.basename(file_a),
"boris_file": os.path.basename(file_b), # "boris_file": os.path.basename(file_b),
"observation": selected_obs # "observation": selected_obs
}, # },
"alignment": { # "alignment": {
"snirf_anchor": snirf_anchor, # "snirf_anchor": snirf_anchor,
"boris_anchor": boris_anchor, # "boris_anchor": boris_anchor,
"time_shift_seconds": time_shift # "time_shift_seconds": time_shift
}, # },
"events": mapped_events, # "events": mapped_events,
"created_at": datetime.utcnow().isoformat() + "Z" # "created_at": datetime.utcnow().isoformat() + "Z"
} # }
with open(save_path, "w", encoding="utf-8") as f: # with open(save_path, "w", encoding="utf-8") as f:
json.dump(payload, f, indent=2) # json.dump(payload, f, indent=2)
return save_path # return save_path
class UpdateEventsBlazesWindow(QWidget): class UpdateEventsBlazesWindow(QWidget):
def __init__(self, parent=None, mode=EventUpdateMode.WRITE_SNIRF, caller=None): def __init__(self, parent: Optional[QWidget]=None, mode=EventUpdateMode.WRITE_SNIRF, caller=None):
super().__init__(parent, Qt.WindowType.Window) super().__init__(parent, Qt.WindowType.Window)
self.mode = mode self.mode = mode
@@ -595,7 +593,7 @@ class UpdateEventsBlazesWindow(QWidget):
help_btn_a = QPushButton("?") help_btn_a = QPushButton("?")
help_btn_a.setFixedWidth(25) help_btn_a.setFixedWidth(25)
help_btn_a.setToolTip(help_text_a) help_btn_a.setToolTip(help_text_a)
help_btn_a.clicked.connect(lambda _, text=help_text_a: self.show_help_popup(text)) help_btn_a.clicked.connect(lambda: self.show_help_popup(help_text_a))
file_a_layout.addWidget(help_btn_a) file_a_layout.addWidget(help_btn_a)
# Container for label + line_edit + browse button with tooltip # Container for label + line_edit + browse button with tooltip
@@ -618,7 +616,7 @@ class UpdateEventsBlazesWindow(QWidget):
help_btn_b = QPushButton("?") help_btn_b = QPushButton("?")
help_btn_b.setFixedWidth(25) help_btn_b.setFixedWidth(25)
help_btn_b.setToolTip(help_text_b) help_btn_b.setToolTip(help_text_b)
help_btn_b.clicked.connect(lambda _, text=help_text_b: self.show_help_popup(text)) help_btn_b.clicked.connect(lambda: self.show_help_popup(help_text_b))
file_b_layout.addWidget(help_btn_b) file_b_layout.addWidget(help_btn_b)
file_b_container = QWidget() file_b_container = QWidget()
@@ -640,7 +638,7 @@ class UpdateEventsBlazesWindow(QWidget):
help_btn_suffix = QPushButton("?") help_btn_suffix = QPushButton("?")
help_btn_suffix.setFixedWidth(25) help_btn_suffix.setFixedWidth(25)
help_btn_suffix.setToolTip(help_text_suffix) help_btn_suffix.setToolTip(help_text_suffix)
help_btn_suffix.clicked.connect(lambda _, text=help_text_suffix: self.show_help_popup(text)) help_btn_suffix.clicked.connect(lambda: self.show_help_popup(help_text_suffix))
suffix2_layout.addWidget(help_btn_suffix) suffix2_layout.addWidget(help_btn_suffix)
suffix2_container = QWidget() suffix2_container = QWidget()
@@ -660,7 +658,7 @@ class UpdateEventsBlazesWindow(QWidget):
help_btn_snirf_events = QPushButton("?") help_btn_snirf_events = QPushButton("?")
help_btn_snirf_events.setFixedWidth(25) help_btn_snirf_events.setFixedWidth(25)
help_btn_snirf_events.setToolTip(help_text_snirf_events) help_btn_snirf_events.setToolTip(help_text_snirf_events)
help_btn_snirf_events.clicked.connect(lambda _, text=help_text_snirf_events: self.show_help_popup(text)) help_btn_snirf_events.clicked.connect(lambda: self.show_help_popup(help_text_snirf_events))
snirf_events_layout.addWidget(help_btn_snirf_events) snirf_events_layout.addWidget(help_btn_snirf_events)
snirf_events_container = QWidget() snirf_events_container = QWidget()
@@ -683,13 +681,13 @@ class UpdateEventsBlazesWindow(QWidget):
self.setLayout(layout) self.setLayout(layout)
def show_help_popup(self, text): def show_help_popup(self, text: str) -> None:
msg = QMessageBox(self) msg = QMessageBox(self)
msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}") msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}")
msg.setText(text) msg.setText(text)
msg.exec() msg.exec()
def browse_file_a(self): def browse_file_a(self) -> None:
file_path, _ = QFileDialog.getOpenFileName(self, "Select SNIRF File", "", "SNIRF Files (*.snirf)") file_path, _ = QFileDialog.getOpenFileName(self, "Select SNIRF File", "", "SNIRF Files (*.snirf)")
if file_path: if file_path:
self.line_edit_file_a.setText(file_path) self.line_edit_file_a.setText(file_path)
@@ -719,7 +717,7 @@ class UpdateEventsBlazesWindow(QWidget):
self.combo_snirf_events.clear() self.combo_snirf_events.clear()
self.combo_snirf_events.setEnabled(False) self.combo_snirf_events.setEnabled(False)
def browse_file_b(self): def browse_file_b(self) -> None:
file_path, _ = QFileDialog.getOpenFileName(self, "Select JSON Timeline File", "", "JSON Files (*.json)") file_path, _ = QFileDialog.getOpenFileName(self, "Select JSON Timeline File", "", "JSON Files (*.json)")
if file_path: if file_path:
self.line_edit_file_b.setText(file_path) self.line_edit_file_b.setText(file_path)
@@ -744,11 +742,11 @@ class UpdateEventsBlazesWindow(QWidget):
self.combo_events.setEnabled(False) self.combo_events.setEnabled(False)
def extract_json_observation_strings(self, data): def extract_json_observation_strings(self, data: dict[str, Any]) -> List[str]:
if "events" not in data: if "events" not in data:
raise KeyError("Missing 'events' key in JSON file.") raise KeyError("Missing 'events' key in JSON file.")
event_strings = [] event_strings: List[str] = []
# The new format is a flat list chronologically ordered # The new format is a flat list chronologically ordered
for event in data["events"]: for event in data["events"]:
@@ -762,14 +760,14 @@ class UpdateEventsBlazesWindow(QWidget):
return event_strings return event_strings
def clear_files(self): def clear_files(self) -> None:
self.line_edit_file_a.clear() self.line_edit_file_a.clear()
self.line_edit_file_b.clear() self.line_edit_file_b.clear()
def go_action(self): def go_action(self) -> None:
file_a = self.line_edit_file_a.text() file_a = self.line_edit_file_a.text()
file_b = self.line_edit_file_b.text() _ = self.line_edit_file_b.text()
suffix = APP_NAME suffix = APP_NAME
if not hasattr(self, "json_data") or self.combo_events.count() == 0 or self.combo_snirf_events.count() == 0: if not hasattr(self, "json_data") or self.combo_events.count() == 0 or self.combo_snirf_events.count() == 0:
+104 -43
View File
@@ -1,16 +1,21 @@
""" """
Filename: updateoptodes.py Filename: updateoptodes.py
Description: Methods to update optode locations for FLARES Description: Methods to update optode locations for FLARES
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
# Built-in imports
import os import os
from pathlib import Path from pathlib import Path
from typing import Dict, Optional, Union
# External library imports
import pandas as pd import pandas as pd
import numpy as np import numpy as np
import numpy.typing as npt
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QHBoxLayout, QMessageBox, QLineEdit, QPushButton, QFileDialog from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QHBoxLayout, QMessageBox, QLineEdit, QPushButton, QFileDialog
from PySide6.QtCore import Qt from PySide6.QtCore import Qt
@@ -24,12 +29,14 @@ from src.shared.shareddata import APP_NAME
class UpdateOptodesWindow(QWidget): class UpdateOptodesWindow(QWidget):
def __init__(self, parent=None): def __init__(self, parent: Optional[QWidget] = None) -> None:
super().__init__(parent, Qt.WindowType.Window) super().__init__(parent, Qt.WindowType.Window)
self.setWindowTitle(f"Update optode positions - {APP_NAME.upper()}") self.setWindowTitle(f"Update optode positions - {APP_NAME.upper()}")
self.resize(760, 200) self.resize(760, 200)
self.label_file_a = QLabel("SNIRF file:") self.selected_snirf_files: list[str] = []
self.label_file_a = QLabel("SNIRF files:")
self.line_edit_file_a = QLineEdit() self.line_edit_file_a = QLineEdit()
self.line_edit_file_a.setReadOnly(True) self.line_edit_file_a.setReadOnly(True)
self.btn_browse_a = QPushButton("Browse .snirf") self.btn_browse_a = QPushButton("Browse .snirf")
@@ -50,7 +57,6 @@ class UpdateOptodesWindow(QWidget):
self.btn_clear.clicked.connect(self.clear_files) self.btn_clear.clicked.connect(self.clear_files)
self.btn_go.clicked.connect(self.go_action) self.btn_go.clicked.connect(self.go_action)
# ---
layout = QVBoxLayout() layout = QVBoxLayout()
self.description = QLabel() self.description = QLabel()
self.description.setTextFormat(Qt.TextFormat.RichText) self.description.setTextFormat(Qt.TextFormat.RichText)
@@ -75,7 +81,7 @@ class UpdateOptodesWindow(QWidget):
help_btn_a = QPushButton("?") help_btn_a = QPushButton("?")
help_btn_a.setFixedWidth(25) help_btn_a.setFixedWidth(25)
help_btn_a.setToolTip(help_text_a) help_btn_a.setToolTip(help_text_a)
help_btn_a.clicked.connect(lambda _, text=help_text_a: self.show_help_popup(text)) help_btn_a.clicked.connect(lambda: self.show_help_popup(help_text_a))
file_a_layout.addWidget(help_btn_a) file_a_layout.addWidget(help_btn_a)
# Container for label + line_edit + browse button with tooltip # Container for label + line_edit + browse button with tooltip
@@ -98,7 +104,7 @@ class UpdateOptodesWindow(QWidget):
help_btn_b = QPushButton("?") help_btn_b = QPushButton("?")
help_btn_b.setFixedWidth(25) help_btn_b.setFixedWidth(25)
help_btn_b.setToolTip(help_text_b) help_btn_b.setToolTip(help_text_b)
help_btn_b.clicked.connect(lambda _, text=help_text_b: self.show_help_popup(text)) help_btn_b.clicked.connect(lambda: self.show_help_popup(help_text_b))
file_b_layout.addWidget(help_btn_b) file_b_layout.addWidget(help_btn_b)
file_b_container = QWidget() file_b_container = QWidget()
@@ -121,7 +127,7 @@ class UpdateOptodesWindow(QWidget):
help_btn_suffix = QPushButton("?") help_btn_suffix = QPushButton("?")
help_btn_suffix.setFixedWidth(25) help_btn_suffix.setFixedWidth(25)
help_btn_suffix.setToolTip(help_text_suffix) help_btn_suffix.setToolTip(help_text_suffix)
help_btn_suffix.clicked.connect(lambda _, text=help_text_suffix: self.show_help_popup(text)) help_btn_suffix.clicked.connect(lambda: self.show_help_popup(help_text_suffix))
suffix_layout.addWidget(help_btn_suffix) suffix_layout.addWidget(help_btn_suffix)
suffix_container = QWidget() suffix_container = QWidget()
@@ -143,13 +149,13 @@ class UpdateOptodesWindow(QWidget):
self.setLayout(layout) self.setLayout(layout)
def show_help_popup(self, text): def show_help_popup(self, text: str) -> None:
msg = QMessageBox(self) msg = QMessageBox(self)
msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}") msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}")
msg.setText(text) msg.setText(text)
msg.exec() msg.exec()
def handle_link_click(self, link): def handle_link_click(self, link: str) -> None:
if link == "custom_link": if link == "custom_link":
msg = QMessageBox(self) msg = QMessageBox(self)
msg.setWindowTitle("Example Digitization File") msg.setWindowTitle("Example Digitization File")
@@ -166,61 +172,110 @@ class UpdateOptodesWindow(QWidget):
msg.setText(text) msg.setText(text)
msg.exec() msg.exec()
def browse_file_a(self): def browse_file_a(self) -> None:
file_path, _ = QFileDialog.getOpenFileName(self, "Select SNIRF File", "", "SNIRF Files (*.snirf)") file_paths, _ = QFileDialog.getOpenFileNames(
if file_path: self,
self.line_edit_file_a.setText(file_path) "Select SNIRF Files",
"",
"SNIRF Files (*.snirf)"
)
def browse_file_b(self): if file_paths:
self.selected_snirf_files = file_paths
self.line_edit_file_a.setText("; ".join(Path(p).name for p in file_paths))
def browse_file_b(self) -> None:
file_path, _ = QFileDialog.getOpenFileName(self, "Select File", "", "Supported Files (*.txt *.xlsx)") file_path, _ = QFileDialog.getOpenFileName(self, "Select File", "", "Supported Files (*.txt *.xlsx)")
if file_path: if file_path:
self.line_edit_file_b.setText(file_path) self.line_edit_file_b.setText(file_path)
def clear_files(self): def clear_files(self) -> None:
self.selected_snirf_files.clear()
self.line_edit_file_a.clear() self.line_edit_file_a.clear()
self.line_edit_file_b.clear() self.line_edit_file_b.clear()
def go_action(self): def go_action(self) -> None:
file_a = self.line_edit_file_a.text() file_a = self.line_edit_file_a.text()
file_b = self.line_edit_file_b.text() file_b = self.line_edit_file_b.text()
suffix = self.line_edit_suffix.text().strip() or "flare" suffix = self.line_edit_suffix.text().strip() or "flare"
if not file_a: if not self.selected_snirf_files:
QMessageBox.critical(self, "Missing File", "Please select a SNIRF file.") QMessageBox.critical(self, "Missing File", "Please select at least one SNIRF file.")
return return
if not file_b: if not file_b:
QMessageBox.critical(self, "Missing File", "Please select a TXT file.") QMessageBox.critical(self, "Missing File", "Please select a TXT or XLSX digitization file.")
return return
# Get original filename without extension output_dir = QFileDialog.getExistingDirectory(
base_name = os.path.splitext(os.path.basename(file_a))[0]
suggested_name = f"{base_name}_{suffix}.snirf"
# Open save dialog with default name
save_path, _ = QFileDialog.getSaveFileName(
self, self,
"Save SNIRF File As", "Select Output Directory"
suggested_name,
"SNIRF Files (*.snirf)"
) )
if not save_path: if not output_dir:
print("Save cancelled.") print("Save cancelled.")
return return
# Ensure .snirf extension output_path = Path(output_dir)
if not save_path.lower().endswith(".snirf"):
save_path += ".snirf" successful_files: list[str] = []
failed_files: list[str] = []
for file_a in self.selected_snirf_files:
input_path = Path(file_a)
# Keep original filename and independently add suffix
save_path = output_path / f"{input_path.stem}_{suffix}.snirf"
try: try:
self.update_optode_positions(file_a=file_a, file_b=file_b, save_path=save_path) self.update_optode_positions(
file_a=file_a,
file_b=file_b,
save_path=save_path
)
successful_files.append(save_path.name)
except Exception as e: except Exception as e:
QMessageBox.critical(self, "Error", f"Failed to write file:\n{e}") failed_files.append(
return f"{input_path.name}: {e}"
)
QMessageBox.information(self, "File Saved", f"File was saved to:\n{save_path}") # Build summary
message_parts: list[str] = []
def update_optode_positions(self, file_a, file_b, save_path): if successful_files:
message_parts.append(
f"Successfully processed {len(successful_files)} "
f"SNIRF file(s):\n\n"
+ "\n".join(successful_files)
)
if failed_files:
message_parts.append(
f"Failed to process {len(failed_files)} "
f"SNIRF file(s):\n\n"
+ "\n".join(failed_files)
)
if failed_files:
QMessageBox.warning(
self,
"Processing Complete",
"\n\n".join(message_parts)
)
else:
QMessageBox.information(
self,
"Files Saved",
"\n\n".join(message_parts)
)
def update_optode_positions(
self,
file_a: Union[str, Path],
file_b: Union[str, Path],
save_path: Union[str, Path]
) -> None:
fiducials = {} fiducials = {}
ch_positions = {} ch_positions = {}
@@ -247,16 +302,22 @@ class UpdateOptodesWindow(QWidget):
elif extension == '.xlsx': elif extension == '.xlsx':
# TODO: Bad! Why assume sheet1 has the contents? # TODO: Bad! Why assume sheet1 has the contents?
df = pd.read_excel(file_b, sheet_name='Sheet1') df = pd.read_excel(file_b, sheet_name='Sheet1') # type: ignore
def _get_block_data(
target_df: pd.DataFrame,
block_id: int,
row_mapping: Union[Dict[int, str], str],
scale: float = 0.001
) -> Dict[str, npt.NDArray[np.float64]]:
def _get_block_data(df, block_id, row_mapping, scale=0.001):
"""Isolates a block, cleans numeric data, and returns a scaled dictionary.""" """Isolates a block, cleans numeric data, and returns a scaled dictionary."""
# 1. Isolate and clean # 1. Isolate and clean
block = df[df['block_id'] == block_id].iloc[:, [1, 2, 3]].copy() block = target_df[target_df['block_id'] == block_id].iloc[:, [1, 2, 3]].copy()
block = block.apply(pd.to_numeric, errors='coerce') block = block.apply(pd.to_numeric, errors='coerce')
# 2. Extract into dictionary based on mapping # 2. Extract into dictionary based on mapping
result = {} result: Dict[str, npt.NDArray[np.float64]] = {}
# If row_mapping is a dict (like {0: 'nz'}), use it directly # If row_mapping is a dict (like {0: 'nz'}), use it directly
if isinstance(row_mapping, dict): if isinstance(row_mapping, dict):
@@ -265,7 +326,7 @@ class UpdateOptodesWindow(QWidget):
result[key] = block.iloc[row_idx].to_numpy(dtype=float) * scale result[key] = block.iloc[row_idx].to_numpy(dtype=float) * scale
# If row_mapping is a string prefix (like 'D' or 'S'), auto-generate keys # If row_mapping is a string prefix (like 'D' or 'S'), auto-generate keys
elif isinstance(row_mapping, str): else:
for i in range(len(block)): for i in range(len(block)):
result[f"{row_mapping}{i+1}"] = block.iloc[i].to_numpy(dtype=float) * scale result[f"{row_mapping}{i+1}"] = block.iloc[i].to_numpy(dtype=float) * scale
@@ -291,6 +352,6 @@ class UpdateOptodesWindow(QWidget):
initial_montage = make_dig_montage(ch_pos=ch_positions, nasion=fiducials.get('nz'), lpa=fiducials.get('lpa'), rpa=fiducials.get('rpa'), coord_frame='head') # type: ignore initial_montage = make_dig_montage(ch_pos=ch_positions, nasion=fiducials.get('nz'), lpa=fiducials.get('lpa'), rpa=fiducials.get('rpa'), coord_frame='head') # type: ignore
# Read the SNIRF file, set the montage, and write it back # Read the SNIRF file, set the montage, and write it back
raw = read_raw_snirf(file_a, preload=True) raw = read_raw_snirf(str(file_a), preload=True)
raw.set_montage(initial_montage) raw.set_montage(initial_montage) # type: ignore
write_raw_snirf(raw, save_path) write_raw_snirf(raw, save_path)
+61 -15
View File
@@ -1,21 +1,30 @@
""" """
Filename: viewerlauncher.py Filename: viewerlauncher.py
Description: Viewer launcher window Description: Viewer launcher window
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
# Built-in imports
from typing import Any, Callable, Type
# External library imports # External library imports
from pandas import DataFrame
from PySide6.QtWidgets import QPushButton, QWidget, QVBoxLayout from PySide6.QtWidgets import QPushButton, QWidget, QVBoxLayout
from PySide6.QtCore import QTimer from PySide6.QtCore import QTimer
from mne import Epochs
from mne.io.base import BaseRaw
from src.analysis.exporttocsv import ExportToCSVWidget from src.analysis.exporttocsv import ExportToCSVWidget
from src.analysis.intragroupbrainimage import IntraGroupBrainImageWidget
from src.analysis.intergroupbrainimage import InterGroupBrainImageWidget from src.analysis.intergroupbrainimage import InterGroupBrainImageWidget
from src.analysis.crossgroupbrainimage import CrossGroupBrainImageWidget from src.analysis.intragroupfunctionalconnectivity import IntraGroupFunctionalConnectivityWidget
from src.analysis.intergroupfunctionalconnectivity import InterGroupFunctionalConnectivityWidget from src.analysis.intragroupstats import IntraGroupStatsWidget
from src.analysis.intergroupstats import InterGroupStatsWidget from src.analysis.intergroupstats import InterGroupStatsWidget
from src.analysis.crossgroupstats import CrossGroupStatsWidget
from src.analysis.participantimage import ParticipantImageViewerWidget from src.analysis.participantimage import ParticipantImageViewerWidget
from src.analysis.participantbrain import ParticipantBrainViewerWidget from src.analysis.participantbrain import ParticipantBrainViewerWidget
from src.analysis.participantfoldchannels import ParticipantFoldChannelsWidget from src.analysis.participantfoldchannels import ParticipantFoldChannelsWidget
@@ -24,44 +33,81 @@ from src.shared.shareddata import APP_NAME
class ViewerLauncherWidget(QWidget): class ViewerLauncherWidget(QWidget):
def __init__(self, haemo_dict, epochs_dict, cha_dict, df_ind_dict, design_matrix_dict, config_dict, fig_bytes_dict, contrast_results_dict, roi_channel_map_dict, folding_bypass): def __init__(
self,
haemo_dict: dict[str, BaseRaw],
epochs_dict: dict[str, Epochs],
cha_dict: dict[str, DataFrame],
df_ind_dict: dict[str, DataFrame],
design_matrix_dict: dict[str, DataFrame],
config_dict: dict[str, dict[str, Any]],
fig_bytes_dict: dict[str, dict[str, bytes]],
contrast_results_dict: dict[str, dict[str, Any]],
roi_channel_map_dict: dict[str, dict[str, str]],
fir_feature_dict: dict[str, dict[str, Any]],
qc_dict: dict[str, dict[str, Any]],
folding_bypass: bool,
) -> None:
super().__init__() super().__init__()
self.setWindowTitle(f"Viewer Launcher - {APP_NAME.upper()}") self.setWindowTitle(f"Viewer Launcher - {APP_NAME.upper()}")
group_dict = {f: c.get("GROUP", "Unknown") for f, c in config_dict.items()} group_dict = {f: c.get("GROUP", "Unknown") for f, c in config_dict.items()}
btn_data = [ btn_data: list[tuple[str, Type[QWidget], list[Any], bool]] = [
("Participant Image Viewer", ParticipantImageViewerWidget, [haemo_dict, fig_bytes_dict], True), ("Participant Image Viewer", ParticipantImageViewerWidget, [haemo_dict, fig_bytes_dict], True),
("Participant Brain Viewer", ParticipantBrainViewerWidget, [haemo_dict, cha_dict], True), ("Participant Brain Viewer", ParticipantBrainViewerWidget, [haemo_dict, cha_dict], True),
("Participant Fold Channels Viewer", ParticipantFoldChannelsWidget, [haemo_dict, cha_dict], False), ("Participant Fold Channels Viewer", ParticipantFoldChannelsWidget, [haemo_dict, cha_dict], False),
("Participant Functional Connectivity Viewer [BETA]", ParticipantFunctionalConnectivityWidget, [haemo_dict, epochs_dict], True), ("Participant Functional Connectivity Viewer [BETA]", ParticipantFunctionalConnectivityWidget, [haemo_dict, epochs_dict], True),
("Inter-Group Functional Connectivity Viewer [BETA]", InterGroupFunctionalConnectivityWidget, [haemo_dict, group_dict, config_dict], True), ("Intra-Group Functional Connectivity Viewer [BETA]", IntraGroupFunctionalConnectivityWidget, [haemo_dict, epochs_dict, group_dict], True),
("Intra-Group Stats Viewer", IntraGroupStatsWidget, [haemo_dict, cha_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, roi_channel_map_dict, group_dict], True),
("Inter-Group Stats Viewer", InterGroupStatsWidget, [haemo_dict, cha_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, roi_channel_map_dict, group_dict], True), ("Inter-Group Stats Viewer", InterGroupStatsWidget, [haemo_dict, cha_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, roi_channel_map_dict, group_dict], True),
("Cross-Group Stats Viewer", CrossGroupStatsWidget, [haemo_dict, cha_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, roi_channel_map_dict, group_dict], True), ("Intra-Group Brain and Image Viewer", IntraGroupBrainImageWidget, [haemo_dict, cha_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, group_dict], True),
("Inter-Group Brain and Image Viewer", InterGroupBrainImageWidget, [haemo_dict, cha_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, group_dict], True), ("Inter-Group Brain and Image Viewer", InterGroupBrainImageWidget, [haemo_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, group_dict], True),
("Cross-Group Brain and Image Viewer", CrossGroupBrainImageWidget, [haemo_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, group_dict], True), ("Export To CSV Viewer", ExportToCSVWidget, [haemo_dict, cha_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, group_dict, config_dict, fir_feature_dict, qc_dict], True)
("Export To CSV Viewer", ExportToCSVWidget, [haemo_dict, cha_dict, df_ind_dict, design_matrix_dict, contrast_results_dict, group_dict, config_dict], True)
] ]
layout = QVBoxLayout(self) layout = QVBoxLayout(self)
for label, widget_class, args, requires_bypass in btn_data: for label, widget_class, args, requires_bypass in btn_data:
btn = QPushButton(f"Open {label}") btn = QPushButton(f"Open {label}")
# Connect directly to the generic opener # Connect directly to the generic opener
btn.clicked.connect(lambda _, c=widget_class, b=btn, a=args: self._open_viewer(c, b, *a)) btn.clicked.connect(self._make_viewer_callback(widget_class, btn, args))
btn.setEnabled(not (requires_bypass and folding_bypass)) btn.setEnabled(not (requires_bypass and folding_bypass))
layout.addWidget(btn) layout.addWidget(btn)
def _open_viewer(self, widget_class, btn, *args): def _make_viewer_callback(
self,
widget_class: Type[QWidget],
btn: QPushButton,
args: list[Any],
) -> Callable[[bool], None]:
def callback(_checked: bool = False) -> None:
self._open_viewer(widget_class, btn, *args)
return callback
def _open_viewer(
self,
widget_class: Type[QWidget],
btn: QPushButton,
*args: Any
) -> None:
# Instantiate and show dynamically # Instantiate and show dynamically
self.active_viewer = widget_class(*args) self.active_viewer = widget_class(*args)
self.active_viewer.show() self.active_viewer.show()
self._trigger_success(btn) self._trigger_success(btn)
def _launch(self, func, btn, *args): def _launch(
self,
func: Callable[..., Any],
btn: QPushButton,
*args: Any
) -> None:
func(*args) func(*args)
self._trigger_success(btn) self._trigger_success(btn)
def _trigger_success(self, button): def _trigger_success(self, button: QPushButton) -> None:
"""Temporarily adds a green checkmark to the button text.""" """Temporarily adds a green checkmark to the button text."""
original_text = button.text() original_text = button.text()
button.setText(f"{original_text} ✔") button.setText(f"{original_text} ✔")
@@ -70,6 +116,6 @@ class ViewerLauncherWidget(QWidget):
# Revert after 1 second # Revert after 1 second
QTimer.singleShot(1000, lambda: self._revert_button(button, original_text)) QTimer.singleShot(1000, lambda: self._revert_button(button, original_text))
def _revert_button(self, button, original_text): def _revert_button(self, button: QPushButton, original_text: str) -> None:
button.setText(original_text) button.setText(original_text)
button.setStyleSheet("") button.setStyleSheet("")
+1
View File
@@ -7,6 +7,7 @@ Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
""" """
# Built-in imports
import os import os
from dataclasses import dataclass from dataclasses import dataclass
-1
View File
@@ -1 +0,0 @@
update
+97 -56
View File
@@ -1,6 +1,7 @@
""" """
Filename: updater.py Filename: updater.py
Description: Generic updater file Description: Generic updater file
Note: Compliant with pylance strict type checking
Author: Tyler de Zeeuw Author: Tyler de Zeeuw
License: GPL-3.0 License: GPL-3.0
@@ -17,13 +18,14 @@ import zipfile
import traceback import traceback
import subprocess import subprocess
import configparser import configparser
from typing import List
# External library imports # External library imports
import psutil import psutil
import requests import requests
from PySide6.QtWidgets import QMessageBox
from PySide6.QtCore import QThread, Signal, QObject from PySide6.QtCore import QThread, Signal, QObject
from PySide6.QtWidgets import QMainWindow, QMessageBox
class UpdateDownloadThread(QThread): class UpdateDownloadThread(QThread):
@@ -38,7 +40,14 @@ class UpdateDownloadThread(QThread):
update_ready = Signal(str, str) update_ready = Signal(str, str)
error_occurred = Signal(str) error_occurred = Signal(str)
def __init__(self, download_url, latest_version, platform_name, app_name): def __init__(
self,
download_url: str,
latest_version: str,
platform_name: str,
app_name: str,
) -> None:
super().__init__() super().__init__()
self.download_url = download_url self.download_url = download_url
self.latest_version = latest_version self.latest_version = latest_version
@@ -54,6 +63,7 @@ class UpdateDownloadThread(QThread):
os.makedirs(tmp_dir, exist_ok=True) os.makedirs(tmp_dir, exist_ok=True)
local_path = os.path.join(tmp_dir, local_filename) local_path = os.path.join(tmp_dir, local_filename)
else: else:
tmp_dir = os.getcwd()
local_path = os.path.join(os.getcwd(), local_filename) local_path = os.path.join(os.getcwd(), local_filename)
# Download the file # Download the file
@@ -92,7 +102,6 @@ class UpdateDownloadThread(QThread):
self.error_occurred.emit(str(e)) self.error_occurred.emit(str(e))
class UpdateCheckThread(QThread): class UpdateCheckThread(QThread):
""" """
Thread that checks for updates by querying the API and emits a signal based on the result. Thread that checks for updates by querying the API and emits a signal based on the result.
@@ -107,7 +116,15 @@ class UpdateCheckThread(QThread):
no_update_available = Signal() no_update_available = Signal()
error_occurred = Signal(str) error_occurred = Signal(str)
def __init__(self, api_url, api_url_sec, current_version, platform_name, app_name): def __init__(
self,
api_url: str,
api_url_sec: str,
current_version: str,
platform_name: str,
app_name: str,
) -> None:
super().__init__() super().__init__()
self.api_url = api_url self.api_url = api_url
self.api_url_sec = api_url_sec self.api_url_sec = api_url_sec
@@ -137,8 +154,9 @@ class UpdateCheckThread(QThread):
except Exception as e: except Exception as e:
self.error_occurred.emit(f"Update check failed: {e}") self.error_occurred.emit(f"Update check failed: {e}")
def version_compare(self, v1, v2): def version_compare(self, v1: str, v2: str) -> int:
def normalize(v): return [int(x) for x in v.split(".")] def normalize(v: str) -> List[int]:
return [int(x) for x in v.split(".")]
return (normalize(v1) > normalize(v2)) - (normalize(v1) < normalize(v2)) return (normalize(v1) > normalize(v2)) - (normalize(v1) < normalize(v2))
def get_latest_release_for_platform(self): def get_latest_release_for_platform(self):
@@ -165,7 +183,7 @@ class UpdateCheckThread(QThread):
return tag, asset["browser_download_url"] return tag, asset["browser_download_url"]
return tag, None return tag, None
except (requests.RequestException, ValueError) as e: except (requests.RequestException, ValueError, KeyError):
continue continue
return None, None return None, None
@@ -182,15 +200,23 @@ class LocalPendingUpdateCheckThread(QThread):
pending_update_found = Signal(str, str) pending_update_found = Signal(str, str)
no_pending_update = Signal() no_pending_update = Signal()
def __init__(self, current_version, platform_suffix, platform_name, app_name): def __init__(
self,
current_version: str,
platform_suffix: str,
platform_name: str,
app_name: str,
) -> None:
super().__init__() super().__init__()
self.current_version = current_version self.current_version = current_version
self.platform_suffix = platform_suffix self.platform_suffix = platform_suffix
self.platform_name = platform_name self.platform_name = platform_name
self.app_name = app_name self.app_name = app_name
def version_compare(self, v1, v2): def version_compare(self, v1: str, v2: str) -> int:
def normalize(v): return [int(x) for x in v.split(".")] def normalize(v: str) -> List[int]:
return [int(x) for x in v.split(".")]
return (normalize(v1) > normalize(v2)) - (normalize(v1) < normalize(v2)) return (normalize(v1) > normalize(v2)) - (normalize(v1) < normalize(v2))
def run(self): def run(self):
@@ -220,18 +246,25 @@ class LocalPendingUpdateCheckThread(QThread):
self.no_pending_update.emit() self.no_pending_update.emit()
class UpdateManager(QObject): class UpdateManager(QObject):
""" """
Orchestrates the update process. Orchestrates the update process.
Main apps should instantiate this and call check_for_updates(). Main apps should instantiate this and call check_for_updates().
""" """
def __init__(self, main_window, api_url, api_url_sec, current_version, platform_name, platform_suffix, app_name): def __init__(
super().__init__() self,
self.parent = main_window main_window: QMainWindow,
api_url: str,
api_url_sec: str,
current_version: str,
platform_name: str,
platform_suffix: str,
app_name: str,
) -> None:
super().__init__(main_window)
self.main_window: QMainWindow = main_window
self.api_url = api_url self.api_url = api_url
self.api_url_sec = api_url_sec self.api_url_sec = api_url_sec
self.current_version = current_version self.current_version = current_version
@@ -243,59 +276,64 @@ class UpdateManager(QObject):
self.pending_update_path = None self.pending_update_path = None
def manual_check_for_updates(self): def manual_check_for_updates(self) -> None:
self.local_check_thread = LocalPendingUpdateCheckThread(self.current_version, self.platform_suffix, self.platform_name, self.app_name) self.local_check_thread = LocalPendingUpdateCheckThread(self.current_version, self.platform_suffix, self.platform_name, self.app_name)
self.local_check_thread.pending_update_found.connect(self.on_pending_update_found) self.local_check_thread.pending_update_found.connect(self.on_pending_update_found)
self.local_check_thread.no_pending_update.connect(self.on_no_pending_update) self.local_check_thread.no_pending_update.connect(self.on_no_pending_update)
self.local_check_thread.start() self.local_check_thread.start()
def on_pending_update_found(self, version, folder_path): def on_pending_update_found(self, version: str, folder_path: str) -> None:
self.parent.statusBar().showMessage(f"Pending update found: version {version}") self.main_window.statusBar().showMessage(f"Pending update found: version {version}")
self.pending_update_version = version self.pending_update_version = version
self.pending_update_path = folder_path self.pending_update_path = folder_path
self.show_pending_update_popup() self.show_pending_update_popup()
def on_no_pending_update(self): def on_no_pending_update(self) -> None:
# No pending update found locally, start server check directly # No pending update found locally, start server check directly
self.parent.statusBar().showMessage("No pending local update found. Checking server...") self.main_window.statusBar().showMessage("No pending local update found. Checking server...")
self.start_update_check_thread() self.start_update_check_thread()
def show_pending_update_popup(self): def show_pending_update_popup(self) -> None:
msg_box = QMessageBox(self.parent) msg_box = QMessageBox(self.main_window)
msg_box.setWindowTitle("Pending Update Found") msg_box.setWindowTitle("Pending Update Found")
msg_box.setText(f"A previously downloaded update for {self.app_name.upper()} (version {self.pending_update_version}) is available at:\n{self.pending_update_path}\nWould you like to install it now?") msg_box.setText(f"A previously downloaded update for {self.app_name.upper()} (version {self.pending_update_version}) is available at:\n{self.pending_update_path}\nWould you like to install it now?")
install_now_button = msg_box.addButton("Install Now", QMessageBox.ButtonRole.AcceptRole) install_now_button = msg_box.addButton("Install Now", QMessageBox.ButtonRole.AcceptRole)
install_later_button = msg_box.addButton("Install Later", QMessageBox.ButtonRole.RejectRole) msg_box.addButton("Install Later", QMessageBox.ButtonRole.RejectRole)
msg_box.exec() msg_box.exec()
if msg_box.clickedButton() == install_now_button: if msg_box.clickedButton() == install_now_button and self.pending_update_path:
self.install_update(self.pending_update_path) self.install_update(self.pending_update_path)
else: else:
self.parent.statusBar().showMessage("Pending update available. Install later.") if self.main_window.statusBar():
self.main_window.statusBar().showMessage("Pending update available. Install later.")
# After user dismisses, still check the server for new updates # After user dismisses, still check the server for new updates
self.start_update_check_thread() self.start_update_check_thread()
def start_update_check_thread(self): def start_update_check_thread(self) -> None:
self.check_thread = UpdateCheckThread(self.api_url, self.api_url_sec, self.current_version, self.platform_name, self.app_name) self.check_thread = UpdateCheckThread(self.api_url, self.api_url_sec, self.current_version, self.platform_name, self.app_name)
self.check_thread.download_requested.connect(self.on_server_update_requested) self.check_thread.download_requested.connect(self.on_server_update_requested)
self.check_thread.no_update_available.connect(self.on_server_no_update) self.check_thread.no_update_available.connect(self.on_server_no_update)
self.check_thread.error_occurred.connect(self.on_error) self.check_thread.error_occurred.connect(self.on_error)
self.check_thread.start() self.check_thread.start()
def on_server_no_update(self): def on_server_no_update(self) -> None:
self.parent.statusBar().showMessage("No new updates found on server.", 5000) if self.main_window.statusBar():
self.main_window.statusBar().showMessage("No new updates found on server.", 5000)
def on_server_update_requested(self, download_url, latest_version): def on_server_update_requested(self, download_url: str, latest_version: str) -> None:
if self.pending_update_version: pending_path = self.pending_update_path
cmp = self.version_compare(latest_version, self.pending_update_version) pending_version = self.pending_update_version
if pending_version and pending_path:
cmp = self.version_compare(latest_version, pending_version)
if cmp > 0: if cmp > 0:
# Server version is newer than pending update # Server version is newer than pending update
self.parent.statusBar().showMessage(f"Newer version {latest_version} available on server. Removing old pending update...") self.main_window.statusBar().showMessage(f"Newer version {latest_version} available on server. Removing old pending update...")
try: try:
shutil.rmtree(self.pending_update_path) shutil.rmtree(pending_path)
self.parent.statusBar().showMessage(f"Deleted old update folder: {self.pending_update_path}") self.main_window.statusBar().showMessage(f"Deleted old update folder: {pending_path}")
except Exception as e: except Exception as e:
self.parent.statusBar().showMessage(f"Failed to delete old update folder: {e}") self.main_window.statusBar().showMessage(f"Failed to delete old update folder: {e}")
# Clear pending update info so new download proceeds # Clear pending update info so new download proceeds
self.pending_update_version = None self.pending_update_version = None
@@ -305,39 +343,41 @@ class UpdateManager(QObject):
self.download_update(download_url, latest_version) self.download_update(download_url, latest_version)
elif cmp == 0: elif cmp == 0:
# Versions equal, no download needed # Versions equal, no download needed
self.parent.statusBar().showMessage(f"Pending update version {self.pending_update_version} is already latest. No download needed.") self.main_window.statusBar().showMessage(f"Pending update version {self.pending_update_version} is already latest. No download needed.")
else: else:
# Server version older than pending? Unlikely but just keep pending update # Server version older than pending? Unlikely but just keep pending update
self.parent.statusBar().showMessage(f"Pending update version {self.pending_update_version} is newer than server version. No action.") self.main_window.statusBar().showMessage(f"Pending update version {self.pending_update_version} is newer than server version. No action.")
else: else:
# No pending update, just download # No pending update, just download
self.download_update(download_url, latest_version) self.download_update(download_url, latest_version)
def download_update(self, download_url, latest_version): def download_update(self, download_url: str, latest_version: str) -> None:
self.parent.statusBar().showMessage("Downloading update...") if self.main_window.statusBar():
self.main_window.statusBar().showMessage("Downloading update...")
self.download_thread = UpdateDownloadThread(download_url, latest_version, self.platform_name, self.app_name) self.download_thread = UpdateDownloadThread(download_url, latest_version, self.platform_name, self.app_name)
self.download_thread.update_ready.connect(self.on_update_ready) self.download_thread.update_ready.connect(self.on_update_ready)
self.download_thread.error_occurred.connect(self.on_error) self.download_thread.error_occurred.connect(self.on_error)
self.download_thread.start() self.download_thread.start()
def on_update_ready(self, latest_version, extract_folder): def on_update_ready(self, latest_version: str, extract_folder: str) -> None:
self.parent.statusBar().showMessage("Update downloaded and extracted.") if self.main_window.statusBar():
self.main_window.statusBar().showMessage("Update downloaded and extracted.")
msg_box = QMessageBox(self.parent) msg_box = QMessageBox(self.main_window)
msg_box.setWindowTitle("Update Ready") msg_box.setWindowTitle("Update Ready")
msg_box.setText(f"Version {latest_version} has been downloaded and extracted to:\n{extract_folder}\nWould you like to install it now?") msg_box.setText(f"Version {latest_version} has been downloaded and extracted to:\n{extract_folder}\nWould you like to install it now?")
install_now_button = msg_box.addButton("Install Now", QMessageBox.ButtonRole.AcceptRole) install_now_button = msg_box.addButton("Install Now", QMessageBox.ButtonRole.AcceptRole)
install_later_button = msg_box.addButton("Install Later", QMessageBox.ButtonRole.RejectRole) msg_box.addButton("Install Later", QMessageBox.ButtonRole.RejectRole)
msg_box.exec() msg_box.exec()
if msg_box.clickedButton() == install_now_button: if msg_box.clickedButton() == install_now_button:
self.install_update(extract_folder) self.install_update(extract_folder)
else: else:
self.parent.statusBar().showMessage("Update ready. Install later.") self.main_window.statusBar().showMessage("Update ready. Install later.")
def install_update(self, extract_folder): def install_update(self, extract_folder: str) -> None:
# Path to updater executable # Path to updater executable
if self.platform_name == 'windows': if self.platform_name == 'windows':
@@ -354,7 +394,7 @@ class UpdateManager(QObject):
updater_path = os.getcwd() updater_path = os.getcwd()
if not os.path.exists(updater_path): if not os.path.exists(updater_path):
QMessageBox.critical(self.parent, "Error", f"Updater not found at:\n{updater_path}. The absolute path was {os.path.abspath(updater_path)}") QMessageBox.critical(self.main_window, "Error", f"Updater not found at:\n{updater_path}. The absolute path was {os.path.abspath(updater_path)}")
return return
# Launch updater with extracted folder path as argument # Launch updater with extracted folder path as argument
@@ -373,18 +413,19 @@ class UpdateManager(QObject):
sys.exit(0) sys.exit(0)
except Exception as e: except Exception as e:
QMessageBox.critical(self.parent, "Error", f"[Updater Launch Failed]\n{str(e)}\n{traceback.format_exc()}") QMessageBox.critical(self.main_window, "Error", f"[Updater Launch Failed]\n{str(e)}\n{traceback.format_exc()}")
def on_error(self, message): def on_error(self, message: str) -> None:
# print(f"Error: {message}") if self.main_window.statusBar():
self.parent.statusBar().showMessage(f"Error occurred during update process. {message}") self.main_window.statusBar().showMessage(f"Error occurred during update process. {message}")
def version_compare(self, v1, v2): def version_compare(self, v1: str, v2: str) -> int:
def normalize(v): return [int(x) for x in v.split(".")] def normalize(v: str) -> List[int]:
return [int(x) for x in v.split(".")]
return (normalize(v1) > normalize(v2)) - (normalize(v1) < normalize(v2)) return (normalize(v1) > normalize(v2)) - (normalize(v1) < normalize(v2))
def wait_for_process_to_exit(process_name, timeout=10): def wait_for_process_to_exit(process_name: str, timeout: int = 10) -> bool:
""" """
Waits for a process with the specified name to exit within a timeout period. Waits for a process with the specified name to exit within a timeout period.
@@ -416,7 +457,7 @@ def wait_for_process_to_exit(process_name, timeout=10):
return False return False
def finish_update_if_needed(platform_name, app_name, cfg_path, finish_update): def finish_update_if_needed(platform_name: str, app_name: str, cfg_path: str, finish_update: bool) -> None:
""" """
Completes a pending application update if '--finish-update' is present in the command-line arguments. Completes a pending application update if '--finish-update' is present in the command-line arguments.
""" """
@@ -534,7 +575,7 @@ def finish_update_if_needed(platform_name, app_name, cfg_path, finish_update):
sys.argv.remove("--finish-update") sys.argv.remove("--finish-update")
def remove_quarantine(app_path, app_name): def remove_quarantine(app_path: str, app_name: str) -> None:
""" """
Removes the macOS quarantine attribute from the specified application path. Removes the macOS quarantine attribute from the specified application path.
""" """