Dataset¶
The central orchestrator for mosaic workflows. Manages named roots, provides methods for media indexing, track conversion, label management, feature extraction, and model training.
Dataset
dataclass
¶
Dataset(manifest_path: Path, name: str = 'unnamed', version: str = '0.1', format: str = 'yaml', roots: Dict[str, str] = (lambda: {'media_raw': '', 'media': '', 'tracks_raw': '', 'tracks': '', 'features': '', 'labels': '', 'models': '', 'frames': ''})(), meta: Dict[str, Any] = dict(), dataset_type: str = 'discrete', segment_duration: str | None = None, time_column: str | None = None)
load ¶
Load dataset metadata from self.manifest_path.
Source code in src/mosaic/core/dataset.py
save ¶
Persist manifest.
Source code in src/mosaic/core/dataset.py
get_root ¶
Return the absolute path for a named dataset root.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Root name (e.g. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Absolute path to the root directory. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If key is not set in the manifest. |
Source code in src/mosaic/core/dataset.py
has_root ¶
resolve_media_root ¶
Return the root key that holds actual video files.
Prefers media_raw (original uploads) when set, falls back to
media for backward compatibility with older datasets.
Source code in src/mosaic/core/dataset.py
set_root ¶
Set a named dataset root and create the directory if needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Root name (e.g. |
required |
path
|
str | Path
|
Directory path (absolute or relative to dataset root). |
required |
Source code in src/mosaic/core/dataset.py
ensure_roots ¶
remap_roots ¶
Remap dataset roots by replacing the longest matching path prefixes using path_map. path_map entries are {source_prefix: dest_prefix}.
Source code in src/mosaic/core/dataset.py
remap_path ¶
Remap a single path using the dataset's path_map.
Applies the longest-matching prefix replacement from path_map
(set during load()). Returns the path unchanged if no prefix matches.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to remap. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Remapped path, or the original if no mapping applies. |
Source code in src/mosaic/core/dataset.py
resolve_path ¶
Resolve a stored path (absolute or relative) to an absolute path.
Relative paths are resolved against anchor (default: dataset root).
Absolute paths that exist are returned as-is; absolute paths that don't
exist are tried through :meth:remap_path.
Source code in src/mosaic/core/dataset.py
rewrite_index_paths ¶
Permanently rewrite abs_path in all index CSV files on disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path_map
|
Mapping[str, str]
|
{old_prefix: new_prefix} mapping |
required |
dry_run
|
bool
|
If True, report what would change without writing |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Dict of {index_path: num_paths_changed} |
Source code in src/mosaic/core/dataset.py
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 | |
make_portable ¶
Convert all internal absolute paths to relative (to dataset root).
Only needed for datasets created before relative-path support. Idempotent — safe to call multiple times. Already-relative paths are left unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dry_run
|
bool
|
If True, report what would change without writing. |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Dict of |
Source code in src/mosaic/core/dataset.py
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 | |
list_groups ¶
Return a sorted list of unique group names in tracks/index.csv.
Source code in src/mosaic/core/dataset.py
list_sequences ¶
Return all sequences (optionally filtered by group) in tracks/index.csv.
Source code in src/mosaic/core/dataset.py
get_sequence_metadata ¶
Return a DataFrame with all sequences and optionally parsed hierarchy columns.
This method provides a way to view the full dataset structure and filter by arbitrary hierarchy levels, supporting datasets with different organizational structures (2, 3, 4+ levels).
Parameters¶
level_names : list[str], optional Names for hierarchy levels. If provided, parses the full path (group + sequence) into columns with these names. E.g., ["fish", "speed", "loop"] for a 3-level hierarchy. separator : str, default "__" The separator used in compound names.
Returns¶
pd.DataFrame DataFrame with columns: - group, sequence: Original values from index - group_safe, sequence_safe: URL-encoded versions - abs_path: Path to the parquet file - Additional columns from index (n_rows, etc.) - If level_names provided: one column per level name
Examples¶
Basic usage - get all sequences¶
meta = ds.get_sequence_metadata() meta[['group', 'sequence']].head()
Parse into hierarchy levels¶
meta = ds.get_sequence_metadata(level_names=["fish", "speed", "loop"]) meta.groupby("speed")["sequence"].count()
4-level hierarchy for continuous recordings¶
meta = ds.get_sequence_metadata( ... level_names=["experiment", "arena", "day", "hour"] ... )
Source code in src/mosaic/core/dataset.py
query_sequences ¶
query_sequences(group_contains: str | None = None, group_startswith: str | None = None, group_endswith: str | None = None, sequence_contains: str | None = None, sequence_startswith: str | None = None, sequence_endswith: str | None = None) -> list[tuple[str, str]]
Return (group, sequence) pairs matching the specified criteria.
Provides flexible filtering for hierarchical datasets where group and/or sequence names encode multiple factors.
Parameters¶
group_contains : str, optional Filter groups containing this substring group_startswith : str, optional Filter groups starting with this prefix group_endswith : str, optional Filter groups ending with this suffix sequence_contains : str, optional Filter sequences containing this substring sequence_startswith : str, optional Filter sequences starting with this prefix sequence_endswith : str, optional Filter sequences ending with this suffix
Returns¶
list[tuple[str, str]] List of (group, sequence) pairs matching all criteria
Examples¶
Get all sequences for fish_01¶
pairs = ds.query_sequences(group_startswith="fish_01")
Get all speed_3 recordings across all fish¶
pairs = ds.query_sequences(sequence_startswith="speed_3")
Get all loop_1 recordings at speed_3¶
pairs = ds.query_sequences( ... sequence_contains="speed_3", ... sequence_endswith="loop_1" ... )
Source code in src/mosaic/core/dataset.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 | |
index_media ¶
index_media(search_dirs: Iterable[str | Path], extensions: Tuple[str, ...] = ('.mp4', '.avi'), index_filename: str = 'index.csv', recursive: bool = True, sequence_match_mode: str = 'exact') -> Path
Scan search_dirs for media files with given extensions and write an index CSV into media root. - No symlinks created; absolute paths recorded. - Columns: name, abs_path, size_bytes, mtime_iso, group, sequence, group_safe, sequence_safe, video_order
Parameters¶
search_dirs : Iterable[str | Path]
Directories to scan for media files.
extensions : tuple of str
File extensions to include.
index_filename : str
Output CSV filename within media root.
recursive : bool
Whether to search subdirectories.
sequence_match_mode : str
How to match video filenames to known sequences from tracks/index.csv.
- "exact" (default): video stem must exactly match a sequence name.
- "prefix": video stem is matched to the longest sequence name that
is a prefix of the stem. This handles split recordings where files
are named like session01_001.mp4, session01_002.mp4 mapping
to sequence session01.
Source code in src/mosaic/core/dataset.py
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 | |
resolve_media_paths ¶
Resolve all media file paths for a given (group, sequence), ordered.
For multi-video sequences, returns paths sorted by video_order.
For single-video sequences, returns a list with one element.
Source code in src/mosaic/core/dataset.py
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 | |
resolve_media_path ¶
Resolve a single media file path for a given (group, sequence).
For multi-video sequences, raises RuntimeError with a message
to use :meth:resolve_media_paths instead.
Source code in src/mosaic/core/dataset.py
index_tracks_raw ¶
index_tracks_raw(search_dirs: Iterable[str | Path], patterns: Iterable[str] | str = ('*.npy', '*.h5', '*.csv'), src_format: str = 'calms21_npy', index_filename: str = 'index.csv', recursive: bool = True, multi_sequences_per_file: bool = False, group_from: Optional[str] = None, group_pattern: Optional[str] = None, exclude_patterns: Optional[Iterable[str]] = None, compute_md5: bool = False) -> Path
Scan for original tracking files and write tracks_raw/index.csv Columns: group, sequence, abs_path, src_format, size_bytes, mtime_iso, md5
Parameters¶
search_dirs : Iterable[str | Path] Directories to search for files patterns : Iterable[str] | str Glob patterns to match files src_format : str Source format identifier (e.g., "trex_npz", "calms21_npy") index_filename : str Name of output index file recursive : bool Whether to search recursively multi_sequences_per_file : bool If True (e.g., CalMS files), set 'group' from group_from and leave 'sequence' blank group_from : str | None For multi_sequences_per_file: 'filename' or 'parent' group_pattern : str | None Regex pattern to extract group from sequence name. Must have a capturing group. Examples: r'^(hex|OCI|OLE)' -> extracts 'hex', 'OCI', or 'OLE' as group r'^([A-Za-z]+)' -> extracts letters before first underscore as group Applied AFTER sequence is determined (e.g., after stripping _fish0 suffix). exclude_patterns : Iterable[str] | None Glob patterns to exclude compute_md5 : bool If True, compute MD5 hash of each file (slow for large files). Default False.
Source code in src/mosaic/core/dataset.py
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 | |
convert_one_track ¶
Convert a single raw track file (row from tracks_raw/index.csv) to standard trex_v1 parquet. Returns path to standardized file, updates tracks/index.csv.
Source code in src/mosaic/core/dataset.py
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 | |
list_converters ¶
list_schemas ¶
convert_all_tracks ¶
convert_all_tracks(params: Optional[dict] = None, overwrite: bool = False, merge_per_sequence: Optional[bool] = None, group_from: Optional[str] = None) -> None
Convert all raw track files (from tracks_raw/index.csv) to standard T-Rex-like parquet files.
By default, for src_format == 'trex_npz', files are merged per (group, sequence) into a single parquet file (one per unique (group, sequence)). For other formats, or if merge_per_sequence=False, each row is converted individually.
Parameters¶
params : dict | None Extra parameters to pass to converters. overwrite : bool If True, overwrite existing output files. merge_per_sequence : bool | None If True, merge per (group, sequence) for formats that support it (currently trex_npz). If None, defaults to True if all rows are trex_npz, else False. group_from : {'infile','filename','both'} | None Controls which group ends up in the standardized output & index: - 'infile' (default): use the group from inside the source file (e.g., 'annotator-id_0'). - 'filename' : use the raw file-level group hint from tracks_raw/index.csv (e.g., 'calms21_task1_test'). - 'both' : set output group to the raw file-level group, and still record in-file group in the data (converters should already keep in-file columns; we always keep raw file-level hint in the 'collection' column). If None, defaults to 'infile'.
Source code in src/mosaic/core/dataset.py
1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 | |
convert_all_labels ¶
convert_all_labels(kind: str = 'behavior', overwrite: bool = False, params: Optional[dict] = None, source_format: Optional[str] = None, **kwargs) -> None
Convert labels from raw files using registered label converters.
This method now uses a plugin architecture via the label_library. Converters are automatically registered for different source formats.
Parameters¶
kind : str, default="behavior" Type of labels to convert (e.g., "behavior", "id_tags") overwrite : bool, default=False Whether to overwrite existing label files params : dict, optional Configuration parameters passed to converter source_format : str, optional Source format identifier (e.g., "calms21_npy", "boris_csv") Must match a registered converter's src_format **kwargs : additional keyword arguments Passed to converter (e.g., group_from, fps, etc.)
Raises¶
ValueError If no converter is registered for (source_format, kind) combination FileNotFoundError If tracks_raw/index.csv is missing
Examples¶
Convert CalMS21 labels:
dataset.convert_all_labels( ... kind="behavior", ... source_format="calms21_npy", ... group_from="filename" ... )
Convert Boris labels (once implemented):
dataset.convert_all_labels( ... kind="behavior", ... source_format="boris_csv", ... fps=30.0 ... )
Source code in src/mosaic/core/dataset.py
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 | |
convert_labels_custom ¶
convert_labels_custom(converter_fn: Callable, kind: str = 'behavior', label_format: str = 'individual_pair_v1', overwrite: bool = False, **kwargs) -> int
Convert labels using a custom converter function.
This method provides flexibility for one-off datasets with unique label structures that don't fit the standard converter pattern. The Dataset handles all index.csv bookkeeping while you provide the conversion logic.
Parameters¶
converter_fn : callable A function that performs the actual label conversion. Must have signature:
converter_fn(dataset, labels_root, existing_pairs, overwrite, **kwargs)
-> list[dict]
Where:
- dataset: This Dataset instance (for accessing paths, metadata, etc.)
- labels_root: Path to output directory (e.g., dataset/labels/behavior/)
- existing_pairs: set of (group, sequence) tuples already converted
- overwrite: bool, whether to overwrite existing files
- **kwargs: Any additional arguments passed to convert_labels_custom
Returns:
- list[dict]: Index rows for each converted sequence. Each dict should have:
- 'kind': str, label kind (e.g., "behavior")
- 'label_format': str, format name (e.g., "individual_pair_v1")
- 'group': str, group name
- 'sequence': str, sequence name
- 'group_safe': str, filesystem-safe group name
- 'sequence_safe': str, filesystem-safe sequence name
- 'abs_path': str, absolute path to output NPZ file
- 'n_frames': int, number of unique frames with labels
- 'n_events': int, total number of label events
- 'label_ids': str, comma-separated label IDs (e.g., "0,1,2")
- 'label_names': str, comma-separated label names (e.g., "none,troph,other")
- (optional) additional metadata columns
str, default="behavior"
Type of labels being converted (e.g., "behavior", "id_tags")
str, default="individual_pair_v1"
Format name for metadata. Should match what's saved in NPZ files.
bool, default=False
Whether to overwrite existing label files
**kwargs Additional arguments passed to converter_fn
Returns¶
int Number of sequences converted
Examples¶
def my_converter(dataset, labels_root, existing_pairs, overwrite, **kwargs): ... '''Custom converter for my unique dataset.''' ... boris_path = kwargs['boris_path'] ... metadata_path = kwargs['metadata_path'] ... fps = kwargs.get('fps', 50.0) ... ... # ... your conversion logic here ... ... # Save NPZ files to labels_root ... # Return list of index row dicts ... ... return index_rows
n_converted = dataset.convert_labels_custom( ... converter_fn=my_converter, ... kind="behavior", ... boris_path=Path("/path/to/boris.tsv"), ... metadata_path=Path("/path/to/metadata.json"), ... fps=50.0, ... )
NPZ File Format (individual_pair_v1)¶
The converter should save NPZ files with these keys: - 'group': str, group name - 'sequence': str, sequence name - 'label_format': str, "individual_pair_v1" - 'frames': int32 array, shape (n_events,), frame indices - 'labels': int32 array, shape (n_events,), label IDs - 'individual_ids': int32 array, shape (n_events, 2), [id1, id2] per event - For individual behaviors: [subject_id, -1] - For pair behaviors: [id1, id2] (symmetric: store both directions) - For scene-level: [-1, -1] - 'label_ids': int32 array, all label IDs (e.g., [0, 1, 2]) - 'label_names': object array, label names (e.g., ["none", "troph", "other"]) - 'fps': float, frames per second - (optional) additional metadata
See Also¶
convert_all_labels : For standard converters registered in label_library load_labels : Load converted labels
Source code in src/mosaic/core/dataset.py
2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 | |
save_id_labels ¶
save_id_labels(kind: str, group: str, sequence: str, per_id_labels: dict, metadata: Optional[dict] = None, overwrite: bool = False) -> Path
Persist per-(sequence, id) tags under labels/
per_id_labels: {id_value -> {"field": value, ...}}
Source code in src/mosaic/core/dataset.py
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 | |
convert_id_tags_from_csv ¶
convert_id_tags_from_csv(csv_path: str | Path, csv_type: str = 'focal', all_ids: Optional[list] = None, overwrite: bool = False, focal_id_column: str = 'focal_id', id_column: str = 'id', category_column: str = 'category', field_columns: Optional[list[str]] = None) -> list[Path]
Convert a CSV file to id_tags labels.
This method supports different CSV formats for per-individual metadata:
Supported csv_type values¶
"focal"
One focal ID per sequence. CSV columns: group, sequence, focal_id.
Creates boolean 'focal' field for all IDs (True for focal, False otherwise).
Requires all_ids parameter to populate non-focal IDs.
"category" Per-ID category labels. CSV columns: group, sequence, id, category. Creates 'category' field with the value from CSV. IDs not in CSV are skipped (or use all_ids to include them with None).
"multi"
Per-ID multiple fields. CSV columns: group, sequence, id, field1, field2...
Creates one field per column specified in field_columns.
Parameters¶
csv_path : str or Path Path to input CSV file csv_type : str One of "focal", "category", "multi" all_ids : list, optional List of all valid IDs. Required for csv_type="focal" to populate non-focal IDs. For other types, auto-detected from CSV if not provided. overwrite : bool Whether to overwrite existing id_tags files focal_id_column : str Column name for focal ID (csv_type="focal") id_column : str Column name for individual ID (csv_type="category" or "multi") category_column : str Column name for category value (csv_type="category") field_columns : list[str], optional List of column names to use as fields (csv_type="multi")
Returns¶
list[Path] Paths to created npz files
Examples¶
Focal labels (one focal fish per sequence)¶
dataset.convert_id_tags_from_csv( ... csv_path="focal_ids.csv", ... csv_type="focal", ... all_ids=list(range(8)), ... overwrite=True, ... )
Category labels (e.g., strain per fish)¶
dataset.convert_id_tags_from_csv( ... csv_path="strain_labels.csv", ... csv_type="category", ... category_column="strain", ... )
Multiple fields per individual¶
dataset.convert_id_tags_from_csv( ... csv_path="fish_metadata.csv", ... csv_type="multi", ... field_columns=["strain", "treatment", "sex"], ... )
Source code in src/mosaic/core/dataset.py
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 | |
load_id_labels ¶
load_id_labels(kind: str = 'id_tags', groups: Optional[Iterable[str]] = None, sequences: Optional[Iterable[str]] = None) -> dict[tuple[str, str], dict]
Load per-id labels for the requested kind. Returns {(group, sequence): {"labels": {id: {field: value}}, "sequence_safe": str, "path": str, "metadata": dict}}
Source code in src/mosaic/core/dataset.py
2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 | |
load_labels ¶
Load behavior labels for a specific (group, sequence).
Returns dict with keys: - frames: np.ndarray of frame indices - labels: np.ndarray of behavior IDs - individual_ids: np.ndarray of shape (n_events, 2) if individual_pair_v1 format - label_ids: np.ndarray of all possible label IDs - label_names: np.ndarray of label names - label_format: str indicating format version - group, sequence, sequence_key: metadata
For backward compatibility with old dense formats, individual_ids may not be present.
Source code in src/mosaic/core/dataset.py
get_label_map ¶
Get the label map {id: name} for a label kind.
Reads from the labels index.csv (first row).
Source code in src/mosaic/core/dataset.py
get_labels_for_individual ¶
get_labels_for_individual(group: str, sequence: str, individual_id: int, kind: str = 'behavior', frame_range: Optional[tuple[int, int]] = None) -> dict
Get all label events for a specific individual.
Parameters¶
group : str Group name sequence : str Sequence name individual_id : int Individual ID to filter by kind : str Label kind (default "behavior") frame_range : tuple[int, int], optional (start_frame, end_frame) to filter events
Returns¶
dict Dictionary with keys: - frames: np.ndarray of frame indices - labels: np.ndarray of behavior IDs - individual_ids: np.ndarray of shape (n_events, 2)
Source code in src/mosaic/core/dataset.py
2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 | |
get_labels_at_frame ¶
get_labels_at_frame(group: str, sequence: str, frame: int, kind: str = 'behavior', individual_id: Optional[int] = None) -> dict
Get all labels at a specific frame.
Parameters¶
group : str Group name sequence : str Sequence name frame : int Frame index kind : str Label kind (default "behavior") individual_id : int, optional Filter by individual ID if provided
Returns¶
dict Dictionary with keys: - frames: np.ndarray of frame indices (should all equal frame) - labels: np.ndarray of behavior IDs - individual_ids: np.ndarray or None
Source code in src/mosaic/core/dataset.py
load_tracks ¶
load_tracks(group: str, sequence: str, prefer: str = 'standard', auto_convert: bool = True, convert_params: Optional[dict] = None) -> pd.DataFrame
Load T-Rex-like standardized tracks if present; otherwise optionally auto-convert from raw.
Source code in src/mosaic/core/dataset.py
run_feature ¶
run_feature(feature: Any, groups: Iterable[str] | None = None, sequences: Iterable[str] | None = None, overwrite: bool = False, parallel_workers: int | None = None, parallel_mode: str | None = 'thread', overlap_frames: int = 0, filter_start_frame: int | None = None, filter_end_frame: int | None = None, filter_start_time: float | None = None, filter_end_time: float | None = None, registry: 'FeatureRegistry | None' = None) -> Any
Execute a feature extraction pipeline over the dataset.
Runs the feature's fit() (if needed) and apply() phases over
the chosen scope. Input routing is determined by feature.inputs:
tracks (default), a single upstream feature result, or a multi-input set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature
|
Any
|
Feature instance implementing the Feature protocol. |
required |
groups
|
Iterable[str] | None
|
Scope filter — restrict to these group names. |
None
|
sequences
|
Iterable[str] | None
|
Scope filter — restrict to these sequence names. |
None
|
overwrite
|
bool
|
Re-run even if outputs exist for this run_id. |
False
|
parallel_workers
|
int | None
|
When >1 and the feature declares itself parallelizable, run the apply phase in parallel. |
None
|
parallel_mode
|
str | None
|
|
'thread'
|
overlap_frames
|
int
|
Extra frames from adjacent segments for edge-effect handling. Mutually exclusive with frame/time filters. |
0
|
filter_start_frame
|
int | None
|
Only include frames >= this value. |
None
|
filter_end_frame
|
int | None
|
Only include frames < this value. |
None
|
filter_start_time
|
float | None
|
Converted to start frame via fps_default from dataset metadata. |
None
|
filter_end_time
|
float | None
|
Converted to end frame via fps_default from dataset metadata. |
None
|
registry
|
'FeatureRegistry | None'
|
Optional feature registry (advanced usage). |
None
|
Returns:
| Type | Description |
|---|---|
Any
|
A |
Any
|
attributes. Pass directly to |
Example
Source code in src/mosaic/core/dataset.py
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 | |
extract_frames ¶
extract_frames(n_frames: int, method: str = 'uniform', *, groups: Iterable[str] | None = None, sequences: Iterable[str] | None = None, overwrite: bool = False, start_frame: int | None = None, end_frame: int | None = None, candidate_step: int = 1, crop=None, kmeans_resize: tuple[int, int] = (64, 64), kmeans_grayscale: bool = True, kmeans_max_candidates: int | None = 5000, kmeans_batch_size: int = 1024, kmeans_max_iter: int = 100, kmeans_n_init='auto', random_state: int = 42, parallel_workers: int | str | None = 'auto', parallel_mode: str = 'thread') -> str
Extract representative frames from each video in the dataset.
Samples n_frames per video using either uniform spacing or k-means
diversity selection. Frames are saved as PNGs under media/frames/.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_frames
|
int
|
Number of frames to extract per video. |
required |
method
|
str
|
|
'uniform'
|
groups
|
Iterable[str] | None
|
Scope filter — restrict to these group names. |
None
|
sequences
|
Iterable[str] | None
|
Scope filter — restrict to these sequence names. |
None
|
overwrite
|
bool
|
Re-run even if outputs exist. |
False
|
start_frame
|
int | None
|
Only consider frames >= this value. |
None
|
end_frame
|
int | None
|
Only consider frames < this value. |
None
|
candidate_step
|
int
|
Step between candidate frames (default 1). |
1
|
crop
|
Optional crop specification. |
None
|
|
kmeans_resize
|
tuple[int, int]
|
Resize frames to this (w, h) before k-means. |
(64, 64)
|
kmeans_grayscale
|
bool
|
Convert to grayscale before k-means. |
True
|
kmeans_max_candidates
|
int | None
|
Cap candidate pool size for k-means. |
5000
|
kmeans_batch_size
|
int
|
Mini-batch size for k-means. |
1024
|
kmeans_max_iter
|
int
|
Max k-means iterations. |
100
|
kmeans_n_init
|
Number of k-means initializations. |
'auto'
|
|
random_state
|
int
|
Random seed for reproducibility. |
42
|
parallel_workers
|
int | str | None
|
Number of parallel workers ( |
'auto'
|
parallel_mode
|
str
|
|
'thread'
|
Returns:
| Type | Description |
|---|---|
str
|
The |
Source code in src/mosaic/core/dataset.py
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 | |
list_frame_runs ¶
List all frame extraction runs tracked in the frames index.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str | None
|
Filter to a specific method ( |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Index rows for matching extraction runs. |
Source code in src/mosaic/core/dataset.py
get_frame_paths ¶
get_frame_paths(method: str, run_id: str | None = None, group: str | None = None, sequence: str | None = None) -> list[Path]
Return paths to extracted frame PNGs for a given scope.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Extraction method ( |
required |
run_id
|
str | None
|
Specific run_id. If None, uses the latest run. |
None
|
group
|
str | None
|
Filter to a specific group. |
None
|
sequence
|
str | None
|
Filter to a specific sequence. |
None
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
Sorted list of PNG file paths. |
Source code in src/mosaic/core/dataset.py
get_frame_manifests ¶
get_frame_manifests(method: str, run_id: str | None = None, group: str | None = None, sequence: str | None = None) -> list[dict[str, object]]
Load run_info.json manifests from extracted frame directories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
Extraction method ( |
required |
run_id
|
str | None
|
Specific run_id. If None, uses the latest run. |
None
|
group
|
str | None
|
Filter to a specific group. |
None
|
sequence
|
str | None
|
Filter to a specific sequence. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, object]]
|
Manifest dicts loaded from run_info.json files, |
list[dict[str, object]]
|
one per sequence directory. |
Source code in src/mosaic/core/dataset.py
train_model ¶
train_model(model: Any, config: str | Path | dict[str, object] | None = None, overwrite: bool = False) -> str
Train a registered model using a JSON or dict configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Any
|
Model/trainer instance implementing |
required |
config
|
str | Path | dict[str, object] | None
|
Path to a JSON config file or an in-memory dict of
hyperparameters. Passed to |
None
|
overwrite
|
bool
|
Reserved for future use (run_ids are hash-based). |
False
|
Returns:
| Type | Description |
|---|---|
str
|
The |