-
Notifications
You must be signed in to change notification settings - Fork 17
/
tde_hmm.py
162 lines (138 loc) · 4.35 KB
/
tde_hmm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
"""Elekta Task Dataset: TDE-HMM Pipeline.
In this script we train an Time-Delay Embedded Hidden Markov Model (TDE-HMM)
on source reconstructed task MEG data.
The examples/toolbox_paper/elekta_task/get_data.py script can be used
to download the training data.
Functions listed in the config are defined in osl_dynamics.config_api.wrappers.
"""
from sys import argv
if len(argv) != 2:
print("Please pass the run id, e.g. python tde_hmm.py 1")
exit()
id = int(argv[1])
import mne
import pickle
import numpy as np
from glob import glob
from osl_dynamics import run_pipeline
from osl_dynamics.analysis import statistics
from osl_dynamics.data import Data
from osl_dynamics.inference import modes
from osl_dynamics.utils import plotting
def epoch_state_time_course(stc, tmin=-0.1, tmax=1.5):
"""Get subject-specific evoked responses in the state occupancies."""
# Parcellated data files
parc_files = sorted(glob("data/src/*/sflip_parc-raw.fif"))
# Epoch the state time courses
event_id = {
"famous/first": 5,
"famous/immediate": 6,
"famous/last": 7,
"unfamiliar/first": 13,
"unfamiliar/immediate": 14,
"unfamiliar/last": 15,
"scrambled/first": 17,
"scrambled/immediate": 18,
"scrambled/last": 19,
}
epochs_ = []
for s, p in zip(stc, parc_files):
raw = modes.convert_to_mne_raw(
s,
p,
n_embeddings=15, # this should be what was used to prepare the training data
)
events = mne.find_events(raw, min_duration=0.005, verbose=False)
e = mne.Epochs(
raw,
events,
event_id,
tmin=tmin,
tmax=tmax,
verbose=False,
)
epochs_.append(e.get_data(picks="misc"))
# Time axis (we need to correct for the 34 ms delay in the trigger)
t = e.times - 34e-3
# Calculate subject-specific averaged evoked responses
epochs = []
for e_ in epochs_:
epochs.append(np.mean(e_, axis=0).T)
epochs = np.array(epochs)
# Baseline correct
epochs -= np.mean(
epochs[:, : int(abs(tmin) * raw.info["sfreq"])],
axis=1,
keepdims=True,
)
return t, epochs
def plot_evoked_response(data, output_dir, n_perm, metric, significance_level):
"""Perform evoked response analysis with state time courses."""
# Directories
inf_params_dir = f"{output_dir}/inf_params"
plots_dir = f"{output_dir}/alphas"
# Get inferred state time course
alp = pickle.load(open(f"{inf_params_dir}/alp.pkl", "rb"))
stc = modes.argmax_time_courses(alp)
# Epoch and do stats
t, epochs = epoch_state_time_course(stc)
pvalues = statistics.evoked_response_max_stat_perm(
epochs, n_perm=n_perm, metric=metric
)
# Plot epoched state time courses with significant time points highlighed
plotting.plot_evoked_response(
t,
np.mean(epochs, axis=0),
pvalues,
significance_level=significance_level,
labels=[f"State {i + 1}" for i in range(epochs.shape[-1])],
x_label="Time (s)",
y_label="State Probability",
filename=f"{plots_dir}/epoched_stc.png",
)
# Load data
data = Data(
inputs=sorted(glob("data/src/*/sflip_parc-raw.fif")),
picks="misc",
reject_by_annotation="omit",
sampling_frequency=250,
mask_file="MNI152_T1_8mm_brain.nii.gz",
parcellation_file="fmri_d100_parcellation_with_PCC_reduced_2mm_ss5mm_ds8mm.nii.gz",
store_dir=f"tmp_{id:02d}",
n_jobs=8,
)
data.prepare({
"tde_pca": {"n_embeddings": 15, "n_pca_components": 80},
"standardize": {},
})
# Full pipeline
config = """
train_hmm:
config_kwargs:
n_states: 8
learn_means: False
learn_covariances: True
multitaper_spectra:
kwargs:
frequency_range: [1, 45]
n_jobs: 8
nnmf_components: 2
plot_group_nnmf_tde_hmm_networks:
nnmf_file: spectra/nnmf_2.npy
power_save_kwargs:
plot_kwargs: {views: [lateral]}
plot_alpha:
kwargs: {n_samples: 2000}
plot_hmm_network_summary_stats: {}
plot_evoked_response:
n_perm: 1000
metric: copes
significance_level: 0.05
"""
# Run analysis
run_pipeline(
config,
data=data,
output_dir=f"results/run{id:02d}",
extra_funcs=[plot_evoked_response],
)