-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathdipole.py
1988 lines (1788 loc) · 62.1 KB
/
dipole.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Single-dipole functions and classes."""
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import functools
import re
from copy import deepcopy
from functools import partial
import numpy as np
from scipy.linalg import eigh
from scipy.optimize import fmin_cobyla
from ._fiff.constants import FIFF
from ._fiff.pick import pick_types
from ._fiff.proj import _needs_eeg_average_ref_proj, make_projector
from ._freesurfer import _get_aseg, head_to_mni, head_to_mri, read_freesurfer_lut
from .bem import _bem_find_surface, _bem_surf_name, _fit_sphere
from .cov import _ensure_cov, compute_whitener
from .evoked import _aspect_rev, _read_evoked, _write_evokeds
from .fixes import _safe_svd
from .forward._compute_forward import _compute_forwards_meeg, _prep_field_computation
from .forward._make_forward import (
_get_trans,
_prep_eeg_channels,
_prep_meg_channels,
_setup_bem,
)
from .parallel import parallel_func
from .source_space._source_space import SourceSpaces, _make_volume_source_space
from .surface import _compute_nearest, _points_outside_surface, transform_surface_to
from .transforms import _coord_frame_name, _print_coord_trans, apply_trans
from .utils import (
ExtendedTimeMixin,
TimeMixin,
_check_fname,
_check_option,
_get_blas_funcs,
_pl,
_repeated_svd,
_svd_lwork,
_time_mask,
_validate_type,
_verbose_safe_false,
check_fname,
copy_function_doc_to_method_doc,
fill_doc,
logger,
pinvh,
verbose,
warn,
)
from .viz import plot_dipole_amplitudes, plot_dipole_locations
from .viz.evoked import _plot_evoked
@fill_doc
class Dipole(TimeMixin):
"""Dipole class for sequential dipole fits.
.. note::
This class should usually not be instantiated directly via
``mne.Dipole(...)``. Instead, use one of the functions
listed in the See Also section below.
Used to store positions, orientations, amplitudes, times, goodness of fit
of dipoles, typically obtained with Neuromag/xfit, mne_dipole_fit
or certain inverse solvers. Note that dipole position vectors are given in
the head coordinate frame.
Parameters
----------
times : array, shape (n_dipoles,)
The time instants at which each dipole was fitted (s).
pos : array, shape (n_dipoles, 3)
The dipoles positions (m) in head coordinates.
amplitude : array, shape (n_dipoles,)
The amplitude of the dipoles (Am).
ori : array, shape (n_dipoles, 3)
The dipole orientations (normalized to unit length).
gof : array, shape (n_dipoles,)
The goodness of fit.
name : str | None
Name of the dipole.
conf : dict
Confidence limits in dipole orientation for "vol" in m^3 (volume),
"depth" in m (along the depth axis), "long" in m (longitudinal axis),
"trans" in m (transverse axis), "qlong" in Am, and "qtrans" in Am
(currents). The current confidence limit in the depth direction is
assumed to be zero (although it can be non-zero when a BEM is used).
.. versionadded:: 0.15
khi2 : array, shape (n_dipoles,)
The χ^2 values for the fits.
.. versionadded:: 0.15
nfree : array, shape (n_dipoles,)
The number of free parameters for each fit.
.. versionadded:: 0.15
%(verbose)s
See Also
--------
fit_dipole
DipoleFixed
read_dipole
Notes
-----
This class is for sequential dipole fits, where the position
changes as a function of time. For fixed dipole fits, where the
position is fixed as a function of time, use :class:`mne.DipoleFixed`.
"""
@verbose
def __init__(
self,
times,
pos,
amplitude,
ori,
gof,
name=None,
conf=None,
khi2=None,
nfree=None,
*,
verbose=None,
):
self._set_times(np.array(times))
self._pos = np.array(pos)
self._amplitude = np.array(amplitude)
self._ori = np.array(ori)
self._gof = np.array(gof)
self._name = name
self._conf = dict()
if conf is not None:
for key, value in conf.items():
self._conf[key] = np.array(value)
self._khi2 = np.array(khi2) if khi2 is not None else None
self._nfree = np.array(nfree) if nfree is not None else None
def __repr__(self): # noqa: D105
s = f"n_times : {len(self.times)}"
s += f", tmin : {np.min(self.times):0.3f}"
s += f", tmax : {np.max(self.times):0.3f}"
return f"<Dipole | {s}>"
@property
def pos(self):
"""The dipoles positions (m) in head coordinates."""
return self._pos
@property
def amplitude(self):
"""The amplitude of the dipoles (Am)."""
return self._amplitude
@property
def ori(self):
"""The dipole orientations (normalized to unit length)."""
return self._ori
@property
def gof(self):
"""The goodness of fit."""
return self._gof
@property
def name(self):
"""Name of the dipole."""
return self._name
@name.setter
def name(self, name):
_validate_type(name, str, "name")
self._name = name
@property
def conf(self):
"""Confidence limits in dipole orientation."""
return self._conf
@property
def khi2(self):
"""The χ^2 values for the fits."""
return self._khi2
@property
def nfree(self):
"""The number of free parameters for each fit."""
return self._nfree
@verbose
def save(self, fname, overwrite=False, *, verbose=None):
"""Save dipole in a ``.dip`` or ``.bdip`` file.
The ``.[b]dip`` format is for :class:`mne.Dipole` objects, that is,
fixed-position dipole fits. For these fits, the amplitude, orientation,
and position vary as a function of time.
Parameters
----------
fname : path-like
The name of the ``.dip`` or ``.bdip`` file.
%(overwrite)s
.. versionadded:: 0.20
%(verbose)s
See Also
--------
read_dipole
Notes
-----
.. versionchanged:: 0.20
Support for writing bdip (Xfit binary) files.
"""
# obligatory fields
fname = _check_fname(fname, overwrite=overwrite)
if fname.suffix == ".bdip":
_write_dipole_bdip(fname, self)
else:
_write_dipole_text(fname, self)
@verbose
def crop(self, tmin=None, tmax=None, include_tmax=True, verbose=None):
"""Crop data to a given time interval.
Parameters
----------
tmin : float | None
Start time of selection in seconds.
tmax : float | None
End time of selection in seconds.
%(include_tmax)s
%(verbose)s
Returns
-------
self : instance of Dipole
The cropped instance.
"""
sfreq = None
if len(self.times) > 1:
sfreq = 1.0 / np.median(np.diff(self.times))
mask = _time_mask(
self.times, tmin, tmax, sfreq=sfreq, include_tmax=include_tmax
)
self._set_times(self.times[mask])
for attr in ("_pos", "_gof", "_amplitude", "_ori", "_khi2", "_nfree"):
if getattr(self, attr) is not None:
setattr(self, attr, getattr(self, attr)[mask])
for key in self.conf.keys():
self.conf[key] = self.conf[key][mask]
return self
def copy(self):
"""Copy the Dipoles object.
Returns
-------
dip : instance of Dipole
The copied dipole instance.
"""
return deepcopy(self)
@verbose
@copy_function_doc_to_method_doc(plot_dipole_locations)
def plot_locations(
self,
trans,
subject,
subjects_dir=None,
mode="orthoview",
coord_frame="mri",
idx="gof",
show_all=True,
ax=None,
block=False,
show=True,
scale=None,
color=None,
*,
highlight_color="r",
fig=None,
title=None,
head_source="seghead",
surf="pial",
width=None,
verbose=None,
):
return plot_dipole_locations(
self,
trans,
subject,
subjects_dir,
mode,
coord_frame,
idx,
show_all,
ax,
block,
show,
scale=scale,
color=color,
highlight_color=highlight_color,
fig=fig,
title=title,
head_source=head_source,
surf=surf,
width=width,
)
@verbose
def to_mni(self, subject, trans, subjects_dir=None, verbose=None):
"""Convert dipole location from head to MNI coordinates.
Parameters
----------
%(subject)s
%(trans_not_none)s
%(subjects_dir)s
%(verbose)s
Returns
-------
pos_mni : array, shape (n_pos, 3)
The MNI coordinates (in mm) of pos.
"""
mri_head_t, trans = _get_trans(trans)
return head_to_mni(
self.pos, subject, mri_head_t, subjects_dir=subjects_dir, verbose=verbose
)
@verbose
def to_mri(self, subject, trans, subjects_dir=None, verbose=None):
"""Convert dipole location from head to MRI surface RAS coordinates.
Parameters
----------
%(subject)s
%(trans_not_none)s
%(subjects_dir)s
%(verbose)s
Returns
-------
pos_mri : array, shape (n_pos, 3)
The Freesurfer surface RAS coordinates (in mm) of pos.
"""
mri_head_t, trans = _get_trans(trans)
return head_to_mri(
self.pos,
subject,
mri_head_t,
subjects_dir=subjects_dir,
verbose=verbose,
kind="mri",
)
@verbose
def to_volume_labels(
self,
trans,
subject="fsaverage",
aseg="aparc+aseg",
subjects_dir=None,
verbose=None,
):
"""Find an ROI in atlas for the dipole positions.
Parameters
----------
%(trans)s
.. versionchanged:: 0.19
Support for 'fsaverage' argument.
%(subject)s
%(aseg)s
%(subjects_dir)s
%(verbose)s
Returns
-------
labels : list
List of anatomical region names from anatomical segmentation atlas.
Notes
-----
.. versionadded:: 0.24
"""
aseg_img, aseg_data = _get_aseg(aseg, subject, subjects_dir)
mri_vox_t = np.linalg.inv(aseg_img.header.get_vox2ras_tkr())
# Load freesurface atlas LUT
lut_inv = read_freesurfer_lut()[0]
lut = {v: k for k, v in lut_inv.items()}
# transform to voxel space from head space
pos = self.to_mri(subject, trans, subjects_dir=subjects_dir, verbose=verbose)
pos = apply_trans(mri_vox_t, pos)
pos = np.rint(pos).astype(int)
# Get voxel value and label from LUT
labels = [lut.get(aseg_data[tuple(coord)], "Unknown") for coord in pos]
return labels
def plot_amplitudes(self, color="k", show=True):
"""Plot the dipole amplitudes as a function of time.
Parameters
----------
color : matplotlib color
Color to use for the trace.
show : bool
Show figure if True.
Returns
-------
fig : matplotlib.figure.Figure
The figure object containing the plot.
"""
return plot_dipole_amplitudes([self], [color], show)
def __getitem__(self, item):
"""Get a time slice.
Parameters
----------
item : array-like or slice
The slice of time points to use.
Returns
-------
dip : instance of Dipole
The sliced dipole.
"""
if isinstance(item, int): # make sure attributes stay 2d
item = [item]
selected_times = self.times[item].copy()
selected_pos = self.pos[item, :].copy()
selected_amplitude = self.amplitude[item].copy()
selected_ori = self.ori[item, :].copy()
selected_gof = self.gof[item].copy()
selected_name = self.name
selected_conf = dict()
for key in self.conf.keys():
selected_conf[key] = self.conf[key][item]
selected_khi2 = self.khi2[item] if self.khi2 is not None else None
selected_nfree = self.nfree[item] if self.nfree is not None else None
return Dipole(
selected_times,
selected_pos,
selected_amplitude,
selected_ori,
selected_gof,
selected_name,
selected_conf,
selected_khi2,
selected_nfree,
)
def __len__(self):
"""Return the number of dipoles.
Returns
-------
len : int
The number of dipoles.
Examples
--------
This can be used as::
>>> len(dipoles) # doctest: +SKIP
10
"""
return self.pos.shape[0]
def _read_dipole_fixed(fname):
"""Read a fixed dipole FIF file."""
logger.info(f"Reading {fname} ...")
info, nave, aspect_kind, comment, times, data, _ = _read_evoked(fname)
return DipoleFixed(info, data, times, nave, aspect_kind, comment=comment)
@fill_doc
class DipoleFixed(ExtendedTimeMixin):
"""Dipole class for fixed-position dipole fits.
.. note::
This class should usually not be instantiated directly
via ``mne.DipoleFixed(...)``. Instead, use one of the functions
listed in the See Also section below.
Parameters
----------
%(info_not_none)s
data : array, shape (n_channels, n_times)
The dipole data.
times : array, shape (n_times,)
The time points.
nave : int
Number of averages.
aspect_kind : int
The kind of data.
comment : str
The dipole comment.
%(verbose)s
See Also
--------
read_dipole
Dipole
fit_dipole
Notes
-----
This class is for fixed-position dipole fits, where the position
(and maybe orientation) is static over time. For sequential dipole fits,
where the position can change a function of time, use :class:`mne.Dipole`.
.. versionadded:: 0.12
"""
@verbose
def __init__(
self, info, data, times, nave, aspect_kind, comment="", *, verbose=None
):
self.info = info
self.nave = nave
self._aspect_kind = aspect_kind
self.kind = _aspect_rev.get(aspect_kind, "unknown")
self.comment = comment
self._set_times(np.array(times))
self.data = data
self.preload = True
self._update_first_last()
def __repr__(self): # noqa: D105
s = f"n_times : {len(self.times)}"
s += f", tmin : {np.min(self.times)}"
s += f", tmax : {np.max(self.times)}"
return f"<DipoleFixed | {s}>"
def copy(self):
"""Copy the DipoleFixed object.
Returns
-------
inst : instance of DipoleFixed
The copy.
Notes
-----
.. versionadded:: 0.16
"""
return deepcopy(self)
@property
def ch_names(self):
"""Channel names."""
return self.info["ch_names"]
@verbose
def save(self, fname, *, overwrite=False, verbose=None):
"""Save fixed dipole in FIF format.
The ``.fif[.gz]`` format is for :class:`mne.DipoleFixed` objects, that is,
fixed-position and optionally fixed-orientation dipole fits. For these fits,
the amplitude (and optionally orientation) vary as a function of time,
but not the position.
Parameters
----------
fname : path-like
The name of the FIF file. Must end with ``'-dip.fif'`` or
``'-dip.fif.gz'`` to make it explicit that the file contains
dipole information in FIF format.
%(overwrite)s
.. versionadded:: 1.10.0
%(verbose)s
See Also
--------
read_dipole
"""
check_fname(
fname,
"DipoleFixed",
(
"-dip.fif",
"-dip.fif.gz",
"_dip.fif",
"_dip.fif.gz",
),
(".fif", ".fif.gz"),
)
_write_evokeds(fname, self, check=False, overwrite=overwrite)
def plot(self, show=True, time_unit="s"):
"""Plot dipole data.
Parameters
----------
show : bool
Call pyplot.show() at the end or not.
time_unit : str
The units for the time axis, can be "ms" or "s" (default).
.. versionadded:: 0.16
Returns
-------
fig : instance of matplotlib.figure.Figure
The figure containing the time courses.
"""
return _plot_evoked(
self,
picks=None,
exclude=(),
unit=True,
show=show,
ylim=None,
xlim="tight",
proj=False,
hline=None,
units=None,
scalings=None,
titles=None,
axes=None,
gfp=False,
window_title=None,
spatial_colors=False,
plot_type="butterfly",
selectable=False,
time_unit=time_unit,
)
# #############################################################################
# IO
@verbose
def read_dipole(fname, verbose=None):
"""Read a dipole object from a file.
Non-fixed-position :class:`mne.Dipole` objects are usually saved in ``.[b]dip``
format. Fixed-position :class:`mne.DipoleFixed` objects are usually saved in
FIF format.
Parameters
----------
fname : path-like
The name of the ``.[b]dip`` or ``.fif[.gz]`` file.
%(verbose)s
Returns
-------
%(dipole)s
See Also
--------
Dipole
DipoleFixed
fit_dipole
Notes
-----
.. versionchanged:: 0.20
Support for reading bdip (Xfit binary) format.
"""
fname = _check_fname(fname, overwrite="read", must_exist=True)
if fname.suffix == ".fif" or fname.name.endswith(".fif.gz"):
return _read_dipole_fixed(fname)
elif fname.suffix == ".bdip":
return _read_dipole_bdip(fname)
else:
return _read_dipole_text(fname)
def _read_dipole_text(fname):
"""Read a dipole text file."""
# Figure out the special fields
need_header = True
def_line = name = None
# There is a bug in older np.loadtxt regarding skipping fields,
# so just read the data ourselves (need to get name and header anyway)
data = list()
with open(fname) as fid:
for line in fid:
if not (line.startswith("%") or line.startswith("#")):
need_header = False
data.append(line.strip().split())
else:
if need_header:
def_line = line
if line.startswith("##") or line.startswith("%%"):
m = re.search('Name "(.*) dipoles"', line)
if m:
name = m.group(1)
del line
data = np.atleast_2d(np.array(data, float))
if def_line is None:
raise OSError(
"Dipole text file is missing field definition comment, cannot parse "
f"{fname}"
)
# actually parse the fields
def_line = def_line.lstrip("%").lstrip("#").strip()
# MNE writes it out differently than Elekta, let's standardize them...
fields = re.sub(
r"([X|Y|Z] )\(mm\)", # "X (mm)", etc.
lambda match: match.group(1).strip() + "/mm",
def_line,
)
fields = re.sub(
r"\((.*?)\)",
lambda match: "/" + match.group(1),
fields, # "Q(nAm)", etc.
)
fields = re.sub(
"(begin|end) ", # "begin" and "end" with no units
lambda match: match.group(1) + "/ms",
fields,
)
fields = fields.lower().split()
required_fields = (
"begin/ms",
"x/mm",
"y/mm",
"z/mm",
"q/nam",
"qx/nam",
"qy/nam",
"qz/nam",
"g/%",
)
optional_fields = (
"khi^2",
"free", # standard ones
# now the confidence fields (up to 5!)
"vol/mm^3",
"depth/mm",
"long/mm",
"trans/mm",
"qlong/nam",
"qtrans/nam",
)
conf_scales = [1e-9, 1e-3, 1e-3, 1e-3, 1e-9, 1e-9]
missing_fields = sorted(set(required_fields) - set(fields))
if len(missing_fields) > 0:
raise RuntimeError(
f"Could not find necessary fields in header: {missing_fields}"
)
handled_fields = set(required_fields) | set(optional_fields)
assert len(handled_fields) == len(required_fields) + len(optional_fields)
ignored_fields = sorted(set(fields) - set(handled_fields) - {"end/ms"})
if len(ignored_fields) > 0:
warn(f"Ignoring extra fields in dipole file: {ignored_fields}")
if len(fields) != data.shape[1]:
raise OSError(
f"More data fields ({len(fields)}) found than data columns ({data.shape[1]}"
f"): {fields}"
)
logger.info(f"{len(data)} dipole(s) found")
if "end/ms" in fields:
if np.diff(
data[:, [fields.index("begin/ms"), fields.index("end/ms")]], 1, -1
).any():
warn(
"begin and end fields differed, but only begin will be used "
"to store time values"
)
# Find the correct column in our data array, then scale to proper units
idx = [fields.index(field) for field in required_fields]
assert len(idx) >= 9
times = data[:, idx[0]] / 1000.0
pos = 1e-3 * data[:, idx[1:4]] # put data in meters
amplitude = data[:, idx[4]]
norm = amplitude.copy()
amplitude /= 1e9
norm[norm == 0] = 1
ori = data[:, idx[5:8]] / norm[:, np.newaxis]
gof = data[:, idx[8]]
# Deal with optional fields
optional = [None] * 2
for fi, field in enumerate(optional_fields[:2]):
if field in fields:
optional[fi] = data[:, fields.index(field)]
khi2, nfree = optional
conf = dict()
for field, scale in zip(optional_fields[2:], conf_scales): # confidence
if field in fields:
conf[field.split("/")[0]] = scale * data[:, fields.index(field)]
return Dipole(times, pos, amplitude, ori, gof, name, conf, khi2, nfree)
def _write_dipole_text(fname, dip):
fmt = " %7.1f %7.1f %8.2f %8.2f %8.2f %8.3f %8.3f %8.3f %8.3f %6.2f"
header = (
"# begin end X (mm) Y (mm) Z (mm)"
" Q(nAm) Qx(nAm) Qy(nAm) Qz(nAm) g/%"
)
t = dip.times[:, np.newaxis] * 1000.0
gof = dip.gof[:, np.newaxis]
amp = 1e9 * dip.amplitude[:, np.newaxis]
out = (t, t, dip.pos / 1e-3, amp, dip.ori * amp, gof)
# optional fields
fmts = dict(
khi2=(" khi^2", " %8.1f", 1.0),
nfree=(" free", " %5d", 1),
vol=(" vol/mm^3", " %9.3f", 1e9),
depth=(" depth/mm", " %9.3f", 1e3),
long=(" long/mm", " %8.3f", 1e3),
trans=(" trans/mm", " %9.3f", 1e3),
qlong=(" Qlong/nAm", " %10.3f", 1e9),
qtrans=(" Qtrans/nAm", " %11.3f", 1e9),
)
for key in ("khi2", "nfree"):
data = getattr(dip, key)
if data is not None:
header += fmts[key][0]
fmt += fmts[key][1]
out += (data[:, np.newaxis] * fmts[key][2],)
for key in ("vol", "depth", "long", "trans", "qlong", "qtrans"):
data = dip.conf.get(key)
if data is not None:
header += fmts[key][0]
fmt += fmts[key][1]
out += (data[:, np.newaxis] * fmts[key][2],)
out = np.concatenate(out, axis=-1)
# NB CoordinateSystem is hard-coded as Head here
with open(fname, "wb") as fid:
fid.write(b'# CoordinateSystem "Head"\n')
fid.write((header + "\n").encode("utf-8"))
np.savetxt(fid, out, fmt=fmt)
if dip.name is not None:
fid.write((f'## Name "{dip.name} dipoles" Style "Dipoles"').encode())
_BDIP_ERROR_KEYS = ("depth", "long", "trans", "qlong", "qtrans")
def _read_dipole_bdip(fname):
name = None
nfree = None
with open(fname, "rb") as fid:
# Which dipole in a multi-dipole set
times = list()
pos = list()
amplitude = list()
ori = list()
gof = list()
conf = dict(vol=list())
khi2 = list()
has_errors = None
while True:
num = np.frombuffer(fid.read(4), ">i4")
if len(num) == 0:
break
times.append(np.frombuffer(fid.read(4), ">f4")[0])
fid.read(4) # end
fid.read(12) # r0
pos.append(np.frombuffer(fid.read(12), ">f4"))
Q = np.frombuffer(fid.read(12), ">f4")
amplitude.append(np.linalg.norm(Q))
ori.append(Q / amplitude[-1])
gof.append(100 * np.frombuffer(fid.read(4), ">f4")[0])
this_has_errors = bool(np.frombuffer(fid.read(4), ">i4")[0])
if has_errors is None:
has_errors = this_has_errors
for key in _BDIP_ERROR_KEYS:
conf[key] = list()
assert has_errors == this_has_errors
fid.read(4) # Noise level used for error computations
limits = np.frombuffer(fid.read(20), ">f4") # error limits
for key, lim in zip(_BDIP_ERROR_KEYS, limits):
conf[key].append(lim)
fid.read(100) # (5, 5) fully describes the conf. ellipsoid
conf["vol"].append(np.frombuffer(fid.read(4), ">f4")[0])
khi2.append(np.frombuffer(fid.read(4), ">f4")[0])
fid.read(4) # prob
fid.read(4) # total noise estimate
return Dipole(times, pos, amplitude, ori, gof, name, conf, khi2, nfree)
def _write_dipole_bdip(fname, dip):
with open(fname, "wb+") as fid:
for ti, t in enumerate(dip.times):
fid.write(np.zeros(1, ">i4").tobytes()) # int dipole
fid.write(np.array([t, 0]).astype(">f4").tobytes())
fid.write(np.zeros(3, ">f4").tobytes()) # r0
fid.write(dip.pos[ti].astype(">f4").tobytes()) # pos
Q = dip.amplitude[ti] * dip.ori[ti]
fid.write(Q.astype(">f4").tobytes())
fid.write(np.array(dip.gof[ti] / 100.0, ">f4").tobytes())
has_errors = int(bool(len(dip.conf)))
fid.write(np.array(has_errors, ">i4").tobytes()) # has_errors
fid.write(np.zeros(1, ">f4").tobytes()) # noise level
for key in _BDIP_ERROR_KEYS:
val = dip.conf[key][ti] if key in dip.conf else 0.0
assert val.shape == ()
fid.write(np.array(val, ">f4").tobytes())
fid.write(np.zeros(25, ">f4").tobytes())
conf = dip.conf["vol"][ti] if "vol" in dip.conf else 0.0
fid.write(np.array(conf, ">f4").tobytes())
khi2 = dip.khi2[ti] if dip.khi2 is not None else 0
fid.write(np.array(khi2, ">f4").tobytes())
fid.write(np.zeros(1, ">f4").tobytes()) # prob
fid.write(np.zeros(1, ">f4").tobytes()) # total noise est
# #############################################################################
# Fitting
def _dipole_forwards(*, sensors, fwd_data, whitener, rr, n_jobs=None):
"""Compute the forward solution and do other nice stuff."""
B = _compute_forwards_meeg(
rr, sensors=sensors, fwd_data=fwd_data, n_jobs=n_jobs, silent=True
)
B = np.concatenate(list(B.values()), axis=1)
assert np.isfinite(B).all()
B_orig = B.copy()
# Apply projection and whiten (cov has projections already)
_, _, dgemm = _get_ddot_dgemv_dgemm()
B = dgemm(1.0, B, whitener.T)
# column normalization doesn't affect our fitting, so skip for now
# S = np.sum(B * B, axis=1) # across channels
# scales = np.repeat(3. / np.sqrt(np.sum(np.reshape(S, (len(rr), 3)),
# axis=1)), 3)
# B *= scales[:, np.newaxis]
scales = np.ones(3)
return B, B_orig, scales
@verbose
def _make_guesses(surf, grid, exclude, mindist, n_jobs=None, verbose=None):
"""Make a guess space inside a sphere or BEM surface."""
if "rr" in surf:
logger.info(
"Guess surface ({}) is in {} coordinates".format(
_bem_surf_name[surf["id"]], _coord_frame_name(surf["coord_frame"])
)
)
else:
logger.info(
"Making a spherical guess space with radius {:7.1f} mm...".format(
1000 * surf["R"]
)
)
logger.info("Filtering (grid = %6.f mm)..." % (1000 * grid))
src = _make_volume_source_space(
surf, grid, exclude, 1000 * mindist, do_neighbors=False, n_jobs=n_jobs
)[0]
assert "vertno" in src
# simplify the result to make things easier later
src = dict(
rr=src["rr"][src["vertno"]],
nn=src["nn"][src["vertno"]],
nuse=src["nuse"],
coord_frame=src["coord_frame"],
vertno=np.arange(src["nuse"]),
type="discrete",
)
return SourceSpaces([src])
def _fit_eval(rd, B, B2, *, sensors, fwd_data, whitener, lwork, fwd_svd):
"""Calculate the residual sum of squares."""
if fwd_svd is None:
assert sensors is not None
fwd = _dipole_forwards(
sensors=sensors, fwd_data=fwd_data, whitener=whitener, rr=rd[np.newaxis, :]
)[0]
uu, sing, vv = _repeated_svd(fwd, lwork, overwrite_a=True)
else:
uu, sing, vv = fwd_svd
gof = _dipole_gof(uu, sing, vv, B, B2)[0]
# mne-c uses fitness=B2-Bm2, but ours (1-gof) is just a normalized version
return 1.0 - gof
@functools.lru_cache(None)
def _get_ddot_dgemv_dgemm():