v2.0.0
Loading...
Searching...
No Matches
xdawn.cpp
Go to the documentation of this file.
1//=============================================================================================================
12
13//=============================================================================================================
14// INCLUDES
15//=============================================================================================================
16
17#include "xdawn.h"
18
19//=============================================================================================================
20// EIGEN INCLUDES
21//=============================================================================================================
22
23#include <Eigen/Dense>
24
25//=============================================================================================================
26// QT INCLUDES
27//=============================================================================================================
28
29#include <QDebug>
30#include <QHash>
31
32//=============================================================================================================
33// C++ INCLUDES
34//=============================================================================================================
35
36#include <algorithm>
37
38//=============================================================================================================
39// USED NAMESPACES
40//=============================================================================================================
41
42using namespace UTILSLIB;
43using namespace MNELIB;
44using namespace Eigen;
45
46//=============================================================================================================
47// PRIVATE HELPERS
48//=============================================================================================================
49
50namespace
51{
52
53MatrixXd computePatterns(const MatrixXd& filters, const MatrixXd& dataCov)
54{
55 if (filters.size() == 0 || dataCov.size() == 0) {
56 return {};
57 }
58
59 MatrixXd gram = filters.transpose() * dataCov * filters;
60 CompleteOrthogonalDecomposition<MatrixXd> cod(gram);
61 return dataCov * filters * cod.pseudoInverse();
62}
63
64} // anonymous namespace
65
66//=============================================================================================================
67// MEMBER DEFINITIONS
68//=============================================================================================================
69
70XdawnResult Xdawn::fit(const QVector<MNEEpochData>& epochs,
71 int iTargetEvent,
72 int nComponents,
73 double dReg)
74{
75 XdawnResult result;
76 result.iTargetEvent = iTargetEvent;
77
78 if (epochs.isEmpty()) {
79 qWarning() << "Xdawn::fit: empty epoch list.";
80 return result;
81 }
82
83 QVector<int> goodIdx;
84 goodIdx.reserve(epochs.size());
85 for (int i = 0; i < epochs.size(); ++i) {
86 if (!epochs[i].bReject) {
87 goodIdx.append(i);
88 }
89 }
90
91 if (goodIdx.isEmpty()) {
92 qWarning() << "Xdawn::fit: no non-rejected epochs available.";
93 return result;
94 }
95
96 const int nCh = static_cast<int>(epochs[goodIdx[0]].epoch.rows());
97 const int nSamp = static_cast<int>(epochs[goodIdx[0]].epoch.cols());
98 if (nCh == 0 || nSamp == 0) {
99 qWarning() << "Xdawn::fit: epoch matrices are empty.";
100 return result;
101 }
102
103 for (int idx : goodIdx) {
104 if (epochs[idx].epoch.rows() != nCh || epochs[idx].epoch.cols() != nSamp) {
105 qWarning() << "Xdawn::fit: epoch dimension mismatch.";
106 return result;
107 }
108 }
109
110 nComponents = std::max(1, std::min(nComponents, nCh));
111
112 QHash<int, MatrixXd> classSums;
113 QHash<int, int> classCounts;
114 MatrixXd targetSum = MatrixXd::Zero(nCh, nSamp);
115 int nTarget = 0;
116
117 for (int idx : goodIdx) {
118 const MNEEpochData& ep = epochs[idx];
119 if (!classSums.contains(ep.event)) {
120 classSums.insert(ep.event, MatrixXd::Zero(nCh, nSamp));
121 classCounts.insert(ep.event, 0);
122 }
123
124 classSums[ep.event] += ep.epoch;
125 classCounts[ep.event] += 1;
126
127 if (ep.event == iTargetEvent) {
128 targetSum += ep.epoch;
129 ++nTarget;
130 }
131 }
132
133 if (nTarget == 0) {
134 qWarning() << "Xdawn::fit: no target epochs found for event" << iTargetEvent;
135 return result;
136 }
137
138 result.matTargetEvoked = targetSum / static_cast<double>(nTarget);
139
140 MatrixXd noiseCov = MatrixXd::Zero(nCh, nCh);
141 MatrixXd dataCov = MatrixXd::Zero(nCh, nCh);
142 long long nNoiseSamples = 0;
143 long long nDataSamples = 0;
144
145 QHash<int, MatrixXd> classMeans;
146 for (auto it = classSums.constBegin(); it != classSums.constEnd(); ++it) {
147 classMeans.insert(it.key(), it.value() / static_cast<double>(classCounts.value(it.key())));
148 }
149
150 for (int idx : goodIdx) {
151 const MNEEpochData& ep = epochs[idx];
152 const MatrixXd residual = ep.epoch - classMeans.value(ep.event);
153
154 dataCov += ep.epoch * ep.epoch.transpose();
155 noiseCov += residual * residual.transpose();
156 nDataSamples += nSamp;
157 nNoiseSamples += nSamp;
158 }
159
160 if (nNoiseSamples <= 0 || nDataSamples <= 0) {
161 qWarning() << "Xdawn::fit: failed to accumulate covariance samples.";
162 return result;
163 }
164
165 result.matSignalCov = result.matTargetEvoked * result.matTargetEvoked.transpose() / static_cast<double>(nSamp);
166 result.matNoiseCov = noiseCov / static_cast<double>(nNoiseSamples);
167 dataCov = dataCov / static_cast<double>(nDataSamples);
168
169 const double traceNoise = result.matNoiseCov.trace();
170 const double regValue = std::max(dReg, 0.0) * ((traceNoise > 0.0) ? traceNoise / static_cast<double>(nCh) : 1.0);
171 MatrixXd regNoiseCov = result.matNoiseCov;
172 regNoiseCov.diagonal().array() += regValue;
173
174 SelfAdjointEigenSolver<MatrixXd> noiseEig(regNoiseCov);
175 if (noiseEig.info() != Success) {
176 qWarning() << "Xdawn::fit: noise covariance eigendecomposition failed.";
177 return result;
178 }
179
180 VectorXd noiseVals = noiseEig.eigenvalues().cwiseMax(1e-12);
181 MatrixXd noiseVecs = noiseEig.eigenvectors();
182 MatrixXd invSqrtNoise = noiseVecs * noiseVals.cwiseInverse().cwiseSqrt().asDiagonal() * noiseVecs.transpose();
183
184 MatrixXd whitenedSignal = invSqrtNoise * result.matSignalCov * invSqrtNoise;
185 SelfAdjointEigenSolver<MatrixXd> signalEig(whitenedSignal);
186 if (signalEig.info() != Success) {
187 qWarning() << "Xdawn::fit: signal covariance eigendecomposition failed.";
188 return result;
189 }
190
191 result.matFilters.resize(nCh, nComponents);
192 const MatrixXd signalVecsAsc = signalEig.eigenvectors().rightCols(nComponents);
193 MatrixXd signalVecs(signalVecsAsc.rows(), signalVecsAsc.cols());
194 for (int i = 0; i < nComponents; ++i) {
195 signalVecs.col(i) = signalVecsAsc.col(nComponents - 1 - i);
196 }
197
198 result.matFilters = invSqrtNoise * signalVecs;
199
200 for (int col = 0; col < result.matFilters.cols(); ++col) {
201 const double noiseNorm = std::sqrt(result.matFilters.col(col).transpose() * regNoiseCov * result.matFilters.col(col));
202 if (noiseNorm > 1e-12) {
203 result.matFilters.col(col) /= noiseNorm;
204 }
205 }
206
207 result.matPatterns = computePatterns(result.matFilters, dataCov);
208 result.bValid = true;
209 return result;
210}
211
212//=============================================================================================================
213
214MatrixXd Xdawn::apply(const MatrixXd& matEpoch, const XdawnResult& result)
215{
216 if (!result.bValid || result.matFilters.size() == 0) {
217 return {};
218 }
219
220 if (matEpoch.rows() != result.matFilters.rows()) {
221 qWarning() << "Xdawn::apply: channel count mismatch.";
222 return {};
223 }
224
225 return result.matFilters.transpose() * matEpoch;
226}
227
228//=============================================================================================================
229
230MatrixXd Xdawn::denoise(const MatrixXd& matEpoch, const XdawnResult& result, int nComponents)
231{
232 if (!result.bValid || result.matFilters.size() == 0 || result.matPatterns.size() == 0) {
233 return matEpoch;
234 }
235
236 if (matEpoch.rows() != result.matFilters.rows()) {
237 qWarning() << "Xdawn::denoise: channel count mismatch.";
238 return {};
239 }
240
241 if (nComponents <= 0 || nComponents > result.matFilters.cols()) {
242 nComponents = result.matFilters.cols();
243 }
244
245 MatrixXd filters = result.matFilters.leftCols(nComponents);
246 MatrixXd patterns = result.matPatterns.leftCols(nComponents);
247
248 return patterns * (filters.transpose() * matEpoch);
249}
250
251//=============================================================================================================
252
253QVector<MNEEpochData> Xdawn::denoiseEpochs(const QVector<MNEEpochData>& epochs,
254 const XdawnResult& result,
255 int nComponents)
256{
257 QVector<MNEEpochData> out = epochs;
258 for (int i = 0; i < out.size(); ++i) {
259 out[i].epoch = denoise(out[i].epoch, result, nComponents);
260 }
261 return out;
262}
Declaration of the Xdawn class for event-related response enhancement.
Core MNE data structures (source spaces, source estimates, hemispheres).
Shared utilities (I/O helpers, spectral analysis, layout management, warp algorithms).
Result of an xDAWN decomposition.
Definition xdawn.h:55
Eigen::MatrixXd matSignalCov
Definition xdawn.h:58
Eigen::MatrixXd matPatterns
Definition xdawn.h:57
Eigen::MatrixXd matNoiseCov
Definition xdawn.h:59
Eigen::MatrixXd matFilters
Definition xdawn.h:56
Eigen::MatrixXd matTargetEvoked
Definition xdawn.h:60
static Eigen::MatrixXd apply(const Eigen::MatrixXd &matEpoch, const XdawnResult &result)
Definition xdawn.cpp:214
static QVector< MNELIB::MNEEpochData > denoiseEpochs(const QVector< MNELIB::MNEEpochData > &epochs, const XdawnResult &result, int nComponents=-1)
Definition xdawn.cpp:253
static XdawnResult fit(const QVector< MNELIB::MNEEpochData > &epochs, int iTargetEvent=1, int nComponents=2, double dReg=1e-6)
Definition xdawn.cpp:70
static Eigen::MatrixXd denoise(const Eigen::MatrixXd &matEpoch, const XdawnResult &result, int nComponents=-1)
Definition xdawn.cpp:230
Single epoch (trial slice) of sensor data with timing and rejection metadata.
Eigen::MatrixXd epoch
FIFFLIB::fiff_int_t event