forked from mne-tools/mne-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmorph.py
1564 lines (1393 loc) · 57.1 KB
/
morph.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
# Author(s): Tommy Clausner <[email protected]>
# Alexandre Gramfort <[email protected]>
# Eric Larson <[email protected]>
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import copy
import os.path as op
import warnings
import numpy as np
from scipy import sparse
from .fixes import _eye_array, _get_img_fdata
from .morph_map import read_morph_map
from .parallel import parallel_func
from .source_estimate import (
_BaseSourceEstimate,
_BaseSurfaceSourceEstimate,
_BaseVolSourceEstimate,
_get_ico_tris,
)
from .source_space._source_space import SourceSpaces, _ensure_src, _grid_interp
from .surface import _compute_nearest, mesh_edges, read_surface
from .utils import (
BunchConst,
ProgressBar,
_check_fname,
_check_option,
_custom_lru_cache,
_ensure_int,
_import_h5io_funcs,
_import_nibabel,
_validate_type,
check_version,
fill_doc,
get_subjects_dir,
logger,
use_log_level,
verbose,
warn,
)
from .utils import (
warn as warn_,
)
@verbose
def compute_source_morph(
src,
subject_from=None,
subject_to="fsaverage",
subjects_dir=None,
zooms="auto",
niter_affine=(100, 100, 10),
niter_sdr=(5, 5, 3),
spacing=5,
smooth=None,
warn=True,
xhemi=False,
sparse=False,
src_to=None,
precompute=False,
verbose=None,
):
"""Create a SourceMorph from one subject to another.
Method is based on spherical morphing by FreeSurfer for surface
cortical estimates :footcite:`GreveEtAl2013` and
Symmetric Diffeomorphic Registration for volumic data
:footcite:`AvantsEtAl2008`.
Parameters
----------
src : instance of SourceSpaces | instance of SourceEstimate
The SourceSpaces of subject_from (can be a
SourceEstimate if only using a surface source space).
subject_from : str | None
Name of the original subject as named in the SUBJECTS_DIR.
If None (default), then ``src[0]['subject_his_id]'`` will be used.
subject_to : str | None
Name of the subject to which to morph as named in the SUBJECTS_DIR.
Default is ``'fsaverage'``. If None, ``src_to[0]['subject_his_id']``
will be used.
.. versionchanged:: 0.20
Support for subject_to=None.
%(subjects_dir)s
zooms : float | tuple | str | None
The voxel size of volume for each spatial dimension in mm.
If spacing is None, MRIs won't be resliced, and both volumes
must have the same number of spatial dimensions.
Can also be ``'auto'`` to use ``5.`` if ``src_to is None`` and
the zooms from ``src_to`` otherwise.
.. versionchanged:: 0.20
Support for 'auto' mode.
niter_affine : tuple of int
Number of levels (``len(niter_affine)``) and number of
iterations per level - for each successive stage of iterative
refinement - to perform the affine transform.
Default is niter_affine=(100, 100, 10).
niter_sdr : tuple of int
Number of levels (``len(niter_sdr)``) and number of
iterations per level - for each successive stage of iterative
refinement - to perform the Symmetric Diffeomorphic Registration (sdr)
transform. Default is niter_sdr=(5, 5, 3).
spacing : int | list | None
The resolution of the icosahedral mesh (typically 5).
If None, all vertices will be used (potentially filling the
surface). If a list, then values will be morphed to the set of
vertices specified in in ``spacing[0]`` and ``spacing[1]``.
This will be ignored if ``src_to`` is supplied.
.. versionchanged:: 0.21
src_to, if provided, takes precedence.
smooth : int | str | None
Number of iterations for the smoothing of the surface data.
If None, smooth is automatically defined to fill the surface
with non-zero values. Can also be ``'nearest'`` to use the nearest
vertices on the surface.
.. versionchanged:: 0.20
Added support for 'nearest'.
warn : bool
If True, warn if not all vertices were used. The default is warn=True.
xhemi : bool
Morph across hemisphere. Currently only implemented for
``subject_to == subject_from``. See notes below.
The default is xhemi=False.
sparse : bool
Morph as a sparse source estimate. Works only with (Vector)
SourceEstimate. If True the only parameters used are subject_to and
subject_from, and spacing has to be None. Default is sparse=False.
src_to : instance of SourceSpaces | None
The destination source space.
- For surface-based morphing, this is the preferred over ``spacing``
for providing the vertices.
- For volumetric morphing, this should be passed so that 1) the
resultingmorph volume is properly constrained to the brain volume,
and 2) STCs from multiple subjects morphed to the same destination
subject/source space have the vertices.
- For mixed (surface + volume) morphing, this is required.
.. versionadded:: 0.20
precompute : bool
If True (default False), compute the sparse matrix representation of
the volumetric morph (if present). This takes a long time to
compute, but can make morphs faster when thousands of points are used.
See :meth:`mne.SourceMorph.compute_vol_morph_mat` (which can be called
later if desired) for more information.
.. versionadded:: 0.22
%(verbose)s
Returns
-------
morph : instance of SourceMorph
The :class:`mne.SourceMorph` object.
Notes
-----
This function can be used to morph surface data between hemispheres by
setting ``xhemi=True``. The full cross-hemisphere morph matrix maps left
to right and right to left. A matrix for cross-mapping only one hemisphere
can be constructed by specifying the appropriate vertices, for example, to
map the right hemisphere to the left::
vertices_from=[[], vert_rh], vertices_to=[vert_lh, []]
Cross-hemisphere mapping requires appropriate ``sphere.left_right``
morph-maps in the subject's directory. These morph maps are included
with the ``fsaverage_sym`` FreeSurfer subject, and can be created for other
subjects with the ``mris_left_right_register`` FreeSurfer command. The
``fsaverage_sym`` subject is included with FreeSurfer > 5.1 and can be
obtained as described `here
<https://surfer.nmr.mgh.harvard.edu/fswiki/Xhemi>`_. For statistical
comparisons between hemispheres, use of the symmetric ``fsaverage_sym``
model is recommended to minimize bias :footcite:`GreveEtAl2013`.
.. versionadded:: 0.17.0
.. versionadded:: 0.21.0
Support for morphing mixed source estimates.
References
----------
.. footbibliography::
"""
src_data, kind, src_subject = _get_src_data(src)
subject_from = _check_subject_src(subject_from, src_subject, warn_none=True)
del src
_validate_type(src_to, (SourceSpaces, None), "src_to")
_validate_type(subject_to, (str, None), "subject_to")
if src_to is None and subject_to is None:
raise ValueError("subject_to cannot be None when src_to is None")
subject_to = _check_subject_src(subject_to, src_to, "subject_to")
# Params
warn = False if sparse else warn
if kind not in "surface" and xhemi:
raise ValueError(
"Inter-hemispheric morphing can only be used "
"with surface source estimates."
)
if sparse and kind != "surface":
raise ValueError("Only surface source estimates can compute a sparse morph.")
subjects_dir = str(get_subjects_dir(subjects_dir, raise_error=True))
shape = affine = pre_affine = sdr_morph = morph_mat = None
vertices_to_surf, vertices_to_vol = list(), list()
if kind in ("volume", "mixed"):
_check_dep(nibabel="2.1.0", dipy="0.10.1")
nib = _import_nibabel("work with a volume source space")
logger.info("Volume source space(s) present...")
# load moving MRI
mri_subpath = op.join("mri", "brain.mgz")
mri_path_from = op.join(subjects_dir, subject_from, mri_subpath)
logger.info(f' Loading {mri_path_from} as "from" volume')
with warnings.catch_warnings():
mri_from = nib.load(mri_path_from)
# eventually we could let this be some other volume, but for now
# let's KISS and use `brain.mgz`, too
mri_path_to = op.join(subjects_dir, subject_to, mri_subpath)
if not op.isfile(mri_path_to):
raise OSError(f"cannot read file: {mri_path_to}")
logger.info(f' Loading {mri_path_to} as "to" volume')
with warnings.catch_warnings():
mri_to = nib.load(mri_path_to)
# deal with `src_to` subsampling
zooms_src_to = None
if src_to is None:
if kind == "mixed":
raise ValueError(
"src_to must be provided when using a mixed source space"
)
else:
surf_offset = 2 if src_to.kind == "mixed" else 0
# All of our computations are in RAS (like img.affine), so we need
# to get the transformation from RAS to the source space
# subsampling of vox (src), not MRI (FreeSurfer surface RAS) to src
src_ras_t = np.dot(
src_to[-1]["mri_ras_t"]["trans"], src_to[-1]["src_mri_t"]["trans"]
)
src_ras_t[:3] *= 1e3
src_data["to_vox_map"] = (src_to[-1]["shape"], src_ras_t)
vertices_to_vol = [s["vertno"] for s in src_to[surf_offset:]]
zooms_src_to = np.diag(src_to[-1]["src_mri_t"]["trans"])[:3] * 1000
zooms_src_to = tuple(zooms_src_to)
# pre-compute non-linear morph
zooms = _check_zooms(mri_from, zooms, zooms_src_to)
shape, zooms, affine, pre_affine, sdr_morph = _compute_morph_sdr(
mri_from, mri_to, niter_affine, niter_sdr, zooms
)
if kind in ("surface", "mixed"):
logger.info("surface source space present ...")
vertices_from = src_data["vertices_from"]
if sparse:
if spacing is not None:
raise ValueError("spacing must be set to None if sparse=True.")
if xhemi:
raise ValueError("xhemi=True can only be used with sparse=False")
vertices_to_surf, morph_mat = _compute_sparse_morph(
vertices_from, subject_from, subject_to, subjects_dir
)
else:
if src_to is not None:
assert src_to.kind in ("surface", "mixed")
vertices_to_surf = [s["vertno"].copy() for s in src_to[:2]]
else:
vertices_to_surf = grade_to_vertices(
subject_to, spacing, subjects_dir, 1
)
morph_mat = _compute_morph_matrix(
subject_from=subject_from,
subject_to=subject_to,
vertices_from=vertices_from,
vertices_to=vertices_to_surf,
subjects_dir=subjects_dir,
smooth=smooth,
warn=warn,
xhemi=xhemi,
)
n_verts = sum(len(v) for v in vertices_to_surf)
assert morph_mat.shape[0] == n_verts
vertices_to = vertices_to_surf + vertices_to_vol
if src_to is not None:
assert len(vertices_to) == len(src_to)
morph = SourceMorph(
subject_from,
subject_to,
kind,
zooms,
niter_affine,
niter_sdr,
spacing,
smooth,
xhemi,
morph_mat,
vertices_to,
shape,
affine,
pre_affine,
sdr_morph,
src_data,
None,
)
if precompute:
morph.compute_vol_morph_mat()
logger.info("[done]")
return morph
def _compute_sparse_morph(vertices_from, subject_from, subject_to, subjects_dir=None):
"""Get nearest vertices from one subject to another."""
from scipy import sparse
maps = read_morph_map(subject_to, subject_from, subjects_dir)
cnt = 0
vertices = list()
cols = list()
for verts, map_hemi in zip(vertices_from, maps):
vertno_h = _sparse_argmax_nnz_row(map_hemi[verts])
order = np.argsort(vertno_h)
cols.append(cnt + order)
vertices.append(vertno_h[order])
cnt += len(vertno_h)
cols = np.concatenate(cols)
rows = np.arange(len(cols))
data = np.ones(len(cols))
morph_mat = sparse.coo_array(
(data, (rows, cols)), shape=(len(cols), len(cols))
).tocsr()
return vertices, morph_mat
_SOURCE_MORPH_ATTRIBUTES = [ # used in writing
"subject_from",
"subject_to",
"kind",
"zooms",
"niter_affine",
"niter_sdr",
"spacing",
"smooth",
"xhemi",
"morph_mat",
"vertices_to",
"shape",
"affine",
"pre_affine",
"sdr_morph",
"src_data",
"vol_morph_mat",
]
@fill_doc
class SourceMorph:
"""Morph source space data from one subject to another.
.. note::
This class should not be instantiated directly via
``mne.SourceMorph(...)``. Instead, use one of the functions
listed in the See Also section below.
Parameters
----------
subject_from : str | None
Name of the subject from which to morph as named in the SUBJECTS_DIR.
subject_to : str | array | list of array
Name of the subject on which to morph as named in the SUBJECTS_DIR.
The default is 'fsaverage'. If morphing a volume source space,
subject_to can be the path to a MRI volume. Can also be a list of
two arrays if morphing to hemisphere surfaces.
kind : str | None
Kind of source estimate. E.g. ``'volume'`` or ``'surface'``.
zooms : float | tuple
See :func:`mne.compute_source_morph`.
niter_affine : tuple of int
Number of levels (``len(niter_affine)``) and number of
iterations per level - for each successive stage of iterative
refinement - to perform the affine transform.
niter_sdr : tuple of int
Number of levels (``len(niter_sdr)``) and number of
iterations per level - for each successive stage of iterative
refinement - to perform the Symmetric Diffeomorphic Registration (sdr)
transform :footcite:`AvantsEtAl2008`.
spacing : int | list | None
See :func:`mne.compute_source_morph`.
smooth : int | str | None
See :func:`mne.compute_source_morph`.
xhemi : bool
Morph across hemisphere.
morph_mat : scipy.sparse.csr_array
The sparse surface morphing matrix for spherical surface
based morphing :footcite:`GreveEtAl2013`.
vertices_to : list of ndarray
The destination surface vertices.
shape : tuple
The volume MRI shape.
affine : ndarray
The volume MRI affine.
pre_affine : instance of dipy.align.AffineMap
The transformation that is applied before the before ``sdr_morph``.
sdr_morph : instance of dipy.align.DiffeomorphicMap
The class that applies the the symmetric diffeomorphic registration
(SDR) morph.
src_data : dict
Additional source data necessary to perform morphing.
vol_morph_mat : scipy.sparse.csr_array | None
The volumetric morph matrix, if :meth:`compute_vol_morph_mat`
was used.
%(verbose)s
See Also
--------
compute_source_morph
read_source_morph
Notes
-----
.. versionadded:: 0.17
References
----------
.. footbibliography::
"""
@verbose
def __init__(
self,
subject_from,
subject_to,
kind,
zooms,
niter_affine,
niter_sdr,
spacing,
smooth,
xhemi,
morph_mat,
vertices_to,
shape,
affine,
pre_affine,
sdr_morph,
src_data,
vol_morph_mat,
*,
verbose=None,
):
# universal
self.subject_from = subject_from
self.subject_to = subject_to
self.kind = kind
# vol input
self.zooms = zooms
self.niter_affine = niter_affine
self.niter_sdr = niter_sdr
# surf input
self.spacing = spacing
self.smooth = smooth
self.xhemi = xhemi
# surf computed
self.morph_mat = morph_mat
# vol computed
self.shape = shape
self.affine = affine
self.sdr_morph = sdr_morph
self.pre_affine = pre_affine
# used by both
self.src_data = src_data
self.vol_morph_mat = vol_morph_mat
# compute vertices_to here (partly for backward compat and no src
# provided)
if vertices_to is None or len(vertices_to) == 0 and kind == "volume":
assert src_data["to_vox_map"] is None
vertices_to = self._get_vol_vertices_to_nz()
self.vertices_to = vertices_to
@property
def _vol_vertices_from(self):
assert isinstance(self.src_data["inuse"], list)
vertices_from = [np.where(in_)[0] for in_ in self.src_data["inuse"]]
return vertices_from
@property
def _vol_vertices_to(self):
return self.vertices_to[0 if self.kind == "volume" else 2 :]
def _get_vol_vertices_to_nz(self):
logger.info("Computing nonzero vertices after morph ...")
n_vertices = sum(len(v) for v in self._vol_vertices_from)
ones = np.ones((n_vertices, 1))
with use_log_level(False):
return [np.where(self._morph_vols(ones, "", subselect=False))[0]]
@verbose
def apply(
self, stc_from, output="stc", mri_resolution=False, mri_space=None, verbose=None
):
"""Morph source space data.
Parameters
----------
stc_from : VolSourceEstimate | VolVectorSourceEstimate | SourceEstimate | VectorSourceEstimate
The source estimate to morph.
output : str
Can be ``'stc'`` (default) or possibly ``'nifti1'``, or
``'nifti2'`` when working with a volume source space defined on a
regular grid.
mri_resolution : bool | tuple | int | float
If True the image is saved in MRI resolution. Default False.
.. warning: If you have many time points the file produced can be
huge. The default is ``mri_resolution=False``.
mri_space : bool | None
Whether the image to world registration should be in mri space. The
default (None) is mri_space=mri_resolution.
%(verbose)s
Returns
-------
stc_to : VolSourceEstimate | SourceEstimate | VectorSourceEstimate | Nifti1Image | Nifti2Image
The morphed source estimates.
""" # noqa: E501
_validate_type(output, str, "output")
_validate_type(stc_from, _BaseSourceEstimate, "stc_from", "source estimate")
if isinstance(stc_from, _BaseSurfaceSourceEstimate):
allowed_kinds = ("stc",)
extra = "when stc is a surface source estimate"
else:
allowed_kinds = ("stc", "nifti1", "nifti2")
extra = ""
_check_option("output", output, allowed_kinds, extra)
stc = copy.deepcopy(stc_from)
mri_space = mri_resolution if mri_space is None else mri_space
if stc.subject is None:
stc.subject = self.subject_from
if self.subject_from is None:
self.subject_from = stc.subject
if stc.subject != self.subject_from:
raise ValueError(
"stc_from.subject and "
"morph.subject_from "
f"must match. ({stc.subject} != {self.subject_from})"
)
out = _apply_morph_data(self, stc)
if output != "stc": # convert to volume
out = _morphed_stc_as_volume(
self,
out,
mri_resolution=mri_resolution,
mri_space=mri_space,
output=output,
)
return out
@verbose
def compute_vol_morph_mat(self, *, verbose=None):
"""Compute the sparse matrix representation of the volumetric morph.
Parameters
----------
%(verbose)s
Returns
-------
morph : instance of SourceMorph
The instance (modified in-place).
Notes
-----
For a volumetric morph, this will compute the morph for an identity
source volume, i.e., with one source vertex active at a time, and store
the result as a :class:`sparse <scipy.sparse.csr_array>`
morphing matrix. This takes a long time (minutes) to compute initially,
but drastically speeds up :meth:`apply` for STCs, so it can be
beneficial when many time points or many morphs (i.e., greater than
the number of volumetric ``src_from`` vertices) will be performed.
When calling :meth:`save`, this sparse morphing matrix is saved with
the instance, so this only needs to be called once. This function does
nothing if the morph matrix has already been computed, or if there is
no volume morphing necessary.
.. versionadded:: 0.22
"""
if self.affine is None or self.vol_morph_mat is not None:
return
logger.info("Computing sparse volumetric morph matrix (will take some time...)")
self.vol_morph_mat = self._morph_vols(None, "Vertex")
return self
def _morph_vols(self, vols, mesg, subselect=True):
from dipy.align.reslice import reslice
interp = self.src_data["interpolator"].tocsc()[
:, np.concatenate(self._vol_vertices_from)
]
n_vols = interp.shape[1] if vols is None else vols.shape[1]
attrs = ("real", "imag") if np.iscomplexobj(vols) else ("real",)
dtype = np.complex128 if len(attrs) == 2 else np.float64
if vols is None: # sparse -> sparse mode
img_to = (list(), list(), [0]) # data, indices, indptr
assert subselect
else: # dense -> dense mode
img_to = None
if subselect:
vol_verts = np.concatenate(self._vol_vertices_to)
else:
vol_verts = slice(None)
# morph data
from_affine = np.dot(
self.src_data["src_affine_ras"], # mri_ras_t
self.src_data["src_affine_vox"],
) # vox_mri_t
from_affine[:3] *= 1000.0
# equivalent of:
# _resample_from_to(img_real, from_affine,
# (self.pre_affine.codomain_shape,
# (self.pre_affine.codomain_grid2world))
src_shape = self.src_data["src_shape_full"][::-1]
resamp_0 = _grid_interp(
src_shape,
self.pre_affine.codomain_shape,
np.linalg.inv(from_affine) @ self.pre_affine.codomain_grid2world,
)
# reslice to match what was used during the morph
# (brain.mgz and whatever was used to create the source space
# will not necessarily have the same domain/zooms)
# equivalent of:
# pre_affine.transform(img_real)
resamp_1 = _grid_interp(
self.pre_affine.codomain_shape,
self.pre_affine.domain_shape,
np.linalg.inv(self.pre_affine.codomain_grid2world)
@ self.pre_affine.affine
@ self.pre_affine.domain_grid2world,
)
resamp_0_1 = resamp_1 @ resamp_0
resamp_2 = None
for ii in ProgressBar(list(range(n_vols)), mesg=mesg):
for attr in attrs:
# transform from source space to mri_from resolution/space
if vols is None:
img_real = interp[:, [ii]]
else:
img_real = interp @ getattr(vols[:, ii], attr)
_debug_img(img_real, from_affine, "From", src_shape)
img_real = resamp_0_1 @ img_real
if sparse.issparse(img_real):
img_real = img_real.toarray()
img_real = img_real.reshape(self.pre_affine.domain_shape, order="F")
if self.sdr_morph is not None:
img_real = self.sdr_morph.transform(img_real)
_debug_img(img_real, self.affine, "From-reslice-transform")
# subselect the correct cube if src_to is provided
if self.src_data["to_vox_map"] is not None:
affine = self.affine
to_zooms = np.diag(self.src_data["to_vox_map"][1])[:3]
# There might be some sparse equivalent to this but
# not sure...
if not np.allclose(self.zooms, to_zooms, atol=1e-3):
img_real, affine = reslice(
img_real, self.affine, self.zooms, to_zooms
)
_debug_img(img_real, affine, "From-reslice-transform-src")
if resamp_2 is None:
resamp_2 = _grid_interp(
img_real.shape,
self.src_data["to_vox_map"][0],
np.linalg.inv(affine) @ self.src_data["to_vox_map"][1],
)
# Equivalent to:
# _resample_from_to(
# img_real, affine, self.src_data['to_vox_map'])
img_real = resamp_2 @ img_real.ravel(order="F")
_debug_img(
img_real,
self.src_data["to_vox_map"][1],
"From-reslice-transform-src-subselect",
self.src_data["to_vox_map"][0],
)
# This can be used to help debug, but it really should just
# show the brain filling the volume:
# img_want = np.zeros(np.prod(img_real.shape))
# img_want[np.concatenate(self._vol_vertices_to)] = 1.
# img_want = np.reshape(
# img_want, self.src_data['src_shape'][::-1], order='F')
# _debug_img(img_want, self.src_data['to_vox_map'][1],
# 'To mask')
# raise RuntimeError('Check')
# combine real and complex parts
img_real = img_real.ravel(order="F")[vol_verts]
# initialize output
if img_to is None and vols is not None:
img_to = np.zeros((img_real.size, n_vols), dtype=dtype)
if vols is None:
idx = np.where(img_real)[0]
img_to[0].extend(img_real[idx])
img_to[1].extend(idx)
img_to[2].append(img_to[2][-1] + len(idx))
else:
if attr == "real":
img_to[:, ii] = img_to[:, ii] + img_real
else:
img_to[:, ii] = img_to[:, ii] + 1j * img_real
if vols is None:
img_to = sparse.csc_array(img_to, shape=(len(vol_verts), n_vols)).tocsr()
return img_to
def __repr__(self): # noqa: D105
s = f"{self.kind}"
s += f", {self.subject_from} -> {self.subject_to}"
if self.kind == "volume":
s += f", zooms : {self.zooms}"
s += f", niter_affine : {self.niter_affine}"
s += f", niter_sdr : {self.niter_sdr}"
elif self.kind in ("surface", "vector"):
s += f", spacing : {self.spacing}"
s += f", smooth : {self.smooth}"
s += ", xhemi" if self.xhemi else ""
return f"<SourceMorph | {s}>"
@verbose
def save(self, fname, overwrite=False, verbose=None):
"""Save the morph for source estimates to a file.
Parameters
----------
fname : path-like
The path to the file. ``'-morph.h5'`` will be added if fname does
not end with ``'.h5'``.
%(overwrite)s
%(verbose)s
"""
_, write_hdf5 = _import_h5io_funcs()
fname = _check_fname(fname, overwrite=overwrite, must_exist=False)
if fname.suffix != ".h5":
fname = fname.with_name(f"{fname.name}-morph.h5")
out_dict = {k: getattr(self, k) for k in _SOURCE_MORPH_ATTRIBUTES}
for key in ("pre_affine", "sdr_morph"): # classes
if out_dict[key] is not None:
out_dict[key] = out_dict[key].__dict__
write_hdf5(fname, out_dict, overwrite=overwrite)
_slicers = list()
def _debug_img(data, affine, title, shape=None):
# Uncomment these lines for debugging help with volume morph:
#
# import nibabel as nib
# if sparse.issparse(data):
# data = data.toarray()
# data = np.asarray(data)
# if shape is not None:
# data = np.reshape(data, shape, order='F')
# _slicers.append(nib.viewers.OrthoSlicer3D(
# data, affine, axes=None, title=title))
# _slicers[-1].figs[0].suptitle(title, color='r')
return
def _check_zooms(mri_from, zooms, zooms_src_to):
# use voxel size of mri_from
if isinstance(zooms, str) and zooms == "auto":
zooms = zooms_src_to if zooms_src_to is not None else 5.0
if zooms is None:
zooms = mri_from.header.get_zooms()[:3]
zooms = np.atleast_1d(zooms).astype(float)
if zooms.shape == (1,):
zooms = np.repeat(zooms, 3)
if zooms.shape != (3,):
raise ValueError(
"zooms must be None, a singleton, or have shape (3,),"
f" got shape {zooms.shape}"
)
zooms = tuple(zooms)
return zooms
# def _resample_from_to(img, affine, to_vox_map):
# # Wrap to dipy for speed, equivalent to:
# # from nibabel.processing import resample_from_to
# # from nibabel.spatialimages import SpatialImage
# # return _get_img_fdata(
# # resample_from_to(SpatialImage(img, affine), to_vox_map, order=1))
# import dipy.align.imaffine
#
# return dipy.align.imaffine.AffineMap(
# None, to_vox_map[0], to_vox_map[1], img.shape, affine
# ).transform(img, resample_only=True)
###############################################################################
# I/O
def _check_subject_src(
subject, src, name="subject_from", src_name="src", *, warn_none=False
):
if isinstance(src, str):
subject_check = src
elif src is None: # assume it's correct although dangerous but unlikely
subject_check = subject
else:
subject_check = src._subject
warn_none = True
if subject_check is None and warn_none:
warn(
"The source space does not contain the subject name, we "
"recommend regenerating the source space (and forward / "
"inverse if applicable) for better code reliability"
)
if subject is None:
subject = subject_check
elif subject_check is not None and subject != subject_check:
raise ValueError(
f"{name} does not match {src_name} subject ({subject} != {subject_check})"
)
if subject is None:
raise ValueError(
f"{name} could not be inferred from {src_name}, it must be specified"
)
return subject
def read_source_morph(fname):
"""Load the morph for source estimates from a file.
Parameters
----------
fname : path-like
Path to the file containing the morph source estimates.
Returns
-------
source_morph : instance of SourceMorph
The loaded morph.
"""
read_hdf5, _ = _import_h5io_funcs()
vals = read_hdf5(fname)
if vals["pre_affine"] is not None: # reconstruct
from dipy.align.imaffine import AffineMap
affine = vals["pre_affine"]
vals["pre_affine"] = AffineMap(None)
vals["pre_affine"].__dict__ = affine
if vals["sdr_morph"] is not None:
from dipy.align.imwarp import DiffeomorphicMap
morph = vals["sdr_morph"]
vals["sdr_morph"] = DiffeomorphicMap(None, [])
vals["sdr_morph"].__dict__ = morph
# Backward compat with when it used to be a list
if isinstance(vals["vertices_to"], np.ndarray):
vals["vertices_to"] = [vals["vertices_to"]]
# Backward compat with when it used to be a single array
if isinstance(vals["src_data"].get("inuse", None), np.ndarray):
vals["src_data"]["inuse"] = [vals["src_data"]["inuse"]]
# added with compute_vol_morph_mat in 0.22:
vals["vol_morph_mat"] = vals.get("vol_morph_mat", None)
return SourceMorph(**vals)
###############################################################################
# Helper functions for SourceMorph methods
def _check_dep(nibabel="2.1.0", dipy="0.10.1"):
"""Check dependencies."""
for lib, ver in zip(["nibabel", "dipy"], [nibabel, dipy]):
passed = True if not ver else check_version(lib, ver)
if not passed:
raise ImportError(
f"{lib} {ver} or higher must be correctly "
"installed and accessible from Python"
)
def _morphed_stc_as_volume(morph, stc, mri_resolution, mri_space, output):
"""Return volume source space as Nifti1Image and/or save to disk."""
assert isinstance(stc, _BaseVolSourceEstimate) # should be guaranteed
if stc._data_ndim == 3:
stc = stc.magnitude()
_check_dep(nibabel="2.1.0", dipy=False)
NiftiImage, NiftiHeader = _triage_output(output)
# if MRI resolution is set manually as a single value, convert to tuple
if isinstance(mri_resolution, (int, float)):
# use iso voxel size
new_zooms = (float(mri_resolution),) * 3
elif isinstance(mri_resolution, tuple):
new_zooms = mri_resolution
# if full MRI resolution, compute zooms from shape and MRI zooms
if isinstance(mri_resolution, bool):
new_zooms = _get_zooms_orig(morph) if mri_resolution else None
# create header
hdr = NiftiHeader()
hdr.set_xyzt_units("mm", "msec")
hdr["pixdim"][4] = 1e3 * stc.tstep
# setup empty volume
if morph.src_data["to_vox_map"] is not None:
shape = morph.src_data["to_vox_map"][0]
affine = morph.src_data["to_vox_map"][1]
else:
shape = morph.shape
affine = morph.affine
assert stc.data.ndim == 2
n_times = stc.data.shape[1]
img = np.zeros((np.prod(shape), n_times))
img[stc.vertices[0], :] = stc.data
img = img.reshape(shape + (n_times,), order="F") # match order='F' above
del shape
# make nifti from data
with warnings.catch_warnings(): # nibabel<->numpy warning
img = NiftiImage(img, affine, header=hdr)
# reslice in case of manually defined voxel size
zooms = morph.zooms[:3]
if new_zooms is not None:
from dipy.align.reslice import reslice
new_zooms = new_zooms[:3]
img, affine = reslice(
_get_img_fdata(img),
img.affine, # MRI to world registration
zooms, # old voxel size in mm
new_zooms,
) # new voxel size in mm
with warnings.catch_warnings(): # nibabel<->numpy warning
img = NiftiImage(img, affine)
zooms = new_zooms
# set zooms in header
img.header.set_zooms(tuple(zooms) + (1,))
return img
def _get_src_data(src, mri_resolution=True):
# copy data to avoid conflicts
_validate_type(
src,
(_BaseSurfaceSourceEstimate, "path-like", SourceSpaces),
"src",
"source space or surface source estimate",
)
if isinstance(src, _BaseSurfaceSourceEstimate):
src_t = [dict(vertno=src.vertices[0]), dict(vertno=src.vertices[1])]
src_kind = "surface"
src_subject = src.subject
else:
src_t = _ensure_src(src).copy()
src_kind = src_t.kind
src_subject = src_t._subject
del src
_check_option("src kind", src_kind, ("surface", "volume", "mixed"))
# extract all relevant data for volume operations
src_data = dict()
if src_kind in ("volume", "mixed"):
use_src = src_t[-1]
shape = use_src["shape"]
start = 0 if src_kind == "volume" else 2
for si, s in enumerate(src_t[start:], start):
if s.get("interpolator", None) is None:
if mri_resolution:
raise RuntimeError(
f"MRI interpolator not present in src[{si}], "
"cannot use mri_resolution=True"
)
interpolator = None