# Bad channel repair via interpolation¶

## Spherical spline interpolation (EEG)¶

In short, data repair using spherical spline interpolation 1 consists of the following steps:

• Project the good and bad electrodes onto a unit sphere

• Compute a mapping matrix that maps $$N$$ good channels to $$M$$ bad channels

• Use this mapping matrix to compute interpolated data in the bad channels

Spherical splines assume that the potential $$V(\boldsymbol{r_i})$$ at any point $$\boldsymbol{r_i}$$ on the surface of the sphere can be represented by:

(1)$V(\boldsymbol{r_i}) = c_0 + \sum_{j=1}^{N}c_{i}g_{m}(cos(\boldsymbol{r_i}, \boldsymbol{r_{j}}))$

where the $$C = (c_{1}, ..., c_{N})^{T}$$ are constants which must be estimated. The function $$g_{m}(\cdot)$$ of order $$m$$ is given by:

(2)$g_{m}(x) = \frac{1}{4 \pi}\sum_{n=1}^{\infty} \frac{2n + 1}{(n(n + 1))^m}P_{n}(x)$

where $$P_{n}(x)$$ are Legendre polynomials of order n.

To estimate the constants $$C$$, we must solve the following two equations simultaneously:

(3)$G_{ss}C + T_{s}c_0 = X$
(4)${T_s}^{T}C = 0$

where $$G_{ss} \in R^{N \times N}$$ is a matrix whose entries are $$G_{ss}[i, j] = g_{m}(cos(\boldsymbol{r_i}, \boldsymbol{r_j}))$$ and $$X \in R^{N \times 1}$$ are the potentials $$V(\boldsymbol{r_i})$$ measured at the good channels. $$T_{s} = (1, 1, ..., 1)^T$$ is a column vector of dimension $$N$$. Equation (3) is the matrix formulation of Equation (1) and equation (4) is like applying an average reference to the data. From equation (3) and (4), we get:

(5)$\begin{split}\begin{bmatrix} c_0 \\ C \end{bmatrix} = {\begin{bmatrix} {T_s}^{T} && 0 \\ T_s && G_{ss} \end{bmatrix}}^{-1} \begin{bmatrix} 0 \\ X \end{bmatrix} = C_{i}X\end{split}$

$$C_{i}$$ is the same as matrix $${\begin{bmatrix} {T_s}^{T} && 0 \\ T_s && G_{ss} \end{bmatrix}}^{-1}$$ but with its first column deleted, therefore giving a matrix of dimension $$(N + 1) \times N$$.

Now, to estimate the potentials $$\hat{X} \in R^{M \times 1}$$ at the bad channels, we have to do:

(6)$\hat{X} = G_{ds}C + T_{d}c_0$

where $$G_{ds} \in R^{M \times N}$$ computes $$g_{m}(\boldsymbol{r_i}, \boldsymbol{r_j})$$ between the bad and good channels. $$T_{d} = (1, 1, ..., 1)^T$$ is a column vector of dimension $$M$$. Plugging in equation (5) in (6), we get

$\begin{split}\hat{X} = \begin{bmatrix} T_d && G_{ds} \end{bmatrix} \begin{bmatrix} c_0 \\ C \end{bmatrix} = \underbrace{\begin{bmatrix} T_d && G_{ds} \end{bmatrix} C_{i}}_\text{mapping matrix}X\end{split}$

To interpolate bad channels, one can simply do:

>>> evoked.interpolate_bads(reset_bads=False)  # doctest: +SKIP


and the bad channel will be fixed.