xarray-behave 0.37.8__tar.gz → 0.38.0a2__tar.gz

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 (62) hide show
  1. xarray_behave-0.38.0a2/PKG-INFO +92 -0
  2. xarray_behave-0.38.0a2/README.md +58 -0
  3. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/pyproject.toml +3 -10
  4. xarray_behave-0.38.0a2/src/xarray_behave/__init__.py +12 -0
  5. xarray_behave-0.38.0a2/src/xarray_behave/_dataset_service.py +299 -0
  6. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/annot.py +70 -106
  7. xarray_behave-0.38.0a2/src/xarray_behave/api.py +646 -0
  8. xarray_behave-0.38.0a2/src/xarray_behave/event_utils.py +152 -0
  9. xarray_behave-0.38.0a2/src/xarray_behave/gui/app.py +5249 -0
  10. xarray_behave-0.38.0a2/src/xarray_behave/gui/checkbox_check.svg +3 -0
  11. xarray_behave-0.38.0a2/src/xarray_behave/gui/event_widgets.py +1977 -0
  12. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/gui/formbuilder.py +20 -167
  13. xarray_behave-0.38.0a2/src/xarray_behave/gui/forms/das_make.yaml +48 -0
  14. xarray_behave-0.38.0a2/src/xarray_behave/gui/forms/envelope_computation.yaml +21 -0
  15. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/gui/forms/from_dir.yaml +2 -2
  16. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/gui/forms/from_file.yaml +0 -6
  17. xarray_behave-0.38.0a2/src/xarray_behave/gui/gui_config.py +448 -0
  18. xarray_behave-0.38.0a2/src/xarray_behave/gui/icon.png +0 -0
  19. xarray_behave-0.38.0a2/src/xarray_behave/gui/media_dialog.py +286 -0
  20. xarray_behave-0.38.0a2/src/xarray_behave/gui/modern_video.py +125 -0
  21. xarray_behave-0.38.0a2/src/xarray_behave/gui/project.py +456 -0
  22. xarray_behave-0.38.0a2/src/xarray_behave/gui/style_profile.py +277 -0
  23. xarray_behave-0.38.0a2/src/xarray_behave/gui/utils.py +191 -0
  24. xarray_behave-0.38.0a2/src/xarray_behave/gui/view_dialog.py +422 -0
  25. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/gui/views.py +160 -228
  26. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/gui/widgets.py +2 -4
  27. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/__init__.py +2 -4
  28. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/annotations.py +2 -4
  29. xarray_behave-0.38.0a2/src/xarray_behave/io/annotations_manual.py +199 -0
  30. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/audio.py +84 -1
  31. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/balltracks.py +0 -2
  32. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/movieparams.py +0 -1
  33. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/timestamps.py +0 -1
  34. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/tracks.py +0 -1
  35. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/loaders.py +2 -42
  36. xarray_behave-0.38.0a2/src/xarray_behave/manifests/default.yaml +94 -0
  37. xarray_behave-0.38.0a2/src/xarray_behave/v1.py +5 -0
  38. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/xarray_behave.py +24 -46
  39. xarray_behave-0.37.8/PKG-INFO +0 -52
  40. xarray_behave-0.37.8/README.md +0 -11
  41. xarray_behave-0.37.8/src/xarray_behave/__init__.py +0 -8
  42. xarray_behave-0.37.8/src/xarray_behave/event_utils.py +0 -227
  43. xarray_behave-0.37.8/src/xarray_behave/gui/app.py +0 -2596
  44. xarray_behave-0.37.8/src/xarray_behave/gui/audio_player.py +0 -108
  45. xarray_behave-0.37.8/src/xarray_behave/gui/das_legacy.py +0 -377
  46. xarray_behave-0.37.8/src/xarray_behave/gui/forms/das_predict.yaml +0 -167
  47. xarray_behave-0.37.8/src/xarray_behave/gui/forms/das_train.yaml +0 -264
  48. xarray_behave-0.37.8/src/xarray_behave/gui/forms/envelope_computation.yaml +0 -123
  49. xarray_behave-0.37.8/src/xarray_behave/gui/forms/spec_freq.yaml +0 -26
  50. xarray_behave-0.37.8/src/xarray_behave/gui/icon.png +0 -0
  51. xarray_behave-0.37.8/src/xarray_behave/gui/table.py +0 -183
  52. xarray_behave-0.37.8/src/xarray_behave/gui/utils.py +0 -384
  53. xarray_behave-0.37.8/src/xarray_behave/gui/view_dialog.py +0 -229
  54. xarray_behave-0.37.8/src/xarray_behave/io/annotations_manual.py +0 -116
  55. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/LICENSE +0 -0
  56. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/gui/__init__.py +0 -0
  57. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/gui/forms/from_zarr.yaml +0 -0
  58. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/poses.py +0 -0
  59. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/samplestamps/__init__.py +0 -0
  60. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/samplestamps/samplestamps.py +0 -0
  61. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/io/samplestamps/utils.py +0 -0
  62. {xarray_behave-0.37.8 → xarray_behave-0.38.0a2}/src/xarray_behave/metrics.py +0 -0
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: xarray-behave
3
+ Version: 0.38.0a2
4
+ Summary: xarray tools for behavioral data.
5
+ Author-email: Jan Clemens <clemensjan@googlemail.com>
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ Classifier: License :: OSI Approved :: Apache Software License
9
+ License-File: LICENSE
10
+ Requires-Dist: defopt==6.3
11
+ Requires-Dist: flammkuchen
12
+ Requires-Dist: h5py
13
+ Requires-Dist: pyyaml
14
+ Requires-Dist: zarr<3
15
+ Requires-Dist: dask
16
+ Requires-Dist: pandas
17
+ Requires-Dist: xarray
18
+ Requires-Dist: numba
19
+ Requires-Dist: numpy
20
+ Requires-Dist: scipy>1.9
21
+ Requires-Dist: soundfile
22
+ Requires-Dist: librosa>0.8
23
+ Requires-Dist: av>=12
24
+ Requires-Dist: PySide6>=6.10
25
+ Requires-Dist: pyqtgraph>0.12.2
26
+ Requires-Dist: qtpy
27
+ Requires-Dist: pytest ; extra == "dev"
28
+ Requires-Dist: flit ; extra == "dev"
29
+ Project-URL: documentation, https://janclemenslab.org/das-alpha/
30
+ Project-URL: source, https://github.com/janclemenslab/xarray-behave
31
+ Provides-Extra: dev
32
+ Import-Name: xarray_behave
33
+
34
+ # xarray-behave
35
+
36
+ Install a working conda installation (see [here](https://docs.conda.io/en/latest/miniconda.html)).
37
+
38
+ ```shell
39
+ conda env create -n xb -y -f https://raw.githubusercontent.com/janclemenslab/xarray-behave/refs/heads/master/env/xb.yml
40
+ ```
41
+
42
+ See `demo.ipynb` for usage examples.
43
+
44
+ ## GUI configuration
45
+
46
+ The GUI saves reusable state to `~/.das.yaml` when it closes cleanly. This
47
+ includes the window and panel layout, display and annotation options, audio and
48
+ threshold settings, event-type presets, and the last reusable load-dialog
49
+ choices. Source-specific values such as file paths, HDF5 dataset names, inferred
50
+ sample rates, and pixel calibration are deliberately not saved.
51
+
52
+ Configuration is applied in this order, with later values taking precedence:
53
+
54
+ 1. Built-in defaults.
55
+ 2. `~/.das.yaml`.
56
+ 3. `.das.yaml` in a directory source, or beside a file or `.zarr` source.
57
+ 4. A file supplied with `--config`.
58
+ 5. Explicit command-line options and edits made in the load dialog.
59
+
60
+ For example:
61
+
62
+ ```shell
63
+ python -m xarray_behave.gui.app recording.wav --config lab-profile.yaml
64
+ ```
65
+
66
+ Use **File > Save Configuration As...** to create a local or shared profile.
67
+ Configuration files are versioned YAML mappings. A minimal profile is:
68
+
69
+ ```yaml
70
+ version: 1
71
+ window:
72
+ panels:
73
+ sidebar: true
74
+ timeline: true
75
+ event_table: true
76
+ viewer:
77
+ spectrogram:
78
+ colormap: magma
79
+ compression: 3
80
+ audio:
81
+ waveform_all: true
82
+ playback_all: false
83
+ event_types:
84
+ - name: pulse
85
+ fixed_duration: true
86
+ duration_seconds: 0.01
87
+ duration_editable: false
88
+ color_hex: "#ffd166"
89
+ visible: true
90
+ editable: true
91
+ ```
92
+
@@ -0,0 +1,58 @@
1
+ # xarray-behave
2
+
3
+ Install a working conda installation (see [here](https://docs.conda.io/en/latest/miniconda.html)).
4
+
5
+ ```shell
6
+ conda env create -n xb -y -f https://raw.githubusercontent.com/janclemenslab/xarray-behave/refs/heads/master/env/xb.yml
7
+ ```
8
+
9
+ See `demo.ipynb` for usage examples.
10
+
11
+ ## GUI configuration
12
+
13
+ The GUI saves reusable state to `~/.das.yaml` when it closes cleanly. This
14
+ includes the window and panel layout, display and annotation options, audio and
15
+ threshold settings, event-type presets, and the last reusable load-dialog
16
+ choices. Source-specific values such as file paths, HDF5 dataset names, inferred
17
+ sample rates, and pixel calibration are deliberately not saved.
18
+
19
+ Configuration is applied in this order, with later values taking precedence:
20
+
21
+ 1. Built-in defaults.
22
+ 2. `~/.das.yaml`.
23
+ 3. `.das.yaml` in a directory source, or beside a file or `.zarr` source.
24
+ 4. A file supplied with `--config`.
25
+ 5. Explicit command-line options and edits made in the load dialog.
26
+
27
+ For example:
28
+
29
+ ```shell
30
+ python -m xarray_behave.gui.app recording.wav --config lab-profile.yaml
31
+ ```
32
+
33
+ Use **File > Save Configuration As...** to create a local or shared profile.
34
+ Configuration files are versioned YAML mappings. A minimal profile is:
35
+
36
+ ```yaml
37
+ version: 1
38
+ window:
39
+ panels:
40
+ sidebar: true
41
+ timeline: true
42
+ event_table: true
43
+ viewer:
44
+ spectrogram:
45
+ colormap: magma
46
+ compression: 3
47
+ audio:
48
+ waveform_all: true
49
+ playback_all: false
50
+ event_types:
51
+ - name: pulse
52
+ fixed_duration: true
53
+ duration_seconds: 0.01
54
+ duration_editable: false
55
+ color_hex: "#ffd166"
56
+ visible: true
57
+ editable: true
58
+ ```
@@ -10,7 +10,6 @@ dynamic = ["version", "description"]
10
10
  requires-python = ">=3.10"
11
11
  dependencies = [
12
12
  'defopt==6.3',
13
- 'rich',
14
13
  'flammkuchen',
15
14
  'h5py',
16
15
  'pyyaml',
@@ -18,21 +17,15 @@ dependencies = [
18
17
  'dask',
19
18
  'pandas',
20
19
  'xarray',
21
- 'scikit-image',
22
- 'peakutils',
23
20
  'numba',
24
21
  'numpy',
25
22
  'scipy>1.9',
26
- 'sounddevice',
27
23
  'soundfile',
28
24
  'librosa>0.8',
29
- 'opencv-python-headless',
30
- 'pyvideoreader',
31
- 'PySide6>=6.10,<7',
25
+ 'av>=12',
26
+ 'PySide6>=6.10',
32
27
  'pyqtgraph>0.12.2',
33
28
  'qtpy',
34
- 'superqt',
35
- 'colorcet',
36
29
  ]
37
30
  readme = "README.md"
38
31
 
@@ -41,7 +34,7 @@ dev = ["pytest", "flit"]
41
34
 
42
35
  [project.urls]
43
36
  source = "https://github.com/janclemenslab/xarray-behave"
44
- documentation = "https://janclemenslab.org/das/"
37
+ documentation = "https://janclemenslab.org/das-alpha/"
45
38
 
46
39
  [tool.flit.module]
47
40
  name = "xarray_behave"
@@ -0,0 +1,12 @@
1
+ """xarray tools for behavioral data."""
2
+
3
+ __version__ = "0.38.0a2"
4
+
5
+ import os
6
+
7
+ os.environ["QT_API"] = "pyside6"
8
+
9
+ from .xarray_behave import assemble_metrics, load, save
10
+ from .api import discover, assemble, resample
11
+
12
+ __all__ = ["assemble", "assemble_metrics", "discover", "load", "resample", "save"]
@@ -0,0 +1,299 @@
1
+ """Internal dataset helpers used by the GUI without depending on Qt."""
2
+
3
+ import logging
4
+ import os
5
+ from typing import Optional
6
+
7
+ import numpy as np
8
+ import scipy.signal as ss
9
+
10
+ from . import annot, api, event_utils, io, v1 as xb
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def assemble_from_media(media_data: dict):
16
+ files = {"audio": {}, "video": {}}
17
+ for source in media_data.get("audio", []):
18
+ name = source["name"]
19
+ entry = {key: value for key, value in source.items() if key != "name"}
20
+ entry["splits"] = {name: ":"}
21
+ files["audio"][name] = entry
22
+ for source in media_data.get("video", []):
23
+ name = source["name"]
24
+ files["video"][name] = {key: value for key, value in source.items() if key != "name"}
25
+ if not files["audio"]:
26
+ raise ValueError("At least one audio source is required.")
27
+ return api.assemble(files, lazy_load_audio=True)
28
+
29
+
30
+ def assemble_project_recording(recording):
31
+ audio = dict(recording.audio)
32
+ audio["splits"] = {"song_raw": ":"}
33
+ videos = {}
34
+ for index, source in enumerate(recording.videos):
35
+ source = dict(source)
36
+ name = source.pop("name", "camera" if index == 0 else f"camera_{index + 1}")
37
+ videos[name] = source
38
+ ds = api.assemble({"audio": {"main": audio}, "video": videos}, lazy_load_audio=True)
39
+ ds.attrs.update(
40
+ {
41
+ "filename": str(recording.audio_path),
42
+ "filebase": str(recording.audio_path.with_suffix("")),
43
+ "datename": "",
44
+ "res_path": "",
45
+ "dat_path": "",
46
+ }
47
+ )
48
+ return replace_event_times(ds, recording.annotations)
49
+
50
+
51
+ def replace_event_times(ds, event_times):
52
+ if "index" in ds.dims:
53
+ ds = ds.drop_dims("index")
54
+ return ds.combine_first(annot.Events(event_times).to_dataset())
55
+
56
+
57
+ def assemble_from_file(filename: str, form_data: dict):
58
+ filter_song_requested = form_data["filter_song"] == "yes"
59
+ ds = xb.assemble(
60
+ filepath_daq=filename,
61
+ filepath_annotations=form_data["annotation_path"],
62
+ filepath_definitions=form_data["definition_path"],
63
+ audio_sampling_rate=form_data["samplerate"],
64
+ target_sampling_rate=form_data["target_samplingrate"],
65
+ audio_dataset=form_data["data_set"],
66
+ lazy_load_song=not filter_song_requested,
67
+ make_song_events=form_data.get("generate_event_traces", False),
68
+ )
69
+
70
+ if filter_song_requested:
71
+ ds = filter_song(ds, form_data["f_low"], form_data["f_high"])
72
+
73
+ ds.attrs["filename"] = filename
74
+ ds.attrs["filebase"] = os.path.splitext(filename)[0]
75
+ ds.attrs["datename"] = ""
76
+ ds.attrs["res_path"] = ""
77
+ ds.attrs["dat_path"] = ""
78
+ return ds
79
+
80
+
81
+ def assemble_from_dir(dirname: str, form_data: dict, pixel_size_mm: Optional[float] = None, manifest: Optional[str] = None):
82
+ if form_data["target_samplingrate"] == 0 or form_data["target_samplingrate"] is None:
83
+ resample_video_data = False
84
+ else:
85
+ resample_video_data = True
86
+
87
+ filter_song_requested = form_data["filter_song"] == "yes"
88
+ include_tracks = not form_data["ignore_tracks"]
89
+ include_poses = not form_data["ignore_tracks"]
90
+ lazy_load_song = not filter_song_requested
91
+ base, datename = os.path.split(os.path.normpath(dirname))
92
+ root, dat_path = os.path.split(base)
93
+ annotation_path = None if not len(form_data["annotation_path"]) else form_data["annotation_path"]
94
+ filepath_video = None if not len(form_data["video_filename"]) else form_data["video_filename"]
95
+ filepath_daq = None if not len(form_data["daq_filename"]) else form_data["daq_filename"]
96
+ discovered = None
97
+ if manifest is not None:
98
+ discovered = api.discover(datename, root=root, dat_path=dat_path, res_path="res", manifest=manifest)
99
+ filepath_video = filepath_video or _discovered_path(discovered, "video", "camera")
100
+ filepath_daq = filepath_daq or _discovered_path(discovered, "audio", "main")
101
+ annotation_path = (
102
+ annotation_path
103
+ or _discovered_path(discovered, "annotations", "manual")
104
+ or _discovered_path(discovered, "annotations", "auto")
105
+ )
106
+
107
+ assemble_kwargs = {
108
+ "res_path": "res",
109
+ "filepath_annotations": annotation_path,
110
+ "filepath_video": filepath_video,
111
+ "filepath_daq": filepath_daq,
112
+ "fix_fly_indices": form_data["fix_fly_indices"],
113
+ "include_song": ~int(form_data["ignore_song"]),
114
+ "target_sampling_rate": form_data["target_samplingrate"],
115
+ "resample_video_data": resample_video_data,
116
+ "pixel_size_mm": pixel_size_mm,
117
+ "lazy_load_song": lazy_load_song,
118
+ "include_tracks": include_tracks,
119
+ "include_poses": include_poses,
120
+ "make_song_events": form_data.get("generate_event_traces", False),
121
+ }
122
+ if discovered is not None:
123
+ assemble_kwargs.update(
124
+ {
125
+ "filepath_timestamps": _discovered_path(discovered, "timestamps", "camera"),
126
+ "filepath_timestamps_ball": _discovered_path(discovered, "timestamps", "ball"),
127
+ "filepath_tracks": _discovered_path(discovered, "tracks", "main"),
128
+ "filepath_poses": _discovered_path(discovered, "poses", "main"),
129
+ "filepath_definitions": _discovered_path(discovered, "definitions", "main"),
130
+ }
131
+ )
132
+ assemble_kwargs = {key: value for key, value in assemble_kwargs.items() if value is not None}
133
+
134
+ ds = xb.assemble(datename, root, dat_path, **assemble_kwargs)
135
+
136
+ if filter_song_requested:
137
+ ds = filter_song(ds, form_data["f_low"], form_data["f_high"])
138
+
139
+ event_names = []
140
+ if form_data["init_annotations"] and len(form_data["events_string"]):
141
+ for pair in form_data["events_string"].split(";"):
142
+ items = pair.strip().split(",")
143
+ if len(items) > 0 and len(items[0].strip()):
144
+ event_names.append(items[0].strip())
145
+
146
+ ds = ensure_event_categories(ds)
147
+
148
+ if "song_events" not in ds or len(ds.event_types) == 0:
149
+ cats = {event_name: "event" for event_name in event_names}
150
+ ds.attrs["event_times"] = annot.Events(categories=cats)
151
+
152
+ return ds
153
+
154
+
155
+ def _discovered_path(files: dict, group: str, name: str):
156
+ entry = files.get(group, {}).get(name)
157
+ if entry is None:
158
+ entries = files.get(group, {})
159
+ entry = next(iter(entries.values()), None)
160
+ if isinstance(entry, str):
161
+ return entry
162
+ if not entry:
163
+ return None
164
+ if "path" in entry:
165
+ return entry["path"]
166
+ paths = entry.get("paths", [])
167
+ return paths[0] if len(paths) == 1 else None
168
+
169
+
170
+ def load_from_zarr(filename: str, form_data: dict):
171
+ ds = xb.load(filename, lazy=True, use_temp=True)
172
+ load_event_traces = form_data.get("load_event_traces", False)
173
+ has_event_table = "event_times" in ds and "event_names" in ds and len(ds["event_names"]) > 0
174
+ if "song_events" in ds and (load_event_traces or not has_event_table):
175
+ ds.song_events.load()
176
+ if not form_data["lazy"]:
177
+ logger.info(" Loading data from ds.")
178
+ if "song" in ds:
179
+ ds.song.load()
180
+ if "pose_positions_allo" in ds:
181
+ ds.pose_positions_allo.load()
182
+ if "sampletime" in ds:
183
+ ds.sampletime.load()
184
+ if "song_raw" in ds:
185
+ ds.song_raw.load()
186
+
187
+ if form_data["filter_song"] == "yes":
188
+ ds = filter_song(ds, form_data["f_low"], form_data["f_high"])
189
+
190
+ ds = ensure_event_categories(ds)
191
+ logger.info(ds)
192
+ return ds
193
+
194
+
195
+ def load_annotation_file(filename: str):
196
+ loader = io.get_loader("annotations_manual", filename, basename_is_full_name=True)
197
+ if loader is None:
198
+ raise ValueError(f"No annotation loader found for {filename}.")
199
+ event_times, categories = loader.load(filename)
200
+ return annot.Events(event_times, categories=categories)
201
+
202
+
203
+ def _event_row_key(name: str, row) -> tuple[str, float, float, int]:
204
+ channel = row[2] if len(row) > 2 else -1
205
+ channel = int(channel) if np.isfinite(channel) else -1
206
+ return str(name), float(row[0]), float(row[1]), channel
207
+
208
+
209
+ def merge_event_times(existing, imported):
210
+ merged = annot.Events(existing)
211
+ imported = annot.Events(imported)
212
+ for name in imported.names:
213
+ imported_rows = np.asarray(imported[name])
214
+ if name not in merged:
215
+ merged.add_name(name, times=imported_rows.copy(), overwrite=True)
216
+ continue
217
+
218
+ imported_keys = {_event_row_key(name, row) for row in imported_rows}
219
+ existing_rows = np.asarray(merged[name])
220
+ if imported_keys and len(existing_rows):
221
+ keep = [_event_row_key(name, row) not in imported_keys for row in existing_rows]
222
+ existing_rows = existing_rows[np.asarray(keep, dtype=bool)]
223
+ if len(imported_rows):
224
+ merged[name] = np.vstack([existing_rows, imported_rows])
225
+ else:
226
+ merged[name] = existing_rows.copy()
227
+ merged.categories[name] = "event"
228
+
229
+ for name in merged.names:
230
+ merged.categories[name] = "event"
231
+ merged.sort()
232
+ return annot.Events(merged)
233
+
234
+
235
+ def filter_song(ds, f_low, f_high):
236
+ if f_low is None:
237
+ f_low = 1.0
238
+ if "song_raw" in ds:
239
+ if f_high is None:
240
+ f_high = ds.song_raw.attrs["sampling_rate_Hz"] / 2 - 1
241
+ else:
242
+ f_high = min(f_high, ds.song_raw.attrs["sampling_rate_Hz"] / 2 - 1)
243
+ sos_bp = ss.butter(
244
+ 5,
245
+ [f_low, f_high],
246
+ "bandpass",
247
+ output="sos",
248
+ fs=ds.song_raw.attrs["sampling_rate_Hz"],
249
+ )
250
+ logger.info(f"Filtering `song_raw` between {f_low} and {f_high} Hz.")
251
+ ds.song_raw.data = ss.sosfiltfilt(sos_bp, ds.song_raw.data, axis=0)
252
+ return ds
253
+
254
+
255
+ def ensure_event_categories(ds):
256
+ if "song_events" in ds and "event_categories" not in ds:
257
+ event_categories = ["event" for _evt in ds.event_types.values]
258
+ ds = ds.assign_coords({"event_categories": (("event_types"), event_categories)})
259
+ elif "song_events" in ds and "event_categories" in ds:
260
+ event_categories = ["event" for _evt in ds.event_types.values]
261
+ ds = ds.assign_coords({"event_categories": (("event_types"), event_categories)})
262
+ return ds
263
+
264
+
265
+ def event_times_from_dataset(ds):
266
+ if "event_times" in ds and "event_names" in ds and len(ds["event_names"]) > 0:
267
+ event_times = annot.Events.from_dataset(ds)
268
+ elif "event_times" in ds.attrs:
269
+ event_times = ds.attrs["event_times"].copy()
270
+ elif "song_events" in ds:
271
+ event_times = event_utils.detect_events(ds)
272
+ else:
273
+ event_times = dict()
274
+ return annot.Events(event_times)
275
+
276
+
277
+ def prepare_for_display(ds):
278
+ original_spatial_units = None
279
+ for name in ["body_positions", "pose_positions", "pose_positions_allo"]:
280
+ if name in ds:
281
+ original_spatial_units = ds[name].attrs["spatial_units"]
282
+ ds = xb.convert_spatial_units(ds, to_units="pixels")
283
+ return ds, original_spatial_units
284
+
285
+
286
+ def prepare_for_save(ds, event_times, original_spatial_units=None, generate_event_traces: bool = False):
287
+ if "song_events" in ds and generate_event_traces:
288
+ logger.info(" Updating song events")
289
+ ds = event_utils.eventtimes_to_traces(ds, event_times)
290
+
291
+ if original_spatial_units is not None:
292
+ logger.info(f"Converting spatial units back to {original_spatial_units} if required.")
293
+ ds = xb.convert_spatial_units(ds, to_units=original_spatial_units)
294
+
295
+ event_times = annot.Events(event_times)
296
+ ds_event_times = event_times.to_dataset()
297
+ if "index" in ds.dims:
298
+ ds = ds.drop_dims("index")
299
+ return ds.combine_first(ds_event_times)