Repository navigation
Expand file tree
/
Copy pathdemo_simulation.py
More file actions
170 lines (136 loc) · 6.59 KB
/
Copy pathdemo_simulation.py
File metadata and controls
170 lines (136 loc) · 6.59 KB
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
163
164
165
166
167
168
169
170
# -*- coding: utf-8 -*-
import glob
import os
import mne.inverse_sparse.mxne_inverse
import neuromaps.transforms
import numpy as np
import pandas as pd
import utils
def main(path_prefix: str = '.'):
subject_dir = f'{path_prefix}/data/freesurfer'
subject = 'fsaverage'
montage = mne.channels.make_standard_montage('biosemi128')
info = mne.create_info(montage.ch_names, sfreq=1000, ch_types='eeg')
info.set_montage(montage)
# Use canonical fsaverage BEM and source spaces so benchmarks are reproducible across runs.
bem = mne.read_bem_solution(os.path.join(subject_dir, subject, 'bem', 'fsaverage-5120-5120-5120-bem-sol.fif'))
src = mne.read_source_spaces(os.path.join(subject_dir, subject, 'bem', 'fsaverage-ico-5-src.fif'))
# Force regeneration of the transform/forward pair to ensure alignment matches the simulated montage.
trans, fwd, _ = utils.pre_process_for_simulation(subject_dir, subject, bem, src, info, write=True, trans_cal=True)
# Fixed orientation simplifies comparison across inverse solvers and GBFs.
fwd_fixed = mne.convert_forward_solution(fwd, surf_ori=True, force_fixed=True, use_cps=True)
leadfield = fwd_fixed['sol']['data']
src = fwd['src']
base_path = f'{path_prefix}/data'
load_benchmark = False
if not load_benchmark:
benchmark_list = []
sim_data_path = os.path.join(base_path, 'benchmark')
print('Loading benchmark data...')
for nii_file in glob.glob('*.nii.gz', root_dir=os.path.join(sim_data_path)):
mni2fsavg = neuromaps.transforms.mni152_to_fsaverage(os.path.join(sim_data_path, nii_file), '10k')
benchmark_lh = mni2fsavg[0].agg_data()
benchmark_rh = mni2fsavg[1].agg_data()
# Replace pathological values introduced by surface resampling.
benchmark_lh[np.isinf(benchmark_lh)] = 0
benchmark_lh = np.nan_to_num(benchmark_lh)
benchmark_rh[np.isinf(benchmark_rh)] = 0
benchmark_rh = np.nan_to_num(benchmark_rh)
benchmark_lh = benchmark_lh[src[0]['vertno']] * 2e3
benchmark_rh = benchmark_rh[src[1]['vertno']] * 2e3
benchmark_combined = np.hstack((benchmark_lh, benchmark_rh))
max_val = np.max(np.abs(benchmark_combined))
if max_val != 0:
# Normalise each map so metrics focus on spatial accuracy, not scale.
benchmark_combined = benchmark_combined / max_val
benchmark_list.append(benchmark_combined)
benchmark_array = np.array(benchmark_list).T
benchmark = benchmark_array[:, :200]
utils.save_gzip_npy(os.path.join(base_path, 'benchmark.npy.gz'), benchmark)
else:
benchmark = utils.load_gzip_npy(os.path.join(base_path, 'benchmark.npy.gz'))
# Simulate sensor data
timelength = 2000
snr = 5
W, noise_cov, evoked_array, data_cov = utils.prepare_sim_data(benchmark, 1, snr, timelength, leadfield, info)
dict_lambda = {
-20: 5,
-10: 10,
-5: 15,
0: 20,
5: 30,
10: 50,
20: 100,
}
# Base inverse operator shared across minimum-norm variants.
inverse_operator = mne.minimum_norm.make_inverse_operator(info, fwd, noise_cov, depth=False, fixed=True)
method = 'MNE'
snr_102 = dict_lambda[snr]
lambda2 = 1. / snr_102 ** 2
stc_MNE = mne.minimum_norm.apply_inverse(evoked_array, inverse_operator, lambda2, method=method, pick_ori=None)
stc_dSPM = mne.minimum_norm.apply_inverse(evoked_array, inverse_operator, lambda2, method='dSPM', pick_ori=None)
stc_sLORETA = mne.minimum_norm.apply_inverse(evoked_array, inverse_operator, lambda2, method='sLORETA', pick_ori=None)
stc_eLORETA = mne.minimum_norm.apply_inverse(evoked_array, inverse_operator, lambda2, method='eLORETA', pick_ori=None)
# Beamformer provides a spatially selective baseline to compare against GBFs.
filters = mne.beamformer.make_lcmv(evoked_array.info, fwd, data_cov,
reg=0.05, noise_cov=noise_cov, pick_ori=None,
weight_norm='unit-noise-gain', rank=None,
)
# Use a small WMNE grid so it aligns with the benchmark evaluation loop.
source_wmne = utils.WMNE(leadfield, evoked_array.data, [0.3])
stc_wmne = stc_MNE.copy()
stc_wmne.data = source_wmne.squeeze()
stc_mxne = mne.inverse_sparse.mxne_inverse.mixed_norm(evoked_array, fwd, noise_cov)
evals_lh, evals_rh, emodes_lh, emodes_rh = utils.calc_eig_from_src(
src=src,
num_modes=300,
cut=True,
subject_dir=subject_dir,
subject=subject,
save=True
)
ex_data, theta = utils.process_evoked_sim(evoked_array, W, 1, evals_lh, evals_rh, emodes_lh, emodes_rh, src, leadfield)
stc_GBFs = stc_MNE.copy()
stc_GBFs.data = ex_data
methods = {
'MNE': stc_MNE,
'dSPM': stc_dSPM,
'sLORETA': stc_sLORETA,
'eLORETA': stc_eLORETA,
'wmne': stc_wmne,
'GBFs': stc_GBFs,
}
# Metrics cover amplitude, localisation, and similarity perspectives.
metrics = {
'NRMSE': utils.NRMSE_compute,
'LE': lambda _gt, _pred: utils.LE_compute(_gt, _pred, src),
'Correlation': utils.coefficient_compute,
'Cosine': utils.cos_compute,
'SD': utils.calculate_sd_with_normalized_source,
}
results = {metric: {method: [] for method in methods} for metric in metrics}
# Evaluate each method on every simulated benchmark class.
for i in range(benchmark.shape[1]):
gt = benchmark[:, i]
for method, stc in methods.items():
pred = stc.data[:, timelength // 2 + i]
for metric_name, metric_func in metrics.items():
try:
value = metric_func(gt, pred)
results[metric_name][method].append(value)
except Exception as e:
print(f"Error in {metric_name} - {method} at index {i}: {e}")
print("\n==== Evaluation Results ====\n")
table_data = []
for metric_name, method_results in results.items():
for method, values in method_results.items():
mean_val = np.mean(values)
table_data.append([metric_name, method, mean_val])
df = pd.DataFrame(table_data, columns=["Metric", "Method", "Mean Value"])
pivot_df = df.pivot(index="Method", columns="Metric", values="Mean Value")
print(pivot_df.to_string())
# save
os.makedirs(f'{path_prefix}/results/simulation')
pivot_df.to_csv(f'{path_prefix}/results/simulation/simulation_results.csv')
if __name__ == '__main__':
main()