v2.0.0
Loading...
Searching...
No Matches
inv_dipole_fit_data.cpp
Go to the documentation of this file.
1//=============================================================================================================
20
21//=============================================================================================================
22// INCLUDES
23//=============================================================================================================
24
25#include <fwd/fwd_types.h>
26
27#include "inv_dipole_fit_data.h"
28#include "inv_guess_data.h"
29#include <mne/mne_meas_data.h>
31#include <mne/mne_proj_item.h>
32#include <mne/mne_cov_matrix.h>
33#include "inv_ecd.h"
34
35#include <fiff/fiff_stream.h>
36#include <fiff/fiff_info.h>
38#include <fwd/fwd_bem_model.h>
39#include <mne/mne_surface.h>
40
41#include <fwd/fwd_comp_data.h>
42
44#include <math/sphere.h>
45
46#include <Eigen/Dense>
47
48#include <QFile>
49#include <QTextStream>
50#include <QCoreApplication>
51#include <QDebug>
52
53#include <cmath>
54
55using namespace Eigen;
56using namespace FIFFLIB;
57using namespace MNELIB;
58using namespace FWDLIB;
59using namespace INVLIB;
60
61constexpr int FAIL = -1;
62constexpr int OK = 0;
63
64//=============================================================================================================
65// DEFINE MEMBER METHODS
66//=============================================================================================================
67
70, nmeg(0)
71, neeg(0)
72, r0(Eigen::Vector3f::Zero())
73, funcs(nullptr)
74, fixed_noise(false)
75, nave(1)
77, fit_mag_dipoles(false)
78, user(nullptr)
79{
80}
81
82//=============================================================================================================
83
85{
86 // unique_ptr members auto-cleanup (including sphere_funcs, bem_funcs, mag_dipole_funcs)
87}
88
89//=============================================================================================================
90
95{
97 int fit_sphere_to_bem = true;
98
99 if (!d->bemname.isEmpty()) {
100 /*
101 * Set up the boundary-element model
102 */
103 QString bemsolname = FwdBemModel::fwd_bem_make_bem_sol_name(d->bemname);
104 d->bemname = bemsolname;
105
106 qInfo("\nSetting up the BEM model using %s...", d->bemname.toUtf8().constData());
107 qInfo("\nLoading surfaces...");
109 if (d->bem_model) {
110 qInfo("Three-layer model surfaces loaded.");
111 } else {
113 if (!d->bem_model)
114 return FAIL;
115 qInfo("Homogeneous model surface loaded.");
116 }
117 if (d->neeg > 0 && d->bem_model->nsurf == 1) {
118 qCritical("Cannot use a homogeneous model in EEG calculations.");
119 return FAIL;
120 }
121 qInfo("\nLoading the solution matrix...");
122 if (d->bem_model->fwd_bem_load_recompute_solution(d->bemname, FWD_BEM_UNKNOWN, false) == FAIL)
123 return FAIL;
124 qInfo("Employing the head->MRI coordinate transform with the BEM model.");
125 Q_ASSERT(d->mri_head_t);
126 if (d->bem_model->fwd_bem_set_head_mri_t(*d->mri_head_t) == FAIL)
127 return FAIL;
128 qInfo("BEM model %s is now set up", d->bem_model->sol_name.toUtf8().constData());
129 /*
130 * Find the best-fitting sphere
131 */
132 if (fit_sphere_to_bem) {
133 MNESurface* inner_skull;
134 float simplex_size = 2e-2f;
135 float R;
136 VectorXf r0_vec;
137
138 if ((inner_skull = d->bem_model->fwd_bem_find_surface(FIFFV_BEM_SURF_ID_BRAIN)) == nullptr)
139 return FAIL;
140
141 if (!UTILSLIB::Sphere::fit_sphere_to_points(inner_skull->rr, simplex_size, r0_vec, R))
142 return FAIL;
143 d->r0 = r0_vec.head<3>();
144
145 FiffCoordTrans::apply_trans(d->r0.data(), *d->mri_head_t, true);
146 qInfo("Fitted sphere model origin : %6.1f %6.1f %6.1f mm rad = %6.1f mm.",
147 1000 * d->r0[0], 1000 * d->r0[1], 1000 * d->r0[2], 1000 * R);
148 }
149 d->bem_funcs = std::make_unique<dipoleFitFuncsRec>();
150 f = d->bem_funcs.get();
151 if (d->nmeg > 0) {
152 /*
153 * Use the new compensated field computation
154 * It works the same way independent of whether or not the compensation is in effect
155 */
156 auto comp = FwdCompData::fwd_make_comp_data(comp_data, d->meg_coils.get(), comp_coils,
157 FwdBemModel::fwd_bem_field, nullptr, nullptr, d->bem_model.get());
158 if (!comp)
159 return FAIL;
160 qInfo("Compensation setup done.");
161
162 qInfo("MEG solution matrix...");
163 if (d->bem_model->fwd_bem_specify_coils(d->meg_coils.get()) == FAIL)
164 return FAIL;
165 if (d->bem_model->fwd_bem_specify_coils(comp->comp_coils.get()) == FAIL)
166 return FAIL;
167 qInfo("[done]");
168
170 f->meg_vec_field = nullptr;
171 f->meg_client = comp.get();
172 f->meg_comp = std::move(comp);
173 }
174 if (d->neeg > 0) {
175 qInfo("\tEEG solution matrix...");
176 if (d->bem_model->fwd_bem_specify_els(d->eeg_els.get()) == FAIL)
177 return FAIL;
178 qInfo("[done]");
180 f->eeg_vec_pot = nullptr;
181 f->eeg_client = d->bem_model.get();
182 }
183 }
184 if (d->neeg > 0 && !d->eeg_model) {
185 qCritical("EEG sphere model not defined.");
186 return FAIL;
187 }
188 d->sphere_funcs = std::make_unique<dipoleFitFuncsRec>();
189 f = d->sphere_funcs.get();
190 if (d->neeg > 0) {
191 d->eeg_model->r0 = d->r0;
194 f->eeg_client = d->eeg_model.get();
195 }
196 if (d->nmeg > 0) {
197 /*
198 * Use the new compensated field computation
199 * It works the same way independent of whether or not the compensation is in effect
200 */
201 auto comp = FwdCompData::fwd_make_comp_data(comp_data, d->meg_coils.get(), comp_coils,
204 nullptr,
205 d->r0.data());
206 if (!comp)
207 return FAIL;
210 f->meg_client = comp.get();
211 f->meg_comp = std::move(comp);
212 }
213 qInfo("Sphere model origin : %6.1f %6.1f %6.1f mm.",
214 1000 * d->r0[0], 1000 * d->r0[1], 1000 * d->r0[2]);
215 /*
216 * Finally add the magnetic dipole fitting functions (for special purposes)
217 */
218 d->mag_dipole_funcs = std::make_unique<dipoleFitFuncsRec>();
219 f = d->mag_dipole_funcs.get();
220 if (d->nmeg > 0) {
221 /*
222 * Use the new compensated field computation
223 * It works the same way independent of whether or not the compensation is in effect
224 */
225 auto comp = FwdCompData::fwd_make_comp_data(comp_data, d->meg_coils.get(), comp_coils,
228 nullptr,
229 nullptr);
230 if (!comp)
231 return FAIL;
234 f->meg_client = comp.get();
235 f->meg_comp = std::move(comp);
236 }
239 /*
240 * Select the appropriate fitting function
241 */
242 d->funcs = !d->bemname.isEmpty() ? d->bem_funcs.get() : d->sphere_funcs.get();
243
244 return OK;
245}
246
247//=============================================================================================================
248
252std::unique_ptr<MNECovMatrix> InvDipoleFitData::ad_hoc_noise(FwdCoilSet* meg, FwdCoilSet* eeg, float grad_std, float mag_std, float eeg_std)
253{
254 int nchan;
255 Eigen::VectorXd stds;
256 QStringList names, ch_names;
257 int k, n;
258
259 qInfo("Using standard noise values "
260 "(MEG grad : %6.1f fT/cm MEG mag : %6.1f fT EEG : %6.1f uV)\n",
261 1e13 * grad_std, 1e15 * mag_std, 1e6 * eeg_std);
262
263 nchan = 0;
264 if (meg)
265 nchan = nchan + meg->ncoil();
266 if (eeg)
267 nchan = nchan + eeg->ncoil();
268
269 stds.resize(nchan);
270
271 n = 0;
272 if (meg) {
273 for (k = 0; k < meg->ncoil(); k++, n++) {
274 if (meg->coils[k]->is_axial_coil()) {
275 stds[n] = static_cast<double>(mag_std) * mag_std;
276#ifdef TEST_REF
277 if (meg->coils[k]->type == FIFFV_COIL_CTF_REF_MAG ||
278 meg->coils[k]->type == FIFFV_COIL_CTF_REF_GRAD ||
279 meg->coils[k]->type == FIFFV_COIL_CTF_REF_GOFF)
280 stds[n] = 1e6 * stds[n];
281#endif
282 } else
283 stds[n] = static_cast<double>(grad_std) * grad_std;
284 ch_names.append(meg->coils[k]->chname);
285 }
286 }
287 if (eeg) {
288 for (k = 0; k < eeg->ncoil(); k++, n++) {
289 stds[n] = static_cast<double>(eeg_std) * eeg_std;
290 ch_names.append(eeg->coils[k]->chname);
291 }
292 }
293 names = ch_names;
294 return MNECovMatrix::create(FIFFV_MNE_NOISE_COV, nchan, names, Eigen::VectorXd(), stds);
295}
296
297//=============================================================================================================
298
300{
301 float nave_ratio = static_cast<float>(f->nave) / static_cast<float>(nave);
302 int k;
303
304 if (!f->noise)
305 return OK;
306
307 if (f->noise->cov.size() > 0) {
308 qInfo("Decomposing the sensor noise covariance matrix...");
309 if (f->noise->decompose_eigen() == FAIL)
310 return FAIL;
311
312 for (k = 0; k < f->noise->ncov * (f->noise->ncov + 1) / 2; k++)
313 f->noise->cov[k] = nave_ratio * f->noise->cov[k];
314 for (k = 0; k < f->noise->ncov; k++) {
315 f->noise->lambda[k] = nave_ratio * f->noise->lambda[k];
316 if (f->noise->lambda[k] < 0.0)
317 f->noise->lambda[k] = 0.0;
318 }
319 if (f->noise->add_inv() == FAIL)
320 return FAIL;
321 } else {
322 for (k = 0; k < f->noise->ncov; k++)
323 f->noise->cov_diag[k] = nave_ratio * f->noise->cov_diag[k];
324 qInfo("Decomposition not needed for a diagonal noise covariance matrix.");
325 if (f->noise->add_inv() == FAIL)
326 return FAIL;
327 }
328 qInfo("Effective nave is now %d", nave);
329 f->nave = nave;
330 return OK;
331}
332
333//=============================================================================================================
334
336{
337 float nave_ratio = static_cast<float>(f->nave) / static_cast<float>(nave);
338 int k;
339
340 if (!f->noise)
341 return OK;
342 if (f->fixed_noise)
343 return OK;
344
345 if (f->noise->cov.size() > 0) {
346 /*
347 * Do the decomposition and check that the matrix is positive definite
348 */
349 qInfo("Decomposing the noise covariance...");
350 if (f->noise->cov.size() > 0) {
351 if (f->noise->decompose_eigen() == FAIL)
352 return FAIL;
353 for (k = 0; k < f->noise->ncov; k++) {
354 if (f->noise->lambda[k] < 0.0)
355 f->noise->lambda[k] = 0.0;
356 }
357 }
358 for (k = 0; k < f->noise->ncov * (f->noise->ncov + 1) / 2; k++)
359 f->noise->cov[k] = nave_ratio * f->noise->cov[k];
360 for (k = 0; k < f->noise->ncov; k++) {
361 f->noise->lambda[k] = nave_ratio * f->noise->lambda[k];
362 if (f->noise->lambda[k] < 0.0)
363 f->noise->lambda[k] = 0.0;
364 }
365 if (f->noise->add_inv() == FAIL)
366 return FAIL;
367 } else {
368 for (k = 0; k < f->noise->ncov; k++)
369 f->noise->cov_diag[k] = nave_ratio * f->noise->cov_diag[k];
370 qInfo("Decomposition not needed for a diagonal noise covariance matrix.");
371 if (f->noise->add_inv() == FAIL)
372 return FAIL;
373 }
374 qInfo("Effective nave is now %d", nave);
375 f->nave = nave;
376 return OK;
377}
378
379//=============================================================================================================
380
391 MNEMeasData* meas,
392 int nave_in,
393 const int* sels)
394{
395 int nave, j, k;
396 float nonsel_w = 30;
397 int min_nchan = 20;
398
399 if (!f || !f->noise_orig)
400 return OK;
401 if (!meas)
402 nave = 1;
403 else {
404 if (nave_in < 0)
405 nave = meas->current->nave;
406 else
407 nave = nave_in;
408 }
409 /*
410 * Channel selection
411 */
412 if (meas && sels) {
413 std::vector<float> wVec(f->noise_orig->ncov);
414 float* w = wVec.data();
415 int nomit_meg, nomit_eeg, nmeg, neeg;
416
417 nmeg = neeg = 0;
418 nomit_meg = nomit_eeg = 0;
419 for (k = 0; k < f->noise_orig->ncov; k++) {
420 if (f->noise_orig->ch_class[k] == MNE_COV_CH_EEG)
421 neeg++;
422 else
423 nmeg++;
424 /* Check whether this channel is selected in the measurement */
425 bool selected = false;
426 for (int c = 0; c < meas->nchan; c++) {
427 if (QString::compare(f->noise_orig->names[k],
428 meas->chs[c].ch_name,
429 Qt::CaseInsensitive) == 0) {
430 selected = sels[c] != 0;
431 break;
432 }
433 }
434 if (selected)
435 w[k] = 1.0;
436 else {
437 w[k] = nonsel_w;
438 if (f->noise_orig->ch_class[k] == MNE_COV_CH_EEG)
439 nomit_eeg++;
440 else
441 nomit_meg++;
442 }
443 }
444 f->noise.reset();
445 if (nmeg > 0 && nmeg - nomit_meg > 0 && nmeg - nomit_meg < min_nchan) {
446 qCritical("Too few MEG channels remaining");
447 return FAIL;
448 }
449 if (neeg > 0 && neeg - nomit_eeg > 0 && neeg - nomit_eeg < min_nchan) {
450 qCritical("Too few EEG channels remaining");
451 return FAIL;
452 }
453 f->noise = f->noise_orig->dup();
454 if (nomit_meg + nomit_eeg > 0) {
455 if (f->noise->cov.size() > 0) {
456 for (j = 0; j < f->noise->ncov; j++)
457 for (k = 0; k <= j; k++) {
458 f->noise->cov[MNECovMatrix::lt_packed_index(j, k)] *= static_cast<double>(w[j]) * w[k];
459 }
460 } else {
461 for (j = 0; j < f->noise->ncov; j++) {
462 f->noise->cov_diag[j] *= static_cast<double>(w[j]) * w[j];
463 }
464 }
465 }
466 } else {
467 if (f->noise && f->nave == nave)
468 return OK;
469 f->noise = f->noise_orig->dup();
470 }
471
473}
474
475//=============================================================================================================
476
481 const QString& measname,
482 const QString& bemname,
483 Vector3f* r0,
485 int accurate_coils,
486 const QString& badname,
487 const QString& noisename,
488 float grad_std,
489 float mag_std,
490 float eeg_std,
491 float mag_reg,
492 float grad_reg,
493 float eeg_reg,
494 int diagnoise,
495 const QList<QString>& projnames,
496 int include_meg,
497 int include_eeg)
498{
499 auto res = std::make_unique<InvDipoleFitData>();
500 QStringList badlist;
501 int nbad = 0;
502 QStringList file_bads;
503 int file_nbad = 0;
505 std::unique_ptr<MNECovMatrix> cov;
506 std::unique_ptr<FwdCoilSet> templates;
507 std::unique_ptr<MNECTFCompDataSet> comp_data;
508 std::unique_ptr<FwdCoilSet> comp_coils;
509
510 /*
511 * Read the coordinate transformations
512 */
513 if (!mriname.isEmpty()) {
514 res->mri_head_t = std::make_unique<FiffCoordTrans>(FiffCoordTrans::readMriTransform(mriname));
515 if (res->mri_head_t->isEmpty())
516 return nullptr;
517 } else if (!bemname.isEmpty()) {
518 qWarning("Source of MRI / head transform required for the BEM model is missing");
519 return nullptr;
520 } else {
521 float move[] = {0.0, 0.0, 0.0};
522 float rot[3][3] = {{1.0, 0.0, 0.0},
523 {0.0, 1.0, 0.0},
524 {0.0, 0.0, 1.0}};
525 Eigen::Matrix3f rotMat;
526 rotMat << rot[0][0], rot[0][1], rot[0][2],
527 rot[1][0], rot[1][1], rot[1][2],
528 rot[2][0], rot[2][1], rot[2][2];
529 Eigen::Vector3f moveVec = Eigen::Map<Eigen::Vector3f>(move);
530 res->mri_head_t = std::make_unique<FiffCoordTrans>(FIFFV_COORD_MRI, FIFFV_COORD_HEAD, rotMat, moveVec);
531 }
532
533 res->mri_head_t->print();
534 res->meg_head_t = std::make_unique<FiffCoordTrans>(FiffCoordTrans::readMeasTransform(measname));
535 if (res->meg_head_t->isEmpty())
536 return nullptr;
537 res->meg_head_t->print();
538 /*
539 * Read the bad channel lists
540 */
541 if (!badname.isEmpty()) {
542 if (!FiffInfoBase::readBadChannelsFromFile(badname, badlist))
543 return nullptr;
544 nbad = badlist.size();
545 qInfo("%d bad channels read from %s.", nbad, badname.toUtf8().data());
546 }
547 {
548 QFile measFile(measname);
549 FiffStream::SPtr measStream(new FiffStream(&measFile));
550 if (measStream->open()) {
551 file_bads = measStream->read_bad_channels(measStream->dirtree());
552 file_nbad = file_bads.size();
553 measStream->close();
554 }
555 }
556 if (file_nbad > 0) {
557 if (badlist.isEmpty())
558 nbad = 0;
559 for (int k = 0; k < file_nbad; k++) {
560 badlist.append(file_bads[k]);
561 nbad++;
562 }
563 file_bads.clear();
564 qInfo("%d bad channels read from the data file.", file_nbad);
565 }
566 qInfo("%d bad channels total.", nbad);
567 /*
568 * Read the channel information
569 */
570 if (!FiffInfo::readMegEegChannels(measname,
571 include_meg,
572 include_eeg,
573 badlist,
574 res->chs,
575 res->nmeg,
576 res->neeg))
577 return nullptr;
578
579 if (res->nmeg > 0)
580 qInfo("Will use %3d MEG channels from %s", res->nmeg, measname.toUtf8().data());
581 if (res->neeg > 0)
582 qInfo("Will use %3d EEG channels from %s", res->neeg, measname.toUtf8().data());
583 {
584 int nch_total = res->nmeg + res->neeg;
585 res->ch_names.clear();
586 for (int i = 0; i < nch_total; i++)
587 res->ch_names.append(res->chs[i].ch_name);
588 }
589 /*
590 * Make coil definitions
591 */
592 res->coord_frame = coord_frame;
594 //#ifdef USE_SHARE_PATH
595 // char *coilfile = mne_compose_mne_name("share/mne","coil_def.dat");
596 //#else
597 // const char *path = "setup/mne";
598 // const char *filename = "coil_def.dat";
599 // const char *coilfile = mne_compose_mne_name(path,filename);
600
601 // QString qPath("/usr/pubsw/packages/mne/stable/share/mne/coil_def.dat");
602
603 QString qPath = QString(QCoreApplication::applicationDirPath() + "/../resources/general/coilDefinitions/coil_def.dat");
604 QFile file(qPath);
605 if (!QCoreApplication::startingUp())
606 qPath = QCoreApplication::applicationDirPath() + QString("/../resources/general/coilDefinitions/coil_def.dat");
607 else if (!file.exists())
608 qPath = "../resources/general/coilDefinitions/coil_def.dat";
609
610 QByteArray coilfileBytes = qPath.toUtf8();
611 const char* coilfile = coilfileBytes.constData();
612 //#endif
613
614 if (!coilfile)
615 return nullptr;
616 templates = FwdCoilSet::read_coil_defs(coilfile);
617 if (!templates) {
618 return nullptr;
619 }
620
621 Q_ASSERT(res->meg_head_t);
622 res->meg_coils = templates->create_meg_coils(res->chs,
623 res->nmeg,
625 *res->meg_head_t);
626 if (!res->meg_coils)
627 return nullptr;
628 res->eeg_els = FwdCoilSet::create_eeg_els(res->chs.mid(res->nmeg),
629 res->neeg);
630 if (!res->eeg_els)
631 return nullptr;
632 qInfo("Head coordinate coil definitions created.");
633 } else {
634 qWarning("Cannot handle computations in %s coordinates", FiffCoordTrans::frame_name(coord_frame).toUtf8().constData());
635 return nullptr;
636 }
637 /*
638 * Forward model setup
639 */
640 res->bemname = bemname;
641 if (r0) {
642 res->r0 = *r0;
643 }
644 res->eeg_model.reset(eeg_model);
645 /*
646 * Compensation data
647 */
648 comp_data = MNECTFCompDataSet::read(measname);
649 if (!comp_data)
650 return nullptr;
651 if (comp_data->ncomp > 0) { /* Compensation channel information may be needed */
652 QList<FiffChInfo> comp_chs;
653 int ncomp = 0;
654
655 qInfo("%d compensation data sets in %s", comp_data->ncomp, measname.toUtf8().data());
656 {
657 QFile compFile(measname);
658 FiffStream::SPtr compStream(new FiffStream(&compFile));
659 if (!compStream->open())
660 return nullptr;
661 FiffInfo compInfo;
662 FiffDirNode::SPtr compInfoNode;
663 if (!compStream->read_meas_info(compStream->dirtree(), compInfo, compInfoNode)) {
664 compStream->close();
665 return nullptr;
666 }
667 compStream->close();
668 for (int k = 0; k < compInfo.chs.size(); k++) {
669 if (compInfo.chs[k].kind == FIFFV_REF_MEG_CH) {
670 comp_chs.append(compInfo.chs[k]);
671 ncomp++;
672 }
673 }
674 }
675 if (ncomp > 0) {
676 comp_coils = templates->create_meg_coils(comp_chs,
677 ncomp,
679 *res->meg_head_t);
680 if (!comp_coils) {
681 return nullptr;
682 }
683 qInfo("%d compensation channels in %s", comp_coils->ncoil(), measname.toUtf8().data());
684 }
685 } else { /* Get rid of the empty data set */
686 comp_data.reset();
687 }
688 /*
689 * Ready to set up the forward model
690 */
691 if (setup_forward_model(res.get(), comp_data.get(), comp_coils.get()) == FAIL)
692 return nullptr;
693 res->column_norm = COLUMN_NORM_LOC;
694 /*
695 * Projection data should go here
696 */
697 if (!MNEProjOp::makeProjection(projnames,
698 res->chs,
699 res->nmeg + res->neeg,
700 res->proj))
701 return nullptr;
702 if (res->proj && res->proj->nitems > 0) {
703 qInfo("Final projection operator is:");
704 {
705 QTextStream errStream(stderr);
706 res->proj->report(errStream, QStringLiteral("\t"));
707 }
708
709 if (res->proj->assign_channels(res->ch_names, res->nmeg + res->neeg) == FAIL)
710 return nullptr;
711 if (res->proj->make_proj() == FAIL)
712 return nullptr;
713 } else
714 qInfo("No projection will be applied to the data.");
715
716 /*
717 * Noise covariance
718 */
719 if (!noisename.isEmpty()) {
720 if ((cov = MNECovMatrix::read(noisename, FIFFV_MNE_SENSOR_COV)) == nullptr)
721 return nullptr;
722 qInfo("Read a %s noise-covariance matrix from %s",
723 cov->cov_diag.size() > 0 ? "diagonal" : "full", noisename.toUtf8().data());
724 } else {
725 if ((cov = ad_hoc_noise(res->meg_coils.get(), res->eeg_els.get(), grad_std, mag_std, eeg_std)) == nullptr)
726 return nullptr;
727 }
728 res->noise = cov->pick_chs_omit(res->ch_names,
729 res->nmeg + res->neeg,
730 true,
731 res->chs);
732 if (!res->noise) {
733 return nullptr;
734 }
735
736 qInfo("Picked appropriate channels from the noise-covariance matrix.");
737 cov.reset();
738
739 /*
740 * Apply the projection operator to the noise-covariance matrix
741 */
742 if (res->proj && res->proj->nitems > 0 && res->proj->nvec > 0) {
743 if (res->proj->apply_cov(res->noise.get()) == FAIL)
744 return nullptr;
745 qInfo("Projection applied to the covariance matrix.");
746 }
747
748 /*
749 * Force diagonal noise covariance?
750 */
751 if (diagnoise) {
752 res->noise->revert_to_diag();
753 qInfo("Using only the main diagonal of the noise-covariance matrix.");
754 }
755
756 /*
757 * Regularize the possibly deficient noise-covariance matrix
758 */
759 if (res->noise->cov.size() > 0) {
760 Eigen::Vector3f regs;
761 int do_it;
762
763 regs[MNE_COV_CH_MEG_MAG] = mag_reg;
764 regs[MNE_COV_CH_MEG_GRAD] = grad_reg;
765 regs[MNE_COV_CH_EEG] = eeg_reg;
766 /*
767 * Classify the channels
768 */
769 if (res->noise->classify_channels(res->chs,
770 res->nmeg + res->neeg) == FAIL)
771 return nullptr;
772 /*
773 * Do we need to do anything?
774 */
775 do_it = 0;
776 for (int k = 0; k < res->noise->ncov; k++) {
777 if (res->noise->ch_class[k] != MNE_COV_CH_UNKNOWN &&
778 regs[res->noise->ch_class[k]] > 0.0)
779 do_it++;
780 }
781 /*
782 * Apply regularization if necessary
783 */
784 if (do_it > 0)
785 res->noise->regularize(regs);
786 else
787 qInfo("No regularization applied to the noise-covariance matrix");
788 }
789
790 /*
791 * Do the decomposition and check that the matrix is positive definite
792 */
793 qInfo("Decomposing the noise covariance...");
794 if (res->noise->cov.size() > 0) {
795 if (res->noise->decompose_eigen() == FAIL)
796 return nullptr;
797 qInfo("Eigenvalue decomposition done.");
798 for (int k = 0; k < res->noise->ncov; k++) {
799 if (res->noise->lambda[k] < 0.0)
800 res->noise->lambda[k] = 0.0;
801 }
802 } else {
803 qInfo("Decomposition not needed for a diagonal covariance matrix.");
804 if (res->noise->add_inv() == FAIL)
805 return nullptr;
806 }
807
808 badlist.clear();
809 return res.release();
810}
811
812//=============================================================================================================
813
814bool InvDipoleFitData::print_fields(const Eigen::Vector3f& rd,
815 const Eigen::Vector3f& Q,
816 float time,
817 float integ,
818 InvDipoleFitData& fit,
819 const MNEMeasData& data,
820 QTextStream& out)
821{
822 const int nch = fit.nmeg + fit.neeg;
823 if (data.nchan != nch || !data.current) {
824 qWarning("print_fields: the data do not hold the %d fit channels", nch);
825 return false;
826 }
827 Eigen::VectorXf measured(nch);
828 if (data.current->getValuesAtTime(time, integ, nch, false, measured.data()) == FAIL) {
829 qWarning("Cannot pick time: %7.1f ms", 1000 * time);
830 return false;
831 }
832 if (fit.proj && fit.proj->project_vector(measured, true) == FAIL)
833 return false;
834
835 Eigen::MatrixXf fwd(nch, 3);
836 if (compute_dipole_field(fit, rd, false, fwd) == FAIL)
837 return false;
838 const Eigen::VectorXf predicted = fwd * Q;
839
840 for (int k = 0; k < nch; ++k) {
841 const double scale = k < fit.nmeg ? 1e15 : 1e6;
842 out << fit.ch_names[k] << '\t' << scale * measured[k] << '\t' << scale * predicted[k] << '\n';
843 }
844 return true;
845}
846
847//=============================================================================================================
848
852std::unique_ptr<InvDipoleForward> dipole_forward(InvDipoleFitData* d,
853 float** rd,
854 int ndip,
855 std::unique_ptr<InvDipoleForward> old)
856{
857 std::unique_ptr<InvDipoleForward> res;
858 float S[3];
859 int k;
860 /*
861 * Allocate data if necessary
862 */
863 if (old && old->ndip == ndip && old->nch == d->nmeg + d->neeg) {
864 res = std::move(old);
865 } else {
866 res = std::make_unique<InvDipoleForward>();
867 int nch = d->nmeg + d->neeg;
868 int m = 3 * ndip;
869 res->fwd.resize(m, nch);
870 res->uu.resize(m, nch);
871 res->vv.resize(m, m);
872 res->sing.resize(m);
873 res->scales.resize(m);
874 res->rd.resize(ndip, 3);
875 res->nch = nch;
876 res->ndip = ndip;
877 }
878
879 for (k = 0; k < ndip; k++) {
880 res->rd.row(k) = Eigen::Map<const Eigen::Vector3f>(rd[k]).transpose();
881 /*
882 * Calculate the field of three orthogonal dipoles
883 */
884 Eigen::MatrixXf this_fwd(d->nmeg + d->neeg, 3);
885 Eigen::Map<const Eigen::Vector3f> rd_k(rd[k]);
886 if ((InvDipoleFitData::compute_dipole_field(*d, rd_k, true, this_fwd)) == FAIL)
887 return nullptr;
888 for (int p = 0; p < 3; p++)
889 res->fwd.row(3 * k + p) = this_fwd.col(p).transpose();
890 /*
891 * Choice of column normalization
892 * (componentwise normalization is not recommended)
893 */
895 for (int p = 0; p < 3; p++)
896 S[p] = res->fwd.row(3 * k + p).squaredNorm();
897 if (d->column_norm == COLUMN_NORM_COMP) {
898 for (int p = 0; p < 3; p++)
899 res->scales[3 * k + p] = sqrt(S[p]);
900 } else {
901 /*
902 * Divide by three or not?
903 */
904 res->scales[3 * k + 0] = res->scales[3 * k + 1] = res->scales[3 * k + 2] = sqrt(S[0] + S[1] + S[2]) / 3.0;
905 }
906 for (int p = 0; p < 3; p++) {
907 if (res->scales[3 * k + p] > 0.0) {
908 res->scales[3 * k + p] = 1.0 / res->scales[3 * k + p];
909 res->fwd.row(3 * k + p) *= res->scales[3 * k + p];
910 } else
911 res->scales[3 * k + p] = 1.0;
912 }
913 } else {
914 res->scales[3 * k] = 1.0;
915 res->scales[3 * k + 1] = 1.0;
916 res->scales[3 * k + 2] = 1.0;
917 }
918 }
919
920 /*
921 * SVD: A = U · Σ · V^T where A is m×n (3*ndip × nch)
922 * uu stores right singular vectors (V^T rows, length nch) for data-space projections
923 * vv stores left singular vectors (U^T rows, length m) for dipole-moment reconstruction
924 */
925 {
926 int m = 3 * ndip;
927 int n = d->nmeg + d->neeg;
928 int udim = std::min(m, n);
929 JacobiSVD<MatrixXf> svd(res->fwd, ComputeFullU | ComputeFullV);
930 res->sing = svd.singularValues();
931 res->uu = svd.matrixV().transpose().topRows(udim);
932 res->vv = svd.matrixU().transpose().topRows(udim);
933 }
934
935 return res;
936}
937
938//=============================================================================================================
939
943std::unique_ptr<InvDipoleForward> InvDipoleFitData::dipole_forward_one(InvDipoleFitData* d,
944 const Eigen::Vector3f& rd,
945 std::unique_ptr<InvDipoleForward> old)
946{
947 float* rds[1];
948 rds[0] = const_cast<float*>(rd.data());
949 return dipole_forward(d, rds, 1, std::move(old));
950}
951
952//=============================================================================================================
953// Dipole fitting - evaluation
957static float fit_eval(const VectorXf& rd, const void* user)
958{
959 InvDipoleFitData* fit = const_cast<InvDipoleFitData*>(static_cast<const InvDipoleFitData*>(user));
960 InvDipoleForward* fwd;
961 FitDipUserRec* fuser = fit->user;
962 double Bm2, one;
963 int ncomp, c;
964
965 fuser->fwd = InvDipoleFitData::dipole_forward_one(fit, rd.head<3>(), std::move(fuser->fwd));
966 fwd = fuser->fwd.get();
967 ncomp = fwd->sing[2] / fwd->sing[0] > fuser->limit ? 3 : 2;
968 if (fuser->report_dim)
969 qInfo("ncomp = %d", ncomp);
970
971 Eigen::Map<const VectorXf> Bmap(fuser->B, fwd->nch);
972 for (c = 0, Bm2 = 0.0; c < ncomp; c++) {
973 one = fwd->uu.row(c).dot(Bmap);
974 Bm2 = Bm2 + one * one;
975 }
976 return fuser->B2 - Bm2;
977}
978
982static int find_best_guess(const Eigen::Ref<const Eigen::VectorXf>& B,
983 int nch,
984 InvGuessData* guess,
985 float limit,
986 int& bestp,
987 float& goodp)
988{
989 int k, c;
990 double B2, Bm2, this_good, one;
991 int best = -1;
992 float good = 0.0;
993 InvDipoleForward* fwd;
994 int ncomp;
995
996 B2 = B.squaredNorm();
997 for (k = 0; k < guess->nguess; k++) {
998 fwd = guess->guess_fwd[k].get();
999 if (fwd->nch == nch) {
1000 ncomp = fwd->sing[2] / fwd->sing[0] > limit ? 3 : 2;
1001 for (c = 0, Bm2 = 0.0; c < ncomp; c++) {
1002 one = fwd->uu.row(c).dot(B);
1003 Bm2 = Bm2 + one * one;
1004 }
1005 this_good = 1.0 - (B2 - Bm2) / B2;
1006 if (this_good > good) {
1007 best = k;
1008 good = this_good;
1009 }
1010 }
1011 }
1012 if (best < 0) {
1013 qWarning("No reasonable initial guess found.");
1014 return FAIL;
1015 }
1016 bestp = best;
1017 goodp = good;
1018 return OK;
1019}
1020
1024static MatrixXf make_initial_dipole_simplex(const Eigen::Vector3f& r0,
1025 float size)
1026{
1027 /*
1028 * For this definition of a regular tetrahedron, see
1029 *
1030 * http://mathworld.wolfram.com/Tetrahedron.html
1031 *
1032 */
1033 float x = sqrt(3.0f) / 3.0f;
1034 float r = sqrt(6.0f) / 12.0f;
1035 float R = 3 * r;
1036 float d = x / 2.0f;
1037 float rr[][3] = {{x, 0.0f, -r},
1038 {-d, 0.5f, -r},
1039 {-d, -0.5f, -r},
1040 {0.0f, 0.0f, R}};
1041
1042 MatrixXf simplex = MatrixXf::Zero(4, 3);
1043
1044 for (int j = 0; j < 4; j++) {
1045 simplex.row(j) = Eigen::Map<const Vector3f>(rr[j]).transpose() * size + r0.transpose();
1046 }
1047 return simplex;
1048}
1049
1050static bool dipole_report_func(int loop,
1051 const VectorXf& fitpar,
1052 double fval_lo,
1053 double fval_hi,
1054 double par_diff)
1055{
1056 qInfo("loop %d rd %7.2f %7.2f %7.2f fval %g %g par diff %g",
1057 loop, 1000 * fitpar[0], 1000 * fitpar[1], 1000 * fitpar[2], fval_lo, fval_hi, 1000 * par_diff);
1058
1059 return true;
1060}
1061
1065static int fit_Q(InvDipoleFitData* fit,
1066 const Eigen::Ref<const Eigen::VectorXf>& B,
1067 const Eigen::Vector3f& rd,
1068 float limit,
1069 Eigen::Vector3f& Q,
1070 int& ncomp,
1071 float& res)
1072{
1073 int c;
1074 const auto fwd = InvDipoleFitData::dipole_forward_one(fit, rd, nullptr);
1075 float Bm2, one;
1076
1077 if (!fwd)
1078 return FAIL;
1079
1080 ncomp = fwd->sing[2] / fwd->sing[0] > limit ? 3 : 2;
1081
1082 Q.setZero();
1083 for (c = 0, Bm2 = 0.0; c < ncomp; c++) {
1084 one = fwd->uu.row(c).dot(B);
1085 Q += (one / fwd->sing[c]) * fwd->vv.row(c).head(3).transpose();
1086 Bm2 = Bm2 + one * one;
1087 }
1088 /*
1089 * Counteract the effect of column normalization
1090 */
1091 for (c = 0; c < 3; c++)
1092 Q[c] = fwd->scales[c] * Q[c];
1093 res = B.squaredNorm() - Bm2;
1094
1095 return OK;
1096}
1097
1098//=============================================================================================================
1099// Dipole fitting - main entry point
1112 InvGuessData* guess,
1113 float time,
1114 Eigen::Ref<Eigen::VectorXf> B,
1115 int verbose,
1116 InvEcd& res)
1117{
1118 VectorXf vals(4); /* Values at the vertices */
1119 float limit = 0.2f; /* (pseudo) radial component omission limit */
1120 float size = 1e-2f; /* Size of the initial simplex */
1121 float ftol[] = {1e-2f, 1e-2f}; /* Tolerances on the the two passes */
1122 float atol[] = {0.2e-3f, 0.2e-3f}; /* If dipole movement between two iterations is less than this,
1123 we consider to have converged */
1124 int ntol = 2;
1125 int max_eval = 1000; /* Limit for fit function evaluations */
1126 int report_interval = verbose ? 1 : -1; /* How often to report the intermediate result */
1127
1128 int best;
1129 float good, final_val;
1130 Eigen::Vector3f rd_final, Q;
1132 int k, neval, neval_tot, nchan, ncomp;
1133 int fit_fail;
1134 Vector3f rd_guess;
1135
1136 nchan = fit->nmeg + fit->neeg;
1137 user.fwd = nullptr;
1138
1139 if (fit->proj && fit->proj->project_vector(B, true) == FAIL)
1140 return false;
1141
1142 if (fit->noise->whiten_vector(B, B, nchan) == FAIL)
1143 return false;
1144 /*
1145 * Get the initial guess
1146 */
1147 if (find_best_guess(B, nchan, guess, limit, best, good) < 0)
1148 return false;
1149
1150 user.limit = limit;
1151 user.B = B.data();
1152 user.B2 = B.squaredNorm();
1153 user.fwd = nullptr;
1154 user.report_dim = false;
1155 fit->user = &user;
1156
1157 rd_guess = guess->rr.row(best).transpose();
1158 rd_final = rd_guess;
1159
1160 neval_tot = 0;
1161 fit_fail = false;
1162 for (k = 0; k < ntol; k++) {
1163 /*
1164 * Do first pass with the sphere model
1165 */
1166 if (fit->fit_mag_dipoles)
1167 fit->funcs = fit->mag_dipole_funcs.get(); // the guesses were computed with these too
1168 else if (k == 0)
1169 fit->funcs = fit->sphere_funcs.get();
1170 else
1171 fit->funcs = !fit->bemname.isEmpty() ? fit->bem_funcs.get() : fit->sphere_funcs.get();
1172
1173 MatrixXf simplexMat = make_initial_dipole_simplex(rd_guess, size);
1174 for (int p = 0; p < 4; p++)
1175 vals[p] = fit_eval(simplexMat.row(p), fit);
1176
1177 // Capture fit pointer in type-safe lambda — no void* needed
1178 auto cost = [fit](const VectorXf& x) -> float {
1179 return fit_eval(x, fit);
1180 };
1181
1183 simplexMat, /* The initial simplex */
1184 vals, /* Function values at the vertices */
1185 ftol[k], /* Relative convergence tolerance for the target function */
1186 atol[k], /* Absolute tolerance for the change in the parameters */
1187 cost, /* The cost function (captures fit data) */
1188 max_eval, /* Maximum number of function evaluations */
1189 neval, /* Number of function evaluations */
1190 report_interval, /* How often to report (-1 = no_reporting) */
1191 dipole_report_func)) {
1192 if (k == 0) {
1193 return false;
1194 } else {
1195 float rv = 2.0f * (vals.maxCoeff() - vals.minCoeff()) / (vals.maxCoeff() + vals.minCoeff());
1196 qWarning("Warning (t = %8.1f ms) : g = %6.1f %% final val = %7.3f rtol = %f",
1197 1000 * time, 100 * (1 - vals[0] / user.B2), vals[0], rv);
1198 fit_fail = true;
1199 }
1200 }
1201 rd_final = simplexMat.row(0).transpose();
1202 rd_guess = simplexMat.row(0).transpose();
1203
1204 neval_tot += neval;
1205 final_val = vals[0];
1206 }
1207 /*
1208 * Confidence limits should be computed here
1209 */
1210 /*
1211 * Compute the dipole moment at the final point
1212 */
1213 if (fit_Q(fit, B, rd_final, user.limit, Q, ncomp, final_val) == OK) {
1214 res.time = time;
1215 res.valid = true;
1216 res.rd = rd_final;
1217 res.Q = Q;
1218 res.good = 1.0 - final_val / user.B2;
1219 if (fit_fail)
1220 res.good = -res.good;
1221 res.khi2 = final_val;
1222 if (fit->proj)
1223 res.nfree = nchan - 3 - ncomp - fit->proj->nvec;
1224 else
1225 res.nfree = nchan - 3 - ncomp;
1226 res.neval = neval_tot;
1227 } else {
1228 return false;
1229 }
1230
1231 return true;
1232}
1233
1234//=============================================================================================================
1235
1241int InvDipoleFitData::compute_dipole_field(InvDipoleFitData& d, const Eigen::Vector3f& rd, int whiten, Eigen::Ref<Eigen::MatrixXf> fwd)
1242{
1243 static const Eigen::Vector3f Qx(1.0f, 0.0f, 0.0f);
1244 static const Eigen::Vector3f Qy(0.0f, 1.0f, 0.0f);
1245 static const Eigen::Vector3f Qz(0.0f, 0.0f, 1.0f);
1246 int nch = d.nmeg + d.neeg;
1247 int k;
1248 /*
1249 * Compute the fields
1250 */
1251 if (d.nmeg > 0) {
1252 int nmeg = d.meg_coils->ncoil();
1253 if (d.funcs->meg_vec_field) {
1254 /*
1255 * Use the vector field function: computes all three dipole
1256 * orientations at once. Output is 3 x ncoil, we need nch x 3.
1257 */
1258 Eigen::MatrixXf vec_meg(3, nmeg);
1259 if (d.funcs->meg_vec_field(rd, *d.meg_coils, vec_meg, d.funcs->meg_client) != OK)
1260 return FAIL;
1261 fwd.topRows(nmeg) = vec_meg.transpose();
1262 } else {
1263 auto fwd0 = fwd.col(0).head(nmeg);
1264 auto fwd1 = fwd.col(1).head(nmeg);
1265 auto fwd2 = fwd.col(2).head(nmeg);
1266 if (d.funcs->meg_field(rd, Qx, *d.meg_coils, fwd0, d.funcs->meg_client) != OK)
1267 return FAIL;
1268 if (d.funcs->meg_field(rd, Qy, *d.meg_coils, fwd1, d.funcs->meg_client) != OK)
1269 return FAIL;
1270 if (d.funcs->meg_field(rd, Qz, *d.meg_coils, fwd2, d.funcs->meg_client) != OK)
1271 return FAIL;
1272 }
1273 }
1274
1275 if (d.neeg > 0) {
1276 int neeg = d.eeg_els->ncoil();
1277 if (d.funcs->eeg_vec_pot) {
1278 /*
1279 * Use the vector potential function: computes all three dipole
1280 * orientations at once. Output is 3 x ncoil, we need nch x 3.
1281 */
1282 Eigen::MatrixXf vec_eeg(3, neeg);
1283 if (d.funcs->eeg_vec_pot(rd, *d.eeg_els, vec_eeg, d.funcs->eeg_client) != OK)
1284 return FAIL;
1285 fwd.block(d.nmeg, 0, neeg, 3) = vec_eeg.transpose();
1286 } else {
1287 auto fwd0 = fwd.col(0).segment(d.nmeg, neeg);
1288 auto fwd1 = fwd.col(1).segment(d.nmeg, neeg);
1289 auto fwd2 = fwd.col(2).segment(d.nmeg, neeg);
1290 if (d.funcs->eeg_pot(rd, Qx, *d.eeg_els, fwd0, d.funcs->eeg_client) != OK)
1291 return FAIL;
1292 if (d.funcs->eeg_pot(rd, Qy, *d.eeg_els, fwd1, d.funcs->eeg_client) != OK)
1293 return FAIL;
1294 if (d.funcs->eeg_pot(rd, Qz, *d.eeg_els, fwd2, d.funcs->eeg_client) != OK)
1295 return FAIL;
1296 }
1297 }
1298
1299 /*
1300 * Apply projection
1301 */
1302 for (k = 0; k < 3; k++)
1303 if (d.proj && d.proj->project_vector(fwd.col(k), true) == FAIL)
1304 return FAIL;
1305
1306 /*
1307 * Whiten
1308 */
1309 if (d.noise && whiten) {
1310 for (k = 0; k < 3; k++) {
1311 auto col_k = fwd.col(k);
1312 if (d.noise->whiten_vector(col_k, col_k, nch) == FAIL)
1313 return FAIL;
1314 }
1315 }
1316
1317 return OK;
1318}
constexpr auto FIFFV_MNE_SENSOR_COV
constexpr auto FIFFV_COORD_HEAD
constexpr auto FIFFV_COIL_CTF_REF_GOFF
constexpr auto FIFFV_COIL_CTF_REF_GRAD
constexpr auto FIFFV_COORD_UNKNOWN
constexpr auto FIFFV_COORD_MRI
constexpr auto FIFFV_MNE_NOISE_COV
constexpr auto FIFFV_COIL_CTF_REF_MAG
constexpr auto FIFFV_REF_MEG_CH
FIFF binary tag-stream layer: wraps a QIODevice to read and write FIFF tags, directories,...
Full FIFF measurement metadata: everything from FIFFB_MEAS / FIFFB_MEAS_INFO needed to interpret a re...
4x4 affine FIFF coordinate transform (FIFF_COORD_TRANS) annotated with source/destination coordinate-...
constexpr auto FIFFV_BEM_SURF_ID_BRAIN
Definition fiff_file.h:740
Eigen::Matrix3f R
Eigen::Vector3f moveVec
Eigen::Matrix3f S
Eigen::JacobiSVD< Eigen::Matrix3f > svd(S, Eigen::ComputeFullU|Eigen::ComputeFullV)
Software-gradiometer compensation wrapper that subtracts the reference-channel contribution from the ...
Boundary Element Method (BEM) volume-conductor model — layered triangulated surfaces,...
std::function aliases for the generic dipole field / potential / field-gradient callbacks driving the...
constexpr int FAIL
constexpr int OK
std::unique_ptr< InvDipoleForward > dipole_forward(InvDipoleFitData *d, float **rd, int ndip, std::unique_ptr< InvDipoleForward > old)
Compute the forward solution for one or more dipoles, applying projections and whitening.
Initial-guess grid for the dipole-fit optimiser, with per-guess forward fields pre-computed.
Dipole-fit workspace bundling sensor geometry, forward-model function pointers, noise covariance and ...
constexpr int COLUMN_NORM_NONE
constexpr int COLUMN_NORM_COMP
constexpr int COLUMN_NORM_LOC
Single equivalent current dipole (ECD) with position, moment and per-fit goodness/χ² metrics.
Best-fit sphere from a 3-D point cloud with closed-form and Nelder–Mead solvers.
Header-only Nelder–Mead simplex minimiser with pluggable cost and report callables.
One condition / averaging slice within a legacy MNELIB::MNEMeasData.
Legacy MNE-C measurement-data container assembling raw/evoked sets and their projection state.
Single SSP projection vector with kind/active flag and channel labels.
Lightweight triangulated surface (vertices, triangles, normals) used by surface-based routines.
Legacy MNE-C noise covariance container preserved for cross-toolchain compatibility.
constexpr auto MNE_COV_CH_EEG
constexpr auto MNE_COV_CH_MEG_GRAD
constexpr auto MNE_COV_CH_UNKNOWN
constexpr auto MNE_COV_CH_MEG_MAG
Core MNE data structures (source spaces, source estimates, hemispheres).
FIFF file I/O, in-memory data structures and high-level readers/writers.
Inverse source estimation (MNE, dSPM, sLORETA, dipole fitting).
Forward modelling — BEM solver, spherical models, sensor/coil definitions and the lead-field assembly...
Definition compute_fwd.h:85
constexpr int FWD_COIL_ACCURACY_NORMAL
Definition fwd_coil.h:76
constexpr int FWD_COIL_ACCURACY_ACCURATE
Definition fwd_coil.h:77
constexpr int FWD_BEM_UNKNOWN
static QString frame_name(int frame)
static FiffCoordTrans readMeasTransform(const QString &name)
static FiffCoordTrans readMriTransform(const QString &name)
Eigen::MatrixX3f apply_trans(const Eigen::MatrixX3f &rr, bool do_move=true) const
QSharedPointer< FiffDirNode > SPtr
Full FIFF measurement info: per-channel descriptors, sampling and filter setup, projectors,...
Definition fiff_info.h:90
static bool readMegEegChannels(const QString &name, bool do_meg, bool do_eeg, const QStringList &bads, QList< FiffChInfo > &chsp, int &nmegp, int &neegp)
QList< FiffChInfo > chs
static bool readBadChannelsFromFile(const QString &name, QStringList &listOut)
FIFF tag-stream reader/writer: wraps a QIODevice and exposes typed read_* / write_* methods for every...
QSharedPointer< FiffStream > SPtr
static FwdBemModel::UPtr fwd_bem_load_three_layer_surfaces(const QString &name)
Load a three-layer BEM model (scalp, outer skull, inner skull) from a FIFF file.
static int fwd_mag_dipole_field_vec(const Eigen::Vector3f &rm, FwdCoilSet &coils, Eigen::Ref< Eigen::MatrixXf > Bval, void *client)
Callback: compute the vector magnetic field of a magnetic dipole at coils.
static QString fwd_bem_make_bem_sol_name(const QString &name)
Build a standard BEM solution file name from a model name.
static int fwd_mag_dipole_field(const Eigen::Vector3f &rm, const Eigen::Vector3f &M, FwdCoilSet &coils, Eigen::Ref< Eigen::VectorXf > Bval, void *client)
Callback: compute the magnetic field of a magnetic dipole at coils.
static int fwd_sphere_field(const Eigen::Vector3f &rd, const Eigen::Vector3f &Q, FwdCoilSet &coils, Eigen::Ref< Eigen::VectorXf > Bval, void *client)
Callback: compute the spherical-model magnetic field at coils.
static int fwd_bem_field(const Eigen::Vector3f &rd, const Eigen::Vector3f &Q, FwdCoilSet &coils, Eigen::Ref< Eigen::VectorXf > B, void *client)
Callback: compute BEM magnetic fields at coils for a dipole.
static int fwd_bem_pot_els(const Eigen::Vector3f &rd, const Eigen::Vector3f &Q, FwdCoilSet &els, Eigen::Ref< Eigen::VectorXf > pot, void *client)
Callback: compute BEM potentials at electrodes for a dipole.
static FwdBemModel::UPtr fwd_bem_load_homog_surface(const QString &name)
Load a single-layer (homogeneous) BEM model from a FIFF file.
static int fwd_sphere_field_vec(const Eigen::Vector3f &rd, FwdCoilSet &coils, Eigen::Ref< Eigen::MatrixXf > Bval, void *client)
Callback: compute the spherical-model vector magnetic field at coils.
Container of FwdCoil instances acting both as the in-memory image of the coil_def....
static FwdCoilSet::UPtr read_coil_defs(const QString &name)
static FwdCoilSet::UPtr create_eeg_els(const QList< FIFFLIB::FiffChInfo > &chs, int nch, const FIFFLIB::FiffCoordTrans &t=FIFFLIB::FiffCoordTrans())
std::vector< FwdCoil::UPtr > coils
static int fwd_comp_field_vec(const Eigen::Vector3f &rd, FwdCoilSet &coils, Eigen::Ref< Eigen::MatrixXf > res, void *client)
static int fwd_comp_field(const Eigen::Vector3f &rd, const Eigen::Vector3f &Q, FwdCoilSet &coils, Eigen::Ref< Eigen::VectorXf > res, void *client)
static std::unique_ptr< FwdCompData > fwd_make_comp_data(MNELIB::MNECTFCompDataSet *set, FwdCoilSet *coils, FwdCoilSet *comp_coils, fwdFieldFunc field, fwdVecFieldFunc vec_field, fwdFieldGradFunc field_grad, void *client)
Multi-shell concentric-sphere head model holding the Berg-Scherg equivalent-source parameters that ac...
static int fwd_eeg_spherepot_coil_vec(const Eigen::Vector3f &rd, FwdCoilSet &els, Eigen::Ref< Eigen::MatrixXf > Vval_vec, void *client)
static int fwd_eeg_spherepot_coil(const Eigen::Vector3f &rd, const Eigen::Vector3f &Q, FwdCoilSet &els, Eigen::Ref< Eigen::VectorXf > Vval, void *client)
Forward field computation function pointers and client data for MEG and EEG dipole fitting.
std::unique_ptr< FWDLIB::FwdCompData > meg_comp
Workspace for the dipole fitting objective function, holding forward model, measured field,...
std::unique_ptr< InvDipoleForward > fwd
Dipole fit workspace holding sensor geometry, forward model, noise covariance, and projection data.
std::unique_ptr< FWDLIB::FwdEegSphereModel > eeg_model
std::unique_ptr< FWDLIB::FwdCoilSet > meg_coils
static InvDipoleFitData * setup_dipole_fit_data(const QString &mriname, const QString &measname, const QString &bemname, Eigen::Vector3f *r0, FWDLIB::FwdEegSphereModel *eeg_model, int accurate_coils, const QString &badname, const QString &noisename, float grad_std, float mag_std, float eeg_std, float mag_reg, float grad_reg, float eeg_reg, int diagnoise, const QList< QString > &projnames, int include_meg, int include_eeg)
Master setup: read all inputs and build a ready-to-use fit workspace.
std::unique_ptr< FIFFLIB::FiffCoordTrans > mri_head_t
static int scale_dipole_fit_noise_cov(InvDipoleFitData *f, int nave)
Scale dipole-fit noise covariance for a given number of averages.
std::unique_ptr< MNELIB::MNEProjOp > proj
static bool print_fields(const Eigen::Vector3f &rd, const Eigen::Vector3f &Q, float time, float integ, InvDipoleFitData &fit, const MNELIB::MNEMeasData &data, QTextStream &out)
Write the measured and the predicted field of a dipole, channel by channel.
std::unique_ptr< MNELIB::MNECovMatrix > noise
std::unique_ptr< dipoleFitFuncsRec > bem_funcs
static int scale_noise_cov(InvDipoleFitData *f, int nave)
Scale the noise-covariance matrix for a given number of averages.
std::unique_ptr< dipoleFitFuncsRec > sphere_funcs
static std::unique_ptr< InvDipoleForward > dipole_forward_one(InvDipoleFitData *d, const Eigen::Vector3f &rd, std::unique_ptr< InvDipoleForward > old)
Compute the forward solution for a single dipole position.
static bool fit_one(InvDipoleFitData *fit, InvGuessData *guess, float time, Eigen::Ref< Eigen::VectorXf > B, int verbose, InvEcd &res)
Fit a single dipole to the given data.
static int compute_dipole_field(InvDipoleFitData &d, const Eigen::Vector3f &rd, int whiten, Eigen::Ref< Eigen::MatrixXf > fwd)
Compute the forward field for a dipole at the given location.
static int setup_forward_model(InvDipoleFitData *d, MNELIB::MNECTFCompDataSet *comp_data, FWDLIB::FwdCoilSet *comp_coils)
Set up the sphere-model and (optionally) BEM forward functions.
std::unique_ptr< FWDLIB::FwdBemModel > bem_model
static int select_dipole_fit_noise_cov(InvDipoleFitData *f, MNELIB::MNEMeasData *meas, int nave, const int *sels)
Select and weight the noise-covariance for the active channel set.
std::unique_ptr< FWDLIB::FwdCoilSet > eeg_els
std::unique_ptr< dipoleFitFuncsRec > mag_dipole_funcs
static std::unique_ptr< MNELIB::MNECovMatrix > ad_hoc_noise(FWDLIB::FwdCoilSet *meg, FWDLIB::FwdCoilSet *eeg, float grad_std, float mag_std, float eeg_std)
Create an ad-hoc diagonal noise-covariance matrix.
std::unique_ptr< MNELIB::MNECovMatrix > noise_orig
Stores forward field matrices and SVD decomposition for magnetic dipole fitting.
Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > uu
Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor > vv
Single equivalent current dipole with position, orientation, amplitude, and goodness-of-fit.
Definition inv_ecd.h:58
Eigen::Vector3f Q
Definition inv_ecd.h:106
Eigen::Vector3f rd
Definition inv_ecd.h:105
Precomputed guess point grid with forward fields for initial dipole position candidates.
std::vector< InvDipoleForward::UPtr > guess_fwd
Eigen::Matrix< float, Eigen::Dynamic, 3, Eigen::RowMajor > rr
static bool simplex_minimize(Eigen::Matrix< T, Eigen::Dynamic, Eigen::Dynamic > &p, Eigen::Matrix< T, Eigen::Dynamic, 1 > &y, T ftol, T stol, CostFunc &&func, int max_eval, int &neval, int report, ReportFunc &&report_func)
static bool fit_sphere_to_points(const Eigen::MatrixXf &rr, float simplex_size, Eigen::VectorXf &r0, float &R)
static std::unique_ptr< MNECovMatrix > read(const QString &name, int kind)
static std::unique_ptr< MNECovMatrix > create(int kind, int ncov, const QStringList &names, const Eigen::VectorXd &cov, const Eigen::VectorXd &cov_diag)
static int lt_packed_index(int j, int k)
Collection of CTF third-order gradient compensation operators.
static std::unique_ptr< MNECTFCompDataSet > read(const QString &name)
Measurement data container for MNE inverse and dipole-fit computations.
MNEMeasDataSet * current
QList< FIFFLIB::FiffChInfo > chs
int getValuesAtTime(float time, float integ, int nch, bool use_abs, float *value) const
static bool makeProjection(const QList< QString > &projnames, const QList< FIFFLIB::FiffChInfo > &chs, int nch, std::unique_ptr< MNEProjOp > &result)
Load and combine SSP projection operators from files for the selected channels.
Lightweight triangulated surface (vertices, triangles, normals).
Definition mne_surface.h:68