Helpers¶
Utility functions for label loading, safe name encoding, and data manipulation.
helpers ¶
make_entry_key ¶
Composite key for a (group, sequence) dataset entry.
Matches the filename stem convention used throughout the pipeline:
{safe_group}__{safe_seq} when group is non-empty, else {safe_seq}.
Source code in src/mosaic/core/helpers.py
detect_label_format ¶
Detect the label format from an NPZ file's contents.
Parameters¶
npz_data : dict or np.lib.npyio.NpzFile Loaded NPZ data (from np.load())
Returns¶
str One of: "individual_pair_v1", "dense", "unknown"
Examples¶
with np.load("labels.npz", allow_pickle=True) as npz: ... fmt = detect_label_format(npz)
Source code in src/mosaic/core/helpers.py
expand_labels_to_dense ¶
expand_labels_to_dense(frames: ndarray, labels: ndarray, individual_ids: Optional[ndarray] = None, n_frames: Optional[int] = None, default_label: int = 0, individual_filter: Optional[Tuple[int, int]] = None) -> np.ndarray
Expand sparse event-based labels to a dense per-frame array.
Converts from individual_pair_v1 format (sparse events) to a dense array where labels[i] is the label at frame i.
Parameters¶
frames : np.ndarray 1D array of frame indices for each event, shape (n_events,) labels : np.ndarray 1D array of label IDs for each event, shape (n_events,) individual_ids : np.ndarray, optional 2D array of [id1, id2] for each event, shape (n_events, 2). If provided with individual_filter, only events matching the filter are included. n_frames : int, optional Total number of frames in the dense output. If None, uses max(frames) + 1. default_label : int, default=0 Label value for frames without events (typically 0 = "none"/"background") individual_filter : tuple of (int, int), optional If provided, only include events where individual_ids matches this pair. For symmetric behaviors, you may want to filter for a specific direction. Use (-1, -1) for scene-level labels, (id, -1) for individual labels.
Returns¶
np.ndarray Dense 1D array of shape (n_frames,) where output[i] is the label at frame i. If multiple events occur at the same frame, the last one wins.
Examples¶
frames = np.array([10, 11, 12, 50, 51]) labels = np.array([1, 1, 1, 2, 2]) dense = expand_labels_to_dense(frames, labels, n_frames=100) dense[10:13] # [1, 1, 1] dense[0] # 0 (default)
With individual filtering:
individual_ids = np.array([[0, 1], [0, 1], [0, 1], [1, 0], [1, 0]]) dense_01 = expand_labels_to_dense(frames, labels, individual_ids, ... individual_filter=(0, 1))
Only includes events where individual_ids == [0, 1]¶
Source code in src/mosaic/core/helpers.py
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 | |
load_labels_auto ¶
load_labels_auto(path, n_frames: Optional[int] = None, default_label: int = 0, individual_filter: Optional[Tuple[int, int]] = None, return_format: str = 'dense') -> np.ndarray
Load labels from NPZ file, auto-detecting format and converting as needed.
Supports both dense (legacy) and individual_pair_v1 (sparse) formats.
Parameters¶
path : str or Path Path to the NPZ label file n_frames : int, optional For sparse formats, the total number of frames to expand to. If None, uses max(frames) + 1 from the file. default_label : int, default=0 Label for unlabeled frames when expanding sparse to dense individual_filter : tuple of (int, int), optional For individual_pair_v1 format, filter to specific individual pair return_format : str, default="dense" Output format: "dense" returns per-frame array, "sparse" returns (frames, labels, individual_ids) tuple for individual_pair_v1
Returns¶
np.ndarray or tuple If return_format="dense": 1D array of shape (n_frames,) If return_format="sparse": tuple of (frames, labels, individual_ids)
Examples¶
labels = load_labels_auto("behavior/hex_03.npz") labels.shape # (n_frames,)
frames, labels, ids = load_labels_auto("behavior/hex_03.npz", ... return_format="sparse")
Source code in src/mosaic/core/helpers.py
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 | |
load_labels_for_feature_frames ¶
load_labels_for_feature_frames(path, feature_frames: ndarray, default_label: int = 0, deduplicate_symmetric: bool = True, individual_filter: Optional[Tuple[int, int]] = None) -> np.ndarray
Load labels from NPZ file and align to specific feature frame indices.
This is the key function for aligning sparse event-based labels (like individual_pair_v1 format) with row-indexed feature data. Rather than expanding to a full dense array, it looks up the label for each specific frame in feature_frames.
Parameters¶
path : str or Path Path to the NPZ label file feature_frames : np.ndarray 1D array of frame indices from the feature data. Each element specifies which video frame that feature row corresponds to. The output will have one label per element in feature_frames. default_label : int, default=0 Label for frames that don't have labeled events (typically 0 = "none") deduplicate_symmetric : bool, default=True For individual_pair_v1 format with symmetric storage (both [i,j] and [j,i] stored), deduplicate by keeping only id1 <= id2 events. Ignored when individual_filter is set (filtering is more specific). individual_filter : tuple of (int, int), optional For individual_pair_v1 format, only include events matching this specific (id1, id2) pair. When set, deduplicate_symmetric is skipped since the filter is already pair-specific.
Returns¶
np.ndarray 1D array of labels with shape (len(feature_frames),). labels[i] is the label for frame feature_frames[i].
Examples¶
Feature data has 1000 rows covering frames 5000-6000¶
feature_frames = np.array([5000, 5001, 5002, ...]) # from parquet labels = load_labels_for_feature_frames("behavior.npz", feature_frames) labels.shape # (1000,) - one label per feature row
Notes¶
This function solves the frame coordinate alignment problem that occurs when: - Behavior labels are stored with original video frame indices (e.g., 15002-65927) - Feature data is row-indexed (0, 1, 2, ...) but each row corresponds to a specific video frame stored in a 'frame' column - The feature frame range may not fully overlap with labeled frames
For frames without labeled events, default_label is returned. For frames with multiple labeled events, the last one wins.
Source code in src/mosaic/core/helpers.py
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 | |
chunk_sequence ¶
Yield (chunk_id, df_chunk, meta) from a per-sequence DataFrame. If time_chunk_sec is provided and 'time' exists, chunk by time. Else if frame_chunk is provided and 'frame' exists, chunk by frame. Else yield the whole sequence as a single chunk. meta contains start/end frame/time if available.
Source code in src/mosaic/core/helpers.py
filter_time_range ¶
filter_time_range(df: DataFrame, filter_start_frame: Optional[int] = None, filter_end_frame: Optional[int] = None, filter_start_time: Optional[float] = None, filter_end_time: Optional[float] = None, frame_col: str = 'frame', time_col: str = 'time') -> pd.DataFrame
Filter DataFrame to a time/frame range.
Parameters¶
df : pd.DataFrame Input DataFrame with frame and/or time columns filter_start_frame : int, optional Discard frames < this value filter_end_frame : int, optional Discard frames >= this value filter_start_time : float, optional Discard rows where time < this value (seconds) filter_end_time : float, optional Discard rows where time >= this value (seconds) frame_col : str, default "frame" Name of the frame column time_col : str, default "time" Name of the time column
Returns¶
pd.DataFrame Filtered DataFrame with index reset
Source code in src/mosaic/core/helpers.py
resolve_frame_range ¶
resolve_frame_range(fps: float | None, start_frame: int | None = None, end_frame: int | None = None, start_time: float | None = None, end_time: float | None = None) -> tuple[int | None, int | None]
Validate mutual exclusivity and convert to frame range.
Raises ValueError if both frame and time are set for the same boundary, or if time-based filters are used without fps.
Source code in src/mosaic/core/helpers.py
parse_compound_name ¶
Split a compound hierarchical name into its components.
Supports arbitrary depths (2, 3, 4+ levels).
Parameters¶
name : str Compound name like "fish_01__speed_3__loop_1" separator : str, default "__" The separator between hierarchy levels
Returns¶
list[str] List of components, e.g. ["fish_01", "speed_3", "loop_1"]
Examples¶
parse_compound_name("fish_01__speed_3__loop_1") ['fish_01', 'speed_3', 'loop_1']
parse_compound_name("arena_1__day_015__hour_14") ['arena_1', 'day_015', 'hour_14']
parse_compound_name("simple_name") ['simple_name']
Source code in src/mosaic/core/helpers.py
build_compound_name ¶
Join hierarchy components into a compound name.
Supports any number of parts.
Parameters¶
*parts : str Hierarchy components to join, e.g. "fish_01", "speed_3", "loop_1" separator : str, default "__" The separator between hierarchy levels
Returns¶
str Compound name, e.g. "fish_01__speed_3__loop_1"
Examples¶
build_compound_name("fish_01", "speed_3", "loop_1") 'fish_01__speed_3__loop_1'
build_compound_name("arena_1", "day_015", "hour_14") 'arena_1__day_015__hour_14'
build_compound_name("single") 'single'
Source code in src/mosaic/core/helpers.py
parse_hierarchy ¶
parse_hierarchy(group: str, sequence: str, level_names: list[str], separator: str = '__') -> dict[str, str | None]
Parse group and sequence into named hierarchy levels.
The full hierarchy is constructed by concatenating group and sequence components, then mapping them to the provided level names.
Parameters¶
group : str The group name (may be compound, e.g. "experiment_A__arena_1") sequence : str The sequence name (may be compound, e.g. "day_015__hour_14") level_names : list[str] Names for each hierarchy level, e.g. ["experiment", "arena", "day", "hour"] separator : str, default "__" The separator between hierarchy levels
Returns¶
dict[str, str | None] Dictionary mapping level names to values. Missing levels are None.
Examples¶
parse_hierarchy("fish_01", "speed_3__loop_1", ... level_names=["fish", "speed", "loop"]) {'fish': 'fish_01', 'speed': 'speed_3', 'loop': 'loop_1'}
parse_hierarchy("experiment_A__arena_1", "day_015__hour_14", ... level_names=["experiment", "arena", "day", "hour"]) {'experiment': 'experiment_A', 'arena': 'arena_1', 'day': 'day_015', 'hour': 'hour_14'}
Handles fewer parts than names (missing levels are None)¶
parse_hierarchy("fish_01", "loop_1", level_names=["fish", "speed", "loop"]) {'fish': 'fish_01', 'speed': 'loop_1', 'loop': None}
Source code in src/mosaic/core/helpers.py
ensure_text_column ¶
Make sure df[column] exists with object/string dtype so string assignments won't raise warnings.