forked from mne-tools/mne-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
forward.py
2201 lines (1922 loc) · 73.7 KB
/
forward.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
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
# The computations in this code were primarily derived from Matti Hämäläinen's
# C code.
import os
import re
import shutil
import tempfile
from copy import deepcopy
from os import PathLike
from os import path as op
from pathlib import Path
from time import time
import numpy as np
from scipy import sparse
from .._fiff.constants import FIFF
from .._fiff.matrix import (
_read_named_matrix,
_transpose_named_matrix,
write_named_matrix,
)
from .._fiff.meas_info import (
Info,
_make_ch_names_mapping,
_read_bad_channels,
_read_extended_ch_info,
_write_bad_channels,
_write_ch_infos,
write_info,
)
from .._fiff.open import fiff_open
from .._fiff.pick import pick_channels, pick_channels_forward, pick_info, pick_types
from .._fiff.tag import find_tag, read_tag
from .._fiff.tree import dir_tree_find
from .._fiff.write import (
end_block,
start_and_end_file,
start_block,
write_coord_trans,
write_id,
write_int,
write_string,
)
from ..epochs import BaseEpochs
from ..evoked import Evoked, EvokedArray
from ..html_templates import _get_html_template
from ..io import BaseRaw, RawArray
from ..label import Label
from ..source_estimate import _BaseSourceEstimate, _BaseVectorSourceEstimate
from ..source_space._source_space import (
SourceSpaces,
_get_src_nn,
_read_source_spaces_from_tree,
_set_source_space_vertices,
_src_kind_dict,
_write_source_spaces_to_fid,
find_source_space_hemi,
)
from ..surface import _normal_orth
from ..transforms import invert_transform, transform_surface_to, write_trans
from ..utils import (
_check_compensation_grade,
_check_fname,
_check_option,
_check_stc_units,
_import_h5io_funcs,
_on_missing,
_stamp_to_dt,
_validate_type,
check_fname,
fill_doc,
get_subjects_dir,
has_mne_c,
logger,
repr_html,
run_subprocess,
verbose,
warn,
)
class Forward(dict):
"""Forward class to represent info from forward solution.
Like :class:`mne.Info`, this data structure behaves like a dictionary.
It contains all metadata necessary for a forward solution.
.. warning::
This class should not be modified or created by users.
Forward objects should be obtained using
:func:`mne.make_forward_solution` or :func:`mne.read_forward_solution`.
Attributes
----------
ch_names : list of str
A convenience wrapper accessible as ``fwd.ch_names`` which wraps
``fwd['info']['ch_names']``.
See Also
--------
mne.make_forward_solution
mne.read_forward_solution
Notes
-----
Forward data is accessible via string keys using standard
:class:`python:dict` access (e.g., ``fwd['nsource'] == 4096``):
source_ori : int
The source orientation, either ``FIFF.FIFFV_MNE_FIXED_ORI`` or
``FIFF.FIFFV_MNE_FREE_ORI``.
coord_frame : int
The coordinate frame of the forward solution, usually
``FIFF.FIFFV_COORD_HEAD``.
nsource : int
The number of source locations.
nchan : int
The number of channels.
sol : dict
The forward solution, with entries:
``'data'`` : ndarray, shape (n_channels, nsource * n_ori)
The forward solution data. The shape will be
``(n_channels, nsource)`` for a fixed-orientation forward and
``(n_channels, nsource * 3)`` for a free-orientation forward.
``'row_names'`` : list of str
The channel names.
mri_head_t : instance of Transform
The mri ↔ head transformation that was used.
info : instance of :class:`~mne.Info`
The measurement information (with contents reduced compared to that
of the original data).
src : instance of :class:`~mne.SourceSpaces`
The source space used during forward computation. This can differ
from the original source space as:
1. Source points are removed due to proximity to (or existing
outside)
the inner skull surface.
2. The source space will be converted to the ``coord_frame`` of the
forward solution, which typically means it gets converted from
MRI to head coordinates.
source_rr : ndarray, shape (n_sources, 3)
The source locations.
source_nn : ndarray, shape (n_sources, 3)
The source normals. Will be all +Z (``(0, 0, 1.)``) for volume
source spaces. For surface source spaces, these are normal to the
cortical surface.
surf_ori : int
Whether ``sol`` is surface-oriented with the surface normal in the
Z component (``FIFF.FIFFV_MNE_FIXED_ORI``) or +Z in the given
``coord_frame`` in the Z component (``FIFF.FIFFV_MNE_FREE_ORI``).
Forward objects also have some attributes that are accessible via ``.``
access, like ``fwd.ch_names``.
"""
def copy(self):
"""Copy the Forward instance."""
return Forward(deepcopy(self))
@verbose
def save(self, fname, *, overwrite=False, verbose=None):
"""Save the forward solution.
Parameters
----------
%(fname_fwd)s
%(overwrite)s
%(verbose)s
"""
write_forward_solution(fname, self, overwrite=overwrite)
def _get_src_type_and_ori_for_repr(self):
src_types = np.array([src["type"] for src in self["src"]])
if (src_types == "surf").all():
src_type = "Surface with %d vertices" % self["nsource"]
elif (src_types == "vol").all():
src_type = "Volume with %d grid points" % self["nsource"]
elif (src_types == "discrete").all():
src_type = "Discrete with %d dipoles" % self["nsource"]
else:
count_string = ""
if (src_types == "surf").any():
count_string += "%d surface, " % (src_types == "surf").sum()
if (src_types == "vol").any():
count_string += "%d volume, " % (src_types == "vol").sum()
if (src_types == "discrete").any():
count_string += "%d discrete, " % (src_types == "discrete").sum()
count_string = count_string.rstrip(", ")
src_type = "Mixed (%s) with %d vertices" % (count_string, self["nsource"])
if self["source_ori"] == FIFF.FIFFV_MNE_UNKNOWN_ORI:
src_ori = "Unknown"
elif self["source_ori"] == FIFF.FIFFV_MNE_FIXED_ORI:
src_ori = "Fixed"
elif self["source_ori"] == FIFF.FIFFV_MNE_FREE_ORI:
src_ori = "Free"
return src_type, src_ori
def __repr__(self):
"""Summarize forward info instead of printing all."""
entr = "<Forward"
nchan = len(pick_types(self["info"], meg=True, eeg=False, exclude=[]))
entr += " | " + "MEG channels: %d" % nchan
nchan = len(pick_types(self["info"], meg=False, eeg=True, exclude=[]))
entr += " | " + "EEG channels: %d" % nchan
src_type, src_ori = self._get_src_type_and_ori_for_repr()
entr += f" | Source space: {src_type}"
entr += f" | Source orientation: {src_ori}"
entr += ">"
return entr
@repr_html
def _repr_html_(self):
src_descr, src_ori = self._get_src_type_and_ori_for_repr()
t = _get_html_template("repr", "forward.html.jinja")
html = t.render(
info=self["info"],
source_space_descr=src_descr,
source_orientation=src_ori,
)
return html
@property
def ch_names(self):
return self["info"]["ch_names"]
def pick_channels(self, ch_names, ordered=False):
"""Pick channels from this forward operator.
Parameters
----------
ch_names : list of str
List of channels to include.
ordered : bool
If true (default False), treat ``include`` as an ordered list
rather than a set.
Returns
-------
fwd : instance of Forward.
The modified forward model.
Notes
-----
Operates in-place.
.. versionadded:: 0.20.0
"""
return pick_channels_forward(
self, ch_names, exclude=[], ordered=ordered, copy=False, verbose=False
)
def _block_diag(A, n):
"""Construct a block diagonal from a packed structure.
You have to try it on a matrix to see what it's doing.
If A is not sparse, then returns a sparse block diagonal "bd",
diagonalized from the
elements in "A".
"A" is ma x na, comprising bdn=(na/"n") blocks of submatrices.
Each submatrix is ma x "n", and these submatrices are
placed down the diagonal of the matrix.
If A is already sparse, then the operation is reversed, yielding
a block
row matrix, where each set of n columns corresponds to a block element
from the block diagonal.
Parameters
----------
A : array
The matrix
n : int
The block size
Returns
-------
bd : scipy.sparse.csc_array
The block diagonal matrix
"""
if sparse.issparse(A): # then make block sparse
raise NotImplementedError("sparse reversal not implemented yet")
ma, na = A.shape
bdn = na // int(n) # number of submatrices
if na % n > 0:
raise ValueError("Width of matrix must be a multiple of n")
tmp = np.arange(ma * bdn, dtype=np.int64).reshape(bdn, ma)
tmp = np.tile(tmp, (1, n))
ii = tmp.ravel()
jj = np.arange(na, dtype=np.int64)[None, :]
jj = jj * np.ones(ma, dtype=np.int64)[:, None]
jj = jj.T.ravel() # column indices foreach sparse bd
bd = sparse.coo_array((A.T.ravel(), np.c_[ii, jj].T)).tocsc()
return bd
def _get_tag_int(fid, node, name, id_):
"""Check we have an appropriate tag."""
tag = find_tag(fid, node, id_)
if tag is None:
fid.close()
raise ValueError(name + " tag not found")
return int(tag.data.item())
def _read_one(fid, node):
"""Read all interesting stuff for one forward solution."""
# This function assumes the fid is open as a context manager
if node is None:
return None
one = Forward()
one["source_ori"] = _get_tag_int(
fid, node, "Source orientation", FIFF.FIFF_MNE_SOURCE_ORIENTATION
)
one["coord_frame"] = _get_tag_int(
fid, node, "Coordinate frame", FIFF.FIFF_MNE_COORD_FRAME
)
one["nsource"] = _get_tag_int(
fid, node, "Number of sources", FIFF.FIFF_MNE_SOURCE_SPACE_NPOINTS
)
one["nchan"] = _get_tag_int(fid, node, "Number of channels", FIFF.FIFF_NCHAN)
try:
one["sol"] = _read_named_matrix(
fid, node, FIFF.FIFF_MNE_FORWARD_SOLUTION, transpose=True
)
one["_orig_sol"] = one["sol"]["data"].copy()
except Exception:
logger.error("Forward solution data not found")
raise
try:
fwd_type = FIFF.FIFF_MNE_FORWARD_SOLUTION_GRAD
one["sol_grad"] = _read_named_matrix(fid, node, fwd_type, transpose=True)
one["_orig_sol_grad"] = one["sol_grad"]["data"].copy()
except Exception:
one["sol_grad"] = None
if one["sol"]["data"].shape[0] != one["nchan"] or (
one["sol"]["data"].shape[1] != one["nsource"]
and one["sol"]["data"].shape[1] != 3 * one["nsource"]
):
raise ValueError("Forward solution matrix has wrong dimensions")
if one["sol_grad"] is not None:
if one["sol_grad"]["data"].shape[0] != one["nchan"] or (
one["sol_grad"]["data"].shape[1] != 3 * one["nsource"]
and one["sol_grad"]["data"].shape[1] != 3 * 3 * one["nsource"]
):
raise ValueError("Forward solution gradient matrix has wrong dimensions")
return one
@fill_doc
def _read_forward_meas_info(tree, fid):
"""Read light measurement info from forward operator.
Parameters
----------
tree : tree
FIF tree structure.
fid : file id
The file id.
Returns
-------
%(info_not_none)s
"""
# This function assumes fid is being used as a context manager
info = Info()
info._unlocked = True
# Information from the MRI file
parent_mri = dir_tree_find(tree, FIFF.FIFFB_MNE_PARENT_MRI_FILE)
if len(parent_mri) == 0:
raise ValueError("No parent MEG information found in operator")
parent_mri = parent_mri[0]
tag = find_tag(fid, parent_mri, FIFF.FIFF_MNE_FILE_NAME)
info["mri_file"] = tag.data if tag is not None else None
tag = find_tag(fid, parent_mri, FIFF.FIFF_PARENT_FILE_ID)
info["mri_id"] = tag.data if tag is not None else None
# Information from the MEG file
parent_meg = dir_tree_find(tree, FIFF.FIFFB_MNE_PARENT_MEAS_FILE)
if len(parent_meg) == 0:
raise ValueError("No parent MEG information found in operator")
parent_meg = parent_meg[0]
tag = find_tag(fid, parent_meg, FIFF.FIFF_MNE_FILE_NAME)
info["meas_file"] = tag.data if tag is not None else None
tag = find_tag(fid, parent_meg, FIFF.FIFF_PARENT_FILE_ID)
info["meas_id"] = tag.data if tag is not None else None
# Add channel information
info["chs"] = chs = list()
for k in range(parent_meg["nent"]):
kind = parent_meg["directory"][k].kind
pos = parent_meg["directory"][k].pos
if kind == FIFF.FIFF_CH_INFO:
tag = read_tag(fid, pos)
chs.append(tag.data)
ch_names_mapping = _read_extended_ch_info(chs, parent_meg, fid)
info._update_redundant()
# Get the MRI <-> head coordinate transformation
tag = find_tag(fid, parent_mri, FIFF.FIFF_COORD_TRANS)
coord_head = FIFF.FIFFV_COORD_HEAD
coord_mri = FIFF.FIFFV_COORD_MRI
coord_device = FIFF.FIFFV_COORD_DEVICE
coord_ctf_head = FIFF.FIFFV_MNE_COORD_CTF_HEAD
if tag is None:
raise ValueError("MRI/head coordinate transformation not found")
cand = tag.data
if cand["from"] == coord_mri and cand["to"] == coord_head:
info["mri_head_t"] = cand
else:
raise ValueError("MRI/head coordinate transformation not found")
# Get the MEG device <-> head coordinate transformation
tag = find_tag(fid, parent_meg, FIFF.FIFF_COORD_TRANS)
if tag is None:
raise ValueError("MEG/head coordinate transformation not found")
cand = tag.data
if cand["from"] == coord_device and cand["to"] == coord_head:
info["dev_head_t"] = cand
elif cand["from"] == coord_ctf_head and cand["to"] == coord_head:
info["ctf_head_t"] = cand
else:
raise ValueError("MEG/head coordinate transformation not found")
bads = _read_bad_channels(fid, parent_meg, ch_names_mapping=ch_names_mapping)
# clean up our bad list, old versions could have non-existent bads
info["bads"] = [bad for bad in bads if bad in info["ch_names"]]
# Check if a custom reference has been applied
tag = find_tag(fid, parent_mri, FIFF.FIFF_MNE_CUSTOM_REF)
if tag is None:
tag = find_tag(fid, parent_mri, 236) # Constant 236 used before v0.11
info["custom_ref_applied"] = int(tag.data.item()) if tag is not None else False
info._unlocked = False
return info
def _subject_from_forward(forward):
"""Get subject id from inverse operator."""
return forward["src"]._subject
# This sets the forward solution order (and gives human-readable names)
_FWD_ORDER = dict(
meg="MEG",
eeg="EEG",
)
@verbose
def _merge_fwds(fwds, *, verbose=None):
"""Merge loaded forward dicts into one dict."""
fwd = None
first_key = None
combined = list()
for key in _FWD_ORDER:
if key not in fwds:
continue
if fwd is None: # assign
fwd = fwds[key]
first_key = key
combined.append(_FWD_ORDER[key])
continue
a = fwd
b = fwds[key]
a_kind, b_kind = _FWD_ORDER[first_key], _FWD_ORDER[key]
combined.append(b_kind)
if (
a["sol"]["data"].shape[1] != b["sol"]["data"].shape[1]
or a["source_ori"] != b["source_ori"]
or a["nsource"] != b["nsource"]
or a["coord_frame"] != b["coord_frame"]
):
raise ValueError(
f"The {a_kind} and {b_kind} forward solutions do not match"
)
for k in ("sol", "sol_grad"):
if a[k] is None:
continue
a[k]["data"] = np.r_[a[k]["data"], b[k]["data"]]
a[f"_orig_{k}"] = np.r_[a[f"_orig_{k}"], b[f"_orig_{k}"]]
a[k]["nrow"] = a[k]["nrow"] + b[k]["nrow"]
a[k]["row_names"] = a[k]["row_names"] + b[k]["row_names"]
a["nchan"] = a["nchan"] + b["nchan"]
if len(fwds) > 1:
logger.info(f' Forward solutions combined: {", ".join(combined)}')
return fwd
@verbose
def read_forward_solution(fname, include=(), exclude=(), *, ordered=True, verbose=None):
"""Read a forward solution a.k.a. lead field.
Parameters
----------
fname : path-like
The file name, which should end with ``-fwd.fif``, ``-fwd.fif.gz``,
``_fwd.fif``, ``_fwd.fif.gz``, ``-fwd.h5``, or ``_fwd.h5``.
include : list, optional
List of names of channels to include. If empty all channels
are included.
exclude : list, optional
List of names of channels to exclude. If empty include all channels.
%(ordered)s
%(verbose)s
Returns
-------
fwd : instance of Forward
The forward solution.
See Also
--------
write_forward_solution, make_forward_solution
Notes
-----
Forward solutions, which are derived from an original forward solution with
free orientation, are always stored on disk as forward solution with free
orientation in X/Y/Z RAS coordinates. To apply any transformation to the
forward operator (surface orientation, fixed orientation) please apply
:func:`convert_forward_solution` after reading the forward solution with
:func:`read_forward_solution`.
Forward solutions, which are derived from an original forward solution with
fixed orientation, are stored on disk as forward solution with fixed
surface-based orientations. Please note that the transformation to
surface-based, fixed orientation cannot be reverted after loading the
forward solution with :func:`read_forward_solution`.
"""
check_fname(
fname,
"forward",
("-fwd.fif", "-fwd.fif.gz", "_fwd.fif", "_fwd.fif.gz", "-fwd.h5", "_fwd.h5"),
)
fname = _check_fname(fname=fname, must_exist=True, overwrite="read")
# Open the file, create directory
logger.info(f"Reading forward solution from {fname}...")
if fname.suffix == ".h5":
return _read_forward_hdf5(fname)
f, tree, _ = fiff_open(fname)
with f as fid:
# Find all forward solutions
fwds = dir_tree_find(tree, FIFF.FIFFB_MNE_FORWARD_SOLUTION)
if len(fwds) == 0:
raise ValueError(f"No forward solutions in {fname}")
# Parent MRI data
parent_mri = dir_tree_find(tree, FIFF.FIFFB_MNE_PARENT_MRI_FILE)
if len(parent_mri) == 0:
raise ValueError(f"No parent MRI information in {fname}")
parent_mri = parent_mri[0]
src = _read_source_spaces_from_tree(fid, tree, patch_stats=False)
for s in src:
s["id"] = find_source_space_hemi(s)
fwd = None
# Locate and read the forward solutions
megnode = None
eegnode = None
for k in range(len(fwds)):
tag = find_tag(fid, fwds[k], FIFF.FIFF_MNE_INCLUDED_METHODS)
if tag is None:
raise ValueError("Methods not listed for one of the forward solutions")
if tag.data == FIFF.FIFFV_MNE_MEG:
megnode = fwds[k]
elif tag.data == FIFF.FIFFV_MNE_EEG:
eegnode = fwds[k]
fwds = dict()
megfwd = _read_one(fid, megnode)
if megfwd is not None:
fwds["meg"] = megfwd
if is_fixed_orient(megfwd):
ori = "fixed"
else:
ori = "free"
logger.info(
" Read MEG forward solution (%d sources, "
"%d channels, %s orientations)"
% (megfwd["nsource"], megfwd["nchan"], ori)
)
del megfwd
eegfwd = _read_one(fid, eegnode)
if eegfwd is not None:
fwds["eeg"] = eegfwd
if is_fixed_orient(eegfwd):
ori = "fixed"
else:
ori = "free"
logger.info(
" Read EEG forward solution (%d sources, "
"%d channels, %s orientations)"
% (eegfwd["nsource"], eegfwd["nchan"], ori)
)
del eegfwd
fwd = _merge_fwds(fwds)
del fwds
# Get the MRI <-> head coordinate transformation
tag = find_tag(fid, parent_mri, FIFF.FIFF_COORD_TRANS)
if tag is None:
raise ValueError("MRI/head coordinate transformation not found")
mri_head_t = tag.data
if (
mri_head_t["from"] != FIFF.FIFFV_COORD_MRI
or mri_head_t["to"] != FIFF.FIFFV_COORD_HEAD
):
mri_head_t = invert_transform(mri_head_t)
if (
mri_head_t["from"] != FIFF.FIFFV_COORD_MRI
or mri_head_t["to"] != FIFF.FIFFV_COORD_HEAD
):
fid.close()
raise ValueError("MRI/head coordinate transformation not found")
fwd["mri_head_t"] = mri_head_t
#
# get parent MEG info
#
fwd["info"] = _read_forward_meas_info(tree, fid)
# MNE environment
parent_env = dir_tree_find(tree, FIFF.FIFFB_MNE_ENV)
if len(parent_env) > 0:
parent_env = parent_env[0]
tag = find_tag(fid, parent_env, FIFF.FIFF_MNE_ENV_WORKING_DIR)
if tag is not None:
with fwd["info"]._unlock():
fwd["info"]["working_dir"] = tag.data
tag = find_tag(fid, parent_env, FIFF.FIFF_MNE_ENV_COMMAND_LINE)
if tag is not None:
with fwd["info"]._unlock():
fwd["info"]["command_line"] = tag.data
# Transform the source spaces to the correct coordinate frame
# if necessary
# Make sure forward solution is in either the MRI or HEAD coordinate frame
if fwd["coord_frame"] not in (FIFF.FIFFV_COORD_MRI, FIFF.FIFFV_COORD_HEAD):
raise ValueError(
"Only forward solutions computed in MRI or head "
"coordinates are acceptable"
)
# Transform each source space to the HEAD or MRI coordinate frame,
# depending on the coordinate frame of the forward solution
# NOTE: the function transform_surface_to will also work on discrete and
# volume sources
nuse = 0
for s in src:
try:
s = transform_surface_to(s, fwd["coord_frame"], mri_head_t)
except Exception as inst:
raise ValueError(f"Could not transform source space ({inst})")
nuse += s["nuse"]
# Make sure the number of sources match after transformation
if nuse != fwd["nsource"]:
raise ValueError("Source spaces do not match the forward solution.")
logger.info(
" Source spaces transformed to the forward solution coordinate frame"
)
fwd["src"] = src
# Handle the source locations and orientations
fwd["source_rr"] = np.concatenate([ss["rr"][ss["vertno"], :] for ss in src], axis=0)
# Store original source orientations
fwd["_orig_source_ori"] = fwd["source_ori"]
# Deal with include and exclude
pick_channels_forward(fwd, include=include, exclude=exclude, copy=False)
if is_fixed_orient(fwd, orig=True):
fwd["source_nn"] = np.concatenate(
[_src["nn"][_src["vertno"], :] for _src in fwd["src"]], axis=0
)
fwd["source_ori"] = FIFF.FIFFV_MNE_FIXED_ORI
fwd["surf_ori"] = True
else:
fwd["source_nn"] = np.kron(np.ones((fwd["nsource"], 1)), np.eye(3))
fwd["source_ori"] = FIFF.FIFFV_MNE_FREE_ORI
fwd["surf_ori"] = False
return Forward(fwd)
@verbose
def convert_forward_solution(
fwd, surf_ori=False, force_fixed=False, copy=True, use_cps=True, *, verbose=None
):
"""Convert forward solution between different source orientations.
Parameters
----------
fwd : Forward
The forward solution to modify.
surf_ori : bool, optional (default False)
Use surface-based source coordinate system? Note that force_fixed=True
implies surf_ori=True.
force_fixed : bool, optional (default False)
If True, force fixed source orientation mode.
copy : bool
Whether to return a new instance or modify in place.
%(use_cps)s
%(verbose)s
Returns
-------
fwd : Forward
The modified forward solution.
"""
fwd = fwd.copy() if copy else fwd
if force_fixed is True:
surf_ori = True
if any([src["type"] == "vol" for src in fwd["src"]]) and force_fixed:
raise ValueError(
"Forward operator was generated with sources from a "
"volume source space. Conversion to fixed orientation is not "
"possible. Consider using a discrete source space if you have "
"meaningful normal orientations."
)
if surf_ori and use_cps:
if any(s.get("patch_inds") is not None for s in fwd["src"]):
logger.info(
" Average patch normals will be employed in "
"the rotation to the local surface coordinates.."
".."
)
else:
use_cps = False
logger.info(
" No patch info available. The standard source "
"space normals will be employed in the rotation "
"to the local surface coordinates...."
)
# We need to change these entries (only):
# 1. source_nn
# 2. sol['data']
# 3. sol['ncol']
# 4. sol_grad['data']
# 5. sol_grad['ncol']
# 6. source_ori
if is_fixed_orient(fwd, orig=True) or (force_fixed and not use_cps):
# Fixed
fwd["source_nn"] = np.concatenate(
[_get_src_nn(s, use_cps) for s in fwd["src"]], axis=0
)
if not is_fixed_orient(fwd, orig=True):
logger.info(
" Changing to fixed-orientation forward "
"solution with surface-based source orientations..."
)
fix_rot = _block_diag(fwd["source_nn"].T, 1)
# newer versions of numpy require explicit casting here, so *= no
# longer works
fwd["sol"]["data"] = (fwd["_orig_sol"] @ fix_rot).astype("float32")
fwd["sol"]["ncol"] = fwd["nsource"]
if fwd["sol_grad"] is not None:
x = sparse.block_diag([fix_rot] * 3)
fwd["sol_grad"]["data"] = fwd["_orig_sol_grad"] @ x
fwd["sol_grad"]["ncol"] = 3 * fwd["nsource"]
fwd["source_ori"] = FIFF.FIFFV_MNE_FIXED_ORI
fwd["surf_ori"] = True
elif surf_ori: # Free, surf-oriented
# Rotate the local source coordinate systems
fwd["source_nn"] = np.kron(np.ones((fwd["nsource"], 1)), np.eye(3))
logger.info(" Converting to surface-based source orientations...")
# Actually determine the source orientations
pp = 0
for s in fwd["src"]:
if s["type"] in ["surf", "discrete"]:
nn = _get_src_nn(s, use_cps)
stop = pp + 3 * s["nuse"]
fwd["source_nn"][pp:stop] = _normal_orth(nn).reshape(-1, 3)
pp = stop
del nn
else:
pp += 3 * s["nuse"]
# Rotate the solution components as well
if force_fixed:
fwd["source_nn"] = fwd["source_nn"][2::3, :]
fix_rot = _block_diag(fwd["source_nn"].T, 1)
# newer versions of numpy require explicit casting here, so *= no
# longer works
fwd["sol"]["data"] = (fwd["_orig_sol"] @ fix_rot).astype("float32")
fwd["sol"]["ncol"] = fwd["nsource"]
if fwd["sol_grad"] is not None:
x = sparse.block_diag([fix_rot] * 3)
fwd["sol_grad"]["data"] = fwd["_orig_sol_grad"] @ x
fwd["sol_grad"]["ncol"] = 3 * fwd["nsource"]
fwd["source_ori"] = FIFF.FIFFV_MNE_FIXED_ORI
fwd["surf_ori"] = True
else:
surf_rot = _block_diag(fwd["source_nn"].T, 3)
fwd["sol"]["data"] = fwd["_orig_sol"] @ surf_rot
fwd["sol"]["ncol"] = 3 * fwd["nsource"]
if fwd["sol_grad"] is not None:
x = sparse.block_diag([surf_rot] * 3)
fwd["sol_grad"]["data"] = fwd["_orig_sol_grad"] @ x
fwd["sol_grad"]["ncol"] = 9 * fwd["nsource"]
fwd["source_ori"] = FIFF.FIFFV_MNE_FREE_ORI
fwd["surf_ori"] = True
else: # Free, cartesian
logger.info(" Cartesian source orientations...")
fwd["source_nn"] = np.tile(np.eye(3), (fwd["nsource"], 1))
fwd["sol"]["data"] = fwd["_orig_sol"].copy()
fwd["sol"]["ncol"] = 3 * fwd["nsource"]
if fwd["sol_grad"] is not None:
fwd["sol_grad"]["data"] = fwd["_orig_sol_grad"].copy()
fwd["sol_grad"]["ncol"] = 9 * fwd["nsource"]
fwd["source_ori"] = FIFF.FIFFV_MNE_FREE_ORI
fwd["surf_ori"] = False
logger.info(" [done]")
return fwd
@verbose
def write_forward_solution(fname, fwd, overwrite=False, verbose=None):
"""Write forward solution to a file.
Parameters
----------
%(fname_fwd)s
fwd : Forward
Forward solution.
%(overwrite)s
%(verbose)s
See Also
--------
read_forward_solution
Notes
-----
Forward solutions, which are derived from an original forward solution with
free orientation, are always stored on disk as forward solution with free
orientation in X/Y/Z RAS coordinates. Transformations (surface orientation,
fixed orientation) will be reverted. To reapply any transformation to the
forward operator please apply :func:`convert_forward_solution` after
reading the forward solution with :func:`read_forward_solution`.
Forward solutions, which are derived from an original forward solution with
fixed orientation, are stored on disk as forward solution with fixed
surface-based orientations. Please note that the transformation to
surface-based, fixed orientation cannot be reverted after loading the
forward solution with :func:`read_forward_solution`.
"""
check_fname(
fname,
"forward",
("-fwd.fif", "-fwd.fif.gz", "_fwd.fif", "_fwd.fif.gz", "-fwd.h5", "_fwd.h5"),
)
# check for file existence and expand `~` if present
fname = _check_fname(fname, overwrite)
if fname.suffix == ".h5":
_write_forward_hdf5(fname, fwd)
else:
with start_and_end_file(fname) as fid:
_write_forward_solution(fid, fwd)
def _write_forward_hdf5(fname, fwd):
_, write_hdf5 = _import_h5io_funcs()
write_hdf5(fname, dict(fwd=fwd), overwrite=True)
def _read_forward_hdf5(fname):
read_hdf5, _ = _import_h5io_funcs()
fwd = Forward(read_hdf5(fname)["fwd"])
fwd["info"] = Info(fwd["info"])
fwd["src"] = SourceSpaces(fwd["src"])
return fwd
def _write_forward_solution(fid, fwd):
start_block(fid, FIFF.FIFFB_MNE)
#
# MNE env
#
start_block(fid, FIFF.FIFFB_MNE_ENV)
write_id(fid, FIFF.FIFF_BLOCK_ID)
data = fwd["info"].get("working_dir", None)
if data is not None:
write_string(fid, FIFF.FIFF_MNE_ENV_WORKING_DIR, data)
data = fwd["info"].get("command_line", None)
if data is not None:
write_string(fid, FIFF.FIFF_MNE_ENV_COMMAND_LINE, data)
end_block(fid, FIFF.FIFFB_MNE_ENV)
#
# Information from the MRI file
#
start_block(fid, FIFF.FIFFB_MNE_PARENT_MRI_FILE)
write_string(fid, FIFF.FIFF_MNE_FILE_NAME, fwd["info"]["mri_file"])
if fwd["info"]["mri_id"] is not None:
write_id(fid, FIFF.FIFF_PARENT_FILE_ID, fwd["info"]["mri_id"])
# store the MRI to HEAD transform in MRI file
write_coord_trans(fid, fwd["info"]["mri_head_t"])
end_block(fid, FIFF.FIFFB_MNE_PARENT_MRI_FILE)
# write measurement info
write_forward_meas_info(fid, fwd["info"])
# invert our original source space transform
src = list()
for s in fwd["src"]:
s = deepcopy(s)
try:
# returns source space to original coordinate frame
# usually MRI
s = transform_surface_to(s, fwd["mri_head_t"]["from"], fwd["mri_head_t"])
except Exception as inst:
raise ValueError(f"Could not transform source space ({inst})")
src.append(s)
#
# Write the source spaces (again)
#
_write_source_spaces_to_fid(fid, src)
n_vert = sum([ss["nuse"] for ss in src])
if fwd["_orig_source_ori"] == FIFF.FIFFV_MNE_FIXED_ORI:
n_col = n_vert
else:
n_col = 3 * n_vert
# Undo transformations
sol = fwd["_orig_sol"].copy()
if fwd["sol_grad"] is not None:
sol_grad = fwd["_orig_sol_grad"].copy()
else:
sol_grad = None
if fwd["surf_ori"] is True:
if fwd["_orig_source_ori"] == FIFF.FIFFV_MNE_FIXED_ORI:
warn(
"The forward solution, which is stored on disk now, is based "
"on a forward solution with fixed orientation. Please note "
"that the transformation to surface-based, fixed orientation "
"cannot be reverted after loading the forward solution with "
"read_forward_solution.",
RuntimeWarning,
)
else:
warn(
"This forward solution is based on a forward solution with "
"free orientation. The original forward solution is stored "
"on disk in X/Y/Z RAS coordinates. Any transformation "
"(surface orientation or fixed orientation) will be "
"reverted. To reapply any transformation to the forward "
"operator please apply convert_forward_solution after "
"reading the forward solution with read_forward_solution.",