spm-python 25.1b1.post2__py3-none-any.whl → 25.1b1.post4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,13 @@
1
- import matplotlib.pyplot as plt
1
+ # MNE2MATLAB2MNE - reads in and preprocesses data using MNE, then moves to SPM to do specific preprocessing, then moves back to MNE for the rest of the analysis
2
+
3
+
4
+ import matplotlib.pyplot as plt
2
5
  import numpy as np
3
6
  import mne
4
- import sys
5
- plt.ion()
6
- sys.path.insert(1, r'C:\Users\ybezsudnova\Documents\Git\spm2mne')
7
+ from spm import Struct, spm_opm_amm
8
+ from spm.utils import spm_2_mne_raw, mne_raw_2_spm
7
9
 
8
- from spm_mne_converter import spm_2_mne_raw, mne_raw_2_spm
9
- from spm import *
10
+ plt.ion()
10
11
 
11
12
  # 1. read in the data using mne
12
13
  subject = "sub-002"
@@ -17,7 +18,7 @@ opm_file = (
17
18
  subjects_dir = data_path / "derivatives" / "freesurfer" / "subjects"
18
19
 
19
20
  raw = mne.io.read_raw_fil(opm_file, verbose="error")
20
- raw.crop(120, 210).load_data()
21
+ raw.crop(120, 210).load_data()
21
22
 
22
23
  # 2. Plot raw data using mne
23
24
  picks = mne.pick_types(raw.info, meg=True)
@@ -34,27 +35,31 @@ plt.grid(True)
34
35
  set_kwargs = dict(
35
36
  ylim=(-500, 500), xlim=time_ds[[0, -1]], xlabel="Time (s)", ylabel="Amplitude (pT)"
36
37
  )
37
- ax.set(title="No preprocessing",**set_kwargs)
38
+ ax.set(title="No preprocessing", **set_kwargs)
38
39
  plt.show()
39
40
 
40
- psd_kwargs = dict(fmax=100, n_fft=int(round(raw.info["sfreq"])*2*2))
41
+ psd_kwargs = dict(fmax=100, n_fft=int(round(raw.info["sfreq"]) * 2 * 2))
41
42
  raw.compute_psd(**psd_kwargs).plot(dB=True, amplitude=True)
42
43
 
43
44
  # 2. Some preproceesing using mne
44
45
  raw.notch_filter(np.arange(50, 251, 50), notch_widths=4)
45
46
  raw.filter(1, 70, picks="meg")
46
47
 
47
- ref_mag_name = [ch['ch_name'] for ch in raw.info['chs'] if ch['kind'] == mne.io.constants.FIFF.FIFFV_REF_MEG_CH]
48
- raw.info['bads'] = ref_mag_name
49
- #raw.info['bads'].extend(['G2-A4-RAD','G2-17-TAN'])
48
+ ref_mag_name = [
49
+ ch["ch_name"]
50
+ for ch in raw.info["chs"]
51
+ if ch["kind"] == mne.io.constants.FIFF.FIFFV_REF_MEG_CH
52
+ ]
53
+ raw.info["bads"] = ref_mag_name
54
+ # raw.info['bads'].extend(['G2-A4-RAD','G2-17-TAN'])
50
55
 
51
56
 
52
57
  # 3. MNE 2 SPM
53
- data = mne_raw_2_spm(raw,'D:/opm-tutorial')
58
+ data = mne_raw_2_spm(raw, "D:/opm-tutorial")
54
59
  data
55
60
 
56
61
  # 4. SPM prossesing
57
- S = Struct()
62
+ S = Struct()
58
63
  S.D = data
59
64
  mD = spm_opm_amm(S)
60
65
 
@@ -65,7 +70,7 @@ cleaned_data
65
70
 
66
71
 
67
72
  # 6. MNE plotting
68
- psd_kwargs = dict(fmax=100, n_fft=int(round(cleaned_data.info["sfreq"])*2*2))
73
+ psd_kwargs = dict(fmax=100, n_fft=int(round(cleaned_data.info["sfreq"]) * 2 * 2))
69
74
  cleaned_data.compute_psd(**psd_kwargs).plot(dB=True, amplitude=True)
70
75
 
71
76
 
@@ -83,38 +88,41 @@ ax.grid(True)
83
88
  set_kwargs = dict(
84
89
  ylim=(-500, 500), xlim=time_ds[[0, -1]], xlabel="Time (s)", ylabel="Amplitude (pT)"
85
90
  )
86
- ax.set(title="No preprocessing",**set_kwargs)
91
+ ax.set(title="No preprocessing", **set_kwargs)
87
92
  plt.show()
88
93
 
89
94
 
90
-
91
95
  # 7. MNE epoching
92
- events=[]
93
- events = mne.find_events(cleaned_data, stim_channel ='NI-TRIG',min_duration=0.001)
94
- events_dict = {'trigger':3}
96
+ events = []
97
+ events = mne.find_events(cleaned_data, stim_channel="NI-TRIG", min_duration=0.001)
98
+ events_dict = {"trigger": 3}
95
99
 
96
100
  cleaned_data.filter(2, 40, picks="meg")
97
- epochs = mne.Epochs(cleaned_data,
98
- events,
99
- tmin=-0.1, tmax=0.4,
100
- event_id=events_dict,
101
- detrend = 1,
102
- baseline=[-0.05,0],
103
- preload=True)
101
+ epochs = mne.Epochs(
102
+ cleaned_data,
103
+ events,
104
+ tmin=-0.1,
105
+ tmax=0.4,
106
+ event_id=events_dict,
107
+ detrend=1,
108
+ baseline=[-0.05, 0],
109
+ preload=True,
110
+ )
104
111
 
105
112
 
106
- evoked = epochs['trigger'].average()
113
+ evoked = epochs["trigger"].average()
107
114
  evoked.plot()
108
115
 
109
116
 
110
- radial_channels = [ch for ch in evoked.ch_names if ch.endswith('RAD')] # take on radial sensors
117
+ radial_channels = [
118
+ ch for ch in evoked.ch_names if ch.endswith("RAD")
119
+ ] # take on radial sensors
111
120
  evoked_radial = evoked.pick_channels(radial_channels)
112
121
  fig = evoked_radial.plot_joint()
113
122
 
114
123
 
115
-
116
- tang_channels = [ch for ch in evoked.ch_names if ch.endswith('TAN')] # take on tangatial sensors
124
+ tang_channels = [
125
+ ch for ch in evoked.ch_names if ch.endswith("TAN")
126
+ ] # take on tangatial sensors
117
127
  evoked_tang = evoked.pick_channels(tang_channels)
118
128
  evoked_tang.plot_joint()
119
-
120
-
spm/_version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "25.01.beta1.post2"
1
+ __version__ = "25.01.beta1.post4"
spm/utils/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .spm_mne_converter import mne_raw_2_spm, spm_2_mne_raw
2
+
3
+
4
+ __all__ = ["mne_raw_2_spm", "spm_2_mne_raw"]
@@ -0,0 +1,373 @@
1
+ # spm_mne_converter - a module with converter functions: 1) spm D object to mne.raw object 2) mne.raw to spm D object
2
+
3
+ import numpy as np
4
+
5
+ __all__ = [
6
+ "spm_2_mne_raw",
7
+ "mne_raw_2_spm",
8
+ ]
9
+
10
+
11
+ def spm_2_mne_raw(D):
12
+ """
13
+ Convert an SPM MEEG object (D) to an MNE Raw object.
14
+ This function translates an SPM D object (typically loaded via SPM's MEEG tools in MATLAB or via spm_matlab)
15
+ into an MNE-Python Raw object, preserving channel information, sensor positions, units, and bad channel markings.
16
+ It is intended for use before epoching and has been primarily tested on OPM (Optically Pumped Magnetometer) data.
17
+ Parameters
18
+ ----------
19
+ D : object
20
+ SPM MEEG object (D), expected to provide methods and attributes such as:
21
+ - nchannels(), nsamples(), fsample(), chanlabels(), chantype(), units()
22
+ - sensors(), badchannels(), path()
23
+ Returns
24
+ -------
25
+ raw : mne.io.RawArray
26
+ The corresponding MNE Raw object containing the data and metadata from the SPM D object.
27
+ Notes
28
+ -----
29
+ - Only works before epoching (continuous/pre-epoched data).
30
+ - Channel types and units are mapped from SPM conventions to MNE conventions.
31
+ - Sensor positions and orientations are embedded for MEG and EEG channels.
32
+ - The function attempts to handle the SPM 'tra' matrix for MEG sensor projections.
33
+ - Bad channels are marked in the resulting MNE Raw object.
34
+ - Additional work may be needed for full compatibility with all SPM data types and sensor configurations.
35
+ Examples
36
+ --------
37
+ >>> raw = spm_2_mne_raw(D)
38
+ >>> raw.plot()
39
+ """
40
+ # Converts SPM D object to MNE Raw object
41
+ # importaint: only works before epoching
42
+ # importaint: checked only on opm data
43
+
44
+ try:
45
+ import mne
46
+ except ImportError:
47
+ raise ImportError(
48
+ "MNE-Python is required for this function. Please install it using 'pip install mne'."
49
+ )
50
+
51
+ n_channels = int(D.nchannels())
52
+ sampling_freq = D.fsample()
53
+ # duration = [float(D.time()[0][0]),float(D.time()[0][-1])]
54
+ n_samples = int(D.nsamples())
55
+
56
+ channel_names = list(D.chanlabels())
57
+ type_mapping = {
58
+ "REFMAG": "ref_meg",
59
+ "REFGRAD": "ref_meg",
60
+ "REFPLANAR": "ref_meg",
61
+ "EEG": "eeg",
62
+ "ECG": "ecg",
63
+ "EMG": "emg",
64
+ "LFP": "bio",
65
+ "PHYS": "bio",
66
+ "ILAM": "bio",
67
+ "SRC": "dipole",
68
+ "EOG": "eog",
69
+ "VEOG": "eog",
70
+ "HEOG": "eog",
71
+ "MEG": "mag",
72
+ "MEGMAG": "mag",
73
+ "MEGCOMB": "misc",
74
+ "MEGGRAD": "mag",
75
+ "MEGPLANAR": "grad",
76
+ "TRIG": "stim",
77
+ "Other": "misc",
78
+ }
79
+ channel_types = [type_mapping.get(ch_type, "misc") for ch_type in D.chantype()]
80
+ info = mne.create_info(
81
+ ch_names=channel_names, sfreq=sampling_freq, ch_types=channel_types
82
+ )
83
+
84
+ unit_multipliers = {
85
+ "Nan": 1,
86
+ "mT": 10 ** (-3),
87
+ "nT": 10 ** (-9),
88
+ "pT": 10 ** (-12),
89
+ "fT": 10 ** (-15),
90
+ "T": 1,
91
+ "V": 1,
92
+ "mV": 1,
93
+ }
94
+
95
+ unit_mul_per_ch = [unit_multipliers[unit] for unit in D.units()]
96
+ data = np.zeros((n_channels, n_samples))
97
+ data[:, :] = D[:, :, :]
98
+ data = np.array(
99
+ [
100
+ channel_data * unit_mul
101
+ for channel_data, unit_mul in zip(data, unit_mul_per_ch)
102
+ ]
103
+ )
104
+
105
+ # todo check EEG channels are translating properly
106
+ # sens_ch_start = np.sum([ch_type == 'TRIG' for ch_type in D.chantype()])
107
+ i_meg = 0
108
+ i_eeg = 0
109
+ i_trig = 0
110
+ for i, ch in enumerate(info["chs"]):
111
+ if ch["kind"] == 1:
112
+ k_unit = 10 ** (-3) if D.sensors("MEG").unit == "mm" else 1
113
+ ch["loc"] = np.concatenate(
114
+ (
115
+ D.sensors("MEG").chanpos[i_meg] * k_unit,
116
+ D.sensors("MEG").chanori[i_meg],
117
+ np.zeros(6),
118
+ )
119
+ )
120
+ ch["unit"] = mne.io.constants.FIFF.FIFF_UNIT_T
121
+ ch["unit_mul"] = mne.io.constants.FIFF.FIFF_UNITM_NONE
122
+ ch["range"] = 1.0
123
+ ch["cal"] = 1.0
124
+ ch["coord_frame"] = mne.io.constants.FIFF.FIFFV_COORD_DEVICE
125
+ i_meg += 1
126
+ elif ch["kind"] == 2: # EEG channels
127
+ ch["loc"] = np.concatenate(
128
+ (D.sensors("EEG").chanpos[i_eeg], np.zeros(9))
129
+ ) # CHECK HOW IT WORKS
130
+ ch["unit"] = (
131
+ mne.io.constants.FIFF.FIFF_UNIT_V
132
+ if D.units()[i_eeg] == "V"
133
+ else mne.io.constants.FIFF.FIFF_UNIT_M
134
+ )
135
+ ch["unit_mul"] = mne.io.constants.FIFF.FIFF_UNITM_NONE
136
+ ch["range"] = 1.0
137
+ ch["cal"] = 1.0
138
+ ch["coord_frame"] = mne.io.constants.FIFF.FIFFV_COORD_HEAD
139
+ i_eeg += 1
140
+ elif ch["kind"] == 3:
141
+ ch["unit"] = (
142
+ mne.io.constants.FIFF.FIFF_UNIT_V
143
+ if D.units()[i_trig] == "V"
144
+ else mne.io.constants.FIFF.FIFF_UNIT_M
145
+ )
146
+ ch["unit_mul"] = mne.io.constants.FIFF.FIFF_UNITM_NONE
147
+ i_trig += 1
148
+ # needs work to embed the tra matrix into prog. for now it is saved separetly for researcher to use for correcting forward model
149
+ if D.sensors("MEG").tra.shape[0] != D.sensors("MEG").tra.shape[1]:
150
+ np.savetxt(
151
+ D.path() + "/tra_matrix_from_spm.tsv", D.sensors("MEG").tra, delimiter="\t"
152
+ )
153
+ else:
154
+ U, S, V = np.linalg.svd(D.sensors("MEG").tra, full_matrices=False)
155
+ rank_tra = np.linalg.matrix_rank(D.sensors("MEG").tra)
156
+ V_real = np.conj(V.T)
157
+ proj_vec = []
158
+ proj_vec = V_real[:, rank_tra:]
159
+ from numpy import arange
160
+
161
+ if proj_vec.shape[1] > 0:
162
+ for ii in arange(proj_vec.shape[1]):
163
+ proj_data = dict(
164
+ col_names=list(D.sensors("MEG").label),
165
+ row_names=None,
166
+ data=proj_vec[:, ii].reshape(1, -1),
167
+ ncol=len(D.sensors("MEG").label),
168
+ nrow=1,
169
+ )
170
+ info["projs"].append(
171
+ mne.Projection(
172
+ active=True,
173
+ data=proj_data,
174
+ desc="from matlab tra matrix",
175
+ kind=1,
176
+ explained_var=None,
177
+ )
178
+ )
179
+ # np.savetxt(D.path()+'/tra_matrix_from_spm.tsv', D.sensors('MEG').tra, delimiter='\t')
180
+ bad_channels = D.badchannels()
181
+ if len(bad_channels) > 0:
182
+ info["bads"] = [
183
+ channel_names[i - 1] # python index = matlab index - 1
184
+ for i in bad_channels
185
+ ]
186
+ raw = mne.io.RawArray(data, info)
187
+ return raw
188
+
189
+
190
+ def mne_raw_2_spm(raw, data_path, file_name=None):
191
+ """Convert MNE raw object to SPM D object.
192
+ Parameters
193
+ ----------
194
+ raw : mne.io.Raw
195
+ MNE raw object.
196
+ data_path : str
197
+ Path to save the SPM D object.
198
+ file_name : str, optional
199
+ Name of the SPM D object file. The default is None, in which case the file name is generated based on the raw object.
200
+ Returns
201
+ -------
202
+ D : spm.meeg
203
+ SPM D object.
204
+ """
205
+
206
+ from datetime import datetime
207
+ import os
208
+
209
+ try:
210
+ import mne
211
+ except ImportError:
212
+ raise ImportError(
213
+ "MNE-Python is required for this function. Please install it using 'pip install mne'."
214
+ )
215
+
216
+ from spm import meeg, Struct
217
+
218
+ current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
219
+
220
+ os.chdir(data_path)
221
+ if file_name is None:
222
+ file_name = (
223
+ f"data from mne {str(raw.info['meas_date'])[:10]}_{current_time}.dat"
224
+ )
225
+
226
+ nChans = raw.info["nchan"]
227
+ nSamples = raw.times.shape[0]
228
+ nTrials = 1
229
+ D = meeg(nChans, nSamples, nTrials)
230
+ D = D.fsample(raw.info["sfreq"])
231
+ D = D.path(str(data_path))
232
+ D = D.chanlabels(D, raw.info["ch_names"])
233
+
234
+ type_mapping = {
235
+ mne.io.constants.FIFF.FIFFV_REF_MEG_CH: "ref_meg",
236
+ mne.io.constants.FIFF.FIFFV_EEG_CH: "EEG",
237
+ mne.io.constants.FIFF.FIFFV_ECG_CH: "ECG",
238
+ mne.io.constants.FIFF.FIFFV_EMG_CH: "emg",
239
+ mne.io.constants.FIFF.FIFFV_BIO_CH: "BIO",
240
+ mne.io.constants.FIFF.FIFFV_DIPOLE_WAVE: "dipole",
241
+ mne.io.constants.FIFF.FIFFV_EOG_CH: "EOG",
242
+ mne.io.constants.FIFF.FIFFV_MEG_CH: "MEGMAG",
243
+ mne.io.constants.FIFF.FIFFV_MISC_CH: "misc",
244
+ mne.io.constants.FIFF.FIFFV_STIM_CH: "TRIG",
245
+ }
246
+
247
+ chan_types = [type_mapping[ch["kind"]] for ch in raw.info["chs"]]
248
+ D = D.chantype(D, chan_types)
249
+
250
+ mapping_units = {
251
+ mne.io.constants.FIFF.FIFF_UNIT_T: "T", # Reference MEG channels
252
+ mne.io.constants.FIFF.FIFF_UNIT_V: "V", # EEG channels
253
+ mne.io.constants.FIFF.FIFFV_STIM_CH: "AU",
254
+ mne.io.constants.FIFF.FIFF_UNIT_T_M: "T/m",
255
+ }
256
+ unit_multipliers = {
257
+ mne.io.constants.FIFF.FIFF_UNITM_NONE: "",
258
+ mne.io.constants.FIFF.FIFF_UNITM_M: "m",
259
+ mne.io.constants.FIFF.FIFF_UNITM_M: "micro",
260
+ mne.io.constants.FIFF.FIFF_UNITM_N: "p",
261
+ mne.io.constants.FIFF.FIFF_UNITM_P: "n",
262
+ mne.io.constants.FIFF.FIFF_UNITM_F: "f",
263
+ mne.io.constants.FIFF.FIFF_UNITM_NONE: "",
264
+ }
265
+ chan_units = [
266
+ str(unit_multipliers[ch["unit_mul"]] + mapping_units[ch["unit"]])
267
+ for ch in raw.info["chs"]
268
+ ]
269
+ D = D.units(D, chan_units)
270
+
271
+ meg_label = [None] * (chan_types.count("MEGMAG"))
272
+ meg_chanunit = [None] * (chan_types.count("MEGMAG"))
273
+ meg_chantype = [None] * (chan_types.count("MEGMAG"))
274
+ meg_pos = np.zeros(((chan_types.count("MEGMAG")), 3))
275
+ meg_ori = np.zeros(((chan_types.count("MEGMAG")), 3))
276
+ meg_conter = 0
277
+ eeg_label = [None] * (chan_types.count("EEG"))
278
+ eeg_chanunit = [None] * (chan_types.count("EEG"))
279
+ eeg_chantype = [None] * (chan_types.count("EEG"))
280
+ eeg_pos = np.zeros(((chan_types.count("EEG")), 3))
281
+ eeg_ori = np.zeros(((chan_types.count("EEG")), 3))
282
+ eeg_conter = 0
283
+ for i, ch in enumerate(raw.info["chs"]):
284
+ if chan_types[i] == "MEGMAG":
285
+ meg_pos[meg_conter, :] = [ch["loc"][0], ch["loc"][1], ch["loc"][2]]
286
+ meg_ori[meg_conter, :] = [ch["loc"][3], ch["loc"][4], ch["loc"][5]]
287
+ meg_label[meg_conter] = ch["ch_name"]
288
+ meg_chanunit[meg_conter] = str(
289
+ unit_multipliers[ch["unit_mul"]] + mapping_units[ch["unit"]]
290
+ )
291
+ meg_chantype[meg_conter] = type_mapping[ch["kind"]]
292
+ meg_conter += 1
293
+ if chan_types[i] == "EEG":
294
+ eeg_pos[eeg_conter, :] = [ch["loc"][0], ch["loc"][1], ch["loc"][2]]
295
+ eeg_ori[eeg_conter, :] = [ch["loc"][3], ch["loc"][4], ch["loc"][5]]
296
+ eeg_label[eeg_conter] = ch["ch_name"]
297
+ eeg_chanunit[eeg_conter] = str(
298
+ unit_multipliers[ch["unit_mul"]] + mapping_units[ch["unit"]]
299
+ )
300
+ eeg_chantype[eeg_conter] = type_mapping[ch["kind"]]
301
+ eeg_conter += 1
302
+
303
+ if meg_conter > 0:
304
+ grad = Struct()
305
+ grad.label = meg_label
306
+ grad.coilpos = np.asarray(meg_pos)
307
+ grad.coilpos = np.asarray(meg_pos)
308
+ grad.coilori = np.asarray(meg_ori)
309
+ grad.coilori = np.asarray(meg_ori)
310
+ grad.chanunit = meg_chanunit
311
+ grad.chantype = meg_chantype
312
+
313
+ vec_base = []
314
+ # works oonly when projector is calculated for all the channels
315
+ magnetometer_count = sum(
316
+ 1
317
+ for ch in raw.info["chs"]
318
+ if ch["unit"] == mne.io.constants.FIFF.FIFF_UNIT_T
319
+ )
320
+ for ii, proj in enumerate(raw.info["projs"]):
321
+ if proj["data"]["ncol"] == len(meg_label) and proj["active"]:
322
+ vec_base.append(proj["data"]["data"])
323
+ if vec_base == []:
324
+ grad.tra = np.eye(len(meg_label))
325
+ else:
326
+ vec_array = np.array(vec_base).reshape(len(vec_base), magnetometer_count).T
327
+ grad.tra = np.eye(vec_array.shape[0]) - vec_array @ np.linalg.pinv(
328
+ vec_array
329
+ )
330
+ D = D.sensors("MEG", grad)
331
+
332
+ if eeg_conter > 0:
333
+ grad = Struct()
334
+ grad.label = eeg_label
335
+ grad.coilpos = np.asarray(eeg_pos)
336
+ grad.coilori = np.asarray(eeg_ori)
337
+ grad.chanunit = eeg_chanunit
338
+ grad.chantype = eeg_chantype
339
+
340
+ vec_base = []
341
+ vec_array = []
342
+ eeg_count = sum(
343
+ 1
344
+ for ch in raw.info["chs"]
345
+ if ch["kind"] == mne.io.constants.FIFF.FIFFV_EEG_CH
346
+ )
347
+ for ii, proj in enumerate(raw.info["projs"]):
348
+ if proj["data"]["ncol"] == eeg_count and proj["active"]:
349
+ vec_base.append(proj["data"]["data"])
350
+ if vec_base == []:
351
+ grad.tra = np.eye(len(eeg_label))
352
+ else:
353
+ vec_array = np.array(vec_base).reshape(len(vec_base), eeg_count).T
354
+ grad.tra = np.eye(vec_array.shape[0]) - vec_array @ np.linalg.pinv(
355
+ vec_array
356
+ )
357
+ D = D.sensors("EEG", grad)
358
+
359
+ D.save()
360
+
361
+ D.blank(file_name)
362
+ D = D.link(file_name)
363
+ data = raw.get_data()
364
+ reshaped_data = data.reshape((data.shape[0], data.shape[1], 1))
365
+ D[:, :, :] = reshaped_data
366
+
367
+ if len(raw.info["bads"]) == 1:
368
+ D = D.badchannels(raw.info["ch_names"].index(raw.info["bads"][0]), 1)
369
+ elif len(raw.info["bads"]) > 1:
370
+ for i_bad in raw.info["bads"]:
371
+ D = D.badchannels(raw.info["ch_names"].index(i_bad), 1)
372
+
373
+ return D
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spm-python
3
- Version: 25.1b1.post2
3
+ Version: 25.1b1.post4
4
4
  Summary: Python bindings for the SPM software.
5
5
  Author: Yulia Bezsudnova, Arthur Mitchell, Peter Zeidman, Olivia Kowalczyk
6
6
  Author-email: Johan Medrano <johan.medrano@ucl.ac.uk>, Yael Balbastre <y.balbastre@ucl.ac.yk>
@@ -1,7 +1,8 @@
1
1
  examples/DCM_ERP.py,sha256=MJ6PvOREzGUZVt9Z-PMHv-AcSirS0Q5L7uh8emPGTyE,3565
2
2
  examples/auditory_batch.py,sha256=Z7za9J9HhpIPHdPd-7FvJUPLRL3ytlG6iU2wwYfXW2E,6484
3
+ examples/mne2spm2mne.py,sha256=q1opcybGU1VbBJclXJm0ZJ2AhNBZVZfyZ9u2tXK7R6U,3461
3
4
  spm/__init__.py,sha256=FXx9wwJLdnWDb7jjtal43Dxrk6GD_2GptVxGKfEOkBE,141498
4
- spm/_version.py,sha256=KlqpD_nG7SQ6dOoZI5iDjH1OGuC0Y9EvalgifR6584Y,34
5
+ spm/_version.py,sha256=Knlb8RGK4BRoSCyzSFQaEokld6DdHYkU3m2wNk26qHY,34
5
6
  spm/file_array.py,sha256=oP9e81qvLhld1E1mR1yQjn3BCDE2SZ2U51191-dY_0U,20634
6
7
  spm/gifti.py,sha256=_mMhspgd7yEzVAc7y6DIAlrAVCo3e6q6-AoPowqOvqc,24429
7
8
  spm/meeg.py,sha256=CWXi4lTepO1sxOidmtmbWu64VNTl12thBjETogSwLyw,50562
@@ -3986,8 +3987,10 @@ spm/__toolbox/__spectral/spm_ssm2mtf.py,sha256=GNlA7FxgjhtS-PC37qD6xkLVvITN8BBfI
3986
3987
  spm/__toolbox/__spectral/spm_wavspec.py,sha256=iN5uKekuqri_4DyAUbcOUcyRoYtzgiwZmU2ZQb1u0OI,817
3987
3988
  spm/_spm/__init__.py,sha256=fxn60t8akbH8cp_AQQqzVoYATdMqwEJjnWlrrduvBiI,17271
3988
3989
  spm/_spm/_spm.ctf,sha256=UtKIBHbqyJhQWEmo0mTLEMWi_-6AHmwc1jAsnSJJrBw,82623371
3989
- spm_python-25.1b1.post2.dist-info/licenses/AUTHORS.txt,sha256=zhOOnVZPeLx4uW5sV0oNFoZkqH7nfqrtj1FTT-A4BYQ,918
3990
- spm_python-25.1b1.post2.dist-info/licenses/LICENCE,sha256=gXf5dRMhNSbfLPYYTY_5hsZ1r7UU1OaKQEAQUhuIBkM,18092
3990
+ spm/utils/__init__.py,sha256=xTKZLBr5fC5NYO5J8q3BkoYPvKrOhBbHFpVSzuXmSIM,107
3991
+ spm/utils/spm_mne_converter.py,sha256=kRW6dUpvcaj4QnlecI68tJ6Z3Rx62nR788hY2TA6eC4,13501
3992
+ spm_python-25.1b1.post4.dist-info/licenses/AUTHORS.txt,sha256=zhOOnVZPeLx4uW5sV0oNFoZkqH7nfqrtj1FTT-A4BYQ,918
3993
+ spm_python-25.1b1.post4.dist-info/licenses/LICENCE,sha256=gXf5dRMhNSbfLPYYTY_5hsZ1r7UU1OaKQEAQUhuIBkM,18092
3991
3994
  tests/test_array.py,sha256=KDvZbiWPItWyPwiJQUK2l-QkqUKKUquvY38XXLJqfCA,8255
3992
3995
  tests/test_batch_creation.py,sha256=4p-drlRMzeRMaBo0Y-KfTtuIoHGov1nwXflUBlKjpdA,20365
3993
3996
  tests/test_cell.py,sha256=tJn0bs4-ZJJ4PQxDT3Q_3EI5hThv9pZjXdukmoEG76k,17083
@@ -3996,9 +3999,7 @@ tests/test_matlab_class.py,sha256=3y7xqCdVObDJiULRoZfYdjD6PZnZR_UBnTTjDv9DX9w,40
3996
3999
  tests/test_runtime.py,sha256=V7-YuEvECkARH4ATLUPpchihefs5wi9hVlzfIli4VEg,3871
3997
4000
  tests/test_struct.py,sha256=ktqpLeF5VRW9ssMJkT__uZVBlRCH4S_pN2v6T0ybDig,11398
3998
4001
  tests/test_structarray.py,sha256=EhuUElHnAuXe9QFKgLvGLwAx7GhOnVB_yGzgSuSIDWU,2952
3999
- utils/mne2spm2mne.py,sha256=ox4kPBm0ahPIJZ5bcuvvgLqzGi-fsLWX3BTfeONjMnY,3418
4000
- utils/spm_mne_converter.py,sha256=7m7EUgNLj7Ef1WdU2AeHL5uT1Pid8g845qCzEoMTOwg,10477
4001
- spm_python-25.1b1.post2.dist-info/METADATA,sha256=9en_T55EZDlUNlcB3OVQKPIsmdcClSlFXvVFOKfMcqg,4311
4002
- spm_python-25.1b1.post2.dist-info/WHEEL,sha256=Nw36Djuh_5VDukK0H78QzOX-_FQEo6V37m3nkm96gtU,91
4003
- spm_python-25.1b1.post2.dist-info/top_level.txt,sha256=y32xcujw3wuh6jiVlZncNhp2H5uC3dmoNYfoYwAJ6Zo,25
4004
- spm_python-25.1b1.post2.dist-info/RECORD,,
4002
+ spm_python-25.1b1.post4.dist-info/METADATA,sha256=MQwJNnh5lG8H1H8Fd_P4FGumoaibnX5OwWOirXiBTGc,4311
4003
+ spm_python-25.1b1.post4.dist-info/WHEEL,sha256=zaaOINJESkSfm_4HQVc5ssNzHCPXhJm0kEUakpsEHaU,91
4004
+ spm_python-25.1b1.post4.dist-info/top_level.txt,sha256=e_sdCN9drTWfv_L8ytIam-pJ7hi05BDwSqT__-iiJkA,19
4005
+ spm_python-25.1b1.post4.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (80.7.1)
2
+ Generator: setuptools (80.8.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,256 +0,0 @@
1
- import numpy as np
2
- import mne
3
- from spm import *
4
-
5
- def spm_2_mne_raw(D):
6
- # Converts SPM D object to MNE Raw object
7
- # importaint: only works before epoching
8
- # importaint: checked only on opm data
9
-
10
-
11
- n_channels = int(D.nchannels())
12
- sampling_freq = D.fsample()
13
- duration = [float(D.time()[0]),float(D.time()[-1])]
14
- n_samples =int(D.nsamples())
15
-
16
- channel_names = list(D.chanlabels())
17
- type_mapping = {
18
- 'REFMAG': 'ref_meg',
19
- 'REFGRAD': 'ref_meg',
20
- 'REFPLANAR': 'ref_meg',
21
- 'EEG': 'eeg',
22
- 'ECG': 'ecg',
23
- 'EMG': 'emg',
24
- 'LFP': 'bio',
25
- 'PHYS': 'bio',
26
- 'ILAM': 'bio',
27
- 'SRC': 'dipole',
28
- 'EOG': 'eog',
29
- 'VEOG': 'eog',
30
- 'HEOG': 'eog',
31
- 'ECG': 'ecg',
32
- 'MEG': 'mag',
33
- 'MEGMAG': 'mag',
34
- 'MEGCOMB': 'misc',
35
- 'MEGGRAD': 'mag',
36
- 'MEGPLANAR': 'grad',
37
- 'TRIG': 'stim',
38
- 'Other': 'misc'
39
- }
40
- channel_types = [type_mapping.get(ch_type, 'misc') for ch_type in D.chantype()]
41
- info = mne.create_info(ch_names=channel_names, sfreq=sampling_freq, ch_types=channel_types)
42
-
43
- unit_multipliers = {
44
- "Nan": 1,
45
- "mT": 10**(-3),
46
- "nT": 10**(-9),
47
- "pT": 10**(-12),
48
- "fT": 10**(-15),
49
- "T": 1,
50
- "V": 1,
51
- "mV": 1}
52
-
53
-
54
- unit_mul_per_ch = [unit_multipliers[unit] for unit in D.units()]
55
- data = np.zeros((n_channels, n_samples))
56
- data[:,:] = D[:,:,:]
57
- data = np.array([channel_data * unit_mul for channel_data, unit_mul in zip(data, unit_mul_per_ch)])
58
-
59
- #todo check EEG channels are translating properly
60
- sens_ch_start = np.sum([ch_type == 'TRIG' for ch_type in D.chantype()])
61
- i_meg = 0
62
- i_eeg = 0
63
- i_trig = 0
64
- for i, ch in enumerate(info['chs']):
65
- if ch['kind'] == 1:
66
- k_unit = 10**(-3) if D.sensors('MEG').unit == 'mm' else 1
67
- ch['loc'] = np.concatenate((D.sensors('MEG').chanpos[i_meg]*k_unit, D.sensors('MEG').chanori[i_meg], np.zeros(6)))
68
- ch['unit'] = mne.io.constants.FIFF.FIFF_UNIT_T
69
- ch['unit_mul'] = mne.io.constants.FIFF.FIFF_UNITM_NONE
70
- ch['range'] = 1.0
71
- ch['cal'] = 1.0
72
- ch['coord_frame'] = mne.io.constants.FIFF.FIFFV_COORD_DEVICE
73
- i_meg += 1
74
- elif ch['kind'] == 2: # EEG channels
75
- ch['loc'] = np.concatenate((D.sensors('EEG').chanpos[i_eeg], np.zeros(9))) #CHECK HOW IT WORKS
76
- ch['unit'] = mne.io.constants.FIFF.FIFF_UNIT_V if D.units()[i_eeg] == 'V' else mne.io.constants.FIFF.FIFF_UNIT_M
77
- ch['unit_mul'] = mne.io.constants.FIFF.FIFF_UNITM_NONE
78
- ch['range'] = 1.0
79
- ch['cal'] = 1.0
80
- ch['coord_frame'] = mne.io.constants.FIFF.FIFFV_COORD_HEAD
81
- i_eeg += 1
82
- elif ch['kind'] == 3:
83
- ch['unit'] = mne.io.constants.FIFF.FIFF_UNIT_V if D.units()[i_trig] == 'V' else mne.io.constants.FIFF.FIFF_UNIT_M
84
- ch['unit_mul'] = mne.io.constants.FIFF.FIFF_UNITM_NONE
85
- i_trig += 1
86
- # needs work to embed the tra matrix into prog. for now it is saved separetly for researcher to use for correcting forward model
87
- if D.sensors('MEG').tra.shape[0] != D.sensors('MEG').tra.shape[1]:
88
- np.savetxt(D.path()+'/tra_matrix_from_spm.tsv', D.sensors('MEG').tra, delimiter='\t')
89
- else:
90
- U,S,V = np.linalg.svd(D.sensors('MEG').tra,full_matrices = False)
91
- rank_tra = np.linalg.matrix_rank(D.sensors('MEG').tra)
92
- V_real = np.conj(V.T)
93
- proj_vec=[]
94
- proj_vec = V_real[:,rank_tra:]
95
- from numpy import arange
96
- if proj_vec.shape[1] > 0 :
97
- for ii in arange(proj_vec.shape[1]):
98
- proj_data = dict(
99
- col_names=list(np.asarray(D.sensors('MEG').label.tolist()).reshape(1, -1)[0]),
100
- row_names=None,
101
- data=proj_vec[:, ii].reshape(1, -1),
102
- ncol=len(D.sensors('MEG').label),
103
- nrow=1,
104
- )
105
- info['projs'].append(mne.Projection(active=True, data=proj_data, desc='from matlab tra matrix', kind=1, explained_var=None))
106
- #np.savetxt(D.path()+'/tra_matrix_from_spm.tsv', D.sensors('MEG').tra, delimiter='\t')
107
- bad_channels = D.badchannels().astype(int) # matlab index = (python index + 1)
108
- if D.badchannels().size ==1:
109
- info['bads'] = [channel_names[bad_channels]]
110
- elif D.badchannels().size !=0:
111
- info['bads'] = [channel_names[i] for i in bad_channels]
112
- raw = mne.io.RawArray(data, info)
113
- return raw
114
-
115
-
116
- def mne_raw_2_spm(raw,data_path,file_name = None):
117
-
118
- from datetime import datetime
119
- current_time = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
120
-
121
- import os
122
- os.chdir(data_path)
123
- if file_name is None:
124
- file_name = f"data from mne {str(raw.info['meas_date'])[:10]}_{current_time}.dat"
125
-
126
- nChans = raw.info['nchan']
127
- nSamples = raw.times.shape[0]
128
- nTrials = 1
129
- D = meeg(nChans,nSamples,nTrials)
130
- D = D.fsample(raw.info['sfreq'])
131
- D = D.path(str(data_path))
132
- D = D.chanlabels(D,raw.info['ch_names'])
133
-
134
- type_mapping = {
135
- mne.io.constants.FIFF.FIFFV_REF_MEG_CH: 'ref_meg',
136
- mne.io.constants.FIFF.FIFFV_EEG_CH: 'EEG',
137
- mne.io.constants.FIFF.FIFFV_ECG_CH: 'ECG',
138
- mne.io.constants.FIFF.FIFFV_EMG_CH: 'emg',
139
- mne.io.constants.FIFF.FIFFV_BIO_CH: 'BIO',
140
- mne.io.constants.FIFF.FIFFV_DIPOLE_WAVE: 'dipole',
141
- mne.io.constants.FIFF.FIFFV_EOG_CH: 'EOG',
142
- mne.io.constants.FIFF.FIFFV_MEG_CH: 'MEGMAG',
143
- mne.io.constants.FIFF.FIFFV_MISC_CH: 'misc',
144
- mne.io.constants.FIFF.FIFFV_STIM_CH: 'TRIG'
145
- }
146
-
147
- chan_types = [type_mapping[ch['kind']] for ch in raw.info['chs']]
148
- D = D.chantype(D,chan_types)
149
-
150
- mapping_units = {
151
- mne.io.constants.FIFF.FIFF_UNIT_T: 'T', # Reference MEG channels
152
- mne.io.constants.FIFF.FIFF_UNIT_V: 'V', # EEG channels
153
- mne.io.constants.FIFF.FIFFV_STIM_CH: 'AU',
154
- mne.io.constants.FIFF.FIFF_UNIT_T_M: 'T/m'
155
- }
156
- unit_multipliers = {
157
- mne.io.constants.FIFF.FIFF_UNITM_NONE: '',
158
- mne.io.constants.FIFF.FIFF_UNITM_M: 'm',
159
- mne.io.constants.FIFF.FIFF_UNITM_M: 'micro',
160
- mne.io.constants.FIFF.FIFF_UNITM_N: 'p',
161
- mne.io.constants.FIFF.FIFF_UNITM_P: 'n',
162
- mne.io.constants.FIFF.FIFF_UNITM_F: 'f',
163
- mne.io.constants.FIFF.FIFF_UNITM_NONE: '',
164
- }
165
- chan_units = [str(unit_multipliers[ch['unit_mul']] +mapping_units[ch['unit']]) for ch in raw.info['chs']]
166
- D = D.units(D,chan_units)
167
-
168
- meg_label = [None] * (chan_types.count('MEGMAG'))
169
- meg_chanunit = [None] * (chan_types.count('MEGMAG'))
170
- meg_chantype = [None] * (chan_types.count('MEGMAG'))
171
- meg_pos = np.zeros(((chan_types.count('MEGMAG')), 3))
172
- meg_ori = np.zeros(((chan_types.count('MEGMAG')), 3))
173
- meg_conter=0
174
- eeg_label = [None] * (chan_types.count('EEG'))
175
- eeg_chanunit = [None] * (chan_types.count('EEG'))
176
- eeg_chantype = [None] * (chan_types.count('EEG'))
177
- eeg_pos = np.zeros(((chan_types.count('EEG')), 3))
178
- eeg_ori = np.zeros(((chan_types.count('EEG')), 3))
179
- eeg_conter=0
180
- for i, ch in enumerate(raw.info['chs']):
181
- if chan_types[i] == 'MEGMAG':
182
- meg_pos[meg_conter,:] = [ch['loc'][0],ch['loc'][1],ch['loc'][2]]
183
- meg_ori[meg_conter,:] = [ch['loc'][3],ch['loc'][4],ch['loc'][5]]
184
- meg_label[meg_conter] = ch['ch_name']
185
- meg_chanunit[meg_conter] = str(unit_multipliers[ch['unit_mul']] + mapping_units[ch['unit']])
186
- meg_chantype[meg_conter] = type_mapping[ch['kind']]
187
- meg_conter += 1
188
- if chan_types[i] == 'EEG':
189
- eeg_pos[eeg_conter,:] = [ch['loc'][0],ch['loc'][1],ch['loc'][2]]
190
- eeg_ori[eeg_conter,:] = [ch['loc'][3],ch['loc'][4],ch['loc'][5]]
191
- eeg_label[eeg_conter] = ch['ch_name']
192
- eeg_chanunit[eeg_conter] = str(unit_multipliers[ch['unit_mul']] + mapping_units[ch['unit']])
193
- eeg_chantype[eeg_conter] = type_mapping[ch['kind']]
194
- eeg_conter += 1
195
-
196
- if meg_conter >0:
197
- grad = Struct()
198
- grad.label = meg_label
199
- grad.coilpos = np.asarray(meg_pos)
200
- grad.coilpos = np.asarray(meg_pos)
201
- grad.coilori = np.asarray(meg_ori)
202
- grad.coilori = np.asarray(meg_ori)
203
- grad.chanunit = meg_chanunit
204
- grad.chantype = meg_chantype
205
-
206
- vec_base = []
207
- #works oonly when projector is calculated for all the channels
208
- magnetometer_count = sum(1 for ch in raw.info['chs'] if ch['unit'] == mne.io.constants.FIFF.FIFF_UNIT_T)
209
- for ii, proj in enumerate(raw.info['projs']):
210
- if proj['data']['ncol'] == len(meg_label) and proj['active']:
211
- vec_base.append(proj['data']['data'])
212
- if vec_base == []:
213
- grad.tra = np.eye(len(meg_label))
214
- else:
215
- vec_array = np.array(vec_base).reshape(len(vec_base), magnetometer_count).T
216
- grad.tra = np.eye(vec_array.shape[0]) - vec_array @ np.linalg.pinv(vec_array)
217
- D = D.sensors('MEG', grad)
218
-
219
- if eeg_conter >0:
220
- grad = Struct()
221
- grad.label = eeg_label
222
- grad.coilpos = np.asarray(eeg_pos)
223
- grad.coilori = np.asarray(eeg_ori)
224
- grad.chanunit = eeg_chanunit
225
- grad.chantype = eeg_chantype
226
-
227
- vec_base = []
228
- vec_array = []
229
- eeg_count = sum(1 for ch in raw.info['chs'] if ch['kind'] == mne.io.constants.FIFF.FIFFV_EEG_CH)
230
- for ii, proj in enumerate(raw.info['projs']):
231
- if proj['data']['ncol'] == eeg_count and proj['active']:
232
- vec_base.append(proj['data']['data'])
233
- if vec_base == []:
234
- grad.tra = np.eye(len(eeg_label))
235
- else:
236
- vec_array = np.array(vec_base).reshape(len(vec_base), eeg_count).T
237
- grad.tra = np.eye(vec_array.shape[0]) - vec_array @ np.linalg.pinv(vec_array)
238
- D = D.sensors('EEG', grad)
239
-
240
-
241
- D.save()
242
-
243
- D.blank(file_name)
244
- D=D.link(file_name)
245
- data = raw.get_data()
246
- reshaped_data = data.reshape((data.shape[0], data.shape[1], 1))
247
- D[:,:,:]=reshaped_data
248
-
249
- if len(raw.info['bads']) ==1:
250
- D = D.badchannels(raw.info['ch_names'].index(raw.info['bads'][0]) ,1)
251
- elif len(raw.info['bads']) >1:
252
- for i_bad in raw.info['bads']:
253
- D = D.badchannels(raw.info['ch_names'].index(i_bad) ,1)
254
-
255
-
256
- return D