forked from mne-tools/mne-python
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path_coreg.py
More file actions
2093 lines (1928 loc) · 76.6 KB
/
_coreg.py
File metadata and controls
2093 lines (1928 loc) · 76.6 KB
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.
import inspect
import os
import os.path as op
import platform
import queue
import re
import threading
import time
from contextlib import contextmanager
from functools import partial
from pathlib import Path
import numpy as np
from traitlets import Bool, Float, HasTraits, Instance, Unicode, observe
from .._fiff.constants import FIFF
from .._fiff.meas_info import _empty_info, read_fiducials, read_info, write_fiducials
from .._fiff.open import dir_tree_find, fiff_open
from .._fiff.pick import pick_types
from ..bem import make_bem_solution, write_bem_solution
from ..channels import read_dig_fif
from ..coreg import (
Coregistration,
_find_head_bem,
_is_mri_subject,
_map_fid_name_to_idx,
_mri_subject_has_bem,
bem_fname,
fid_fname,
scale_mri,
)
from ..defaults import DEFAULTS
from ..io._read_raw import _get_supported, read_raw
from ..surface import _CheckInside, _DistanceQuery
from ..transforms import (
Transform,
_ensure_trans,
_get_trans,
_get_transforms_to_coord_frame,
read_trans,
rotation_angles,
write_trans,
)
from ..utils import (
_check_fname,
_validate_type,
check_fname,
fill_doc,
get_subjects_dir,
logger,
verbose,
)
from ..viz._3d import (
_plot_head_fiducials,
_plot_head_shape_points,
_plot_head_surface,
_plot_helmet,
_plot_hpi_coils,
_plot_mri_fiducials,
_plot_sensors_3d,
)
from ..viz.backends._utils import _qt_app_exec, _qt_safe_window
from ..viz.utils import safe_event
class _WorkerData:
def __init__(self, name, params=None):
self._name = name
self._params = params
def _get_subjects(sdir):
# XXX: would be nice to move this function to util
is_dir = sdir and op.isdir(sdir)
if is_dir:
dir_content = os.listdir(sdir)
subjects = [s for s in dir_content if _is_mri_subject(s, sdir)]
if len(subjects) == 0:
subjects.append("")
else:
subjects = [""]
return sorted(subjects)
@fill_doc
class CoregistrationUI(HasTraits):
"""Class for coregistration assisted by graphical interface.
Parameters
----------
info_file : None | path-like
The FIFF file with digitizer data for coregistration.
%(subject)s
%(subjects_dir)s
%(fiducials)s
head_resolution : bool
If ``True``, use a high-resolution head surface. Defaults to ``False``.
head_opacity : float
The opacity of the head surface. Defaults to ``0.8``.
hpi_coils : bool
If ``True``, display the HPI coils. Defaults to ``True``.
head_shape_points : bool
If ``True``, display the head shape points. Defaults to ``True``.
eeg_channels : bool
If ``True``, display the EEG channels. Defaults to ``True``.
meg_channels : bool
If ``True``, display the MEG channels. Defaults to ``False``.
fnirs_channels : bool
If ``True``, display the fNIRS channels. Defaults to ``True``.
orient_glyphs : bool
If ``True``, orient the sensors towards the head surface. Default to ``False``.
scale_by_distance : bool
If ``True``, scale the sensors based on their distance to the head surface.
Defaults to ``True``.
mark_inside : bool
If ``True``, mark the head shape points that are inside the head surface
with a different color. Defaults to ``True``.
sensor_opacity : float
The opacity of the sensors between ``0`` and ``1``. Defaults to ``1.``.
trans : path-like | Transform
The Head<->MRI transform or the path to its FIF file (``"-trans.fif"``).
size : tuple
The dimensions (width, height) of the rendering view. The default is
``(800, 600)``.
bgcolor : tuple of float | str
The background color as a tuple (red, green, blue) of float
values between ``0`` and ``1`` or a valid color name (i.e. ``'white'``
or ``'w'``). Defaults to ``'grey'``.
show : bool
Display the window as soon as it is ready. Defaults to ``True``.
block : bool
Whether to halt program execution until the GUI has been closed
(``True``) or not (``False``, default).
%(fullscreen)s
The default is ``False``.
.. versionadded:: 1.1
%(interaction_scene)s
Defaults to ``'terrain'``.
.. versionadded:: 1.0
%(verbose)s
Attributes
----------
coreg : mne.coreg.Coregistration
The coregistration instance used by the graphical interface.
"""
_subject = Unicode()
_subjects_dir = Unicode()
_lock_fids = Bool()
_current_fiducial = Unicode()
_info_file = Instance(Path, default_value=Path("."))
_orient_glyphs = Bool()
_scale_by_distance = Bool()
_mark_inside = Bool()
_hpi_coils = Bool()
_head_shape_points = Bool()
_eeg_channels = Bool()
_meg_channels = Bool()
_fnirs_channels = Bool()
_head_resolution = Bool()
_head_opacity = Float()
_helmet = Bool()
_grow_hair = Float()
_subject_to = Unicode()
_scale_mode = Unicode()
_icp_fid_match = Unicode()
@_qt_safe_window(
splash="_renderer.figure.splash", window="_renderer.figure.plotter"
)
@verbose
def __init__(
self,
info_file,
*,
subject=None,
subjects_dir=None,
fiducials="auto",
head_resolution=None,
head_opacity=None,
hpi_coils=None,
head_shape_points=None,
eeg_channels=None,
meg_channels=None,
fnirs_channels=None,
orient_glyphs=None,
scale_by_distance=None,
mark_inside=None,
sensor_opacity=None,
trans=None,
size=None,
bgcolor=None,
show=True,
block=False,
fullscreen=False,
interaction="terrain",
verbose=None,
):
from ..viz.backends.renderer import _get_renderer
def _get_default(var, val):
return var if var is not None else val
self._actors = dict()
self._surfaces = dict()
self._widgets = dict()
self._verbose = verbose
self._plot_locked = False
self._params_locked = False
self._refresh_rate_ms = max(int(round(1000.0 / 60.0)), 1)
self._redraws_pending = set()
self._parameter_mutex = threading.Lock()
self._redraw_mutex = threading.Lock()
self._job_queue = queue.Queue()
self._parameter_queue = queue.Queue()
self._head_geo = None
self._check_inside = None
self._nearest = None
self._coord_frame = "mri"
self._mouse_no_mvt = -1
self._to_cf_t = None
self._omit_hsp_distance = 0.0
self._fiducials_file = None
self._trans_modified = False
self._mri_fids_modified = False
self._mri_scale_modified = False
self._accept_close_event = True
self._fid_colors = tuple(
DEFAULTS["coreg"][f"{key}_color"] for key in ("lpa", "nasion", "rpa")
)
self._defaults = dict(
size=_get_default(size, (800, 600)),
bgcolor=_get_default(bgcolor, "grey"),
orient_glyphs=_get_default(orient_glyphs, True),
scale_by_distance=_get_default(scale_by_distance, True),
mark_inside=_get_default(mark_inside, True),
hpi_coils=_get_default(hpi_coils, True),
head_shape_points=_get_default(head_shape_points, True),
eeg_channels=_get_default(eeg_channels, True),
meg_channels=_get_default(meg_channels, False),
fnirs_channels=_get_default(fnirs_channels, True),
head_resolution=_get_default(head_resolution, True),
head_opacity=_get_default(head_opacity, 0.8),
helmet=False,
sensor_opacity=_get_default(sensor_opacity, 1.0),
fiducials=("LPA", "Nasion", "RPA"),
fiducial="LPA",
lock_fids=True,
grow_hair=0.0,
subject_to="",
scale_modes=["None", "uniform", "3-axis"],
scale_mode="None",
icp_fid_matches=("nearest", "matched"),
icp_fid_match="matched",
icp_n_iterations=20,
omit_hsp_distance=10.0,
lock_head_opacity=self._head_opacity < 1.0,
weights=dict(
lpa=1.0,
nasion=10.0,
rpa=1.0,
hsp=1.0,
eeg=1.0,
hpi=1.0,
),
)
# process requirements
info = None
subjects_dir = str(
get_subjects_dir(subjects_dir=subjects_dir, raise_error=True)
)
subject = _get_default(subject, _get_subjects(subjects_dir)[0])
# setup the window
splash = "Initializing coregistration GUI..." if show else False
self._renderer = _get_renderer(
size=self._defaults["size"],
bgcolor=self._defaults["bgcolor"],
splash=splash,
fullscreen=fullscreen,
)
self._renderer._window_close_connect(self._clean)
self._renderer._window_close_connect(self._close_callback, after=False)
self._renderer.set_interaction(interaction)
# coregistration model setup
self._picking_targets = list()
self._immediate_redraw = self._renderer._kind != "qt"
self._info = info
self._fiducials = fiducials
self.coreg = Coregistration(
info=self._info,
subject=subject,
subjects_dir=subjects_dir,
fiducials=fiducials,
on_defects="ignore", # safe due to interactive visual inspection
)
fid_accurate = self.coreg._fid_accurate
for fid in self._defaults["weights"].keys():
setattr(self, f"_{fid}_weight", self._defaults["weights"][fid])
# set main traits
self._set_head_opacity(self._defaults["head_opacity"])
self._old_head_opacity = self._head_opacity
self._set_subjects_dir(subjects_dir)
self._set_subject(subject)
self._set_info_file(info_file)
self._set_orient_glyphs(self._defaults["orient_glyphs"])
self._set_scale_by_distance(self._defaults["scale_by_distance"])
self._set_mark_inside(self._defaults["mark_inside"])
self._set_hpi_coils(self._defaults["hpi_coils"])
self._set_head_shape_points(self._defaults["head_shape_points"])
self._set_eeg_channels(self._defaults["eeg_channels"])
self._set_meg_channels(self._defaults["meg_channels"])
self._set_fnirs_channels(self._defaults["fnirs_channels"])
self._set_head_resolution(self._defaults["head_resolution"])
self._set_helmet(self._defaults["helmet"])
self._set_grow_hair(self._defaults["grow_hair"])
self._set_omit_hsp_distance(self._defaults["omit_hsp_distance"])
self._set_icp_n_iterations(self._defaults["icp_n_iterations"])
self._set_icp_fid_match(self._defaults["icp_fid_match"])
# configure UI
self._reset_fitting_parameters()
self._configure_dialogs()
self._configure_status_bar()
self._configure_dock()
self._configure_picking()
self._configure_legend()
# once the docks are initialized
self._set_current_fiducial(self._defaults["fiducial"])
self._set_scale_mode(self._defaults["scale_mode"])
self._set_subject_to(self._defaults["subject_to"])
if trans is not None:
self._load_trans(trans)
self._redraw() # we need the elements to be present now
if fid_accurate:
assert self.coreg._fid_filename is not None
# _set_fiducials_file() calls _update_fiducials_label()
# internally
self._set_fiducials_file(self.coreg._fid_filename)
else:
self._set_head_resolution("high")
self._forward_widget_command("high_res_head", "set_value", True)
self._set_lock_fids(True) # hack to make the dig disappear
self._update_fiducials_label()
self._update_fiducials()
self._set_lock_fids(fid_accurate)
# configure worker
self._configure_worker()
# must be done last
if show:
self._renderer.show()
# update the view once shown
views = {
True: dict(azimuth=90, elevation=90), # front
False: dict(azimuth=180, elevation=90),
} # left
self._renderer.set_camera(distance="auto", **views[self._lock_fids])
self._redraw()
# XXX: internal plotter/renderer should not be exposed
if not self._immediate_redraw:
self._renderer.plotter.add_callback(self._redraw, self._refresh_rate_ms)
self._renderer.plotter.show_axes()
# initialization does not count as modification by the user
self._trans_modified = False
self._mri_fids_modified = False
self._mri_scale_modified = False
if block and self._renderer._kind != "notebook":
_qt_app_exec(self._renderer.figure.store["app"])
def _set_subjects_dir(self, subjects_dir):
if subjects_dir is None or not subjects_dir:
return
try:
subjects_dir = str(
_check_fname(
subjects_dir,
overwrite="read",
must_exist=True,
need_dir=True,
)
)
subjects = _get_subjects(subjects_dir)
low_res_path = _find_head_bem(subjects[0], subjects_dir, high_res=False)
high_res_path = _find_head_bem(subjects[0], subjects_dir, high_res=True)
valid = low_res_path is not None or high_res_path is not None
except Exception:
valid = False
if valid:
style = dict(border="initial")
self._subjects_dir = subjects_dir
else:
style = dict(border="2px solid #ff0000")
self._forward_widget_command("subjects_dir_field", "set_style", style)
def _set_subject(self, subject):
self._subject = subject
def _set_lock_fids(self, state):
self._lock_fids = bool(state)
def _set_fiducials_file(self, fname):
if fname is None:
fids = "auto"
else:
fname = str(
_check_fname(
fname,
overwrite="read",
must_exist=True,
need_dir=False,
)
)
fids, _ = read_fiducials(fname)
self._fiducials_file = fname
self.coreg._setup_fiducials(fids)
self._update_distance_estimation()
self._update_fiducials_label()
self._update_fiducials()
self._reset(keep_trans=True)
if fname is None:
self._set_lock_fids(False)
self._forward_widget_command("reload_mri_fids", "set_enabled", False)
else:
self._set_lock_fids(True)
self._forward_widget_command("reload_mri_fids", "set_enabled", True)
self._display_message(f"Loading MRI fiducials from {fname}... Done!")
def _set_current_fiducial(self, fid):
self._current_fiducial = fid.lower()
def _set_info_file(self, fname):
if fname is None:
return
# info file can be anything supported by read_raw
supported = _get_supported()
try:
check_fname(
fname,
"info",
tuple(supported),
endings_err=tuple(supported),
)
fname = Path(fname)
# ctf ds `files` are actually directories
if fname.suffix == ".ds":
info_file = _check_fname(
fname, overwrite="read", must_exist=True, need_dir=True
)
else:
info_file = _check_fname(
fname, overwrite="read", must_exist=True, need_dir=False
)
valid = True
except OSError:
valid = False
if valid:
style = dict(border="initial")
self._info_file = info_file
else:
style = dict(border="2px solid #ff0000")
self._forward_widget_command("info_file_field", "set_style", style)
def _set_omit_hsp_distance(self, distance):
self._omit_hsp_distance = distance
def _set_orient_glyphs(self, state):
self._orient_glyphs = bool(state)
def _set_scale_by_distance(self, state):
self._scale_by_distance = bool(state)
def _set_mark_inside(self, state):
self._mark_inside = bool(state)
def _set_hpi_coils(self, state):
self._hpi_coils = bool(state)
def _set_head_shape_points(self, state):
self._head_shape_points = bool(state)
def _set_eeg_channels(self, state):
self._eeg_channels = bool(state)
def _set_meg_channels(self, state):
self._meg_channels = bool(state)
def _set_fnirs_channels(self, state):
self._fnirs_channels = bool(state)
def _set_head_resolution(self, state):
self._head_resolution = bool(state)
def _set_head_opacity(self, value):
self._head_opacity = value
def _set_helmet(self, state):
self._helmet = bool(state)
def _set_grow_hair(self, value):
self._grow_hair = value
def _set_subject_to(self, value):
self._subject_to = value
self._forward_widget_command("save_subject", "set_enabled", len(value) > 0)
if self._check_subject_exists():
style = dict(border="2px solid #ff0000")
else:
style = dict(border="initial")
self._forward_widget_command("subject_to", "set_style", style)
def _set_scale_mode(self, mode):
self._scale_mode = mode
def _set_fiducial(self, value, coord):
self._mri_fids_modified = True
fid = self._current_fiducial
fid_idx = _map_fid_name_to_idx(name=fid)
coords = ["X", "Y", "Z"]
coord_idx = coords.index(coord)
self.coreg.fiducials.dig[fid_idx]["r"][coord_idx] = value / 1e3
self._update_plot("mri_fids")
def _set_parameter(self, value, mode_name, coord, plot_locked=False):
if mode_name == "scale":
self._mri_scale_modified = True
else:
self._trans_modified = True
if self._params_locked:
return
if mode_name == "scale" and self._scale_mode == "uniform":
with self._lock(params=True):
self._forward_widget_command(["sY", "sZ"], "set_value", value)
with self._parameter_mutex:
self._set_parameter_safe(value, mode_name, coord)
if not plot_locked:
self._update_plot("sensors")
def _set_parameter_safe(self, value, mode_name, coord):
params = dict(
rotation=self.coreg._rotation,
translation=self.coreg._translation,
scale=self.coreg._scale,
)
idx = ["X", "Y", "Z"].index(coord)
if mode_name == "rotation":
params[mode_name][idx] = np.deg2rad(value)
elif mode_name == "translation":
params[mode_name][idx] = value / 1e3
else:
assert mode_name == "scale"
if self._scale_mode == "uniform":
params[mode_name][:] = value / 1e2
else:
params[mode_name][idx] = value / 1e2
self._update_plot("head")
self.coreg._update_params(
rot=params["rotation"],
tra=params["translation"],
sca=params["scale"],
)
def _set_icp_n_iterations(self, n_iterations):
self._icp_n_iterations = n_iterations
def _set_icp_fid_match(self, method):
self._icp_fid_match = method
def _set_point_weight(self, weight, point):
funcs = {
"hpi": "_set_hpi_coils",
"hsp": "_set_head_shape_points",
"eeg": "_set_eeg_channels",
"meg": "_set_meg_channels",
"fnirs": "_set_fnirs_channels",
}
if point in funcs.keys():
getattr(self, funcs[point])(weight > 0)
setattr(self, f"_{point}_weight", weight)
setattr(self.coreg, f"_{point}_weight", weight)
self._update_distance_estimation()
@observe("_subjects_dir")
def _subjects_dir_changed(self, change=None):
# XXX: add coreg.set_subjects_dir
self.coreg._subjects_dir = self._subjects_dir
subjects = _get_subjects(self._subjects_dir)
if self._subject not in subjects: # Just pick the first available one
self._subject = subjects[0]
self._reset()
@observe("_subject")
def _subject_changed(self, change=None):
# XXX: add coreg.set_subject()
self.coreg._subject = self._subject
self.coreg._setup_bem()
self.coreg._setup_fiducials(self._fiducials)
self._reset()
default_fid_fname = fid_fname.format(
subjects_dir=self._subjects_dir, subject=self._subject
)
if Path(default_fid_fname).exists():
fname = default_fid_fname
else:
fname = None
self._set_fiducials_file(fname)
self._reset_fiducials()
@observe("_lock_fids")
def _lock_fids_changed(self, change=None):
locked_widgets = [
# MRI fiducials
"save_mri_fids",
# View options
"helmet",
"meg",
"head_opacity",
"high_res_head",
# Digitization source
"info_file",
"grow_hair",
"omit_distance",
"omit",
"reset_omit",
# Scaling
"scaling_mode",
"sX",
"sY",
"sZ",
# Transformation
"tX",
"tY",
"tZ",
"rX",
"rY",
"rZ",
# Fitting buttons
"fit_fiducials",
"fit_icp",
# Transformation I/O
"save_trans",
"load_trans",
"reset_trans",
# ICP
"icp_n_iterations",
"icp_fid_match",
"reset_fitting_options",
# Weights
"hsp_weight",
"eeg_weight",
"hpi_weight",
"lpa_weight",
"nasion_weight",
"rpa_weight",
]
fits_widgets = ["fits_fiducials", "fits_icp"]
fid_widgets = ["fid_X", "fid_Y", "fid_Z", "fids_file", "fids"]
if self._lock_fids:
self._forward_widget_command(locked_widgets, "set_enabled", True)
self._forward_widget_command(
"head_opacity", "set_value", self._old_head_opacity
)
self._scale_mode_changed()
self._display_message()
self._update_distance_estimation()
else:
self._old_head_opacity = self._head_opacity
self._forward_widget_command("head_opacity", "set_value", 1.0)
self._forward_widget_command(locked_widgets, "set_enabled", False)
self._forward_widget_command(fits_widgets, "set_enabled", False)
self._display_message(
f"Placing MRI fiducials - {self._current_fiducial.upper()}"
)
self._set_sensors_visibility(self._lock_fids)
self._forward_widget_command("lock_fids", "set_value", self._lock_fids)
self._forward_widget_command(fid_widgets, "set_enabled", not self._lock_fids)
@observe("_current_fiducial")
def _current_fiducial_changed(self, change=None):
self._update_fiducials()
self._follow_fiducial_view()
if not self._lock_fids:
self._display_message(
f"Placing MRI fiducials - {self._current_fiducial.upper()}"
)
@observe("_info_file")
def _info_file_changed(self, change=None):
if not self._info_file:
return
elif self._info_file.name.endswith((".fif", ".fif.gz")):
fid, tree, _ = fiff_open(self._info_file)
fid.close()
if len(dir_tree_find(tree, FIFF.FIFFB_MEAS_INFO)) > 0:
self._info = read_info(self._info_file, verbose=False)
elif len(dir_tree_find(tree, FIFF.FIFFB_ISOTRAK)) > 0:
self._info = _empty_info(1)
self._info["dig"] = read_dig_fif(fname=self._info_file).dig
self._info._unlocked = False
else:
self._info = read_raw(self._info_file).info
# XXX: add coreg.set_info()
self.coreg._info = self._info
self.coreg._setup_digs()
self._reset()
@observe("_orient_glyphs")
def _orient_glyphs_changed(self, change=None):
self._update_plot(["hpi", "hsp", "sensors"])
@observe("_scale_by_distance")
def _scale_by_distance_changed(self, change=None):
self._update_plot(["hpi", "hsp", "sensors"])
@observe("_mark_inside")
def _mark_inside_changed(self, change=None):
self._update_plot("hsp")
@observe("_hpi_coils")
def _hpi_coils_changed(self, change=None):
self._update_plot("hpi")
@observe("_head_shape_points")
def _head_shape_point_changed(self, change=None):
self._update_plot("hsp")
@observe("_eeg_channels")
def _eeg_channels_changed(self, change=None):
self._update_plot("sensors")
@observe("_meg_channels")
def _meg_channels_changed(self, change=None):
self._update_plot("sensors")
@observe("_fnirs_channels")
def _fnirs_channels_changed(self, change=None):
self._update_plot("sensors")
@observe("_head_resolution")
def _head_resolution_changed(self, change=None):
self._update_plot(["head", "hsp"])
@observe("_head_opacity")
def _head_opacity_changed(self, change=None):
if "head" in self._actors:
self._actors["head"].GetProperty().SetOpacity(self._head_opacity)
self._renderer._update()
@observe("_helmet")
def _helmet_changed(self, change=None):
self._update_plot("helmet")
@observe("_grow_hair")
def _grow_hair_changed(self, change=None):
self.coreg.set_grow_hair(self._grow_hair)
self._update_plot("head")
self._update_plot("hsp") # inside/outside could change
@observe("_scale_mode")
def _scale_mode_changed(self, change=None):
locked_widgets = ["sX", "sY", "sZ", "fits_icp", "subject_to"]
mode = None if self._scale_mode == "None" else self._scale_mode
self.coreg.set_scale_mode(mode)
if self._lock_fids:
self._forward_widget_command(
locked_widgets, "set_enabled", mode is not None
)
self._forward_widget_command(
"fits_fiducials", "set_enabled", mode not in (None, "3-axis")
)
if self._scale_mode == "uniform":
self._forward_widget_command(["sY", "sZ"], "set_enabled", False)
@observe("_icp_fid_match")
def _icp_fid_match_changed(self, change=None):
self.coreg.set_fid_match(self._icp_fid_match)
def _run_worker(self, queue, jobs):
while True:
data = queue.get()
func = jobs[data._name]
if data._params is not None:
func(**data._params)
else:
func()
queue.task_done()
def _configure_dialogs(self):
from ..viz.backends.renderer import MNE_3D_BACKEND_TESTING
for name, buttons in zip(
["overwrite_subject", "overwrite_subject_exit"],
[["Yes", "No"], ["Yes", "Discard", "Cancel"]],
):
self._widgets[name] = self._renderer._dialog_create(
title="CoregistrationUI",
text="The name of the output subject used to "
"save the scaled anatomy already exists.",
info_text="Do you want to overwrite?",
callback=self._overwrite_subject_callback,
buttons=buttons,
modal=not MNE_3D_BACKEND_TESTING,
)
def _configure_worker(self):
work_plan = {
"_job_queue": dict(save_subject=self._save_subject),
"_parameter_queue": dict(set_parameter=self._set_parameter),
}
for queue_name, jobs in work_plan.items():
t = threading.Thread(
target=partial(
self._run_worker,
queue=getattr(self, queue_name),
jobs=jobs,
)
)
t.daemon = True
t.start()
def _configure_picking(self):
self._renderer._update_picking_callback(
self._on_mouse_move,
self._on_button_press,
self._on_button_release,
self._on_pick,
)
def _configure_legend(self):
colors = [
np.array(DEFAULTS["coreg"][f"{fid.lower()}_color"]).astype(float)
for fid in self._defaults["fiducials"]
]
labels = list(zip(self._defaults["fiducials"], colors))
mri_fids_legend_actor = self._renderer.legend(labels=labels)
self._update_actor("mri_fids_legend", mri_fids_legend_actor)
@safe_event
@verbose
def _redraw(self, *, verbose=None):
if not self._redraws_pending:
return
draw_map = dict(
head=self._add_head_surface,
mri_fids=self._add_mri_fiducials,
hsp=self._add_head_shape_points,
hpi=self._add_hpi_coils,
sensors=self._add_channels,
head_fids=self._add_head_fiducials,
helmet=self._add_helmet,
)
with self._redraw_mutex:
# We need at least "head" before "hsp", because the grow_hair param
# for head sets the rr that are used for inside/outside hsp
redraws_ordered = sorted(
self._redraws_pending, key=lambda key: list(draw_map).index(key)
)
logger.debug(f"Redrawing {redraws_ordered}")
for ki, key in enumerate(redraws_ordered):
logger.debug(f"{ki}. Drawing {repr(key)}")
draw_map[key]()
self._redraws_pending.clear()
self._renderer._update()
# necessary for MacOS
if platform.system() == "Darwin":
self._renderer._process_events()
def _on_mouse_move(self, vtk_picker, event):
if self._mouse_no_mvt:
self._mouse_no_mvt -= 1
def _on_button_press(self, vtk_picker, event):
self._mouse_no_mvt = 2
def _on_button_release(self, vtk_picker, event):
if self._mouse_no_mvt > 0:
x, y = vtk_picker.GetEventPosition()
# XXX: internal plotter/renderer should not be exposed
picker = self._renderer._picker
picked_renderer = self._renderer.figure.plotter.renderer
# trigger the pick
picker.Pick(x, y, 0, picked_renderer)
self._mouse_no_mvt = 0
def _on_pick(self, vtk_picker, event):
if self._lock_fids:
return
# XXX: taken from Brain, can be refactored
cell_id = vtk_picker.GetCellId()
mesh = vtk_picker.GetDataSet()
if mesh is None or cell_id == -1 or not self._mouse_no_mvt:
return
if not any(mesh is target for target in self._picking_targets):
return
pos = np.array(vtk_picker.GetPickPosition())
vtk_cell = mesh.GetCell(cell_id)
cell = [
vtk_cell.GetPointId(point_id)
for point_id in range(vtk_cell.GetNumberOfPoints())
]
vertices = mesh.points[cell]
idx = np.argmin(abs(vertices - pos), axis=0)
vertex_id = cell[idx[0]]
fiducials = [s.lower() for s in self._defaults["fiducials"]]
idx = fiducials.index(self._current_fiducial.lower())
# XXX: add coreg.set_fids
self.coreg._fid_points[idx] = self._surfaces["head"].points[vertex_id]
self.coreg._reset_fiducials()
self._update_fiducials()
self._update_plot("mri_fids")
def _reset_fitting_parameters(self):
self._forward_widget_command(
"icp_n_iterations", "set_value", self._defaults["icp_n_iterations"]
)
self._forward_widget_command(
"icp_fid_match", "set_value", self._defaults["icp_fid_match"]
)
weights_widgets = [f"{w}_weight" for w in self._defaults["weights"].keys()]
self._forward_widget_command(
weights_widgets, "set_value", list(self._defaults["weights"].values())
)
def _reset_fiducials(self):
self._set_current_fiducial(self._defaults["fiducial"])
def _omit_hsp(self):
self.coreg.omit_head_shape_points(self._omit_hsp_distance / 1e3)
n_omitted = np.sum(~self.coreg._extra_points_filter)
n_remaining = len(self.coreg._dig_dict["hsp"]) - n_omitted
self._update_plot("hsp")
self._update_distance_estimation()
self._display_message(
f"{n_omitted} head shape points omitted, {n_remaining} remaining."
)
def _reset_omit_hsp_filter(self):
self.coreg._extra_points_filter = None
self.coreg._update_params(force_update=True)
self._update_plot("hsp")
self._update_distance_estimation()
n_total = len(self.coreg._dig_dict["hsp"])
self._display_message(
f"No head shape point is omitted, the total is {n_total}."
)
@verbose
def _update_plot(self, changes="all", verbose=None):
# Update list of things that need to be updated/plotted (and maybe
# draw them immediately)
try:
fun_name = inspect.currentframe().f_back.f_back.f_code.co_name
except Exception: # just in case one of these attrs is missing
fun_name = "unknown"
logger.debug(f"Updating plots based on {fun_name}: {repr(changes)}")
if self._plot_locked:
return
if self._info is None:
changes = ["head", "mri_fids"]
self._to_cf_t = dict(mri=dict(trans=np.eye(4)), head=None)
else:
self._to_cf_t = _get_transforms_to_coord_frame(
self._info, self.coreg.trans, coord_frame=self._coord_frame
)
all_keys = (
"head",
"mri_fids", # MRI first
"hsp",
"hpi",
"sensors",
"head_fids", # then dig
"helmet",
)
if changes == "all":
changes = list(all_keys)