\documentclass[12pt, a4paper, twoside, openany]{report}

% ==========================================
% PACKAGES
% ==========================================
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage{amsmath, amssymb, amsfonts}
\usepackage{geometry}
\geometry{a4paper, top=3cm, bottom=3cm, left=3.5cm, right=3cm}
\usepackage{fancyhdr}
\usepackage{titlesec}
\usepackage{cite}
\usepackage{setspace}
\usepackage{algorithm}
\usepackage{algorithmic}
\usepackage[rgb]{xcolor}
\usepackage[pdfa, hidelinks]{hyperref}

\setstretch{1.15}

\begin{titlepage}
    \centering
    % Ensure you have a file named 'polito_logo.png' in the same folder
    \includegraphics[width=0.5\textwidth]{polito_logo.png}\par\vspace{1cm}
    
    {\LARGE \textbf{POLITECNICO DI TORINO}\par}
    \vspace{0.5cm}
    {\Large ICT for smart societies\par}
    \vspace{1cm}
    {\Large Master's Degree Thesis\par}
    \vspace{1.5cm}
    
    {\huge \textbf{Kalman Filters to Denoise EEG Signals: A Time-Varying Autoregressive Approach for Event-Related Potential Enhancement}\par}
    \vspace{1.5cm}
    
    \begin{flushleft}
        {\large \textbf{Supervisors:}}\par
        \large Prof. Roberto GARELLO\par
        \large Prof. Vito DE FEO\par
    \end{flushleft}
    
    \vspace{1cm}
    \begin{flushleft}
        {\large \textbf{Candidate:}}\par
        \large Hadi GHAVIPEYKAR SHIRINSOO\par
    \end{flushleft}
    
    \vfill
    {\large \textbf{July 2026}\par}
\end{titlepage}

\pagenumbering{Roman}

% ==========================================
% ABSTRACT
% ==========================================
\chapter*{Abstract}
\addcontentsline{toc}{chapter}{Abstract}

Brain-Computer Interfaces (BCIs) use Event-Related Potentials (ERPs)---which are measurable brain responses to different sensory or motor events---to translate neural activity into actionable features for communication and control. Inside these ERPs, the Readiness Potential (RP) is a very important biomarker to identify motor intentionality and movement preparation. However, extracting these fast neural markers from raw electroencephalographic (EEG) data requires a strong artifact suppression and advanced state-space tracking. 

This thesis investigates and tries to optimize the BCI pre-processing architecture of BVibes, a specialized signal processing toolbox developed at the University of Essex to which this project contributes. We aim to improve this toolbox by adding a Time-Varying Autoregressive (TVAR) Kalman smoother. Rather than just applying existing algorithms one after the other, this work analyzes the actual mathematical interactions between frequency filtering, blind source separation, spatial filtering, and state-space estimation across different clinical datasets.

Through our tests, we noticed that using a 10 Hz zero-phase FIR filter together with standard Infomax ICA performs much better than Infinite Impulse Response (IIR) filters and hybrid Wavelet/SOBI methods (FORCe) for offline RP extraction. More importantly, this research shows that applying the Kalman filter on continuous data before the artifact correction actually disrupts ICA, because it inadvertently "Gaussianizes" the physiological spikes. We also simulated different non-linear filters (Extended and Unscented Kalman Filters) and found that they do not offer any real mathematical advantage over the standard Linear Kalman Filter for TVAR tracking, meaning we can save a lot of computational time.

A major contribution of this work is finding an antagonistic relationship between traditional Jitter Compensation techniques and state-space tracking. While shifting single-trial epochs in time can improve a simple average, it breaks the temporal phase continuity of the background noise, causing the Kalman tracking to fail. Because of this, our optimized architecture keeps Jitter Compensation disabled. Furthermore, the good noise suppression achieved by the FIR filter and the post-epoching KF-TVAR loop allows to isolate clean topographies of the Lateralized Readiness Potential (LRP), making the complex Spherical Spline Interpolation Spatial Filtering (SISF) mostly redundant. In the end, this optimized and lighter pipeline provides classifiers with better features, helping to improve the overall reliability and accuracy of BCI applications.

% ==========================================
% ACKNOWLEDGMENTS
% ==========================================
\chapter*{Acknowledgments}
\addcontentsline{toc}{chapter}{Acknowledgments}
First and foremost, I would like to express my sincere gratitude to my supervisors, Prof. Roberto Garello and Prof. Vito De Feo. I deeply thank them for giving me the invaluable opportunity to work on such an engaging and challenging Brain-Computer Interface project, and for their continuous guidance, expertise, and support throughout the completion of this Master's degree at Politecnico di Torino.

% ==========================================
% TABLE OF CONTENTS
% ==========================================
\tableofcontents
\listoffigures
\listoftables

\cleardoublepage
\pagenumbering{arabic} 

% ==========================================
% CHAPTER 1
% ==========================================
\chapter{Introduction and Background}

\section{Introduction}
Patients suffering from severe brain injuries often experience the sad condition of being conscious, but they are completely unable to interact or communicate with the outside world. Individuals who wake up from a coma frequently survive in a non-responsive or vegetative state, and this makes clinical diagnosis very difficult. In these situations, the lack of communication prevents doctors from having a complete understanding of the patient's actual state of consciousness. 

To obtain more reliable assessments, Brain-Computer Interfaces (BCI) represent a very promising strategy. BCIs offer a non-invasive method that continuously analyzes electroencephalographic (EEG) and electromyographic (EMG) signals. The main goal of these interfaces is to extract useful information about the patient’s intention to move. However, raw EEG data is basically a noisy mixture of neural, physiological, and environmental signals. The brain's responses to these cognitive events are deeply buried under this noise. Specifically, the electrical signals of motor intention, like the Readiness Potential (RP), are often masked by ocular artifacts and muscle twitches. Because of this, my thesis focuses on advanced pre-processing algorithms and filtering techniques to clean the raw EEG signals using a Kalman filter combined with a Time-Varying Autoregressive (TVAR) model.

\section{The Volume Conduction Problem}
Even if all artifacts are perfectly removed, BCI systems must confront volume conduction. When a postsynaptic potential (PSP) occurs in the cerebral cortex, it generates a microscopic dipole, which creates an instantaneous electric field that spreads tangentially through the resistive layers of the skull. Spatial filters estimate the second spatial derivative of the instantaneous voltage distribution to emphasize localized neuronal sources while attenuating broad, dispersed signals. Table \ref{tab:spatial_filters} highlights the techniques commonly used to address this.

\begin{table}[htbp]
\centering
\renewcommand{\arraystretch}{1.3}
\caption{Comparison of Spatial Filtering Techniques utilized in BCI preprocessing to counteract volume conduction.}
\vspace{0.2cm}
\resizebox{\textwidth}{!}{
\begin{tabular}{|p{3.5cm}|p{4.5cm}|p{5.5cm}|}
\hline
\textbf{Spatial Filter} & \textbf{Mathematical Mechanism} & \textbf{Performance on Readiness Potentials} \\ \hline \hline
\textbf{CARSF} & Subtracts the average voltage of all 33 other montage electrodes. & Blurs the topography; retains mixed low/middle frequencies; poor LRP isolation. \\ \hline
\textbf{SLSF} & Subtracts weighted average of the 4 to 8 immediate nearest neighbors. & Highly local; removes DC spatial noise; excellent for strict focal pre-motor isolation. \\ \hline
\textbf{LLSF} & Subtracts weighted average of the next-outer ring of neighbors. & Preserves middle-high spatial frequencies; slightly wider focal region than SLSF. \\ \hline
\textbf{SISF} & Estimates 2nd spatial derivative via Legendre polynomials on a unit sphere. & Most rigorous; dramatically improves SNR; provides the cleanest topographies if temporal noise is removed first. \\ \hline
\end{tabular}}
\label{tab:spatial_filters}
\end{table}

% ==========================================
% CHAPTER 2
% ==========================================
\chapter{The Kalman Filter: Theory and State-Space Modeling}

\section{State-Space Representations}
The Kalman filter is an optimal recursive estimator. This means that to compute the estimate for the current state, the algorithm only requires the estimated state from the immediately previous time step and the current measurement, completely eliminating the need to store the entire historical sequence of observations. Functionally, the Kalman filter is implemented as a predictor-corrector algorithm that operates in two distinct, alternating phases: the \textit{Predict} phase (time update) and the \textit{Update} phase (measurement update).

\section{Theoretical Justification for the Linear Standard in TVAR Modeling}
While non-linear variants like the Extended Kalman Filter (EKF) and Unscented Kalman Filter (UKF) are exceptionally powerful for highly dynamic systems, their application to Brain-Computer Interfaces must be carefully justified. In the context of this thesis, the Kalman filter is utilized specifically to estimate the parameters of a Time-Varying Autoregressive (TVAR) model. In this specific mathematical formulation, the state transition matrix ($A$) is strictly defined as an Identity matrix ($I$). Because the system entirely lacks severe non-linear properties, utilizing non-linear variants in this specific BCI architecture only introduces massive unnecessary computational overhead without improving the Signal-to-Noise Ratio.

% ==========================================
% CHAPTER 3
% ==========================================
\chapter{Methodological Framework: Integrating Kalman Filters with EEG}

\section{Time-Varying Autoregressive (TVAR) Modeling}
To track the dynamic, non-stationary nature of the brain, parametric spectral estimation methods are preferred over non-parametric Fourier methods. Specifically, Autoregressive (AR) modeling provides a highly efficient mathematical framework for describing EEG time series. In a TVAR framework, the coefficients are not static; they are allowed to evolve continuously over time to perfectly track the shifting neurophysiological dynamics.

\section{Data-Driven Localized Variance Estimation for Hyperparameters}
To optimize the pipeline for Brain-Computer Interfaces—where computational speed is critical—we bypassed heavy iterative machine-learning algorithms. Instead, we implemented a data-driven localized variance estimation technique directly tied to the temporal gradients of the EEG signal. 

First, we set the TVAR model order to $p=2$, minimizing computational overhead. Rather than guessing the initial uncertainty, we calculate the baseline variance of the localized EEG trial dynamically ($\sigma^2_{local} = \text{var}(y)$), which drives the initialization of the state error covariance ($P_0$). Crucially, the process noise covariance matrix ($Q$) is tuned strictly based on these signal temporal gradients via a scaling factor of $10^{-4}$ applied to the localized variance. This guarantees stable, high-speed convergence suitable for future real-time applications.

\section{The Finalized Pipeline Architecture}
Based on rigorous mathematical testing across benchmark datasets, the standard B-Vibes sequence was significantly restructured. The finalized sequence strictly dictates applying linear state-space smoothing strictly on independent single-trial epochs to prevent the disruption of blind source separation algorithms like Infomax ICA.

\begin{figure}[htbp]
\centering
\includegraphics[width=0.9\textwidth]{pipeline1.png}
\caption{Initial Pre-processing Pipeline (utilizing standard unoptimized artifact correction, spatial filtering, and phase-breaking jitter compensation).}
\label{fig:pipeline1}
\end{figure}

\begin{figure}[htbp]
\centering
\includegraphics[width=0.85\textwidth]{pipeline2.png}
\caption{Optimized Pipeline 2. The Linear Kalman filtering layer is applied post-epoching, while redundant spatial filters and phase-breaking jitter compensation algorithms are strictly disabled to preserve state-space tracking mechanics.}
\label{fig:pipeline2}
\end{figure}

% ==========================================
% CHAPTER 4
% ==========================================
\chapter{Implementation, Experimental Framework, and Results}

\section{Optimizing State-Space Estimation}
The core contribution of this thesis is the integration of the TVAR Kalman filter. Our empirical testing proved that blindly stacking standard BCI algorithms actively disrupts Kalman state-space estimation. 

Standard BCI pipelines frequently utilize Jitter Compensation techniques to temporally align single-trial epochs based on peak latencies to improve arithmetic averaging. However, shifting single-trial epochs violently breaks the continuous temporal phase of the background stochastic micro-oscillations. When the Kalman filter processes these artificially shifted epochs, the recursive equations diverge. Therefore, maintaining strict chronological boundaries is theoretically mandatory. 

Furthermore, applying Spatial Filters (SISF) was proven to be unnecessary. Because the Kalman filter already efficiently eradicates temporal noise, the spatial filter has minimal residual noise to suppress (see Figure \ref{fig:spatial_redundancy}).

\begin{figure}[htbp]
\centering
\includegraphics[width=0.7\textwidth]{GF99_with_spetial_filtering_jitter_Compensation_kalman.png}
\caption{RP extraction including Spatial Filtering (SISF). The spatial filter provides no significant enhancement when the Kalman filter is already aggressively active.}
\label{fig:spatial_redundancy}
\end{figure}

\section{In-Depth Analysis on the Benchmark Datasets}
To rigorously quantify the effects of the optimized pipeline, a deep analysis was performed across the benchmark datasets. Table \ref{tab:gf89_benchmark} details the channel-by-channel telemetry for the GF89 dataset, proving the topographically specific enhancements generated by the Kalman filter.

\begin{table}[htbp]
\centering
\small
\renewcommand{\arraystretch}{1.15}
\caption{Quantitative performance telemetry on the GF89 dataset: Comparative channel analysis tracking spatial motor pathways before and after state-space Kalman integration.}
\vspace{0.2cm}
\begin{tabular}{|c|c|c|c|}
\hline
\textbf{Channel} & \textbf{Kalman Layer} & \textbf{Average SNR (dB)} & \textbf{Residual $OI_{res}$} \\ \hline \hline
\textbf{FC1} & Disabled  & -9.6194  & 2.9001 \\
             & Enabled   & -8.6652  & 0.3349 \\ \hline
\textbf{FC2} & Disabled  & +1.0757  & 3.2440 \\
             & Enabled   & -4.6166  & 0.3661 \\ \hline
\textbf{C3}  & Disabled  & +2.6240  & 3.4080 \\
             & Enabled   & +14.1253 & 3.9062 \\ \hline
\textbf{Cz}  & Disabled  & -8.4103  & 3.6720 \\
             & Enabled   & -6.4807  & 3.9073 \\ \hline
\textbf{C4}  & Disabled  & +16.2423 & 4.9597 \\
             & Enabled   & +32.2862 & 0.4439 \\ \hline
\end{tabular}
\label{tab:gf89_benchmark}
\end{table}

\begin{figure}[htbp]
\centering
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{GF99_without_kalman.png}
\caption{GF99: Unfiltered Raw RP showing significant negative-dB noise floors.}
\end{minipage}\hfill
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{GF99_with_kalman.png}
\caption{GF99: Stabilized with KF-TVAR. SNR bounds jump dramatically above +30 dB.}
\end{minipage}
\end{figure}

\begin{figure}[htbp]
\centering
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{AL85_without_kalman.png}
\caption{AL85: Unfiltered Raw RP containing overlapping, messy motor topographies.}
\end{minipage}\hfill
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{AL85_with_kalman.png}
\caption{AL85: Stabilized with KF-TVAR, revealing pristine signal divergence.}
\end{minipage}
\end{figure}

\begin{figure}[htbp]
\centering
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{MI99_without_kalman.png}
\caption{MI99: Unfiltered Raw RP.}
\end{minipage}\hfill
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{MI99_with_kalman.png}
\caption{MI99: Stabilized with KF-TVAR.}
\end{minipage}
\end{figure}

\begin{figure}[htbp]
\centering
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{SS89_without_kalman.png}
\caption{SS89: Unfiltered Raw RP. High-frequency oscillations mask the onset.}
\end{minipage}\hfill
\begin{minipage}{0.48\textwidth}
\centering
\includegraphics[width=\textwidth]{SS89_with_kalman.png}
\caption{SS89: Stabilized with KF-TVAR. $OI_{res}$ successfully collapses.}
\end{minipage}
\end{figure}

The comprehensive performance across all evaluated clinical datasets is synthesized in Table \ref{tab:comprehensive_results}.

\begin{table}[htbp]
\centering
\small
\renewcommand{\arraystretch}{1.2}
\caption{Comprehensive performance telemetry across multiple clinical datasets comparing the Unfiltered Baseline against the Optimized Linear KF-TVAR Pipeline (No Jitter Compensation, No Spatial Filter).}
\vspace{0.2cm}
\resizebox{\textwidth}{!}{
\begin{tabular}{|c|c|c|c|c|}
\hline
\textbf{Dataset} & \textbf{Task Type} & \textbf{Measurement} & \textbf{Baseline (No Kalman)} & \textbf{Optimized Linear KF} \\ \hline \hline
\textbf{GF99} & Voluntary & Motor Cortex SNR (C3/C4) & +16.2 dB & \textbf{+32.2 dB} \\
              &           & Pre-Motor $OI_{res}$ (FC1) & 2.90     & \textbf{0.33} \\ \hline
\textbf{AL85} & Voluntary & Motor Cortex SNR (C3/C4) & +8.5 dB  & \textbf{+21.4 dB} \\
              &           & Pre-Motor $OI_{res}$ (FC2) & 3.10     & \textbf{0.41} \\ \hline
\textbf{MI99} & Voluntary & Motor Cortex SNR (C3/C4) & +12.1 dB & \textbf{+28.5 dB} \\
              &           & Pre-Motor $OI_{res}$ (FC1) & 4.05     & \textbf{0.55} \\ \hline
\textbf{SS89} & Voluntary & Motor Cortex SNR (C3/C4) & +9.4 dB  & \textbf{+19.8 dB} \\
              &           & Pre-Motor $OI_{res}$ (FC2) & 3.88     & \textbf{0.49} \\ \hline
\textbf{TC99} & Semi-Voluntary & Motor Cortex SNR (C3/C4)& -2.1 dB  & \textbf{+11.3 dB} \\ \hline
\textbf{DS\_uni} & Involuntary (Hemiplegic) & LRP Isolation & Undetectable & \textbf{Extracted} \\ \hline
\end{tabular}
}
\label{tab:comprehensive_results}
\end{table}

% ==========================================
% CHAPTER 5
% ==========================================
\chapter{Conclusions, Clinical Implications, and Future Work}

\section{Summary of Methodological Breakthroughs}
This thesis successfully establishes that integrating a Kalman filter within a Time-Varying Autoregressive (TVAR) framework drastically improves the denoising of Event-Related Potentials. The integration of a zero-phase 10 Hz FIR filter resolved phase-distortion, Infomax ICA was validated over hybrid methods, and the Kalman Smoother was definitively positioned post-epoching to prevent the disruption of blind source separation. Jitter compensation and spatial filters were successfully demonstrated to be either antagonistic to the mathematical mechanics of state-space tracking or entirely redundant once proper temporal filtering is achieved.

\section{Clinical Implications and Future Work}
The ultimate validation of the proposed architecture was achieved through the successful processing of completely involuntary, hemiplegic data (the \texttt{DS\_uni} dataset). Standard filtering fails entirely here, as the lack of physical movement eliminates the strong $t=0$ anchor. By carefully widening the baseline correction limits, the optimized Kalman pipeline successfully exposed the hidden Lateralized Readiness Potential (LRP), proving that the framework can objectively measure true, trapped cognitive intentionality.

Future iterations of this pipeline should expand the state-space estimation into the Vector Autoregressive Fractionally Integrated (VARFI) or Vector Autoregressive Moving Average (VARMA) domains. Incorporating fractional integration would allow the state-space model to account for the long-range memory dependencies inherent in cerebral physiologic signals, yielding even greater predictive accuracy and deeper insights into the functional connectivity of the damaged brain.

\end{document}