updates for next version

This commit is contained in:
2025-08-19 13:57:14 -07:00
parent 6b50e7f9f5
commit 65e33c8619
3 changed files with 173 additions and 26 deletions

View File

@@ -42,14 +42,14 @@ from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib.axes import Axes
from numpy.typing import NDArray
import vtkmodules.util.data_model
#import vtkmodules.util.data_model
from numpy import floating, float64
from matplotlib.lines import Line2D
import matplotlib.colors as mcolors
from scipy.stats import ttest_1samp # type: ignore
from matplotlib.figure import Figure
import statsmodels.formula.api as smf # type: ignore
import vtkmodules.util.execution_model
#import vtkmodules.util.execution_model
from nilearn.plotting import plot_design_matrix # type: ignore
from scipy.signal import welch, butter, filtfilt # type: ignore
from matplotlib.colors import LinearSegmentedColormap
@@ -127,7 +127,7 @@ EXCLUDE_CHANNELS: bool
MAX_BAD_CHANNELS: int
LONG_CHANNEL_THRESH: float
PPF: float
METADATA: dict
DRIFT_MODEL: str
DURATION_BETWEEN_ACTIVITIES: int
@@ -223,7 +223,7 @@ REQUIRED_KEYS: dict[str, Any] = {
"EXCLUDE_CHANNELS": bool,
"MAX_BAD_CHANNELS": int,
"LONG_CHANNEL_THRESH": float,
"PPF": float,
"METADATA": dict,
"DRIFT_MODEL": str,
"DURATION_BETWEEN_ACTIVITIES": int,
"HRF_MODEL": str,
@@ -284,8 +284,6 @@ else:
logger = logging.getLogger()
class ProcessingError(Exception):
def __init__(self, message: str = "Something went wrong!"):
self.message = message
@@ -1615,7 +1613,7 @@ def calculate_optical_density(data: BaseRaw, ID: str) -> tuple[BaseRaw, Figure]:
# STEP 9: Haemoglobin concentration
def calculate_haemoglobin_concentration(optical_density_data: BaseRaw, ID: str) -> tuple[BaseRaw, Figure]:
def calculate_haemoglobin_concentration(optical_density_data: BaseRaw, ID: str, file_path: str) -> tuple[BaseRaw, Figure]:
"""
Calculates haemoglobin concentration from optical density data using the Beer-Lambert law and generates a plot.
@@ -1625,7 +1623,9 @@ def calculate_haemoglobin_concentration(optical_density_data: BaseRaw, ID: str)
The data in optical density format.
ID : str
File name of the the snirf file that was loaded.
file_path : str
Entire file path if snirf file that was loaded.
Returns
-------
tuple[BaseRaw, Figure]
@@ -1636,7 +1636,7 @@ def calculate_haemoglobin_concentration(optical_density_data: BaseRaw, ID: str)
logger.info("Calculating haemoglobin concentration data...")
# Get the haemoglobin concentration using beer lambert law
haemoglobin_concentration_data = beer_lambert_law(optical_density_data, PPF)
haemoglobin_concentration_data = beer_lambert_law(optical_density_data, ppf=calculate_dpf(file_path))
logger.info("Creating the figure...")
fig = cast(Figure, optical_density_data.plot(show=False, n_channels=len(getattr(optical_density_data, "ch_names")), duration=getattr(optical_density_data, "times")[-1]).figure) # type: ignore
@@ -1720,10 +1720,10 @@ def calculate_and_apply_negative_correlation_enhancement(haemoglobin_concentrati
def calculate_and_apply_short_channel_correction(optical_density_data: BaseRaw) -> dict[str, list[Any] | mne.evoked.EvokedArray]:
def calculate_and_apply_short_channel_correction(optical_density_data: BaseRaw, file_path: str) -> dict[str, list[Any] | mne.evoked.EvokedArray]:
od_corrected = short_channel_regression(optical_density_data, SHORT_CHANNEL_THRESH)
haemoglobin_concentration_data = beer_lambert_law(od_corrected, PPF)
haemoglobin_concentration_data = beer_lambert_law(od_corrected, ppf=calculate_dpf(file_path))
events, _ = mne.events_from_annotations(haemoglobin_concentration_data, event_id={"Reach": 1, "Start of Rest": 2}, verbose=VERBOSITY) # type: ignore
event_dict = {"Reach": 1, "Start of Rest": 2}
@@ -1917,6 +1917,33 @@ def run_GLM_analysis(data: BaseRaw, design_matrix: DataFrame) -> RegressionResul
return glm_est
def calculate_dpf(file_path):
# order is hbo / hbr
import h5py
with h5py.File(file_path, 'r') as f:
wavelengths = f['/nirs/probe/wavelengths'][:]
print("Wavelengths (nm):", wavelengths)
wavelengths = sorted(wavelengths, reverse=True)
data = METADATA.get(file_path)
if data is None:
age = 25
else:
age = data['Age']
logger.info(age)
age = float(age)
a = 223.3
b = 0.05624
c = 0.8493
d = -5.723e-7
e = 0.001245
f = -0.9025
dpf = []
for w in wavelengths:
logger.info(w)
dpf.append(a + b * (age**c) + d* (w**3) + e * (w**2) + f*w)
logger.info(dpf)
return dpf
def individual_GLM_analysis(file_path: str, ID: str, stim_duration: float = 5.0, progress_callback=None) -> tuple[BaseRaw, BaseRaw, DataFrame, DataFrame, DataFrame, DataFrame, dict[str, Figure], str, bool, bool]:
"""
@@ -1971,6 +1998,12 @@ def individual_GLM_analysis(file_path: str, ID: str, stim_duration: float = 5.0,
# Initalize the participants full layout to be the current data regardless if it will be updated later
raw_full_layout = data
logger.info(file_path)
logger.info(ID)
logger.info(METADATA.get(file_path))
calculate_dpf(file_path)
try:
# Did the user want to load new channel positions from an optode file?
# STEP 2
@@ -1985,7 +2018,7 @@ def individual_GLM_analysis(file_path: str, ID: str, stim_duration: float = 5.0,
# but i shouldnt need to do od and bll just check the last three numbers
temp = data.copy()
temp_od = cast(BaseRaw, optical_density(temp, verbose=VERBOSITY))
raw_full_layout = beer_lambert_law(temp_od, ppf=PPF)
raw_full_layout = beer_lambert_law(temp_od, ppf=calculate_dpf(file_path))
# If specified, apply TDDR to the data
# STEP 3
@@ -2082,11 +2115,11 @@ def individual_GLM_analysis(file_path: str, ID: str, stim_duration: float = 5.0,
if SHORT_CHANNEL:
short_chans_od = cast(BaseRaw, optical_density(short_chans))
data_recombined = cast(BaseRaw, data.copy().add_channels([short_chans_od])) # type: ignore
evoked_dict_corr = calculate_and_apply_short_channel_correction(data_recombined.copy())
evoked_dict_corr = calculate_and_apply_short_channel_correction(data_recombined.copy(), file_path)
# Calculate the haemoglobin concentration
# STEP 9
data, fig = calculate_haemoglobin_concentration(data, ID)
data, fig = calculate_haemoglobin_concentration(data, ID, file_path)
order_of_operations += " + Haemoglobin Concentration"
fig_dict['HaemoglobinConcentration'] = fig
if progress_callback: progress_callback(9)