-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathsource_estimate.py
4059 lines (3579 loc) · 133 KB
/
source_estimate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Authors: The MNE-Python contributors.
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import contextlib
import copy
import os.path as op
from types import GeneratorType
import numpy as np
from scipy import sparse
from scipy.spatial.distance import cdist, pdist
from ._fiff.constants import FIFF
from ._fiff.meas_info import Info
from ._fiff.pick import _picks_to_idx, pick_types
from ._freesurfer import _get_atlas_values, _get_mri_info_data, read_freesurfer_lut
from .baseline import rescale
from .cov import Covariance
from .evoked import _get_peak
from .filter import FilterMixin, _check_fun, resample
from .fixes import _eye_array, _safe_svd
from .parallel import parallel_func
from .source_space._source_space import (
SourceSpaces,
_check_volume_labels,
_ensure_src,
_ensure_src_subject,
_get_morph_src_reordering,
_get_src_nn,
get_decimated_surfaces,
)
from .surface import _get_ico_surface, _project_onto_surface, mesh_edges, read_surface
from .transforms import _get_trans, apply_trans
from .utils import (
TimeMixin,
_build_data_frame,
_check_fname,
_check_option,
_check_pandas_index_arguments,
_check_pandas_installed,
_check_preload,
_check_src_normal,
_check_stc_units,
_check_subject,
_check_time_format,
_convert_times,
_ensure_int,
_import_h5io_funcs,
_import_nibabel,
_path_like,
_pl,
_time_mask,
_validate_type,
copy_function_doc_to_method_doc,
fill_doc,
get_subjects_dir,
logger,
object_size,
sizeof_fmt,
verbose,
warn,
)
from .viz import (
plot_source_estimates,
plot_vector_source_estimates,
plot_volume_source_estimates,
)
def _read_stc(filename):
"""Aux Function."""
with open(filename, "rb") as fid:
buf = fid.read()
stc = dict()
offset = 0
num_bytes = 4
# read tmin in ms
stc["tmin"] = (
float(np.frombuffer(buf, dtype=">f4", count=1, offset=offset).item()) / 1000.0
)
offset += num_bytes
# read sampling rate in ms
stc["tstep"] = (
float(np.frombuffer(buf, dtype=">f4", count=1, offset=offset).item()) / 1000.0
)
offset += num_bytes
# read number of vertices/sources
vertices_n = int(np.frombuffer(buf, dtype=">u4", count=1, offset=offset).item())
offset += num_bytes
# read the source vector
stc["vertices"] = np.frombuffer(buf, dtype=">u4", count=vertices_n, offset=offset)
offset += num_bytes * vertices_n
# read the number of timepts
data_n = int(np.frombuffer(buf, dtype=">u4", count=1, offset=offset).item())
offset += num_bytes
if (
vertices_n
and ( # vertices_n can be 0 (empty stc)
(len(buf) // 4 - 4 - vertices_n) % (data_n * vertices_n)
)
!= 0
):
raise ValueError("incorrect stc file size")
# read the data matrix
stc["data"] = np.frombuffer(
buf, dtype=">f4", count=vertices_n * data_n, offset=offset
)
stc["data"] = stc["data"].reshape([data_n, vertices_n]).T
return stc
def _write_stc(filename, tmin, tstep, vertices, data):
"""Write an STC file.
Parameters
----------
filename : path-like
The name of the STC file.
tmin : float
The first time point of the data in seconds.
tstep : float
Time between frames in seconds.
vertices : array of integers
Vertex indices (0 based).
data : 2D array
The data matrix (nvert * ntime).
"""
with open(filename, "wb") as fid:
# write start time in ms
fid.write(np.array(1000 * tmin, dtype=">f4").tobytes())
# write sampling rate in ms
fid.write(np.array(1000 * tstep, dtype=">f4").tobytes())
# write number of vertices
fid.write(np.array(vertices.shape[0], dtype=">u4").tobytes())
# write the vertex indices
fid.write(np.array(vertices, dtype=">u4").tobytes())
# write the number of timepts
fid.write(np.array(data.shape[1], dtype=">u4").tobytes())
# write the data
fid.write(np.array(data.T, dtype=">f4").tobytes())
def _read_3(fid):
"""Read 3 byte integer from file."""
data = np.fromfile(fid, dtype=np.uint8, count=3).astype(np.int32)
out = np.left_shift(data[0], 16) + np.left_shift(data[1], 8) + data[2]
return out
def _read_w(filename):
"""Read a w file.
w files contain activations or source reconstructions for a single time
point.
Parameters
----------
filename : path-like
The name of the w file.
Returns
-------
data: dict
The w structure. It has the following keys:
vertices vertex indices (0 based)
data The data matrix (nvert long)
"""
with open(filename, "rb", buffering=0) as fid: # buffering=0 for np bug
# skip first 2 bytes
fid.read(2)
# read number of vertices/sources (3 byte integer)
vertices_n = int(_read_3(fid))
vertices = np.zeros((vertices_n), dtype=np.int32)
data = np.zeros((vertices_n), dtype=np.float32)
# read the vertices and data
for i in range(vertices_n):
vertices[i] = _read_3(fid)
data[i] = np.fromfile(fid, dtype=">f4", count=1).item()
w = dict()
w["vertices"] = vertices
w["data"] = data
return w
def _write_3(fid, val):
"""Write 3 byte integer to file."""
f_bytes = np.zeros((3), dtype=np.uint8)
f_bytes[0] = (val >> 16) & 255
f_bytes[1] = (val >> 8) & 255
f_bytes[2] = val & 255
fid.write(f_bytes.tobytes())
def _write_w(filename, vertices, data):
"""Write a w file.
w files contain activations or source reconstructions for a single time
point.
Parameters
----------
filename: path-like
The name of the w file.
vertices: array of int
Vertex indices (0 based).
data: 1D array
The data array (nvert).
"""
assert len(vertices) == len(data)
with open(filename, "wb") as fid:
# write 2 zero bytes
fid.write(np.zeros((2), dtype=np.uint8).tobytes())
# write number of vertices/sources (3 byte integer)
vertices_n = len(vertices)
_write_3(fid, vertices_n)
# write the vertices and data
for i in range(vertices_n):
_write_3(fid, vertices[i])
# XXX: without float() endianness is wrong, not sure why
fid.write(np.array(float(data[i]), dtype=">f4").tobytes())
def read_source_estimate(fname, subject=None):
"""Read a source estimate object.
Parameters
----------
fname : path-like
Path to (a) source-estimate file(s).
subject : str | None
Name of the subject the source estimate(s) is (are) from.
It is good practice to set this attribute to avoid combining
incompatible labels and SourceEstimates (e.g., ones from other
subjects). Note that due to file specification limitations, the
subject name isn't saved to or loaded from files written to disk.
Returns
-------
stc : SourceEstimate | VectorSourceEstimate | VolSourceEstimate | MixedSourceEstimate
The source estimate object loaded from file.
Notes
-----
- for volume source estimates, ``fname`` should provide the path to a
single file named ``'*-vl.stc``` or ``'*-vol.stc'``
- for surface source estimates, ``fname`` should either provide the
path to the file corresponding to a single hemisphere (``'*-lh.stc'``,
``'*-rh.stc'``) or only specify the asterisk part in these patterns. In
any case, the function expects files for both hemisphere with names
following this pattern.
- for vector surface source estimates, only HDF5 files are supported.
- for mixed source estimates, only HDF5 files are supported.
- for single time point ``.w`` files, ``fname`` should follow the same
pattern as for surface estimates, except that files are named
``'*-lh.w'`` and ``'*-rh.w'``.
""" # noqa: E501
fname_arg = fname
# expand `~` without checking whether the file actually exists – we'll
# take care of that later, as it's complicated by the different suffixes
# STC files can have
fname = str(_check_fname(fname=fname, overwrite="read", must_exist=False))
# make sure corresponding file(s) can be found
ftype = None
if op.exists(fname):
if fname.endswith(("-vl.stc", "-vol.stc", "-vl.w", "-vol.w")):
ftype = "volume"
elif fname.endswith(".stc"):
ftype = "surface"
if fname.endswith(("-lh.stc", "-rh.stc")):
fname = fname[:-7]
else:
err = (
f"Invalid .stc filename: {fname!r}; needs to end with "
"hemisphere tag ('...-lh.stc' or '...-rh.stc')"
)
raise OSError(err)
elif fname.endswith(".w"):
ftype = "w"
if fname.endswith(("-lh.w", "-rh.w")):
fname = fname[:-5]
else:
err = (
f"Invalid .w filename: {fname!r}; needs to end with "
"hemisphere tag ('...-lh.w' or '...-rh.w')"
)
raise OSError(err)
elif fname.endswith(".h5"):
ftype = "h5"
fname = fname[:-3]
else:
raise RuntimeError(f"Unknown extension for file {fname_arg}")
if ftype != "volume":
stc_exist = [op.exists(f) for f in [fname + "-rh.stc", fname + "-lh.stc"]]
w_exist = [op.exists(f) for f in [fname + "-rh.w", fname + "-lh.w"]]
if all(stc_exist) and ftype != "w":
ftype = "surface"
elif all(w_exist):
ftype = "w"
elif op.exists(fname + ".h5"):
ftype = "h5"
elif op.exists(fname + "-stc.h5"):
ftype = "h5"
fname += "-stc"
elif any(stc_exist) or any(w_exist):
raise OSError(f"Hemisphere missing for {fname_arg!r}")
else:
raise OSError(f"SourceEstimate File(s) not found for: {fname_arg!r}")
# read the files
if ftype == "volume": # volume source space
if fname.endswith(".stc"):
kwargs = _read_stc(fname)
elif fname.endswith(".w"):
kwargs = _read_w(fname)
kwargs["data"] = kwargs["data"][:, np.newaxis]
kwargs["tmin"] = 0.0
kwargs["tstep"] = 0.0
else:
raise OSError("Volume source estimate must end with .stc or .w")
kwargs["vertices"] = [kwargs["vertices"]]
elif ftype == "surface": # stc file with surface source spaces
lh = _read_stc(fname + "-lh.stc")
rh = _read_stc(fname + "-rh.stc")
assert lh["tmin"] == rh["tmin"]
assert lh["tstep"] == rh["tstep"]
kwargs = lh.copy()
kwargs["data"] = np.r_[lh["data"], rh["data"]]
kwargs["vertices"] = [lh["vertices"], rh["vertices"]]
elif ftype == "w": # w file with surface source spaces
lh = _read_w(fname + "-lh.w")
rh = _read_w(fname + "-rh.w")
kwargs = lh.copy()
kwargs["data"] = np.atleast_2d(np.r_[lh["data"], rh["data"]]).T
kwargs["vertices"] = [lh["vertices"], rh["vertices"]]
# w files only have a single time point
kwargs["tmin"] = 0.0
kwargs["tstep"] = 1.0
ftype = "surface"
elif ftype == "h5":
read_hdf5, _ = _import_h5io_funcs()
kwargs = read_hdf5(fname + ".h5", title="mnepython")
ftype = kwargs.pop("src_type", "surface")
if isinstance(kwargs["vertices"], np.ndarray):
kwargs["vertices"] = [kwargs["vertices"]]
if ftype != "volume":
# Make sure the vertices are ordered
vertices = kwargs["vertices"]
if any(np.any(np.diff(v.astype(int)) <= 0) for v in vertices):
sidx = [np.argsort(verts) for verts in vertices]
vertices = [verts[idx] for verts, idx in zip(vertices, sidx)]
data = kwargs["data"][np.r_[sidx[0], len(sidx[0]) + sidx[1]]]
kwargs["vertices"] = vertices
kwargs["data"] = data
if "subject" not in kwargs:
kwargs["subject"] = subject
if subject is not None and subject != kwargs["subject"]:
raise RuntimeError(
f'provided subject name "{subject}" does not match '
f'subject name from the file "{kwargs["subject"]}'
)
if ftype in ("volume", "discrete"):
klass = VolVectorSourceEstimate
elif ftype == "mixed":
klass = MixedVectorSourceEstimate
else:
assert ftype == "surface"
klass = VectorSourceEstimate
if kwargs["data"].ndim < 3:
klass = klass._scalar_class
return klass(**kwargs)
def _get_src_type(src, vertices, warn_text=None):
src_type = None
if src is None:
if warn_text is None:
warn("src should not be None for a robust guess of stc type.")
else:
warn(warn_text)
if isinstance(vertices, list) and len(vertices) == 2:
src_type = "surface"
elif (
isinstance(vertices, np.ndarray)
or isinstance(vertices, list)
and len(vertices) == 1
):
src_type = "volume"
elif isinstance(vertices, list) and len(vertices) > 2:
src_type = "mixed"
else:
src_type = src.kind
assert src_type in ("surface", "volume", "mixed", "discrete")
return src_type
def _make_stc(
data,
vertices,
src_type=None,
tmin=None,
tstep=None,
subject=None,
vector=False,
source_nn=None,
warn_text=None,
):
"""Generate a surface, vector-surface, volume or mixed source estimate."""
def guess_src_type():
return _get_src_type(src=None, vertices=vertices, warn_text=warn_text)
src_type = guess_src_type() if src_type is None else src_type
if vector and src_type == "surface" and source_nn is None:
raise RuntimeError("No source vectors supplied.")
# infer Klass from src_type
if src_type == "surface":
Klass = VectorSourceEstimate if vector else SourceEstimate
elif src_type in ("volume", "discrete"):
Klass = VolVectorSourceEstimate if vector else VolSourceEstimate
elif src_type == "mixed":
Klass = MixedVectorSourceEstimate if vector else MixedSourceEstimate
else:
raise ValueError(
"vertices has to be either a list with one or more arrays or an array"
)
# Rotate back for vector source estimates
if vector:
n_vertices = sum(len(v) for v in vertices)
assert data.shape[0] in (n_vertices, n_vertices * 3)
if len(data) == n_vertices:
assert src_type == "surface" # should only be possible for this
assert source_nn.shape == (n_vertices, 3)
data = data[:, np.newaxis] * source_nn[:, :, np.newaxis]
else:
data = data.reshape((-1, 3, data.shape[-1]))
assert source_nn.shape in ((n_vertices, 3, 3), (n_vertices * 3, 3))
# This will be an identity transform for volumes, but let's keep
# the code simple and general and just do the matrix mult
data = np.matmul(
np.transpose(source_nn.reshape(n_vertices, 3, 3), axes=[0, 2, 1]), data
)
return Klass(data=data, vertices=vertices, tmin=tmin, tstep=tstep, subject=subject)
def _verify_source_estimate_compat(a, b):
"""Make sure two SourceEstimates are compatible for arith. operations."""
compat = False
if type(a) is not type(b):
raise ValueError(f"Cannot combine {type(a)} and {type(b)}.")
if len(a.vertices) == len(b.vertices):
if all(np.array_equal(av, vv) for av, vv in zip(a.vertices, b.vertices)):
compat = True
if not compat:
raise ValueError(
"Cannot combine source estimates that do not have "
"the same vertices. Consider using stc.expand()."
)
if a.subject != b.subject:
raise ValueError(
"source estimates do not have the same subject "
f"names, {repr(a.subject)} and {repr(b.subject)}"
)
class _BaseSourceEstimate(TimeMixin, FilterMixin):
_data_ndim = 2
@verbose
def __init__(self, data, vertices, tmin, tstep, subject=None, verbose=None):
assert hasattr(self, "_data_ndim"), self.__class__.__name__
assert hasattr(self, "_src_type"), self.__class__.__name__
assert hasattr(self, "_src_count"), self.__class__.__name__
kernel, sens_data = None, None
if isinstance(data, tuple):
if len(data) != 2:
raise ValueError("If data is a tuple it has to be length 2")
kernel, sens_data = data
data = None
if kernel.shape[1] != sens_data.shape[0]:
raise ValueError(
f"kernel ({kernel.shape}) and sens_data ({sens_data.shape}) "
"have invalid dimensions"
)
if sens_data.ndim != 2:
raise ValueError(
"The sensor data must have 2 dimensions, got {sens_data.ndim}"
)
_validate_type(vertices, list, "vertices")
if self._src_count is not None:
if len(vertices) != self._src_count:
raise ValueError(
f"vertices must be a list with {self._src_count} entries, "
f"got {len(vertices)}."
)
vertices = [np.array(v, np.int64) for v in vertices] # makes copy
if any(np.any(np.diff(v) <= 0) for v in vertices):
raise ValueError("Vertices must be ordered in increasing order.")
n_src = sum([len(v) for v in vertices])
# safeguard the user against doing something silly
if data is not None:
if data.ndim not in (self._data_ndim, self._data_ndim - 1):
raise ValueError(
f"Data (shape {data.shape}) must have {self._data_ndim} "
f"dimensions for {self.__class__.__name__}"
)
if data.shape[0] != n_src:
raise ValueError(
f"Number of vertices ({n_src}) and stc.data.shape[0] "
f"({data.shape[0]}) must match"
)
if self._data_ndim == 3:
if data.shape[1] != 3:
raise ValueError(
"Data for VectorSourceEstimate must have "
f"shape[1] == 3, got shape {data.shape}"
)
if data.ndim == self._data_ndim - 1: # allow upbroadcasting
data = data[..., np.newaxis]
self._data = data
self._tmin = tmin
self._tstep = tstep
self.vertices = vertices
self._kernel = kernel
self._sens_data = sens_data
self._kernel_removed = False
self._times = None
self._update_times()
self.subject = _check_subject(None, subject, raise_error=False)
def __repr__(self): # noqa: D105
s = f"{sum(len(v) for v in self.vertices)} vertices"
if self.subject is not None:
s += f", subject : {self.subject}"
s += ", tmin : %s (ms)" % (1e3 * self.tmin)
s += ", tmax : %s (ms)" % (1e3 * self.times[-1])
s += ", tstep : %s (ms)" % (1e3 * self.tstep)
s += f", data shape : {self.shape}"
sz = sum(object_size(x) for x in (self.vertices + [self.data]))
s += f", ~{sizeof_fmt(sz)}"
return f"<{type(self).__name__} | {s}>"
@fill_doc
def get_peak(
self, tmin=None, tmax=None, mode="abs", vert_as_index=False, time_as_index=False
):
"""Get location and latency of peak amplitude.
Parameters
----------
%(get_peak_parameters)s
Returns
-------
pos : int
The vertex exhibiting the maximum response, either ID or index.
latency : float
The latency in seconds.
"""
stc = self.magnitude() if self._data_ndim == 3 else self
if self._n_vertices == 0:
raise RuntimeError("Cannot find peaks with no vertices")
vert_idx, time_idx, _ = _get_peak(stc.data, self.times, tmin, tmax, mode)
if not vert_as_index:
vert_idx = np.concatenate(self.vertices)[vert_idx]
if not time_as_index:
time_idx = self.times[time_idx]
return vert_idx, time_idx
@verbose
def extract_label_time_course(
self, labels, src, mode="auto", allow_empty=False, verbose=None
):
"""Extract label time courses for lists of labels.
This function will extract one time course for each label. The way the
time courses are extracted depends on the mode parameter.
Parameters
----------
%(labels_eltc)s
%(src_eltc)s
%(mode_eltc)s
%(allow_empty_eltc)s
%(verbose)s
Returns
-------
%(label_tc_el_returns)s
See Also
--------
extract_label_time_course : Extract time courses for multiple STCs.
Notes
-----
%(eltc_mode_notes)s
"""
return extract_label_time_course(
self,
labels,
src,
mode=mode,
return_generator=False,
allow_empty=allow_empty,
verbose=verbose,
)
@verbose
def apply_function(
self, fun, picks=None, dtype=None, n_jobs=None, verbose=None, **kwargs
):
"""Apply a function to a subset of vertices.
%(applyfun_summary_stc)s
Parameters
----------
%(fun_applyfun_stc)s
%(picks_all)s
%(dtype_applyfun)s
%(n_jobs)s Ignored if ``vertice_wise=False`` as the workload
is split across vertices.
%(verbose)s
%(kwargs_fun)s
Returns
-------
self : instance of SourceEstimate
The SourceEstimate object with transformed data.
"""
_check_preload(self, "source_estimate.apply_function")
picks = _picks_to_idx(len(self._data), picks, exclude=(), with_ref_meg=False)
if not callable(fun):
raise ValueError("fun needs to be a function")
data_in = self._data
if dtype is not None and dtype != self._data.dtype:
self._data = self._data.astype(dtype)
# check the dimension of the source estimate data
_check_option("source_estimate.ndim", self._data.ndim, [2, 3])
parallel, p_fun, n_jobs = parallel_func(_check_fun, n_jobs)
if n_jobs == 1:
# modify data inplace to save memory
for idx in picks:
self._data[idx, :] = _check_fun(fun, data_in[idx, :], **kwargs)
else:
# use parallel function
data_picks_new = parallel(
p_fun(fun, data_in[p, :], **kwargs) for p in picks
)
for pp, p in enumerate(picks):
self._data[p, :] = data_picks_new[pp]
return self
@verbose
def apply_baseline(self, baseline=(None, 0), *, verbose=None):
"""Baseline correct source estimate data.
Parameters
----------
%(baseline_stc)s
Defaults to ``(None, 0)``, i.e. beginning of the the data until
time point zero.
%(verbose)s
Returns
-------
stc : instance of SourceEstimate
The baseline-corrected source estimate object.
Notes
-----
Baseline correction can be done multiple times.
"""
self.data = rescale(self.data, self.times, baseline, copy=False)
return self
@verbose
def save(self, fname, ftype="h5", *, overwrite=False, verbose=None):
"""Save the full source estimate to an HDF5 file.
Parameters
----------
fname : path-like
The file name to write the source estimate to, should end in
``'-stc.h5'``.
ftype : str
File format to use. Currently, the only allowed values is ``"h5"``.
%(overwrite)s
.. versionadded:: 1.0
%(verbose)s
"""
fname = _check_fname(fname=fname, overwrite=True) # check below
if ftype != "h5":
raise ValueError(
f"{self.__class__.__name__} objects can only be written as HDF5 files."
)
_, write_hdf5 = _import_h5io_funcs()
if fname.suffix != ".h5":
fname = fname.with_name(f"{fname.name}-stc.h5")
fname = _check_fname(fname=fname, overwrite=overwrite)
write_hdf5(
fname,
dict(
vertices=self.vertices,
data=self.data,
tmin=self.tmin,
tstep=self.tstep,
subject=self.subject,
src_type=self._src_type,
),
title="mnepython",
overwrite=True,
)
@copy_function_doc_to_method_doc(plot_source_estimates)
def plot(
self,
subject=None,
surface="inflated",
hemi="lh",
colormap="auto",
time_label="auto",
smoothing_steps=10,
transparent=True,
alpha=1.0,
time_viewer="auto",
*,
subjects_dir=None,
figure=None,
views="auto",
colorbar=True,
clim="auto",
cortex="classic",
size=800,
background="black",
foreground=None,
initial_time=None,
time_unit="s",
backend="auto",
spacing="oct6",
title=None,
show_traces="auto",
src=None,
volume_options=1.0,
view_layout="vertical",
add_data_kwargs=None,
brain_kwargs=None,
verbose=None,
):
brain = plot_source_estimates(
self,
subject,
surface=surface,
hemi=hemi,
colormap=colormap,
time_label=time_label,
smoothing_steps=smoothing_steps,
transparent=transparent,
alpha=alpha,
time_viewer=time_viewer,
subjects_dir=subjects_dir,
figure=figure,
views=views,
colorbar=colorbar,
clim=clim,
cortex=cortex,
size=size,
background=background,
foreground=foreground,
initial_time=initial_time,
time_unit=time_unit,
backend=backend,
spacing=spacing,
title=title,
show_traces=show_traces,
src=src,
volume_options=volume_options,
view_layout=view_layout,
add_data_kwargs=add_data_kwargs,
brain_kwargs=brain_kwargs,
verbose=verbose,
)
return brain
@property
def sfreq(self):
"""Sample rate of the data."""
return 1.0 / self.tstep
@property
def _n_vertices(self):
return sum(len(v) for v in self.vertices)
def _remove_kernel_sens_data_(self):
"""Remove kernel and sensor space data and compute self._data."""
if self._kernel is not None or self._sens_data is not None:
self._kernel_removed = True
self._data = np.dot(self._kernel, self._sens_data)
self._kernel = None
self._sens_data = None
@fill_doc
def crop(self, tmin=None, tmax=None, include_tmax=True):
"""Restrict SourceEstimate to a time interval.
Parameters
----------
tmin : float | None
The first time point in seconds. If None the first present is used.
tmax : float | None
The last time point in seconds. If None the last present is used.
%(include_tmax)s
Returns
-------
stc : instance of SourceEstimate
The cropped source estimate.
"""
mask = _time_mask(
self.times, tmin, tmax, sfreq=self.sfreq, include_tmax=include_tmax
)
self.tmin = self.times[np.where(mask)[0][0]]
if self._kernel is not None and self._sens_data is not None:
self._sens_data = self._sens_data[..., mask]
else:
self.data = self.data[..., mask]
return self # return self for chaining methods
@verbose
def resample(
self,
sfreq,
*,
npad=100,
method="fft",
window="auto",
pad="auto",
n_jobs=None,
verbose=None,
):
"""Resample data.
If appropriate, an anti-aliasing filter is applied before resampling.
See :ref:`resampling-and-decimating` for more information.
Parameters
----------
sfreq : float
New sample rate to use.
npad : int | str
Amount to pad the start and end of the data.
Can also be "auto" to use a padding that will result in
a power-of-two size (can be much faster).
%(method_resample)s
.. versionadded:: 1.7
%(window_resample)s
.. versionadded:: 1.7
%(pad_resample_auto)s
.. versionadded:: 1.7
%(n_jobs)s
%(verbose)s
Returns
-------
stc : instance of SourceEstimate
The resampled source estimate.
Notes
-----
For some data, it may be more accurate to use npad=0 to reduce
artifacts. This is dataset dependent -- check your data!
Note that the sample rate of the original data is inferred from tstep.
"""
from .filter import _check_resamp_noop
o_sfreq = 1.0 / self.tstep
if _check_resamp_noop(sfreq, o_sfreq):
return self
# resampling in sensor instead of source space gives a somewhat
# different result, so we don't allow it
self._remove_kernel_sens_data_()
data = self.data
if data.dtype == np.float32:
data = data.astype(np.float64)
self.data = resample(
data, sfreq, o_sfreq, npad=npad, window=window, n_jobs=n_jobs, method=method
)
# adjust indirectly affected variables
self.tstep = 1.0 / sfreq
return self
@property
def data(self):
"""Numpy array of source estimate data."""
if self._data is None:
# compute the solution the first time the data is accessed and
# remove the kernel and sensor data
self._remove_kernel_sens_data_()
return self._data
@data.setter
def data(self, value):
value = np.asarray(value)
if self._data is not None and value.ndim != self._data.ndim:
raise ValueError(f"Data array should have {self._data.ndim} dimensions.")
n_verts = sum(len(v) for v in self.vertices)
if value.shape[0] != n_verts:
raise ValueError(
"The first dimension of the data array must match the number of "
f"vertices ({value.shape[0]} != {n_verts})."
)
self._data = value
self._update_times()
@property
def shape(self):
"""Shape of the data."""
if self._data is not None:
return self._data.shape
return (self._kernel.shape[0], self._sens_data.shape[1])
@property
def tmin(self):
"""The first timestamp."""
return self._tmin
@tmin.setter
def tmin(self, value):
self._tmin = float(value)
self._update_times()
@property
def tstep(self):
"""The change in time between two consecutive samples (1 / sfreq)."""
return self._tstep
@tstep.setter
def tstep(self, value):
if value <= 0:
raise ValueError(".tstep must be greater than 0.")
self._tstep = float(value)
self._update_times()
@property
def times(self):
"""A timestamp for each sample."""
return self._times
@times.setter
def times(self, value):
raise ValueError(
"You cannot write to the .times attribute directly. "