-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathprobe.py
More file actions
1651 lines (1374 loc) · 55.8 KB
/
probe.py
File metadata and controls
1651 lines (1374 loc) · 55.8 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
import numpy as np
from typing import Literal
from pathlib import Path
from .shank import Shank
_possible_contact_shapes = ["circle", "square", "rect"]
def _raise_non_unique_positions_error(positions):
"""
Check for duplicate positions and raise ValueError with detailed information.
Parameters
----------
positions : array
Array of positions to check for duplicates.
Raises
------
ValueError
If duplicate positions are found, with detailed information about duplicates.
"""
duplicates = {}
for index, pos in enumerate(positions):
pos_key = tuple(pos)
if pos_key in duplicates:
duplicates[pos_key].append(index)
else:
duplicates[pos_key] = [index]
duplicate_groups = {pos: indices for pos, indices in duplicates.items() if len(indices) > 1}
duplicate_info = []
for pos, indices in duplicate_groups.items():
pos_str = f"({', '.join(map(str, pos))})"
indices_str = f"[{', '.join(map(str, indices))}]"
duplicate_info.append(f"Position {pos_str} appears at indices {indices_str}")
raise ValueError(
f"Contact positions must be unique within a probe. Found {len(duplicate_groups)} duplicate(s): {'; '.join(duplicate_info)}"
)
class Probe:
"""
Class to handle the geometry of one probe.
This class mainly handles contact positions, in 2D or 3D.
Optionally, it can also handle the shape of the
contacts and the shape of the probe.
"""
def __init__(
self,
ndim: int = 2,
si_units: str = "um",
name: str | None = None,
serial_number: str | None = None,
model_name: str | None = None,
manufacturer: str | None = None,
):
"""
Some attributes are protected and have to be set with setters:
* set_contacts(...)
* set_shank_ids(...)
Parameters
----------
ndim: 2 or 3, default: 2
Handles 2D or 3D probe
si_units: "um" | "mm" | "m", default: "um"
The si units to use for the probe
name: str | None, default: None
The name of the probe
serial_number: str | None, default: None
The serial number of the probe
model_name: str | None, default: None
The model of the probe
manufacturer: str | None, default: None
The manufacturer of the probe
Returns
-------
Probe: instance of Probe
"""
assert ndim in (2, 3), "ndim can only be 2 or 3"
self.ndim = int(ndim)
self.si_units = str(si_units)
# contact position and shape : handle with arrays
self._contact_positions = None
self._contact_plane_axes = None
self._contact_shapes = None
self._contact_shape_params = None
# vertices for the shape of the probe
self.probe_planar_contour = None
# the Probe can belong to a ProbeGroup
self._probe_group = None
# This handles the shank id per contact
# If None then one shank only
self._shank_ids = None
# This handles the wiring to device : channel index on device side.
# this is due to complex routing
# This must be unique at Probe AND ProbeGroup level
self.device_channel_indices = None
# Handle ids with str so it can be displayed like names
# This must be unique at Probe AND ProbeGroup level
self._contact_ids = None
# Handle contact side for double face probes
# If None then one face only
self._contact_sides = None
# annotation: a dict that contains all meta information about
# the probe (name, manufacturor, date of production, ...)
self.annotations = dict()
# set key properties
self.name = name
self.serial_number = serial_number
self.model_name = model_name
self.manufacturer = manufacturer
# same idea but handle in vector way for contacts
self.contact_annotations = dict()
@property
def contact_positions(self):
"""The position of the center for each contact"""
return self._contact_positions
@property
def contact_plane_axes(self):
return self._contact_plane_axes
@property
def contact_shapes(self):
return self._contact_shapes
@property
def contact_shape_params(self):
return self._contact_shape_params
@property
def contact_ids(self):
return self._contact_ids
@property
def shank_ids(self):
return self._shank_ids
@property
def contact_sides(self):
return self._contact_sides
@property
def name(self):
return self.annotations.get("name", None)
@name.setter
def name(self, value):
if value is not None:
self.annotate(name=value)
else:
# we remove the annotation if it exists
_ = self.annotations.pop("name", None)
@property
def serial_number(self):
return self.annotations.get("serial_number", None)
@serial_number.setter
def serial_number(self, value):
if value is not None:
self.annotate(serial_number=value)
else:
# we remove the annotation if it exists
_ = self.annotations.pop("serial_number", None)
@property
def model_name(self):
return self.annotations.get("model_name", None)
@model_name.setter
def model_name(self, value):
if value is not None:
self.annotate(model_name=value)
else:
# we remove the annotation if it exists
_ = self.annotations.pop("model_name", None)
@property
def manufacturer(self):
return self.annotations.get("manufacturer", None)
@manufacturer.setter
def manufacturer(self, value):
if value is not None:
self.annotate(manufacturer=value)
else:
# we remove the annotation if it exists
_ = self.annotations.pop("manufacturer", None)
@property
def description(self):
return self.annotations.get("description", None)
@description.setter
def description(self, value):
if value is not None:
self.annotate(description=value)
else:
# we remove the annotation if it exists
_ = self.annotations.pop("description", None)
def get_title(self) -> str:
if self.contact_positions is None:
txt = "Undefined probe"
else:
n = self.get_contact_count()
name = self.name
serial_number = self.serial_number
model_name = self.model_name
manufacturer = self.manufacturer
txt = ""
if name is not None:
txt += f"{name}"
else:
txt += f"Probe"
if manufacturer is not None:
txt += f" - {manufacturer}"
if model_name is not None:
txt += f" - {model_name}"
if serial_number is not None:
txt += f" - {serial_number}"
txt += f" - {n}ch"
if self.shank_ids is not None:
num_shank = self.get_shank_count()
txt += f" - {num_shank}shanks"
if self._contact_sides is not None:
txt += f" - 2 sides"
return txt
def __repr__(self):
return self.get_title()
def annotate(self, **kwargs):
"""
Annotates the probe object.
Parameters
----------
**kwargs : list of keyword arguments to add to the annotations (e.g., brain_area="CA1")
"""
if self._probe_group is not None:
raise ValueError(
"You cannot annotate a probe that belongs to a ProbeGroup. "
"Annotate the probe before adding it to the ProbeGroup or use the `ProbeGroup.annotate_probe` method."
)
self.annotations.update(kwargs)
self.check_annotations()
def annotate_contacts(self, **kwargs):
"""
Annotates the contacts of the probe.
Parameters
----------
**kwargs : list of keyword arguments to add to the annotations (e.g., quality=["good", "bad", ...])
"""
if self._probe_group is not None:
raise ValueError(
"You cannot annotate contacts of a probe that belongs to a ProbeGroup. "
"Annotate the probe before adding it to the ProbeGroup instead."
)
n = self.get_contact_count()
for k, values in kwargs.items():
assert len(values) == n, (
f"annotate_contacts requires a list or array as values with length {n}, "
f"you entered a value of type: {type(values)} and length of {len(values)}"
)
values = np.asarray(values)
self.contact_annotations[k] = values
def check_annotations(self):
d = self.annotations
if "first_index" in d:
assert d["first_index"] in (0, 1), f"The 'first_index' must be 0 or 1, it is currently {d['first_index']}"
def get_contact_count(self) -> int:
"""
Return the number of contacts on the probe.
"""
assert self.contact_positions is not None
return len(self.contact_positions)
def get_shank_count(self) -> int:
"""
Return the number of shanks for this probe.
"""
# assert self.shank_ids is not None
if self.shank_ids is None:
n = 1
else:
n = len(np.unique(self.shank_ids))
return n
def set_contacts(
self,
positions,
shapes="circle",
shape_params={"radius": 10},
plane_axes=None,
contact_ids=None,
shank_ids=None,
contact_sides=None,
):
"""Sets contacts to a Probe.
This sets four attributes of the probe:
contact_positions,
contact_shapes,
contact_shape_params,
_contact_plane_axes
Parameters
----------
positions : array (num_contacts, ndim)
Positions of contacts (2D or 3D depending on probe 'ndim').
shapes : "circle" | "square" | "rect" | array, default: "circle"
Shape of each contact ('circle'/'square'/'rect').
shape_params : dict or list of dict, default: {"radius": 10}
Contains kwargs for shapes:
* "radius" for circle
* "width" for square,
* "width/height" for rect
plane_axes : np.array (num_contacts, 2, ndim) | None, default: None
Defines the two axes of the contact plane for each electrode.
The third dimension corresponds to the probe `ndim` (2d or 3d).
contact_ids: array[str] | None, default: None
Defines the contact ids for the contacts. If None, contact ids are not assigned.
shank_ids : array[str] | None, default: None
Defines the shank ids for the contacts. If None, then
these are assigned to a unique Shank.
contact_sides : array[str] | None, default: None
If probe is double sided, defines sides by a vector of ['front' | 'back']
"""
positions = np.array(positions)
if positions.shape[1] != self.ndim:
raise ValueError(f"positions.shape[1]: {positions.shape[1]} and ndim: {self.ndim} do not match!")
if contact_sides is None:
# Check for duplicate positions
unique_positions = np.unique(positions, axis=0)
positions_are_not_unique = unique_positions.shape[0] != positions.shape[0]
if positions_are_not_unique:
_raise_non_unique_positions_error(positions)
else:
# Check for duplicate positions side by side
contact_sides = np.asarray(contact_sides).astype(str)
for side in ("front", "back"):
mask = contact_sides == side
unique_positions = np.unique(positions[mask], axis=0)
positions_are_not_unique = unique_positions.shape[0] != positions[mask].shape[0]
if positions_are_not_unique:
_raise_non_unique_positions_error(positions[mask])
self._contact_positions = positions
n = positions.shape[0]
# This defines the contact plane (2D or 3D) along which the contacts lie.
# For 2D we make auto
if plane_axes is None:
if self.ndim == 3:
raise ValueError("For ndim==3, you need to give a 'plane_axes'")
else:
plane_axes = np.zeros((n, 2, self.ndim))
plane_axes[:, 0, 0] = 1
plane_axes[:, 1, 1] = 1
plane_axes = np.array(plane_axes)
self._contact_plane_axes = plane_axes
if contact_ids is not None:
self.set_contact_ids(contact_ids)
if shank_ids is None:
# self._shank_ids = np.zeros(n, dtype=str)
self._shank_ids = None
else:
self._shank_ids = np.asarray(shank_ids).astype(str)
if self.shank_ids.size != n:
raise ValueError(f"shank_ids have wrong size: {self.shanks.ids.size} != {n}")
if contact_sides is None:
self._contact_sides = contact_sides
else:
self._contact_sides = contact_sides
if self._contact_sides.size != n:
raise ValueError(f"contact_sides have wrong size: {self._contact_sides.ids.size} != {n}")
if not np.all(np.isin(self._contact_sides, ["front", "back"])):
raise ValueError(f"contact_sides must 'front' or 'back'")
# shape
if isinstance(shapes, str):
shapes = [shapes] * n
shapes = np.array(shapes)
if not np.all(np.isin(shapes, _possible_contact_shapes)):
raise ValueError(f"contacts shape must be in {_possible_contact_shapes}")
if shapes.shape[0] != n:
raise ValueError(f"contacts shape {shapes.shape[0]} must have same length as positions {n}")
self._contact_shapes = np.array(shapes)
# shape params
if isinstance(shape_params, dict):
shape_params = [shape_params] * n
self._contact_shape_params = np.array(shape_params)
def set_planar_contour(self, contour_polygon: list):
"""Set the planar contour (the shape) of the probe.
Parameters
----------
contour_polygon : list
List of contour points (2D or 3D depending on ndim)
"""
contour_polygon = np.asarray(contour_polygon)
if contour_polygon.shape[1] != self.ndim:
raise ValueError(f"contour_polygon.shape[1] {contour_polygon.shape[1]} and ndim {self.ndim} do not match!")
self.probe_planar_contour = contour_polygon
def create_auto_shape(self, probe_type: Literal["tip", "rect", "circular"] = "tip", margin: float = 20.0):
"""Create a planar contour automatically based on probe contact positions.
This function generates a 2D polygon that outlines the shape of the probe, adjusted
by a specified margin. The resulting contour is set as the planar contour of the probe.
Parameters
----------
probe_type : {"tip", "rect", "circular"}, default: "tip"
The type of probe used to collect contact data:
* "tip": Assumes a single-point contact probe. The generated contour is
a rectangle with a triangular "tip" extending downwards.
* "rect": Assumes a rectangular contact probe. The generated contour is
a rectangle.
* "circular": Assumes a circular contact probe. The generated contour
is a circle.
margin : float, default: 20.0
The margin to add around the contact positions. The behavior varies by
probe type:
* "tip": The margin is added around the rectangular portion of the contour
and to the base of the tip. The tip itself is extended downwards by
four times the margin value.
* "rect": The margin is added evenly around all sides of the rectangle.
* "circular": The margin is added to the radius of the circle.
Notes
-----
This function is designed for 2D data only. If you have 3D data, consider projecting
it onto a plane before using this method.
"""
if self.ndim != 2:
raise ValueError(f"Auto shape is supported only for 2d, you have ndim {self.ndim}")
if self._shank_ids is None:
shank_ids = np.zeros((self.get_contact_count()), dtype="int64")
else:
shank_ids = self._shank_ids
polygon = []
for i, shank_id in enumerate(np.unique(shank_ids)):
mask = shank_ids == shank_id
x0 = np.min(self.contact_positions[mask, 0])
x1 = np.max(self.contact_positions[mask, 0])
x0 -= margin
x1 += margin
y0 = np.min(self.contact_positions[:, 1])
y1 = np.max(self.contact_positions[:, 1])
y0 -= margin
y1 += margin
if probe_type == "rect":
polygon += [
(x0, y1),
(x0, y0),
(x1, y0),
(x1, y1),
]
elif probe_type == "tip":
tip = ((x0 + x1) * 0.5, y0 - margin * 4)
polygon += [
(x0, y1),
(x0, y0),
tip,
(x1, y0),
(x1, y1),
]
elif probe_type == "circular":
radius_x = (x1 - x0) / 2
radius_y = (y1 - y0) / 2
center = ((x0 + x1) / 2, (y0 + y1) / 2)
radius = max(radius_x, radius_y) + margin
num_vertices = 100
theta = np.linspace(0, 2 * np.pi, num_vertices, endpoint=False)
x = center[0] + radius * np.cos(theta)
y = center[1] + radius * np.sin(theta)
vertices = np.vstack((x, y)).T
polygon += vertices.tolist()
else:
raise ValueError(f"'probe_type' can only be 'rect, 'tip' or 'circular', you have entered {probe_type}")
self.set_planar_contour(polygon)
def set_device_channel_indices(self, channel_indices: np.ndarray | list):
"""
Manually set the device channel indices.
If some channels are not connected or not recorded then channel should be set to "-1"
Parameters
----------
channel_indices : array[int] | list[int]
The device channel indices to set
"""
channel_indices = np.asarray(channel_indices, dtype=int)
if channel_indices.size != self.get_contact_count():
ValueError(
f"channel_indices {channel_indices.size} do not have "
f"the same size as contacts {self.get_contact_count()}"
)
self.device_channel_indices = channel_indices
if self._probe_group is not None:
self._probe_group.check_global_device_wiring_and_ids()
def wiring_to_device(self, pathway: str, channel_offset: int = 0):
"""
Automatically set device_channel_indices based on a pathway.
See probeinterface.get_available_pathways()
Parameters
----------
pathway : str
The pathway. E.g. 'H32>RHD'
channel_offset: int, default: 0
An optional offset to add to the device_channel_indices
"""
from .wiring import wire_probe
wire_probe(self, pathway, channel_offset=channel_offset)
def set_contact_ids(self, contact_ids: np.ndarray | list):
"""
Set contact ids. Channel ids are converted to strings.
Contact ids must be **unique** for the **Probe**
and also for the **ProbeGroup**
Parameters
----------
contact_ids : list or array
Array with contact ids. If contact_ids are int or float they are converted to str
"""
contact_ids = np.asarray(contact_ids)
if np.all([c == "" for c in contact_ids]):
self._contact_ids = None
return
if contact_ids.size != self.get_contact_count():
raise ValueError(
f"contact_ids {contact_ids.size} do not have the same size "
f"as number of contacts {self.get_contact_count()}"
)
if np.unique(contact_ids).size != contact_ids.size:
raise ValueError("contact_ids must be unique within a Probe")
if contact_ids.dtype.kind != "U":
contact_ids = contact_ids.astype("U")
self._contact_ids = contact_ids
if self._probe_group is not None:
self._probe_group.check_global_device_wiring_and_ids()
def set_shank_ids(self, shank_ids: np.ndarray | list):
"""
Set shank ids.
Parameters
----------
shank_ids : list or array
Array with shank ids, if int or float converted to strings
"""
shank_ids = np.asarray(shank_ids).astype(str)
if shank_ids.size != self.get_contact_count():
raise ValueError(
f"shank_ids have wrong size. Has to match number " f"of contacts: {self.get_contact_count()}"
)
self._shank_ids = shank_ids
def get_shanks(self):
"""
Return the list of Shank objects for this Probe
"""
# assert self.shank_ids is not None, "Can only get shanks if `shank_ids` exist"
if self.shank_ids is None:
# has a unique shank
shanks = [Shank(probe=self, shank_id=None)]
else:
shanks = []
for shank_id in np.unique(self.shank_ids):
shank = Shank(probe=self, shank_id=shank_id)
shanks.append(shank)
return shanks
def __eq__(self, other):
if not isinstance(other, Probe):
return False
if not (
self.ndim == other.ndim
and self.si_units == other.si_units
and self.name == other.name
and self.serial_number == other.serial_number
and self.model_name == other.model_name
and self.manufacturer == other.manufacturer
and np.array_equal(self._contact_positions, other._contact_positions)
and np.array_equal(self._contact_plane_axes, other._contact_plane_axes)
and np.array_equal(self._contact_shapes, other._contact_shapes)
and np.array_equal(self._contact_shape_params, other._contact_shape_params)
and np.array_equal(self.probe_planar_contour, other.probe_planar_contour)
and np.array_equal(self._shank_ids, other._shank_ids)
and np.array_equal(self.device_channel_indices, other.device_channel_indices)
and np.array_equal(self._contact_ids, other._contact_ids)
and self.annotations == other.annotations
):
return False
if self._contact_sides is None:
if other._contact_sides is not None:
return False
else:
if not np.array_equal(self._contact_sides, other._contact_sides):
return False
# Compare contact_annotations dictionaries
if self.contact_annotations.keys() != other.contact_annotations.keys():
return False
for key in self.contact_annotations:
if not np.array_equal(self.contact_annotations[key], other.contact_annotations[key]):
return False
# planar contour
if self.probe_planar_contour is not None:
if other.probe_planar_contour is None:
return False
if not np.array_equal(self.probe_planar_contour, other.probe_planar_contour):
return False
return True
def copy(self):
"""
Copy to another Probe instance.
Note: device_channel_indices are not copied
and contact_ids are not copied
"""
other = Probe()
other.set_contacts(
positions=self.contact_positions.copy(),
plane_axes=self.contact_plane_axes.copy(),
shapes=self.contact_shapes.copy(),
shape_params=self.contact_shape_params.copy(),
)
if self.probe_planar_contour is not None:
other.set_planar_contour(self.probe_planar_contour.copy())
# channel_indices are not copied
return other
def to_3d(self, axes: Literal["xy", "yz", "xz"] = "xz"):
"""
Transform 2d probe to 3d probe.
Note: device_channel_indices are not copied.
Parameters
----------
axes : "xy" | "yz" | "xz", default: "xz"
The axes that define the plane on which the 2D probe is defined. 'xy', 'yz' ', xz'
"""
assert self.ndim == 2, "to convert to_3d you should start with a 2d probe"
probe3d = Probe(ndim=3, si_units=self.si_units)
# contacts
positions = _2d_to_3d(self.contact_positions, axes)
plane0 = _2d_to_3d(self.contact_plane_axes[:, 0, :], axes)
plane1 = _2d_to_3d(self.contact_plane_axes[:, 1, :], axes)
plane_axes = np.concatenate([plane0[:, np.newaxis, :], plane1[:, np.newaxis, :]], axis=1)
probe3d.set_contacts(
positions=positions,
plane_axes=plane_axes,
shapes=self.contact_shapes.copy(),
shape_params=self.contact_shape_params.copy(),
)
# shape
if self.probe_planar_contour is not None:
vertices3d = _2d_to_3d(self.probe_planar_contour, axes)
probe3d.set_planar_contour(vertices3d)
if self.device_channel_indices is not None:
probe3d.device_channel_indices = self.device_channel_indices
return probe3d
def to_2d(self, axes: Literal["xy", "yz", "xz"] = "xy"):
"""
Transform 3d probe to 2d probe.
Note: device_channel_indices are not copied.
Parameters
----------
plane : "xy" | "yz" | "xz", default: "xy"
The plane on which the 2D probe is defined.
"""
assert self.ndim == 3, "To use to_2d you should start with a 3d probe"
probe2d = Probe(ndim=2, si_units=self.si_units)
# contacts
positions = _3d_to_2d(self.contact_positions, axes)
probe2d.set_contacts(
positions=positions, shapes=self.contact_shapes.copy(), shape_params=self.contact_shape_params.copy()
)
# shape
if self.probe_planar_contour is not None:
vertices3d = _3d_to_2d(self.probe_planar_contour, axes)
probe2d.set_planar_contour(vertices3d)
if self.device_channel_indices is not None:
probe2d.device_channel_indices = self.device_channel_indices
return probe2d
def get_contact_vertices(self) -> list:
"""
Return a list of contact vertices.
"""
vertices = []
for i in range(self.get_contact_count()):
shape = self.contact_shapes[i]
shape_param = self.contact_shape_params[i]
plane_axe = self.contact_plane_axes[i]
pos = self.contact_positions[i]
if shape == "circle":
r = shape_param["radius"]
theta = np.linspace(0, 2 * np.pi, 360)
theta = np.tile(theta[:, np.newaxis], [1, self.ndim])
one_vertice = pos + r * np.cos(theta) * plane_axe[0] + r * np.sin(theta) * plane_axe[1]
elif shape == "square":
w = shape_param["width"]
one_vertice = [
pos - w / 2 * plane_axe[0] - w / 2 * plane_axe[1],
pos - w / 2 * plane_axe[0] + w / 2 * plane_axe[1],
pos + w / 2 * plane_axe[0] + w / 2 * plane_axe[1],
pos + w / 2 * plane_axe[0] - w / 2 * plane_axe[1],
]
one_vertice = np.array(one_vertice)
elif shape == "rect":
w = shape_param["width"]
h = shape_param["height"]
one_vertice = [
pos - w / 2 * plane_axe[0] - h / 2 * plane_axe[1],
pos - w / 2 * plane_axe[0] + h / 2 * plane_axe[1],
pos + w / 2 * plane_axe[0] + h / 2 * plane_axe[1],
pos + w / 2 * plane_axe[0] - h / 2 * plane_axe[1],
]
one_vertice = np.array(one_vertice)
else:
raise ValueError(f"'shape' of {shape} is not supported")
vertices.append(one_vertice)
return vertices
def move(self, translation_vector: np.ndarray | list):
"""
Translate the probe in one direction.
Parameters
----------
translation_vector : list or array
The translation vector in shape 2D or 3D
"""
translation_vector = np.asarray(translation_vector)
assert translation_vector.shape[0] == self.ndim
self._contact_positions += translation_vector
if self.probe_planar_contour is not None:
self.probe_planar_contour += translation_vector
def rotate(
self, theta: float, center: list | np.ndarray | None = None, axis: Literal["xy", "yz", "xz"] | None = None
):
"""
Rotate the probe around a specified axis.
Parameters
----------
theta : float
In degrees, anticlockwise/counterclockwise
center : array | list | None, default: None
Center of rotation. If None, the center of probe is used
axis : "xy" | "yz" | "xz" | None, default: None
Axis of rotation.
It must be None for 2D probes
It must be given for 3D probes
"""
if center is None:
center = np.mean(self.contact_positions, axis=0)
center = np.asarray(center)
assert center.size == self.ndim, f"If center given it must have size of ndim: {center.size} != {self.ndim}"
center = center[None, :]
theta = np.deg2rad(theta)
if self.ndim == 2:
assert axis is None, "axis must be None for 2d probes"
R = _rotation_matrix_2d(theta)
elif self.ndim == 3:
assert axis is not None, "axis must be specified for 3d probes"
R = _rotation_matrix_3d(axis, theta).T
new_positions = (self.contact_positions - center) @ R + center
new_plane_axes = np.zeros_like(self.contact_plane_axes)
for i in range(2):
new_plane_axes[:, i, :] = (
(self.contact_plane_axes[:, i, :] - center + self.contact_positions) @ R + center - new_positions
)
self._contact_positions = new_positions
self._contact_plane_axes = new_plane_axes
if self.probe_planar_contour is not None:
new_vertices = (self.probe_planar_contour - center) @ R + center
self.probe_planar_contour = new_vertices
def rotate_contacts(self, thetas: float | np.ndarray[float] | list[float]):
"""
Rotate each contact of the probe.
Internally, it modifies the contact_plane_axes.
Parameters
----------
thetas : float | array[float] | list[float]
Rotation angle in degrees.
If scalar, then it is applied to all contacts.
"""
if self.ndim == 3:
raise ValueError("By contact rotation is implemented only for 2d")
n = self.get_contact_count()
if isinstance(thetas, (int, float)):
thetas = np.array([thetas] * n, dtype="float64")
thetas = np.deg2rad(thetas)
for e in range(n):
R = _rotation_matrix_2d(thetas[e])
for i in range(2):
self.contact_plane_axes[e, i, :] = self.contact_plane_axes[e, i, :] @ R
_dump_attr_names = [
"ndim",
"si_units",
"annotations",
"contact_annotations",
"_contact_positions",
"_contact_plane_axes",
"_contact_shapes",
"_contact_shape_params",
"probe_planar_contour",
"device_channel_indices",
"_contact_ids",
"_shank_ids",
"_contact_sides",
]
def to_dict(self, array_as_list: bool = False) -> dict:
"""Create a dictionary of all necessary attributes.
Useful for dumping and saving to json.
Parameters
----------
array_as_list : bool, default: False
If True, arrays are converted to lists
Returns
-------
d : dict
The dictionary representation of the probe
"""
d = {}
for k in self._dump_attr_names:
v = getattr(self, k, None)
if array_as_list and isinstance(v, dict):
for kk, vv in v.items():
if isinstance(vv, np.ndarray):
v[kk] = vv.tolist()
if array_as_list and v is not None and isinstance(v, np.ndarray):
v = v.tolist()
if v is not None:
if k.startswith("_"):
d[k[1:]] = v
else:
d[k] = v
return d
@staticmethod
def from_dict(d: dict) -> "Probe":
"""Instantiate a Probe from a dictionary
Parameters
----------
d : dict
The dictionary representation of the probe
Returns
-------
probe : Probe
The instantiated Probe object
"""
probe = Probe(ndim=d["ndim"], si_units=d["si_units"])
shank_ids = d.get("shank_ids", None)
if shank_ids is not None and np.all([s == "" for s in shank_ids]):
# backward compatible hack with previous version
shank_ids = None
probe.set_contacts(
positions=d["contact_positions"],
plane_axes=d["contact_plane_axes"],
shapes=d["contact_shapes"],
shape_params=d["contact_shape_params"],
contact_ids=d.get("contact_ids", None),
shank_ids=shank_ids,
contact_sides=d.get("contact_sides", None),
)
v = d.get("probe_planar_contour", None)
if v is not None:
probe.set_planar_contour(v)
v = d.get("device_channel_indices", None)
if v is not None:
probe.set_device_channel_indices(v)
if "annotations" in d:
probe.annotate(**d["annotations"])
if "contact_annotations" in d:
probe.annotate_contacts(**d["contact_annotations"])
return probe
def to_numpy(self, complete: bool = False, probe_index: int | None = None) -> np.ndarray:
"""
Export the probe to a numpy structured array.
This array handles all contact attributes.
Similar to the 'to_dataframe()' pandas function, but without pandas dependency.
The intended use is to attach this array to a recording object as a property ("contact vector")
Parameters
----------