Compare commits
14
Commits
v1.6.0
...
57492a479b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57492a479b | ||
|
|
8ef352add3 | ||
|
|
c566527f48 | ||
|
|
2fe6f42c48 | ||
|
|
71b6280cc2 | ||
|
|
f0b8266cf9 | ||
|
|
a9ea0efcb4 | ||
|
|
83ab73a05a | ||
|
|
2fa3188296 | ||
|
|
d9d5b6d940 | ||
|
|
e37275a1bb | ||
|
|
19bd3f1279 | ||
|
|
7a438b1798 | ||
|
|
2f76622e52 |
+4
-1
@@ -175,10 +175,13 @@ cython_debug/
|
||||
.pypirc
|
||||
|
||||
/individual_images
|
||||
/plugins
|
||||
*.xlsx
|
||||
*.csv
|
||||
*.snirf
|
||||
*.json
|
||||
flares-*
|
||||
*.flare
|
||||
*.cfg
|
||||
*.cfg
|
||||
tempCodeRunnerFile.py
|
||||
*.pkl
|
||||
@@ -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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -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:
|
||||
|
||||
flares Copyright (C) 2025 tyler
|
||||
flares Copyright (C) 2025-2026 tyler
|
||||
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.
|
||||
|
||||
|
||||
@@ -1,3 +1,44 @@
|
||||
# Version 1.7.1
|
||||
|
||||
- Fixed an issue where the application could not automatically update between versions 1.5.1 to 1.7.1. Sorry!
|
||||
|
||||
|
||||
# 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
|
||||
|
||||
- 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
|
||||
|
||||
@@ -10,15 +10,14 @@ License: GPL-3.0
|
||||
# Built-in imports
|
||||
import os
|
||||
import sys
|
||||
import plistlib
|
||||
import subprocess
|
||||
from typing import Optional, Tuple
|
||||
|
||||
# External library imports
|
||||
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,
|
||||
@@ -27,7 +26,6 @@ def register_file_association(ext: Optional[str] = None,
|
||||
bundle_id: Optional[str] = None,
|
||||
force_admin: bool = False,
|
||||
) -> Tuple[bool, str]:
|
||||
|
||||
"""
|
||||
Registers a custom file extension across Windows, Linux, and macOS.
|
||||
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"):
|
||||
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:
|
||||
lsregister_path = (
|
||||
"/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],
|
||||
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:
|
||||
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:
|
||||
return False, f"macOS Registration failed: {str(e)}"
|
||||
+92
-54
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Filename: flares_updater.py
|
||||
Description: FLARES updater executable
|
||||
Note: Compliant with pylance strict type checking
|
||||
|
||||
Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
@@ -13,26 +14,33 @@ import time
|
||||
import shlex
|
||||
import psutil
|
||||
import shutil
|
||||
import platform
|
||||
import subprocess
|
||||
from typing import Union
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
PLATFORM_NAME = platform.system().lower()
|
||||
APP_NAME = "flares"
|
||||
# External library imports
|
||||
from src.shared.shareddata import APP_NAME, PLATFORM_NAME, get_app_dir
|
||||
|
||||
|
||||
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:
|
||||
LOG_FILE = os.path.join(os.getcwd(), f"{APP_NAME}_updater.log")
|
||||
_log_path = os.path.join(get_app_dir(), f"{APP_NAME}_updater.log")
|
||||
|
||||
LOG_FILE = _log_path
|
||||
|
||||
|
||||
def log(msg):
|
||||
with open(LOG_FILE, "a", encoding="utf-8") as f:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
f.write(f"{timestamp} - {msg}\n")
|
||||
def log(msg: str) -> None:
|
||||
try:
|
||||
with open(LOG_FILE, "a", encoding="utf-8") as f:
|
||||
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
f.write(f"{timestamp} - {msg}\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def kill_all_processes_by_executable(exe_path):
|
||||
def kill_all_processes_by_executable(exe_path: Union[str, Path]) -> bool:
|
||||
terminated_any = False
|
||||
exe_path = os.path.realpath(exe_path)
|
||||
|
||||
@@ -40,22 +48,28 @@ def kill_all_processes_by_executable(exe_path):
|
||||
for proc in psutil.process_iter(['pid', 'exe']):
|
||||
try:
|
||||
proc_exe = proc.info.get('exe')
|
||||
if proc_exe and os.path.samefile(os.path.realpath(proc_exe), exe_path):
|
||||
log(f"Terminating process: PID {proc.pid}")
|
||||
_terminate_process(proc)
|
||||
terminated_any = True
|
||||
if proc_exe and os.path.exists(proc_exe) and os.path.exists(exe_path):
|
||||
if os.path.samefile(os.path.realpath(proc_exe), exe_path):
|
||||
log(f"Terminating process: PID {proc.pid}")
|
||||
_terminate_process(proc)
|
||||
terminated_any = True
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, FileNotFoundError) as e:
|
||||
continue
|
||||
except Exception as e:
|
||||
log(f"Error terminating process (Windows): {e}")
|
||||
|
||||
elif PLATFORM_NAME == 'linux':
|
||||
for proc in psutil.process_iter(['pid', 'cmdline']):
|
||||
try:
|
||||
cmdline = proc.info.get('cmdline', [])
|
||||
if cmdline:
|
||||
if cmdline and os.path.exists(cmdline[0]) and os.path.exists(exe_path):
|
||||
proc_cmd = os.path.realpath(cmdline[0])
|
||||
if os.path.samefile(proc_cmd, exe_path):
|
||||
log(f"Terminating process: PID {proc.pid}")
|
||||
_terminate_process(proc)
|
||||
terminated_any = True
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, FileNotFoundError) as e:
|
||||
continue
|
||||
except Exception as e:
|
||||
log(f"Error terminating process (Linux): {e}")
|
||||
|
||||
@@ -64,7 +78,7 @@ def kill_all_processes_by_executable(exe_path):
|
||||
return terminated_any
|
||||
|
||||
|
||||
def _terminate_process(proc):
|
||||
def _terminate_process(proc: psutil.Process) -> None:
|
||||
try:
|
||||
proc.terminate()
|
||||
proc.wait(timeout=10)
|
||||
@@ -76,7 +90,10 @@ def _terminate_process(proc):
|
||||
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:
|
||||
if not os.path.exists(path):
|
||||
return
|
||||
|
||||
start_time = time.time()
|
||||
while time.time() - start_time < timeout:
|
||||
try:
|
||||
@@ -90,9 +107,9 @@ def wait_for_unlock(path, timeout=100):
|
||||
log(f"Still locked: {path} - {e}")
|
||||
time.sleep(1)
|
||||
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):
|
||||
try:
|
||||
if os.path.isdir(path):
|
||||
@@ -105,7 +122,7 @@ def delete_path(path):
|
||||
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):
|
||||
if item.lower() == updater_name.lower():
|
||||
log(f"Skipping updater executable: {item}")
|
||||
@@ -124,9 +141,9 @@ def copy_update_files(src_folder, dest_folder, updater_name):
|
||||
log(f"Error copying {s} -> {d}: {e}")
|
||||
|
||||
|
||||
def copy_update_files_darwin(src_folder, dest_folder, updater_name):
|
||||
|
||||
updater_name = updater_name + ".app"
|
||||
def copy_update_files_darwin(src_folder: Union[str, Path], dest_folder: Union[str, Path], updater_name: str) -> None:
|
||||
if not updater_name.endswith(".app"):
|
||||
updater_name = updater_name + ".app"
|
||||
|
||||
for item in os.listdir(src_folder):
|
||||
if item.lower() == updater_name.lower():
|
||||
@@ -146,19 +163,30 @@ def copy_update_files_darwin(src_folder, dest_folder, updater_name):
|
||||
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."""
|
||||
clean_path: str = str(app_path)
|
||||
escaped_path: str = shlex.quote(clean_path)
|
||||
|
||||
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:
|
||||
subprocess.run(['osascript', '-e', script], check=True)
|
||||
subprocess.run(["osascript", "-e", script], check=True)
|
||||
print("✅ Quarantine attribute removed.")
|
||||
return True
|
||||
except subprocess.CalledProcessError as e:
|
||||
print("❌ Failed to remove quarantine attribute.")
|
||||
print(e)
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
main_exe: str = ""
|
||||
app_dir: Path = Path()
|
||||
bundle_dir: Path = Path()
|
||||
parent_bundle_dir: Path = Path()
|
||||
|
||||
try:
|
||||
log(f"[Updater] sys.argv: {sys.argv}")
|
||||
|
||||
@@ -169,43 +197,53 @@ def main():
|
||||
update_folder = sys.argv[1]
|
||||
main_exe = sys.argv[2]
|
||||
|
||||
# Interesting naming convention
|
||||
parent_dir = os.path.dirname(os.path.abspath(main_exe))
|
||||
pparent_dir = os.path.dirname(parent_dir)
|
||||
ppparent_dir = os.path.dirname(pparent_dir)
|
||||
pppparent_dir = os.path.dirname(ppparent_dir)
|
||||
main_exe_path = Path(main_exe).resolve()
|
||||
app_dir = main_exe_path.parent
|
||||
|
||||
updater_name = os.path.basename(sys.argv[0])
|
||||
if PLATFORM_NAME == 'darwin':
|
||||
# Bundle hierarchy on macOS: App.app/Contents/MacOS/executable
|
||||
if len(main_exe_path.parents) >= 4:
|
||||
bundle_dir = main_exe_path.parents[2]
|
||||
parent_bundle_dir = main_exe_path.parents[3]
|
||||
else:
|
||||
bundle_dir = app_dir
|
||||
parent_bundle_dir = app_dir.parent
|
||||
|
||||
updater_name = os.path.basename(sys.executable if getattr(sys, 'frozen', False) else sys.argv[0])
|
||||
|
||||
log("Updater started.")
|
||||
log(f"Update folder: {update_folder}")
|
||||
log(f"Main EXE: {main_exe}")
|
||||
log(f"Updater EXE: {updater_name}")
|
||||
if PLATFORM_NAME == 'darwin':
|
||||
log(f"Main App Folder: {ppparent_dir}")
|
||||
if PLATFORM_NAME == 'darwin' and bundle_dir:
|
||||
log(f"Main App Folder: {bundle_dir}")
|
||||
|
||||
# Kill all instances of main app
|
||||
kill_all_processes_by_executable(main_exe)
|
||||
|
||||
# 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
|
||||
for proc in psutil.process_iter(['exe', 'cmdline']):
|
||||
try:
|
||||
if PLATFORM_NAME == 'windows':
|
||||
proc_exe = proc.info.get('exe')
|
||||
if proc_exe and os.path.samefile(os.path.realpath(proc_exe), os.path.realpath(main_exe)):
|
||||
running = True
|
||||
break
|
||||
if proc_exe and os.path.exists(proc_exe) and os.path.exists(main_exe):
|
||||
if os.path.samefile(os.path.realpath(proc_exe), os.path.realpath(main_exe)):
|
||||
running = True
|
||||
break
|
||||
elif PLATFORM_NAME == 'linux':
|
||||
cmdline = proc.info.get('cmdline', [])
|
||||
if cmdline:
|
||||
if cmdline and os.path.exists(cmdline[0]) and os.path.exists(main_exe):
|
||||
proc_cmd = os.path.realpath(cmdline[0])
|
||||
if os.path.samefile(proc_cmd, os.path.realpath(main_exe)):
|
||||
running = True
|
||||
break
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, FileNotFoundError):
|
||||
continue
|
||||
except Exception as e:
|
||||
log(f"Polling error: {e}")
|
||||
|
||||
if not running:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
@@ -213,18 +251,18 @@ def main():
|
||||
log("Warning: main executable still running after wait timeout.")
|
||||
|
||||
# Delete old version files
|
||||
if PLATFORM_NAME == 'darwin':
|
||||
log(f'Attempting to delete {ppparent_dir}')
|
||||
delete_path(ppparent_dir)
|
||||
update_folder = os.path.join(sys.argv[1], f"{APP_NAME}-darwin")
|
||||
copy_update_files_darwin(update_folder, pppparent_dir, updater_name)
|
||||
if PLATFORM_NAME == 'darwin' and bundle_dir and parent_bundle_dir:
|
||||
log(f'Attempting to delete {bundle_dir}')
|
||||
delete_path(str(bundle_dir))
|
||||
extracted_update_folder = os.path.join(update_folder, f"{APP_NAME}-darwin")
|
||||
copy_update_files_darwin(extracted_update_folder, str(parent_bundle_dir), updater_name)
|
||||
|
||||
else:
|
||||
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_update_files(update_folder, parent_dir, updater_name)
|
||||
copy_update_files(update_folder, str(app_dir), updater_name)
|
||||
|
||||
except Exception as e:
|
||||
log(f"Something went wrong: {e}")
|
||||
@@ -234,15 +272,15 @@ def main():
|
||||
if PLATFORM_NAME == 'linux':
|
||||
os.chmod(main_exe, 0o755)
|
||||
log("Added executable bit")
|
||||
|
||||
if PLATFORM_NAME == 'darwin':
|
||||
os.chmod(ppparent_dir, 0o755)
|
||||
|
||||
if PLATFORM_NAME == 'darwin' and bundle_dir:
|
||||
os.chmod(str(bundle_dir), 0o755)
|
||||
log("Added executable bit")
|
||||
remove_quarantine(ppparent_dir)
|
||||
log(f"Removed the quarantine flag on {ppparent_dir}")
|
||||
subprocess.Popen(['open', ppparent_dir, "--args", "--finish-update"])
|
||||
remove_quarantine(str(bundle_dir))
|
||||
log(f"Removed the quarantine flag on {bundle_dir}")
|
||||
subprocess.Popen(['open', str(bundle_dir), "--args", "--finish-update"])
|
||||
else:
|
||||
subprocess.Popen([main_exe, "--finish-update"], cwd=parent_dir)
|
||||
subprocess.Popen([main_exe, "--finish-update"], cwd=str(app_dir))
|
||||
|
||||
log("Relaunched main app.")
|
||||
except Exception as e:
|
||||
|
||||
@@ -19,6 +19,7 @@ from queue import Empty
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
from functools import partial
|
||||
from multiprocessing import Process, current_process, freeze_support, Queue, set_start_method
|
||||
|
||||
# External library imports
|
||||
@@ -28,8 +29,8 @@ from PySide6.QtWidgets import (
|
||||
QApplication, QWidget, QMessageBox, QVBoxLayout, QHBoxLayout, QTextEdit, QScrollArea, QComboBox, QGridLayout, QSplitter, QDialogButtonBox, QHeaderView,
|
||||
QPushButton, QMainWindow, QLabel, QLineEdit, QGroupBox, QDialog, QMenu, QSpinBox, QTableWidget, QTableWidgetItem
|
||||
)
|
||||
from PySide6.QtCore import Signal, Qt, QTimer
|
||||
from PySide6.QtGui import QAction, QFontMetrics, QKeySequence, QIcon
|
||||
from PySide6.QtCore import QEvent, QObject, Signal, Qt, QTimer
|
||||
from PySide6.QtGui import QAction, QActionGroup, QFontMetrics, QKeySequence, QIcon
|
||||
from PySide6.QtSvgWidgets import QSvgWidget # needed to show svgs when app is not frozen
|
||||
|
||||
from file_ext_registration import register_file_association, ELEVATION_FLAG
|
||||
@@ -64,6 +65,7 @@ show_welcome_dialog = false
|
||||
first_startup = true
|
||||
|
||||
[Preferences]
|
||||
theme = auto
|
||||
2d_data_bypass = false
|
||||
incompatible_save_bypass = false
|
||||
missing_events_bypass = false
|
||||
@@ -129,10 +131,10 @@ SECTIONS = [
|
||||
"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_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_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_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": "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_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",
|
||||
"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_TIME_WINDOW", "default": 3, "type": int, "depends_on": "PSP", "advanced": False, "help": "Length of each independent PSP calculation window in seconds."},
|
||||
{"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 cutoff for PSP bandpass filtering (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_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_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_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_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": "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": "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": "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": "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": "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": "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": "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",
|
||||
"params": [
|
||||
{"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_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_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, "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."},
|
||||
]
|
||||
},
|
||||
@@ -320,7 +323,7 @@ SECTIONS = [
|
||||
BIDS_FIELD_MAP = {
|
||||
"BIDS - Age": "AGE",
|
||||
"BIDS - Sex": "SEX",
|
||||
"BIDS - Hand": "HAND",
|
||||
"BIDS - Handedness": "HAND",
|
||||
}
|
||||
|
||||
|
||||
@@ -488,6 +491,46 @@ class GroupAssignmentDialog(QDialog):
|
||||
return mappings
|
||||
|
||||
|
||||
|
||||
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):
|
||||
@@ -623,10 +666,10 @@ class MainApplication(QMainWindow):
|
||||
self.left_v_splitter.setChildrenCollapsible(False)
|
||||
self.left_v_splitter.setMinimumWidth(460)
|
||||
|
||||
top_left_container = QGroupBox("File information")
|
||||
top_left_container.setStyleSheet("QGroupBox { font-weight: bold; }")
|
||||
top_left_container.setMinimumHeight(240)
|
||||
top_left_layout = QHBoxLayout(top_left_container)
|
||||
self.top_left_container = QGroupBox("File Information")
|
||||
self.top_left_container.setStyleSheet("QGroupBox { font-weight: bold; }")
|
||||
self.top_left_container.setMinimumHeight(240)
|
||||
top_left_layout = QHBoxLayout(self.top_left_container)
|
||||
|
||||
self.top_left_widget = QTextEdit()
|
||||
self.top_left_widget.setReadOnly(True)
|
||||
@@ -639,22 +682,25 @@ class MainApplication(QMainWindow):
|
||||
font_metrics = QFontMetrics(self.font())
|
||||
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():
|
||||
row_layout = QHBoxLayout()
|
||||
row_layout.setContentsMargins(0, 0, 0, 0)
|
||||
row_layout.setSpacing(0)
|
||||
|
||||
label = QLabel(key.capitalize() + ":")
|
||||
self.meta_labels[key] = label
|
||||
label.setFixedWidth(label_width)
|
||||
row_layout.addWidget(label)
|
||||
row_layout.addWidget(field)
|
||||
right_column_layout.addLayout(row_layout)
|
||||
field.textChanged.connect(self.sync_bubble_data)
|
||||
|
||||
label_desc = QLabel('<a href="#">Why are these useful?</a>')
|
||||
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."))
|
||||
right_column_layout.addWidget(label_desc)
|
||||
self.label_desc = QLabel('<a href="#">Why are these useful?</a>')
|
||||
self.label_desc.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
|
||||
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(self.label_desc)
|
||||
right_column_layout.addStretch()
|
||||
self.right_column_widget.hide()
|
||||
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.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.right_container = QWidget()
|
||||
@@ -825,6 +871,31 @@ class MainApplication(QMainWindow):
|
||||
self.pref_actions = {}
|
||||
|
||||
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 = [
|
||||
("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"),
|
||||
@@ -851,6 +922,31 @@ class MainApplication(QMainWindow):
|
||||
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):
|
||||
self.current_section_index = index
|
||||
|
||||
@@ -1119,6 +1215,8 @@ class MainApplication(QMainWindow):
|
||||
data_map["fig_bytes_dict"],
|
||||
data_map["contrast_results_dict"],
|
||||
data_map["roi_channel_map_dict"],
|
||||
data_map["fir_feature_dict"],
|
||||
data_map["qc_dict"],
|
||||
self.folding_bypass,
|
||||
]
|
||||
|
||||
@@ -1137,6 +1235,19 @@ class MainApplication(QMainWindow):
|
||||
self.top_left_widget.paste() # Trigger paste
|
||||
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):
|
||||
"""Helper to update memory configuration and save to disk."""
|
||||
# configparser expects string values
|
||||
@@ -1334,7 +1445,6 @@ class MainApplication(QMainWindow):
|
||||
def apply_splitter_ratios(self):
|
||||
"""Applies saved ratio positions to main_h_splitter and left_v_splitter."""
|
||||
if hasattr(self, 'main_h_splitter'):
|
||||
print("Splitter actual width:", self.main_h_splitter.width())
|
||||
total_width = self.main_h_splitter.width()
|
||||
if total_width > 0:
|
||||
left_w = int(total_width * self.main_h_ratio)
|
||||
@@ -1836,7 +1946,7 @@ class MainApplication(QMainWindow):
|
||||
if self.button3.isVisible():
|
||||
msg = QMessageBox(self)
|
||||
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
|
||||
msg.setStandardButtons(QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel)
|
||||
@@ -1852,11 +1962,18 @@ class MainApplication(QMainWindow):
|
||||
else:
|
||||
return
|
||||
|
||||
self.button3.setVisible(False)
|
||||
self.button3.setVisible(False)
|
||||
|
||||
for item in DATA_SCHEMA:
|
||||
setattr(self, item["key"], {})
|
||||
for item in DATA_SCHEMA:
|
||||
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.setText("Cancel")
|
||||
self.button1.clicked.connect(self.cancel_task)
|
||||
@@ -2182,10 +2299,11 @@ class MainApplication(QMainWindow):
|
||||
return
|
||||
|
||||
for widget in list(QApplication.topLevelWidgets()):
|
||||
if widget is not self:
|
||||
if not widget.close():
|
||||
event.ignore()
|
||||
return
|
||||
if widget is not self and widget.isWindow() and not isinstance(widget, QMenu):
|
||||
try:
|
||||
widget.close()
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
if hasattr(self, 'loading_session_id'):
|
||||
self.loading_session_id += 1
|
||||
@@ -2648,11 +2766,14 @@ if __name__ == "__main__":
|
||||
|
||||
# Only run GUI in the main process
|
||||
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)
|
||||
icon_ext = "icns" if PLATFORM_NAME == "darwin" else "ico"
|
||||
app.setWindowIcon(QIcon(resource_path(f"icons/main.{icon_ext}")))
|
||||
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.show()
|
||||
sys.exit(app.exec())
|
||||
|
||||
@@ -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"])
|
||||
+44
-34
@@ -6,40 +6,47 @@ Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
# Built-in imports
|
||||
import os
|
||||
import sys
|
||||
import copy
|
||||
import pickle
|
||||
import concurrent
|
||||
import configparser
|
||||
from pathlib import Path, PurePosixPath
|
||||
from typing import TYPE_CHECKING, Any, List, Optional, Union
|
||||
|
||||
# External library imports
|
||||
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.QtGui import QAction
|
||||
|
||||
from mne.io import read_raw_snirf
|
||||
from mne.preprocessing.nirs import source_detector_distances
|
||||
from mne_nirs.channels import get_short_channels # type: ignore
|
||||
from mne.io import read_raw_snirf # type: ignore
|
||||
from mne.preprocessing.nirs import source_detector_distances # type: ignore
|
||||
from mne_nirs.channels import get_short_channels # type: ignore
|
||||
|
||||
from src.shared.flaresbasewidget import ProgressBubble
|
||||
from src.shared.shareddata import APP_NAME, CURRENT_VERSION, PLATFORM_NAME, DATA_SCHEMA
|
||||
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from main import MainApplication
|
||||
|
||||
|
||||
class SaveProjectThread(QThread):
|
||||
finished_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__()
|
||||
self.filename = filename
|
||||
self.project_data = project_data
|
||||
|
||||
def run(self):
|
||||
def run(self) -> None:
|
||||
try:
|
||||
with open(self.filename, "wb") as f:
|
||||
pickle.dump(self.project_data, f)
|
||||
@@ -50,7 +57,7 @@ class SaveProjectThread(QThread):
|
||||
|
||||
|
||||
class SavingOverlay(QDialog):
|
||||
def __init__(self, parent=None):
|
||||
def __init__(self, parent: Optional[QWidget] = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.FramelessWindowHint)
|
||||
self.setModal(True)
|
||||
@@ -75,7 +82,11 @@ class ProjectManager:
|
||||
- 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.file_cfg = file_cfg
|
||||
self.cfg_path = cfg_path
|
||||
@@ -83,7 +94,7 @@ class ProjectManager:
|
||||
# =========================================================================
|
||||
# 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."""
|
||||
try:
|
||||
target = Path(target_path).resolve()
|
||||
@@ -96,7 +107,7 @@ class ProjectManager:
|
||||
# =========================================================================
|
||||
# File & Folder Opening Dialogs
|
||||
# =========================================================================
|
||||
def open_file_dialog(self):
|
||||
def open_file_dialog(self) -> None:
|
||||
"""Opens dialog to pick a single .snirf file."""
|
||||
file_path, _ = QFileDialog.getOpenFileName(
|
||||
self.app, "Open File", "", "SNIRF Files (*.snirf);;All Files (*)"
|
||||
@@ -104,14 +115,14 @@ class ProjectManager:
|
||||
if 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."""
|
||||
folder_path = QFileDialog.getExistingDirectory(self.app, "Select Folder", "")
|
||||
if folder_path:
|
||||
snirf_files = [os.path.normpath(str(f)) for f in Path(folder_path).rglob("*.snirf")]
|
||||
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."""
|
||||
app = self.app
|
||||
if not file_paths:
|
||||
@@ -151,7 +162,7 @@ class ProjectManager:
|
||||
# Queue chunked widget creation
|
||||
CHUNK_SIZE = 10
|
||||
|
||||
def process_chunk(file_queue):
|
||||
def process_chunk(file_queue: List[str]) -> None:
|
||||
chunk = file_queue[:CHUNK_SIZE]
|
||||
remaining = file_queue[CHUNK_SIZE:]
|
||||
|
||||
@@ -187,7 +198,7 @@ class ProjectManager:
|
||||
|
||||
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."""
|
||||
app = self.app
|
||||
normalized_paths = [os.path.normpath(p) for p in file_paths]
|
||||
@@ -220,7 +231,7 @@ class ProjectManager:
|
||||
# =========================================================================
|
||||
# Project Loading
|
||||
# =========================================================================
|
||||
def load_project_dialog(self):
|
||||
def load_project_dialog(self) -> None:
|
||||
"""Prompts for a project file and loads it."""
|
||||
app = self.app
|
||||
filename, _ = QFileDialog.getOpenFileName(
|
||||
@@ -229,7 +240,7 @@ class ProjectManager:
|
||||
if 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."""
|
||||
app = self.app
|
||||
try:
|
||||
@@ -325,7 +336,7 @@ class ProjectManager:
|
||||
|
||||
has_data = any(len(getattr(app, item["key"], {})) > 0 for item in DATA_SCHEMA)
|
||||
if hasattr(app, "button1"):
|
||||
app.button1.setVisible(not has_data)
|
||||
app.button1.setVisible(has_data)
|
||||
if hasattr(app, "button3"):
|
||||
app.button3.setVisible(has_data)
|
||||
|
||||
@@ -343,7 +354,7 @@ class ProjectManager:
|
||||
# =========================================================================
|
||||
# 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.
|
||||
- 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]
|
||||
|
||||
# 5. Build Serialized Payload
|
||||
project_data = {
|
||||
project_data: dict[str, Any] = {
|
||||
item["key"]: getattr(app, item["key"], {}) for item in DATA_SCHEMA
|
||||
}
|
||||
project_data.update({
|
||||
@@ -448,7 +459,7 @@ class ProjectManager:
|
||||
"current_ui_params": current_params,
|
||||
})
|
||||
|
||||
def sanitize(obj):
|
||||
def sanitize(obj: Any) -> Any:
|
||||
if isinstance(obj, Path):
|
||||
return str(PurePosixPath(obj))
|
||||
elif isinstance(obj, dict):
|
||||
@@ -469,7 +480,7 @@ class ProjectManager:
|
||||
|
||||
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"):
|
||||
app.saving_overlay.close()
|
||||
|
||||
@@ -483,7 +494,7 @@ class ProjectManager:
|
||||
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"):
|
||||
app.saving_overlay.close()
|
||||
if not onCrash:
|
||||
@@ -500,7 +511,7 @@ class ProjectManager:
|
||||
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."""
|
||||
app = self.app
|
||||
if not hasattr(app, "recent_projects_menu"):
|
||||
@@ -526,7 +537,7 @@ class ProjectManager:
|
||||
)
|
||||
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."""
|
||||
raw_projects = self.file_cfg.get("File", "recent_projects", fallback="")
|
||||
projects = [p.strip() for p in raw_projects.split(",") if p.strip()]
|
||||
@@ -546,7 +557,7 @@ class ProjectManager:
|
||||
|
||||
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."""
|
||||
if os.path.exists(project_path):
|
||||
print(f"Opening recent project: {project_path}")
|
||||
@@ -577,7 +588,7 @@ class ProjectManager:
|
||||
# =========================================================================
|
||||
# Recent Files Operations
|
||||
# =========================================================================
|
||||
def update_recent_files_menu(self):
|
||||
def update_recent_files_menu(self) -> None:
|
||||
"""Clears and rebuilds the Recent Files submenu items."""
|
||||
app = self.app
|
||||
if not hasattr(app, "recent_files_menu"):
|
||||
@@ -600,7 +611,7 @@ class ProjectManager:
|
||||
)
|
||||
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."""
|
||||
raw_files = self.file_cfg.get("File", "recent_files", fallback="")
|
||||
files = [f.strip() for f in raw_files.split(",") if f.strip()]
|
||||
@@ -620,7 +631,7 @@ class ProjectManager:
|
||||
|
||||
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."""
|
||||
if os.path.exists(file_path):
|
||||
print(f"Opening recent file: {file_path}")
|
||||
@@ -647,11 +658,11 @@ class ProjectManager:
|
||||
# =========================================================================
|
||||
# Baseline Synchronization & Dirty Checks
|
||||
# =========================================================================
|
||||
def sync_metadata_baseline(self):
|
||||
def sync_metadata_baseline(self) -> None:
|
||||
"""Captures current file_metadata state as baseline."""
|
||||
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."""
|
||||
current_meta = getattr(self.app, "file_metadata", {})
|
||||
saved_meta = getattr(self.app, "saved_file_metadata", {})
|
||||
@@ -671,7 +682,7 @@ class ProjectManager:
|
||||
|
||||
return False
|
||||
|
||||
def reset_all_dirty_states(self):
|
||||
def reset_all_dirty_states(self) -> None:
|
||||
"""Resets parameter, file, and metadata baselines after load/save."""
|
||||
# 1. Sync file list baseline
|
||||
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]:
|
||||
"""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) -
|
||||
@@ -708,7 +718,7 @@ def _get_bids_demographics(snirf_path: str) -> dict[str, str]:
|
||||
if not sub_id:
|
||||
return {}
|
||||
|
||||
def _row_to_dict(row) -> dict[str, str]:
|
||||
def _row_to_dict(row: pd.Series) -> dict[str, str]:
|
||||
result = {}
|
||||
for field in fields:
|
||||
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."""
|
||||
|
||||
# 1. Use preload=False! We only need metadata.
|
||||
|
||||
@@ -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
|
||||
@@ -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}")
|
||||
@@ -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")
|
||||
@@ -9,7 +9,6 @@ License: GPL-3.0
|
||||
|
||||
# Built-in imports
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
# External library imports
|
||||
@@ -27,26 +26,33 @@ from src.shared.shareddata import APP_NAME
|
||||
class ExportToCSVWidget(CSVUIMixin, FlaresBaseWidget):
|
||||
def __init__(
|
||||
self,
|
||||
haemo_dict: dict[str | Path, BaseRaw],
|
||||
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],
|
||||
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:
|
||||
|
||||
super().__init__("ExportToCSV")
|
||||
self.setWindowTitle(f"Export To CSV Viewer - {APP_NAME.upper()}")
|
||||
self.haemo_dict = haemo_dict
|
||||
self.cha_dict = cha_dict
|
||||
# self.df_ind = df_ind_dict
|
||||
# self.design_matrix = design_matrix_dict
|
||||
# self.contrast_results_dict = contrast_results_dict
|
||||
# self.group = group_dict
|
||||
self.df_ind_dict = df_ind_dict
|
||||
self.design_matrix = design_matrix_dict
|
||||
self.contrast_results_dict = contrast_results_dict
|
||||
self.group_dict = group_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):
|
||||
@@ -114,6 +120,68 @@ class ExportToCSVWidget(CSVUIMixin, FlaresBaseWidget):
|
||||
magic_string = self.gen_magic_str(first_params)
|
||||
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:
|
||||
print(f"No method defined for index {idx}")
|
||||
|
||||
@@ -134,7 +202,7 @@ class ExportToCSVWidget(CSVUIMixin, FlaresBaseWidget):
|
||||
# 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. "
|
||||
if all_params['DOWNSAMPLE']:
|
||||
|
||||
@@ -7,52 +7,22 @@ Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in Imports
|
||||
from pathlib import Path
|
||||
# Built-in imports
|
||||
from typing import Any, cast
|
||||
|
||||
# External library imports
|
||||
from mne.io.base import BaseRaw
|
||||
|
||||
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 flares import aggregate_fnirs_group_geometry, plot_2d_3d_contrasts_between_groups
|
||||
from src.shared.flaresbasewidget import InterGroupUIMixin, 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": "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",
|
||||
"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",
|
||||
"label": "Display informative text on the top left corner. THIS DOES NOT WORK AND SHOULD BE LEFT AT FALSE",
|
||||
"default": "False",
|
||||
"label": "Display informative text on the top left corner about the contrast.",
|
||||
"default": "True",
|
||||
"type": bool,
|
||||
},
|
||||
{
|
||||
@@ -76,145 +46,118 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
|
||||
"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,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
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):
|
||||
def __init__(
|
||||
self,
|
||||
haemo_dict: dict[str | Path, BaseRaw],
|
||||
cha_dict: dict[str, DataFrame],
|
||||
haemo_dict: dict[str, 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]
|
||||
group_dict: dict[str, str],
|
||||
) -> None:
|
||||
|
||||
|
||||
super().__init__("InterGroupBrainImage")
|
||||
self.setWindowTitle(f"Inter-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_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):
|
||||
|
||||
request = self.get_common_request_data(PARAMETERIZED_INDEXES)
|
||||
if request is None:
|
||||
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)
|
||||
|
||||
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)
|
||||
# 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:
|
||||
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)
|
||||
print(f"Event '{event}' not found for {fp}")
|
||||
return group_df
|
||||
|
||||
# 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)
|
||||
print("Selected event:", selected_event)
|
||||
print("File paths A:", file_paths_a)
|
||||
print("File paths B:", file_paths_b)
|
||||
|
||||
df_group = pd.DataFrame()
|
||||
contrast_df_a = concat_group_contrasts(file_paths_a, selected_event)
|
||||
contrast_df_b = concat_group_contrasts(file_paths_b, selected_event)
|
||||
|
||||
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)
|
||||
|
||||
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, {})
|
||||
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)
|
||||
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:
|
||||
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
|
||||
|
||||
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)
|
||||
|
||||
elif idx == 3:
|
||||
pass
|
||||
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}")
|
||||
@@ -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}")
|
||||
+177
-225
@@ -8,17 +8,15 @@ 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 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 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.shareddata import APP_NAME
|
||||
|
||||
@@ -34,7 +32,7 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
|
||||
{
|
||||
"key": "min_subjects",
|
||||
"label": "Minimum number of participants to process",
|
||||
"default": "5",
|
||||
"default": "3",
|
||||
"type": int,
|
||||
},
|
||||
{
|
||||
@@ -50,10 +48,10 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
|
||||
"type": str,
|
||||
},
|
||||
{
|
||||
"key": "graph_bounds",
|
||||
"label": "Graph Upper/Lower Limit",
|
||||
"default": "0.0",
|
||||
"type": float,
|
||||
"key": "threshold_topo",
|
||||
"label": "threshold_topo: TBD",
|
||||
"default": False,
|
||||
"type": bool,
|
||||
}
|
||||
],
|
||||
1: [
|
||||
@@ -66,7 +64,7 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
|
||||
{
|
||||
"key": "min_subjects",
|
||||
"label": "Minimum number of participants to process",
|
||||
"default": "5",
|
||||
"default": "3",
|
||||
"type": int,
|
||||
},
|
||||
{
|
||||
@@ -104,7 +102,7 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
|
||||
{
|
||||
"key": "min_subjects",
|
||||
"label": "Minimum number of participants to process",
|
||||
"default": "5",
|
||||
"default": "3",
|
||||
"type": int,
|
||||
},
|
||||
{
|
||||
@@ -125,31 +123,19 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
|
||||
"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.
|
||||
DESCRIPTION = """0. Raw ROI Comparison (run_inter_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_inter_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_inter_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.
|
||||
@@ -157,9 +143,10 @@ DESCRIPTION = """0. ROI vs. Zero (run_roi_second_level_analysis)
|
||||
|
||||
|
||||
class InterGroupStatsWidget(InterGroupUIMixin, FlaresBaseWidget):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
haemo_dict: dict[str | Path, BaseRaw],
|
||||
haemo_dict: dict[str, BaseRaw],
|
||||
cha_dict: dict[str, DataFrame],
|
||||
df_ind_dict: dict[str, DataFrame],
|
||||
design_matrix_dict: dict[str, DataFrame],
|
||||
@@ -178,226 +165,191 @@ class InterGroupStatsWidget(InterGroupUIMixin, FlaresBaseWidget):
|
||||
self.roi_channel_map_dict = roi_channel_map_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):
|
||||
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
|
||||
(selected_event, file_paths_a, file_paths_b, _, 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)
|
||||
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()
|
||||
|
||||
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)
|
||||
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", 5)
|
||||
min_subjects = params.get("min_subjects", 3)
|
||||
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 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,
|
||||
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
|
||||
|
||||
print(min_subjects)
|
||||
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)
|
||||
threshold_topo = params.get("threshold_topo", False)
|
||||
|
||||
selected_roi_maps = {
|
||||
fp: self.roi_channel_map_dict[fp]
|
||||
for fp in selected_file_paths
|
||||
for fp in (file_paths_a + file_paths_b)
|
||||
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
|
||||
|
||||
# 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,
|
||||
run_inter_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,
|
||||
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:
|
||||
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_inter_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_inter_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(f"No method defined for index {idx}")
|
||||
print("no")
|
||||
@@ -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}")
|
||||
@@ -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}")
|
||||
@@ -8,7 +8,6 @@ License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in imports
|
||||
from pathlib import Path
|
||||
from typing import Any, cast
|
||||
|
||||
# External library imports
|
||||
@@ -69,7 +68,7 @@ PARAMETERIZED_INDEXES: dict[int, list[dict[str, Any]]] = {
|
||||
class ParticipantBrainViewerWidget(ParticipantUIMixin, FlaresBaseWidget):
|
||||
def __init__(
|
||||
self,
|
||||
haemo_dict: dict[str | Path, BaseRaw],
|
||||
haemo_dict: dict[str, BaseRaw],
|
||||
cha_dict: dict[str, DataFrame],
|
||||
) -> None:
|
||||
|
||||
|
||||
@@ -6,11 +6,16 @@ Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in Imports
|
||||
import os
|
||||
from pathlib import Path
|
||||
import time
|
||||
import traceback
|
||||
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 matplotlib.pyplot as plt
|
||||
@@ -18,25 +23,27 @@ import matplotlib.image as mpimg
|
||||
from matplotlib.figure import Figure
|
||||
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.QtCore import QThread, Qt, QSize, QTimer
|
||||
from PySide6.QtGui import QPixmap, QImage
|
||||
from PySide6.QtWidgets import QFrame, QGridLayout, QHBoxLayout, QLabel, QLayout, QProgressBar, QPushButton, QScrollArea, QSizePolicy, QWidget, QDialog, QVBoxLayout
|
||||
from PySide6.QtCore import QThread, Qt, QSize, QTimer, QObject, Signal
|
||||
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.shareddata import APP_NAME, resource_path
|
||||
|
||||
|
||||
class MultiProgressDialog(QDialog):
|
||||
def __init__(self, parent=None):
|
||||
def __init__(self, parent: Optional[QWidget] = None) -> None:
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("fOLD Analysis Progress")
|
||||
self.setFixedWidth(400)
|
||||
self.setWindowModality(Qt.WindowModality.NonModal)
|
||||
self.layout = QVBoxLayout(self)
|
||||
self.bars = {}
|
||||
self.main_layout = QVBoxLayout(self)
|
||||
self.bars: Dict[str, QProgressBar] = {}
|
||||
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()
|
||||
label_widget = QLabel(f"Analyzing {clean_key}...")
|
||||
pbar = QProgressBar()
|
||||
@@ -44,16 +51,17 @@ class MultiProgressDialog(QDialog):
|
||||
pbar.setMaximum(int(total_steps)) # Ensure this is a strict integer
|
||||
pbar.setValue(0)
|
||||
|
||||
self.layout.addWidget(label_widget)
|
||||
self.layout.addWidget(pbar)
|
||||
self.bars[label] = pbar
|
||||
self.main_layout.addWidget(label_widget)
|
||||
self.main_layout.addWidget(pbar)
|
||||
self.bars[clean_key] = pbar
|
||||
|
||||
def update_bar(self, label, value):
|
||||
if label in self.bars:
|
||||
def update_bar(self, label: Any, value: Union[int, float, str]) -> None:
|
||||
clean_key = str(label).strip()
|
||||
if clean_key in self.bars:
|
||||
# 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:
|
||||
event.accept()
|
||||
else:
|
||||
@@ -64,8 +72,13 @@ class MultiProgressDialog(QDialog):
|
||||
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 """
|
||||
p_name = os.path.basename(file_path)
|
||||
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)}")
|
||||
|
||||
|
||||
|
||||
def get_landmark_color_map():
|
||||
def get_landmark_color_map() -> Dict[str, Tuple[float, float, float, float]]:
|
||||
"""Generates the unified 40-color map for fOLD landmarks."""
|
||||
landmarks = [
|
||||
"1 - Primary Somatosensory Cortex", "2 - Primary Somatosensory Cortex",
|
||||
@@ -116,7 +128,15 @@ class StaticChannelCanvas(FigureCanvas):
|
||||
"""The Pop-up Window Canvas.
|
||||
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.ax = self.fig.subplots(1, 2)
|
||||
@@ -194,7 +214,7 @@ class StaticChannelCanvas(FigureCanvas):
|
||||
|
||||
self.mpl_connect('motion_notify_event', self._on_hover)
|
||||
|
||||
def _on_hover(self, event):
|
||||
def _on_hover(self, event: Event) -> None:
|
||||
try:
|
||||
# FIX: Only track mouse events when hovering over the LEFT axis frame containing the pie chart
|
||||
if event.inaxes != self.ax[0]:
|
||||
@@ -231,10 +251,10 @@ class StaticChannelCanvas(FigureCanvas):
|
||||
self.draw_idle()
|
||||
|
||||
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()
|
||||
|
||||
def _explode_wedge(self, index_to_expand):
|
||||
def _explode_wedge(self, index_to_expand: int) -> None:
|
||||
changed = False
|
||||
for idx, wedge in enumerate(self.wedges):
|
||||
if idx == index_to_expand:
|
||||
@@ -252,7 +272,7 @@ class StaticChannelCanvas(FigureCanvas):
|
||||
if changed:
|
||||
self.draw_idle()
|
||||
|
||||
def _reset_wedges(self):
|
||||
def _reset_wedges(self) -> None:
|
||||
changed = False
|
||||
for wedge in self.wedges:
|
||||
if wedge.center != (0.0, 0.0):
|
||||
@@ -274,7 +294,7 @@ class StandaloneLegendDialog(QWidget):
|
||||
layout.setContentsMargins(10, 10, 10, 10)
|
||||
|
||||
# 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)
|
||||
|
||||
|
||||
@@ -381,7 +401,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
|
||||
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."""
|
||||
# 1. Create matching styled container card frame
|
||||
card_frame = QFrame()
|
||||
@@ -422,7 +442,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
|
||||
layout_to_attach_to.addWidget(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
|
||||
if event.inaxes is None:
|
||||
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.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."""
|
||||
totals = {}
|
||||
num_channels = len(channels_data)
|
||||
@@ -553,7 +574,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
|
||||
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."""
|
||||
# 1. Calculate the normalized profile data payload using the instance's own 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.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
|
||||
if event.button() == Qt.MouseButton.LeftButton:
|
||||
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.setStyleSheet("QFrame { background-color: #ffffff; border-radius: 8px; border: 1px solid #e9ecef; }")
|
||||
|
||||
@@ -686,7 +707,7 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
|
||||
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."""
|
||||
popup = QWidget(None)
|
||||
popup.setWindowTitle(f"Grand Total Profile Details - {title_prefix}")
|
||||
@@ -719,16 +740,18 @@ class InteractiveParticipantGridCanvas(FigureCanvas):
|
||||
self._summary_popups.append(popup)
|
||||
|
||||
|
||||
from PySide6.QtCore import QObject, Signal
|
||||
from multiprocessing import Manager, Process
|
||||
|
||||
class ProcessOrchestrator(QObject):
|
||||
# Fires when Manager + Processes are completely ready
|
||||
# Emits: (manager_instance, result_queue, progress_queue, active_processes_list)
|
||||
setup_finished = Signal(object, object, object, list)
|
||||
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__()
|
||||
self.selected_files = selected_files
|
||||
self.haemo_dict = haemo_dict
|
||||
@@ -758,7 +781,12 @@ class ProcessOrchestrator(QObject):
|
||||
|
||||
|
||||
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")
|
||||
self.setWindowTitle(f"Participant Fold Channels Viewer - {APP_NAME.upper()}")
|
||||
self.haemo_dict = haemo_dict
|
||||
@@ -773,9 +801,9 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
self.participant_map[file_path] = short_label
|
||||
self.participant_dropdown_items.append(display_label)
|
||||
|
||||
self.layout = QVBoxLayout(self)
|
||||
self.main_layout = QVBoxLayout(self)
|
||||
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.currentIndexChanged.connect(self.update_participant_dropdown_label)
|
||||
@@ -803,11 +831,10 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
self.scroll_area.setWidgetResizable(True)
|
||||
self.scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
|
||||
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
|
||||
self.scroll_content_widget = QWidget()
|
||||
self.scroll_content_widget.setStyleSheet("background-color: #f1f3f5;")
|
||||
|
||||
# 3. Establish the strict 3-column layout grid engine
|
||||
self.grid_layout = QGridLayout(self.scroll_content_widget)
|
||||
@@ -829,7 +856,7 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
self.scroll_area.setWidget(self.scroll_content_widget)
|
||||
|
||||
# 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.showMaximized()
|
||||
@@ -889,7 +916,14 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
self.orchestrator_thread.start()
|
||||
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 """
|
||||
self.manager = manager
|
||||
self.result_queue = result_queue
|
||||
@@ -902,15 +936,15 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
self.result_timer.timeout.connect(self.check_parallel_results)
|
||||
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 """
|
||||
if hasattr(self, 'multi_progress'):
|
||||
self.multi_progress.close()
|
||||
print(f"[CRITICAL FAILURE] Background Orchestration Failed:\n{error_msg}")
|
||||
|
||||
|
||||
|
||||
def check_parallel_results(self):
|
||||
def check_parallel_results(self) -> None:
|
||||
# Check for progress/completion signals
|
||||
|
||||
while not self.progress_queue.empty():
|
||||
@@ -991,8 +1025,7 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
|
||||
legend_title = "Grand Total Brodmann Mapping Profile"
|
||||
legend_card = global_canvas.create_legend_card(
|
||||
title_prefix=legend_title,
|
||||
layout_to_attach_to=self.scroll_content_widget.layout()
|
||||
title_prefix=legend_title
|
||||
)
|
||||
|
||||
def handle_legend_click(event):
|
||||
@@ -1006,52 +1039,8 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
col = count % 3
|
||||
self.grid_layout.addWidget(legend_card, row, col)
|
||||
|
||||
|
||||
|
||||
|
||||
# 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):
|
||||
def add_images_to_grid(self, result_dict: Dict[str, Dict[str, Any]]) -> None:
|
||||
color_map = get_landmark_color_map()
|
||||
|
||||
for file_path, channels_data in result_dict.items():
|
||||
@@ -1091,12 +1080,12 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
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."""
|
||||
image = QImage.fromData(png_bytes)
|
||||
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."""
|
||||
view = QDialog(self)
|
||||
view.setWindowTitle(f"Full View - {title}")
|
||||
@@ -1106,7 +1095,7 @@ class ParticipantFoldChannelsWidget(FlaresBaseWidget):
|
||||
layout.addWidget(label)
|
||||
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."""
|
||||
container = QFrame()
|
||||
container.setStyleSheet("background-color: #f9f9f9; border: 1px solid #ccc;")
|
||||
|
||||
@@ -7,16 +7,13 @@ Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in Imports
|
||||
from pathlib import Path
|
||||
# Built-in imports
|
||||
from typing import Any, cast
|
||||
|
||||
# External library imports
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
|
||||
from pandas import DataFrame
|
||||
|
||||
from mne import Annotations
|
||||
from mne import Annotations, Epochs
|
||||
from mne.io.base import BaseRaw
|
||||
|
||||
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]]] = {
|
||||
0: [
|
||||
{
|
||||
"key": "n_lines",
|
||||
"label": "<Description>",
|
||||
"default": "20",
|
||||
"type": int,
|
||||
},
|
||||
{
|
||||
"key": "vmin",
|
||||
"label": "<Description>",
|
||||
"default": "0.9",
|
||||
"type": float,
|
||||
},
|
||||
0: [ # 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 coherence value to display", "default": "0.3", "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},
|
||||
],
|
||||
1: [
|
||||
{
|
||||
"key": "n_lines",
|
||||
"label": "<Description>",
|
||||
"default": "20",
|
||||
"type": int,
|
||||
},
|
||||
{
|
||||
"key": "vmin",
|
||||
"label": "<Description>",
|
||||
"default": "0.9",
|
||||
"type": float,
|
||||
},
|
||||
|
||||
1: [ # Envelope Correlation
|
||||
{"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
|
||||
{"key": "vmin", "label": "Minimum correlation value to display", "default": "0.9", "type": float},
|
||||
{"key": "fmin", "label": "Band-pass lower frequency (Hz)", "default": "0.04", "type": float},
|
||||
{"key": "fmax", "label": "Band-pass upper frequency (Hz)", "default": "0.2", "type": float},
|
||||
{"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},
|
||||
],
|
||||
2: [
|
||||
{
|
||||
"key": "n_lines",
|
||||
"label": "<Description>",
|
||||
"default": "20",
|
||||
"type": int,
|
||||
},
|
||||
{
|
||||
"key": "vmin",
|
||||
"label": "<Description>",
|
||||
"default": "0.9",
|
||||
"type": float,
|
||||
},
|
||||
|
||||
2: [ # Beta-Series Correlation
|
||||
{"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
|
||||
{"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": "min_effect_size", "label": "Minimum |r| to display", "default": "0.7", "type": float},
|
||||
{"key": "alpha", "label": "FDR significance threshold", "default": "0.05", "type": float},
|
||||
],
|
||||
3: [
|
||||
{
|
||||
"key": "n_lines",
|
||||
"label": "<Description>",
|
||||
"default": "20",
|
||||
"type": int,
|
||||
},
|
||||
{
|
||||
"key": "vmin",
|
||||
"label": "<Description>",
|
||||
"default": "0.9",
|
||||
"type": float,
|
||||
},
|
||||
|
||||
3: [ # Time-Resolved Spectral Coherence
|
||||
{"key": "method", "label": "Connectivity method", "default": "wpli", "type": list, "options": ["coh", "pli", "wpli"]},
|
||||
{"key": "n_lines", "label": "Number of strongest connections to draw", "default": "20", "type": int},
|
||||
{"key": "vmin", "label": "Minimum coherence value to display", "default": "0.3", "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": "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},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
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):
|
||||
def __init__(
|
||||
self,
|
||||
haemo_dict: dict[str | Path, BaseRaw],
|
||||
epochs_dict: dict[str, DataFrame],
|
||||
haemo_dict: dict[str, BaseRaw],
|
||||
epochs_dict: dict[str, Epochs],
|
||||
) -> None:
|
||||
|
||||
super().__init__("ParticipantFunctionalConnectivity")
|
||||
@@ -99,11 +89,12 @@ class ParticipantFunctionalConnectivityWidget(ParticipantUIMixin, FlaresBaseWidg
|
||||
self.haemo_dict = haemo_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. "
|
||||
"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)",])
|
||||
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.")
|
||||
|
||||
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):
|
||||
request = self.get_common_request_data(PARAMETERIZED_INDEXES)
|
||||
@@ -117,9 +108,9 @@ class ParticipantFunctionalConnectivityWidget(ParticipantUIMixin, FlaresBaseWidg
|
||||
# Pass the necessary arguments to each method
|
||||
for file_path in selected_file_paths:
|
||||
haemo_obj = self.haemo_dict.get(file_path)
|
||||
epochs_obj = self.epochs_dict.get(file_path)
|
||||
|
||||
if haemo_obj is None:
|
||||
epochs_obj = self.epochs_dict.get(file_path)
|
||||
|
||||
if haemo_obj is None or epochs_obj is None:
|
||||
continue
|
||||
|
||||
if selected_event:
|
||||
@@ -137,46 +128,75 @@ class ParticipantFunctionalConnectivityWidget(ParticipantUIMixin, FlaresBaseWidg
|
||||
continue
|
||||
|
||||
for idx in selected_indexes:
|
||||
params = param_values.get(idx, {})
|
||||
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
|
||||
functional_connectivity_spectral_epochs(epochs_obj, n_lines, vmin)
|
||||
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)
|
||||
|
||||
functional_connectivity_spectral_epochs(epochs=epochs_obj, n_lines=n_lines, vmin=vmin, fmin=fmin, fmax=fmax, method=method)
|
||||
|
||||
elif idx == 1:
|
||||
params = param_values.get(idx, {})
|
||||
n_lines = params.get("n_lines", None)
|
||||
vmin = params.get("vmin", None)
|
||||
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)
|
||||
orthogonalize = params.get("orthogonalize", False)
|
||||
absolute = params.get("absolute", True)
|
||||
|
||||
functional_connectivity_envelope(
|
||||
epochs=epochs_obj,
|
||||
n_lines=n_lines,
|
||||
vmin=vmin, fmin=fmin,
|
||||
fmax=fmax,
|
||||
orthogonalize=orthogonalize,
|
||||
absolute=absolute,
|
||||
)
|
||||
|
||||
if n_lines is None or vmin is None:
|
||||
print(f"Missing parameters for index {idx}, skipping.")
|
||||
continue
|
||||
functional_connectivity_envelope(epochs_obj, n_lines, vmin)
|
||||
|
||||
elif idx == 2:
|
||||
params = param_values.get(idx, {})
|
||||
n_lines = params.get("n_lines", None)
|
||||
vmin = params.get("vmin", None)
|
||||
n_lines = params.get("n_lines", 20)
|
||||
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)
|
||||
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:
|
||||
print(f"Missing parameters for index {idx}, skipping.")
|
||||
continue
|
||||
functional_connectivity_betas(haemo_obj, n_lines, vmin, selected_event)
|
||||
functional_connectivity_betas(
|
||||
raw_hbo=haemo_obj,
|
||||
n_lines=n_lines,
|
||||
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:
|
||||
params = param_values.get(idx, {})
|
||||
n_lines = params.get("n_lines", None)
|
||||
vmin = params.get("vmin", None)
|
||||
method = params.get("method", "wpli")
|
||||
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)
|
||||
n_freqs = params.get("n_freqs", 10)
|
||||
cycles_multiplier = params.get("cycles_multiplier", 2.0)
|
||||
|
||||
if n_lines is None or vmin is None:
|
||||
print(f"Missing parameters for index {idx}, skipping.")
|
||||
continue
|
||||
functional_connectivity_spectral_time(epochs_obj, n_lines, vmin)
|
||||
functional_connectivity_spectral_time(
|
||||
epochs=epochs_obj,
|
||||
n_lines=n_lines,
|
||||
vmin=vmin,
|
||||
fmin=fmin,
|
||||
fmax=fmax,
|
||||
n_freqs=n_freqs,
|
||||
cycles_multiplier=cycles_multiplier,
|
||||
method=method
|
||||
)
|
||||
|
||||
else:
|
||||
print(f"No method defined for index {idx}")
|
||||
@@ -7,7 +7,7 @@ Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in Imports
|
||||
# Built-in imports
|
||||
import os.path as op
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
@@ -24,10 +24,9 @@ from src.shared.shareddata import APP_NAME
|
||||
|
||||
|
||||
class ParticipantImageViewerWidget(FlaresBaseWidget):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
haemo_dict: dict[str, BaseRaw],
|
||||
haemo_dict: dict[str, BaseRaw],
|
||||
fig_bytes_dict: dict[str, dict[str, bytes]]
|
||||
) -> None:
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import pandas as pd
|
||||
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.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 src.shared.shareddata import APP_NAME, PIPELINE_STAGES
|
||||
@@ -323,10 +323,10 @@ class ParamSection(QWidget):
|
||||
self._updating_checkstates = False
|
||||
|
||||
# Title label
|
||||
title_label = QLabel(section_data["title"])
|
||||
title_label.setStyleSheet("font-weight: bold; font-size: 14px; margin-top: 10px; margin-bottom: 5px;")
|
||||
layout.addWidget(title_label)
|
||||
self.header_widgets.append(title_label)
|
||||
self.title_label = QLabel(section_data["title"])
|
||||
self.title_label.setStyleSheet("font-weight: bold; font-size: 14px; margin-top: 10px; margin-bottom: 5px;")
|
||||
layout.addWidget(self.title_label)
|
||||
self.header_widgets.append(self.title_label)
|
||||
|
||||
# Horizontal line
|
||||
line = QFrame()
|
||||
@@ -444,6 +444,10 @@ class ParamSection(QWidget):
|
||||
|
||||
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):
|
||||
"""Compares two parameter values to determine if they differ."""
|
||||
type_str = str(param_type).lower()
|
||||
@@ -890,6 +894,7 @@ class ProgressBubble(QWidget):
|
||||
border-radius: 10px;
|
||||
padding: 8px 12px;
|
||||
background-color: #e0f0ff;
|
||||
color: #000000;
|
||||
}
|
||||
""")
|
||||
|
||||
@@ -985,6 +990,13 @@ class ProgressBubble(QWidget):
|
||||
self.spinner_idx += 1
|
||||
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):
|
||||
def __init__(self, caller):
|
||||
@@ -1346,11 +1358,11 @@ class FlaresBaseWidget(QWidget):
|
||||
self.update_participant_dropdown_label(combo=target_combo)
|
||||
|
||||
|
||||
class CrossGroupUIMixin:
|
||||
class InterGroupUIMixin:
|
||||
|
||||
participant_map: dict[str, str]
|
||||
|
||||
def setup_cross_group_ui(
|
||||
def setup_inter_group_ui(
|
||||
self,
|
||||
index_texts: Sequence[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,
|
||||
index_texts: Sequence[str],
|
||||
placeholder_text: str = ""
|
||||
@@ -1877,7 +1889,8 @@ class InterGroupUIMixin:
|
||||
class ParticipantUIMixin:
|
||||
def setup_participant_ui(
|
||||
self,
|
||||
index_texts: Sequence[str]
|
||||
index_texts: Sequence[str],
|
||||
placeholder_text: str = ""
|
||||
) -> None:
|
||||
|
||||
# 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_dropdown_items.append(display_label)
|
||||
|
||||
self.layout = QVBoxLayout(self)
|
||||
self.main_layout = QVBoxLayout(self)
|
||||
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.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.submit_button)
|
||||
|
||||
self.scroll = QScrollArea()
|
||||
self.scroll.setWidgetResizable(True)
|
||||
self.scroll_area = QScrollArea()
|
||||
self.scroll_area.setWidgetResizable(True)
|
||||
self.scroll_content = QWidget()
|
||||
self.grid_layout = QGridLayout(self.scroll_content)
|
||||
self.scroll.setWidget(self.scroll_content)
|
||||
self.layout.addWidget(self.scroll)
|
||||
self.scroll_area.setWidget(self.scroll_content)
|
||||
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.showMaximized()
|
||||
|
||||
@@ -13,7 +13,7 @@ import sys
|
||||
import platform
|
||||
|
||||
|
||||
CURRENT_VERSION = "1.6.0"
|
||||
CURRENT_VERSION = "1.6.1"
|
||||
APP_NAME = "flares"
|
||||
APP_NAME_EXPANDED = "fNIRS Lightweight Analysis, Research, & Evaluation Suite"
|
||||
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": "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": "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"}
|
||||
]
|
||||
|
||||
|
||||
+53
-5
@@ -8,11 +8,13 @@ License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in imports
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
# External library imports
|
||||
from PySide6.QtWidgets import QWidget, QVBoxLayout, QTextEdit, QLineEdit
|
||||
from PySide6.QtCore import Qt, QThread, Signal
|
||||
from PySide6.QtWidgets import QWidget, QVBoxLayout, QTextEdit, QLineEdit, QMainWindow
|
||||
from PySide6.QtCore import QProcess, Qt, QThread, Signal
|
||||
|
||||
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
|
||||
@@ -55,6 +57,8 @@ class TerminalWindow(QWidget):
|
||||
layout.addWidget(self.input_line)
|
||||
self.setLayout(layout)
|
||||
|
||||
self._process: QProcess | None = None
|
||||
|
||||
self.commands: dict[str, Callable[..., Any]] = {
|
||||
"hello": self.cmd_hello,
|
||||
"help": self.cmd_help,
|
||||
@@ -62,6 +66,7 @@ class TerminalWindow(QWidget):
|
||||
"about": self.cmd_about,
|
||||
"assoc": self.cmd_assoc,
|
||||
"update": self.cmd_update,
|
||||
"utest": self.cmd_utest,
|
||||
}
|
||||
|
||||
self._pending_assoc_confirmation: bool = False
|
||||
@@ -107,7 +112,8 @@ class TerminalWindow(QWidget):
|
||||
return "Hello from the terminal!"
|
||||
|
||||
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:
|
||||
return f"{APP_NAME.upper()} is running version {CURRENT_VERSION}."
|
||||
@@ -118,7 +124,7 @@ class TerminalWindow(QWidget):
|
||||
|
||||
def cmd_update(self, *args: Any) -> str:
|
||||
main_win = self.parent()
|
||||
if not isinstance(main_win, QWidget):
|
||||
if not isinstance(main_win, QMainWindow):
|
||||
return "[Error] Main window context not found."
|
||||
|
||||
self.updater = UpdateManager(
|
||||
@@ -163,4 +169,46 @@ class TerminalWindow(QWidget):
|
||||
|
||||
def _on_assoc_result(self, ok: bool, msg: str) -> None:
|
||||
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
@@ -6,19 +6,19 @@ Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in imports
|
||||
import os
|
||||
import json
|
||||
from enum import Enum, auto
|
||||
from datetime import datetime
|
||||
|
||||
import numpy as np
|
||||
from typing import Any, List, Optional, cast
|
||||
|
||||
# External library imports
|
||||
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QLineEdit, QPushButton, QComboBox, QHBoxLayout, QMessageBox, QFileDialog
|
||||
from PySide6.QtCore import Qt
|
||||
|
||||
from mne import Annotations
|
||||
from mne.io import read_raw_snirf
|
||||
from mne_nirs.io import write_raw_snirf
|
||||
from mne.io import read_raw_snirf #type: ignore
|
||||
from mne_nirs.io import write_raw_snirf #type: ignore
|
||||
|
||||
from src.shared.shareddata import APP_NAME
|
||||
|
||||
@@ -29,7 +29,7 @@ class EventUpdateMode(Enum):
|
||||
|
||||
|
||||
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)
|
||||
|
||||
self.mode = mode
|
||||
@@ -91,7 +91,7 @@ class UpdateEventsWindow(QWidget):
|
||||
help_btn_a = QPushButton("?")
|
||||
help_btn_a.setFixedWidth(25)
|
||||
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)
|
||||
|
||||
# Container for label + line_edit + browse button with tooltip
|
||||
@@ -114,7 +114,7 @@ class UpdateEventsWindow(QWidget):
|
||||
help_btn_b = QPushButton("?")
|
||||
help_btn_b.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -136,7 +136,7 @@ class UpdateEventsWindow(QWidget):
|
||||
help_btn_suffix = QPushButton("?")
|
||||
help_btn_suffix.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -157,7 +157,7 @@ class UpdateEventsWindow(QWidget):
|
||||
help_btn_suffix = QPushButton("?")
|
||||
help_btn_suffix.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -177,7 +177,7 @@ class UpdateEventsWindow(QWidget):
|
||||
help_btn_snirf_events = QPushButton("?")
|
||||
help_btn_snirf_events.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -199,13 +199,13 @@ class UpdateEventsWindow(QWidget):
|
||||
|
||||
self.setLayout(layout)
|
||||
|
||||
def show_help_popup(self, text):
|
||||
def show_help_popup(self, text: str) -> None:
|
||||
msg = QMessageBox(self)
|
||||
msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}")
|
||||
msg.setText(text)
|
||||
msg.exec()
|
||||
|
||||
def browse_file_a(self):
|
||||
def browse_file_a(self) -> None:
|
||||
file_path, _ = QFileDialog.getOpenFileName(self, "Select SNIRF File", "", "SNIRF Files (*.snirf)")
|
||||
if 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.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)")
|
||||
if file_path:
|
||||
self.line_edit_file_b.setText(file_path)
|
||||
@@ -252,15 +252,13 @@ class UpdateEventsWindow(QWidget):
|
||||
except (json.JSONDecodeError, FileNotFoundError, KeyError) as 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:
|
||||
raise KeyError("Missing 'observations' key in BORIS file.")
|
||||
|
||||
observations = data["observations"]
|
||||
if not isinstance(observations, dict):
|
||||
raise TypeError("'observations' must be a dictionary.")
|
||||
|
||||
observations = cast(dict[str, Any], data["observations"])
|
||||
return list(observations.keys())
|
||||
|
||||
|
||||
def on_observation_selected(self):
|
||||
selected_obs = self.combo_suffix.currentText()
|
||||
@@ -288,11 +286,11 @@ class UpdateEventsWindow(QWidget):
|
||||
self.combo_events.addItems(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_b.clear()
|
||||
|
||||
def go_action(self):
|
||||
def go_action(self) -> None:
|
||||
|
||||
file_a = self.line_edit_file_a.text()
|
||||
suffix = "flare"
|
||||
@@ -451,7 +449,7 @@ class UpdateEventsWindow(QWidget):
|
||||
save_path += ".json"
|
||||
|
||||
# Build JSON dict
|
||||
json_data = {
|
||||
json_data: dict[str, Any] = {
|
||||
"observation": selected_obs,
|
||||
"snirf_anchor": {"label": snirf_label, "time": snirf_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}")
|
||||
|
||||
|
||||
def update_optode_positions(self, file_a, file_b, save_path):
|
||||
# def update_optode_positions(self, file_a, file_b, save_path):
|
||||
|
||||
fiducials = {}
|
||||
ch_positions = {}
|
||||
# fiducials = {}
|
||||
# ch_positions = {}
|
||||
|
||||
# Read the lines from the optode file
|
||||
with open(file_b, 'r') as f:
|
||||
for line in f:
|
||||
if line.strip():
|
||||
# Split by the semicolon and convert to meters
|
||||
ch_name, coords_str = line.split(":")
|
||||
coords = np.array(list(map(float, coords_str.strip().split()))) * 0.001
|
||||
# # Read the lines from the optode file
|
||||
# with open(file_b, 'r') as f:
|
||||
# for line in f:
|
||||
# if line.strip():
|
||||
# # Split by the semicolon and convert to meters
|
||||
# ch_name, coords_str = line.split(":")
|
||||
# coords = np.array(list(map(float, coords_str.strip().split()))) * 0.001
|
||||
|
||||
# The key we have is a fiducial
|
||||
if ch_name.lower() in ['lpa', 'nz', 'rpa']:
|
||||
fiducials[ch_name.lower()] = coords
|
||||
# # The key we have is a fiducial
|
||||
# if ch_name.lower() in ['lpa', 'nz', 'rpa']:
|
||||
# fiducials[ch_name.lower()] = coords
|
||||
|
||||
# The key we have is a source or detector
|
||||
else:
|
||||
ch_positions[ch_name.upper()] = coords
|
||||
# # The key we have is a source or detector
|
||||
# else:
|
||||
# ch_positions[ch_name.upper()] = coords
|
||||
|
||||
# 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
|
||||
# # 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
|
||||
|
||||
# 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
|
||||
raw = read_raw_snirf(file_a, preload=True)
|
||||
raw.set_montage(initial_montage)
|
||||
write_raw_snirf(raw, save_path)
|
||||
# # 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
|
||||
# raw = read_raw_snirf(file_a, preload=True)
|
||||
# raw.set_montage(initial_montage)
|
||||
# write_raw_snirf(raw, save_path)
|
||||
|
||||
|
||||
def _apply_events_to_snirf(self, raw, new_annotations, save_path):
|
||||
raw.set_annotations(new_annotations)
|
||||
write_raw_snirf(raw, save_path)
|
||||
# def _apply_events_to_snirf(self, raw, new_annotations, save_path):
|
||||
# raw.set_annotations(new_annotations)
|
||||
# write_raw_snirf(raw, save_path)
|
||||
|
||||
def _write_event_mapping_json(
|
||||
self,
|
||||
file_a,
|
||||
file_b,
|
||||
selected_obs,
|
||||
snirf_anchor,
|
||||
boris_anchor,
|
||||
time_shift,
|
||||
mapped_events,
|
||||
save_path
|
||||
):
|
||||
# def _write_event_mapping_json(
|
||||
# self,
|
||||
# file_a,
|
||||
# file_b,
|
||||
# selected_obs,
|
||||
# snirf_anchor,
|
||||
# boris_anchor,
|
||||
# time_shift,
|
||||
# mapped_events,
|
||||
# save_path
|
||||
# ):
|
||||
|
||||
payload = {
|
||||
"source": {
|
||||
"called_from": self.caller,
|
||||
"snirf_file": os.path.basename(file_a),
|
||||
"boris_file": os.path.basename(file_b),
|
||||
"observation": selected_obs
|
||||
},
|
||||
"alignment": {
|
||||
"snirf_anchor": snirf_anchor,
|
||||
"boris_anchor": boris_anchor,
|
||||
"time_shift_seconds": time_shift
|
||||
},
|
||||
"events": mapped_events,
|
||||
"created_at": datetime.utcnow().isoformat() + "Z"
|
||||
}
|
||||
# payload = {
|
||||
# "source": {
|
||||
# "called_from": self.caller,
|
||||
# "snirf_file": os.path.basename(file_a),
|
||||
# "boris_file": os.path.basename(file_b),
|
||||
# "observation": selected_obs
|
||||
# },
|
||||
# "alignment": {
|
||||
# "snirf_anchor": snirf_anchor,
|
||||
# "boris_anchor": boris_anchor,
|
||||
# "time_shift_seconds": time_shift
|
||||
# },
|
||||
# "events": mapped_events,
|
||||
# "created_at": datetime.utcnow().isoformat() + "Z"
|
||||
# }
|
||||
|
||||
with open(save_path, "w", encoding="utf-8") as f:
|
||||
json.dump(payload, f, indent=2)
|
||||
# with open(save_path, "w", encoding="utf-8") as f:
|
||||
# json.dump(payload, f, indent=2)
|
||||
|
||||
return save_path
|
||||
# return save_path
|
||||
|
||||
|
||||
|
||||
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)
|
||||
|
||||
self.mode = mode
|
||||
@@ -595,7 +593,7 @@ class UpdateEventsBlazesWindow(QWidget):
|
||||
help_btn_a = QPushButton("?")
|
||||
help_btn_a.setFixedWidth(25)
|
||||
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)
|
||||
|
||||
# Container for label + line_edit + browse button with tooltip
|
||||
@@ -618,7 +616,7 @@ class UpdateEventsBlazesWindow(QWidget):
|
||||
help_btn_b = QPushButton("?")
|
||||
help_btn_b.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -640,7 +638,7 @@ class UpdateEventsBlazesWindow(QWidget):
|
||||
help_btn_suffix = QPushButton("?")
|
||||
help_btn_suffix.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -660,7 +658,7 @@ class UpdateEventsBlazesWindow(QWidget):
|
||||
help_btn_snirf_events = QPushButton("?")
|
||||
help_btn_snirf_events.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -683,13 +681,13 @@ class UpdateEventsBlazesWindow(QWidget):
|
||||
self.setLayout(layout)
|
||||
|
||||
|
||||
def show_help_popup(self, text):
|
||||
def show_help_popup(self, text: str) -> None:
|
||||
msg = QMessageBox(self)
|
||||
msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}")
|
||||
msg.setText(text)
|
||||
msg.exec()
|
||||
|
||||
def browse_file_a(self):
|
||||
def browse_file_a(self) -> None:
|
||||
file_path, _ = QFileDialog.getOpenFileName(self, "Select SNIRF File", "", "SNIRF Files (*.snirf)")
|
||||
if 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.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)")
|
||||
if file_path:
|
||||
self.line_edit_file_b.setText(file_path)
|
||||
@@ -744,11 +742,11 @@ class UpdateEventsBlazesWindow(QWidget):
|
||||
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:
|
||||
raise KeyError("Missing 'events' key in JSON file.")
|
||||
|
||||
event_strings = []
|
||||
event_strings: List[str] = []
|
||||
|
||||
# The new format is a flat list chronologically ordered
|
||||
for event in data["events"]:
|
||||
@@ -762,14 +760,14 @@ class UpdateEventsBlazesWindow(QWidget):
|
||||
return event_strings
|
||||
|
||||
|
||||
def clear_files(self):
|
||||
def clear_files(self) -> None:
|
||||
self.line_edit_file_a.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_b = self.line_edit_file_b.text()
|
||||
_ = self.line_edit_file_b.text()
|
||||
suffix = APP_NAME
|
||||
|
||||
if not hasattr(self, "json_data") or self.combo_events.count() == 0 or self.combo_snirf_events.count() == 0:
|
||||
|
||||
+107
-46
@@ -1,16 +1,21 @@
|
||||
"""
|
||||
Filename: updateoptodes.py
|
||||
Description: Methods to update optode locations for FLARES
|
||||
Note: Compliant with pylance strict type checking
|
||||
|
||||
Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in imports
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Dict, Optional, Union
|
||||
|
||||
# External library imports
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import numpy.typing as npt
|
||||
|
||||
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLabel, QHBoxLayout, QMessageBox, QLineEdit, QPushButton, QFileDialog
|
||||
from PySide6.QtCore import Qt
|
||||
@@ -24,12 +29,14 @@ from src.shared.shareddata import APP_NAME
|
||||
|
||||
class UpdateOptodesWindow(QWidget):
|
||||
|
||||
def __init__(self, parent=None):
|
||||
def __init__(self, parent: Optional[QWidget] = None) -> None:
|
||||
super().__init__(parent, Qt.WindowType.Window)
|
||||
self.setWindowTitle(f"Update optode positions - {APP_NAME.upper()}")
|
||||
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.setReadOnly(True)
|
||||
self.btn_browse_a = QPushButton("Browse .snirf")
|
||||
@@ -50,7 +57,6 @@ class UpdateOptodesWindow(QWidget):
|
||||
self.btn_clear.clicked.connect(self.clear_files)
|
||||
self.btn_go.clicked.connect(self.go_action)
|
||||
|
||||
# ---
|
||||
layout = QVBoxLayout()
|
||||
self.description = QLabel()
|
||||
self.description.setTextFormat(Qt.TextFormat.RichText)
|
||||
@@ -75,7 +81,7 @@ class UpdateOptodesWindow(QWidget):
|
||||
help_btn_a = QPushButton("?")
|
||||
help_btn_a.setFixedWidth(25)
|
||||
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)
|
||||
|
||||
# Container for label + line_edit + browse button with tooltip
|
||||
@@ -98,7 +104,7 @@ class UpdateOptodesWindow(QWidget):
|
||||
help_btn_b = QPushButton("?")
|
||||
help_btn_b.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -121,7 +127,7 @@ class UpdateOptodesWindow(QWidget):
|
||||
help_btn_suffix = QPushButton("?")
|
||||
help_btn_suffix.setFixedWidth(25)
|
||||
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_container = QWidget()
|
||||
@@ -143,13 +149,13 @@ class UpdateOptodesWindow(QWidget):
|
||||
|
||||
self.setLayout(layout)
|
||||
|
||||
def show_help_popup(self, text):
|
||||
def show_help_popup(self, text: str) -> None:
|
||||
msg = QMessageBox(self)
|
||||
msg.setWindowTitle(f"Parameter Info - {APP_NAME.upper()}")
|
||||
msg.setText(text)
|
||||
msg.exec()
|
||||
|
||||
def handle_link_click(self, link):
|
||||
def handle_link_click(self, link: str) -> None:
|
||||
if link == "custom_link":
|
||||
msg = QMessageBox(self)
|
||||
msg.setWindowTitle("Example Digitization File")
|
||||
@@ -166,61 +172,110 @@ class UpdateOptodesWindow(QWidget):
|
||||
msg.setText(text)
|
||||
msg.exec()
|
||||
|
||||
def browse_file_a(self):
|
||||
file_path, _ = QFileDialog.getOpenFileName(self, "Select SNIRF File", "", "SNIRF Files (*.snirf)")
|
||||
if file_path:
|
||||
self.line_edit_file_a.setText(file_path)
|
||||
def browse_file_a(self) -> None:
|
||||
file_paths, _ = QFileDialog.getOpenFileNames(
|
||||
self,
|
||||
"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)")
|
||||
if 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_b.clear()
|
||||
|
||||
def go_action(self):
|
||||
def go_action(self) -> None:
|
||||
file_a = self.line_edit_file_a.text()
|
||||
file_b = self.line_edit_file_b.text()
|
||||
suffix = self.line_edit_suffix.text().strip() or "flare"
|
||||
|
||||
if not file_a:
|
||||
QMessageBox.critical(self, "Missing File", "Please select a SNIRF file.")
|
||||
if not self.selected_snirf_files:
|
||||
QMessageBox.critical(self, "Missing File", "Please select at least one SNIRF file.")
|
||||
return
|
||||
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
|
||||
|
||||
# Get original filename without extension
|
||||
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(
|
||||
output_dir = QFileDialog.getExistingDirectory(
|
||||
self,
|
||||
"Save SNIRF File As",
|
||||
suggested_name,
|
||||
"SNIRF Files (*.snirf)"
|
||||
"Select Output Directory"
|
||||
)
|
||||
|
||||
if not save_path:
|
||||
if not output_dir:
|
||||
print("Save cancelled.")
|
||||
return
|
||||
|
||||
# Ensure .snirf extension
|
||||
if not save_path.lower().endswith(".snirf"):
|
||||
save_path += ".snirf"
|
||||
output_path = Path(output_dir)
|
||||
|
||||
try:
|
||||
self.update_optode_positions(file_a=file_a, file_b=file_b, save_path=save_path)
|
||||
except Exception as e:
|
||||
QMessageBox.critical(self, "Error", f"Failed to write file:\n{e}")
|
||||
return
|
||||
|
||||
QMessageBox.information(self, "File Saved", f"File was saved to:\n{save_path}")
|
||||
successful_files: list[str] = []
|
||||
failed_files: list[str] = []
|
||||
|
||||
def update_optode_positions(self, file_a, file_b, save_path):
|
||||
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:
|
||||
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:
|
||||
failed_files.append(
|
||||
f"{input_path.name}: {e}"
|
||||
)
|
||||
|
||||
# Build summary
|
||||
message_parts: list[str] = []
|
||||
|
||||
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 = {}
|
||||
ch_positions = {}
|
||||
@@ -247,16 +302,22 @@ class UpdateOptodesWindow(QWidget):
|
||||
elif extension == '.xlsx':
|
||||
|
||||
# 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(df, block_id, row_mapping, scale=0.001):
|
||||
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]]:
|
||||
|
||||
"""Isolates a block, cleans numeric data, and returns a scaled dictionary."""
|
||||
# 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')
|
||||
|
||||
# 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 isinstance(row_mapping, dict):
|
||||
@@ -265,7 +326,7 @@ class UpdateOptodesWindow(QWidget):
|
||||
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
|
||||
elif isinstance(row_mapping, str):
|
||||
else:
|
||||
for i in range(len(block)):
|
||||
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
|
||||
|
||||
# Read the SNIRF file, set the montage, and write it back
|
||||
raw = read_raw_snirf(file_a, preload=True)
|
||||
raw.set_montage(initial_montage)
|
||||
raw = read_raw_snirf(str(file_a), preload=True)
|
||||
raw.set_montage(initial_montage) # type: ignore
|
||||
write_raw_snirf(raw, save_path)
|
||||
@@ -1,21 +1,30 @@
|
||||
"""
|
||||
Filename: viewerlauncher.py
|
||||
Description: Viewer launcher window
|
||||
Note: Compliant with pylance strict type checking
|
||||
|
||||
Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in imports
|
||||
from typing import Any, Callable, Type
|
||||
|
||||
# External library imports
|
||||
from pandas import DataFrame
|
||||
|
||||
from PySide6.QtWidgets import QPushButton, QWidget, QVBoxLayout
|
||||
from PySide6.QtCore import QTimer
|
||||
|
||||
from mne import Epochs
|
||||
from mne.io.base import BaseRaw
|
||||
|
||||
from src.analysis.exporttocsv import ExportToCSVWidget
|
||||
from src.analysis.intragroupbrainimage import IntraGroupBrainImageWidget
|
||||
from src.analysis.intergroupbrainimage import InterGroupBrainImageWidget
|
||||
from src.analysis.crossgroupbrainimage import CrossGroupBrainImageWidget
|
||||
from src.analysis.intergroupfunctionalconnectivity import InterGroupFunctionalConnectivityWidget
|
||||
from src.analysis.intragroupfunctionalconnectivity import IntraGroupFunctionalConnectivityWidget
|
||||
from src.analysis.intragroupstats import IntraGroupStatsWidget
|
||||
from src.analysis.intergroupstats import InterGroupStatsWidget
|
||||
from src.analysis.crossgroupstats import CrossGroupStatsWidget
|
||||
from src.analysis.participantimage import ParticipantImageViewerWidget
|
||||
from src.analysis.participantbrain import ParticipantBrainViewerWidget
|
||||
from src.analysis.participantfoldchannels import ParticipantFoldChannelsWidget
|
||||
@@ -24,44 +33,81 @@ from src.shared.shareddata import APP_NAME
|
||||
|
||||
|
||||
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__()
|
||||
self.setWindowTitle(f"Viewer Launcher - {APP_NAME.upper()}")
|
||||
|
||||
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 Brain Viewer", ParticipantBrainViewerWidget, [haemo_dict, cha_dict], True),
|
||||
("Participant Fold Channels Viewer", ParticipantFoldChannelsWidget, [haemo_dict, cha_dict], False),
|
||||
("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),
|
||||
("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),
|
||||
("Inter-Group Brain and Image Viewer", InterGroupBrainImageWidget, [haemo_dict, cha_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], 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, 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)
|
||||
]
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
for label, widget_class, args, requires_bypass in btn_data:
|
||||
btn = QPushButton(f"Open {label}")
|
||||
# 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))
|
||||
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
|
||||
self.active_viewer = widget_class(*args)
|
||||
self.active_viewer.show()
|
||||
self._trigger_success(btn)
|
||||
|
||||
def _launch(self, func, btn, *args):
|
||||
def _launch(
|
||||
self,
|
||||
func: Callable[..., Any],
|
||||
btn: QPushButton,
|
||||
*args: Any
|
||||
|
||||
) -> None:
|
||||
func(*args)
|
||||
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."""
|
||||
original_text = button.text()
|
||||
button.setText(f"{original_text} ✔")
|
||||
@@ -70,6 +116,6 @@ class ViewerLauncherWidget(QWidget):
|
||||
# Revert after 1 second
|
||||
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.setStyleSheet("")
|
||||
@@ -7,6 +7,7 @@ Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
"""
|
||||
|
||||
# Built-in imports
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
update
|
||||
+230
-181
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Filename: updater.py
|
||||
Description: Generic updater file
|
||||
Note: Compliant with pylance strict type checking
|
||||
|
||||
Author: Tyler de Zeeuw
|
||||
License: GPL-3.0
|
||||
@@ -17,14 +18,16 @@ import zipfile
|
||||
import traceback
|
||||
import subprocess
|
||||
import configparser
|
||||
from typing import List, Tuple, Optional, Callable, Any
|
||||
|
||||
|
||||
# External library imports
|
||||
import psutil
|
||||
import requests
|
||||
|
||||
from PySide6.QtWidgets import QMessageBox
|
||||
from PySide6.QtCore import QThread, Signal, QObject
|
||||
|
||||
from PySide6.QtWidgets import QMainWindow, QMessageBox
|
||||
from src.shared.shareddata import get_app_dir
|
||||
|
||||
class UpdateDownloadThread(QThread):
|
||||
"""
|
||||
@@ -38,14 +41,21 @@ class UpdateDownloadThread(QThread):
|
||||
update_ready = Signal(str, 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__()
|
||||
self.download_url = download_url
|
||||
self.latest_version = latest_version
|
||||
self.platform_name = platform_name
|
||||
self.app_name = app_name
|
||||
|
||||
def run(self):
|
||||
def run(self) -> None:
|
||||
try:
|
||||
local_filename = os.path.basename(self.download_url)
|
||||
|
||||
@@ -54,7 +64,8 @@ class UpdateDownloadThread(QThread):
|
||||
os.makedirs(tmp_dir, exist_ok=True)
|
||||
local_path = os.path.join(tmp_dir, local_filename)
|
||||
else:
|
||||
local_path = os.path.join(os.getcwd(), local_filename)
|
||||
tmp_dir = get_app_dir()
|
||||
local_path = os.path.join(tmp_dir, local_filename)
|
||||
|
||||
# Download the file
|
||||
with requests.get(self.download_url, stream=True, timeout=15) as r:
|
||||
@@ -68,10 +79,9 @@ class UpdateDownloadThread(QThread):
|
||||
if self.platform_name == 'darwin':
|
||||
extract_folder = os.path.splitext(local_filename)[0]
|
||||
extract_path = os.path.join(tmp_dir, extract_folder)
|
||||
|
||||
else:
|
||||
extract_folder = os.path.splitext(local_filename)[0]
|
||||
extract_path = os.path.join(os.getcwd(), extract_folder)
|
||||
extract_path = os.path.join(get_app_dir(), extract_folder)
|
||||
|
||||
# Create the folder if not exists
|
||||
os.makedirs(extract_path, exist_ok=True)
|
||||
@@ -92,7 +102,6 @@ class UpdateDownloadThread(QThread):
|
||||
self.error_occurred.emit(str(e))
|
||||
|
||||
|
||||
|
||||
class UpdateCheckThread(QThread):
|
||||
"""
|
||||
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()
|
||||
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__()
|
||||
self.api_url = api_url
|
||||
self.api_url_sec = api_url_sec
|
||||
@@ -115,10 +132,7 @@ class UpdateCheckThread(QThread):
|
||||
self.platform_name = platform_name
|
||||
self.app_name = app_name
|
||||
|
||||
def run(self):
|
||||
# if not getattr(sys, 'frozen', False):
|
||||
# self.error_occurred.emit("Application is not frozen (Development mode).")
|
||||
# return
|
||||
def run(self) -> None:
|
||||
try:
|
||||
latest_version, download_url = self.get_latest_release_for_platform()
|
||||
if not latest_version:
|
||||
@@ -137,15 +151,15 @@ class UpdateCheckThread(QThread):
|
||||
except Exception as e:
|
||||
self.error_occurred.emit(f"Update check failed: {e}")
|
||||
|
||||
def version_compare(self, v1, v2):
|
||||
def normalize(v): return [int(x) for x in v.split(".")]
|
||||
def version_compare(self, v1: str, v2: str) -> int:
|
||||
def normalize(v: str) -> List[int]:
|
||||
return [int(x) for x in v.split(".")]
|
||||
return (normalize(v1) > normalize(v2)) - (normalize(v1) < normalize(v2))
|
||||
|
||||
def get_latest_release_for_platform(self):
|
||||
def get_latest_release_for_platform(self) -> Tuple[Optional[str], Optional[str]]:
|
||||
urls = [self.api_url, self.api_url_sec]
|
||||
for url in urls:
|
||||
try:
|
||||
|
||||
response = requests.get(url, timeout=5)
|
||||
response.raise_for_status()
|
||||
releases = response.json()
|
||||
@@ -165,7 +179,7 @@ class UpdateCheckThread(QThread):
|
||||
return tag, asset["browser_download_url"]
|
||||
|
||||
return tag, None
|
||||
except (requests.RequestException, ValueError) as e:
|
||||
except (requests.RequestException, ValueError, KeyError):
|
||||
continue
|
||||
return None, None
|
||||
|
||||
@@ -182,22 +196,30 @@ class LocalPendingUpdateCheckThread(QThread):
|
||||
pending_update_found = Signal(str, str)
|
||||
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__()
|
||||
self.current_version = current_version
|
||||
self.platform_suffix = platform_suffix
|
||||
self.platform_name = platform_name
|
||||
self.app_name = app_name
|
||||
|
||||
def version_compare(self, v1, v2):
|
||||
def normalize(v): return [int(x) for x in v.split(".")]
|
||||
def version_compare(self, v1: str, v2: str) -> int:
|
||||
def normalize(v: str) -> List[int]:
|
||||
return [int(x) for x in v.split(".")]
|
||||
return (normalize(v1) > normalize(v2)) - (normalize(v1) < normalize(v2))
|
||||
|
||||
def run(self):
|
||||
def run(self) -> None:
|
||||
if self.platform_name == 'darwin':
|
||||
cwd = f'/tmp/{self.app_name}tempupdate'
|
||||
else:
|
||||
cwd = os.getcwd()
|
||||
cwd = get_app_dir()
|
||||
|
||||
pattern = re.compile(r".*-(\d+\.\d+\.\d+)" + re.escape(self.platform_suffix) + r"$")
|
||||
found = False
|
||||
@@ -213,25 +235,32 @@ class LocalPendingUpdateCheckThread(QThread):
|
||||
self.pending_update_found.emit(folder_version, folder_path)
|
||||
found = True
|
||||
break
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not found:
|
||||
self.no_pending_update.emit()
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class UpdateManager(QObject):
|
||||
"""
|
||||
Orchestrates the update process.
|
||||
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):
|
||||
super().__init__()
|
||||
self.parent = main_window
|
||||
def __init__(
|
||||
self,
|
||||
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_sec = api_url_sec
|
||||
self.current_version = current_version
|
||||
@@ -239,63 +268,69 @@ class UpdateManager(QObject):
|
||||
self.platform_suffix = platform_suffix
|
||||
self.app_name = app_name
|
||||
|
||||
self.pending_update_version = None
|
||||
self.pending_update_path = None
|
||||
self.pending_update_version: Optional[str] = None
|
||||
self.pending_update_path: Optional[str] = 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.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.start()
|
||||
|
||||
def on_pending_update_found(self, version, folder_path):
|
||||
self.parent.statusBar().showMessage(f"Pending update found: version {version}")
|
||||
def on_pending_update_found(self, version: str, folder_path: str) -> None:
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage(f"Pending update found: version {version}")
|
||||
self.pending_update_version = version
|
||||
self.pending_update_path = folder_path
|
||||
self.show_pending_update_popup()
|
||||
|
||||
def on_no_pending_update(self):
|
||||
# No pending update found locally, start server check directly
|
||||
self.parent.statusBar().showMessage("No pending local update found. Checking server...")
|
||||
def on_no_pending_update(self) -> None:
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage("No pending local update found. Checking server...")
|
||||
self.start_update_check_thread()
|
||||
|
||||
def show_pending_update_popup(self):
|
||||
msg_box = QMessageBox(self.parent)
|
||||
def show_pending_update_popup(self) -> None:
|
||||
msg_box = QMessageBox(self.main_window)
|
||||
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?")
|
||||
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()
|
||||
|
||||
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)
|
||||
else:
|
||||
self.parent.statusBar().showMessage("Pending update available. Install later.")
|
||||
# After user dismisses, still check the server for new updates
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage("Pending update available. Install later.")
|
||||
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.download_requested.connect(self.on_server_update_requested)
|
||||
self.check_thread.no_update_available.connect(self.on_server_no_update)
|
||||
self.check_thread.error_occurred.connect(self.on_error)
|
||||
self.check_thread.start()
|
||||
|
||||
def on_server_no_update(self):
|
||||
self.parent.statusBar().showMessage("No new updates found on server.", 5000)
|
||||
def on_server_no_update(self) -> None:
|
||||
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):
|
||||
if self.pending_update_version:
|
||||
cmp = self.version_compare(latest_version, self.pending_update_version)
|
||||
def on_server_update_requested(self, download_url: str, latest_version: str) -> None:
|
||||
pending_path = self.pending_update_path
|
||||
pending_version = self.pending_update_version
|
||||
|
||||
if pending_version and pending_path:
|
||||
cmp = self.version_compare(latest_version, pending_version)
|
||||
if cmp > 0:
|
||||
# Server version is newer than pending update
|
||||
self.parent.statusBar().showMessage(f"Newer version {latest_version} available on server. Removing old pending update...")
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage(f"Newer version {latest_version} available on server. Removing old pending update...")
|
||||
try:
|
||||
shutil.rmtree(self.pending_update_path)
|
||||
self.parent.statusBar().showMessage(f"Deleted old update folder: {self.pending_update_path}")
|
||||
shutil.rmtree(pending_path)
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage(f"Deleted old update folder: {pending_path}")
|
||||
except Exception as e:
|
||||
self.parent.statusBar().showMessage(f"Failed to delete old update folder: {e}")
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage(f"Failed to delete old update folder: {e}")
|
||||
|
||||
# Clear pending update info so new download proceeds
|
||||
self.pending_update_version = None
|
||||
@@ -304,63 +339,66 @@ class UpdateManager(QObject):
|
||||
# Download the new update
|
||||
self.download_update(download_url, latest_version)
|
||||
elif cmp == 0:
|
||||
# Versions equal, no download needed
|
||||
self.parent.statusBar().showMessage(f"Pending update version {self.pending_update_version} is already latest. No download needed.")
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage(f"Pending update version {self.pending_update_version} is already latest. No download needed.")
|
||||
else:
|
||||
# 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:
|
||||
# No pending update, just download
|
||||
self.download_update(download_url, latest_version)
|
||||
|
||||
def download_update(self, download_url, latest_version):
|
||||
self.parent.statusBar().showMessage("Downloading update...")
|
||||
def download_update(self, download_url: str, latest_version: str) -> None:
|
||||
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.update_ready.connect(self.on_update_ready)
|
||||
self.download_thread.error_occurred.connect(self.on_error)
|
||||
self.download_thread.start()
|
||||
|
||||
def on_update_ready(self, latest_version, extract_folder):
|
||||
self.parent.statusBar().showMessage("Update downloaded and extracted.")
|
||||
def on_update_ready(self, latest_version: str, extract_folder: str) -> None:
|
||||
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.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_later_button = msg_box.addButton("Install Later", QMessageBox.ButtonRole.RejectRole)
|
||||
msg_box.addButton("Install Later", QMessageBox.ButtonRole.RejectRole)
|
||||
|
||||
msg_box.exec()
|
||||
|
||||
if msg_box.clickedButton() == install_now_button:
|
||||
self.install_update(extract_folder)
|
||||
else:
|
||||
self.parent.statusBar().showMessage("Update ready. Install later.")
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage("Update ready. Install later.")
|
||||
|
||||
def install_update(self, extract_folder: str) -> None:
|
||||
base_dir = get_app_dir()
|
||||
|
||||
def install_update(self, extract_folder):
|
||||
# Path to updater executable
|
||||
|
||||
if self.platform_name == 'windows':
|
||||
updater_path = os.path.join(os.getcwd(), f"{self.app_name}_updater.exe")
|
||||
updater_path = os.path.join(base_dir, f"{self.app_name}_updater.exe")
|
||||
elif self.platform_name == 'darwin':
|
||||
if getattr(sys, 'frozen', False):
|
||||
updater_path = os.path.join(os.path.dirname(sys.executable), f"../../../{self.app_name}_updater.app")
|
||||
updater_path = os.path.join(base_dir, f"../../../{self.app_name}_updater.app")
|
||||
else:
|
||||
updater_path = os.path.join(os.getcwd(), f"../{self.app_name}_updater.app")
|
||||
|
||||
updater_path = os.path.join(base_dir, f"../{self.app_name}_updater.app")
|
||||
elif self.platform_name == 'linux':
|
||||
updater_path = os.path.join(os.getcwd(), f"{self.app_name}_updater")
|
||||
updater_path = os.path.join(base_dir, f"{self.app_name}_updater")
|
||||
else:
|
||||
updater_path = os.getcwd()
|
||||
updater_path = base_dir
|
||||
|
||||
updater_path = os.path.abspath(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
|
||||
|
||||
# Launch updater with extracted folder path as argument
|
||||
try:
|
||||
# Pass current app's executable path for updater to relaunch
|
||||
main_app_executable = os.path.abspath(sys.argv[0])
|
||||
main_app_executable = sys.executable if getattr(sys, 'frozen', False) else os.path.abspath(sys.argv[0])
|
||||
|
||||
print(f'Launching updater with: "{updater_path}" "{extract_folder}" "{main_app_executable}"')
|
||||
|
||||
@@ -373,18 +411,19 @@ class UpdateManager(QObject):
|
||||
sys.exit(0)
|
||||
|
||||
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):
|
||||
# print(f"Error: {message}")
|
||||
self.parent.statusBar().showMessage(f"Error occurred during update process. {message}")
|
||||
def on_error(self, message: str) -> None:
|
||||
if self.main_window.statusBar():
|
||||
self.main_window.statusBar().showMessage(f"Error occurred during update process. {message}")
|
||||
|
||||
def version_compare(self, v1, v2):
|
||||
def normalize(v): return [int(x) for x in v.split(".")]
|
||||
def version_compare(self, v1: str, v2: str) -> int:
|
||||
def normalize(v: str) -> List[int]:
|
||||
return [int(x) for x in v.split(".")]
|
||||
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.
|
||||
|
||||
@@ -416,125 +455,135 @@ def wait_for_process_to_exit(process_name, timeout=10):
|
||||
return False
|
||||
|
||||
|
||||
def finish_update_if_needed(platform_name, app_name, cfg_path, finish_update):
|
||||
def _remove_readonly(func: Callable[[str], Any], path: str, exc: Any) -> None:
|
||||
"""Error handler for shutil.rmtree to clear read-only files on Windows."""
|
||||
import stat
|
||||
os.chmod(path, stat.S_IWRITE)
|
||||
func(path)
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
|
||||
if finish_update:
|
||||
print("Finishing update...")
|
||||
|
||||
update_cfg = configparser.ConfigParser()
|
||||
try:
|
||||
update_cfg.read(cfg_path)
|
||||
if not finish_update:
|
||||
return
|
||||
|
||||
print("Finishing update...")
|
||||
|
||||
# 1. Reset welcome dialog config flag
|
||||
update_cfg = configparser.ConfigParser()
|
||||
try:
|
||||
if os.path.exists(cfg_path):
|
||||
update_cfg.read(cfg_path)
|
||||
if not update_cfg.has_section("Options"):
|
||||
update_cfg.add_section("Options")
|
||||
update_cfg.set("Options", "show_welcome_dialog", "true")
|
||||
|
||||
with open(cfg_path, "w") as f:
|
||||
update_cfg.write(f)
|
||||
print("Welcome dialog flag successfully reset to 'true' for next run.")
|
||||
except Exception as e:
|
||||
print(f"Warning: Could not update welcome dialog preference flag: {e}")
|
||||
except Exception as e:
|
||||
print(f"Warning: Could not update welcome dialog preference flag: {e}")
|
||||
|
||||
if platform_name == 'darwin':
|
||||
app_dir = f'/tmp/{app_name}tempupdate'
|
||||
else:
|
||||
app_dir = os.getcwd()
|
||||
app_dir = f'/tmp/{app_name}tempupdate' if platform_name == 'darwin' else get_app_dir()
|
||||
|
||||
# 1. Find update folder
|
||||
update_folder = None
|
||||
if not os.path.exists(app_dir):
|
||||
print(f"App directory does not exist: {app_dir}. Skipping cleanup.")
|
||||
return
|
||||
|
||||
# 2. Find update folder(s)
|
||||
update_folders: List[str] = []
|
||||
try:
|
||||
for entry in os.listdir(app_dir):
|
||||
entry_path = os.path.join(app_dir, entry)
|
||||
if os.path.isdir(entry_path) and entry.startswith(f"{app_name}-") and entry.endswith("-" + platform_name):
|
||||
update_folder = os.path.join(app_dir, entry)
|
||||
break
|
||||
update_folders.append(entry_path)
|
||||
except Exception as e:
|
||||
print(f"Error scanning app directory for update folders: {e}")
|
||||
|
||||
if update_folder is None:
|
||||
print("No update folder found. Skipping update steps.")
|
||||
return
|
||||
|
||||
if platform_name == 'darwin':
|
||||
update_folder = os.path.join(update_folder, f"{app_name}-darwin")
|
||||
if not update_folders:
|
||||
print("No update folder found. Skipping update steps.")
|
||||
return
|
||||
|
||||
# 2. Wait for updater to exit
|
||||
print(f"Waiting for {app_name}_updater to exit...")
|
||||
for proc in psutil.process_iter(['pid', 'name']):
|
||||
if proc.info['name'] and f"{app_name}_updater" in proc.info['name'].lower():
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except psutil.TimeoutExpired:
|
||||
print(f"Force killing lingering {app_name}_updater")
|
||||
proc.kill()
|
||||
primary_update_folder = update_folders[0]
|
||||
target_updater_folder = os.path.join(primary_update_folder, f"{app_name}-darwin") if platform_name == 'darwin' else primary_update_folder
|
||||
|
||||
# 3. Replace the updater
|
||||
if platform_name == 'windows':
|
||||
new_updater = os.path.join(update_folder, f"{app_name}_updater.exe")
|
||||
dest_updater = os.path.join(app_dir, f"{app_name}_updater.exe")
|
||||
|
||||
elif platform_name == 'darwin':
|
||||
new_updater = os.path.join(update_folder, f"{app_name}_updater.app")
|
||||
dest_updater = os.path.abspath(os.path.join(sys.executable, f"../../../../{app_name}_updater.app"))
|
||||
|
||||
elif platform_name == 'linux':
|
||||
new_updater = os.path.join(update_folder, f"{app_name}_updater")
|
||||
dest_updater = os.path.join(app_dir, f"{app_name}_updater")
|
||||
|
||||
else:
|
||||
print("Unknown Platform")
|
||||
new_updater = os.getcwd()
|
||||
dest_updater = os.getcwd()
|
||||
|
||||
print(f"New updater is {new_updater}")
|
||||
print(f"Dest updater is {dest_updater}")
|
||||
|
||||
print("Writable?", os.access(dest_updater, os.W_OK))
|
||||
print("Executable path:", sys.executable)
|
||||
print("Trying to copy:", new_updater, "->", dest_updater)
|
||||
|
||||
if os.path.exists(new_updater):
|
||||
try:
|
||||
if os.path.exists(dest_updater):
|
||||
if platform_name == 'darwin':
|
||||
try:
|
||||
if os.path.isdir(dest_updater):
|
||||
shutil.rmtree(dest_updater)
|
||||
print(f"Deleted directory: {dest_updater}")
|
||||
else:
|
||||
os.remove(dest_updater)
|
||||
print(f"Deleted file: {dest_updater}")
|
||||
except Exception as e:
|
||||
print(f"Error deleting {dest_updater}: {e}")
|
||||
else:
|
||||
os.remove(dest_updater)
|
||||
|
||||
if platform_name == 'darwin':
|
||||
wait_for_process_to_exit(f"{app_name}_updater", timeout=10)
|
||||
subprocess.check_call(["ditto", new_updater, dest_updater])
|
||||
else:
|
||||
shutil.copy2(new_updater, dest_updater)
|
||||
|
||||
if platform_name in ('linux', 'darwin'):
|
||||
os.chmod(dest_updater, 0o755)
|
||||
|
||||
if platform_name == 'darwin':
|
||||
remove_quarantine(dest_updater, app_name)
|
||||
|
||||
print(f"{app_name}_updater replaced.")
|
||||
except Exception as e:
|
||||
print(f"Failed to replace {app_name}_updater: {e}")
|
||||
|
||||
# 4. Delete the update folder
|
||||
# 3. Wait for updater process to exit
|
||||
print(f"Waiting for {app_name}_updater to exit...")
|
||||
updater_bin_name = f"{app_name}_updater"
|
||||
for proc in psutil.process_iter(['pid', 'name']):
|
||||
try:
|
||||
if platform_name == 'darwin':
|
||||
shutil.rmtree(app_dir)
|
||||
else:
|
||||
shutil.rmtree(update_folder)
|
||||
except Exception as e:
|
||||
print(f"Failed to delete update folder: {e}")
|
||||
if proc.info['name'] and updater_bin_name.lower() in proc.info['name'].lower():
|
||||
proc.wait(timeout=5)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
||||
pass
|
||||
except psutil.TimeoutExpired:
|
||||
print(f"Force killing lingering {app_name}_updater")
|
||||
try:
|
||||
proc.kill()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 4. Replace the updater executable
|
||||
target_base = get_app_dir()
|
||||
if platform_name == 'windows':
|
||||
new_updater = os.path.join(target_updater_folder, f"{app_name}_updater.exe")
|
||||
dest_updater = os.path.join(target_base, f"{app_name}_updater.exe")
|
||||
elif platform_name == 'darwin':
|
||||
new_updater = os.path.join(target_updater_folder, f"{app_name}_updater.app")
|
||||
dest_updater = os.path.abspath(os.path.join(sys.executable, f"../../../../{app_name}_updater.app"))
|
||||
elif platform_name == 'linux':
|
||||
new_updater = os.path.join(target_updater_folder, f"{app_name}_updater")
|
||||
dest_updater = os.path.join(target_base, f"{app_name}_updater")
|
||||
else:
|
||||
new_updater = target_base
|
||||
dest_updater = target_base
|
||||
|
||||
if os.path.exists(new_updater):
|
||||
try:
|
||||
if os.path.exists(dest_updater):
|
||||
if platform_name == 'darwin' and os.path.isdir(dest_updater):
|
||||
shutil.rmtree(dest_updater, onexc=_remove_readonly)
|
||||
else:
|
||||
os.remove(dest_updater)
|
||||
|
||||
if platform_name == 'darwin':
|
||||
wait_for_process_to_exit(f"{app_name}_updater", timeout=10)
|
||||
subprocess.check_call(["ditto", new_updater, dest_updater])
|
||||
else:
|
||||
shutil.copy2(new_updater, dest_updater)
|
||||
|
||||
if platform_name in ('linux', 'darwin'):
|
||||
os.chmod(dest_updater, 0o755)
|
||||
|
||||
if platform_name == 'darwin':
|
||||
remove_quarantine(dest_updater, app_name)
|
||||
|
||||
print(f"{app_name}_updater replaced successfully.")
|
||||
except Exception as e:
|
||||
print(f"Failed to replace {app_name}_updater: {e}")
|
||||
|
||||
# 5. Clean up all temporary update folders (with retries for Windows file locks)
|
||||
for folder in update_folders:
|
||||
for attempt in range(3):
|
||||
try:
|
||||
if os.path.exists(folder):
|
||||
shutil.rmtree(folder, onexc=_remove_readonly)
|
||||
print(f"Successfully deleted update folder: {folder}")
|
||||
break
|
||||
except Exception as e:
|
||||
if attempt < 2:
|
||||
time.sleep(1.0)
|
||||
else:
|
||||
print(f"Failed to delete update folder '{folder}' after 3 attempts: {e}")
|
||||
|
||||
if "--finish-update" in sys.argv:
|
||||
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.
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user