sortingview 0.15.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. examples/example_autocorrelograms.py +33 -0
  2. examples/example_average_waveforms.py +82 -0
  3. examples/example_box_layout.py +70 -0
  4. examples/example_confusion_matrix.py +97 -0
  5. examples/example_cross_correlograms.py +36 -0
  6. examples/example_image.py +19 -0
  7. examples/example_markdown.py +41 -0
  8. examples/example_mountain_layout.py +54 -0
  9. examples/example_plotly.py +21 -0
  10. examples/example_position_plot.py +29 -0
  11. examples/example_raster_plot.py +34 -0
  12. examples/example_sorting_curation.py +33 -0
  13. examples/example_spike_amplitudes.py +47 -0
  14. examples/example_spike_locations.py +77 -0
  15. examples/example_splitter_layout.py +64 -0
  16. examples/example_tab_layout.py +44 -0
  17. examples/example_tiled_image.py +70 -0
  18. examples/example_timeseries_graph.py +49 -0
  19. examples/example_track_position_animation.py +76 -0
  20. examples/example_unit_locations.py +53 -0
  21. examples/example_unit_metrics_graph.py +44 -0
  22. examples/example_unit_similarity_matrix.py +35 -0
  23. examples/example_units_table.py +49 -0
  24. examples/helpers/compute_correlogram_data.py +66 -0
  25. examples/helpers/create_units_table.py +12 -0
  26. sortingview/SpikeSortingView/Figure.py +46 -0
  27. sortingview/SpikeSortingView/MultiTimeseries.py +29 -0
  28. sortingview/SpikeSortingView/SpikeSortingView.py +172 -0
  29. sortingview/SpikeSortingView/__init__.py +10 -0
  30. sortingview/SpikeSortingView/_autocorrelograms_view.py +22 -0
  31. sortingview/SpikeSortingView/_average_waveforms_view.py +32 -0
  32. sortingview/SpikeSortingView/_create_autocorrelograms.py +23 -0
  33. sortingview/SpikeSortingView/_create_average_waveforms.py +40 -0
  34. sortingview/SpikeSortingView/_create_electrode_geometry.py +19 -0
  35. sortingview/SpikeSortingView/_create_live_cross_correlograms.py +15 -0
  36. sortingview/SpikeSortingView/_create_mountain_layout.py +26 -0
  37. sortingview/SpikeSortingView/_create_raster_plot.py +32 -0
  38. sortingview/SpikeSortingView/_create_spike_amplitudes.py +35 -0
  39. sortingview/SpikeSortingView/_create_summary.py +34 -0
  40. sortingview/SpikeSortingView/_create_units_table.py +46 -0
  41. sortingview/SpikeSortingView/_cross_correlograms_view.py +24 -0
  42. sortingview/SpikeSortingView/_electrode_geometry_view.py +14 -0
  43. sortingview/SpikeSortingView/_raster_plot_view.py +31 -0
  44. sortingview/SpikeSortingView/_sorting_summary_view.py +32 -0
  45. sortingview/SpikeSortingView/_spike_amplitudes_view.py +31 -0
  46. sortingview/SpikeSortingView/_units_table_view.py +45 -0
  47. sortingview/SpikeSortingView/create_console_view.py +8 -0
  48. sortingview/SpikeSortingView/create_epochs.py +8 -0
  49. sortingview/SpikeSortingView/create_position_pdf_plot.py +54 -0
  50. sortingview/SpikeSortingView/create_position_plot.py +38 -0
  51. sortingview/SpikeSortingView/create_raw_traces_plot.py +8 -0
  52. sortingview/SpikeSortingView/create_spike_raster_plot.py +15 -0
  53. sortingview/SpikeSortingView/helpers/__init__.py +0 -0
  54. sortingview/SpikeSortingView/helpers/compute_correlogram_data.py +63 -0
  55. sortingview/SpikeSortingView/prepare_spikesortingview_data.py +258 -0
  56. sortingview/__init__.py +1 -0
  57. sortingview/figpack_backend.py +730 -0
  58. sortingview/sortingview_view_url.py +3 -0
  59. sortingview/version.py +2 -0
  60. sortingview/views/Autocorrelograms.py +34 -0
  61. sortingview/views/AverageWaveforms.py +77 -0
  62. sortingview/views/Box.py +32 -0
  63. sortingview/views/ConfusionMatrix.py +55 -0
  64. sortingview/views/CrossCorrelograms.py +36 -0
  65. sortingview/views/ElectrodeGeometry.py +19 -0
  66. sortingview/views/EphysTraces.py +23 -0
  67. sortingview/views/Image.py +39 -0
  68. sortingview/views/LayoutItem.py +39 -0
  69. sortingview/views/Markdown.py +19 -0
  70. sortingview/views/MountainLayout.py +37 -0
  71. sortingview/views/PlotlyFigure.py +20 -0
  72. sortingview/views/PositionPlot.py +58 -0
  73. sortingview/views/RasterPlot.py +36 -0
  74. sortingview/views/SortingCuration.py +18 -0
  75. sortingview/views/SortingCuration2.py +24 -0
  76. sortingview/views/SortingSelection.py +21 -0
  77. sortingview/views/SortingSummary.py +52 -0
  78. sortingview/views/SpikeAmplitudes.py +44 -0
  79. sortingview/views/SpikeLocations.py +59 -0
  80. sortingview/views/Splitter.py +26 -0
  81. sortingview/views/TabLayout.py +32 -0
  82. sortingview/views/TiledImage.py +116 -0
  83. sortingview/views/TimeseriesGraph.py +158 -0
  84. sortingview/views/UnitImages.py +41 -0
  85. sortingview/views/UnitLocations.py +36 -0
  86. sortingview/views/UnitMetricsGraph.py +47 -0
  87. sortingview/views/UnitSimilarityMatrix.py +34 -0
  88. sortingview/views/UnitsTable.py +51 -0
  89. sortingview/views/View.py +176 -0
  90. sortingview/views/__init__.py +31 -0
  91. sortingview/views/franklab/DecodedLinearPositionV1.py +43 -0
  92. sortingview/views/franklab/TrackPositionAnimationV1.py +187 -0
  93. sortingview/views/franklab/__init__.py +2 -0
  94. sortingview-0.15.0.dist-info/METADATA +25 -0
  95. sortingview-0.15.0.dist-info/RECORD +119 -0
  96. sortingview-0.15.0.dist-info/WHEEL +5 -0
  97. sortingview-0.15.0.dist-info/licenses/LICENSE +201 -0
  98. sortingview-0.15.0.dist-info/top_level.txt +3 -0
  99. tests/helpers/compute_correlogram_data.py +66 -0
  100. tests/test_autocorrelograms.py +32 -0
  101. tests/test_average_waveforms.py +71 -0
  102. tests/test_confusion_matrix.py +95 -0
  103. tests/test_cross_correlograms.py +35 -0
  104. tests/test_large_timeseries_graph.py +46 -0
  105. tests/test_layout.py +65 -0
  106. tests/test_markdown.py +38 -0
  107. tests/test_position_plot.py +27 -0
  108. tests/test_raster_plot.py +32 -0
  109. tests/test_sorting_curation_2.py +37 -0
  110. tests/test_sorting_selection.py +68 -0
  111. tests/test_spike_amplitudes.py +37 -0
  112. tests/test_spike_locations.py +74 -0
  113. tests/test_tab_layout.py +45 -0
  114. tests/test_tiled_image.py +68 -0
  115. tests/test_track_position_animation.py +73 -0
  116. tests/test_unit_locations.py +59 -0
  117. tests/test_unit_metrics_graph.py +41 -0
  118. tests/test_unit_similarity_matrix.py +33 -0
  119. tests/test_units_table.py +40 -0
@@ -0,0 +1,44 @@
1
+ import numpy as np
2
+ from typing import List, Union
3
+ from .View import View
4
+
5
+
6
+ class SpikeAmplitudesItem:
7
+ """
8
+ Spike amplitudes for a single unit
9
+ """
10
+
11
+ def __init__(self, unit_id: Union[int, str], spike_times_sec: np.ndarray, spike_amplitudes: np.ndarray) -> None:
12
+ self.unit_id = unit_id
13
+ self.spike_times_sec = spike_times_sec
14
+ self.spike_amplitudes = spike_amplitudes
15
+
16
+ def to_dict(self):
17
+ ret = {"unitId": self.unit_id, "spikeTimesSec": self.spike_times_sec, "spikeAmplitudes": self.spike_amplitudes}
18
+ return ret
19
+
20
+
21
+ class SpikeAmplitudes(View):
22
+ """
23
+ Spike amplitudes view
24
+ """
25
+
26
+ def __init__(self, *, start_time_sec: float, end_time_sec: float, plots: List[SpikeAmplitudesItem], hide_unit_selector: bool = False, **kwargs) -> None:
27
+ super().__init__("SpikeAmplitudes", **kwargs)
28
+ self._start_time_sec = start_time_sec
29
+ self._end_time_sec = end_time_sec
30
+ self._plots = plots
31
+ self._hide_unit_selector = hide_unit_selector
32
+
33
+ def to_dict(self) -> dict:
34
+ ret = {
35
+ "type": self.type,
36
+ "startTimeSec": self._start_time_sec,
37
+ "endTimeSec": self._end_time_sec,
38
+ "units": [a.to_dict() for a in self._plots],
39
+ "hideUnitSelector": self._hide_unit_selector,
40
+ }
41
+ return ret
42
+
43
+ def child_views(self) -> List[View]:
44
+ return []
@@ -0,0 +1,59 @@
1
+ from typing import Any, Dict, List, Tuple, Union
2
+ import numpy as np
3
+ from .View import View
4
+
5
+
6
+ class SpikeLocationsItem:
7
+ """
8
+ Single unit spike locations
9
+ """
10
+
11
+ def __init__(self, unit_id: Union[int, str], spike_times_sec: np.ndarray, x_locations: np.ndarray, y_locations: np.ndarray) -> None:
12
+ self.unit_id = unit_id
13
+ self.spike_times_sec = spike_times_sec
14
+ self.x_locations = x_locations
15
+ self.y_locations = y_locations
16
+
17
+ def to_dict(self):
18
+ ret = {"unitId": self.unit_id, "spikeTimesSec": self.spike_times_sec, "xLocations": self.x_locations, "yLocations": self.y_locations}
19
+ return ret
20
+
21
+
22
+ class SpikeLocations(View):
23
+ """
24
+ Spike locations view
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ units: List[SpikeLocationsItem],
30
+ *,
31
+ x_range: Tuple[float, float],
32
+ y_range: Tuple[float, float],
33
+ hide_unit_selector: bool,
34
+ channel_locations: Dict[str, Any],
35
+ disable_auto_rotate: bool = False,
36
+ **kwargs
37
+ ) -> None:
38
+ super().__init__("SpikeLocations", **kwargs)
39
+ self._units = units
40
+ self._x_range = x_range
41
+ self._y_range = y_range
42
+ self._hide_unit_selector = hide_unit_selector
43
+ self._channel_locations = channel_locations
44
+ self._disable_auto_rotate = disable_auto_rotate
45
+
46
+ def to_dict(self) -> dict:
47
+ ret = {
48
+ "type": self.type,
49
+ "units": [a.to_dict() for a in self._units],
50
+ "xRange": [self._x_range[0], self._x_range[1]],
51
+ "yRange": [self._y_range[0], self._y_range[1]],
52
+ "hideUnitSelector": self._hide_unit_selector,
53
+ "channelLocations": self._channel_locations,
54
+ "disableAutoRotate": self._disable_auto_rotate,
55
+ }
56
+ return ret
57
+
58
+ def child_views(self) -> List[View]:
59
+ return []
@@ -0,0 +1,26 @@
1
+ from typing import List, Literal
2
+ from .LayoutItem import LayoutItem
3
+ from .View import View
4
+
5
+
6
+ class Splitter(View):
7
+ """
8
+ Splitter layout - resizeable along the direction of the layout
9
+ """
10
+
11
+ def __init__(self, item1: LayoutItem, item2: LayoutItem, *, direction: Literal["horizontal", "vertical"], **kwargs) -> None:
12
+ super().__init__("Splitter", is_layout=True, **kwargs)
13
+ self._items = [item1, item2]
14
+ self._direction = direction
15
+
16
+ def to_dict(self) -> dict:
17
+ ret = {
18
+ "type": self.type,
19
+ "direction": self._direction,
20
+ "items": [item.view.to_dict() if item.view.is_layout else {"type": "View", "viewId": item.view.id} for item in self._items],
21
+ "itemProperties": [item.properties_dict() for item in self._items],
22
+ }
23
+ return ret
24
+
25
+ def child_views(self) -> List[View]:
26
+ return [item.view for item in self._items]
@@ -0,0 +1,32 @@
1
+ from typing import List, Literal
2
+ from .View import View
3
+
4
+
5
+ class TabLayoutItem:
6
+ def __init__(self, *, label: str, view: View) -> None:
7
+ self.label = label
8
+ self.view = view
9
+
10
+
11
+ class TabLayout(View):
12
+ """
13
+ Tab layout
14
+ """
15
+
16
+ def __init__(self, items: List[TabLayoutItem], tab_bar_layout: Literal["horizontal", "vertical"] = "horizontal", **kwargs) -> None:
17
+ super().__init__("TabLayout", is_layout=True, **kwargs)
18
+ self._items = items
19
+ self._tab_bar_layout = tab_bar_layout
20
+
21
+ def to_dict(self) -> dict:
22
+ ret = {
23
+ "type": self.type,
24
+ "items": [item.view.to_dict() if item.view.is_layout else {"type": "View", "viewId": item.view.id} for item in self._items],
25
+ "itemProperties": [{"label": item.label} for item in self._items],
26
+ }
27
+ if self._tab_bar_layout != "horizontal":
28
+ ret["tabBarLayout"] = self._tab_bar_layout
29
+ return ret
30
+
31
+ def child_views(self) -> List[View]:
32
+ return [item.view for item in self._items]
@@ -0,0 +1,116 @@
1
+ from concurrent.futures import ThreadPoolExecutor
2
+ from tempfile import TemporaryDirectory
3
+ import os
4
+ from typing import Any, List, Union
5
+ import numpy as np
6
+ import kachery as ka
7
+ from .View import View
8
+
9
+ pyvips_installation_msg = "To use TiledImage you need to install pyvips (conda recommended)"
10
+
11
+
12
+ class TiledImageLayer:
13
+ def __init__(self, label: str, data: Union[np.ndarray, Any]) -> None:
14
+ try:
15
+ import pyvips
16
+ except ImportError:
17
+ raise ImportError(pyvips_installation_msg)
18
+ self.label = label
19
+ self.data = data
20
+ if isinstance(data, pyvips.Image):
21
+ image: pyvips.Image = data
22
+ else:
23
+ assert data.dtype == np.uint8, "Data must be of type uint8"
24
+ image: pyvips.Image = pyvips.Image.new_from_array(data) # type: ignore
25
+ self.image = image
26
+
27
+
28
+ class TiledImage(View):
29
+ def __init__(self, *, tile_size: int, layers: List[TiledImageLayer], verbose=False, **kwargs) -> None:
30
+ # try:
31
+ # import pyvips
32
+ # except ImportError:
33
+ # raise ImportError(pyvips_installation_msg)
34
+ super().__init__("TiledImage", **kwargs)
35
+ self._tile_size = tile_size
36
+ self._layers = layers
37
+ self._verbose = verbose
38
+
39
+ def to_dict(self) -> dict:
40
+ import pyvips
41
+
42
+ data = {"type": self.type, "layers": []}
43
+ for L in self._layers:
44
+ layer_label: str = L.label
45
+ image: pyvips.Image = L.image
46
+ num_zoom_levels = 0
47
+ with TemporaryDirectory() as tmpdir:
48
+ image.dzsave(f"{tmpdir}/output", overlap=0, tile_size=self._tile_size, layout=pyvips.enums.ForeignDzLayout.DZ) # type: ignore
49
+ output_dirname = f"{tmpdir}/output_files"
50
+
51
+ # Collect image files in a dict
52
+ image_files = {}
53
+ z = 1
54
+ while True:
55
+ dirname = f"{output_dirname}/{z}"
56
+ if not os.path.exists(dirname):
57
+ break
58
+ num_zoom_levels = z
59
+ j = 0
60
+ while True:
61
+ if not os.path.exists(f"{dirname}/{j}_0.jpeg"):
62
+ break
63
+ k = 0
64
+ while True:
65
+ fname = f"{dirname}/{j}_{k}.jpeg"
66
+ if not os.path.exists(fname):
67
+ break
68
+
69
+ image_files[f"{z}_{j}_{k}"] = fname
70
+ k = k + 1
71
+ j = j + 1
72
+ z = z + 1
73
+
74
+ keys = list(image_files.keys())
75
+
76
+ # Store image files in kachery-cloud
77
+ uris = _store_files_parallel([image_files[key] for key in keys], labels=[f"{key}.jpeg" for key in keys], verbose=self._verbose)
78
+
79
+ # Replace image file names with URIs
80
+ for key, uri in zip(keys, uris):
81
+ image_files[key] = uri
82
+
83
+ layer = {
84
+ "label": layer_label,
85
+ "tileSize": self._tile_size,
86
+ "width": image.width,
87
+ "height": image.height,
88
+ "numZoomLevels": num_zoom_levels,
89
+ "imageFiles": image_files,
90
+ }
91
+ data["layers"].append(layer)
92
+ return data
93
+
94
+ def child_views(self) -> List[View]:
95
+ return []
96
+
97
+
98
+ # def _store_files(fnames: List[str], *, labels: List[str]) -> List[str]:
99
+ # uris: List[str] = []
100
+ # for fname, label in zip(fnames, labels):
101
+ # print(f'Storing file: {fname}')
102
+ # uri = ka.store_file(fname, label=label)
103
+ # uris.append(uri)
104
+ # return uris
105
+
106
+
107
+ def _store_files_parallel(fnames: List[str], verbose: bool = True, *, labels: List[str]) -> List[str]:
108
+ executor = ThreadPoolExecutor(max_workers=10)
109
+ results = list(executor.map(_store_file, fnames, labels, [verbose] * len(fnames)))
110
+ return results
111
+
112
+
113
+ def _store_file(fname: str, label: str, verbose: str):
114
+ if verbose:
115
+ print(f"Storing file: {fname}")
116
+ return ka.store_file(fname, label=label)
@@ -0,0 +1,158 @@
1
+ import numpy as np
2
+ from typing import List, Union, Dict, Any
3
+ from .View import View
4
+
5
+
6
+ class TGDataset:
7
+ def __init__(self, *, name: str, data: dict) -> None:
8
+ self._name = name
9
+ self._data = data
10
+
11
+ def to_dict(self):
12
+ return {"name": self._name, "data": self._data}
13
+
14
+
15
+ class TGSeries:
16
+ def __init__(self, *, type: str, dataset: str, encoding: dict, attributes: dict, title: str = "") -> None:
17
+ self._type = type
18
+ self._dataset = dataset
19
+ self._encoding = encoding
20
+ self._attributes = attributes
21
+ self._title = title
22
+
23
+ def to_dict(self):
24
+ return {"type": self._type, "dataset": self._dataset, "encoding": self._encoding, "attributes": self._attributes, "title": self._title}
25
+
26
+
27
+ class TimeseriesGraph(View):
28
+ def __init__(
29
+ self,
30
+ *,
31
+ legend_opts: Union[None, dict] = None,
32
+ y_range: Union[List[float], None] = None,
33
+ hide_x_gridlines: Union[bool, None] = None,
34
+ hide_y_gridlines: Union[bool, None] = None,
35
+ **kwargs,
36
+ ) -> None:
37
+ super().__init__("TimeseriesGraph", **kwargs)
38
+ self._datasets = []
39
+ self._series = []
40
+ self._legend_opts = legend_opts
41
+ self._y_range = y_range
42
+ # time_offset is used to allow float64 type in the time arrays
43
+ self._time_offset = None
44
+ self._hide_x_gridlines = hide_x_gridlines
45
+ self._hide_y_gridlines = hide_y_gridlines
46
+
47
+ def add_line_series(self, *, name: str, t: np.ndarray, y: np.ndarray, color: str, width: Union[None, int] = None, dash: Union[None, List[int]] = None):
48
+ # allow float64 for time array
49
+ t = self._handle_time_offset_t(t)
50
+
51
+ if t.dtype == np.float64:
52
+ raise Exception("Cannot handle float64 datatype for t parameter in add_line_series")
53
+ if y.dtype == np.float64:
54
+ raise Exception("Cannot handle float64 datatype for y parameter in add_line_series")
55
+
56
+ attributes: Dict[str, Any] = {"color": color}
57
+ if width is not None:
58
+ attributes["width"] = width
59
+ if dash is not None:
60
+ attributes["dash"] = dash
61
+ self._add_series(type="line", name=name, t=t, y=y, attributes=attributes)
62
+ return self
63
+
64
+ def add_marker_series(self, *, name: str, t: np.ndarray, y: np.ndarray, color: str, radius: Union[None, int] = None, shape: Union[None, str] = None):
65
+ # allow float64 for time array
66
+ t = self._handle_time_offset_t(t)
67
+
68
+ if t.dtype == np.float64:
69
+ raise Exception("Cannot handle float64 datatype for t parameter in add_marker_series")
70
+ if y.dtype == np.float64:
71
+ raise Exception("Cannot handle float64 datatype for y parameter in add_marker_series")
72
+ attributes: Dict[str, Any] = {"color": color}
73
+ if radius is not None:
74
+ attributes["radius"] = radius
75
+ if shape is not None:
76
+ attributes["shape"] = shape
77
+ self._add_series(type="marker", name=name, t=t, y=y, attributes=attributes)
78
+ return self
79
+
80
+ def add_interval_series(
81
+ self,
82
+ *,
83
+ name: str,
84
+ t_start: np.ndarray,
85
+ t_end: np.ndarray,
86
+ color: str,
87
+ ):
88
+ # allow float64 for time array
89
+ t_start = self._handle_time_offset_t(t_start)
90
+ t_end = self._handle_time_offset_t(t_end)
91
+
92
+ if t_start.dtype == np.float64:
93
+ raise Exception("Cannot handle float64 datatype for t_start parameter in add_interval_series")
94
+ if t_end.dtype == np.float64:
95
+ raise Exception("Cannot handle float64 datatype for t_end parameter in add_interval_series")
96
+ attributes = {"color": color}
97
+ t = np.zeros((len(t_start) * 2,), dtype=t_start.dtype)
98
+ t[0::2] = t_start
99
+ t[1::2] = t_end
100
+ y = np.zeros((len(t_start) * 2,), dtype=np.int16)
101
+ y[0::2] = 0
102
+ y[1::2] = 1
103
+ self._add_series(type="interval", name=name, t=t, y=y, attributes=attributes)
104
+ return self
105
+
106
+ def add_dataset(self, ds: TGDataset):
107
+ self._datasets.append(ds)
108
+ return self
109
+
110
+ def add_series(self, s: TGSeries):
111
+ self._series.append(s)
112
+ return self
113
+
114
+ def to_dict(self) -> dict:
115
+ ret = {"type": self.type, "datasets": [ds.to_dict() for ds in self._datasets], "series": [s.to_dict() for s in self._series]}
116
+ if self._time_offset is not None:
117
+ ret["timeOffset"] = self._time_offset
118
+ if self._legend_opts is not None:
119
+ ret["legendOpts"] = self._legend_opts
120
+ if self._y_range is not None:
121
+ assert len(self._y_range) == 2
122
+ ret["yRange"] = self._y_range
123
+ if (self._hide_x_gridlines is not None) or (self._hide_y_gridlines is not None):
124
+ ret["gridlineOpts"] = {"hideX": True if self._hide_x_gridlines is True else False, "hideY": True if self._hide_y_gridlines is True else False}
125
+ return ret
126
+
127
+ def child_views(self) -> List[View]:
128
+ return []
129
+
130
+ def _add_series(self, *, type: str, name: str, t: np.ndarray, y: np.ndarray, attributes: dict):
131
+ if t.ndim != 1:
132
+ print("WARNING: TimeseriesGraph::_add_series t argument is not 1D array. Using squeeze.")
133
+ t = np.squeeze(t)
134
+ if y.ndim != 1:
135
+ print("WARNING: TimeseriesGraph::_add_series y argument is not 1D array. Using squeeze.")
136
+ y = np.squeeze(y)
137
+ ds = TGDataset(name=name, data={"t": t, "y": y})
138
+ s = TGSeries(type=type, encoding={"t": "t", "y": "y"}, dataset=name, attributes=attributes, title=name)
139
+ self.add_dataset(ds)
140
+ self.add_series(s)
141
+
142
+ def _handle_time_offset_t(self, t: np.ndarray):
143
+ if t.dtype == np.float64:
144
+ # We have a float64, let's see if we have a time offset
145
+ if self._time_offset is None:
146
+ # we don't, let's make one
147
+ self._time_offset = t[0]
148
+ # adjust the existing ones
149
+ for ds in self._datasets:
150
+ if "t" in ds._data:
151
+ ds._data["t"] = (ds._data["t"] - self._time_offset).astype(np.float32)
152
+ if self._time_offset is not None:
153
+ # if we have a time offset, let's subtract it
154
+ t = t - self._time_offset
155
+ if t.dtype == np.float64:
156
+ # if we have a float64, now that we've subtracted the time offset, it's safe to use float32
157
+ t = t.astype(np.float32)
158
+ return t
@@ -0,0 +1,41 @@
1
+ from typing import List, Union
2
+ from tempfile import TemporaryDirectory
3
+ from .View import View
4
+ from .Image import _form_data_url
5
+ import kachery as ka
6
+
7
+
8
+ class UnitImagesItem:
9
+ """
10
+ Single unit image
11
+ """
12
+
13
+ def __init__(self, unit_id: Union[int, str], figure, dpi: int) -> None:
14
+ self.unit_id = unit_id
15
+ with TemporaryDirectory() as tmpdir:
16
+ fname = f"{tmpdir}/image.jpg"
17
+ figure.savefig(fname, dpi=dpi)
18
+ self.url = _form_data_url(fname)
19
+
20
+ def to_dict(self):
21
+ ret = {"unitId": self.unit_id, "url": self.url}
22
+ return ret
23
+
24
+
25
+ class UnitImages(View):
26
+ """
27
+ Unit images view
28
+ """
29
+
30
+ def __init__(self, items: List[UnitImagesItem], item_width: float, item_height: float, **kwargs) -> None:
31
+ super().__init__("UnitImages", **kwargs)
32
+ self._items = items
33
+ self._item_width = item_width
34
+ self._item_height = item_height
35
+
36
+ def to_dict(self) -> dict:
37
+ ret = {"type": self.type, "items": [a.to_dict() for a in self._items], "itemWidth": self._item_width, "itemHeight": self._item_height}
38
+ return ret
39
+
40
+ def child_views(self) -> List[View]:
41
+ return []
@@ -0,0 +1,36 @@
1
+ from typing import Any, Dict, List, Union
2
+ from .View import View
3
+
4
+
5
+ class UnitLocationsItem:
6
+ """
7
+ Single unit location
8
+ """
9
+
10
+ def __init__(self, unit_id: Union[int, str], x: float, y: float) -> None:
11
+ self.unit_id = unit_id
12
+ self.x = x
13
+ self.y = y
14
+
15
+ def to_dict(self):
16
+ ret = {"unitId": self.unit_id, "x": self.x, "y": self.y}
17
+ return ret
18
+
19
+
20
+ class UnitLocations(View):
21
+ """
22
+ Unit locations view
23
+ """
24
+
25
+ def __init__(self, units: List[UnitLocationsItem], *, channel_locations: Dict[str, Any], disable_auto_rotate: bool = False, **kwargs) -> None:
26
+ super().__init__("UnitLocations", **kwargs)
27
+ self._units = units
28
+ self._channel_locations = channel_locations
29
+ self._disable_auto_rotate = disable_auto_rotate
30
+
31
+ def to_dict(self) -> dict:
32
+ ret = {"type": self.type, "units": [a.to_dict() for a in self._units], "channelLocations": self._channel_locations, "disableAutoRotate": self._disable_auto_rotate}
33
+ return ret
34
+
35
+ def child_views(self) -> List[View]:
36
+ return []
@@ -0,0 +1,47 @@
1
+ from typing import List, Literal, Union
2
+ from .View import View
3
+
4
+
5
+ class UnitMetricsGraphMetric:
6
+ """
7
+ Single metric
8
+ """
9
+
10
+ def __init__(self, key: str, label: str, dtype: Literal["int", "float"]) -> None:
11
+ self.key = key
12
+ self.label = label
13
+ self.dtype = dtype
14
+
15
+ def to_dict(self):
16
+ return {"key": self.key, "label": self.label, "dtype": self.dtype}
17
+
18
+
19
+ class UnitMetricsGraphUnit:
20
+ """
21
+ Single unit
22
+ """
23
+
24
+ def __init__(self, unit_id: Union[int, str], values: dict) -> None:
25
+ self.unit_id = unit_id
26
+ self.values = values
27
+
28
+ def to_dict(self):
29
+ return {"unitId": self.unit_id, "values": self.values}
30
+
31
+
32
+ class UnitMetricsGraph(View):
33
+ """
34
+ Units table view
35
+ """
36
+
37
+ def __init__(self, *, metrics: List[UnitMetricsGraphMetric], units: List[UnitMetricsGraphUnit], **kwargs) -> None:
38
+ super().__init__("UnitMetricsGraph", **kwargs)
39
+ self._metrics = metrics
40
+ self._units = units
41
+
42
+ def to_dict(self) -> dict:
43
+ ret = {"type": self.type, "units": [a.to_dict() for a in self._units], "metrics": [a.to_dict() for a in self._metrics]}
44
+ return ret
45
+
46
+ def child_views(self) -> List[View]:
47
+ return []
@@ -0,0 +1,34 @@
1
+ from typing import List, Union
2
+ from .View import View
3
+
4
+
5
+ class UnitSimilarityScore:
6
+ """
7
+ A single similarity score
8
+ """
9
+
10
+ def __init__(self, unit_id1: Union[int, str], unit_id2: Union[int, str], similarity: float) -> None:
11
+ self.unit_id1 = unit_id1
12
+ self.unit_id2 = unit_id2
13
+ self.similarity = similarity
14
+
15
+ def to_dict(self):
16
+ return {"unitId1": self.unit_id1, "unitId2": self.unit_id2, "similarity": self.similarity}
17
+
18
+
19
+ class UnitSimilarityMatrix(View):
20
+ """
21
+ Unit similarity matrix view
22
+ """
23
+
24
+ def __init__(self, unit_ids: List[Union[int, str]], similarity_scores: List[UnitSimilarityScore], **kwargs) -> None:
25
+ super().__init__("UnitSimilarityMatrix", **kwargs)
26
+ self._unit_ids = unit_ids
27
+ self._similarity_scores = similarity_scores
28
+
29
+ def to_dict(self) -> dict:
30
+ ret = {"type": self.type, "unitIds": self._unit_ids, "similarityScores": [a.to_dict() for a in self._similarity_scores]}
31
+ return ret
32
+
33
+ def child_views(self) -> List[View]:
34
+ return []
@@ -0,0 +1,51 @@
1
+ from typing import List, Literal, Union
2
+ from .View import View
3
+ from .UnitSimilarityMatrix import UnitSimilarityScore
4
+
5
+
6
+ class UnitsTableColumn:
7
+ """
8
+ Single column in a units table
9
+ """
10
+
11
+ def __init__(self, key: str, label: str, dtype: Literal["int", "float"]) -> None:
12
+ self.key = key
13
+ self.label = label
14
+ self.dtype = dtype
15
+
16
+ def to_dict(self):
17
+ return {"key": self.key, "label": self.label, "dtype": self.dtype}
18
+
19
+
20
+ class UnitsTableRow:
21
+ """
22
+ Single row in a units table
23
+ """
24
+
25
+ def __init__(self, unit_id: Union[int, str], values: dict) -> None:
26
+ self.unit_id = unit_id
27
+ self.values = values
28
+
29
+ def to_dict(self):
30
+ return {"unitId": self.unit_id, "values": self.values}
31
+
32
+
33
+ class UnitsTable(View):
34
+ """
35
+ Units table view
36
+ """
37
+
38
+ def __init__(self, *, columns: List[UnitsTableColumn], rows: List[UnitsTableRow], similarity_scores: Union[List[UnitSimilarityScore], None] = None, **kwargs) -> None:
39
+ super().__init__("UnitsTable", **kwargs)
40
+ self._columns = columns
41
+ self._rows = rows
42
+ self._similarity_scores = similarity_scores
43
+
44
+ def to_dict(self) -> dict:
45
+ ret = {"type": self.type, "columns": [a.to_dict() for a in self._columns], "rows": [a.to_dict() for a in self._rows]}
46
+ if self._similarity_scores is not None:
47
+ ret["similarityScores"] = [x.to_dict() for x in self._similarity_scores]
48
+ return ret
49
+
50
+ def child_views(self) -> List[View]:
51
+ return []