|
2 | 2 | import math
|
3 | 3 | from cmath import sqrt
|
4 | 4 |
|
| 5 | +import mne |
5 | 6 | import numpy as np
|
6 | 7 | import scipy.interpolate
|
| 8 | +from mne.surface import _normalize_vectors |
| 9 | +from numpy.polynomial.legendre import legval |
7 | 10 | from psutil import virtual_memory
|
| 11 | +from scipy import linalg |
8 | 12 | from scipy.signal import firwin, lfilter, lfilter_zi
|
9 | 13 |
|
10 | 14 |
|
@@ -235,6 +239,143 @@ def _eeglab_fir_filter(data, filt):
|
235 | 239 | return out
|
236 | 240 |
|
237 | 241 |
|
| 242 | +def _eeglab_calc_g(pos_from, pos_to, stiffness=4, num_lterms=7): |
| 243 | + """Calculate spherical spline g function between points on a sphere. |
| 244 | +
|
| 245 | + Parameters |
| 246 | + ---------- |
| 247 | + pos_from : np.ndarray of float, shape(n_good_sensors, 3) |
| 248 | + The electrode positions to interpolate from. |
| 249 | + pos_to : np.ndarray of float, shape(n_bad_sensors, 3) |
| 250 | + The electrode positions to interpolate. |
| 251 | + stiffness : float |
| 252 | + Stiffness of the spline. |
| 253 | + num_lterms : int |
| 254 | + Number of Legendre terms to evaluate. |
| 255 | +
|
| 256 | + Returns |
| 257 | + ------- |
| 258 | + G : np.ndarray of float, shape(n_channels, n_channels) |
| 259 | + The G matrix. |
| 260 | +
|
| 261 | + Notes |
| 262 | + ----- |
| 263 | + Produces identical output to the private ``computeg`` function in EEGLAB's |
| 264 | + ``eeg_interp.m``. |
| 265 | +
|
| 266 | + """ |
| 267 | + # https://github.com/sccn/eeglab/blob/167dfc8/functions/popfunc/eeg_interp.m#L347 |
| 268 | + |
| 269 | + n_to = pos_to.shape[0] |
| 270 | + n_from = pos_from.shape[0] |
| 271 | + |
| 272 | + # Calculate the Euclidian distances between the 'to' and 'from' electrodes |
| 273 | + dxyz = [] |
| 274 | + for i in range(0, 3): |
| 275 | + d1 = np.repeat(pos_to[:, i], n_from).reshape((n_to, n_from)) |
| 276 | + d2 = np.repeat(pos_from[:, i], n_to).reshape((n_from, n_to)).T |
| 277 | + dxyz.append((d1 - d2) ** 2) |
| 278 | + elec_dists = np.sqrt(sum(dxyz)) |
| 279 | + |
| 280 | + # Subtract all the Euclidian electrode distances from 1 (why?) |
| 281 | + EI = np.ones([n_to, n_from]) - elec_dists |
| 282 | + |
| 283 | + # Calculate Legendre coefficients for the given degree and stiffness |
| 284 | + factors = [0] |
| 285 | + for n in range(1, num_lterms + 1): |
| 286 | + f = (2 * n + 1) / (n ** stiffness * (n + 1) ** stiffness * 4 * np.pi) |
| 287 | + factors.append(f) |
| 288 | + |
| 289 | + return legval(EI, factors) |
| 290 | + |
| 291 | + |
| 292 | +def _eeglab_interpolate(data, pos_from, pos_to): |
| 293 | + """Interpolate bad channels using EEGLAB's custom method. |
| 294 | +
|
| 295 | + Parameters |
| 296 | + ---------- |
| 297 | + data : np.ndarray |
| 298 | + A 2-D array containing signals from currently-good EEG channels with |
| 299 | + which to interpolate signals for bad channels. |
| 300 | + pos_from : np.ndarray of float, shape(n_good_sensors, 3) |
| 301 | + The electrode positions to interpolate from. |
| 302 | + pos_to : np.ndarray of float, shape(n_bad_sensors, 3) |
| 303 | + The electrode positions to interpolate. |
| 304 | +
|
| 305 | + Returns |
| 306 | + ------- |
| 307 | + interpolated : np.ndarray |
| 308 | + The interpolated signals for all bad channels. |
| 309 | +
|
| 310 | + Notes |
| 311 | + ----- |
| 312 | + Produces identical output to the private ``spheric_spline`` function in |
| 313 | + EEGLAB's ``eeg_interp.m`` (with minor rounding errors). |
| 314 | +
|
| 315 | + """ |
| 316 | + # https://github.com/sccn/eeglab/blob/167dfc8/functions/popfunc/eeg_interp.m#L314 |
| 317 | + |
| 318 | + # Calculate G for distances between good electrodes + between goods & bads |
| 319 | + G_from = _eeglab_calc_g(pos_from, pos_from) |
| 320 | + G_to_from = _eeglab_calc_g(pos_from, pos_to) |
| 321 | + |
| 322 | + # Get average reference signal for all good channels and subtract from data |
| 323 | + avg_ref = np.mean(data, axis=0) |
| 324 | + data_tmp = data - avg_ref |
| 325 | + |
| 326 | + # Calculate interpolation matrix from electrode locations |
| 327 | + pad_ones = np.ones((1, pos_from.shape[0])) |
| 328 | + C_inv = linalg.pinv(np.vstack([G_from, pad_ones])) |
| 329 | + interp_mat = np.matmul(G_to_from, C_inv[:, :-1]) |
| 330 | + |
| 331 | + # Interpolate bad channels and add average good reference to them |
| 332 | + interpolated = np.matmul(interp_mat, data_tmp) + avg_ref |
| 333 | + |
| 334 | + return interpolated |
| 335 | + |
| 336 | + |
| 337 | +def _eeglab_interpolate_bads(raw): |
| 338 | + """Interpolate bad channels using EEGLAB's custom method. |
| 339 | +
|
| 340 | + This method modifies the provided Raw object in place. |
| 341 | +
|
| 342 | + Parameters |
| 343 | + ---------- |
| 344 | + raw : mne.io.Raw |
| 345 | + An MNE Raw object for which channels marked as "bad" should be |
| 346 | + interpolated. |
| 347 | +
|
| 348 | + Notes |
| 349 | + ----- |
| 350 | + Produces identical results as EEGLAB's ``eeg_interp`` function when using |
| 351 | + the default spheric spline method (with minor rounding errors). This method |
| 352 | + appears to be loosely based on the same general Perrin et al. (1989) method |
| 353 | + as MNE's interpolation, but there are several quirks with the implementation |
| 354 | + that cause it to produce fairly different numbers. |
| 355 | +
|
| 356 | + """ |
| 357 | + # Get the indices of good and bad EEG channels |
| 358 | + eeg_chans = mne.pick_types(raw.info, eeg=True, exclude=[]) |
| 359 | + good_idx = mne.pick_types(raw.info, eeg=True, exclude="bads") |
| 360 | + bad_idx = sorted(_set_diff(eeg_chans, good_idx)) |
| 361 | + |
| 362 | + # Get the spatial coordinates of the good and bad electrodes |
| 363 | + elec_pos = raw._get_channel_positions(picks=eeg_chans) |
| 364 | + pos_good = elec_pos[good_idx, :].copy() |
| 365 | + pos_bad = elec_pos[bad_idx, :].copy() |
| 366 | + _normalize_vectors(pos_good) |
| 367 | + _normalize_vectors(pos_bad) |
| 368 | + |
| 369 | + # Interpolate bad channels |
| 370 | + interp = _eeglab_interpolate(raw._data[good_idx, :], pos_good, pos_bad) |
| 371 | + raw._data[bad_idx, :] = interp |
| 372 | + |
| 373 | + # Clear all bad EEG channels |
| 374 | + eeg_bad_names = [raw.info["ch_names"][i] for i in bad_idx] |
| 375 | + bads_non_eeg = _set_diff(raw.info["bads"], eeg_bad_names) |
| 376 | + raw.info["bads"] = bads_non_eeg |
| 377 | + |
| 378 | + |
238 | 379 | def _get_random_subset(x, size, rand_state):
|
239 | 380 | """Get a random subset of items from a list or array, without replacement.
|
240 | 381 |
|
|
0 commit comments