forked from mne-tools/mne-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
surface.py
2210 lines (1926 loc) · 70.8 KB
/
surface.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: Matti Hämäläinen <[email protected]>
# Alexandre Gramfort <[email protected]>
# Matti Hämäläinen <[email protected]>
# Denis A. Engemann <[email protected]>
#
# License: BSD-3-Clause
# Many of the computations in this code were derived from Matti Hämäläinen's
# C code.
from copy import deepcopy
from functools import partial, lru_cache
from collections import OrderedDict
from glob import glob
from os import path as op
import time
import warnings
import numpy as np
from .channels.channels import _get_meg_system
from .fixes import jit, prange, bincount
from .io.constants import FIFF
from .io.pick import pick_types
from .parallel import parallel_func
from .transforms import (
transform_surface_to,
_pol_to_cart,
_cart_to_sph,
_get_trans,
apply_trans,
Transform,
)
from .utils import (
logger,
verbose,
get_subjects_dir,
warn,
_check_fname,
_check_option,
_ensure_int,
_TempDir,
run_subprocess,
_check_freesurfer_home,
_hashable_ndarray,
fill_doc,
_validate_type,
_pl,
_import_nibabel,
)
###############################################################################
# AUTOMATED SURFACE FINDING
@verbose
def get_head_surf(
subject, source=("bem", "head"), subjects_dir=None, on_defects="raise", verbose=None
):
"""Load the subject head surface.
Parameters
----------
subject : str
Subject name.
source : str | list of str
Type to load. Common choices would be ``'bem'`` or ``'head'``. We first
try loading ``'$SUBJECTS_DIR/$SUBJECT/bem/$SUBJECT-$SOURCE.fif'``, and
then look for ``'$SUBJECT*$SOURCE.fif'`` in the same directory by going
through all files matching the pattern. The head surface will be read
from the first file containing a head surface. Can also be a list
to try multiple strings.
subjects_dir : path-like | None
Path to the ``SUBJECTS_DIR``. If None, the path is obtained by using
the environment variable ``SUBJECTS_DIR``.
%(on_defects)s
.. versionadded:: 1.0
%(verbose)s
Returns
-------
surf : dict
The head surface.
"""
return _get_head_surface(
subject=subject, source=source, subjects_dir=subjects_dir, on_defects=on_defects
)
# TODO this should be refactored with mne._freesurfer._get_head_surface
def _get_head_surface(subject, source, subjects_dir, on_defects, raise_error=True):
"""Load the subject head surface."""
from .bem import read_bem_surfaces
# Load the head surface from the BEM
subjects_dir = str(get_subjects_dir(subjects_dir, raise_error=True))
if not isinstance(subject, str):
raise TypeError(
"subject must be a string, not %s."
% (
type(
subject,
)
)
)
# use realpath to allow for linked surfaces (c.f. MNE manual 196-197)
if isinstance(source, str):
source = [source]
surf = None
for this_source in source:
this_head = op.realpath(
op.join(subjects_dir, subject, "bem", "%s-%s.fif" % (subject, this_source))
)
if op.exists(this_head):
surf = read_bem_surfaces(
this_head,
True,
FIFF.FIFFV_BEM_SURF_ID_HEAD,
on_defects=on_defects,
verbose=False,
)
else:
# let's do a more sophisticated search
path = op.join(subjects_dir, subject, "bem")
if not op.isdir(path):
raise OSError('Subject bem directory "%s" does not exist.' % path)
files = sorted(glob(op.join(path, "%s*%s.fif" % (subject, this_source))))
for this_head in files:
try:
surf = read_bem_surfaces(
this_head,
True,
FIFF.FIFFV_BEM_SURF_ID_HEAD,
on_defects=on_defects,
verbose=False,
)
except ValueError:
pass
else:
break
if surf is not None:
break
if surf is None:
if raise_error:
raise OSError(
'No file matching "%s*%s" and containing a head '
"surface found." % (subject, this_source)
)
else:
return surf
logger.info("Using surface from %s." % this_head)
return surf
@verbose
def get_meg_helmet_surf(info, trans=None, verbose=None):
"""Load the MEG helmet associated with the MEG sensors.
Parameters
----------
%(info_not_none)s
trans : dict
The head<->MRI transformation, usually obtained using
read_trans(). Can be None, in which case the surface will
be in head coordinates instead of MRI coordinates.
%(verbose)s
Returns
-------
surf : dict
The MEG helmet as a surface.
Notes
-----
A built-in helmet is loaded if possible. If not, a helmet surface
will be approximated based on the sensor locations.
"""
from scipy.spatial import ConvexHull, Delaunay
from .bem import read_bem_surfaces, _fit_sphere
system, have_helmet = _get_meg_system(info)
if have_helmet:
logger.info("Getting helmet for system %s" % system)
fname = op.join(op.split(__file__)[0], "data", "helmets", system + ".fif.gz")
surf = read_bem_surfaces(
fname, False, FIFF.FIFFV_MNE_SURF_MEG_HELMET, verbose=False
)
else:
rr = np.array(
[
info["chs"][pick]["loc"][:3]
for pick in pick_types(info, meg=True, ref_meg=False, exclude=())
]
)
logger.info(
"Getting helmet for system %s (derived from %d MEG "
"channel locations)" % (system, len(rr))
)
hull = ConvexHull(rr)
rr = rr[np.unique(hull.simplices)]
R, center = _fit_sphere(rr, disp=False)
sph = _cart_to_sph(rr - center)[:, 1:]
# add a point at the front of the helmet (where the face should be):
# 90 deg az and maximal el (down from Z/up axis)
front_sph = [[np.pi / 2.0, sph[:, 1].max()]]
sph = np.concatenate((sph, front_sph))
xy = _pol_to_cart(sph[:, ::-1])
tris = Delaunay(xy).simplices
# remove the frontal point we added from the simplices
tris = tris[(tris != len(sph) - 1).all(-1)]
tris = _reorder_ccw(rr, tris)
surf = dict(rr=rr, tris=tris)
complete_surface_info(surf, copy=False, verbose=False)
# Ignore what the file says, it's in device coords and we want MRI coords
surf["coord_frame"] = FIFF.FIFFV_COORD_DEVICE
dev_head_t = info["dev_head_t"]
if dev_head_t is None:
dev_head_t = Transform("meg", "head")
transform_surface_to(surf, "head", dev_head_t)
if trans is not None:
transform_surface_to(surf, "mri", trans)
return surf
def _reorder_ccw(rrs, tris):
"""Reorder tris of a convex hull to be wound counter-clockwise."""
# This ensures that rendering with front-/back-face culling works properly
com = np.mean(rrs, axis=0)
rr_tris = rrs[tris]
dirs = np.sign(
(
np.cross(rr_tris[:, 1] - rr_tris[:, 0], rr_tris[:, 2] - rr_tris[:, 0])
* (rr_tris[:, 0] - com)
).sum(-1)
).astype(int)
return np.array([t[::d] for d, t in zip(dirs, tris)])
###############################################################################
# EFFICIENCY UTILITIES
def fast_cross_3d(x, y):
"""Compute cross product between list of 3D vectors.
Much faster than np.cross() when the number of cross products
becomes large (>= 500). This is because np.cross() methods become
less memory efficient at this stage.
Parameters
----------
x : array
Input array 1, shape (..., 3).
y : array
Input array 2, shape (..., 3).
Returns
-------
z : array, shape (..., 3)
Cross product of x and y along the last dimension.
Notes
-----
x and y must broadcast against each other.
"""
assert x.ndim >= 1
assert y.ndim >= 1
assert x.shape[-1] == 3
assert y.shape[-1] == 3
if max(x.size, y.size) >= 500:
out = np.empty(np.broadcast(x, y).shape)
_jit_cross(out, x, y)
return out
else:
return np.cross(x, y)
@jit()
def _jit_cross(out, x, y):
out[..., 0] = x[..., 1] * y[..., 2]
out[..., 0] -= x[..., 2] * y[..., 1]
out[..., 1] = x[..., 2] * y[..., 0]
out[..., 1] -= x[..., 0] * y[..., 2]
out[..., 2] = x[..., 0] * y[..., 1]
out[..., 2] -= x[..., 1] * y[..., 0]
@jit()
def _fast_cross_nd_sum(a, b, c):
"""Fast cross and sum."""
return (
(a[..., 1] * b[..., 2] - a[..., 2] * b[..., 1]) * c[..., 0]
+ (a[..., 2] * b[..., 0] - a[..., 0] * b[..., 2]) * c[..., 1]
+ (a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]) * c[..., 2]
)
@jit()
def _accumulate_normals(tris, tri_nn, npts):
"""Efficiently accumulate triangle normals."""
# this code replaces the following, but is faster (vectorized):
#
# this['nn'] = np.zeros((this['np'], 3))
# for p in xrange(this['ntri']):
# verts = this['tris'][p]
# this['nn'][verts, :] += this['tri_nn'][p, :]
#
nn = np.zeros((npts, 3))
for vi in range(3):
verts = tris[:, vi]
for idx in range(3): # x, y, z
nn[:, idx] += bincount(verts, weights=tri_nn[:, idx], minlength=npts)
return nn
def _triangle_neighbors(tris, npts):
"""Efficiently compute vertex neighboring triangles."""
# this code replaces the following, but is faster (vectorized):
# neighbor_tri = [list() for _ in range(npts)]
# for ti, tri in enumerate(tris):
# for t in tri:
# neighbor_tri[t].append(ti)
from scipy.sparse import coo_matrix
rows = tris.ravel()
cols = np.repeat(np.arange(len(tris)), 3)
data = np.ones(len(cols))
csr = coo_matrix((data, (rows, cols)), shape=(npts, len(tris))).tocsr()
neighbor_tri = [
csr.indices[start:stop] for start, stop in zip(csr.indptr[:-1], csr.indptr[1:])
]
assert len(neighbor_tri) == npts
return neighbor_tri
@jit()
def _triangle_coords(r, best, r1, nn, r12, r13, a, b, c): # pragma: no cover
"""Get coordinates of a vertex projected to a triangle."""
r1 = r1[best]
tri_nn = nn[best]
r12 = r12[best]
r13 = r13[best]
a = a[best]
b = b[best]
c = c[best]
rr = r - r1
z = np.sum(rr * tri_nn)
v1 = np.sum(rr * r12)
v2 = np.sum(rr * r13)
det = a * b - c * c
x = (b * v1 - c * v2) / det
y = (a * v2 - c * v1) / det
return x, y, z
def _project_onto_surface(
rrs, surf, project_rrs=False, return_nn=False, method="accurate"
):
"""Project points onto (scalp) surface."""
if method == "accurate":
surf_geom = _get_tri_supp_geom(surf)
pt_tris = np.empty((0,), int)
pt_lens = np.zeros(len(rrs) + 1, int)
out = _find_nearest_tri_pts(rrs, pt_tris, pt_lens, reproject=True, **surf_geom)
if project_rrs: #
out += (np.einsum("ij,ijk->ik", out[0], surf["rr"][surf["tris"][out[1]]]),)
if return_nn:
out += (surf_geom["nn"][out[1]],)
else: # nearest neighbor
assert project_rrs
idx = _compute_nearest(surf["rr"], rrs)
out = (None, None, surf["rr"][idx])
if return_nn:
surf_geom = _get_tri_supp_geom(surf)
nn = _accumulate_normals(
surf["tris"].astype(int), surf_geom["nn"], len(surf["rr"])
)
nn = nn[idx]
_normalize_vectors(nn)
out += (nn,)
return out
def _normal_orth(nn):
"""Compute orthogonal basis given a normal."""
assert nn.shape[-1:] == (3,)
prod = np.einsum("...i,...j->...ij", nn, nn)
_, u = np.linalg.eigh(np.eye(3) - prod)
u = u[..., ::-1]
# Make sure that ez is in the direction of nn
signs = np.sign(np.matmul(nn[..., np.newaxis, :], u[..., -1:]))
signs[signs == 0] = 1
u *= signs
return u.swapaxes(-1, -2)
@verbose
def complete_surface_info(
surf, do_neighbor_vert=False, copy=True, do_neighbor_tri=True, *, verbose=None
):
"""Complete surface information.
Parameters
----------
surf : dict
The surface.
do_neighbor_vert : bool
If True (default False), add neighbor vertex information.
copy : bool
If True (default), make a copy. If False, operate in-place.
do_neighbor_tri : bool
If True (default), compute triangle neighbors.
%(verbose)s
Returns
-------
surf : dict
The transformed surface.
"""
if copy:
surf = deepcopy(surf)
# based on mne_source_space_add_geometry_info() in mne_add_geometry_info.c
# Main triangulation [mne_add_triangle_data()]
surf["ntri"] = surf.get("ntri", len(surf["tris"]))
surf["np"] = surf.get("np", len(surf["rr"]))
surf["tri_area"] = np.zeros(surf["ntri"])
r1 = surf["rr"][surf["tris"][:, 0], :]
r2 = surf["rr"][surf["tris"][:, 1], :]
r3 = surf["rr"][surf["tris"][:, 2], :]
surf["tri_cent"] = (r1 + r2 + r3) / 3.0
surf["tri_nn"] = fast_cross_3d((r2 - r1), (r3 - r1))
# Triangle normals and areas
surf["tri_area"] = _normalize_vectors(surf["tri_nn"]) / 2.0
zidx = np.where(surf["tri_area"] == 0)[0]
if len(zidx) > 0:
logger.info(" Warning: zero size triangles: %s" % zidx)
# Find neighboring triangles, accumulate vertex normals, normalize
logger.info(" Triangle neighbors and vertex normals...")
surf["nn"] = _accumulate_normals(
surf["tris"].astype(int), surf["tri_nn"], surf["np"]
)
_normalize_vectors(surf["nn"])
# Check for topological defects
if do_neighbor_tri:
surf["neighbor_tri"] = _triangle_neighbors(surf["tris"], surf["np"])
zero, fewer = list(), list()
for ni, n in enumerate(surf["neighbor_tri"]):
if len(n) < 3:
if len(n) == 0:
zero.append(ni)
else:
fewer.append(ni)
surf["neighbor_tri"][ni] = np.array([], int)
if len(zero) > 0:
logger.info(
" Vertices do not have any neighboring "
"triangles: [%s]" % ", ".join(str(z) for z in zero)
)
if len(fewer) > 0:
logger.info(
" Vertices have fewer than three neighboring "
"triangles, removing neighbors: [%s]" % ", ".join(str(f) for f in fewer)
)
# Determine the neighboring vertices and fix errors
if do_neighbor_vert is True:
logger.info(" Vertex neighbors...")
surf["neighbor_vert"] = [
_get_surf_neighbors(surf, k) for k in range(surf["np"])
]
return surf
def _get_surf_neighbors(surf, k):
"""Calculate the surface neighbors based on triangulation."""
verts = set()
for v in surf["tris"][surf["neighbor_tri"][k]].flat:
verts.add(v)
verts.remove(k)
verts = np.array(sorted(verts))
assert np.all(verts < surf["np"])
nneighbors = len(verts)
nneigh_max = len(surf["neighbor_tri"][k])
if nneighbors > nneigh_max:
raise RuntimeError("Too many neighbors for vertex %d" % k)
elif nneighbors != nneigh_max:
logger.info(
" Incorrect number of distinct neighbors for vertex"
" %d (%d instead of %d) [fixed]." % (k, nneighbors, nneigh_max)
)
return verts
def _normalize_vectors(rr):
"""Normalize surface vertices."""
size = np.linalg.norm(rr, axis=1)
mask = size > 0
rr[mask] /= size[mask, np.newaxis] # operate in-place
return size
class _CDist:
"""Wrapper for cdist that uses a Tree-like pattern."""
def __init__(self, xhs):
self._xhs = xhs
def query(self, rr):
from scipy.spatial.distance import cdist
nearest = list()
dists = list()
for r in rr:
d = cdist(r[np.newaxis, :], self._xhs)
idx = np.argmin(d)
nearest.append(idx)
dists.append(d[0, idx])
return np.array(dists), np.array(nearest)
def _compute_nearest(xhs, rr, method="BallTree", return_dists=False):
"""Find nearest neighbors.
Parameters
----------
xhs : array, shape=(n_samples, n_dim)
Points of data set.
rr : array, shape=(n_query, n_dim)
Points to find nearest neighbors for.
method : str
The query method. If scikit-learn and scipy<1.0 are installed,
it will fall back to the slow brute-force search.
return_dists : bool
If True, return associated distances.
Returns
-------
nearest : array, shape=(n_query,)
Index of nearest neighbor in xhs for every point in rr.
distances : array, shape=(n_query,)
The distances. Only returned if return_dists is True.
"""
if xhs.size == 0 or rr.size == 0:
if return_dists:
return np.array([], int), np.array([])
return np.array([], int)
tree = _DistanceQuery(xhs, method=method)
out = tree.query(rr)
return out[::-1] if return_dists else out[1]
def _safe_query(rr, func, reduce=False, **kwargs):
if len(rr) == 0:
return np.array([]), np.array([], int)
out = func(rr)
out = [out[0][:, 0], out[1][:, 0]] if reduce else out
return out
class _DistanceQuery:
"""Wrapper for fast distance queries."""
def __init__(self, xhs, method="BallTree", allow_kdtree=False):
assert method in ("BallTree", "cKDTree", "cdist")
# Fastest for our problems: balltree
if method == "BallTree":
try:
from sklearn.neighbors import BallTree
except ImportError:
logger.info(
"Nearest-neighbor searches will be significantly "
"faster if scikit-learn is installed."
)
method = "cKDTree"
else:
self.query = partial(
_safe_query,
func=BallTree(xhs).query,
reduce=True,
return_distance=True,
)
# Then cKDTree
if method == "cKDTree":
try:
from scipy.spatial import cKDTree
except ImportError:
method = "cdist"
else:
self.query = cKDTree(xhs).query
# KDTree is really only faster for huge (~100k) sets,
# (e.g., with leafsize=2048), and it's slower for small (~5k)
# sets. We can add it later if we think it will help.
# Then the worst: cdist
if method == "cdist":
self.query = _CDist(xhs).query
self.data = xhs
@verbose
def _points_outside_surface(rr, surf, n_jobs=None, verbose=None):
"""Check whether points are outside a surface.
Parameters
----------
rr : ndarray
Nx3 array of points to check.
surf : dict
Surface with entries "rr" and "tris".
Returns
-------
outside : ndarray
1D logical array of size N for which points are outside the surface.
"""
rr = np.atleast_2d(rr)
assert rr.shape[1] == 3
parallel, p_fun, n_jobs = parallel_func(_get_solids, n_jobs)
tot_angles = parallel(
p_fun(surf["rr"][tris], rr) for tris in np.array_split(surf["tris"], n_jobs)
)
return np.abs(np.sum(tot_angles, axis=0) / (2 * np.pi) - 1.0) > 1e-5
def _surface_to_polydata(surf):
import pyvista as pv
vertices = np.array(surf["rr"])
if "tris" not in surf:
return pv.PolyData(vertices)
else:
triangles = np.array(surf["tris"])
triangles = np.c_[np.full(len(triangles), 3), triangles]
return pv.PolyData(vertices, triangles)
def _polydata_to_surface(pd, normals=True):
from pyvista import PolyData
if not isinstance(pd, PolyData):
pd = PolyData(pd)
out = dict(rr=pd.points, tris=pd.faces.reshape(-1, 4)[:, 1:])
if normals:
out["nn"] = pd.point_normals
return out
class _CheckInside:
"""Efficiently check if points are inside a surface."""
@verbose
def __init__(self, surf, *, mode="old", verbose=None):
assert mode in ("pyvista", "old")
self.mode = mode
t0 = time.time()
self.surf = surf
if self.mode == "pyvista":
self._init_pyvista()
else:
self._init_old()
logger.debug(
f'Setting up {mode} interior check for {len(self.surf["rr"])} '
f"points took {(time.time() - t0) * 1000:0.1f} ms"
)
def _init_old(self):
from scipy.spatial import Delaunay
self.inner_r = None
self.cm = self.surf["rr"].mean(0)
# We could use Delaunay or ConvexHull here, Delaunay is slightly slower
# to construct but faster to evaluate
# See https://stackoverflow.com/questions/16750618/whats-an-efficient-way-to-find-if-a-point-lies-in-the-convex-hull-of-a-point-cl # noqa
self.del_tri = Delaunay(self.surf["rr"])
if self.del_tri.find_simplex(self.cm) >= 0:
# Immediately cull some points from the checks
dists = np.linalg.norm(self.surf["rr"] - self.cm, axis=-1)
self.inner_r = dists.min()
self.outer_r = dists.max()
def _init_pyvista(self):
if not isinstance(self.surf, dict):
self.pdata = self.surf
self.surf = _polydata_to_surface(self.pdata)
else:
self.pdata = _surface_to_polydata(self.surf).clean()
@verbose
def __call__(self, rr, n_jobs=None, verbose=None):
n_orig = len(rr)
logger.info(
f"Checking surface interior status for "
f'{n_orig} point{_pl(n_orig, " ")}...'
)
t0 = time.time()
if self.mode == "pyvista":
inside = self._call_pyvista(rr)
else:
inside = self._call_old(rr, n_jobs)
n = inside.sum()
logger.info(f' Total {n}/{n_orig} point{_pl(n, " ")} inside the surface')
logger.info(f"Interior check completed in {(time.time() - t0) * 1000:0.1f} ms")
return inside
def _call_pyvista(self, rr):
pdata = _surface_to_polydata(dict(rr=rr))
out = pdata.select_enclosed_points(self.pdata, check_surface=False)
return out["SelectedPoints"].astype(bool)
def _call_old(self, rr, n_jobs):
n_orig = len(rr)
prec = int(np.ceil(np.log10(max(n_orig, 10))))
inside = np.ones(n_orig, bool) # innocent until proven guilty
idx = np.arange(n_orig)
# Limit to indices that can plausibly be outside the surf
# but are not definitely outside it
if self.inner_r is not None:
dists = np.linalg.norm(rr - self.cm, axis=-1)
in_mask = dists < self.inner_r
n = (in_mask).sum()
n_pad = str(n).rjust(prec)
logger.info(
f' Found {n_pad}/{n_orig} point{_pl(n, " ")} '
f"inside an interior sphere of radius "
f"{1000 * self.inner_r:6.1f} mm"
)
out_mask = dists > self.outer_r
inside[out_mask] = False
n = (out_mask).sum()
n_pad = str(n).rjust(prec)
logger.info(
f' Found {n_pad}/{n_orig} point{_pl(n, " ")} '
f"outside an exterior sphere of radius "
f"{1000 * self.outer_r:6.1f} mm"
)
mask = (~in_mask) & (~out_mask) # not definitely inside or outside
idx = idx[mask]
rr = rr[mask]
# Use qhull as our first pass (*much* faster than our check)
del_outside = self.del_tri.find_simplex(rr) < 0
n = sum(del_outside)
inside[idx[del_outside]] = False
idx = idx[~del_outside]
rr = rr[~del_outside]
n_pad = str(n).rjust(prec)
check_pad = str(len(del_outside)).rjust(prec)
logger.info(
f' Found {n_pad}/{check_pad} point{_pl(n, " ")} outside using '
"surface Qhull"
)
# use our more accurate check
solid_outside = _points_outside_surface(rr, self.surf, n_jobs)
n = np.sum(solid_outside)
n_pad = str(n).rjust(prec)
check_pad = str(len(solid_outside)).rjust(prec)
logger.info(
f' Found {n_pad}/{check_pad} point{_pl(n, " ")} outside using '
"solid angles"
)
inside[idx[solid_outside]] = False
return inside
###############################################################################
# Handle freesurfer
def _fread3(fobj):
"""Read 3 bytes and adjust."""
b1, b2, b3 = np.fromfile(fobj, ">u1", 3)
return (b1 << 16) + (b2 << 8) + b3
def _fread3_many(fobj, n):
"""Read 3-byte ints from an open binary file object."""
b1, b2, b3 = np.fromfile(fobj, ">u1", 3 * n).reshape(-1, 3).astype(np.int64).T
return (b1 << 16) + (b2 << 8) + b3
def read_curvature(filepath, binary=True):
"""Load in curvature values from the ?h.curv file.
Parameters
----------
filepath : path-like
Input path to the ``.curv`` file.
binary : bool
Specify if the output array is to hold binary values. Defaults to True.
Returns
-------
curv : array of shape (n_vertices,)
The curvature values loaded from the user given file.
"""
with open(filepath, "rb") as fobj:
magic = _fread3(fobj)
if magic == 16777215:
vnum = np.fromfile(fobj, ">i4", 3)[0]
curv = np.fromfile(fobj, ">f4", vnum)
else:
vnum = magic
_fread3(fobj)
curv = np.fromfile(fobj, ">i2", vnum) / 100
if binary:
return 1 - np.array(curv != 0, np.int64)
else:
return curv
@verbose
def read_surface(
fname, read_metadata=False, return_dict=False, file_format="auto", verbose=None
):
"""Load a Freesurfer surface mesh in triangular format.
Parameters
----------
fname : path-like
The name of the file containing the surface.
read_metadata : bool
Read metadata as key-value pairs. Only works when reading a FreeSurfer
surface file. For .obj files this dictionary will be empty.
Valid keys:
* 'head' : array of int
* 'valid' : str
* 'filename' : str
* 'volume' : array of int, shape (3,)
* 'voxelsize' : array of float, shape (3,)
* 'xras' : array of float, shape (3,)
* 'yras' : array of float, shape (3,)
* 'zras' : array of float, shape (3,)
* 'cras' : array of float, shape (3,)
.. versionadded:: 0.13.0
return_dict : bool
If True, a dictionary with surface parameters is returned.
file_format : 'auto' | 'freesurfer' | 'obj'
File format to use. Can be 'freesurfer' to read a FreeSurfer surface
file, or 'obj' to read a Wavefront .obj file (common format for
importing in other software), or 'auto' to attempt to infer from the
file name. Defaults to 'auto'.
.. versionadded:: 0.21.0
%(verbose)s
Returns
-------
rr : array, shape=(n_vertices, 3)
Coordinate points.
tris : int array, shape=(n_faces, 3)
Triangulation (each line contains indices for three points which
together form a face).
volume_info : dict-like
If read_metadata is true, key-value pairs found in the geometry file.
surf : dict
The surface parameters. Only returned if ``return_dict`` is True.
See Also
--------
write_surface
read_tri
"""
fname = _check_fname(fname, "read", True)
_check_option("file_format", file_format, ["auto", "freesurfer", "obj"])
if file_format == "auto":
if fname.suffix.lower() == ".obj":
file_format = "obj"
else:
file_format = "freesurfer"
if file_format == "freesurfer":
_import_nibabel("read surface geometry")
from nibabel.freesurfer import read_geometry
ret = read_geometry(fname, read_metadata=read_metadata)
elif file_format == "obj":
ret = _read_wavefront_obj(fname)
if read_metadata:
ret += (dict(),)
if return_dict:
ret += (_rr_tris_dict(ret[0], ret[1]),)
return ret
def _rr_tris_dict(rr, tris):
return dict(rr=rr, tris=tris, ntri=len(tris), use_tris=tris, np=len(rr))
def _read_mri_surface(fname):
surf = read_surface(fname, return_dict=True)[2]
surf["rr"] /= 1000.0
surf.update(coord_frame=FIFF.FIFFV_COORD_MRI)
return surf
def _read_wavefront_obj(fname):
"""Read a surface form a Wavefront .obj file.
Parameters
----------
fname : str
Name of the .obj file to read.
Returns
-------
coords : ndarray, shape (n_points, 3)
The XYZ coordinates of each vertex.
faces : ndarray, shape (n_faces, 3)
For each face of the mesh, the integer indices of the vertices that
make up the face.
"""
coords = []
faces = []
with open(fname) as f:
for line in f:
line = line.strip()
if len(line) == 0 or line[0] == "#":
continue
split = line.split()
if split[0] == "v": # vertex
coords.append([float(item) for item in split[1:]])
elif split[0] == "f": # face
dat = [int(item.split("/")[0]) for item in split[1:]]
if len(dat) != 3:
raise RuntimeError("Only triangle faces allowed.")
# In .obj files, indexing starts at 1
faces.append([d - 1 for d in dat])
return np.array(coords), np.array(faces)
def _read_patch(fname):
"""Load a FreeSurfer binary patch file.
Parameters
----------
fname : str
The filename.
Returns
-------
rrs : ndarray, shape (n_vertices, 3)
The points.
tris : ndarray, shape (n_tris, 3)
The patches. Not all vertices will be present.
"""
# This is adapted from PySurfer PR #269, Bruce Fischl's read_patch.m,
# and PyCortex (BSD)
patch = dict()
with open(fname, "r") as fid:
ver = np.fromfile(fid, dtype=">i4", count=1).item()
if ver != -1:
raise RuntimeError(f"incorrect version # {ver} (not -1) found")
npts = np.fromfile(fid, dtype=">i4", count=1).item()
dtype = np.dtype([("vertno", ">i4"), ("x", ">f"), ("y", ">f"), ("z", ">f")])
recs = np.fromfile(fid, dtype=dtype, count=npts)
# numpy to dict
patch = {key: recs[key] for key in dtype.fields.keys()}
patch["vertno"] -= 1
# read surrogate surface
rrs, tris = read_surface(
op.join(op.dirname(fname), op.basename(fname)[:3] + "sphere")
)
orig_tris = tris
is_vert = patch["vertno"] > 0 # negative are edges, ignored for now
verts = patch["vertno"][is_vert]
# eliminate invalid tris and zero out unused rrs
mask = np.zeros((len(rrs),), dtype=bool)
mask[verts] = True
rrs[~mask] = 0.0
tris = tris[mask[tris].all(1)]
for ii, key in enumerate(["x", "y", "z"]):
rrs[verts, ii] = patch[key][is_vert]
return rrs, tris, orig_tris
##############################################################################
# SURFACE CREATION